Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

3270 lines
215KB

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