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.

PregnancyHeartRateResolver.cs 61KB

3 months ago
4 months ago
4 months ago
3 months ago
4 months ago
4 months ago
3 months ago
3 months ago
4 months ago
3 months ago
4 months ago
3 months ago
4 months ago
3 months ago
4 months ago
4 months ago
3 months ago
3 months ago
3 months ago
4 months ago
3 months ago
3 months ago
4 months ago
3 months ago
3 months ago
4 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
3 months ago
4 months ago
4 months ago
4 months ago
4 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
4 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. using Etcdserverpb;
  2. using HealthMonitor.Common;
  3. using HealthMonitor.Common.helper;
  4. using HealthMonitor.Model.Service.Mapper;
  5. using HealthMonitor.Service.Biz;
  6. using HealthMonitor.Service.Biz.db;
  7. using HealthMonitor.Service.Cache;
  8. using HealthMonitor.Service.Etcd;
  9. using HealthMonitor.Service.MessageQueue;
  10. using HealthMonitor.Service.Resolver.Interface;
  11. using HealthMonitor.Service.Sub;
  12. using HealthMonitor.Service.Sub.Topic.Model;
  13. using Microsoft.EntityFrameworkCore.Metadata;
  14. using Microsoft.Extensions.Logging;
  15. using Newtonsoft.Json;
  16. using Newtonsoft.Json.Linq;
  17. using SqlSugar;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Linq;
  21. using System.Net;
  22. using System.Text;
  23. using System.Threading.Tasks;
  24. using TelpoDataService.Util.Clients;
  25. using TelpoDataService.Util.Entities.GpsCard;
  26. using TelpoDataService.Util.Entities.GpsLocationHistory;
  27. using TelpoDataService.Util.Models;
  28. using TelpoDataService.Util.QueryObjects;
  29. namespace HealthMonitor.Service.Resolver
  30. {
  31. public class PregnancyHeartRateResolver : IResolver
  32. {
  33. private readonly ILogger<PregnancyHeartRateResolver> _logger;
  34. private readonly TDengineService _serviceTDengine;
  35. private readonly DeviceCacheManager _deviceCacheMgr;
  36. private readonly IotApiService _serviceIotApi;
  37. private readonly AsyncLocal<string> _messageId = new();
  38. private readonly AsyncLocal<HisGpsHeartRate> _msgData = new();
  39. private readonly HttpHelper _httpHelper = default!;
  40. private readonly EtcdService _serviceEtcd;
  41. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> _hisFetalHeartApiClient;
  42. private readonly GpsLocationHistoryAccessorClient<HisGpsFetalMovement> _hisFetalMovementApiClient;
  43. private readonly FetalMovementNormalValueRangeCacheManager _mgrFetalMovementNormalValueRangeCache;
  44. private readonly MqProcessLogic _serviceMqProcess;
  45. public PregnancyHeartRateResolver(ILogger<PregnancyHeartRateResolver> logger,
  46. HttpHelper httpHelper, EtcdService serviceEtcd, DeviceCacheManager deviceCacheMgr,
  47. MqProcessLogic serviceMqProcess,
  48. IotApiService iotApiService, TDengineService serviceDengine, FetalMovementNormalValueRangeCacheManager fetalMovementNormalValueRangeCacheMgr,
  49. GpsLocationHistoryAccessorClient<HisGpsFetalHeartRate> hisFetalHeartApiClient,
  50. GpsLocationHistoryAccessorClient<HisGpsFetalMovement> hisFetalMovementApiClient
  51. )
  52. {
  53. _logger = logger;
  54. _httpHelper = httpHelper;
  55. _serviceEtcd = serviceEtcd;
  56. _serviceTDengine = serviceDengine;
  57. _deviceCacheMgr = deviceCacheMgr;
  58. _serviceIotApi = iotApiService;
  59. _serviceMqProcess= serviceMqProcess;
  60. _hisFetalHeartApiClient = hisFetalHeartApiClient;
  61. _hisFetalMovementApiClient = hisFetalMovementApiClient;
  62. _mgrFetalMovementNormalValueRangeCache = fetalMovementNormalValueRangeCacheMgr;
  63. }
  64. public void SetResolveInfo(PackageMsgModel msg)
  65. {
  66. var topicHmPregnancyHeartRate = JsonConvert.DeserializeObject<TopicHmPregnancyHeartRate>(msg.DetailData.ToString()!);
  67. _messageId.Value = msg.MessageId;
  68. _msgData.Value = new HisGpsHeartRate()
  69. {
  70. HeartRateId = topicHmPregnancyHeartRate!.PregnancyHeartRateId,
  71. MessageId = topicHmPregnancyHeartRate!.MessageId,
  72. Serialno = topicHmPregnancyHeartRate!.Serialno,
  73. HeartRate= topicHmPregnancyHeartRate.PregnancyHeartRate,
  74. LastUpdate = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmPregnancyHeartRate.LastUpdate) / 1000000),
  75. CreateTime = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmPregnancyHeartRate.CreateTime) / 1000000),
  76. Method = topicHmPregnancyHeartRate!.Method,
  77. IsDisplay = topicHmPregnancyHeartRate!.IsDisplay ? 1 : 0
  78. };
  79. }
  80. public override string ToString()
  81. {
  82. return $"{nameof(PregnancyHeartRateResolver)}[{_messageId.Value}]";
  83. }
  84. public async Task ExecuteMessageAsync()
  85. {
  86. var messageId = _messageId.Value;
  87. var heartRate = _msgData.Value!;
  88. var watchConfig = await _deviceCacheMgr.GetGpsDeviceWatchConfigCacheObjectBySerialNoAsync(heartRate.Serialno, "0067");
  89. var isFetalHeartEnable = watchConfig != null && (int)watchConfig["enabled"]! == 1;
  90. if (isFetalHeartEnable)
  91. {
  92. // 高频心率采样间隔
  93. var highFreqSampleInterval = (int)watchConfig!["highFreqSampleInterval"]!;
  94. // 触发高频监测的心率上限值
  95. var triggerHighFreqHigh = (int)watchConfig["triggerHighFreqHigh"]!;
  96. // 触发高频监测的心率下限值
  97. var triggerHighFreqLow = (int)watchConfig["triggerHighFreqLow"]!;
  98. //停止高频心率采样心率连续正常次数
  99. var stopHighFreqSampleCount = (int)watchConfig["stopHighFreqSampleCount"]!;
  100. // 高频心率采集时长 0 为持续采集,非零为高频心率的采集时长
  101. var highFreqSampleTimes = (int)watchConfig["stopHighFreqSampleCount"]!;
  102. // 告警上限阀值
  103. var upperAlarmThreshold = (int)watchConfig["upperAlarmThreshold"]!;
  104. // 告警下限阀值
  105. var lowerAlarmThreshold = (int)watchConfig["lowerAlarmThreshold"]!;
  106. // EDOC
  107. var edoc = DateTimeUtil.ToDateTime(watchConfig!["EDOC"]!.ToString());
  108. // interval (分钟)
  109. var intervalFHR= (int)watchConfig["interval"]!;
  110. var fetalHeartRateIsAbnormal = 0;
  111. var phr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  112. if (phr.Count >= 30)
  113. {
  114. /**
  115. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(heartRate.Serialno);
  116. if (commonPHR != null)
  117. {
  118. var lastUpdateNow = (DateTime)heartRate.LastUpdate!;
  119. var midNight = new DateTime(lastUpdateNow.Year, lastUpdateNow.Month, lastUpdateNow.Day, 0, 0, 0);
  120. #region 计算胎心数据
  121. _logger.LogInformation($"{heartRate.Serialno} 计算胎心数据 ");
  122. var fhrNow = lastUpdateNow;
  123. TimeSpan fhrTS = fhrNow - midNight;
  124. // 当天每隔intervalFHR 分钟的段数,取整数部分
  125. int segmentCountFHR = (int)(fhrTS.TotalMinutes / intervalFHR);
  126. for (int i = 0; i < segmentCountFHR; i++)
  127. {
  128. // 每intervalFHR * i分钟
  129. var fhrSampleTime = DateTimeUtil.ConvertToTimeStamp(midNight.AddMinutes(intervalFHR * i)).ToString()[..10];
  130. // 统计开始时间
  131. var statStartTimeFHR = midNight.AddMinutes(intervalFHR * i);
  132. // 统计结束时间
  133. var statEndTimeFHR = midNight.AddMinutes(intervalFHR * (i + 1));
  134. var isFHRExisted =await _mgrFetalHeartRateCache.FetalHeartRateIsExistedAsync(heartRate.Serialno, fhrSampleTime);
  135. _logger.LogInformation($"{heartRate.Serialno} 胎心数据采样时间:{fhrSampleTime}|{midNight.AddMinutes(intervalFHR * i).ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTimeFHR}-{statEndTimeFHR},isFHRExisted:{isFHRExisted} ");
  136. if (!isFHRExisted)
  137. {
  138. // 开始计算 ,每intervalFHR分钟计算一个
  139. var phrRange = phr.Where(i => i.LastUpdate >= statStartTimeFHR && i.LastUpdate <= statEndTimeFHR)
  140. .OrderByDescending(i => i.LastUpdate)
  141. .ToList();
  142. // 胎心数据每intervalFHR分钟计算1个值,采集的数据多于1个取平均值再*胎心系数。
  143. var phrValue = phrRange.Count == 1
  144. ? phrRange.First().PregnancyHeartRate
  145. : phrRange.Average(i => i.PregnancyHeartRate);
  146. // 当天的系数,没有的就实时计算
  147. var fprCoefficient = 0f;
  148. //if (commonPHR.CreateTime.Year == lastUpdateNow.Year &&
  149. // commonPHR.CreateTime.Month == lastUpdateNow.Month &&
  150. // commonPHR.CreateTime.Day == lastUpdateNow.Day
  151. // )
  152. //{
  153. // fprCoefficient = (float)commonPHR?.StatModeAvgFprCoefficient!;
  154. //}
  155. //else
  156. //{
  157. // //var daysDiff = 7 - (DateTime.Now.Day - lastUpdateNow.Day);
  158. // //var realtimePCHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(heartRate.Serialno, daysDiff);
  159. // //fprCoefficient = realtimePCHR!.StatModeAvgFprCoefficient;
  160. // var pchr = await _serviceTDengine.GetBySerialNoAsync<PregnancyCommonHeartRateModel>(heartRate.Serialno);
  161. // var dayPCHR = pchr.Where(i => i.CreateTime.Year == lastUpdateNow.Year && i.CreateTime.Month == lastUpdateNow.Month && i.CreateTime.Day == i.CreateTime.Day);
  162. // fprCoefficient=dayPCHR.First().StatModeAvgFprCoefficient;
  163. //}
  164. fprCoefficient = (float)commonPHR?.StatModeAvgFprCoefficient!;
  165. var fetalHeartRate = SafeType.SafeInt(phrValue * fprCoefficient);
  166. var fetalHeartRateIsAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  167. fetalHeartRateIsAbnormal = 0;// 不是高频数据,按正常值
  168. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  169. {
  170. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  171. PersonId = commonPHR!.PersonId,
  172. Serialno = heartRate.Serialno,
  173. HeartRate = fetalHeartRate,
  174. SampleTime = fhrSampleTime.Length > 10 ? fhrSampleTime.Substring(0, 10) : fhrSampleTime,
  175. IsAbnormal = fetalHeartRateIsAbnormal,
  176. StatStartTime = phrRange.OrderBy(i => i.LastUpdate).First().LastUpdate,
  177. StatEndTime = phrRange.OrderBy(i => i.LastUpdate).Last().LastUpdate,
  178. CreateTime = DateTime.Now,
  179. Method = 1,
  180. IsDisplay = 1,
  181. DeviceKey = commonPHR!.DeviceKey
  182. };
  183. // 保存到 数据服务 MySQL 数据库
  184. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  185. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  186. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, fhrSampleTime, fetalHeartRateIsAbnormal);
  187. // 推送到微信
  188. // 设置入库缓存记录
  189. await _mgrFetalHeartRateCache.SetFetalHeartRateAsync(heartRate.Serialno, fhrSampleTime);
  190. }
  191. }
  192. #endregion
  193. #region 计算胎动数据
  194. _logger.LogInformation($"{heartRate.Serialno} 计算胎动数据 ");
  195. var fmNow = lastUpdateNow;
  196. TimeSpan fmTS = fmNow - midNight;
  197. // 当天每隔2小时的段数,取整数部分
  198. int segmentCountFM = (int)(fmTS.TotalHours / 2);
  199. for (int i = 0; i < segmentCountFM; i++)
  200. {
  201. // 每两小时
  202. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(midNight.AddHours(2 * i)).ToString()[..10];
  203. // 统计开始时间
  204. var statStartTime = midNight.AddHours(2 * i);
  205. // 统计结束时间
  206. var statEndTime = midNight.AddHours(2 * (i + 1));
  207. //var isFetalMovementExist = await _hisFetalMovementApiClient.GetFirstAsync(param, heartRate.Serialno[^2..], null, new RequestHeader { RequestId = Guid.NewGuid().ToString("D") });
  208. var isFetalMovementExisted = await _mgrFetalMovement.FetalMovementIsExistedAsync(heartRate.Serialno, fetalMovementSampleTime);
  209. if (!isFetalMovementExisted)
  210. {
  211. /// 开始计算
  212. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate <= statEndTime)
  213. .OrderByDescending(i => i.LastUpdate)
  214. .Select(i => i.LastUpdate)
  215. .ToList();
  216. if (phrRange.Count >= 2)
  217. {
  218. var duringMins = Math.Abs((phrRange.First() - statStartTime).TotalMinutes);
  219. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  220. bool isInTimeRanges = IsLastUpdateInTimeRanges(fmNow);
  221. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  222. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  223. {
  224. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  225. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  226. .Where(i =>
  227. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  228. i.PregnancyPeriod[1] >= pregnancyWeeks)
  229. .Select(i => i.MedianMovement)
  230. .FirstOrDefault()
  231. :
  232. fetalMovementMap
  233. .Where(i =>
  234. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  235. i.PregnancyPeriod[1] >= pregnancyWeeks)
  236. .Select(i => i.InitialMovement)
  237. .FirstOrDefault()
  238. ;
  239. var fetalMovementValue = (fetalMovementMapValue * duringMins * 2) / 120;
  240. // 四舍五入
  241. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  242. // _logger.LogInformation($"{heartRate.Serialno} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");
  243. _logger.LogInformation($"{heartRate.Serialno} 胎动数据采样时间:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 原始胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{statStartTime}-{phrRange.First()}, 胎动计算值:{fetalMovementValue}, 胎动最终值:{fetalMovement}");
  244. // 获取胎心数据状态与胎动数据状态一致
  245. //var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  246. var feltalMovementIsAbnormal = 0;
  247. // 推送到api/v1/open/OpenIot/SetFetalMovementConfig
  248. await _serviceIotApi.SetFetalMovementConfig(heartRate.Serialno, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  249. // 保存到MySQL数据库
  250. HisGpsFetalMovement fm = new()
  251. {
  252. FetalMovementId = Guid.NewGuid().ToString("D"),
  253. PersonId = commonPHR!.PersonId,
  254. Serialno = heartRate.Serialno,
  255. CreateTime = DateTime.Now,
  256. IsAbnormal = feltalMovementIsAbnormal,
  257. FetalMovementValue = fetalMovement,
  258. SampleTime = fetalMovementSampleTime,
  259. Method = 1,
  260. IsDisplay = 1,
  261. DeviceKey = commonPHR!.DeviceKey
  262. };
  263. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  264. // 设置入库缓存记录
  265. await _mgrFetalMovement.SetFetalMovementAsync(heartRate.Serialno, fetalMovementSampleTime);
  266. }
  267. }
  268. }
  269. }
  270. #endregion
  271. }
  272. */
  273. #region 高频心率计算
  274. //// 获取最近的两个记录,并计算它们的 LastUpdate 时间差
  275. //var firstTwoPhr = phr.OrderByDescending(i => i.LastUpdate).Take(2).Select(i => i.LastUpdate).ToList();
  276. //var timeDiff = firstTwoPhr[0] - firstTwoPhr[1];
  277. //// 如果需要,将时间差转换为秒
  278. //var timeDiffInSeconds = timeDiff.TotalSeconds;
  279. //// 高频心率启动
  280. //if (timeDiffInSeconds<=highFreqSampleInterval)
  281. //{
  282. // var phrFreqstatus =await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  283. // if (phrFreqstatus == null)
  284. // {
  285. // /// 设置高频状态
  286. // _logger.LogInformation($"进入高频心率启动状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval}");
  287. // // 设置高频状态
  288. // var freqFirstPhr= phr.OrderByDescending(i => i.Timestamp).First();
  289. // await _deviceCacheMgr.SetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno, freqFirstPhr);
  290. // phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  291. // }
  292. // /// phr PregnancyHeartRate 连续连续正常次数个值都是正常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  293. // /// 取连续正常次数正常值的平均值,推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  294. // #region 检查是否连续12个值都是正常的
  295. // // 获取最近连续正常次数个心率记录
  296. // var lastPhr = phr.OrderByDescending(i => i.Timestamp).Take(stopHighFreqSampleCount).ToList();
  297. // // 检查是否连续12个值都是正常的
  298. // if (lastPhr.All(i => i.PregnancyHeartRate >= triggerHighFreqLow && i.PregnancyHeartRate <= triggerHighFreqHigh))
  299. // {
  300. // var avgPhr = lastPhr.Select(i => i.PregnancyHeartRate).Average();
  301. // // 计算一般心率得到胎心系数
  302. // await SaveAndPushFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr);
  303. // }
  304. // #endregion
  305. //}
  306. //// 高频心率结束
  307. //else
  308. //{
  309. // var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  310. // if (phrFreqstatus != null)
  311. // {
  312. // /// 在highFreqSampleTimes=0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  313. // /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  314. // if (highFreqSampleTimes==0)
  315. // {
  316. // // if (phr.OrderByDescending(i => i.Timestamp)
  317. // //.Where(i => i.Timestamp >= phrFreqstatus?.Timestamp)
  318. // //.Skip(1) // 去除首条
  319. // //.All(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHig))
  320. // // {
  321. // // var avgPhr = phr.Select(i => i.PregnancyHeartRate).Average();
  322. // // // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  323. // // // 计算一般心率得到胎心系数
  324. // // }
  325. // var avgPhr = phr.OrderByDescending(i => i.Timestamp)
  326. // .Where(i => i.Timestamp >= phrFreqstatus?.Timestamp)
  327. // .Skip(1) // 去除首条
  328. // .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh)
  329. // .Select(i => i.PregnancyHeartRate).Average();
  330. // // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  331. // // 计算一般心率得到胎心系数
  332. // await SaveAndPushFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr);
  333. // }
  334. // /// 在highFreqSampleTimes>0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  335. // /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  336. // if (highFreqSampleTimes > 0 && heartRate.LastUpdate >= (phrFreqstatus?.LastUpdate + TimeSpan.FromSeconds(highFreqSampleTimes)))
  337. // {
  338. // var avgPhr = phr
  339. // .Where(i => i.Timestamp >= phrFreqstatus?.Timestamp)
  340. // .Skip(1) // 去除首条
  341. // .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh)
  342. // .Select(i => i.PregnancyHeartRate).Average();
  343. // // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  344. // // 计算一般心率得到胎心系数
  345. // await SaveAndPushFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr);
  346. // }
  347. // // 删除高频状态的首条记录
  348. // await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  349. // /// 设置高频状态
  350. // _logger.LogInformation($"结束高频心率状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval}");
  351. // }
  352. //}
  353. #endregion
  354. #region 计算胎心和胎动数据
  355. var commonPHR = await _serviceTDengine.GetLastAsync<PregnancyCommonHeartRateModel>(heartRate.Serialno);
  356. if (commonPHR != null)
  357. {
  358. #region 计算胎心数据
  359. // 获取最近的两个记录,并计算它们的 LastUpdate 时间差
  360. var firstTwoPhr = phr.OrderByDescending(i => i.LastUpdate).Take(2).Select(i => i.LastUpdate).ToList();
  361. var timeDiff = firstTwoPhr[0] - firstTwoPhr[1];
  362. // 如果需要,将时间差转换为秒
  363. var timeDiffInSeconds = timeDiff.TotalSeconds;
  364. // 高频心率启动
  365. if (timeDiffInSeconds <= highFreqSampleInterval)
  366. {
  367. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  368. if (phrFreqstatus == null)
  369. {
  370. /// 设置高频状态
  371. _logger.LogInformation($"进入高频心率启动状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval}");
  372. // 设置高频状态
  373. var freqFirstPhr = phr.OrderByDescending(i => i.Timestamp).First();
  374. await _deviceCacheMgr.SetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno, freqFirstPhr);
  375. //phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  376. }
  377. /// phr PregnancyHeartRate 连续连续正常次数个值都是正常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  378. /// 取连续正常次数正常值的平均值,推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  379. #region 检查是否连续12个值都是正常的
  380. // 获取最近连续正常次数个心率记录
  381. var lastPhr = phr.OrderByDescending(i => i.Timestamp).Take(stopHighFreqSampleCount).ToList();
  382. // 检查是否连续12个值都是正常的
  383. if (lastPhr.All(i => i.PregnancyHeartRate >= triggerHighFreqLow && i.PregnancyHeartRate <= triggerHighFreqHigh))
  384. {
  385. var avgPhr = lastPhr.Select(i => i.PregnancyHeartRate).Average();
  386. // 计算一般心率得到胎心系数
  387. await SaveAndPushFreqFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(DateTime.Now).ToString());
  388. }
  389. #endregion
  390. }
  391. // 高频心率结束或正常心率
  392. else
  393. {
  394. var phrFreqstatus = await _deviceCacheMgr.GetPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  395. if (phrFreqstatus != null)
  396. {
  397. /// 在highFreqSampleTimes=0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  398. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  399. if (highFreqSampleTimes == 0)
  400. {
  401. var avgPhr = phr.OrderByDescending(i => i.Timestamp)
  402. .Where(i => i.Timestamp >= phrFreqstatus?.Timestamp)
  403. .Skip(1) // 去除首条
  404. .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh)
  405. .Select(i => i.PregnancyHeartRate).Average();
  406. // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  407. // 计算一般心率得到胎心系数
  408. //await SaveAndPushFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr);
  409. await SaveAndPushFreqFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(DateTime.Now).ToString());
  410. }
  411. /// 在highFreqSampleTimes>0一直异常(大于等于triggerHighFreqLow,少于等于triggerHighFreqHig),
  412. /// 取所有值的平均值,推送胎心数据到api/v1/open/OpenIot/SetFetalHeartRateConfig
  413. if (highFreqSampleTimes > 0 && heartRate.LastUpdate >= (phrFreqstatus?.LastUpdate + TimeSpan.FromSeconds(highFreqSampleTimes)))
  414. {
  415. var avgPhr = phr
  416. .Where(i => i.Timestamp >= phrFreqstatus?.Timestamp)
  417. .Skip(1) // 去除首条
  418. .Where(i => i.PregnancyHeartRate < triggerHighFreqLow || i.PregnancyHeartRate > triggerHighFreqHigh)
  419. .Select(i => i.PregnancyHeartRate).Average();
  420. // 推送胎心数据到 api/v1/open/OpenIot/SetFetalHeartRateConfig
  421. // 计算一般心率得到胎心系数
  422. //await SaveAndPushFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr);
  423. await SaveAndPushFreqFetalHeartRateAsync(heartRate, upperAlarmThreshold, lowerAlarmThreshold, avgPhr, DateTimeUtil.ConvertToTimeStamp(DateTime.Now).ToString());
  424. }
  425. // 删除高频状态的首条记录
  426. await _deviceCacheMgr.DelPregnancyHeartRateFreqStatusAsync(heartRate.Serialno);
  427. /// 设置高频状态
  428. _logger.LogInformation($"结束高频心率状态 timeDiffInSeconds {timeDiffInSeconds},highFreqSampleInterval:{highFreqSampleInterval}");
  429. }
  430. // 正常心率
  431. else
  432. {
  433. // 上15分钟的数据
  434. // 获取当前时间
  435. DateTime nowInterval = (DateTime)heartRate.LastUpdate!;
  436. // 计算last_update到上一刻钟的分钟数
  437. int minutesToSubtract = nowInterval.Minute % intervalFHR;
  438. // 计算上一刻钟的时间
  439. DateTime previousInterval = nowInterval.AddMinutes(-minutesToSubtract).AddSeconds(-nowInterval.Second).AddMilliseconds(-nowInterval.Millisecond);
  440. // 使用 last_update 上一刻
  441. var sampleTimeFHR = DateTimeUtil.ConvertToTimeStamp(previousInterval).ToString();
  442. // 计算last_update到下一刻钟的分钟数
  443. int minutesToAdd = intervalFHR - (nowInterval.Minute % intervalFHR);
  444. if (minutesToAdd == intervalFHR)
  445. {
  446. minutesToAdd = 0; // 如果已经是刻钟,则不需要增加分钟
  447. }
  448. // 计算下一刻钟的时间
  449. DateTime nextInterval = nowInterval.AddMinutes(minutesToAdd)
  450. .AddSeconds(-nowInterval.Second)
  451. .AddMilliseconds(-nowInterval.Millisecond);
  452. var daysPhr = await _serviceTDengine.GetBySerialNoAsync<PregnancyHeartRateModel>(heartRate.Serialno, 7);
  453. var normalPhrStatStartTime = nextInterval;
  454. var normalPhrStatEndTime = nextInterval.AddMinutes(-intervalFHR);
  455. _logger.LogInformation($"{heartRate.Serialno} 计算胎心数据, 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} ");
  456. var filteredPhr = daysPhr
  457. // 使用 last_update 下一刻
  458. .Where(i => i.LastUpdate <= normalPhrStatStartTime && i.LastUpdate >= normalPhrStatEndTime)
  459. .ToList();
  460. if (filteredPhr.Count == 0)
  461. {
  462. _logger.LogWarning($"{heartRate.Serialno} 周期:{normalPhrStatStartTime}-{normalPhrStatEndTime} 孕妇心率数据不足,{filteredPhr.Count}条记录");
  463. return;
  464. }
  465. var phrValue = filteredPhr.Count == 1
  466. ? filteredPhr.First().PregnancyHeartRate
  467. : filteredPhr.Average(i => i.PregnancyHeartRate);
  468. var fetalHeartRate = SafeType.SafeInt(phrValue * commonPHR?.StatModeAvgFprCoefficient!);
  469. fetalHeartRateIsAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  470. fetalHeartRateIsAbnormal = 0;// 不是高频数据,按正常值
  471. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  472. {
  473. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  474. PersonId = commonPHR!.PersonId,
  475. Serialno = heartRate.Serialno,
  476. HeartRate = fetalHeartRate,
  477. SampleTime = sampleTimeFHR.Length > 10 ? sampleTimeFHR.Substring(0, 10) : sampleTimeFHR,
  478. IsAbnormal = fetalHeartRateIsAbnormal,
  479. StatStartTime = filteredPhr.OrderBy(i => i.LastUpdate).First().LastUpdate,
  480. StatEndTime = filteredPhr.OrderBy(i => i.LastUpdate).Last().LastUpdate,
  481. CreateTime = DateTime.Now,
  482. Method = 1,
  483. IsDisplay = 1,
  484. DeviceKey = commonPHR!.DeviceKey
  485. };
  486. // 保存到 数据服务 MySQL 数据库
  487. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  488. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  489. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTimeFHR, fetalHeartRateIsAbnormal);
  490. // 推送送微信
  491. if (fetalHeartRateIsAbnormal!=0)
  492. {
  493. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  494. var fhrMsgId = $"{heartRate.Serialno}-{sampleTimeFHR}-{Guid.NewGuid().ToString("D")[^3..]}";
  495. var topic = "topic.push.wx";
  496. var fhrMsg = new
  497. {
  498. messageId = fhrMsgId,
  499. topic = topic,
  500. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTimeFHR.Length < 13 ? sampleTimeFHR.PadRight(13, '0') : sampleTimeFHR)).ToString("yyyy-MM-dd HH:mm:ss"),
  501. data = new
  502. {
  503. deviceId = device?.DeviceId,
  504. imei = heartRate.Serialno,
  505. alarmTypeId = 12,
  506. alarmDeviceName = heartRate.Serialno,
  507. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = fetalHeartRateIsAbnormal }),
  508. address = string.Empty,
  509. deviceKey = device?.DeviceId
  510. }
  511. };
  512. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  513. }
  514. }
  515. }
  516. #endregion
  517. #region 计算胎动数据
  518. _logger.LogInformation($"{heartRate.Serialno} 计算胎动数据 ");
  519. var fetalMovementNow = (DateTime)heartRate.LastUpdate!;
  520. var midNight = new DateTime(fetalMovementNow.Year, fetalMovementNow.Month, fetalMovementNow.Day, 0, 0, 0);
  521. TimeSpan fetalMovementTS = fetalMovementNow - midNight;
  522. // 当天每隔2小时的段数,取整数部分
  523. int segmentCountFM = (int)(fetalMovementTS.TotalHours / 2);
  524. for (int i = 0; i < segmentCountFM; i++)
  525. {
  526. // 每两小时
  527. var fetalMovementSampleTime = DateTimeUtil.ConvertToTimeStamp(midNight.AddHours(2 * i)).ToString()[..10];
  528. // 统计开始时间
  529. var statStartTime = midNight.AddHours(2 * i);
  530. // 统计结束时间
  531. var statEndTime = midNight.AddHours(2 * (i+1));
  532. var isFetalMovementExisted = await _deviceCacheMgr.FetalMovementIsExistedAsync(heartRate.Serialno, fetalMovementSampleTime);
  533. _logger.LogInformation($"{heartRate.Serialno} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 开始");
  534. if (!isFetalMovementExisted)
  535. {
  536. /// 开始计算
  537. var phrRange = phr.Where(i => i.LastUpdate >= statStartTime && i.LastUpdate<= statEndTime)
  538. .OrderByDescending(i => i.LastUpdate)
  539. .Select(i => i.LastUpdate)
  540. .ToList();
  541. // 判断是否有持续佩戴
  542. if (phrRange.Count >= 2)
  543. {
  544. var duringMins = Math.Abs((phrRange.First()- statStartTime).TotalMinutes);
  545. //在餐后时间段(8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00)取中间值。其他时间段取正常起始值
  546. bool isInTimeRanges = IsLastUpdateInTimeRanges(fetalMovementNow);
  547. int pregnancyWeeks = (DateTime.Now - edoc.AddDays(-280)).Days / 7;
  548. if (pregnancyWeeks >= 12 && pregnancyWeeks <= 50)
  549. {
  550. var fetalMovementMap = _mgrFetalMovementNormalValueRangeCache.GetFetalMovements();
  551. var fetalMovementMapValue = isInTimeRanges ? fetalMovementMap
  552. .Where(i =>
  553. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  554. i.PregnancyPeriod[1] >= pregnancyWeeks)
  555. .Select(i => i.MedianMovement)
  556. .FirstOrDefault()
  557. :
  558. fetalMovementMap
  559. .Where(i =>
  560. i.PregnancyPeriod![0] <= pregnancyWeeks &&
  561. i.PregnancyPeriod[1] >= pregnancyWeeks)
  562. .Select(i => i.InitialMovement)
  563. .FirstOrDefault()
  564. ;
  565. var fetalMovementValue = (fetalMovementMapValue * duringMins * 2) / 120;
  566. // 四舍五入
  567. var fetalMovement = (int)Math.Round(fetalMovementValue, 0, MidpointRounding.AwayFromZero);
  568. // _logger.LogInformation($"{heartRate.Serialno} segmentCountFMIndex: {i} -- fetalMovementSampleTime:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")} -- statStartTime: {statStartTime} -- statEndTime: {statEndTime}-- isFetalMovementExisted: {isFetalMovementExisted} ");
  569. _logger.LogInformation($"{heartRate.Serialno} 胎动数据采样时间:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")}, 采样周期:{statStartTime}-{statEndTime}, 原始胎动值:{fetalMovementMapValue}, 佩戴时间 :{duringMins}|{statStartTime}-{phrRange.First()}, 胎动计算值:{fetalMovementValue}, 胎动最终值:{fetalMovement} 已完成.");
  570. // 获取胎心数据状态与胎动数据状态一致
  571. var feltalMovementIsAbnormal = fetalHeartRateIsAbnormal;
  572. //var feltalMovementIsAbnormal = 0;
  573. // 推送到api/v1/open/OpenIot/SetFetalMovementConfig
  574. await _serviceIotApi.SetFetalMovementConfig(heartRate.Serialno, fetalMovement, fetalMovementSampleTime, feltalMovementIsAbnormal);
  575. // 保存到MySQL数据库
  576. HisGpsFetalMovement fm = new()
  577. {
  578. FetalMovementId = Guid.NewGuid().ToString("D"),
  579. PersonId = commonPHR!.PersonId,
  580. Serialno = heartRate.Serialno,
  581. CreateTime = DateTime.Now,
  582. IsAbnormal = feltalMovementIsAbnormal,
  583. FetalMovementValue = fetalMovement,
  584. SampleTime = fetalMovementSampleTime,
  585. Method = 1,
  586. IsDisplay = 1,
  587. DeviceKey = commonPHR!.DeviceKey
  588. };
  589. await _hisFetalMovementApiClient.AddAsync(fm).ConfigureAwait(false);
  590. // 发送到微信
  591. if (feltalMovementIsAbnormal != 0)
  592. {
  593. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  594. var fmMsgId = $"{heartRate.Serialno}-{fetalMovementSampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  595. var topic = "topic.push.wx";
  596. var fmMsg = new
  597. {
  598. messageId = Guid.NewGuid().ToString("D"),
  599. topic = topic,
  600. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(fetalMovementSampleTime.Length < 13 ? fetalMovementSampleTime.PadRight(13, '0') : fetalMovementSampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
  601. data = new
  602. {
  603. deviceId = device?.DeviceId,
  604. imei = heartRate.Serialno,
  605. alarmTypeId = 12,
  606. alarmDeviceName = heartRate.Serialno,
  607. alarmRemarks = JsonConvert.SerializeObject(new { fetalMovementValue = fetalMovement, isAbnormal = feltalMovementIsAbnormal }),
  608. address = string.Empty,
  609. deviceKey = device?.DeviceId
  610. }
  611. };
  612. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fmMsgId, topic, fmMsg).ConfigureAwait(false);
  613. }
  614. // 设置入库缓存记录
  615. await _deviceCacheMgr.SetFetalMovementAsync(heartRate.Serialno, fetalMovementSampleTime,fm);
  616. }
  617. else
  618. {
  619. _logger.LogWarning($"{heartRate.Serialno} 孕周 {pregnancyWeeks},超出胎动计算范围");
  620. }
  621. }
  622. else
  623. {
  624. _logger.LogInformation($"{heartRate.Serialno} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 不足两条,不能判断是否持续佩戴");
  625. }
  626. }
  627. else
  628. {
  629. _logger.LogInformation($"{heartRate.Serialno} 胎动记录{isFetalMovementExisted},数据采样时间:{fetalMovementSampleTime}|{midNight.AddHours(2 * i).ToString("yyyy-MM-dd HH:mm:ss")}, 周期:{statStartTime}-{statEndTime} 已处理");
  630. }
  631. }
  632. #endregion
  633. }
  634. #endregion
  635. #region 定时计算胎心数据触发器 {interval} 秒后
  636. //var fetalKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  637. //await SetIntervalTriggerAsync(fetalKey, heartRate.Serialno, 60 * 15);
  638. #endregion
  639. #region 定时计算胎心数据触发器下一刻钟后
  640. //// 获取当前时间
  641. //DateTime nowInterval = DateTime.Now;
  642. //// 计算下一个15分钟的刻钟
  643. //int minutesToAdd = 15 - (nowInterval.Minute % 15);
  644. //if (minutesToAdd == 15)
  645. //{
  646. // minutesToAdd = 0; // 如果已经是刻钟,则不需要增加分钟
  647. //}
  648. //// 计算下一刻钟的时间
  649. //DateTime nextInterval = nowInterval.AddMinutes(minutesToAdd)
  650. // .AddSeconds(-nowInterval.Second)
  651. // .AddMilliseconds(-nowInterval.Millisecond);
  652. //// 计算时间差
  653. //TimeSpan timeDifference = nextInterval - nowInterval;
  654. //var fetalKey = $"health_monitor/schedule_push/cal_fetal_heart_rate/imei/{heartRate.Serialno}";
  655. //await SetIntervalTriggerAsync(fetalKey, heartRate.Serialno, (long)timeDifference.TotalSeconds);
  656. #endregion
  657. #region 定时计算胎动数据触发器 0 点开始
  658. //var fetalMovementKey = $"health_monitor/schedule_push/cal_fetal_movement/imei/{heartRate.Serialno}";
  659. ///// 计算 0 点秒数
  660. //DateTime now = DateTime.Now;
  661. //var rand = new Random();
  662. //var pushSec = rand.Next(59);
  663. //int pushMin = int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  664. //DateTime nextRunTime = new (now.Year, now.Month, now.Day, 0, pushMin, pushSec);
  665. //TimeSpan timeUntilNextRun = nextRunTime - now;
  666. //if (timeUntilNextRun < TimeSpan.Zero)
  667. //{
  668. // timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  669. // nextRunTime += timeUntilNextRun;
  670. //}
  671. //var ttl = (long)timeUntilNextRun.TotalSeconds;
  672. //await SetIntervalTriggerAsync(fetalMovementKey, heartRate.Serialno, ttl);
  673. #endregion
  674. }
  675. #region 定时下发触发器(定时建模)
  676. var key = $"health_monitor/schedule_push/pregnancy_heart_rate/imei/{heartRate.Serialno}";
  677. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  678. if (string.IsNullOrWhiteSpace(schedule_push))
  679. {
  680. // 注册首次下推
  681. #if DEBUG
  682. // await _serviceEtcd.PutValAsync(key, result, 60*1, false).ConfigureAwait(false);
  683. var interval = 0;
  684. // 获取当前时间
  685. DateTime now = DateTime.Now;
  686. // 计算距离下一个$interval天后的8点的时间间隔
  687. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 1, 58).AddDays(interval);
  688. TimeSpan timeUntilNextRun = nextRunTime - now;
  689. // 如果当前时间已经超过了8点,将等待到明天后的8点
  690. if (timeUntilNextRun < TimeSpan.Zero)
  691. {
  692. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  693. nextRunTime += timeUntilNextRun;
  694. }
  695. var ttl = (long)timeUntilNextRun.TotalSeconds;
  696. var data = new
  697. {
  698. imei = heartRate.Serialno,
  699. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  700. ttl,
  701. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  702. };
  703. var result = JsonConvert.SerializeObject(data);
  704. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  705. #else
  706. var interval = 0;
  707. // 获取当前时间
  708. DateTime now = DateTime.Now;
  709. var rand=new Random();
  710. var pushSec = rand.Next(59);
  711. int pushMin= int.TryParse(heartRate.Serialno.AsSpan(heartRate.Serialno.Length - 1), out pushMin) ? pushMin : 10;
  712. // 计算距离下一个$interval天后的8点的时间间隔
  713. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 0, pushMin, pushSec).AddDays(interval);
  714. TimeSpan timeUntilNextRun = nextRunTime - now;
  715. if (timeUntilNextRun < TimeSpan.Zero)
  716. {
  717. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  718. nextRunTime += TimeSpan.FromDays(1);
  719. }
  720. var ttl =(long)timeUntilNextRun.TotalSeconds;
  721. var data = new
  722. {
  723. imei = heartRate.Serialno,
  724. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  725. ttl,
  726. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  727. };
  728. var result = JsonConvert.SerializeObject(data);
  729. await _serviceEtcd.PutValAsync(key, result,ttl, false).ConfigureAwait(false);
  730. #endif
  731. }
  732. #endregion
  733. }
  734. }
  735. private async Task SaveAndPushFetalHeartRateAsync(HisGpsHeartRate heartRate, int upperAlarmThreshold, int lowerAlarmThreshold, double avgPhr)
  736. {
  737. var commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(heartRate.Serialno);
  738. if (commonPHR != null)
  739. {
  740. // 保存到TDengine数据库
  741. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR);
  742. // 计算胎心=孕妇心率*系数
  743. var fetalHeartRate = SafeType.SafeInt(avgPhr * commonPHR?.StatModeAvgFprCoefficient!);
  744. var sampleTime = DateTimeUtil.ConvertToTimeStamp(DateTime.Now).ToString();
  745. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  746. // 保存到 数据服务 MySQL 数据库
  747. HisGpsFetalHeartRate gpsFetalHeartRate = new ()
  748. {
  749. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  750. PersonId = commonPHR!.PersonId,
  751. Serialno = heartRate.Serialno,
  752. HeartRate = fetalHeartRate,
  753. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  754. IsAbnormal = isAbnormal,
  755. StatStartTime = commonPHR.StatStartTime,
  756. StatEndTime = commonPHR.StatEndTime,
  757. CreateTime = DateTime.Now,
  758. Method = 1,
  759. IsDisplay = 1,
  760. DeviceKey = commonPHR!.DeviceKey
  761. };
  762. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  763. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  764. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  765. // 推送到微信
  766. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  767. var deviceId = device?.DeviceId;
  768. var msg = new
  769. {
  770. messageId = "",
  771. topic = "topic.push.wx",
  772. time=""
  773. };
  774. }
  775. }
  776. private async Task SaveAndPushFreqFetalHeartRateAsync(HisGpsHeartRate heartRate, int upperAlarmThreshold, int lowerAlarmThreshold, double avgPhr,string sampleTime)
  777. {
  778. var commonPHR = await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(heartRate.Serialno);
  779. if (commonPHR != null)
  780. {
  781. // 保存到TDengine数据库
  782. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR);
  783. // 计算胎心=孕妇心率*系数
  784. var fetalHeartRate = SafeType.SafeInt(avgPhr * commonPHR?.StatModeAvgFprCoefficient!);
  785. var isAbnormal = fetalHeartRate > upperAlarmThreshold ? 1 : (fetalHeartRate < lowerAlarmThreshold ? 2 : 0);
  786. // 保存到 数据服务 MySQL 数据库
  787. HisGpsFetalHeartRate gpsFetalHeartRate = new()
  788. {
  789. FetalHeartRateId = Guid.NewGuid().ToString("D"),
  790. PersonId = commonPHR!.PersonId,
  791. Serialno = heartRate.Serialno,
  792. HeartRate = fetalHeartRate,
  793. SampleTime = sampleTime.Length > 10 ? sampleTime.Substring(0, 10) : sampleTime,
  794. IsAbnormal = isAbnormal,
  795. StatStartTime = commonPHR.StatStartTime,
  796. StatEndTime = commonPHR.StatEndTime,
  797. CreateTime = DateTime.Now,
  798. Method = 1,
  799. IsDisplay = 1,
  800. DeviceKey = commonPHR!.DeviceKey
  801. };
  802. await _hisFetalHeartApiClient.AddAsync(gpsFetalHeartRate).ConfigureAwait(false);
  803. // 推送到api/v1/open/OpenIot/SetFetalHeartRateConfig
  804. await _serviceIotApi.SetFetalHeartRateConfig(heartRate.Serialno, fetalHeartRate, sampleTime, isAbnormal);
  805. // 推送到微信
  806. if (isAbnormal!=0)
  807. {
  808. var device = await _deviceCacheMgr.GetDeviceBySerialNoAsync(heartRate.Serialno).ConfigureAwait(false);
  809. var fhrMsgId = $"{heartRate.Serialno}-{sampleTime}-{Guid.NewGuid().ToString("D")[^3..]}";
  810. var topic = "topic.push.wx";
  811. var fhrMsg = new
  812. {
  813. messageId = fhrMsgId,
  814. topic = topic,
  815. time = DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(long.Parse(sampleTime.Length < 13 ? sampleTime.PadRight(13, '0') : sampleTime)).ToString("yyyy-MM-dd HH:mm:ss"),
  816. data = new
  817. {
  818. deviceId = device?.DeviceId,
  819. imei = heartRate.Serialno,
  820. alarmTypeId = 12,
  821. alarmDeviceName = heartRate.Serialno,
  822. alarmRemarks = JsonConvert.SerializeObject(new { fetalHeartValue = fetalHeartRate, isAbnormal = isAbnormal }),
  823. address = string.Empty,
  824. deviceKey = device?.DeviceId
  825. }
  826. };
  827. await _serviceMqProcess.ProcessIMEIEventMessageAsync(fhrMsgId, topic, fhrMsg).ConfigureAwait(false);
  828. }
  829. }
  830. }
  831. private async Task SetIntervalTriggerAsync(string key,string imei, long interval)
  832. {
  833. // var key = $"health_monitor/schedule_push/{type}/imei/{imei}";
  834. var schedulePush = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  835. if (string.IsNullOrWhiteSpace(schedulePush))
  836. {
  837. var now = DateTime.Now;
  838. var timeNextRun = now.Add(TimeSpan.FromSeconds(interval));
  839. var data = new
  840. {
  841. imei,
  842. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  843. ttl = interval,
  844. next_run_time = timeNextRun.ToString("yyyy-MM-dd HH:mm:ss")
  845. };
  846. var result = JsonConvert.SerializeObject(data);
  847. await _serviceEtcd.PutValAsync(key, result, interval, false).ConfigureAwait(false);
  848. }
  849. }
  850. public static bool IsLastUpdateInTimeRanges(DateTime lastUpdate)
  851. {
  852. var now = lastUpdate.TimeOfDay;
  853. var timeRanges = new List<(TimeSpan Start, TimeSpan End)>
  854. {
  855. // 8:00~10:00,12:00~14:00,18:00~20:00,22:00~24:00
  856. (new TimeSpan(8, 0, 0), new TimeSpan(10, 0, 0)),
  857. (new TimeSpan(12, 0, 0), new TimeSpan(14, 0, 0)),
  858. (new TimeSpan(18, 0, 0), new TimeSpan(20, 0, 0)),
  859. (new TimeSpan(22, 0, 0), new TimeSpan(24, 0, 0))
  860. };
  861. return timeRanges.Any(range => now >= range.Start && now <= range.End);
  862. }
  863. }
  864. }