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.

1193 lines
71KB

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