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.

1164 lines
77KB

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