Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

611 rindas
35KB

  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[] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24 };
  47. public PregnancyHeartRateResolver(ILogger<PregnancyHeartRateResolver> logger,
  48. HttpHelper httpHelper, EtcdService serviceEtcd, DeviceCacheManager deviceCacheMgr,
  49. MqProcessLogic serviceMqProcess,
  50. IotApiService iotApiService, TDengineService serviceDengine, FetalMovementNormalValueRangeCacheManager fetalMovementNormalValueRangeCacheMgr,
  51. GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> hisFetalHeartApiClient,
  52. GpsLocationHistoryAccessorClient<HisGpsFetalMovement> hisFetalMovementApiClient
  53. )
  54. {
  55. _logger = logger;
  56. _httpHelper = httpHelper;
  57. _serviceEtcd = serviceEtcd;
  58. _serviceTDengine = serviceDengine;
  59. _deviceCacheMgr = deviceCacheMgr;
  60. _serviceIotApi = iotApiService;
  61. _serviceMqProcess= serviceMqProcess;
  62. _hisFetalHeartApiClient = hisFetalHeartApiClient;
  63. _hisFetalMovementApiClient = hisFetalMovementApiClient;
  64. _mgrFetalMovementNormalValueRangeCache = fetalMovementNormalValueRangeCacheMgr;
  65. }
  66. public void SetResolveInfo(PackageMsgModel msg)
  67. {
  68. var topicHmPregnancyHeartRate = JsonConvert.DeserializeObject<TopicHmPregnancyHeartRate>(msg.DetailData.ToString()!);
  69. _messageId.Value = msg.MessageId;
  70. _msgData.Value = new HisGpsHeartRate()
  71. {
  72. HeartRateId = topicHmPregnancyHeartRate!.PregnancyHeartRateId,
  73. MessageId = topicHmPregnancyHeartRate!.MessageId,
  74. Serialno = topicHmPregnancyHeartRate!.Serialno,
  75. HeartRate= topicHmPregnancyHeartRate.PregnancyHeartRate,
  76. LastUpdate = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmPregnancyHeartRate.LastUpdate) / 1000000),
  77. CreateTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmPregnancyHeartRate.CreateTime) / 1000000),
  78. Method = topicHmPregnancyHeartRate!.Method,
  79. IsDisplay = topicHmPregnancyHeartRate!.IsDisplay ? 1 : 0
  80. };
  81. }
  82. public override string ToString()
  83. {
  84. return $"{nameof(PregnancyHeartRateResolver)}[{_messageId.Value}]";
  85. }
  86. public async Task ExecuteMessageAsync()
  87. {
  88. var messageId = _messageId.Value;
  89. var heartRate = _msgData.Value!;
  90. try
  91. {
  92. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(heartRate.Serialno, "0067");
  93. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  94. if (isFetalHeartEnable)
  95. {
  96. //_logger.LogInformation($"{heartRate.Serialno} 计算胎心胎动启动");
  97. #region 定时下发触发器(定时建模)
  98. var key = $"health_monitor/schedule_push/pregnancy_heart_rate/imei/{heartRate.Serialno}";
  99. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  100. if (string.IsNullOrWhiteSpace(schedule_push))
  101. {
  102. // 注册首次下推
  103. var interval = 0;
  104. // 获取当前时间
  105. DateTime now = DateTime.Now;
  106. var rand = new Random();
  107. var pushSec = rand.Next(59);
  108. int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  109. // 计算距离下一个$interval天后的8点的时间间隔
  110. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 6, pushMin, pushSec).AddDays(interval);
  111. TimeSpan timeUntilNextRun = nextRunTime - now;
  112. if (timeUntilNextRun < TimeSpan.Zero)
  113. {
  114. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  115. nextRunTime += TimeSpan.FromDays(1);
  116. }
  117. var ttl = (long)timeUntilNextRun.TotalSeconds;
  118. var data = new
  119. {
  120. imei = heartRate.Serialno,
  121. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  122. ttl,
  123. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  124. };
  125. var result = JsonConvert.SerializeObject(data);
  126. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  127. }
  128. #endregion
  129. //_logger.LogInformation($"{heartRate.Serialno} 触发定时建模");
  130. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容
  131. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! + 5;
  132. // 触发高频监测的心率上限值
  133. var triggerHighFreqHigh = (int)watchConfig["triggerHighFreqHigh"]!;
  134. // 触发高频监测的心率下限值
  135. var triggerHighFreqLow = (int)watchConfig["triggerHighFreqLow"]!;
  136. //停止高频心率采样心率连续正常次数
  137. var stopHighFreqSampleCount = (int)watchConfig["stopHighFreqSampleCount"]!;
  138. // 高频心率采集时长 0 为持续采集,非零为高频心率的采集时长
  139. var highFreqSampleTimes = (int)watchConfig["highFreqSampleTimes"]!;
  140. // 告警上限阀值
  141. var upperAlarmThreshold = (int)watchConfig["upperAlarmThreshold"]!;
  142. // 告警下限阀值
  143. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  144. // EDOC
  145. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  146. // interval (分钟) 固定15分钟
  147. var intervalFHR = 15;//int)watchConfig["interval"]!;
  148. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  149. if (phr.Count >= 30)
  150. {
  151. #region 定时计算胎动数据触发器两小时间隔开始
  152. var fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}";
  153. ///// 计算 0 点秒数
  154. var fetalMovementLastUpdate = (DateTime)heartRate.LastUpdate!;
  155. DateTime fmScheduleNow = DateTime.Now;
  156. // 小于两小时
  157. if (fmScheduleNow > fetalMovementLastUpdate && (fmScheduleNow - fetalMovementLastUpdate).TotalHours <= 2)
  158. {
  159. var rand = new Random();
  160. var pushSec = rand.Next(59);
  161. int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  162. var scheduleHourDiff = SCHEDULE_HOUR
  163. .Where(h => h > fetalMovementLastUpdate.Hour)
  164. .OrderBy(h => h - fetalMovementLastUpdate.Hour)
  165. .FirstOrDefault() - fetalMovementLastUpdate.Hour;
  166. var scheduleTime = fetalMovementLastUpdate.AddHours(scheduleHourDiff);
  167. DateTime nextRunTime = new(scheduleTime.Year, scheduleTime.Month, scheduleTime.Day, scheduleTime.Hour, pushMin, pushSec);
  168. TimeSpan timeUntilNextRun = nextRunTime - fmScheduleNow;
  169. var ttl = (long)timeUntilNextRun.TotalSeconds;
  170. await SetIntervalTriggerAsync(fetalMovementKey, heartRate.Serialno, ttl);
  171. }
  172. #endregion
  173. #region 计算胎心数据(按心率时间LastUpdate)
  174. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(heartRate.Serialno);
  175. if (commonPHR == null)
  176. {
  177. // 处理孕妇业务,计算一般心率并下发
  178. commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(heartRate.Serialno, highFreqSampleInterval: highFreqSampleInterval);
  179. // 建模完成
  180. var flag = await _serviceIotApi.SetFetalConfig(heartRate.Serialno, 1, commonPHR!.MaxValue, commonPHR!.MinValue);
  181. _logger.LogInformation($"{heartRate.Serialno} 记录数量足够,建模完成");
  182. // 保存到TDengine数据库
  183. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR!);
  184. _logger.LogInformation($"保存TDengine完成");
  185. }
  186. // 获取最近的两个记录,并计算它们的 LastUpdate 时间差
  187. var firstTwoPhr = phr.OrderByDescending(i => i.LastUpdate).Take(2).Select(i => i.LastUpdate).ToList();
  188. var timeDiff = firstTwoPhr[0] - firstTwoPhr[1];
  189. // 如果需要,将时间差转换为秒
  190. var timeDiffInSeconds = timeDiff.TotalSeconds;
  191. // 高频统计结束时间
  192. var FreqStatsEnd = DateTime.Now;
  193. // 高频心率启动
  194. if (timeDiffInSeconds <= highFreqSampleInterval)
  195. {
  196. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  197. if (phrFreqstatus == null)
  198. {
  199. /// 设置高频状态
  200. _logger.LogInformation($"{heartRate.Serialno} 进入高频心率启动状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval}");
  201. // 设置高频状态
  202. _logger.LogInformation($"{heartRate.Serialno} phr.Count {phr.Count}");
  203. var freqFirstPhr = phr.OrderByDescending(i => i.LastUpdate).First();
  204. await _deviceCacheMgr.SetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno, freqFirstPhr);
  205. _logger.LogInformation($"{heartRate.Serialno} 设置高频状态");
  206. phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  207. }
  208. /// phr PregnancyHeartRate 连续连续正常次数个值都是正常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  209. /// 取连续正常次数正常值的平均值,推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  210. #region 检查是否连续12个心率值都是正常的
  211. // 获取最近连续正常次数个心率记录
  212. _logger.LogInformation($"{heartRate.Serialno} 设置 stopHighFreqSampleCount {stopHighFreqSampleCount}");
  213. var lastPhr = phr.OrderByDescending(i => i.LastUpdate).Take(stopHighFreqSampleCount).ToList();
  214. _logger.LogInformation($"{heartRate.Serialno} 设置 lastPhr {lastPhr.Count}");
  215. _logger.LogInformation($"{heartRate.Serialno} 设置 triggerHighFreqLow {triggerHighFreqLow}");
  216. _logger.LogInformation($"{heartRate.Serialno} 设置 triggerHighFreqHigh {triggerHighFreqHigh}");
  217. // 检查是否连续12个值都是正常的
  218. if (lastPhr.All(i => i.PregnancyHeartRate >= triggerHighFreqLow && i.PregnancyHeartRate <= triggerHighFreqHigh))
  219. {
  220. var avgPhr = lastPhr.Select(i => i.PregnancyHeartRate).Average();
  221. // 计算一般心率得到胎心系数
  222. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(DateTime.Now).ToString());
  223. // 高频数据不建模
  224. FreqStatsEnd = (DateTime)heartRate.LastUpdate!;
  225. _logger.LogInformation($"{heartRate.Serialno} 高频状态已经持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,连续 {stopHighFreqSampleCount} 次采样心率正常,将下发指令");
  226. var freqSaveAndPushFetalHeartRate = await _deviceCacheMgr.GetBizIntervalAsync(heartRate.Serialno, "SaveAndPushFetalHeartRate");
  227. // 高频不停,15分钟内只下发一条
  228. if (string.IsNullOrEmpty(freqSaveAndPushFetalHeartRate))
  229. {
  230. await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  231. // 删除高频状态的首条记录
  232. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  233. // 设置15分的SaveAndPushFetalHeartRate业务间隔
  234. await _deviceCacheMgr.SetBizIntervalAsync(heartRate.Serialno, "SaveAndPushFetalHeartRate");
  235. _logger.LogInformation($"{heartRate.Serialno} 连续 {stopHighFreqSampleCount} 次采样心率正常,结束高频心率状态, timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval},高频状态持续{((DateTime)heartRate.LastUpdate - phrFreqstatus!.LastUpdate).TotalSeconds} 秒");
  236. }
  237. else
  238. {
  239. _logger.LogWarning($"{heartRate.Serialno} 连续 {stopHighFreqSampleCount} 次采样心率正常,设备端应该结束高频状态,但设备端没有结束高频,平台高频15分钟内已经下发过指令");
  240. }
  241. }
  242. else
  243. {
  244. _logger.LogInformation($"{heartRate.Serialno} 处于高频状态...");
  245. }
  246. #endregion
  247. }
  248. // 高频心率结束或平常心率
  249. else
  250. {
  251. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  252. // 高频心率结束
  253. if (phrFreqstatus != null)
  254. {
  255. /// 在highFreqSampleTimes=0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  256. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  257. if (highFreqSampleTimes == 0)
  258. {
  259. var avgPhr = phr.OrderByDescending(i => i.LastUpdate)
  260. .Where(i => i.LastUpdate >= phrFreqstatus?.LastUpdate)
  261. .Skip(1) // 去除首条
  262. .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh)
  263. .Select(i => i.PregnancyHeartRate).Average();
  264. // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  265. // 计算一般心率得到胎心系数
  266. // 高频数据不建模
  267. FreqStatsEnd = firstTwoPhr[1];
  268. _logger.LogInformation($"{heartRate.Serialno} 高频状态已经持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,highFreqSampleTimes={highFreqSampleTimes}秒,即将结束高频状态,将下发指令");
  269. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString());
  270. await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  271. }
  272. /// 在highFreqSampleTimes>0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  273. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  274. if (highFreqSampleTimes > 0 && heartRate.LastUpdate >= (phrFreqstatus?.LastUpdate.AddSeconds(highFreqSampleTimes)))
  275. {
  276. // 获取高频心率数据个数
  277. var filterPhr = phr
  278. .Where(i => i.LastUpdate >= phrFreqstatus?.LastUpdate)
  279. .Skip(1)
  280. .ToList();
  281. //var freqCollection = new List<PregnancyHeartRateModel>();
  282. //PregnancyHeartRateModel? previousItem = null;
  283. //foreach (var item in filterPhr)
  284. //{
  285. // if (previousItem != null)
  286. // {
  287. // var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  288. // if (timeNextDiff <= highFreqSampleInterval)
  289. // {
  290. // freqCollection.Add(item);
  291. // }
  292. // }
  293. // previousItem = item;
  294. //}
  295. _logger.LogInformation($"{heartRate.Serialno} {phrFreqstatus?.LastUpdate.ToString("yyyy-MM-dd HH:mm:ss")}--{firstTwoPhr[1].ToString("yyyy-MM-dd HH:mm:ss")} 产生高频心率数量 {filterPhr.Count} 条");
  296. // 高频心率数据大于等于stopHighFreqSampleCount/12个才计算胎心数据
  297. if (filterPhr.Count >= stopHighFreqSampleCount)
  298. {
  299. var avgPhr = filterPhr
  300. .OrderByDescending(i => i.LastUpdate)
  301. .Take(stopHighFreqSampleCount) // 计算最后12条
  302. //.Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh)
  303. .Select(i => i.PregnancyHeartRate).Average();
  304. // 高频数据不建模
  305. FreqStatsEnd = firstTwoPhr[1];
  306. _logger.LogInformation($"{heartRate.Serialno} 高频状态已经持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,超过约定的 {highFreqSampleTimes} 秒,即将结束高频状态,将下发指令");
  307. await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  308. }
  309. else
  310. {
  311. _logger.LogInformation($"{heartRate.Serialno} 高频心率的数据不足{stopHighFreqSampleCount}条,不进行胎心计算");
  312. }
  313. }
  314. //不满足持续10分钟highFreqSampleTimes
  315. else
  316. {
  317. _logger.LogInformation($"{heartRate.Serialno} 高频持续时间不足{highFreqSampleTimes},只持续{(firstTwoPhr[1] - phrFreqstatus!.LastUpdate).TotalSeconds} 秒");
  318. }
  319. // 删除高频状态的首条记录
  320. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  321. _logger.LogInformation($"{heartRate.Serialno} 超时结束高频心率状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval},高频状态持续{(firstTwoPhr[1] - phrFreqstatus!.LastUpdate).TotalSeconds} 秒");
  322. // 计算本次平常心率的胎心数据
  323. //await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  324. // 使用延后计算
  325. var fhrScheduleKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  326. var fhrScheduleTTL = 10;
  327. await SetIntervalTriggerAsync(fhrScheduleKey, heartRate.Serialno, fhrScheduleTTL);
  328. }
  329. // 平常心率
  330. else
  331. {
  332. // 计算本次平常心率的胎心数据
  333. //await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  334. // 使用延后计算
  335. var fhrScheduleKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  336. var fhrScheduleTTL = 10;
  337. await SetIntervalTriggerAsync(fhrScheduleKey, heartRate.Serialno, fhrScheduleTTL);
  338. }
  339. }
  340. #endregion
  341. }
  342. else
  343. {
  344. _logger.LogInformation($"{heartRate.Serialno} 记录不足30条,建模中");
  345. }
  346. }
  347. }
  348. catch (Exception ex)
  349. {
  350. _logger.LogError($"{heartRate.Serialno} 处理孕妇心率数据异常 \n{ex.Message}\n{ex.StackTrace}");
  351. }
  352. }
  353. /// <summary>
  354. /// 平常心率计算胎心数据
  355. /// </summary>
  356. /// <param name="heartRate"></param>
  357. /// <param name="upperAlarmThreshold"></param>
  358. /// <param name="lowerAlarmThreshold"></param>
  359. /// <param name="intervalFHR"></param>
  360. /// <param name="commonPHR"></param>
  361. /// <returns></returns>
  362. private async Task CalculateNormalFetalHeartRateAsync(HisGpsHeartRate heartRate, int upperAlarmThreshold, int lowerAlarmThreshold, int intervalFHR, PregnancyCommonHeartRateModel? commonPHR)
  363. {
  364. // 上15分钟的数据
  365. // 获取当前时间
  366. DateTime nowInterval = (DateTime)heartRate.LastUpdate!;
  367. // 计算last_update到上一间隔的分钟数
  368. int minutesToSubtract = nowInterval.Minute % intervalFHR;
  369. // 计算上一间隔的时间
  370. DateTime previousInterval = nowInterval.AddMinutes(-minutesToSubtract).AddSeconds(-nowInterval.Second).AddMilliseconds(-nowInterval.Millisecond);
  371. // 使用 last_update 上一刻
  372. var sampleTimeFHR = DateTimeUtil.ConvertToTimeStamp(previousInterval).ToString();
  373. // 计算last_update到下一间隔的分钟数
  374. int minutesToAdd = intervalFHR - (nowInterval.Minute % intervalFHR);
  375. if (minutesToAdd == intervalFHR)
  376. {
  377. minutesToAdd = 0; // 如果已经是间隔,则不需要增加分钟
  378. }
  379. // 计算下一间隔的时间
  380. DateTime nextInterval = nowInterval.AddMinutes(minutesToAdd)
  381. .AddSeconds(-nowInterval.Second)
  382. .AddMilliseconds(-nowInterval.Millisecond);
  383. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  384. var normalPhrStatStartTime = nextInterval.AddMinutes(-intervalFHR) ;
  385. var normalPhrStatEndTime = nextInterval;
  386. _logger.LogInformation($"{heartRate.Serialno} 计算胎心数据, 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} ");
  387. var filteredPhr = daysPhr
  388. // 使用 last_update 下一刻
  389. .Where(i => i.LastUpdate <= normalPhrStatEndTime && i.LastUpdate >= normalPhrStatStartTime)
  390. .ToList();
  391. if (filteredPhr.Count == 0)
  392. {
  393. _logger.LogWarning($"{heartRate.Serialno} 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} 孕妇心率数据不足,{filteredPhr.Count}条记录");
  394. return;
  395. }
  396. var phrValue = filteredPhr.Count == 1
  397. ? filteredPhr.First().PregnancyHeartRate
  398. : filteredPhr.Average(i => i.PregnancyHeartRate);
  399. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, phrValue, sampleTimeFHR);
  400. await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, phrValue, sampleTimeFHR, normalPhrStatStartTime, normalPhrStatEndTime);
  401. }
  402. /// <summary>
  403. ///
  404. /// </summary>
  405. /// <param name="heartRate"></param>
  406. /// <param name="commonPHR"></param>
  407. /// <param name="upperAlarmThreshold"></param>
  408. /// <param name="lowerAlarmThreshold"></param>
  409. /// <param name="phrValue"></param>
  410. /// <param name="sampleTime"></param>
  411. /// <param name="statStartTime"></param>
  412. /// <param name="statEndTime"></param>
  413. /// <returns></returns>
  414. private async Task SaveAndPushFetalHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int upperAlarmThreshold, int lowerAlarmThreshold, double phrValue, string sampleTime,DateTime statStartTime, DateTime statEndTime)
  415. {
  416. // 计算胎心=孕妇心率*系数
  417. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  418. //fetalHeartRate = fetalHeartRate > 220 ? 220 : fetalHeartRate; // 胎心的最大值调整为220,超过都按该值220输出
  419. if (fetalHeartRate >= 220)
  420. {
  421. // 先使用最小系数计算
  422. var statMaxValueFprCoefficient = commonPHR?.StatMaxValueFprCoefficient!;
  423. var statMinValueFprCoefficient = commonPHR?.StatMinValueFprCoefficient!;
  424. var coefficient = statMaxValueFprCoefficient < statMinValueFprCoefficient ? statMaxValueFprCoefficient : statMinValueFprCoefficient;
  425. fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  426. if (fetalHeartRate < 220)
  427. {
  428. _logger.LogWarning($"{heartRate.Serialno} 使用极值系数 {coefficient} ,建模数据可能出现异常,请检查");
  429. }
  430. else
  431. {
  432. fetalHeartRate = 220;
  433. _logger.LogWarning($"{heartRate.Serialno} 使用所有系数都不能放映实际,建模数据可能出现异常,请检查");
  434. }
  435. }
  436. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  437. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  438. if (phrFreqstatus == null) isAbnormal = 0;
  439. //if (!isFreq)
  440. //{
  441. // statStartTime = heartRate.LastUpdate;
  442. //
  443. //}
  444. // 保存到 数据服务 MySQL 数据库
  445. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  446. {
  447. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  448. PersonId = commonPHR!.PersonId,
  449. Serialno = heartRate.Serialno,
  450. HeartRate = fetalHeartRate,
  451. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  452. IsAbnormal = isAbnormal,
  453. StatStartTime = statStartTime,
  454. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  455. CreateTime = DateTime.Now,
  456. Method = 1,
  457. IsDisplay = 1,
  458. DeviceKey = commonPHR!.DeviceKey
  459. };
  460. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  461. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  462. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  463. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  464. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  465. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  466. // 胎心数据推送到第三方
  467. var topic = "topic.push.third";
  468. var fhrThridMsg = new
  469. {
  470. messageId = fhrMsgId,
  471. topic = topic,
  472. time = fhrMsgTime,
  473. data = new
  474. {
  475. imei = heartRate.Serialno,
  476. value = fetalHeartRate,
  477. isAbnormal,
  478. type = "fetalHeart"
  479. }
  480. };
  481. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  482. // 胎心数据推送到微信
  483. if (isAbnormal != 0)
  484. {
  485. topic = "topic.push.wx";
  486. var fhrMsg = new
  487. {
  488. messageId = fhrMsgId,
  489. topic = topic,
  490. time = fhrMsgTime,
  491. data = new
  492. {
  493. deviceId = device?.DeviceId,
  494. imei = heartRate.Serialno,
  495. alarmTypeId = 12,
  496. alarmDeviceName = heartRate.Serialno,
  497. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  498. address = string.Empty,
  499. deviceKey = device?.DeviceId
  500. }
  501. };
  502. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  503. }
  504. }
  505. private async Task SetIntervalTriggerAsync(string key,string imei, long interval)
  506. {
  507. // var key = $"health_monitor/schedule_push/{type}/imei/{imei}";
  508. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  509. if (string.IsNullOrWhiteSpace(schedulePush))
  510. {
  511. var now = DateTime.Now;
  512. var timeNextRun = now.Add(TimeSpan.FromSeconds(interval));
  513. var data = new
  514. {
  515. imei,
  516. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  517. ttl = interval,
  518. next_run_time = timeNextRun.ToString("yyyy-MM-dd HH:mm:ss")
  519. };
  520. var result = JsonConvert.SerializeObject(data);
  521. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  522. }
  523. }
  524. }
  525. }