No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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