Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

452 lignes
22KB

  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.EntityFrameworkCore.Metadata;
  10. using Microsoft.Extensions.Logging;
  11. using Newtonsoft.Json;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Data.Common;
  15. using System.Linq;
  16. using System.Text;
  17. using System.Text.Json.Serialization;
  18. using System.Threading.Tasks;
  19. using TDengineTMQ;
  20. using TelpoDataService.Util.Entities.GpsCard;
  21. using TelpoDataService.Util;
  22. using TelpoDataService.Util.Entities.GpsLocationHistory;
  23. using HealthMonitor.Service.Biz;
  24. using HealthMonitor.Model.Service;
  25. using Microsoft.Extensions.Options;
  26. using HealthMonitor.Model.Config;
  27. using HealthMonitor.Model.Service.Mapper;
  28. using Mvccpb;
  29. namespace HealthMonitor.Service.Resolver
  30. {
  31. public class BloodpressResolver: IResolver
  32. {
  33. private readonly ILogger<BloodpressResolver> _logger;
  34. private readonly BoodPressResolverConfig _configBoodPressResolver;
  35. private readonly PersonCacheManager _personCacheMgr;
  36. private readonly TDengineService _serviceTDengine;
  37. private readonly BloodPressReferenceValueCacheManager _bpRefValCacheManager;
  38. private readonly HttpHelper _httpHelper = default!;
  39. private readonly GpsCardAccessorClient<GpsPerson> _gpsPersonApiClient;
  40. private readonly IotWebApiService _serviceIotWebApi;
  41. private readonly AsyncLocal<string> _messageId = new();
  42. private readonly AsyncLocal<HisGpsBloodPress> _msgData = new();
  43. private readonly EtcdService _serviceEtcd;
  44. public BloodpressResolver(
  45. TDengineService serviceDengine,
  46. BloodPressReferenceValueCacheManager bpRefValCacheManager,
  47. PersonCacheManager personCacheMgr, HttpHelper httpHelper,
  48. GpsCardAccessorClient<GpsPerson> gpsPersonApiClient,
  49. IotWebApiService iotWebApiService,
  50. EtcdService serviceEtcd,
  51. IOptions<BoodPressResolverConfig> optionBoodPressResolver,
  52. ILogger<BloodpressResolver> logger)
  53. {
  54. _httpHelper = httpHelper;
  55. _serviceTDengine = serviceDengine;
  56. _bpRefValCacheManager = bpRefValCacheManager;
  57. _gpsPersonApiClient = gpsPersonApiClient;
  58. _serviceIotWebApi = iotWebApiService;
  59. _logger = logger;
  60. _personCacheMgr = personCacheMgr;
  61. _serviceEtcd = serviceEtcd;
  62. _configBoodPressResolver= optionBoodPressResolver.Value;
  63. }
  64. public void SetResolveInfo(PackageMsgModel msg)
  65. {
  66. var topicHmBloodPress = JsonConvert.DeserializeObject<TopicHmBloodPress>(msg.DetailData.ToString()!);
  67. _messageId.Value = msg.MessageId;
  68. _msgData.Value = new HisGpsBloodPress()
  69. {
  70. BloodPressId = topicHmBloodPress!.BloodPressId,
  71. MessageId = topicHmBloodPress!.MessageId,
  72. Serialno= topicHmBloodPress!.Serialno,
  73. SystolicValue = topicHmBloodPress!.SystolicValue,
  74. DiastolicValue= topicHmBloodPress!.DiastolicValue,
  75. LastUpdate= DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmBloodPress.LastUpdate) / 1000000),
  76. CreateTime= DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmBloodPress.CreateTime) / 1000000),
  77. Method= topicHmBloodPress!.Method,
  78. IsDisplay=topicHmBloodPress!.IsDisplay ? 1 : 0
  79. };
  80. }
  81. public override string ToString()
  82. {
  83. return $"{nameof(BloodpressResolver)}[{_messageId.Value}]";
  84. }
  85. public async Task ExecuteMessageAsync()
  86. {
  87. try
  88. {
  89. var messageId = _messageId.Value;
  90. var bp = _msgData.Value!;
  91. int systolicRefValue;
  92. int diastolicRefValue;
  93. int systolicInc;
  94. int diastolicInc;
  95. int systolicAvg;
  96. int diastolicAvg;
  97. int systolicMax = 0;
  98. int diastolicMax = 0;
  99. // 最小值
  100. int systolicMin = 0;
  101. int diastolicMin = 0;
  102. // 偏移参数
  103. var avgOffset = 0.25M;
  104. var systolicAvgOffset = avgOffset;
  105. var diastolicAvgOffset = avgOffset;
  106. // 统计时间
  107. DateTime endTime = DateTime.Now; //测试
  108. DateTime startTime = DateTime.Now;
  109. // 最后一次下发值
  110. //int lastPushSystolicInc = 0;
  111. //int lastPushDiastolicInc = 0;
  112. bool remarkFlag = false;
  113. //long duration = 7 * 24 * 3600 * 1000;
  114. string sql = string.Empty;
  115. #region 获取个人信息
  116. var person = await _personCacheMgr.GetDeviceGpsPersonCacheBySerialNoAsync(bp.MessageId, bp.Serialno).ConfigureAwait(false);
  117. //验证这个信息是否存在
  118. if (person == null || person?.Person.BornDate == null)
  119. {
  120. _logger.LogWarning($"{bp.Serialno}--{bp.MessageId} 验证个人信息,找不到个人信息,跳过此消息");
  121. return;
  122. }
  123. // 验证年龄是否在范围 (2 - 120)
  124. var age = SafeType.SafeInt(DateTime.Today.Year - person?.Person.BornDate!.Value.Year!);
  125. if (age < 2 || age > 120)
  126. {
  127. _logger.LogWarning($"{bp.Serialno}--{bp.MessageId} 验证年龄,不在范围 (2 - 120)岁,跳过此消息");
  128. return;
  129. }
  130. var gender = person?.Person.Gender == true ? 1 : 2;
  131. var isHypertension = SafeType.SafeBool(person?.Person.Ishypertension!);
  132. var height = SafeType.SafeDouble(person?.Person.Height!);
  133. var weight = SafeType.SafeDouble(person?.Person.Weight!);
  134. #endregion
  135. #region 初始化常规血压标定值标定值
  136. var bpRef = await _bpRefValCacheManager.GetBloodPressReferenceValueAsync(age, gender, isHypertension);
  137. systolicRefValue = bpRef!.Systolic;//?
  138. diastolicRefValue = bpRef!.Diastolic;//?
  139. #endregion
  140. _logger.LogInformation($"Person Remarks 值:{person?.Person.Remarks}");
  141. if (string.IsNullOrWhiteSpace(person?.Person.Remarks))
  142. {
  143. _logger.LogInformation($"{bp.Serialno},设备解绑后绑定,首次手工测量了血压值,下发年龄标定值和增量值(测量值=平均值计算得出的)");
  144. #region 初始化计算增量值(个人血压信息)
  145. // 测量值当作平均值
  146. systolicAvg = bp.SystolicValue;
  147. diastolicAvg = bp.DiastolicValue;
  148. systolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
  149. diastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
  150. #region 更新 gps_persoon remarks 下发增量值到iot
  151. // 更新
  152. remarkFlag = await _serviceIotWebApi.UpdatePersonRemarksAsync(bp.Serialno, (int)systolicRefValue!, (int)diastolicRefValue!, systolicInc, diastolicInc).ConfigureAwait(false);
  153. if (remarkFlag)
  154. {
  155. _logger.LogInformation($"{nameof(BloodpressResolver)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
  156. // 启血压标定值下发开关
  157. if (_configBoodPressResolver.EnableBPRefPush)
  158. {
  159. // 下推
  160. BloodPressCalibrationConfigModel bpIncData = new()
  161. {
  162. Imei = bp.Serialno,
  163. SystolicRefValue = (int)systolicRefValue!, //收缩压标定值,值为0 表示不生效
  164. DiastolicRefValue = (int)diastolicRefValue!, //舒张压标定值,值为0表示不生效
  165. SystolicIncValue = systolicInc, //收缩压显示增量,值为0 表示不生效
  166. DiastolicIncValue = diastolicInc //舒张压显示增量,值为0 表示不生效
  167. };
  168. // 下发 IOT 增量值
  169. var flagIot = await _serviceIotWebApi.SetBloodPressCalibrationConfigAsync(bpIncData).ConfigureAwait(false);
  170. if (flagIot)
  171. {
  172. startTime = (DateTime)bp.LastUpdate!;
  173. endTime = DateTime.Now;
  174. #region 保存下推记录 stb_hm_bp_push_ref_inc_value
  175. sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{bp.Serialno.Substring(bp.Serialno.Length - 2)} " +
  176. $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
  177. $"TAGS ('{bp.Serialno.Substring(bp.Serialno.Length - 2)}') " +
  178. $"VALUES(" +
  179. $"'{endTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  180. $"'{bp.Serialno}'," +
  181. $"{systolicRefValue}," +
  182. $"{diastolicRefValue}," +
  183. $"{systolicInc}," +
  184. $"{diastolicInc}," +
  185. $"{true}," +
  186. $"{systolicAvg}," +
  187. $"{diastolicAvg}," +
  188. $"{systolicAvgOffset}," +
  189. $"{diastolicAvgOffset}," +
  190. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  191. $"'{endTime:yyyy-MM-dd HH:mm:ss.fff}'" +
  192. $")";
  193. _serviceTDengine.ExecuteInsertSQL(sql);
  194. #endregion
  195. }
  196. }
  197. }
  198. #endregion
  199. #endregion
  200. }
  201. else
  202. {
  203. #region (暂时取消)正常计算增量值
  204. /**
  205. // var lastPush = await _serviceTDengine.GetLastAsync("stb_hm_bp_push_ref_inc_value", $"serialno='{bp.Serialno}' order by ts desc");
  206. var lastPushResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bp_push_ref_inc_value", $"serialno='{bp.Serialno}' order by ts desc", "last_row(*)");
  207. if (lastPushResponse == null)
  208. {
  209. return;
  210. }
  211. var lastPushParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressurePushRefIncModel>>(lastPushResponse);
  212. var lastPush = lastPushParser!.Select().FirstOrDefault();
  213. //var ts = last?[0];
  214. // 曾经有下发记录
  215. if (lastPushParser?.Rows != 0)
  216. {
  217. // 重置设备,取正常值标定值
  218. if (
  219. lastPush!.SystolicRefValue == 0
  220. && lastPush!.DiastolicRefValue == 0
  221. && lastPush!.SystolicIncValue == 0
  222. && lastPush!.DiastolicIncValue == 0
  223. )
  224. {
  225. systolicRefValue = bpRef!.Systolic;//?
  226. diastolicRefValue = bpRef!.Diastolic;//?
  227. }
  228. // 取最后一条下推的标定值
  229. else
  230. {
  231. systolicRefValue = lastPush!.SystolicRefValue;
  232. diastolicRefValue = lastPush!.DiastolicRefValue;
  233. }
  234. duration = SafeType.SafeInt64(((DateTime)bp.LastUpdate! - lastPush!.Timestamp).TotalMilliseconds);
  235. lastPushSystolicInc = lastPush!.SystolicIncValue;
  236. lastPushDiastolicInc = lastPush!.DiastolicIncValue;
  237. }
  238. TimeSpan ts = TimeSpan.FromMilliseconds(duration);
  239. // 获取历史数据
  240. ////DateTime now = DateTime.Now;
  241. //DateTime now = (DateTime)bp.LastUpdate!; //测试
  242. //DateTime startTime = now.AddDays(-duration);
  243. //DateTime endTime = now;
  244. endTime = (DateTime)bp.LastUpdate!; //测试
  245. startTime = endTime - ts;
  246. var condition = $"ts between '{startTime:yyyy-MM-dd HH:mm:ss.fff}' and '{endTime:yyyy-MM-dd HH:mm:ss.fff}' and serialno='{bp.Serialno}'";
  247. var hmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition);
  248. var hmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(hmBpResponse!);
  249. var hmBp = hmBpParser?.Select();
  250. if (hmBp?.ToList().Count < 2)
  251. {
  252. _logger.LogInformation($"{bp.Serialno} 数据值不足");
  253. return;
  254. }
  255. // 最大值
  256. systolicMax = (int)hmBpParser?.Select(i => i.SystolicValue).Max()!;
  257. diastolicMax = (int)hmBpParser?.Select(i => i.DiastolicValue).Max()!;
  258. // 最小值
  259. systolicMin = (int)hmBpParser?.Select(i => i.SystolicValue).Min()!;
  260. diastolicMin = (int)hmBpParser?.Select(i => i.DiastolicValue).Min()!;
  261. // 计算去除最大值和最小值和异常值的平均值
  262. //var systolicAvg = await _serviceTDengine.GetAvgExceptMaxMinValueAsync("systolic_value", "stb_hm_bloodpress", $"ts>='{startTime:yyyy-MM-dd HH:mm:ss.fff}' and ts <='{endTime:yyyy-MM-dd HH:mm:ss.fff}' and serialno='{bp.Serialno}' and systolic_value < {systolicRefValue} ");
  263. //var diastolicAvg = await _serviceTDengine.GetAvgExceptMaxMinValueAsync("diastolic_value", "stb_hm_bloodpress", $"ts>='{startTime:yyyy-MM-dd HH:mm:ss.fff}' and ts <='{endTime:yyyy-MM-dd HH:mm:ss.fff}' and serialno='{bp.Serialno}' and diastolic_value < {diastolicRefValue}");
  264. systolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.SystolicValue, SafeType.SafeInt(systolicRefValue!)))!;
  265. diastolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.DiastolicValue, SafeType.SafeInt(diastolicRefValue!)))!;
  266. if (systolicAvg.Equals(0) || diastolicAvg.Equals(0))
  267. {
  268. _logger.LogWarning($"{bp.Serialno} 历史数据{startTime}---{endTime}除最大值和最小值和异常值的平均值为0,使用测试量当做平均值");
  269. systolicAvg = bp.SystolicValue;
  270. diastolicAvg = bp.DiastolicValue;
  271. }
  272. //var systolicAvg = _serviceTDengine.GetAvgExceptMaxMinValue("systolic_value", "hm_bloodpress", $"ts>='{startTime:yyyy-MM-dd HH:mm:ss.fff}' and ts <='{endTime:yyyy-MM-dd HH:mm:ss.fff}' and serialno='{bp.Serialno}' and systolic_value < {systolicRefValue} ");
  273. //var diastolicAvg = _serviceTDengine.GetAvgExceptMaxMinValue("diastolic_value", "hm_bloodpress", $"ts>='{startTime:yyyy-MM-dd HH:mm:ss.fff}' and ts <='{endTime:yyyy-MM-dd HH:mm:ss.fff}' and serialno='{bp.Serialno}' and diastolic_value < {diastolicRefValue}");
  274. // 增量值=(标定值-平均值)* 0.25
  275. var currentSystolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
  276. var currentDiastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
  277. // 累计增量
  278. systolicInc = currentSystolicInc + lastPushSystolicInc;
  279. diastolicInc = currentDiastolicInc + lastPushDiastolicInc;
  280. */
  281. #endregion
  282. }
  283. #region (暂时取消)插入BP增量值 hm_bloodpress_stats_inc
  284. // 自动建表
  285. /** sql = $"INSERT INTO health_monitor.hm_bp_stats_inc_{bp.Serialno.Substring(bp.Serialno.Length - 2)} " +
  286. $"USING health_monitor.stb_hm_bloodpress_stats_inc " +
  287. $"TAGS ('{bp.Serialno.Substring(bp.Serialno.Length - 2)}') " +
  288. $"VALUES(" +
  289. $"'{bp.LastUpdate:yyyy-MM-dd HH:mm:ss.fff}'," +
  290. $"'{bp.BloodPressId}'," +
  291. $"'{bp.MessageId}'," +
  292. $"'{bp.Serialno}'," +
  293. $"{bp.SystolicValue}," +
  294. $"{systolicRefValue}," +
  295. $"{systolicAvg}," +
  296. $"{systolicMax}," +
  297. $"{systolicMin}," +
  298. $"{systolicAvgOffset}," +
  299. $"{systolicInc}," +
  300. $"{bp.DiastolicValue}," +
  301. $"{diastolicRefValue}," +
  302. $"{diastolicAvg}," +
  303. $"{diastolicMax}," +
  304. $"{diastolicMin}," +
  305. $"{diastolicAvgOffset}," +
  306. $"{diastolicInc}," +
  307. $"{gender}," +
  308. $"{age}," +
  309. $"{height}," +
  310. $"{weight}," +
  311. $"'{bp.LastUpdate:yyyy-MM-dd HH:mm:ss.fff}'," +
  312. $"{duration}," +
  313. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  314. $"'{endTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  315. $"'{string.Empty}'," +
  316. $"{isHypertension})";
  317. _serviceTDengine.ExecuteInsertSQL(sql);
  318. */
  319. // 发送到 设置设备血压标定参数
  320. #endregion
  321. #region 定时下发触发器
  322. var key = $"health_moniter/schedule_push/imei/{bp.Serialno}";
  323. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  324. if (string.IsNullOrWhiteSpace(schedule_push))
  325. {
  326. // 注册首次下推
  327. #if DEBUG
  328. // await _serviceEtcd.PutValAsync(key, result, 60*1, false).ConfigureAwait(false);
  329. var interval = 0;
  330. // 获取当前时间
  331. DateTime now = DateTime.Now;
  332. // 计算距离下一个$interval天后的8点的时间间隔
  333. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 1, 58).AddDays(interval);
  334. TimeSpan timeUntilNextRun = nextRunTime - now;
  335. // 如果当前时间已经超过了8点,将等待到明天后的8点
  336. if (timeUntilNextRun < TimeSpan.Zero)
  337. {
  338. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  339. nextRunTime += timeUntilNextRun;
  340. }
  341. var ttl = (long)timeUntilNextRun.TotalSeconds;
  342. var data = new
  343. {
  344. imei = bp.Serialno,
  345. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  346. ttl,
  347. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  348. };
  349. var result = JsonConvert.SerializeObject(data);
  350. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  351. #else
  352. //DateTime sNow = DateTime.Now;
  353. //// 计算距离19:59:55点的时间间隔
  354. //TimeSpan timeUntil = new DateTime(sNow.Year, sNow.Month, sNow.Day, 19, 59, 55) - sNow;
  355. //// 如果当前时间已经超过了12点,将等待到明天
  356. //if (timeUntil < TimeSpan.Zero)
  357. //{
  358. // timeUntil = timeUntil.Add(TimeSpan.FromHours(24));
  359. //}
  360. //var ttl = (long)timeUntil.TotalSeconds;
  361. var interval = 0;
  362. // 获取当前时间
  363. DateTime now = DateTime.Now;
  364. // 计算距离下一个$interval天后的8点的时间间隔
  365. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 19, 59, 58).AddDays(interval);
  366. TimeSpan timeUntilNextRun = nextRunTime - now;
  367. // 如果当前时间已经超过了8点,将等待到明天后的8点
  368. if (timeUntilNextRun < TimeSpan.Zero)
  369. {
  370. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  371. nextRunTime += timeUntilNextRun;
  372. }
  373. var ttl =(long)timeUntilNextRun.TotalSeconds;
  374. var data = new
  375. {
  376. imei = bp.Serialno,
  377. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  378. ttl,
  379. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  380. };
  381. var result = JsonConvert.SerializeObject(data);
  382. await _serviceEtcd.PutValAsync(key, result,ttl, false).ConfigureAwait(false);
  383. #endif
  384. }
  385. #endregion
  386. }
  387. catch (Exception ex)
  388. {
  389. _logger.LogError($"解析血压出错, {ex.Message}\n{ex.StackTrace}");
  390. }
  391. }
  392. }
  393. }