Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

488 linhas
24KB

  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("验证个人信息,找不到个人信息,跳过此消息");
  121. return;
  122. }
  123. // 验证年龄是否在范围 (2 - 120)
  124. var age = SafeType.SafeInt(DateTime.Today.Year - person?.Person.BornDate!.Value.Year!);
  125. if (age < 1 || age > 120)
  126. {
  127. _logger.LogWarning("验证年龄,不在范围 (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. #region 初始化计算增量值(个人血压信息)
  144. // 测量值当作平均值
  145. systolicAvg = bp.SystolicValue;
  146. diastolicAvg = bp.DiastolicValue;
  147. systolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
  148. diastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
  149. #region 更新 gps_persoon remarks 下发增量值到iot
  150. // 更新
  151. remarkFlag = await _serviceIotWebApi.UpdatePersonRemarksAsync(bp.Serialno, (int)systolicRefValue!, (int)diastolicRefValue!, systolicInc, diastolicInc).ConfigureAwait(false);
  152. if (remarkFlag)
  153. {
  154. _logger.LogInformation($"{nameof(BloodpressResolver)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
  155. // 启血压标定值下发开关
  156. if (_configBoodPressResolver.EnableBPRefPush)
  157. {
  158. // 下推
  159. BloodPressCalibrationConfigModel bpIncData = new()
  160. {
  161. Imei = bp.Serialno,
  162. SystolicRefValue = (int)systolicRefValue!, //收缩压标定值,值为0 表示不生效
  163. DiastolicRefValue = (int)diastolicRefValue!, //舒张压标定值,值为0表示不生效
  164. SystolicIncValue = systolicInc, //收缩压显示增量,值为0 表示不生效
  165. DiastolicIncValue = diastolicInc //舒张压显示增量,值为0 表示不生效
  166. };
  167. // 下发 IOT 增量值
  168. var flagIot = await _serviceIotWebApi.SetBloodPressCalibrationConfigAsync(bpIncData).ConfigureAwait(false);
  169. if (flagIot)
  170. {
  171. startTime = (DateTime)bp.LastUpdate!;
  172. endTime = DateTime.Now;
  173. #region 保存下推记录 stb_hm_bp_push_ref_inc_value
  174. sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{bp.Serialno.Substring(bp.Serialno.Length - 2)} " +
  175. $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
  176. $"TAGS ('{bp.Serialno.Substring(bp.Serialno.Length - 2)}') " +
  177. $"VALUES(" +
  178. $"'{endTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  179. $"'{bp.Serialno}'," +
  180. $"{systolicRefValue}," +
  181. $"{diastolicRefValue}," +
  182. $"{systolicInc}," +
  183. $"{diastolicInc}," +
  184. $"{true}," +
  185. $"{systolicAvg}," +
  186. $"{diastolicAvg}," +
  187. $"{systolicAvgOffset}," +
  188. $"{diastolicAvgOffset}," +
  189. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  190. $"'{endTime:yyyy-MM-dd HH:mm:ss.fff}'" +
  191. $")";
  192. _serviceTDengine.ExecuteInsertSQL(sql);
  193. #endregion
  194. }
  195. }
  196. }
  197. #endregion
  198. #endregion
  199. }
  200. else
  201. {
  202. #region 正常计算增量值
  203. // var lastPush = await _serviceTDengine.GetLastAsync("stb_hm_bp_push_ref_inc_value", $"serialno='{bp.Serialno}' order by ts desc");
  204. var lastPushResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bp_push_ref_inc_value", $"serialno='{bp.Serialno}' order by ts desc", "last_row(*)");
  205. if (lastPushResponse == null)
  206. {
  207. return;
  208. }
  209. var lastPushParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressurePushRefIncModel>>(lastPushResponse);
  210. var lastPush = lastPushParser!.Select().FirstOrDefault();
  211. //var ts = last?[0];
  212. // 曾经有下发记录
  213. if (lastPushParser?.Rows != 0)
  214. {
  215. // 重置设备,取正常值标定值
  216. if (
  217. lastPush!.SystolicRefValue == 0
  218. && lastPush!.DiastolicRefValue == 0
  219. && lastPush!.SystolicIncValue == 0
  220. && lastPush!.DiastolicIncValue == 0
  221. )
  222. {
  223. systolicRefValue = bpRef!.Systolic;//?
  224. diastolicRefValue = bpRef!.Diastolic;//?
  225. }
  226. // 取最后一条下推的标定值
  227. else
  228. {
  229. systolicRefValue = lastPush!.SystolicRefValue;
  230. diastolicRefValue = lastPush!.DiastolicRefValue;
  231. }
  232. duration = SafeType.SafeInt64(((DateTime)bp.LastUpdate! - lastPush!.Timestamp).TotalMilliseconds);
  233. lastPushSystolicInc = lastPush!.SystolicIncValue;
  234. lastPushDiastolicInc = lastPush!.DiastolicIncValue;
  235. }
  236. TimeSpan ts = TimeSpan.FromMilliseconds(duration);
  237. // 获取历史数据
  238. ////DateTime now = DateTime.Now;
  239. //DateTime now = (DateTime)bp.LastUpdate!; //测试
  240. //DateTime startTime = now.AddDays(-duration);
  241. //DateTime endTime = now;
  242. endTime = (DateTime)bp.LastUpdate!; //测试
  243. startTime = endTime - ts;
  244. 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}'";
  245. var hmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition);
  246. var hmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(hmBpResponse!);
  247. var hmBp = hmBpParser?.Select();
  248. if (hmBp?.ToList().Count < 2)
  249. {
  250. _logger.LogInformation($"{bp.Serialno} 数据值不足");
  251. return;
  252. }
  253. // 最大值
  254. systolicMax = (int)hmBpParser?.Select(i => i.SystolicValue).Max()!;
  255. diastolicMax = (int)hmBpParser?.Select(i => i.DiastolicValue).Max()!;
  256. // 最小值
  257. systolicMin = (int)hmBpParser?.Select(i => i.SystolicValue).Min()!;
  258. diastolicMin = (int)hmBpParser?.Select(i => i.DiastolicValue).Min()!;
  259. // 计算去除最大值和最小值和异常值的平均值
  260. //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} ");
  261. //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}");
  262. systolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.SystolicValue, SafeType.SafeInt(systolicRefValue!)))!;
  263. diastolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.DiastolicValue, SafeType.SafeInt(diastolicRefValue!)))!;
  264. if (systolicAvg.Equals(0) || diastolicAvg.Equals(0))
  265. {
  266. _logger.LogWarning($"{bp.Serialno} 历史数据{startTime}---{endTime}除最大值和最小值和异常值的平均值为0,使用测试量当做平均值");
  267. systolicAvg = bp.SystolicValue;
  268. diastolicAvg = bp.DiastolicValue;
  269. /*
  270. systolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
  271. diastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
  272. // 初始化 remark
  273. remarkFlag = await _serviceIotWebApi.UpdatePersonRemarksAsync(bp.Serialno, (int)systolicRefValue!, (int)diastolicRefValue!, systolicInc, diastolicInc).ConfigureAwait(false);
  274. if (remarkFlag)
  275. {
  276. // 下推
  277. BloodPressCalibrationConfigModel bpIncData = new()
  278. {
  279. Imei = bp.Serialno,
  280. SystolicRefValue = (int)systolicRefValue!, //收缩压标定值,值为0 表示不生效
  281. DiastolicRefValue = (int)diastolicRefValue!, //舒张压标定值,值为0表示不生效
  282. SystolicIncValue = systolicInc, //收缩压显示增量,值为0 表示不生效
  283. DiastolicIncValue = diastolicInc //舒张压显示增量,值为0 表示不生效
  284. };
  285. // 下发 IOT 增量值
  286. var flagIot = await _serviceIotWebApi.SetBloodPressCalibrationConfigAsync(bpIncData).ConfigureAwait(false);
  287. if (flagIot)
  288. {
  289. #region 保存下推记录 stb_hm_bp_push_ref_inc_value
  290. sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{bp.Serialno.Substring(bp.Serialno.Length - 2)} " +
  291. $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
  292. $"TAGS ('{bp.Serialno.Substring(bp.Serialno.Length - 2)}') " +
  293. $"VALUES(" +
  294. $"'{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}'," +
  295. $"'{bp.Serialno}'," +
  296. $"{systolicRefValue}," +
  297. $"{diastolicRefValue}," +
  298. $"{systolicInc}," +
  299. $"{diastolicInc}," +
  300. $"{true})";
  301. _serviceTDengine.ExecuteInsertSQL(sql);
  302. #endregion
  303. }
  304. }
  305. return;
  306. */
  307. }
  308. //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} ");
  309. //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}");
  310. // 增量值=(标定值-平均值)* 0.25
  311. var currentSystolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
  312. var currentDiastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
  313. // 累计增量
  314. systolicInc = currentSystolicInc + lastPushSystolicInc;
  315. diastolicInc = currentDiastolicInc + lastPushDiastolicInc;
  316. #endregion
  317. }
  318. #region 插入BP增量值 hm_bloodpress_stats_inc
  319. // 自动建表
  320. sql = $"INSERT INTO health_monitor.hm_bp_stats_inc_{bp.Serialno.Substring(bp.Serialno.Length - 2)} " +
  321. $"USING health_monitor.stb_hm_bloodpress_stats_inc " +
  322. $"TAGS ('{bp.Serialno.Substring(bp.Serialno.Length - 2)}') " +
  323. $"VALUES(" +
  324. $"'{bp.LastUpdate:yyyy-MM-dd HH:mm:ss.fff}'," +
  325. $"'{bp.BloodPressId}'," +
  326. $"'{bp.MessageId}'," +
  327. $"'{bp.Serialno}'," +
  328. $"{bp.SystolicValue}," +
  329. $"{systolicRefValue}," +
  330. $"{systolicAvg}," +
  331. $"{systolicMax}," +
  332. $"{systolicMin}," +
  333. $"{systolicAvgOffset}," +
  334. $"{systolicInc}," +
  335. $"{bp.DiastolicValue}," +
  336. $"{diastolicRefValue}," +
  337. $"{diastolicAvg}," +
  338. $"{diastolicMax}," +
  339. $"{diastolicMin}," +
  340. $"{diastolicAvgOffset}," +
  341. $"{diastolicInc}," +
  342. $"{gender}," +
  343. $"{age}," +
  344. $"{height}," +
  345. $"{weight}," +
  346. $"'{bp.LastUpdate:yyyy-MM-dd HH:mm:ss.fff}'," +
  347. $"{duration}," +
  348. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  349. $"'{endTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  350. $"'{string.Empty}'," +
  351. $"{isHypertension})";
  352. _serviceTDengine.ExecuteInsertSQL(sql);
  353. // 发送到 设置设备血压标定参数
  354. #endregion
  355. #region 定时下发触发器
  356. var key = $"health_moniter/schedule_push/imei/{bp.Serialno}";
  357. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  358. if (string.IsNullOrWhiteSpace(schedule_push))
  359. {
  360. // 注册首次下推
  361. #if DEBUG
  362. // await _serviceEtcd.PutValAsync(key, result, 60*1, false).ConfigureAwait(false);
  363. var interval = 0;
  364. // 获取当前时间
  365. DateTime now = DateTime.Now;
  366. // 计算距离下一个$interval天后的8点的时间间隔
  367. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 1, 58).AddDays(interval);
  368. TimeSpan timeUntilNextRun = nextRunTime - now;
  369. // 如果当前时间已经超过了8点,将等待到明天后的8点
  370. if (timeUntilNextRun < TimeSpan.Zero)
  371. {
  372. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  373. nextRunTime += timeUntilNextRun;
  374. }
  375. var ttl = (long)timeUntilNextRun.TotalSeconds;
  376. var data = new
  377. {
  378. imei = bp.Serialno,
  379. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  380. ttl,
  381. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  382. };
  383. var result = JsonConvert.SerializeObject(data);
  384. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  385. #else
  386. //DateTime sNow = DateTime.Now;
  387. //// 计算距离19:59:55点的时间间隔
  388. //TimeSpan timeUntil = new DateTime(sNow.Year, sNow.Month, sNow.Day, 19, 59, 55) - sNow;
  389. //// 如果当前时间已经超过了12点,将等待到明天
  390. //if (timeUntil < TimeSpan.Zero)
  391. //{
  392. // timeUntil = timeUntil.Add(TimeSpan.FromHours(24));
  393. //}
  394. //var ttl = (long)timeUntil.TotalSeconds;
  395. var interval = 0;
  396. // 获取当前时间
  397. DateTime now = DateTime.Now;
  398. // 计算距离下一个$interval天后的8点的时间间隔
  399. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 19, 59, 58).AddDays(interval);
  400. TimeSpan timeUntilNextRun = nextRunTime - now;
  401. // 如果当前时间已经超过了8点,将等待到明天后的8点
  402. if (timeUntilNextRun < TimeSpan.Zero)
  403. {
  404. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  405. nextRunTime += timeUntilNextRun;
  406. }
  407. var ttl =(long)timeUntilNextRun.TotalSeconds;
  408. var data = new
  409. {
  410. imei = bp.Serialno,
  411. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  412. ttl,
  413. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  414. };
  415. var result = JsonConvert.SerializeObject(data);
  416. await _serviceEtcd.PutValAsync(key, result,ttl, false).ConfigureAwait(false);
  417. #endif
  418. }
  419. #endregion
  420. }
  421. catch (Exception ex)
  422. {
  423. _logger.LogError($"解析血压出错, {ex.Message}\n{ex.StackTrace}");
  424. }
  425. }
  426. }
  427. }