Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

671 lines
39KB

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