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.

1120 line
73KB

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