您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
4 个月前
3 个月前
4 个月前
3 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
3 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
3 个月前
4 个月前
4 个月前
4 个月前
4 个月前
3 个月前
4 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
4 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
3 个月前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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.Threading.Channels;
  27. using TDengineDriver;
  28. using TDengineTMQ;
  29. using TelpoDataService.Util.Clients;
  30. using TelpoDataService.Util.Entities.GpsCard;
  31. using TelpoDataService.Util.Entities.GpsLocationHistory;
  32. using TelpoDataService.Util.Models;
  33. using TelpoDataService.Util.QueryObjects;
  34. namespace HealthMonitor.WebApi
  35. {
  36. public class Worker : BackgroundService
  37. {
  38. private readonly ILogger<Worker> _logger;
  39. private readonly IServiceProvider _services;
  40. private readonly TDengineDataSubcribe _tdEngineDataSubcribe;
  41. private readonly PackageProcess _processor;
  42. private readonly TDengineService _serviceTDengine;
  43. private readonly EtcdService _serviceEtcd;
  44. private readonly HttpHelper _httpHelper = default!;
  45. private readonly IotApiService _serviceIotApi;
  46. private readonly BoodPressResolverConfig _configBoodPressResolver;
  47. private readonly BloodPressReferenceValueCacheManager _bpRefValCacheManager;
  48. private readonly PersonCacheManager _personCacheMgr;
  49. private readonly DeviceCacheManager _deviceCacheMgr;
  50. private readonly FetalMovementNormalValueRangeCacheManager _mgrFetalMovementNormalValueRangeCache;
  51. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> _hisFetalHeartApiClient;
  52. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalMovement> _hisFetalMovementApiClient;
  53. private readonly MqProcessLogic _serviceMqProcess;
  54. private CancellationTokenSource _tokenSource = default!;
  55. public Worker(ILogger<Worker> logger, IServiceProvider services, PersonCacheManager personCacheMgr,
  56. BloodPressReferenceValueCacheManager bpRefValCacheManager, IotApiService IotApiService,
  57. IOptions<BoodPressResolverConfig> optionBoodPressResolver, PackageProcess processor,
  58. TDengineDataSubcribe tdEngineDataSubcribe, TDengineService serviceDengine,
  59. GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> hisFetalHeartApiClient,
  60. GpsLocationHistoryAccessorClient<HisGpsFetalMovement> hisFetalMovementApiClient,
  61. FetalMovementNormalValueRangeCacheManager fetalMovementNormalValueRangeCacheMgr, MqProcessLogic serviceMqProcess,
  62. HttpHelper httpHelper, EtcdService serviceEtcd, DeviceCacheManager deviceCacheMgr)
  63. {
  64. _logger = logger;
  65. _tdEngineDataSubcribe = tdEngineDataSubcribe;
  66. _services = services;
  67. _serviceIotApi = IotApiService;
  68. _processor = processor;
  69. _serviceEtcd = serviceEtcd;
  70. _serviceTDengine = serviceDengine;
  71. _httpHelper = httpHelper;
  72. _configBoodPressResolver = optionBoodPressResolver.Value;
  73. _bpRefValCacheManager = bpRefValCacheManager;
  74. _personCacheMgr = personCacheMgr;
  75. _deviceCacheMgr = deviceCacheMgr;
  76. _hisFetalHeartApiClient = hisFetalHeartApiClient;
  77. _hisFetalMovementApiClient = hisFetalMovementApiClient;
  78. _serviceMqProcess = serviceMqProcess;
  79. _mgrFetalMovementNormalValueRangeCache = fetalMovementNormalValueRangeCacheMgr;
  80. }
  81. public override Task StartAsync(CancellationToken cancellationToken)
  82. {
  83. //_logger.LogInformation("------StartAsync");
  84. _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  85. return base.StartAsync(cancellationToken);
  86. }
  87. public override Task StopAsync(CancellationToken cancellationToken)
  88. {
  89. //_logger.LogInformation("------StopAsync");
  90. _tokenSource.Cancel(); //停止工作线程
  91. return base.StopAsync(cancellationToken);
  92. }
  93. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  94. {
  95. var tasks = new[]
  96. {
  97. Task.Run(async () =>
  98. {
  99. _logger.LogInformation("解析器启动");
  100. while (!stoppingToken.IsCancellationRequested)
  101. {
  102. await _processor.ResolveAsync().ConfigureAwait(false);
  103. }
  104. }, stoppingToken),
  105. Task.Run(() =>
  106. {
  107. _logger.LogInformation("TDengine 订阅启动");
  108. while (!stoppingToken.IsCancellationRequested)
  109. {
  110. _tdEngineDataSubcribe.BeginListen(stoppingToken);
  111. }
  112. }, stoppingToken),
  113. Task.Run(() =>
  114. _serviceEtcd.WacthKeysWithPrefixResponseAsync("health_monitor/schedule_push", WatchEvents),
  115. stoppingToken)
  116. };
  117. await Task.WhenAll(tasks);
  118. }
  119. private void WatchEvents(WatchResponse response)
  120. {
  121. response.Events.ToList<Mvccpb.Event>().ForEach(async e =>
  122. {
  123. try
  124. {
  125. switch (e.Type.ToString())
  126. {
  127. case "Put":
  128. // 获取时间点计算TTL
  129. Console.BackgroundColor = ConsoleColor.Blue;
  130. Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  131. Console.BackgroundColor = ConsoleColor.Black;
  132. break;
  133. case "Delete":
  134. // TTL到了重新计算TTL,下发
  135. //Console.BackgroundColor = ConsoleColor.Green;
  136. //Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  137. // var key = $"health_monitor/schedule_push/imei/{bp.Serialno}";
  138. var key = e.Kv.Key.ToStringUtf8();
  139. var imeiDel = key.Split('/')[^1];
  140. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  141. if (string.IsNullOrWhiteSpace(schedule_push))
  142. {
  143. if (key.Contains("pregnancy_heart_rate"))
  144. {
  145. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  146. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  147. if (isFetalHeartEnable)
  148. {
  149. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容
  150. //var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! + 5;
  151. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容(最小highFreqSampleInterval=60)
  152. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! + 5 : 60;
  153. // 处理孕妇业务,计算一般心率并下发
  154. var commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(imeiDel, highFreqSampleInterval: highFreqSampleInterval);
  155. if (commonPHR == null)
  156. {
  157. // 建模中
  158. var flag = await _serviceIotApi.SetFetalConfig(imeiDel);
  159. _logger.LogInformation($"{imeiDel} 建模建模中");
  160. }
  161. else
  162. {
  163. // 建模完成
  164. var flag = await _serviceIotApi.SetFetalConfig(imeiDel, 1, commonPHR.MaxValue, commonPHR.MinValue);
  165. _logger.LogInformation($"{imeiDel} 建模完成");
  166. // 保存到TDengine数据库
  167. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR);
  168. _logger.LogInformation($"保存TDengine完成");
  169. //
  170. }
  171. }
  172. #region 注册定时下发
  173. var startTime = DateTime.Now;
  174. // 注册下次下推
  175. var endTime = DateTime.Now;
  176. #if DEBUG
  177. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  178. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  179. var interval = 0;
  180. // 获取当前时间
  181. DateTime now = DateTime.Now;
  182. // 计算距离下一个$interval天后的8点的时间间隔
  183. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  184. TimeSpan timeUntilNextRun = nextRunTime - now;
  185. // 如果当前时间已经超过了8点,将等待到明天后的8点
  186. if (timeUntilNextRun < TimeSpan.Zero)
  187. {
  188. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  189. nextRunTime += timeUntilNextRun;
  190. }
  191. //long ttl = timeUntilNextRun.Milliseconds/1000;
  192. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  193. var data = new
  194. {
  195. imei = imeiDel,
  196. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  197. ttl,
  198. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  199. };
  200. var result = JsonConvert.SerializeObject(data);
  201. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  202. #else
  203. // 每$interval天,晚上8点
  204. var interval = 1;
  205. // 获取当前时间
  206. DateTime now = DateTime.Now;
  207. var rand = new Random();
  208. var pushSec = rand.Next(59);
  209. int pushMin = int.TryParse(imeiDel.AsSpan(imeiDel.Length - 1), out pushMin) ? pushMin : 10;
  210. // 计算距离下一个$interval天后的0点的时间间隔
  211. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 6, pushMin, pushSec).AddDays(interval);
  212. TimeSpan timeUntilNextRun = nextRunTime - now;
  213. // 如果当前时间已经超过了8点,将等待到明天后的8点
  214. if (timeUntilNextRun < TimeSpan.Zero)
  215. {
  216. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  217. nextRunTime += timeUntilNextRun;
  218. }
  219. // var ttl = timeUntilNextRun.TotalMilliseconds;
  220. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  221. var data = new
  222. {
  223. imei = imeiDel,
  224. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  225. ttl,
  226. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  227. };
  228. var result = JsonConvert.SerializeObject(data);
  229. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  230. #endif
  231. #endregion
  232. }
  233. // health_monitor/schedule_push/cal_fetal_heart_rate/imei/
  234. else if (key.Contains("health_monitor/schedule_push/cal_fetal_heart_rate/imei/"))
  235. {
  236. /**
  237. var triggerValue= (JObject)JsonConvert.DeserializeObject(e.PrevKv.Value.ToStringUtf8())!;
  238. var trigger = triggerValue["trigger"]?.ToString();
  239. if (!string.IsNullOrEmpty(trigger))
  240. {
  241. var triggerHeartRate= JsonConvert.DeserializeObject<HisGpsHeartRate>(trigger);
  242. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = triggerHeartRate?.MessageId! }))
  243. {
  244. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  245. _logger.LogInformation($"触发常规心率计算胎心");
  246. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  247. if (isFetalHeartEnable)
  248. {
  249. // 告警上限阀值
  250. var upperAlarmThreshold = (int)watchConfig!["upperAlarmThreshold"]!;
  251. // 告警下限阀值
  252. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  253. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容(最小highFreqSampleInterval=60)
  254. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! + 5 : 60;
  255. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  256. // 最后一条孕妇心率
  257. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(imeiDel);
  258. var isNormalHeartRate = triggerHeartRate?.MessageId == lastPhr.MessageId;
  259. // 判断最后一条孕妇心率与解析器的触发心率是否一致
  260. if (isNormalHeartRate)
  261. {
  262. //最后一条孕妇心率与解析器的触发心率一致
  263. HisGpsHeartRate heartRate = new()
  264. {
  265. CreateTime = lastPhr.CreateTime,
  266. DeviceKey = lastPhr.DeviceKey,
  267. HeartRate = lastPhr.PregnancyHeartRate,
  268. HeartRateId = lastPhr.PregnancyHeartRateId,
  269. IsDisplay = lastPhr.IsDisplay ? 1 : 0,
  270. MessageId = lastPhr.MessageId,
  271. LastUpdate = lastPhr.LastUpdate,
  272. Method = lastPhr.Method,
  273. PersonId = lastPhr.PersonId,
  274. Serialno = lastPhr.SerialNumber
  275. };
  276. var intervalFHR = 15;
  277. await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  278. }
  279. // 最后一条孕妇心率与解析器的触发心率不一致,触发心率是高频心率的首条
  280. else
  281. {
  282. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  283. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(imeiDel);
  284. if (phrFreqstatus != null)
  285. {
  286. #region 高频缓存
  287. // 高频首条是触发心率,30秒后,高频第二条已经写入首条高频缓存
  288. var diffCount = phr.Where(i => i.CreateTime >= phrFreqstatus.CreateTime && i.CreateTime <= lastPhr.CreateTime)
  289. .OrderByDescending(i => i.CreateTime);
  290. _logger.LogInformation($"{imeiDel} 存在高频缓存,高频心率首条记录${phrFreqstatus.MessageId},高频首条到当前的MSG ID{string.Join(",",diffCount.Select(i=>i.MessageId))}");
  291. #endregion
  292. }
  293. // 不在高频状态状态,但触发孕妇心率与最后一条孕妇心率不一致,
  294. // 常规心率数据是批量上报,需要计算每条心率对应的胎心数据
  295. else
  296. {
  297. _logger.LogInformation($"{imeiDel} 常规心率数据是批量上报,需要计算每条心率对应的胎心数据");
  298. #region 计算每条心率对应的胎心数据
  299. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  300. // 获取高频数据
  301. var freqCollection = new List<PregnancyHeartRateModel>();
  302. PregnancyHeartRateModel? previousItem = null;
  303. foreach (var item in phr)
  304. {
  305. if (previousItem != null)
  306. {
  307. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  308. if (timeNextDiff <= highFreqSampleInterval)
  309. {
  310. freqCollection.Add(item);
  311. }
  312. }
  313. previousItem = item;
  314. }
  315. //去除高频
  316. foreach (var item in freqCollection)
  317. {
  318. phr.Remove(item);
  319. }
  320. // 排序并过滤高频数据
  321. //var previousItem = phr.OrderByDescending(i => i.LastUpdate).ToList().First();
  322. //phr = phr.Skip(1)
  323. // .Where(item =>
  324. // {
  325. // var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  326. // previousItem = item;
  327. // return timeNextDiff > highFreqSampleInterval;
  328. // })
  329. // .Prepend(previousItem)
  330. // .OrderByDescending(i => i.LastUpdate)
  331. // .ToList();
  332. var calFhrTasks = phr.Where(p => p.LastUpdate >= triggerHeartRate!.LastUpdate)
  333. .Select( async p =>
  334. {
  335. HisGpsHeartRate heartRate = new()
  336. {
  337. CreateTime = p.CreateTime,
  338. DeviceKey = p.DeviceKey,
  339. HeartRate = p.PregnancyHeartRate,
  340. HeartRateId = p.PregnancyHeartRateId,
  341. IsDisplay = p.IsDisplay ? 1 : 0,
  342. MessageId = p.MessageId,
  343. LastUpdate = p.LastUpdate,
  344. Method = p.Method,
  345. PersonId = p.PersonId,
  346. Serialno = p.SerialNumber
  347. };
  348. var intervalFHR = 15;
  349. await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  350. });
  351. await Task.WhenAll(calFhrTasks);
  352. #endregion
  353. }
  354. }
  355. }
  356. else
  357. {
  358. _logger.LogWarning($"{imeiDel} 胎心监测功能没有开启");
  359. }
  360. }
  361. }
  362. else
  363. {
  364. _logger.LogWarning($"{imeiDel} trigger is not set");
  365. }
  366. */
  367. }
  368. //health_monitor/schedule_push/cal_fetal_movement/imei/
  369. else if (key.Contains("health_monitor/schedule_push/cal_fetal_movement/imei/"))
  370. {
  371. #region 胎动延时计算
  372. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  373. _logger.LogInformation($"触发胎动计算,设备配置{JsonConvert.SerializeObject(watchConfig)}");
  374. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  375. if (isFetalHeartEnable)
  376. {
  377. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  378. // 已经建模
  379. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  380. if (commonPHR != null)
  381. {
  382. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  383. _logger.LogInformation($"{imeiDel} 计算胎动数据 ");
  384. var fmNow = DateTime.Now;
  385. // 两小时前
  386. var fmNowSubtract = fmNow.AddMinutes(-fmNow.Minute).AddSeconds(-fmNow.Second).AddMilliseconds(-fmNow.Millisecond);
  387. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(fmNowSubtract).ToString()[..10];
  388. // 统计开始时间
  389. var statStartTime = fmNowSubtract.AddHours(-2);
  390. // 统计结束时间
  391. var statEndTime = fmNowSubtract;
  392. var isFetalMovementExisted = await _deviceCacheMgr.FetalMovementIsExistedAsync(imeiDel, fetalMovementSampleTime);
  393. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 开始");
  394. if (!isFetalMovementExisted)
  395. {
  396. /// 开始计算
  397. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate <= statEndTime)
  398. .OrderByDescending(i => i.LastUpdate)
  399. .Select(i => i.LastUpdate)
  400. .ToList();
  401. // 判断是否有持续佩戴
  402. if (phrRange.Count >= 2)
  403. {
  404. // 读取胎心数据
  405. GeneralParam param = new()
  406. {
  407. Filters = new List<QueryFilterCondition>
  408. {
  409. new ()
  410. {
  411. Key=nameof(HisGpsFetalHeartRate.Serialno),
  412. Value=imeiDel,
  413. ValueType=QueryValueTypeEnum.String,
  414. Operator=QueryOperatorEnum.Equal
  415. },
  416. //new ()
  417. //{
  418. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  419. // Value=sampleTime,
  420. // ValueType=QueryValueTypeEnum.String,
  421. // Operator=QueryOperatorEnum.GreaterEqual
  422. //},
  423. },
  424. OrderBys = new List<OrderByCondition>
  425. {
  426. new (){
  427. IsDesc=true,
  428. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  429. }
  430. }
  431. };
  432. var fetalHeartRateIsAbnormal = 0;
  433. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  434. // 胎心数据时间与胎动时间一致
  435. var time = long.Parse(fhr.SampleTime.Length < 13 ? fhr.SampleTime.PadRight(13, '0') : fhr.SampleTime);
  436. var fhrSampleTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(time);
  437. // 胎心数据时间与胎动时间一致,最后一条胎心数据与胎动数据的小时差不大于2
  438. if ((DateTime.Now.Hour - fhrSampleTime.Hour) <= 2)
  439. {
  440. var duringMins = Math.Abs((phrRange.First() - phrRange.Last()).TotalMinutes);
  441. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  442. bool isInTimeRanges = IsLastUpdateInTimeRanges(phrRange.First());
  443. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  444. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  445. {
  446. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  447. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  448. .Where(i =>
  449. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  450. i.PregnancyPeriod[1] >= pregnancyWeeks)
  451. .Select(i => i.MedianMovement)
  452. .FirstOrDefault()
  453. :
  454. fetalMovementMap
  455. .Where(i =>
  456. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  457. i.PregnancyPeriod[1] >= pregnancyWeeks)
  458. .Select(i => i.InitialMovement)
  459. .FirstOrDefault()
  460. ;
  461. var fetalMovementValue = (fetalMovementMapValue * duringMins * 2) / 120;
  462. // 四舍五入
  463. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  464. // _logger.LogInformation($"{imeiDel} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");
  465. _logger.LogInformation($"{imeiDel} 孕周:{pregnancyWeeks},胎动数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 原始胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{phrRange.Last()}-{phrRange.First()}, 胎动计算值:{fetalMovementValue}, 胎动最终值:{fetalMovement} 已完成.");
  466. // 获取胎心数据状态与胎动数据状态一致
  467. //etalHeartRateIsAbnormal= fhr.IsAbnormal;
  468. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  469. await _serviceIotApi.SetFetalMovementConfig(imeiDel, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  470. // 保存到MySQL数据库
  471. HisGpsFetalMovement fm = new()
  472. {
  473. FetalMovementId = Guid.NewGuid().ToString("D"),
  474. PersonId = commonPHR!.PersonId,
  475. Serialno = imeiDel,
  476. CreateTime = DateTime.Now,
  477. IsAbnormal = feltalMovementIsAbnormal,
  478. FetalMovementValue = fetalMovement,
  479. SampleTime = fetalMovementSampleTime,
  480. Method = 1,
  481. IsDisplay = 1,
  482. DeviceKey = commonPHR!.DeviceKey
  483. };
  484. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  485. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(imeiDel).ConfigureAwait(false);
  486. var fmMsgId = $"{imeiDel}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  487. var fmMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  488. // 胎动数据推送到第三方
  489. var topic = "topic.push.third";
  490. var fmThridMsg = new
  491. {
  492. messageId = fmMsgId,
  493. topic = topic,
  494. time = fmMsgTime,
  495. data = new
  496. {
  497. imei = imeiDel,
  498. value = fetalMovement,
  499. isAbnormal = feltalMovementIsAbnormal,
  500. type = "fetalMovement"
  501. }
  502. };
  503. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, 31, fmThridMsg).ConfigureAwait(false);
  504. // 胎动数据推送到微信
  505. if (feltalMovementIsAbnormal != 0)
  506. {
  507. topic = "topic.push.wx";
  508. var fmMsg = new
  509. {
  510. messageId = Guid.NewGuid().ToString("D"),
  511. topic = topic,
  512. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
  513. data = new
  514. {
  515. deviceId = device?.DeviceId,
  516. imei = imeiDel,
  517. alarmTypeId = 12,
  518. alarmDeviceName = imeiDel,
  519. alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
  520. address = string.Empty,
  521. deviceKey = device?.DeviceId
  522. }
  523. };
  524. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
  525. }
  526. // 设置入库缓存记录
  527. await _deviceCacheMgr.SetFetalMovementAsync(imeiDel, fetalMovementSampleTime, fm);
  528. }
  529. else
  530. {
  531. _logger.LogWarning($"{imeiDel} 孕周 {pregnancyWeeks},超出胎动计算范围");
  532. }
  533. }
  534. else
  535. {
  536. _logger.LogWarning($"{imeiDel} 最后一条胎心数据与胎动数据的小时差大于2,不计算胎动数据");
  537. }
  538. }
  539. else
  540. {
  541. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 不足两条,不能判断是否持续佩戴");
  542. }
  543. }
  544. else
  545. {
  546. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 已处理");
  547. }
  548. }
  549. }
  550. #endregion
  551. }
  552. else
  553. {
  554. // 处理血压业务
  555. int systolicInc;
  556. int diastolicInc;
  557. int systolicRefValue;
  558. int diastolicRefValue;
  559. decimal systolicAvg;
  560. decimal diastolicAvg;
  561. int systolicMax = 0;
  562. int diastolicMax = 0;
  563. // 统计时间
  564. //DateTime endTime = DateTime.Now; //测试
  565. DateTime statStartTime = DateTime.Now;
  566. // 最小值
  567. int systolicMin = 0;
  568. int diastolicMin = 0;
  569. // 偏移参数
  570. var avgOffset = 0.25M;
  571. var systolicAvgOffset = avgOffset;
  572. var diastolicAvgOffset = avgOffset;
  573. // 最后一次下发值
  574. int lastPushSystolicInc = 0;
  575. int lastPushDiastolicInc = 0;
  576. var startTime = DateTime.Now;
  577. // 下发增量值
  578. #region 统计定时下发增量值
  579. //var last = await _serviceTDengine.GetLastAsync("stb_hm_bloodpress_stats_inc", $"serialno='{imeiDel}' order by last_update desc");
  580. //var ts = last?[0];
  581. // 最后一条血压数据
  582. var condition = $"serialno='{imeiDel}' order by last_update desc";
  583. var field = "last_row(*)";
  584. var lastHmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition, field);
  585. var lastHmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(lastHmBpResponse!);
  586. var lastHmBp = lastHmBpParser?.Select().FirstOrDefault();
  587. //if (lastHmBpParser?.Select()?.ToList().Count < 2)
  588. //{
  589. // _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 血压数据条目不足");
  590. // break;
  591. //}
  592. // 7 天有效数据
  593. if (lastHmBp?.Timestamp.AddDays(7) > DateTime.Now)
  594. {
  595. // 计算增量值
  596. condition = $"serialno='{imeiDel}' order by ts desc";
  597. var lastPushResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bp_push_ref_inc_value", condition, field);
  598. if (lastPushResponse == null)
  599. {
  600. _logger.LogInformation($"{imeiDel}--没有下发记录");
  601. break;
  602. }
  603. var lastPushParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressurePushRefIncModel>>(lastPushResponse);
  604. var lastPush = lastPushParser!.Select().FirstOrDefault();
  605. // 有下推记录
  606. if (lastPush != null)
  607. {
  608. systolicRefValue = lastPush!.SystolicRefValue;
  609. diastolicRefValue = lastPush!.DiastolicRefValue;
  610. lastPushSystolicInc = lastPush!.SystolicIncValue;
  611. lastPushDiastolicInc = lastPush!.DiastolicIncValue;
  612. condition = $"ts between '{lastPush?.Timestamp:yyyy-MM-dd HH:mm:ss.fff}' and '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  613. $"and serialno='{imeiDel}' " +
  614. $"and is_display = true";
  615. // 使用最近一次的下推时间作为统计的开始时间
  616. statStartTime = lastPush!.Timestamp;
  617. }
  618. // 没有下推记录(历史遗留数据),没有初始的测量值产生的平均值(测量值=平均值)
  619. else
  620. {
  621. #region 获取个人信息
  622. var person = await _personCacheMgr.GetDeviceGpsPersonCacheBySerialNoAsync(Guid.NewGuid().ToString(), imeiDel).ConfigureAwait(false);
  623. //验证这个信息是否存在
  624. if (person == null || person?.Person.BornDate == null)
  625. {
  626. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证个人信息,找不到个人信息,跳过此消息");
  627. break;
  628. }
  629. // 验证年龄是否在范围 (2 - 120)
  630. var age = SafeType.SafeInt(DateTime.Today.Year - person?.Person.BornDate!.Value.Year!);
  631. if (age < 2 || age > 120)
  632. {
  633. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证年龄,不在范围 (2 - 120)岁,跳过此消息");
  634. break;
  635. }
  636. var gender = person?.Person.Gender == true ? 1 : 2;
  637. var isHypertension = SafeType.SafeBool(person?.Person.Ishypertension!);
  638. var height = SafeType.SafeDouble(person?.Person.Height!);
  639. var weight = SafeType.SafeDouble(person?.Person.Weight!);
  640. #endregion
  641. #region 初始化常规血压标定值标定值
  642. var bpRef = await _bpRefValCacheManager.GetBloodPressReferenceValueAsync(age, gender, isHypertension);
  643. //systolicRefValue = bpRef!.Systolic;//?
  644. //diastolicRefValue = bpRef!.Diastolic;//?
  645. #endregion
  646. systolicRefValue = bpRef!.Systolic;
  647. diastolicRefValue = bpRef!.Diastolic;
  648. lastPushSystolicInc = 0;
  649. lastPushDiastolicInc = 0;
  650. condition = $"ts <= '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  651. $"and serialno='{imeiDel}' " +
  652. $"and is_display = true";
  653. }
  654. var hmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition);
  655. var hmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(hmBpResponse!);
  656. var hmBp = hmBpParser?.Select();
  657. //if (hmBp?.ToList().Count < 2)
  658. // 1. 判断数据样本数量
  659. if (hmBpParser!.Rows < 5)
  660. {
  661. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 统计定时下发,计算增量值的数据条目不足:{hmBpParser!.Rows} < 5");
  662. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} 没有足够的数据样本,不会定时下发");
  663. break;
  664. }
  665. // 没有下推记录重新计算统计时间
  666. if (lastPush == null)
  667. {
  668. var firstHmBp = hmBpParser?.Select(i => i).OrderBy(i => i.Timestamp).FirstOrDefault();
  669. statStartTime = firstHmBp!.Timestamp;
  670. }
  671. // NewMethod(systolicRefValue, hmBpParser);
  672. // 最大值
  673. //systolicMax = (int)hmBpParser?.Select(i => i.SystolicValue).Max()!;
  674. //diastolicMax = (int)hmBpParser?.Select(i => i.DiastolicValue).Max()!;
  675. //// 最小值
  676. //systolicMin = (int)hmBpParser?.Select(i => i.SystolicValue).Min()!;
  677. //diastolicMin = (int)hmBpParser?.Select(i => i.DiastolicValue).Min()!;
  678. //systolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.SystolicValue, SafeType.SafeInt(systolicRefValue!)))!;
  679. //diastolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.DiastolicValue, SafeType.SafeInt(diastolicRefValue!)))!;
  680. var avgs = _serviceTDengine.AverageAfterRemovingOneMinMaxRef(hmBpParser!);
  681. systolicAvg = avgs[0];
  682. diastolicAvg = avgs[1];
  683. // 2. 判断能否计算增量值
  684. if (systolicAvg.Equals(0))
  685. {
  686. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算平均值" +
  687. $"\n currentSystolicAvg:{systolicAvg} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  688. $"\n currentDiastolicInc:{diastolicAvg} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  689. _logger.LogInformation($"{imeiDel}--{nameof(Worker)} 没有足够的数据样本计算平均值,不会定时下发");
  690. break;
  691. }
  692. // 除最大值和最小值后的平均值与标定值差值少于4后(当天计算出该结果则也不产生增量调整),就不再进行增量值调整了。
  693. if (systolicRefValue - systolicAvg < 4)
  694. {
  695. _logger.LogInformation($"diastolic 舒张压 {imeiDel}除最大值和最小值后的平均值:{diastolicAvg}与标定值:{diastolicRefValue}\n systolic 收缩压 {imeiDel}除最大值和最小值后的平均值:{systolicAvg}与标定值:{systolicRefValue}的差值(标定值-平均值)少于4后,systolic 收缩压 不再进行增量值调整");
  696. break;
  697. }
  698. if (diastolicRefValue - diastolicAvg < 4)
  699. {
  700. _logger.LogInformation($"systolic 收缩压 {imeiDel}除最大值和最小值后的平均值:{systolicAvg}与标定值:{systolicRefValue}\n diastolic 舒张压 {imeiDel}除最大值和最小值后的平均值:{diastolicAvg}与标定值:{diastolicRefValue}的差值(标定值-平均值)少于4后,diastolic 舒张压 不再进行增量值调整");
  701. break;
  702. }
  703. // 增量值=(标定值-平均值)* 0.25
  704. var currentSystolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
  705. var currentDiastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
  706. // 累计增量
  707. systolicInc = currentSystolicInc + lastPushSystolicInc;
  708. diastolicInc = currentDiastolicInc + lastPushDiastolicInc;
  709. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算增量值" +
  710. $"\n {imeiDel} -- systolicAvg:{systolicAvg}-- systolicInc:{systolicInc}-- currentSystolicInc:{currentSystolicInc} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  711. $"\n {imeiDel} -- diastolicAvg:{diastolicAvg}-- diastolicInc:{diastolicInc} --currentDiastolicInc:{currentDiastolicInc} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  712. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}-- 定时校准,发给设备的绝对增量值=(上次绝对增量值+新数据的增量值)");
  713. _logger.LogInformation($"{nameof(Worker)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
  714. if (_configBoodPressResolver.EnableBPRefPush)
  715. // if (false) // 临时关闭
  716. {
  717. BloodPressCalibrationConfigModel bpIncData = new()
  718. {
  719. Imei = imeiDel,
  720. SystolicRefValue = SafeType.SafeInt(((int)systolicRefValue!)), //收缩压标定值,值为0 表示不生效
  721. DiastolicRefValue = SafeType.SafeInt(((int)diastolicRefValue!)), //舒张压标定值,值为0表示不生效
  722. SystolicIncValue = SafeType.SafeInt(((int)systolicInc!)), //收缩压显示增量,值为0 表示不生效
  723. DiastolicIncValue = SafeType.SafeInt(((int)diastolicInc!)) //舒张压显示增量,值为0 表示不生效
  724. };
  725. //var pushedBP = await _serviceIotApi.SetBloodPressCalibrationConfigAsync(bpIncData).ConfigureAwait(false);
  726. var response = await _serviceIotApi.SetBloodPressCalibrationConfig2Async(bpIncData).ConfigureAwait(false);
  727. var pushedBP = response.Flag;
  728. if (pushedBP)
  729. {
  730. #region 保存下推记录 stb_hm_bp_push_ref_inc_value
  731. var sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{imeiDel.Substring(imeiDel.Length - 2)} " +
  732. $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
  733. $"TAGS ('{imeiDel.Substring(imeiDel.Length - 2)}') " +
  734. $"VALUES(" +
  735. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  736. $"'{imeiDel}'," +
  737. $"{bpIncData.SystolicRefValue}," +
  738. $"{bpIncData.DiastolicRefValue}," +
  739. $"{bpIncData.SystolicIncValue}," +
  740. $"{bpIncData.DiastolicIncValue}," +
  741. $"{false}," +
  742. $"{systolicAvg}," +
  743. $"{diastolicAvg}," +
  744. $"{systolicAvgOffset}," +
  745. $"{diastolicAvgOffset}," +
  746. $"'{statStartTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  747. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'" +
  748. $")";
  749. _serviceTDengine.ExecuteInsertSQL(sql);
  750. #endregion
  751. #region 注册定时下发
  752. // 注册下次下推
  753. var endTime = DateTime.Now;
  754. #if DEBUG
  755. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  756. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  757. var interval = 0;
  758. // 获取当前时间
  759. DateTime now = DateTime.Now;
  760. // 计算距离下一个$interval天后的8点的时间间隔
  761. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  762. TimeSpan timeUntilNextRun = nextRunTime - now;
  763. // 如果当前时间已经超过了8点,将等待到明天后的8点
  764. if (timeUntilNextRun < TimeSpan.Zero)
  765. {
  766. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  767. nextRunTime += timeUntilNextRun;
  768. }
  769. // var ttl = timeUntilNextRun.TotalMilliseconds;
  770. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  771. var data = new
  772. {
  773. imei = imeiDel,
  774. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  775. ttl,
  776. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  777. };
  778. var result = JsonConvert.SerializeObject(data);
  779. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  780. #else
  781. // 每$interval天,晚上8点
  782. var interval = 1;
  783. // 获取当前时间
  784. DateTime now = DateTime.Now;
  785. // 计算距离下一个$interval天后的8点的时间间隔
  786. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 20, 0, 0).AddDays(interval);
  787. TimeSpan timeUntilNextRun = nextRunTime - now;
  788. // 如果当前时间已经超过了8点,将等待到明天后的8点
  789. if (timeUntilNextRun < TimeSpan.Zero)
  790. {
  791. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  792. nextRunTime += timeUntilNextRun;
  793. }
  794. // var ttl = timeUntilNextRun.TotalMilliseconds;
  795. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  796. var data = new
  797. {
  798. imei = imeiDel,
  799. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  800. ttl,
  801. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  802. };
  803. var result = JsonConvert.SerializeObject(data);
  804. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  805. #endif
  806. #endregion
  807. }
  808. else
  809. {
  810. _logger.LogInformation($"错误响应,没有下推数据:{response.Message}");
  811. }
  812. }
  813. }
  814. else
  815. {
  816. _logger.LogInformation($"向{imeiDel}统计数据已经失效");
  817. }
  818. #endregion
  819. }
  820. }
  821. break;
  822. }
  823. }
  824. catch (Exception ex)
  825. {
  826. _logger.LogInformation($"{nameof(WatchEvents)},出错: |{ex.Message}|{ex.StackTrace}");
  827. }
  828. });
  829. }
  830. private async Task SetIntervalTriggerAsync(string key, string imei, long interval)
  831. {
  832. // var key = $"health_monitor/schedule_push/{type}/imei/{imei}";
  833. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  834. if (string.IsNullOrWhiteSpace(schedulePush))
  835. {
  836. var now = DateTime.Now;
  837. var timeNextRun = now.Add(TimeSpan.FromSeconds(interval));
  838. var data = new
  839. {
  840. imei,
  841. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  842. ttl = interval,
  843. next_run_time = timeNextRun.ToString("yyyy-MM-dd HH:mm:ss")
  844. };
  845. var result = JsonConvert.SerializeObject(data);
  846. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  847. }
  848. }
  849. public static bool IsNowInTimeRanges()
  850. {
  851. var now = DateTime.Now.TimeOfDay;
  852. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  853. {
  854. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  855. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  856. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  857. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  858. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  859. };
  860. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  861. }
  862. public static bool IsLastUpdateInTimeRanges(DateTime lastUpdate)
  863. {
  864. var now = lastUpdate.TimeOfDay;
  865. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  866. {
  867. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  868. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  869. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  870. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  871. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  872. };
  873. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  874. }
  875. private async Task CalculateNormalFetalHeartRateAsync(HisGpsHeartRate heartRate, int upperAlarmThreshold, int lowerAlarmThreshold, int intervalFHR, PregnancyCommonHeartRateModel? commonPHR)
  876. {
  877. // 上15分钟的数据
  878. // 获取当前时间
  879. DateTime nowInterval = (DateTime)heartRate.LastUpdate!;
  880. if (nowInterval.Second > 0)
  881. {
  882. nowInterval = nowInterval.AddMinutes(1);
  883. }
  884. // 计算last_update到上一间隔的分钟数
  885. int minutesToSubtract = nowInterval.Minute % intervalFHR;
  886. // 计算上一间隔的时间
  887. DateTime previousInterval = nowInterval.AddMinutes(-minutesToSubtract).AddSeconds(-nowInterval.Second).AddMilliseconds(-nowInterval.Millisecond);
  888. // 使用 last_update 上一刻
  889. var sampleTimeFHR = DateTimeUtil.ConvertToTimeStamp(previousInterval).ToString();
  890. // 计算last_update到下一间隔的分钟数
  891. int minutesToAdd = intervalFHR - (nowInterval.Minute % intervalFHR);
  892. if (minutesToAdd == intervalFHR)
  893. {
  894. minutesToAdd = 0; // 如果已经是间隔,则不需要增加分钟
  895. }
  896. // 计算下一间隔的时间
  897. DateTime nextInterval = nowInterval.AddMinutes(minutesToAdd)
  898. .AddSeconds(-nowInterval.Second)
  899. .AddMilliseconds(-nowInterval.Millisecond);
  900. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  901. var normalPhrStatStartTime = nextInterval.AddMinutes(-intervalFHR);
  902. var normalPhrStatEndTime = nextInterval;
  903. _logger.LogInformation($" {heartRate.MessageId} -- {heartRate.Serialno} 计算胎心数据, 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} ");
  904. var filteredPhr = daysPhr
  905. // 使用 last_update 下一刻
  906. .Where(i => i.LastUpdate <= normalPhrStatEndTime && i.LastUpdate >= normalPhrStatStartTime)
  907. .ToList();
  908. if (filteredPhr.Count == 0)
  909. {
  910. _logger.LogWarning($"{heartRate.MessageId} -- {heartRate.Serialno} 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} 孕妇心率数据不足,{filteredPhr.Count}条记录");
  911. return;
  912. }
  913. var phrValue = filteredPhr.Count == 1
  914. ? filteredPhr.First().PregnancyHeartRate
  915. : filteredPhr.Average(i => i.PregnancyHeartRate);
  916. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, phrValue, sampleTimeFHR);
  917. await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, phrValue, sampleTimeFHR, normalPhrStatStartTime, normalPhrStatEndTime);
  918. }
  919. private async Task SaveAndPushFetalHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int upperAlarmThreshold, int lowerAlarmThreshold, double phrValue, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  920. {
  921. // 计算胎心=孕妇心率*系数
  922. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  923. //fetalHeartRate = fetalHeartRate > 220 ? 220 : fetalHeartRate; // 胎心的最大值调整为220,超过都按该值220输出
  924. if (fetalHeartRate >= 220)
  925. {
  926. // 先使用最小系数计算
  927. var statMaxValueFprCoefficient = commonPHR?.StatMaxValueFprCoefficient!;
  928. var statMinValueFprCoefficient = commonPHR?.StatMinValueFprCoefficient!;
  929. var coefficient = statMaxValueFprCoefficient < statMinValueFprCoefficient ? statMaxValueFprCoefficient : statMinValueFprCoefficient;
  930. fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  931. if (fetalHeartRate < 220)
  932. {
  933. _logger.LogWarning($"{heartRate.Serialno} 使用极值系数 {coefficient} ,建模数据可能出现异常,请检查");
  934. }
  935. else
  936. {
  937. fetalHeartRate = 220;
  938. _logger.LogWarning($"{heartRate.Serialno} 使用所有系数都不能放映实际,建模数据可能出现异常,请检查");
  939. }
  940. }
  941. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  942. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  943. if (phrFreqstatus == null) isAbnormal = 0;
  944. var statsusDesc = (phrFreqstatus == null) ? $"MSG ID: {heartRate.MessageId} 常规" : "高频";
  945. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,心率值{heartRate.HeartRate},生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  946. //if (!isFreq)
  947. //{
  948. // statStartTime = heartRate.LastUpdate;
  949. //
  950. //}
  951. // 保存到 数据服务 MySQL 数据库
  952. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  953. {
  954. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  955. PersonId = commonPHR!.PersonId,
  956. Serialno = heartRate.Serialno,
  957. HeartRate = fetalHeartRate,
  958. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  959. IsAbnormal = isAbnormal,
  960. StatStartTime = statStartTime,
  961. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  962. CreateTime = DateTime.Now,
  963. Method = 1,
  964. IsDisplay = 1,
  965. DeviceKey = commonPHR!.DeviceKey
  966. };
  967. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  968. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  969. // 推送最后一条常规心率计算的胎心数据到iot设备
  970. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  971. if (lastPhr.MessageId== heartRate.MessageId)
  972. {
  973. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  974. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备");
  975. }
  976. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  977. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  978. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  979. // 胎心数据推送到第三方
  980. var topic = "topic.push.third";
  981. var fhrThridMsg = new
  982. {
  983. messageId = fhrMsgId,
  984. topic = topic,
  985. time = fhrMsgTime,
  986. data = new
  987. {
  988. imei = heartRate.Serialno,
  989. value = fetalHeartRate,
  990. isAbnormal,
  991. type = "fetalHeart"
  992. }
  993. };
  994. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  995. // 胎心数据推送到微信
  996. if (isAbnormal != 0)
  997. {
  998. topic = "topic.push.wx";
  999. var fhrMsg = new
  1000. {
  1001. messageId = fhrMsgId,
  1002. topic = topic,
  1003. time = fhrMsgTime,
  1004. data = new
  1005. {
  1006. deviceId = device?.DeviceId,
  1007. imei = heartRate.Serialno,
  1008. alarmTypeId = 12,
  1009. alarmDeviceName = heartRate.Serialno,
  1010. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  1011. address = string.Empty,
  1012. deviceKey = device?.DeviceId
  1013. }
  1014. };
  1015. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  1016. }
  1017. }
  1018. }
  1019. }