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.

1061 line
58KB

  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. // 告警上限阀值
  146. var upperAlarmThreshold = (int)watchConfig["upperAlarmThreshold"]!;
  147. // 告警下限阀值
  148. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  149. // EDOC
  150. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  151. // interval (分钟) 固定15分钟
  152. var intervalFHR = 15;//int)watchConfig["interval"]!;
  153. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  154. var phr = daysPhr
  155. .Where(p => p.LastUpdate <= heartRate.LastUpdate)
  156. .ToList();
  157. var nonFreqPhr = GetNonFreqPregnancyHeartRate(phr, highFreqSampleInterval);
  158. if (nonFreqPhr.Count >= 30)
  159. {
  160. #region 定时计算胎动数据触发器两小时间隔开始
  161. /**
  162. var fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}";
  163. ///// 计算 0 点秒数
  164. var fetalMovementLastUpdate = (DateTime)heartRate.LastUpdate!;
  165. DateTime fmScheduleNow = DateTime.Now;
  166. // 小于两小时
  167. if (fmScheduleNow > fetalMovementLastUpdate && (fmScheduleNow - fetalMovementLastUpdate).TotalHours <= 2)
  168. {
  169. var rand = new Random();
  170. var pushSec = rand.Next(59);
  171. int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  172. var scheduleHourDiff = SCHEDULE_HOUR
  173. .Where(h => h > fetalMovementLastUpdate.Hour)
  174. .OrderBy(h => h - fetalMovementLastUpdate.Hour)
  175. .FirstOrDefault() - fetalMovementLastUpdate.Hour;
  176. var scheduleTime = fetalMovementLastUpdate.AddHours(scheduleHourDiff);
  177. DateTime nextRunTime = new(scheduleTime.Year, scheduleTime.Month, scheduleTime.Day, scheduleTime.Hour, pushMin, pushSec);
  178. TimeSpan timeUntilNextRun = nextRunTime - fmScheduleNow;
  179. var ttl = (long)timeUntilNextRun.TotalSeconds;
  180. await SetIntervalTriggerAsync(fetalMovementKey, heartRate.Serialno, ttl, heartRate);
  181. }
  182. */
  183. #endregion
  184. #region 定时计算胎动数据触发器两小时间隔开始(奇数小时计算)
  185. var fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}";
  186. var rand = new Random();
  187. var pushSec = rand.Next(59);
  188. int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  189. DateTime fmScheduleNow = DateTime.Now;
  190. int hour = fmScheduleNow.Hour;
  191. int selectedScheduleHour;
  192. // 使用模运算来获取相应的ODD_SCHEDULE_HOUR
  193. if (hour % 2 == 0)
  194. {
  195. selectedScheduleHour = ODD_SCHEDULE_HOUR[hour / 2 % ODD_SCHEDULE_HOUR.Length];
  196. }
  197. else
  198. {
  199. selectedScheduleHour = ODD_SCHEDULE_HOUR[(hour + 1) / 2 % ODD_SCHEDULE_HOUR.Length];
  200. }
  201. DateTime scheduledDateTime = new DateTime(
  202. fmScheduleNow.Year,
  203. fmScheduleNow.Month,
  204. fmScheduleNow.Day,
  205. selectedScheduleHour,
  206. pushMin,
  207. pushSec
  208. );
  209. // 如果生成的时间在当前时间之前
  210. // 或者 fmScheduleNow 在 23 点之后并且 selectedScheduleHour 在 1 点(即次日)
  211. if (scheduledDateTime < fmScheduleNow || (fmScheduleNow.Hour >= 23 && selectedScheduleHour <= 1))
  212. {
  213. scheduledDateTime = scheduledDateTime.AddDays(1);
  214. }
  215. TimeSpan timeUntilNextRun = scheduledDateTime - fmScheduleNow;
  216. var ttl = (long)timeUntilNextRun.TotalSeconds;
  217. await SetIntervalTriggerAsync(fetalMovementKey, heartRate.Serialno, ttl, heartRate);
  218. _logger.LogInformation($"{heartRate.Serialno}-{heartRate.MessageId} 创建计划统计胎动时间{scheduledDateTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  219. #endregion
  220. #region 计算胎心数据(按心率时间LastUpdate)
  221. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(heartRate.Serialno);
  222. if (commonPHR == null)
  223. {
  224. // 处理孕妇业务,计算一般心率并下发
  225. commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(heartRate.Serialno, highFreqSampleInterval: highFreqSampleInterval);
  226. // 建模完成
  227. var flag = await _serviceIotApi.SetFetalConfig(heartRate.Serialno, 1, commonPHR!.MaxValue, commonPHR!.MinValue);
  228. _logger.LogInformation($"{heartRate.Serialno} 记录数量足够,建模完成");
  229. // 保存到TDengine数据库
  230. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR!);
  231. _logger.LogInformation($"保存TDengine完成");
  232. }
  233. // 获取最近的两个记录,并计算它们的 LastUpdate 时间差
  234. var firstTwoPhr = phr.OrderByDescending(i => i.LastUpdate).Take(2).Select(i => i.LastUpdate).ToList();
  235. var timeDiff = firstTwoPhr[0] - firstTwoPhr[1];
  236. // 如果需要,将时间差转换为秒
  237. var timeDiffInSeconds = timeDiff.TotalSeconds;
  238. // 高频统计结束时间
  239. var FreqStatsEnd = DateTime.Now;
  240. // 高频心率启动(在高频第二条才能判断)
  241. if (timeDiffInSeconds <= highFreqSampleInterval)
  242. {
  243. // 设置延时计算高频心率的胎心
  244. var freqHearRateHey = $"health_monitor/schedule_push/cal_freqhr_fetal_heart_rate/imei/{heartRate.Serialno}";
  245. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  246. if (phrFreqstatus == null)
  247. {
  248. /// 设置高频状态
  249. _logger.LogInformation($"{heartRate.Serialno} 进入高频心率启动状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval}");
  250. // 设置高频状态
  251. _logger.LogInformation($"{heartRate.Serialno} phr.Count {phr.Count}");
  252. var freqFirstPhr = phr.OrderByDescending(i => i.LastUpdate)
  253. .Skip(1) //在高频第二条才能判断,所以要去除本条记录
  254. .First();
  255. await _deviceCacheMgr.SetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno, freqFirstPhr);
  256. _logger.LogInformation($"{heartRate.Serialno} 设置高频状态");
  257. phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  258. HisGpsHeartRate freqFirstHR = new()
  259. {
  260. CreateTime = freqFirstPhr.CreateTime,
  261. DeviceKey = freqFirstPhr.DeviceKey,
  262. HeartRate = freqFirstPhr.PregnancyHeartRate,
  263. HeartRateId = freqFirstPhr.PregnancyHeartRateId,
  264. IsDisplay = freqFirstPhr.IsDisplay ? 1 : 0,
  265. LastUpdate = freqFirstPhr.LastUpdate,
  266. MessageId = freqFirstPhr.MessageId,
  267. Method = freqFirstPhr.Method,
  268. PersonId = freqFirstPhr.PersonId,
  269. Serialno = freqFirstPhr.SerialNumber,
  270. };
  271. await SetFreqHeartRateTriggerAsync(freqHearRateHey, heartRate.Serialno, highFreqSampleInterval, freqFirstHR);
  272. }
  273. // 续租延时计算高频心率的胎心
  274. await SetFreqHeartRateTriggerAsync(freqHearRateHey, heartRate.Serialno, highFreqSampleInterval);
  275. /// phr PregnancyHeartRate 连续连续正常次数个值都是正常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  276. /// 取连续正常次数正常值的平均值,推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  277. #region 检查高频状态是否连续12个心率值都是正常的
  278. // 获取最近连续正常次数个心率记录
  279. //_logger.LogInformation($"{heartRate.Serialno} 设置 stopHighFreqSampleCount {stopHighFreqSampleCount}");
  280. //var lastPhr = phr.OrderByDescending(i => i.LastUpdate).Take(stopHighFreqSampleCount).ToList();
  281. var lastPhr = phr.Where(i => i.LastUpdate >= phrFreqstatus!.LastUpdate)
  282. .OrderByDescending(i => i.LastUpdate).Take(stopHighFreqSampleCount).ToList();
  283. _logger.LogInformation($"{heartRate.Serialno} lastPhr.Count {lastPhr.Count},stopHighFreqSampleCount {stopHighFreqSampleCount}");
  284. _logger.LogInformation($"{heartRate.Serialno} count :{lastPhr.Count >= stopHighFreqSampleCount}");
  285. _logger.LogInformation($"{heartRate.Serialno} All {lastPhr.All(i => i.PregnancyHeartRate >= triggerHighFreqLow && i.PregnancyHeartRate <= triggerHighFreqHigh)}");
  286. // 检查是否连续12个值都是正常的
  287. if ((lastPhr.Count >= stopHighFreqSampleCount) &&
  288. lastPhr.All(i => i.PregnancyHeartRate >= triggerHighFreqLow && i.PregnancyHeartRate <= triggerHighFreqHigh)
  289. )
  290. {
  291. var avgPhr = lastPhr.Select(i => i.PregnancyHeartRate).Average();
  292. // 计算一般心率得到胎心系数
  293. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(DateTime.Now).ToString());
  294. // 高频数据不建模
  295. FreqStatsEnd = (DateTime)heartRate.LastUpdate!;
  296. _logger.LogInformation($"{heartRate.Serialno} 高频状态已经持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,连续 {stopHighFreqSampleCount} 次采样心率正常,将下发指令");
  297. var freqSaveAndPushFetalHeartRate = await _deviceCacheMgr.GetBizIntervalAsync(heartRate.Serialno, "SaveAndPushFetalHeartRate");
  298. // 高频不停,15分钟内只下发一条
  299. if (string.IsNullOrEmpty(freqSaveAndPushFetalHeartRate))
  300. {
  301. await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  302. // 删除高频状态的首条记录
  303. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  304. // 设置15分的SaveAndPushFetalHeartRate业务间隔
  305. await _deviceCacheMgr.SetBizIntervalAsync(heartRate.Serialno, "SaveAndPushFetalHeartRate");
  306. _logger.LogInformation($"{heartRate.Serialno} 连续 {stopHighFreqSampleCount} 次采样心率正常,结束高频心率状态, timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval},高频状态持续{((DateTime)heartRate.LastUpdate - phrFreqstatus!.LastUpdate).TotalSeconds} 秒");
  307. }
  308. else
  309. {
  310. _logger.LogWarning($"{heartRate.Serialno} 连续 {stopHighFreqSampleCount} 次采样心率正常,设备端应该结束高频状态,但设备端没有结束高频,平台高频15分钟内已经下发过指令");
  311. }
  312. }
  313. else
  314. {
  315. _logger.LogInformation($"{heartRate.Serialno} 处于高频状态...");
  316. }
  317. #endregion
  318. }
  319. // 高频心率结束或常规心率
  320. else
  321. {
  322. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  323. // 高频心率结束
  324. if (phrFreqstatus != null)
  325. {
  326. /// 在highFreqSampleTimes=0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  327. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  328. if (highFreqSampleTimes == 0)
  329. {
  330. var avgPhr = phr.OrderByDescending(i => i.LastUpdate)
  331. .Where(i => i.LastUpdate >= phrFreqstatus?.LastUpdate)
  332. .Skip(1) // 去除首条
  333. .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh)
  334. .Select(i => i.PregnancyHeartRate).Average();
  335. // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  336. // 计算一般心率得到胎心系数
  337. // 高频数据不建模
  338. FreqStatsEnd = firstTwoPhr[1];
  339. _logger.LogInformation($"{heartRate.Serialno} 高频状态已经持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,highFreqSampleTimes={highFreqSampleTimes}秒,即将结束高频状态,将下发指令");
  340. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString());
  341. await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  342. }
  343. /// 在highFreqSampleTimes>0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  344. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  345. if (highFreqSampleTimes > 0 && heartRate.LastUpdate >= (phrFreqstatus?.LastUpdate.AddSeconds(highFreqSampleTimes)))
  346. {
  347. // 获取高频心率数据个数
  348. var filterPhr = phr
  349. .Where(i => i.LastUpdate >= phrFreqstatus?.LastUpdate)
  350. .Skip(1)
  351. .ToList();
  352. _logger.LogInformation($"{heartRate.Serialno} 高频周期 {phrFreqstatus?.LastUpdate.ToString("yyyy-MM-dd HH:mm:ss")}--{firstTwoPhr[1].ToString("yyyy-MM-dd HH:mm:ss")} 产生高频心率数量 {filterPhr.Count} 条");
  353. // 高频心率数据大于stopHighFreqSampleCount/12个才计算胎心数据
  354. //
  355. if (filterPhr.Count > stopHighFreqSampleCount)
  356. {
  357. FreqStatsEnd = firstTwoPhr[1];
  358. var avgPhr = filterPhr
  359. .OrderByDescending(i => i.LastUpdate)
  360. .Take(stopHighFreqSampleCount) // 计算最后12条
  361. .Select(i => i.PregnancyHeartRate).Average();
  362. _logger.LogInformation($"{heartRate.Serialno} 高频状态已经持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,超过约定的 {highFreqSampleTimes} 秒,即将结束高频状态,将下发指令");
  363. //计算高频
  364. await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  365. }
  366. else
  367. {
  368. _logger.LogWarning($"{heartRate.Serialno} 高频心率的数据不大于{stopHighFreqSampleCount}条,不进行高频数据的胎心计算");
  369. }
  370. // 删除高频状态的首条记录
  371. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  372. // (逐条计算)计算本次常规心率的胎心数据(高频结束后,实时处理)
  373. // await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  374. await CalculateNormalFetalHeartRateScheduleAsync(heartRate);
  375. }
  376. ///不满足持续10分钟highFreqSampleTimes或出现时间倒叙
  377. ///
  378. else
  379. {
  380. // 高频结束后与常规的心率时间倒叙
  381. if ((firstTwoPhr[1] - phrFreqstatus!.LastUpdate).TotalSeconds < 0)
  382. {
  383. _logger.LogInformation($"{heartRate.Serialno} 高频结束出现时间倒叙,计算当条心率创建之前的高频心率");
  384. #region 计算当条心率创建之前的高频心率
  385. // 取得高频之后的所有数据
  386. var phrFlashBack = daysPhr.Where(p => p.LastUpdate >= phrFreqstatus!.LastUpdate)
  387. .OrderByDescending(i => i.LastUpdate);
  388. // 取得高频数据
  389. var freqCollection = phrFlashBack.ToList();
  390. //var freqCollection = new List<PregnancyHeartRateModel>();
  391. //PregnancyHeartRateModel? previousItem = null;
  392. //foreach (var item in phrFlashBack)
  393. //{
  394. // if (previousItem != null)
  395. // {
  396. // var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  397. // if (timeNextDiff <= highFreqSampleInterval)
  398. // {
  399. // freqCollection.Add(item);
  400. // }
  401. // }
  402. // previousItem = item;
  403. //}
  404. _logger.LogInformation($"{heartRate.Serialno} 高频数据个数{freqCollection.Count},触发高频开始时间{phrFreqstatus!.LastUpdate}");
  405. if (freqCollection.Count > stopHighFreqSampleCount)
  406. {
  407. // 计算高频产生的胎心
  408. var avgPhr = freqCollection
  409. .OrderByDescending(i => i.LastUpdate)
  410. .Take(stopHighFreqSampleCount) // 计算最后12条
  411. .Select(i => i.PregnancyHeartRate).Average();
  412. await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), freqCollection.Last().LastUpdate, freqCollection.First().LastUpdate);
  413. }
  414. else
  415. {
  416. _logger.LogInformation($"{heartRate.Serialno} 时间倒叙触发计算高频心率的数据不足{stopHighFreqSampleCount}条,不进行胎心计算");
  417. }
  418. #endregion
  419. }
  420. else
  421. {
  422. _logger.LogInformation($"{heartRate.Serialno} 高频持续时间不足{highFreqSampleTimes},只持续{(firstTwoPhr[1] - phrFreqstatus!.LastUpdate).TotalSeconds} 秒");
  423. }
  424. // 删除高频状态的首条记录
  425. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  426. // (逐条计算)计算本次常规心率的胎心数据(高频结束后,实时处理)
  427. //await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  428. await CalculateNormalFetalHeartRateScheduleAsync(heartRate);
  429. }
  430. // 删除高频状态的首条记录
  431. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  432. _logger.LogInformation($"{heartRate.Serialno} 超时结束高频心率状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval},高频状态持续{(firstTwoPhr[1] - phrFreqstatus!.LastUpdate).TotalSeconds} 秒");
  433. //// 使用延后计算
  434. //var fhrScheduleKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  435. //var fhrScheduleTTL = 60;
  436. //await SetIntervalTriggerAsync(fhrScheduleKey, heartRate.Serialno, fhrScheduleTTL, heartRate);
  437. }
  438. // 常规心率(本次心率可能是高频心率的首条,所以要使用延后计算胎心率)
  439. else
  440. {
  441. // 本次心率可能是高频心率的首条,所以要使用本次常规心率延后计算胎心率
  442. //var fhrScheduleKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  443. //var fhrScheduleTTL = 30;
  444. //await SetIntervalTriggerAsync(fhrScheduleKey, heartRate.Serialno, fhrScheduleTTL, heartRate);
  445. //_logger.LogInformation($"{heartRate.Serialno} 延时50秒,判断当前数据是否为高频首条");
  446. // 本次心率可能是高频心率的首条,所以要使用本次常规心率延后计算胎心率 查询30秒后是否有高频缓存
  447. Thread thread = new(async () =>
  448. {
  449. try
  450. {
  451. #region 休眠highFreqSampleInterval2秒
  452. var startTime = DateTime.Now;
  453. //var highFreqSampleInterval2 = (int)watchConfig!["highFreqSampleInterval"]!+5;
  454. var highFreqSampleInterval2 = highFreqSampleInterval;
  455. var during = TimeSpan.FromSeconds(highFreqSampleInterval2);
  456. while (true)
  457. {
  458. if (DateTime.Now - startTime > during)
  459. {
  460. break;
  461. }
  462. await Task.Delay(TimeSpan.FromSeconds(1));
  463. }
  464. #endregion
  465. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  466. _logger.LogInformation($"phrFreqstatus==null:{phrFreqstatus == null}");
  467. _logger.LogInformation($"phrFreqstatus.LastUpdate < heartRate.LastUpdate:{phrFreqstatus?.LastUpdate < heartRate.LastUpdate}");
  468. if (phrFreqstatus == null || phrFreqstatus.LastUpdate < heartRate.LastUpdate)
  469. {
  470. // (逐条计算)常规心率
  471. //await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  472. //_logger.LogInformation($"{heartRate.Serialno} 计算常规心率");
  473. // 延时计算常规心率
  474. await CalculateNormalFetalHeartRateScheduleAsync(heartRate);
  475. }
  476. }
  477. catch (Exception ex)
  478. {
  479. _logger.LogError($"处理延时计算异常:{ex.Message}, {ex.StackTrace}");
  480. }
  481. });
  482. thread.Start();
  483. }
  484. }
  485. #endregion
  486. }
  487. else
  488. {
  489. _logger.LogInformation($"{heartRate.Serialno} 记录不足30条,建模中");
  490. }
  491. }
  492. }
  493. catch (Exception ex)
  494. {
  495. _logger.LogError($"{heartRate.Serialno} 处理孕妇心率数据异常 \n{ex.Message}\n{ex.StackTrace}");
  496. }
  497. }
  498. /// <summary>
  499. /// (逐条计算)常规心率计算胎心数据
  500. /// </summary>
  501. /// <param name="heartRate"></param>
  502. /// <param name="upperAlarmThreshold"></param>
  503. /// <param name="lowerAlarmThreshold"></param>
  504. /// <param name="intervalFHR"></param>
  505. /// <param name="commonPHR"></param>
  506. /// <returns></returns>
  507. private async Task CalculateNormalFetalHeartRateAsync(HisGpsHeartRate heartRate, int upperAlarmThreshold, int lowerAlarmThreshold, int intervalFHR, PregnancyCommonHeartRateModel? commonPHR)
  508. {
  509. // 上15分钟的数据
  510. // 获取当前时间
  511. DateTime nowInterval = (DateTime)heartRate.LastUpdate!;
  512. if (nowInterval.Second > 0)
  513. {
  514. nowInterval = nowInterval.AddMinutes(1);
  515. }
  516. // 计算last_update到上一间隔的分钟数
  517. int minutesToSubtract = nowInterval.Minute % intervalFHR;
  518. // 计算上一间隔的时间
  519. DateTime previousInterval = nowInterval.AddMinutes(-minutesToSubtract).AddSeconds(-nowInterval.Second).AddMilliseconds(-nowInterval.Millisecond);
  520. // 使用 last_update 上一刻
  521. var sampleTimeFHR = DateTimeUtil.ConvertToTimeStamp(previousInterval).ToString();
  522. // 计算last_update到下一间隔的分钟数
  523. int minutesToAdd = intervalFHR - (nowInterval.Minute % intervalFHR);
  524. if (minutesToAdd == intervalFHR)
  525. {
  526. minutesToAdd = 0; // 如果已经是间隔,则不需要增加分钟
  527. }
  528. // 计算下一间隔的时间
  529. DateTime nextInterval = nowInterval.AddMinutes(minutesToAdd)
  530. .AddSeconds(-nowInterval.Second)
  531. .AddMilliseconds(-nowInterval.Millisecond);
  532. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  533. var normalPhrStatStartTime = nextInterval.AddMinutes(-intervalFHR);
  534. var normalPhrStatEndTime = nextInterval;
  535. _logger.LogInformation($"{heartRate.Serialno} 计算胎心数据, 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} ");
  536. var filteredPhr = daysPhr
  537. // 使用 last_update 下一刻
  538. .Where(i => i.LastUpdate <= normalPhrStatEndTime && i.LastUpdate >= normalPhrStatStartTime)
  539. .ToList();
  540. if (filteredPhr.Count == 0)
  541. {
  542. _logger.LogWarning($"{heartRate.Serialno} 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} 孕妇心率数据不足,{filteredPhr.Count}条记录");
  543. return;
  544. }
  545. var phrValue = filteredPhr.Count == 1
  546. ? filteredPhr.First().PregnancyHeartRate
  547. : filteredPhr.Average(i => i.PregnancyHeartRate);
  548. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, phrValue, sampleTimeFHR);
  549. await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, phrValue, sampleTimeFHR, normalPhrStatStartTime, normalPhrStatEndTime);
  550. }
  551. /// <summary>
  552. /// 延时计算
  553. /// </summary>
  554. /// <param name="heartRate"></param>
  555. /// <returns></returns>
  556. public async Task CalculateNormalFetalHeartRateScheduleAsync(HisGpsHeartRate heartRate)
  557. {
  558. var fhrScheduleKey = $"health_monitor/schedule_push/cal_normalphr_fetal_heart_rate/imei/{heartRate.Serialno}";
  559. DateTime nowInterval = DateTime.Now;
  560. if (nowInterval.Second > 0)
  561. {
  562. nowInterval = nowInterval.AddMinutes(1);
  563. }
  564. // 需要减去的分钟
  565. int minutesToSubtract = nowInterval.Minute % INTERVAL_FHR;
  566. var nextRunTime=nowInterval
  567. .AddMinutes(-minutesToSubtract)
  568. .AddMinutes(INTERVAL_FHR);
  569. TimeSpan timeUntilNextRun = nextRunTime - nowInterval;
  570. var ttl = (long)timeUntilNextRun.TotalSeconds;
  571. await SetIntervalTriggerAsync(fhrScheduleKey, heartRate.Serialno, ttl, heartRate);
  572. }
  573. /// <summary>
  574. ///
  575. /// </summary>
  576. /// <param name="heartRate"></param>
  577. /// <param name="commonPHR"></param>
  578. /// <param name="upperAlarmThreshold"></param>
  579. /// <param name="lowerAlarmThreshold"></param>
  580. /// <param name="phrValue"></param>
  581. /// <param name="sampleTime"></param>
  582. /// <param name="statStartTime"></param>
  583. /// <param name="statEndTime"></param>
  584. /// <returns></returns>
  585. private async Task SaveAndPushFetalHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int upperAlarmThreshold, int lowerAlarmThreshold, double phrValue, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  586. {
  587. // 计算胎心=孕妇心率*系数
  588. /**
  589. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  590. fetalHeartRate = fetalHeartRate > 220 ? 220 : fetalHeartRate; // 胎心的最大值调整为220,超过都按该值220输出
  591. if (fetalHeartRate >= 220)
  592. {
  593. // 先使用最小系数计算
  594. var statMaxValueFprCoefficient = commonPHR?.StatMaxValueFprCoefficient!;
  595. var statMinValueFprCoefficient = commonPHR?.StatMinValueFprCoefficient!;
  596. var coefficient = statMaxValueFprCoefficient < statMinValueFprCoefficient ? statMaxValueFprCoefficient : statMinValueFprCoefficient;
  597. fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  598. if (fetalHeartRate < 220)
  599. {
  600. _logger.LogWarning($"{heartRate.Serialno} 使用极值系数 {coefficient} ,建模数据可能出现异常,请检查");
  601. }
  602. else
  603. {
  604. fetalHeartRate = 220;
  605. _logger.LogWarning($"{heartRate.Serialno} 使用所有系数都不能放映实际,建模数据可能出现异常,请检查");
  606. }
  607. }
  608. */
  609. #region 胎心系数使用基于心率与中位数对比
  610. var coefficient = 0f;
  611. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  612. if (heartRate.HeartRate < commonPHR!.Mode)
  613. {
  614. coefficient = commonPHR.StatMinValueFprCoefficient!;
  615. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  616. }
  617. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  618. else if (heartRate.HeartRate > commonPHR.Mode)
  619. {
  620. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  621. {
  622. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  623. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  624. }
  625. else
  626. {
  627. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  628. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  629. }
  630. }
  631. else
  632. {
  633. coefficient = commonPHR.StatModeAvgFprCoefficient;
  634. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  635. }
  636. #endregion
  637. var fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  638. // 胎心的最大值调整为220,超过都按该值220输出
  639. // fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  640. if (fetalHeartRate > 220)
  641. {
  642. fetalHeartRate = 220;
  643. _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")}");
  644. }
  645. // 胎心的最小值调整为90,超过都按该值90
  646. if (fetalHeartRate < 90)
  647. {
  648. fetalHeartRate = 90;
  649. _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")}");
  650. }
  651. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  652. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  653. if (phrFreqstatus == null) isAbnormal = 0;
  654. var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  655. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  656. //if (!isFreq)
  657. //{
  658. // statStartTime = heartRate.LastUpdate;
  659. //
  660. //}
  661. // 保存到 数据服务 MySQL 数据库
  662. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  663. {
  664. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  665. PersonId = commonPHR!.PersonId,
  666. Serialno = heartRate.Serialno,
  667. HeartRate = fetalHeartRate,
  668. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  669. IsAbnormal = isAbnormal,
  670. StatStartTime = statStartTime,
  671. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  672. CreateTime = DateTime.Now,
  673. Method = 1,
  674. IsDisplay = 1,
  675. DeviceKey = commonPHR!.DeviceKey
  676. };
  677. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  678. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  679. // 推送最后一条常规心率计算的胎心数据到iot设备
  680. #region 推送最后一条常规心率计算的胎心数据到iot设备
  681. // 高频(<=12)-常规
  682. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  683. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  684. {
  685. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  686. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  687. }
  688. // 高频(13)-常规-高频(13)
  689. if (phrFreqstatus != null)
  690. {
  691. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  692. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  693. // 获取高频数据
  694. var freqCollection = new List<PregnancyHeartRateModel>();
  695. PregnancyHeartRateModel? previousItem = null;
  696. foreach (var item in phr)
  697. {
  698. if (previousItem != null)
  699. {
  700. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  701. if (timeNextDiff <= 60)
  702. {
  703. freqCollection.Add(item);
  704. }
  705. }
  706. // 高频最后一条
  707. if (lastPhr.MessageId == item.MessageId)
  708. {
  709. freqCollection.Add(item);
  710. }
  711. previousItem = item;
  712. }
  713. //去除高频
  714. foreach (var item in freqCollection)
  715. {
  716. phr.Remove(item);
  717. }
  718. lastPhr = phr.FirstOrDefault();
  719. if (lastPhr?.MessageId == heartRate.MessageId)
  720. {
  721. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  722. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  723. }
  724. }
  725. #endregion
  726. #region 高频心率计算胎心数据到iot设备
  727. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  728. if (phrFreqstatus != null && isAbnormal!=0)
  729. {
  730. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  731. }
  732. #endregion
  733. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  734. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  735. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  736. // 胎心数据推送到第三方
  737. var topic = "topic.push.third";
  738. var fhrThridMsg = new
  739. {
  740. messageId = fhrMsgId,
  741. topic = topic,
  742. time = fhrMsgTime,
  743. data = new
  744. {
  745. imei = heartRate.Serialno,
  746. value = fetalHeartRate,
  747. isAbnormal,
  748. type = "fetalHeart"
  749. }
  750. };
  751. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  752. // 胎心数据推送到微信
  753. if (isAbnormal != 0)
  754. {
  755. topic = "topic.push.wx";
  756. var fhrMsg = new
  757. {
  758. messageId = fhrMsgId,
  759. topic = topic,
  760. time = fhrMsgTime,
  761. data = new
  762. {
  763. deviceId = device?.DeviceId,
  764. imei = heartRate.Serialno,
  765. alarmTypeId = 12,
  766. alarmDeviceName = heartRate.Serialno,
  767. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  768. address = string.Empty,
  769. deviceKey = device?.DeviceId
  770. }
  771. };
  772. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  773. }
  774. }
  775. private async Task SetIntervalTriggerAsync(string key, string imei, long interval, HisGpsHeartRate heartRate)
  776. {
  777. // var key = $"health_monitor/schedule_push/{type}/imei/{imei}";
  778. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  779. if (string.IsNullOrWhiteSpace(schedulePush))
  780. {
  781. var now = DateTime.Now;
  782. var timeNextRun = now.Add(TimeSpan.FromSeconds(interval));
  783. var data = new
  784. {
  785. imei,
  786. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  787. ttl = interval,
  788. next_run_time = timeNextRun.ToString("yyyy-MM-dd HH:mm:ss"),
  789. trigger = heartRate,
  790. };
  791. var result = JsonConvert.SerializeObject(data);
  792. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  793. }
  794. }
  795. /// <summary>
  796. /// 高频延时计算触发器
  797. /// </summary>
  798. /// <param name="key"></param>
  799. /// <param name="imei"></param>
  800. /// <param name="interval"></param>
  801. /// <param name="heartRate"></param>
  802. /// <returns></returns>
  803. private async Task SetFreqHeartRateTriggerAsync(string key, string imei, long interval, HisGpsHeartRate? heartRate=null)
  804. {
  805. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  806. if (string.IsNullOrWhiteSpace(schedulePush))
  807. {
  808. var now = DateTime.Now;
  809. var data = new
  810. {
  811. imei,
  812. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  813. lease = interval,
  814. trigger = heartRate,
  815. };
  816. var result = JsonConvert.SerializeObject(data);
  817. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  818. }
  819. else
  820. {
  821. await _serviceEtcd.PutValAsync(key, schedulePush, interval, false).ConfigureAwait(false);
  822. }
  823. }
  824. /// <summary>
  825. /// 去除高频数据
  826. /// </summary>
  827. /// <param name="phr"></param>
  828. /// <param name="highFreqSampleInterva"></param>
  829. /// <returns></returns>
  830. private static List<PregnancyHeartRateModel> GetNonFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr,int highFreqSampleInterval)
  831. {
  832. //phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  833. //var result = 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 > highFreqSampleInterval)
  841. // {
  842. // result.Add(previousItem);
  843. // }
  844. // }
  845. // previousItem = item;
  846. //}
  847. //// 添加上一个
  848. //if (previousItem != null)
  849. //{
  850. // result.Add(previousItem);
  851. //}
  852. //return result;
  853. #region 反向
  854. var phr1 = phr.OrderByDescending(i => i.LastUpdate).ToList();
  855. var result = new List<PregnancyHeartRateModel>();
  856. PregnancyHeartRateModel? previousItem1 = null;
  857. foreach (var item in phr1)
  858. {
  859. if (previousItem1 != null)
  860. {
  861. var timeNextDiff = (previousItem1!.LastUpdate - item.LastUpdate).TotalSeconds;
  862. if (timeNextDiff > highFreqSampleInterval)
  863. {
  864. result.Add(previousItem1);
  865. }
  866. }
  867. previousItem1 = item;
  868. }
  869. // 添加上一个
  870. if (previousItem1 != null)
  871. {
  872. result.Add(previousItem1);
  873. }
  874. #endregion
  875. #region 正向
  876. var phr2 = phr.OrderByDescending(i => i.LastUpdate).ToList(); ;
  877. var freqCollection = new List<PregnancyHeartRateModel>();
  878. PregnancyHeartRateModel? previousItem = null;
  879. foreach (var item in phr2)
  880. {
  881. if (previousItem != null)
  882. {
  883. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  884. if (timeNextDiff <= highFreqSampleInterval)
  885. {
  886. freqCollection.Add(item);
  887. }
  888. }
  889. previousItem = item;
  890. }
  891. //去除高频
  892. foreach (var item in freqCollection)
  893. {
  894. phr2.Remove(item);
  895. }
  896. #endregion
  897. // 交集
  898. var commonElements = phr2.Intersect(result).ToList();
  899. return commonElements;
  900. }
  901. /// <summary>
  902. /// 获取高频数据
  903. /// </summary>
  904. /// <param name="phr"></param>
  905. /// <param name="highFreqSampleInterval"></param>
  906. /// <returns></returns>
  907. private static List<PregnancyHeartRateModel> GetFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr, int highFreqSampleInterval)
  908. {
  909. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  910. var freqCollection = new List<PregnancyHeartRateModel>();
  911. PregnancyHeartRateModel? previousItem = null;
  912. foreach (var item in phr)
  913. {
  914. if (previousItem != null)
  915. {
  916. var timeNextDiff = (previousItem.LastUpdate - item.LastUpdate).TotalSeconds;
  917. if (timeNextDiff <= highFreqSampleInterval)
  918. {
  919. freqCollection.Add(previousItem);
  920. }
  921. }
  922. previousItem = item;
  923. }
  924. // 检查最后一条是否高频
  925. if (previousItem != null && (phr.Last().LastUpdate - previousItem.LastUpdate).TotalSeconds <= highFreqSampleInterval)
  926. {
  927. freqCollection.Add(previousItem);
  928. }
  929. return freqCollection;
  930. }
  931. }
  932. }