Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

604 lignes
33KB

  1. using HealthMonitor.Common;
  2. using HealthMonitor.Common.helper;
  3. using HealthMonitor.Model.Service.Mapper;
  4. using HealthMonitor.Service.Biz;
  5. using HealthMonitor.Service.Biz.db;
  6. using HealthMonitor.Service.Cache;
  7. using HealthMonitor.Service.Etcd;
  8. using HealthMonitor.Service.Resolver.Interface;
  9. using HealthMonitor.Service.Sub;
  10. using HealthMonitor.Service.Sub.Topic.Model;
  11. using Microsoft.EntityFrameworkCore.Metadata;
  12. using Microsoft.Extensions.Logging;
  13. using Newtonsoft.Json;
  14. using SqlSugar;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Linq;
  18. using System.Text;
  19. using System.Threading.Tasks;
  20. using TelpoDataService.Util.Clients;
  21. using TelpoDataService.Util.Entities.GpsCard;
  22. using TelpoDataService.Util.Entities.GpsLocationHistory;
  23. using TelpoDataService.Util.Models;
  24. using TelpoDataService.Util.QueryObjects;
  25. namespace HealthMonitor.Service.Resolver
  26. {
  27. public class PregnancyHeartRateResolver : IResolver
  28. {
  29. private readonly ILogger<PregnancyHeartRateResolver> _logger;
  30. private readonly TDengineService _serviceTDengine;
  31. private readonly DeviceCacheManager _deviceCacheMgr;
  32. private readonly IotApiService _serviceIotApi;
  33. private readonly AsyncLocal<string> _messageId = new();
  34. private readonly AsyncLocal<HisGpsHeartRate> _msgData = new();
  35. private readonly HttpHelper _httpHelper = default!;
  36. private readonly EtcdService _serviceEtcd;
  37. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> _hisFetalHeartApiClient;
  38. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalMovement> _hisFetalMovementApiClient;
  39. private readonly FetalMovementNormalValueRangeCacheManager _mgrFetalMovementNormalValueRangeCache;
  40. private readonly FetalMovementCacheManager _mgrFetalMovement;
  41. public PregnancyHeartRateResolver(ILogger<PregnancyHeartRateResolver> logger,
  42. HttpHelper httpHelper, EtcdService serviceEtcd, DeviceCacheManager deviceCacheMgr,
  43. IotApiService iotApiService, TDengineService serviceDengine, FetalMovementNormalValueRangeCacheManager fetalMovementNormalValueRangeCacheMgr,
  44. GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> hisFetalHeartApiClient,
  45. FetalMovementCacheManager fetalMovementCacheManager,
  46. GpsLocationHistoryAccessorClient<HisGpsFetalMovement> hisFetalMovementApiClient
  47. )
  48. {
  49. _logger = logger;
  50. _httpHelper = httpHelper;
  51. _serviceEtcd = serviceEtcd;
  52. _serviceTDengine = serviceDengine;
  53. _deviceCacheMgr = deviceCacheMgr;
  54. _serviceIotApi = iotApiService;
  55. _hisFetalHeartApiClient = hisFetalHeartApiClient;
  56. _hisFetalMovementApiClient = hisFetalMovementApiClient;
  57. _mgrFetalMovementNormalValueRangeCache = fetalMovementNormalValueRangeCacheMgr;
  58. _mgrFetalMovement = fetalMovementCacheManager;
  59. }
  60. public void SetResolveInfo(PackageMsgModel msg)
  61. {
  62. var topicHmPregnancyHeartRate = JsonConvert.DeserializeObject<TopicHmPregnancyHeartRate>(msg.DetailData.ToString()!);
  63. _messageId.Value = msg.MessageId;
  64. _msgData.Value = new HisGpsHeartRate()
  65. {
  66. HeartRateId = topicHmPregnancyHeartRate!.PregnancyHeartRateId,
  67. MessageId = topicHmPregnancyHeartRate!.MessageId,
  68. Serialno = topicHmPregnancyHeartRate!.Serialno,
  69. HeartRate= topicHmPregnancyHeartRate.PregnancyHeartRate,
  70. LastUpdate = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmPregnancyHeartRate.LastUpdate) / 1000000),
  71. CreateTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmPregnancyHeartRate.CreateTime) / 1000000),
  72. Method = topicHmPregnancyHeartRate!.Method,
  73. IsDisplay = topicHmPregnancyHeartRate!.IsDisplay ? 1 : 0
  74. };
  75. }
  76. public override string ToString()
  77. {
  78. return $"{nameof(PregnancyHeartRateResolver)}[{_messageId.Value}]";
  79. }
  80. public async Task ExecuteMessageAsync()
  81. {
  82. //throw new NotImplementedException();
  83. var messageId = _messageId.Value;
  84. var heartRate = _msgData.Value!;
  85. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(heartRate.Serialno, "0067");
  86. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  87. if (isFetalHeartEnable)
  88. {
  89. // 高频心率采样间隔
  90. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]!;
  91. // 触发高频监测的心率上限值
  92. var triggerHighFreqHigh = (int)watchConfig["triggerHighFreqHigh"]!;
  93. // 触发高频监测的心率下限值
  94. var triggerHighFreqLow = (int)watchConfig["triggerHighFreqLow"]!;
  95. //停止高频心率采样心率连续正常次数
  96. var stopHighFreqSampleCount = (int)watchConfig["stopHighFreqSampleCount"]!;
  97. // 高频心率采集时长 0 为持续采集,非零为高频心率的采集时长
  98. var highFreqSampleTimes = (int)watchConfig["stopHighFreqSampleCount"]!;
  99. // 告警上限阀值
  100. var upperAlarmThreshold = (int)watchConfig["upperAlarmThreshold"]!;
  101. // 告警下限阀值
  102. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  103. // EDOC
  104. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  105. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  106. if (phr.Count >= 30)
  107. {
  108. #region 高频心率计算
  109. // 获取最近的两个记录,并计算它们的 LastUpdate 时间差
  110. var firstTwoPhr = phr.OrderByDescending(i => i.LastUpdate).Take(2).Select(i => i.LastUpdate).ToList();
  111. var timeDiff = firstTwoPhr[0] - firstTwoPhr[1];
  112. // 如果需要,将时间差转换为秒
  113. var timeDiffInSeconds = timeDiff.TotalSeconds;
  114. // 高频心率启动
  115. if (timeDiffInSeconds<=highFreqSampleInterval)
  116. {
  117. var phrFreqstatus =await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  118. if (phrFreqstatus == null)
  119. {
  120. /// 设置高频状态
  121. _logger.LogInformation($"进入高频心率启动状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval}");
  122. // 设置高频状态
  123. var freqFirstPhr= phr.OrderByDescending(i => i.Timestamp).First();
  124. await _deviceCacheMgr.SetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno, freqFirstPhr);
  125. phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  126. }
  127. /// phr PregnancyHeartRate 连续连续正常次数个值都是正常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  128. /// 取连续正常次数正常值的平均值,推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  129. #region 检查是否连续12个值都是正常的
  130. // 获取最近连续正常次数个心率记录
  131. var lastPhr = phr.OrderByDescending(i => i.Timestamp).Take(stopHighFreqSampleCount).ToList();
  132. // 检查是否连续12个值都是正常的
  133. if (lastPhr.All(i => i.PregnancyHeartRate >= triggerHighFreqLow && i.PregnancyHeartRate <= triggerHighFreqHigh))
  134. {
  135. var avgPhr = lastPhr.Select(i => i.PregnancyHeartRate).Average();
  136. // 计算一般心率得到胎心系数
  137. await SaveAndPushFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr);
  138. }
  139. #endregion
  140. }
  141. // 高频心率结束
  142. else
  143. {
  144. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  145. if (phrFreqstatus != null)
  146. {
  147. /// 在highFreqSampleTimes=0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  148. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  149. if (highFreqSampleTimes==0)
  150. {
  151. // if (phr.OrderByDescending(i => i.Timestamp)
  152. //.Where(i => i.Timestamp >= phrFreqstatus?.Timestamp)
  153. //.Skip(1) // 去除首条
  154. //.All(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHig))
  155. // {
  156. // var avgPhr = phr.Select(i => i.PregnancyHeartRate).Average();
  157. // // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  158. // // 计算一般心率得到胎心系数
  159. // }
  160. var avgPhr = phr.OrderByDescending(i => i.Timestamp)
  161. .Where(i => i.Timestamp >= phrFreqstatus?.Timestamp)
  162. .Skip(1) // 去除首条
  163. .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh)
  164. .Select(i => i.PregnancyHeartRate).Average();
  165. // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  166. // 计算一般心率得到胎心系数
  167. await SaveAndPushFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr);
  168. }
  169. /// 在highFreqSampleTimes>0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  170. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  171. if (highFreqSampleTimes > 0 && heartRate.LastUpdate >= (phrFreqstatus?.LastUpdate + TimeSpan.FromSeconds(highFreqSampleTimes)))
  172. {
  173. var avgPhr = phr
  174. .Where(i => i.Timestamp >= phrFreqstatus?.Timestamp)
  175. .Skip(1) // 去除首条
  176. .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh)
  177. .Select(i => i.PregnancyHeartRate).Average();
  178. // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  179. // 计算一般心率得到胎心系数
  180. await SaveAndPushFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr);
  181. }
  182. // 删除高频状态的首条记录
  183. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  184. /// 设置高频状态
  185. _logger.LogInformation($"结束高频心率状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval}");
  186. }
  187. }
  188. #endregion
  189. #region 计算胎心和胎动数据
  190. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(heartRate.Serialno);
  191. if (commonPHR != null)
  192. {
  193. #region 计算胎心数据
  194. _logger.LogInformation($"{heartRate.Serialno} 计算胎心数据 ");
  195. // 上15分钟的数据
  196. // 获取当前时间
  197. DateTime nowQuarter = (DateTime)heartRate.LastUpdate!;
  198. // 计算last_update到上一刻钟的分钟数
  199. int minutesToSubtract = nowQuarter.Minute % 15;
  200. // 计算上一刻钟的时间
  201. DateTime previousQuarter = nowQuarter.AddMinutes(-minutesToSubtract).AddSeconds(-nowQuarter.Second).AddMilliseconds(-nowQuarter.Millisecond);
  202. // 使用 last_update 上一刻
  203. var sampleTime = DateTimeUtil.ConvertToTimeStamp(previousQuarter).ToString();
  204. // 计算last_update到下一刻钟的分钟数
  205. int minutesToAdd = 15 - (nowQuarter.Minute % 15);
  206. if (minutesToAdd == 15)
  207. {
  208. minutesToAdd = 0; // 如果已经是刻钟,则不需要增加分钟
  209. }
  210. // 计算下一刻钟的时间
  211. DateTime nextQuarter = nowQuarter.AddMinutes(minutesToAdd)
  212. .AddSeconds(-nowQuarter.Second)
  213. .AddMilliseconds(-nowQuarter.Millisecond);
  214. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  215. var filteredPhr = daysPhr
  216. // 使用 last_update 下一刻
  217. .Where(i => i.LastUpdate <= nextQuarter && i.LastUpdate >= nextQuarter.AddMinutes(-15))
  218. .ToList();
  219. var qarterPhrValue = filteredPhr.Count == 1
  220. ? filteredPhr.First().PregnancyHeartRate
  221. : filteredPhr.Average(i => i.PregnancyHeartRate);
  222. var fetalHeartRate = SafeType.SafeInt(qarterPhrValue * commonPHR?.StatModeAvgFprCoefficient!);
  223. var fetalHeartRateIsAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  224. fetalHeartRateIsAbnormal = 0;// 不是高频数据,按正常值
  225. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  226. {
  227. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  228. PersonId = commonPHR!.PersonId,
  229. Serialno = heartRate.Serialno,
  230. HeartRate = fetalHeartRate,
  231. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  232. IsAbnormal = fetalHeartRateIsAbnormal,
  233. StatStartTime = filteredPhr.OrderBy(i => i.LastUpdate).First().LastUpdate,
  234. StatEndTime = filteredPhr.OrderBy(i => i.LastUpdate).Last().LastUpdate,
  235. CreateTime = DateTime.Now,
  236. Method = 1,
  237. IsDisplay = 1,
  238. DeviceKey = commonPHR!.DeviceKey
  239. };
  240. // 保存到 数据服务 MySQL 数据库
  241. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  242. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  243. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, fetalHeartRateIsAbnormal);
  244. #endregion
  245. #region 计算胎动数据
  246. _logger.LogInformation($"{heartRate.Serialno} 计算胎动数据 ");
  247. var fetalMovementNow = (DateTime)heartRate.LastUpdate!;
  248. var midNight = new DateTime(fetalMovementNow.Year, fetalMovementNow.Month, fetalMovementNow.Day, 0, 0, 0);
  249. TimeSpan fetalMovementTS = fetalMovementNow - midNight;
  250. // 当天每隔2小时的段数,取整数部分
  251. int segmentCount = (int)(fetalMovementTS.TotalHours / 2);
  252. for (int i = 0; i < segmentCount; i++)
  253. {
  254. // 每两小时
  255. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(midNight.AddHours(2 * i)).ToString()[..10];
  256. // 统计开始时间
  257. var statStartTime = midNight.AddHours(2 * i);
  258. // 统计结束时间
  259. var statEndTime = midNight.AddHours(2 * (i+1));
  260. //var isFetalMovementExist = await _hisFetalMovementApiClient.GetFirstAsync(param, heartRate.Serialno[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  261. var isFetalMovementExisted = await _mgrFetalMovement.FetalMovementIsExistedAsync(heartRate.Serialno, fetalMovementSampleTime);
  262. if (!isFetalMovementExisted)
  263. {
  264. /// 开始计算
  265. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate<= statEndTime)
  266. .OrderByDescending(i => i.LastUpdate)
  267. .Select(i => i.LastUpdate)
  268. .ToList();
  269. if (phrRange.Count >= 2)
  270. {
  271. var duringMins = Math.Abs((phrRange.First()- statStartTime).TotalMinutes);
  272. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  273. bool isInTimeRanges = IsLastUpdateInTimeRanges(fetalMovementNow);
  274. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  275. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  276. {
  277. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  278. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  279. .Where(i =>
  280. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  281. i.PregnancyPeriod[1] >= pregnancyWeeks)
  282. .Select(i => i.MedianMovement)
  283. .FirstOrDefault()
  284. :
  285. fetalMovementMap
  286. .Where(i =>
  287. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  288. i.PregnancyPeriod[1] >= pregnancyWeeks)
  289. .Select(i => i.InitialMovement)
  290. .FirstOrDefault()
  291. ;
  292. var fetalMovementValue = (fetalMovementMapValue * duringMins * 2) / 120;
  293. // 四舍五入
  294. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  295. // _logger.LogInformation($"{heartRate.Serialno} segmentCountIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");
  296. _logger.LogInformation($"{heartRate.Serialno} 胎动数据采样时间:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 原始胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{statStartTime}-{phrRange.First()}, 胎动计算值:{fetalMovementValue}, 胎动最终值:{fetalMovement}");
  297. // 获取胎心数据状态与胎动数据状态一致
  298. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  299. // 推送到api/v1/open/OpenIot/SetFetalMovementConfig
  300. await _serviceIotApi.SetFetalMovementConfig(heartRate.Serialno, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  301. // 保存到MySQL数据库
  302. HisGpsFetalMovement fm = new()
  303. {
  304. FetalMovementId = Guid.NewGuid().ToString("D"),
  305. PersonId = commonPHR!.PersonId,
  306. Serialno = heartRate.Serialno,
  307. CreateTime = DateTime.Now,
  308. IsAbnormal = feltalMovementIsAbnormal,
  309. FetalMovementValue = fetalMovement,
  310. SampleTime = fetalMovementSampleTime,
  311. Method = 1,
  312. IsDisplay = 1,
  313. DeviceKey = commonPHR!.DeviceKey
  314. };
  315. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  316. // 设置入库缓存记录
  317. await _mgrFetalMovement.SetFetalMovementAsync(heartRate.Serialno, fetalMovementSampleTime);
  318. }
  319. }
  320. }
  321. }
  322. #endregion
  323. }
  324. #endregion
  325. #region 定时计算胎心数据触发器 {interval} 秒后
  326. //var fetalKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  327. //await SetIntervalTriggerAsync(fetalKey, heartRate.Serialno, 60 * 15);
  328. #endregion
  329. #region 定时计算胎心数据触发器下一刻钟后
  330. //// 获取当前时间
  331. //DateTime nowQuarter = DateTime.Now;
  332. //// 计算下一个15分钟的刻钟
  333. //int minutesToAdd = 15 - (nowQuarter.Minute % 15);
  334. //if (minutesToAdd == 15)
  335. //{
  336. // minutesToAdd = 0; // 如果已经是刻钟,则不需要增加分钟
  337. //}
  338. //// 计算下一刻钟的时间
  339. //DateTime nextQuarter = nowQuarter.AddMinutes(minutesToAdd)
  340. // .AddSeconds(-nowQuarter.Second)
  341. // .AddMilliseconds(-nowQuarter.Millisecond);
  342. //// 计算时间差
  343. //TimeSpan timeDifference = nextQuarter - nowQuarter;
  344. //var fetalKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  345. //await SetIntervalTriggerAsync(fetalKey, heartRate.Serialno, (long)timeDifference.TotalSeconds);
  346. #endregion
  347. #region 定时计算胎动数据触发器 0 点开始
  348. //var fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}";
  349. ///// 计算 0 点秒数
  350. //DateTime now = DateTime.Now;
  351. //var rand = new Random();
  352. //var pushSec = rand.Next(59);
  353. //int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  354. //DateTime nextRunTime = new (now.Year, now.Month, now.Day, 0, pushMin, pushSec);
  355. //TimeSpan timeUntilNextRun = nextRunTime - now;
  356. //if (timeUntilNextRun < TimeSpan.Zero)
  357. //{
  358. // timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  359. // nextRunTime += timeUntilNextRun;
  360. //}
  361. //var ttl = (long)timeUntilNextRun.TotalSeconds;
  362. //await SetIntervalTriggerAsync(fetalMovementKey, heartRate.Serialno, ttl);
  363. #endregion
  364. }
  365. #region 定时下发触发器(定时建模)
  366. var key = $"health_monitor/schedule_push/pregnancy_heart_rate/imei/{heartRate.Serialno}";
  367. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  368. if (string.IsNullOrWhiteSpace(schedule_push))
  369. {
  370. // 注册首次下推
  371. #if DEBUG
  372. // await _serviceEtcd.PutValAsync(key, result, 60*1, false).ConfigureAwait(false);
  373. var interval = 0;
  374. // 获取当前时间
  375. DateTime now = DateTime.Now;
  376. // 计算距离下一个$interval天后的8点的时间间隔
  377. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 1, 58).AddDays(interval);
  378. TimeSpan timeUntilNextRun = nextRunTime - now;
  379. // 如果当前时间已经超过了8点,将等待到明天后的8点
  380. if (timeUntilNextRun < TimeSpan.Zero)
  381. {
  382. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  383. nextRunTime += timeUntilNextRun;
  384. }
  385. var ttl = (long)timeUntilNextRun.TotalSeconds;
  386. var data = new
  387. {
  388. imei = heartRate.Serialno,
  389. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  390. ttl,
  391. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  392. };
  393. var result = JsonConvert.SerializeObject(data);
  394. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  395. #else
  396. var interval = 0;
  397. // 获取当前时间
  398. DateTime now = DateTime.Now;
  399. var rand=new Random();
  400. var pushSec = rand.Next(59);
  401. int pushMin= int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  402. // 计算距离下一个$interval天后的8点的时间间隔
  403. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 18, pushMin, pushSec).AddDays(interval);
  404. TimeSpan timeUntilNextRun = nextRunTime - now;
  405. if (timeUntilNextRun < TimeSpan.Zero)
  406. {
  407. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  408. nextRunTime += TimeSpan.FromDays(1);
  409. }
  410. var ttl =(long)timeUntilNextRun.TotalSeconds;
  411. var data = new
  412. {
  413. imei = heartRate.Serialno,
  414. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  415. ttl,
  416. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  417. };
  418. var result = JsonConvert.SerializeObject(data);
  419. await _serviceEtcd.PutValAsync(key, result,ttl, false).ConfigureAwait(false);
  420. #endif
  421. }
  422. #endregion
  423. }
  424. }
  425. private async Task SaveAndPushFetalHeartRateAsync(HisGpsHeartRate heartRate, int upperAlarmThreshold, int lowerAlarmThreshold, double avgPhr)
  426. {
  427. var commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(heartRate.Serialno);
  428. if (commonPHR != null)
  429. {
  430. // 保存到TDengine数据库
  431. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR);
  432. // 计算胎心=孕妇心率*系数
  433. var fetalHeartRate = SafeType.SafeInt(avgPhr * commonPHR?.StatModeAvgFprCoefficient!);
  434. var sampleTime = DateTimeUtil.ConvertToTimeStamp(DateTime.Now).ToString();
  435. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  436. // 保存到 数据服务 MySQL 数据库
  437. HisGpsFetalHeartRate gpsFetalHeartRate = new ()
  438. {
  439. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  440. PersonId = commonPHR!.PersonId,
  441. Serialno = heartRate.Serialno,
  442. HeartRate = fetalHeartRate,
  443. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  444. IsAbnormal = isAbnormal,
  445. StatStartTime = commonPHR.StatStartTime,
  446. StatEndTime = commonPHR.StatEndTime,
  447. CreateTime = DateTime.Now,
  448. Method = 1,
  449. IsDisplay = 1,
  450. DeviceKey = commonPHR!.DeviceKey
  451. };
  452. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  453. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  454. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  455. }
  456. }
  457. private async Task SetIntervalTriggerAsync(string key,string imei, long interval)
  458. {
  459. // var key = $"health_monitor/schedule_push/{type}/imei/{imei}";
  460. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  461. if (string.IsNullOrWhiteSpace(schedulePush))
  462. {
  463. var now = DateTime.Now;
  464. var timeNextRun = now.Add(TimeSpan.FromSeconds(interval));
  465. var data = new
  466. {
  467. imei,
  468. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  469. ttl = interval,
  470. next_run_time = timeNextRun.ToString("yyyy-MM-dd HH:mm:ss")
  471. };
  472. var result = JsonConvert.SerializeObject(data);
  473. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  474. }
  475. }
  476. public static bool IsNowInTimeRanges()
  477. {
  478. var now = DateTime.Now.TimeOfDay;
  479. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  480. {
  481. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  482. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  483. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  484. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  485. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  486. };
  487. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  488. }
  489. public static bool IsLastUpdateInTimeRanges(DateTime lastUpdate)
  490. {
  491. var now = lastUpdate.TimeOfDay;
  492. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  493. {
  494. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  495. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  496. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  497. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  498. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  499. };
  500. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  501. }
  502. }
  503. }