Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

762 lines
45KB

  1. using dotnet_etcd;
  2. using Etcdserverpb;
  3. using Google.Protobuf.WellKnownTypes;
  4. using HealthMonitor.Common;
  5. using HealthMonitor.Common.helper;
  6. using HealthMonitor.Core.Common.Extensions;
  7. using HealthMonitor.Model.Config;
  8. using HealthMonitor.Model.Service;
  9. using HealthMonitor.Model.Service.Mapper;
  10. using HealthMonitor.Service.Biz;
  11. using HealthMonitor.Service.Biz.db;
  12. using HealthMonitor.Service.Cache;
  13. using HealthMonitor.Service.Etcd;
  14. using HealthMonitor.Service.Sub;
  15. using Microsoft.AspNetCore.Mvc.RazorPages;
  16. using Microsoft.EntityFrameworkCore.Metadata.Internal;
  17. using Microsoft.Extensions.Options;
  18. using Newtonsoft.Json;
  19. using Newtonsoft.Json.Linq;
  20. using System.Reflection;
  21. using System.Threading.Channels;
  22. using TDengineDriver;
  23. using TDengineTMQ;
  24. namespace HealthMonitor.WebApi
  25. {
  26. public class Worker : BackgroundService
  27. {
  28. private readonly ILogger<Worker> _logger;
  29. private readonly IServiceProvider _services;
  30. private readonly TDengineDataSubcribe _tdEngineDataSubcribe;
  31. private readonly PackageProcess _processor;
  32. private readonly TDengineService _serviceTDengine;
  33. private readonly EtcdService _serviceEtcd;
  34. private readonly HttpHelper _httpHelper = default!;
  35. private readonly IotWebApiService _serviceIotWebApi;
  36. private readonly BoodPressResolverConfig _configBoodPressResolver;
  37. private readonly BloodPressReferenceValueCacheManager _bpRefValCacheManager;
  38. private readonly PersonCacheManager _personCacheMgr;
  39. private CancellationTokenSource _tokenSource = default!;
  40. public Worker(ILogger<Worker> logger, IServiceProvider services, PersonCacheManager personCacheMgr, BloodPressReferenceValueCacheManager bpRefValCacheManager, IotWebApiService iotWebApiService, IOptions<BoodPressResolverConfig> optionBoodPressResolver, PackageProcess processor, TDengineDataSubcribe tdEngineDataSubcribe, TDengineService serviceDengine, HttpHelper httpHelper, EtcdService serviceEtcd)
  41. {
  42. _logger = logger;
  43. _tdEngineDataSubcribe = tdEngineDataSubcribe;
  44. _services = services;
  45. _serviceIotWebApi = iotWebApiService;
  46. _processor = processor;
  47. _serviceEtcd = serviceEtcd;
  48. _serviceTDengine = serviceDengine;
  49. _httpHelper = httpHelper;
  50. _configBoodPressResolver = optionBoodPressResolver.Value;
  51. _bpRefValCacheManager = bpRefValCacheManager;
  52. _personCacheMgr = personCacheMgr;
  53. }
  54. public override Task StartAsync(CancellationToken cancellationToken)
  55. {
  56. _logger.LogInformation("------StartAsync");
  57. _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  58. // 创建消费者
  59. // _tdEngineDataSubcribe.CreateConsumer();
  60. return base.StartAsync(cancellationToken);
  61. }
  62. public override Task StopAsync(CancellationToken cancellationToken)
  63. {
  64. _logger.LogInformation("------StopAsync");
  65. _tokenSource.Cancel(); //停止工作线程
  66. // 关闭消费者
  67. // _tdEngineDataSubcribe.CloseConsumer();
  68. return base.StopAsync(cancellationToken);
  69. }
  70. protected override Task ExecuteAsync(CancellationToken stoppingToken)
  71. {
  72. // var processor = _services.GetService<PackageProcess>();
  73. TaskFactory factory = new(_tokenSource.Token);
  74. factory.StartNew(async () =>
  75. {
  76. if (_tokenSource.IsCancellationRequested)
  77. _logger.LogWarning("Worker exit");
  78. _logger.LogInformation("------ResolveAsync");
  79. while (!_tokenSource.IsCancellationRequested)
  80. {
  81. //
  82. await _processor.ResolveAsync().ConfigureAwait(false);
  83. // await _tdEngineDataSubcribe.ProcessMsg();
  84. }
  85. }, TaskCreationOptions.LongRunning);
  86. factory.StartNew(() =>
  87. {
  88. _logger.LogInformation("------_tdEngineDataSubcribe");
  89. while (!_tokenSource.IsCancellationRequested)
  90. {
  91. _tdEngineDataSubcribe.BeginListen(_tokenSource.Token);
  92. }
  93. }, TaskCreationOptions.LongRunning);
  94. Task.Run(() =>
  95. _serviceEtcd.WacthKeysWithPrefixResponseAsync($"health_moniter/schedule_push", WatchEvents)
  96. , stoppingToken);
  97. // watch
  98. //factory.StartNew(() =>
  99. //{
  100. // while (!_tokenSource.IsCancellationRequested)
  101. // {
  102. // //_serviceEtcd.WacthKeysWithPrefixAsync($"health_moniter/schedule_push", watchEvents => WatchEvents(watchEvents));
  103. // _serviceEtcd.WacthKeysWithPrefixResponseAsync($"health_moniter/schedule_push", WatchEvents);
  104. // }
  105. //}, TaskCreationOptions.LongRunning);
  106. // _serviceEtcd.WacthKeysWithPrefixResponseAsync($"health_moniter/schedule_push", WatchEvents);
  107. return Task.Delay(1000, _tokenSource.Token);
  108. }
  109. private void WatchEvents(WatchEvent[] response)
  110. {
  111. foreach (WatchEvent e1 in response)
  112. {
  113. // Console.WriteLine($"{nameof(WatchEventsAsync)} --- {e1.Key}:{e1.Value}:{e1.Type}");
  114. switch (e1.Type.ToString())
  115. {
  116. //case "Put":
  117. // // 获取时间点计算TTL
  118. // break;
  119. case "Delete":
  120. // TTL到了重新计算TTL,下发
  121. Console.WriteLine($"--- {e1.Key}:{e1.Value}:{e1.Type}");
  122. break;
  123. }
  124. }
  125. }
  126. private void WatchEvents(WatchResponse response)
  127. {
  128. response.Events.ToList<Mvccpb.Event>().ForEach(async e =>
  129. {
  130. switch (e.Type.ToString())
  131. {
  132. case "Put":
  133. // 获取时间点计算TTL
  134. Console.BackgroundColor = ConsoleColor.Blue;
  135. Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  136. Console.BackgroundColor = ConsoleColor.Black;
  137. break;
  138. case "Delete":
  139. // TTL到了重新计算TTL,下发
  140. Console.BackgroundColor = ConsoleColor.Green;
  141. Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  142. // var key = $"health_moniter/schedule_push/imei/{bp.Serialno}";
  143. var key = e.Kv.Key.ToStringUtf8();
  144. var imeiDel = key.Split('/')[3];
  145. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  146. if (string.IsNullOrWhiteSpace(schedule_push))
  147. {
  148. int systolicInc;
  149. int diastolicInc;
  150. int systolicRefValue;
  151. int diastolicRefValue;
  152. decimal systolicAvg;
  153. decimal diastolicAvg;
  154. int systolicMax = 0;
  155. int diastolicMax = 0;
  156. // 最小值
  157. int systolicMin = 0;
  158. int diastolicMin = 0;
  159. // 偏移参数
  160. var avgOffset = 0.25M;
  161. var systolicAvgOffset = avgOffset;
  162. var diastolicAvgOffset = avgOffset;
  163. // 最后一次下发值
  164. int lastPushSystolicInc = 0;
  165. int lastPushDiastolicInc = 0;
  166. var startTime = DateTime.Now;
  167. // 下发增量值
  168. #region 统计定时下发增量值
  169. //var last = await _serviceTDengine.GetLastAsync("stb_hm_bloodpress_stats_inc", $"serialno='{imeiDel}' order by last_update desc");
  170. //var ts = last?[0];
  171. // 最后一条血压数据
  172. var condition = $"serialno='{imeiDel}' order by last_update desc";
  173. var field = "last_row(*)";
  174. var lastHmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition, field);
  175. var lastHmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(lastHmBpResponse!);
  176. var lastHmBp = lastHmBpParser?.Select().FirstOrDefault();
  177. //if (lastHmBpParser?.Select()?.ToList().Count < 2)
  178. //{
  179. // _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 血压数据条目不足");
  180. // break;
  181. //}
  182. // 7 天有效数据
  183. if (lastHmBp?.Timestamp.AddDays(7) > DateTime.Now)
  184. {
  185. // 计算增量值
  186. condition = $"serialno='{imeiDel}' order by ts desc";
  187. var lastPushResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bp_push_ref_inc_value", condition, field);
  188. if (lastPushResponse == null)
  189. {
  190. _logger.LogInformation($"{imeiDel}--没有下发记录");
  191. break;
  192. }
  193. var lastPushParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressurePushRefIncModel>>(lastPushResponse);
  194. var lastPush = lastPushParser!.Select().FirstOrDefault();
  195. // 有下推记录
  196. if (lastPush != null)
  197. {
  198. systolicRefValue = lastPush!.SystolicRefValue;
  199. diastolicRefValue = lastPush!.DiastolicRefValue;
  200. lastPushSystolicInc = lastPush!.SystolicIncValue;
  201. lastPushDiastolicInc = lastPush!.DiastolicIncValue;
  202. condition = $"ts between '{lastPush?.Timestamp:yyyy-MM-dd HH:mm:ss.fff}' and '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  203. $"and serialno='{imeiDel}' " +
  204. $"and is_display = true";
  205. }
  206. // 没有下推记录(历史遗留数据),没有初始的测量值产生的平均值(测量值=平均值)
  207. else
  208. {
  209. #region 获取个人信息
  210. var person = await _personCacheMgr.GetDeviceGpsPersonCacheBySerialNoAsync(Guid.NewGuid().ToString(), imeiDel).ConfigureAwait(false);
  211. //验证这个信息是否存在
  212. if (person == null || person?.Person.BornDate == null)
  213. {
  214. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证个人信息,找不到个人信息,跳过此消息");
  215. break;
  216. }
  217. // 验证年龄是否在范围 (2 - 120)
  218. var age = SafeType.SafeInt(DateTime.Today.Year - person?.Person.BornDate!.Value.Year!);
  219. if (age < 2 || age > 120)
  220. {
  221. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证年龄,不在范围 (2 - 120)岁,跳过此消息");
  222. break;
  223. }
  224. var gender = person?.Person.Gender == true ? 1 : 2;
  225. var isHypertension = SafeType.SafeBool(person?.Person.Ishypertension!);
  226. var height = SafeType.SafeDouble(person?.Person.Height!);
  227. var weight = SafeType.SafeDouble(person?.Person.Weight!);
  228. #endregion
  229. #region 初始化常规血压标定值标定值
  230. var bpRef = await _bpRefValCacheManager.GetBloodPressReferenceValueAsync(age, gender, isHypertension);
  231. //systolicRefValue = bpRef!.Systolic;//?
  232. //diastolicRefValue = bpRef!.Diastolic;//?
  233. #endregion
  234. systolicRefValue = bpRef!.Systolic;
  235. diastolicRefValue = bpRef!.Diastolic;
  236. lastPushSystolicInc = 0;
  237. lastPushDiastolicInc = 0;
  238. condition = $"ts <= '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  239. $"and serialno='{imeiDel}' " +
  240. $"and is_display = true";
  241. }
  242. var hmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition);
  243. var hmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(hmBpResponse!);
  244. var hmBp = hmBpParser?.Select();
  245. //if (hmBp?.ToList().Count < 2)
  246. // 1. 判断数据样本数量
  247. if (hmBpParser!.Rows < 5)
  248. {
  249. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 统计定时下发,计算增量值的数据条目不足:{hmBpParser!.Rows} < 5");
  250. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} 没有足够的数据样本,不会定时下发");
  251. break;
  252. }
  253. // NewMethod(systolicRefValue, hmBpParser);
  254. // 最大值
  255. //systolicMax = (int)hmBpParser?.Select(i => i.SystolicValue).Max()!;
  256. //diastolicMax = (int)hmBpParser?.Select(i => i.DiastolicValue).Max()!;
  257. //// 最小值
  258. //systolicMin = (int)hmBpParser?.Select(i => i.SystolicValue).Min()!;
  259. //diastolicMin = (int)hmBpParser?.Select(i => i.DiastolicValue).Min()!;
  260. //systolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.SystolicValue, SafeType.SafeInt(systolicRefValue!)))!;
  261. //diastolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.DiastolicValue, SafeType.SafeInt(diastolicRefValue!)))!;
  262. var avgs = _serviceTDengine.AverageAfterRemovingOneMinMaxRef(SafeType.SafeInt(systolicRefValue!), hmBpParser!);
  263. systolicAvg = avgs[0];
  264. diastolicAvg = avgs[1];
  265. // 2. 判断能否计算增量值
  266. if (systolicAvg.Equals(0))
  267. {
  268. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算平均值" +
  269. $"\n currentSystolicAvg:{systolicAvg} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  270. $"\n currentDiastolicInc:{diastolicAvg} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  271. _logger.LogInformation($"{imeiDel}--{nameof(Worker)} 没有足够的数据样本计算平均值,不会定时下发");
  272. break;
  273. }
  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. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算增量值" +
  281. $"\n {imeiDel} -- systolicAvg:{systolicAvg}-- systolicInc:{systolicInc}-- currentSystolicInc:{currentSystolicInc} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  282. $"\n {imeiDel} -- diastolicAvg:{diastolicAvg}-- diastolicInc:{diastolicInc} --currentDiastolicInc:{currentDiastolicInc} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  283. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}-- 定时校准,发给设备的绝对增量值=(上次绝对增量值+新数据的增量值)");
  284. _logger.LogInformation($"{nameof(Worker)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
  285. if (_configBoodPressResolver.EnableBPRefPush)
  286. // if (false) // 临时关闭
  287. {
  288. BloodPressCalibrationConfigModel bpIncData = new()
  289. {
  290. Imei = imeiDel,
  291. SystolicRefValue = SafeType.SafeInt(((int)systolicRefValue!)), //收缩压标定值,值为0 表示不生效
  292. DiastolicRefValue = SafeType.SafeInt(((int)diastolicRefValue!)), //舒张压标定值,值为0表示不生效
  293. SystolicIncValue = SafeType.SafeInt(((int)systolicInc!)), //收缩压显示增量,值为0 表示不生效
  294. DiastolicIncValue = SafeType.SafeInt(((int)diastolicInc!)) //舒张压显示增量,值为0 表示不生效
  295. };
  296. var pushedBP = await _serviceIotWebApi.SetBloodPressCalibrationConfigAsync(bpIncData).ConfigureAwait(false);
  297. if (pushedBP)
  298. {
  299. #region 保存下推记录 stb_hm_bp_push_ref_inc_value
  300. var sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{imeiDel.Substring(imeiDel.Length - 2)} " +
  301. $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
  302. $"TAGS ('{imeiDel.Substring(imeiDel.Length - 2)}') " +
  303. $"VALUES(" +
  304. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  305. $"'{imeiDel}'," +
  306. $"{bpIncData.SystolicRefValue}," +
  307. $"{bpIncData.DiastolicRefValue}," +
  308. $"{bpIncData.SystolicIncValue}," +
  309. $"{bpIncData.DiastolicIncValue}," +
  310. $"{false}," +
  311. $"{systolicAvg}," +
  312. $"{diastolicAvg}," +
  313. $"{systolicAvgOffset}," +
  314. $"{diastolicAvgOffset}," +
  315. $"'{lastPush?.Timestamp:yyyy-MM-dd HH:mm:ss.fff}'," +
  316. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'" +
  317. $")";
  318. _serviceTDengine.ExecuteInsertSQL(sql);
  319. #endregion
  320. #region 注册定时下发
  321. // 注册下次下推
  322. var endTime = DateTime.Now;
  323. #if DEBUG
  324. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  325. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  326. var interval = 0;
  327. // 获取当前时间
  328. DateTime now = DateTime.Now;
  329. // 计算距离下一个$interval天后的8点的时间间隔
  330. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  331. TimeSpan timeUntilNextRun = nextRunTime - now;
  332. // 如果当前时间已经超过了8点,将等待到明天后的8点
  333. if (timeUntilNextRun < TimeSpan.Zero)
  334. {
  335. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  336. nextRunTime += timeUntilNextRun;
  337. }
  338. // var ttl = timeUntilNextRun.TotalMilliseconds;
  339. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  340. var data = new
  341. {
  342. imei = imeiDel,
  343. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  344. ttl,
  345. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  346. };
  347. var result = JsonConvert.SerializeObject(data);
  348. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  349. #else
  350. // 每$interval天,晚上8点
  351. var interval = 1;
  352. // 获取当前时间
  353. DateTime now = DateTime.Now;
  354. // 计算距离下一个$interval天后的8点的时间间隔
  355. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 20, 0, 0).AddDays(interval);
  356. TimeSpan timeUntilNextRun = nextRunTime - now;
  357. // 如果当前时间已经超过了8点,将等待到明天后的8点
  358. if (timeUntilNextRun < TimeSpan.Zero)
  359. {
  360. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  361. nextRunTime += timeUntilNextRun;
  362. }
  363. // var ttl = timeUntilNextRun.TotalMilliseconds;
  364. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  365. var data = new
  366. {
  367. imei = imeiDel,
  368. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  369. ttl,
  370. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  371. };
  372. var result = JsonConvert.SerializeObject(data);
  373. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  374. #endif
  375. #endregion
  376. }
  377. else
  378. {
  379. _logger.LogInformation($"错误响应,没有下推数据");
  380. }
  381. }
  382. }
  383. else
  384. {
  385. _logger.LogInformation($"向{imeiDel}统计数据已经失效");
  386. }
  387. #endregion
  388. }
  389. break;
  390. }
  391. });
  392. }
  393. private static void NewMethod(int systolicRefValue, ParseTDengineRestResponse<BloodPressureModel>? hmBpParser)
  394. {
  395. var sortedList = hmBpParser?.Select(i => i)
  396. .Where(i => i.IsDisplay.Equals(true))
  397. .OrderByDescending(i => i.SystolicValue)
  398. .ThenByDescending(i => i.DiastolicValue)
  399. .ToList();
  400. // 去除最大值和最小值各一个(列表的头和尾)
  401. var trimmedList = sortedList?
  402. .Skip(1)
  403. .Take(sortedList.Count - 2)
  404. .ToList();
  405. // 去除异常值
  406. var filteredList = trimmedList?.Where(bp => bp.SystolicValue < SafeType.SafeInt(systolicRefValue!)).ToList();
  407. var systolicAvg1 = filteredList?.Select(bp => bp.SystolicValue).Average();
  408. var diastolicAvg1 = filteredList?.Select(bp => bp.DiastolicValue).Average();
  409. }
  410. // private void WatchEvents(WatchResponse response)
  411. // {
  412. // response.Events.ToList().ForEach(async e =>
  413. // {
  414. // switch (e.Type.ToString())
  415. // {
  416. // case "Put":
  417. // // 获取时间点计算TTL
  418. // Console.BackgroundColor = ConsoleColor.Blue;
  419. // Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  420. // Console.BackgroundColor = ConsoleColor.Black;
  421. // break;
  422. // case "Delete":
  423. // // TTL到了重新计算TTL,下发
  424. // Console.BackgroundColor = ConsoleColor.Green;
  425. // Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  426. // // var key = $"health_moniter/schedule_push/imei/{bp.Serialno}";
  427. // var key = e.Kv.Key.ToStringUtf8();
  428. // var imeiDel = key.Split('/')[3];
  429. // var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  430. // if (string.IsNullOrWhiteSpace(schedule_push))
  431. // {
  432. // var startTime =DateTime.Now;
  433. // // 下发增量值
  434. // #region 定时下发增量值
  435. // var last= await _serviceTDengine.GetLastAsync("stb_hm_bloodpress_stats_inc", $"serialno='{imeiDel}' order by last_update desc");
  436. // var ts = last?[0];
  437. // if (DateTime.TryParse(ts?.ToString(),out DateTime newTs))
  438. // {
  439. // // 7 天有效数据
  440. // if (newTs.AddDays(7) > DateTime.Now)
  441. // {
  442. // Console.WriteLine(ts);
  443. // var systolic_ref_value = last?[5];
  444. // var diastolic_ref_value = last?[12];
  445. // var systolic_inc_value = last?[10];
  446. // var diastolic_inc_value = last?[17];
  447. // #region 判断是否初始化remark
  448. // // 判断是否初始化remark
  449. // /**
  450. // *
  451. // var imei = imeiDel;
  452. // var last_push = await _serviceTDengine.GetLastAsync("stb_hm_bp_push_ref_inc_value", $"serialno='{imei}' order by ts desc");
  453. // if (last_push?.Count == 0)
  454. // {
  455. // var dataServiceBaseUrl = $"https://id.ssjlai.com/data";
  456. // var DataServicePersionGet = $"{dataServiceBaseUrl}/api/GpsCard/GpsPerson/GetFirst";
  457. // List<KeyValuePair<string, string>> Dataheaders = new()
  458. // {
  459. // new KeyValuePair<string, string>("requestId", $"{imei}")
  460. // };
  461. // var dataPersion = new
  462. // {
  463. // filters = new List<object>() { new { key = "serialno", value = $"{imei}", valueType = "string", @operator = "Equal" } },
  464. // orderBys = new List<object>() { new { key = "serialno", isDesc = true } }
  465. // };
  466. // var resRef = await _httpHelper.HttpToPostAsync(DataServicePersionGet, dataPersion, Dataheaders).ConfigureAwait(false);
  467. // var resObj = JsonConvert.DeserializeObject(resRef!) as JToken;
  468. // var remark = resObj?["remarks"]?.ToString();
  469. // // 修改数据库
  470. // if (string.IsNullOrWhiteSpace(remark))
  471. // {
  472. // var newRemarkData = new
  473. // {
  474. // imei,
  475. // time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  476. // commandValue = new
  477. // {
  478. // systolicCalibrationValue = systolic_ref_value, //收缩压标定值,值为0 表示不生效
  479. // diastolicCalibrationValue = diastolic_ref_value, //舒张压标定值,值为0表示不生效
  480. // systolicIncValue = 0, //收缩压显示增量,值为0 表示不生效
  481. // diastolicIncValue = 0 //舒张压显示增量,值为0 表示不生效
  482. // }
  483. // };
  484. // resObj!["remarks"] = $"is_blood_press:{JsonConvert.SerializeObject(newRemarkData)}|";
  485. // var DataServicePersionUpdate = $"{dataServiceBaseUrl}/api/GpsCard/GpsPerson/Update";
  486. // var resUpdate = await _httpHelper.HttpToPostAsync(DataServicePersionUpdate, resObj, Dataheaders).ConfigureAwait(false);
  487. // _logger.LogInformation($"更新Person数据库|{resUpdate}");
  488. // //更新缓存
  489. // List<KeyValuePair<string, string>> headersCache = new()
  490. // {
  491. // new KeyValuePair<string, string>("AuthKey", "key1")
  492. // };
  493. // var cacheUrl = $"http://id.ssjlai.com/webapi/api/Device/UpdatePersonInfoCache?imei={imei}";
  494. // var updateCache = await _httpHelper.HttpToGetAsync(cacheUrl, headersCache);
  495. // _logger.LogInformation($"更新Person缓存|{updateCache}");
  496. // }
  497. // }
  498. // */
  499. // #endregion
  500. // //var bpData = new
  501. // //{
  502. // // imei = imeiDel,
  503. // // //systolicCalibrationValue = last?[5], //收缩压标定值,值为0 表示不生效
  504. // // //diastolicCalibrationValue = last?[12], //舒张压标定值,值为0表示不生效
  505. // // //systolicIncValue = last?[10], //收缩压显示增量,值为0 表示不生效
  506. // // //diastolicIncValue = last?[17] //舒张压显示增量,值为0 表示不生效
  507. // // systolicCalibrationValue = systolic_ref_value, //收缩压标定值,值为0 表示不生效
  508. // // diastolicCalibrationValue = diastolic_ref_value, //舒张压标定值,值为0表示不生效
  509. // // systolicIncValue = systolic_inc_value, //收缩压显示增量,值为0 表示不生效
  510. // // diastolicIncValue = diastolic_inc_value //舒张压显示增量,值为0 表示不生效
  511. // //};
  512. // //var str = JsonConvert.SerializeObject(bpData);
  513. // //var url = $"http://id.ssjlai.com/webapi/api/Command/SetBloodPressCalibrationConfig";
  514. // //List<KeyValuePair<string, string>> headers = new()
  515. // //{
  516. // // new KeyValuePair<string, string>("AuthKey", "key1")
  517. // //};
  518. // //var res = await _httpHelper.HttpToPostAsync(url, bpData, headers).ConfigureAwait(false);
  519. // //_logger.LogInformation($"向{imeiDel}下发增量值数据:{str},响应:{res}");
  520. // //var resJToken = JsonConvert.DeserializeObject(res!) as JToken;
  521. // //if (resJToken!["message"]!.ToString().Equals("ok"))
  522. // Console.WriteLine($"{nameof(Worker)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
  523. // // if (_configBoodPressResolver.EnableBPRefPush)
  524. // if (false) // 临时关闭
  525. // {
  526. // BloodPressCalibrationConfigModel bpIncData = new()
  527. // {
  528. // Imei = imeiDel,
  529. // SystolicRefValue = SafeType.SafeInt(((int)systolic_ref_value!)), //收缩压标定值,值为0 表示不生效
  530. // DiastolicRefValue = SafeType.SafeInt(((int)diastolic_ref_value!)), //舒张压标定值,值为0表示不生效
  531. // SystolicIncValue = SafeType.SafeInt(((int)systolic_inc_value!)), //收缩压显示增量,值为0 表示不生效
  532. // DiastolicIncValue = SafeType.SafeInt(((int)diastolic_inc_value!)) //舒张压显示增量,值为0 表示不生效
  533. // };
  534. // var pushedBP = await _serviceIotWebApi.SetBloodPressCalibrationConfigAsync(bpIncData).ConfigureAwait(false);
  535. // if (pushedBP)
  536. // {
  537. // #region 保存下推记录 stb_hm_bp_push_ref_inc_value
  538. // var sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{imeiDel.Substring(imeiDel.Length - 2)} " +
  539. // $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
  540. // $"TAGS ('{imeiDel.Substring(imeiDel.Length - 2)}') " +
  541. // $"VALUES(" +
  542. // $"'{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}'," +
  543. // $"'{imeiDel}'," +
  544. // $"{systolic_ref_value}," +
  545. // $"{diastolic_ref_value}," +
  546. // $"{systolic_inc_value}," +
  547. // $"{diastolic_inc_value}," +
  548. // $"{false})";
  549. // _serviceTDengine.ExecuteInsertSQL(sql);
  550. // #endregion
  551. // // 注册下次下推
  552. // var endTime = DateTime.Now;
  553. //#if DEBUG
  554. // //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  555. // //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  556. // var interval = 0;
  557. // // 获取当前时间
  558. // DateTime now = DateTime.Now;
  559. // // 计算距离下一个$interval天后的8点的时间间隔
  560. // DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  561. // TimeSpan timeUntilNextRun = nextRunTime - now;
  562. // // 如果当前时间已经超过了8点,将等待到明天后的8点
  563. // if (timeUntilNextRun < TimeSpan.Zero)
  564. // {
  565. // timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  566. // nextRunTime += timeUntilNextRun;
  567. // }
  568. // // var ttl = timeUntilNextRun.TotalMilliseconds;
  569. // long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  570. // var data = new
  571. // {
  572. // imei = imeiDel,
  573. // create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  574. // ttl,
  575. // next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  576. // };
  577. // var result = JsonConvert.SerializeObject(data);
  578. // await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  579. //#else
  580. // // 每$interval天,晚上8点
  581. // var interval = 1;
  582. // // 获取当前时间
  583. // DateTime now = DateTime.Now;
  584. // // 计算距离下一个$interval天后的8点的时间间隔
  585. // DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 20, 0, 0).AddDays(interval);
  586. // TimeSpan timeUntilNextRun = nextRunTime - now;
  587. // // 如果当前时间已经超过了8点,将等待到明天后的8点
  588. // if (timeUntilNextRun < TimeSpan.Zero)
  589. // {
  590. // timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  591. // nextRunTime += timeUntilNextRun;
  592. // }
  593. // // var ttl = timeUntilNextRun.TotalMilliseconds;
  594. // long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  595. // var data = new
  596. // {
  597. // imei = imeiDel,
  598. // create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  599. // ttl,
  600. // next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  601. // };
  602. // var result = JsonConvert.SerializeObject(data);
  603. // await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  604. //#endif
  605. // }
  606. // else
  607. // {
  608. // _logger.LogInformation($"错误响应,没有下推数据");
  609. // }
  610. // }
  611. // }
  612. // }
  613. // else
  614. // {
  615. // _logger.LogInformation($"向{imeiDel}准备下推的数据已经失效ts,{ts}");
  616. // }
  617. // #endregion
  618. // //if (imeiDel.Equals("861281060086216"))
  619. // //{
  620. // // var result = await _httpHelper.HttpToPostAsync(url, data, headers).ConfigureAwait(false);
  621. // // _logger.LogInformation($"向{imeiDel}下发增量值数据:{str},响应:{result}");
  622. // // Console.WriteLine(str);
  623. // //}
  624. // //Console.BackgroundColor = ConsoleColor.Black;
  625. // }
  626. // break;
  627. // }
  628. // });
  629. // //if (response.Events.Count == 0)
  630. // //{
  631. // // Console.WriteLine(response);
  632. // //}
  633. // //else
  634. // //{
  635. // // Console.WriteLine($"{response.Events[0].Kv.Key.ToStringUtf8()}:{response.Events.Kv.Value.ToStringUtf8()}");
  636. // //}
  637. // }
  638. }
  639. }