Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

1676 lines
94KB

  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+30, freqFirstHR);
  340. }
  341. // 续租延时计算高频心率的胎心
  342. await SetFreqHeartRateTriggerAsync(freqHearRateHey, heartRate.Serialno, highFreqSampleInterval+30);
  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. //await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  370. heartRate.HeartRate = (int)avgPhr;
  371. //await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  372. // 最后一条高频心率
  373. var lastFreqHr = lastPhr.First();
  374. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)lastFreqHr.LastUpdate!, phrFreqstatus!.LastUpdate);
  375. // 判断是否够highFreqSampleTimes,540s
  376. if (ts < highFreqSampleTimes)
  377. {
  378. /// 不够10分钟最近12个数据的最小值生成胎心值
  379. _logger.LogInformation($"{heartRate.Serialno} 不够10分钟最近12个数据的最小值生成胎心值");
  380. heartRate.HeartRate = lastPhr.Select(i=>i.PregnancyHeartRate).Min();
  381. heartRate.LastUpdate = lastFreqHr.LastUpdate;
  382. }
  383. _logger.LogInformation($"{heartRate.Serialno} 高频数据触发连续12个值都是正常的的高频心率处理");
  384. await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR,highFreqSampleTimes ,upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  385. // 删除高频状态的首条记录
  386. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  387. // 设置15分的SaveAndPushFetalHeartRate业务间隔
  388. await _deviceCacheMgr.SetBizIntervalAsync(heartRate.Serialno, "SaveAndPushFetalHeartRate");
  389. _logger.LogInformation($"{heartRate.Serialno} 连续 {stopHighFreqSampleCount} 次采样心率正常,结束高频心率状态, timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval},高频状态持续{((DateTime)heartRate.LastUpdate - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,高频心率平均值:{(int)avgPhr}");
  390. }
  391. else
  392. {
  393. _logger.LogWarning($"{heartRate.Serialno} 连续 {stopHighFreqSampleCount} 次采样心率正常,设备端应该结束高频状态,但设备端没有结束高频,平台高频15分钟内已经下发过指令");
  394. }
  395. }
  396. else
  397. {
  398. _logger.LogInformation($"{heartRate.Serialno} 处于高频状态...");
  399. }
  400. #endregion
  401. }
  402. // 高频心率结束或常规心率
  403. else
  404. {
  405. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  406. // 高频心率结束
  407. if (phrFreqstatus != null)
  408. {
  409. /// 在highFreqSampleTimes=0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  410. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  411. if (highFreqSampleTimes == 0)
  412. {
  413. var lastPhr = phr.OrderByDescending(i => i.LastUpdate)
  414. .Where(i => i.LastUpdate >= phrFreqstatus?.LastUpdate)
  415. .Skip(1) // 去除首条
  416. .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh);
  417. //.Select(i => i.PregnancyHeartRate);
  418. //.Average();
  419. var avgPhr = lastPhr.Select(i => i.PregnancyHeartRate).Average();
  420. // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  421. // 计算一般心率得到胎心系数
  422. // 高频数据不建模
  423. FreqStatsEnd = firstTwoPhr[1];
  424. _logger.LogInformation($"{heartRate.Serialno} 高频状态已经持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,highFreqSampleTimes={highFreqSampleTimes}秒,即将结束高频状态,高频心率平均值:{(int)avgPhr},将下发指令");
  425. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString());
  426. //await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  427. heartRate.HeartRate = (int)avgPhr;
  428. //await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  429. // 最后一条高频心率
  430. var lastFreqHr = lastPhr.First();
  431. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)lastFreqHr.LastUpdate!, phrFreqstatus!.LastUpdate);
  432. // 判断是否够highFreqSampleTimes,540s
  433. if (ts < highFreqSampleTimes)
  434. {
  435. /// 不够10分钟最近12个数据的最小值生成胎心值
  436. _logger.LogInformation($"{heartRate.Serialno} 不够10分钟最近12个数据的最小值生成胎心值");
  437. heartRate.HeartRate = lastPhr.Select(i => i.PregnancyHeartRate).Min();
  438. heartRate.LastUpdate = lastFreqHr.LastUpdate;
  439. }
  440. _logger.LogInformation($"{heartRate.Serialno} 高频结束后的highFreqSampleTimes=0的高频心率处理");
  441. await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, highFreqSampleTimes, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  442. }
  443. /// 在highFreqSampleTimes>0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  444. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  445. if (highFreqSampleTimes > 0 && heartRate.LastUpdate >= (phrFreqstatus?.LastUpdate.AddSeconds(highFreqSampleTimes)))
  446. {
  447. // 获取高频心率数据个数
  448. var filterPhr = phr
  449. .Where(i => i.LastUpdate >= phrFreqstatus?.LastUpdate)
  450. .Skip(1)
  451. .ToList();
  452. _logger.LogInformation($"{heartRate.Serialno} 高频周期 {phrFreqstatus?.LastUpdate.ToString("yyyy-MM-dd HH:mm:ss")}--{firstTwoPhr[1].ToString("yyyy-MM-dd HH:mm:ss")} 产生高频心率数量 {filterPhr.Count} 条");
  453. // 高频心率数据大于stopHighFreqSampleCount/12个才计算胎心数据
  454. //
  455. if (filterPhr.Count > stopHighFreqSampleCount)
  456. {
  457. FreqStatsEnd = firstTwoPhr[1];
  458. var avgPhr = filterPhr
  459. .OrderByDescending(i => i.LastUpdate)
  460. .Take(stopHighFreqSampleCount) // 计算最后12条
  461. .Select(i => i.PregnancyHeartRate).Average();
  462. //_logger.LogInformation($"{heartRate.Serialno} 高频状态已经持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,约定的 {highFreqSampleTimes} 秒,即将结束高频状态,高频心率平均值:{(int)avgPhr},将下发指令");
  463. //计算高频
  464. //await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  465. heartRate.HeartRate = (int)avgPhr;
  466. //await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  467. // 判断是否够highFreqSampleTimes,540s
  468. var lastPhr = filterPhr
  469. .OrderByDescending(i => i.LastUpdate)
  470. .Take(stopHighFreqSampleCount);
  471. // 最后一条高频心率
  472. var lastFreqHr = lastPhr.First();
  473. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)lastFreqHr.LastUpdate!, phrFreqstatus!.LastUpdate);
  474. if (ts < highFreqSampleTimes)
  475. {
  476. /// 不够10分钟最近12个数据的最小值生成胎心值
  477. _logger.LogInformation($"{heartRate.Serialno} 不够10分钟最近12个数据的最小值生成胎心值");
  478. heartRate.HeartRate = lastPhr.Select(i => i.PregnancyHeartRate).Min();
  479. heartRate.LastUpdate = lastFreqHr.LastUpdate;
  480. }
  481. _logger.LogInformation($"{heartRate.Serialno} 高频结束后的在highFreqSampleTimes>0 正常心率(通常情况)触发的高频心率处理");
  482. await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, highFreqSampleTimes, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  483. }
  484. else
  485. {
  486. _logger.LogWarning($"{heartRate.Serialno} 高频心率的数据不大于{stopHighFreqSampleCount}条,不进行高频数据的胎心计算");
  487. }
  488. // 删除高频状态的首条记录
  489. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  490. // (逐条计算)计算本次常规心率的胎心数据(高频结束后,实时处理)
  491. // await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  492. await CalculateNormalFetalHeartRateScheduleAsync(heartRate);
  493. }
  494. ///不满足持续10分钟highFreqSampleTimes或出现时间倒叙
  495. ///
  496. else
  497. {
  498. // 高频结束后与常规的心率时间倒叙
  499. if ((firstTwoPhr[1] - phrFreqstatus!.LastUpdate).TotalSeconds < 0)
  500. {
  501. _logger.LogInformation($"{heartRate.Serialno} 高频结束出现时间倒叙,计算当条心率创建之前的高频心率");
  502. #region 计算当条心率创建之前的高频心率
  503. // 取得高频之后的所有数据
  504. var phrFlashBack = daysPhr.Where(p => p.LastUpdate >= phrFreqstatus!.LastUpdate)
  505. .OrderByDescending(i => i.LastUpdate);
  506. // 取得高频数据
  507. var freqCollection = phrFlashBack.ToList();
  508. //var freqCollection = new List<PregnancyHeartRateModel>();
  509. //PregnancyHeartRateModel? previousItem = null;
  510. //foreach (var item in phrFlashBack)
  511. //{
  512. // if (previousItem != null)
  513. // {
  514. // var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  515. // if (timeNextDiff <= highFreqSampleInterval)
  516. // {
  517. // freqCollection.Add(item);
  518. // }
  519. // }
  520. // previousItem = item;
  521. //}
  522. _logger.LogInformation($"{heartRate.Serialno} 高频数据个数{freqCollection.Count},触发高频开始时间{phrFreqstatus!.LastUpdate}");
  523. if (freqCollection.Count > stopHighFreqSampleCount)
  524. {
  525. // 计算高频产生的胎心
  526. var avgPhr = freqCollection
  527. .OrderByDescending(i => i.LastUpdate)
  528. .Take(stopHighFreqSampleCount) // 计算最后12条
  529. .Select(i => i.PregnancyHeartRate).Average();
  530. heartRate.HeartRate = (int)avgPhr;
  531. // await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  532. //_logger.LogInformation($"{heartRate.Serialno} 高频数据个数{freqCollection.Count},触发高频开始时间{phrFreqstatus!.LastUpdate},高频心率平均值:{(int)avgPhr}");
  533. // 判断是否够highFreqSampleTimes,540s
  534. var lastPhr = freqCollection
  535. .OrderByDescending(i => i.LastUpdate)
  536. .Take(stopHighFreqSampleCount);
  537. // 最后一条高频心率
  538. var lastFreqHr = lastPhr.First();
  539. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)lastFreqHr.LastUpdate!, phrFreqstatus!.LastUpdate);
  540. if (ts < highFreqSampleTimes)
  541. {
  542. /// 不够10分钟最近12个数据的最小值生成胎心值
  543. _logger.LogInformation($"{heartRate.Serialno} 不够10分钟最近12个数据的最小值生成胎心值");
  544. heartRate.HeartRate = lastPhr.Select(i => i.PregnancyHeartRate).Min();
  545. heartRate.LastUpdate = lastFreqHr.LastUpdate;
  546. }
  547. _logger.LogInformation($"{heartRate.Serialno} 高频结束后的时间倒序的正常心率触发的高频心率处理");
  548. await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, highFreqSampleTimes, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  549. _logger.LogInformation($"{heartRate.Serialno} 高频数据个数{freqCollection.Count},触发高频开始时间{phrFreqstatus!.LastUpdate},时间倒叙");
  550. }
  551. else
  552. {
  553. _logger.LogInformation($"{heartRate.Serialno} 时间倒叙触发计算高频心率的数据不足{stopHighFreqSampleCount}条,不进行胎心计算");
  554. }
  555. #endregion
  556. }
  557. else
  558. {
  559. _logger.LogInformation($"{heartRate.Serialno} 高频持续时间不足{highFreqSampleTimes},只持续{(firstTwoPhr[1] - phrFreqstatus!.LastUpdate).TotalSeconds} 秒");
  560. }
  561. // 删除高频状态的首条记录
  562. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  563. // (逐条计算)计算本次常规心率的胎心数据(高频结束后,实时处理)
  564. //await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  565. await CalculateNormalFetalHeartRateScheduleAsync(heartRate);
  566. }
  567. // 删除高频状态的首条记录
  568. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  569. _logger.LogInformation($"{heartRate.Serialno} 超时结束高频心率状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval},高频状态持续{(firstTwoPhr[1] - phrFreqstatus!.LastUpdate).TotalSeconds} 秒");
  570. //// 使用延后计算
  571. //var fhrScheduleKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  572. //var fhrScheduleTTL = 60;
  573. //await SetIntervalTriggerAsync(fhrScheduleKey, heartRate.Serialno, fhrScheduleTTL, heartRate);
  574. }
  575. // 常规心率(本次心率可能是高频心率的首条,所以要使用延后计算胎心率)
  576. else
  577. {
  578. // 本次心率可能是高频心率的首条,所以要使用本次常规心率延后计算胎心率
  579. //var fhrScheduleKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  580. //var fhrScheduleTTL = 30;
  581. //await SetIntervalTriggerAsync(fhrScheduleKey, heartRate.Serialno, fhrScheduleTTL, heartRate);
  582. //_logger.LogInformation($"{heartRate.Serialno} 延时50秒,判断当前数据是否为高频首条");
  583. // 本次心率可能是高频心率的首条,所以要使用本次常规心率延后计算胎心率 查询30秒后是否有高频缓存
  584. Thread thread = new(async () =>
  585. {
  586. try
  587. {
  588. #region 休眠highFreqSampleInterval2秒
  589. var startTime = DateTime.Now;
  590. //var highFreqSampleInterval2 = (int)watchConfig!["highFreqSampleInterval"]!+5;
  591. var highFreqSampleInterval2 = highFreqSampleInterval;
  592. var during = TimeSpan.FromSeconds(highFreqSampleInterval2);
  593. while (true)
  594. {
  595. if (DateTime.Now - startTime > during)
  596. {
  597. break;
  598. }
  599. await Task.Delay(TimeSpan.FromSeconds(1));
  600. }
  601. #endregion
  602. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  603. _logger.LogInformation($"phrFreqstatus==null:{phrFreqstatus == null}");
  604. _logger.LogInformation($"phrFreqstatus.LastUpdate < heartRate.LastUpdate:{phrFreqstatus?.LastUpdate < heartRate.LastUpdate}");
  605. if (phrFreqstatus == null || phrFreqstatus.LastUpdate < heartRate.LastUpdate)
  606. {
  607. // (逐条计算)常规心率
  608. //await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  609. //_logger.LogInformation($"{heartRate.Serialno} 计算常规心率");
  610. // 延时计算常规心率
  611. await CalculateNormalFetalHeartRateScheduleAsync(heartRate);
  612. }
  613. }
  614. catch (Exception ex)
  615. {
  616. _logger.LogError($"处理延时计算异常:{ex.Message}, {ex.StackTrace}");
  617. }
  618. });
  619. thread.Start();
  620. }
  621. }
  622. #endregion
  623. }
  624. else
  625. {
  626. _logger.LogInformation($"{heartRate.Serialno} 记录不足30条,建模中");
  627. }
  628. }
  629. }
  630. catch (Exception ex)
  631. {
  632. _logger.LogError($"{heartRate.Serialno} 处理孕妇心率数据异常 \n{ex.Message}\n{ex.StackTrace}");
  633. }
  634. }
  635. /// <summary>
  636. /// (逐条计算)常规心率计算胎心数据
  637. /// </summary>
  638. /// <param name="heartRate"></param>
  639. /// <param name="upperAlarmThreshold"></param>
  640. /// <param name="lowerAlarmThreshold"></param>
  641. /// <param name="intervalFHR"></param>
  642. /// <param name="commonPHR"></param>
  643. /// <returns></returns>
  644. /**
  645. private async Task CalculateNormalFetalHeartRateAsync(HisGpsHeartRate heartRate, int upperAlarmThreshold, int lowerAlarmThreshold, int intervalFHR, PregnancyCommonHeartRateModel? commonPHR)
  646. {
  647. // 上15分钟的数据
  648. // 获取当前时间
  649. DateTime nowInterval = (DateTime)heartRate.LastUpdate!;
  650. if (nowInterval.Second > 0)
  651. {
  652. nowInterval = nowInterval.AddMinutes(1);
  653. }
  654. // 计算last_update到上一间隔的分钟数
  655. int minutesToSubtract = nowInterval.Minute % intervalFHR;
  656. // 计算上一间隔的时间
  657. DateTime previousInterval = nowInterval.AddMinutes(-minutesToSubtract).AddSeconds(-nowInterval.Second).AddMilliseconds(-nowInterval.Millisecond);
  658. // 使用 last_update 上一刻
  659. var sampleTimeFHR = DateTimeUtil.ConvertToTimeStamp(previousInterval).ToString();
  660. // 计算last_update到下一间隔的分钟数
  661. int minutesToAdd = intervalFHR - (nowInterval.Minute % intervalFHR);
  662. if (minutesToAdd == intervalFHR)
  663. {
  664. minutesToAdd = 0; // 如果已经是间隔,则不需要增加分钟
  665. }
  666. // 计算下一间隔的时间
  667. DateTime nextInterval = nowInterval.AddMinutes(minutesToAdd)
  668. .AddSeconds(-nowInterval.Second)
  669. .AddMilliseconds(-nowInterval.Millisecond);
  670. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  671. var normalPhrStatStartTime = nextInterval.AddMinutes(-intervalFHR);
  672. var normalPhrStatEndTime = nextInterval;
  673. _logger.LogInformation($"{heartRate.Serialno} 计算胎心数据, 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} ");
  674. var filteredPhr = daysPhr
  675. // 使用 last_update 下一刻
  676. .Where(i => i.LastUpdate <= normalPhrStatEndTime && i.LastUpdate >= normalPhrStatStartTime)
  677. .ToList();
  678. if (filteredPhr.Count == 0)
  679. {
  680. _logger.LogWarning($"{heartRate.Serialno} 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} 孕妇心率数据不足,{filteredPhr.Count}条记录");
  681. return;
  682. }
  683. var phrValue = filteredPhr.Count == 1
  684. ? filteredPhr.First().PregnancyHeartRate
  685. : filteredPhr.Average(i => i.PregnancyHeartRate);
  686. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, phrValue, sampleTimeFHR);
  687. //await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, phrValue, sampleTimeFHR, normalPhrStatStartTime, normalPhrStatEndTime);
  688. heartRate.HeartRate = (int)phrValue;
  689. //await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, sampleTimeFHR, normalPhrStatStartTime, normalPhrStatEndTime);
  690. }
  691. */
  692. /// <summary>
  693. /// 延时计算
  694. /// </summary>
  695. /// <param name="heartRate"></param>
  696. /// <returns></returns>
  697. public async Task CalculateNormalFetalHeartRateScheduleAsync(HisGpsHeartRate heartRate)
  698. {
  699. var fhrScheduleKey = $"health_monitor/schedule_push/cal_normalphr_fetal_heart_rate/imei/{heartRate.Serialno}";
  700. DateTime nowInterval = DateTime.Now;
  701. if (nowInterval.Second > 0)
  702. {
  703. nowInterval = nowInterval.AddMinutes(1);
  704. }
  705. // 需要减去的分钟
  706. int minutesToSubtract = nowInterval.Minute % INTERVAL_FHR;
  707. var nextRunTime=nowInterval
  708. .AddMinutes(-minutesToSubtract)
  709. .AddMinutes(INTERVAL_FHR);
  710. TimeSpan timeUntilNextRun = nextRunTime - nowInterval;
  711. var ttl = (long)timeUntilNextRun.TotalSeconds;
  712. await SetIntervalTriggerAsync(fhrScheduleKey, heartRate.Serialno, ttl, heartRate);
  713. _logger.LogInformation($"{heartRate.Serialno}--{heartRate.MessageId} 触发延时计算常规胎心");
  714. }
  715. /// <summary>
  716. ///
  717. /// </summary>
  718. /// <param name="heartRate"></param>
  719. /// <param name="commonPHR"></param>
  720. /// <param name="upperAlarmThreshold"></param>
  721. /// <param name="lowerAlarmThreshold"></param>
  722. /// <param name="phrValue"></param>
  723. /// <param name="sampleTime"></param>
  724. /// <param name="statStartTime"></param>
  725. /// <param name="statEndTime"></param>
  726. /// <returns></returns>
  727. private async Task SaveAndPushFetalHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int upperAlarmThreshold, int lowerAlarmThreshold, double phrValue, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  728. {
  729. // 计算胎心=孕妇心率*系数
  730. /**
  731. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  732. fetalHeartRate = fetalHeartRate > 220 ? 220 : fetalHeartRate; // 胎心的最大值调整为220,超过都按该值220输出
  733. if (fetalHeartRate >= 220)
  734. {
  735. // 先使用最小系数计算
  736. var statMaxValueFprCoefficient = commonPHR?.StatMaxValueFprCoefficient!;
  737. var statMinValueFprCoefficient = commonPHR?.StatMinValueFprCoefficient!;
  738. var coefficient = statMaxValueFprCoefficient < statMinValueFprCoefficient ? statMaxValueFprCoefficient : statMinValueFprCoefficient;
  739. fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  740. if (fetalHeartRate < 220)
  741. {
  742. _logger.LogWarning($"{heartRate.Serialno} 使用极值系数 {coefficient} ,建模数据可能出现异常,请检查");
  743. }
  744. else
  745. {
  746. fetalHeartRate = 220;
  747. _logger.LogWarning($"{heartRate.Serialno} 使用所有系数都不能放映实际,建模数据可能出现异常,请检查");
  748. }
  749. }
  750. */
  751. #region 胎心系数使用基于心率与中位数对比
  752. var coefficient = 0f;
  753. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  754. if (heartRate.HeartRate < commonPHR!.Mode)
  755. {
  756. coefficient = commonPHR.StatMinValueFprCoefficient!;
  757. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  758. }
  759. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  760. else if (heartRate.HeartRate > commonPHR.Mode)
  761. {
  762. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  763. {
  764. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  765. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  766. }
  767. else
  768. {
  769. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  770. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  771. }
  772. }
  773. else
  774. {
  775. coefficient = commonPHR.StatModeAvgFprCoefficient;
  776. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  777. }
  778. #endregion
  779. var fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  780. // 胎心的最大值调整为220,超过都按该值220输出
  781. // fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  782. if (fetalHeartRate > 220)
  783. {
  784. fetalHeartRate = 220;
  785. _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")}");
  786. }
  787. // 胎心的最小值调整为90,超过都按该值90
  788. if (fetalHeartRate < 90)
  789. {
  790. fetalHeartRate = 90;
  791. _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")}");
  792. }
  793. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  794. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  795. if (phrFreqstatus == null) isAbnormal = 0;
  796. var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  797. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  798. //if (!isFreq)
  799. //{
  800. // statStartTime = heartRate.LastUpdate;
  801. //
  802. //}
  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. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  821. // 推送最后一条常规心率计算的胎心数据到iot设备
  822. #region 推送最后一条常规心率计算的胎心数据到iot设备
  823. // 高频(<=12)-常规
  824. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  825. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  826. {
  827. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  828. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  829. }
  830. // 高频(13)-常规-高频(13)
  831. if (phrFreqstatus != null)
  832. {
  833. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  834. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  835. // 获取高频数据
  836. var freqCollection = new List<PregnancyHeartRateModel>();
  837. PregnancyHeartRateModel? previousItem = null;
  838. foreach (var item in phr)
  839. {
  840. if (previousItem != null)
  841. {
  842. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  843. if (timeNextDiff <= 60)
  844. {
  845. freqCollection.Add(item);
  846. }
  847. }
  848. // 高频最后一条
  849. if (lastPhr.MessageId == item.MessageId)
  850. {
  851. freqCollection.Add(item);
  852. }
  853. previousItem = item;
  854. }
  855. //去除高频
  856. foreach (var item in freqCollection)
  857. {
  858. phr.Remove(item);
  859. }
  860. lastPhr = phr.FirstOrDefault();
  861. if (lastPhr?.MessageId == heartRate.MessageId)
  862. {
  863. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  864. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  865. }
  866. }
  867. #endregion
  868. #region 高频心率计算胎心数据到iot设备
  869. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  870. if (phrFreqstatus != null && isAbnormal!=0)
  871. {
  872. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  873. }
  874. #endregion
  875. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  876. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  877. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  878. // 胎心数据推送到第三方
  879. var topic = "topic.push.third";
  880. var fhrThridMsg = new
  881. {
  882. messageId = fhrMsgId,
  883. topic = topic,
  884. time = fhrMsgTime,
  885. data = new
  886. {
  887. imei = heartRate.Serialno,
  888. value = fetalHeartRate,
  889. isAbnormal,
  890. type = "fetalHeart"
  891. }
  892. };
  893. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  894. // 胎心数据推送到微信
  895. if (isAbnormal != 0)
  896. {
  897. topic = "topic.push.wx";
  898. var fhrMsg = new
  899. {
  900. messageId = fhrMsgId,
  901. topic = topic,
  902. time = fhrMsgTime,
  903. data = new
  904. {
  905. deviceId = device?.DeviceId,
  906. imei = heartRate.Serialno,
  907. alarmTypeId = 12,
  908. alarmDeviceName = heartRate.Serialno,
  909. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  910. address = string.Empty,
  911. deviceKey = device?.DeviceId
  912. }
  913. };
  914. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  915. }
  916. }
  917. private async Task SaveAndPushFetalHeartRateEndFreqHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int upperAlarmThreshold, int lowerAlarmThreshold, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  918. {
  919. // 计算胎心=孕妇心率*系数
  920. /**
  921. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  922. fetalHeartRate = fetalHeartRate > 220 ? 220 : fetalHeartRate; // 胎心的最大值调整为220,超过都按该值220输出
  923. if (fetalHeartRate >= 220)
  924. {
  925. // 先使用最小系数计算
  926. var statMaxValueFprCoefficient = commonPHR?.StatMaxValueFprCoefficient!;
  927. var statMinValueFprCoefficient = commonPHR?.StatMinValueFprCoefficient!;
  928. var coefficient = statMaxValueFprCoefficient < statMinValueFprCoefficient ? statMaxValueFprCoefficient : statMinValueFprCoefficient;
  929. fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  930. if (fetalHeartRate < 220)
  931. {
  932. _logger.LogWarning($"{heartRate.Serialno} 使用极值系数 {coefficient} ,建模数据可能出现异常,请检查");
  933. }
  934. else
  935. {
  936. fetalHeartRate = 220;
  937. _logger.LogWarning($"{heartRate.Serialno} 使用所有系数都不能放映实际,建模数据可能出现异常,请检查");
  938. }
  939. }
  940. */
  941. #region 胎心系数使用基于心率与中位数对比
  942. var coefficient = 0f;
  943. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  944. if (heartRate.HeartRate < commonPHR!.Mode)
  945. {
  946. coefficient = commonPHR.StatMinValueFprCoefficient!;
  947. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  948. }
  949. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  950. else if (heartRate.HeartRate > commonPHR.Mode)
  951. {
  952. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  953. {
  954. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  955. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  956. }
  957. else
  958. {
  959. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  960. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  961. }
  962. }
  963. else
  964. {
  965. coefficient = commonPHR.StatModeAvgFprCoefficient;
  966. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  967. }
  968. #endregion
  969. var fetalHeartRate = SafeType.SafeInt(heartRate.HeartRate! * coefficient);
  970. // 胎心的最大值调整为220,超过都按该值220输出
  971. // fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  972. if (fetalHeartRate > 220)
  973. {
  974. fetalHeartRate = 220;
  975. _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")}");
  976. }
  977. // 胎心的最小值调整为90,超过都按该值90
  978. if (fetalHeartRate < 90)
  979. {
  980. fetalHeartRate = 90;
  981. _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")}");
  982. }
  983. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  984. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  985. if (phrFreqstatus == null) isAbnormal = 0;
  986. var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  987. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  988. //if (!isFreq)
  989. //{
  990. // statStartTime = heartRate.LastUpdate;
  991. //
  992. //}
  993. // 保存到 数据服务 MySQL 数据库
  994. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  995. {
  996. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  997. PersonId = commonPHR!.PersonId,
  998. Serialno = heartRate.Serialno,
  999. HeartRate = fetalHeartRate,
  1000. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  1001. IsAbnormal = isAbnormal,
  1002. StatStartTime = statStartTime,
  1003. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  1004. CreateTime = DateTime.Now,
  1005. Method = 1,
  1006. IsDisplay = 1,
  1007. DeviceKey = commonPHR!.DeviceKey
  1008. };
  1009. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  1010. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  1011. // 推送最后一条常规心率计算的胎心数据到iot设备
  1012. #region 推送最后一条常规心率计算的胎心数据到iot设备
  1013. // 高频(<=12)-常规
  1014. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  1015. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  1016. {
  1017. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1018. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  1019. }
  1020. // 高频(13)-常规-高频(13)
  1021. if (phrFreqstatus != null)
  1022. {
  1023. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  1024. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1025. // 获取高频数据
  1026. var freqCollection = new List<PregnancyHeartRateModel>();
  1027. PregnancyHeartRateModel? previousItem = null;
  1028. foreach (var item in phr)
  1029. {
  1030. if (previousItem != null)
  1031. {
  1032. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1033. if (timeNextDiff <= 60)
  1034. {
  1035. freqCollection.Add(item);
  1036. }
  1037. }
  1038. // 高频最后一条
  1039. if (lastPhr.MessageId == item.MessageId)
  1040. {
  1041. freqCollection.Add(item);
  1042. }
  1043. previousItem = item;
  1044. }
  1045. //去除高频
  1046. foreach (var item in freqCollection)
  1047. {
  1048. phr.Remove(item);
  1049. }
  1050. lastPhr = phr.FirstOrDefault();
  1051. if (lastPhr?.MessageId == heartRate.MessageId)
  1052. {
  1053. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1054. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  1055. }
  1056. }
  1057. #endregion
  1058. #region 高频心率计算胎心数据到iot设备
  1059. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  1060. if (phrFreqstatus != null && isAbnormal != 0)
  1061. {
  1062. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1063. }
  1064. #endregion
  1065. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  1066. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  1067. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  1068. // 胎心数据推送到第三方
  1069. var topic = "topic.push.third";
  1070. var fhrThridMsg = new
  1071. {
  1072. messageId = fhrMsgId,
  1073. topic = topic,
  1074. time = fhrMsgTime,
  1075. data = new
  1076. {
  1077. imei = heartRate.Serialno,
  1078. value = fetalHeartRate,
  1079. isAbnormal,
  1080. type = "fetalHeart"
  1081. }
  1082. };
  1083. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  1084. // 胎心数据推送到微信
  1085. if (isAbnormal != 0)
  1086. {
  1087. topic = "topic.push.wx";
  1088. var fhrMsg = new
  1089. {
  1090. messageId = fhrMsgId,
  1091. topic = topic,
  1092. time = fhrMsgTime,
  1093. data = new
  1094. {
  1095. deviceId = device?.DeviceId,
  1096. imei = heartRate.Serialno,
  1097. alarmTypeId = 12,
  1098. alarmDeviceName = heartRate.Serialno,
  1099. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  1100. address = string.Empty,
  1101. deviceKey = device?.DeviceId
  1102. }
  1103. };
  1104. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  1105. }
  1106. }
  1107. /// <summary>
  1108. /// 高频胎心处理
  1109. /// 1. 高频数据触发连续12个值都是正常的的高频心率处理
  1110. /// 2. 高频结束后的highFreqSampleTimes=0的高频心率处理
  1111. /// 3. 高频结束后的在highFreqSampleTimes>0 正常心率触发的高频心率处理(常态)
  1112. /// 4. 高频结束后的时间倒序的正常心率触发的高频心率处理
  1113. /// 5. 高频结束后计算胎心数据,防止结束后与常规心理的胎心处理过长,定时器时长highFreqSampleInterval触发的高频心率处理
  1114. /// 高频结束后超过9分钟且不在阈值内才告警
  1115. /// </summary>
  1116. /// <param name="heartRate"></param>
  1117. /// <param name="commonPHR"></param>
  1118. /// <param name="highFreqSampleTimes"></param>
  1119. /// <param name="upperAlarmThreshold"></param>
  1120. /// <param name="lowerAlarmThreshold"></param>
  1121. /// <param name="sampleTime"></param>
  1122. /// <param name="statStartTime"></param>
  1123. /// <param name="statEndTime"></param>
  1124. /// <returns></returns>
  1125. private async Task SaveAndPushFetalHeartRateEndFreqHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int highFreqSampleTimes, int upperAlarmThreshold, int lowerAlarmThreshold, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  1126. {
  1127. // 计算胎心=孕妇心率*系数
  1128. #region 胎心系数使用基于心率与中位数对比
  1129. var coefficient = 0f;
  1130. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  1131. if (heartRate.HeartRate < commonPHR!.Mode)
  1132. {
  1133. coefficient = commonPHR.StatMinValueFprCoefficient!;
  1134. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  1135. }
  1136. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  1137. else if (heartRate.HeartRate > commonPHR.Mode)
  1138. {
  1139. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  1140. {
  1141. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  1142. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  1143. }
  1144. else
  1145. {
  1146. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  1147. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  1148. }
  1149. }
  1150. else
  1151. {
  1152. coefficient = commonPHR.StatModeAvgFprCoefficient;
  1153. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  1154. }
  1155. #endregion
  1156. var fetalHeartRate = SafeType.SafeInt(heartRate.HeartRate! * coefficient);
  1157. // 胎心的最大值调整为220,超过都按该值220输出
  1158. // fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  1159. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  1160. var isAbnormal = 0;
  1161. #region 判断是否够highFreqSampleTimes,540s
  1162. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)heartRate.LastUpdate!, phrFreqstatus!.LastUpdate);
  1163. // 判断是否够highFreqSampleTimes,540s
  1164. ///高频时长不足10分钟停止高频的胎心值生成说明:最近12个数据的最小值生成胎心值,
  1165. ///对于小于高频下限阀值取高频下限阀值进行转换;
  1166. ///对于高于高频上限阀值取高频上限阀值进行转换。并输出相关日志后续进行数据分析。
  1167. if (ts < highFreqSampleTimes)
  1168. {
  1169. if (fetalHeartRate > upperAlarmThreshold)
  1170. {
  1171. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,计算胎心值 {fetalHeartRate} 高于高频警告上限阀值{upperAlarmThreshold},最后胎心值{upperAlarmThreshold},并且不告警");
  1172. fetalHeartRate = upperAlarmThreshold;
  1173. }
  1174. else if (fetalHeartRate < lowerAlarmThreshold)
  1175. {
  1176. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,计算胎心值 {fetalHeartRate} 低于高频警告下限阀值 {lowerAlarmThreshold},最后胎心值{lowerAlarmThreshold},并且不告警");
  1177. fetalHeartRate = lowerAlarmThreshold;
  1178. }
  1179. else
  1180. {
  1181. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,在高频警告下限阀值 {lowerAlarmThreshold} 和 高频警告上限阀值:{upperAlarmThreshold}之间,最后胎心值{fetalHeartRate},并且不告警");
  1182. }
  1183. }
  1184. // 超过highFreqSampleTimes,540s
  1185. else
  1186. {
  1187. if (fetalHeartRate > 220)
  1188. {
  1189. fetalHeartRate = 220;
  1190. _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")}");
  1191. }
  1192. // 胎心的最小值调整为90,超过都按该值90
  1193. if (fetalHeartRate < 90)
  1194. {
  1195. fetalHeartRate = 90;
  1196. _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")}");
  1197. }
  1198. isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  1199. }
  1200. #endregion
  1201. //if (phrFreqstatus == null) isAbnormal = 0;
  1202. //var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  1203. var statsusDesc = "高频";
  1204. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1205. // 保存到 数据服务 MySQL 数据库
  1206. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  1207. {
  1208. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  1209. PersonId = commonPHR!.PersonId,
  1210. Serialno = heartRate.Serialno,
  1211. HeartRate = fetalHeartRate,
  1212. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  1213. IsAbnormal = isAbnormal,
  1214. StatStartTime = statStartTime,
  1215. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  1216. CreateTime = DateTime.Now,
  1217. Method = 1,
  1218. IsDisplay = 1,
  1219. DeviceKey = commonPHR!.DeviceKey
  1220. };
  1221. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  1222. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  1223. // 推送最后一条常规心率计算的胎心数据到iot设备
  1224. #region 推送最后一条常规心率计算的胎心数据到iot设备
  1225. // 高频(<=12)-常规
  1226. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  1227. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  1228. {
  1229. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1230. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  1231. }
  1232. // 高频(13)-常规-高频(13)
  1233. if (phrFreqstatus != null)
  1234. {
  1235. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  1236. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1237. // 获取高频数据
  1238. var freqCollection = new List<PregnancyHeartRateModel>();
  1239. PregnancyHeartRateModel? previousItem = null;
  1240. foreach (var item in phr)
  1241. {
  1242. if (previousItem != null)
  1243. {
  1244. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1245. if (timeNextDiff <= 60)
  1246. {
  1247. freqCollection.Add(item);
  1248. }
  1249. }
  1250. // 高频最后一条
  1251. if (lastPhr.MessageId == item.MessageId)
  1252. {
  1253. freqCollection.Add(item);
  1254. }
  1255. previousItem = item;
  1256. }
  1257. //去除高频
  1258. foreach (var item in freqCollection)
  1259. {
  1260. phr.Remove(item);
  1261. }
  1262. lastPhr = phr.FirstOrDefault();
  1263. if (lastPhr?.MessageId == heartRate.MessageId)
  1264. {
  1265. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1266. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  1267. }
  1268. }
  1269. #endregion
  1270. #region 高频心率计算胎心数据到iot设备
  1271. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  1272. if (phrFreqstatus != null && isAbnormal != 0)
  1273. {
  1274. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1275. }
  1276. #endregion
  1277. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  1278. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  1279. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  1280. // 胎心数据推送到第三方
  1281. var topic = "topic.push.third";
  1282. var fhrThridMsg = new
  1283. {
  1284. messageId = fhrMsgId,
  1285. topic = topic,
  1286. time = fhrMsgTime,
  1287. data = new
  1288. {
  1289. imei = heartRate.Serialno,
  1290. value = fetalHeartRate,
  1291. isAbnormal,
  1292. type = "fetalHeart"
  1293. }
  1294. };
  1295. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  1296. // 胎心数据推送到微信
  1297. if (isAbnormal != 0)
  1298. {
  1299. topic = "topic.push.wx";
  1300. var fhrMsg = new
  1301. {
  1302. messageId = fhrMsgId,
  1303. topic = topic,
  1304. time = fhrMsgTime,
  1305. data = new
  1306. {
  1307. deviceId = device?.DeviceId,
  1308. imei = heartRate.Serialno,
  1309. alarmTypeId = 12,
  1310. alarmDeviceName = heartRate.Serialno,
  1311. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  1312. address = string.Empty,
  1313. deviceKey = device?.DeviceId
  1314. }
  1315. };
  1316. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  1317. }
  1318. }
  1319. private async Task SetIntervalTriggerAsync(string key, string imei, long interval, HisGpsHeartRate heartRate)
  1320. {
  1321. // var key = $"health_monitor/schedule_push/{type}/imei/{imei}";
  1322. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  1323. if (string.IsNullOrWhiteSpace(schedulePush))
  1324. {
  1325. var now = DateTime.Now;
  1326. var timeNextRun = now.Add(TimeSpan.FromSeconds(interval));
  1327. var data = new
  1328. {
  1329. imei,
  1330. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1331. ttl = interval,
  1332. next_run_time = timeNextRun.ToString("yyyy-MM-dd HH:mm:ss"),
  1333. trigger = heartRate,
  1334. };
  1335. var result = JsonConvert.SerializeObject(data);
  1336. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  1337. }
  1338. }
  1339. /// <summary>
  1340. /// 高频延时计算触发器
  1341. /// </summary>
  1342. /// <param name="key">键</param>
  1343. /// <param name="imei">IMEI</param>
  1344. /// <param name="interval">高频采集间隔</param>
  1345. /// <param name="heartRate">首条高频心率</param>
  1346. /// <returns></returns>
  1347. private async Task SetFreqHeartRateTriggerAsync(string key, string imei, long interval, HisGpsHeartRate? heartRate=null)
  1348. {
  1349. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  1350. if (string.IsNullOrWhiteSpace(schedulePush))
  1351. {
  1352. var now = DateTime.Now;
  1353. var data = new
  1354. {
  1355. imei,
  1356. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1357. lease = interval,
  1358. trigger = heartRate,
  1359. };
  1360. var result = JsonConvert.SerializeObject(data);
  1361. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  1362. _logger.LogInformation($"{imei} 心率高频状态创建首条高频心率的触发记录,创建高频延时计算触发器");
  1363. }
  1364. else
  1365. {
  1366. // 不断修改时长,直到最后的一条高频胎心
  1367. await _serviceEtcd.PutValAsync(key, schedulePush, interval, false).ConfigureAwait(false);
  1368. _logger.LogInformation($"{imei} 心率高频状态续租");
  1369. }
  1370. }
  1371. /// <summary>
  1372. /// 去除高频数据
  1373. /// </summary>
  1374. /// <param name="phr"></param>
  1375. /// <param name="highFreqSampleInterva"></param>
  1376. /// <returns></returns>
  1377. private static List<PregnancyHeartRateModel> GetNonFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr,int highFreqSampleInterval)
  1378. {
  1379. //phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1380. //var result = new List<PregnancyHeartRateModel>();
  1381. //PregnancyHeartRateModel? previousItem = null;
  1382. //foreach (var item in phr)
  1383. //{
  1384. // if (previousItem != null)
  1385. // {
  1386. // var timeNextDiff =(previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1387. // if (timeNextDiff > highFreqSampleInterval)
  1388. // {
  1389. // result.Add(previousItem);
  1390. // }
  1391. // }
  1392. // previousItem = item;
  1393. //}
  1394. //// 添加上一个
  1395. //if (previousItem != null)
  1396. //{
  1397. // result.Add(previousItem);
  1398. //}
  1399. //return result;
  1400. #region 反向
  1401. var phr1 = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1402. var result = new List<PregnancyHeartRateModel>();
  1403. PregnancyHeartRateModel? previousItem1 = null;
  1404. foreach (var item in phr1)
  1405. {
  1406. if (previousItem1 != null)
  1407. {
  1408. var timeNextDiff = (previousItem1!.LastUpdate - item.LastUpdate).TotalSeconds;
  1409. if (timeNextDiff > highFreqSampleInterval)
  1410. {
  1411. result.Add(previousItem1);
  1412. }
  1413. }
  1414. previousItem1 = item;
  1415. }
  1416. // 添加上一个
  1417. if (previousItem1 != null)
  1418. {
  1419. result.Add(previousItem1);
  1420. }
  1421. #endregion
  1422. #region 正向
  1423. var phr2 = phr.OrderByDescending(i => i.LastUpdate).ToList(); ;
  1424. var freqCollection = new List<PregnancyHeartRateModel>();
  1425. PregnancyHeartRateModel? previousItem = null;
  1426. foreach (var item in phr2)
  1427. {
  1428. if (previousItem != null)
  1429. {
  1430. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1431. if (timeNextDiff <= highFreqSampleInterval)
  1432. {
  1433. freqCollection.Add(item);
  1434. }
  1435. }
  1436. previousItem = item;
  1437. }
  1438. //去除高频
  1439. foreach (var item in freqCollection)
  1440. {
  1441. phr2.Remove(item);
  1442. }
  1443. #endregion
  1444. // 交集
  1445. var commonElements = phr2.Intersect(result).ToList();
  1446. return commonElements;
  1447. }
  1448. /// <summary>
  1449. /// 获取高频数据
  1450. /// </summary>
  1451. /// <param name="phr"></param>
  1452. /// <param name="highFreqSampleInterval"></param>
  1453. /// <returns></returns>
  1454. private static List<PregnancyHeartRateModel> GetFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr, int highFreqSampleInterval)
  1455. {
  1456. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1457. var freqCollection = new List<PregnancyHeartRateModel>();
  1458. PregnancyHeartRateModel? previousItem = null;
  1459. foreach (var item in phr)
  1460. {
  1461. if (previousItem != null)
  1462. {
  1463. var timeNextDiff = (previousItem.LastUpdate - item.LastUpdate).TotalSeconds;
  1464. if (timeNextDiff <= highFreqSampleInterval)
  1465. {
  1466. freqCollection.Add(previousItem);
  1467. }
  1468. }
  1469. previousItem = item;
  1470. }
  1471. // 检查最后一条是否高频
  1472. if (previousItem != null && (phr.Last().LastUpdate - previousItem.LastUpdate).TotalSeconds <= highFreqSampleInterval)
  1473. {
  1474. freqCollection.Add(previousItem);
  1475. }
  1476. return freqCollection;
  1477. }
  1478. }
  1479. }