You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Worker.cs 39KB

1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
11 달 전
1 년 전
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. condition = $"ts between '{startTime:yyyy-MM-dd HH:mm:ss.fff}' and '{lastPush?.Timestamp:yyyy-MM-dd HH:mm:ss.fff}' " +
  193. $"and serialno='{imeiDel}' " +
  194. $"and is_display = true";
  195. var hmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition);
  196. var hmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(hmBpResponse!);
  197. var hmBp = hmBpParser?.Select();
  198. if (hmBp?.ToList().Count < 2)
  199. {
  200. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 统计定时下发,计算增量值的数据条目不足");
  201. break;
  202. }
  203. // 最大值
  204. systolicMax = (int)hmBpParser?.Select(i => i.SystolicValue).Max()!;
  205. diastolicMax = (int)hmBpParser?.Select(i => i.DiastolicValue).Max()!;
  206. // 最小值
  207. systolicMin = (int)hmBpParser?.Select(i => i.SystolicValue).Min()!;
  208. diastolicMin = (int)hmBpParser?.Select(i => i.DiastolicValue).Min()!;
  209. systolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.SystolicValue, SafeType.SafeInt(systolicRefValue!)))!;
  210. diastolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.DiastolicValue, SafeType.SafeInt(diastolicRefValue!)))!;
  211. // 增量值=(标定值-平均值)* 0.25
  212. var currentSystolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
  213. var currentDiastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
  214. // 累计增量
  215. systolicInc = currentSystolicInc + lastPushSystolicInc;
  216. diastolicInc = currentDiastolicInc + lastPushDiastolicInc;
  217. _logger.LogInformation($"{nameof(Worker)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
  218. if (_configBoodPressResolver.EnableBPRefPush)
  219. // if (false) // 临时关闭
  220. {
  221. BloodPressCalibrationConfigModel bpIncData = new()
  222. {
  223. Imei = imeiDel,
  224. SystolicRefValue = SafeType.SafeInt(((int)systolicRefValue!)), //收缩压标定值,值为0 表示不生效
  225. DiastolicRefValue = SafeType.SafeInt(((int)diastolicRefValue!)), //舒张压标定值,值为0表示不生效
  226. SystolicIncValue = SafeType.SafeInt(((int)systolicInc!)), //收缩压显示增量,值为0 表示不生效
  227. DiastolicIncValue = SafeType.SafeInt(((int)diastolicInc!)) //舒张压显示增量,值为0 表示不生效
  228. };
  229. var pushedBP = await _serviceIotWebApi.SetBloodPressCalibrationConfigAsync(bpIncData).ConfigureAwait(false);
  230. if (pushedBP)
  231. {
  232. #region 保存下推记录 stb_hm_bp_push_ref_inc_value
  233. var sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{imeiDel.Substring(imeiDel.Length - 2)} " +
  234. $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
  235. $"TAGS ('{imeiDel.Substring(imeiDel.Length - 2)}') " +
  236. $"VALUES(" +
  237. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  238. $"'{imeiDel}'," +
  239. $"{bpIncData.SystolicRefValue}," +
  240. $"{bpIncData.DiastolicRefValue}," +
  241. $"{bpIncData.SystolicIncValue}," +
  242. $"{bpIncData.DiastolicIncValue}," +
  243. $"{false}," +
  244. $"{systolicAvg}," +
  245. $"{diastolicAvg}," +
  246. $"{systolicAvgOffset}," +
  247. $"{diastolicAvgOffset}," +
  248. $"'{lastPush?.Timestamp:yyyy-MM-dd HH:mm:ss.fff}'," +
  249. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'" +
  250. $")";
  251. _serviceTDengine.ExecuteInsertSQL(sql);
  252. #endregion
  253. #region 注册定时下发
  254. // 注册下次下推
  255. var endTime = DateTime.Now;
  256. #if DEBUG
  257. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  258. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  259. var interval = 0;
  260. // 获取当前时间
  261. DateTime now = DateTime.Now;
  262. // 计算距离下一个$interval天后的8点的时间间隔
  263. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  264. TimeSpan timeUntilNextRun = nextRunTime - now;
  265. // 如果当前时间已经超过了8点,将等待到明天后的8点
  266. if (timeUntilNextRun < TimeSpan.Zero)
  267. {
  268. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  269. nextRunTime += timeUntilNextRun;
  270. }
  271. // var ttl = timeUntilNextRun.TotalMilliseconds;
  272. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  273. var data = new
  274. {
  275. imei = imeiDel,
  276. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  277. ttl,
  278. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  279. };
  280. var result = JsonConvert.SerializeObject(data);
  281. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  282. #else
  283. // 每$interval天,晚上8点
  284. var interval = 1;
  285. // 获取当前时间
  286. DateTime now = DateTime.Now;
  287. // 计算距离下一个$interval天后的8点的时间间隔
  288. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 20, 0, 0).AddDays(interval);
  289. TimeSpan timeUntilNextRun = nextRunTime - now;
  290. // 如果当前时间已经超过了8点,将等待到明天后的8点
  291. if (timeUntilNextRun < TimeSpan.Zero)
  292. {
  293. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  294. nextRunTime += timeUntilNextRun;
  295. }
  296. // var ttl = timeUntilNextRun.TotalMilliseconds;
  297. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  298. var data = new
  299. {
  300. imei = imeiDel,
  301. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  302. ttl,
  303. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  304. };
  305. var result = JsonConvert.SerializeObject(data);
  306. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  307. #endif
  308. #endregion
  309. }
  310. else
  311. {
  312. _logger.LogInformation($"错误响应,没有下推数据");
  313. }
  314. }
  315. }
  316. else
  317. {
  318. _logger.LogInformation($"向{imeiDel}统计数据已经失效");
  319. }
  320. #endregion
  321. }
  322. break;
  323. }
  324. });
  325. }
  326. // private void WatchEvents(WatchResponse response)
  327. // {
  328. // response.Events.ToList().ForEach(async e =>
  329. // {
  330. // switch (e.Type.ToString())
  331. // {
  332. // case "Put":
  333. // // 获取时间点计算TTL
  334. // Console.BackgroundColor = ConsoleColor.Blue;
  335. // Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  336. // Console.BackgroundColor = ConsoleColor.Black;
  337. // break;
  338. // case "Delete":
  339. // // TTL到了重新计算TTL,下发
  340. // Console.BackgroundColor = ConsoleColor.Green;
  341. // Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  342. // // var key = $"health_moniter/schedule_push/imei/{bp.Serialno}";
  343. // var key = e.Kv.Key.ToStringUtf8();
  344. // var imeiDel = key.Split('/')[3];
  345. // var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  346. // if (string.IsNullOrWhiteSpace(schedule_push))
  347. // {
  348. // var startTime =DateTime.Now;
  349. // // 下发增量值
  350. // #region 定时下发增量值
  351. // var last= await _serviceTDengine.GetLastAsync("stb_hm_bloodpress_stats_inc", $"serialno='{imeiDel}' order by last_update desc");
  352. // var ts = last?[0];
  353. // if (DateTime.TryParse(ts?.ToString(),out DateTime newTs))
  354. // {
  355. // // 7 天有效数据
  356. // if (newTs.AddDays(7) > DateTime.Now)
  357. // {
  358. // Console.WriteLine(ts);
  359. // var systolic_ref_value = last?[5];
  360. // var diastolic_ref_value = last?[12];
  361. // var systolic_inc_value = last?[10];
  362. // var diastolic_inc_value = last?[17];
  363. // #region 判断是否初始化remark
  364. // // 判断是否初始化remark
  365. // /**
  366. // *
  367. // var imei = imeiDel;
  368. // var last_push = await _serviceTDengine.GetLastAsync("stb_hm_bp_push_ref_inc_value", $"serialno='{imei}' order by ts desc");
  369. // if (last_push?.Count == 0)
  370. // {
  371. // var dataServiceBaseUrl = $"https://id.ssjlai.com/data";
  372. // var DataServicePersionGet = $"{dataServiceBaseUrl}/api/GpsCard/GpsPerson/GetFirst";
  373. // List<KeyValuePair<string, string>> Dataheaders = new()
  374. // {
  375. // new KeyValuePair<string, string>("requestId", $"{imei}")
  376. // };
  377. // var dataPersion = new
  378. // {
  379. // filters = new List<object>() { new { key = "serialno", value = $"{imei}", valueType = "string", @operator = "Equal" } },
  380. // orderBys = new List<object>() { new { key = "serialno", isDesc = true } }
  381. // };
  382. // var resRef = await _httpHelper.HttpToPostAsync(DataServicePersionGet, dataPersion, Dataheaders).ConfigureAwait(false);
  383. // var resObj = JsonConvert.DeserializeObject(resRef!) as JToken;
  384. // var remark = resObj?["remarks"]?.ToString();
  385. // // 修改数据库
  386. // if (string.IsNullOrWhiteSpace(remark))
  387. // {
  388. // var newRemarkData = new
  389. // {
  390. // imei,
  391. // time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  392. // commandValue = new
  393. // {
  394. // systolicCalibrationValue = systolic_ref_value, //收缩压标定值,值为0 表示不生效
  395. // diastolicCalibrationValue = diastolic_ref_value, //舒张压标定值,值为0表示不生效
  396. // systolicIncValue = 0, //收缩压显示增量,值为0 表示不生效
  397. // diastolicIncValue = 0 //舒张压显示增量,值为0 表示不生效
  398. // }
  399. // };
  400. // resObj!["remarks"] = $"is_blood_press:{JsonConvert.SerializeObject(newRemarkData)}|";
  401. // var DataServicePersionUpdate = $"{dataServiceBaseUrl}/api/GpsCard/GpsPerson/Update";
  402. // var resUpdate = await _httpHelper.HttpToPostAsync(DataServicePersionUpdate, resObj, Dataheaders).ConfigureAwait(false);
  403. // _logger.LogInformation($"更新Person数据库|{resUpdate}");
  404. // //更新缓存
  405. // List<KeyValuePair<string, string>> headersCache = new()
  406. // {
  407. // new KeyValuePair<string, string>("AuthKey", "key1")
  408. // };
  409. // var cacheUrl = $"http://id.ssjlai.com/webapi/api/Device/UpdatePersonInfoCache?imei={imei}";
  410. // var updateCache = await _httpHelper.HttpToGetAsync(cacheUrl, headersCache);
  411. // _logger.LogInformation($"更新Person缓存|{updateCache}");
  412. // }
  413. // }
  414. // */
  415. // #endregion
  416. // //var bpData = new
  417. // //{
  418. // // imei = imeiDel,
  419. // // //systolicCalibrationValue = last?[5], //收缩压标定值,值为0 表示不生效
  420. // // //diastolicCalibrationValue = last?[12], //舒张压标定值,值为0表示不生效
  421. // // //systolicIncValue = last?[10], //收缩压显示增量,值为0 表示不生效
  422. // // //diastolicIncValue = last?[17] //舒张压显示增量,值为0 表示不生效
  423. // // systolicCalibrationValue = systolic_ref_value, //收缩压标定值,值为0 表示不生效
  424. // // diastolicCalibrationValue = diastolic_ref_value, //舒张压标定值,值为0表示不生效
  425. // // systolicIncValue = systolic_inc_value, //收缩压显示增量,值为0 表示不生效
  426. // // diastolicIncValue = diastolic_inc_value //舒张压显示增量,值为0 表示不生效
  427. // //};
  428. // //var str = JsonConvert.SerializeObject(bpData);
  429. // //var url = $"http://id.ssjlai.com/webapi/api/Command/SetBloodPressCalibrationConfig";
  430. // //List<KeyValuePair<string, string>> headers = new()
  431. // //{
  432. // // new KeyValuePair<string, string>("AuthKey", "key1")
  433. // //};
  434. // //var res = await _httpHelper.HttpToPostAsync(url, bpData, headers).ConfigureAwait(false);
  435. // //_logger.LogInformation($"向{imeiDel}下发增量值数据:{str},响应:{res}");
  436. // //var resJToken = JsonConvert.DeserializeObject(res!) as JToken;
  437. // //if (resJToken!["message"]!.ToString().Equals("ok"))
  438. // Console.WriteLine($"{nameof(Worker)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
  439. // // if (_configBoodPressResolver.EnableBPRefPush)
  440. // if (false) // 临时关闭
  441. // {
  442. // BloodPressCalibrationConfigModel bpIncData = new()
  443. // {
  444. // Imei = imeiDel,
  445. // SystolicRefValue = SafeType.SafeInt(((int)systolic_ref_value!)), //收缩压标定值,值为0 表示不生效
  446. // DiastolicRefValue = SafeType.SafeInt(((int)diastolic_ref_value!)), //舒张压标定值,值为0表示不生效
  447. // SystolicIncValue = SafeType.SafeInt(((int)systolic_inc_value!)), //收缩压显示增量,值为0 表示不生效
  448. // DiastolicIncValue = SafeType.SafeInt(((int)diastolic_inc_value!)) //舒张压显示增量,值为0 表示不生效
  449. // };
  450. // var pushedBP = await _serviceIotWebApi.SetBloodPressCalibrationConfigAsync(bpIncData).ConfigureAwait(false);
  451. // if (pushedBP)
  452. // {
  453. // #region 保存下推记录 stb_hm_bp_push_ref_inc_value
  454. // var sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{imeiDel.Substring(imeiDel.Length - 2)} " +
  455. // $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
  456. // $"TAGS ('{imeiDel.Substring(imeiDel.Length - 2)}') " +
  457. // $"VALUES(" +
  458. // $"'{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}'," +
  459. // $"'{imeiDel}'," +
  460. // $"{systolic_ref_value}," +
  461. // $"{diastolic_ref_value}," +
  462. // $"{systolic_inc_value}," +
  463. // $"{diastolic_inc_value}," +
  464. // $"{false})";
  465. // _serviceTDengine.ExecuteInsertSQL(sql);
  466. // #endregion
  467. // // 注册下次下推
  468. // var endTime = DateTime.Now;
  469. //#if DEBUG
  470. // //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  471. // //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  472. // var interval = 0;
  473. // // 获取当前时间
  474. // DateTime now = DateTime.Now;
  475. // // 计算距离下一个$interval天后的8点的时间间隔
  476. // DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  477. // TimeSpan timeUntilNextRun = nextRunTime - now;
  478. // // 如果当前时间已经超过了8点,将等待到明天后的8点
  479. // if (timeUntilNextRun < TimeSpan.Zero)
  480. // {
  481. // timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  482. // nextRunTime += timeUntilNextRun;
  483. // }
  484. // // var ttl = timeUntilNextRun.TotalMilliseconds;
  485. // long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  486. // var data = new
  487. // {
  488. // imei = imeiDel,
  489. // create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  490. // ttl,
  491. // next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  492. // };
  493. // var result = JsonConvert.SerializeObject(data);
  494. // await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  495. //#else
  496. // // 每$interval天,晚上8点
  497. // var interval = 1;
  498. // // 获取当前时间
  499. // DateTime now = DateTime.Now;
  500. // // 计算距离下一个$interval天后的8点的时间间隔
  501. // DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 20, 0, 0).AddDays(interval);
  502. // TimeSpan timeUntilNextRun = nextRunTime - now;
  503. // // 如果当前时间已经超过了8点,将等待到明天后的8点
  504. // if (timeUntilNextRun < TimeSpan.Zero)
  505. // {
  506. // timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  507. // nextRunTime += timeUntilNextRun;
  508. // }
  509. // // var ttl = timeUntilNextRun.TotalMilliseconds;
  510. // long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  511. // var data = new
  512. // {
  513. // imei = imeiDel,
  514. // create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  515. // ttl,
  516. // next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  517. // };
  518. // var result = JsonConvert.SerializeObject(data);
  519. // await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  520. //#endif
  521. // }
  522. // else
  523. // {
  524. // _logger.LogInformation($"错误响应,没有下推数据");
  525. // }
  526. // }
  527. // }
  528. // }
  529. // else
  530. // {
  531. // _logger.LogInformation($"向{imeiDel}准备下推的数据已经失效ts,{ts}");
  532. // }
  533. // #endregion
  534. // //if (imeiDel.Equals("861281060086216"))
  535. // //{
  536. // // var result = await _httpHelper.HttpToPostAsync(url, data, headers).ConfigureAwait(false);
  537. // // _logger.LogInformation($"向{imeiDel}下发增量值数据:{str},响应:{result}");
  538. // // Console.WriteLine(str);
  539. // //}
  540. // //Console.BackgroundColor = ConsoleColor.Black;
  541. // }
  542. // break;
  543. // }
  544. // });
  545. // //if (response.Events.Count == 0)
  546. // //{
  547. // // Console.WriteLine(response);
  548. // //}
  549. // //else
  550. // //{
  551. // // Console.WriteLine($"{response.Events[0].Kv.Key.ToStringUtf8()}:{response.Events.Kv.Value.ToStringUtf8()}");
  552. // //}
  553. // }
  554. }
  555. }