Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

3073 linhas
200KB

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