Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1623 Zeilen
90KB

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