Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

3006 lines
210KB

  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. private static int INTERVAL_FHR = 15;
  57. public Worker(ILogger<Worker> logger, IServiceProvider services, PersonCacheManager personCacheMgr,
  58. BloodPressReferenceValueCacheManager bpRefValCacheManager, IotApiService IotApiService,
  59. IOptions<BoodPressResolverConfig> optionBoodPressResolver, PackageProcess processor,
  60. TDengineDataSubcribe tdEngineDataSubcribe, TDengineService serviceDengine,
  61. GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> hisFetalHeartApiClient,
  62. GpsLocationHistoryAccessorClient<HisGpsFetalMovement> hisFetalMovementApiClient,
  63. GpsLocationHistoryAccessorClient<HisGpsPsychResult> hisGpsPsychResultApiClient,
  64. FetalMovementNormalValueRangeCacheManager fetalMovementNormalValueRangeCacheMgr, MqProcessLogic serviceMqProcess,
  65. HttpHelper httpHelper, EtcdService serviceEtcd, DeviceCacheManager deviceCacheMgr)
  66. {
  67. _logger = logger;
  68. _tdEngineDataSubcribe = tdEngineDataSubcribe;
  69. _services = services;
  70. _serviceIotApi = IotApiService;
  71. _processor = processor;
  72. _serviceEtcd = serviceEtcd;
  73. _serviceTDengine = serviceDengine;
  74. _httpHelper = httpHelper;
  75. _configBoodPressResolver = optionBoodPressResolver.Value;
  76. _bpRefValCacheManager = bpRefValCacheManager;
  77. _personCacheMgr = personCacheMgr;
  78. _deviceCacheMgr = deviceCacheMgr;
  79. _hisFetalHeartApiClient = hisFetalHeartApiClient;
  80. _hisFetalMovementApiClient = hisFetalMovementApiClient;
  81. _hisPsychResultApiClient = hisGpsPsychResultApiClient;
  82. _serviceMqProcess = serviceMqProcess;
  83. _mgrFetalMovementNormalValueRangeCache = fetalMovementNormalValueRangeCacheMgr;
  84. }
  85. public override Task StartAsync(CancellationToken cancellationToken)
  86. {
  87. //_logger.LogInformation("------StartAsync");
  88. _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  89. return base.StartAsync(cancellationToken);
  90. }
  91. public override Task StopAsync(CancellationToken cancellationToken)
  92. {
  93. //_logger.LogInformation("------StopAsync");
  94. _tokenSource.Cancel(); //停止工作线程
  95. return base.StopAsync(cancellationToken);
  96. }
  97. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  98. {
  99. var tasks = new[]
  100. {
  101. Task.Run(async () =>
  102. {
  103. _logger.LogInformation("解析器启动");
  104. while (!stoppingToken.IsCancellationRequested)
  105. {
  106. await _processor.ResolveAsync().ConfigureAwait(false);
  107. }
  108. }, stoppingToken),
  109. Task.Run(() =>
  110. {
  111. _logger.LogInformation("TDengine 订阅启动");
  112. while (!stoppingToken.IsCancellationRequested)
  113. {
  114. _tdEngineDataSubcribe.BeginListen(stoppingToken);
  115. }
  116. }, stoppingToken),
  117. Task.Run(() =>
  118. _serviceEtcd.WacthKeysWithPrefixResponseAsync("health_monitor/schedule_push", WatchEvents),
  119. stoppingToken)
  120. };
  121. await Task.WhenAll(tasks);
  122. }
  123. private void WatchEvents(WatchResponse response)
  124. {
  125. response.Events.ToList<Mvccpb.Event>().ForEach(async e =>
  126. {
  127. try
  128. {
  129. switch (e.Type.ToString())
  130. {
  131. case "Put":
  132. // 获取时间点计算TTL
  133. Console.BackgroundColor = ConsoleColor.Blue;
  134. Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  135. Console.BackgroundColor = ConsoleColor.Black;
  136. break;
  137. case "Delete":
  138. // TTL到了重新计算TTL,下发
  139. //Console.BackgroundColor = ConsoleColor.Green;
  140. //Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  141. // var key = $"health_monitor/schedule_push/imei/{bp.Serialno}";
  142. var key = e.Kv.Key.ToStringUtf8();
  143. var imeiDel = key.Split('/')[^1];
  144. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  145. if (string.IsNullOrWhiteSpace(schedule_push))
  146. {
  147. // 胎心数据建模
  148. if (key.Contains("pregnancy_heart_rate"))
  149. {
  150. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = $"MODE-{imeiDel}-{DateTime.Now.ToString("yyyyMMddHHmmss")}" }))
  151. {
  152. #region 胎心数据建模
  153. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  154. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  155. if (isFetalHeartEnable)
  156. {
  157. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容
  158. //var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! + 5;
  159. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容(最小highFreqSampleInterval=60)
  160. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! + 5 : 60;
  161. // 处理孕妇业务,计算一般心率并下发
  162. var commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(imeiDel, highFreqSampleInterval: highFreqSampleInterval);
  163. if (commonPHR == null)
  164. {
  165. // 建模中
  166. var flag = await _serviceIotApi.SetFetalConfig(imeiDel);
  167. _logger.LogInformation($"{imeiDel} 建模建模中");
  168. }
  169. else
  170. {
  171. // 建模完成
  172. var flag = await _serviceIotApi.SetFetalConfig(imeiDel, 1, commonPHR.MaxValue, commonPHR.MinValue);
  173. _logger.LogInformation($"{imeiDel} 建模完成");
  174. // 保存到TDengine数据库
  175. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR);
  176. _logger.LogInformation($"保存TDengine完成");
  177. //
  178. }
  179. }
  180. #endregion
  181. #region 注册定时下发
  182. var startTime = DateTime.Now;
  183. // 注册下次下推
  184. var endTime = DateTime.Now;
  185. #if DEBUG
  186. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  187. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  188. var interval = 0;
  189. // 获取当前时间
  190. DateTime now = DateTime.Now;
  191. // 计算距离下一个$interval天后的8点的时间间隔
  192. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  193. TimeSpan timeUntilNextRun = nextRunTime - now;
  194. // 如果当前时间已经超过了8点,将等待到明天后的8点
  195. if (timeUntilNextRun < TimeSpan.Zero)
  196. {
  197. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  198. nextRunTime += timeUntilNextRun;
  199. }
  200. //long ttl = timeUntilNextRun.Milliseconds/1000;
  201. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  202. var data = new
  203. {
  204. imei = imeiDel,
  205. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  206. ttl,
  207. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  208. };
  209. var result = JsonConvert.SerializeObject(data);
  210. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  211. #else
  212. // 每$interval天,晚上8点
  213. var interval = 1;
  214. // 获取当前时间
  215. DateTime now = DateTime.Now;
  216. var rand = new Random();
  217. var pushSec = rand.Next(59);
  218. int pushMin = int.TryParse(imeiDel.AsSpan(imeiDel.Length - 1), out pushMin) ? pushMin : 10;
  219. // 计算距离下一个$interval天后的0点的时间间隔
  220. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 6, pushMin, pushSec).AddDays(interval);
  221. TimeSpan timeUntilNextRun = nextRunTime - now;
  222. // 如果当前时间已经超过了8点,将等待到明天后的8点
  223. if (timeUntilNextRun < TimeSpan.Zero)
  224. {
  225. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  226. nextRunTime += timeUntilNextRun;
  227. }
  228. // var ttl = timeUntilNextRun.TotalMilliseconds;
  229. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  230. var data = new
  231. {
  232. imei = imeiDel,
  233. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  234. ttl,
  235. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  236. };
  237. var result = JsonConvert.SerializeObject(data);
  238. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  239. #endif
  240. #endregion
  241. }
  242. }
  243. // health_monitor/schedule_push/cal_fetal_heart_rate/imei/
  244. // 高频结束后计算胎心数据,防止结束后与常规心理的胎心处理过长
  245. if (key.Contains("health_monitor/schedule_push/cal_freqhr_fetal_heart_rate/imei/"))
  246. {
  247. /// 延时计算高频状态的胎心数据,防止高频结束后与触发数据时间相隔过长。
  248. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(imeiDel);
  249. // 高频不停,15分钟内只下发一条
  250. var push = await _deviceCacheMgr.GetBizIntervalAsync(imeiDel, "SaveAndPushFetalHeartRate");
  251. var triggerValue = (JObject)JsonConvert.DeserializeObject(e.PrevKv.Value.ToStringUtf8())!;
  252. var trigger = triggerValue["trigger"]?.ToString();
  253. // 验证高频首条是否还存在
  254. if (phrFreqstatus != null && string.IsNullOrEmpty(push))
  255. {
  256. if (!string.IsNullOrEmpty(trigger))
  257. {
  258. var triggerHeartRate = JsonConvert.DeserializeObject<HisGpsHeartRate>(trigger);
  259. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = triggerHeartRate?.MessageId! }))
  260. {
  261. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  262. _logger.LogInformation($"{imeiDel}高频结束后,延迟计算高频数据产生的胎心数据");
  263. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  264. if (isFetalHeartEnable)
  265. {
  266. // 防止超过12条连续正常,高频不停止
  267. if (phrFreqstatus.MessageId == triggerHeartRate?.MessageId)
  268. {
  269. // 告警上限阀值
  270. var upperAlarmThreshold = (int)watchConfig!["upperAlarmThreshold"]!;
  271. // 告警下限阀值
  272. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  273. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容(最小highFreqSampleInterval=60)
  274. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! + 5 : 60;
  275. //停止高频心率采样心率连续正常次数
  276. var stopHighFreqSampleCount = (int)watchConfig["stopHighFreqSampleCount"]!;
  277. // 高频心率采集时长 0 为持续采集,非零为高频心率的采集时长
  278. //var highFreqSampleTimes = (int)watchConfig["highFreqSampleTimes"]!;
  279. var highFreqSampleTimes = 540;
  280. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  281. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  282. var phrFromFreqstatus = phr.Where(i => i.LastUpdate >= phrFreqstatus.LastUpdate).ToList();
  283. // 高频数据
  284. var phrInFreqstatus = GetFreqPregnancyHeartRate(phrFromFreqstatus, highFreqSampleInterval)
  285. .OrderByDescending(i => i.LastUpdate).ToList();
  286. if (phrInFreqstatus.Count > stopHighFreqSampleCount)
  287. {
  288. // 取最后 stopHighFreqSampleCount 条高频数据
  289. phrInFreqstatus = phrInFreqstatus
  290. .OrderByDescending(i => i.LastUpdate)
  291. .Take(stopHighFreqSampleCount).ToList(); // 计算最后12条
  292. var avgPhr = phrInFreqstatus
  293. .Select(i => i.PregnancyHeartRate).Average();
  294. var FreqStatsEnd = phrInFreqstatus.First().LastUpdate;
  295. _logger.LogInformation($"延时计算,{imeiDel} 高频状态持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,统计周期:{phrFreqstatus!.LastUpdate.ToString("yyyy-MM-dd HH:mm:ss")}----{FreqStatsEnd.ToString("yyyy-MM-dd HH:mm:ss")},高频心率平均值:{(int)avgPhr},将下发指令");
  296. //await SaveAndPushFetalHeartRateAsync(triggerHeartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  297. triggerHeartRate.HeartRate = (int)avgPhr;
  298. //await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(triggerHeartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  299. // 判断是否够highFreqSampleTimes,540s
  300. var lastPhr = phrInFreqstatus;
  301. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)triggerHeartRate.LastUpdate!, phrFreqstatus!.LastUpdate);
  302. if (ts < highFreqSampleTimes)
  303. {
  304. /// 不够10分钟最近12个数据的最小值生成胎心值
  305. triggerHeartRate.HeartRate = lastPhr.Select(i => i.PregnancyHeartRate).Min();
  306. }
  307. await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(triggerHeartRate, commonPHR, highFreqSampleTimes, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  308. }
  309. else
  310. {
  311. _logger.LogWarning($"{imeiDel} 高频心率的数据不大于{stopHighFreqSampleCount}条,不进行高频数据的胎心计算");
  312. }
  313. // 删除高频状态的首条记录
  314. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(imeiDel);
  315. }
  316. else
  317. {
  318. _logger.LogWarning($"{imeiDel} 超过12条连续正常,高频不停止,暂不处理");
  319. }
  320. }
  321. else
  322. {
  323. _logger.LogWarning($"{imeiDel} 胎心监测功能没有启动");
  324. }
  325. }
  326. }
  327. }
  328. }
  329. // 延时计算常规胎心数据
  330. else if (key.Contains("health_monitor/schedule_push/cal_normalphr_fetal_heart_rate/imei/"))
  331. {
  332. var triggerValue = (JObject)JsonConvert.DeserializeObject(e.PrevKv.Value.ToStringUtf8())!;
  333. var trigger = triggerValue["trigger"]?.ToString();
  334. if (!string.IsNullOrEmpty(trigger))
  335. {
  336. var triggerHeartRate = JsonConvert.DeserializeObject<HisGpsHeartRate>(trigger);
  337. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = triggerHeartRate?.MessageId! }))
  338. {
  339. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  340. _logger.LogInformation($"{imeiDel}延迟常规胎心数据产生的胎心数据");
  341. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  342. if (isFetalHeartEnable)
  343. {
  344. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  345. if (commonPHR!=null)
  346. {
  347. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! : 60;
  348. await CalculateNormalFetalHeartRateIntervalAsync(triggerHeartRate!, commonPHR, highFreqSampleInterval);
  349. }
  350. else
  351. {
  352. _logger.LogWarning($"{imeiDel} 胎心数据建模中...");
  353. }
  354. }
  355. else
  356. {
  357. _logger.LogWarning($"{imeiDel} 胎心监测功能没有启动");
  358. }
  359. }
  360. }
  361. }
  362. else if (key.Contains("health_monitor/schedule_push/cal_fetal_heart_rate/imei/"))
  363. {
  364. /**
  365. var triggerValue= (JObject)JsonConvert.DeserializeObject(e.PrevKv.Value.ToStringUtf8())!;
  366. var trigger = triggerValue["trigger"]?.ToString();
  367. if (!string.IsNullOrEmpty(trigger))
  368. {
  369. var triggerHeartRate= JsonConvert.DeserializeObject<HisGpsHeartRate>(trigger);
  370. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = triggerHeartRate?.MessageId! }))
  371. {
  372. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  373. _logger.LogInformation($"触发常规心率计算胎心");
  374. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  375. if (isFetalHeartEnable)
  376. {
  377. // 告警上限阀值
  378. var upperAlarmThreshold = (int)watchConfig!["upperAlarmThreshold"]!;
  379. // 告警下限阀值
  380. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  381. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容(最小highFreqSampleInterval=60)
  382. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! + 5 : 60;
  383. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  384. // 最后一条孕妇心率
  385. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(imeiDel);
  386. var isNormalHeartRate = triggerHeartRate?.MessageId == lastPhr.MessageId;
  387. // 判断最后一条孕妇心率与解析器的触发心率是否一致
  388. if (isNormalHeartRate)
  389. {
  390. //最后一条孕妇心率与解析器的触发心率一致
  391. HisGpsHeartRate heartRate = new()
  392. {
  393. CreateTime = lastPhr.CreateTime,
  394. DeviceKey = lastPhr.DeviceKey,
  395. HeartRate = lastPhr.PregnancyHeartRate,
  396. HeartRateId = lastPhr.PregnancyHeartRateId,
  397. IsDisplay = lastPhr.IsDisplay ? 1 : 0,
  398. MessageId = lastPhr.MessageId,
  399. LastUpdate = lastPhr.LastUpdate,
  400. Method = lastPhr.Method,
  401. PersonId = lastPhr.PersonId,
  402. Serialno = lastPhr.SerialNumber
  403. };
  404. var intervalFHR = 15;
  405. await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  406. }
  407. // 最后一条孕妇心率与解析器的触发心率不一致,触发心率是高频心率的首条
  408. else
  409. {
  410. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  411. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(imeiDel);
  412. if (phrFreqstatus != null)
  413. {
  414. #region 高频缓存
  415. // 高频首条是触发心率,30秒后,高频第二条已经写入首条高频缓存
  416. var diffCount = phr.Where(i => i.CreateTime >= phrFreqstatus.CreateTime && i.CreateTime <= lastPhr.CreateTime)
  417. .OrderByDescending(i => i.CreateTime);
  418. _logger.LogInformation($"{imeiDel} 存在高频缓存,高频心率首条记录${phrFreqstatus.MessageId},高频首条到当前的MSG ID{string.Join(",",diffCount.Select(i=>i.MessageId))}");
  419. #endregion
  420. }
  421. // 不在高频状态状态,但触发孕妇心率与最后一条孕妇心率不一致,
  422. // 常规心率数据是批量上报,需要计算每条心率对应的胎心数据
  423. else
  424. {
  425. _logger.LogInformation($"{imeiDel} 常规心率数据是批量上报,需要计算每条心率对应的胎心数据");
  426. #region 计算每条心率对应的胎心数据
  427. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  428. // 获取高频数据
  429. var freqCollection = new List<PregnancyHeartRateModel>();
  430. PregnancyHeartRateModel? previousItem = null;
  431. foreach (var item in phr)
  432. {
  433. if (previousItem != null)
  434. {
  435. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  436. if (timeNextDiff <= highFreqSampleInterval)
  437. {
  438. freqCollection.Add(item);
  439. }
  440. }
  441. previousItem = item;
  442. }
  443. //去除高频
  444. foreach (var item in freqCollection)
  445. {
  446. phr.Remove(item);
  447. }
  448. // 排序并过滤高频数据
  449. //var previousItem = phr.OrderByDescending(i => i.LastUpdate).ToList().First();
  450. //phr = phr.Skip(1)
  451. // .Where(item =>
  452. // {
  453. // var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  454. // previousItem = item;
  455. // return timeNextDiff > highFreqSampleInterval;
  456. // })
  457. // .Prepend(previousItem)
  458. // .OrderByDescending(i => i.LastUpdate)
  459. // .ToList();
  460. var calFhrTasks = phr.Where(p => p.LastUpdate >= triggerHeartRate!.LastUpdate)
  461. .Select( async p =>
  462. {
  463. HisGpsHeartRate heartRate = new()
  464. {
  465. CreateTime = p.CreateTime,
  466. DeviceKey = p.DeviceKey,
  467. HeartRate = p.PregnancyHeartRate,
  468. HeartRateId = p.PregnancyHeartRateId,
  469. IsDisplay = p.IsDisplay ? 1 : 0,
  470. MessageId = p.MessageId,
  471. LastUpdate = p.LastUpdate,
  472. Method = p.Method,
  473. PersonId = p.PersonId,
  474. Serialno = p.SerialNumber
  475. };
  476. var intervalFHR = 15;
  477. await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  478. });
  479. await Task.WhenAll(calFhrTasks);
  480. #endregion
  481. }
  482. }
  483. }
  484. else
  485. {
  486. _logger.LogWarning($"{imeiDel} 胎心监测功能没有开启");
  487. }
  488. }
  489. }
  490. else
  491. {
  492. _logger.LogWarning($"{imeiDel} trigger is not set");
  493. }
  494. */
  495. }
  496. // 胎动计算
  497. //health_monitor/schedule_push/cal_fetal_movement/imei/
  498. else if (key.Contains("health_monitor/schedule_push/cal_fetal_movement/imei/"))
  499. {
  500. #region 胎动延时计算
  501. /**
  502. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = $"FM-{imeiDel}-{DateTime.Now.ToString("yyyyMMddHHmmss")}" }))
  503. {
  504. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  505. _logger.LogInformation($"触发胎动计算,设备配置{JsonConvert.SerializeObject(watchConfig)}");
  506. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  507. if (isFetalHeartEnable)
  508. {
  509. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  510. // 已经建模
  511. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  512. if (commonPHR != null)
  513. {
  514. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  515. _logger.LogInformation($"{imeiDel} 计算胎动数据 ");
  516. var fmNow = DateTime.Now;
  517. // 两小时前
  518. var fmNowSubtract = fmNow.AddMinutes(-fmNow.Minute).AddSeconds(-fmNow.Second).AddMilliseconds(-fmNow.Millisecond);
  519. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(fmNowSubtract).ToString()[..10];
  520. // 统计开始时间
  521. var statStartTime = fmNowSubtract.AddHours(-2);
  522. // 统计结束时间
  523. var statEndTime = fmNowSubtract;
  524. var isFetalMovementExisted = await _deviceCacheMgr.FetalMovementIsExistedAsync(imeiDel, fetalMovementSampleTime);
  525. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 开始");
  526. if (!isFetalMovementExisted)
  527. {
  528. /// 开始计算
  529. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate <= statEndTime)
  530. .OrderByDescending(i => i.LastUpdate)
  531. .Select(i => i.LastUpdate)
  532. .ToList();
  533. // 判断是否有持续佩戴
  534. if (phrRange.Count >= 2)
  535. {
  536. // 读取胎心数据
  537. GeneralParam param = new()
  538. {
  539. Filters = new List<QueryFilterCondition>
  540. {
  541. new ()
  542. {
  543. Key=nameof(HisGpsFetalHeartRate.Serialno),
  544. Value=imeiDel,
  545. ValueType=QueryValueTypeEnum.String,
  546. Operator=QueryOperatorEnum.Equal
  547. },
  548. //new ()
  549. //{
  550. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  551. // Value=sampleTime,
  552. // ValueType=QueryValueTypeEnum.String,
  553. // Operator=QueryOperatorEnum.GreaterEqual
  554. //},
  555. },
  556. OrderBys = new List<OrderByCondition>
  557. {
  558. new (){
  559. IsDesc=true,
  560. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  561. }
  562. }
  563. };
  564. var fetalHeartRateIsAbnormal = 0;
  565. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  566. // 胎心数据时间与胎动时间一致
  567. var time = long.Parse(fhr.SampleTime.Length < 13 ? fhr.SampleTime.PadRight(13, '0') : fhr.SampleTime);
  568. var fhrSampleTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(time);
  569. // 胎心数据时间与胎动时间一致,最后一条胎心数据与胎动数据的小时差不大于2
  570. if ((DateTime.Now.Hour - fhrSampleTime.Hour) <= 2)
  571. {
  572. var duringMins = Math.Abs((phrRange.First() - phrRange.Last()).TotalMinutes);
  573. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  574. bool isInTimeRanges = IsLastUpdateInTimeRanges(phrRange.First());
  575. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  576. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  577. {
  578. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  579. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  580. .Where(i =>
  581. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  582. i.PregnancyPeriod[1] >= pregnancyWeeks)
  583. .Select(i => i.MedianMovement)
  584. .FirstOrDefault()
  585. :
  586. fetalMovementMap
  587. .Where(i =>
  588. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  589. i.PregnancyPeriod[1] >= pregnancyWeeks)
  590. .Select(i => i.InitialMovement)
  591. .FirstOrDefault()
  592. ;
  593. var fetalMovementValue = (fetalMovementMapValue * duringMins * 2) / 120;
  594. // 四舍五入
  595. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  596. // _logger.LogInformation($"{imeiDel} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");
  597. #region 生理健康与胎动的关系
  598. /// (步数)运动步数超过1500步则加1;
  599. /// (体温)低烧则胎动减1,高烧胎动减2;低烧是37.3~38.5,38.6以上是高烧。
  600. /// (血压)血压收缩压大于160则加1。
  601. /// (心理)心理压力高加2,压力中加1;
  602. var fetalMovementStepVar = 0;
  603. var fetalMovementTempVar = 0;
  604. var fetalMovementBpVar = 0;
  605. var fetalMovementPpVar = 0;
  606. var fetalMovementFhrVar = 0;
  607. // 步数
  608. if (true)
  609. {
  610. var step = await _personCacheMgr.GetStepPeriodicityAsync(imeiDel);
  611. if (step != null)
  612. {
  613. if (DateTime.Now.Hour - ((DateTime)step?.LastUpdate!).Hour <= 2)
  614. {
  615. if (step.Steps > 1500) fetalMovementStepVar = 1;
  616. }
  617. else
  618. {
  619. _logger.LogWarning($"{imeiDel} 周期步数 时间无效");
  620. }
  621. }
  622. else
  623. {
  624. _logger.LogWarning($"{imeiDel} 周期步数无数据");
  625. }
  626. }
  627. // 体温
  628. if (true)
  629. {
  630. var temp = await _personCacheMgr.GetTemperaturePeriodicityAsync(imeiDel);
  631. if (temp != null)
  632. {
  633. if (DateTime.Now.Hour - ((DateTime)temp?.LastUpdate!).Hour <= 2)
  634. {
  635. // 中烧
  636. if (temp.Temperature >= 37.3M && temp.Temperature <= 38.5M)
  637. {
  638. fetalMovementTempVar = -1;
  639. }
  640. // 高烧
  641. if (temp.Temperature >= 38.6M)
  642. {
  643. fetalMovementTempVar = -2;
  644. }
  645. }
  646. else
  647. {
  648. _logger.LogWarning($"{imeiDel} 周期体温 时间无效");
  649. }
  650. }
  651. else
  652. {
  653. _logger.LogWarning($"{imeiDel} 周期体温无数据");
  654. }
  655. }
  656. // 血压
  657. if (true)
  658. {
  659. var bp = await _personCacheMgr.GetBloodPressPeriodicityAsync(imeiDel);
  660. if (bp != null)
  661. {
  662. if (DateTime.Now.Hour - ((DateTime)bp?.LastUpdate!).Hour <= 2)
  663. {
  664. if (bp.SystolicValue > 160)
  665. {
  666. fetalMovementBpVar = 1;
  667. }
  668. }
  669. else
  670. {
  671. _logger.LogWarning($"{imeiDel} 周期血压 时间无效");
  672. }
  673. }
  674. else
  675. {
  676. _logger.LogWarning($"{imeiDel} 周期血压无数据");
  677. }
  678. }
  679. // 心理
  680. if (true)
  681. {
  682. //-1 不处理,
  683. //0 正常,
  684. //1 轻度,
  685. //2 中度;
  686. //3 重度;
  687. GeneralParam psychResultParam = new()
  688. {
  689. Filters = new List<QueryFilterCondition>
  690. {
  691. new ()
  692. {
  693. Key=nameof(HisGpsPsychResult.Serialno),
  694. Value=imeiDel,
  695. ValueType=QueryValueTypeEnum.String,
  696. Operator=QueryOperatorEnum.Equal
  697. },
  698. //new ()
  699. //{
  700. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  701. // Value=sampleTime,
  702. // ValueType=QueryValueTypeEnum.String,
  703. // Operator=QueryOperatorEnum.GreaterEqual
  704. //},
  705. },
  706. OrderBys = new List<OrderByCondition>
  707. {
  708. new (){
  709. IsDesc=true,
  710. Key=nameof(HisGpsPsychResult.Serialno)
  711. }
  712. }
  713. };
  714. var psych = await _hisPsychResultApiClient.GetFirstAsync(psychResultParam, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  715. if (psych != null)
  716. {
  717. if (psych?.StressScore == 2)
  718. {
  719. fetalMovementPpVar = 1;
  720. }
  721. if (psych?.StressScore == 3)
  722. {
  723. fetalMovementPpVar = 2;
  724. }
  725. }
  726. else
  727. {
  728. _logger.LogWarning($"{imeiDel} 周期心理压力无数据");
  729. }
  730. }
  731. #endregion
  732. #region 胎心与胎动的关系
  733. /// 胎心值过缓时,则胎动数量减1;胎心值过速时,则胎动也加1。
  734. /// 此值允许在上限值上继续增加,在下限值上继续减少,最小值为0。
  735. /// 告警上限阀值
  736. //1表示偏高;2表示偏低
  737. if (true)
  738. {
  739. if (fhr.IsAbnormal == 2)
  740. {
  741. fetalMovementPpVar = -1;
  742. }
  743. if (fhr.IsAbnormal == 1)
  744. {
  745. fetalMovementPpVar = 1;
  746. }
  747. }
  748. #endregion
  749. _logger.LogInformation($"{imeiDel} 原始胎动值:{fetalMovementValue}, 步数参数变动值:{fetalMovementStepVar},体温参数变动值:{fetalMovementTempVar},血压参数变动值:{fetalMovementBpVar},心理压力参数变动值:{fetalMovementPpVar},胎心参数变动值:{fetalMovementFhrVar}");
  750. fetalMovementValue = fetalMovementValue + fetalMovementStepVar + fetalMovementTempVar + fetalMovementBpVar + fetalMovementPpVar + fetalMovementFhrVar;
  751. _logger.LogInformation($"{imeiDel} 孕周:{pregnancyWeeks},胎动数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 原始胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{phrRange.Last()}-{phrRange.First()}, 胎动计算值:{fetalMovementValue}, 胎动最终值:{fetalMovement} 已完成.");
  752. // 获取胎心数据状态与胎动数据状态一致
  753. //etalHeartRateIsAbnormal= fhr.IsAbnormal;
  754. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  755. await _serviceIotApi.SetFetalMovementConfig(imeiDel, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  756. // 保存到MySQL数据库
  757. HisGpsFetalMovement fm = new()
  758. {
  759. FetalMovementId = Guid.NewGuid().ToString("D"),
  760. PersonId = commonPHR!.PersonId,
  761. Serialno = imeiDel,
  762. CreateTime = DateTime.Now,
  763. IsAbnormal = feltalMovementIsAbnormal,
  764. FetalMovementValue = fetalMovement,
  765. SampleTime = fetalMovementSampleTime,
  766. Method = 1,
  767. IsDisplay = 1,
  768. DeviceKey = commonPHR!.DeviceKey
  769. };
  770. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  771. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(imeiDel).ConfigureAwait(false);
  772. var fmMsgId = $"{imeiDel}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  773. var fmMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  774. // 胎动数据推送到第三方
  775. var topic = "topic.push.third";
  776. var fmThridMsg = new
  777. {
  778. messageId = fmMsgId,
  779. topic = topic,
  780. time = fmMsgTime,
  781. data = new
  782. {
  783. imei = imeiDel,
  784. value = fetalMovement,
  785. isAbnormal = feltalMovementIsAbnormal,
  786. type = "fetalMovement"
  787. }
  788. };
  789. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, 31, fmThridMsg).ConfigureAwait(false);
  790. // 胎动数据推送到微信
  791. if (feltalMovementIsAbnormal != 0)
  792. {
  793. topic = "topic.push.wx";
  794. var fmMsg = new
  795. {
  796. messageId = Guid.NewGuid().ToString("D"),
  797. topic = topic,
  798. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
  799. data = new
  800. {
  801. deviceId = device?.DeviceId,
  802. imei = imeiDel,
  803. alarmTypeId = 12,
  804. alarmDeviceName = imeiDel,
  805. alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
  806. address = string.Empty,
  807. deviceKey = device?.DeviceId
  808. }
  809. };
  810. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
  811. }
  812. // 设置入库缓存记录
  813. await _deviceCacheMgr.SetFetalMovementAsync(imeiDel, fetalMovementSampleTime, fm);
  814. }
  815. else
  816. {
  817. _logger.LogWarning($"{imeiDel} 孕周 {pregnancyWeeks},超出胎动计算范围");
  818. }
  819. }
  820. else
  821. {
  822. _logger.LogWarning($"{imeiDel} 最后一条胎心数据与胎动数据的小时差大于2,不计算胎动数据");
  823. }
  824. }
  825. else
  826. {
  827. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 不足两条,不能判断是否持续佩戴");
  828. }
  829. }
  830. else
  831. {
  832. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 已处理");
  833. }
  834. }
  835. }
  836. }
  837. */
  838. #endregion
  839. #region 胎动延时计算(使用线程再延时)
  840. /**
  841. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = $"FM-{imeiDel}-{DateTime.Now.ToString("yyyyMMddHHmmss")}" }))
  842. {
  843. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  844. _logger.LogInformation($"触发胎动计算,设备配置{JsonConvert.SerializeObject(watchConfig)}");
  845. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  846. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! : 60;
  847. if (isFetalHeartEnable)
  848. {
  849. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  850. // 已经建模
  851. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  852. if (commonPHR != null)
  853. {
  854. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  855. _logger.LogInformation($"{imeiDel} 计算胎动数据 ");
  856. var fmNow = DateTime.Now;
  857. // 两小时前
  858. var fmNowSubtract = fmNow.AddMinutes(-fmNow.Minute).AddSeconds(-fmNow.Second).AddMilliseconds(-fmNow.Millisecond);
  859. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(fmNowSubtract).ToString()[..10];
  860. // 统计开始时间
  861. var statStartTime = fmNowSubtract.AddHours(-2);
  862. // 统计结束时间
  863. var statEndTime = fmNowSubtract;
  864. Thread thread = new(async () => {
  865. try
  866. {
  867. #region 休眠65分钟
  868. var startTime = DateTime.Now;
  869. //var highFreqSampleInterval2 = (int)watchConfig!["highFreqSampleInterval"]!+5;
  870. var highFreqSampleInterval2 = 65*60;
  871. var during = TimeSpan.FromSeconds(highFreqSampleInterval2);
  872. while (true)
  873. {
  874. if (DateTime.Now - startTime > during)
  875. {
  876. break;
  877. }
  878. await Task.Delay(TimeSpan.FromSeconds(1));
  879. }
  880. #endregion
  881. //var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel,1);
  882. //// 去除高频
  883. //var normalPhr = GetNonFreqPregnancyHeartRate(daysPhr, highFreqSampleInterval).OrderByDescending(i => i.LastUpdate);
  884. //// 常规最后一条
  885. //var lastNormalPhr = normalPhr.First();
  886. //statEndTime = lastNormalPhr.LastUpdate;
  887. PregnancyHeartRateModel lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(imeiDel);
  888. statEndTime = lastPhr.LastUpdate;
  889. #region 计算
  890. var isFetalMovementExisted = await _deviceCacheMgr.FetalMovementIsExistedAsync(imeiDel, fetalMovementSampleTime);
  891. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 开始");
  892. if (!isFetalMovementExisted)
  893. {
  894. /// 开始计算
  895. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate <= statEndTime)
  896. .OrderByDescending(i => i.LastUpdate)
  897. .Select(i => i.LastUpdate)
  898. .ToList();
  899. // 判断是否有持续佩戴
  900. if (phrRange.Count >= 2)
  901. {
  902. // 读取胎心数据
  903. GeneralParam param = new()
  904. {
  905. Filters = new List<QueryFilterCondition>
  906. {
  907. new ()
  908. {
  909. Key=nameof(HisGpsFetalHeartRate.Serialno),
  910. Value=imeiDel,
  911. ValueType=QueryValueTypeEnum.String,
  912. Operator=QueryOperatorEnum.Equal
  913. },
  914. //new ()
  915. //{
  916. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  917. // Value=sampleTime,
  918. // ValueType=QueryValueTypeEnum.String,
  919. // Operator=QueryOperatorEnum.GreaterEqual
  920. //},
  921. },
  922. OrderBys = new List<OrderByCondition>
  923. {
  924. new (){
  925. IsDesc=true,
  926. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  927. }
  928. }
  929. };
  930. var fetalHeartRateIsAbnormal = 0;
  931. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  932. // 胎心数据时间与胎动时间一致
  933. var time = long.Parse(fhr.SampleTime.Length < 13 ? fhr.SampleTime.PadRight(13, '0') : fhr.SampleTime);
  934. var fhrSampleTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(time);
  935. // 胎心数据时间与胎动时间一致,最后一条胎心数据与胎动数据的小时差不大于2
  936. if ((DateTime.Now.Hour - fhrSampleTime.Hour) <= 4)
  937. {
  938. var duringMins = Math.Abs((phrRange.First() - phrRange.Last()).TotalMinutes);
  939. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  940. bool isInTimeRanges = IsLastUpdateInTimeRanges(phrRange.First());
  941. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  942. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  943. {
  944. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  945. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  946. .Where(i =>
  947. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  948. i.PregnancyPeriod[1] >= pregnancyWeeks)
  949. .Select(i => i.MedianMovement)
  950. .FirstOrDefault()
  951. :
  952. fetalMovementMap
  953. .Where(i =>
  954. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  955. i.PregnancyPeriod[1] >= pregnancyWeeks)
  956. .Select(i => i.InitialMovement)
  957. .FirstOrDefault()
  958. ;
  959. var fetalMovementValue = (fetalMovementMapValue * duringMins * 2) / 120;
  960. // 四舍五入
  961. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  962. // _logger.LogInformation($"{imeiDel} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");
  963. #region 生理健康与胎动的关系
  964. /// (步数)运动步数超过1500步则加1;
  965. /// (体温)低烧则胎动减1,高烧胎动减2;低烧是37.3~38.5,38.6以上是高烧。
  966. /// (血压)血压收缩压大于160则加1。
  967. /// (心理)心理压力高加2,压力中加1;
  968. var fetalMovementStepVar = 0;
  969. var fetalMovementTempVar = 0;
  970. var fetalMovementBpVar = 0;
  971. var fetalMovementPpVar = 0;
  972. var fetalMovementFhrVar = 0;
  973. // 步数
  974. if (true)
  975. {
  976. var step = await _personCacheMgr.GetStepPeriodicityAsync(imeiDel);
  977. if (step != null)
  978. {
  979. if (DateTime.Now.Hour - ((DateTime)step?.LastUpdate!).Hour <= 2)
  980. {
  981. if (step.Steps > 1500) fetalMovementStepVar = 1;
  982. }
  983. else
  984. {
  985. _logger.LogWarning($"{imeiDel} 周期步数 时间无效");
  986. }
  987. }
  988. else
  989. {
  990. _logger.LogWarning($"{imeiDel} 周期步数无数据");
  991. }
  992. }
  993. // 体温
  994. if (true)
  995. {
  996. var temp = await _personCacheMgr.GetTemperaturePeriodicityAsync(imeiDel);
  997. if (temp != null)
  998. {
  999. if (DateTime.Now.Hour - ((DateTime)temp?.LastUpdate!).Hour <= 2)
  1000. {
  1001. // 中烧
  1002. if (temp.Temperature >= 37.3M && temp.Temperature <= 38.5M)
  1003. {
  1004. fetalMovementTempVar = -1;
  1005. }
  1006. // 高烧
  1007. if (temp.Temperature >= 38.6M)
  1008. {
  1009. fetalMovementTempVar = -2;
  1010. }
  1011. }
  1012. else
  1013. {
  1014. _logger.LogWarning($"{imeiDel} 周期体温 时间无效");
  1015. }
  1016. }
  1017. else
  1018. {
  1019. _logger.LogWarning($"{imeiDel} 周期体温无数据");
  1020. }
  1021. }
  1022. // 血压
  1023. if (true)
  1024. {
  1025. var bp = await _personCacheMgr.GetBloodPressPeriodicityAsync(imeiDel);
  1026. if (bp != null)
  1027. {
  1028. if (DateTime.Now.Hour - ((DateTime)bp?.LastUpdate!).Hour <= 2)
  1029. {
  1030. if (bp.SystolicValue > 160)
  1031. {
  1032. fetalMovementBpVar = 1;
  1033. }
  1034. }
  1035. else
  1036. {
  1037. _logger.LogWarning($"{imeiDel} 周期血压 时间无效");
  1038. }
  1039. }
  1040. else
  1041. {
  1042. _logger.LogWarning($"{imeiDel} 周期血压无数据");
  1043. }
  1044. }
  1045. // 心理
  1046. if (true)
  1047. {
  1048. //-1 不处理,
  1049. //0 正常,
  1050. //1 轻度,
  1051. //2 中度;
  1052. //3 重度;
  1053. GeneralParam psychResultParam = new()
  1054. {
  1055. Filters = new List<QueryFilterCondition>
  1056. {
  1057. new ()
  1058. {
  1059. Key=nameof(HisGpsPsychResult.Serialno),
  1060. Value=imeiDel,
  1061. ValueType=QueryValueTypeEnum.String,
  1062. Operator=QueryOperatorEnum.Equal
  1063. },
  1064. //new ()
  1065. //{
  1066. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  1067. // Value=sampleTime,
  1068. // ValueType=QueryValueTypeEnum.String,
  1069. // Operator=QueryOperatorEnum.GreaterEqual
  1070. //},
  1071. },
  1072. OrderBys = new List<OrderByCondition>
  1073. {
  1074. new (){
  1075. IsDesc=true,
  1076. Key=nameof(HisGpsPsychResult.Serialno)
  1077. }
  1078. }
  1079. };
  1080. var psych = await _hisPsychResultApiClient.GetFirstAsync(psychResultParam, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  1081. if (psych != null)
  1082. {
  1083. if (psych?.StressScore == 2)
  1084. {
  1085. fetalMovementPpVar = 1;
  1086. }
  1087. if (psych?.StressScore == 3)
  1088. {
  1089. fetalMovementPpVar = 2;
  1090. }
  1091. }
  1092. else
  1093. {
  1094. _logger.LogWarning($"{imeiDel} 周期心理压力无数据");
  1095. }
  1096. }
  1097. #endregion
  1098. #region 胎心与胎动的关系
  1099. /// 胎心值过缓时,则胎动数量减1;胎心值过速时,则胎动也加1。
  1100. /// 此值允许在上限值上继续增加,在下限值上继续减少,最小值为0。
  1101. /// 告警上限阀值
  1102. //1表示偏高;2表示偏低
  1103. if (true)
  1104. {
  1105. if (fhr.IsAbnormal == 2)
  1106. {
  1107. fetalMovementPpVar = -1;
  1108. }
  1109. if (fhr.IsAbnormal == 1)
  1110. {
  1111. fetalMovementPpVar = 1;
  1112. }
  1113. }
  1114. #endregion
  1115. _logger.LogInformation($"{imeiDel} 原始胎动值:{fetalMovementValue}, 步数参数变动值:{fetalMovementStepVar},体温参数变动值:{fetalMovementTempVar},血压参数变动值:{fetalMovementBpVar},心理压力参数变动值:{fetalMovementPpVar},胎心参数变动值:{fetalMovementFhrVar}");
  1116. fetalMovementValue = fetalMovementValue + fetalMovementStepVar + fetalMovementTempVar + fetalMovementBpVar + fetalMovementPpVar + fetalMovementFhrVar;
  1117. _logger.LogInformation($"{imeiDel} 孕周:{pregnancyWeeks},胎动数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 原始胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{phrRange.Last()}-{phrRange.First()}, 胎动计算值:{fetalMovementValue}, 胎动最终值:{fetalMovement} 已完成.");
  1118. // 获取胎心数据状态与胎动数据状态一致
  1119. //etalHeartRateIsAbnormal= fhr.IsAbnormal;
  1120. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  1121. await _serviceIotApi.SetFetalMovementConfig(imeiDel, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  1122. // 保存到MySQL数据库
  1123. HisGpsFetalMovement fm = new()
  1124. {
  1125. FetalMovementId = Guid.NewGuid().ToString("D"),
  1126. PersonId = commonPHR!.PersonId,
  1127. Serialno = imeiDel,
  1128. CreateTime = DateTime.Now,
  1129. IsAbnormal = feltalMovementIsAbnormal,
  1130. FetalMovementValue = fetalMovement,
  1131. SampleTime = fetalMovementSampleTime,
  1132. Method = 1,
  1133. IsDisplay = 1,
  1134. DeviceKey = commonPHR!.DeviceKey
  1135. };
  1136. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  1137. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(imeiDel).ConfigureAwait(false);
  1138. var fmMsgId = $"{imeiDel}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  1139. var fmMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  1140. // 胎动数据推送到第三方
  1141. var topic = "topic.push.third";
  1142. var fmThridMsg = new
  1143. {
  1144. messageId = fmMsgId,
  1145. topic = topic,
  1146. time = fmMsgTime,
  1147. data = new
  1148. {
  1149. imei = imeiDel,
  1150. value = fetalMovement,
  1151. isAbnormal = feltalMovementIsAbnormal,
  1152. type = "fetalMovement"
  1153. }
  1154. };
  1155. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, 31, fmThridMsg).ConfigureAwait(false);
  1156. // 胎动数据推送到微信
  1157. if (feltalMovementIsAbnormal != 0)
  1158. {
  1159. topic = "topic.push.wx";
  1160. var fmMsg = new
  1161. {
  1162. messageId = Guid.NewGuid().ToString("D"),
  1163. topic = topic,
  1164. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
  1165. data = new
  1166. {
  1167. deviceId = device?.DeviceId,
  1168. imei = imeiDel,
  1169. alarmTypeId = 12,
  1170. alarmDeviceName = imeiDel,
  1171. alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
  1172. address = string.Empty,
  1173. deviceKey = device?.DeviceId
  1174. }
  1175. };
  1176. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
  1177. }
  1178. // 设置入库缓存记录
  1179. await _deviceCacheMgr.SetFetalMovementAsync(imeiDel, fetalMovementSampleTime, fm);
  1180. }
  1181. else
  1182. {
  1183. _logger.LogWarning($"{imeiDel} 孕周 {pregnancyWeeks},超出胎动计算范围");
  1184. }
  1185. }
  1186. else
  1187. {
  1188. _logger.LogWarning($"{imeiDel} 最后一条胎心数据与胎动数据的小时差大于2,不计算胎动数据");
  1189. }
  1190. }
  1191. else
  1192. {
  1193. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 不足两条,不能判断是否持续佩戴");
  1194. }
  1195. }
  1196. else
  1197. {
  1198. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 已处理");
  1199. }
  1200. #endregion
  1201. }
  1202. catch (Exception ex)
  1203. {
  1204. _logger.LogError($"处理延时计算胎动数据异常:{ex.Message}, {ex.StackTrace}");
  1205. }
  1206. });
  1207. thread.Start();
  1208. }
  1209. }
  1210. }
  1211. */
  1212. #endregion
  1213. #region 胎动延时计算(实时now是3小时,计算 lastupdate 0~2范围的数据,)
  1214. ///实时now的hour是3小时,计算 lastupdate 0~2范围的数据,
  1215. ///只在 HOUR = new int[] { 1, 3, 5, 7, 9, 11,13, 15, 17, 19, 21, 23 };是奇数
  1216. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = $"FM-{imeiDel}-{DateTime.Now.ToString("yyyyMMddHHmmss")}" }))
  1217. {
  1218. try
  1219. {
  1220. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  1221. _logger.LogInformation($"触发胎动计算,设备配置{JsonConvert.SerializeObject(watchConfig)}");
  1222. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  1223. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! : 60;
  1224. if (isFetalHeartEnable)
  1225. {
  1226. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  1227. // 已经建模
  1228. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  1229. if (commonPHR != null)
  1230. {
  1231. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  1232. _logger.LogInformation($"{imeiDel} 计算胎动数据 ");
  1233. DateTime fmNow = DateTime.Now;
  1234. int fmNowHour = fmNow.Hour;
  1235. DateTime statStartTime;
  1236. DateTime statEndTime;
  1237. if (fmNowHour == 1)
  1238. {
  1239. // last_update 22~0
  1240. statStartTime = fmNow.Date.AddDays(-1).AddHours(22);
  1241. statEndTime = fmNow.Date;
  1242. }
  1243. else
  1244. {
  1245. statStartTime = fmNow.Date.AddHours(fmNowHour - 3);
  1246. statEndTime = fmNow.Date.AddHours(fmNowHour - 1);
  1247. }
  1248. _logger.LogInformation($"{imeiDel} 胎动统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1249. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(statEndTime).ToString()[..10];
  1250. var isFetalMovementExisted = await _deviceCacheMgr.FetalMovementIsExistedAsync(imeiDel, fetalMovementSampleTime);
  1251. if (!isFetalMovementExisted)
  1252. {
  1253. /// 开始计算
  1254. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate <= statEndTime)
  1255. .OrderByDescending(i => i.LastUpdate)
  1256. .Select(i => i.LastUpdate)
  1257. .ToList();
  1258. // 判断是否有持续佩戴
  1259. if (phrRange.Count >= 2)
  1260. {
  1261. // 读取胎心数据
  1262. GeneralParam param = new()
  1263. {
  1264. Filters = new List<QueryFilterCondition>
  1265. {
  1266. new ()
  1267. {
  1268. Key=nameof(HisGpsFetalHeartRate.Serialno),
  1269. Value=imeiDel,
  1270. ValueType=QueryValueTypeEnum.String,
  1271. Operator=QueryOperatorEnum.Equal
  1272. },
  1273. //new ()
  1274. //{
  1275. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  1276. // Value=sampleTime,
  1277. // ValueType=QueryValueTypeEnum.String,
  1278. // Operator=QueryOperatorEnum.GreaterEqual
  1279. //},
  1280. },
  1281. OrderBys = new List<OrderByCondition>
  1282. {
  1283. new (){
  1284. IsDesc=true,
  1285. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  1286. }
  1287. }
  1288. };
  1289. var fetalHeartRateIsAbnormal = 0;
  1290. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  1291. // 胎心数据时间与胎动时间一致
  1292. var time = long.Parse(fhr.SampleTime.Length < 13 ? fhr.SampleTime.PadRight(13, '0') : fhr.SampleTime);
  1293. var fhrSampleTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(time);
  1294. // 胎心数据时间与胎动时间一致,最后一条胎心数据与胎动数据的小时差不大于3
  1295. if ((DateTime.Now.Hour - fhrSampleTime.Hour) <= 3)
  1296. {
  1297. var duringMins = Math.Abs((phrRange.First() - phrRange.Last()).TotalMinutes);
  1298. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  1299. bool isInTimeRanges = IsLastUpdateInTimeRanges(phrRange.First());
  1300. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  1301. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  1302. {
  1303. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  1304. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  1305. .Where(i =>
  1306. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  1307. i.PregnancyPeriod[1] >= pregnancyWeeks)
  1308. .Select(i => i.MedianMovement)
  1309. .FirstOrDefault()
  1310. :
  1311. fetalMovementMap
  1312. .Where(i =>
  1313. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  1314. i.PregnancyPeriod[1] >= pregnancyWeeks)
  1315. .Select(i => i.InitialMovement)
  1316. .FirstOrDefault()
  1317. ;
  1318. var fetalMovementTimeVar = (fetalMovementMapValue * duringMins * 2) / 120;
  1319. //// 四舍五入
  1320. //var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  1321. // _logger.LogInformation($"{imeiDel} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");
  1322. #region 生理健康与胎动的关系
  1323. /// (步数)运动步数超过1500步则加1;
  1324. /// (体温)低烧则胎动减1,高烧胎动减2;低烧是37.3~38.5,38.6以上是高烧。
  1325. /// (血压)血压收缩压大于160则加1。
  1326. /// (心理)心理压力高加2,压力中加1;
  1327. var fetalMovementStepVar = 0;
  1328. var fetalMovementTempVar = 0;
  1329. var fetalMovementBpVar = 0;
  1330. var fetalMovementPpVar = 0;
  1331. var fetalMovementFhrVar = 0;
  1332. // 步数
  1333. if (false)
  1334. {
  1335. var step = await _personCacheMgr.GetStepPeriodicityAsync(imeiDel);
  1336. if (step != null)
  1337. {
  1338. if (DateTime.Now.Hour - ((DateTime)step?.LastUpdate!).Hour <= 2)
  1339. {
  1340. if (step.Steps > 1500) fetalMovementStepVar = 1;
  1341. }
  1342. else
  1343. {
  1344. _logger.LogWarning($"{imeiDel} 周期步数 时间无效");
  1345. }
  1346. }
  1347. else
  1348. {
  1349. _logger.LogWarning($"{imeiDel} 周期步数无数据");
  1350. }
  1351. }
  1352. // 体温
  1353. if (true)
  1354. {
  1355. var temp = await _personCacheMgr.GetTemperaturePeriodicityAsync(imeiDel);
  1356. if (temp != null)
  1357. {
  1358. if (DateTime.Now.Hour - ((DateTime)temp?.LastUpdate!).Hour <= 2)
  1359. {
  1360. // 中烧
  1361. if (temp.Temperature >= 37.3M && temp.Temperature <= 38.5M)
  1362. {
  1363. fetalMovementTempVar = -1;
  1364. }
  1365. // 高烧
  1366. if (temp.Temperature >= 38.6M)
  1367. {
  1368. fetalMovementTempVar = -2;
  1369. }
  1370. }
  1371. else
  1372. {
  1373. _logger.LogWarning($"{imeiDel} 周期体温 时间无效");
  1374. }
  1375. }
  1376. else
  1377. {
  1378. _logger.LogWarning($"{imeiDel} 周期体温无数据");
  1379. }
  1380. }
  1381. // 血压
  1382. if (true)
  1383. {
  1384. var bp = await _personCacheMgr.GetBloodPressPeriodicityAsync(imeiDel);
  1385. if (bp != null)
  1386. {
  1387. if (DateTime.Now.Hour - ((DateTime)bp?.LastUpdate!).Hour <= 2)
  1388. {
  1389. if (bp.SystolicValue > 160)
  1390. {
  1391. fetalMovementBpVar = 1;
  1392. }
  1393. }
  1394. else
  1395. {
  1396. _logger.LogWarning($"{imeiDel} 周期血压 时间无效");
  1397. }
  1398. }
  1399. else
  1400. {
  1401. _logger.LogWarning($"{imeiDel} 周期血压无数据");
  1402. }
  1403. }
  1404. // 心理
  1405. if (false)
  1406. {
  1407. //-1 不处理,
  1408. //0 正常,
  1409. //1 轻度,
  1410. //2 中度;
  1411. //3 重度;
  1412. GeneralParam psychResultParam = new()
  1413. {
  1414. Filters = new List<QueryFilterCondition>
  1415. {
  1416. new ()
  1417. {
  1418. Key=nameof(HisGpsPsychResult.Serialno),
  1419. Value=imeiDel,
  1420. ValueType=QueryValueTypeEnum.String,
  1421. Operator=QueryOperatorEnum.Equal
  1422. },
  1423. //new ()
  1424. //{
  1425. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  1426. // Value=sampleTime,
  1427. // ValueType=QueryValueTypeEnum.String,
  1428. // Operator=QueryOperatorEnum.GreaterEqual
  1429. //},
  1430. },
  1431. OrderBys = new List<OrderByCondition>
  1432. {
  1433. new (){
  1434. IsDesc=true,
  1435. Key=nameof(HisGpsPsychResult.Serialno)
  1436. }
  1437. }
  1438. };
  1439. var psych = await _hisPsychResultApiClient.GetFirstAsync(psychResultParam, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  1440. if (psych != null)
  1441. {
  1442. if (psych?.StressScore == 2)
  1443. {
  1444. fetalMovementPpVar = 1;
  1445. }
  1446. if (psych?.StressScore == 3)
  1447. {
  1448. fetalMovementPpVar = 2;
  1449. }
  1450. }
  1451. else
  1452. {
  1453. _logger.LogWarning($"{imeiDel} 周期心理压力无数据");
  1454. }
  1455. }
  1456. #endregion
  1457. #region 胎心与胎动的关系
  1458. /// 胎心值过缓时,则胎动数量减1;胎心值过速时,则胎动也加1。
  1459. /// 此值允许在上限值上继续增加,在下限值上继续减少,最小值为0。
  1460. /// 告警上限阀值
  1461. //1表示偏高;2表示偏低
  1462. if (true)
  1463. {
  1464. if (fhr.IsAbnormal == 2)
  1465. {
  1466. fetalMovementPpVar = -1;
  1467. }
  1468. if (fhr.IsAbnormal == 1)
  1469. {
  1470. fetalMovementPpVar = 1;
  1471. }
  1472. }
  1473. #endregion
  1474. //var fetalMovementTimeVar = fetalMovementValue;
  1475. _logger.LogInformation($"{imeiDel} 时间比例胎动值:{fetalMovementTimeVar}, 步数参数变动值:{fetalMovementStepVar},体温参数变动值:{fetalMovementTempVar},血压参数变动值:{fetalMovementBpVar},心理压力参数变动值:{fetalMovementPpVar},胎心参数变动值:{fetalMovementFhrVar}");
  1476. var fetalMovementValue = fetalMovementTimeVar + fetalMovementStepVar + fetalMovementTempVar + fetalMovementBpVar + fetalMovementPpVar + fetalMovementFhrVar;
  1477. // 四舍五入
  1478. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  1479. _logger.LogInformation($"{imeiDel} 孕周:{pregnancyWeeks},胎动数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 时间比例胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{phrRange.Last()}-{phrRange.First()}, 胎动计算值:{fetalMovementTimeVar}, 胎动四舍五入最终值:{fetalMovement} 已完成.");
  1480. // 获取胎心数据状态与胎动数据状态一致
  1481. //etalHeartRateIsAbnormal= fhr.IsAbnormal;
  1482. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  1483. await _serviceIotApi.SetFetalMovementConfig(imeiDel, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  1484. // 保存到MySQL数据库
  1485. HisGpsFetalMovement fm = new()
  1486. {
  1487. FetalMovementId = Guid.NewGuid().ToString("D"),
  1488. PersonId = commonPHR!.PersonId,
  1489. Serialno = imeiDel,
  1490. CreateTime = DateTime.Now,
  1491. IsAbnormal = feltalMovementIsAbnormal,
  1492. FetalMovementValue = fetalMovement,
  1493. SampleTime = fetalMovementSampleTime,
  1494. Method = 1,
  1495. IsDisplay = 1,
  1496. DeviceKey = commonPHR!.DeviceKey
  1497. };
  1498. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  1499. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(imeiDel).ConfigureAwait(false);
  1500. var fmMsgId = $"{imeiDel}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  1501. var fmMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  1502. // 胎动数据推送到第三方
  1503. var topic = "topic.push.third";
  1504. var fmThridMsg = new
  1505. {
  1506. messageId = fmMsgId,
  1507. topic = topic,
  1508. time = fmMsgTime,
  1509. data = new
  1510. {
  1511. imei = imeiDel,
  1512. value = fetalMovement,
  1513. isAbnormal = feltalMovementIsAbnormal,
  1514. type = "fetalMovement"
  1515. }
  1516. };
  1517. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, 31, fmThridMsg).ConfigureAwait(false);
  1518. // 胎动数据推送到微信
  1519. if (feltalMovementIsAbnormal != 0)
  1520. {
  1521. topic = "topic.push.wx";
  1522. var fmMsg = new
  1523. {
  1524. messageId = Guid.NewGuid().ToString("D"),
  1525. topic = topic,
  1526. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
  1527. data = new
  1528. {
  1529. deviceId = device?.DeviceId,
  1530. imei = imeiDel,
  1531. alarmTypeId = 12,
  1532. alarmDeviceName = imeiDel,
  1533. alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
  1534. address = string.Empty,
  1535. deviceKey = device?.DeviceId
  1536. }
  1537. };
  1538. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
  1539. }
  1540. // 设置入库缓存记录
  1541. await _deviceCacheMgr.SetFetalMovementAsync(imeiDel, fetalMovementSampleTime, fm);
  1542. }
  1543. else
  1544. {
  1545. _logger.LogWarning($"{imeiDel} 孕周 {pregnancyWeeks},超出胎动计算范围");
  1546. }
  1547. }
  1548. else
  1549. {
  1550. _logger.LogWarning($"{imeiDel} 最后一条胎心数据与胎动数据的小时差大于2,不计算胎动数据");
  1551. }
  1552. }
  1553. else
  1554. {
  1555. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 不足两条,不能判断是否持续佩戴");
  1556. }
  1557. }
  1558. else
  1559. {
  1560. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 已处理");
  1561. }
  1562. }
  1563. else
  1564. {
  1565. _logger.LogWarning($"{imeiDel} 没有胎心建模数据");
  1566. }
  1567. }
  1568. else
  1569. {
  1570. _logger.LogWarning($"{imeiDel} 胎心监测功能没有开启");
  1571. }
  1572. }
  1573. catch (Exception ex )
  1574. {
  1575. _logger.LogError($"{imeiDel} 计算胎动数据异常 {ex.Message}\n {ex.StackTrace}");
  1576. }
  1577. }
  1578. #endregion
  1579. }
  1580. else
  1581. {
  1582. // 处理血压业务
  1583. int systolicInc;
  1584. int diastolicInc;
  1585. int systolicRefValue;
  1586. int diastolicRefValue;
  1587. decimal systolicAvg;
  1588. decimal diastolicAvg;
  1589. int systolicMax = 0;
  1590. int diastolicMax = 0;
  1591. // 统计时间
  1592. //DateTime endTime = DateTime.Now; //测试
  1593. DateTime statStartTime = DateTime.Now;
  1594. // 最小值
  1595. int systolicMin = 0;
  1596. int diastolicMin = 0;
  1597. // 偏移参数
  1598. var avgOffset = 0.25M;
  1599. var systolicAvgOffset = avgOffset;
  1600. var diastolicAvgOffset = avgOffset;
  1601. // 最后一次下发值
  1602. int lastPushSystolicInc = 0;
  1603. int lastPushDiastolicInc = 0;
  1604. var startTime = DateTime.Now;
  1605. // 下发增量值
  1606. #region 统计定时下发增量值
  1607. //var last = await _serviceTDengine.GetLastAsync("stb_hm_bloodpress_stats_inc", $"serialno='{imeiDel}' order by last_update desc");
  1608. //var ts = last?[0];
  1609. // 最后一条血压数据
  1610. var condition = $"serialno='{imeiDel}' order by last_update desc";
  1611. var field = "last_row(*)";
  1612. var lastHmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition, field);
  1613. var lastHmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(lastHmBpResponse!);
  1614. var lastHmBp = lastHmBpParser?.Select().FirstOrDefault();
  1615. //if (lastHmBpParser?.Select()?.ToList().Count < 2)
  1616. //{
  1617. // _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 血压数据条目不足");
  1618. // break;
  1619. //}
  1620. // 7 天有效数据
  1621. if (lastHmBp?.Timestamp.AddDays(7) > DateTime.Now)
  1622. {
  1623. // 计算增量值
  1624. condition = $"serialno='{imeiDel}' order by ts desc";
  1625. var lastPushResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bp_push_ref_inc_value", condition, field);
  1626. if (lastPushResponse == null)
  1627. {
  1628. _logger.LogInformation($"{imeiDel}--没有下发记录");
  1629. break;
  1630. }
  1631. var lastPushParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressurePushRefIncModel>>(lastPushResponse);
  1632. var lastPush = lastPushParser!.Select().FirstOrDefault();
  1633. // 有下推记录
  1634. if (lastPush != null)
  1635. {
  1636. systolicRefValue = lastPush!.SystolicRefValue;
  1637. diastolicRefValue = lastPush!.DiastolicRefValue;
  1638. lastPushSystolicInc = lastPush!.SystolicIncValue;
  1639. lastPushDiastolicInc = lastPush!.DiastolicIncValue;
  1640. condition = $"ts between '{lastPush?.Timestamp:yyyy-MM-dd HH:mm:ss.fff}' and '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  1641. $"and serialno='{imeiDel}' " +
  1642. $"and is_display = true";
  1643. // 使用最近一次的下推时间作为统计的开始时间
  1644. statStartTime = lastPush!.Timestamp;
  1645. }
  1646. // 没有下推记录(历史遗留数据),没有初始的测量值产生的平均值(测量值=平均值)
  1647. else
  1648. {
  1649. #region 获取个人信息
  1650. var person = await _personCacheMgr.GetDeviceGpsPersonCacheBySerialNoAsync(Guid.NewGuid().ToString(), imeiDel).ConfigureAwait(false);
  1651. //验证这个信息是否存在
  1652. if (person == null || person?.Person.BornDate == null)
  1653. {
  1654. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证个人信息,找不到个人信息,跳过此消息");
  1655. break;
  1656. }
  1657. // 验证年龄是否在范围 (2 - 120)
  1658. var age = SafeType.SafeInt(DateTime.Today.Year - person?.Person.BornDate!.Value.Year!);
  1659. if (age < 2 || age > 120)
  1660. {
  1661. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证年龄,不在范围 (2 - 120)岁,跳过此消息");
  1662. break;
  1663. }
  1664. var gender = person?.Person.Gender == true ? 1 : 2;
  1665. var isHypertension = SafeType.SafeBool(person?.Person.Ishypertension!);
  1666. var height = SafeType.SafeDouble(person?.Person.Height!);
  1667. var weight = SafeType.SafeDouble(person?.Person.Weight!);
  1668. #endregion
  1669. #region 初始化常规血压标定值标定值
  1670. var bpRef = await _bpRefValCacheManager.GetBloodPressReferenceValueAsync(age, gender, isHypertension);
  1671. //systolicRefValue = bpRef!.Systolic;//?
  1672. //diastolicRefValue = bpRef!.Diastolic;//?
  1673. #endregion
  1674. systolicRefValue = bpRef!.Systolic;
  1675. diastolicRefValue = bpRef!.Diastolic;
  1676. lastPushSystolicInc = 0;
  1677. lastPushDiastolicInc = 0;
  1678. condition = $"ts <= '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  1679. $"and serialno='{imeiDel}' " +
  1680. $"and is_display = true";
  1681. }
  1682. var hmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition);
  1683. var hmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(hmBpResponse!);
  1684. var hmBp = hmBpParser?.Select();
  1685. //if (hmBp?.ToList().Count < 2)
  1686. // 1. 判断数据样本数量
  1687. if (hmBpParser!.Rows < 5)
  1688. {
  1689. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 统计定时下发,计算增量值的数据条目不足:{hmBpParser!.Rows} < 5");
  1690. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} 没有足够的数据样本,不会定时下发");
  1691. break;
  1692. }
  1693. // 没有下推记录重新计算统计时间
  1694. if (lastPush == null)
  1695. {
  1696. var firstHmBp = hmBpParser?.Select(i => i).OrderBy(i => i.Timestamp).FirstOrDefault();
  1697. statStartTime = firstHmBp!.Timestamp;
  1698. }
  1699. // GetSampleTime(systolicRefValue, hmBpParser);
  1700. // 最大值
  1701. //systolicMax = (int)hmBpParser?.Select(i => i.SystolicValue).Max()!;
  1702. //diastolicMax = (int)hmBpParser?.Select(i => i.DiastolicValue).Max()!;
  1703. //// 最小值
  1704. //systolicMin = (int)hmBpParser?.Select(i => i.SystolicValue).Min()!;
  1705. //diastolicMin = (int)hmBpParser?.Select(i => i.DiastolicValue).Min()!;
  1706. //systolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.SystolicValue, SafeType.SafeInt(systolicRefValue!)))!;
  1707. //diastolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.DiastolicValue, SafeType.SafeInt(diastolicRefValue!)))!;
  1708. var avgs = _serviceTDengine.AverageAfterRemovingOneMinMaxRef(hmBpParser!);
  1709. systolicAvg = avgs[0];
  1710. diastolicAvg = avgs[1];
  1711. // 2. 判断能否计算增量值
  1712. if (systolicAvg.Equals(0))
  1713. {
  1714. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算平均值" +
  1715. $"\n currentSystolicAvg:{systolicAvg} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  1716. $"\n currentDiastolicInc:{diastolicAvg} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  1717. _logger.LogInformation($"{imeiDel}--{nameof(Worker)} 没有足够的数据样本计算平均值,不会定时下发");
  1718. break;
  1719. }
  1720. // 除最大值和最小值后的平均值与标定值差值少于4后(当天计算出该结果则也不产生增量调整),就不再进行增量值调整了。
  1721. if (systolicRefValue - systolicAvg < 4)
  1722. {
  1723. _logger.LogInformation($"diastolic 舒张压 {imeiDel}除最大值和最小值后的平均值:{diastolicAvg}与标定值:{diastolicRefValue}\n systolic 收缩压 {imeiDel}除最大值和最小值后的平均值:{systolicAvg}与标定值:{systolicRefValue}的差值(标定值-平均值)少于4后,systolic 收缩压 不再进行增量值调整");
  1724. break;
  1725. }
  1726. if (diastolicRefValue - diastolicAvg < 4)
  1727. {
  1728. _logger.LogInformation($"systolic 收缩压 {imeiDel}除最大值和最小值后的平均值:{systolicAvg}与标定值:{systolicRefValue}\n diastolic 舒张压 {imeiDel}除最大值和最小值后的平均值:{diastolicAvg}与标定值:{diastolicRefValue}的差值(标定值-平均值)少于4后,diastolic 舒张压 不再进行增量值调整");
  1729. break;
  1730. }
  1731. // 增量值=(标定值-平均值)* 0.25
  1732. var currentSystolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
  1733. var currentDiastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
  1734. // 累计增量
  1735. systolicInc = currentSystolicInc + lastPushSystolicInc;
  1736. diastolicInc = currentDiastolicInc + lastPushDiastolicInc;
  1737. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算增量值" +
  1738. $"\n {imeiDel} -- systolicAvg:{systolicAvg}-- systolicInc:{systolicInc}-- currentSystolicInc:{currentSystolicInc} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  1739. $"\n {imeiDel} -- diastolicAvg:{diastolicAvg}-- diastolicInc:{diastolicInc} --currentDiastolicInc:{currentDiastolicInc} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  1740. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}-- 定时校准,发给设备的绝对增量值=(上次绝对增量值+新数据的增量值)");
  1741. _logger.LogInformation($"{nameof(Worker)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
  1742. if (_configBoodPressResolver.EnableBPRefPush)
  1743. // if (false) // 临时关闭
  1744. {
  1745. BloodPressCalibrationConfigModel bpIncData = new()
  1746. {
  1747. Imei = imeiDel,
  1748. SystolicRefValue = SafeType.SafeInt(((int)systolicRefValue!)), //收缩压标定值,值为0 表示不生效
  1749. DiastolicRefValue = SafeType.SafeInt(((int)diastolicRefValue!)), //舒张压标定值,值为0表示不生效
  1750. SystolicIncValue = SafeType.SafeInt(((int)systolicInc!)), //收缩压显示增量,值为0 表示不生效
  1751. DiastolicIncValue = SafeType.SafeInt(((int)diastolicInc!)) //舒张压显示增量,值为0 表示不生效
  1752. };
  1753. //var pushedBP = await _serviceIotApi.SetBloodPressCalibrationConfigAsync(bpIncData).ConfigureAwait(false);
  1754. var response = await _serviceIotApi.SetBloodPressCalibrationConfig2Async(bpIncData).ConfigureAwait(false);
  1755. var pushedBP = response.Flag;
  1756. if (pushedBP)
  1757. {
  1758. #region 保存下推记录 stb_hm_bp_push_ref_inc_value
  1759. var sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{imeiDel.Substring(imeiDel.Length - 2)} " +
  1760. $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
  1761. $"TAGS ('{imeiDel.Substring(imeiDel.Length - 2)}') " +
  1762. $"VALUES(" +
  1763. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  1764. $"'{imeiDel}'," +
  1765. $"{bpIncData.SystolicRefValue}," +
  1766. $"{bpIncData.DiastolicRefValue}," +
  1767. $"{bpIncData.SystolicIncValue}," +
  1768. $"{bpIncData.DiastolicIncValue}," +
  1769. $"{false}," +
  1770. $"{systolicAvg}," +
  1771. $"{diastolicAvg}," +
  1772. $"{systolicAvgOffset}," +
  1773. $"{diastolicAvgOffset}," +
  1774. $"'{statStartTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  1775. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'" +
  1776. $")";
  1777. _serviceTDengine.ExecuteInsertSQL(sql);
  1778. #endregion
  1779. #region 注册定时下发
  1780. // 注册下次下推
  1781. var endTime = DateTime.Now;
  1782. #if DEBUG
  1783. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  1784. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  1785. var interval = 0;
  1786. // 获取当前时间
  1787. DateTime now = DateTime.Now;
  1788. // 计算距离下一个$interval天后的8点的时间间隔
  1789. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  1790. TimeSpan timeUntilNextRun = nextRunTime - now;
  1791. // 如果当前时间已经超过了8点,将等待到明天后的8点
  1792. if (timeUntilNextRun < TimeSpan.Zero)
  1793. {
  1794. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  1795. nextRunTime += timeUntilNextRun;
  1796. }
  1797. // var ttl = timeUntilNextRun.TotalMilliseconds;
  1798. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  1799. var data = new
  1800. {
  1801. imei = imeiDel,
  1802. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1803. ttl,
  1804. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  1805. };
  1806. var result = JsonConvert.SerializeObject(data);
  1807. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  1808. #else
  1809. // 每$interval天,晚上8点
  1810. var interval = 1;
  1811. // 获取当前时间
  1812. DateTime now = DateTime.Now;
  1813. // 计算距离下一个$interval天后的8点的时间间隔
  1814. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 20, 0, 0).AddDays(interval);
  1815. TimeSpan timeUntilNextRun = nextRunTime - now;
  1816. // 如果当前时间已经超过了8点,将等待到明天后的8点
  1817. if (timeUntilNextRun < TimeSpan.Zero)
  1818. {
  1819. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  1820. nextRunTime += timeUntilNextRun;
  1821. }
  1822. // var ttl = timeUntilNextRun.TotalMilliseconds;
  1823. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  1824. var data = new
  1825. {
  1826. imei = imeiDel,
  1827. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1828. ttl,
  1829. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  1830. };
  1831. var result = JsonConvert.SerializeObject(data);
  1832. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  1833. #endif
  1834. #endregion
  1835. }
  1836. else
  1837. {
  1838. _logger.LogInformation($"错误响应,没有下推数据:{response.Message}");
  1839. }
  1840. }
  1841. }
  1842. else
  1843. {
  1844. _logger.LogInformation($"向{imeiDel}统计数据已经失效");
  1845. }
  1846. #endregion
  1847. }
  1848. }
  1849. break;
  1850. }
  1851. }
  1852. catch (Exception ex)
  1853. {
  1854. _logger.LogError($"{nameof(WatchEvents)},出错: |{ex.Message}|{ex.StackTrace}");
  1855. }
  1856. });
  1857. }
  1858. private async Task SetIntervalTriggerAsync(string key, string imei, long interval)
  1859. {
  1860. // var key = $"health_monitor/schedule_push/{type}/imei/{imei}";
  1861. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  1862. if (string.IsNullOrWhiteSpace(schedulePush))
  1863. {
  1864. var now = DateTime.Now;
  1865. var timeNextRun = now.Add(TimeSpan.FromSeconds(interval));
  1866. var data = new
  1867. {
  1868. imei,
  1869. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1870. ttl = interval,
  1871. next_run_time = timeNextRun.ToString("yyyy-MM-dd HH:mm:ss")
  1872. };
  1873. var result = JsonConvert.SerializeObject(data);
  1874. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  1875. }
  1876. }
  1877. public static bool IsNowInTimeRanges()
  1878. {
  1879. var now = DateTime.Now.TimeOfDay;
  1880. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  1881. {
  1882. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  1883. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  1884. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  1885. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  1886. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  1887. };
  1888. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  1889. }
  1890. public static bool IsLastUpdateInTimeRanges(DateTime lastUpdate)
  1891. {
  1892. var now = lastUpdate.TimeOfDay;
  1893. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  1894. {
  1895. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  1896. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  1897. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  1898. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  1899. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  1900. };
  1901. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  1902. }
  1903. private async Task SaveAndPushFetalHeartRateEndFreqHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int upperAlarmThreshold, int lowerAlarmThreshold, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  1904. {
  1905. // 计算胎心=孕妇心率*系数
  1906. /**
  1907. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  1908. fetalHeartRate = fetalHeartRate > 220 ? 220 : fetalHeartRate; // 胎心的最大值调整为220,超过都按该值220输出
  1909. if (fetalHeartRate >= 220)
  1910. {
  1911. // 先使用最小系数计算
  1912. var statMaxValueFprCoefficient = commonPHR?.StatMaxValueFprCoefficient!;
  1913. var statMinValueFprCoefficient = commonPHR?.StatMinValueFprCoefficient!;
  1914. var coefficient = statMaxValueFprCoefficient < statMinValueFprCoefficient ? statMaxValueFprCoefficient : statMinValueFprCoefficient;
  1915. fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  1916. if (fetalHeartRate < 220)
  1917. {
  1918. _logger.LogWarning($"{heartRate.Serialno} 使用极值系数 {coefficient} ,建模数据可能出现异常,请检查");
  1919. }
  1920. else
  1921. {
  1922. fetalHeartRate = 220;
  1923. _logger.LogWarning($"{heartRate.Serialno} 使用所有系数都不能放映实际,建模数据可能出现异常,请检查");
  1924. }
  1925. }
  1926. */
  1927. #region 胎心系数使用基于心率与中位数对比
  1928. var coefficient = 0f;
  1929. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  1930. if (heartRate.HeartRate < commonPHR!.Mode)
  1931. {
  1932. coefficient = commonPHR.StatMinValueFprCoefficient!;
  1933. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  1934. }
  1935. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  1936. else if (heartRate.HeartRate > commonPHR.Mode)
  1937. {
  1938. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  1939. {
  1940. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  1941. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  1942. }
  1943. else
  1944. {
  1945. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  1946. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  1947. }
  1948. }
  1949. else
  1950. {
  1951. coefficient = commonPHR.StatModeAvgFprCoefficient;
  1952. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  1953. }
  1954. #endregion
  1955. var fetalHeartRate = SafeType.SafeInt(heartRate.HeartRate! * coefficient);
  1956. // 胎心的最大值调整为220,超过都按该值220输出
  1957. fetalHeartRate = fetalHeartRate >= 220 ? 220 : fetalHeartRate;
  1958. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  1959. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  1960. if (phrFreqstatus == null) isAbnormal = 0;
  1961. var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  1962. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1963. //if (!isFreq)
  1964. //{
  1965. // statStartTime = heartRate.LastUpdate;
  1966. //
  1967. //}
  1968. // 保存到 数据服务 MySQL 数据库
  1969. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  1970. {
  1971. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  1972. PersonId = commonPHR!.PersonId,
  1973. Serialno = heartRate.Serialno,
  1974. HeartRate = fetalHeartRate,
  1975. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  1976. IsAbnormal = isAbnormal,
  1977. StatStartTime = statStartTime,
  1978. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  1979. CreateTime = DateTime.Now,
  1980. Method = 1,
  1981. IsDisplay = 1,
  1982. DeviceKey = commonPHR!.DeviceKey
  1983. };
  1984. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  1985. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  1986. // 推送最后一条常规心率计算的胎心数据到iot设备
  1987. #region 推送最后一条常规心率计算的胎心数据到iot设备
  1988. // 高频(<=12)-常规
  1989. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  1990. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  1991. {
  1992. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1993. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  1994. }
  1995. // 高频(13)-常规-高频(13)
  1996. if (phrFreqstatus != null)
  1997. {
  1998. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  1999. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  2000. // 获取高频数据
  2001. var freqCollection = new List<PregnancyHeartRateModel>();
  2002. PregnancyHeartRateModel? previousItem = null;
  2003. foreach (var item in phr)
  2004. {
  2005. if (previousItem != null)
  2006. {
  2007. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  2008. if (timeNextDiff <= 60)
  2009. {
  2010. freqCollection.Add(item);
  2011. }
  2012. }
  2013. // 高频最后一条
  2014. if (lastPhr.MessageId == item.MessageId)
  2015. {
  2016. freqCollection.Add(item);
  2017. }
  2018. previousItem = item;
  2019. }
  2020. //去除高频
  2021. foreach (var item in freqCollection)
  2022. {
  2023. phr.Remove(item);
  2024. }
  2025. lastPhr = phr.FirstOrDefault();
  2026. if (lastPhr?.MessageId == heartRate.MessageId)
  2027. {
  2028. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  2029. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  2030. }
  2031. }
  2032. #endregion
  2033. #region 高频心率计算胎心数据到iot设备
  2034. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  2035. if (phrFreqstatus != null && isAbnormal != 0)
  2036. {
  2037. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  2038. }
  2039. #endregion
  2040. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  2041. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  2042. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  2043. // 胎心数据推送到第三方
  2044. var topic = "topic.push.third";
  2045. var fhrThridMsg = new
  2046. {
  2047. messageId = fhrMsgId,
  2048. topic = topic,
  2049. time = fhrMsgTime,
  2050. data = new
  2051. {
  2052. imei = heartRate.Serialno,
  2053. value = fetalHeartRate,
  2054. isAbnormal,
  2055. type = "fetalHeart"
  2056. }
  2057. };
  2058. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  2059. // 胎心数据推送到微信
  2060. if (isAbnormal != 0)
  2061. {
  2062. topic = "topic.push.wx";
  2063. var fhrMsg = new
  2064. {
  2065. messageId = fhrMsgId,
  2066. topic = topic,
  2067. time = fhrMsgTime,
  2068. data = new
  2069. {
  2070. deviceId = device?.DeviceId,
  2071. imei = heartRate.Serialno,
  2072. alarmTypeId = 12,
  2073. alarmDeviceName = heartRate.Serialno,
  2074. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  2075. address = string.Empty,
  2076. deviceKey = device?.DeviceId
  2077. }
  2078. };
  2079. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  2080. }
  2081. }
  2082. private async Task SaveAndPushFetalHeartRateEndFreqHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int highFreqSampleTimes, int upperAlarmThreshold, int lowerAlarmThreshold, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  2083. {
  2084. // 计算胎心=孕妇心率*系数
  2085. #region 胎心系数使用基于心率与中位数对比
  2086. var coefficient = 0f;
  2087. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  2088. if (heartRate.HeartRate < commonPHR!.Mode)
  2089. {
  2090. coefficient = commonPHR.StatMinValueFprCoefficient!;
  2091. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  2092. }
  2093. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  2094. else if (heartRate.HeartRate > commonPHR.Mode)
  2095. {
  2096. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  2097. {
  2098. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  2099. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  2100. }
  2101. else
  2102. {
  2103. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  2104. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  2105. }
  2106. }
  2107. else
  2108. {
  2109. coefficient = commonPHR.StatModeAvgFprCoefficient;
  2110. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  2111. }
  2112. #endregion
  2113. var fetalHeartRate = SafeType.SafeInt(heartRate.HeartRate! * coefficient);
  2114. // 胎心的最大值调整为220,超过都按该值220输出
  2115. // fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  2116. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  2117. #region 判断是否够highFreqSampleTimes,540s
  2118. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)heartRate.LastUpdate!, phrFreqstatus!.LastUpdate);
  2119. // 判断是否够highFreqSampleTimes,540s
  2120. ///高频时长不足10分钟停止高频的胎心值生成说明:最近12个数据的最小值生成胎心值,
  2121. ///对于小于高频下限阀值取高频下限阀值进行转换;
  2122. ///对于高于高频上限阀值取高频上限阀值进行转换。并输出相关日志后续进行数据分析。
  2123. if (ts < highFreqSampleTimes)
  2124. {
  2125. if (fetalHeartRate > upperAlarmThreshold)
  2126. {
  2127. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,计算胎心值 {fetalHeartRate} 高于高频警告上限阀值{upperAlarmThreshold},最后胎心值{upperAlarmThreshold}");
  2128. fetalHeartRate = upperAlarmThreshold;
  2129. }
  2130. else if (fetalHeartRate < lowerAlarmThreshold)
  2131. {
  2132. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,计算胎心值 {fetalHeartRate} 低于高频警告下限阀值 {lowerAlarmThreshold},最后胎心值{lowerAlarmThreshold}");
  2133. fetalHeartRate = lowerAlarmThreshold;
  2134. }
  2135. else
  2136. {
  2137. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,在高频警告下限阀值 {lowerAlarmThreshold} 和 高频警告上限阀值:{upperAlarmThreshold}之间,最后胎心值{fetalHeartRate}");
  2138. }
  2139. }
  2140. // 超过highFreqSampleTimes,540s
  2141. else
  2142. {
  2143. if (fetalHeartRate > 220)
  2144. {
  2145. fetalHeartRate = 220;
  2146. _logger.LogWarning($"{heartRate.Serialno} 大于220,按220输出,计算因子:孕妇心率 {heartRate.HeartRate},系数 {coefficient},周期 周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2147. }
  2148. // 胎心的最小值调整为90,超过都按该值90
  2149. if (fetalHeartRate < 90)
  2150. {
  2151. fetalHeartRate = 90;
  2152. _logger.LogWarning($"{heartRate.Serialno} 小于90,按90输出,计算因子:孕妇心率 {heartRate.HeartRate},系数 {coefficient},周期 周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2153. }
  2154. }
  2155. #endregion
  2156. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  2157. if (phrFreqstatus == null) isAbnormal = 0;
  2158. var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  2159. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2160. //if (!isFreq)
  2161. //{
  2162. // statStartTime = heartRate.LastUpdate;
  2163. //
  2164. //}
  2165. // 保存到 数据服务 MySQL 数据库
  2166. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  2167. {
  2168. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  2169. PersonId = commonPHR!.PersonId,
  2170. Serialno = heartRate.Serialno,
  2171. HeartRate = fetalHeartRate,
  2172. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  2173. IsAbnormal = isAbnormal,
  2174. StatStartTime = statStartTime,
  2175. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  2176. CreateTime = DateTime.Now,
  2177. Method = 1,
  2178. IsDisplay = 1,
  2179. DeviceKey = commonPHR!.DeviceKey
  2180. };
  2181. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  2182. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  2183. // 推送最后一条常规心率计算的胎心数据到iot设备
  2184. #region 推送最后一条常规心率计算的胎心数据到iot设备
  2185. // 高频(<=12)-常规
  2186. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  2187. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  2188. {
  2189. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  2190. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  2191. }
  2192. // 高频(13)-常规-高频(13)
  2193. if (phrFreqstatus != null)
  2194. {
  2195. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  2196. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  2197. // 获取高频数据
  2198. var freqCollection = new List<PregnancyHeartRateModel>();
  2199. PregnancyHeartRateModel? previousItem = null;
  2200. foreach (var item in phr)
  2201. {
  2202. if (previousItem != null)
  2203. {
  2204. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  2205. if (timeNextDiff <= 60)
  2206. {
  2207. freqCollection.Add(item);
  2208. }
  2209. }
  2210. // 高频最后一条
  2211. if (lastPhr.MessageId == item.MessageId)
  2212. {
  2213. freqCollection.Add(item);
  2214. }
  2215. previousItem = item;
  2216. }
  2217. //去除高频
  2218. foreach (var item in freqCollection)
  2219. {
  2220. phr.Remove(item);
  2221. }
  2222. lastPhr = phr.FirstOrDefault();
  2223. if (lastPhr?.MessageId == heartRate.MessageId)
  2224. {
  2225. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  2226. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  2227. }
  2228. }
  2229. #endregion
  2230. #region 高频心率计算胎心数据到iot设备
  2231. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  2232. if (phrFreqstatus != null && isAbnormal != 0)
  2233. {
  2234. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  2235. }
  2236. #endregion
  2237. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  2238. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  2239. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  2240. // 胎心数据推送到第三方
  2241. var topic = "topic.push.third";
  2242. var fhrThridMsg = new
  2243. {
  2244. messageId = fhrMsgId,
  2245. topic = topic,
  2246. time = fhrMsgTime,
  2247. data = new
  2248. {
  2249. imei = heartRate.Serialno,
  2250. value = fetalHeartRate,
  2251. isAbnormal,
  2252. type = "fetalHeart"
  2253. }
  2254. };
  2255. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  2256. // 胎心数据推送到微信
  2257. if (isAbnormal != 0)
  2258. {
  2259. topic = "topic.push.wx";
  2260. var fhrMsg = new
  2261. {
  2262. messageId = fhrMsgId,
  2263. topic = topic,
  2264. time = fhrMsgTime,
  2265. data = new
  2266. {
  2267. deviceId = device?.DeviceId,
  2268. imei = heartRate.Serialno,
  2269. alarmTypeId = 12,
  2270. alarmDeviceName = heartRate.Serialno,
  2271. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  2272. address = string.Empty,
  2273. deviceKey = device?.DeviceId
  2274. }
  2275. };
  2276. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  2277. }
  2278. }
  2279. /// <summary>
  2280. /// 去除高频数据
  2281. /// </summary>
  2282. /// <param name="phr"></param>
  2283. /// <param name="highFreqSampleInterva"></param>
  2284. /// <returns></returns>
  2285. private static List<PregnancyHeartRateModel> GetNonFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr, int highFreqSampleInterval)
  2286. {
  2287. //phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  2288. //var result = new List<PregnancyHeartRateModel>();
  2289. //PregnancyHeartRateModel? previousItem = null;
  2290. //foreach (var item in phr)
  2291. //{
  2292. // if (previousItem != null)
  2293. // {
  2294. // var timeNextDiff =(previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  2295. // if (timeNextDiff > highFreqSampleInterval)
  2296. // {
  2297. // result.Add(previousItem);
  2298. // }
  2299. // }
  2300. // previousItem = item;
  2301. //}
  2302. //// 添加上一个
  2303. //if (previousItem != null)
  2304. //{
  2305. // result.Add(previousItem);
  2306. //}
  2307. //return result;
  2308. #region 反向
  2309. var phr1 = phr.OrderByDescending(i => i.LastUpdate).ToList();
  2310. var result = new List<PregnancyHeartRateModel>();
  2311. PregnancyHeartRateModel? previousItem1 = null;
  2312. foreach (var item in phr1)
  2313. {
  2314. if (previousItem1 != null)
  2315. {
  2316. var timeNextDiff = (previousItem1!.LastUpdate - item.LastUpdate).TotalSeconds;
  2317. if (timeNextDiff > highFreqSampleInterval)
  2318. {
  2319. result.Add(previousItem1);
  2320. }
  2321. }
  2322. previousItem1 = item;
  2323. }
  2324. // 添加上一个
  2325. if (previousItem1 != null)
  2326. {
  2327. result.Add(previousItem1);
  2328. }
  2329. #endregion
  2330. #region 正向
  2331. var phr2 = phr.OrderByDescending(i => i.LastUpdate).ToList(); ;
  2332. var freqCollection = new List<PregnancyHeartRateModel>();
  2333. PregnancyHeartRateModel? previousItem = null;
  2334. foreach (var item in phr2)
  2335. {
  2336. if (previousItem != null)
  2337. {
  2338. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  2339. if (timeNextDiff <= highFreqSampleInterval)
  2340. {
  2341. freqCollection.Add(item);
  2342. }
  2343. }
  2344. previousItem = item;
  2345. }
  2346. //去除高频
  2347. foreach (var item in freqCollection)
  2348. {
  2349. phr2.Remove(item);
  2350. }
  2351. #endregion
  2352. // 交集
  2353. var commonElements = phr2.Intersect(result).ToList();
  2354. return commonElements;
  2355. }
  2356. /// <summary>
  2357. /// 获取高频数据
  2358. /// </summary>
  2359. /// <param name="phr"></param>
  2360. /// <param name="highFreqSampleInterval"></param>
  2361. /// <returns></returns>
  2362. private static List<PregnancyHeartRateModel> GetFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr, int highFreqSampleInterval)
  2363. {
  2364. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  2365. var freqCollection = new List<PregnancyHeartRateModel>();
  2366. PregnancyHeartRateModel? previousItem = null;
  2367. foreach (var item in phr)
  2368. {
  2369. if (previousItem != null)
  2370. {
  2371. var timeNextDiff = (previousItem.LastUpdate - item.LastUpdate).TotalSeconds;
  2372. if (timeNextDiff <= highFreqSampleInterval)
  2373. {
  2374. freqCollection.Add(previousItem);
  2375. }
  2376. }
  2377. previousItem = item;
  2378. }
  2379. // 检查最后一条是否高频
  2380. if (previousItem != null && (phr.Last().LastUpdate - previousItem.LastUpdate).TotalSeconds <= highFreqSampleInterval)
  2381. {
  2382. freqCollection.Add(previousItem);
  2383. }
  2384. return freqCollection;
  2385. }
  2386. public async Task CalculateNormalFetalHeartRateIntervalAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR,int highFreqSampleInterval)
  2387. {
  2388. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  2389. var now = DateTime.Now;
  2390. var filteredPhr = daysPhr.Where(i => i.LastUpdate >= heartRate.LastUpdate && i.LastUpdate <= now).ToList();
  2391. // 去除高频
  2392. var normalPhr = GetNonFreqPregnancyHeartRate(filteredPhr, highFreqSampleInterval).OrderBy(i => i.LastUpdate);
  2393. if (normalPhr.ToList().Count==0)
  2394. {
  2395. _logger.LogWarning($"{heartRate.Serialno} 时间段{heartRate.LastUpdate}-{now},去除高频心率数据后,没有常规数据,不计算常规胎心数据");
  2396. return;
  2397. }
  2398. var startPhr = normalPhr.First();
  2399. var endPhr = normalPhr.Last();
  2400. //var sampleTime = GetSampleTimeFromLastUpdate((DateTime)heartRate.LastUpdate!, INTERVAL_FHR);
  2401. // 数据统计边界
  2402. var boundaryStatStartTime = GetSampleTimeFromLastUpdate((DateTime)startPhr.LastUpdate!, INTERVAL_FHR);
  2403. var boundaryStatEndTime = GetSampleTimeFromLastUpdate((DateTime)endPhr.LastUpdate!, INTERVAL_FHR).AddMinutes(INTERVAL_FHR);
  2404. _logger.LogInformation($"{heartRate.Serialno} 统计边界{boundaryStatStartTime}-{boundaryStatEndTime}");
  2405. try
  2406. {
  2407. //var CalNow = DateTime.Now;
  2408. //var during = TimeSpan.FromSeconds(300); //5分钟
  2409. var c = 0;
  2410. while (true)
  2411. {
  2412. //if (DateTime.Now - CalNow > during)
  2413. //{
  2414. // _logger.LogInformation($"{heartRate.Serialno} 超过1分钟,迭代完成跳出循环 ");
  2415. // break;
  2416. //}
  2417. await Task.Delay(TimeSpan.FromSeconds(1));
  2418. var segmentStatStartTime = boundaryStatStartTime.AddMinutes(c * INTERVAL_FHR);
  2419. var segmentStatEndTime = segmentStatStartTime.AddMinutes(INTERVAL_FHR);
  2420. c++;
  2421. var statStartTime = segmentStatStartTime;
  2422. var statEndTime = segmentStatEndTime;
  2423. _logger.LogInformation($"{heartRate.Serialno} 当前统计周期{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2424. if (statEndTime > boundaryStatEndTime)
  2425. {
  2426. _logger.LogInformation($"{heartRate.Serialno} 超过时间边界,迭代完成跳出循环 ");
  2427. break;
  2428. }
  2429. var segmentPhr = normalPhr
  2430. .Where(i => i.LastUpdate <= statEndTime && i.LastUpdate >= statStartTime)
  2431. .ToList();
  2432. if (segmentPhr.Count == 0)
  2433. {
  2434. // 跳出当次迭代,进入下次迭代
  2435. _logger.LogWarning($"{heartRate.Serialno} 统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")} 孕妇心率数据不足,{segmentPhr.Count}条记录,不处理");
  2436. continue;
  2437. }
  2438. _logger.LogInformation($"{heartRate.Serialno} 当前统计周期{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")},对应的常规心率ID{string.Join(",", segmentPhr.Select(i=>i.MessageId))}");
  2439. var sampleTime = DateTimeUtil.ConvertToTimeStamp(segmentStatStartTime).ToString();
  2440. sampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime;
  2441. //检测 是否存在,不存在则处理
  2442. GeneralParam param = new()
  2443. {
  2444. Filters = new List<QueryFilterCondition>
  2445. {
  2446. new ()
  2447. {
  2448. Key=nameof(HisGpsFetalHeartRate.Serialno),
  2449. Value=heartRate.Serialno,
  2450. ValueType=QueryValueTypeEnum.String,
  2451. Operator=QueryOperatorEnum.Equal
  2452. },
  2453. new ()
  2454. {
  2455. Key=nameof(HisGpsFetalHeartRate.SampleTime),
  2456. Value=sampleTime,
  2457. ValueType=QueryValueTypeEnum.String,
  2458. Operator=QueryOperatorEnum.Equal
  2459. },
  2460. },
  2461. OrderBys = new List<OrderByCondition>
  2462. {
  2463. new (){
  2464. IsDesc=true,
  2465. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  2466. }
  2467. }
  2468. };
  2469. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, heartRate.Serialno[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  2470. if (fhr == null)
  2471. {
  2472. var avgPhr = segmentPhr.Count == 1
  2473. ? segmentPhr.First().PregnancyHeartRate
  2474. : segmentPhr.Average(i => i.PregnancyHeartRate);
  2475. heartRate.HeartRate = (int)avgPhr;
  2476. #region 胎心系数使用基于心率与中位数对比
  2477. var coefficient = 0f;
  2478. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  2479. if (heartRate.HeartRate < commonPHR!.Mode)
  2480. {
  2481. coefficient = commonPHR.StatMinValueFprCoefficient!;
  2482. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  2483. }
  2484. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  2485. else if (heartRate.HeartRate > commonPHR.Mode)
  2486. {
  2487. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  2488. {
  2489. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  2490. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  2491. }
  2492. else
  2493. {
  2494. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  2495. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  2496. }
  2497. }
  2498. else
  2499. {
  2500. coefficient = commonPHR.StatModeAvgFprCoefficient;
  2501. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  2502. }
  2503. #endregion
  2504. #region 胎心阈值判断
  2505. //var fetalHeartRate = SafeType.SafeInt(heartRate.HeartRate * coefficient);
  2506. //// 胎心的最大值调整为220,超过都按该值220输出
  2507. //// fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  2508. //if (fetalHeartRate > 220)
  2509. //{
  2510. // fetalHeartRate = 220;
  2511. // _logger.LogWarning($"{heartRate.Serialno} 大于220,按220输出,计算因子:孕妇心率 {heartRate.HeartRate},系数 {coefficient},周期 周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2512. //}
  2513. //// 胎心的最小值调整为90,超过都按该值90
  2514. //if (fetalHeartRate < 90)
  2515. //{
  2516. // fetalHeartRate = 90;
  2517. // _logger.LogWarning($"{heartRate.Serialno} 小于90,按90输出,计算因子:孕妇心率 {heartRate.HeartRate},系数 {coefficient},周期 周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2518. //}
  2519. // 计算胎心率并进行边界检查
  2520. var fetalHeartRate = Math.Clamp((int)(heartRate.HeartRate * coefficient), 90, 220);
  2521. if (fetalHeartRate != (int)(heartRate.HeartRate * coefficient))
  2522. {
  2523. _logger.LogWarning($"{heartRate.Serialno} 胎心率超出范围, 按修正值 {fetalHeartRate} 输出, 计算因子:孕妇心率 {heartRate.HeartRate}, 系数 {coefficient}, 周期 {statStartTime} - {statEndTime}");
  2524. }
  2525. #endregion
  2526. _logger.LogInformation($"{heartRate.Serialno} 在 常规 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2527. var isAbnormal = 0;
  2528. #region 保存到Mysql数据库
  2529. // 保存到 数据服务 MySQL 数据库
  2530. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  2531. {
  2532. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  2533. PersonId = commonPHR!.PersonId,
  2534. Serialno = heartRate.Serialno,
  2535. HeartRate = fetalHeartRate,
  2536. SampleTime = sampleTime,
  2537. IsAbnormal = isAbnormal,
  2538. StatStartTime = statStartTime,
  2539. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  2540. CreateTime = DateTime.Now,
  2541. Method = 1,
  2542. IsDisplay = 1,
  2543. DeviceKey = commonPHR!.DeviceKey
  2544. };
  2545. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  2546. #endregion
  2547. #region 推送最后一条常规心率计算的胎心数据到iot设备
  2548. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  2549. if (segmentStatEndTime == boundaryStatEndTime)
  2550. {
  2551. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  2552. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备");
  2553. }
  2554. #endregion
  2555. #region 推送到第三方
  2556. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  2557. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  2558. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  2559. var topic = "topic.push.third";
  2560. var fhrThridMsg = new
  2561. {
  2562. messageId = fhrMsgId,
  2563. topic = topic,
  2564. time = fhrMsgTime,
  2565. data = new
  2566. {
  2567. imei = heartRate.Serialno,
  2568. value = fetalHeartRate,
  2569. isAbnormal,
  2570. type = "fetalHeart"
  2571. }
  2572. };
  2573. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  2574. #endregion
  2575. #region 推送到微信
  2576. if (isAbnormal != 0)
  2577. {
  2578. topic = "topic.push.wx";
  2579. var fhrMsg = new
  2580. {
  2581. messageId = fhrMsgId,
  2582. topic = topic,
  2583. time = fhrMsgTime,
  2584. data = new
  2585. {
  2586. deviceId = device?.DeviceId,
  2587. imei = heartRate.Serialno,
  2588. alarmTypeId = 12,
  2589. alarmDeviceName = heartRate.Serialno,
  2590. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  2591. address = string.Empty,
  2592. deviceKey = device?.DeviceId
  2593. }
  2594. };
  2595. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  2596. }
  2597. #endregion
  2598. }
  2599. else
  2600. {
  2601. _logger.LogInformation($"{heartRate.Serialno},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")} ,胎心已处理");
  2602. }
  2603. //await Task.Delay(TimeSpan.FromSeconds(1));
  2604. // 跳出循环
  2605. if (statEndTime.ToString("yyyyMMddHHmm") == boundaryStatEndTime.ToString("yyyyMMddHHmm"))
  2606. {
  2607. _logger.LogInformation($"{heartRate.Serialno} 迭代完成跳出循环 ");
  2608. break;
  2609. }
  2610. //if (statEndTime>= boundaryStatEndTime)
  2611. //{
  2612. // _logger.LogInformation($"{heartRate.Serialno} 时间边界,迭代完成跳出循环 ");
  2613. // break;
  2614. //}
  2615. }
  2616. }
  2617. catch (Exception ex)
  2618. {
  2619. _logger.LogError($"处理心率数据时发生错误: {ex.Message}");
  2620. }
  2621. //for (var segmentStatStartTime = boundaryStatStartTime;
  2622. // segmentStatStartTime < boundaryStatEndTime;
  2623. // segmentStatStartTime = segmentStatStartTime.AddMinutes(INTERVAL_FHR))
  2624. //{
  2625. // var segmentStatEndTime = segmentStatStartTime.AddMinutes(INTERVAL_FHR);
  2626. // var segmentPhr = daysPhr
  2627. // .Where(i => i.LastUpdate <= segmentStatEndTime && i.LastUpdate >= segmentStatStartTime)
  2628. // .ToList();
  2629. // if (segmentStatEndTime == boundaryStatEndTime)
  2630. // {
  2631. // break;
  2632. // }
  2633. //}
  2634. }
  2635. private DateTime GetSampleTimeFromLastUpdate(DateTime lastUpdate,int interval)
  2636. {
  2637. DateTime nowInterval = lastUpdate;
  2638. if (nowInterval.Second > 0)
  2639. {
  2640. nowInterval = nowInterval.AddMinutes(1);
  2641. }
  2642. // 计算last_update到上一间隔的分钟数
  2643. int minutesToSubtract = nowInterval.Minute % interval;
  2644. // 计算上一间隔的时间
  2645. DateTime previousInterval = nowInterval.AddMinutes(-minutesToSubtract).AddSeconds(-nowInterval.Second).AddMilliseconds(-nowInterval.Millisecond);
  2646. return previousInterval;
  2647. }
  2648. }
  2649. }