Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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