選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

993 行
66KB

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