Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

BloodpressResolver.cs 17KB

před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
před 1 rokem
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. 
  2. using HealthMonitor.Common;
  3. using HealthMonitor.Common.helper;
  4. using HealthMonitor.Service.Biz.db;
  5. using HealthMonitor.Service.Cache;
  6. using HealthMonitor.Service.Etcd;
  7. using HealthMonitor.Service.Resolver.Interface;
  8. using HealthMonitor.Service.Sub;
  9. using HealthMonitor.Service.Sub.Topic.Model;
  10. using Microsoft.EntityFrameworkCore.Metadata;
  11. using Microsoft.Extensions.Logging;
  12. using Newtonsoft.Json;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Data.Common;
  16. using System.Linq;
  17. using System.Text;
  18. using System.Text.Json.Serialization;
  19. using System.Threading.Tasks;
  20. using TDengineTMQ;
  21. using TelpoDataService.Util.Entities.GpsLocationHistory;
  22. namespace HealthMonitor.Service.Resolver
  23. {
  24. public class BloodpressResolver: IResolver
  25. {
  26. private readonly ILogger<BloodpressResolver> _logger;
  27. private readonly PersonCacheManager _personCacheMgr;
  28. private readonly TDengineService _serviceTDengine;
  29. private readonly BloodPressReferenceValueCacheManager _bpRefValCacheManager;
  30. private readonly HttpHelper _httpHelper = default!;
  31. private readonly AsyncLocal<string> _messageId = new();
  32. private readonly AsyncLocal<HisGpsBloodPress> _msgData = new();
  33. private readonly EtcdService _serviceEtcd;
  34. public BloodpressResolver(
  35. TDengineService serviceDengine,
  36. BloodPressReferenceValueCacheManager bpRefValCacheManager,
  37. PersonCacheManager personCacheMgr, HttpHelper httpHelper,
  38. EtcdService serviceEtcd,
  39. ILogger<BloodpressResolver> logger)
  40. {
  41. _httpHelper = httpHelper;
  42. _serviceTDengine = serviceDengine;
  43. _bpRefValCacheManager = bpRefValCacheManager;
  44. _logger = logger;
  45. _personCacheMgr = personCacheMgr;
  46. _serviceEtcd = serviceEtcd;
  47. }
  48. public void SetResolveInfo(PackageMsgModel msg)
  49. {
  50. var topicHmBloodPress = JsonConvert.DeserializeObject<TopicHmBloodPress>(msg.DetailData.ToString()!);
  51. _messageId.Value = msg.MessageId;
  52. _msgData.Value = new HisGpsBloodPress()
  53. {
  54. BloodPressId = topicHmBloodPress!.BloodPressId,
  55. MessageId = topicHmBloodPress!.MessageId,
  56. Serialno= topicHmBloodPress!.Serialno,
  57. SystolicValue = topicHmBloodPress!.SystolicValue,
  58. DiastolicValue= topicHmBloodPress!.DiastolicValue,
  59. LastUpdate= DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmBloodPress.LastUpdate) / 1000000),
  60. CreateTime= DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmBloodPress.CreateTime) / 1000000),
  61. Method= topicHmBloodPress!.Method,
  62. IsDisplay=topicHmBloodPress!.IsDisplay ? 1 : 0
  63. };
  64. }
  65. public override string ToString()
  66. {
  67. return $"{nameof(BloodpressResolver)}[{_messageId.Value}]";
  68. }
  69. public async Task ExecuteMessageAsync()
  70. {
  71. var messageId = _messageId.Value;
  72. var bp = _msgData.Value!;
  73. #region 获取个人信息
  74. var person = await _personCacheMgr.GetDeviceGpsPersonCacheBySerialNoAsync(bp.MessageId, bp.Serialno).ConfigureAwait(false);
  75. //验证这个信息是否存在
  76. if (person == null || person?.Person.BornDate == null)
  77. {
  78. _logger.LogWarning("验证个人信息,找不到个人信息,跳过此消息");
  79. return;
  80. }
  81. // 验证年龄是否在范围 (2 - 120)
  82. var age = SafeType.SafeInt(DateTime.Today.Year - person?.Person.BornDate!.Value.Year!);
  83. if (age < 1 || age > 120)
  84. {
  85. _logger.LogWarning("验证年龄,不在范围 (2 - 120)岁,跳过此消息");
  86. return;
  87. }
  88. #endregion
  89. var gender = person?.Person.Gender == true ? 1 : 2;
  90. var isHypertension = SafeType.SafeBool(person?.Person.Ishypertension!);
  91. var height = SafeType.SafeDouble(person?.Person.Height!);
  92. var weight = SafeType.SafeDouble(person?.Person.Weight!);
  93. #region 计算增量值
  94. var bpRef = await _bpRefValCacheManager.GetBloodPressReferenceValueAsync(age, gender, isHypertension);
  95. var last = await _serviceTDengine.GetLastAsync("stb_hm_bp_push_ref_inc_value", $"serialno='{bp.Serialno}' order by ts desc");
  96. //var ts = last?[0];
  97. var systolicRefValue = bpRef?.Systolic;//?
  98. var diastolicRefValue = bpRef?.Diastolic;//?
  99. long duration = 7 * 24 * 3600 * 1000;
  100. // 曾经有下发记录
  101. if (last?.Count!=0)
  102. {
  103. if (DateTime.TryParse(last?[0]!.ToString(), out DateTime newTs))
  104. {
  105. systolicRefValue = (int)last?[2]!;
  106. diastolicRefValue = (int)last?[3]!;
  107. duration = SafeType.SafeInt64(((DateTime)bp.LastUpdate! - newTs).TotalMilliseconds);
  108. }
  109. }
  110. TimeSpan ts= TimeSpan.FromMilliseconds(duration);
  111. // 获取历史数据
  112. ////DateTime now = DateTime.Now;
  113. //DateTime now = (DateTime)bp.LastUpdate!; //测试
  114. //DateTime startTime = now.AddDays(-duration);
  115. //DateTime endTime = now;
  116. DateTime endTime = (DateTime)bp.LastUpdate!; //测试
  117. DateTime startTime = endTime-ts;
  118. // 如果hm_bp_config_manual_calibration存在数据,使用最新数据
  119. //
  120. var systolicAggregate = await _serviceTDengine.GetAggregateValueAsync("systolic_value", "stb_hm_bloodpress", $"ts>='{startTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and ts <='{endTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and serialno='{bp.Serialno}'");
  121. var diastolicAggregate = await _serviceTDengine.GetAggregateValueAsync("diastolic_value", "stb_hm_bloodpress", $"ts>='{startTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and ts <='{endTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and serialno='{bp.Serialno}'");
  122. //var systolicAggregate = _serviceTDengine.GetAggregateValue("systolic_value", "hm_bloodpress", $"ts>='{startTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and ts <='{endTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and serialno='{bp.Serialno}'");
  123. //var diastolicAggregate = _serviceTDengine.GetAggregateValue("diastolic_value", "hm_bloodpress", $"ts>='{startTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and ts <='{endTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and serialno='{bp.Serialno}'");
  124. // 最大值
  125. var systolicMax = systolicAggregate.Max;
  126. var diastolicMax = diastolicAggregate.Max;
  127. // 最小值
  128. var systolicMin = systolicAggregate.Min;
  129. var diastolicMin = diastolicAggregate.Min;
  130. // 计算去除最大值和最小值和异常值的平均值
  131. var systolicAvg = await _serviceTDengine.GetAvgExceptMaxMinValueAsync("systolic_value", "stb_hm_bloodpress", $"ts>='{startTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and ts <='{endTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and serialno='{bp.Serialno}' and systolic_value < {systolicRefValue} ");
  132. var diastolicAvg = await _serviceTDengine.GetAvgExceptMaxMinValueAsync("diastolic_value", "stb_hm_bloodpress", $"ts>='{startTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and ts <='{endTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and serialno='{bp.Serialno}' and diastolic_value < {diastolicRefValue}");
  133. if (systolicAvg.Equals(0) || diastolicAvg.Equals(0))
  134. {
  135. _logger.LogWarning("平均值为0不保存");
  136. return;
  137. }
  138. //var systolicAvg = _serviceTDengine.GetAvgExceptMaxMinValue("systolic_value", "hm_bloodpress", $"ts>='{startTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and ts <='{endTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and serialno='{bp.Serialno}' and systolic_value < {systolicRefValue} ");
  139. //var diastolicAvg = _serviceTDengine.GetAvgExceptMaxMinValue("diastolic_value", "hm_bloodpress", $"ts>='{startTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and ts <='{endTime:yyyy-MM-ddTHH:mm:ss.fffZ}' and serialno='{bp.Serialno}' and diastolic_value < {diastolicRefValue}");
  140. // 偏移参数
  141. var avgOffset = 0.25M;
  142. var systolicAvgOffset = avgOffset;
  143. var diastolicAvgOffset = avgOffset;
  144. // 增量值=(标定值-平均值)* 0.25
  145. var systolicInc = systolicAvg.Equals(0M) ? 0 : (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
  146. var diastolicInc = diastolicAvg.Equals(0M) ? 0 : (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
  147. #endregion
  148. #region 插入BP增量值 hm_bloodpress_stats_inc
  149. // 自动建表
  150. var sql = $"INSERT INTO health_monitor.hm_bp_stats_inc_{bp.Serialno.Substring(bp.Serialno.Length - 2)} " +
  151. $"USING health_monitor.stb_hm_bloodpress_stats_inc " +
  152. $"TAGS ('{bp.Serialno.Substring(bp.Serialno.Length - 2)}') " +
  153. $"VALUES(" +
  154. $"'{bp.LastUpdate:yyyy-MM-dd HH:mm:ss.fff}'," +
  155. $"'{bp.BloodPressId}'," +
  156. $"'{bp.MessageId}'," +
  157. $"'{bp.Serialno}'," +
  158. $"{bp.SystolicValue}," +
  159. $"{systolicRefValue}," +
  160. $"{systolicAvg}," +
  161. $"{systolicMax}," +
  162. $"{systolicMin}," +
  163. $"{systolicAvgOffset}," +
  164. $"{systolicInc}," +
  165. $"{bp.DiastolicValue}," +
  166. $"{diastolicRefValue}," +
  167. $"{diastolicAvg}," +
  168. $"{diastolicMax}," +
  169. $"{diastolicMin}," +
  170. $"{diastolicAvgOffset}," +
  171. $"{diastolicInc}," +
  172. $"{gender}," +
  173. $"{age}," +
  174. $"{height}," +
  175. $"{weight}," +
  176. $"'{bp.LastUpdate:yyyy-MM-dd HH:mm:ss.fff}'," +
  177. $"{duration}," +
  178. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  179. $"'{endTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  180. $"'{string.Empty}'," +
  181. $"{isHypertension})";
  182. _serviceTDengine.ExecuteInsertSQL(sql);
  183. // 发送到 设置设备血压标定参数
  184. #endregion
  185. // 注册定时下发事件
  186. // 获取当前时间
  187. //DateTime sNow = DateTime.Now;
  188. //// 计算距离明天12点的时间间隔
  189. //TimeSpan timeUntil = new DateTime(sNow.Year, sNow.Month, sNow.Day, 12, 0, 0) - sNow;
  190. //// 如果当前时间已经超过了12点,将等待到明天
  191. //if (timeUntil < TimeSpan.Zero)
  192. //{
  193. // timeUntil = timeUntil.Add(TimeSpan.FromHours(24));
  194. //}
  195. //var data = new
  196. //{
  197. // imei = bp.Serialno,
  198. // systolicCalibrationValue = systolicRefValue, //收缩压标定值,值为0 表示不生效
  199. // diastolicCalibrationValue = diastolicRefValue, //舒张压标定值,值为0表示不生效
  200. // systolicIncValue = systolicInc, //收缩压显示增量,值为0 表示不生效
  201. // diastolicIncValue = diastolicInc //舒张压显示增量,值为0 表示不生效
  202. //};
  203. //var url = $"http://id.ssjlai.com/webapi/api/Command/SetBloodPressCalibrationConfig";
  204. //List<KeyValuePair<string, string>> headers = new()
  205. //{
  206. // new KeyValuePair<string, string>("AuthKey", "key1")
  207. //};
  208. //var data = new
  209. //{
  210. // imei = bp.Serialno,
  211. // systolicCalibrationValue = systolicRefValue, //收缩压标定值,值为0 表示不生效
  212. // diastolicCalibrationValue = diastolicRefValue, //舒张压标定值,值为0表示不生效
  213. // systolicIncValue = systolicInc, //收缩压显示增量,值为0 表示不生效
  214. // diastolicIncValue = diastolicInc //舒张压显示增量,值为0 表示不生效
  215. //};
  216. //var result = JsonConvert.SerializeObject(data);
  217. //var result = bp.Serialno;
  218. var key = $"health_moniter/schedule_push/imei/{bp.Serialno}";
  219. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  220. if (string.IsNullOrWhiteSpace(schedule_push))
  221. {
  222. // 注册首次下推
  223. #if DEBUG
  224. // await _serviceEtcd.PutValAsync(key, result, 60*1, false).ConfigureAwait(false);
  225. var interval = 0;
  226. // 获取当前时间
  227. DateTime now = DateTime.Now;
  228. // 计算距离下一个$interval天后的8点的时间间隔
  229. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute+1, 58).AddDays(interval);
  230. TimeSpan timeUntilNextRun = nextRunTime - now;
  231. // 如果当前时间已经超过了8点,将等待到明天后的8点
  232. if (timeUntilNextRun < TimeSpan.Zero)
  233. {
  234. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  235. nextRunTime += timeUntilNextRun;
  236. }
  237. var ttl = (long)timeUntilNextRun.TotalSeconds;
  238. var data = new
  239. {
  240. imei = bp.Serialno,
  241. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  242. ttl,
  243. next_run_time= nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  244. };
  245. var result=JsonConvert.SerializeObject(data);
  246. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  247. #else
  248. //DateTime sNow = DateTime.Now;
  249. //// 计算距离19:59:55点的时间间隔
  250. //TimeSpan timeUntil = new DateTime(sNow.Year, sNow.Month, sNow.Day, 19, 59, 55) - sNow;
  251. //// 如果当前时间已经超过了12点,将等待到明天
  252. //if (timeUntil < TimeSpan.Zero)
  253. //{
  254. // timeUntil = timeUntil.Add(TimeSpan.FromHours(24));
  255. //}
  256. //var ttl = (long)timeUntil.TotalSeconds;
  257. var interval = 0;
  258. // 获取当前时间
  259. DateTime now = DateTime.Now;
  260. // 计算距离下一个$interval天后的8点的时间间隔
  261. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 19, 59, 58).AddDays(interval);
  262. TimeSpan timeUntilNextRun = nextRunTime - now;
  263. // 如果当前时间已经超过了8点,将等待到明天后的8点
  264. if (timeUntilNextRun < TimeSpan.Zero)
  265. {
  266. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  267. nextRunTime += timeUntilNextRun;
  268. }
  269. var ttl =(long)timeUntilNextRun.TotalSeconds;
  270. var data = new
  271. {
  272. imei = bp.Serialno,
  273. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  274. ttl,
  275. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  276. };
  277. var result = JsonConvert.SerializeObject(data);
  278. await _serviceEtcd.PutValAsync(key, result,ttl, false).ConfigureAwait(false);
  279. #endif
  280. }
  281. //// 生效
  282. //if (DateTime.Now.Hour == 1)
  283. //{
  284. // var data = new
  285. // {
  286. // imei = bp.Serialno,
  287. // systolicCalibrationValue = systolicRefValue, //收缩压标定值,值为0 表示不生效
  288. // diastolicCalibrationValue = diastolicRefValue, //舒张压标定值,值为0表示不生效
  289. // systolicIncValue = systolicInc, //收缩压显示增量,值为0 表示不生效
  290. // diastolicIncValue = diastolicInc //舒张压显示增量,值为0 表示不生效
  291. // };
  292. // var result = await _httpHelper.HttpToPostAsync(url, data, headers).ConfigureAwait(false);
  293. // _logger.LogInformation($"将 {JsonConvert.SerializeObject(data)}发送到 {url} 并且返回 {JsonConvert.SerializeObject(result)}");
  294. //}
  295. //// 不生效
  296. //else if (DateTime.Now.Hour == 3)
  297. //{
  298. // var data = new
  299. // {
  300. // imei = bp.Serialno,
  301. // systolicCalibrationValue = 0, //收缩压标定值,值为0 表示不生效
  302. // diastolicCalibrationValue = 0, //舒张压标定值,值为0表示不生效
  303. // systolicIncValue = 0, //收缩压显示增量,值为0 表示不生效
  304. // diastolicIncValue = 0 //舒张压显示增量,值为0 表示不生效
  305. // };
  306. // var result = await _httpHelper.HttpToPostAsync(url, data, headers).ConfigureAwait(false);
  307. // _logger.LogInformation($"将 {JsonConvert.SerializeObject(data)}发送到 {url} 并且返回 {JsonConvert.SerializeObject(result)}");
  308. //}
  309. }
  310. }
  311. }