Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

895 lines
53KB

  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. public PregnancyHeartRateResolver(ILogger<PregnancyHeartRateResolver> logger,
  41. HttpHelper httpHelper, EtcdService serviceEtcd, DeviceCacheManager deviceCacheMgr,
  42. IotApiService iotApiService, TDengineService serviceDengine, FetalMovementNormalValueRangeCacheManager fetalMovementNormalValueRangeCacheMgr,
  43. GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> hisFetalHeartApiClient,
  44. GpsLocationHistoryAccessorClient<HisGpsFetalMovement> hisFetalMovementApiClient
  45. )
  46. {
  47. _logger = logger;
  48. _httpHelper = httpHelper;
  49. _serviceEtcd = serviceEtcd;
  50. _serviceTDengine = serviceDengine;
  51. _deviceCacheMgr = deviceCacheMgr;
  52. _serviceIotApi = iotApiService;
  53. _hisFetalHeartApiClient = hisFetalHeartApiClient;
  54. _hisFetalMovementApiClient = hisFetalMovementApiClient;
  55. _mgrFetalMovementNormalValueRangeCache = fetalMovementNormalValueRangeCacheMgr;
  56. }
  57. public void SetResolveInfo(PackageMsgModel msg)
  58. {
  59. var topicHmPregnancyHeartRate = JsonConvert.DeserializeObject<TopicHmPregnancyHeartRate>(msg.DetailData.ToString()!);
  60. _messageId.Value = msg.MessageId;
  61. _msgData.Value = new HisGpsHeartRate()
  62. {
  63. HeartRateId = topicHmPregnancyHeartRate!.PregnancyHeartRateId,
  64. MessageId = topicHmPregnancyHeartRate!.MessageId,
  65. Serialno = topicHmPregnancyHeartRate!.Serialno,
  66. HeartRate= topicHmPregnancyHeartRate.PregnancyHeartRate,
  67. LastUpdate = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmPregnancyHeartRate.LastUpdate) / 1000000),
  68. CreateTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmPregnancyHeartRate.CreateTime) / 1000000),
  69. Method = topicHmPregnancyHeartRate!.Method,
  70. IsDisplay = topicHmPregnancyHeartRate!.IsDisplay ? 1 : 0
  71. };
  72. }
  73. public override string ToString()
  74. {
  75. return $"{nameof(PregnancyHeartRateResolver)}[{_messageId.Value}]";
  76. }
  77. public async Task ExecuteMessageAsync()
  78. {
  79. var messageId = _messageId.Value;
  80. var heartRate = _msgData.Value!;
  81. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(heartRate.Serialno, "0067");
  82. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  83. if (isFetalHeartEnable)
  84. {
  85. // 高频心率采样间隔
  86. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]!;
  87. // 触发高频监测的心率上限值
  88. var triggerHighFreqHigh = (int)watchConfig["triggerHighFreqHigh"]!;
  89. // 触发高频监测的心率下限值
  90. var triggerHighFreqLow = (int)watchConfig["triggerHighFreqLow"]!;
  91. //停止高频心率采样心率连续正常次数
  92. var stopHighFreqSampleCount = (int)watchConfig["stopHighFreqSampleCount"]!;
  93. // 高频心率采集时长 0 为持续采集,非零为高频心率的采集时长
  94. var highFreqSampleTimes = (int)watchConfig["stopHighFreqSampleCount"]!;
  95. // 告警上限阀值
  96. var upperAlarmThreshold = (int)watchConfig["upperAlarmThreshold"]!;
  97. // 告警下限阀值
  98. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  99. // EDOC
  100. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  101. // interval (分钟)
  102. var intervalFHR= (int)watchConfig["interval"]!;
  103. var fetalHeartRateIsAbnormal = 0;
  104. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  105. if (phr.Count >= 30)
  106. {
  107. /**
  108. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(heartRate.Serialno);
  109. if (commonPHR != null)
  110. {
  111. var lastUpdateNow = (DateTime)heartRate.LastUpdate!;
  112. var midNight = new DateTime(lastUpdateNow.Year, lastUpdateNow.Month, lastUpdateNow.Day, 0, 0, 0);
  113. #region 计算胎心数据
  114. _logger.LogInformation($"{heartRate.Serialno} 计算胎心数据 ");
  115. var fhrNow = lastUpdateNow;
  116. TimeSpan fhrTS = fhrNow - midNight;
  117. // 当天每隔intervalFHR 分钟的段数,取整数部分
  118. int segmentCountFHR = (int)(fhrTS.TotalMinutes / intervalFHR);
  119. for (int i = 0; i < segmentCountFHR; i++)
  120. {
  121. // 每intervalFHR * i分钟
  122. var fhrSampleTime = DateTimeUtil.ConvertToTimeStamp(midNight.AddMinutes(intervalFHR * i)).ToString()[..10];
  123. // 统计开始时间
  124. var statStartTimeFHR = midNight.AddMinutes(intervalFHR * i);
  125. // 统计结束时间
  126. var statEndTimeFHR = midNight.AddMinutes(intervalFHR * (i + 1));
  127. var isFHRExisted =await _mgrFetalHeartRateCache.FetalHeartRateIsExistedAsync(heartRate.Serialno, fhrSampleTime);
  128. _logger.LogInformation($"{heartRate.Serialno} 胎心数据采样时间:{fhrSampleTime}|{midNight.AddMinutes(intervalFHR * i).ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTimeFHR}-{statEndTimeFHR},isFHRExisted:{isFHRExisted} ");
  129. if (!isFHRExisted)
  130. {
  131. // 开始计算 ,每intervalFHR分钟计算一个
  132. var phrRange = phr.Where(i => i.LastUpdate >= statStartTimeFHR && i.LastUpdate <= statEndTimeFHR)
  133. .OrderByDescending(i => i.LastUpdate)
  134. .ToList();
  135. // 胎心数据每intervalFHR分钟计算1个值,采集的数据多于1个取平均值再*胎心系数。
  136. var phrValue = phrRange.Count == 1
  137. ? phrRange.First().PregnancyHeartRate
  138. : phrRange.Average(i => i.PregnancyHeartRate);
  139. // 当天的系数,没有的就实时计算
  140. var fprCoefficient = 0f;
  141. //if (commonPHR.CreateTime.Year == lastUpdateNow.Year &&
  142. // commonPHR.CreateTime.Month == lastUpdateNow.Month &&
  143. // commonPHR.CreateTime.Day == lastUpdateNow.Day
  144. // )
  145. //{
  146. // fprCoefficient = (float)commonPHR?.StatModeAvgFprCoefficient!;
  147. //}
  148. //else
  149. //{
  150. // //var daysDiff = 7 - (DateTime.Now.Day - lastUpdateNow.Day);
  151. // //var realtimePCHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(heartRate.Serialno, daysDiff);
  152. // //fprCoefficient = realtimePCHR!.StatModeAvgFprCoefficient;
  153. // var pchr = await _serviceTDengine.GetBySerialNoAsync<PregnancyCommonHeartRateModel>(heartRate.Serialno);
  154. // var dayPCHR = pchr.Where(i => i.CreateTime.Year == lastUpdateNow.Year && i.CreateTime.Month == lastUpdateNow.Month && i.CreateTime.Day == i.CreateTime.Day);
  155. // fprCoefficient=dayPCHR.First().StatModeAvgFprCoefficient;
  156. //}
  157. fprCoefficient = (float)commonPHR?.StatModeAvgFprCoefficient!;
  158. var fetalHeartRate = SafeType.SafeInt(phrValue * fprCoefficient);
  159. var fetalHeartRateIsAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  160. fetalHeartRateIsAbnormal = 0;// 不是高频数据,按正常值
  161. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  162. {
  163. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  164. PersonId = commonPHR!.PersonId,
  165. Serialno = heartRate.Serialno,
  166. HeartRate = fetalHeartRate,
  167. SampleTime = fhrSampleTime.Length > 10 ? fhrSampleTime.Substring(0, 10) : fhrSampleTime,
  168. IsAbnormal = fetalHeartRateIsAbnormal,
  169. StatStartTime = phrRange.OrderBy(i => i.LastUpdate).First().LastUpdate,
  170. StatEndTime = phrRange.OrderBy(i => i.LastUpdate).Last().LastUpdate,
  171. CreateTime = DateTime.Now,
  172. Method = 1,
  173. IsDisplay = 1,
  174. DeviceKey = commonPHR!.DeviceKey
  175. };
  176. // 保存到 数据服务 MySQL 数据库
  177. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  178. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  179. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, fhrSampleTime, fetalHeartRateIsAbnormal);
  180. // 推送到微信
  181. // 设置入库缓存记录
  182. await _mgrFetalHeartRateCache.SetFetalHeartRateAsync(heartRate.Serialno, fhrSampleTime);
  183. }
  184. }
  185. #endregion
  186. #region 计算胎动数据
  187. _logger.LogInformation($"{heartRate.Serialno} 计算胎动数据 ");
  188. var fmNow = lastUpdateNow;
  189. TimeSpan fmTS = fmNow - midNight;
  190. // 当天每隔2小时的段数,取整数部分
  191. int segmentCountFM = (int)(fmTS.TotalHours / 2);
  192. for (int i = 0; i < segmentCountFM; i++)
  193. {
  194. // 每两小时
  195. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(midNight.AddHours(2 * i)).ToString()[..10];
  196. // 统计开始时间
  197. var statStartTime = midNight.AddHours(2 * i);
  198. // 统计结束时间
  199. var statEndTime = midNight.AddHours(2 * (i + 1));
  200. //var isFetalMovementExist = await _hisFetalMovementApiClient.GetFirstAsync(param, heartRate.Serialno[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  201. var isFetalMovementExisted = await _mgrFetalMovement.FetalMovementIsExistedAsync(heartRate.Serialno, fetalMovementSampleTime);
  202. if (!isFetalMovementExisted)
  203. {
  204. /// 开始计算
  205. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate <= statEndTime)
  206. .OrderByDescending(i => i.LastUpdate)
  207. .Select(i => i.LastUpdate)
  208. .ToList();
  209. if (phrRange.Count >= 2)
  210. {
  211. var duringMins = Math.Abs((phrRange.First() - statStartTime).TotalMinutes);
  212. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  213. bool isInTimeRanges = IsLastUpdateInTimeRanges(fmNow);
  214. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  215. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  216. {
  217. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  218. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  219. .Where(i =>
  220. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  221. i.PregnancyPeriod[1] >= pregnancyWeeks)
  222. .Select(i => i.MedianMovement)
  223. .FirstOrDefault()
  224. :
  225. fetalMovementMap
  226. .Where(i =>
  227. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  228. i.PregnancyPeriod[1] >= pregnancyWeeks)
  229. .Select(i => i.InitialMovement)
  230. .FirstOrDefault()
  231. ;
  232. var fetalMovementValue = (fetalMovementMapValue * duringMins * 2) / 120;
  233. // 四舍五入
  234. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  235. // _logger.LogInformation($"{heartRate.Serialno} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");
  236. _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}");
  237. // 获取胎心数据状态与胎动数据状态一致
  238. //var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  239. var feltalMovementIsAbnormal = 0;
  240. // 推送到api/v1/open/OpenIot/SetFetalMovementConfig
  241. await _serviceIotApi.SetFetalMovementConfig(heartRate.Serialno, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  242. // 保存到MySQL数据库
  243. HisGpsFetalMovement fm = new()
  244. {
  245. FetalMovementId = Guid.NewGuid().ToString("D"),
  246. PersonId = commonPHR!.PersonId,
  247. Serialno = heartRate.Serialno,
  248. CreateTime = DateTime.Now,
  249. IsAbnormal = feltalMovementIsAbnormal,
  250. FetalMovementValue = fetalMovement,
  251. SampleTime = fetalMovementSampleTime,
  252. Method = 1,
  253. IsDisplay = 1,
  254. DeviceKey = commonPHR!.DeviceKey
  255. };
  256. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  257. // 设置入库缓存记录
  258. await _mgrFetalMovement.SetFetalMovementAsync(heartRate.Serialno, fetalMovementSampleTime);
  259. }
  260. }
  261. }
  262. }
  263. #endregion
  264. }
  265. */
  266. #region 高频心率计算
  267. //// 获取最近的两个记录,并计算它们的 LastUpdate 时间差
  268. //var firstTwoPhr = phr.OrderByDescending(i => i.LastUpdate).Take(2).Select(i => i.LastUpdate).ToList();
  269. //var timeDiff = firstTwoPhr[0] - firstTwoPhr[1];
  270. //// 如果需要,将时间差转换为秒
  271. //var timeDiffInSeconds = timeDiff.TotalSeconds;
  272. //// 高频心率启动
  273. //if (timeDiffInSeconds<=highFreqSampleInterval)
  274. //{
  275. // var phrFreqstatus =await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  276. // if (phrFreqstatus == null)
  277. // {
  278. // /// 设置高频状态
  279. // _logger.LogInformation($"进入高频心率启动状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval}");
  280. // // 设置高频状态
  281. // var freqFirstPhr= phr.OrderByDescending(i => i.Timestamp).First();
  282. // await _deviceCacheMgr.SetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno, freqFirstPhr);
  283. // phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  284. // }
  285. // /// phr PregnancyHeartRate 连续连续正常次数个值都是正常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  286. // /// 取连续正常次数正常值的平均值,推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  287. // #region 检查是否连续12个值都是正常的
  288. // // 获取最近连续正常次数个心率记录
  289. // var lastPhr = phr.OrderByDescending(i => i.Timestamp).Take(stopHighFreqSampleCount).ToList();
  290. // // 检查是否连续12个值都是正常的
  291. // if (lastPhr.All(i => i.PregnancyHeartRate >= triggerHighFreqLow && i.PregnancyHeartRate <= triggerHighFreqHigh))
  292. // {
  293. // var avgPhr = lastPhr.Select(i => i.PregnancyHeartRate).Average();
  294. // // 计算一般心率得到胎心系数
  295. // await SaveAndPushFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr);
  296. // }
  297. // #endregion
  298. //}
  299. //// 高频心率结束
  300. //else
  301. //{
  302. // var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  303. // if (phrFreqstatus != null)
  304. // {
  305. // /// 在highFreqSampleTimes=0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  306. // /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  307. // if (highFreqSampleTimes==0)
  308. // {
  309. // // if (phr.OrderByDescending(i => i.Timestamp)
  310. // //.Where(i => i.Timestamp >= phrFreqstatus?.Timestamp)
  311. // //.Skip(1) // 去除首条
  312. // //.All(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHig))
  313. // // {
  314. // // var avgPhr = phr.Select(i => i.PregnancyHeartRate).Average();
  315. // // // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  316. // // // 计算一般心率得到胎心系数
  317. // // }
  318. // var avgPhr = phr.OrderByDescending(i => i.Timestamp)
  319. // .Where(i => i.Timestamp >= phrFreqstatus?.Timestamp)
  320. // .Skip(1) // 去除首条
  321. // .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh)
  322. // .Select(i => i.PregnancyHeartRate).Average();
  323. // // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  324. // // 计算一般心率得到胎心系数
  325. // await SaveAndPushFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr);
  326. // }
  327. // /// 在highFreqSampleTimes>0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  328. // /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  329. // if (highFreqSampleTimes > 0 && heartRate.LastUpdate >= (phrFreqstatus?.LastUpdate + TimeSpan.FromSeconds(highFreqSampleTimes)))
  330. // {
  331. // var avgPhr = phr
  332. // .Where(i => i.Timestamp >= phrFreqstatus?.Timestamp)
  333. // .Skip(1) // 去除首条
  334. // .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh)
  335. // .Select(i => i.PregnancyHeartRate).Average();
  336. // // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  337. // // 计算一般心率得到胎心系数
  338. // await SaveAndPushFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr);
  339. // }
  340. // // 删除高频状态的首条记录
  341. // await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  342. // /// 设置高频状态
  343. // _logger.LogInformation($"结束高频心率状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval}");
  344. // }
  345. //}
  346. #endregion
  347. #region 计算胎心和胎动数据
  348. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(heartRate.Serialno);
  349. if (commonPHR != null)
  350. {
  351. #region 计算胎心数据
  352. // 获取最近的两个记录,并计算它们的 LastUpdate 时间差
  353. var firstTwoPhr = phr.OrderByDescending(i => i.LastUpdate).Take(2).Select(i => i.LastUpdate).ToList();
  354. var timeDiff = firstTwoPhr[0] - firstTwoPhr[1];
  355. // 如果需要,将时间差转换为秒
  356. var timeDiffInSeconds = timeDiff.TotalSeconds;
  357. // 高频心率启动
  358. if (timeDiffInSeconds <= highFreqSampleInterval)
  359. {
  360. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  361. if (phrFreqstatus == null)
  362. {
  363. /// 设置高频状态
  364. _logger.LogInformation($"进入高频心率启动状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval}");
  365. // 设置高频状态
  366. var freqFirstPhr = phr.OrderByDescending(i => i.Timestamp).First();
  367. await _deviceCacheMgr.SetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno, freqFirstPhr);
  368. //phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  369. }
  370. /// phr PregnancyHeartRate 连续连续正常次数个值都是正常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  371. /// 取连续正常次数正常值的平均值,推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  372. #region 检查是否连续12个值都是正常的
  373. // 获取最近连续正常次数个心率记录
  374. var lastPhr = phr.OrderByDescending(i => i.Timestamp).Take(stopHighFreqSampleCount).ToList();
  375. // 检查是否连续12个值都是正常的
  376. if (lastPhr.All(i => i.PregnancyHeartRate >= triggerHighFreqLow && i.PregnancyHeartRate <= triggerHighFreqHigh))
  377. {
  378. var avgPhr = lastPhr.Select(i => i.PregnancyHeartRate).Average();
  379. // 计算一般心率得到胎心系数
  380. await SaveAndPushFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr);
  381. }
  382. #endregion
  383. }
  384. // 高频心率结束或正常心率
  385. else
  386. {
  387. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  388. if (phrFreqstatus != null)
  389. {
  390. /// 在highFreqSampleTimes=0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  391. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  392. if (highFreqSampleTimes == 0)
  393. {
  394. var avgPhr = phr.OrderByDescending(i => i.Timestamp)
  395. .Where(i => i.Timestamp >= phrFreqstatus?.Timestamp)
  396. .Skip(1) // 去除首条
  397. .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh)
  398. .Select(i => i.PregnancyHeartRate).Average();
  399. // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  400. // 计算一般心率得到胎心系数
  401. await SaveAndPushFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr);
  402. }
  403. /// 在highFreqSampleTimes>0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  404. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  405. if (highFreqSampleTimes > 0 && heartRate.LastUpdate >= (phrFreqstatus?.LastUpdate + TimeSpan.FromSeconds(highFreqSampleTimes)))
  406. {
  407. var avgPhr = phr
  408. .Where(i => i.Timestamp >= phrFreqstatus?.Timestamp)
  409. .Skip(1) // 去除首条
  410. .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh)
  411. .Select(i => i.PregnancyHeartRate).Average();
  412. // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  413. // 计算一般心率得到胎心系数
  414. await SaveAndPushFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr);
  415. }
  416. // 删除高频状态的首条记录
  417. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  418. /// 设置高频状态
  419. _logger.LogInformation($"结束高频心率状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval}");
  420. }
  421. // 正常心率
  422. else
  423. {
  424. _logger.LogInformation($"{heartRate.Serialno} 计算胎心数据");
  425. // 上15分钟的数据
  426. // 获取当前时间
  427. DateTime nowInterval = (DateTime)heartRate.LastUpdate!;
  428. // 计算last_update到上一刻钟的分钟数
  429. int minutesToSubtract = nowInterval.Minute % intervalFHR;
  430. // 计算上一刻钟的时间
  431. DateTime previousInterval = nowInterval.AddMinutes(-minutesToSubtract).AddSeconds(-nowInterval.Second).AddMilliseconds(-nowInterval.Millisecond);
  432. // 使用 last_update 上一刻
  433. var sampleTimeFHR = DateTimeUtil.ConvertToTimeStamp(previousInterval).ToString();
  434. // 计算last_update到下一刻钟的分钟数
  435. int minutesToAdd = intervalFHR - (nowInterval.Minute % intervalFHR);
  436. if (minutesToAdd == intervalFHR)
  437. {
  438. minutesToAdd = 0; // 如果已经是刻钟,则不需要增加分钟
  439. }
  440. // 计算下一刻钟的时间
  441. DateTime nextInterval = nowInterval.AddMinutes(minutesToAdd)
  442. .AddSeconds(-nowInterval.Second)
  443. .AddMilliseconds(-nowInterval.Millisecond);
  444. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  445. var filteredPhr = daysPhr
  446. // 使用 last_update 下一刻
  447. .Where(i => i.LastUpdate <= nextInterval && i.LastUpdate >= nextInterval.AddMinutes(-intervalFHR))
  448. .ToList();
  449. var phrValue = filteredPhr.Count == 1
  450. ? filteredPhr.First().PregnancyHeartRate
  451. : filteredPhr.Average(i => i.PregnancyHeartRate);
  452. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  453. fetalHeartRateIsAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  454. fetalHeartRateIsAbnormal = 0;// 不是高频数据,按正常值
  455. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  456. {
  457. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  458. PersonId = commonPHR!.PersonId,
  459. Serialno = heartRate.Serialno,
  460. HeartRate = fetalHeartRate,
  461. SampleTime = sampleTimeFHR.Length > 10 ? sampleTimeFHR.Substring(0, 10) : sampleTimeFHR,
  462. IsAbnormal = fetalHeartRateIsAbnormal,
  463. StatStartTime = filteredPhr.OrderBy(i => i.LastUpdate).First().LastUpdate,
  464. StatEndTime = filteredPhr.OrderBy(i => i.LastUpdate).Last().LastUpdate,
  465. CreateTime = DateTime.Now,
  466. Method = 1,
  467. IsDisplay = 1,
  468. DeviceKey = commonPHR!.DeviceKey
  469. };
  470. // 保存到 数据服务 MySQL 数据库
  471. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  472. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  473. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTimeFHR, fetalHeartRateIsAbnormal);
  474. }
  475. }
  476. #endregion
  477. #region 计算胎动数据
  478. _logger.LogInformation($"{heartRate.Serialno} 计算胎动数据 ");
  479. var fetalMovementNow = (DateTime)heartRate.LastUpdate!;
  480. var midNight = new DateTime(fetalMovementNow.Year, fetalMovementNow.Month, fetalMovementNow.Day, 0, 0, 0);
  481. TimeSpan fetalMovementTS = fetalMovementNow - midNight;
  482. // 当天每隔2小时的段数,取整数部分
  483. int segmentCountFM = (int)(fetalMovementTS.TotalHours / 2);
  484. for (int i = 0; i < segmentCountFM; i++)
  485. {
  486. // 每两小时
  487. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(midNight.AddHours(2 * i)).ToString()[..10];
  488. // 统计开始时间
  489. var statStartTime = midNight.AddHours(2 * i);
  490. // 统计结束时间
  491. var statEndTime = midNight.AddHours(2 * (i+1));
  492. var isFetalMovementExisted = await _deviceCacheMgr.FetalMovementIsExistedAsync(heartRate.Serialno, fetalMovementSampleTime);
  493. _logger.LogInformation($"{heartRate.Serialno} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 开始");
  494. if (!isFetalMovementExisted)
  495. {
  496. /// 开始计算
  497. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate<= statEndTime)
  498. .OrderByDescending(i => i.LastUpdate)
  499. .Select(i => i.LastUpdate)
  500. .ToList();
  501. // 判断是否有持续佩戴
  502. if (phrRange.Count >= 2)
  503. {
  504. var duringMins = Math.Abs((phrRange.First()- statStartTime).TotalMinutes);
  505. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  506. bool isInTimeRanges = IsLastUpdateInTimeRanges(fetalMovementNow);
  507. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  508. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  509. {
  510. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  511. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  512. .Where(i =>
  513. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  514. i.PregnancyPeriod[1] >= pregnancyWeeks)
  515. .Select(i => i.MedianMovement)
  516. .FirstOrDefault()
  517. :
  518. fetalMovementMap
  519. .Where(i =>
  520. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  521. i.PregnancyPeriod[1] >= pregnancyWeeks)
  522. .Select(i => i.InitialMovement)
  523. .FirstOrDefault()
  524. ;
  525. var fetalMovementValue = (fetalMovementMapValue * duringMins * 2) / 120;
  526. // 四舍五入
  527. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  528. // _logger.LogInformation($"{heartRate.Serialno} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");
  529. _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} 已完成.");
  530. // 获取胎心数据状态与胎动数据状态一致
  531. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  532. //var feltalMovementIsAbnormal = 0;
  533. // 推送到api/v1/open/OpenIot/SetFetalMovementConfig
  534. await _serviceIotApi.SetFetalMovementConfig(heartRate.Serialno, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  535. // 保存到MySQL数据库
  536. HisGpsFetalMovement fm = new()
  537. {
  538. FetalMovementId = Guid.NewGuid().ToString("D"),
  539. PersonId = commonPHR!.PersonId,
  540. Serialno = heartRate.Serialno,
  541. CreateTime = DateTime.Now,
  542. IsAbnormal = feltalMovementIsAbnormal,
  543. FetalMovementValue = fetalMovement,
  544. SampleTime = fetalMovementSampleTime,
  545. Method = 1,
  546. IsDisplay = 1,
  547. DeviceKey = commonPHR!.DeviceKey
  548. };
  549. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  550. // 设置入库缓存记录
  551. await _deviceCacheMgr.SetFetalMovementAsync(heartRate.Serialno, fetalMovementSampleTime,fm);
  552. }
  553. else
  554. {
  555. _logger.LogWarning($"{heartRate.Serialno} 孕周 {pregnancyWeeks},超出胎动计算范围");
  556. }
  557. }
  558. else
  559. {
  560. _logger.LogInformation($"{heartRate.Serialno} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 不足两条,不能判断是否持续佩戴");
  561. }
  562. }
  563. else
  564. {
  565. _logger.LogInformation($"{heartRate.Serialno} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 已处理");
  566. }
  567. }
  568. #endregion
  569. }
  570. #endregion
  571. #region 定时计算胎心数据触发器 {interval} 秒后
  572. //var fetalKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  573. //await SetIntervalTriggerAsync(fetalKey, heartRate.Serialno, 60 * 15);
  574. #endregion
  575. #region 定时计算胎心数据触发器下一刻钟后
  576. //// 获取当前时间
  577. //DateTime nowInterval = DateTime.Now;
  578. //// 计算下一个15分钟的刻钟
  579. //int minutesToAdd = 15 - (nowInterval.Minute % 15);
  580. //if (minutesToAdd == 15)
  581. //{
  582. // minutesToAdd = 0; // 如果已经是刻钟,则不需要增加分钟
  583. //}
  584. //// 计算下一刻钟的时间
  585. //DateTime nextInterval = nowInterval.AddMinutes(minutesToAdd)
  586. // .AddSeconds(-nowInterval.Second)
  587. // .AddMilliseconds(-nowInterval.Millisecond);
  588. //// 计算时间差
  589. //TimeSpan timeDifference = nextInterval - nowInterval;
  590. //var fetalKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  591. //await SetIntervalTriggerAsync(fetalKey, heartRate.Serialno, (long)timeDifference.TotalSeconds);
  592. #endregion
  593. #region 定时计算胎动数据触发器 0 点开始
  594. //var fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}";
  595. ///// 计算 0 点秒数
  596. //DateTime now = DateTime.Now;
  597. //var rand = new Random();
  598. //var pushSec = rand.Next(59);
  599. //int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  600. //DateTime nextRunTime = new (now.Year, now.Month, now.Day, 0, pushMin, pushSec);
  601. //TimeSpan timeUntilNextRun = nextRunTime - now;
  602. //if (timeUntilNextRun < TimeSpan.Zero)
  603. //{
  604. // timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  605. // nextRunTime += timeUntilNextRun;
  606. //}
  607. //var ttl = (long)timeUntilNextRun.TotalSeconds;
  608. //await SetIntervalTriggerAsync(fetalMovementKey, heartRate.Serialno, ttl);
  609. #endregion
  610. }
  611. #region 定时下发触发器(定时建模)
  612. var key = $"health_monitor/schedule_push/pregnancy_heart_rate/imei/{heartRate.Serialno}";
  613. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  614. if (string.IsNullOrWhiteSpace(schedule_push))
  615. {
  616. // 注册首次下推
  617. #if DEBUG
  618. // await _serviceEtcd.PutValAsync(key, result, 60*1, false).ConfigureAwait(false);
  619. var interval = 0;
  620. // 获取当前时间
  621. DateTime now = DateTime.Now;
  622. // 计算距离下一个$interval天后的8点的时间间隔
  623. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 1, 58).AddDays(interval);
  624. TimeSpan timeUntilNextRun = nextRunTime - now;
  625. // 如果当前时间已经超过了8点,将等待到明天后的8点
  626. if (timeUntilNextRun < TimeSpan.Zero)
  627. {
  628. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  629. nextRunTime += timeUntilNextRun;
  630. }
  631. var ttl = (long)timeUntilNextRun.TotalSeconds;
  632. var data = new
  633. {
  634. imei = heartRate.Serialno,
  635. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  636. ttl,
  637. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  638. };
  639. var result = JsonConvert.SerializeObject(data);
  640. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  641. #else
  642. var interval = 0;
  643. // 获取当前时间
  644. DateTime now = DateTime.Now;
  645. var rand=new Random();
  646. var pushSec = rand.Next(59);
  647. int pushMin= int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  648. // 计算距离下一个$interval天后的8点的时间间隔
  649. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 0, pushMin, pushSec).AddDays(interval);
  650. TimeSpan timeUntilNextRun = nextRunTime - now;
  651. if (timeUntilNextRun < TimeSpan.Zero)
  652. {
  653. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  654. nextRunTime += TimeSpan.FromDays(1);
  655. }
  656. var ttl =(long)timeUntilNextRun.TotalSeconds;
  657. var data = new
  658. {
  659. imei = heartRate.Serialno,
  660. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  661. ttl,
  662. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  663. };
  664. var result = JsonConvert.SerializeObject(data);
  665. await _serviceEtcd.PutValAsync(key, result,ttl, false).ConfigureAwait(false);
  666. #endif
  667. }
  668. #endregion
  669. }
  670. }
  671. private async Task SaveAndPushFetalHeartRateAsync(HisGpsHeartRate heartRate, int upperAlarmThreshold, int lowerAlarmThreshold, double avgPhr)
  672. {
  673. var commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(heartRate.Serialno);
  674. if (commonPHR != null)
  675. {
  676. // 保存到TDengine数据库
  677. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR);
  678. // 计算胎心=孕妇心率*系数
  679. var fetalHeartRate = SafeType.SafeInt(avgPhr * commonPHR?.StatModeAvgFprCoefficient!);
  680. var sampleTime = DateTimeUtil.ConvertToTimeStamp(DateTime.Now).ToString();
  681. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  682. // 保存到 数据服务 MySQL 数据库
  683. HisGpsFetalHeartRate gpsFetalHeartRate = new ()
  684. {
  685. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  686. PersonId = commonPHR!.PersonId,
  687. Serialno = heartRate.Serialno,
  688. HeartRate = fetalHeartRate,
  689. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  690. IsAbnormal = isAbnormal,
  691. StatStartTime = commonPHR.StatStartTime,
  692. StatEndTime = commonPHR.StatEndTime,
  693. CreateTime = DateTime.Now,
  694. Method = 1,
  695. IsDisplay = 1,
  696. DeviceKey = commonPHR!.DeviceKey
  697. };
  698. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  699. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  700. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  701. // 推送到微信
  702. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  703. var deviceId = device?.DeviceId;
  704. var msg = new
  705. {
  706. messageId = "",
  707. topic = "topic.push.wx",
  708. time=""
  709. };
  710. }
  711. }
  712. private async Task SetIntervalTriggerAsync(string key,string imei, long interval)
  713. {
  714. // var key = $"health_monitor/schedule_push/{type}/imei/{imei}";
  715. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  716. if (string.IsNullOrWhiteSpace(schedulePush))
  717. {
  718. var now = DateTime.Now;
  719. var timeNextRun = now.Add(TimeSpan.FromSeconds(interval));
  720. var data = new
  721. {
  722. imei,
  723. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  724. ttl = interval,
  725. next_run_time = timeNextRun.ToString("yyyy-MM-dd HH:mm:ss")
  726. };
  727. var result = JsonConvert.SerializeObject(data);
  728. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  729. }
  730. }
  731. public static bool IsLastUpdateInTimeRanges(DateTime lastUpdate)
  732. {
  733. var now = lastUpdate.TimeOfDay;
  734. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  735. {
  736. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  737. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  738. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  739. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  740. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  741. };
  742. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  743. }
  744. }
  745. }