You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

799 lines
51KB

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