|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534 |
-
- using HealthMonitor.Common;
- using HealthMonitor.Common.helper;
- using HealthMonitor.Service.Biz.db;
- using HealthMonitor.Service.Cache;
- using HealthMonitor.Service.Etcd;
- using HealthMonitor.Service.Resolver.Interface;
- using HealthMonitor.Service.Sub;
- using HealthMonitor.Service.Sub.Topic.Model;
- using Microsoft.EntityFrameworkCore.Metadata;
- using Microsoft.Extensions.Logging;
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.Data.Common;
- using System.Linq;
- using System.Text;
- using System.Text.Json.Serialization;
- using System.Threading.Tasks;
- using TDengineTMQ;
- using TelpoDataService.Util.Entities.GpsCard;
- using TelpoDataService.Util;
- using TelpoDataService.Util.Entities.GpsLocationHistory;
- using HealthMonitor.Service.Biz;
- using HealthMonitor.Model.Service;
- using Microsoft.Extensions.Options;
- using HealthMonitor.Model.Config;
- using HealthMonitor.Model.Service.Mapper;
- using Mvccpb;
-
- namespace HealthMonitor.Service.Resolver
- {
-
- public class BloodpressResolver: IResolver
- {
- private readonly ILogger<BloodpressResolver> _logger;
- private readonly BoodPressResolverConfig _configBoodPressResolver;
- private readonly PersonCacheManager _personCacheMgr;
- private readonly TDengineService _serviceTDengine;
- private readonly BloodPressReferenceValueCacheManager _bpRefValCacheManager;
-
- private readonly HttpHelper _httpHelper = default!;
-
- private readonly GpsCardAccessorClient<GpsPerson> _gpsPersonApiClient;
- private readonly IotWebApiService _serviceIotWebApi;
-
- private readonly AsyncLocal<string> _messageId = new();
- private readonly AsyncLocal<HisGpsBloodPress> _msgData = new();
-
- private readonly EtcdService _serviceEtcd;
-
- public BloodpressResolver(
- TDengineService serviceDengine,
- BloodPressReferenceValueCacheManager bpRefValCacheManager,
- PersonCacheManager personCacheMgr, HttpHelper httpHelper,
- GpsCardAccessorClient<GpsPerson> gpsPersonApiClient,
- IotWebApiService iotWebApiService,
- EtcdService serviceEtcd,
- IOptions<BoodPressResolverConfig> optionBoodPressResolver,
- ILogger<BloodpressResolver> logger)
- {
- _httpHelper = httpHelper;
- _serviceTDengine = serviceDengine;
- _bpRefValCacheManager = bpRefValCacheManager;
- _gpsPersonApiClient = gpsPersonApiClient;
- _serviceIotWebApi = iotWebApiService;
- _logger = logger;
- _personCacheMgr = personCacheMgr;
- _serviceEtcd = serviceEtcd;
- _configBoodPressResolver= optionBoodPressResolver.Value;
-
- }
-
- public void SetResolveInfo(PackageMsgModel msg)
- {
- var topicHmBloodPress = JsonConvert.DeserializeObject<TopicHmBloodPress>(msg.DetailData.ToString()!);
- _messageId.Value = msg.MessageId;
- _msgData.Value = new HisGpsBloodPress()
- {
- BloodPressId = topicHmBloodPress!.BloodPressId,
- MessageId = topicHmBloodPress!.MessageId,
- Serialno= topicHmBloodPress!.Serialno,
- SystolicValue = topicHmBloodPress!.SystolicValue,
- DiastolicValue= topicHmBloodPress!.DiastolicValue,
- LastUpdate= DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmBloodPress.LastUpdate) / 1000000),
- CreateTime= DateTimeUtil.GetDateTimeFromUnixTimeMilliseconds(SafeType.SafeInt64(topicHmBloodPress.CreateTime) / 1000000),
- Method= topicHmBloodPress!.Method,
- IsDisplay=topicHmBloodPress!.IsDisplay ? 1 : 0
- };
- }
-
- public override string ToString()
- {
- return $"{nameof(BloodpressResolver)}[{_messageId.Value}]";
- }
-
- public async Task ExecuteMessageAsync()
- {
- try
- {
- var messageId = _messageId.Value;
- var bp = _msgData.Value!;
-
- int systolicRefValue;
- int diastolicRefValue;
- int systolicInc;
- int diastolicInc;
- decimal systolicAvg;
- decimal diastolicAvg;
-
- int systolicMax = 0;
- int diastolicMax = 0;
-
- int systolicMin = 0;
- int diastolicMin = 0;
-
-
- var avgOffset = 0.25M;
- var systolicAvgOffset = avgOffset;
- var diastolicAvgOffset = avgOffset;
-
- DateTime endTime = DateTime.Now;
- DateTime startTime = DateTime.Now;
-
-
-
-
- bool remarkFlag = false;
-
- string sql = string.Empty;
-
- #region 获取个人信息
-
- var person = await _personCacheMgr.GetDeviceGpsPersonCacheBySerialNoAsync(bp.MessageId, bp.Serialno).ConfigureAwait(false);
-
- if (person == null || person?.Person.BornDate == null)
- {
- _logger.LogWarning($"{bp.Serialno}--{bp.MessageId} 验证个人信息,找不到个人信息,跳过此消息");
- return;
- }
-
- var age = SafeType.SafeInt(DateTime.Today.Year - person?.Person.BornDate!.Value.Year!);
- if (age < 2 || age > 120)
- {
- _logger.LogWarning($"{bp.Serialno}--{bp.MessageId} 验证年龄,不在范围 (2 - 120)岁,跳过此消息");
- return;
- }
-
- var gender = person?.Person.Gender == true ? 1 : 2;
- var isHypertension = SafeType.SafeBool(person?.Person.Ishypertension!);
- var height = SafeType.SafeDouble(person?.Person.Height!);
- var weight = SafeType.SafeDouble(person?.Person.Weight!);
-
- #endregion
-
- #region 初始化常规血压标定值标定值
- var bpRef = await _bpRefValCacheManager.GetBloodPressReferenceValueAsync(age, gender, isHypertension);
- systolicRefValue = bpRef!.Systolic;
- diastolicRefValue = bpRef!.Diastolic;
- #endregion
- _logger.LogInformation($"{bp.Serialno} -- Person 值:{JsonConvert.SerializeObject(person)}");
- _logger.LogInformation($"{bp.Serialno} -- Person Remarks 值:{person?.Person.Remarks}");
- if (string.IsNullOrWhiteSpace(person?.Person.Remarks))
- {
- _logger.LogInformation($"{bp.Serialno},设备解绑后绑定,首次手工测量了血压值,下发年龄标定值和增量值(测量值=平均值计算得出的)");
- #region 初始化计算增量值(个人血压信息)
-
- systolicAvg = bp.SystolicValue;
- diastolicAvg = bp.DiastolicValue;
- systolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
- diastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
-
- #region 更新 gps_persoon remarks 下发增量值到iot
-
- remarkFlag = await _serviceIotWebApi.UpdatePersonRemarksAsync(bp.Serialno, (int)systolicRefValue!, (int)diastolicRefValue!, systolicInc, diastolicInc).ConfigureAwait(false);
- if (remarkFlag)
- {
- _logger.LogInformation($"{nameof(BloodpressResolver)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
-
- if (_configBoodPressResolver.EnableBPRefPush)
- {
-
- BloodPressCalibrationConfigModel bpIncData = new()
- {
- Imei = bp.Serialno,
- SystolicRefValue = (int)systolicRefValue!,
- DiastolicRefValue = (int)diastolicRefValue!,
- SystolicIncValue = systolicInc,
- DiastolicIncValue = diastolicInc
- };
-
-
-
- var response = await _serviceIotWebApi.SetBloodPressCalibrationConfig2Async(bpIncData).ConfigureAwait(false);
- var flagIot = response.Flag;
- if (flagIot)
- {
- startTime = (DateTime)bp.LastUpdate!;
- endTime = DateTime.Now;
- #region 保存下推记录 stb_hm_bp_push_ref_inc_value
- sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{bp.Serialno.Substring(bp.Serialno.Length - 2)} " +
- $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
- $"TAGS ('{bp.Serialno.Substring(bp.Serialno.Length - 2)}') " +
- $"VALUES(" +
- $"'{endTime:yyyy-MM-dd HH:mm:ss.fff}'," +
- $"'{bp.Serialno}'," +
- $"{systolicRefValue}," +
- $"{diastolicRefValue}," +
- $"{systolicInc}," +
- $"{diastolicInc}," +
- $"{true}," +
- $"{systolicAvg}," +
- $"{diastolicAvg}," +
- $"{systolicAvgOffset}," +
- $"{diastolicAvgOffset}," +
- $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
- $"'{endTime:yyyy-MM-dd HH:mm:ss.fff}'" +
- $")";
-
- _serviceTDengine.ExecuteInsertSQL(sql);
- #endregion
- }
- }
-
- }
-
- #endregion
-
- #endregion
- }
- else if (person.Person.Remarks.Contains("lastPushRefValue"))
- {
- _logger.LogInformation($"{bp.Serialno},有新标定值(lastPushRefValue),使用最近一次下推的标定值和增量值(测量值=平均值计算得出的)");
- var lastPushResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bp_push_ref_inc_value", $"serialno='{bp.Serialno}' order by ts desc", "last_row(*)");
- var lastPushParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressurePushRefIncModel>>(lastPushResponse!);
- var lastPush = lastPushParser!.Select().FirstOrDefault();
-
- var lastPushSystolicRefValue = lastPush!.SystolicRefValue;
- var lastPushDiastolicRefValue = lastPush!.DiastolicRefValue;
-
-
-
- systolicRefValue = lastPushSystolicRefValue;
- diastolicRefValue = lastPushDiastolicRefValue;
-
-
- systolicAvg = bp.SystolicValue;
- diastolicAvg = bp.DiastolicValue;
-
-
-
- systolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
- diastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
- #region 更新 gps_persoon remarks 下发增量值到iot
-
- remarkFlag = await _serviceIotWebApi.UpdatePersonRemarksAsync(bp.Serialno, (int)systolicRefValue!, (int)diastolicRefValue!, systolicInc, diastolicInc).ConfigureAwait(false);
- if (remarkFlag)
- {
- _logger.LogInformation($"{nameof(BloodpressResolver)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
-
- if (_configBoodPressResolver.EnableBPRefPush)
- {
-
- BloodPressCalibrationConfigModel bpIncData = new()
- {
- Imei = bp.Serialno,
- SystolicRefValue = (int)systolicRefValue!,
- DiastolicRefValue = (int)diastolicRefValue!,
- SystolicIncValue = systolicInc,
- DiastolicIncValue = diastolicInc
- };
-
-
- var response = await _serviceIotWebApi.SetBloodPressCalibrationConfig2Async(bpIncData).ConfigureAwait(false);
- var flagIot = response.Flag;
- if (flagIot)
- {
- startTime = (DateTime)bp.LastUpdate!;
- endTime = DateTime.Now;
- #region 保存下推记录 stb_hm_bp_push_ref_inc_value
- sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{bp.Serialno.Substring(bp.Serialno.Length - 2)} " +
- $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
- $"TAGS ('{bp.Serialno.Substring(bp.Serialno.Length - 2)}') " +
- $"VALUES(" +
- $"'{endTime:yyyy-MM-dd HH:mm:ss.fff}'," +
- $"'{bp.Serialno}'," +
- $"{systolicRefValue}," +
- $"{diastolicRefValue}," +
- $"{systolicInc}," +
- $"{diastolicInc}," +
- $"{true}," +
- $"{systolicAvg}," +
- $"{diastolicAvg}," +
- $"{systolicAvgOffset}," +
- $"{diastolicAvgOffset}," +
- $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
- $"'{endTime:yyyy-MM-dd HH:mm:ss.fff}'" +
- $")";
-
- _serviceTDengine.ExecuteInsertSQL(sql);
- #endregion
- }
- }
-
- }
-
- #endregion
- }
- else
- {
- #region (暂时取消)正常计算增量值
-
-
- #endregion
- }
-
- #region (暂时取消)插入BP增量值 hm_bloodpress_stats_inc
-
-
-
-
-
- #endregion
-
- #region 定时下发触发器
- var key = $"health_moniter/schedule_push/imei/{bp.Serialno}";
- var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
- if (string.IsNullOrWhiteSpace(schedule_push))
- {
-
- #if DEBUG
-
-
- var interval = 0;
-
- DateTime now = DateTime.Now;
-
-
- DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 1, 58).AddDays(interval);
- TimeSpan timeUntilNextRun = nextRunTime - now;
-
-
- if (timeUntilNextRun < TimeSpan.Zero)
- {
- timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
- nextRunTime += timeUntilNextRun;
- }
- var ttl = (long)timeUntilNextRun.TotalSeconds;
- var data = new
- {
- imei = bp.Serialno,
- create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
- ttl,
- next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
- };
- var result = JsonConvert.SerializeObject(data);
- await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
-
- #else
-
-
-
-
-
-
-
-
-
-
-
-
-
- var interval = 0;
-
- DateTime now = DateTime.Now;
-
-
- DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 19, 59, 58).AddDays(interval);
- TimeSpan timeUntilNextRun = nextRunTime - now;
-
-
- if (timeUntilNextRun < TimeSpan.Zero)
- {
- timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
-
- nextRunTime += TimeSpan.FromDays(1);
- }
-
- var ttl =(long)timeUntilNextRun.TotalSeconds;
- var data = new
- {
- imei = bp.Serialno,
- create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
- ttl,
- next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
- };
- var result = JsonConvert.SerializeObject(data);
- await _serviceEtcd.PutValAsync(key, result,ttl, false).ConfigureAwait(false);
- #endif
-
- }
-
- #endregion
- }
- catch (Exception ex)
- {
-
- _logger.LogError($"解析血压出错, {ex.Message}\n{ex.StackTrace}");
- }
- }
- }
- }
|