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

3083 line
201KB

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