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.

1003 lignes
67KB

  1. using dotnet_etcd;
  2. using Etcdserverpb;
  3. using Google.Protobuf.WellKnownTypes;
  4. using HealthMonitor.Common;
  5. using HealthMonitor.Common.helper;
  6. using HealthMonitor.Core.Common.Extensions;
  7. using HealthMonitor.Core.Pipeline;
  8. using HealthMonitor.Model.Config;
  9. using HealthMonitor.Model.Service;
  10. using HealthMonitor.Model.Service.Mapper;
  11. using HealthMonitor.Service.Biz;
  12. using HealthMonitor.Service.Biz.db;
  13. using HealthMonitor.Service.Cache;
  14. using HealthMonitor.Service.Etcd;
  15. using HealthMonitor.Service.MessageQueue;
  16. using HealthMonitor.Service.Sub;
  17. using Microsoft.AspNetCore.Mvc.RazorPages;
  18. using Microsoft.EntityFrameworkCore.Metadata.Internal;
  19. using Microsoft.Extensions.Options;
  20. using Newtonsoft.Json;
  21. using Newtonsoft.Json.Linq;
  22. using System;
  23. using System.Reflection;
  24. using System.Threading.Channels;
  25. using TDengineDriver;
  26. using TDengineTMQ;
  27. using TelpoDataService.Util.Clients;
  28. using TelpoDataService.Util.Entities.GpsCard;
  29. using TelpoDataService.Util.Entities.GpsLocationHistory;
  30. using TelpoDataService.Util.Models;
  31. using TelpoDataService.Util.QueryObjects;
  32. namespace HealthMonitor.WebApi
  33. {
  34. public class Worker : BackgroundService
  35. {
  36. private readonly ILogger<Worker> _logger;
  37. private readonly IServiceProvider _services;
  38. private readonly TDengineDataSubcribe _tdEngineDataSubcribe;
  39. private readonly PackageProcess _processor;
  40. private readonly TDengineService _serviceTDengine;
  41. private readonly EtcdService _serviceEtcd;
  42. private readonly HttpHelper _httpHelper = default!;
  43. private readonly IotApiService _serviceIotApi;
  44. private readonly BoodPressResolverConfig _configBoodPressResolver;
  45. private readonly BloodPressReferenceValueCacheManager _bpRefValCacheManager;
  46. private readonly PersonCacheManager _personCacheMgr;
  47. private readonly DeviceCacheManager _deviceCacheMgr;
  48. private readonly FetalMovementNormalValueRangeCacheManager _mgrFetalMovementNormalValueRangeCache;
  49. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> _hisFetalHeartApiClient;
  50. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalMovement> _hisFetalMovementApiClient;
  51. private readonly MqProcessLogic _serviceMqProcess;
  52. private CancellationTokenSource _tokenSource = default!;
  53. public Worker(ILogger<Worker> logger, IServiceProvider services, PersonCacheManager personCacheMgr,
  54. BloodPressReferenceValueCacheManager bpRefValCacheManager, IotApiService IotApiService,
  55. IOptions<BoodPressResolverConfig> optionBoodPressResolver, PackageProcess processor,
  56. TDengineDataSubcribe tdEngineDataSubcribe, TDengineService serviceDengine,
  57. GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> hisFetalHeartApiClient,
  58. GpsLocationHistoryAccessorClient<HisGpsFetalMovement> hisFetalMovementApiClient,
  59. FetalMovementNormalValueRangeCacheManager fetalMovementNormalValueRangeCacheMgr, MqProcessLogic serviceMqProcess,
  60. HttpHelper httpHelper, EtcdService serviceEtcd, DeviceCacheManager deviceCacheMgr)
  61. {
  62. _logger = logger;
  63. _tdEngineDataSubcribe = tdEngineDataSubcribe;
  64. _services = services;
  65. _serviceIotApi = IotApiService;
  66. _processor = processor;
  67. _serviceEtcd = serviceEtcd;
  68. _serviceTDengine = serviceDengine;
  69. _httpHelper = httpHelper;
  70. _configBoodPressResolver = optionBoodPressResolver.Value;
  71. _bpRefValCacheManager = bpRefValCacheManager;
  72. _personCacheMgr = personCacheMgr;
  73. _deviceCacheMgr = deviceCacheMgr;
  74. _hisFetalHeartApiClient = hisFetalHeartApiClient;
  75. _hisFetalMovementApiClient = hisFetalMovementApiClient;
  76. _serviceMqProcess = serviceMqProcess;
  77. _mgrFetalMovementNormalValueRangeCache = fetalMovementNormalValueRangeCacheMgr;
  78. }
  79. public override Task StartAsync(CancellationToken cancellationToken)
  80. {
  81. //_logger.LogInformation("------StartAsync");
  82. _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  83. return base.StartAsync(cancellationToken);
  84. }
  85. public override Task StopAsync(CancellationToken cancellationToken)
  86. {
  87. //_logger.LogInformation("------StopAsync");
  88. _tokenSource.Cancel(); //停止工作线程
  89. return base.StopAsync(cancellationToken);
  90. }
  91. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  92. {
  93. var tasks = new[]
  94. {
  95. Task.Run(async () =>
  96. {
  97. _logger.LogInformation("解析器启动");
  98. while (!stoppingToken.IsCancellationRequested)
  99. {
  100. await _processor.ResolveAsync().ConfigureAwait(false);
  101. }
  102. }, stoppingToken),
  103. Task.Run(() =>
  104. {
  105. _logger.LogInformation("TDengine 订阅启动");
  106. while (!stoppingToken.IsCancellationRequested)
  107. {
  108. _tdEngineDataSubcribe.BeginListen(stoppingToken);
  109. }
  110. }, stoppingToken),
  111. Task.Run(() =>
  112. _serviceEtcd.WacthKeysWithPrefixResponseAsync("health_monitor/schedule_push", WatchEvents),
  113. stoppingToken)
  114. };
  115. await Task.WhenAll(tasks);
  116. }
  117. private void WatchEvents(WatchResponse response)
  118. {
  119. response.Events.ToList<Mvccpb.Event>().ForEach(async e =>
  120. {
  121. try
  122. {
  123. switch (e.Type.ToString())
  124. {
  125. case "Put":
  126. // 获取时间点计算TTL
  127. Console.BackgroundColor = ConsoleColor.Blue;
  128. Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  129. Console.BackgroundColor = ConsoleColor.Black;
  130. break;
  131. case "Delete":
  132. // TTL到了重新计算TTL,下发
  133. //Console.BackgroundColor = ConsoleColor.Green;
  134. //Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  135. // var key = $"health_monitor/schedule_push/imei/{bp.Serialno}";
  136. var key = e.Kv.Key.ToStringUtf8();
  137. var imeiDel = key.Split('/')[^1];
  138. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  139. if (string.IsNullOrWhiteSpace(schedule_push))
  140. {
  141. if (key.Contains("pregnancy_heart_rate"))
  142. {
  143. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  144. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  145. if (isFetalHeartEnable)
  146. {
  147. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容
  148. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! + 5;
  149. // 处理孕妇业务,计算一般心率并下发
  150. var commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(imeiDel, highFreqSampleInterval: highFreqSampleInterval);
  151. if (commonPHR == null)
  152. {
  153. // 建模中
  154. var flag = await _serviceIotApi.SetFetalConfig(imeiDel);
  155. _logger.LogInformation($"{imeiDel} 建模建模中");
  156. }
  157. else
  158. {
  159. // 建模完成
  160. var flag = await _serviceIotApi.SetFetalConfig(imeiDel, 1, commonPHR.MaxValue, commonPHR.MinValue);
  161. _logger.LogInformation($"{imeiDel} 建模完成");
  162. // 保存到TDengine数据库
  163. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR);
  164. _logger.LogInformation($"保存TDengine完成");
  165. //
  166. }
  167. }
  168. #region 注册定时下发
  169. var startTime = DateTime.Now;
  170. // 注册下次下推
  171. var endTime = DateTime.Now;
  172. #if DEBUG
  173. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  174. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  175. var interval = 0;
  176. // 获取当前时间
  177. DateTime now = DateTime.Now;
  178. // 计算距离下一个$interval天后的8点的时间间隔
  179. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  180. TimeSpan timeUntilNextRun = nextRunTime - now;
  181. // 如果当前时间已经超过了8点,将等待到明天后的8点
  182. if (timeUntilNextRun < TimeSpan.Zero)
  183. {
  184. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  185. nextRunTime += timeUntilNextRun;
  186. }
  187. //long ttl = timeUntilNextRun.Milliseconds/1000;
  188. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  189. var data = new
  190. {
  191. imei = imeiDel,
  192. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  193. ttl,
  194. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  195. };
  196. var result = JsonConvert.SerializeObject(data);
  197. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  198. #else
  199. // 每$interval天,晚上8点
  200. var interval = 1;
  201. // 获取当前时间
  202. DateTime now = DateTime.Now;
  203. var rand = new Random();
  204. var pushSec = rand.Next(59);
  205. int pushMin = int.TryParse(imeiDel.AsSpan(imeiDel.Length - 1), out pushMin) ? pushMin : 10;
  206. // 计算距离下一个$interval天后的0点的时间间隔
  207. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 6, pushMin, pushSec).AddDays(interval);
  208. TimeSpan timeUntilNextRun = nextRunTime - now;
  209. // 如果当前时间已经超过了8点,将等待到明天后的8点
  210. if (timeUntilNextRun < TimeSpan.Zero)
  211. {
  212. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  213. nextRunTime += timeUntilNextRun;
  214. }
  215. // var ttl = timeUntilNextRun.TotalMilliseconds;
  216. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  217. var data = new
  218. {
  219. imei = imeiDel,
  220. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  221. ttl,
  222. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  223. };
  224. var result = JsonConvert.SerializeObject(data);
  225. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  226. #endif
  227. #endregion
  228. }
  229. // health_monitor/schedule_push/cal_fetal_heart_rate/imei/
  230. else if (key.Contains("health_monitor/schedule_push/cal_fetal_heart_rate/imei/"))
  231. {
  232. /**
  233. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  234. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  235. if (isFetalHeartEnable)
  236. {
  237. // 处理胎心计算业务,计算一般心率获取胎心系数
  238. var commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(imeiDel);
  239. if (commonPHR != null)
  240. {
  241. # region 计算上刻钟的胎心数据
  242. // 告警上限阀值
  243. var upperAlarmThreshold = (int)watchConfig!["upperAlarmThreshold"]!;
  244. // 告警下限阀值
  245. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  246. //var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>();
  247. // 计算胎心=孕妇心率*系数
  248. //var fetalHeartRate = SafeType.SafeInt(lastPhr.PregnancyHeartRate * commonPHR?.StatModeAvgFprCoefficient!);
  249. // 上15分钟的数据
  250. // 获取当前时间
  251. DateTime now = DateTime.Now;
  252. // 计算当前时间到上一刻钟的分钟数
  253. int minutesToSubtract = now.Minute % 15;
  254. // 计算上一刻钟的时间
  255. DateTime previousQuarter = now.AddMinutes(-minutesToSubtract).AddSeconds(-now.Second).AddMilliseconds(-now.Millisecond);
  256. var lastQuarterPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 1);
  257. var filteredPhr = lastQuarterPhr
  258. .Where(i => i.LastUpdate <= previousQuarter && i.LastUpdate >= previousQuarter.AddMinutes(-15))
  259. .ToList();
  260. var lastQuarterPhrValue = filteredPhr.Count == 1
  261. ? filteredPhr.First().PregnancyHeartRate
  262. : filteredPhr.Average(i => i.PregnancyHeartRate);
  263. var fetalHeartRate = SafeType.SafeInt(lastQuarterPhrValue * commonPHR?.StatModeAvgFprCoefficient!);
  264. var sampleTime = DateTimeUtil.ConvertToTimeStamp(DateTime.Now).ToString();
  265. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  266. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  267. {
  268. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  269. PersonId = commonPHR!.PersonId,
  270. Serialno = imeiDel,
  271. HeartRate = fetalHeartRate,
  272. SampleTime = sampleTime,
  273. IsAbnormal = isAbnormal,
  274. StatStartTime = filteredPhr.OrderByDescending(i=>i.LastUpdate).First().LastUpdate,
  275. StatEndTime = filteredPhr.OrderByDescending(i => i.LastUpdate).Last().LastUpdate,
  276. CreateTime = DateTime.Now,
  277. Method = 1,
  278. IsDisplay = 1,
  279. DeviceKey = commonPHR!.DeviceKey
  280. };
  281. // 保存到 数据服务 MySQL 数据库
  282. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  283. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  284. await _serviceIotApi.SetFetalHeartRateConfig(imeiDel, fetalHeartRate, sampleTime, isAbnormal);
  285. #endregion
  286. #region 注册定时计算胎心数据触发器 {interval} 秒后
  287. //await SetIntervalTriggerAsync(key, imeiDel, 60 * 15);
  288. #endregion
  289. }
  290. }
  291. */
  292. }
  293. //health_monitor/schedule_push/cal_fetal_movement/imei/
  294. else if (key.Contains("health_monitor/schedule_push/cal_fetal_movement/imei/"))
  295. {
  296. //// 计算胎动数据
  297. //var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  298. //var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  299. //if (isFetalHeartEnable)
  300. //{
  301. // // 检查胎心建模
  302. // var fchr = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  303. // if (fchr != null)
  304. // {
  305. // // 获取孕妇心率数据接近最近2小时的数据
  306. // var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  307. // var now = DateTime.Now;
  308. // var ago2hrs = now.AddHours(-2);
  309. // var phrRange = phr.Where(i => i.LastUpdate >= ago2hrs)
  310. // .OrderByDescending(i => i.LastUpdate)
  311. // .Select(i => i.LastUpdate)
  312. // .ToList();
  313. // if (phrRange.Count >= 2)
  314. // {
  315. // var duringMins = (phrRange.First() - phrRange.Last()).TotalMinutes;
  316. // //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  317. // bool isInTimeRanges = IsNowInTimeRanges();
  318. // //long.TryParse(watchConfig!["EDOC"]!.ToString(), out long edoc);
  319. // var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  320. // int pregnancyWeeks = (DateTime.Now -edoc.AddDays(-280)).Days / 7;
  321. // if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  322. // {
  323. // var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  324. // var fetalMovementMapValue = isInTimeRanges? fetalMovementMap
  325. // .Where(i =>
  326. // i.PregnancyPeriod![0] <= pregnancyWeeks &&
  327. // i.PregnancyPeriod[1] >= pregnancyWeeks)
  328. // .Select(i=>i.MedianMovement)
  329. // .FirstOrDefault()
  330. // :
  331. // fetalMovementMap
  332. // .Where(i =>
  333. // i.PregnancyPeriod![0] <= pregnancyWeeks &&
  334. // i.PregnancyPeriod[1] >= pregnancyWeeks)
  335. // .Select(i => i.InitialMovement)
  336. // .FirstOrDefault()
  337. // ;
  338. // var fetalMovementValue = fetalMovementMapValue * duringMins * 2 / 120;
  339. // // 四舍五入
  340. // var fetalMovement= (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  341. // var sampleTime = DateTimeUtil.ConvertToTimeStamp(DateTime.Now).ToString();
  342. // // 告警上限阀值
  343. // var upperAlarmThreshold = (int)watchConfig["upperAlarmThreshold"]!;
  344. // // 告警下限阀值
  345. // var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  346. // GeneralParam param = new()
  347. // {
  348. // Filters = new List<QueryFilterCondition>
  349. // {
  350. // new ()
  351. // {
  352. // Key=nameof(HisGpsFetalimeiDel),
  353. // Value=imeiDel,
  354. // ValueType=QueryValueTypeEnum.String,
  355. // Operator=QueryOperatorEnum.Equal
  356. // }
  357. // },
  358. // OrderBys = new List<OrderByCondition>
  359. // {
  360. // new() {
  361. // IsDesc=true,
  362. // Key=nameof(HisGpsFetalHeartRate.CreateTime)
  363. // }
  364. // }
  365. // };
  366. // var frh = await _hisFetalHeartApiClient.GetFirstAsync(param, imeiDel.Substring(imeiDel.Length - 2), null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") }).ConfigureAwait(false);
  367. // if (frh != null)
  368. // {
  369. // var fetalHeartRate = frh.HeartRate;
  370. // var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  371. // // 推送到api/v1/open/OpenIot/SetFetalMovementConfig
  372. // await _serviceIotApi.SetFetalMovementConfig(imeiDel, fetalMovement, sampleTime, isAbnormal);
  373. // // 保存到MySQL数据库
  374. // }
  375. // }
  376. // }
  377. // }
  378. // #region 定时计算胎动数据触发器 2小时后
  379. // await SetIntervalTriggerAsync(key, imeiDel, 60 * 60 * 2);
  380. // #endregion
  381. //}
  382. #region 胎动延时计算
  383. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  384. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  385. if (isFetalHeartEnable)
  386. {
  387. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  388. // 已经建模
  389. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  390. if (commonPHR != null)
  391. {
  392. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  393. _logger.LogInformation($"{imeiDel} 计算胎动数据 ");
  394. var fmNow = DateTime.Now;
  395. // 两小时前
  396. var fmNowSubtract = fmNow.AddMinutes(-fmNow.Minute).AddSeconds(-fmNow.Second).AddMilliseconds(-fmNow.Millisecond);
  397. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(fmNowSubtract).ToString()[..10];
  398. // 统计开始时间
  399. var statStartTime = fmNowSubtract.AddHours(-2);
  400. // 统计结束时间
  401. var statEndTime = fmNowSubtract;
  402. var isFetalMovementExisted = await _deviceCacheMgr.FetalMovementIsExistedAsync(imeiDel, fetalMovementSampleTime);
  403. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 开始");
  404. if (!isFetalMovementExisted)
  405. {
  406. /// 开始计算
  407. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate <= statEndTime)
  408. .OrderByDescending(i => i.LastUpdate)
  409. .Select(i => i.LastUpdate)
  410. .ToList();
  411. // 判断是否有持续佩戴
  412. if (phrRange.Count >= 2)
  413. {
  414. var duringMins = Math.Abs((phrRange.First() - statStartTime).TotalMinutes);
  415. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  416. bool isInTimeRanges = IsLastUpdateInTimeRanges(phrRange.First());
  417. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  418. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  419. {
  420. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  421. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  422. .Where(i =>
  423. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  424. i.PregnancyPeriod[1] >= pregnancyWeeks)
  425. .Select(i => i.MedianMovement)
  426. .FirstOrDefault()
  427. :
  428. fetalMovementMap
  429. .Where(i =>
  430. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  431. i.PregnancyPeriod[1] >= pregnancyWeeks)
  432. .Select(i => i.InitialMovement)
  433. .FirstOrDefault()
  434. ;
  435. var fetalMovementValue = (fetalMovementMapValue * duringMins * 2) / 120;
  436. // 四舍五入
  437. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  438. // _logger.LogInformation($"{imeiDel} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");
  439. _logger.LogInformation($"{imeiDel} 孕周:{pregnancyWeeks},胎动数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 原始胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{statStartTime}-{phrRange.First()}, 胎动计算值:{fetalMovementValue}, 胎动最终值:{fetalMovement} 已完成.");
  440. // 读取胎心数据
  441. GeneralParam param = new()
  442. {
  443. Filters = new List<QueryFilterCondition>
  444. {
  445. new ()
  446. {
  447. Key=nameof(HisGpsFetalHeartRate.Serialno),
  448. Value=imeiDel,
  449. ValueType=QueryValueTypeEnum.String,
  450. Operator=QueryOperatorEnum.Equal
  451. },
  452. //new ()
  453. //{
  454. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  455. // Value=sampleTime,
  456. // ValueType=QueryValueTypeEnum.String,
  457. // Operator=QueryOperatorEnum.GreaterEqual
  458. //},
  459. },
  460. OrderBys=new List<OrderByCondition>
  461. {
  462. new (){
  463. IsDesc=true,
  464. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  465. }
  466. }
  467. };
  468. var fetalHeartRateIsAbnormal = 0;
  469. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  470. // 获取胎心数据状态与胎动数据状态一致
  471. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  472. //var feltalMovementIsAbnormal = 0;
  473. // 推送到api/v1/open/OpenIot/SetFetalMovementConfig
  474. await _serviceIotApi.SetFetalMovementConfig(imeiDel, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  475. // 保存到MySQL数据库
  476. HisGpsFetalMovement fm = new()
  477. {
  478. FetalMovementId = Guid.NewGuid().ToString("D"),
  479. PersonId = commonPHR!.PersonId,
  480. Serialno = imeiDel,
  481. CreateTime = DateTime.Now,
  482. IsAbnormal = feltalMovementIsAbnormal,
  483. FetalMovementValue = fetalMovement,
  484. SampleTime = fetalMovementSampleTime,
  485. Method = 1,
  486. IsDisplay = 1,
  487. DeviceKey = commonPHR!.DeviceKey
  488. };
  489. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  490. // 发送到微信
  491. if (feltalMovementIsAbnormal != 0)
  492. {
  493. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(imeiDel).ConfigureAwait(false);
  494. var fmMsgId = $"{imeiDel}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  495. var topic = "topic.push.wx";
  496. var fmMsg = new
  497. {
  498. messageId = Guid.NewGuid().ToString("D"),
  499. topic = topic,
  500. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
  501. data = new
  502. {
  503. deviceId = device?.DeviceId,
  504. imei = imeiDel,
  505. alarmTypeId = 12,
  506. alarmDeviceName = imeiDel,
  507. alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
  508. address = string.Empty,
  509. deviceKey = device?.DeviceId
  510. }
  511. };
  512. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
  513. }
  514. // 设置入库缓存记录
  515. await _deviceCacheMgr.SetFetalMovementAsync(imeiDel, fetalMovementSampleTime, fm);
  516. }
  517. else
  518. {
  519. _logger.LogWarning($"{imeiDel} 孕周 {pregnancyWeeks},超出胎动计算范围");
  520. }
  521. }
  522. else
  523. {
  524. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 不足两条,不能判断是否持续佩戴");
  525. }
  526. }
  527. else
  528. {
  529. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 已处理");
  530. }
  531. }
  532. }
  533. #endregion
  534. }
  535. else
  536. {
  537. // 处理血压业务
  538. int systolicInc;
  539. int diastolicInc;
  540. int systolicRefValue;
  541. int diastolicRefValue;
  542. decimal systolicAvg;
  543. decimal diastolicAvg;
  544. int systolicMax = 0;
  545. int diastolicMax = 0;
  546. // 统计时间
  547. //DateTime endTime = DateTime.Now; //测试
  548. DateTime statStartTime = DateTime.Now;
  549. // 最小值
  550. int systolicMin = 0;
  551. int diastolicMin = 0;
  552. // 偏移参数
  553. var avgOffset = 0.25M;
  554. var systolicAvgOffset = avgOffset;
  555. var diastolicAvgOffset = avgOffset;
  556. // 最后一次下发值
  557. int lastPushSystolicInc = 0;
  558. int lastPushDiastolicInc = 0;
  559. var startTime = DateTime.Now;
  560. // 下发增量值
  561. #region 统计定时下发增量值
  562. //var last = await _serviceTDengine.GetLastAsync("stb_hm_bloodpress_stats_inc", $"serialno='{imeiDel}' order by last_update desc");
  563. //var ts = last?[0];
  564. // 最后一条血压数据
  565. var condition = $"serialno='{imeiDel}' order by last_update desc";
  566. var field = "last_row(*)";
  567. var lastHmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition, field);
  568. var lastHmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(lastHmBpResponse!);
  569. var lastHmBp = lastHmBpParser?.Select().FirstOrDefault();
  570. //if (lastHmBpParser?.Select()?.ToList().Count < 2)
  571. //{
  572. // _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 血压数据条目不足");
  573. // break;
  574. //}
  575. // 7 天有效数据
  576. if (lastHmBp?.Timestamp.AddDays(7) > DateTime.Now)
  577. {
  578. // 计算增量值
  579. condition = $"serialno='{imeiDel}' order by ts desc";
  580. var lastPushResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bp_push_ref_inc_value", condition, field);
  581. if (lastPushResponse == null)
  582. {
  583. _logger.LogInformation($"{imeiDel}--没有下发记录");
  584. break;
  585. }
  586. var lastPushParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressurePushRefIncModel>>(lastPushResponse);
  587. var lastPush = lastPushParser!.Select().FirstOrDefault();
  588. // 有下推记录
  589. if (lastPush != null)
  590. {
  591. systolicRefValue = lastPush!.SystolicRefValue;
  592. diastolicRefValue = lastPush!.DiastolicRefValue;
  593. lastPushSystolicInc = lastPush!.SystolicIncValue;
  594. lastPushDiastolicInc = lastPush!.DiastolicIncValue;
  595. condition = $"ts between '{lastPush?.Timestamp:yyyy-MM-dd HH:mm:ss.fff}' and '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  596. $"and serialno='{imeiDel}' " +
  597. $"and is_display = true";
  598. // 使用最近一次的下推时间作为统计的开始时间
  599. statStartTime = lastPush!.Timestamp;
  600. }
  601. // 没有下推记录(历史遗留数据),没有初始的测量值产生的平均值(测量值=平均值)
  602. else
  603. {
  604. #region 获取个人信息
  605. var person = await _personCacheMgr.GetDeviceGpsPersonCacheBySerialNoAsync(Guid.NewGuid().ToString(), imeiDel).ConfigureAwait(false);
  606. //验证这个信息是否存在
  607. if (person == null || person?.Person.BornDate == null)
  608. {
  609. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证个人信息,找不到个人信息,跳过此消息");
  610. break;
  611. }
  612. // 验证年龄是否在范围 (2 - 120)
  613. var age = SafeType.SafeInt(DateTime.Today.Year - person?.Person.BornDate!.Value.Year!);
  614. if (age < 2 || age > 120)
  615. {
  616. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证年龄,不在范围 (2 - 120)岁,跳过此消息");
  617. break;
  618. }
  619. var gender = person?.Person.Gender == true ? 1 : 2;
  620. var isHypertension = SafeType.SafeBool(person?.Person.Ishypertension!);
  621. var height = SafeType.SafeDouble(person?.Person.Height!);
  622. var weight = SafeType.SafeDouble(person?.Person.Weight!);
  623. #endregion
  624. #region 初始化常规血压标定值标定值
  625. var bpRef = await _bpRefValCacheManager.GetBloodPressReferenceValueAsync(age, gender, isHypertension);
  626. //systolicRefValue = bpRef!.Systolic;//?
  627. //diastolicRefValue = bpRef!.Diastolic;//?
  628. #endregion
  629. systolicRefValue = bpRef!.Systolic;
  630. diastolicRefValue = bpRef!.Diastolic;
  631. lastPushSystolicInc = 0;
  632. lastPushDiastolicInc = 0;
  633. condition = $"ts <= '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  634. $"and serialno='{imeiDel}' " +
  635. $"and is_display = true";
  636. }
  637. var hmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition);
  638. var hmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(hmBpResponse!);
  639. var hmBp = hmBpParser?.Select();
  640. //if (hmBp?.ToList().Count < 2)
  641. // 1. 判断数据样本数量
  642. if (hmBpParser!.Rows < 5)
  643. {
  644. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 统计定时下发,计算增量值的数据条目不足:{hmBpParser!.Rows} < 5");
  645. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} 没有足够的数据样本,不会定时下发");
  646. break;
  647. }
  648. // 没有下推记录重新计算统计时间
  649. if (lastPush == null)
  650. {
  651. var firstHmBp = hmBpParser?.Select(i => i).OrderBy(i => i.Timestamp).FirstOrDefault();
  652. statStartTime = firstHmBp!.Timestamp;
  653. }
  654. // NewMethod(systolicRefValue, hmBpParser);
  655. // 最大值
  656. //systolicMax = (int)hmBpParser?.Select(i => i.SystolicValue).Max()!;
  657. //diastolicMax = (int)hmBpParser?.Select(i => i.DiastolicValue).Max()!;
  658. //// 最小值
  659. //systolicMin = (int)hmBpParser?.Select(i => i.SystolicValue).Min()!;
  660. //diastolicMin = (int)hmBpParser?.Select(i => i.DiastolicValue).Min()!;
  661. //systolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.SystolicValue, SafeType.SafeInt(systolicRefValue!)))!;
  662. //diastolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.DiastolicValue, SafeType.SafeInt(diastolicRefValue!)))!;
  663. var avgs = _serviceTDengine.AverageAfterRemovingOneMinMaxRef(hmBpParser!);
  664. systolicAvg = avgs[0];
  665. diastolicAvg = avgs[1];
  666. // 2. 判断能否计算增量值
  667. if (systolicAvg.Equals(0))
  668. {
  669. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算平均值" +
  670. $"\n currentSystolicAvg:{systolicAvg} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  671. $"\n currentDiastolicInc:{diastolicAvg} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  672. _logger.LogInformation($"{imeiDel}--{nameof(Worker)} 没有足够的数据样本计算平均值,不会定时下发");
  673. break;
  674. }
  675. // 除最大值和最小值后的平均值与标定值差值少于4后(当天计算出该结果则也不产生增量调整),就不再进行增量值调整了。
  676. if (systolicRefValue - systolicAvg < 4)
  677. {
  678. _logger.LogInformation($"diastolic 舒张压 {imeiDel}除最大值和最小值后的平均值:{diastolicAvg}与标定值:{diastolicRefValue}\n systolic 收缩压 {imeiDel}除最大值和最小值后的平均值:{systolicAvg}与标定值:{systolicRefValue}的差值(标定值-平均值)少于4后,systolic 收缩压 不再进行增量值调整");
  679. break;
  680. }
  681. if (diastolicRefValue - diastolicAvg < 4)
  682. {
  683. _logger.LogInformation($"systolic 收缩压 {imeiDel}除最大值和最小值后的平均值:{systolicAvg}与标定值:{systolicRefValue}\n diastolic 舒张压 {imeiDel}除最大值和最小值后的平均值:{diastolicAvg}与标定值:{diastolicRefValue}的差值(标定值-平均值)少于4后,diastolic 舒张压 不再进行增量值调整");
  684. break;
  685. }
  686. // 增量值=(标定值-平均值)* 0.25
  687. var currentSystolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
  688. var currentDiastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
  689. // 累计增量
  690. systolicInc = currentSystolicInc + lastPushSystolicInc;
  691. diastolicInc = currentDiastolicInc + lastPushDiastolicInc;
  692. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算增量值" +
  693. $"\n {imeiDel} -- systolicAvg:{systolicAvg}-- systolicInc:{systolicInc}-- currentSystolicInc:{currentSystolicInc} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  694. $"\n {imeiDel} -- diastolicAvg:{diastolicAvg}-- diastolicInc:{diastolicInc} --currentDiastolicInc:{currentDiastolicInc} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  695. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}-- 定时校准,发给设备的绝对增量值=(上次绝对增量值+新数据的增量值)");
  696. _logger.LogInformation($"{nameof(Worker)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
  697. if (_configBoodPressResolver.EnableBPRefPush)
  698. // if (false) // 临时关闭
  699. {
  700. BloodPressCalibrationConfigModel bpIncData = new()
  701. {
  702. Imei = imeiDel,
  703. SystolicRefValue = SafeType.SafeInt(((int)systolicRefValue!)), //收缩压标定值,值为0 表示不生效
  704. DiastolicRefValue = SafeType.SafeInt(((int)diastolicRefValue!)), //舒张压标定值,值为0表示不生效
  705. SystolicIncValue = SafeType.SafeInt(((int)systolicInc!)), //收缩压显示增量,值为0 表示不生效
  706. DiastolicIncValue = SafeType.SafeInt(((int)diastolicInc!)) //舒张压显示增量,值为0 表示不生效
  707. };
  708. //var pushedBP = await _serviceIotApi.SetBloodPressCalibrationConfigAsync(bpIncData).ConfigureAwait(false);
  709. var response = await _serviceIotApi.SetBloodPressCalibrationConfig2Async(bpIncData).ConfigureAwait(false);
  710. var pushedBP = response.Flag;
  711. if (pushedBP)
  712. {
  713. #region 保存下推记录 stb_hm_bp_push_ref_inc_value
  714. var sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{imeiDel.Substring(imeiDel.Length - 2)} " +
  715. $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
  716. $"TAGS ('{imeiDel.Substring(imeiDel.Length - 2)}') " +
  717. $"VALUES(" +
  718. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  719. $"'{imeiDel}'," +
  720. $"{bpIncData.SystolicRefValue}," +
  721. $"{bpIncData.DiastolicRefValue}," +
  722. $"{bpIncData.SystolicIncValue}," +
  723. $"{bpIncData.DiastolicIncValue}," +
  724. $"{false}," +
  725. $"{systolicAvg}," +
  726. $"{diastolicAvg}," +
  727. $"{systolicAvgOffset}," +
  728. $"{diastolicAvgOffset}," +
  729. $"'{statStartTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  730. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'" +
  731. $")";
  732. _serviceTDengine.ExecuteInsertSQL(sql);
  733. #endregion
  734. #region 注册定时下发
  735. // 注册下次下推
  736. var endTime = DateTime.Now;
  737. #if DEBUG
  738. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  739. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  740. var interval = 0;
  741. // 获取当前时间
  742. DateTime now = DateTime.Now;
  743. // 计算距离下一个$interval天后的8点的时间间隔
  744. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  745. TimeSpan timeUntilNextRun = nextRunTime - now;
  746. // 如果当前时间已经超过了8点,将等待到明天后的8点
  747. if (timeUntilNextRun < TimeSpan.Zero)
  748. {
  749. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  750. nextRunTime += timeUntilNextRun;
  751. }
  752. // var ttl = timeUntilNextRun.TotalMilliseconds;
  753. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  754. var data = new
  755. {
  756. imei = imeiDel,
  757. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  758. ttl,
  759. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  760. };
  761. var result = JsonConvert.SerializeObject(data);
  762. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  763. #else
  764. // 每$interval天,晚上8点
  765. var interval = 1;
  766. // 获取当前时间
  767. DateTime now = DateTime.Now;
  768. // 计算距离下一个$interval天后的8点的时间间隔
  769. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 20, 0, 0).AddDays(interval);
  770. TimeSpan timeUntilNextRun = nextRunTime - now;
  771. // 如果当前时间已经超过了8点,将等待到明天后的8点
  772. if (timeUntilNextRun < TimeSpan.Zero)
  773. {
  774. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  775. nextRunTime += timeUntilNextRun;
  776. }
  777. // var ttl = timeUntilNextRun.TotalMilliseconds;
  778. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  779. var data = new
  780. {
  781. imei = imeiDel,
  782. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  783. ttl,
  784. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  785. };
  786. var result = JsonConvert.SerializeObject(data);
  787. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  788. #endif
  789. #endregion
  790. }
  791. else
  792. {
  793. _logger.LogInformation($"错误响应,没有下推数据:{response.Message}");
  794. }
  795. }
  796. }
  797. else
  798. {
  799. _logger.LogInformation($"向{imeiDel}统计数据已经失效");
  800. }
  801. #endregion
  802. }
  803. }
  804. break;
  805. }
  806. }
  807. catch (Exception ex)
  808. {
  809. _logger.LogInformation($"{nameof(WatchEvents)},出错: |{ex.Message}|{ex.StackTrace}");
  810. }
  811. });
  812. }
  813. private async Task SetIntervalTriggerAsync(string key, string imei, long interval)
  814. {
  815. // var key = $"health_monitor/schedule_push/{type}/imei/{imei}";
  816. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  817. if (string.IsNullOrWhiteSpace(schedulePush))
  818. {
  819. var now = DateTime.Now;
  820. var timeNextRun = now.Add(TimeSpan.FromSeconds(interval));
  821. var data = new
  822. {
  823. imei,
  824. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  825. ttl = interval,
  826. next_run_time = timeNextRun.ToString("yyyy-MM-dd HH:mm:ss")
  827. };
  828. var result = JsonConvert.SerializeObject(data);
  829. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  830. }
  831. }
  832. public static bool IsNowInTimeRanges()
  833. {
  834. var now = DateTime.Now.TimeOfDay;
  835. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  836. {
  837. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  838. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  839. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  840. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  841. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  842. };
  843. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  844. }
  845. public static bool IsLastUpdateInTimeRanges(DateTime lastUpdate)
  846. {
  847. var now = lastUpdate.TimeOfDay;
  848. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  849. {
  850. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  851. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  852. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  853. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  854. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  855. };
  856. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  857. }
  858. }
  859. }