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.

Worker.cs 153KB

3 maanden geleden
1 jaar geleden
1 jaar geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
1 jaar geleden
1 jaar geleden
4 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
1 jaar geleden
4 maanden geleden
1 jaar geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
1 jaar geleden
4 maanden geleden
1 jaar geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
11 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
2 maanden geleden
4 maanden geleden
2 maanden geleden
4 maanden geleden
2 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
2 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
2 maanden geleden
4 maanden geleden
2 maanden geleden
4 maanden geleden
2 maanden geleden
4 maanden geleden
2 maanden geleden
4 maanden geleden
2 maanden geleden
4 maanden geleden
2 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
3 maanden geleden
4 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
3 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
3 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
2 maanden geleden
3 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
11 maanden geleden
4 maanden geleden
11 maanden geleden
4 maanden geleden
11 maanden geleden
4 maanden geleden
11 maanden geleden
4 maanden geleden
11 maanden geleden
4 maanden geleden
11 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
11 maanden geleden
4 maanden geleden
11 maanden geleden
2 maanden geleden
11 maanden geleden
4 maanden geleden
1 jaar geleden
4 maanden geleden
4 maanden geleden
1 jaar geleden
11 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
11 maanden geleden
4 maanden geleden
11 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
1 jaar geleden
4 maanden geleden
4 maanden geleden
1 jaar geleden
4 maanden geleden
4 maanden geleden
11 maanden geleden
4 maanden geleden
4 maanden geleden
4 maanden geleden
11 maanden geleden
4 maanden geleden
2 maanden geleden
4 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
3 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
2 maanden geleden
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236
  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 GpsLocationHistoryAccessorClient<HisGpsPsychResult> _hisPsychResultApiClient;
  54. private readonly MqProcessLogic _serviceMqProcess;
  55. private CancellationTokenSource _tokenSource = default!;
  56. private static int INTERVAL_FHR = 15;
  57. public Worker(ILogger<Worker> logger, IServiceProvider services, PersonCacheManager personCacheMgr,
  58. BloodPressReferenceValueCacheManager bpRefValCacheManager, IotApiService IotApiService,
  59. IOptions<BoodPressResolverConfig> optionBoodPressResolver, PackageProcess processor,
  60. TDengineDataSubcribe tdEngineDataSubcribe, TDengineService serviceDengine,
  61. GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> hisFetalHeartApiClient,
  62. GpsLocationHistoryAccessorClient<HisGpsFetalMovement> hisFetalMovementApiClient,
  63. GpsLocationHistoryAccessorClient<HisGpsPsychResult> hisGpsPsychResultApiClient,
  64. FetalMovementNormalValueRangeCacheManager fetalMovementNormalValueRangeCacheMgr, MqProcessLogic serviceMqProcess,
  65. HttpHelper httpHelper, EtcdService serviceEtcd, DeviceCacheManager deviceCacheMgr)
  66. {
  67. _logger = logger;
  68. _tdEngineDataSubcribe = tdEngineDataSubcribe;
  69. _services = services;
  70. _serviceIotApi = IotApiService;
  71. _processor = processor;
  72. _serviceEtcd = serviceEtcd;
  73. _serviceTDengine = serviceDengine;
  74. _httpHelper = httpHelper;
  75. _configBoodPressResolver = optionBoodPressResolver.Value;
  76. _bpRefValCacheManager = bpRefValCacheManager;
  77. _personCacheMgr = personCacheMgr;
  78. _deviceCacheMgr = deviceCacheMgr;
  79. _hisFetalHeartApiClient = hisFetalHeartApiClient;
  80. _hisFetalMovementApiClient = hisFetalMovementApiClient;
  81. _hisPsychResultApiClient = hisGpsPsychResultApiClient;
  82. _serviceMqProcess = serviceMqProcess;
  83. _mgrFetalMovementNormalValueRangeCache = fetalMovementNormalValueRangeCacheMgr;
  84. }
  85. public override Task StartAsync(CancellationToken cancellationToken)
  86. {
  87. //_logger.LogInformation("------StartAsync");
  88. _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  89. return base.StartAsync(cancellationToken);
  90. }
  91. public override Task StopAsync(CancellationToken cancellationToken)
  92. {
  93. //_logger.LogInformation("------StopAsync");
  94. _tokenSource.Cancel(); //停止工作线程
  95. return base.StopAsync(cancellationToken);
  96. }
  97. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  98. {
  99. var tasks = new[]
  100. {
  101. Task.Run(async () =>
  102. {
  103. _logger.LogInformation("解析器启动");
  104. while (!stoppingToken.IsCancellationRequested)
  105. {
  106. await _processor.ResolveAsync().ConfigureAwait(false);
  107. }
  108. }, stoppingToken),
  109. Task.Run(() =>
  110. {
  111. _logger.LogInformation("TDengine 订阅启动");
  112. while (!stoppingToken.IsCancellationRequested)
  113. {
  114. _tdEngineDataSubcribe.BeginListen(stoppingToken);
  115. }
  116. }, stoppingToken),
  117. Task.Run(() =>
  118. _serviceEtcd.WacthKeysWithPrefixResponseAsync("health_monitor/schedule_push", WatchEvents),
  119. stoppingToken)
  120. };
  121. await Task.WhenAll(tasks);
  122. }
  123. private void WatchEvents(WatchResponse response)
  124. {
  125. response.Events.ToList<Mvccpb.Event>().ForEach(async e =>
  126. {
  127. try
  128. {
  129. switch (e.Type.ToString())
  130. {
  131. case "Put":
  132. // 获取时间点计算TTL
  133. Console.BackgroundColor = ConsoleColor.Blue;
  134. Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  135. Console.BackgroundColor = ConsoleColor.Black;
  136. break;
  137. case "Delete":
  138. // TTL到了重新计算TTL,下发
  139. //Console.BackgroundColor = ConsoleColor.Green;
  140. //Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  141. // var key = $"health_monitor/schedule_push/imei/{bp.Serialno}";
  142. var key = e.Kv.Key.ToStringUtf8();
  143. var imeiDel = key.Split('/')[^1];
  144. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  145. if (string.IsNullOrWhiteSpace(schedule_push))
  146. {
  147. // 胎心数据建模
  148. if (key.Contains("pregnancy_heart_rate"))
  149. {
  150. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = $"MODE-{imeiDel}-{DateTime.Now.ToString("yyyyMMddHHmmss")}" }))
  151. {
  152. #region 胎心数据建模
  153. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  154. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  155. if (isFetalHeartEnable)
  156. {
  157. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容
  158. //var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! + 5;
  159. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容(最小highFreqSampleInterval=60)
  160. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! + 5 : 60;
  161. // 处理孕妇业务,计算一般心率并下发
  162. var commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(imeiDel, highFreqSampleInterval: highFreqSampleInterval);
  163. if (commonPHR == null)
  164. {
  165. // 建模中
  166. var flag = await _serviceIotApi.SetFetalConfig(imeiDel);
  167. _logger.LogInformation($"{imeiDel} 建模建模中");
  168. }
  169. else
  170. {
  171. // 建模完成
  172. var flag = await _serviceIotApi.SetFetalConfig(imeiDel, 1, commonPHR.MaxValue, commonPHR.MinValue);
  173. _logger.LogInformation($"{imeiDel} 建模完成");
  174. // 保存到TDengine数据库
  175. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR);
  176. _logger.LogInformation($"保存TDengine完成");
  177. //
  178. }
  179. }
  180. #endregion
  181. #region 注册定时下发
  182. var startTime = DateTime.Now;
  183. // 注册下次下推
  184. var endTime = DateTime.Now;
  185. #if DEBUG
  186. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  187. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  188. var interval = 0;
  189. // 获取当前时间
  190. DateTime now = DateTime.Now;
  191. // 计算距离下一个$interval天后的8点的时间间隔
  192. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  193. TimeSpan timeUntilNextRun = nextRunTime - now;
  194. // 如果当前时间已经超过了8点,将等待到明天后的8点
  195. if (timeUntilNextRun < TimeSpan.Zero)
  196. {
  197. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  198. nextRunTime += timeUntilNextRun;
  199. }
  200. //long ttl = timeUntilNextRun.Milliseconds/1000;
  201. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  202. var data = new
  203. {
  204. imei = imeiDel,
  205. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  206. ttl,
  207. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  208. };
  209. var result = JsonConvert.SerializeObject(data);
  210. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  211. #else
  212. // 每$interval天,晚上8点
  213. var interval = 1;
  214. // 获取当前时间
  215. DateTime now = DateTime.Now;
  216. var rand = new Random();
  217. var pushSec = rand.Next(59);
  218. int pushMin = int.TryParse(imeiDel.AsSpan(imeiDel.Length - 1), out pushMin) ? pushMin : 10;
  219. // 计算距离下一个$interval天后的0点的时间间隔
  220. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 6, pushMin, pushSec).AddDays(interval);
  221. TimeSpan timeUntilNextRun = nextRunTime - now;
  222. // 如果当前时间已经超过了8点,将等待到明天后的8点
  223. if (timeUntilNextRun < TimeSpan.Zero)
  224. {
  225. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  226. nextRunTime += timeUntilNextRun;
  227. }
  228. // var ttl = timeUntilNextRun.TotalMilliseconds;
  229. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  230. var data = new
  231. {
  232. imei = imeiDel,
  233. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  234. ttl,
  235. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  236. };
  237. var result = JsonConvert.SerializeObject(data);
  238. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  239. #endif
  240. #endregion
  241. }
  242. }
  243. // health_monitor/schedule_push/cal_fetal_heart_rate/imei/
  244. // 高频结束后计算胎心数据,防止结束后与常规心理的胎心处理过长
  245. if (key.Contains("health_monitor/schedule_push/cal_freqhr_fetal_heart_rate/imei/"))
  246. {
  247. /// 延时计算高频状态的胎心数据,防止高频结束后与触发数据时间相隔过长。
  248. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(imeiDel);
  249. // 高频不停,15分钟内只下发一条
  250. var push = await _deviceCacheMgr.GetBizIntervalAsync(imeiDel, "SaveAndPushFetalHeartRate");
  251. var triggerValue = (JObject)JsonConvert.DeserializeObject(e.PrevKv.Value.ToStringUtf8())!;
  252. var trigger = triggerValue["trigger"]?.ToString();
  253. // 验证高频首条是否还存在
  254. if (phrFreqstatus != null && string.IsNullOrEmpty(push))
  255. {
  256. if (!string.IsNullOrEmpty(trigger))
  257. {
  258. var triggerHeartRate = JsonConvert.DeserializeObject<HisGpsHeartRate>(trigger);
  259. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = triggerHeartRate?.MessageId! }))
  260. {
  261. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  262. _logger.LogInformation($"{imeiDel}高频结束后,延迟计算高频数据产生的胎心数据");
  263. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  264. if (isFetalHeartEnable)
  265. {
  266. // 防止超过12条连续正常,高频不停止
  267. if (phrFreqstatus.MessageId == triggerHeartRate?.MessageId)
  268. {
  269. // 告警上限阀值
  270. var upperAlarmThreshold = (int)watchConfig!["upperAlarmThreshold"]!;
  271. // 告警下限阀值
  272. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  273. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容(最小highFreqSampleInterval=60)
  274. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! + 5 : 60;
  275. //停止高频心率采样心率连续正常次数
  276. var stopHighFreqSampleCount = (int)watchConfig["stopHighFreqSampleCount"]!;
  277. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  278. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  279. var phrFromFreqstatus = phr.Where(i => i.LastUpdate >= phrFreqstatus.LastUpdate).ToList();
  280. // 高频数据
  281. var phrInFreqstatus = GetFreqPregnancyHeartRate(phrFromFreqstatus, highFreqSampleInterval)
  282. .OrderByDescending(i => i.LastUpdate).ToList();
  283. if (phrInFreqstatus.Count > stopHighFreqSampleCount)
  284. {
  285. // 取最后 stopHighFreqSampleCount 条高频数据
  286. phrInFreqstatus = phrInFreqstatus
  287. .OrderByDescending(i => i.LastUpdate)
  288. .Take(stopHighFreqSampleCount).ToList(); // 计算最后12条
  289. var avgPhr = phrInFreqstatus
  290. .Select(i => i.PregnancyHeartRate).Average();
  291. var FreqStatsEnd = phrInFreqstatus.First().LastUpdate;
  292. _logger.LogInformation($"延时计算,{imeiDel} 高频状态持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,统计周期:{phrFreqstatus!.LastUpdate.ToString("yyyy-MM-dd HH:mm:ss")}----{FreqStatsEnd.ToString("yyyy-MM-dd HH:mm:ss")},将下发指令");
  293. await SaveAndPushFetalHeartRateAsync(triggerHeartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  294. }
  295. else
  296. {
  297. _logger.LogWarning($"{imeiDel} 高频心率的数据不大于{stopHighFreqSampleCount}条,不进行高频数据的胎心计算");
  298. }
  299. // 删除高频状态的首条记录
  300. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(imeiDel);
  301. }
  302. else
  303. {
  304. _logger.LogWarning($"{imeiDel} 超过12条连续正常,高频不停止,暂不处理");
  305. }
  306. }
  307. else
  308. {
  309. _logger.LogWarning($"{imeiDel} 胎心监测功能没有启动");
  310. }
  311. }
  312. }
  313. }
  314. }
  315. // 延时计算常规胎心数据
  316. else if (key.Contains("health_monitor/schedule_push/cal_normalphr_fetal_heart_rate/imei/"))
  317. {
  318. var triggerValue = (JObject)JsonConvert.DeserializeObject(e.PrevKv.Value.ToStringUtf8())!;
  319. var trigger = triggerValue["trigger"]?.ToString();
  320. if (!string.IsNullOrEmpty(trigger))
  321. {
  322. var triggerHeartRate = JsonConvert.DeserializeObject<HisGpsHeartRate>(trigger);
  323. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = triggerHeartRate?.MessageId! }))
  324. {
  325. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  326. _logger.LogInformation($"{imeiDel}延迟常规胎心数据产生的胎心数据");
  327. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  328. if (isFetalHeartEnable)
  329. {
  330. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  331. if (commonPHR!=null)
  332. {
  333. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! : 60;
  334. await CalculateNormalFetalHeartRateIntervalAsync(triggerHeartRate!, commonPHR, highFreqSampleInterval);
  335. }
  336. else
  337. {
  338. _logger.LogWarning($"{imeiDel} 胎心数据建模中...");
  339. }
  340. }
  341. else
  342. {
  343. _logger.LogWarning($"{imeiDel} 胎心监测功能没有启动");
  344. }
  345. }
  346. }
  347. }
  348. else if (key.Contains("health_monitor/schedule_push/cal_fetal_heart_rate/imei/"))
  349. {
  350. /**
  351. var triggerValue= (JObject)JsonConvert.DeserializeObject(e.PrevKv.Value.ToStringUtf8())!;
  352. var trigger = triggerValue["trigger"]?.ToString();
  353. if (!string.IsNullOrEmpty(trigger))
  354. {
  355. var triggerHeartRate= JsonConvert.DeserializeObject<HisGpsHeartRate>(trigger);
  356. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = triggerHeartRate?.MessageId! }))
  357. {
  358. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  359. _logger.LogInformation($"触发常规心率计算胎心");
  360. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  361. if (isFetalHeartEnable)
  362. {
  363. // 告警上限阀值
  364. var upperAlarmThreshold = (int)watchConfig!["upperAlarmThreshold"]!;
  365. // 告警下限阀值
  366. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  367. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval+5,增加5秒兼容(最小highFreqSampleInterval=60)
  368. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]! + 5 : 60;
  369. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  370. // 最后一条孕妇心率
  371. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(imeiDel);
  372. var isNormalHeartRate = triggerHeartRate?.MessageId == lastPhr.MessageId;
  373. // 判断最后一条孕妇心率与解析器的触发心率是否一致
  374. if (isNormalHeartRate)
  375. {
  376. //最后一条孕妇心率与解析器的触发心率一致
  377. HisGpsHeartRate heartRate = new()
  378. {
  379. CreateTime = lastPhr.CreateTime,
  380. DeviceKey = lastPhr.DeviceKey,
  381. HeartRate = lastPhr.PregnancyHeartRate,
  382. HeartRateId = lastPhr.PregnancyHeartRateId,
  383. IsDisplay = lastPhr.IsDisplay ? 1 : 0,
  384. MessageId = lastPhr.MessageId,
  385. LastUpdate = lastPhr.LastUpdate,
  386. Method = lastPhr.Method,
  387. PersonId = lastPhr.PersonId,
  388. Serialno = lastPhr.SerialNumber
  389. };
  390. var intervalFHR = 15;
  391. await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  392. }
  393. // 最后一条孕妇心率与解析器的触发心率不一致,触发心率是高频心率的首条
  394. else
  395. {
  396. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  397. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(imeiDel);
  398. if (phrFreqstatus != null)
  399. {
  400. #region 高频缓存
  401. // 高频首条是触发心率,30秒后,高频第二条已经写入首条高频缓存
  402. var diffCount = phr.Where(i => i.CreateTime >= phrFreqstatus.CreateTime && i.CreateTime <= lastPhr.CreateTime)
  403. .OrderByDescending(i => i.CreateTime);
  404. _logger.LogInformation($"{imeiDel} 存在高频缓存,高频心率首条记录${phrFreqstatus.MessageId},高频首条到当前的MSG ID{string.Join(",",diffCount.Select(i=>i.MessageId))}");
  405. #endregion
  406. }
  407. // 不在高频状态状态,但触发孕妇心率与最后一条孕妇心率不一致,
  408. // 常规心率数据是批量上报,需要计算每条心率对应的胎心数据
  409. else
  410. {
  411. _logger.LogInformation($"{imeiDel} 常规心率数据是批量上报,需要计算每条心率对应的胎心数据");
  412. #region 计算每条心率对应的胎心数据
  413. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  414. // 获取高频数据
  415. var freqCollection = new List<PregnancyHeartRateModel>();
  416. PregnancyHeartRateModel? previousItem = null;
  417. foreach (var item in phr)
  418. {
  419. if (previousItem != null)
  420. {
  421. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  422. if (timeNextDiff <= highFreqSampleInterval)
  423. {
  424. freqCollection.Add(item);
  425. }
  426. }
  427. previousItem = item;
  428. }
  429. //去除高频
  430. foreach (var item in freqCollection)
  431. {
  432. phr.Remove(item);
  433. }
  434. // 排序并过滤高频数据
  435. //var previousItem = phr.OrderByDescending(i => i.LastUpdate).ToList().First();
  436. //phr = phr.Skip(1)
  437. // .Where(item =>
  438. // {
  439. // var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  440. // previousItem = item;
  441. // return timeNextDiff > highFreqSampleInterval;
  442. // })
  443. // .Prepend(previousItem)
  444. // .OrderByDescending(i => i.LastUpdate)
  445. // .ToList();
  446. var calFhrTasks = phr.Where(p => p.LastUpdate >= triggerHeartRate!.LastUpdate)
  447. .Select( async p =>
  448. {
  449. HisGpsHeartRate heartRate = new()
  450. {
  451. CreateTime = p.CreateTime,
  452. DeviceKey = p.DeviceKey,
  453. HeartRate = p.PregnancyHeartRate,
  454. HeartRateId = p.PregnancyHeartRateId,
  455. IsDisplay = p.IsDisplay ? 1 : 0,
  456. MessageId = p.MessageId,
  457. LastUpdate = p.LastUpdate,
  458. Method = p.Method,
  459. PersonId = p.PersonId,
  460. Serialno = p.SerialNumber
  461. };
  462. var intervalFHR = 15;
  463. await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  464. });
  465. await Task.WhenAll(calFhrTasks);
  466. #endregion
  467. }
  468. }
  469. }
  470. else
  471. {
  472. _logger.LogWarning($"{imeiDel} 胎心监测功能没有开启");
  473. }
  474. }
  475. }
  476. else
  477. {
  478. _logger.LogWarning($"{imeiDel} trigger is not set");
  479. }
  480. */
  481. }
  482. // 胎动计算
  483. //health_monitor/schedule_push/cal_fetal_movement/imei/
  484. else if (key.Contains("health_monitor/schedule_push/cal_fetal_movement/imei/"))
  485. {
  486. #region 胎动延时计算
  487. /**
  488. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = $"FM-{imeiDel}-{DateTime.Now.ToString("yyyyMMddHHmmss")}" }))
  489. {
  490. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  491. _logger.LogInformation($"触发胎动计算,设备配置{JsonConvert.SerializeObject(watchConfig)}");
  492. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  493. if (isFetalHeartEnable)
  494. {
  495. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  496. // 已经建模
  497. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  498. if (commonPHR != null)
  499. {
  500. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  501. _logger.LogInformation($"{imeiDel} 计算胎动数据 ");
  502. var fmNow = DateTime.Now;
  503. // 两小时前
  504. var fmNowSubtract = fmNow.AddMinutes(-fmNow.Minute).AddSeconds(-fmNow.Second).AddMilliseconds(-fmNow.Millisecond);
  505. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(fmNowSubtract).ToString()[..10];
  506. // 统计开始时间
  507. var statStartTime = fmNowSubtract.AddHours(-2);
  508. // 统计结束时间
  509. var statEndTime = fmNowSubtract;
  510. var isFetalMovementExisted = await _deviceCacheMgr.FetalMovementIsExistedAsync(imeiDel, fetalMovementSampleTime);
  511. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 开始");
  512. if (!isFetalMovementExisted)
  513. {
  514. /// 开始计算
  515. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate <= statEndTime)
  516. .OrderByDescending(i => i.LastUpdate)
  517. .Select(i => i.LastUpdate)
  518. .ToList();
  519. // 判断是否有持续佩戴
  520. if (phrRange.Count >= 2)
  521. {
  522. // 读取胎心数据
  523. GeneralParam param = new()
  524. {
  525. Filters = new List<QueryFilterCondition>
  526. {
  527. new ()
  528. {
  529. Key=nameof(HisGpsFetalHeartRate.Serialno),
  530. Value=imeiDel,
  531. ValueType=QueryValueTypeEnum.String,
  532. Operator=QueryOperatorEnum.Equal
  533. },
  534. //new ()
  535. //{
  536. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  537. // Value=sampleTime,
  538. // ValueType=QueryValueTypeEnum.String,
  539. // Operator=QueryOperatorEnum.GreaterEqual
  540. //},
  541. },
  542. OrderBys = new List<OrderByCondition>
  543. {
  544. new (){
  545. IsDesc=true,
  546. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  547. }
  548. }
  549. };
  550. var fetalHeartRateIsAbnormal = 0;
  551. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  552. // 胎心数据时间与胎动时间一致
  553. var time = long.Parse(fhr.SampleTime.Length < 13 ? fhr.SampleTime.PadRight(13, '0') : fhr.SampleTime);
  554. var fhrSampleTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(time);
  555. // 胎心数据时间与胎动时间一致,最后一条胎心数据与胎动数据的小时差不大于2
  556. if ((DateTime.Now.Hour - fhrSampleTime.Hour) <= 2)
  557. {
  558. var duringMins = Math.Abs((phrRange.First() - phrRange.Last()).TotalMinutes);
  559. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  560. bool isInTimeRanges = IsLastUpdateInTimeRanges(phrRange.First());
  561. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  562. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  563. {
  564. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  565. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  566. .Where(i =>
  567. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  568. i.PregnancyPeriod[1] >= pregnancyWeeks)
  569. .Select(i => i.MedianMovement)
  570. .FirstOrDefault()
  571. :
  572. fetalMovementMap
  573. .Where(i =>
  574. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  575. i.PregnancyPeriod[1] >= pregnancyWeeks)
  576. .Select(i => i.InitialMovement)
  577. .FirstOrDefault()
  578. ;
  579. var fetalMovementValue = (fetalMovementMapValue * duringMins * 2) / 120;
  580. // 四舍五入
  581. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  582. // _logger.LogInformation($"{imeiDel} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");
  583. #region 生理健康与胎动的关系
  584. /// (步数)运动步数超过1500步则加1;
  585. /// (体温)低烧则胎动减1,高烧胎动减2;低烧是37.3~38.5,38.6以上是高烧。
  586. /// (血压)血压收缩压大于160则加1。
  587. /// (心理)心理压力高加2,压力中加1;
  588. var fetalMovementStepVar = 0;
  589. var fetalMovementTempVar = 0;
  590. var fetalMovementBpVar = 0;
  591. var fetalMovementPpVar = 0;
  592. var fetalMovementFhrVar = 0;
  593. // 步数
  594. if (true)
  595. {
  596. var step = await _personCacheMgr.GetStepPeriodicityAsync(imeiDel);
  597. if (step != null)
  598. {
  599. if (DateTime.Now.Hour - ((DateTime)step?.LastUpdate!).Hour <= 2)
  600. {
  601. if (step.Steps > 1500) fetalMovementStepVar = 1;
  602. }
  603. else
  604. {
  605. _logger.LogWarning($"{imeiDel} 周期步数 时间无效");
  606. }
  607. }
  608. else
  609. {
  610. _logger.LogWarning($"{imeiDel} 周期步数无数据");
  611. }
  612. }
  613. // 体温
  614. if (true)
  615. {
  616. var temp = await _personCacheMgr.GetTemperaturePeriodicityAsync(imeiDel);
  617. if (temp != null)
  618. {
  619. if (DateTime.Now.Hour - ((DateTime)temp?.LastUpdate!).Hour <= 2)
  620. {
  621. // 中烧
  622. if (temp.Temperature >= 37.3M && temp.Temperature <= 38.5M)
  623. {
  624. fetalMovementTempVar = -1;
  625. }
  626. // 高烧
  627. if (temp.Temperature >= 38.6M)
  628. {
  629. fetalMovementTempVar = -2;
  630. }
  631. }
  632. else
  633. {
  634. _logger.LogWarning($"{imeiDel} 周期体温 时间无效");
  635. }
  636. }
  637. else
  638. {
  639. _logger.LogWarning($"{imeiDel} 周期体温无数据");
  640. }
  641. }
  642. // 血压
  643. if (true)
  644. {
  645. var bp = await _personCacheMgr.GetBloodPressPeriodicityAsync(imeiDel);
  646. if (bp != null)
  647. {
  648. if (DateTime.Now.Hour - ((DateTime)bp?.LastUpdate!).Hour <= 2)
  649. {
  650. if (bp.SystolicValue > 160)
  651. {
  652. fetalMovementBpVar = 1;
  653. }
  654. }
  655. else
  656. {
  657. _logger.LogWarning($"{imeiDel} 周期血压 时间无效");
  658. }
  659. }
  660. else
  661. {
  662. _logger.LogWarning($"{imeiDel} 周期血压无数据");
  663. }
  664. }
  665. // 心理
  666. if (true)
  667. {
  668. //-1 不处理,
  669. //0 正常,
  670. //1 轻度,
  671. //2 中度;
  672. //3 重度;
  673. GeneralParam psychResultParam = new()
  674. {
  675. Filters = new List<QueryFilterCondition>
  676. {
  677. new ()
  678. {
  679. Key=nameof(HisGpsPsychResult.Serialno),
  680. Value=imeiDel,
  681. ValueType=QueryValueTypeEnum.String,
  682. Operator=QueryOperatorEnum.Equal
  683. },
  684. //new ()
  685. //{
  686. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  687. // Value=sampleTime,
  688. // ValueType=QueryValueTypeEnum.String,
  689. // Operator=QueryOperatorEnum.GreaterEqual
  690. //},
  691. },
  692. OrderBys = new List<OrderByCondition>
  693. {
  694. new (){
  695. IsDesc=true,
  696. Key=nameof(HisGpsPsychResult.Serialno)
  697. }
  698. }
  699. };
  700. var psych = await _hisPsychResultApiClient.GetFirstAsync(psychResultParam, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  701. if (psych != null)
  702. {
  703. if (psych?.StressScore == 2)
  704. {
  705. fetalMovementPpVar = 1;
  706. }
  707. if (psych?.StressScore == 3)
  708. {
  709. fetalMovementPpVar = 2;
  710. }
  711. }
  712. else
  713. {
  714. _logger.LogWarning($"{imeiDel} 周期心理压力无数据");
  715. }
  716. }
  717. #endregion
  718. #region 胎心与胎动的关系
  719. /// 胎心值过缓时,则胎动数量减1;胎心值过速时,则胎动也加1。
  720. /// 此值允许在上限值上继续增加,在下限值上继续减少,最小值为0。
  721. /// 告警上限阀值
  722. //1表示偏高;2表示偏低
  723. if (true)
  724. {
  725. if (fhr.IsAbnormal == 2)
  726. {
  727. fetalMovementPpVar = -1;
  728. }
  729. if (fhr.IsAbnormal == 1)
  730. {
  731. fetalMovementPpVar = 1;
  732. }
  733. }
  734. #endregion
  735. _logger.LogInformation($"{imeiDel} 原始胎动值:{fetalMovementValue}, 步数参数变动值:{fetalMovementStepVar},体温参数变动值:{fetalMovementTempVar},血压参数变动值:{fetalMovementBpVar},心理压力参数变动值:{fetalMovementPpVar},胎心参数变动值:{fetalMovementFhrVar}");
  736. fetalMovementValue = fetalMovementValue + fetalMovementStepVar + fetalMovementTempVar + fetalMovementBpVar + fetalMovementPpVar + fetalMovementFhrVar;
  737. _logger.LogInformation($"{imeiDel} 孕周:{pregnancyWeeks},胎动数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 原始胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{phrRange.Last()}-{phrRange.First()}, 胎动计算值:{fetalMovementValue}, 胎动最终值:{fetalMovement} 已完成.");
  738. // 获取胎心数据状态与胎动数据状态一致
  739. //etalHeartRateIsAbnormal= fhr.IsAbnormal;
  740. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  741. await _serviceIotApi.SetFetalMovementConfig(imeiDel, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  742. // 保存到MySQL数据库
  743. HisGpsFetalMovement fm = new()
  744. {
  745. FetalMovementId = Guid.NewGuid().ToString("D"),
  746. PersonId = commonPHR!.PersonId,
  747. Serialno = imeiDel,
  748. CreateTime = DateTime.Now,
  749. IsAbnormal = feltalMovementIsAbnormal,
  750. FetalMovementValue = fetalMovement,
  751. SampleTime = fetalMovementSampleTime,
  752. Method = 1,
  753. IsDisplay = 1,
  754. DeviceKey = commonPHR!.DeviceKey
  755. };
  756. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  757. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(imeiDel).ConfigureAwait(false);
  758. var fmMsgId = $"{imeiDel}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  759. var fmMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  760. // 胎动数据推送到第三方
  761. var topic = "topic.push.third";
  762. var fmThridMsg = new
  763. {
  764. messageId = fmMsgId,
  765. topic = topic,
  766. time = fmMsgTime,
  767. data = new
  768. {
  769. imei = imeiDel,
  770. value = fetalMovement,
  771. isAbnormal = feltalMovementIsAbnormal,
  772. type = "fetalMovement"
  773. }
  774. };
  775. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, 31, fmThridMsg).ConfigureAwait(false);
  776. // 胎动数据推送到微信
  777. if (feltalMovementIsAbnormal != 0)
  778. {
  779. topic = "topic.push.wx";
  780. var fmMsg = new
  781. {
  782. messageId = Guid.NewGuid().ToString("D"),
  783. topic = topic,
  784. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
  785. data = new
  786. {
  787. deviceId = device?.DeviceId,
  788. imei = imeiDel,
  789. alarmTypeId = 12,
  790. alarmDeviceName = imeiDel,
  791. alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
  792. address = string.Empty,
  793. deviceKey = device?.DeviceId
  794. }
  795. };
  796. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
  797. }
  798. // 设置入库缓存记录
  799. await _deviceCacheMgr.SetFetalMovementAsync(imeiDel, fetalMovementSampleTime, fm);
  800. }
  801. else
  802. {
  803. _logger.LogWarning($"{imeiDel} 孕周 {pregnancyWeeks},超出胎动计算范围");
  804. }
  805. }
  806. else
  807. {
  808. _logger.LogWarning($"{imeiDel} 最后一条胎心数据与胎动数据的小时差大于2,不计算胎动数据");
  809. }
  810. }
  811. else
  812. {
  813. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 不足两条,不能判断是否持续佩戴");
  814. }
  815. }
  816. else
  817. {
  818. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 已处理");
  819. }
  820. }
  821. }
  822. }
  823. */
  824. #endregion
  825. #region 胎动延时计算(再延时)
  826. using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = $"FM-{imeiDel}-{DateTime.Now.ToString("yyyyMMddHHmmss")}" }))
  827. {
  828. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(imeiDel, "0067");
  829. _logger.LogInformation($"触发胎动计算,设备配置{JsonConvert.SerializeObject(watchConfig)}");
  830. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  831. if (isFetalHeartEnable)
  832. {
  833. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  834. // 已经建模
  835. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(imeiDel);
  836. if (commonPHR != null)
  837. {
  838. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(imeiDel, 7);
  839. _logger.LogInformation($"{imeiDel} 计算胎动数据 ");
  840. var fmNow = DateTime.Now;
  841. // 两小时前
  842. var fmNowSubtract = fmNow.AddMinutes(-fmNow.Minute).AddSeconds(-fmNow.Second).AddMilliseconds(-fmNow.Millisecond);
  843. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(fmNowSubtract).ToString()[..10];
  844. // 统计开始时间
  845. var statStartTime = fmNowSubtract.AddHours(-2);
  846. // 统计结束时间
  847. var statEndTime = fmNowSubtract;
  848. // 最后一条
  849. PregnancyHeartRateModel lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(imeiDel);
  850. Thread thread = new(async () => {
  851. });
  852. thread.Start();
  853. var isFetalMovementExisted = await _deviceCacheMgr.FetalMovementIsExistedAsync(imeiDel, fetalMovementSampleTime);
  854. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 开始");
  855. if (!isFetalMovementExisted)
  856. {
  857. /// 开始计算
  858. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate <= statEndTime)
  859. .OrderByDescending(i => i.LastUpdate)
  860. .Select(i => i.LastUpdate)
  861. .ToList();
  862. // 判断是否有持续佩戴
  863. if (phrRange.Count >= 2)
  864. {
  865. // 读取胎心数据
  866. GeneralParam param = new()
  867. {
  868. Filters = new List<QueryFilterCondition>
  869. {
  870. new ()
  871. {
  872. Key=nameof(HisGpsFetalHeartRate.Serialno),
  873. Value=imeiDel,
  874. ValueType=QueryValueTypeEnum.String,
  875. Operator=QueryOperatorEnum.Equal
  876. },
  877. //new ()
  878. //{
  879. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  880. // Value=sampleTime,
  881. // ValueType=QueryValueTypeEnum.String,
  882. // Operator=QueryOperatorEnum.GreaterEqual
  883. //},
  884. },
  885. OrderBys = new List<OrderByCondition>
  886. {
  887. new (){
  888. IsDesc=true,
  889. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  890. }
  891. }
  892. };
  893. var fetalHeartRateIsAbnormal = 0;
  894. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  895. // 胎心数据时间与胎动时间一致
  896. var time = long.Parse(fhr.SampleTime.Length < 13 ? fhr.SampleTime.PadRight(13, '0') : fhr.SampleTime);
  897. var fhrSampleTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(time);
  898. // 胎心数据时间与胎动时间一致,最后一条胎心数据与胎动数据的小时差不大于2
  899. if ((DateTime.Now.Hour - fhrSampleTime.Hour) <= 2)
  900. {
  901. var duringMins = Math.Abs((phrRange.First() - phrRange.Last()).TotalMinutes);
  902. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  903. bool isInTimeRanges = IsLastUpdateInTimeRanges(phrRange.First());
  904. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  905. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  906. {
  907. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  908. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  909. .Where(i =>
  910. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  911. i.PregnancyPeriod[1] >= pregnancyWeeks)
  912. .Select(i => i.MedianMovement)
  913. .FirstOrDefault()
  914. :
  915. fetalMovementMap
  916. .Where(i =>
  917. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  918. i.PregnancyPeriod[1] >= pregnancyWeeks)
  919. .Select(i => i.InitialMovement)
  920. .FirstOrDefault()
  921. ;
  922. var fetalMovementValue = (fetalMovementMapValue * duringMins * 2) / 120;
  923. // 四舍五入
  924. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  925. // _logger.LogInformation($"{imeiDel} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");
  926. #region 生理健康与胎动的关系
  927. /// (步数)运动步数超过1500步则加1;
  928. /// (体温)低烧则胎动减1,高烧胎动减2;低烧是37.3~38.5,38.6以上是高烧。
  929. /// (血压)血压收缩压大于160则加1。
  930. /// (心理)心理压力高加2,压力中加1;
  931. var fetalMovementStepVar = 0;
  932. var fetalMovementTempVar = 0;
  933. var fetalMovementBpVar = 0;
  934. var fetalMovementPpVar = 0;
  935. var fetalMovementFhrVar = 0;
  936. // 步数
  937. if (true)
  938. {
  939. var step = await _personCacheMgr.GetStepPeriodicityAsync(imeiDel);
  940. if (step != null)
  941. {
  942. if (DateTime.Now.Hour - ((DateTime)step?.LastUpdate!).Hour <= 2)
  943. {
  944. if (step.Steps > 1500) fetalMovementStepVar = 1;
  945. }
  946. else
  947. {
  948. _logger.LogWarning($"{imeiDel} 周期步数 时间无效");
  949. }
  950. }
  951. else
  952. {
  953. _logger.LogWarning($"{imeiDel} 周期步数无数据");
  954. }
  955. }
  956. // 体温
  957. if (true)
  958. {
  959. var temp = await _personCacheMgr.GetTemperaturePeriodicityAsync(imeiDel);
  960. if (temp != null)
  961. {
  962. if (DateTime.Now.Hour - ((DateTime)temp?.LastUpdate!).Hour <= 2)
  963. {
  964. // 中烧
  965. if (temp.Temperature >= 37.3M && temp.Temperature <= 38.5M)
  966. {
  967. fetalMovementTempVar = -1;
  968. }
  969. // 高烧
  970. if (temp.Temperature >= 38.6M)
  971. {
  972. fetalMovementTempVar = -2;
  973. }
  974. }
  975. else
  976. {
  977. _logger.LogWarning($"{imeiDel} 周期体温 时间无效");
  978. }
  979. }
  980. else
  981. {
  982. _logger.LogWarning($"{imeiDel} 周期体温无数据");
  983. }
  984. }
  985. // 血压
  986. if (true)
  987. {
  988. var bp = await _personCacheMgr.GetBloodPressPeriodicityAsync(imeiDel);
  989. if (bp != null)
  990. {
  991. if (DateTime.Now.Hour - ((DateTime)bp?.LastUpdate!).Hour <= 2)
  992. {
  993. if (bp.SystolicValue > 160)
  994. {
  995. fetalMovementBpVar = 1;
  996. }
  997. }
  998. else
  999. {
  1000. _logger.LogWarning($"{imeiDel} 周期血压 时间无效");
  1001. }
  1002. }
  1003. else
  1004. {
  1005. _logger.LogWarning($"{imeiDel} 周期血压无数据");
  1006. }
  1007. }
  1008. // 心理
  1009. if (true)
  1010. {
  1011. //-1 不处理,
  1012. //0 正常,
  1013. //1 轻度,
  1014. //2 中度;
  1015. //3 重度;
  1016. GeneralParam psychResultParam = new()
  1017. {
  1018. Filters = new List<QueryFilterCondition>
  1019. {
  1020. new ()
  1021. {
  1022. Key=nameof(HisGpsPsychResult.Serialno),
  1023. Value=imeiDel,
  1024. ValueType=QueryValueTypeEnum.String,
  1025. Operator=QueryOperatorEnum.Equal
  1026. },
  1027. //new ()
  1028. //{
  1029. // Key=nameof(HisGpsFetalHeartRate.SampleTime),
  1030. // Value=sampleTime,
  1031. // ValueType=QueryValueTypeEnum.String,
  1032. // Operator=QueryOperatorEnum.GreaterEqual
  1033. //},
  1034. },
  1035. OrderBys = new List<OrderByCondition>
  1036. {
  1037. new (){
  1038. IsDesc=true,
  1039. Key=nameof(HisGpsPsychResult.Serialno)
  1040. }
  1041. }
  1042. };
  1043. var psych = await _hisPsychResultApiClient.GetFirstAsync(psychResultParam, imeiDel[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  1044. if (psych != null)
  1045. {
  1046. if (psych?.StressScore == 2)
  1047. {
  1048. fetalMovementPpVar = 1;
  1049. }
  1050. if (psych?.StressScore == 3)
  1051. {
  1052. fetalMovementPpVar = 2;
  1053. }
  1054. }
  1055. else
  1056. {
  1057. _logger.LogWarning($"{imeiDel} 周期心理压力无数据");
  1058. }
  1059. }
  1060. #endregion
  1061. #region 胎心与胎动的关系
  1062. /// 胎心值过缓时,则胎动数量减1;胎心值过速时,则胎动也加1。
  1063. /// 此值允许在上限值上继续增加,在下限值上继续减少,最小值为0。
  1064. /// 告警上限阀值
  1065. //1表示偏高;2表示偏低
  1066. if (true)
  1067. {
  1068. if (fhr.IsAbnormal == 2)
  1069. {
  1070. fetalMovementPpVar = -1;
  1071. }
  1072. if (fhr.IsAbnormal == 1)
  1073. {
  1074. fetalMovementPpVar = 1;
  1075. }
  1076. }
  1077. #endregion
  1078. _logger.LogInformation($"{imeiDel} 原始胎动值:{fetalMovementValue}, 步数参数变动值:{fetalMovementStepVar},体温参数变动值:{fetalMovementTempVar},血压参数变动值:{fetalMovementBpVar},心理压力参数变动值:{fetalMovementPpVar},胎心参数变动值:{fetalMovementFhrVar}");
  1079. fetalMovementValue = fetalMovementValue + fetalMovementStepVar + fetalMovementTempVar + fetalMovementBpVar + fetalMovementPpVar + fetalMovementFhrVar;
  1080. _logger.LogInformation($"{imeiDel} 孕周:{pregnancyWeeks},胎动数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 原始胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{phrRange.Last()}-{phrRange.First()}, 胎动计算值:{fetalMovementValue}, 胎动最终值:{fetalMovement} 已完成.");
  1081. // 获取胎心数据状态与胎动数据状态一致
  1082. //etalHeartRateIsAbnormal= fhr.IsAbnormal;
  1083. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  1084. await _serviceIotApi.SetFetalMovementConfig(imeiDel, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  1085. // 保存到MySQL数据库
  1086. HisGpsFetalMovement fm = new()
  1087. {
  1088. FetalMovementId = Guid.NewGuid().ToString("D"),
  1089. PersonId = commonPHR!.PersonId,
  1090. Serialno = imeiDel,
  1091. CreateTime = DateTime.Now,
  1092. IsAbnormal = feltalMovementIsAbnormal,
  1093. FetalMovementValue = fetalMovement,
  1094. SampleTime = fetalMovementSampleTime,
  1095. Method = 1,
  1096. IsDisplay = 1,
  1097. DeviceKey = commonPHR!.DeviceKey
  1098. };
  1099. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  1100. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(imeiDel).ConfigureAwait(false);
  1101. var fmMsgId = $"{imeiDel}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  1102. var fmMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  1103. // 胎动数据推送到第三方
  1104. var topic = "topic.push.third";
  1105. var fmThridMsg = new
  1106. {
  1107. messageId = fmMsgId,
  1108. topic = topic,
  1109. time = fmMsgTime,
  1110. data = new
  1111. {
  1112. imei = imeiDel,
  1113. value = fetalMovement,
  1114. isAbnormal = feltalMovementIsAbnormal,
  1115. type = "fetalMovement"
  1116. }
  1117. };
  1118. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, 31, fmThridMsg).ConfigureAwait(false);
  1119. // 胎动数据推送到微信
  1120. if (feltalMovementIsAbnormal != 0)
  1121. {
  1122. topic = "topic.push.wx";
  1123. var fmMsg = new
  1124. {
  1125. messageId = Guid.NewGuid().ToString("D"),
  1126. topic = topic,
  1127. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
  1128. data = new
  1129. {
  1130. deviceId = device?.DeviceId,
  1131. imei = imeiDel,
  1132. alarmTypeId = 12,
  1133. alarmDeviceName = imeiDel,
  1134. alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
  1135. address = string.Empty,
  1136. deviceKey = device?.DeviceId
  1137. }
  1138. };
  1139. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
  1140. }
  1141. // 设置入库缓存记录
  1142. await _deviceCacheMgr.SetFetalMovementAsync(imeiDel, fetalMovementSampleTime, fm);
  1143. }
  1144. else
  1145. {
  1146. _logger.LogWarning($"{imeiDel} 孕周 {pregnancyWeeks},超出胎动计算范围");
  1147. }
  1148. }
  1149. else
  1150. {
  1151. _logger.LogWarning($"{imeiDel} 最后一条胎心数据与胎动数据的小时差大于2,不计算胎动数据");
  1152. }
  1153. }
  1154. else
  1155. {
  1156. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 不足两条,不能判断是否持续佩戴");
  1157. }
  1158. }
  1159. else
  1160. {
  1161. _logger.LogInformation($"{imeiDel} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{fmNowSubtract.ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 已处理");
  1162. }
  1163. }
  1164. }
  1165. }
  1166. #endregion
  1167. }
  1168. else
  1169. {
  1170. // 处理血压业务
  1171. int systolicInc;
  1172. int diastolicInc;
  1173. int systolicRefValue;
  1174. int diastolicRefValue;
  1175. decimal systolicAvg;
  1176. decimal diastolicAvg;
  1177. int systolicMax = 0;
  1178. int diastolicMax = 0;
  1179. // 统计时间
  1180. //DateTime endTime = DateTime.Now; //测试
  1181. DateTime statStartTime = DateTime.Now;
  1182. // 最小值
  1183. int systolicMin = 0;
  1184. int diastolicMin = 0;
  1185. // 偏移参数
  1186. var avgOffset = 0.25M;
  1187. var systolicAvgOffset = avgOffset;
  1188. var diastolicAvgOffset = avgOffset;
  1189. // 最后一次下发值
  1190. int lastPushSystolicInc = 0;
  1191. int lastPushDiastolicInc = 0;
  1192. var startTime = DateTime.Now;
  1193. // 下发增量值
  1194. #region 统计定时下发增量值
  1195. //var last = await _serviceTDengine.GetLastAsync("stb_hm_bloodpress_stats_inc", $"serialno='{imeiDel}' order by last_update desc");
  1196. //var ts = last?[0];
  1197. // 最后一条血压数据
  1198. var condition = $"serialno='{imeiDel}' order by last_update desc";
  1199. var field = "last_row(*)";
  1200. var lastHmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition, field);
  1201. var lastHmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(lastHmBpResponse!);
  1202. var lastHmBp = lastHmBpParser?.Select().FirstOrDefault();
  1203. //if (lastHmBpParser?.Select()?.ToList().Count < 2)
  1204. //{
  1205. // _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 血压数据条目不足");
  1206. // break;
  1207. //}
  1208. // 7 天有效数据
  1209. if (lastHmBp?.Timestamp.AddDays(7) > DateTime.Now)
  1210. {
  1211. // 计算增量值
  1212. condition = $"serialno='{imeiDel}' order by ts desc";
  1213. var lastPushResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bp_push_ref_inc_value", condition, field);
  1214. if (lastPushResponse == null)
  1215. {
  1216. _logger.LogInformation($"{imeiDel}--没有下发记录");
  1217. break;
  1218. }
  1219. var lastPushParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressurePushRefIncModel>>(lastPushResponse);
  1220. var lastPush = lastPushParser!.Select().FirstOrDefault();
  1221. // 有下推记录
  1222. if (lastPush != null)
  1223. {
  1224. systolicRefValue = lastPush!.SystolicRefValue;
  1225. diastolicRefValue = lastPush!.DiastolicRefValue;
  1226. lastPushSystolicInc = lastPush!.SystolicIncValue;
  1227. lastPushDiastolicInc = lastPush!.DiastolicIncValue;
  1228. condition = $"ts between '{lastPush?.Timestamp:yyyy-MM-dd HH:mm:ss.fff}' and '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  1229. $"and serialno='{imeiDel}' " +
  1230. $"and is_display = true";
  1231. // 使用最近一次的下推时间作为统计的开始时间
  1232. statStartTime = lastPush!.Timestamp;
  1233. }
  1234. // 没有下推记录(历史遗留数据),没有初始的测量值产生的平均值(测量值=平均值)
  1235. else
  1236. {
  1237. #region 获取个人信息
  1238. var person = await _personCacheMgr.GetDeviceGpsPersonCacheBySerialNoAsync(Guid.NewGuid().ToString(), imeiDel).ConfigureAwait(false);
  1239. //验证这个信息是否存在
  1240. if (person == null || person?.Person.BornDate == null)
  1241. {
  1242. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证个人信息,找不到个人信息,跳过此消息");
  1243. break;
  1244. }
  1245. // 验证年龄是否在范围 (2 - 120)
  1246. var age = SafeType.SafeInt(DateTime.Today.Year - person?.Person.BornDate!.Value.Year!);
  1247. if (age < 2 || age > 120)
  1248. {
  1249. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证年龄,不在范围 (2 - 120)岁,跳过此消息");
  1250. break;
  1251. }
  1252. var gender = person?.Person.Gender == true ? 1 : 2;
  1253. var isHypertension = SafeType.SafeBool(person?.Person.Ishypertension!);
  1254. var height = SafeType.SafeDouble(person?.Person.Height!);
  1255. var weight = SafeType.SafeDouble(person?.Person.Weight!);
  1256. #endregion
  1257. #region 初始化常规血压标定值标定值
  1258. var bpRef = await _bpRefValCacheManager.GetBloodPressReferenceValueAsync(age, gender, isHypertension);
  1259. //systolicRefValue = bpRef!.Systolic;//?
  1260. //diastolicRefValue = bpRef!.Diastolic;//?
  1261. #endregion
  1262. systolicRefValue = bpRef!.Systolic;
  1263. diastolicRefValue = bpRef!.Diastolic;
  1264. lastPushSystolicInc = 0;
  1265. lastPushDiastolicInc = 0;
  1266. condition = $"ts <= '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  1267. $"and serialno='{imeiDel}' " +
  1268. $"and is_display = true";
  1269. }
  1270. var hmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition);
  1271. var hmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(hmBpResponse!);
  1272. var hmBp = hmBpParser?.Select();
  1273. //if (hmBp?.ToList().Count < 2)
  1274. // 1. 判断数据样本数量
  1275. if (hmBpParser!.Rows < 5)
  1276. {
  1277. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 统计定时下发,计算增量值的数据条目不足:{hmBpParser!.Rows} < 5");
  1278. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} 没有足够的数据样本,不会定时下发");
  1279. break;
  1280. }
  1281. // 没有下推记录重新计算统计时间
  1282. if (lastPush == null)
  1283. {
  1284. var firstHmBp = hmBpParser?.Select(i => i).OrderBy(i => i.Timestamp).FirstOrDefault();
  1285. statStartTime = firstHmBp!.Timestamp;
  1286. }
  1287. // GetSampleTime(systolicRefValue, hmBpParser);
  1288. // 最大值
  1289. //systolicMax = (int)hmBpParser?.Select(i => i.SystolicValue).Max()!;
  1290. //diastolicMax = (int)hmBpParser?.Select(i => i.DiastolicValue).Max()!;
  1291. //// 最小值
  1292. //systolicMin = (int)hmBpParser?.Select(i => i.SystolicValue).Min()!;
  1293. //diastolicMin = (int)hmBpParser?.Select(i => i.DiastolicValue).Min()!;
  1294. //systolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.SystolicValue, SafeType.SafeInt(systolicRefValue!)))!;
  1295. //diastolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.DiastolicValue, SafeType.SafeInt(diastolicRefValue!)))!;
  1296. var avgs = _serviceTDengine.AverageAfterRemovingOneMinMaxRef(hmBpParser!);
  1297. systolicAvg = avgs[0];
  1298. diastolicAvg = avgs[1];
  1299. // 2. 判断能否计算增量值
  1300. if (systolicAvg.Equals(0))
  1301. {
  1302. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算平均值" +
  1303. $"\n currentSystolicAvg:{systolicAvg} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  1304. $"\n currentDiastolicInc:{diastolicAvg} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  1305. _logger.LogInformation($"{imeiDel}--{nameof(Worker)} 没有足够的数据样本计算平均值,不会定时下发");
  1306. break;
  1307. }
  1308. // 除最大值和最小值后的平均值与标定值差值少于4后(当天计算出该结果则也不产生增量调整),就不再进行增量值调整了。
  1309. if (systolicRefValue - systolicAvg < 4)
  1310. {
  1311. _logger.LogInformation($"diastolic 舒张压 {imeiDel}除最大值和最小值后的平均值:{diastolicAvg}与标定值:{diastolicRefValue}\n systolic 收缩压 {imeiDel}除最大值和最小值后的平均值:{systolicAvg}与标定值:{systolicRefValue}的差值(标定值-平均值)少于4后,systolic 收缩压 不再进行增量值调整");
  1312. break;
  1313. }
  1314. if (diastolicRefValue - diastolicAvg < 4)
  1315. {
  1316. _logger.LogInformation($"systolic 收缩压 {imeiDel}除最大值和最小值后的平均值:{systolicAvg}与标定值:{systolicRefValue}\n diastolic 舒张压 {imeiDel}除最大值和最小值后的平均值:{diastolicAvg}与标定值:{diastolicRefValue}的差值(标定值-平均值)少于4后,diastolic 舒张压 不再进行增量值调整");
  1317. break;
  1318. }
  1319. // 增量值=(标定值-平均值)* 0.25
  1320. var currentSystolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
  1321. var currentDiastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
  1322. // 累计增量
  1323. systolicInc = currentSystolicInc + lastPushSystolicInc;
  1324. diastolicInc = currentDiastolicInc + lastPushDiastolicInc;
  1325. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算增量值" +
  1326. $"\n {imeiDel} -- systolicAvg:{systolicAvg}-- systolicInc:{systolicInc}-- currentSystolicInc:{currentSystolicInc} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  1327. $"\n {imeiDel} -- diastolicAvg:{diastolicAvg}-- diastolicInc:{diastolicInc} --currentDiastolicInc:{currentDiastolicInc} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  1328. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}-- 定时校准,发给设备的绝对增量值=(上次绝对增量值+新数据的增量值)");
  1329. _logger.LogInformation($"{nameof(Worker)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
  1330. if (_configBoodPressResolver.EnableBPRefPush)
  1331. // if (false) // 临时关闭
  1332. {
  1333. BloodPressCalibrationConfigModel bpIncData = new()
  1334. {
  1335. Imei = imeiDel,
  1336. SystolicRefValue = SafeType.SafeInt(((int)systolicRefValue!)), //收缩压标定值,值为0 表示不生效
  1337. DiastolicRefValue = SafeType.SafeInt(((int)diastolicRefValue!)), //舒张压标定值,值为0表示不生效
  1338. SystolicIncValue = SafeType.SafeInt(((int)systolicInc!)), //收缩压显示增量,值为0 表示不生效
  1339. DiastolicIncValue = SafeType.SafeInt(((int)diastolicInc!)) //舒张压显示增量,值为0 表示不生效
  1340. };
  1341. //var pushedBP = await _serviceIotApi.SetBloodPressCalibrationConfigAsync(bpIncData).ConfigureAwait(false);
  1342. var response = await _serviceIotApi.SetBloodPressCalibrationConfig2Async(bpIncData).ConfigureAwait(false);
  1343. var pushedBP = response.Flag;
  1344. if (pushedBP)
  1345. {
  1346. #region 保存下推记录 stb_hm_bp_push_ref_inc_value
  1347. var sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{imeiDel.Substring(imeiDel.Length - 2)} " +
  1348. $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
  1349. $"TAGS ('{imeiDel.Substring(imeiDel.Length - 2)}') " +
  1350. $"VALUES(" +
  1351. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  1352. $"'{imeiDel}'," +
  1353. $"{bpIncData.SystolicRefValue}," +
  1354. $"{bpIncData.DiastolicRefValue}," +
  1355. $"{bpIncData.SystolicIncValue}," +
  1356. $"{bpIncData.DiastolicIncValue}," +
  1357. $"{false}," +
  1358. $"{systolicAvg}," +
  1359. $"{diastolicAvg}," +
  1360. $"{systolicAvgOffset}," +
  1361. $"{diastolicAvgOffset}," +
  1362. $"'{statStartTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  1363. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'" +
  1364. $")";
  1365. _serviceTDengine.ExecuteInsertSQL(sql);
  1366. #endregion
  1367. #region 注册定时下发
  1368. // 注册下次下推
  1369. var endTime = DateTime.Now;
  1370. #if DEBUG
  1371. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  1372. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  1373. var interval = 0;
  1374. // 获取当前时间
  1375. DateTime now = DateTime.Now;
  1376. // 计算距离下一个$interval天后的8点的时间间隔
  1377. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  1378. TimeSpan timeUntilNextRun = nextRunTime - now;
  1379. // 如果当前时间已经超过了8点,将等待到明天后的8点
  1380. if (timeUntilNextRun < TimeSpan.Zero)
  1381. {
  1382. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  1383. nextRunTime += timeUntilNextRun;
  1384. }
  1385. // var ttl = timeUntilNextRun.TotalMilliseconds;
  1386. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  1387. var data = new
  1388. {
  1389. imei = imeiDel,
  1390. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1391. ttl,
  1392. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  1393. };
  1394. var result = JsonConvert.SerializeObject(data);
  1395. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  1396. #else
  1397. // 每$interval天,晚上8点
  1398. var interval = 1;
  1399. // 获取当前时间
  1400. DateTime now = DateTime.Now;
  1401. // 计算距离下一个$interval天后的8点的时间间隔
  1402. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 20, 0, 0).AddDays(interval);
  1403. TimeSpan timeUntilNextRun = nextRunTime - now;
  1404. // 如果当前时间已经超过了8点,将等待到明天后的8点
  1405. if (timeUntilNextRun < TimeSpan.Zero)
  1406. {
  1407. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  1408. nextRunTime += timeUntilNextRun;
  1409. }
  1410. // var ttl = timeUntilNextRun.TotalMilliseconds;
  1411. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  1412. var data = new
  1413. {
  1414. imei = imeiDel,
  1415. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1416. ttl,
  1417. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  1418. };
  1419. var result = JsonConvert.SerializeObject(data);
  1420. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  1421. #endif
  1422. #endregion
  1423. }
  1424. else
  1425. {
  1426. _logger.LogInformation($"错误响应,没有下推数据:{response.Message}");
  1427. }
  1428. }
  1429. }
  1430. else
  1431. {
  1432. _logger.LogInformation($"向{imeiDel}统计数据已经失效");
  1433. }
  1434. #endregion
  1435. }
  1436. }
  1437. break;
  1438. }
  1439. }
  1440. catch (Exception ex)
  1441. {
  1442. _logger.LogError($"{nameof(WatchEvents)},出错: |{ex.Message}|{ex.StackTrace}");
  1443. }
  1444. });
  1445. }
  1446. private async Task SetIntervalTriggerAsync(string key, string imei, long interval)
  1447. {
  1448. // var key = $"health_monitor/schedule_push/{type}/imei/{imei}";
  1449. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  1450. if (string.IsNullOrWhiteSpace(schedulePush))
  1451. {
  1452. var now = DateTime.Now;
  1453. var timeNextRun = now.Add(TimeSpan.FromSeconds(interval));
  1454. var data = new
  1455. {
  1456. imei,
  1457. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1458. ttl = interval,
  1459. next_run_time = timeNextRun.ToString("yyyy-MM-dd HH:mm:ss")
  1460. };
  1461. var result = JsonConvert.SerializeObject(data);
  1462. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  1463. }
  1464. }
  1465. public static bool IsNowInTimeRanges()
  1466. {
  1467. var now = DateTime.Now.TimeOfDay;
  1468. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  1469. {
  1470. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  1471. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  1472. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  1473. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  1474. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  1475. };
  1476. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  1477. }
  1478. public static bool IsLastUpdateInTimeRanges(DateTime lastUpdate)
  1479. {
  1480. var now = lastUpdate.TimeOfDay;
  1481. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  1482. {
  1483. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  1484. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  1485. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  1486. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  1487. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  1488. };
  1489. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  1490. }
  1491. private async Task SaveAndPushFetalHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int upperAlarmThreshold, int lowerAlarmThreshold, double phrValue, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  1492. {
  1493. // 计算胎心=孕妇心率*系数
  1494. /**
  1495. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  1496. fetalHeartRate = fetalHeartRate > 220 ? 220 : fetalHeartRate; // 胎心的最大值调整为220,超过都按该值220输出
  1497. if (fetalHeartRate >= 220)
  1498. {
  1499. // 先使用最小系数计算
  1500. var statMaxValueFprCoefficient = commonPHR?.StatMaxValueFprCoefficient!;
  1501. var statMinValueFprCoefficient = commonPHR?.StatMinValueFprCoefficient!;
  1502. var coefficient = statMaxValueFprCoefficient < statMinValueFprCoefficient ? statMaxValueFprCoefficient : statMinValueFprCoefficient;
  1503. fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  1504. if (fetalHeartRate < 220)
  1505. {
  1506. _logger.LogWarning($"{heartRate.Serialno} 使用极值系数 {coefficient} ,建模数据可能出现异常,请检查");
  1507. }
  1508. else
  1509. {
  1510. fetalHeartRate = 220;
  1511. _logger.LogWarning($"{heartRate.Serialno} 使用所有系数都不能放映实际,建模数据可能出现异常,请检查");
  1512. }
  1513. }
  1514. */
  1515. #region 胎心系数使用基于心率与中位数对比
  1516. var coefficient = 0f;
  1517. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  1518. if (heartRate.HeartRate < commonPHR!.Mode)
  1519. {
  1520. coefficient = commonPHR.StatMinValueFprCoefficient!;
  1521. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  1522. }
  1523. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  1524. else if (heartRate.HeartRate > commonPHR.Mode)
  1525. {
  1526. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  1527. {
  1528. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  1529. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  1530. }
  1531. else
  1532. {
  1533. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  1534. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  1535. }
  1536. }
  1537. else
  1538. {
  1539. coefficient = commonPHR.StatModeAvgFprCoefficient;
  1540. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  1541. }
  1542. #endregion
  1543. var fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  1544. // 胎心的最大值调整为220,超过都按该值220输出
  1545. fetalHeartRate = fetalHeartRate >= 220 ? 220 : fetalHeartRate;
  1546. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  1547. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  1548. if (phrFreqstatus == null) isAbnormal = 0;
  1549. var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  1550. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1551. //if (!isFreq)
  1552. //{
  1553. // statStartTime = heartRate.LastUpdate;
  1554. //
  1555. //}
  1556. // 保存到 数据服务 MySQL 数据库
  1557. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  1558. {
  1559. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  1560. PersonId = commonPHR!.PersonId,
  1561. Serialno = heartRate.Serialno,
  1562. HeartRate = fetalHeartRate,
  1563. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  1564. IsAbnormal = isAbnormal,
  1565. StatStartTime = statStartTime,
  1566. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  1567. CreateTime = DateTime.Now,
  1568. Method = 1,
  1569. IsDisplay = 1,
  1570. DeviceKey = commonPHR!.DeviceKey
  1571. };
  1572. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  1573. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  1574. // 推送最后一条常规心率计算的胎心数据到iot设备
  1575. #region 推送最后一条常规心率计算的胎心数据到iot设备
  1576. // 高频(<=12)-常规
  1577. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  1578. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  1579. {
  1580. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1581. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  1582. }
  1583. // 高频(13)-常规-高频(13)
  1584. if (phrFreqstatus != null)
  1585. {
  1586. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  1587. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1588. // 获取高频数据
  1589. var freqCollection = new List<PregnancyHeartRateModel>();
  1590. PregnancyHeartRateModel? previousItem = null;
  1591. foreach (var item in phr)
  1592. {
  1593. if (previousItem != null)
  1594. {
  1595. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1596. if (timeNextDiff <= 60)
  1597. {
  1598. freqCollection.Add(item);
  1599. }
  1600. }
  1601. // 高频最后一条
  1602. if (lastPhr.MessageId == item.MessageId)
  1603. {
  1604. freqCollection.Add(item);
  1605. }
  1606. previousItem = item;
  1607. }
  1608. //去除高频
  1609. foreach (var item in freqCollection)
  1610. {
  1611. phr.Remove(item);
  1612. }
  1613. lastPhr = phr.FirstOrDefault();
  1614. if (lastPhr?.MessageId == heartRate.MessageId)
  1615. {
  1616. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1617. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  1618. }
  1619. }
  1620. #endregion
  1621. #region 高频心率计算胎心数据到iot设备
  1622. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  1623. if (phrFreqstatus != null && isAbnormal != 0)
  1624. {
  1625. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1626. }
  1627. #endregion
  1628. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  1629. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  1630. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  1631. // 胎心数据推送到第三方
  1632. var topic = "topic.push.third";
  1633. var fhrThridMsg = new
  1634. {
  1635. messageId = fhrMsgId,
  1636. topic = topic,
  1637. time = fhrMsgTime,
  1638. data = new
  1639. {
  1640. imei = heartRate.Serialno,
  1641. value = fetalHeartRate,
  1642. isAbnormal,
  1643. type = "fetalHeart"
  1644. }
  1645. };
  1646. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  1647. // 胎心数据推送到微信
  1648. if (isAbnormal != 0)
  1649. {
  1650. topic = "topic.push.wx";
  1651. var fhrMsg = new
  1652. {
  1653. messageId = fhrMsgId,
  1654. topic = topic,
  1655. time = fhrMsgTime,
  1656. data = new
  1657. {
  1658. deviceId = device?.DeviceId,
  1659. imei = heartRate.Serialno,
  1660. alarmTypeId = 12,
  1661. alarmDeviceName = heartRate.Serialno,
  1662. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  1663. address = string.Empty,
  1664. deviceKey = device?.DeviceId
  1665. }
  1666. };
  1667. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  1668. }
  1669. }
  1670. /// <summary>
  1671. /// 去除高频数据
  1672. /// </summary>
  1673. /// <param name="phr"></param>
  1674. /// <param name="highFreqSampleInterva"></param>
  1675. /// <returns></returns>
  1676. private static List<PregnancyHeartRateModel> GetNonFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr, int highFreqSampleInterval)
  1677. {
  1678. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1679. var result = new List<PregnancyHeartRateModel>();
  1680. PregnancyHeartRateModel? previousItem = null;
  1681. foreach (var item in phr)
  1682. {
  1683. if (previousItem != null)
  1684. {
  1685. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1686. if (timeNextDiff > highFreqSampleInterval)
  1687. {
  1688. result.Add(previousItem);
  1689. }
  1690. }
  1691. previousItem = item;
  1692. }
  1693. // 添加上一个
  1694. if (previousItem != null)
  1695. {
  1696. result.Add(previousItem);
  1697. }
  1698. return result;
  1699. }
  1700. /// <summary>
  1701. /// 获取高频数据
  1702. /// </summary>
  1703. /// <param name="phr"></param>
  1704. /// <param name="highFreqSampleInterval"></param>
  1705. /// <returns></returns>
  1706. private static List<PregnancyHeartRateModel> GetFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr, int highFreqSampleInterval)
  1707. {
  1708. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1709. var freqCollection = new List<PregnancyHeartRateModel>();
  1710. PregnancyHeartRateModel? previousItem = null;
  1711. foreach (var item in phr)
  1712. {
  1713. if (previousItem != null)
  1714. {
  1715. var timeNextDiff = (previousItem.LastUpdate - item.LastUpdate).TotalSeconds;
  1716. if (timeNextDiff <= highFreqSampleInterval)
  1717. {
  1718. freqCollection.Add(previousItem);
  1719. }
  1720. }
  1721. previousItem = item;
  1722. }
  1723. // 检查最后一条是否高频
  1724. if (previousItem != null && (phr.Last().LastUpdate - previousItem.LastUpdate).TotalSeconds <= highFreqSampleInterval)
  1725. {
  1726. freqCollection.Add(previousItem);
  1727. }
  1728. return freqCollection;
  1729. }
  1730. public async Task CalculateNormalFetalHeartRateIntervalAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR,int highFreqSampleInterval)
  1731. {
  1732. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  1733. var filteredPhr = daysPhr.Where(i => i.LastUpdate >= heartRate.LastUpdate && i.LastUpdate <= DateTime.Now).ToList();
  1734. // 去除高频
  1735. var normalPhr = GetNonFreqPregnancyHeartRate(filteredPhr, highFreqSampleInterval).OrderBy(i => i.LastUpdate);
  1736. var startPhr = normalPhr.First();
  1737. var endPhr = normalPhr.Last();
  1738. //var sampleTime = GetSampleTimeFromLastUpdate((DateTime)heartRate.LastUpdate!, INTERVAL_FHR);
  1739. // 数据统计边界
  1740. var boundaryStatStartTime = GetSampleTimeFromLastUpdate((DateTime)startPhr.LastUpdate!, INTERVAL_FHR);
  1741. var boundaryStatEndTime = GetSampleTimeFromLastUpdate((DateTime)endPhr.LastUpdate!, INTERVAL_FHR).AddMinutes(INTERVAL_FHR);
  1742. _logger.LogInformation($"{heartRate.Serialno} 统计边界{boundaryStatStartTime}-{boundaryStatEndTime}");
  1743. try
  1744. {
  1745. var c = 0;
  1746. while (true)
  1747. {
  1748. var segmentStatStartTime = boundaryStatStartTime.AddMinutes(c * INTERVAL_FHR);
  1749. var segmentStatEndTime = segmentStatStartTime.AddMinutes(INTERVAL_FHR);
  1750. c++;
  1751. var statStartTime = segmentStatStartTime;
  1752. var statEndTime = segmentStatEndTime;
  1753. _logger.LogInformation($"{heartRate.Serialno} 当前统计周期{statStartTime}-{statEndTime}");
  1754. var segmentPhr = daysPhr
  1755. .Where(i => i.LastUpdate <= statEndTime && i.LastUpdate >= statStartTime)
  1756. .ToList();
  1757. if (segmentPhr.Count == 0)
  1758. {
  1759. // 跳出当次迭代,进入下次迭代
  1760. _logger.LogWarning($"{heartRate.Serialno} 统计周期:{statStartTime}-{statEndTime} 孕妇心率数据不足,{segmentPhr.Count}条记录,不处理");
  1761. continue;
  1762. }
  1763. var sampleTime = DateTimeUtil.ConvertToTimeStamp(segmentStatStartTime).ToString();
  1764. sampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime;
  1765. //检测 是否存在,不存在则处理
  1766. GeneralParam param = new()
  1767. {
  1768. Filters = new List<QueryFilterCondition>
  1769. {
  1770. new ()
  1771. {
  1772. Key=nameof(HisGpsFetalHeartRate.Serialno),
  1773. Value=heartRate.Serialno,
  1774. ValueType=QueryValueTypeEnum.String,
  1775. Operator=QueryOperatorEnum.Equal
  1776. },
  1777. new ()
  1778. {
  1779. Key=nameof(HisGpsFetalHeartRate.SampleTime),
  1780. Value=sampleTime,
  1781. ValueType=QueryValueTypeEnum.String,
  1782. Operator=QueryOperatorEnum.Equal
  1783. },
  1784. },
  1785. OrderBys = new List<OrderByCondition>
  1786. {
  1787. new (){
  1788. IsDesc=true,
  1789. Key=nameof(HisGpsFetalHeartRate.SampleTime)
  1790. }
  1791. }
  1792. };
  1793. var fhr = await _hisFetalHeartApiClient.GetFirstAsync(param, heartRate.Serialno[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  1794. if (fhr == null)
  1795. {
  1796. var avgPhr = segmentPhr.Count == 1
  1797. ? segmentPhr.First().PregnancyHeartRate
  1798. : segmentPhr.Average(i => i.PregnancyHeartRate);
  1799. heartRate.HeartRate = (int)avgPhr;
  1800. #region 胎心系数使用基于心率与中位数对比
  1801. var coefficient = 0f;
  1802. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  1803. if (heartRate.HeartRate < commonPHR!.Mode)
  1804. {
  1805. coefficient = commonPHR.StatMinValueFprCoefficient!;
  1806. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  1807. }
  1808. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  1809. else if (heartRate.HeartRate > commonPHR.Mode)
  1810. {
  1811. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  1812. {
  1813. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  1814. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  1815. }
  1816. else
  1817. {
  1818. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  1819. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  1820. }
  1821. }
  1822. else
  1823. {
  1824. coefficient = commonPHR.StatModeAvgFprCoefficient;
  1825. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  1826. }
  1827. #endregion
  1828. #region 胎心阈值判断
  1829. //var fetalHeartRate = SafeType.SafeInt(heartRate.HeartRate * coefficient);
  1830. //// 胎心的最大值调整为220,超过都按该值220输出
  1831. //// fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  1832. //if (fetalHeartRate > 220)
  1833. //{
  1834. // fetalHeartRate = 220;
  1835. // _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")}");
  1836. //}
  1837. //// 胎心的最小值调整为90,超过都按该值90
  1838. //if (fetalHeartRate < 90)
  1839. //{
  1840. // fetalHeartRate = 90;
  1841. // _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")}");
  1842. //}
  1843. // 计算胎心率并进行边界检查
  1844. var fetalHeartRate = Math.Clamp((int)(heartRate.HeartRate * coefficient), 90, 220);
  1845. if (fetalHeartRate != (int)(heartRate.HeartRate * coefficient))
  1846. {
  1847. _logger.LogWarning($"{heartRate.Serialno} 胎心率超出范围, 按修正值 {fetalHeartRate} 输出, 计算因子:孕妇心率 {heartRate.HeartRate}, 系数 {coefficient}, 周期 {statStartTime} - {statEndTime}");
  1848. }
  1849. #endregion
  1850. _logger.LogInformation($"{heartRate.Serialno} 在 常规 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1851. var isAbnormal = 0;
  1852. #region 保存到Mysql数据库
  1853. // 保存到 数据服务 MySQL 数据库
  1854. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  1855. {
  1856. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  1857. PersonId = commonPHR!.PersonId,
  1858. Serialno = heartRate.Serialno,
  1859. HeartRate = fetalHeartRate,
  1860. SampleTime = sampleTime,
  1861. IsAbnormal = isAbnormal,
  1862. StatStartTime = statStartTime,
  1863. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  1864. CreateTime = DateTime.Now,
  1865. Method = 1,
  1866. IsDisplay = 1,
  1867. DeviceKey = commonPHR!.DeviceKey
  1868. };
  1869. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  1870. #endregion
  1871. #region 推送最后一条常规心率计算的胎心数据到iot设备
  1872. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  1873. if (segmentStatEndTime == boundaryStatEndTime)
  1874. {
  1875. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1876. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备");
  1877. }
  1878. #endregion
  1879. #region 推送到第三方
  1880. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  1881. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  1882. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  1883. var topic = "topic.push.third";
  1884. var fhrThridMsg = new
  1885. {
  1886. messageId = fhrMsgId,
  1887. topic = topic,
  1888. time = fhrMsgTime,
  1889. data = new
  1890. {
  1891. imei = heartRate.Serialno,
  1892. value = fetalHeartRate,
  1893. isAbnormal,
  1894. type = "fetalHeart"
  1895. }
  1896. };
  1897. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  1898. #endregion
  1899. #region 推送到微信
  1900. if (isAbnormal != 0)
  1901. {
  1902. topic = "topic.push.wx";
  1903. var fhrMsg = new
  1904. {
  1905. messageId = fhrMsgId,
  1906. topic = topic,
  1907. time = fhrMsgTime,
  1908. data = new
  1909. {
  1910. deviceId = device?.DeviceId,
  1911. imei = heartRate.Serialno,
  1912. alarmTypeId = 12,
  1913. alarmDeviceName = heartRate.Serialno,
  1914. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  1915. address = string.Empty,
  1916. deviceKey = device?.DeviceId
  1917. }
  1918. };
  1919. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  1920. }
  1921. #endregion
  1922. }
  1923. else
  1924. {
  1925. _logger.LogInformation($"{heartRate.Serialno},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")} ,胎心已处理");
  1926. }
  1927. // 跳出循环
  1928. if (statEndTime == boundaryStatEndTime)
  1929. {
  1930. break;
  1931. }
  1932. }
  1933. }
  1934. catch (Exception ex)
  1935. {
  1936. _logger.LogError($"处理心率数据时发生错误: {ex.Message}");
  1937. }
  1938. //for (var segmentStatStartTime = boundaryStatStartTime;
  1939. // segmentStatStartTime < boundaryStatEndTime;
  1940. // segmentStatStartTime = segmentStatStartTime.AddMinutes(INTERVAL_FHR))
  1941. //{
  1942. // var segmentStatEndTime = segmentStatStartTime.AddMinutes(INTERVAL_FHR);
  1943. // var segmentPhr = daysPhr
  1944. // .Where(i => i.LastUpdate <= segmentStatEndTime && i.LastUpdate >= segmentStatStartTime)
  1945. // .ToList();
  1946. // if (segmentStatEndTime == boundaryStatEndTime)
  1947. // {
  1948. // break;
  1949. // }
  1950. //}
  1951. }
  1952. private DateTime GetSampleTimeFromLastUpdate(DateTime lastUpdate,int interval)
  1953. {
  1954. DateTime nowInterval = lastUpdate;
  1955. if (nowInterval.Second > 0)
  1956. {
  1957. nowInterval = nowInterval.AddMinutes(1);
  1958. }
  1959. // 计算last_update到上一间隔的分钟数
  1960. int minutesToSubtract = nowInterval.Minute % interval;
  1961. // 计算上一间隔的时间
  1962. DateTime previousInterval = nowInterval.AddMinutes(-minutesToSubtract).AddSeconds(-nowInterval.Second).AddMilliseconds(-nowInterval.Millisecond);
  1963. return previousInterval;
  1964. }
  1965. }
  1966. }