You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3269 lines
214KB

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