Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

PregnancyHeartRateResolver.cs 94KB

pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 3 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 4 mēnešiem
pirms 3 mēnešiem
pirms 4 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 4 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 4 mēnešiem
pirms 3 mēnešiem
pirms 4 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 nedēļām
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 1 mēnesi
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 4 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 2 mēnešiem
pirms 2 mēnešiem
pirms 3 mēnešiem
pirms 2 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 2 mēnešiem
pirms 2 mēnešiem
pirms 2 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 2 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 2 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 4 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 4 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 4 mēnešiem
pirms 3 mēnešiem
pirms 4 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 2 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 2 mēnešiem
pirms 2 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 4 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 3 mēnešiem
pirms 4 mēnešiem
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  1. using Etcdserverpb;
  2. using Google.Protobuf.WellKnownTypes;
  3. using HealthMonitor.Common;
  4. using HealthMonitor.Common.helper;
  5. using HealthMonitor.Model.Service.Mapper;
  6. using HealthMonitor.Service.Biz;
  7. using HealthMonitor.Service.Biz.db;
  8. using HealthMonitor.Service.Cache;
  9. using HealthMonitor.Service.Etcd;
  10. using HealthMonitor.Service.MessageQueue;
  11. using HealthMonitor.Service.Resolver.Interface;
  12. using HealthMonitor.Service.Sub;
  13. using HealthMonitor.Service.Sub.Topic.Model;
  14. using Microsoft.EntityFrameworkCore.Metadata;
  15. using Microsoft.Extensions.Logging;
  16. using Newtonsoft.Json;
  17. using Newtonsoft.Json.Linq;
  18. using SqlSugar;
  19. using System;
  20. using System.Collections.Generic;
  21. using System.Linq;
  22. using System.Net;
  23. using System.Text;
  24. using System.Threading.Tasks;
  25. using TelpoDataService.Util.Clients;
  26. using TelpoDataService.Util.Entities.GpsCard;
  27. using TelpoDataService.Util.Entities.GpsLocationHistory;
  28. using TelpoDataService.Util.Models;
  29. using TelpoDataService.Util.QueryObjects;
  30. namespace HealthMonitor.Service.Resolver
  31. {
  32. public class PregnancyHeartRateResolver : IResolver
  33. {
  34. private readonly ILogger<PregnancyHeartRateResolver> _logger;
  35. private readonly TDengineService _serviceTDengine;
  36. private readonly DeviceCacheManager _deviceCacheMgr;
  37. private readonly IotApiService _serviceIotApi;
  38. private readonly AsyncLocal<string> _messageId = new();
  39. private readonly AsyncLocal<HisGpsHeartRate> _msgData = new();
  40. private readonly HttpHelper _httpHelper = default!;
  41. private readonly EtcdService _serviceEtcd;
  42. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> _hisFetalHeartApiClient;
  43. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalMovement> _hisFetalMovementApiClient;
  44. private readonly FetalMovementNormalValueRangeCacheManager _mgrFetalMovementNormalValueRangeCache;
  45. private readonly MqProcessLogic _serviceMqProcess;
  46. private static int[] SCHEDULE_HOUR = new int[] {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22};
  47. private static int[] ODD_SCHEDULE_HOUR = new int[] { 1, 3, 5, 7, 9, 11,13, 15, 17, 19, 21, 23 };
  48. // 延时胎心计算间隔周期
  49. private static int INTERVAL_FHR=15;
  50. public PregnancyHeartRateResolver(ILogger<PregnancyHeartRateResolver> logger,
  51. HttpHelper httpHelper, EtcdService serviceEtcd, DeviceCacheManager deviceCacheMgr,
  52. MqProcessLogic serviceMqProcess,
  53. IotApiService iotApiService, TDengineService serviceDengine, FetalMovementNormalValueRangeCacheManager fetalMovementNormalValueRangeCacheMgr,
  54. GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> hisFetalHeartApiClient,
  55. GpsLocationHistoryAccessorClient<HisGpsFetalMovement> hisFetalMovementApiClient
  56. )
  57. {
  58. _logger = logger;
  59. _httpHelper = httpHelper;
  60. _serviceEtcd = serviceEtcd;
  61. _serviceTDengine = serviceDengine;
  62. _deviceCacheMgr = deviceCacheMgr;
  63. _serviceIotApi = iotApiService;
  64. _serviceMqProcess = serviceMqProcess;
  65. _hisFetalHeartApiClient = hisFetalHeartApiClient;
  66. _hisFetalMovementApiClient = hisFetalMovementApiClient;
  67. _mgrFetalMovementNormalValueRangeCache = fetalMovementNormalValueRangeCacheMgr;
  68. }
  69. public void SetResolveInfo(PackageMsgModel msg)
  70. {
  71. var topicHmPregnancyHeartRate = JsonConvert.DeserializeObject<TopicHmPregnancyHeartRate>(msg.DetailData.ToString()!);
  72. _messageId.Value = msg.MessageId;
  73. _msgData.Value = new HisGpsHeartRate()
  74. {
  75. HeartRateId = topicHmPregnancyHeartRate!.PregnancyHeartRateId,
  76. MessageId = topicHmPregnancyHeartRate!.MessageId,
  77. Serialno = topicHmPregnancyHeartRate!.Serialno,
  78. HeartRate = topicHmPregnancyHeartRate.PregnancyHeartRate,
  79. LastUpdate = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmPregnancyHeartRate.LastUpdate) / 1000000),
  80. CreateTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmPregnancyHeartRate.CreateTime) / 1000000),
  81. Method = topicHmPregnancyHeartRate!.Method,
  82. IsDisplay = topicHmPregnancyHeartRate!.IsDisplay ? 1 : 0
  83. };
  84. }
  85. public override string ToString()
  86. {
  87. return $"{nameof(PregnancyHeartRateResolver)}[{_messageId.Value}]";
  88. }
  89. public async Task ExecuteMessageAsync()
  90. {
  91. var messageId = _messageId.Value;
  92. var heartRate = _msgData.Value!;
  93. try
  94. {
  95. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(heartRate.Serialno, "0067");
  96. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  97. if (isFetalHeartEnable)
  98. {
  99. //_logger.LogInformation($"{heartRate.Serialno} 计算胎心胎动启动");
  100. #region 定时下发触发器(定时建模)
  101. var key = $"health_monitor/schedule_push/pregnancy_heart_rate/imei/{heartRate.Serialno}";
  102. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  103. if (string.IsNullOrWhiteSpace(schedule_push))
  104. {
  105. // 注册首次下推
  106. var interval = 0;
  107. // 获取当前时间
  108. DateTime now = DateTime.Now;
  109. var rand = new Random();
  110. var pushSec = rand.Next(59);
  111. int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  112. // 计算距离下一个$interval天后的8点的时间间隔
  113. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 6, pushMin, pushSec).AddDays(interval);
  114. TimeSpan timeUntilNextRun = nextRunTime - now;
  115. if (timeUntilNextRun < TimeSpan.Zero)
  116. {
  117. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  118. nextRunTime += TimeSpan.FromDays(1);
  119. }
  120. var ttl = (long)timeUntilNextRun.TotalSeconds;
  121. var data = new
  122. {
  123. imei = heartRate.Serialno,
  124. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  125. ttl,
  126. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  127. };
  128. var result = JsonConvert.SerializeObject(data);
  129. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  130. }
  131. #endregion
  132. //_logger.LogInformation($"{heartRate.Serialno} 触发定时建模");
  133. // 高频心率采样间隔 highFreqSampleInterval = highFreqSampleInterval 最小highFreqSampleInterval=60)
  134. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]! >= 60 ? (int)watchConfig!["highFreqSampleInterval"]!:60;
  135. // 触发高频监测的心率上限值
  136. var triggerHighFreqHigh = (int)watchConfig["triggerHighFreqHigh"]!;
  137. // 触发高频监测的心率下限值
  138. var triggerHighFreqLow = (int)watchConfig["triggerHighFreqLow"]!;
  139. // 暂时处理
  140. triggerHighFreqLow = triggerHighFreqLow > 60 && triggerHighFreqLow < 67 ? 60 : triggerHighFreqLow;
  141. //停止高频心率采样心率连续正常次数
  142. var stopHighFreqSampleCount = (int)watchConfig["stopHighFreqSampleCount"]!;
  143. // 高频心率采集时长 0 为持续采集,非零为高频心率的采集时长
  144. //var highFreqSampleTimes = (int)watchConfig["highFreqSampleTimes"]!;
  145. var highFreqSampleTimes = 540;
  146. // 告警上限阀值
  147. var upperAlarmThreshold = (int)watchConfig["upperAlarmThreshold"]!;
  148. // 告警下限阀值
  149. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  150. // EDOC
  151. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  152. // interval (分钟) 固定15分钟
  153. var intervalFHR = 15;//int)watchConfig["interval"]!;
  154. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  155. var phr = daysPhr
  156. .Where(p => p.LastUpdate <= heartRate.LastUpdate)
  157. .ToList();
  158. _logger.LogInformation($"{heartRate.Serialno} 当前数据在TD数据库:{phr.Select(i=>i.MessageId).Contains(heartRate.MessageId)}");
  159. var nonFreqPhr = GetNonFreqPregnancyHeartRate(phr, highFreqSampleInterval);
  160. if (nonFreqPhr.Count >= 30)
  161. {
  162. #region 定时计算胎动数据触发器两小时间隔开始(奇数小时计算)
  163. /**
  164. var fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}";
  165. var rand = new Random();
  166. var pushSec = rand.Next(59);
  167. int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  168. DateTime fmScheduleNow = DateTime.Now;
  169. int hour = fmScheduleNow.Hour;
  170. int selectedScheduleHour;
  171. // 使用模运算来获取相应的ODD_SCHEDULE_HOUR
  172. if (hour % 2 == 0)
  173. {
  174. selectedScheduleHour = ODD_SCHEDULE_HOUR[hour / 2 % ODD_SCHEDULE_HOUR.Length];
  175. }
  176. else
  177. {
  178. selectedScheduleHour = ODD_SCHEDULE_HOUR[(hour + 1) / 2 % ODD_SCHEDULE_HOUR.Length];
  179. }
  180. DateTime scheduledDateTime = new DateTime(
  181. fmScheduleNow.Year,
  182. fmScheduleNow.Month,
  183. fmScheduleNow.Day,
  184. selectedScheduleHour,
  185. pushMin,
  186. pushSec
  187. );
  188. // 如果生成的时间在当前时间之前
  189. // 或者 fmScheduleNow 在 23 点之后并且 selectedScheduleHour 在 1 点(即次日)
  190. if (scheduledDateTime < fmScheduleNow || (fmScheduleNow.Hour >= 23 && selectedScheduleHour <= 1))
  191. {
  192. scheduledDateTime = scheduledDateTime.AddDays(1);
  193. }
  194. TimeSpan timeUntilNextRun = scheduledDateTime - fmScheduleNow;
  195. var ttl = (long)timeUntilNextRun.TotalSeconds;
  196. await SetIntervalTriggerAsync(fetalMovementKey, heartRate.Serialno, ttl, heartRate);
  197. _logger.LogInformation($"{heartRate.Serialno}-{heartRate.MessageId} 创建计划统计胎动时间{scheduledDateTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  198. */
  199. #endregion
  200. #region 定时计算胎动数据触发器每小时间隔开始,延时一个小时计算
  201. /*
  202. ///当前时间是的0~1小时返回2小时 ,
  203. ///当前时间是的1~2小时返回3小时 ,如此类推,
  204. ///当前时间是的21~22小时返回23小时
  205. ///当前时间是的23~0小时返回次日1小时
  206. var fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}";
  207. var rand = new Random();
  208. var pushSec = rand.Next(59);
  209. int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  210. DateTime fmScheduleNow = DateTime.Now;
  211. int hour = fmScheduleNow.Hour;
  212. int selectedScheduleHour=DateTimeUtil.GetNextHour(fmScheduleNow.Hour);
  213. DateTime scheduledDateTime = new DateTime(
  214. fmScheduleNow.Year,
  215. fmScheduleNow.Month,
  216. fmScheduleNow.Day,
  217. selectedScheduleHour,
  218. pushMin,
  219. pushSec
  220. );
  221. // 跨天
  222. if (selectedScheduleHour == 1 || selectedScheduleHour == 0)
  223. {
  224. scheduledDateTime = scheduledDateTime.AddDays(1);
  225. }
  226. TimeSpan timeUntilNextRun = scheduledDateTime - fmScheduleNow;
  227. var ttl = (long)timeUntilNextRun.TotalSeconds;
  228. await SetIntervalTriggerAsync(fetalMovementKey, heartRate.Serialno, ttl, heartRate);
  229. _logger.LogInformation($"{heartRate.Serialno}-{heartRate.MessageId} 创建计划统计胎动时间{scheduledDateTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  230. */
  231. #endregion
  232. #region 定时计算胎动数据触发器每小时间隔开始,延时一个小时计算
  233. ///当前时间是的0~1小时返回2小时 ,
  234. ///当前时间是的1~2小时返回3小时 ,如此类推,
  235. ///当前时间是的21~22小时返回23小时
  236. ///当前时间是的23~0小时返回次日1小时
  237. // lastUpdate默认奇数 // lastUpdate偶数小时
  238. var fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}";
  239. var rand = new Random();
  240. var pushSec = rand.Next(59);
  241. int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  242. DateTime fmScheduleNow = DateTime.Now;
  243. int hour = fmScheduleNow.Hour;
  244. int selectedScheduleHour = DateTimeUtil.GetNextHour(fmScheduleNow.Hour);
  245. DateTime scheduledDateTime = DateTime.Now.Date
  246. .AddHours(selectedScheduleHour)
  247. .AddMinutes(pushMin)
  248. .AddSeconds(pushSec);
  249. // 当前时间与lastUpdate的时间差小于2小时,0~1->2,0~1的数据是1点的sample_time,2点计算
  250. if (DateTime.Now.Subtract((DateTime)heartRate.LastUpdate!).TotalHours <= 2)
  251. {
  252. selectedScheduleHour = DateTimeUtil.GetNextHour(((DateTime)heartRate.LastUpdate).Hour);
  253. scheduledDateTime = DateTime.Now.Date
  254. .AddHours(selectedScheduleHour)
  255. .AddMinutes(pushMin)
  256. .AddSeconds(pushSec);
  257. if (((DateTime)heartRate.LastUpdate).Hour % 2 == 0)
  258. {
  259. // lastUpdate偶数小时
  260. fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}/even_hour";
  261. }
  262. else
  263. {
  264. // lastUpdate奇数小时
  265. fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}/odd_hour";
  266. }
  267. }
  268. // sample_time采集时间与计划计算时间最长是2小时,次日上报引起
  269. else
  270. {
  271. _logger.LogWarning($"iot 上报延迟,last_update与计划计算时间超过2小时");
  272. }
  273. // 跨天
  274. if (selectedScheduleHour == 1 || selectedScheduleHour == 0)
  275. {
  276. scheduledDateTime = scheduledDateTime.AddDays(1);
  277. }
  278. TimeSpan timeUntilNextRun = scheduledDateTime - fmScheduleNow;
  279. var ttl = (long)timeUntilNextRun.TotalSeconds;
  280. await SetIntervalTriggerAsync(fetalMovementKey, heartRate.Serialno, ttl, heartRate);
  281. _logger.LogInformation($"{heartRate.Serialno}-{heartRate.MessageId} 创建计划统计胎动时间{scheduledDateTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  282. #endregion
  283. #region 计算胎心数据(按心率时间LastUpdate)
  284. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(heartRate.Serialno);
  285. // 如果commonPHR为空或已建模已过期,进行建模和保存
  286. if (commonPHR == null || !commonPHR.CreateTime.Date.Equals(DateTime.Now.Date))
  287. // 获取当天 6:11 的时间点, 6:11 所有数据都已经全部建模
  288. //if (commonPHR == null || commonPHR.CreateTime < DateTime.Today.AddHours(6).AddMinutes(11))
  289. {
  290. // 处理孕妇业务,计算一般心率并下发
  291. commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(heartRate.Serialno, highFreqSampleInterval: highFreqSampleInterval);
  292. // 建模完成
  293. var flag = await _serviceIotApi.SetFetalConfig(heartRate.Serialno, 1, commonPHR!.MaxValue, commonPHR!.MinValue);
  294. _logger.LogInformation($"{heartRate.Serialno} 记录数量足够,建模完成");
  295. // 保存到TDengine数据库
  296. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR!);
  297. _logger.LogInformation($"保存TDengine完成");
  298. }
  299. // 获取最近的两个记录,并计算它们的 LastUpdate 时间差
  300. var firstTwoPhr = phr.OrderByDescending(i => i.LastUpdate).Take(2).Select(i => i.LastUpdate).ToList();
  301. var timeDiff = firstTwoPhr[0] - firstTwoPhr[1];
  302. // 如果需要,将时间差转换为秒
  303. var timeDiffInSeconds = timeDiff.TotalSeconds;
  304. // 高频统计结束时间
  305. var FreqStatsEnd = DateTime.Now;
  306. // 高频心率启动(在高频第二条才能判断)
  307. if (timeDiffInSeconds <= highFreqSampleInterval)
  308. {
  309. // 设置延时计算高频心率的胎心
  310. var freqHearRateHey = $"health_monitor/schedule_push/cal_freqhr_fetal_heart_rate/imei/{heartRate.Serialno}";
  311. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  312. if (phrFreqstatus == null)
  313. {
  314. /// 设置高频状态
  315. _logger.LogInformation($"{heartRate.Serialno} 进入高频心率启动状态,时间差 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval}");
  316. // 设置高频状态
  317. _logger.LogInformation($"{heartRate.Serialno} 前7天到当前记录数 {phr.Count},当前 {phr.First().MessageId}");
  318. var freqFirstPhr = phr.OrderByDescending(i => i.LastUpdate)
  319. .Skip(1) //在高频第二条才能判断,所以要去除本条记录
  320. .First();
  321. _logger.LogInformation($"首条高频附近的3条:{string.Join(',', phr.OrderByDescending(i => i.LastUpdate).Take(3).Select(i=>i.MessageId))}");
  322. await _deviceCacheMgr.SetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno, freqFirstPhr);
  323. _logger.LogInformation($"{heartRate.Serialno} 设置高频状态,首条高频心率ID:{freqFirstPhr.MessageId}");
  324. phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  325. HisGpsHeartRate freqFirstHR = new()
  326. {
  327. CreateTime = freqFirstPhr.CreateTime,
  328. DeviceKey = freqFirstPhr.DeviceKey,
  329. HeartRate = freqFirstPhr.PregnancyHeartRate,
  330. HeartRateId = freqFirstPhr.PregnancyHeartRateId,
  331. IsDisplay = freqFirstPhr.IsDisplay ? 1 : 0,
  332. LastUpdate = freqFirstPhr.LastUpdate,
  333. MessageId = freqFirstPhr.MessageId,
  334. Method = freqFirstPhr.Method,
  335. PersonId = freqFirstPhr.PersonId,
  336. Serialno = freqFirstPhr.SerialNumber,
  337. };
  338. // 设置的续租周期
  339. await SetFreqHeartRateTriggerAsync(freqHearRateHey, heartRate.Serialno, highFreqSampleInterval+30, freqFirstHR);
  340. }
  341. // 续租延时计算高频心率的胎心
  342. await SetFreqHeartRateTriggerAsync(freqHearRateHey, heartRate.Serialno, highFreqSampleInterval+30);
  343. /// phr PregnancyHeartRate 连续连续正常次数个值都是正常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  344. /// 取连续正常次数正常值的平均值,推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  345. #region 检查高频状态是否连续12个心率值都是正常的
  346. // 获取最近连续正常次数个心率记录
  347. //_logger.LogInformation($"{heartRate.Serialno} 设置 stopHighFreqSampleCount {stopHighFreqSampleCount}");
  348. //var lastPhr = phr.OrderByDescending(i => i.LastUpdate).Take(stopHighFreqSampleCount).ToList();
  349. var lastPhr = phr.Where(i => i.LastUpdate >= phrFreqstatus!.LastUpdate)
  350. .OrderByDescending(i => i.LastUpdate).Take(stopHighFreqSampleCount).ToList();
  351. _logger.LogInformation($"{heartRate.Serialno} 最后段记录数量:lastPhr.Count {lastPhr.Count},stopHighFreqSampleCount {stopHighFreqSampleCount}");
  352. _logger.LogInformation($"{heartRate.Serialno} 条件1-数量 Count:{lastPhr.Count >= stopHighFreqSampleCount}");
  353. _logger.LogInformation($"{heartRate.Serialno} 条件2-是否正常值 ALL{lastPhr.All(i => i.PregnancyHeartRate >= triggerHighFreqLow && i.PregnancyHeartRate <= triggerHighFreqHigh)}");
  354. // 检查是否连续12个值都是正常的
  355. if ((lastPhr.Count >= stopHighFreqSampleCount) &&
  356. lastPhr.All(i => i.PregnancyHeartRate >= triggerHighFreqLow && i.PregnancyHeartRate <= triggerHighFreqHigh)
  357. )
  358. {
  359. var avgPhr = lastPhr.Select(i => i.PregnancyHeartRate).Average();
  360. // 计算一般心率得到胎心系数
  361. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(DateTime.Now).ToString());
  362. // 高频数据不建模
  363. FreqStatsEnd = (DateTime)heartRate.LastUpdate!;
  364. _logger.LogInformation($"{heartRate.Serialno} 高频状态已经持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,连续 {stopHighFreqSampleCount} 次采样心率正常,将下发指令");
  365. var freqSaveAndPushFetalHeartRate = await _deviceCacheMgr.GetBizIntervalAsync(heartRate.Serialno, "SaveAndPushFetalHeartRate");
  366. // 高频不停,15分钟内只下发一条
  367. if (string.IsNullOrEmpty(freqSaveAndPushFetalHeartRate))
  368. {
  369. //await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  370. heartRate.HeartRate = (int)avgPhr;
  371. //await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  372. // 最后一条高频心率
  373. var lastFreqHr = lastPhr.First();
  374. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)lastFreqHr.LastUpdate!, phrFreqstatus!.LastUpdate);
  375. // 判断是否够highFreqSampleTimes,540s
  376. if (ts < highFreqSampleTimes)
  377. {
  378. /// 不够10分钟最近12个数据的最小值生成胎心值
  379. _logger.LogInformation($"{heartRate.Serialno} 不够10分钟最近12个数据的最小值生成胎心值");
  380. heartRate.HeartRate = lastPhr.Select(i=>i.PregnancyHeartRate).Min();
  381. heartRate.LastUpdate = lastFreqHr.LastUpdate;
  382. }
  383. _logger.LogInformation($"{heartRate.Serialno} 高频数据触发连续12个值都是正常的的高频心率处理");
  384. await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR,highFreqSampleTimes ,upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  385. // 删除高频状态的首条记录
  386. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  387. // 设置15分的SaveAndPushFetalHeartRate业务间隔
  388. await _deviceCacheMgr.SetBizIntervalAsync(heartRate.Serialno, "SaveAndPushFetalHeartRate");
  389. _logger.LogInformation($"{heartRate.Serialno} 连续 {stopHighFreqSampleCount} 次采样心率正常,结束高频心率状态, timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval},高频状态持续{((DateTime)heartRate.LastUpdate - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,高频心率平均值:{(int)avgPhr}");
  390. }
  391. else
  392. {
  393. _logger.LogWarning($"{heartRate.Serialno} 连续 {stopHighFreqSampleCount} 次采样心率正常,设备端应该结束高频状态,但设备端没有结束高频,平台高频15分钟内已经下发过指令");
  394. }
  395. }
  396. else
  397. {
  398. _logger.LogInformation($"{heartRate.Serialno} 处于高频状态...");
  399. }
  400. #endregion
  401. }
  402. // 高频心率结束或常规心率
  403. else
  404. {
  405. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  406. // 高频心率结束
  407. if (phrFreqstatus != null)
  408. {
  409. /// 在highFreqSampleTimes=0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  410. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  411. if (highFreqSampleTimes == 0)
  412. {
  413. var lastPhr = phr.OrderByDescending(i => i.LastUpdate)
  414. .Where(i => i.LastUpdate >= phrFreqstatus?.LastUpdate)
  415. .Skip(1) // 去除首条
  416. .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh);
  417. //.Select(i => i.PregnancyHeartRate);
  418. //.Average();
  419. var avgPhr = lastPhr.Select(i => i.PregnancyHeartRate).Average();
  420. // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  421. // 计算一般心率得到胎心系数
  422. // 高频数据不建模
  423. FreqStatsEnd = firstTwoPhr[1];
  424. _logger.LogInformation($"{heartRate.Serialno} 高频状态已经持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,highFreqSampleTimes={highFreqSampleTimes}秒,即将结束高频状态,高频心率平均值:{(int)avgPhr},将下发指令");
  425. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString());
  426. //await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  427. heartRate.HeartRate = (int)avgPhr;
  428. //await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  429. // 最后一条高频心率
  430. var lastFreqHr = lastPhr.First();
  431. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)lastFreqHr.LastUpdate!, phrFreqstatus!.LastUpdate);
  432. // 判断是否够highFreqSampleTimes,540s
  433. if (ts < highFreqSampleTimes)
  434. {
  435. /// 不够10分钟最近12个数据的最小值生成胎心值
  436. _logger.LogInformation($"{heartRate.Serialno} 不够10分钟最近12个数据的最小值生成胎心值");
  437. heartRate.HeartRate = lastPhr.Select(i => i.PregnancyHeartRate).Min();
  438. heartRate.LastUpdate = lastFreqHr.LastUpdate;
  439. }
  440. _logger.LogInformation($"{heartRate.Serialno} 高频结束后的highFreqSampleTimes=0的高频心率处理");
  441. await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, highFreqSampleTimes, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  442. }
  443. /// 在highFreqSampleTimes>0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  444. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  445. if (highFreqSampleTimes > 0 && heartRate.LastUpdate >= (phrFreqstatus?.LastUpdate.AddSeconds(highFreqSampleTimes)))
  446. {
  447. // 获取高频心率数据个数
  448. var filterPhr = phr
  449. .Where(i => i.LastUpdate >= phrFreqstatus?.LastUpdate)
  450. .Skip(1)
  451. .ToList();
  452. _logger.LogInformation($"{heartRate.Serialno} 高频周期 {phrFreqstatus?.LastUpdate.ToString("yyyy-MM-dd HH:mm:ss")}--{firstTwoPhr[1].ToString("yyyy-MM-dd HH:mm:ss")} 产生高频心率数量 {filterPhr.Count} 条");
  453. // 高频心率数据大于stopHighFreqSampleCount/12个才计算胎心数据
  454. //
  455. if (filterPhr.Count > stopHighFreqSampleCount)
  456. {
  457. FreqStatsEnd = firstTwoPhr[1];
  458. var avgPhr = filterPhr
  459. .OrderByDescending(i => i.LastUpdate)
  460. .Take(stopHighFreqSampleCount) // 计算最后12条
  461. .Select(i => i.PregnancyHeartRate).Average();
  462. //_logger.LogInformation($"{heartRate.Serialno} 高频状态已经持续{(FreqStatsEnd - phrFreqstatus!.LastUpdate).TotalSeconds} 秒,约定的 {highFreqSampleTimes} 秒,即将结束高频状态,高频心率平均值:{(int)avgPhr},将下发指令");
  463. //计算高频
  464. //await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  465. heartRate.HeartRate = (int)avgPhr;
  466. //await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  467. // 判断是否够highFreqSampleTimes,540s
  468. var lastPhr = filterPhr
  469. .OrderByDescending(i => i.LastUpdate)
  470. .Take(stopHighFreqSampleCount);
  471. // 最后一条高频心率
  472. var lastFreqHr = lastPhr.First();
  473. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)lastFreqHr.LastUpdate!, phrFreqstatus!.LastUpdate);
  474. if (ts < highFreqSampleTimes)
  475. {
  476. /// 不够10分钟最近12个数据的最小值生成胎心值
  477. _logger.LogInformation($"{heartRate.Serialno} 不够10分钟最近12个数据的最小值生成胎心值");
  478. heartRate.HeartRate = lastPhr.Select(i => i.PregnancyHeartRate).Min();
  479. heartRate.LastUpdate = lastFreqHr.LastUpdate;
  480. }
  481. _logger.LogInformation($"{heartRate.Serialno} 高频结束后的在highFreqSampleTimes>0 正常心率(通常情况)触发的高频心率处理");
  482. await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, highFreqSampleTimes, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  483. }
  484. else
  485. {
  486. _logger.LogWarning($"{heartRate.Serialno} 高频心率的数据不大于{stopHighFreqSampleCount}条,不进行高频数据的胎心计算");
  487. }
  488. // 删除高频状态的首条记录
  489. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  490. // (逐条计算)计算本次常规心率的胎心数据(高频结束后,实时处理)
  491. // await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  492. await CalculateNormalFetalHeartRateScheduleAsync(heartRate);
  493. }
  494. ///不满足持续10分钟highFreqSampleTimes或出现时间倒叙
  495. ///
  496. else
  497. {
  498. // 高频结束后与常规的心率时间倒叙
  499. if ((firstTwoPhr[1] - phrFreqstatus!.LastUpdate).TotalSeconds < 0)
  500. {
  501. _logger.LogInformation($"{heartRate.Serialno} 高频结束出现时间倒叙,计算当条心率创建之前的高频心率");
  502. #region 计算当条心率创建之前的高频心率
  503. // 取得高频之后的所有数据
  504. var phrFlashBack = daysPhr.Where(p => p.LastUpdate >= phrFreqstatus!.LastUpdate)
  505. .OrderByDescending(i => i.LastUpdate);
  506. // 取得高频数据
  507. var freqCollection = phrFlashBack.ToList();
  508. //var freqCollection = new List<PregnancyHeartRateModel>();
  509. //PregnancyHeartRateModel? previousItem = null;
  510. //foreach (var item in phrFlashBack)
  511. //{
  512. // if (previousItem != null)
  513. // {
  514. // var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  515. // if (timeNextDiff <= highFreqSampleInterval)
  516. // {
  517. // freqCollection.Add(item);
  518. // }
  519. // }
  520. // previousItem = item;
  521. //}
  522. _logger.LogInformation($"{heartRate.Serialno} 高频数据个数{freqCollection.Count},触发高频开始时间{phrFreqstatus!.LastUpdate}");
  523. if (freqCollection.Count > stopHighFreqSampleCount)
  524. {
  525. // 计算高频产生的胎心
  526. var avgPhr = freqCollection
  527. .OrderByDescending(i => i.LastUpdate)
  528. .Take(stopHighFreqSampleCount) // 计算最后12条
  529. .Select(i => i.PregnancyHeartRate).Average();
  530. heartRate.HeartRate = (int)avgPhr;
  531. // await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  532. //_logger.LogInformation($"{heartRate.Serialno} 高频数据个数{freqCollection.Count},触发高频开始时间{phrFreqstatus!.LastUpdate},高频心率平均值:{(int)avgPhr}");
  533. // 判断是否够highFreqSampleTimes,540s
  534. var lastPhr = freqCollection
  535. .OrderByDescending(i => i.LastUpdate)
  536. .Take(stopHighFreqSampleCount);
  537. // 最后一条高频心率
  538. var lastFreqHr = lastPhr.First();
  539. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)lastFreqHr.LastUpdate!, phrFreqstatus!.LastUpdate);
  540. if (ts < highFreqSampleTimes)
  541. {
  542. /// 不够10分钟最近12个数据的最小值生成胎心值
  543. _logger.LogInformation($"{heartRate.Serialno} 不够10分钟最近12个数据的最小值生成胎心值");
  544. heartRate.HeartRate = lastPhr.Select(i => i.PregnancyHeartRate).Min();
  545. heartRate.LastUpdate = lastFreqHr.LastUpdate;
  546. }
  547. _logger.LogInformation($"{heartRate.Serialno} 高频结束后的时间倒序的正常心率触发的高频心率处理");
  548. await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR, highFreqSampleTimes, upperAlarmThreshold, lowerAlarmThreshold, DateTimeUtil.ConvertToTimeStamp(phrFreqstatus!.LastUpdate).ToString(), phrFreqstatus!.LastUpdate, FreqStatsEnd);
  549. _logger.LogInformation($"{heartRate.Serialno} 高频数据个数{freqCollection.Count},触发高频开始时间{phrFreqstatus!.LastUpdate},时间倒叙");
  550. }
  551. else
  552. {
  553. _logger.LogInformation($"{heartRate.Serialno} 时间倒叙触发计算高频心率的数据不足{stopHighFreqSampleCount}条,不进行胎心计算");
  554. }
  555. #endregion
  556. }
  557. else
  558. {
  559. _logger.LogInformation($"{heartRate.Serialno} 高频持续时间不足{highFreqSampleTimes},只持续{(firstTwoPhr[1] - phrFreqstatus!.LastUpdate).TotalSeconds} 秒");
  560. }
  561. // 删除高频状态的首条记录
  562. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  563. // (逐条计算)计算本次常规心率的胎心数据(高频结束后,实时处理)
  564. //await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  565. await CalculateNormalFetalHeartRateScheduleAsync(heartRate);
  566. }
  567. // 删除高频状态的首条记录
  568. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  569. _logger.LogInformation($"{heartRate.Serialno} 超时结束高频心率状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval},高频状态持续{(firstTwoPhr[1] - phrFreqstatus!.LastUpdate).TotalSeconds} 秒");
  570. //// 使用延后计算
  571. //var fhrScheduleKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  572. //var fhrScheduleTTL = 60;
  573. //await SetIntervalTriggerAsync(fhrScheduleKey, heartRate.Serialno, fhrScheduleTTL, heartRate);
  574. }
  575. // 常规心率(本次心率可能是高频心率的首条,所以要使用延后计算胎心率)
  576. else
  577. {
  578. // 本次心率可能是高频心率的首条,所以要使用本次常规心率延后计算胎心率
  579. //var fhrScheduleKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  580. //var fhrScheduleTTL = 30;
  581. //await SetIntervalTriggerAsync(fhrScheduleKey, heartRate.Serialno, fhrScheduleTTL, heartRate);
  582. //_logger.LogInformation($"{heartRate.Serialno} 延时50秒,判断当前数据是否为高频首条");
  583. // 本次心率可能是高频心率的首条,所以要使用本次常规心率延后计算胎心率 查询30秒后是否有高频缓存
  584. Thread thread = new(async () =>
  585. {
  586. try
  587. {
  588. #region 休眠highFreqSampleInterval2秒
  589. var startTime = DateTime.Now;
  590. //var highFreqSampleInterval2 = (int)watchConfig!["highFreqSampleInterval"]!+5;
  591. var highFreqSampleInterval2 = highFreqSampleInterval;
  592. var during = TimeSpan.FromSeconds(highFreqSampleInterval2);
  593. while (true)
  594. {
  595. if (DateTime.Now - startTime > during)
  596. {
  597. break;
  598. }
  599. await Task.Delay(TimeSpan.FromSeconds(1));
  600. }
  601. #endregion
  602. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  603. _logger.LogInformation($"phrFreqstatus==null:{phrFreqstatus == null}");
  604. _logger.LogInformation($"phrFreqstatus.LastUpdate < heartRate.LastUpdate:{phrFreqstatus?.LastUpdate < heartRate.LastUpdate}");
  605. if (phrFreqstatus == null || phrFreqstatus.LastUpdate < heartRate.LastUpdate)
  606. {
  607. // (逐条计算)常规心率
  608. //await CalculateNormalFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, intervalFHR, commonPHR);
  609. //_logger.LogInformation($"{heartRate.Serialno} 计算常规心率");
  610. // 延时计算常规心率
  611. await CalculateNormalFetalHeartRateScheduleAsync(heartRate);
  612. }
  613. }
  614. catch (Exception ex)
  615. {
  616. _logger.LogError($"处理延时计算异常:{ex.Message}, {ex.StackTrace}");
  617. }
  618. });
  619. thread.Start();
  620. }
  621. }
  622. #endregion
  623. }
  624. else
  625. {
  626. _logger.LogInformation($"{heartRate.Serialno} 记录不足30条,建模中");
  627. }
  628. }
  629. }
  630. catch (Exception ex)
  631. {
  632. _logger.LogError($"{heartRate.Serialno} 处理孕妇心率数据异常 \n{ex.Message}\n{ex.StackTrace}");
  633. }
  634. }
  635. /// <summary>
  636. /// (逐条计算)常规心率计算胎心数据
  637. /// </summary>
  638. /// <param name="heartRate"></param>
  639. /// <param name="upperAlarmThreshold"></param>
  640. /// <param name="lowerAlarmThreshold"></param>
  641. /// <param name="intervalFHR"></param>
  642. /// <param name="commonPHR"></param>
  643. /// <returns></returns>
  644. /**
  645. private async Task CalculateNormalFetalHeartRateAsync(HisGpsHeartRate heartRate, int upperAlarmThreshold, int lowerAlarmThreshold, int intervalFHR, PregnancyCommonHeartRateModel? commonPHR)
  646. {
  647. // 上15分钟的数据
  648. // 获取当前时间
  649. DateTime nowInterval = (DateTime)heartRate.LastUpdate!;
  650. if (nowInterval.Second > 0)
  651. {
  652. nowInterval = nowInterval.AddMinutes(1);
  653. }
  654. // 计算last_update到上一间隔的分钟数
  655. int minutesToSubtract = nowInterval.Minute % intervalFHR;
  656. // 计算上一间隔的时间
  657. DateTime previousInterval = nowInterval.AddMinutes(-minutesToSubtract).AddSeconds(-nowInterval.Second).AddMilliseconds(-nowInterval.Millisecond);
  658. // 使用 last_update 上一刻
  659. var sampleTimeFHR = DateTimeUtil.ConvertToTimeStamp(previousInterval).ToString();
  660. // 计算last_update到下一间隔的分钟数
  661. int minutesToAdd = intervalFHR - (nowInterval.Minute % intervalFHR);
  662. if (minutesToAdd == intervalFHR)
  663. {
  664. minutesToAdd = 0; // 如果已经是间隔,则不需要增加分钟
  665. }
  666. // 计算下一间隔的时间
  667. DateTime nextInterval = nowInterval.AddMinutes(minutesToAdd)
  668. .AddSeconds(-nowInterval.Second)
  669. .AddMilliseconds(-nowInterval.Millisecond);
  670. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  671. var normalPhrStatStartTime = nextInterval.AddMinutes(-intervalFHR);
  672. var normalPhrStatEndTime = nextInterval;
  673. _logger.LogInformation($"{heartRate.Serialno} 计算胎心数据, 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} ");
  674. var filteredPhr = daysPhr
  675. // 使用 last_update 下一刻
  676. .Where(i => i.LastUpdate <= normalPhrStatEndTime && i.LastUpdate >= normalPhrStatStartTime)
  677. .ToList();
  678. if (filteredPhr.Count == 0)
  679. {
  680. _logger.LogWarning($"{heartRate.Serialno} 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} 孕妇心率数据不足,{filteredPhr.Count}条记录");
  681. return;
  682. }
  683. var phrValue = filteredPhr.Count == 1
  684. ? filteredPhr.First().PregnancyHeartRate
  685. : filteredPhr.Average(i => i.PregnancyHeartRate);
  686. //await SaveAndPushFreqFetalHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, phrValue, sampleTimeFHR);
  687. //await SaveAndPushFetalHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, phrValue, sampleTimeFHR, normalPhrStatStartTime, normalPhrStatEndTime);
  688. heartRate.HeartRate = (int)phrValue;
  689. //await SaveAndPushFetalHeartRateEndFreqHeartRateAsync(heartRate, commonPHR!, upperAlarmThreshold, lowerAlarmThreshold, sampleTimeFHR, normalPhrStatStartTime, normalPhrStatEndTime);
  690. }
  691. */
  692. /// <summary>
  693. /// 延时计算
  694. /// </summary>
  695. /// <param name="heartRate"></param>
  696. /// <returns></returns>
  697. public async Task CalculateNormalFetalHeartRateScheduleAsync(HisGpsHeartRate heartRate)
  698. {
  699. var fhrScheduleKey = $"health_monitor/schedule_push/cal_normalphr_fetal_heart_rate/imei/{heartRate.Serialno}";
  700. DateTime nowInterval = DateTime.Now;
  701. if (nowInterval.Second > 0)
  702. {
  703. nowInterval = nowInterval.AddMinutes(1);
  704. }
  705. // 需要减去的分钟
  706. int minutesToSubtract = nowInterval.Minute % INTERVAL_FHR;
  707. var nextRunTime=nowInterval
  708. .AddMinutes(-minutesToSubtract)
  709. .AddMinutes(INTERVAL_FHR);
  710. TimeSpan timeUntilNextRun = nextRunTime - nowInterval;
  711. var ttl = (long)timeUntilNextRun.TotalSeconds;
  712. await SetIntervalTriggerAsync(fhrScheduleKey, heartRate.Serialno, ttl, heartRate);
  713. }
  714. /// <summary>
  715. ///
  716. /// </summary>
  717. /// <param name="heartRate"></param>
  718. /// <param name="commonPHR"></param>
  719. /// <param name="upperAlarmThreshold"></param>
  720. /// <param name="lowerAlarmThreshold"></param>
  721. /// <param name="phrValue"></param>
  722. /// <param name="sampleTime"></param>
  723. /// <param name="statStartTime"></param>
  724. /// <param name="statEndTime"></param>
  725. /// <returns></returns>
  726. private async Task SaveAndPushFetalHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int upperAlarmThreshold, int lowerAlarmThreshold, double phrValue, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  727. {
  728. // 计算胎心=孕妇心率*系数
  729. /**
  730. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  731. fetalHeartRate = fetalHeartRate > 220 ? 220 : fetalHeartRate; // 胎心的最大值调整为220,超过都按该值220输出
  732. if (fetalHeartRate >= 220)
  733. {
  734. // 先使用最小系数计算
  735. var statMaxValueFprCoefficient = commonPHR?.StatMaxValueFprCoefficient!;
  736. var statMinValueFprCoefficient = commonPHR?.StatMinValueFprCoefficient!;
  737. var coefficient = statMaxValueFprCoefficient < statMinValueFprCoefficient ? statMaxValueFprCoefficient : statMinValueFprCoefficient;
  738. fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  739. if (fetalHeartRate < 220)
  740. {
  741. _logger.LogWarning($"{heartRate.Serialno} 使用极值系数 {coefficient} ,建模数据可能出现异常,请检查");
  742. }
  743. else
  744. {
  745. fetalHeartRate = 220;
  746. _logger.LogWarning($"{heartRate.Serialno} 使用所有系数都不能放映实际,建模数据可能出现异常,请检查");
  747. }
  748. }
  749. */
  750. #region 胎心系数使用基于心率与中位数对比
  751. var coefficient = 0f;
  752. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  753. if (heartRate.HeartRate < commonPHR!.Mode)
  754. {
  755. coefficient = commonPHR.StatMinValueFprCoefficient!;
  756. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  757. }
  758. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  759. else if (heartRate.HeartRate > commonPHR.Mode)
  760. {
  761. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  762. {
  763. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  764. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  765. }
  766. else
  767. {
  768. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  769. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  770. }
  771. }
  772. else
  773. {
  774. coefficient = commonPHR.StatModeAvgFprCoefficient;
  775. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  776. }
  777. #endregion
  778. var fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  779. // 胎心的最大值调整为220,超过都按该值220输出
  780. // fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  781. if (fetalHeartRate > 220)
  782. {
  783. fetalHeartRate = 220;
  784. _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")}");
  785. }
  786. // 胎心的最小值调整为90,超过都按该值90
  787. if (fetalHeartRate < 90)
  788. {
  789. fetalHeartRate = 90;
  790. _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")}");
  791. }
  792. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  793. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  794. if (phrFreqstatus == null) isAbnormal = 0;
  795. var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  796. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  797. //if (!isFreq)
  798. //{
  799. // statStartTime = heartRate.LastUpdate;
  800. //
  801. //}
  802. // 保存到 数据服务 MySQL 数据库
  803. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  804. {
  805. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  806. PersonId = commonPHR!.PersonId,
  807. Serialno = heartRate.Serialno,
  808. HeartRate = fetalHeartRate,
  809. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  810. IsAbnormal = isAbnormal,
  811. StatStartTime = statStartTime,
  812. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  813. CreateTime = DateTime.Now,
  814. Method = 1,
  815. IsDisplay = 1,
  816. DeviceKey = commonPHR!.DeviceKey
  817. };
  818. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  819. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  820. // 推送最后一条常规心率计算的胎心数据到iot设备
  821. #region 推送最后一条常规心率计算的胎心数据到iot设备
  822. // 高频(<=12)-常规
  823. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  824. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  825. {
  826. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  827. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  828. }
  829. // 高频(13)-常规-高频(13)
  830. if (phrFreqstatus != null)
  831. {
  832. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  833. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  834. // 获取高频数据
  835. var freqCollection = new List<PregnancyHeartRateModel>();
  836. PregnancyHeartRateModel? previousItem = null;
  837. foreach (var item in phr)
  838. {
  839. if (previousItem != null)
  840. {
  841. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  842. if (timeNextDiff <= 60)
  843. {
  844. freqCollection.Add(item);
  845. }
  846. }
  847. // 高频最后一条
  848. if (lastPhr.MessageId == item.MessageId)
  849. {
  850. freqCollection.Add(item);
  851. }
  852. previousItem = item;
  853. }
  854. //去除高频
  855. foreach (var item in freqCollection)
  856. {
  857. phr.Remove(item);
  858. }
  859. lastPhr = phr.FirstOrDefault();
  860. if (lastPhr?.MessageId == heartRate.MessageId)
  861. {
  862. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  863. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  864. }
  865. }
  866. #endregion
  867. #region 高频心率计算胎心数据到iot设备
  868. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  869. if (phrFreqstatus != null && isAbnormal!=0)
  870. {
  871. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  872. }
  873. #endregion
  874. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  875. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  876. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  877. // 胎心数据推送到第三方
  878. var topic = "topic.push.third";
  879. var fhrThridMsg = new
  880. {
  881. messageId = fhrMsgId,
  882. topic = topic,
  883. time = fhrMsgTime,
  884. data = new
  885. {
  886. imei = heartRate.Serialno,
  887. value = fetalHeartRate,
  888. isAbnormal,
  889. type = "fetalHeart"
  890. }
  891. };
  892. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  893. // 胎心数据推送到微信
  894. if (isAbnormal != 0)
  895. {
  896. topic = "topic.push.wx";
  897. var fhrMsg = new
  898. {
  899. messageId = fhrMsgId,
  900. topic = topic,
  901. time = fhrMsgTime,
  902. data = new
  903. {
  904. deviceId = device?.DeviceId,
  905. imei = heartRate.Serialno,
  906. alarmTypeId = 12,
  907. alarmDeviceName = heartRate.Serialno,
  908. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  909. address = string.Empty,
  910. deviceKey = device?.DeviceId
  911. }
  912. };
  913. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  914. }
  915. }
  916. private async Task SaveAndPushFetalHeartRateEndFreqHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int upperAlarmThreshold, int lowerAlarmThreshold, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  917. {
  918. // 计算胎心=孕妇心率*系数
  919. /**
  920. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  921. fetalHeartRate = fetalHeartRate > 220 ? 220 : fetalHeartRate; // 胎心的最大值调整为220,超过都按该值220输出
  922. if (fetalHeartRate >= 220)
  923. {
  924. // 先使用最小系数计算
  925. var statMaxValueFprCoefficient = commonPHR?.StatMaxValueFprCoefficient!;
  926. var statMinValueFprCoefficient = commonPHR?.StatMinValueFprCoefficient!;
  927. var coefficient = statMaxValueFprCoefficient < statMinValueFprCoefficient ? statMaxValueFprCoefficient : statMinValueFprCoefficient;
  928. fetalHeartRate = SafeType.SafeInt(phrValue * coefficient);
  929. if (fetalHeartRate < 220)
  930. {
  931. _logger.LogWarning($"{heartRate.Serialno} 使用极值系数 {coefficient} ,建模数据可能出现异常,请检查");
  932. }
  933. else
  934. {
  935. fetalHeartRate = 220;
  936. _logger.LogWarning($"{heartRate.Serialno} 使用所有系数都不能放映实际,建模数据可能出现异常,请检查");
  937. }
  938. }
  939. */
  940. #region 胎心系数使用基于心率与中位数对比
  941. var coefficient = 0f;
  942. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  943. if (heartRate.HeartRate < commonPHR!.Mode)
  944. {
  945. coefficient = commonPHR.StatMinValueFprCoefficient!;
  946. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  947. }
  948. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  949. else if (heartRate.HeartRate > commonPHR.Mode)
  950. {
  951. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  952. {
  953. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  954. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  955. }
  956. else
  957. {
  958. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  959. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  960. }
  961. }
  962. else
  963. {
  964. coefficient = commonPHR.StatModeAvgFprCoefficient;
  965. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  966. }
  967. #endregion
  968. var fetalHeartRate = SafeType.SafeInt(heartRate.HeartRate! * coefficient);
  969. // 胎心的最大值调整为220,超过都按该值220输出
  970. // fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  971. if (fetalHeartRate > 220)
  972. {
  973. fetalHeartRate = 220;
  974. _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")}");
  975. }
  976. // 胎心的最小值调整为90,超过都按该值90
  977. if (fetalHeartRate < 90)
  978. {
  979. fetalHeartRate = 90;
  980. _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")}");
  981. }
  982. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  983. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  984. if (phrFreqstatus == null) isAbnormal = 0;
  985. var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  986. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  987. //if (!isFreq)
  988. //{
  989. // statStartTime = heartRate.LastUpdate;
  990. //
  991. //}
  992. // 保存到 数据服务 MySQL 数据库
  993. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  994. {
  995. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  996. PersonId = commonPHR!.PersonId,
  997. Serialno = heartRate.Serialno,
  998. HeartRate = fetalHeartRate,
  999. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  1000. IsAbnormal = isAbnormal,
  1001. StatStartTime = statStartTime,
  1002. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  1003. CreateTime = DateTime.Now,
  1004. Method = 1,
  1005. IsDisplay = 1,
  1006. DeviceKey = commonPHR!.DeviceKey
  1007. };
  1008. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  1009. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  1010. // 推送最后一条常规心率计算的胎心数据到iot设备
  1011. #region 推送最后一条常规心率计算的胎心数据到iot设备
  1012. // 高频(<=12)-常规
  1013. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  1014. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  1015. {
  1016. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1017. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  1018. }
  1019. // 高频(13)-常规-高频(13)
  1020. if (phrFreqstatus != null)
  1021. {
  1022. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  1023. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1024. // 获取高频数据
  1025. var freqCollection = new List<PregnancyHeartRateModel>();
  1026. PregnancyHeartRateModel? previousItem = null;
  1027. foreach (var item in phr)
  1028. {
  1029. if (previousItem != null)
  1030. {
  1031. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1032. if (timeNextDiff <= 60)
  1033. {
  1034. freqCollection.Add(item);
  1035. }
  1036. }
  1037. // 高频最后一条
  1038. if (lastPhr.MessageId == item.MessageId)
  1039. {
  1040. freqCollection.Add(item);
  1041. }
  1042. previousItem = item;
  1043. }
  1044. //去除高频
  1045. foreach (var item in freqCollection)
  1046. {
  1047. phr.Remove(item);
  1048. }
  1049. lastPhr = phr.FirstOrDefault();
  1050. if (lastPhr?.MessageId == heartRate.MessageId)
  1051. {
  1052. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1053. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  1054. }
  1055. }
  1056. #endregion
  1057. #region 高频心率计算胎心数据到iot设备
  1058. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  1059. if (phrFreqstatus != null && isAbnormal != 0)
  1060. {
  1061. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1062. }
  1063. #endregion
  1064. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  1065. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  1066. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  1067. // 胎心数据推送到第三方
  1068. var topic = "topic.push.third";
  1069. var fhrThridMsg = new
  1070. {
  1071. messageId = fhrMsgId,
  1072. topic = topic,
  1073. time = fhrMsgTime,
  1074. data = new
  1075. {
  1076. imei = heartRate.Serialno,
  1077. value = fetalHeartRate,
  1078. isAbnormal,
  1079. type = "fetalHeart"
  1080. }
  1081. };
  1082. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  1083. // 胎心数据推送到微信
  1084. if (isAbnormal != 0)
  1085. {
  1086. topic = "topic.push.wx";
  1087. var fhrMsg = new
  1088. {
  1089. messageId = fhrMsgId,
  1090. topic = topic,
  1091. time = fhrMsgTime,
  1092. data = new
  1093. {
  1094. deviceId = device?.DeviceId,
  1095. imei = heartRate.Serialno,
  1096. alarmTypeId = 12,
  1097. alarmDeviceName = heartRate.Serialno,
  1098. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  1099. address = string.Empty,
  1100. deviceKey = device?.DeviceId
  1101. }
  1102. };
  1103. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  1104. }
  1105. }
  1106. /// <summary>
  1107. /// 高频胎心处理
  1108. /// 1. 高频数据触发连续12个值都是正常的的高频心率处理
  1109. /// 2. 高频结束后的highFreqSampleTimes=0的高频心率处理
  1110. /// 3. 高频结束后的在highFreqSampleTimes>0 正常心率触发的高频心率处理(常态)
  1111. /// 4. 高频结束后的时间倒序的正常心率触发的高频心率处理
  1112. /// 5. 高频结束后计算胎心数据,防止结束后与常规心理的胎心处理过长,定时器时长highFreqSampleInterval触发的高频心率处理
  1113. /// 高频结束后超过9分钟且不在阈值内才告警
  1114. /// </summary>
  1115. /// <param name="heartRate"></param>
  1116. /// <param name="commonPHR"></param>
  1117. /// <param name="highFreqSampleTimes"></param>
  1118. /// <param name="upperAlarmThreshold"></param>
  1119. /// <param name="lowerAlarmThreshold"></param>
  1120. /// <param name="sampleTime"></param>
  1121. /// <param name="statStartTime"></param>
  1122. /// <param name="statEndTime"></param>
  1123. /// <returns></returns>
  1124. private async Task SaveAndPushFetalHeartRateEndFreqHeartRateAsync(HisGpsHeartRate heartRate, PregnancyCommonHeartRateModel commonPHR, int highFreqSampleTimes, int upperAlarmThreshold, int lowerAlarmThreshold, string sampleTime, DateTime statStartTime, DateTime statEndTime)
  1125. {
  1126. // 计算胎心=孕妇心率*系数
  1127. #region 胎心系数使用基于心率与中位数对比
  1128. var coefficient = 0f;
  1129. // 孕妇心率少于中位数,取StatMinValueFprCoefficient
  1130. if (heartRate.HeartRate < commonPHR!.Mode)
  1131. {
  1132. coefficient = commonPHR.StatMinValueFprCoefficient!;
  1133. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率少于中位数,使用最小值系数 {coefficient}");
  1134. }
  1135. // 孕妇心率大于中位数,取StatMaxValueFprCoefficient与StatModeAvgFprCoefficient中少的那个
  1136. else if (heartRate.HeartRate > commonPHR.Mode)
  1137. {
  1138. if (commonPHR.StatModeAvgFprCoefficient > commonPHR.StatMaxValueFprCoefficient)
  1139. {
  1140. coefficient = commonPHR.StatMaxValueFprCoefficient!;
  1141. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用最大值系数 {coefficient}");
  1142. }
  1143. else
  1144. {
  1145. coefficient = commonPHR.StatModeAvgFprCoefficient!;
  1146. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率大于中位数,使用均值系数 {coefficient}");
  1147. }
  1148. }
  1149. else
  1150. {
  1151. coefficient = commonPHR.StatModeAvgFprCoefficient;
  1152. _logger.LogInformation($"{heartRate.Serialno} 孕妇心率等于中位数,使用均值系数 {coefficient}");
  1153. }
  1154. #endregion
  1155. var fetalHeartRate = SafeType.SafeInt(heartRate.HeartRate! * coefficient);
  1156. // 胎心的最大值调整为220,超过都按该值220输出
  1157. // fetalHeartRate = fetalHeartRate>= 220 ? 220 : fetalHeartRate;
  1158. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  1159. var isAbnormal = 0;
  1160. #region 判断是否够highFreqSampleTimes,540s
  1161. var ts = DateTimeUtil.GetTimeDifferenceInSeconds((DateTime)heartRate.LastUpdate!, phrFreqstatus!.LastUpdate);
  1162. // 判断是否够highFreqSampleTimes,540s
  1163. ///高频时长不足10分钟停止高频的胎心值生成说明:最近12个数据的最小值生成胎心值,
  1164. ///对于小于高频下限阀值取高频下限阀值进行转换;
  1165. ///对于高于高频上限阀值取高频上限阀值进行转换。并输出相关日志后续进行数据分析。
  1166. if (ts < highFreqSampleTimes)
  1167. {
  1168. if (fetalHeartRate > upperAlarmThreshold)
  1169. {
  1170. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,计算胎心值 {fetalHeartRate} 高于高频警告上限阀值{upperAlarmThreshold},最后胎心值{upperAlarmThreshold},并且不告警");
  1171. fetalHeartRate = upperAlarmThreshold;
  1172. }
  1173. else if (fetalHeartRate < lowerAlarmThreshold)
  1174. {
  1175. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,计算胎心值 {fetalHeartRate} 低于高频警告下限阀值 {lowerAlarmThreshold},最后胎心值{lowerAlarmThreshold},并且不告警");
  1176. fetalHeartRate = lowerAlarmThreshold;
  1177. }
  1178. else
  1179. {
  1180. _logger.LogWarning($"{heartRate.Serialno} 高频持续不足10分钟,在高频警告下限阀值 {lowerAlarmThreshold} 和 高频警告上限阀值:{upperAlarmThreshold}之间,最后胎心值{fetalHeartRate},并且不告警");
  1181. }
  1182. }
  1183. // 超过highFreqSampleTimes,540s
  1184. else
  1185. {
  1186. if (fetalHeartRate > 220)
  1187. {
  1188. fetalHeartRate = 220;
  1189. _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")}");
  1190. }
  1191. // 胎心的最小值调整为90,超过都按该值90
  1192. if (fetalHeartRate < 90)
  1193. {
  1194. fetalHeartRate = 90;
  1195. _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")}");
  1196. }
  1197. isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  1198. }
  1199. #endregion
  1200. //if (phrFreqstatus == null) isAbnormal = 0;
  1201. //var statsusDesc = (phrFreqstatus == null) ? "常规" : "高频";
  1202. var statsusDesc = "高频";
  1203. _logger.LogInformation($"{heartRate.Serialno} 在 {statsusDesc} 状态,生成胎心值:{fetalHeartRate},统计周期:{statStartTime.ToString("yyyy-MM-dd HH:mm:ss")}----{statEndTime.ToString("yyyy-MM-dd HH:mm:ss")}");
  1204. // 保存到 数据服务 MySQL 数据库
  1205. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  1206. {
  1207. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  1208. PersonId = commonPHR!.PersonId,
  1209. Serialno = heartRate.Serialno,
  1210. HeartRate = fetalHeartRate,
  1211. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  1212. IsAbnormal = isAbnormal,
  1213. StatStartTime = statStartTime,
  1214. StatEndTime = statEndTime,//commonPHR.StatEndTime,
  1215. CreateTime = DateTime.Now,
  1216. Method = 1,
  1217. IsDisplay = 1,
  1218. DeviceKey = commonPHR!.DeviceKey
  1219. };
  1220. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  1221. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  1222. // 推送最后一条常规心率计算的胎心数据到iot设备
  1223. #region 推送最后一条常规心率计算的胎心数据到iot设备
  1224. // 高频(<=12)-常规
  1225. var lastPhr = await _serviceTDengine.GetLastAsync<PregnancyHeartRateModel>(heartRate.Serialno);
  1226. if (lastPhr.MessageId == heartRate.MessageId && phrFreqstatus == null)
  1227. {
  1228. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1229. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(<=12)-常规");
  1230. }
  1231. // 高频(13)-常规-高频(13)
  1232. if (phrFreqstatus != null)
  1233. {
  1234. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 1);
  1235. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1236. // 获取高频数据
  1237. var freqCollection = new List<PregnancyHeartRateModel>();
  1238. PregnancyHeartRateModel? previousItem = null;
  1239. foreach (var item in phr)
  1240. {
  1241. if (previousItem != null)
  1242. {
  1243. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1244. if (timeNextDiff <= 60)
  1245. {
  1246. freqCollection.Add(item);
  1247. }
  1248. }
  1249. // 高频最后一条
  1250. if (lastPhr.MessageId == item.MessageId)
  1251. {
  1252. freqCollection.Add(item);
  1253. }
  1254. previousItem = item;
  1255. }
  1256. //去除高频
  1257. foreach (var item in freqCollection)
  1258. {
  1259. phr.Remove(item);
  1260. }
  1261. lastPhr = phr.FirstOrDefault();
  1262. if (lastPhr?.MessageId == heartRate.MessageId)
  1263. {
  1264. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1265. _logger.LogInformation($"{heartRate.Serialno} 推送最后一条常规心率计算的胎心数据到iot设备,高频(13)-常规-高频(13)");
  1266. }
  1267. }
  1268. #endregion
  1269. #region 高频心率计算胎心数据到iot设备
  1270. // 高频(17) ,连续12个高频正常,也不停止且数据偏高和偏低也推送到iot
  1271. if (phrFreqstatus != null && isAbnormal != 0)
  1272. {
  1273. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  1274. }
  1275. #endregion
  1276. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  1277. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  1278. var fhrMsgTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss");
  1279. // 胎心数据推送到第三方
  1280. var topic = "topic.push.third";
  1281. var fhrThridMsg = new
  1282. {
  1283. messageId = fhrMsgId,
  1284. topic = topic,
  1285. time = fhrMsgTime,
  1286. data = new
  1287. {
  1288. imei = heartRate.Serialno,
  1289. value = fetalHeartRate,
  1290. isAbnormal,
  1291. type = "fetalHeart"
  1292. }
  1293. };
  1294. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, 31, fhrThridMsg).ConfigureAwait(false);
  1295. // 胎心数据推送到微信
  1296. if (isAbnormal != 0)
  1297. {
  1298. topic = "topic.push.wx";
  1299. var fhrMsg = new
  1300. {
  1301. messageId = fhrMsgId,
  1302. topic = topic,
  1303. time = fhrMsgTime,
  1304. data = new
  1305. {
  1306. deviceId = device?.DeviceId,
  1307. imei = heartRate.Serialno,
  1308. alarmTypeId = 12,
  1309. alarmDeviceName = heartRate.Serialno,
  1310. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  1311. address = string.Empty,
  1312. deviceKey = device?.DeviceId
  1313. }
  1314. };
  1315. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  1316. }
  1317. }
  1318. private async Task SetIntervalTriggerAsync(string key, string imei, long interval, HisGpsHeartRate heartRate)
  1319. {
  1320. // var key = $"health_monitor/schedule_push/{type}/imei/{imei}";
  1321. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  1322. if (string.IsNullOrWhiteSpace(schedulePush))
  1323. {
  1324. var now = DateTime.Now;
  1325. var timeNextRun = now.Add(TimeSpan.FromSeconds(interval));
  1326. var data = new
  1327. {
  1328. imei,
  1329. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1330. ttl = interval,
  1331. next_run_time = timeNextRun.ToString("yyyy-MM-dd HH:mm:ss"),
  1332. trigger = heartRate,
  1333. };
  1334. var result = JsonConvert.SerializeObject(data);
  1335. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  1336. }
  1337. }
  1338. /// <summary>
  1339. /// 高频延时计算触发器
  1340. /// </summary>
  1341. /// <param name="key">键</param>
  1342. /// <param name="imei">IMEI</param>
  1343. /// <param name="interval">高频采集间隔</param>
  1344. /// <param name="heartRate">首条高频心率</param>
  1345. /// <returns></returns>
  1346. private async Task SetFreqHeartRateTriggerAsync(string key, string imei, long interval, HisGpsHeartRate? heartRate=null)
  1347. {
  1348. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  1349. if (string.IsNullOrWhiteSpace(schedulePush))
  1350. {
  1351. var now = DateTime.Now;
  1352. var data = new
  1353. {
  1354. imei,
  1355. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  1356. lease = interval,
  1357. trigger = heartRate,
  1358. };
  1359. var result = JsonConvert.SerializeObject(data);
  1360. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  1361. _logger.LogInformation($"{imei} 心率高频状态创建首条高频心率的触发记录,创建高频延时计算触发器");
  1362. }
  1363. else
  1364. {
  1365. // 不断修改时长,直到最后的一条高频胎心
  1366. await _serviceEtcd.PutValAsync(key, schedulePush, interval, false).ConfigureAwait(false);
  1367. _logger.LogInformation($"{imei} 心率高频状态续租");
  1368. }
  1369. }
  1370. /// <summary>
  1371. /// 去除高频数据
  1372. /// </summary>
  1373. /// <param name="phr"></param>
  1374. /// <param name="highFreqSampleInterva"></param>
  1375. /// <returns></returns>
  1376. private static List<PregnancyHeartRateModel> GetNonFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr,int highFreqSampleInterval)
  1377. {
  1378. //phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1379. //var result = new List<PregnancyHeartRateModel>();
  1380. //PregnancyHeartRateModel? previousItem = null;
  1381. //foreach (var item in phr)
  1382. //{
  1383. // if (previousItem != null)
  1384. // {
  1385. // var timeNextDiff =(previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1386. // if (timeNextDiff > highFreqSampleInterval)
  1387. // {
  1388. // result.Add(previousItem);
  1389. // }
  1390. // }
  1391. // previousItem = item;
  1392. //}
  1393. //// 添加上一个
  1394. //if (previousItem != null)
  1395. //{
  1396. // result.Add(previousItem);
  1397. //}
  1398. //return result;
  1399. #region 反向
  1400. var phr1 = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1401. var result = new List<PregnancyHeartRateModel>();
  1402. PregnancyHeartRateModel? previousItem1 = null;
  1403. foreach (var item in phr1)
  1404. {
  1405. if (previousItem1 != null)
  1406. {
  1407. var timeNextDiff = (previousItem1!.LastUpdate - item.LastUpdate).TotalSeconds;
  1408. if (timeNextDiff > highFreqSampleInterval)
  1409. {
  1410. result.Add(previousItem1);
  1411. }
  1412. }
  1413. previousItem1 = item;
  1414. }
  1415. // 添加上一个
  1416. if (previousItem1 != null)
  1417. {
  1418. result.Add(previousItem1);
  1419. }
  1420. #endregion
  1421. #region 正向
  1422. var phr2 = phr.OrderByDescending(i => i.LastUpdate).ToList(); ;
  1423. var freqCollection = new List<PregnancyHeartRateModel>();
  1424. PregnancyHeartRateModel? previousItem = null;
  1425. foreach (var item in phr2)
  1426. {
  1427. if (previousItem != null)
  1428. {
  1429. var timeNextDiff = (previousItem!.LastUpdate - item.LastUpdate).TotalSeconds;
  1430. if (timeNextDiff <= highFreqSampleInterval)
  1431. {
  1432. freqCollection.Add(item);
  1433. }
  1434. }
  1435. previousItem = item;
  1436. }
  1437. //去除高频
  1438. foreach (var item in freqCollection)
  1439. {
  1440. phr2.Remove(item);
  1441. }
  1442. #endregion
  1443. // 交集
  1444. var commonElements = phr2.Intersect(result).ToList();
  1445. return commonElements;
  1446. }
  1447. /// <summary>
  1448. /// 获取高频数据
  1449. /// </summary>
  1450. /// <param name="phr"></param>
  1451. /// <param name="highFreqSampleInterval"></param>
  1452. /// <returns></returns>
  1453. private static List<PregnancyHeartRateModel> GetFreqPregnancyHeartRate(List<PregnancyHeartRateModel> phr, int highFreqSampleInterval)
  1454. {
  1455. phr = phr.OrderByDescending(i => i.LastUpdate).ToList();
  1456. var freqCollection = new List<PregnancyHeartRateModel>();
  1457. PregnancyHeartRateModel? previousItem = null;
  1458. foreach (var item in phr)
  1459. {
  1460. if (previousItem != null)
  1461. {
  1462. var timeNextDiff = (previousItem.LastUpdate - item.LastUpdate).TotalSeconds;
  1463. if (timeNextDiff <= highFreqSampleInterval)
  1464. {
  1465. freqCollection.Add(previousItem);
  1466. }
  1467. }
  1468. previousItem = item;
  1469. }
  1470. // 检查最后一条是否高频
  1471. if (previousItem != null && (phr.Last().LastUpdate - previousItem.LastUpdate).TotalSeconds <= highFreqSampleInterval)
  1472. {
  1473. freqCollection.Add(previousItem);
  1474. }
  1475. return freqCollection;
  1476. }
  1477. }
  1478. }