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.

3049 lines
201KB

  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 SaveAndPushFetalHeartRateEndFreqHeartRateAsync(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. /// </summary>
  1801. /// <param name="phr"></param>
  1802. /// <param name="highFreqSampleInterva"></param>
  1803. /// <returns></returns>
  1804. private static List<PregnancyHeartRateModel> GetNonFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr, int highFreqSampleInterval)
  1805. {
  1806. //phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1807. //var result = new List<PregnancyHeartRateModel>();
  1808. //PregnancyHeartRateModel? previousItem = null;
  1809. //foreach (var item in phr)
  1810. //{
  1811. // if (previousItem != null)
  1812. // {
  1813. // var timeNextDiff =(previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1814. // if (timeNextDiff > highFreqSampleInterval)
  1815. // {
  1816. // result.Add(previousItem);
  1817. // }
  1818. // }
  1819. // previousItem = item;
  1820. //}
  1821. //// 添加上一个
  1822. //if (previousItem != null)
  1823. //{
  1824. // result.Add(previousItem);
  1825. //}
  1826. //return result;
  1827. #region 反向
  1828. var phr1 = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1829. var result = new List<PregnancyHeartRateModel>();
  1830. PregnancyHeartRateModel? previousItem1 = null;
  1831. foreach (var item in phr1)
  1832. {
  1833. if (previousItem1 != null)
  1834. {
  1835. var timeNextDiff = (previousItem1!.LastUpdate - item.LastUpdate).TotalSeconds;
  1836. if (timeNextDiff > highFreqSampleInterval)
  1837. {
  1838. result.Add(previousItem1);
  1839. }
  1840. }
  1841. previousItem1 = item;
  1842. }
  1843. // 添加上一个
  1844. if (previousItem1 != null)
  1845. {
  1846. result.Add(previousItem1);
  1847. }
  1848. #endregion
  1849. #region 正向
  1850. var phr2 = phr.OrderByDescending(i => i.LastUpdate).ToList(); ;
  1851. var freqCollection = new List<PregnancyHeartRateModel>();
  1852. PregnancyHeartRateModel? previousItem = null;
  1853. foreach (var item in phr2)
  1854. {
  1855. if (previousItem != null)
  1856. {
  1857. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1858. if (timeNextDiff <= highFreqSampleInterval)
  1859. {
  1860. freqCollection.Add(item);
  1861. }
  1862. }
  1863. previousItem = item;
  1864. }
  1865. //去除高频
  1866. foreach (var item in freqCollection)
  1867. {
  1868. phr2.Remove(item);
  1869. }
  1870. #endregion
  1871. // 交集
  1872. var commonElements = phr2.Intersect(result).ToList();
  1873. return commonElements;
  1874. }
  1875. /// <summary>
  1876. /// 获取高频数据
  1877. /// </summary>
  1878. /// <param name="phr"></param>
  1879. /// <param name="highFreqSampleInterval"></param>
  1880. /// <returns></returns>
  1881. private static List<PregnancyHeartRateModel> GetFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr, int highFreqSampleInterval)
  1882. {
  1883. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1884. var freqCollection = new List<PregnancyHeartRateModel>();
  1885. PregnancyHeartRateModel? previousItem = null;
  1886. foreach (var item in phr)
  1887. {
  1888. if (previousItem != null)
  1889. {
  1890. var timeNextDiff = (previousItem.LastUpdate - item.LastUpdate).TotalSeconds;
  1891. if (timeNextDiff <= highFreqSampleInterval)
  1892. {
  1893. freqCollection.Add(previousItem);
  1894. }
  1895. }
  1896. previousItem = item;
  1897. }
  1898. // 检查最后一条是否高频
  1899. if (previousItem != null && (phr.Last().LastUpdate - previousItem.LastUpdate).TotalSeconds <= highFreqSampleInterval)
  1900. {
  1901. freqCollection.Add(previousItem);
  1902. }
  1903. return freqCollection;
  1904. }
  1905. /// <summary>
  1906. /// 周期性常规心率计算胎心值
  1907. /// </summary>
  1908. /// <param name="heartRate"></param>
  1909. /// <param name="commonPHR"></param>
  1910. /// <param name="highFreqSampleInterval"></param>
  1911. /// <returns></returns>
  1912. public async Task CalculateNormalFetalHeartRateIntervalAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR,int highFreqSampleInterval)
  1913. {
  1914. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  1915. var now = DateTime.Now;
  1916. var filteredPhr = daysPhr.Where(i => i.LastUpdate >= heartRate.LastUpdate && i.LastUpdate <= now).ToList();
  1917. // 去除高频
  1918. var normalPhr = GetNonFreqPregnancyHeartRate(filteredPhr, highFreqSampleInterval).OrderBy(i => i.LastUpdate);
  1919. if (normalPhr.ToList().Count==0)
  1920. {
  1921. _logger.LogWarning($"{heartRate.Serialno} 时间段{heartRate.LastUpdate}-{now},去除高频心率数据后,没有常规数据,不计算常规胎心数据");
  1922. return;
  1923. }
  1924. var startPhr = normalPhr.First();
  1925. var endPhr = normalPhr.Last();
  1926. //var sampleTime = GetSampleTimeFromLastUpdate((DateTime)heartRate.LastUpdate!, INTERVAL_FHR);
  1927. // 数据统计边界
  1928. var boundaryStatStartTime = GetSampleTimeFromLastUpdate((DateTime)startPhr.LastUpdate!, INTERVAL_FHR);
  1929. var boundaryStatEndTime = GetSampleTimeFromLastUpdate((DateTime)endPhr.LastUpdate!, INTERVAL_FHR).AddMinutes(INTERVAL_FHR);
  1930. _logger.LogInformation($"{heartRate.Serialno} 常规胎心统计边界{boundaryStatStartTime}-{boundaryStatEndTime}");
  1931. try
  1932. {
  1933. //var CalNow = DateTime.Now;
  1934. //var during = TimeSpan.FromSeconds(300); //5分钟
  1935. var c = 0;
  1936. while (true)
  1937. {
  1938. //if (DateTime.Now - CalNow > during)
  1939. //{
  1940. // _logger.LogInformation($"{heartRate.Serialno} 超过1分钟,迭代完成跳出循环 ");
  1941. // break;
  1942. //}
  1943. await Task.Delay(TimeSpan.FromSeconds(1));
  1944. var segmentStatStartTime = boundaryStatStartTime.AddMinutes(c * INTERVAL_FHR);
  1945. var segmentStatEndTime = segmentStatStartTime.AddMinutes(INTERVAL_FHR);
  1946. c++;
  1947. var statStartTime = segmentStatStartTime;
  1948. var statEndTime = segmentStatEndTime;
  1949. _logger.LogInformation($"{heartRate.Serialno} 当前统计周期{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1950. if (statEndTime > boundaryStatEndTime)
  1951. {
  1952. _logger.LogInformation($"{heartRate.Serialno} 常规胎心统计超过时间边界,迭代完成跳出循环 ");
  1953. break;
  1954. }
  1955. var segmentPhr = normalPhr
  1956. .Where(i => i.LastUpdate <= statEndTime && i.LastUpdate >= statStartTime)
  1957. .ToList();
  1958. if (segmentPhr.Count == 0)
  1959. {
  1960. // 跳出当次迭代,进入下次迭代
  1961. _logger.LogWarning($"{heartRate.Serialno} 统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")} 孕妇心率数据不足,{segmentPhr.Count}条记录,不处理");
  1962. continue;
  1963. }
  1964. _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))}");
  1965. var sampleTime = DateTimeUtil.ConvertToTimeStamp(segmentStatStartTime).ToString();
  1966. sampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime;
  1967. //检测 是否存在,不存在则处理
  1968. GeneralParam param = new()
  1969. {
  1970. Filters = new List<QueryFilterCondition>
  1971. {
  1972. new ()
  1973. {
  1974. Key=nameof(HisGpsFetalHeartRate.Serialno),
  1975. Value=heartRate.Serialno,
  1976. ValueType=QueryValueTypeEnum.String,
  1977. Operator=QueryOperatorEnum.Equal
  1978. },
  1979. new ()
  1980. {
  1981. Key=nameof(HisGpsFetalHeartRate.SampleTime),
  1982. Value=sampleTime,
  1983. ValueType=QueryValueTypeEnum.String,
  1984. Operator=QueryOperatorEnum.Equal
  1985. },
  1986. },
  1987. OrderBys = new List<OrderByCondition>
  1988. {
  1989. new (){
  1990. IsDesc=true,
  1991. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  1992. }
  1993. }
  1994. };
  1995. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, heartRate.Serialno[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  1996. if (fhr == null)
  1997. {
  1998. var avgPhr = segmentPhr.Count == 1
  1999. ? segmentPhr.First().PregnancyHeartRate
  2000. : segmentPhr.Average(i => i.PregnancyHeartRate);
  2001. heartRate.HeartRate = (int)avgPhr;
  2002. #region 胎心系数使用基于心率与众数对比
  2003. var coefficient = 0f;
  2004. /**
  2005. // 孕妇心率少于众数,取StatMinValueFprCoefficient
  2006. if (heartRate.HeartRate < commonPHR!.Mode)
  2007. {
  2008. coefficient = commonPHR.StatMinValueFprCoefficient!;
  2009. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于众数,使用最小值系数 {coefficient}");
  2010. }
  2011. // 孕妇心率大于众数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  2012. else if (heartRate.HeartRate > commonPHR.Mode)
  2013. {
  2014. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  2015. {
  2016. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  2017. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于众数,使用最大值系数 {coefficient}");
  2018. }
  2019. else
  2020. {
  2021. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  2022. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于众数,使用均值系数 {coefficient}");
  2023. }
  2024. }
  2025. else
  2026. {
  2027. coefficient = commonPHR.StatModeAvgFprCoefficient;
  2028. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于众数,使用均值系数 {coefficient}");
  2029. }
  2030. */
  2031. ///1、高频最小值>心率,取高频最小值系数
  2032. ///2、高频最小值 < 心率 < 众数,取众数系数与高频最小值系数较小值
  2033. ///3、众数 < 心率 < 高频最大值,取众数系数与高频最大值系数较小值
  2034. ///4、心率 > 高频最大值,取高频最大值系数
  2035. // 1、高频最小值>心率,取高频最小值系数
  2036. if (commonPHR.MinValue > heartRate.HeartRate)
  2037. {
  2038. coefficient = commonPHR.StatMinValueFprCoefficient!;
  2039. _logger.LogInformation($"{heartRate.Serialno} 高频最小值>心率,取高频最小值系数 {coefficient}");
  2040. }
  2041. // 2、高频最小值 < 心率 < 众数,取众数系数与高频最小值系数较小值
  2042. if (commonPHR.MinValue <heartRate.HeartRate && heartRate.HeartRate<commonPHR.Mode)
  2043. {
  2044. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMinValueFprCoefficient)
  2045. {
  2046. coefficient = commonPHR.StatMinValueFprCoefficient!;
  2047. _logger.LogInformation($"{heartRate.Serialno} 高频最小值 < 心率 < 众数,平均值系数大于最小值系数,使用最小值系数 {coefficient}");
  2048. }
  2049. else
  2050. {
  2051. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  2052. _logger.LogInformation($"{heartRate.Serialno} 高频最小值 < 心率 < 众数,平均值系数小于最小值系数,使用均值系数 {coefficient}");
  2053. }
  2054. }
  2055. // 3、众数 < 心率 < 高频最大值,取众数系数与高频最大值系数较小值
  2056. if (commonPHR.Mode < heartRate.HeartRate && heartRate.HeartRate < commonPHR.MaxValue)
  2057. {
  2058. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  2059. {
  2060. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  2061. _logger.LogInformation($"{heartRate.Serialno} 众数 < 心率 < 高频最大值,平均值系数大于最最大值系数,使用最大值系数 {coefficient}");
  2062. }
  2063. else
  2064. {
  2065. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  2066. _logger.LogInformation($"{heartRate.Serialno} 众数 < 心率 < 高频最大值,平均值系数小于最小值系数,使用均值系数 {coefficient}");
  2067. }
  2068. }
  2069. // 4、心率 > 高频最大值,取高频最大值系数
  2070. if (heartRate.HeartRate > commonPHR.MaxValue)
  2071. {
  2072. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  2073. _logger.LogInformation($"{heartRate.Serialno} 心率 > 高频最大值,取高频最大值系数 {coefficient}");
  2074. }
  2075. if (heartRate.HeartRate == commonPHR.Mode)
  2076. {
  2077. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  2078. _logger.LogInformation($"{heartRate.Serialno} 心率 == 众数,取均值系数 {coefficient}");
  2079. }
  2080. #endregion
  2081. #region 胎心阈值判断
  2082. //var fetalHeartRate = SafeType.SafeInt(heartRate.HeartRate * coefficient);
  2083. //// 胎心的最大值调整为220,超过都按该值220输出
  2084. //// fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  2085. //if (fetalHeartRate > 220)
  2086. //{
  2087. // fetalHeartRate = 220;
  2088. // _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")}");
  2089. //}
  2090. //// 胎心的最小值调整为90,超过都按该值90
  2091. //if (fetalHeartRate < 90)
  2092. //{
  2093. // fetalHeartRate = 90;
  2094. // _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")}");
  2095. //}
  2096. // 计算胎心率并进行边界检查
  2097. var fetalHeartRate = Math.Clamp((int)(heartRate.HeartRate * coefficient), 90, 220);
  2098. if (fetalHeartRate != (int)(heartRate.HeartRate * coefficient))
  2099. {
  2100. _logger.LogWarning($"{heartRate.Serialno} 胎心率超出范围, 按修正值 {fetalHeartRate} 输出, 计算因子:孕妇心率 {heartRate.HeartRate}, 系数 {coefficient}, 周期 {statStartTime} - {statEndTime}");
  2101. }
  2102. #endregion
  2103. _logger.LogInformation($"{heartRate.Serialno} 在 常规 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2104. var isAbnormal = 0;
  2105. #region 保存到Mysql数据库
  2106. // 保存到 数据服务 MySQL 数据库
  2107. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  2108. {
  2109. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  2110. PersonId = commonPHR!.PersonId,
  2111. Serialno = heartRate.Serialno,
  2112. HeartRate = fetalHeartRate,
  2113. SampleTime = sampleTime,
  2114. IsAbnormal = isAbnormal,
  2115. StatStartTime = statStartTime,
  2116. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  2117. CreateTime = DateTime.Now,
  2118. Method = 1,
  2119. IsDisplay = 1,
  2120. DeviceKey = commonPHR!.DeviceKey
  2121. };
  2122. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  2123. #endregion
  2124. #region 推送最后一条常规心率计算的胎心数据到iot设备
  2125. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  2126. if (segmentStatEndTime == boundaryStatEndTime)
  2127. {
  2128. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  2129. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备");
  2130. }
  2131. #endregion
  2132. #region 推送到第三方
  2133. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  2134. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  2135. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  2136. var topic = "topic.push.third";
  2137. var fhrThridMsg = new
  2138. {
  2139. messageId = fhrMsgId,
  2140. topic = topic,
  2141. time = fhrMsgTime,
  2142. data = new
  2143. {
  2144. imei = heartRate.Serialno,
  2145. value = fetalHeartRate,
  2146. isAbnormal,
  2147. type = "fetalHeart"
  2148. }
  2149. };
  2150. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  2151. #endregion
  2152. #region 推送到微信
  2153. if (isAbnormal != 0)
  2154. {
  2155. topic = "topic.push.wx";
  2156. var fhrMsg = new
  2157. {
  2158. messageId = fhrMsgId,
  2159. topic = topic,
  2160. time = fhrMsgTime,
  2161. data = new
  2162. {
  2163. deviceId = device?.DeviceId,
  2164. imei = heartRate.Serialno,
  2165. alarmTypeId = 12,
  2166. alarmDeviceName = heartRate.Serialno,
  2167. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  2168. address = string.Empty,
  2169. deviceKey = device?.DeviceId
  2170. }
  2171. };
  2172. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  2173. }
  2174. #endregion
  2175. }
  2176. else
  2177. {
  2178. _logger.LogInformation($"{heartRate.Serialno},统计常规胎心周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")} ,常规胎心已处理");
  2179. }
  2180. //await Task.Delay(TimeSpan.FromSeconds(1));
  2181. // 跳出循环
  2182. if (statEndTime.ToString("yyyyMMddHHmm") == boundaryStatEndTime.ToString("yyyyMMddHHmm"))
  2183. {
  2184. _logger.LogInformation($"{heartRate.Serialno} 迭代完成跳出循环 ");
  2185. break;
  2186. }
  2187. //if (statEndTime>= boundaryStatEndTime)
  2188. //{
  2189. // _logger.LogInformation($"{heartRate.Serialno} 时间边界,迭代完成跳出循环 ");
  2190. // break;
  2191. //}
  2192. }
  2193. }
  2194. catch (Exception ex)
  2195. {
  2196. _logger.LogError($"处理常规胎心数据时发生错误: {ex.Message}");
  2197. }
  2198. //for (var segmentStatStartTime = boundaryStatStartTime;
  2199. // segmentStatStartTime < boundaryStatEndTime;
  2200. // segmentStatStartTime = segmentStatStartTime.AddMinutes(INTERVAL_FHR))
  2201. //{
  2202. // var segmentStatEndTime = segmentStatStartTime.AddMinutes(INTERVAL_FHR);
  2203. // var segmentPhr = daysPhr
  2204. // .Where(i => i.LastUpdate <= segmentStatEndTime && i.LastUpdate >= segmentStatStartTime)
  2205. // .ToList();
  2206. // if (segmentStatEndTime == boundaryStatEndTime)
  2207. // {
  2208. // break;
  2209. // }
  2210. //}
  2211. }
  2212. public async Task CalculateFetalMovementIntervalAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR,DateTime edoc)
  2213. {
  2214. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  2215. DateTime fmNow = DateTime.Now;
  2216. int fmNowHour = fmNow.Hour;
  2217. DateTime startHour;
  2218. DateTime endHour;
  2219. if (fmNow.Subtract((DateTime)heartRate.LastUpdate!).Hours>2)
  2220. {
  2221. _logger.LogWarning($"{heartRate.Serialno} 当前计算时间与lastUpdate 时差超过2小时,将从当前触发心率到当天的所有心率计算对应的胎动");
  2222. startHour = ((DateTime)heartRate.LastUpdate!).Date.AddHours(((DateTime)heartRate.LastUpdate!).Hour);
  2223. endHour = ((DateTime)heartRate.LastUpdate!).Date.AddDays(1);
  2224. }
  2225. else
  2226. {
  2227. // 跨天
  2228. if (fmNowHour == 1)
  2229. {
  2230. // last_update 23~0
  2231. startHour = fmNow.Date.AddDays(-1).AddHours(((DateTime)heartRate.LastUpdate!).Hour);
  2232. endHour = fmNow.Date;
  2233. }
  2234. else
  2235. {
  2236. // last_update 0~1->2,1~2->3,2~3->4...21~22->23
  2237. startHour = fmNow.Date.AddHours(((DateTime)heartRate.LastUpdate!).Hour);
  2238. endHour = fmNow.Date.AddHours(fmNowHour - 1);
  2239. }
  2240. }
  2241. try
  2242. {
  2243. var filterPhr = daysPhr
  2244. .Where(i => i.LastUpdate >= startHour && i.LastUpdate <= endHour)
  2245. .OrderBy(i => i.LastUpdate).ToList();
  2246. //if (filterPhr.Count < 2)
  2247. //{
  2248. // _logger.LogWarning($"{heartRate.Serialno} 胎动统计数据少于2条,不统计,{string.Join('-', filterPhr.Select(i=>i.LastUpdate))}");
  2249. // return;
  2250. //}
  2251. if (filterPhr.Count < 1)
  2252. {
  2253. _logger.LogWarning($"{heartRate.Serialno} 胎动统计数据少于1条,不统计,{string.Join('-', filterPhr.Select(i => i.LastUpdate))}");
  2254. return;
  2255. }
  2256. var startPhr = filterPhr.First();
  2257. var endPhr = filterPhr.Last();
  2258. // 数据统计边界
  2259. var boundaryStatStartTime = startPhr.LastUpdate.Date.AddHours(startPhr.LastUpdate.Hour);
  2260. var boundaryStatEndTime = endPhr.LastUpdate.Date.AddHours(endPhr.LastUpdate.Hour + 1);
  2261. _logger.LogInformation($"{heartRate.Serialno} 胎动统计边界{boundaryStatStartTime}-{boundaryStatEndTime}");
  2262. var c = 0;
  2263. while (true)
  2264. {
  2265. await Task.Delay(TimeSpan.FromSeconds(1));
  2266. var segmentStatStartTime = boundaryStatStartTime.AddHours(c * 1);
  2267. var segmentStatEndTime = segmentStatStartTime.AddHours(1);
  2268. c++;
  2269. var statStartTime = segmentStatStartTime;
  2270. var statEndTime = segmentStatEndTime;
  2271. _logger.LogInformation($"{heartRate.Serialno} 当前胎动统计周期{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  2272. if (statEndTime > boundaryStatEndTime)
  2273. {
  2274. _logger.LogInformation($"{heartRate.Serialno} 常规胎心统计超过时间边界,迭代完成跳出循环 ");
  2275. break;
  2276. }
  2277. var segmentPhr = filterPhr
  2278. .Where(i => i.LastUpdate <= statEndTime && i.LastUpdate >= statStartTime)
  2279. .ToList();
  2280. if (segmentPhr.Count == 0)
  2281. {
  2282. // 跳出当次迭代,进入下次迭代
  2283. _logger.LogWarning($"{heartRate.Serialno} 胎动统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")} 孕妇心率数据不足,{segmentPhr.Count}条记录,不处理");
  2284. continue;
  2285. }
  2286. _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))}");
  2287. // 0~1 点的lastUpdate数据sample_time是1点,计算是2点
  2288. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(statEndTime).ToString()[..10];
  2289. var isFetalMovementExisted = await _deviceCacheMgr.FetalMovementIsExistedAsync(heartRate.Serialno, fetalMovementSampleTime);
  2290. if (!isFetalMovementExisted)
  2291. {
  2292. /// 开始计算
  2293. var phrRange = segmentPhr.OrderByDescending(i => i.LastUpdate)
  2294. .Select(i => i.LastUpdate)
  2295. .ToList();
  2296. if (phrRange.Count >= 1)
  2297. {
  2298. // 读取胎心数据
  2299. GeneralParam param = new()
  2300. {
  2301. Filters = new List<QueryFilterCondition>
  2302. {
  2303. new ()
  2304. {
  2305. Key=nameof(HisGpsFetalHeartRate.Serialno),
  2306. Value=heartRate.Serialno,
  2307. ValueType=QueryValueTypeEnum.String,
  2308. Operator=QueryOperatorEnum.Equal
  2309. },
  2310. //new ()
  2311. //{
  2312. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  2313. // Value=sampleTime,
  2314. // ValueType=QueryValueTypeEnum.String,
  2315. // Operator=QueryOperatorEnum.GreaterEqual
  2316. //},
  2317. },
  2318. OrderBys = new List<OrderByCondition>
  2319. {
  2320. new (){
  2321. IsDesc=true,
  2322. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  2323. }
  2324. }
  2325. };
  2326. var fetalHeartRateIsAbnormal = 0;
  2327. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, heartRate.Serialno[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  2328. // 胎心数据时间与胎动时间一致
  2329. var time = long.Parse(fhr.SampleTime.Length < 13 ? fhr.SampleTime.PadRight(13, '0') : fhr.SampleTime);
  2330. var fhrSampleTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(time);
  2331. // 胎心数据时间与胎动时间一致,最后一条胎心数据与胎动数据的小时差不大于2
  2332. //if ((DateTime.Now.Hour - fhrSampleTime.Hour) <= 2)
  2333. if(true)
  2334. {
  2335. var duringMins = Math.Abs((phrRange.First() - phrRange.Last()).TotalMinutes);
  2336. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  2337. bool isInTimeRanges = IsLastUpdateInTimeRanges(phrRange.First());
  2338. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  2339. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  2340. {
  2341. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  2342. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  2343. .Where(i =>
  2344. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  2345. i.PregnancyPeriod[1] >= pregnancyWeeks)
  2346. .Select(i => i.MedianMovement)
  2347. .FirstOrDefault()
  2348. :
  2349. fetalMovementMap
  2350. .Where(i =>
  2351. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  2352. i.PregnancyPeriod[1] >= pregnancyWeeks)
  2353. .Select(i => i.InitialMovement)
  2354. .FirstOrDefault()
  2355. ;
  2356. // var fetalMovementTimeVar = (fetalMovementMapValue * duringMins * 2) / 120;
  2357. #region 取消使用时间长度比例
  2358. //var fetalMovementTimeVar = (fetalMovementMapValue * duringMins) / 60;
  2359. //if (duringMins < 59)
  2360. //{
  2361. // // 取12小时胎动总数最小值
  2362. // fetalMovementMapValue = fetalMovementMap
  2363. // .Where(i => i.PregnancyPeriod![0] <= pregnancyWeeks && i.PregnancyPeriod[1] >= pregnancyWeeks)
  2364. // .First()
  2365. // .TwelveHourMovementRange[0];
  2366. // //取12小时胎动总数最小值的平均值
  2367. // fetalMovementTimeVar = fetalMovementMapValue / 12;
  2368. // _logger.LogWarning($"{heartRate.Serialno} 佩戴不足1小时,12小时胎动总数最小值{fetalMovementMapValue},平均值{fetalMovementTimeVar}");
  2369. //}
  2370. #endregion
  2371. var fetalMovementTimeVar = (double)fetalMovementMapValue;
  2372. #region 生理健康与胎动的关系
  2373. /// (步数)运动步数超过1500步则加1;
  2374. /// (体温)低烧则胎动减1,高烧胎动减2;低烧是37.3~38.5,38.6以上是高烧。
  2375. /// (血压)血压收缩压大于160则加1。
  2376. /// (心理)心理压力高加2,压力中加1;
  2377. var fetalMovementStepVar = 0;
  2378. var fetalMovementTempVar = 0;
  2379. var fetalMovementBpVar = 0;
  2380. var fetalMovementPpVar = 0;
  2381. var fetalMovementFhrVar = 0;
  2382. // 步数
  2383. if (false)
  2384. {
  2385. var step = await _personCacheMgr.GetStepPeriodicityAsync(heartRate.Serialno);
  2386. if (step != null)
  2387. {
  2388. if (DateTime.Now.Hour - ((DateTime)step?.LastUpdate!).Hour <= 2)
  2389. {
  2390. if (step.Steps > 1500) fetalMovementStepVar = 1;
  2391. }
  2392. else
  2393. {
  2394. _logger.LogWarning($"{heartRate.Serialno} 周期步数 时间无效");
  2395. }
  2396. }
  2397. else
  2398. {
  2399. _logger.LogWarning($"{heartRate.Serialno} 周期步数无数据");
  2400. }
  2401. }
  2402. // 体温
  2403. if (true)
  2404. {
  2405. var temp = await _personCacheMgr.GetTemperaturePeriodicityAsync(heartRate.Serialno);
  2406. if (temp != null)
  2407. {
  2408. if (DateTime.Now.Hour - ((DateTime)temp?.LastUpdate!).Hour <= 2)
  2409. {
  2410. // 中烧
  2411. if (temp.Temperature >= 37.3M && temp.Temperature <= 38.5M)
  2412. {
  2413. fetalMovementTempVar = -1;
  2414. }
  2415. // 高烧
  2416. if (temp.Temperature >= 38.6M)
  2417. {
  2418. fetalMovementTempVar = -2;
  2419. }
  2420. }
  2421. else
  2422. {
  2423. _logger.LogWarning($"{heartRate.Serialno} 周期体温 时间无效");
  2424. }
  2425. }
  2426. else
  2427. {
  2428. _logger.LogWarning($"{heartRate.Serialno} 周期体温无数据");
  2429. }
  2430. }
  2431. // 血压
  2432. if (true)
  2433. {
  2434. var bp = await _personCacheMgr.GetBloodPressPeriodicityAsync(heartRate.Serialno);
  2435. if (bp != null)
  2436. {
  2437. if (DateTime.Now.Hour - ((DateTime)bp?.LastUpdate!).Hour <= 2)
  2438. {
  2439. if (bp.SystolicValue > 160)
  2440. {
  2441. fetalMovementBpVar = 1;
  2442. }
  2443. }
  2444. else
  2445. {
  2446. _logger.LogWarning($"{heartRate.Serialno} 周期血压 时间无效");
  2447. }
  2448. }
  2449. else
  2450. {
  2451. _logger.LogWarning($"{heartRate.Serialno} 周期血压无数据");
  2452. }
  2453. }
  2454. // 心理
  2455. if (false)
  2456. {
  2457. //-1 不处理,
  2458. //0 正常,
  2459. //1 轻度,
  2460. //2 中度;
  2461. //3 重度;
  2462. GeneralParam psychResultParam = new()
  2463. {
  2464. Filters = new List<QueryFilterCondition>
  2465. {
  2466. new ()
  2467. {
  2468. Key=nameof(HisGpsPsychResult.Serialno),
  2469. Value=heartRate.Serialno,
  2470. ValueType=QueryValueTypeEnum.String,
  2471. Operator=QueryOperatorEnum.Equal
  2472. },
  2473. //new ()
  2474. //{
  2475. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  2476. // Value=sampleTime,
  2477. // ValueType=QueryValueTypeEnum.String,
  2478. // Operator=QueryOperatorEnum.GreaterEqual
  2479. //},
  2480. },
  2481. OrderBys = new List<OrderByCondition>
  2482. {
  2483. new (){
  2484. IsDesc=true,
  2485. Key=nameof(HisGpsPsychResult.Serialno)
  2486. }
  2487. }
  2488. };
  2489. var psych = await _hisPsychResultApiClient.GetFirstAsync(psychResultParam, heartRate.Serialno[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  2490. if (psych != null)
  2491. {
  2492. if (psych?.StressScore == 2)
  2493. {
  2494. fetalMovementPpVar = 1;
  2495. }
  2496. if (psych?.StressScore == 3)
  2497. {
  2498. fetalMovementPpVar = 2;
  2499. }
  2500. }
  2501. else
  2502. {
  2503. _logger.LogWarning($"{heartRate.Serialno} 周期心理压力无数据");
  2504. }
  2505. }
  2506. #endregion
  2507. #region 胎心与胎动的关系
  2508. /// 胎心值过缓时,则胎动数量减1;胎心值过速时,则胎动也加1。
  2509. /// 此值允许在上限值上继续增加,在下限值上继续减少,最小值为0。
  2510. /// 告警上限阀值
  2511. //1表示偏高;2表示偏低
  2512. if (true)
  2513. {
  2514. if (fhr.IsAbnormal == 2)
  2515. {
  2516. fetalMovementPpVar = -1;
  2517. }
  2518. if (fhr.IsAbnormal == 1)
  2519. {
  2520. fetalMovementPpVar = 1;
  2521. }
  2522. }
  2523. #endregion
  2524. _logger.LogInformation($"{heartRate.Serialno} 时间比例胎动值:{fetalMovementTimeVar}, 步数参数变动值:{fetalMovementStepVar},体温参数变动值:{fetalMovementTempVar},血压参数变动值:{fetalMovementBpVar},心理压力参数变动值:{fetalMovementPpVar},胎心参数变动值:{fetalMovementFhrVar}");
  2525. var fetalMovementValue = fetalMovementTimeVar + fetalMovementStepVar + fetalMovementTempVar + fetalMovementBpVar + fetalMovementPpVar + fetalMovementFhrVar;
  2526. // 四舍五入
  2527. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  2528. _logger.LogInformation($"{heartRate.Serialno} 孕周:{pregnancyWeeks},胎动数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 时间比例胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{phrRange.Last()}-{phrRange.First()}, 胎动计算值:{fetalMovementTimeVar}, 胎动四舍五入最终值:{fetalMovement} 已完成.");
  2529. // 获取胎心数据状态与胎动数据状态一致
  2530. //etalHeartRateIsAbnormal= fhr.IsAbnormal;
  2531. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  2532. await _serviceIotApi.SetFetalMovementConfig(heartRate.Serialno, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  2533. // 保存到MySQL数据库
  2534. HisGpsFetalMovement fm = new()
  2535. {
  2536. FetalMovementId = Guid.NewGuid().ToString("D"),
  2537. PersonId = commonPHR!.PersonId,
  2538. Serialno = heartRate.Serialno,
  2539. CreateTime = DateTime.Now,
  2540. IsAbnormal = feltalMovementIsAbnormal,
  2541. FetalMovementValue = fetalMovement,
  2542. SampleTime = fetalMovementSampleTime,
  2543. Method = 1,
  2544. IsDisplay = 1,
  2545. DeviceKey = commonPHR!.DeviceKey
  2546. };
  2547. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  2548. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  2549. var fmMsgId = $"{heartRate.Serialno}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  2550. var fmMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  2551. // 胎动数据推送到第三方
  2552. var topic = "topic.push.third";
  2553. var fmThridMsg = new
  2554. {
  2555. messageId = fmMsgId,
  2556. topic = topic,
  2557. time = fmMsgTime,
  2558. data = new
  2559. {
  2560. imei = heartRate.Serialno,
  2561. value = fetalMovement,
  2562. isAbnormal = feltalMovementIsAbnormal,
  2563. type = "fetalMovement"
  2564. }
  2565. };
  2566. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, 31, fmThridMsg).ConfigureAwait(false);
  2567. // 胎动数据推送到微信
  2568. if (feltalMovementIsAbnormal != 0)
  2569. {
  2570. topic = "topic.push.wx";
  2571. var fmMsg = new
  2572. {
  2573. messageId = Guid.NewGuid().ToString("D"),
  2574. topic = topic,
  2575. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
  2576. data = new
  2577. {
  2578. deviceId = device?.DeviceId,
  2579. imei = heartRate.Serialno,
  2580. alarmTypeId = 12,
  2581. alarmDeviceName = heartRate.Serialno,
  2582. alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
  2583. address = string.Empty,
  2584. deviceKey = device?.DeviceId
  2585. }
  2586. };
  2587. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
  2588. }
  2589. // 设置入库缓存记录
  2590. await _deviceCacheMgr.SetFetalMovementAsync(heartRate.Serialno, fetalMovementSampleTime, fm);
  2591. }
  2592. else
  2593. {
  2594. _logger.LogWarning($"{heartRate.Serialno} 孕周 {pregnancyWeeks},超出胎动计算范围");
  2595. }
  2596. }
  2597. else
  2598. {
  2599. _logger.LogWarning($"{heartRate.Serialno} 最后一条胎心数据与胎动数据的小时差大于2,不计算胎动数据");
  2600. }
  2601. }
  2602. else
  2603. {
  2604. _logger.LogInformation($"{heartRate.Serialno} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 不足1条,不能判断是否持续佩戴");
  2605. }
  2606. }
  2607. else
  2608. {
  2609. _logger.LogInformation($"{heartRate.Serialno} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 已处理");
  2610. }
  2611. // 跳出循环
  2612. if (statEndTime.ToString("yyyyMMddHHmm") == boundaryStatEndTime.ToString("yyyyMMddHHmm"))
  2613. {
  2614. _logger.LogInformation($"{heartRate.Serialno} 胎动记录迭代完成跳出循环 ");
  2615. break;
  2616. }
  2617. else
  2618. {
  2619. _logger.LogInformation($"{heartRate.Serialno} 胎动周期{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}-{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}计算完成, ");
  2620. }
  2621. }
  2622. }
  2623. catch (Exception ex)
  2624. {
  2625. _logger.LogError($"处理胎动数据时发生错误: {ex.Message}");
  2626. }
  2627. }
  2628. public static DateTime GetSampleTimeFromLastUpdate(DateTime lastUpdate, int interval)
  2629. {
  2630. // 获取当前的分钟
  2631. int minute = lastUpdate.Minute;
  2632. // 按 15 分钟为单位划分时间段
  2633. int intervalStartMinute = (minute / interval) * interval;
  2634. // 返回当前时间刻度下的 DateTime,保留小时和新计算的分钟,秒和毫秒设为0
  2635. return new DateTime(lastUpdate.Year, lastUpdate.Month, lastUpdate.Day, lastUpdate.Hour, intervalStartMinute, 0, 0);
  2636. }
  2637. public static string ExtractImei(string input)
  2638. {
  2639. // 提取 'imei/' 后的数字
  2640. string pattern = @"imei/(\d+)";
  2641. Match match = Regex.Match(input, pattern);
  2642. if (match.Success)
  2643. {
  2644. return match.Groups[1].Value;
  2645. }
  2646. else
  2647. {
  2648. return string.Empty;
  2649. }
  2650. }
  2651. }
  2652. }