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

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