RabbitMQService.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. using System.Linq;
  2. using System.Data;
  3. using Microsoft.EntityFrameworkCore;
  4. using Newtonsoft.Json;
  5. using Ropin.Inspection.Model.Entities;
  6. using Ropin.Inspection.Model.ViewModel.DEV;
  7. using Ropin.Inspection.Model;
  8. using Ropin.Inspection.Repository.DEV.Interface;
  9. using Ropin.Inspection.Repository;
  10. using Ropin.Inspection.Common.Helper;
  11. using InitQ.Cache;
  12. using InfluxData.Net.InfluxDb;
  13. using InfluxData.Net.Common.Enums;
  14. using RabbitMQ.Client;
  15. using Microsoft.Extensions.Hosting;
  16. using System;
  17. using Microsoft.Extensions.Logging;
  18. using System.Threading.Tasks;
  19. using System.Threading;
  20. using Microsoft.Extensions.DependencyInjection;
  21. using System.Collections.Generic;
  22. using log4net;
  23. using RabbitMQ.Client.Events;
  24. using System.Text;
  25. using System.Threading.Channels;
  26. using FBoxClientDriver.Contract.Entity;
  27. namespace Ropin.Environmentally.LedgeService1
  28. {
  29. public class RabbitMQService : IHostedService, IDisposable
  30. {
  31. private readonly IServiceProvider _provider;
  32. private InfluxDbClient clientDb;
  33. private static readonly ILog log = LogManager.GetLogger(typeof(RabbitMQService));
  34. private readonly RabbitMQModel _rabbitMQModel;
  35. private readonly IniInfluxData _IniInfluxData;
  36. public RabbitMQService(IServiceProvider provider, RabbitMQModel rabbitMQModel, IniInfluxData IniInfluxData)
  37. {
  38. this._provider = provider;
  39. _rabbitMQModel = rabbitMQModel;
  40. _IniInfluxData = IniInfluxData;
  41. IniInflux();
  42. }
  43. private IConnection con;
  44. private IModel channel;
  45. public Task StartAsync(CancellationToken cancellationToken)
  46. {
  47. Task.Run(async () =>
  48. {
  49. await AddRabbitMQ();
  50. //while (true)
  51. //{
  52. // //await DevStatusChange("0", "8453d5ed-8a21-4880-88e7-f872e93551bf", "295458455312930168", DateTime.Now);
  53. // await Task.Delay(5000);//10000:10s
  54. //}
  55. });
  56. return Task.CompletedTask;
  57. }
  58. public Task StopAsync(CancellationToken cancellationToken)
  59. {
  60. Dispose();
  61. return Task.CompletedTask;
  62. }
  63. public void Dispose()
  64. {
  65. channel.Close();
  66. con.Close();
  67. }
  68. public async Task AddRabbitMQ()
  69. {
  70. try
  71. {
  72. var factory = new ConnectionFactory()
  73. {
  74. HostName = _rabbitMQModel.HostName,//"60.204.212.71",//IP地址
  75. Port = _rabbitMQModel.Port,//5672,//端口号
  76. UserName = _rabbitMQModel.UserName,//"guest",//用户账号
  77. VirtualHost = _rabbitMQModel.VirtualHost,//"/",
  78. Password = _rabbitMQModel.Password,// "guest"//用户密码
  79. };
  80. if (con == null || con.IsOpen == false)
  81. {
  82. con = factory.CreateConnection();//创建连接对象
  83. }
  84. if (channel == null || channel.IsOpen == false)
  85. {
  86. channel = con.CreateModel();//创建连接会话对象
  87. }
  88. channel.ExchangeDeclare(_rabbitMQModel.ExchangeName, type: ExchangeType.Direct); // Direct 交换机示例
  89. //声明队列
  90. var queueName = channel.QueueDeclare(
  91. queue: _rabbitMQModel.QueueName, //消息队列名称
  92. durable: false, //是否缓存
  93. exclusive: false,
  94. autoDelete: false,
  95. arguments: null
  96. ).QueueName;
  97. channel.QueueBind(queueName, _rabbitMQModel.ExchangeName, _rabbitMQModel.RoutingKey);
  98. //告诉Rabbit每次只能向消费者发送一条信息,再消费者未确认之前,不再向他发送信息
  99. channel.BasicQos(0, 1, false);
  100. channel.ConfirmSelect(); // 开启消息确认模式
  101. //创建消费者对象
  102. var consumer = new EventingBasicConsumer(channel);
  103. consumer.Received += async (model, ea) =>
  104. {
  105. try
  106. {
  107. var body = ea.Body.ToArray();
  108. var message = Encoding.UTF8.GetString(body);
  109. log.Info("【RabbitMQ】" + message);
  110. var ReceiveData = JsonConvert.DeserializeObject<ReceiveRabbitMQData>(message);
  111. bool result =await DevStatusChange("0", ReceiveData.devStoreCode, ReceiveData.devRunSpot, ReceiveData.time);
  112. if (result)
  113. {
  114. channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
  115. }
  116. else
  117. {
  118. channel.BasicNack(ea.DeliveryTag, false, true); // 重新入队或发送到死信队列的逻辑需要自定义实现
  119. }
  120. }
  121. catch (Exception ex)
  122. {
  123. channel.BasicNack(ea.DeliveryTag, false, true); // 重新入队或发送到死信队列的逻辑需要自定义实现
  124. log.Info("【RabbitMQ-接收消息处理异常了】" + ex.Message);
  125. }
  126. };
  127. //消费者开启监听 将autoAck设置false 手动确认关闭;true:自动关闭;
  128. channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer);
  129. }
  130. catch (Exception ex)
  131. {
  132. log.Info("【异常-RabbitMQ】" + ex.Message);
  133. }
  134. }
  135. #region
  136. /// <summary>
  137. /// 运行台账-【动态】
  138. /// </summary>
  139. /// <param name="devStatus"></param>
  140. /// <param name="devStoreCode"></param>
  141. /// <param name="devRunSpot"></param>
  142. /// <returns></returns>
  143. private async Task<bool> DevStatusChange(string devStatus, string devStoreCode, string devRunSpot, DateTime? time)
  144. {
  145. bool result = false;
  146. try
  147. {
  148. using (var scope = _provider.GetRequiredService<IServiceScopeFactory>().CreateScope())
  149. {
  150. var _redisService = scope.ServiceProvider.GetService<ICacheService>();
  151. DateTime startTime = await _redisService.GetAsync<DateTime>("fanyibox_devStartRun_" + devRunSpot);
  152. DateTime endTime = await _redisService.GetAsync<DateTime>("fanyibox_devEndRun_" + devRunSpot);
  153. var _tmtnDevOpsRecordRepository = scope.ServiceProvider.GetService<ITmtnDevOpsRecordRepository>();
  154. var _devDevOpeAccountConfigService = scope.ServiceProvider.GetService<Idev_DevOpeAccountConfigRepository>();
  155. //var _mtnPushMsgResultRepository = scope.ServiceProvider.GetService<ITmtnPushMsgResultRepository>();
  156. var _tsysMessageRepository = scope.ServiceProvider.GetService<ITsysMessageRepository>();
  157. var solidWasteRecordItems = await _tmtnDevOpsRecordRepository.GetRecordsConditionAsync(new TmtnDevOpsRecordDetailSearchModel { bSolidWaste = true, C_DevStoreCode = devStoreCode, IsPagination = false, Start = startTime, End = endTime });
  158. var devAccountConfig = await _devDevOpeAccountConfigService.GetByConditionAsync(t => t.C_DevStoreCode == devStoreCode);
  159. using (var dbContext = scope.ServiceProvider.GetService<InspectionDbContext>())//
  160. {
  161. var devStore = dbContext.TDEV_DevStore.Where(x => x.C_ID == devStoreCode).FirstOrDefault();
  162. //运行台账
  163. if (devStatus == "0")
  164. {
  165. bool isAlarm = false;
  166. var devOpeAccountS = dbContext.GetDbSet<TDEV_DevOpeAccount>();
  167. var devAccountConfigModel = devAccountConfig.OrderByDescending(t => t.D_CreateOn).FirstOrDefault();
  168. if (devAccountConfigModel != null)
  169. {
  170. if (!string.IsNullOrEmpty(devAccountConfigModel.C_Config))
  171. {
  172. TdevDevOpeAccountConfigViewModel configList = JsonConvert.DeserializeObject<TdevDevOpeAccountConfigViewModel>(devAccountConfigModel.C_Config);
  173. if (configList != null)
  174. {
  175. IEnumerable<TDEV_WebScadaDevSpot> items = _redisService.Get<IEnumerable<TDEV_WebScadaDevSpot>>("fanyibox_devStore_" + devStoreCode + "_spot");
  176. if (startTime.IsNotEmptyOrNull() && endTime.IsNotEmptyOrNull() && startTime != DateTime.MinValue && endTime != DateTime.MinValue)
  177. {
  178. isAlarm = await GetDevAlarmData(devStoreCode, startTime, endTime) >= 1;
  179. }
  180. List<SolidWaste> DevOpsRecordSolidWaste = new List<SolidWaste>();
  181. if (solidWasteRecordItems.Any() && solidWasteRecordItems.FirstOrDefault() != null)
  182. foreach (var item in solidWasteRecordItems.ToList())
  183. {
  184. if (item.C_Status == "4")
  185. {
  186. if (!string.IsNullOrWhiteSpace(item.C_SolidWaste))
  187. DevOpsRecordSolidWaste.Add(JsonConvert.DeserializeObject<SolidWaste>(item.C_SolidWaste));
  188. }
  189. }
  190. Dictionary<string, object> datas = new Dictionary<string, object>();
  191. #region
  192. datas.Add("Date", time);
  193. foreach (Inspection.Model.ViewModel.DEV.RunSpotConfig item in configList.RunSpotConfigList)
  194. {
  195. if (item.Name == "DevStoreName")
  196. {
  197. datas.Add(item.Name, devStore.C_Name);
  198. }
  199. else if (item.Name == "RunStartTime")
  200. {
  201. datas.Add(item.Name, startTime);
  202. }
  203. else if (item.Name == "RunEndTime")
  204. {
  205. datas.Add(item.Name, endTime);
  206. }
  207. else if (item.Name == "RunWhetherNormal")
  208. {
  209. datas.Add(item.Name, isAlarm);
  210. }
  211. else if (item.Name == "DischargeTime")
  212. { datas.Add(item.Name, (endTime - startTime).TotalHours.ToString("F2")); }
  213. else if (item.Name == "ConsumableName" || item.Name == "WasteName")
  214. {
  215. datas.Add(item.Name, DevOpsRecordSolidWaste.Any() ? string.Join(",", DevOpsRecordSolidWaste.Select(x => x.NameSpecification).ToList().ToArray()) : "/");
  216. }
  217. else if (item.Name == "ConsumableReplacementQuantity")
  218. {
  219. int number = DevOpsRecordSolidWaste.Any() ? DevOpsRecordSolidWaste.Sum(x => (string.IsNullOrEmpty(x.SolidWasteNumber) ? 0 : Convert.ToInt32(x.SolidWasteNumber))) : 0;
  220. datas.Add(item.Name, number);
  221. }
  222. else if (item.Name == "WasteProduction")
  223. {
  224. int number = DevOpsRecordSolidWaste.Any() ? DevOpsRecordSolidWaste.Sum(x => (string.IsNullOrEmpty(x.DropNumber) ? 0 : Convert.ToInt32(x.DropNumber))) : 0;
  225. datas.Add(item.Name, number);
  226. }
  227. else
  228. {
  229. if (item.BReadDevSpot)
  230. {
  231. string vals = "0"; string valsMax = "0"; string valsMin = "0";
  232. TDEV_WebScadaDevSpot webScadaDevSpot = items?.Where(x => x.C_Name == item.DevSpotName).FirstOrDefault();
  233. if (webScadaDevSpot == null)
  234. {
  235. datas.Add(item.Name, vals);
  236. datas.Add(item.Name + "_Max", valsMax);
  237. datas.Add(item.Name + "_Min", valsMin);
  238. continue;
  239. }
  240. string SpotId = webScadaDevSpot.C_DevSpotCode.ToString();
  241. if (!string.IsNullOrEmpty(SpotId) && startTime.IsNotEmptyOrNull() && endTime.IsNotEmptyOrNull() && startTime != DateTime.MinValue && endTime != DateTime.MinValue)
  242. {
  243. endTime = DateTime.Now;
  244. vals = await GetMeanData(SpotId, startTime, endTime);
  245. valsMax = await GetDataMax(SpotId, startTime, endTime);
  246. valsMin = await GetDataMin(SpotId, startTime, endTime);
  247. if (vals == null)
  248. {
  249. SpotId = webScadaDevSpot.C_ID.ToString();
  250. vals = await GetMeanData(SpotId, startTime, endTime);
  251. valsMax = await GetDataMax(SpotId, startTime, endTime);
  252. valsMin = await GetDataMin(SpotId, startTime, endTime);
  253. }
  254. }
  255. vals = string.IsNullOrEmpty(vals) ? "0" : Convert.ToDouble(vals).ToString("0.0");
  256. valsMax = string.IsNullOrEmpty(valsMax) ? "0" : Convert.ToDouble(valsMax).ToString("0.0");
  257. valsMin = string.IsNullOrEmpty(valsMin) ? "0" : Convert.ToDouble(valsMin).ToString("0.0");
  258. datas.Add(item.Name, vals);
  259. datas.Add(item.Name + "_Max", valsMax);
  260. datas.Add(item.Name + "_Min", valsMin);
  261. }
  262. else
  263. {
  264. var itemData = configList.RunSpotConfigList?.Where(x => x.Name == item.Name).FirstOrDefault();
  265. datas.Add(item.Name, itemData?.Value);
  266. }
  267. }
  268. }
  269. #endregion
  270. await devOpeAccountS.AddRangeAsync(new TDEV_DevOpeAccount
  271. {
  272. C_ID = Guid.NewGuid().ToString(),
  273. C_DevStoreCode = devStoreCode,
  274. C_Content = JsonConvert.SerializeObject(datas),
  275. C_Remark = "",
  276. C_DevOpeAccountConfigCode = devAccountConfigModel.C_ID,
  277. C_CreateBy = Guid.Parse("6e864cbc-5252-11ec-8681-fa163e02b3e4"),
  278. D_CreateOn = DateTime.Now
  279. });
  280. var qty = await dbContext.SaveChangesAsync();
  281. result = qty > 0 ? true : false;
  282. if (!result)
  283. {
  284. log.Info($"台账保存失败:【{JsonConvert.SerializeObject(datas)}】");
  285. }
  286. }
  287. }
  288. }
  289. else
  290. {
  291. result=true;
  292. }
  293. }
  294. if (result)
  295. {
  296. var devStoreLog = dbContext.GetDbSet<TDEV_DevStoreLog>();
  297. await devStoreLog.AddAsync(new TDEV_DevStoreLog
  298. {
  299. C_ID = Guid.NewGuid().ToString(),
  300. C_DeviceCode = devStoreCode,
  301. C_Type = devStatus == "1" ? "2" : "3",
  302. C_LogMsg = devStatus == "1" ? "开启" : "关闭",
  303. C_CreateBy = Guid.Parse("6e864cbc-5252-11ec-8681-fa163e02b3e4"),
  304. D_CreateOn = DateTime.Now
  305. });
  306. int sumbitLog = await dbContext.SaveChangesAsync();
  307. if (sumbitLog <= 0)
  308. {
  309. log.Info($"[TDEV_DevStoreLog]保存失败:【devStoreCode={devStoreCode}】");
  310. }
  311. }
  312. #region 业主设备运行记录
  313. try
  314. {
  315. DevStoreRunRecord runRecord = new DevStoreRunRecord();
  316. if (!string.IsNullOrEmpty(devStore.C_RunRecord))
  317. {
  318. runRecord = JsonConvert.DeserializeObject<DevStoreRunRecord>(devStore.C_RunRecord);
  319. //TmtnPushMsgResultSearchModel ResultSearchMode = new TmtnPushMsgResultSearchModel();
  320. //ResultSearchMode.C_DevStoreCode = devStoreCode;
  321. //ResultSearchMode.D_Start = Convert.ToDateTime(runRecord.LastOffDate);
  322. TsysMessageSearchModel tsysMessage = new TsysMessageSearchModel();
  323. tsysMessage.C_DevCode = devStoreCode;
  324. if (!string.IsNullOrEmpty(runRecord.LastOffDate) && runRecord.LastOffDate != "null")
  325. {
  326. tsysMessage.BeginTime = Convert.ToDateTime(runRecord.LastOffDate);
  327. }
  328. else
  329. {
  330. tsysMessage.BeginTime = null;
  331. }
  332. DevAlarmCount alarmCount = await _tsysMessageRepository.GetMsgDevRunTimeAsync(tsysMessage);
  333. //await _mtnPushMsgResultRepository.GetPushMsgResultContentAsync(ResultSearchMode);
  334. if (alarmCount.TotalTime!="0.0.0")
  335. {
  336. runRecord.LastOffDate = alarmCount.LastOffDate;
  337. runRecord.RunDuration = alarmCount.nowTime;
  338. var arrayRun = runRecord.TotalRunDuration.Split('.');
  339. var runData = alarmCount.TotalTime.Split(".");
  340. int m = Convert.ToInt32(arrayRun[2]) + Convert.ToInt32(runData[2]);
  341. int h = 0;
  342. if (m >= 60)
  343. {
  344. m = m - 60;
  345. h++;
  346. }
  347. h = h + Convert.ToInt32(arrayRun[1]) + Convert.ToInt32(runData[1]);
  348. int d = 0;
  349. if (h >= 24)
  350. {
  351. h = h - 24;
  352. d++;
  353. }
  354. d = d + Convert.ToInt32(arrayRun[0]) + Convert.ToInt32(runData[0]);
  355. runRecord.TotalRunDuration = d + "." + h + "." + m;
  356. if (!string.IsNullOrEmpty(runRecord.FiratOnDate) && !string.IsNullOrEmpty(runRecord.LastOffDate))
  357. {
  358. DateTime time1 = Convert.ToDateTime(runRecord.FiratOnDate);
  359. DateTime time2 = Convert.ToDateTime(runRecord.LastOffDate);
  360. TimeSpan diff = time2.Subtract(time1);
  361. int day = d - diff.Days;
  362. if (diff.Hours > h)
  363. {
  364. d--; h = h + 24;
  365. }
  366. int hours = h - diff.Hours;
  367. if (diff.Minutes > m)
  368. {
  369. h--; m = m + 60;
  370. }
  371. int minutes = m - diff.Minutes;
  372. runRecord.TotalSpotDuration = day + "." + hours + "." + minutes;
  373. }
  374. devStore.C_RunRecord = JsonConvert.SerializeObject(runRecord);
  375. dbContext.TDEV_DevStore.Update(devStore);
  376. int saveresult = await dbContext.SaveChangesAsync();
  377. }
  378. }
  379. else
  380. {
  381. //TmtnPushMsgResultSearchModel ResultSearchMode = new TmtnPushMsgResultSearchModel();
  382. //ResultSearchMode.C_DevStoreCode = devStoreCode;
  383. //DevAlarmCount alarmCount = await _mtnPushMsgResultRepository.GetPushMsgResultContentAsync(ResultSearchMode);
  384. TsysMessageSearchModel tsysMessage = new TsysMessageSearchModel();
  385. tsysMessage.C_DevCode = devStoreCode;
  386. if (!string.IsNullOrEmpty(runRecord.LastOffDate) && runRecord.LastOffDate != "null")
  387. {
  388. tsysMessage.BeginTime = Convert.ToDateTime(runRecord.LastOffDate);
  389. }
  390. else
  391. {
  392. tsysMessage.BeginTime = null;
  393. }
  394. DevAlarmCount alarmCount = await _tsysMessageRepository.GetMsgDevRunTimeAsync(tsysMessage);
  395. runRecord.LastOffDate = alarmCount.LastOffDate;
  396. runRecord.FiratOnDate = alarmCount.FiratOnDate;
  397. runRecord.TotalRunDuration = alarmCount.TotalTime;
  398. runRecord.TotalSpotDuration = alarmCount.TotalSpotTime;
  399. runRecord.RunDuration = alarmCount.nowTime;
  400. int RepairOrder = dbContext.TMTN_RepairOrder.Where(x => x.C_DevStoreCode == devStoreCode && x.C_Status == "7").Count();
  401. TmtnDevOpsDetailSearchModel tmtnDevOps = new TmtnDevOpsDetailSearchModel();
  402. tmtnDevOps.C_Status = "7";
  403. tmtnDevOps.C_DevStoreCode = devStoreCode;
  404. var DevOps = _tmtnDevOpsRecordRepository.GetDevOpsList(tmtnDevOps);
  405. runRecord.MTNRepairOrder = RepairOrder;
  406. runRecord.MTNDevOps = DevOps.Result.Count();
  407. devStore.C_RunRecord = JsonConvert.SerializeObject(runRecord);
  408. dbContext.TDEV_DevStore.Update(devStore);
  409. int saveresult = await dbContext.SaveChangesAsync();
  410. }
  411. }
  412. catch (Exception ex)
  413. {
  414. log.Info($"【业主设备运行记录】【异常信息:{ex.Message}】【devStoreCode={devStoreCode}】");
  415. }
  416. #endregion
  417. }
  418. }
  419. }
  420. catch (Exception ex)
  421. {
  422. log.Info($"【台账异常】【异常信息:{ex.Message}】【devStoreCode={devStoreCode};devRunSpot={devRunSpot};time={time}】");
  423. }
  424. return result;
  425. }
  426. private void IniInflux()
  427. {
  428. //连接InfluxDb的API地址、账号、密码
  429. var infuxUrl = _IniInfluxData.infuxUrl;// "http://60.204.212.71:8085/";
  430. var infuxUser = _IniInfluxData.infuxUser;// "admin";
  431. var infuxPwd = _IniInfluxData.infuxPwd;//"123456";
  432. //创建InfluxDbClient实例
  433. clientDb = new InfluxDbClient(infuxUrl, infuxUser, infuxPwd, InfluxDbVersion.Latest);
  434. }
  435. public async Task<string> GetMeanData(string id, DateTime start, DateTime end)
  436. {
  437. //传入查询命令,支持多条
  438. var queries = new[]
  439. {
  440. //"SELECT mean(Val) FROM fanyidev where (Id ='"+id+"') and time > '"+ start.ToUniversalTime().ToString("yyyy-MM-dd hh:mm:ss") +"' and time < '" + end.ToUniversalTime().ToString("yyyy-MM-dd hh:mm:ss") + "'"
  441. "SELECT mean(Val) FROM fanyidev where (Id ='"+id+"') and time > '"+ start.AddHours(-8).ToString("yyyy-MM-ddTHH:mm:ssZ") +"' and time < '" + end.AddHours(-8).ToString("yyyy-MM-ddTHH:mm:ssZ") + "' TZ('Asia/Shanghai')"
  442. //"SELECT mean(Val) FROM fanyidev where (Id ='224873679711261516') and time > now() - 5m and time < now()"
  443. };
  444. var dbName = "fanyidb";
  445. //从指定库中查询数据
  446. var response = await clientDb.Client.QueryAsync(queries, dbName);
  447. if (!response.Any())
  448. return "0";
  449. //得到Serie集合对象(返回执行多个查询的结果)
  450. var series = response.ToList();
  451. //取出第一条命令的查询结果,是一个集合
  452. var list = series[0].Values;
  453. //从集合中取出第一条数据
  454. var info_model = list.FirstOrDefault();
  455. Console.WriteLine($"GetMeanData from DevEvent: ${info_model[1]}");
  456. using (var scope = _provider.GetRequiredService<IServiceScopeFactory>().CreateScope())
  457. {
  458. var _redisService = scope.ServiceProvider.GetService<ICacheService>();
  459. await _redisService.SetAsync("fanyibox_devspot_mean_" + id, info_model[1]);
  460. }
  461. return info_model[1]?.ToString();
  462. }
  463. public async Task<string> GetDataMax(string id, DateTime start, DateTime end)
  464. {
  465. //传入查询命令,支持多条
  466. var queries = new[]
  467. {
  468. "SELECT Max(Val) FROM fanyidev where (Id ='"+id+"') and time > '"+ start.AddHours(-8).ToString("yyyy-MM-ddTHH:mm:ssZ") +"' and time < '" + end.AddHours(-8).ToString("yyyy-MM-ddTHH:mm:ssZ") + "' TZ('Asia/Shanghai')"
  469. };
  470. var dbName = "fanyidb";
  471. //从指定库中查询数据
  472. var response = await clientDb.Client.QueryAsync(queries, dbName);
  473. if (!response.Any())
  474. return "0";
  475. //得到Serie集合对象(返回执行多个查询的结果)
  476. var series = response.ToList();
  477. //取出第一条命令的查询结果,是一个集合
  478. var list = series[0].Values;
  479. //从集合中取出第一条数据
  480. var info_model = list.FirstOrDefault();
  481. Console.WriteLine($"GetMeanData from DevEvent: ${info_model[1]}");
  482. using (var scope = _provider.GetRequiredService<IServiceScopeFactory>().CreateScope())
  483. {
  484. var _redisService = scope.ServiceProvider.GetService<ICacheService>();
  485. await _redisService.SetAsync("fanyibox_devspot_max_" + id, info_model[1]);
  486. }
  487. return info_model[1]?.ToString();
  488. }
  489. public async Task<string> GetDataMin(string id, DateTime start, DateTime end)
  490. {
  491. //传入查询命令,支持多条
  492. var queries = new[]
  493. {
  494. "SELECT MIN(Val) FROM fanyidev where (Id ='"+id+"') and time > '"+ start.AddHours(-8).ToString("yyyy-MM-ddTHH:mm:ssZ") +"' and time < '" + end.AddHours(-8).ToString("yyyy-MM-ddTHH:mm:ssZ") + "' TZ('Asia/Shanghai')"
  495. };
  496. var dbName = "fanyidb";
  497. //从指定库中查询数据
  498. var response = await clientDb.Client.QueryAsync(queries, dbName);
  499. if (!response.Any())
  500. return "0";
  501. //得到Serie集合对象(返回执行多个查询的结果)
  502. var series = response.ToList();
  503. //取出第一条命令的查询结果,是一个集合
  504. var list = series[0].Values;
  505. //从集合中取出第一条数据
  506. var info_model = list.FirstOrDefault();
  507. Console.WriteLine($"GetMeanData from DevEvent: ${info_model[1]}");
  508. using (var scope = _provider.GetRequiredService<IServiceScopeFactory>().CreateScope())
  509. {
  510. var _redisService = scope.ServiceProvider.GetService<ICacheService>();
  511. await _redisService.SetAsync("fanyibox_devspot_min_" + id, info_model[1]);
  512. }
  513. return info_model[1]?.ToString();
  514. }
  515. public async Task<int> GetDevAlarmData(string id, DateTime start, DateTime end)
  516. {
  517. //传入查询命令,支持多条
  518. var queries = new[]
  519. {
  520. //"SELECT Max(Val) FROM fanyidevalarm where (Id ='"+id+"') and time > '"+ start.ToUniversalTime().ToString("yyyy-MM-dd hh:mm:ss") +"' and time < '" + end.ToUniversalTime().ToString("yyyy-MM-dd hh:mm:ss") + "'"
  521. "SELECT Max(Val) FROM fanyidevalarm where (Id ='"+id+"') and time > '"+ start.AddHours(-8).ToString("yyyy-MM-ddTHH:mm:ssZ") +"' and time < '" + end.AddHours(-8).ToString("yyyy-MM-ddTHH:mm:ssZ") + "' TZ('Asia/Shanghai')"
  522. //"SELECT mean(Val) FROM fanyidev where (Id ='224873679711261516') and time > now() - 5m and time < now()"
  523. };
  524. var dbName = "fanyidb";
  525. //从指定库中查询数据
  526. var response = await clientDb.Client.QueryAsync(queries, dbName);
  527. if (!response.Any())
  528. return 0;
  529. //得到Serie集合对象(返回执行多个查询的结果)
  530. var series = response.ToList();
  531. //取出第一条命令的查询结果,是一个集合
  532. var list = series[0].Values;
  533. //从集合中取出第一条数据
  534. var info_model = list.FirstOrDefault();
  535. if (!info_model.Any())
  536. return 0;
  537. Console.WriteLine($"GetMeanData from DevEvent: ${info_model[1]}");
  538. return await Task.FromResult<int>(Convert.ToInt32(info_model[1]));
  539. }
  540. #endregion
  541. }
  542. }