Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

361 Zeilen
16KB

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