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.

1297 lignes
88KB

  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;
  19. using Microsoft.EntityFrameworkCore.Metadata.Internal;
  20. using Microsoft.Extensions.Options;
  21. using NetTaste;
  22. using Newtonsoft.Json;
  23. using Newtonsoft.Json.Linq;
  24. using System;
  25. using System.Reflection;
  26. using System.Threading.Channels;
  27. using TDengineDriver;
  28. using TDengineTMQ;
  29. using TelpoDataService.Util.Clients;
  30. using TelpoDataService.Util.Entities.GpsCard;
  31. using TelpoDataService.Util.Entities.GpsLocationHistory;
  32. using TelpoDataService.Util.Models;
  33. using TelpoDataService.Util.QueryObjects;
  34. namespace HealthMonitor.WebApi
  35. {
  36. public class Worker : BackgroundService
  37. {
  38. private readonly ILogger<Worker> _logger;
  39. private readonly IServiceProvider _services;
  40. private readonly TDengineDataSubcribe _tdEngineDataSubcribe;
  41. private readonly PackageProcess _processor;
  42. private readonly TDengineService _serviceTDengine;
  43. private readonly EtcdService _serviceEtcd;
  44. private readonly HttpHelper _httpHelper = default!;
  45. private readonly IotApiService _serviceIotApi;
  46. private readonly BoodPressResolverConfig _configBoodPressResolver;
  47. private readonly BloodPressReferenceValueCacheManager _bpRefValCacheManager;
  48. private readonly PersonCacheManager _personCacheMgr;
  49. private readonly DeviceCacheManager _deviceCacheMgr;
  50. private readonly FetalMovementNormalValueRangeCacheManager _mgrFetalMovementNormalValueRangeCache;
  51. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> _hisFetalHeartApiClient;
  52. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalMovement> _hisFetalMovementApiClient;
  53. private readonly GpsLocationHistoryAccessorClient<HisGpsPsychResult> _hisPsychResultApiClient;
  54. private readonly MqProcessLogic _serviceMqProcess;
  55. private CancellationTokenSource _tokenSource = default!;
  56. public Worker(ILogger<Worker> logger, IServiceProvider services, PersonCacheManager personCacheMgr,
  57. BloodPressReferenceValueCacheManager bpRefValCacheManager, IotApiService IotApiService,
  58. IOptions<BoodPressResolverConfig> optionBoodPressResolver, PackageProcess processor,
  59. TDengineDataSubcribe tdEngineDataSubcribe, TDengineService serviceDengine,
  60. GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> hisFetalHeartApiClient,
  61. GpsLocationHistoryAccessorClient<HisGpsFetalMovement> hisFetalMovementApiClient,
  62. GpsLocationHistoryAccessorClient<HisGpsPsychResult> hisGpsPsychResultApiClient,
  63. FetalMovementNormalValueRangeCacheManager fetalMovementNormalValueRangeCacheMgr, MqProcessLogic serviceMqProcess,
  64. HttpHelper httpHelper, EtcdService serviceEtcd, DeviceCacheManager deviceCacheMgr)
  65. {
  66. _logger = logger;
  67. _tdEngineDataSubcribe = tdEngineDataSubcribe;
  68. _services = services;
  69. _serviceIotApi = IotApiService;
  70. _processor = processor;
  71. _serviceEtcd = serviceEtcd;
  72. _serviceTDengine = serviceDengine;
  73. _httpHelper = httpHelper;
  74. _configBoodPressResolver = optionBoodPressResolver.Value;
  75. _bpRefValCacheManager = bpRefValCacheManager;
  76. _personCacheMgr = personCacheMgr;
  77. _deviceCacheMgr = deviceCacheMgr;
  78. _hisFetalHeartApiClient = hisFetalHeartApiClient;
  79. _hisFetalMovementApiClient = hisFetalMovementApiClient;
  80. _hisPsychResultApiClient = hisGpsPsychResultApiClient;
  81. _serviceMqProcess = serviceMqProcess;
  82. _mgrFetalMovementNormalValueRangeCache = fetalMovementNormalValueRangeCacheMgr;
  83. }
  84. public override Task StartAsync(CancellationToken cancellationToken)
  85. {
  86. //_logger.LogInformation("------StartAsync");
  87. _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  88. return base.StartAsync(cancellationToken);
  89. }
  90. public override Task StopAsync(CancellationToken cancellationToken)
  91. {
  92. //_logger.LogInformation("------StopAsync");
  93. _tokenSource.Cancel(); //停止工作线程
  94. return base.StopAsync(cancellationToken);
  95. }
  96. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  97. {
  98. var tasks = new[]
  99. {
  100. Task.Run(async () =>
  101. {
  102. _logger.LogInformation("解析器启动");
  103. while (!stoppingToken.IsCancellationRequested)
  104. {
  105. await _processor.ResolveAsync().ConfigureAwait(false);
  106. }
  107. }, stoppingToken),
  108. Task.Run(() =>
  109. {
  110. _logger.LogInformation("TDengine 订阅启动");
  111. while (!stoppingToken.IsCancellationRequested)
  112. {
  113. _tdEngineDataSubcribe.BeginListen(stoppingToken);
  114. }
  115. }, stoppingToken),
  116. Task.Run(() =>
  117. _serviceEtcd.WacthKeysWithPrefixResponseAsync("health_monitor/schedule_push", WatchEvents),
  118. stoppingToken)
  119. };
  120. await Task.WhenAll(tasks);
  121. }
  122. private void WatchEvents(WatchResponse response)
  123. {
  124. response.Events.ToList<Mvccpb.Event>().ForEach(async e =>
  125. {
  126. try
  127. {
  128. switch (e.Type.ToString())
  129. {
  130. case "Put":
  131. // 获取时间点计算TTL
  132. Console.BackgroundColor = ConsoleColor.Blue;
  133. Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  134. Console.BackgroundColor = ConsoleColor.Black;
  135. break;
  136. case "Delete":
  137. // TTL到了重新计算TTL,下发
  138. //Console.BackgroundColor = ConsoleColor.Green;
  139. //Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  140. // var key = $"health_monitor/schedule_push/imei/{bp.Serialno}";
  141. var key = e.Kv.Key.ToStringUtf8();
  142. var imeiDel = key.Split('/')[^1];
  143. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  144. if (string.IsNullOrWhiteSpace(schedule_push))
  145. {
  146. if (key.Contains("pregnancy_heart_rate"))
  147. {
  148. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  149. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  150. if (isFetalHeartEnable)
  151. {
  152. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容
  153. //var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! + 5;
  154. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容(最小highFreqSampleInterval=60)
  155. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! + 5 : 60;
  156. // 处理孕妇业务,计算一般心率并下发
  157. var commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(imeiDel, highFreqSampleInterval: highFreqSampleInterval);
  158. if (commonPHR == null)
  159. {
  160. // 建模中
  161. var flag = await _serviceIotApi.SetFetalConfig(imeiDel);
  162. _logger.LogInformation($"{imeiDel} 建模建模中");
  163. }
  164. else
  165. {
  166. // 建模完成
  167. var flag = await _serviceIotApi.SetFetalConfig(imeiDel, 1, commonPHR.MaxValue, commonPHR.MinValue);
  168. _logger.LogInformation($"{imeiDel} 建模完成");
  169. // 保存到TDengine数据库
  170. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR);
  171. _logger.LogInformation($"保存TDengine完成");
  172. //
  173. }
  174. }
  175. #region 注册定时下发
  176. var startTime = DateTime.Now;
  177. // 注册下次下推
  178. var endTime = DateTime.Now;
  179. #if DEBUG
  180. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  181. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  182. var interval = 0;
  183. // 获取当前时间
  184. DateTime now = DateTime.Now;
  185. // 计算距离下一个$interval天后的8点的时间间隔
  186. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  187. TimeSpan timeUntilNextRun = nextRunTime - now;
  188. // 如果当前时间已经超过了8点,将等待到明天后的8点
  189. if (timeUntilNextRun < TimeSpan.Zero)
  190. {
  191. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  192. nextRunTime += timeUntilNextRun;
  193. }
  194. //long ttl = timeUntilNextRun.Milliseconds/1000;
  195. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  196. var data = new
  197. {
  198. imei = imeiDel,
  199. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  200. ttl,
  201. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  202. };
  203. var result = JsonConvert.SerializeObject(data);
  204. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  205. #else
  206. // 每$interval天,晚上8点
  207. var interval = 1;
  208. // 获取当前时间
  209. DateTime now = DateTime.Now;
  210. var rand = new Random();
  211. var pushSec = rand.Next(59);
  212. int pushMin = int.TryParse(imeiDel.AsSpan(imeiDel.Length - 1), out pushMin) ? pushMin : 10;
  213. // 计算距离下一个$interval天后的0点的时间间隔
  214. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 6, pushMin, pushSec).AddDays(interval);
  215. TimeSpan timeUntilNextRun = nextRunTime - now;
  216. // 如果当前时间已经超过了8点,将等待到明天后的8点
  217. if (timeUntilNextRun < TimeSpan.Zero)
  218. {
  219. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  220. nextRunTime += timeUntilNextRun;
  221. }
  222. // var ttl = timeUntilNextRun.TotalMilliseconds;
  223. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  224. var data = new
  225. {
  226. imei = imeiDel,
  227. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  228. ttl,
  229. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  230. };
  231. var result = JsonConvert.SerializeObject(data);
  232. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  233. #endif
  234. #endregion
  235. }
  236. // health_monitor/schedule_push/cal_fetal_heart_rate/imei/
  237. else if (key.Contains("health_monitor/schedule_push/cal_fetal_heart_rate/imei/"))
  238. {
  239. /**
  240. var triggerValue= (JObject)JsonConvert.DeserializeObject(e.PrevKv.Value.ToStringUtf8())!;
  241. var trigger = triggerValue["trigger"]?.ToString();
  242. if (!string.IsNullOrEmpty(trigger))
  243. {
  244. var triggerHeartRate= JsonConvert.DeserializeObject<HisGpsHeartRate>(trigger);
  245. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = triggerHeartRate?.MessageId! }))
  246. {
  247. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  248. _logger.LogInformation($"触发常规心率计算胎心");
  249. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  250. if (isFetalHeartEnable)
  251. {
  252. // 告警上限阀值
  253. var upperAlarmThreshold = (int)watchConfig!["upperAlarmThreshold"]!;
  254. // 告警下限阀值
  255. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  256. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容(最小highFreqSampleInterval=60)
  257. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! + 5 : 60;
  258. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  259. // 最后一条孕妇心率
  260. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(imeiDel);
  261. var isNormalHeartRate = triggerHeartRate?.MessageId == lastPhr.MessageId;
  262. // 判断最后一条孕妇心率与解析器的触发心率是否一致
  263. if (isNormalHeartRate)
  264. {
  265. //最后一条孕妇心率与解析器的触发心率一致
  266. HisGpsHeartRate heartRate = new()
  267. {
  268. CreateTime = lastPhr.CreateTime,
  269. DeviceKey = lastPhr.DeviceKey,
  270. HeartRate = lastPhr.PregnancyHeartRate,
  271. HeartRateId = lastPhr.PregnancyHeartRateId,
  272. IsDisplay = lastPhr.IsDisplay ? 1 : 0,
  273. MessageId = lastPhr.MessageId,
  274. LastUpdate = lastPhr.LastUpdate,
  275. Method = lastPhr.Method,
  276. PersonId = lastPhr.PersonId,
  277. Serialno = lastPhr.SerialNumber
  278. };
  279. var intervalFHR = 15;
  280. await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  281. }
  282. // 最后一条孕妇心率与解析器的触发心率不一致,触发心率是高频心率的首条
  283. else
  284. {
  285. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  286. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(imeiDel);
  287. if (phrFreqstatus != null)
  288. {
  289. #region 高频缓存
  290. // 高频首条是触发心率,30秒后,高频第二条已经写入首条高频缓存
  291. var diffCount = phr.Where(i => i.CreateTime >= phrFreqstatus.CreateTime && i.CreateTime <= lastPhr.CreateTime)
  292. .OrderByDescending(i => i.CreateTime);
  293. _logger.LogInformation($"{imeiDel} 存在高频缓存,高频心率首条记录${phrFreqstatus.MessageId},高频首条到当前的MSG ID{string.Join(",",diffCount.Select(i=>i.MessageId))}");
  294. #endregion
  295. }
  296. // 不在高频状态状态,但触发孕妇心率与最后一条孕妇心率不一致,
  297. // 常规心率数据是批量上报,需要计算每条心率对应的胎心数据
  298. else
  299. {
  300. _logger.LogInformation($"{imeiDel} 常规心率数据是批量上报,需要计算每条心率对应的胎心数据");
  301. #region 计算每条心率对应的胎心数据
  302. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  303. // 获取高频数据
  304. var freqCollection = new List<PregnancyHeartRateModel>();
  305. PregnancyHeartRateModel? previousItem = null;
  306. foreach (var item in phr)
  307. {
  308. if (previousItem != null)
  309. {
  310. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  311. if (timeNextDiff <= highFreqSampleInterval)
  312. {
  313. freqCollection.Add(item);
  314. }
  315. }
  316. previousItem = item;
  317. }
  318. //去除高频
  319. foreach (var item in freqCollection)
  320. {
  321. phr.Remove(item);
  322. }
  323. // 排序并过滤高频数据
  324. //var previousItem = phr.OrderByDescending(i => i.LastUpdate).ToList().First();
  325. //phr = phr.Skip(1)
  326. // .Where(item =>
  327. // {
  328. // var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  329. // previousItem = item;
  330. // return timeNextDiff > highFreqSampleInterval;
  331. // })
  332. // .Prepend(previousItem)
  333. // .OrderByDescending(i => i.LastUpdate)
  334. // .ToList();
  335. var calFhrTasks = phr.Where(p => p.LastUpdate >= triggerHeartRate!.LastUpdate)
  336. .Select( async p =>
  337. {
  338. HisGpsHeartRate heartRate = new()
  339. {
  340. CreateTime = p.CreateTime,
  341. DeviceKey = p.DeviceKey,
  342. HeartRate = p.PregnancyHeartRate,
  343. HeartRateId = p.PregnancyHeartRateId,
  344. IsDisplay = p.IsDisplay ? 1 : 0,
  345. MessageId = p.MessageId,
  346. LastUpdate = p.LastUpdate,
  347. Method = p.Method,
  348. PersonId = p.PersonId,
  349. Serialno = p.SerialNumber
  350. };
  351. var intervalFHR = 15;
  352. await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  353. });
  354. await Task.WhenAll(calFhrTasks);
  355. #endregion
  356. }
  357. }
  358. }
  359. else
  360. {
  361. _logger.LogWarning($"{imeiDel} 胎心监测功能没有开启");
  362. }
  363. }
  364. }
  365. else
  366. {
  367. _logger.LogWarning($"{imeiDel} trigger is not set");
  368. }
  369. */
  370. }
  371. //health_monitor/schedule_push/cal_fetal_movement/imei/
  372. else if (key.Contains("health_monitor/schedule_push/cal_fetal_movement/imei/"))
  373. {
  374. #region 胎动延时计算
  375. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  376. _logger.LogInformation($"触发胎动计算,设备配置{JsonConvert.SerializeObject(watchConfig)}");
  377. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  378. if (isFetalHeartEnable)
  379. {
  380. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  381. // 已经建模
  382. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  383. if (commonPHR != null)
  384. {
  385. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  386. _logger.LogInformation($"{imeiDel} 计算胎动数据 ");
  387. var fmNow = DateTime.Now;
  388. // 两小时前
  389. var fmNowSubtract = fmNow.AddMinutes(-fmNow.Minute).AddSeconds(-fmNow.Second).AddMilliseconds(-fmNow.Millisecond);
  390. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(fmNowSubtract).ToString()[..10];
  391. // 统计开始时间
  392. var statStartTime = fmNowSubtract.AddHours(-2);
  393. // 统计结束时间
  394. var statEndTime = fmNowSubtract;
  395. var isFetalMovementExisted = await _deviceCacheMgr.FetalMovementIsExistedAsync(imeiDel, fetalMovementSampleTime);
  396. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 开始");
  397. if (!isFetalMovementExisted)
  398. {
  399. /// 开始计算
  400. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate <= statEndTime)
  401. .OrderByDescending(i => i.LastUpdate)
  402. .Select(i => i.LastUpdate)
  403. .ToList();
  404. // 判断是否有持续佩戴
  405. if (phrRange.Count >= 2)
  406. {
  407. // 读取胎心数据
  408. GeneralParam param = new()
  409. {
  410. Filters = new List<QueryFilterCondition>
  411. {
  412. new ()
  413. {
  414. Key=nameof(HisGpsFetalHeartRate.Serialno),
  415. Value=imeiDel,
  416. ValueType=QueryValueTypeEnum.String,
  417. Operator=QueryOperatorEnum.Equal
  418. },
  419. //new ()
  420. //{
  421. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  422. // Value=sampleTime,
  423. // ValueType=QueryValueTypeEnum.String,
  424. // Operator=QueryOperatorEnum.GreaterEqual
  425. //},
  426. },
  427. OrderBys = new List<OrderByCondition>
  428. {
  429. new (){
  430. IsDesc=true,
  431. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  432. }
  433. }
  434. };
  435. var fetalHeartRateIsAbnormal = 0;
  436. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  437. // 胎心数据时间与胎动时间一致
  438. var time = long.Parse(fhr.SampleTime.Length < 13 ? fhr.SampleTime.PadRight(13, '0') : fhr.SampleTime);
  439. var fhrSampleTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(time);
  440. // 胎心数据时间与胎动时间一致,最后一条胎心数据与胎动数据的小时差不大于2
  441. if ((DateTime.Now.Hour - fhrSampleTime.Hour) <= 2)
  442. {
  443. var duringMins = Math.Abs((phrRange.First() - phrRange.Last()).TotalMinutes);
  444. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  445. bool isInTimeRanges = IsLastUpdateInTimeRanges(phrRange.First());
  446. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  447. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  448. {
  449. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  450. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  451. .Where(i =>
  452. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  453. i.PregnancyPeriod[1] >= pregnancyWeeks)
  454. .Select(i => i.MedianMovement)
  455. .FirstOrDefault()
  456. :
  457. fetalMovementMap
  458. .Where(i =>
  459. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  460. i.PregnancyPeriod[1] >= pregnancyWeeks)
  461. .Select(i => i.InitialMovement)
  462. .FirstOrDefault()
  463. ;
  464. var fetalMovementValue = (fetalMovementMapValue * duringMins * 2) / 120;
  465. // 四舍五入
  466. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  467. // _logger.LogInformation($"{imeiDel} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");
  468. #region 生理健康与胎动的关系
  469. /// (步数)运动步数超过1500步则加1;
  470. /// (体温)低烧则胎动减1,高烧胎动减2;低烧是37.3~38.5,38.6以上是高烧。
  471. /// (血压)血压收缩压大于160则加1。
  472. /// (心理)心理压力高加2,压力中加1;
  473. var fetalMovementStepVar = 0;
  474. var fetalMovementTempVar = 0;
  475. var fetalMovementBpVar = 0;
  476. var fetalMovementPpVar = 0;
  477. // 步数
  478. if (true)
  479. {
  480. var step = await _personCacheMgr.GetStepPeriodicityAsync(imeiDel);
  481. if (DateTime.Now.Hour - ((DateTime)step?.LastUpdate!).Hour <= 2)
  482. {
  483. if (step.Steps > 1500) fetalMovementStepVar = 1;
  484. }
  485. else
  486. {
  487. _logger.LogWarning($"{imeiDel} 周期步数 时间无效");
  488. }
  489. }
  490. // 体温
  491. if (true)
  492. {
  493. var temp = await _personCacheMgr.GetTemperaturePeriodicityAsync(imeiDel);
  494. if (DateTime.Now.Hour - ((DateTime)temp?.LastUpdate!).Hour <= 2)
  495. {
  496. // 中烧
  497. if (temp.Temperature>=37.3M&& temp.Temperature<= 38.5M)
  498. {
  499. fetalMovementTempVar = -1;
  500. }
  501. // 高烧
  502. if (temp.Temperature >= 38.6M)
  503. {
  504. fetalMovementTempVar = -2;
  505. }
  506. }
  507. else
  508. {
  509. _logger.LogWarning($"{imeiDel} 周期体温 时间无效");
  510. }
  511. }
  512. // 血压
  513. if (true)
  514. {
  515. var bp = await _personCacheMgr.GetBloodPressPeriodicityAsync(imeiDel);
  516. if (DateTime.Now.Hour - ((DateTime)bp?.LastUpdate!).Hour <= 2)
  517. {
  518. if (bp.SystolicValue>160)
  519. {
  520. fetalMovementBpVar = 1;
  521. }
  522. }
  523. else
  524. {
  525. _logger.LogWarning($"{imeiDel} 周期血压 时间无效");
  526. }
  527. }
  528. // 心理
  529. if (true)
  530. {
  531. //-1 不处理,
  532. //0 正常,
  533. //1 轻度,
  534. //2 中度;
  535. //3 重度;
  536. GeneralParam psychResultParam = new()
  537. {
  538. Filters = new List<QueryFilterCondition>
  539. {
  540. new ()
  541. {
  542. Key=nameof(HisGpsPsychResult.Serialno),
  543. Value=imeiDel,
  544. ValueType=QueryValueTypeEnum.String,
  545. Operator=QueryOperatorEnum.Equal
  546. },
  547. //new ()
  548. //{
  549. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  550. // Value=sampleTime,
  551. // ValueType=QueryValueTypeEnum.String,
  552. // Operator=QueryOperatorEnum.GreaterEqual
  553. //},
  554. },
  555. OrderBys = new List<OrderByCondition>
  556. {
  557. new (){
  558. IsDesc=true,
  559. Key=nameof(HisGpsPsychResult.Serialno)
  560. }
  561. }
  562. };
  563. var psych = await _hisPsychResultApiClient.GetFirstAsync(psychResultParam, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  564. if (psych?.StressScore == 2)
  565. {
  566. fetalMovementPpVar = 1;
  567. }
  568. if (psych?.StressScore == 3)
  569. {
  570. fetalMovementPpVar = 2;
  571. }
  572. }
  573. _logger.LogInformation($"{imeiDel} 原始胎动值:{fetalMovementValue}, 步数变动值:{fetalMovementStepVar},体温变动值:{fetalMovementTempVar},血压变动值:{fetalMovementBpVar},心理压力变动值{fetalMovementPpVar}");
  574. fetalMovementValue = fetalMovementValue + fetalMovementStepVar + fetalMovementTempVar + fetalMovementBpVar + fetalMovementPpVar;
  575. #endregion
  576. #region 胎心与胎动的关系
  577. // 胎心值过缓时,则胎动数量减1;胎心值过速时,则胎动也加1。
  578. // 此值允许在上限值上继续增加,在下限值上继续减少,最小值为0。
  579. #endregion
  580. _logger.LogInformation($"{imeiDel} 孕周:{pregnancyWeeks},胎动数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 原始胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{phrRange.Last()}-{phrRange.First()}, 胎动计算值:{fetalMovementValue}, 胎动最终值:{fetalMovement} 已完成.");
  581. // 获取胎心数据状态与胎动数据状态一致
  582. //etalHeartRateIsAbnormal= fhr.IsAbnormal;
  583. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  584. await _serviceIotApi.SetFetalMovementConfig(imeiDel, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  585. // 保存到MySQL数据库
  586. HisGpsFetalMovement fm = new()
  587. {
  588. FetalMovementId = Guid.NewGuid().ToString("D"),
  589. PersonId = commonPHR!.PersonId,
  590. Serialno = imeiDel,
  591. CreateTime = DateTime.Now,
  592. IsAbnormal = feltalMovementIsAbnormal,
  593. FetalMovementValue = fetalMovement,
  594. SampleTime = fetalMovementSampleTime,
  595. Method = 1,
  596. IsDisplay = 1,
  597. DeviceKey = commonPHR!.DeviceKey
  598. };
  599. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  600. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(imeiDel).ConfigureAwait(false);
  601. var fmMsgId = $"{imeiDel}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  602. var fmMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  603. // 胎动数据推送到第三方
  604. var topic = "topic.push.third";
  605. var fmThridMsg = new
  606. {
  607. messageId = fmMsgId,
  608. topic = topic,
  609. time = fmMsgTime,
  610. data = new
  611. {
  612. imei = imeiDel,
  613. value = fetalMovement,
  614. isAbnormal = feltalMovementIsAbnormal,
  615. type = "fetalMovement"
  616. }
  617. };
  618. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, 31, fmThridMsg).ConfigureAwait(false);
  619. // 胎动数据推送到微信
  620. if (feltalMovementIsAbnormal != 0)
  621. {
  622. topic = "topic.push.wx";
  623. var fmMsg = new
  624. {
  625. messageId = Guid.NewGuid().ToString("D"),
  626. topic = topic,
  627. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
  628. data = new
  629. {
  630. deviceId = device?.DeviceId,
  631. imei = imeiDel,
  632. alarmTypeId = 12,
  633. alarmDeviceName = imeiDel,
  634. alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
  635. address = string.Empty,
  636. deviceKey = device?.DeviceId
  637. }
  638. };
  639. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
  640. }
  641. // 设置入库缓存记录
  642. await _deviceCacheMgr.SetFetalMovementAsync(imeiDel, fetalMovementSampleTime, fm);
  643. }
  644. else
  645. {
  646. _logger.LogWarning($"{imeiDel} 孕周 {pregnancyWeeks},超出胎动计算范围");
  647. }
  648. }
  649. else
  650. {
  651. _logger.LogWarning($"{imeiDel} 最后一条胎心数据与胎动数据的小时差大于2,不计算胎动数据");
  652. }
  653. }
  654. else
  655. {
  656. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 不足两条,不能判断是否持续佩戴");
  657. }
  658. }
  659. else
  660. {
  661. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 已处理");
  662. }
  663. }
  664. }
  665. #endregion
  666. }
  667. else
  668. {
  669. // 处理血压业务
  670. int systolicInc;
  671. int diastolicInc;
  672. int systolicRefValue;
  673. int diastolicRefValue;
  674. decimal systolicAvg;
  675. decimal diastolicAvg;
  676. int systolicMax = 0;
  677. int diastolicMax = 0;
  678. // 统计时间
  679. //DateTime endTime = DateTime.Now; //测试
  680. DateTime statStartTime = DateTime.Now;
  681. // 最小值
  682. int systolicMin = 0;
  683. int diastolicMin = 0;
  684. // 偏移参数
  685. var avgOffset = 0.25M;
  686. var systolicAvgOffset = avgOffset;
  687. var diastolicAvgOffset = avgOffset;
  688. // 最后一次下发值
  689. int lastPushSystolicInc = 0;
  690. int lastPushDiastolicInc = 0;
  691. var startTime = DateTime.Now;
  692. // 下发增量值
  693. #region 统计定时下发增量值
  694. //var last = await _serviceTDengine.GetLastAsync("stb_hm_bloodpress_stats_inc", $"serialno='{imeiDel}' order by last_update desc");
  695. //var ts = last?[0];
  696. // 最后一条血压数据
  697. var condition = $"serialno='{imeiDel}' order by last_update desc";
  698. var field = "last_row(*)";
  699. var lastHmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition, field);
  700. var lastHmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(lastHmBpResponse!);
  701. var lastHmBp = lastHmBpParser?.Select().FirstOrDefault();
  702. //if (lastHmBpParser?.Select()?.ToList().Count < 2)
  703. //{
  704. // _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 血压数据条目不足");
  705. // break;
  706. //}
  707. // 7 天有效数据
  708. if (lastHmBp?.Timestamp.AddDays(7) > DateTime.Now)
  709. {
  710. // 计算增量值
  711. condition = $"serialno='{imeiDel}' order by ts desc";
  712. var lastPushResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bp_push_ref_inc_value", condition, field);
  713. if (lastPushResponse == null)
  714. {
  715. _logger.LogInformation($"{imeiDel}--没有下发记录");
  716. break;
  717. }
  718. var lastPushParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressurePushRefIncModel>>(lastPushResponse);
  719. var lastPush = lastPushParser!.Select().FirstOrDefault();
  720. // 有下推记录
  721. if (lastPush != null)
  722. {
  723. systolicRefValue = lastPush!.SystolicRefValue;
  724. diastolicRefValue = lastPush!.DiastolicRefValue;
  725. lastPushSystolicInc = lastPush!.SystolicIncValue;
  726. lastPushDiastolicInc = lastPush!.DiastolicIncValue;
  727. condition = $"ts between '{lastPush?.Timestamp:yyyy-MM-dd HH:mm:ss.fff}' and '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  728. $"and serialno='{imeiDel}' " +
  729. $"and is_display = true";
  730. // 使用最近一次的下推时间作为统计的开始时间
  731. statStartTime = lastPush!.Timestamp;
  732. }
  733. // 没有下推记录(历史遗留数据),没有初始的测量值产生的平均值(测量值=平均值)
  734. else
  735. {
  736. #region 获取个人信息
  737. var person = await _personCacheMgr.GetDeviceGpsPersonCacheBySerialNoAsync(Guid.NewGuid().ToString(), imeiDel).ConfigureAwait(false);
  738. //验证这个信息是否存在
  739. if (person == null || person?.Person.BornDate == null)
  740. {
  741. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证个人信息,找不到个人信息,跳过此消息");
  742. break;
  743. }
  744. // 验证年龄是否在范围 (2 - 120)
  745. var age = SafeType.SafeInt(DateTime.Today.Year - person?.Person.BornDate!.Value.Year!);
  746. if (age < 2 || age > 120)
  747. {
  748. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证年龄,不在范围 (2 - 120)岁,跳过此消息");
  749. break;
  750. }
  751. var gender = person?.Person.Gender == true ? 1 : 2;
  752. var isHypertension = SafeType.SafeBool(person?.Person.Ishypertension!);
  753. var height = SafeType.SafeDouble(person?.Person.Height!);
  754. var weight = SafeType.SafeDouble(person?.Person.Weight!);
  755. #endregion
  756. #region 初始化常规血压标定值标定值
  757. var bpRef = await _bpRefValCacheManager.GetBloodPressReferenceValueAsync(age, gender, isHypertension);
  758. //systolicRefValue = bpRef!.Systolic;//?
  759. //diastolicRefValue = bpRef!.Diastolic;//?
  760. #endregion
  761. systolicRefValue = bpRef!.Systolic;
  762. diastolicRefValue = bpRef!.Diastolic;
  763. lastPushSystolicInc = 0;
  764. lastPushDiastolicInc = 0;
  765. condition = $"ts <= '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  766. $"and serialno='{imeiDel}' " +
  767. $"and is_display = true";
  768. }
  769. var hmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition);
  770. var hmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(hmBpResponse!);
  771. var hmBp = hmBpParser?.Select();
  772. //if (hmBp?.ToList().Count < 2)
  773. // 1. 判断数据样本数量
  774. if (hmBpParser!.Rows < 5)
  775. {
  776. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 统计定时下发,计算增量值的数据条目不足:{hmBpParser!.Rows} < 5");
  777. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} 没有足够的数据样本,不会定时下发");
  778. break;
  779. }
  780. // 没有下推记录重新计算统计时间
  781. if (lastPush == null)
  782. {
  783. var firstHmBp = hmBpParser?.Select(i => i).OrderBy(i => i.Timestamp).FirstOrDefault();
  784. statStartTime = firstHmBp!.Timestamp;
  785. }
  786. // NewMethod(systolicRefValue, hmBpParser);
  787. // 最大值
  788. //systolicMax = (int)hmBpParser?.Select(i => i.SystolicValue).Max()!;
  789. //diastolicMax = (int)hmBpParser?.Select(i => i.DiastolicValue).Max()!;
  790. //// 最小值
  791. //systolicMin = (int)hmBpParser?.Select(i => i.SystolicValue).Min()!;
  792. //diastolicMin = (int)hmBpParser?.Select(i => i.DiastolicValue).Min()!;
  793. //systolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.SystolicValue, SafeType.SafeInt(systolicRefValue!)))!;
  794. //diastolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.DiastolicValue, SafeType.SafeInt(diastolicRefValue!)))!;
  795. var avgs = _serviceTDengine.AverageAfterRemovingOneMinMaxRef(hmBpParser!);
  796. systolicAvg = avgs[0];
  797. diastolicAvg = avgs[1];
  798. // 2. 判断能否计算增量值
  799. if (systolicAvg.Equals(0))
  800. {
  801. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算平均值" +
  802. $"\n currentSystolicAvg:{systolicAvg} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  803. $"\n currentDiastolicInc:{diastolicAvg} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  804. _logger.LogInformation($"{imeiDel}--{nameof(Worker)} 没有足够的数据样本计算平均值,不会定时下发");
  805. break;
  806. }
  807. // 除最大值和最小值后的平均值与标定值差值少于4后(当天计算出该结果则也不产生增量调整),就不再进行增量值调整了。
  808. if (systolicRefValue - systolicAvg < 4)
  809. {
  810. _logger.LogInformation($"diastolic 舒张压 {imeiDel}除最大值和最小值后的平均值:{diastolicAvg}与标定值:{diastolicRefValue}\n systolic 收缩压 {imeiDel}除最大值和最小值后的平均值:{systolicAvg}与标定值:{systolicRefValue}的差值(标定值-平均值)少于4后,systolic 收缩压 不再进行增量值调整");
  811. break;
  812. }
  813. if (diastolicRefValue - diastolicAvg < 4)
  814. {
  815. _logger.LogInformation($"systolic 收缩压 {imeiDel}除最大值和最小值后的平均值:{systolicAvg}与标定值:{systolicRefValue}\n diastolic 舒张压 {imeiDel}除最大值和最小值后的平均值:{diastolicAvg}与标定值:{diastolicRefValue}的差值(标定值-平均值)少于4后,diastolic 舒张压 不再进行增量值调整");
  816. break;
  817. }
  818. // 增量值=(标定值-平均值)* 0.25
  819. var currentSystolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
  820. var currentDiastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
  821. // 累计增量
  822. systolicInc = currentSystolicInc + lastPushSystolicInc;
  823. diastolicInc = currentDiastolicInc + lastPushDiastolicInc;
  824. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算增量值" +
  825. $"\n {imeiDel} -- systolicAvg:{systolicAvg}-- systolicInc:{systolicInc}-- currentSystolicInc:{currentSystolicInc} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  826. $"\n {imeiDel} -- diastolicAvg:{diastolicAvg}-- diastolicInc:{diastolicInc} --currentDiastolicInc:{currentDiastolicInc} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  827. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}-- 定时校准,发给设备的绝对增量值=(上次绝对增量值+新数据的增量值)");
  828. _logger.LogInformation($"{nameof(Worker)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
  829. if (_configBoodPressResolver.EnableBPRefPush)
  830. // if (false) // 临时关闭
  831. {
  832. BloodPressCalibrationConfigModel bpIncData = new()
  833. {
  834. Imei = imeiDel,
  835. SystolicRefValue = SafeType.SafeInt(((int)systolicRefValue!)), //收缩压标定值,值为0 表示不生效
  836. DiastolicRefValue = SafeType.SafeInt(((int)diastolicRefValue!)), //舒张压标定值,值为0表示不生效
  837. SystolicIncValue = SafeType.SafeInt(((int)systolicInc!)), //收缩压显示增量,值为0 表示不生效
  838. DiastolicIncValue = SafeType.SafeInt(((int)diastolicInc!)) //舒张压显示增量,值为0 表示不生效
  839. };
  840. //var pushedBP = await _serviceIotApi.SetBloodPressCalibrationConfigAsync(bpIncData).ConfigureAwait(false);
  841. var response = await _serviceIotApi.SetBloodPressCalibrationConfig2Async(bpIncData).ConfigureAwait(false);
  842. var pushedBP = response.Flag;
  843. if (pushedBP)
  844. {
  845. #region 保存下推记录 stb_hm_bp_push_ref_inc_value
  846. var sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{imeiDel.Substring(imeiDel.Length - 2)} " +
  847. $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
  848. $"TAGS ('{imeiDel.Substring(imeiDel.Length - 2)}') " +
  849. $"VALUES(" +
  850. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  851. $"'{imeiDel}'," +
  852. $"{bpIncData.SystolicRefValue}," +
  853. $"{bpIncData.DiastolicRefValue}," +
  854. $"{bpIncData.SystolicIncValue}," +
  855. $"{bpIncData.DiastolicIncValue}," +
  856. $"{false}," +
  857. $"{systolicAvg}," +
  858. $"{diastolicAvg}," +
  859. $"{systolicAvgOffset}," +
  860. $"{diastolicAvgOffset}," +
  861. $"'{statStartTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  862. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'" +
  863. $")";
  864. _serviceTDengine.ExecuteInsertSQL(sql);
  865. #endregion
  866. #region 注册定时下发
  867. // 注册下次下推
  868. var endTime = DateTime.Now;
  869. #if DEBUG
  870. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  871. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  872. var interval = 0;
  873. // 获取当前时间
  874. DateTime now = DateTime.Now;
  875. // 计算距离下一个$interval天后的8点的时间间隔
  876. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  877. TimeSpan timeUntilNextRun = nextRunTime - now;
  878. // 如果当前时间已经超过了8点,将等待到明天后的8点
  879. if (timeUntilNextRun < TimeSpan.Zero)
  880. {
  881. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  882. nextRunTime += timeUntilNextRun;
  883. }
  884. // var ttl = timeUntilNextRun.TotalMilliseconds;
  885. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  886. var data = new
  887. {
  888. imei = imeiDel,
  889. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  890. ttl,
  891. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  892. };
  893. var result = JsonConvert.SerializeObject(data);
  894. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  895. #else
  896. // 每$interval天,晚上8点
  897. var interval = 1;
  898. // 获取当前时间
  899. DateTime now = DateTime.Now;
  900. // 计算距离下一个$interval天后的8点的时间间隔
  901. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 20, 0, 0).AddDays(interval);
  902. TimeSpan timeUntilNextRun = nextRunTime - now;
  903. // 如果当前时间已经超过了8点,将等待到明天后的8点
  904. if (timeUntilNextRun < TimeSpan.Zero)
  905. {
  906. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  907. nextRunTime += timeUntilNextRun;
  908. }
  909. // var ttl = timeUntilNextRun.TotalMilliseconds;
  910. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  911. var data = new
  912. {
  913. imei = imeiDel,
  914. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  915. ttl,
  916. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  917. };
  918. var result = JsonConvert.SerializeObject(data);
  919. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  920. #endif
  921. #endregion
  922. }
  923. else
  924. {
  925. _logger.LogInformation($"错误响应,没有下推数据:{response.Message}");
  926. }
  927. }
  928. }
  929. else
  930. {
  931. _logger.LogInformation($"向{imeiDel}统计数据已经失效");
  932. }
  933. #endregion
  934. }
  935. }
  936. break;
  937. }
  938. }
  939. catch (Exception ex)
  940. {
  941. _logger.LogInformation($"{nameof(WatchEvents)},出错: |{ex.Message}|{ex.StackTrace}");
  942. }
  943. });
  944. }
  945. private async Task SetIntervalTriggerAsync(string key, string imei, long interval)
  946. {
  947. // var key = $"health_monitor/schedule_push/{type}/imei/{imei}";
  948. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  949. if (string.IsNullOrWhiteSpace(schedulePush))
  950. {
  951. var now = DateTime.Now;
  952. var timeNextRun = now.Add(TimeSpan.FromSeconds(interval));
  953. var data = new
  954. {
  955. imei,
  956. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  957. ttl = interval,
  958. next_run_time = timeNextRun.ToString("yyyy-MM-dd HH:mm:ss")
  959. };
  960. var result = JsonConvert.SerializeObject(data);
  961. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  962. }
  963. }
  964. public static bool IsNowInTimeRanges()
  965. {
  966. var now = DateTime.Now.TimeOfDay;
  967. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  968. {
  969. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  970. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  971. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  972. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  973. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  974. };
  975. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  976. }
  977. public static bool IsLastUpdateInTimeRanges(DateTime lastUpdate)
  978. {
  979. var now = lastUpdate.TimeOfDay;
  980. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  981. {
  982. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  983. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  984. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  985. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  986. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  987. };
  988. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  989. }
  990. private async Task CalculateNormalFetalHeartRateAsync(HisGpsHeartRate heartRate, int upperAlarmThreshold, int lowerAlarmThreshold, int intervalFHR, PregnancyCommonHeartRateModel? commonPHR)
  991. {
  992. // 上15分钟的数据
  993. // 获取当前时间
  994. DateTime nowInterval = (DateTime)heartRate.LastUpdate!;
  995. if (nowInterval.Second > 0)
  996. {
  997. nowInterval = nowInterval.AddMinutes(1);
  998. }
  999. // 计算last_update到上一间隔的分钟数
  1000. int minutesToSubtract = nowInterval.Minute % intervalFHR;
  1001. // 计算上一间隔的时间
  1002. DateTime previousInterval = nowInterval.AddMinutes(-minutesToSubtract).AddSeconds(-nowInterval.Second).AddMilliseconds(-nowInterval.Millisecond);
  1003. // 使用 last_update 上一刻
  1004. var sampleTimeFHR = DateTimeUtil.ConvertToTimeStamp(previousInterval).ToString();
  1005. // 计算last_update到下一间隔的分钟数
  1006. int minutesToAdd = intervalFHR - (nowInterval.Minute % intervalFHR);
  1007. if (minutesToAdd == intervalFHR)
  1008. {
  1009. minutesToAdd = 0; // 如果已经是间隔,则不需要增加分钟
  1010. }
  1011. // 计算下一间隔的时间
  1012. DateTime nextInterval = nowInterval.AddMinutes(minutesToAdd)
  1013. .AddSeconds(-nowInterval.Second)
  1014. .AddMilliseconds(-nowInterval.Millisecond);
  1015. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  1016. var normalPhrStatStartTime = nextInterval.AddMinutes(-intervalFHR);
  1017. var normalPhrStatEndTime = nextInterval;
  1018. _logger.LogInformation($" {heartRate.MessageId} -- {heartRate.Serialno} 计算胎心数据, 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} ");
  1019. var filteredPhr = daysPhr
  1020. // 使用 last_update 下一刻
  1021. .Where(i => i.LastUpdate <= normalPhrStatEndTime && i.LastUpdate >= normalPhrStatStartTime)
  1022. .ToList();
  1023. if (filteredPhr.Count == 0)
  1024. {
  1025. _logger.LogWarning($"{heartRate.MessageId} -- {heartRate.Serialno} 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} 孕妇心率数据不足,{filteredPhr.Count}条记录");
  1026. return;
  1027. }
  1028. var phrValue = filteredPhr.Count == 1
  1029. ? filteredPhr.First().PregnancyHeartRate
  1030. : filteredPhr.Average(i => i.PregnancyHeartRate);
  1031. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, phrValue, sampleTimeFHR);
  1032. await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, phrValue, sampleTimeFHR, normalPhrStatStartTime, normalPhrStatEndTime);
  1033. }
  1034. private async Task SaveAndPushFetalHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int upperAlarmThreshold, int lowerAlarmThreshold, double phrValue, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  1035. {
  1036. // 计算胎心=孕妇心率*系数
  1037. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  1038. //fetalHeartRate = fetalHeartRate > 220 ? 220 : fetalHeartRate; // 胎心的最大值调整为220,超过都按该值220输出
  1039. if (fetalHeartRate >= 220)
  1040. {
  1041. // 先使用最小系数计算
  1042. var statMaxValueFprCoefficient = commonPHR?.StatMaxValueFprCoefficient!;
  1043. var statMinValueFprCoefficient = commonPHR?.StatMinValueFprCoefficient!;
  1044. var coefficient = statMaxValueFprCoefficient < statMinValueFprCoefficient ? statMaxValueFprCoefficient : statMinValueFprCoefficient;
  1045. fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  1046. if (fetalHeartRate < 220)
  1047. {
  1048. _logger.LogWarning($"{heartRate.Serialno} 使用极值系数 {coefficient} ,建模数据可能出现异常,请检查");
  1049. }
  1050. else
  1051. {
  1052. fetalHeartRate = 220;
  1053. _logger.LogWarning($"{heartRate.Serialno} 使用所有系数都不能放映实际,建模数据可能出现异常,请检查");
  1054. }
  1055. }
  1056. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  1057. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  1058. if (phrFreqstatus == null) isAbnormal = 0;
  1059. var statsusDesc = (phrFreqstatus == null) ? $"MSG ID: {heartRate.MessageId} 常规" : "高频";
  1060. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,心率值{heartRate.HeartRate},生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1061. //if (!isFreq)
  1062. //{
  1063. // statStartTime = heartRate.LastUpdate;
  1064. //
  1065. //}
  1066. // 保存到 数据服务 MySQL 数据库
  1067. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  1068. {
  1069. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  1070. PersonId = commonPHR!.PersonId,
  1071. Serialno = heartRate.Serialno,
  1072. HeartRate = fetalHeartRate,
  1073. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  1074. IsAbnormal = isAbnormal,
  1075. StatStartTime = statStartTime,
  1076. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  1077. CreateTime = DateTime.Now,
  1078. Method = 1,
  1079. IsDisplay = 1,
  1080. DeviceKey = commonPHR!.DeviceKey
  1081. };
  1082. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  1083. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  1084. // 推送最后一条常规心率计算的胎心数据到iot设备
  1085. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  1086. if (lastPhr.MessageId== heartRate.MessageId)
  1087. {
  1088. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1089. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备");
  1090. }
  1091. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  1092. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  1093. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  1094. // 胎心数据推送到第三方
  1095. var topic = "topic.push.third";
  1096. var fhrThridMsg = new
  1097. {
  1098. messageId = fhrMsgId,
  1099. topic = topic,
  1100. time = fhrMsgTime,
  1101. data = new
  1102. {
  1103. imei = heartRate.Serialno,
  1104. value = fetalHeartRate,
  1105. isAbnormal,
  1106. type = "fetalHeart"
  1107. }
  1108. };
  1109. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  1110. // 胎心数据推送到微信
  1111. if (isAbnormal != 0)
  1112. {
  1113. topic = "topic.push.wx";
  1114. var fhrMsg = new
  1115. {
  1116. messageId = fhrMsgId,
  1117. topic = topic,
  1118. time = fhrMsgTime,
  1119. data = new
  1120. {
  1121. deviceId = device?.DeviceId,
  1122. imei = heartRate.Serialno,
  1123. alarmTypeId = 12,
  1124. alarmDeviceName = heartRate.Serialno,
  1125. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  1126. address = string.Empty,
  1127. deviceKey = device?.DeviceId
  1128. }
  1129. };
  1130. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  1131. }
  1132. }
  1133. }
  1134. }