You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1672 lines
93KB

  1. using Etcdserverpb;
  2. using Google.Protobuf.WellKnownTypes;
  3. using HealthMonitor.Common;
  4. using HealthMonitor.Common.helper;
  5. using HealthMonitor.Model.Service.Mapper;
  6. using HealthMonitor.Service.Biz;
  7. using HealthMonitor.Service.Biz.db;
  8. using HealthMonitor.Service.Cache;
  9. using HealthMonitor.Service.Etcd;
  10. using HealthMonitor.Service.MessageQueue;
  11. using HealthMonitor.Service.Resolver.Interface;
  12. using HealthMonitor.Service.Sub;
  13. using HealthMonitor.Service.Sub.Topic.Model;
  14. using Microsoft.EntityFrameworkCore.Metadata;
  15. using Microsoft.Extensions.Logging;
  16. using Newtonsoft.Json;
  17. using Newtonsoft.Json.Linq;
  18. using SqlSugar;
  19. using System;
  20. using System.Collections.Generic;
  21. using System.Linq;
  22. using System.Net;
  23. using System.Text;
  24. using System.Threading.Tasks;
  25. using TelpoDataService.Util.Clients;
  26. using TelpoDataService.Util.Entities.GpsCard;
  27. using TelpoDataService.Util.Entities.GpsLocationHistory;
  28. using TelpoDataService.Util.Models;
  29. using TelpoDataService.Util.QueryObjects;
  30. namespace HealthMonitor.Service.Resolver
  31. {
  32. public class PregnancyHeartRateResolver : IResolver
  33. {
  34. private readonly ILogger<PregnancyHeartRateResolver> _logger;
  35. private readonly TDengineService _serviceTDengine;
  36. private readonly DeviceCacheManager _deviceCacheMgr;
  37. private readonly IotApiService _serviceIotApi;
  38. private readonly AsyncLocal<string> _messageId = new();
  39. private readonly AsyncLocal<HisGpsHeartRate> _msgData = new();
  40. private readonly HttpHelper _httpHelper = default!;
  41. private readonly EtcdService _serviceEtcd;
  42. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> _hisFetalHeartApiClient;
  43. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalMovement> _hisFetalMovementApiClient;
  44. private readonly FetalMovementNormalValueRangeCacheManager _mgrFetalMovementNormalValueRangeCache;
  45. private readonly MqProcessLogic _serviceMqProcess;
  46. private static int[] SCHEDULE_HOUR = new int[] {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22};
  47. private static int[] ODD_SCHEDULE_HOUR = new int[] { 1, 3, 5, 7, 9, 11,13, 15, 17, 19, 21, 23 };
  48. // 延时胎心计算间隔周期
  49. private static int INTERVAL_FHR=15;
  50. public PregnancyHeartRateResolver(ILogger<PregnancyHeartRateResolver> logger,
  51. HttpHelper httpHelper, EtcdService serviceEtcd, DeviceCacheManager deviceCacheMgr,
  52. MqProcessLogic serviceMqProcess,
  53. IotApiService iotApiService, TDengineService serviceDengine, FetalMovementNormalValueRangeCacheManager fetalMovementNormalValueRangeCacheMgr,
  54. GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> hisFetalHeartApiClient,
  55. GpsLocationHistoryAccessorClient<HisGpsFetalMovement> hisFetalMovementApiClient
  56. )
  57. {
  58. _logger = logger;
  59. _httpHelper = httpHelper;
  60. _serviceEtcd = serviceEtcd;
  61. _serviceTDengine = serviceDengine;
  62. _deviceCacheMgr = deviceCacheMgr;
  63. _serviceIotApi = iotApiService;
  64. _serviceMqProcess = serviceMqProcess;
  65. _hisFetalHeartApiClient = hisFetalHeartApiClient;
  66. _hisFetalMovementApiClient = hisFetalMovementApiClient;
  67. _mgrFetalMovementNormalValueRangeCache = fetalMovementNormalValueRangeCacheMgr;
  68. }
  69. public void SetResolveInfo(PackageMsgModel msg)
  70. {
  71. var topicHmPregnancyHeartRate = JsonConvert.DeserializeObject<TopicHmPregnancyHeartRate>(msg.DetailData.ToString()!);
  72. _messageId.Value = msg.MessageId;
  73. _msgData.Value = new HisGpsHeartRate()
  74. {
  75. HeartRateId = topicHmPregnancyHeartRate!.PregnancyHeartRateId,
  76. MessageId = topicHmPregnancyHeartRate!.MessageId,
  77. Serialno = topicHmPregnancyHeartRate!.Serialno,
  78. HeartRate = topicHmPregnancyHeartRate.PregnancyHeartRate,
  79. LastUpdate = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmPregnancyHeartRate.LastUpdate) / 1000000),
  80. CreateTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmPregnancyHeartRate.CreateTime) / 1000000),
  81. Method = topicHmPregnancyHeartRate!.Method,
  82. IsDisplay = topicHmPregnancyHeartRate!.IsDisplay ? 1 : 0
  83. };
  84. }
  85. public override string ToString()
  86. {
  87. return $"{nameof(PregnancyHeartRateResolver)}[{_messageId.Value}]";
  88. }
  89. public async Task ExecuteMessageAsync()
  90. {
  91. var messageId = _messageId.Value;
  92. var heartRate = _msgData.Value!;
  93. try
  94. {
  95. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(heartRate.Serialno, "0067");
  96. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  97. if (isFetalHeartEnable)
  98. {
  99. //_logger.LogInformation($"{heartRate.Serialno} 计算胎心胎动启动");
  100. #region 定时下发触发器(定时建模)
  101. var key = $"health_monitor/schedule_push/pregnancy_heart_rate/imei/{heartRate.Serialno}";
  102. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  103. if (string.IsNullOrWhiteSpace(schedule_push))
  104. {
  105. // 注册首次下推
  106. var interval = 0;
  107. // 获取当前时间
  108. DateTime now = DateTime.Now;
  109. var rand = new Random();
  110. var pushSec = rand.Next(59);
  111. int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  112. // 计算距离下一个$interval天后的8点的时间间隔
  113. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 6, pushMin, pushSec).AddDays(interval);
  114. TimeSpan timeUntilNextRun = nextRunTime - now;
  115. if (timeUntilNextRun < TimeSpan.Zero)
  116. {
  117. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  118. nextRunTime += TimeSpan.FromDays(1);
  119. }
  120. var ttl = (long)timeUntilNextRun.TotalSeconds;
  121. var data = new
  122. {
  123. imei = heartRate.Serialno,
  124. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  125. ttl,
  126. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  127. };
  128. var result = JsonConvert.SerializeObject(data);
  129. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  130. }
  131. #endregion
  132. //_logger.LogInformation($"{heartRate.Serialno} 触发定时建模");
  133. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval 最小highFreqSampleInterval=60)
  134. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]!:60;
  135. // 触发高频监测的心率上限值
  136. var triggerHighFreqHigh = (int)watchConfig["triggerHighFreqHigh"]!;
  137. // 触发高频监测的心率下限值
  138. var triggerHighFreqLow = (int)watchConfig["triggerHighFreqLow"]!;
  139. // 暂时处理
  140. triggerHighFreqLow = triggerHighFreqLow > 60 && triggerHighFreqLow < 67 ? 60 : triggerHighFreqLow;
  141. //停止高频心率采样心率连续正常次数
  142. var stopHighFreqSampleCount = (int)watchConfig["stopHighFreqSampleCount"]!;
  143. // 高频心率采集时长 0 为持续采集,非零为高频心率的采集时长
  144. //var highFreqSampleTimes = (int)watchConfig["highFreqSampleTimes"]!;
  145. var highFreqSampleTimes = 540;
  146. // 告警上限阀值
  147. var upperAlarmThreshold = (int)watchConfig["upperAlarmThreshold"]!;
  148. // 告警下限阀值
  149. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  150. // EDOC
  151. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  152. // interval (分钟) 固定15分钟
  153. var intervalFHR = 15;//int)watchConfig["interval"]!;
  154. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  155. var phr = daysPhr
  156. .Where(p => p.LastUpdate <= heartRate.LastUpdate)
  157. .ToList();
  158. var nonFreqPhr = GetNonFreqPregnancyHeartRate(phr, highFreqSampleInterval);
  159. if (nonFreqPhr.Count >= 30)
  160. {
  161. #region 定时计算胎动数据触发器两小时间隔开始(奇数小时计算)
  162. /**
  163. var fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}";
  164. var rand = new Random();
  165. var pushSec = rand.Next(59);
  166. int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  167. DateTime fmScheduleNow = DateTime.Now;
  168. int hour = fmScheduleNow.Hour;
  169. int selectedScheduleHour;
  170. // 使用模运算来获取相应的ODD_SCHEDULE_HOUR
  171. if (hour % 2 == 0)
  172. {
  173. selectedScheduleHour = ODD_SCHEDULE_HOUR[hour / 2 % ODD_SCHEDULE_HOUR.Length];
  174. }
  175. else
  176. {
  177. selectedScheduleHour = ODD_SCHEDULE_HOUR[(hour + 1) / 2 % ODD_SCHEDULE_HOUR.Length];
  178. }
  179. DateTime scheduledDateTime = new DateTime(
  180. fmScheduleNow.Year,
  181. fmScheduleNow.Month,
  182. fmScheduleNow.Day,
  183. selectedScheduleHour,
  184. pushMin,
  185. pushSec
  186. );
  187. // 如果生成的时间在当前时间之前
  188. // 或者 fmScheduleNow 在 23 点之后并且 selectedScheduleHour 在 1 点(即次日)
  189. if (scheduledDateTime < fmScheduleNow || (fmScheduleNow.Hour >= 23 && selectedScheduleHour <= 1))
  190. {
  191. scheduledDateTime = scheduledDateTime.AddDays(1);
  192. }
  193. TimeSpan timeUntilNextRun = scheduledDateTime - fmScheduleNow;
  194. var ttl = (long)timeUntilNextRun.TotalSeconds;
  195. await SetIntervalTriggerAsync(fetalMovementKey, heartRate.Serialno, ttl, heartRate);
  196. _logger.LogInformation($"{heartRate.Serialno}-{heartRate.MessageId} 创建计划统计胎动时间{scheduledDateTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  197. */
  198. #endregion
  199. #region 定时计算胎动数据触发器每小时间隔开始,延时一个小时计算
  200. /*
  201. ///当前时间是的0~1小时返回2小时 ,
  202. ///当前时间是的1~2小时返回3小时 ,如此类推,
  203. ///当前时间是的21~22小时返回23小时
  204. ///当前时间是的23~0小时返回次日1小时
  205. var fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}";
  206. var rand = new Random();
  207. var pushSec = rand.Next(59);
  208. int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  209. DateTime fmScheduleNow = DateTime.Now;
  210. int hour = fmScheduleNow.Hour;
  211. int selectedScheduleHour=DateTimeUtil.GetNextHour(fmScheduleNow.Hour);
  212. DateTime scheduledDateTime = new DateTime(
  213. fmScheduleNow.Year,
  214. fmScheduleNow.Month,
  215. fmScheduleNow.Day,
  216. selectedScheduleHour,
  217. pushMin,
  218. pushSec
  219. );
  220. // 跨天
  221. if (selectedScheduleHour == 1 || selectedScheduleHour == 0)
  222. {
  223. scheduledDateTime = scheduledDateTime.AddDays(1);
  224. }
  225. TimeSpan timeUntilNextRun = scheduledDateTime - fmScheduleNow;
  226. var ttl = (long)timeUntilNextRun.TotalSeconds;
  227. await SetIntervalTriggerAsync(fetalMovementKey, heartRate.Serialno, ttl, heartRate);
  228. _logger.LogInformation($"{heartRate.Serialno}-{heartRate.MessageId} 创建计划统计胎动时间{scheduledDateTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  229. */
  230. #endregion
  231. #region 定时计算胎动数据触发器每小时间隔开始,延时一个小时计算
  232. ///当前时间是的0~1小时返回2小时 ,
  233. ///当前时间是的1~2小时返回3小时 ,如此类推,
  234. ///当前时间是的21~22小时返回23小时
  235. ///当前时间是的23~0小时返回次日1小时
  236. // lastUpdate默认奇数 // lastUpdate偶数小时
  237. var fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}";
  238. var rand = new Random();
  239. var pushSec = rand.Next(59);
  240. int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  241. DateTime fmScheduleNow = DateTime.Now;
  242. int hour = fmScheduleNow.Hour;
  243. int selectedScheduleHour = DateTimeUtil.GetNextHour(fmScheduleNow.Hour);
  244. DateTime scheduledDateTime = DateTime.Now.Date
  245. .AddHours(selectedScheduleHour)
  246. .AddMinutes(pushMin)
  247. .AddSeconds(pushSec);
  248. // 当前时间与lastUpdate的时间差小于2小时,0~1->2,0~1的数据是1点的sample_time,2点计算
  249. if (DateTime.Now.Subtract((DateTime)heartRate.LastUpdate!).TotalHours <= 2)
  250. {
  251. selectedScheduleHour = DateTimeUtil.GetNextHour(((DateTime)heartRate.LastUpdate).Hour);
  252. scheduledDateTime = DateTime.Now.Date
  253. .AddHours(selectedScheduleHour)
  254. .AddMinutes(pushMin)
  255. .AddSeconds(pushSec);
  256. if (((DateTime)heartRate.LastUpdate).Hour % 2 == 0)
  257. {
  258. // lastUpdate偶数小时
  259. fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}/even_hour";
  260. }
  261. else
  262. {
  263. // lastUpdate奇数小时
  264. fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}/odd_hour";
  265. }
  266. }
  267. // sample_time采集时间与计划计算时间最长是2小时,次日上报引起
  268. else
  269. {
  270. _logger.LogWarning($"iot 上报延迟,last_update与计划计算时间超过2小时");
  271. }
  272. // 跨天
  273. if (selectedScheduleHour == 1 || selectedScheduleHour == 0)
  274. {
  275. scheduledDateTime = scheduledDateTime.AddDays(1);
  276. }
  277. TimeSpan timeUntilNextRun = scheduledDateTime - fmScheduleNow;
  278. var ttl = (long)timeUntilNextRun.TotalSeconds;
  279. await SetIntervalTriggerAsync(fetalMovementKey, heartRate.Serialno, ttl, heartRate);
  280. _logger.LogInformation($"{heartRate.Serialno}-{heartRate.MessageId} 创建计划统计胎动时间{scheduledDateTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  281. #endregion
  282. #region 计算胎心数据(按心率时间LastUpdate)
  283. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(heartRate.Serialno);
  284. // 如果commonPHR为空或已建模已过期,进行建模和保存
  285. if (commonPHR == null || !commonPHR.CreateTime.Date.Equals(DateTime.Now.Date))
  286. // 获取当天 6:11 的时间点, 6:11 所有数据都已经全部建模
  287. //if (commonPHR == null || commonPHR.CreateTime < DateTime.Today.AddHours(6).AddMinutes(11))
  288. {
  289. // 处理孕妇业务,计算一般心率并下发
  290. commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(heartRate.Serialno, highFreqSampleInterval: highFreqSampleInterval);
  291. // 建模完成
  292. var flag = await _serviceIotApi.SetFetalConfig(heartRate.Serialno, 1, commonPHR!.MaxValue, commonPHR!.MinValue);
  293. _logger.LogInformation($"{heartRate.Serialno} 记录数量足够,建模完成");
  294. // 保存到TDengine数据库
  295. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR!);
  296. _logger.LogInformation($"保存TDengine完成");
  297. }
  298. // 获取最近的两个记录,并计算它们的 LastUpdate 时间差
  299. var firstTwoPhr = phr.OrderByDescending(i => i.LastUpdate).Take(2).Select(i => i.LastUpdate).ToList();
  300. var timeDiff = firstTwoPhr[0] - firstTwoPhr[1];
  301. // 如果需要,将时间差转换为秒
  302. var timeDiffInSeconds = timeDiff.TotalSeconds;
  303. // 高频统计结束时间
  304. var FreqStatsEnd = DateTime.Now;
  305. // 高频心率启动(在高频第二条才能判断)
  306. if (timeDiffInSeconds <= highFreqSampleInterval)
  307. {
  308. // 设置延时计算高频心率的胎心
  309. var freqHearRateHey = $"health_monitor/schedule_push/cal_freqhr_fetal_heart_rate/imei/{heartRate.Serialno}";
  310. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  311. if (phrFreqstatus == null)
  312. {
  313. /// 设置高频状态
  314. _logger.LogInformation($"{heartRate.Serialno} 进入高频心率启动状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval}");
  315. // 设置高频状态
  316. _logger.LogInformation($"{heartRate.Serialno} phr.Count {phr.Count}");
  317. var freqFirstPhr = phr.OrderByDescending(i => i.LastUpdate)
  318. .Skip(1) //在高频第二条才能判断,所以要去除本条记录
  319. .First();
  320. _logger.LogInformation($"首条高频附近的3条:{string.Join(',', phr.OrderByDescending(i => i.LastUpdate).Take(3).Select(i=>i.MessageId))}");
  321. await _deviceCacheMgr.SetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno, freqFirstPhr);
  322. _logger.LogInformation($"{heartRate.Serialno} 设置高频状态,首条高频心率ID:{freqFirstPhr.MessageId}");
  323. phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  324. HisGpsHeartRate freqFirstHR = new()
  325. {
  326. CreateTime = freqFirstPhr.CreateTime,
  327. DeviceKey = freqFirstPhr.DeviceKey,
  328. HeartRate = freqFirstPhr.PregnancyHeartRate,
  329. HeartRateId = freqFirstPhr.PregnancyHeartRateId,
  330. IsDisplay = freqFirstPhr.IsDisplay ? 1 : 0,
  331. LastUpdate = freqFirstPhr.LastUpdate,
  332. MessageId = freqFirstPhr.MessageId,
  333. Method = freqFirstPhr.Method,
  334. PersonId = freqFirstPhr.PersonId,
  335. Serialno = freqFirstPhr.SerialNumber,
  336. };
  337. await SetFreqHeartRateTriggerAsync(freqHearRateHey, heartRate.Serialno, highFreqSampleInterval, freqFirstHR);
  338. }
  339. // 续租延时计算高频心率的胎心
  340. await SetFreqHeartRateTriggerAsync(freqHearRateHey, heartRate.Serialno, highFreqSampleInterval);
  341. /// phr PregnancyHeartRate 连续连续正常次数个值都是正常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  342. /// 取连续正常次数正常值的平均值,推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  343. #region 检查高频状态是否连续12个心率值都是正常的
  344. // 获取最近连续正常次数个心率记录
  345. //_logger.LogInformation($"{heartRate.Serialno} 设置 stopHighFreqSampleCount {stopHighFreqSampleCount}");
  346. //var lastPhr = phr.OrderByDescending(i => i.LastUpdate).Take(stopHighFreqSampleCount).ToList();
  347. var lastPhr = phr.Where(i => i.LastUpdate >= phrFreqstatus!.LastUpdate)
  348. .OrderByDescending(i => i.LastUpdate).Take(stopHighFreqSampleCount).ToList();
  349. _logger.LogInformation($"{heartRate.Serialno} lastPhr.Count {lastPhr.Count},stopHighFreqSampleCount {stopHighFreqSampleCount}");
  350. _logger.LogInformation($"{heartRate.Serialno} count :{lastPhr.Count >= stopHighFreqSampleCount}");
  351. _logger.LogInformation($"{heartRate.Serialno} All {lastPhr.All(i => i.PregnancyHeartRate >= triggerHighFreqLow && i.PregnancyHeartRate <= triggerHighFreqHigh)}");
  352. // 检查是否连续12个值都是正常的
  353. if ((lastPhr.Count >= stopHighFreqSampleCount) &&
  354. lastPhr.All(i => i.PregnancyHeartRate >= triggerHighFreqLow && i.PregnancyHeartRate <= triggerHighFreqHigh)
  355. )
  356. {
  357. var avgPhr = lastPhr.Select(i => i.PregnancyHeartRate).Average();
  358. // 计算一般心率得到胎心系数
  359. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(DateTime.Now).ToString());
  360. // 高频数据不建模
  361. FreqStatsEnd = (DateTime)heartRate.LastUpdate!;
  362. _logger.LogInformation($"{heartRate.Serialno} 高频状态已经持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,连续 {stopHighFreqSampleCount} 次采样心率正常,将下发指令");
  363. var freqSaveAndPushFetalHeartRate = await _deviceCacheMgr.GetBizIntervalAsync(heartRate.Serialno, "SaveAndPushFetalHeartRate");
  364. // 高频不停,15分钟内只下发一条
  365. if (string.IsNullOrEmpty(freqSaveAndPushFetalHeartRate))
  366. {
  367. //await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  368. heartRate.HeartRate = (int)avgPhr;
  369. //await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  370. // 最后一条高频心率
  371. var lastFreqHr = lastPhr.First();
  372. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)lastFreqHr.LastUpdate!, phrFreqstatus!.LastUpdate);
  373. // 判断是否够highFreqSampleTimes,540s
  374. if (ts < highFreqSampleTimes)
  375. {
  376. /// 不够10分钟最近12个数据的最小值生成胎心值
  377. _logger.LogInformation($"{heartRate.Serialno} 不够10分钟最近12个数据的最小值生成胎心值");
  378. heartRate.HeartRate = lastPhr.Select(i=>i.PregnancyHeartRate).Min();
  379. heartRate.LastUpdate = lastFreqHr.LastUpdate;
  380. }
  381. _logger.LogInformation($"{heartRate.Serialno} 高频15分钟不停止的高频心率处理");
  382. await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR,highFreqSampleTimes ,upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  383. // 删除高频状态的首条记录
  384. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  385. // 设置15分的SaveAndPushFetalHeartRate业务间隔
  386. await _deviceCacheMgr.SetBizIntervalAsync(heartRate.Serialno, "SaveAndPushFetalHeartRate");
  387. _logger.LogInformation($"{heartRate.Serialno} 连续 {stopHighFreqSampleCount} 次采样心率正常,结束高频心率状态, timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval},高频状态持续{((DateTime)heartRate.LastUpdate - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,高频心率平均值:{(int)avgPhr}");
  388. }
  389. else
  390. {
  391. _logger.LogWarning($"{heartRate.Serialno} 连续 {stopHighFreqSampleCount} 次采样心率正常,设备端应该结束高频状态,但设备端没有结束高频,平台高频15分钟内已经下发过指令");
  392. }
  393. }
  394. else
  395. {
  396. _logger.LogInformation($"{heartRate.Serialno} 处于高频状态...");
  397. }
  398. #endregion
  399. }
  400. // 高频心率结束或常规心率
  401. else
  402. {
  403. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  404. // 高频心率结束
  405. if (phrFreqstatus != null)
  406. {
  407. /// 在highFreqSampleTimes=0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  408. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  409. if (highFreqSampleTimes == 0)
  410. {
  411. var lastPhr = phr.OrderByDescending(i => i.LastUpdate)
  412. .Where(i => i.LastUpdate >= phrFreqstatus?.LastUpdate)
  413. .Skip(1) // 去除首条
  414. .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh);
  415. //.Select(i => i.PregnancyHeartRate);
  416. //.Average();
  417. var avgPhr = lastPhr.Select(i => i.PregnancyHeartRate).Average();
  418. // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  419. // 计算一般心率得到胎心系数
  420. // 高频数据不建模
  421. FreqStatsEnd = firstTwoPhr[1];
  422. _logger.LogInformation($"{heartRate.Serialno} 高频状态已经持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,highFreqSampleTimes={highFreqSampleTimes}秒,即将结束高频状态,高频心率平均值:{(int)avgPhr},将下发指令");
  423. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString());
  424. //await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  425. heartRate.HeartRate = (int)avgPhr;
  426. //await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  427. // 最后一条高频心率
  428. var lastFreqHr = lastPhr.First();
  429. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)lastFreqHr.LastUpdate!, phrFreqstatus!.LastUpdate);
  430. // 判断是否够highFreqSampleTimes,540s
  431. if (ts < highFreqSampleTimes)
  432. {
  433. /// 不够10分钟最近12个数据的最小值生成胎心值
  434. _logger.LogInformation($"{heartRate.Serialno} 不够10分钟最近12个数据的最小值生成胎心值");
  435. heartRate.HeartRate = lastPhr.Select(i => i.PregnancyHeartRate).Min();
  436. heartRate.LastUpdate = lastFreqHr.LastUpdate;
  437. }
  438. _logger.LogInformation($"{heartRate.Serialno} 高频结束后的highFreqSampleTimes=0的高频心率处理");
  439. await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, highFreqSampleTimes, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  440. }
  441. /// 在highFreqSampleTimes>0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  442. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  443. if (highFreqSampleTimes > 0 && heartRate.LastUpdate >= (phrFreqstatus?.LastUpdate.AddSeconds(highFreqSampleTimes)))
  444. {
  445. // 获取高频心率数据个数
  446. var filterPhr = phr
  447. .Where(i => i.LastUpdate >= phrFreqstatus?.LastUpdate)
  448. .Skip(1)
  449. .ToList();
  450. _logger.LogInformation($"{heartRate.Serialno} 高频周期 {phrFreqstatus?.LastUpdate.ToString("yyyy-MM-dd HH:mm:ss")}--{firstTwoPhr[1].ToString("yyyy-MM-dd HH:mm:ss")} 产生高频心率数量 {filterPhr.Count} 条");
  451. // 高频心率数据大于stopHighFreqSampleCount/12个才计算胎心数据
  452. //
  453. if (filterPhr.Count > stopHighFreqSampleCount)
  454. {
  455. FreqStatsEnd = firstTwoPhr[1];
  456. var avgPhr = filterPhr
  457. .OrderByDescending(i => i.LastUpdate)
  458. .Take(stopHighFreqSampleCount) // 计算最后12条
  459. .Select(i => i.PregnancyHeartRate).Average();
  460. //_logger.LogInformation($"{heartRate.Serialno} 高频状态已经持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,约定的 {highFreqSampleTimes} 秒,即将结束高频状态,高频心率平均值:{(int)avgPhr},将下发指令");
  461. //计算高频
  462. //await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  463. heartRate.HeartRate = (int)avgPhr;
  464. //await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  465. // 判断是否够highFreqSampleTimes,540s
  466. var lastPhr = filterPhr
  467. .OrderByDescending(i => i.LastUpdate)
  468. .Take(stopHighFreqSampleCount);
  469. // 最后一条高频心率
  470. var lastFreqHr = lastPhr.First();
  471. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)lastFreqHr.LastUpdate!, phrFreqstatus!.LastUpdate);
  472. if (ts < highFreqSampleTimes)
  473. {
  474. /// 不够10分钟最近12个数据的最小值生成胎心值
  475. _logger.LogInformation($"{heartRate.Serialno} 不够10分钟最近12个数据的最小值生成胎心值");
  476. heartRate.HeartRate = lastPhr.Select(i => i.PregnancyHeartRate).Min();
  477. heartRate.LastUpdate = lastFreqHr.LastUpdate;
  478. }
  479. _logger.LogInformation($"{heartRate.Serialno} 高频结束后的在highFreqSampleTimes>0 正常心率(通常情况)触发的高频心率处理");
  480. await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, highFreqSampleTimes, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  481. }
  482. else
  483. {
  484. _logger.LogWarning($"{heartRate.Serialno} 高频心率的数据不大于{stopHighFreqSampleCount}条,不进行高频数据的胎心计算");
  485. }
  486. // 删除高频状态的首条记录
  487. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  488. // (逐条计算)计算本次常规心率的胎心数据(高频结束后,实时处理)
  489. // await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  490. await CalculateNormalFetalHeartRateScheduleAsync(heartRate);
  491. }
  492. ///不满足持续10分钟highFreqSampleTimes或出现时间倒叙
  493. ///
  494. else
  495. {
  496. // 高频结束后与常规的心率时间倒叙
  497. if ((firstTwoPhr[1] - phrFreqstatus!.LastUpdate).TotalSeconds < 0)
  498. {
  499. _logger.LogInformation($"{heartRate.Serialno} 高频结束出现时间倒叙,计算当条心率创建之前的高频心率");
  500. #region 计算当条心率创建之前的高频心率
  501. // 取得高频之后的所有数据
  502. var phrFlashBack = daysPhr.Where(p => p.LastUpdate >= phrFreqstatus!.LastUpdate)
  503. .OrderByDescending(i => i.LastUpdate);
  504. // 取得高频数据
  505. var freqCollection = phrFlashBack.ToList();
  506. //var freqCollection = new List<PregnancyHeartRateModel>();
  507. //PregnancyHeartRateModel? previousItem = null;
  508. //foreach (var item in phrFlashBack)
  509. //{
  510. // if (previousItem != null)
  511. // {
  512. // var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  513. // if (timeNextDiff <= highFreqSampleInterval)
  514. // {
  515. // freqCollection.Add(item);
  516. // }
  517. // }
  518. // previousItem = item;
  519. //}
  520. _logger.LogInformation($"{heartRate.Serialno} 高频数据个数{freqCollection.Count},触发高频开始时间{phrFreqstatus!.LastUpdate}");
  521. if (freqCollection.Count > stopHighFreqSampleCount)
  522. {
  523. // 计算高频产生的胎心
  524. var avgPhr = freqCollection
  525. .OrderByDescending(i => i.LastUpdate)
  526. .Take(stopHighFreqSampleCount) // 计算最后12条
  527. .Select(i => i.PregnancyHeartRate).Average();
  528. heartRate.HeartRate = (int)avgPhr;
  529. // await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  530. //_logger.LogInformation($"{heartRate.Serialno} 高频数据个数{freqCollection.Count},触发高频开始时间{phrFreqstatus!.LastUpdate},高频心率平均值:{(int)avgPhr}");
  531. // 判断是否够highFreqSampleTimes,540s
  532. var lastPhr = freqCollection
  533. .OrderByDescending(i => i.LastUpdate)
  534. .Take(stopHighFreqSampleCount);
  535. // 最后一条高频心率
  536. var lastFreqHr = lastPhr.First();
  537. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)lastFreqHr.LastUpdate!, phrFreqstatus!.LastUpdate);
  538. if (ts < highFreqSampleTimes)
  539. {
  540. /// 不够10分钟最近12个数据的最小值生成胎心值
  541. _logger.LogInformation($"{heartRate.Serialno} 不够10分钟最近12个数据的最小值生成胎心值");
  542. heartRate.HeartRate = lastPhr.Select(i => i.PregnancyHeartRate).Min();
  543. heartRate.LastUpdate = lastFreqHr.LastUpdate;
  544. }
  545. _logger.LogInformation($"{heartRate.Serialno} 高频结束后的时间倒序的正常心率触发的高频心率处理");
  546. await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, highFreqSampleTimes, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  547. _logger.LogInformation($"{heartRate.Serialno} 高频数据个数{freqCollection.Count},触发高频开始时间{phrFreqstatus!.LastUpdate},时间倒叙");
  548. }
  549. else
  550. {
  551. _logger.LogInformation($"{heartRate.Serialno} 时间倒叙触发计算高频心率的数据不足{stopHighFreqSampleCount}条,不进行胎心计算");
  552. }
  553. #endregion
  554. }
  555. else
  556. {
  557. _logger.LogInformation($"{heartRate.Serialno} 高频持续时间不足{highFreqSampleTimes},只持续{(firstTwoPhr[1] - phrFreqstatus!.LastUpdate).TotalSeconds} 秒");
  558. }
  559. // 删除高频状态的首条记录
  560. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  561. // (逐条计算)计算本次常规心率的胎心数据(高频结束后,实时处理)
  562. //await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  563. await CalculateNormalFetalHeartRateScheduleAsync(heartRate);
  564. }
  565. // 删除高频状态的首条记录
  566. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  567. _logger.LogInformation($"{heartRate.Serialno} 超时结束高频心率状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval},高频状态持续{(firstTwoPhr[1] - phrFreqstatus!.LastUpdate).TotalSeconds} 秒");
  568. //// 使用延后计算
  569. //var fhrScheduleKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  570. //var fhrScheduleTTL = 60;
  571. //await SetIntervalTriggerAsync(fhrScheduleKey, heartRate.Serialno, fhrScheduleTTL, heartRate);
  572. }
  573. // 常规心率(本次心率可能是高频心率的首条,所以要使用延后计算胎心率)
  574. else
  575. {
  576. // 本次心率可能是高频心率的首条,所以要使用本次常规心率延后计算胎心率
  577. //var fhrScheduleKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  578. //var fhrScheduleTTL = 30;
  579. //await SetIntervalTriggerAsync(fhrScheduleKey, heartRate.Serialno, fhrScheduleTTL, heartRate);
  580. //_logger.LogInformation($"{heartRate.Serialno} 延时50秒,判断当前数据是否为高频首条");
  581. // 本次心率可能是高频心率的首条,所以要使用本次常规心率延后计算胎心率 查询30秒后是否有高频缓存
  582. Thread thread = new(async () =>
  583. {
  584. try
  585. {
  586. #region 休眠highFreqSampleInterval2秒
  587. var startTime = DateTime.Now;
  588. //var highFreqSampleInterval2 = (int)watchConfig!["highFreqSampleInterval"]!+5;
  589. var highFreqSampleInterval2 = highFreqSampleInterval;
  590. var during = TimeSpan.FromSeconds(highFreqSampleInterval2);
  591. while (true)
  592. {
  593. if (DateTime.Now - startTime > during)
  594. {
  595. break;
  596. }
  597. await Task.Delay(TimeSpan.FromSeconds(1));
  598. }
  599. #endregion
  600. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  601. _logger.LogInformation($"phrFreqstatus==null:{phrFreqstatus == null}");
  602. _logger.LogInformation($"phrFreqstatus.LastUpdate < heartRate.LastUpdate:{phrFreqstatus?.LastUpdate < heartRate.LastUpdate}");
  603. if (phrFreqstatus == null || phrFreqstatus.LastUpdate < heartRate.LastUpdate)
  604. {
  605. // (逐条计算)常规心率
  606. //await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  607. //_logger.LogInformation($"{heartRate.Serialno} 计算常规心率");
  608. // 延时计算常规心率
  609. await CalculateNormalFetalHeartRateScheduleAsync(heartRate);
  610. }
  611. }
  612. catch (Exception ex)
  613. {
  614. _logger.LogError($"处理延时计算异常:{ex.Message}, {ex.StackTrace}");
  615. }
  616. });
  617. thread.Start();
  618. }
  619. }
  620. #endregion
  621. }
  622. else
  623. {
  624. _logger.LogInformation($"{heartRate.Serialno} 记录不足30条,建模中");
  625. }
  626. }
  627. }
  628. catch (Exception ex)
  629. {
  630. _logger.LogError($"{heartRate.Serialno} 处理孕妇心率数据异常 \n{ex.Message}\n{ex.StackTrace}");
  631. }
  632. }
  633. /// <summary>
  634. /// (逐条计算)常规心率计算胎心数据
  635. /// </summary>
  636. /// <param name="heartRate"></param>
  637. /// <param name="upperAlarmThreshold"></param>
  638. /// <param name="lowerAlarmThreshold"></param>
  639. /// <param name="intervalFHR"></param>
  640. /// <param name="commonPHR"></param>
  641. /// <returns></returns>
  642. /**
  643. private async Task CalculateNormalFetalHeartRateAsync(HisGpsHeartRate heartRate, int upperAlarmThreshold, int lowerAlarmThreshold, int intervalFHR, PregnancyCommonHeartRateModel? commonPHR)
  644. {
  645. // 上15分钟的数据
  646. // 获取当前时间
  647. DateTime nowInterval = (DateTime)heartRate.LastUpdate!;
  648. if (nowInterval.Second > 0)
  649. {
  650. nowInterval = nowInterval.AddMinutes(1);
  651. }
  652. // 计算last_update到上一间隔的分钟数
  653. int minutesToSubtract = nowInterval.Minute % intervalFHR;
  654. // 计算上一间隔的时间
  655. DateTime previousInterval = nowInterval.AddMinutes(-minutesToSubtract).AddSeconds(-nowInterval.Second).AddMilliseconds(-nowInterval.Millisecond);
  656. // 使用 last_update 上一刻
  657. var sampleTimeFHR = DateTimeUtil.ConvertToTimeStamp(previousInterval).ToString();
  658. // 计算last_update到下一间隔的分钟数
  659. int minutesToAdd = intervalFHR - (nowInterval.Minute % intervalFHR);
  660. if (minutesToAdd == intervalFHR)
  661. {
  662. minutesToAdd = 0; // 如果已经是间隔,则不需要增加分钟
  663. }
  664. // 计算下一间隔的时间
  665. DateTime nextInterval = nowInterval.AddMinutes(minutesToAdd)
  666. .AddSeconds(-nowInterval.Second)
  667. .AddMilliseconds(-nowInterval.Millisecond);
  668. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  669. var normalPhrStatStartTime = nextInterval.AddMinutes(-intervalFHR);
  670. var normalPhrStatEndTime = nextInterval;
  671. _logger.LogInformation($"{heartRate.Serialno} 计算胎心数据, 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} ");
  672. var filteredPhr = daysPhr
  673. // 使用 last_update 下一刻
  674. .Where(i => i.LastUpdate <= normalPhrStatEndTime && i.LastUpdate >= normalPhrStatStartTime)
  675. .ToList();
  676. if (filteredPhr.Count == 0)
  677. {
  678. _logger.LogWarning($"{heartRate.Serialno} 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} 孕妇心率数据不足,{filteredPhr.Count}条记录");
  679. return;
  680. }
  681. var phrValue = filteredPhr.Count == 1
  682. ? filteredPhr.First().PregnancyHeartRate
  683. : filteredPhr.Average(i => i.PregnancyHeartRate);
  684. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, phrValue, sampleTimeFHR);
  685. //await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, phrValue, sampleTimeFHR, normalPhrStatStartTime, normalPhrStatEndTime);
  686. heartRate.HeartRate = (int)phrValue;
  687. //await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, sampleTimeFHR, normalPhrStatStartTime, normalPhrStatEndTime);
  688. }
  689. */
  690. /// <summary>
  691. /// 延时计算
  692. /// </summary>
  693. /// <param name="heartRate"></param>
  694. /// <returns></returns>
  695. public async Task CalculateNormalFetalHeartRateScheduleAsync(HisGpsHeartRate heartRate)
  696. {
  697. var fhrScheduleKey = $"health_monitor/schedule_push/cal_normalphr_fetal_heart_rate/imei/{heartRate.Serialno}";
  698. DateTime nowInterval = DateTime.Now;
  699. if (nowInterval.Second > 0)
  700. {
  701. nowInterval = nowInterval.AddMinutes(1);
  702. }
  703. // 需要减去的分钟
  704. int minutesToSubtract = nowInterval.Minute % INTERVAL_FHR;
  705. var nextRunTime=nowInterval
  706. .AddMinutes(-minutesToSubtract)
  707. .AddMinutes(INTERVAL_FHR);
  708. TimeSpan timeUntilNextRun = nextRunTime - nowInterval;
  709. var ttl = (long)timeUntilNextRun.TotalSeconds;
  710. await SetIntervalTriggerAsync(fhrScheduleKey, heartRate.Serialno, ttl, heartRate);
  711. }
  712. /// <summary>
  713. ///
  714. /// </summary>
  715. /// <param name="heartRate"></param>
  716. /// <param name="commonPHR"></param>
  717. /// <param name="upperAlarmThreshold"></param>
  718. /// <param name="lowerAlarmThreshold"></param>
  719. /// <param name="phrValue"></param>
  720. /// <param name="sampleTime"></param>
  721. /// <param name="statStartTime"></param>
  722. /// <param name="statEndTime"></param>
  723. /// <returns></returns>
  724. private async Task SaveAndPushFetalHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int upperAlarmThreshold, int lowerAlarmThreshold, double phrValue, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  725. {
  726. // 计算胎心=孕妇心率*系数
  727. /**
  728. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  729. fetalHeartRate = fetalHeartRate > 220 ? 220 : fetalHeartRate; // 胎心的最大值调整为220,超过都按该值220输出
  730. if (fetalHeartRate >= 220)
  731. {
  732. // 先使用最小系数计算
  733. var statMaxValueFprCoefficient = commonPHR?.StatMaxValueFprCoefficient!;
  734. var statMinValueFprCoefficient = commonPHR?.StatMinValueFprCoefficient!;
  735. var coefficient = statMaxValueFprCoefficient < statMinValueFprCoefficient ? statMaxValueFprCoefficient : statMinValueFprCoefficient;
  736. fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  737. if (fetalHeartRate < 220)
  738. {
  739. _logger.LogWarning($"{heartRate.Serialno} 使用极值系数 {coefficient} ,建模数据可能出现异常,请检查");
  740. }
  741. else
  742. {
  743. fetalHeartRate = 220;
  744. _logger.LogWarning($"{heartRate.Serialno} 使用所有系数都不能放映实际,建模数据可能出现异常,请检查");
  745. }
  746. }
  747. */
  748. #region 胎心系数使用基于心率与中位数对比
  749. var coefficient = 0f;
  750. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  751. if (heartRate.HeartRate < commonPHR!.Mode)
  752. {
  753. coefficient = commonPHR.StatMinValueFprCoefficient!;
  754. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  755. }
  756. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  757. else if (heartRate.HeartRate > commonPHR.Mode)
  758. {
  759. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  760. {
  761. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  762. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  763. }
  764. else
  765. {
  766. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  767. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  768. }
  769. }
  770. else
  771. {
  772. coefficient = commonPHR.StatModeAvgFprCoefficient;
  773. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  774. }
  775. #endregion
  776. var fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  777. // 胎心的最大值调整为220,超过都按该值220输出
  778. // fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  779. if (fetalHeartRate > 220)
  780. {
  781. fetalHeartRate = 220;
  782. _logger.LogWarning($"{heartRate.Serialno} 大于220,按220输出,计算因子:孕妇心率 {heartRate.HeartRate},系数 {coefficient},周期 周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  783. }
  784. // 胎心的最小值调整为90,超过都按该值90
  785. if (fetalHeartRate < 90)
  786. {
  787. fetalHeartRate = 90;
  788. _logger.LogWarning($"{heartRate.Serialno} 小于90,按90输出,计算因子:孕妇心率 {heartRate.HeartRate},系数 {coefficient},周期 周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  789. }
  790. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  791. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  792. if (phrFreqstatus == null) isAbnormal = 0;
  793. var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  794. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  795. //if (!isFreq)
  796. //{
  797. // statStartTime = heartRate.LastUpdate;
  798. //
  799. //}
  800. // 保存到 数据服务 MySQL 数据库
  801. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  802. {
  803. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  804. PersonId = commonPHR!.PersonId,
  805. Serialno = heartRate.Serialno,
  806. HeartRate = fetalHeartRate,
  807. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  808. IsAbnormal = isAbnormal,
  809. StatStartTime = statStartTime,
  810. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  811. CreateTime = DateTime.Now,
  812. Method = 1,
  813. IsDisplay = 1,
  814. DeviceKey = commonPHR!.DeviceKey
  815. };
  816. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  817. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  818. // 推送最后一条常规心率计算的胎心数据到iot设备
  819. #region 推送最后一条常规心率计算的胎心数据到iot设备
  820. // 高频(<=12)-常规
  821. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  822. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  823. {
  824. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  825. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  826. }
  827. // 高频(13)-常规-高频(13)
  828. if (phrFreqstatus != null)
  829. {
  830. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  831. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  832. // 获取高频数据
  833. var freqCollection = new List<PregnancyHeartRateModel>();
  834. PregnancyHeartRateModel? previousItem = null;
  835. foreach (var item in phr)
  836. {
  837. if (previousItem != null)
  838. {
  839. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  840. if (timeNextDiff <= 60)
  841. {
  842. freqCollection.Add(item);
  843. }
  844. }
  845. // 高频最后一条
  846. if (lastPhr.MessageId == item.MessageId)
  847. {
  848. freqCollection.Add(item);
  849. }
  850. previousItem = item;
  851. }
  852. //去除高频
  853. foreach (var item in freqCollection)
  854. {
  855. phr.Remove(item);
  856. }
  857. lastPhr = phr.FirstOrDefault();
  858. if (lastPhr?.MessageId == heartRate.MessageId)
  859. {
  860. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  861. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  862. }
  863. }
  864. #endregion
  865. #region 高频心率计算胎心数据到iot设备
  866. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  867. if (phrFreqstatus != null && isAbnormal!=0)
  868. {
  869. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  870. }
  871. #endregion
  872. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  873. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  874. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  875. // 胎心数据推送到第三方
  876. var topic = "topic.push.third";
  877. var fhrThridMsg = new
  878. {
  879. messageId = fhrMsgId,
  880. topic = topic,
  881. time = fhrMsgTime,
  882. data = new
  883. {
  884. imei = heartRate.Serialno,
  885. value = fetalHeartRate,
  886. isAbnormal,
  887. type = "fetalHeart"
  888. }
  889. };
  890. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  891. // 胎心数据推送到微信
  892. if (isAbnormal != 0)
  893. {
  894. topic = "topic.push.wx";
  895. var fhrMsg = new
  896. {
  897. messageId = fhrMsgId,
  898. topic = topic,
  899. time = fhrMsgTime,
  900. data = new
  901. {
  902. deviceId = device?.DeviceId,
  903. imei = heartRate.Serialno,
  904. alarmTypeId = 12,
  905. alarmDeviceName = heartRate.Serialno,
  906. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  907. address = string.Empty,
  908. deviceKey = device?.DeviceId
  909. }
  910. };
  911. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  912. }
  913. }
  914. private async Task SaveAndPushFetalHeartRateEndFreqHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int upperAlarmThreshold, int lowerAlarmThreshold, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  915. {
  916. // 计算胎心=孕妇心率*系数
  917. /**
  918. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  919. fetalHeartRate = fetalHeartRate > 220 ? 220 : fetalHeartRate; // 胎心的最大值调整为220,超过都按该值220输出
  920. if (fetalHeartRate >= 220)
  921. {
  922. // 先使用最小系数计算
  923. var statMaxValueFprCoefficient = commonPHR?.StatMaxValueFprCoefficient!;
  924. var statMinValueFprCoefficient = commonPHR?.StatMinValueFprCoefficient!;
  925. var coefficient = statMaxValueFprCoefficient < statMinValueFprCoefficient ? statMaxValueFprCoefficient : statMinValueFprCoefficient;
  926. fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  927. if (fetalHeartRate < 220)
  928. {
  929. _logger.LogWarning($"{heartRate.Serialno} 使用极值系数 {coefficient} ,建模数据可能出现异常,请检查");
  930. }
  931. else
  932. {
  933. fetalHeartRate = 220;
  934. _logger.LogWarning($"{heartRate.Serialno} 使用所有系数都不能放映实际,建模数据可能出现异常,请检查");
  935. }
  936. }
  937. */
  938. #region 胎心系数使用基于心率与中位数对比
  939. var coefficient = 0f;
  940. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  941. if (heartRate.HeartRate < commonPHR!.Mode)
  942. {
  943. coefficient = commonPHR.StatMinValueFprCoefficient!;
  944. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  945. }
  946. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  947. else if (heartRate.HeartRate > commonPHR.Mode)
  948. {
  949. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  950. {
  951. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  952. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  953. }
  954. else
  955. {
  956. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  957. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  958. }
  959. }
  960. else
  961. {
  962. coefficient = commonPHR.StatModeAvgFprCoefficient;
  963. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  964. }
  965. #endregion
  966. var fetalHeartRate = SafeType.SafeInt(heartRate.HeartRate! * coefficient);
  967. // 胎心的最大值调整为220,超过都按该值220输出
  968. // fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  969. if (fetalHeartRate > 220)
  970. {
  971. fetalHeartRate = 220;
  972. _logger.LogWarning($"{heartRate.Serialno} 大于220,按220输出,计算因子:孕妇心率 {heartRate.HeartRate},系数 {coefficient},周期 周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  973. }
  974. // 胎心的最小值调整为90,超过都按该值90
  975. if (fetalHeartRate < 90)
  976. {
  977. fetalHeartRate = 90;
  978. _logger.LogWarning($"{heartRate.Serialno} 小于90,按90输出,计算因子:孕妇心率 {heartRate.HeartRate},系数 {coefficient},周期 周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  979. }
  980. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  981. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  982. if (phrFreqstatus == null) isAbnormal = 0;
  983. var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  984. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  985. //if (!isFreq)
  986. //{
  987. // statStartTime = heartRate.LastUpdate;
  988. //
  989. //}
  990. // 保存到 数据服务 MySQL 数据库
  991. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  992. {
  993. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  994. PersonId = commonPHR!.PersonId,
  995. Serialno = heartRate.Serialno,
  996. HeartRate = fetalHeartRate,
  997. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  998. IsAbnormal = isAbnormal,
  999. StatStartTime = statStartTime,
  1000. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  1001. CreateTime = DateTime.Now,
  1002. Method = 1,
  1003. IsDisplay = 1,
  1004. DeviceKey = commonPHR!.DeviceKey
  1005. };
  1006. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  1007. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  1008. // 推送最后一条常规心率计算的胎心数据到iot设备
  1009. #region 推送最后一条常规心率计算的胎心数据到iot设备
  1010. // 高频(<=12)-常规
  1011. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  1012. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  1013. {
  1014. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1015. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  1016. }
  1017. // 高频(13)-常规-高频(13)
  1018. if (phrFreqstatus != null)
  1019. {
  1020. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  1021. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1022. // 获取高频数据
  1023. var freqCollection = new List<PregnancyHeartRateModel>();
  1024. PregnancyHeartRateModel? previousItem = null;
  1025. foreach (var item in phr)
  1026. {
  1027. if (previousItem != null)
  1028. {
  1029. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1030. if (timeNextDiff <= 60)
  1031. {
  1032. freqCollection.Add(item);
  1033. }
  1034. }
  1035. // 高频最后一条
  1036. if (lastPhr.MessageId == item.MessageId)
  1037. {
  1038. freqCollection.Add(item);
  1039. }
  1040. previousItem = item;
  1041. }
  1042. //去除高频
  1043. foreach (var item in freqCollection)
  1044. {
  1045. phr.Remove(item);
  1046. }
  1047. lastPhr = phr.FirstOrDefault();
  1048. if (lastPhr?.MessageId == heartRate.MessageId)
  1049. {
  1050. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1051. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  1052. }
  1053. }
  1054. #endregion
  1055. #region 高频心率计算胎心数据到iot设备
  1056. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  1057. if (phrFreqstatus != null && isAbnormal != 0)
  1058. {
  1059. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1060. }
  1061. #endregion
  1062. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  1063. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  1064. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  1065. // 胎心数据推送到第三方
  1066. var topic = "topic.push.third";
  1067. var fhrThridMsg = new
  1068. {
  1069. messageId = fhrMsgId,
  1070. topic = topic,
  1071. time = fhrMsgTime,
  1072. data = new
  1073. {
  1074. imei = heartRate.Serialno,
  1075. value = fetalHeartRate,
  1076. isAbnormal,
  1077. type = "fetalHeart"
  1078. }
  1079. };
  1080. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  1081. // 胎心数据推送到微信
  1082. if (isAbnormal != 0)
  1083. {
  1084. topic = "topic.push.wx";
  1085. var fhrMsg = new
  1086. {
  1087. messageId = fhrMsgId,
  1088. topic = topic,
  1089. time = fhrMsgTime,
  1090. data = new
  1091. {
  1092. deviceId = device?.DeviceId,
  1093. imei = heartRate.Serialno,
  1094. alarmTypeId = 12,
  1095. alarmDeviceName = heartRate.Serialno,
  1096. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  1097. address = string.Empty,
  1098. deviceKey = device?.DeviceId
  1099. }
  1100. };
  1101. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  1102. }
  1103. }
  1104. /// <summary>
  1105. /// 高频胎心处理
  1106. /// 1. 高频15分钟不停止的高频心率处理
  1107. /// 2. 高频结束后的highFreqSampleTimes=0的高频心率处理
  1108. /// 3. 高频结束后的在highFreqSampleTimes>0 正常心率触发的高频心率处理(常态)
  1109. /// 4. 高频结束后的时间倒序的正常心率触发的高频心率处理
  1110. /// 5. 高频结束后计算胎心数据,防止结束后与常规心理的胎心处理过长,定时器时长highFreqSampleInterval触发的高频心率处理
  1111. /// </summary>
  1112. /// <param name="heartRate"></param>
  1113. /// <param name="commonPHR"></param>
  1114. /// <param name="highFreqSampleTimes"></param>
  1115. /// <param name="upperAlarmThreshold"></param>
  1116. /// <param name="lowerAlarmThreshold"></param>
  1117. /// <param name="sampleTime"></param>
  1118. /// <param name="statStartTime"></param>
  1119. /// <param name="statEndTime"></param>
  1120. /// <returns></returns>
  1121. private async Task SaveAndPushFetalHeartRateEndFreqHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int highFreqSampleTimes, int upperAlarmThreshold, int lowerAlarmThreshold, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  1122. {
  1123. // 计算胎心=孕妇心率*系数
  1124. #region 胎心系数使用基于心率与中位数对比
  1125. var coefficient = 0f;
  1126. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  1127. if (heartRate.HeartRate < commonPHR!.Mode)
  1128. {
  1129. coefficient = commonPHR.StatMinValueFprCoefficient!;
  1130. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  1131. }
  1132. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  1133. else if (heartRate.HeartRate > commonPHR.Mode)
  1134. {
  1135. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  1136. {
  1137. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  1138. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  1139. }
  1140. else
  1141. {
  1142. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  1143. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  1144. }
  1145. }
  1146. else
  1147. {
  1148. coefficient = commonPHR.StatModeAvgFprCoefficient;
  1149. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  1150. }
  1151. #endregion
  1152. var fetalHeartRate = SafeType.SafeInt(heartRate.HeartRate! * coefficient);
  1153. // 胎心的最大值调整为220,超过都按该值220输出
  1154. // fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  1155. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  1156. #region 判断是否够highFreqSampleTimes,540s
  1157. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)heartRate.LastUpdate!, phrFreqstatus!.LastUpdate);
  1158. // 判断是否够highFreqSampleTimes,540s
  1159. ///高频时长不足10分钟停止高频的胎心值生成说明:最近12个数据的最小值生成胎心值,
  1160. ///对于小于高频下限阀值取高频下限阀值进行转换;
  1161. ///对于高于高频上限阀值取高频上限阀值进行转换。并输出相关日志后续进行数据分析。
  1162. if (ts < highFreqSampleTimes)
  1163. {
  1164. if (fetalHeartRate > upperAlarmThreshold)
  1165. {
  1166. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,计算胎心值 {fetalHeartRate} 高于高频警告上限阀值{upperAlarmThreshold},最后胎心值{upperAlarmThreshold}");
  1167. fetalHeartRate = upperAlarmThreshold;
  1168. }
  1169. else if (fetalHeartRate < lowerAlarmThreshold)
  1170. {
  1171. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,计算胎心值 {fetalHeartRate} 低于高频警告下限阀值 {lowerAlarmThreshold},最后胎心值{lowerAlarmThreshold}");
  1172. fetalHeartRate = lowerAlarmThreshold;
  1173. }
  1174. else
  1175. {
  1176. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,在高频警告下限阀值 {lowerAlarmThreshold} 和 高频警告上限阀值:{upperAlarmThreshold}之间,最后胎心值{fetalHeartRate}");
  1177. }
  1178. }
  1179. // 超过highFreqSampleTimes,540s
  1180. else
  1181. {
  1182. if (fetalHeartRate > 220)
  1183. {
  1184. fetalHeartRate = 220;
  1185. _logger.LogWarning($"{heartRate.Serialno} 大于220,按220输出,计算因子:孕妇心率 {heartRate.HeartRate},系数 {coefficient},周期 周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1186. }
  1187. // 胎心的最小值调整为90,超过都按该值90
  1188. if (fetalHeartRate < 90)
  1189. {
  1190. fetalHeartRate = 90;
  1191. _logger.LogWarning($"{heartRate.Serialno} 小于90,按90输出,计算因子:孕妇心率 {heartRate.HeartRate},系数 {coefficient},周期 周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1192. }
  1193. }
  1194. #endregion
  1195. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  1196. if (phrFreqstatus == null) isAbnormal = 0;
  1197. var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  1198. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1199. //if (!isFreq)
  1200. //{
  1201. // statStartTime = heartRate.LastUpdate;
  1202. //
  1203. //}
  1204. // 保存到 数据服务 MySQL 数据库
  1205. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  1206. {
  1207. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  1208. PersonId = commonPHR!.PersonId,
  1209. Serialno = heartRate.Serialno,
  1210. HeartRate = fetalHeartRate,
  1211. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  1212. IsAbnormal = isAbnormal,
  1213. StatStartTime = statStartTime,
  1214. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  1215. CreateTime = DateTime.Now,
  1216. Method = 1,
  1217. IsDisplay = 1,
  1218. DeviceKey = commonPHR!.DeviceKey
  1219. };
  1220. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  1221. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  1222. // 推送最后一条常规心率计算的胎心数据到iot设备
  1223. #region 推送最后一条常规心率计算的胎心数据到iot设备
  1224. // 高频(<=12)-常规
  1225. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  1226. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  1227. {
  1228. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1229. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  1230. }
  1231. // 高频(13)-常规-高频(13)
  1232. if (phrFreqstatus != null)
  1233. {
  1234. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  1235. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1236. // 获取高频数据
  1237. var freqCollection = new List<PregnancyHeartRateModel>();
  1238. PregnancyHeartRateModel? previousItem = null;
  1239. foreach (var item in phr)
  1240. {
  1241. if (previousItem != null)
  1242. {
  1243. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1244. if (timeNextDiff <= 60)
  1245. {
  1246. freqCollection.Add(item);
  1247. }
  1248. }
  1249. // 高频最后一条
  1250. if (lastPhr.MessageId == item.MessageId)
  1251. {
  1252. freqCollection.Add(item);
  1253. }
  1254. previousItem = item;
  1255. }
  1256. //去除高频
  1257. foreach (var item in freqCollection)
  1258. {
  1259. phr.Remove(item);
  1260. }
  1261. lastPhr = phr.FirstOrDefault();
  1262. if (lastPhr?.MessageId == heartRate.MessageId)
  1263. {
  1264. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1265. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  1266. }
  1267. }
  1268. #endregion
  1269. #region 高频心率计算胎心数据到iot设备
  1270. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  1271. if (phrFreqstatus != null && isAbnormal != 0)
  1272. {
  1273. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1274. }
  1275. #endregion
  1276. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  1277. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  1278. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  1279. // 胎心数据推送到第三方
  1280. var topic = "topic.push.third";
  1281. var fhrThridMsg = new
  1282. {
  1283. messageId = fhrMsgId,
  1284. topic = topic,
  1285. time = fhrMsgTime,
  1286. data = new
  1287. {
  1288. imei = heartRate.Serialno,
  1289. value = fetalHeartRate,
  1290. isAbnormal,
  1291. type = "fetalHeart"
  1292. }
  1293. };
  1294. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  1295. // 胎心数据推送到微信
  1296. if (isAbnormal != 0)
  1297. {
  1298. topic = "topic.push.wx";
  1299. var fhrMsg = new
  1300. {
  1301. messageId = fhrMsgId,
  1302. topic = topic,
  1303. time = fhrMsgTime,
  1304. data = new
  1305. {
  1306. deviceId = device?.DeviceId,
  1307. imei = heartRate.Serialno,
  1308. alarmTypeId = 12,
  1309. alarmDeviceName = heartRate.Serialno,
  1310. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  1311. address = string.Empty,
  1312. deviceKey = device?.DeviceId
  1313. }
  1314. };
  1315. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  1316. }
  1317. }
  1318. private async Task SetIntervalTriggerAsync(string key, string imei, long interval, HisGpsHeartRate heartRate)
  1319. {
  1320. // var key = $"health_monitor/schedule_push/{type}/imei/{imei}";
  1321. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  1322. if (string.IsNullOrWhiteSpace(schedulePush))
  1323. {
  1324. var now = DateTime.Now;
  1325. var timeNextRun = now.Add(TimeSpan.FromSeconds(interval));
  1326. var data = new
  1327. {
  1328. imei,
  1329. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1330. ttl = interval,
  1331. next_run_time = timeNextRun.ToString("yyyy-MM-dd HH:mm:ss"),
  1332. trigger = heartRate,
  1333. };
  1334. var result = JsonConvert.SerializeObject(data);
  1335. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  1336. }
  1337. }
  1338. /// <summary>
  1339. /// 高频延时计算触发器
  1340. /// </summary>
  1341. /// <param name="key"></param>
  1342. /// <param name="imei"></param>
  1343. /// <param name="interval"></param>
  1344. /// <param name="heartRate"></param>
  1345. /// <returns></returns>
  1346. private async Task SetFreqHeartRateTriggerAsync(string key, string imei, long interval, HisGpsHeartRate? heartRate=null)
  1347. {
  1348. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  1349. if (string.IsNullOrWhiteSpace(schedulePush))
  1350. {
  1351. var now = DateTime.Now;
  1352. var data = new
  1353. {
  1354. imei,
  1355. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1356. lease = interval,
  1357. trigger = heartRate,
  1358. };
  1359. var result = JsonConvert.SerializeObject(data);
  1360. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  1361. }
  1362. else
  1363. {
  1364. // 不断修改时长,直到最后的一条高频胎心
  1365. await _serviceEtcd.PutValAsync(key, schedulePush, interval, false).ConfigureAwait(false);
  1366. }
  1367. }
  1368. /// <summary>
  1369. /// 去除高频数据
  1370. /// </summary>
  1371. /// <param name="phr"></param>
  1372. /// <param name="highFreqSampleInterva"></param>
  1373. /// <returns></returns>
  1374. private static List<PregnancyHeartRateModel> GetNonFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr,int highFreqSampleInterval)
  1375. {
  1376. //phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1377. //var result = new List<PregnancyHeartRateModel>();
  1378. //PregnancyHeartRateModel? previousItem = null;
  1379. //foreach (var item in phr)
  1380. //{
  1381. // if (previousItem != null)
  1382. // {
  1383. // var timeNextDiff =(previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1384. // if (timeNextDiff > highFreqSampleInterval)
  1385. // {
  1386. // result.Add(previousItem);
  1387. // }
  1388. // }
  1389. // previousItem = item;
  1390. //}
  1391. //// 添加上一个
  1392. //if (previousItem != null)
  1393. //{
  1394. // result.Add(previousItem);
  1395. //}
  1396. //return result;
  1397. #region 反向
  1398. var phr1 = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1399. var result = new List<PregnancyHeartRateModel>();
  1400. PregnancyHeartRateModel? previousItem1 = null;
  1401. foreach (var item in phr1)
  1402. {
  1403. if (previousItem1 != null)
  1404. {
  1405. var timeNextDiff = (previousItem1!.LastUpdate - item.LastUpdate).TotalSeconds;
  1406. if (timeNextDiff > highFreqSampleInterval)
  1407. {
  1408. result.Add(previousItem1);
  1409. }
  1410. }
  1411. previousItem1 = item;
  1412. }
  1413. // 添加上一个
  1414. if (previousItem1 != null)
  1415. {
  1416. result.Add(previousItem1);
  1417. }
  1418. #endregion
  1419. #region 正向
  1420. var phr2 = phr.OrderByDescending(i => i.LastUpdate).ToList(); ;
  1421. var freqCollection = new List<PregnancyHeartRateModel>();
  1422. PregnancyHeartRateModel? previousItem = null;
  1423. foreach (var item in phr2)
  1424. {
  1425. if (previousItem != null)
  1426. {
  1427. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1428. if (timeNextDiff <= highFreqSampleInterval)
  1429. {
  1430. freqCollection.Add(item);
  1431. }
  1432. }
  1433. previousItem = item;
  1434. }
  1435. //去除高频
  1436. foreach (var item in freqCollection)
  1437. {
  1438. phr2.Remove(item);
  1439. }
  1440. #endregion
  1441. // 交集
  1442. var commonElements = phr2.Intersect(result).ToList();
  1443. return commonElements;
  1444. }
  1445. /// <summary>
  1446. /// 获取高频数据
  1447. /// </summary>
  1448. /// <param name="phr"></param>
  1449. /// <param name="highFreqSampleInterval"></param>
  1450. /// <returns></returns>
  1451. private static List<PregnancyHeartRateModel> GetFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr, int highFreqSampleInterval)
  1452. {
  1453. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1454. var freqCollection = new List<PregnancyHeartRateModel>();
  1455. PregnancyHeartRateModel? previousItem = null;
  1456. foreach (var item in phr)
  1457. {
  1458. if (previousItem != null)
  1459. {
  1460. var timeNextDiff = (previousItem.LastUpdate - item.LastUpdate).TotalSeconds;
  1461. if (timeNextDiff <= highFreqSampleInterval)
  1462. {
  1463. freqCollection.Add(previousItem);
  1464. }
  1465. }
  1466. previousItem = item;
  1467. }
  1468. // 检查最后一条是否高频
  1469. if (previousItem != null && (phr.Last().LastUpdate - previousItem.LastUpdate).TotalSeconds <= highFreqSampleInterval)
  1470. {
  1471. freqCollection.Add(previousItem);
  1472. }
  1473. return freqCollection;
  1474. }
  1475. }
  1476. }