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.

3454 line
221KB

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