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.

8 月之前
8 月之前
8 月之前
1 年之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
1 年之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
8 月之前
1 年之前
8 月之前
8 月之前
8 月之前
8 月之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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 IotApiService _serviceIotApi;
  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, IotApiService IotApiService, IOptions<BoodPressResolverConfig> optionBoodPressResolver, PackageProcess processor, TDengineDataSubcribe tdEngineDataSubcribe, TDengineService serviceDengine, HttpHelper httpHelper, EtcdService serviceEtcd)
  41. {
  42. _logger = logger;
  43. _tdEngineDataSubcribe = tdEngineDataSubcribe;
  44. _services = services;
  45. _serviceIotApi = IotApiService;
  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. return base.StartAsync(cancellationToken);
  59. }
  60. public override Task StopAsync(CancellationToken cancellationToken)
  61. {
  62. //_logger.LogInformation("------StopAsync");
  63. _tokenSource.Cancel(); //停止工作线程
  64. return base.StopAsync(cancellationToken);
  65. }
  66. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  67. {
  68. var tasks = new[]
  69. {
  70. Task.Run(async () =>
  71. {
  72. _logger.LogInformation("解析器启动");
  73. while (!stoppingToken.IsCancellationRequested)
  74. {
  75. await _processor.ResolveAsync().ConfigureAwait(false);
  76. }
  77. }, stoppingToken),
  78. Task.Run(() =>
  79. {
  80. _logger.LogInformation("TDengine 订阅启动");
  81. while (!stoppingToken.IsCancellationRequested)
  82. {
  83. _tdEngineDataSubcribe.BeginListen(stoppingToken);
  84. }
  85. }, stoppingToken),
  86. Task.Run(() =>
  87. _serviceEtcd.WacthKeysWithPrefixResponseAsync("health_moniter/schedule_push", WatchEvents),
  88. stoppingToken)
  89. };
  90. await Task.WhenAll(tasks);
  91. }
  92. private void WatchEvents(WatchResponse response)
  93. {
  94. response.Events.ToList<Mvccpb.Event>().ForEach(async e =>
  95. {
  96. try
  97. {
  98. switch (e.Type.ToString())
  99. {
  100. case "Put":
  101. // 获取时间点计算TTL
  102. Console.BackgroundColor = ConsoleColor.Blue;
  103. Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  104. Console.BackgroundColor = ConsoleColor.Black;
  105. break;
  106. case "Delete":
  107. // TTL到了重新计算TTL,下发
  108. //Console.BackgroundColor = ConsoleColor.Green;
  109. //Console.WriteLine($"--- {e.Type}--{e.Kv.Key.ToStringUtf8()}--{e.Kv.Value.ToStringUtf8()}---{DateTime.Now}");
  110. // var key = $"health_moniter/schedule_push/imei/{bp.Serialno}";
  111. var key = e.Kv.Key.ToStringUtf8();
  112. var imeiDel = key.Split('/')[^1];
  113. var schedule_push = await _serviceEtcd.GetValAsync(key).ConfigureAwait(false);
  114. if (string.IsNullOrWhiteSpace(schedule_push))
  115. {
  116. if (key.Contains("pregnancy_heart_rate"))
  117. {
  118. // 处理孕妇业务,计算一般心率并下发
  119. var commonPHR= await _serviceTDengine.InitPregnancyCommonHeartRateModeAsync(imeiDel);
  120. // 设置胎心监测参数
  121. if (commonPHR == null)
  122. {
  123. // 建模中
  124. var flag= await _serviceIotApi.SetFetalHeartRateConfig(imeiDel);
  125. _logger.LogInformation($"{imeiDel} 建模建模中");
  126. }
  127. else
  128. {
  129. // 建模完成
  130. var flag = await _serviceIotApi.SetFetalHeartRateConfig(imeiDel,1,commonPHR.MaxValue,commonPHR.MinValue);
  131. _logger.LogInformation($"{imeiDel} 建模完成");
  132. // 保存到TDengine数据库
  133. await _serviceTDengine.InsertAsync<PregnancyCommonHeartRateModel>("hm_pchr", commonPHR);
  134. _logger.LogInformation($"保存TDengine完成");
  135. }
  136. #region 注册定时下发
  137. var startTime = DateTime.Now;
  138. // 注册下次下推
  139. var endTime = DateTime.Now;
  140. #if DEBUG
  141. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  142. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  143. var interval = 0;
  144. // 获取当前时间
  145. DateTime now = DateTime.Now;
  146. // 计算距离下一个$interval天后的8点的时间间隔
  147. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  148. TimeSpan timeUntilNextRun = nextRunTime - now;
  149. // 如果当前时间已经超过了8点,将等待到明天后的8点
  150. if (timeUntilNextRun < TimeSpan.Zero)
  151. {
  152. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  153. nextRunTime += timeUntilNextRun;
  154. }
  155. //long ttl = timeUntilNextRun.Milliseconds/1000;
  156. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  157. var data = new
  158. {
  159. imei = imeiDel,
  160. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  161. ttl,
  162. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  163. };
  164. var result = JsonConvert.SerializeObject(data);
  165. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  166. #else
  167. // 每$interval天,晚上8点
  168. var interval = 1;
  169. // 获取当前时间
  170. DateTime now = DateTime.Now;
  171. var rand = new Random();
  172. var pushSec = rand.Next(59);
  173. int pushMin = int.TryParse(imeiDel.AsSpan(imeiDel.Length - 1), out pushMin) ? pushMin : 10;
  174. // 计算距离下一个$interval天后的8点的时间间隔
  175. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 18, pushMin, pushSec).AddDays(interval);
  176. TimeSpan timeUntilNextRun = nextRunTime - now;
  177. // 如果当前时间已经超过了8点,将等待到明天后的8点
  178. if (timeUntilNextRun < TimeSpan.Zero)
  179. {
  180. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  181. nextRunTime += timeUntilNextRun;
  182. }
  183. // var ttl = timeUntilNextRun.TotalMilliseconds;
  184. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  185. var data = new
  186. {
  187. imei = imeiDel,
  188. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  189. ttl,
  190. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  191. };
  192. var result = JsonConvert.SerializeObject(data);
  193. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  194. #endif
  195. #endregion
  196. }
  197. else
  198. {
  199. // 处理血压业务
  200. int systolicInc;
  201. int diastolicInc;
  202. int systolicRefValue;
  203. int diastolicRefValue;
  204. decimal systolicAvg;
  205. decimal diastolicAvg;
  206. int systolicMax = 0;
  207. int diastolicMax = 0;
  208. // 统计时间
  209. //DateTime endTime = DateTime.Now; //测试
  210. DateTime statStartTime = DateTime.Now;
  211. // 最小值
  212. int systolicMin = 0;
  213. int diastolicMin = 0;
  214. // 偏移参数
  215. var avgOffset = 0.25M;
  216. var systolicAvgOffset = avgOffset;
  217. var diastolicAvgOffset = avgOffset;
  218. // 最后一次下发值
  219. int lastPushSystolicInc = 0;
  220. int lastPushDiastolicInc = 0;
  221. var startTime = DateTime.Now;
  222. // 下发增量值
  223. #region 统计定时下发增量值
  224. //var last = await _serviceTDengine.GetLastAsync("stb_hm_bloodpress_stats_inc", $"serialno='{imeiDel}' order by last_update desc");
  225. //var ts = last?[0];
  226. // 最后一条血压数据
  227. var condition = $"serialno='{imeiDel}' order by last_update desc";
  228. var field = "last_row(*)";
  229. var lastHmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition, field);
  230. var lastHmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(lastHmBpResponse!);
  231. var lastHmBp = lastHmBpParser?.Select().FirstOrDefault();
  232. //if (lastHmBpParser?.Select()?.ToList().Count < 2)
  233. //{
  234. // _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 血压数据条目不足");
  235. // break;
  236. //}
  237. // 7 天有效数据
  238. if (lastHmBp?.Timestamp.AddDays(7) > DateTime.Now)
  239. {
  240. // 计算增量值
  241. condition = $"serialno='{imeiDel}' order by ts desc";
  242. var lastPushResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bp_push_ref_inc_value", condition, field);
  243. if (lastPushResponse == null)
  244. {
  245. _logger.LogInformation($"{imeiDel}--没有下发记录");
  246. break;
  247. }
  248. var lastPushParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressurePushRefIncModel>>(lastPushResponse);
  249. var lastPush = lastPushParser!.Select().FirstOrDefault();
  250. // 有下推记录
  251. if (lastPush != null)
  252. {
  253. systolicRefValue = lastPush!.SystolicRefValue;
  254. diastolicRefValue = lastPush!.DiastolicRefValue;
  255. lastPushSystolicInc = lastPush!.SystolicIncValue;
  256. lastPushDiastolicInc = lastPush!.DiastolicIncValue;
  257. condition = $"ts between '{lastPush?.Timestamp:yyyy-MM-dd HH:mm:ss.fff}' and '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  258. $"and serialno='{imeiDel}' " +
  259. $"and is_display = true";
  260. // 使用最近一次的下推时间作为统计的开始时间
  261. statStartTime = lastPush!.Timestamp;
  262. }
  263. // 没有下推记录(历史遗留数据),没有初始的测量值产生的平均值(测量值=平均值)
  264. else
  265. {
  266. #region 获取个人信息
  267. var person = await _personCacheMgr.GetDeviceGpsPersonCacheBySerialNoAsync(Guid.NewGuid().ToString(), imeiDel).ConfigureAwait(false);
  268. //验证这个信息是否存在
  269. if (person == null || person?.Person.BornDate == null)
  270. {
  271. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证个人信息,找不到个人信息,跳过此消息");
  272. break;
  273. }
  274. // 验证年龄是否在范围 (2 - 120)
  275. var age = SafeType.SafeInt(DateTime.Today.Year - person?.Person.BornDate!.Value.Year!);
  276. if (age < 2 || age > 120)
  277. {
  278. _logger.LogWarning($"{nameof(Worker)}--{imeiDel} 验证年龄,不在范围 (2 - 120)岁,跳过此消息");
  279. break;
  280. }
  281. var gender = person?.Person.Gender == true ? 1 : 2;
  282. var isHypertension = SafeType.SafeBool(person?.Person.Ishypertension!);
  283. var height = SafeType.SafeDouble(person?.Person.Height!);
  284. var weight = SafeType.SafeDouble(person?.Person.Weight!);
  285. #endregion
  286. #region 初始化常规血压标定值标定值
  287. var bpRef = await _bpRefValCacheManager.GetBloodPressReferenceValueAsync(age, gender, isHypertension);
  288. //systolicRefValue = bpRef!.Systolic;//?
  289. //diastolicRefValue = bpRef!.Diastolic;//?
  290. #endregion
  291. systolicRefValue = bpRef!.Systolic;
  292. diastolicRefValue = bpRef!.Diastolic;
  293. lastPushSystolicInc = 0;
  294. lastPushDiastolicInc = 0;
  295. condition = $"ts <= '{startTime:yyyy-MM-dd HH:mm:ss.fff}' " +
  296. $"and serialno='{imeiDel}' " +
  297. $"and is_display = true";
  298. }
  299. var hmBpResponse = await _serviceTDengine.ExecuteSelectRestResponseAsync("stb_hm_bloodpress", condition);
  300. var hmBpParser = JsonConvert.DeserializeObject<ParseTDengineRestResponse<BloodPressureModel>>(hmBpResponse!);
  301. var hmBp = hmBpParser?.Select();
  302. //if (hmBp?.ToList().Count < 2)
  303. // 1. 判断数据样本数量
  304. if (hmBpParser!.Rows < 5)
  305. {
  306. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} -- 统计定时下发,计算增量值的数据条目不足:{hmBpParser!.Rows} < 5");
  307. _logger.LogInformation($"{imeiDel} -- {nameof(Worker)} --{nameof(WatchEvents)} 没有足够的数据样本,不会定时下发");
  308. break;
  309. }
  310. // 没有下推记录重新计算统计时间
  311. if (lastPush == null)
  312. {
  313. var firstHmBp = hmBpParser?.Select(i => i).OrderBy(i => i.Timestamp).FirstOrDefault();
  314. statStartTime = firstHmBp!.Timestamp;
  315. }
  316. // NewMethod(systolicRefValue, hmBpParser);
  317. // 最大值
  318. //systolicMax = (int)hmBpParser?.Select(i => i.SystolicValue).Max()!;
  319. //diastolicMax = (int)hmBpParser?.Select(i => i.DiastolicValue).Max()!;
  320. //// 最小值
  321. //systolicMin = (int)hmBpParser?.Select(i => i.SystolicValue).Min()!;
  322. //diastolicMin = (int)hmBpParser?.Select(i => i.DiastolicValue).Min()!;
  323. //systolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.SystolicValue, SafeType.SafeInt(systolicRefValue!)))!;
  324. //diastolicAvg = (int)(hmBpParser?.AverageAfterRemovingOneMinMaxRef(i => i.DiastolicValue, SafeType.SafeInt(diastolicRefValue!)))!;
  325. var avgs = _serviceTDengine.AverageAfterRemovingOneMinMaxRef(hmBpParser!);
  326. systolicAvg = avgs[0];
  327. diastolicAvg = avgs[1];
  328. // 2. 判断能否计算增量值
  329. if (systolicAvg.Equals(0))
  330. {
  331. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算平均值" +
  332. $"\n currentSystolicAvg:{systolicAvg} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  333. $"\n currentDiastolicInc:{diastolicAvg} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  334. _logger.LogInformation($"{imeiDel}--{nameof(Worker)} 没有足够的数据样本计算平均值,不会定时下发");
  335. break;
  336. }
  337. // 除最大值和最小值后的平均值与标定值差值少于4后(当天计算出该结果则也不产生增量调整),就不再进行增量值调整了。
  338. if (systolicRefValue - systolicAvg < 4)
  339. {
  340. _logger.LogInformation($"diastolic 舒张压 {imeiDel}除最大值和最小值后的平均值:{diastolicAvg}与标定值:{diastolicRefValue}\n systolic 收缩压 {imeiDel}除最大值和最小值后的平均值:{systolicAvg}与标定值:{systolicRefValue}的差值(标定值-平均值)少于4后,systolic 收缩压 不再进行增量值调整");
  341. break;
  342. }
  343. if (diastolicRefValue - diastolicAvg < 4)
  344. {
  345. _logger.LogInformation($"systolic 收缩压 {imeiDel}除最大值和最小值后的平均值:{systolicAvg}与标定值:{systolicRefValue}\n diastolic 舒张压 {imeiDel}除最大值和最小值后的平均值:{diastolicAvg}与标定值:{diastolicRefValue}的差值(标定值-平均值)少于4后,diastolic 舒张压 不再进行增量值调整");
  346. break;
  347. }
  348. // 增量值=(标定值-平均值)* 0.25
  349. var currentSystolicInc = (int)((systolicRefValue - systolicAvg) * systolicAvgOffset)!;
  350. var currentDiastolicInc = (int)((diastolicRefValue - diastolicAvg) * diastolicAvgOffset)!;
  351. // 累计增量
  352. systolicInc = currentSystolicInc + lastPushSystolicInc;
  353. diastolicInc = currentDiastolicInc + lastPushDiastolicInc;
  354. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}--计算增量值" +
  355. $"\n {imeiDel} -- systolicAvg:{systolicAvg}-- systolicInc:{systolicInc}-- currentSystolicInc:{currentSystolicInc} -- lastPushSystolicInc:{lastPushSystolicInc}" +
  356. $"\n {imeiDel} -- diastolicAvg:{diastolicAvg}-- diastolicInc:{diastolicInc} --currentDiastolicInc:{currentDiastolicInc} -- lastPushDiastolicInc:{lastPushDiastolicInc}");
  357. _logger.LogInformation($"{imeiDel}--{nameof(Worker)}-- 定时校准,发给设备的绝对增量值=(上次绝对增量值+新数据的增量值)");
  358. _logger.LogInformation($"{nameof(Worker)} 开启血压标定值下发: {_configBoodPressResolver.EnableBPRefPush}");
  359. if (_configBoodPressResolver.EnableBPRefPush)
  360. // if (false) // 临时关闭
  361. {
  362. BloodPressCalibrationConfigModel bpIncData = new()
  363. {
  364. Imei = imeiDel,
  365. SystolicRefValue = SafeType.SafeInt(((int)systolicRefValue!)), //收缩压标定值,值为0 表示不生效
  366. DiastolicRefValue = SafeType.SafeInt(((int)diastolicRefValue!)), //舒张压标定值,值为0表示不生效
  367. SystolicIncValue = SafeType.SafeInt(((int)systolicInc!)), //收缩压显示增量,值为0 表示不生效
  368. DiastolicIncValue = SafeType.SafeInt(((int)diastolicInc!)) //舒张压显示增量,值为0 表示不生效
  369. };
  370. //var pushedBP = await _serviceIotApi.SetBloodPressCalibrationConfigAsync(bpIncData).ConfigureAwait(false);
  371. var response = await _serviceIotApi.SetBloodPressCalibrationConfig2Async(bpIncData).ConfigureAwait(false);
  372. var pushedBP = response.Flag;
  373. if (pushedBP)
  374. {
  375. #region 保存下推记录 stb_hm_bp_push_ref_inc_value
  376. var sql = $"INSERT INTO health_monitor.hm_bp_push_ref_inc_value_{imeiDel.Substring(imeiDel.Length - 2)} " +
  377. $"USING health_monitor.stb_hm_bp_push_ref_inc_value " +
  378. $"TAGS ('{imeiDel.Substring(imeiDel.Length - 2)}') " +
  379. $"VALUES(" +
  380. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  381. $"'{imeiDel}'," +
  382. $"{bpIncData.SystolicRefValue}," +
  383. $"{bpIncData.DiastolicRefValue}," +
  384. $"{bpIncData.SystolicIncValue}," +
  385. $"{bpIncData.DiastolicIncValue}," +
  386. $"{false}," +
  387. $"{systolicAvg}," +
  388. $"{diastolicAvg}," +
  389. $"{systolicAvgOffset}," +
  390. $"{diastolicAvgOffset}," +
  391. $"'{statStartTime:yyyy-MM-dd HH:mm:ss.fff}'," +
  392. $"'{startTime:yyyy-MM-dd HH:mm:ss.fff}'" +
  393. $")";
  394. _serviceTDengine.ExecuteInsertSQL(sql);
  395. #endregion
  396. #region 注册定时下发
  397. // 注册下次下推
  398. var endTime = DateTime.Now;
  399. #if DEBUG
  400. //long ttl = (long)((60 * 1000-(endTime-startTime).TotalMilliseconds)/1000);
  401. //await _serviceEtcd.PutValAsync(key, imeiDel,ttl, false).ConfigureAwait(false);
  402. var interval = 0;
  403. // 获取当前时间
  404. DateTime now = DateTime.Now;
  405. // 计算距离下一个$interval天后的8点的时间间隔
  406. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute + 2, 0).AddDays(interval);
  407. TimeSpan timeUntilNextRun = nextRunTime - now;
  408. // 如果当前时间已经超过了8点,将等待到明天后的8点
  409. if (timeUntilNextRun < TimeSpan.Zero)
  410. {
  411. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromMinutes(1));
  412. nextRunTime += timeUntilNextRun;
  413. }
  414. // var ttl = timeUntilNextRun.TotalMilliseconds;
  415. long ttl = (long)((timeUntilNextRun.TotalMilliseconds - (endTime - startTime).TotalMilliseconds) / 1000);
  416. var data = new
  417. {
  418. imei = imeiDel,
  419. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  420. ttl,
  421. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  422. };
  423. var result = JsonConvert.SerializeObject(data);
  424. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  425. #else
  426. // 每$interval天,晚上8点
  427. var interval = 1;
  428. // 获取当前时间
  429. DateTime now = DateTime.Now;
  430. // 计算距离下一个$interval天后的8点的时间间隔
  431. DateTime nextRunTime = new DateTime(now.Year, now.Month, now.Day, 20, 0, 0).AddDays(interval);
  432. TimeSpan timeUntilNextRun = nextRunTime - now;
  433. // 如果当前时间已经超过了8点,将等待到明天后的8点
  434. if (timeUntilNextRun < TimeSpan.Zero)
  435. {
  436. timeUntilNextRun = timeUntilNextRun.Add(TimeSpan.FromDays(1));
  437. nextRunTime += timeUntilNextRun;
  438. }
  439. // var ttl = timeUntilNextRun.TotalMilliseconds;
  440. long ttl = (long)((timeUntilNextRun.TotalMilliseconds-(endTime-startTime).TotalMilliseconds)/1000);
  441. var data = new
  442. {
  443. imei = imeiDel,
  444. create_time = now.ToString("yyyy-MM-dd HH:mm:ss"),
  445. ttl,
  446. next_run_time = nextRunTime.ToString("yyyy-MM-dd HH:mm:ss")
  447. };
  448. var result = JsonConvert.SerializeObject(data);
  449. await _serviceEtcd.PutValAsync(key, result, ttl, false).ConfigureAwait(false);
  450. #endif
  451. #endregion
  452. }
  453. else
  454. {
  455. _logger.LogInformation($"错误响应,没有下推数据:{response.Message}");
  456. }
  457. }
  458. }
  459. else
  460. {
  461. _logger.LogInformation($"向{imeiDel}统计数据已经失效");
  462. }
  463. #endregion
  464. }
  465. }
  466. break;
  467. }
  468. }
  469. catch (Exception ex)
  470. {
  471. _logger.LogInformation($"{nameof(WatchEvents)},出错: |{ex.Message}|{ex.StackTrace}");
  472. }
  473. });
  474. }
  475. }
  476. }