using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Linq; using System.Data; using InitQ.Cache; using FBoxClientDriver.Contract; using Ropin.Inspection.Service; using Ropin.Inspection.Repository; using Ropin.Inspection.Model.Entities; using Ropin.Inspection.Model; using Newtonsoft.Json; using LinqKit; using Ropin.Inspection.Common.Helper; using Microsoft.AspNetCore.NodeServices; using Microsoft.EntityFrameworkCore; using InfluxData.Net.InfluxDb; using InfluxData.Net.Common.Enums; using InfluxData.Net.InfluxDb.Models; using Newtonsoft.Json.Linq; using System.Net.Http; using System.Net; using Coravel.Events.Interfaces; using Ropin.Inspection.Common; using Castle.Core.Internal; using System.Collections.Concurrent; using System.Diagnostics; using Ropin.Inspection.Model.ViewModel.DEV; using Ropin.Inspection.Repository.DEV.Interface; using RabbitMQ.Client; using log4net; using Microsoft.AspNetCore.SignalR; using Ropin.Environmentally.WebScada.Hubs; using Autofac.Core; using Google.Protobuf.WellKnownTypes; using System.Text.RegularExpressions; namespace Ropin.Environmentally.WebScada.Work { public class HostedService : IHostedService, IDisposable { private readonly ILogger _logger; private readonly IServiceProvider _provider; //private readonly ICacheService _redisService; private readonly IDbContextFactory _dbContextFactory; private readonly Func _dbFuncContextFactory; private readonly INodeServices _nodeServices; private readonly ITdevWebScadaDevSpotRepository _devWebScadaDevSpotRepository; //private readonly ITdevDevStoreService _devDevStoreService; private readonly ITdevDevStoreRepository _tdevDevStoreRepository; private readonly IPushMsgService _pushMsgService; private readonly IHttpClientFactory httpClientFactory; private demo fanyi; private InfluxDbClient clientDb; private readonly IDispatcher _dispatcher; private readonly ITdevDevStoreLogRepository _tdevDevStoreLogRepository; private readonly ITmtnDevOpsRecordRepository _tmtnDevOpsRecordRepository; private readonly Idev_DevOpeAccountConfigRepository _devDevOpeAccountConfigService; private readonly IHubContext _hubContext; private static readonly ILog log = LogManager.GetLogger(typeof(HostedService)); private readonly RabbitMQModel _rabbitMQModel; private readonly APIUrlData _aPIUrlData; private readonly IniInfluxData _IniInfluxData; //bool IsFirst = true; public HostedService(ILogger logger, IServiceProvider provider, ITdevDevStoreRepository devDevStoreRepository, INodeServices nodeServices, //IPushMsgService pushMsgService, Func dbContextFactory, IHttpClientFactory httpClientFactory, IDispatcher dispatcher, //IDbContextFactory dbContextFactory, ITdevWebScadaDevSpotRepository devWebScadaDevSpotRepository, ITdevDevStoreLogRepository tdevDevStoreLogRepository, Idev_DevOpeAccountConfigRepository devDevOpeAccountConfigService, ITmtnDevOpsRecordRepository tmtnDevOpsRecordRepository, IHubContext hubContext, RabbitMQModel rabbitMQModel, APIUrlData aPIUrlData, IniInfluxData iniInfluxData) { _logger = logger; _provider = provider; _tdevDevStoreRepository = devDevStoreRepository; _devWebScadaDevSpotRepository = devWebScadaDevSpotRepository; _nodeServices = nodeServices; this.httpClientFactory = httpClientFactory; _dispatcher = dispatcher; //_pushMsgService = pushMsgService; 用不了 // _devDevStoreService = devDevStoreService; //using (var scope = _provider.GetRequiredService().CreateScope()) //{ // _redisService = scope.ServiceProvider.GetService(); //}; _dbFuncContextFactory = dbContextFactory; //var v = _provider.GetRequiredService>(); //_dbContextFactory = dbContextFactory;// _IniInfluxData = iniInfluxData; IniInflux(); _tdevDevStoreLogRepository = tdevDevStoreLogRepository; _tmtnDevOpsRecordRepository = tmtnDevOpsRecordRepository; _devDevOpeAccountConfigService = devDevOpeAccountConfigService; _hubContext = hubContext; _rabbitMQModel = rabbitMQModel; _aPIUrlData = aPIUrlData; } private object _locker = new object(); public Task StartAsync(CancellationToken cancellationToken) { //Task.Run(async () => //{ // await Test(new TDEV_DevStore { C_ID = "59e98720-f26a-4322-9dad-c92bb5d7ae8b" }); //}); //测试定时 Task.Run(async() => { fanyi = new demo(); fanyi._fbox.DataMonitorValueChanged += _fbox_DataMonitorValueChanged; //fanyi.Start().Wait(); //while (true) //{ // //string str = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); // //log.Info("-testWebSocket:" + str); // //await _hubContext.Clients.All.SendAsync("testWebSocket", str); // using (var scope = _provider.GetRequiredService().CreateScope()) // { // var _redisService = scope.ServiceProvider.GetService(); // var devValues = _redisService.Get("fanyibox_devStore_015ea688-0698-408c-94b7-0475b14a20fc"); // log.Info("-testWebSocket:" + devValues.ToString()); // await _hubContext.Clients.All.SendAsync("testWebSocket_015ea688-0698-408c-94b7-0475b14a20fc", devValues.ToString()); // } // await Task.Delay(60000); // } }); //Task.Run(() => //{ // Timer t0 = new Timer(async (o) => { // using (var dbContext = _dbFuncContextFactory()) // { // IEnumerable devStore = dbContext.TDEV_DevStore.AsEnumerable(); // //IList itemList = items.ToList(); // //var devStore = await _tdevDevStoreRepository.GetAllAsync(); // await _redisService.SetAsync("fanyibox_devStore", devStore.ToList()); // } // }, null, 500, 5000); //}); #region Task.Run(async () => { while (true) { try { //await this._dispatcher.Broadcast(new DevEvent("niu","aa")); //var services = new ServiceCollection(); //var provider = services.BuildServiceProvider(); //var dispatcher = provider.GetRequiredService() as Dispatcher; //dispatcher.Register() // .Subscribe(); //await dispatcher.Broadcast(new DevEvent("niu")); //List tasks = new List(); //tasks.Add(); IList devStore = null; IList devStoreSpot = null; using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); //var _tmtnDevOpsRecordRepository = scope.ServiceProvider.GetService(); //var solidWasteRecordItems = await _tmtnDevOpsRecordRepository.GetRecordsConditionAsync(new TmtnDevOpsRecordDetailSearchModel { bSolidWaste = true, C_DevStoreCode = "8793c6c8-d855-421e-9fa1-d25f914bb730", IsPagination = false, Start = DateTime.Now.AddDays(-1), End = DateTime.Now }); //var devAccountConfig = await _devDevOpeAccountConfigService.GetByConditionAsync(t => t.C_DevStoreCode == "8793c6c8-d855-421e-9fa1-d25f914bb730"); using (var dbContext = scope.ServiceProvider.GetService()) { devStore = dbContext.TDEV_DevStore.AsQueryable().ToList(); devStoreSpot = dbContext.TDEV_WebScadaDevSpot.AsQueryable().ToList(); if (devStore != null && devStore.Count > 0) { //devStore = devStore.Where(t => t.C_Status != "0" && t.C_Status != "5").ToList(); devStore = devStore.Where(t => t.C_Status != "0").ToList(); } await _redisService.SetAsync("fanyibox_devStore", devStore); } if (devStore != null) { foreach (var devstore in devStore) { var predicate = PredicateBuilder.New(true);//查询条件,推荐后台使用这种方式灵活筛选 predicate = predicate.And(i => i.C_Status.Equals("1")); predicate = predicate.And(i => i.C_DevCode.Equals(devstore.C_ID)); IEnumerable items = devStoreSpot.Where(predicate).OrderBy(x => x.I_Sort).AsEnumerable(); await _redisService.SetAsync("fanyibox_devStore_" + devstore.C_ID + "_spot", items); } } }; await Task.Delay(10000); } catch (Exception ex) { _logger.LogInformation(ex.Message); await Task.Delay(1000); } } }); Task.Run(async () => { while (true) { try { //List tasks = new List(); //tasks.Add(); IEnumerable devStoresList = null; using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); if (await _redisService.ExistsAsync("fanyibox_devStore")) { var devStores = await _redisService.GetAsync("fanyibox_devStore"); if (string.IsNullOrWhiteSpace(devStores)) { Console.WriteLine("队列中数据不存在!"); await _redisService.SetAsync("fanyibox_error", "队列中数据不存在!"); } else { devStoresList = JsonConvert.DeserializeObject>(devStores); if (devStoresList != null) { devStoresList = devStoresList.Where(t => t.C_Status != "0").ToList(); foreach (var devstore in devStoresList) { JObject result = new JObject { { "device", new JArray() }, { "alarmlight", new JArray() } }; JArray deviceJarray = new JArray(); JArray alarmlightJarray = new JArray(); if (!jObjectDic.ContainsKey(devstore.C_ID)) jObjectDic.TryAdd(devstore.C_ID, result); if (!jArrayDic.ContainsKey(devstore.C_ID)) jArrayDic.TryAdd(devstore.C_ID, deviceJarray); if (!alarmlightJarrayDic.ContainsKey(devstore.C_ID)) alarmlightJarrayDic.TryAdd(devstore.C_ID, alarmlightJarray); if (!webScadaDevSpotDic.ContainsKey(devstore.C_ID)) webScadaDevSpotDic.TryAdd(devstore.C_ID, null); } //wait SendInterval(devStoresList); await SendIntervalNoDb(devStoresList); } } } } await Task.Delay(10000); //10000 } catch (Exception ex) { log.Info("Task2-异常:" + ex.Message); await Task.Delay(1000); } } }); Task.Run(async () => { while (true) { try { IEnumerable devStore = null; using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); if (await _redisService.ExistsAsync("fanyibox_devStore")) { var devStores = await _redisService.GetAsync("fanyibox_devStore"); if (string.IsNullOrWhiteSpace(devStores)) { Console.WriteLine("队列中数据不存在!"); await _redisService.SetAsync("fanyibox_error", "队列中数据不存在!"); } else { devStore = JsonConvert.DeserializeObject>(devStores); if (devStore != null) { devStore = devStore.Where(t => t.C_Status != "0").ToList(); } if (devStore != null) { await WebScadaDevSpotInterval(devStore); } } } } await Task.Delay(100); //10000 } catch (Exception ex) { _logger.LogInformation(ex.Message); await Task.Delay(100); } } }); Task.Run(async () => { while (true) { try { IEnumerable devStoresList = null; using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); if (await _redisService.ExistsAsync("fanyibox_devStore")) { var devStores = await _redisService.GetAsync("fanyibox_devStore"); if (string.IsNullOrWhiteSpace(devStores)) { Console.WriteLine("队列中数据不存在!"); await _redisService.SetAsync("fanyibox_error", "队列中数据不存在!"); } else { devStoresList = JsonConvert.DeserializeObject>(devStores); if (devStoresList.Any()) { devStoresList = devStoresList.Where(t => t.C_Status != "0").ToList(); foreach (var devstore in devStoresList) { string value = _redisService.Get("fanyibox_devStore_" + devstore.C_ID); if (!string.IsNullOrWhiteSpace(value) && value != "\"\"") { var devValues = JsonConvert.DeserializeObject(value); await AddData(devValues); } } } } } } await Task.Delay(60000); } catch (Exception ex) { _logger.LogInformation(ex.Message); await Task.Delay(1000); } } }); #endregion #region //AI报警同步 Task.Run(async () => { while (true) { try { using (HttpClient httpClient = httpClientFactory.CreateClient()) { var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(_aPIUrlData.PublicPushMessageAPI) }; var response = await httpClient.SendAsync(httpRequestMessage); string responseResult = await response.Content.ReadAsStringAsync(); log.Info($"AI报警数据同步接口返回【{responseResult}】"); } } catch (Exception ex) { _logger.LogInformation("AI报警同步"+ex.Message); } await Task.Delay(120000);//2分钟 } }); #endregion #region //Timer t = new Timer(async (o) => { // if (await _redisService.ExistsAsync("fanyibox_devStore")) // { // var devStores = await _redisService.GetAsync("fanyibox_devStore"); // if (string.IsNullOrWhiteSpace(devStores)) // { // Console.WriteLine("队列中数据不存在!"); // await _redisService.SetAsync("fanyibox_error", "队列中数据不存在!"); // } // else // { // IList devStoresList = JsonConvert.DeserializeObject>(devStores); // ParallelLoopResult result = Parallel.ForEach(devStoresList, (devstore, loopState, curIndex) => // { // using (var dbContext = _dbFuncContextFactory()) // { // var predicate = PredicateBuilder.New(true);//查询条件,推荐后台使用这种方式灵活筛选 // predicate = predicate.And(i => i.C_Status.Equals("1")); // predicate = predicate.And(i => i.C_DevCode.Equals(devstore.C_ID)); // IEnumerable items = dbContext.TDEV_WebScadaDevSpot.Where(predicate).AsEnumerable(); // IList itemList = items.ToList(); // if (!itemList.Any()) // { // _redisService.SetAsync("fanyibox_devStore_" + devstore.C_ID, string.Empty); // loopState.Break(); // } // List names = items.Select(x => x.C_Name).ToList(); // List groupnames = items.Select(x => x.C_GroupName).ToList(); // List calFormula = items.Select(x => x.C_CalFormula).ToList(); // List> calFormulaList = new List>(); // //var calFormulaList = JsonConvert.DeserializeObject>>(JsonConvert.SerializeObject(calFormula)); // foreach (var v in calFormula) // { // if (v != null) // calFormulaList.Add(JsonConvert.DeserializeObject>(v)); // } // if (calFormulaList.Count == 0) // { // calFormulaList = null; // calFormula = null; // } // string boxno = items.Select(x => x.C_BoxNo).FirstOrDefault(); // string storeCode = items.Select(x => x.C_StoreCode).FirstOrDefault(); // lock (_locker) // { // //var result = FanyiHelper.GetWebScadaDevSpotValue(devstore.C_ID, boxno, storeCode, names, groupnames, calFormula, _nodeServices, calFormulaList); // var result = ""; // _redisService.SetAsync("fanyibox_msgalarmdic", FanyiHelper.msgAlarmDic); // _redisService.SetAsync("fanyibox_devStore_" + devstore.C_ID, result); // } // } // }); // } // } // }, null, 500, 5000); //Task.Run(() => //{ // Timer t = new Timer( async (o) => // { // if (await _redisService.ExistsAsync("fanyibox_devStore")) // { // var devStores = await _redisService.GetAsync("fanyibox_devStore"); // if (string.IsNullOrWhiteSpace(devStores)) // { // Console.WriteLine("队列中数据不存在!"); // await _redisService.SetAsync("fanyibox_error", "队列中数据不存在!"); // } // else // { // IList devStoresList = JsonConvert.DeserializeObject>(devStores); // foreach (var devstore in devStoresList) // { // //using (var dbContext = _dbContextFactory.CreateDbContext()) // using (var dbContext = _dbFuncContextFactory()) // { // var predicate = PredicateBuilder.New(true);//查询条件,推荐后台使用这种方式灵活筛选 // predicate = predicate.And(i => i.C_Status.Equals("1")); // predicate = predicate.And(i => i.C_DevCode.Equals(devstore.C_ID)); // IEnumerable items = dbContext.TDEV_WebScadaDevSpot.Where(predicate).AsEnumerable(); // IList itemList = items.ToList(); // if (!itemList.Any()) // { // _redisService.Set("fanyibox_devStore_" + devstore.C_ID, string.Empty); // continue; // } // List names = items.Select(x => x.C_Name).ToList(); // List groupnames = items.Select(x => x.C_GroupName).ToList(); // List calFormula = items.Select(x => x.C_CalFormula).ToList(); // List> calFormulaList = new List>(); // //var calFormulaList = JsonConvert.DeserializeObject>>(JsonConvert.SerializeObject(calFormula)); // foreach (var v in calFormula) // { // if (v != null) // calFormulaList.Add(JsonConvert.DeserializeObject>(v)); // } // if (calFormulaList.Count == 0) // { // calFormulaList = null; // calFormula = null; // } // string boxno = items.Select(x => x.C_BoxNo).FirstOrDefault(); // string storeCode = items.Select(x => x.C_StoreCode).FirstOrDefault(); // var result = await FanyiHelper.GetWebScadaDevSpotValue(devstore.C_ID, boxno, storeCode, names, groupnames, calFormula, _nodeServices, calFormulaList); // _redisService.Set("fanyibox_msgalarmdic", FanyiHelper.msgAlarmDic); // _redisService.Set("fanyibox_devStore_" + devstore.C_ID, result); // } // } // //查询是否还有,如果有返回yes,没有返回no // } // } // else // Thread.Sleep(500); // //为避免CPU空转,在队列为空时休息0.5秒 // }, null, 500, 5000);//每5秒取一次 //}); #endregion return Task.CompletedTask; } private async Task Test(TDEV_DevStore devstore) { //await _redisService.SetAsync("fanyibox_devStore_" + devstore.C_ID, ""); #region xiaoxi HttpClient httpClient = httpClientFactory.CreateClient(); var msgData = new TpushMsgModel { C_DevStoreCode = "2ff323d3-fa27-4d02-836f-30d7c2bf6654", C_MsgTypeCode = "MSG_TYPE_012", Msg = "设备点报警", Subject = devstore.C_Name + "的设备点报警", DevNumber = devstore.C_NumberCode, DevName = devstore.C_Name, CreateOn = DateTime.Now.ToString(), UserName = "设备", GenerationType = 1, msgStatus = 1, }; var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(_aPIUrlData.PublicPushMessageAPI), Content = new StringContent(JsonConvert.SerializeObject(msgData), Encoding.UTF8, "application/json") }; var response = await httpClient.SendAsync(httpRequestMessage); string responseResult = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { } else { //todo } #endregion using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); using (var dbContext = scope.ServiceProvider.GetService()) { //using (var dbContext = _dbFuncContextFactory()) //{ var predicate = PredicateBuilder.New(true);//查询条件,推荐后台使用这种方式灵活筛选 predicate = predicate.And(i => i.C_Status.Equals("1")); predicate = predicate.And(i => i.C_DevCode.Equals(devstore.C_ID)); IEnumerable items = dbContext.TDEV_WebScadaDevSpot.Where(predicate).OrderBy(x => x.I_Sort).AsEnumerable(); //var list = await _repository.GetPageAsync(predicate, "I_Sort", searchModel.IsPagination, searchModel.PageIndex, searchModel.PageSize); //searchModel.TotalCount = list.Totals; //var dtoList = _mapper.Map, List>(list.Rows); IList itemList = items.ToList(); if (!itemList.Any()) { await _redisService.SetAsync("fanyibox_devStore_" + devstore.C_ID, string.Empty); } else { List devSpotCodes = items.Select(x => x.C_DevSpotCode).ToList(); List names = items.Select(x => x.C_Name).ToList(); List unitNames = items.Select(x => x.C_UnitName).ToList(); List groupnames = items.Select(x => x.C_GroupName).ToList(); List calFormula = items.Select(x => x.C_CalFormula).ToList(); List runs = items.Select(x => x.C_Run).ToList(); List Public = items.Select(x => x.C_Public).ToList(); List sort = items.Select(x => x.I_Sort).ToList(); List> calFormulaList = new List>(); foreach (var v in calFormula) { if (v != null) calFormulaList.Add(JsonConvert.DeserializeObject>(v)); } if (calFormulaList.Count == 0) { calFormulaList = null; calFormula = null; } string boxno = items.Select(x => x.C_BoxNo).FirstOrDefault(); string storeCode = items.Select(x => x.C_StoreCode).FirstOrDefault(); //lock (_locker) //{ var result = await FanyiHelper.GetWebScadaDevSpotValue(boxno, storeCode, names, unitNames, groupnames, calFormula, sort, runs, _nodeServices, calFormulaList, devSpotCodes, Public); //var result = ""; await _redisService.SetAsync("fanyibox_msgalarmdic", FanyiHelper.msgAlarmDic); await _redisService.SetAsync("fanyibox_devStore_" + devstore.C_ID, result); await AddData(result); string bAlaColour = "black"; foreach (var ala in result["alarmlight"]) { string strAlaColour = (string)ala["alarmcolour"]; if (strAlaColour == "red") { bAlaColour = "red"; } } if (bAlaColour == "red") { devstore.C_Status = "4"; dbContext.TDEV_DevStore.Update(devstore); await dbContext.SaveChangesAsync(); } else if (bAlaColour == "black") { devstore.C_Status = "2"; //后期通过TDEV_DevStore_Log取设备是否报警 dbContext.TDEV_DevStore.Update(devstore); await dbContext.SaveChangesAsync(); //await _pushMsgService.PushAlarmMsgAsync(new TpushMsgModel //{ // C_DevStoreCode = devstore.C_ID, // C_MsgTypeCode = "MSG_TYPE_013", // Msg = "设备点报警已消除", // Subject = devstore.C_Name + "的设备点报警已消除", // DevNumber = devstore.C_NumberCode, // DevName = devstore.C_Name, //}); } //} } //} } } } private static readonly object boxnolocker = new object(); ConcurrentDictionary jObjectDic = new ConcurrentDictionary(); ConcurrentDictionary jArrayDic = new ConcurrentDictionary(); ConcurrentDictionary alarmlightJarrayDic = new ConcurrentDictionary(); ConcurrentDictionary> webScadaDevSpotDic = new ConcurrentDictionary>(); private async Task IntervalBoxnoList(TDEV_DevStore devstore, IEnumerable items) { List boxnotasks = new List(); JObject result; lock (boxnolocker) { result = new JObject { {"device",new JArray() },{ "alarmlight", new JArray() },{ "package", new JObject() } }; JArray deviceJarray = new JArray(); JArray alarmlightJarray = new JArray(); jObjectDic[devstore.C_ID] = result; jArrayDic[devstore.C_ID] = alarmlightJarray; alarmlightJarrayDic[devstore.C_ID] = alarmlightJarray; List boxnoList = items.Select(x => x.C_BoxNo).Distinct(StringComparer.InvariantCultureIgnoreCase).ToList(); if (!jObjectDic.ContainsKey(devstore.C_ID)) jObjectDic.TryAdd(devstore.C_ID, result); if (!jArrayDic.ContainsKey(devstore.C_ID)) jArrayDic.TryAdd(devstore.C_ID, deviceJarray); if (!alarmlightJarrayDic.ContainsKey(devstore.C_ID)) alarmlightJarrayDic.TryAdd(devstore.C_ID, alarmlightJarray); boxnoList.ForEach(async boxno => { boxnotasks.Add(Task.Run(async () => { List devSpotCodes = items.Where(a => a.C_BoxNo == boxno).Select(x => x.C_DevSpotCode).ToList(); List names = items.Where(a => a.C_BoxNo == boxno).Select(x => x.C_Name).ToList(); List unitNames = items.Where(a => a.C_BoxNo == boxno).Select(x => x.C_UnitName).ToList(); List groupnames = items.Where(a => a.C_BoxNo == boxno).Select(x => x.C_GroupName).ToList(); List calFormula = items.Where(a => a.C_BoxNo == boxno).Select(x => x.C_CalFormula).ToList(); List sort = items.Where(a => a.C_BoxNo == boxno).Select(x => x.I_Sort).ToList(); List Public = items.Where(a => a.C_BoxNo == boxno).Select(x => x.C_Public).ToList(); List runs = items.Where(a => a.C_BoxNo == boxno).Select(x => x.C_Run).ToList(); List> calFormulaList = new List>(); foreach (var v in calFormula) { if (v != null) calFormulaList.Add(JsonConvert.DeserializeObject>(v)); } if (calFormulaList.Count == 0) { calFormulaList = null; calFormula = null; } string storeCode = items.Where(a => a.C_BoxNo == boxno).Select(x => x.C_StoreCode).FirstOrDefault(); JObject re = await FanyiHelper.GetWebScadaDevSpotValue(boxno, storeCode, names, unitNames, groupnames, calFormula, sort, runs, _nodeServices, calFormulaList, devSpotCodes, Public); if (re != null) { //if (devstore.C_ID == "5b6368b1-3bbb-410f-945c-4d1b2783ab47") //{ jArrayDic.TryGetValue(devstore.C_ID, out deviceJarray); alarmlightJarrayDic.TryGetValue(devstore.C_ID, out alarmlightJarray); deviceJarray?.Merge(re.SelectToken("device") as JArray, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Union }); alarmlightJarray?.Merge(re.SelectToken("alarmlight") as JArray, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Union }); jArrayDic[devstore.C_ID] = deviceJarray; alarmlightJarrayDic[devstore.C_ID] = alarmlightJarray; JArray deviceOrderJarray = new JArray(deviceJarray.OrderBy(obj => (int)obj["sort"]));//升序 Console.WriteLine(deviceOrderJarray); result = new JObject { { "device", deviceOrderJarray }, { "alarmlight", alarmlightJarray }, { "package", new JObject() { { "time", DateTime.Now } } } }; if (devstore.C_ID == "8793c6c8-d855-421e-9fa1-d25f914bb730") { int idebug = 0; } jObjectDic[devstore.C_ID] = result; //} } await Task.Delay(100); })); }); } await Task.WhenAll(boxnotasks); //Task.WaitAll(); return await Task.FromResult(result); } private async Task WebScadaDevSpotInterval(IEnumerable devStoresList) { //devStoresList.AsParallel().ForAll(async devstore => //{ //}); foreach (var devstore in devStoresList) { using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); IEnumerable items = null; webScadaDevSpotDic.TryGetValue(devstore.C_ID, out items); if (devstore.C_ID == "8793c6c8-d855-421e-9fa1-d25f914bb730") { int idebug = 0; } if (items == null || !items.ToList().Any()) { await _redisService.SetAsync("fanyibox_devStore_" + devstore.C_ID, string.Empty); bool bol = await _redisService.ExistsAsync($"webSocket_devStore_{devstore.C_ID}"); if (bol) { var webSocketVal = _redisService.Get($"webSocket_devStore_{devstore.C_ID}"); if (webSocketVal == "1") { await _hubContext.Clients.All.SendAsync("webSocket_devStore_" + devstore.C_ID, string.Empty); } } } else { await IntervalBoxnoList(devstore, items); } } } } //private readonly object devRunLock = new object(); List jol = new List(); private async Task SendIntervalNoDb(IEnumerable devStoresList) { List tasks = new List(); foreach (var dev in devStoresList) { //线程 tasks.Add(Task.Run(async () => { //lock (devRunLock) //{ //} using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); using (var dbContext = scope.ServiceProvider.GetService()) { IEnumerable items = _redisService.Get>("fanyibox_devStore_" + dev.C_ID + "_spot"); TDEV_DevStore devstore = await dbContext.TDEV_DevStore.Where(x => x.C_ID == dev.C_ID).FirstOrDefaultAsync(); if (devstore == null) { devstore = dev; } //#region 修正设备点ID //foreach (var dev in jsonObject["device"]) //{ // if (string.IsNullOrEmpty((string)dev["id"]) || string.IsNullOrEmpty((string)dev["value"])) // continue; // string strId = (string)dev["id"]; // float dValue = (float)dev["value"]; // string strName = (string)dev["name"]; // var v = items.Select(y =>y.C_StoreCode == devstore.C_ID && y.C_Name == strName); //} ////更新 //dbContext.TDEV_WebScadaDevSpot.UpdateRange(items); //await dbContext.SaveChangesAsync(); //#endregion if (!webScadaDevSpotDic.ContainsKey(devstore.C_ID)) webScadaDevSpotDic.TryAdd(devstore.C_ID, items); else { webScadaDevSpotDic[devstore.C_ID] = items; } if (items != null && items.ToList().Any()) { JObject devValue = (JObject)jObjectDic[devstore.C_ID]?.DeepClone(); if (devValue != null && devValue["device"].Any()) { var devValues = _redisService.Get("fanyibox_devStore_" + devstore.C_ID); await _redisService.SetAsync("fanyibox_devStore_" + devstore.C_ID, devValue); await _redisService.SetAsync("fanyibox_alarmDic_" + devstore.C_ID, FanyiHelper.alarmDic); await _redisService.SetAsync("fanyibox_msgalarmdic", FanyiHelper.msgAlarmDic); if (_redisService.Exists($"webSocket_devStore_{devstore.C_ID}")) { var webSocketVal = _redisService.Get($"webSocket_devStore_{devstore.C_ID}"); if (!String.Equals(devValues, devValue.ToString()) && webSocketVal == "1") { await _hubContext.Clients.All.SendAsync("webSocket_devStore_" + devstore.C_ID, devValue.ToString()); log.Info($"webSocket_devStore_{devstore.C_ID}数据:【{devValue.ToString()}】"); } } int alarmCount = 0; //设备点报警推送 foreach (var ala in devValue["device"]) { //_logger.LogInformation($"SendIntervalNoDb设备信息中【device】有数据【{devstore.C_ID},数据={ala}】 "); if (ala["id"] == null) continue; string strDotName = (string)ala["name"]; string strDotRun = (string)ala["run"]; if ("86b61dbd-0f45-4d68-95ed-4b7da82f3740" == devstore.C_ID) //东清 8453d5ed-8a21-4880-88e7-f872e93551bf { //jol.Add(devValue); if (!string.IsNullOrEmpty(strDotName) && strDotName.Contains("温度")) { Debug.WriteLine("温度 " + ala["value"] + DateTime.Now.ToString()); //continue; } } //if (!string.IsNullOrEmpty(strDotName) && strDotName.Contains("风机") && (strDotName.Contains("主机")|| strDotName.Contains("运行"))) //_logger.LogInformation($"-设备点开关机开始【设备ID={devstore.C_ID},strDotName={strDotName},strDotRun={strDotRun}】"); if (!string.IsNullOrEmpty(strDotRun) && strDotRun == "1") { //_logger.LogInformation($"-设备点开关机开始-进入-Begin【设备ID={devstore.C_ID}】"); if ("86b61dbd-0f45-4d68-95ed-4b7da82f3740" == devstore.C_ID) { int idebug = 0; //ala["value"] = "0"; //ala["value"] = "1"; } try { Convert.ToDouble(ala["value"]); } catch(Exception ex) { continue; } string nowDevStatus = Math.Abs(Convert.ToDouble(ala["value"])) > 0.01 ? "1" : "0"; string strMsg = Math.Abs(Convert.ToDouble(ala["value"])) > 0.01 ? "开启" : "关闭"; devstore.C_Status = Math.Abs(Convert.ToDouble(ala["value"])) > 0.01 ? ((int)DevStatusEnum.Start).ToString() : ((int)DevStatusEnum.Stop).ToString(); if ("224870650814550567" == (string)ala["id"]) { int idebug = 0; } string devRunStatus = _redisService.Get("fanyibox_devRunStatus_" + (string)ala["id"]); //_logger.LogInformation($"-设备点开关机开始-进入【设备ID={devstore.C_ID},nowDevStatus={nowDevStatus},strMsg={strMsg},devstore.C_Status={devstore.C_Status},devRunStatus={devRunStatus}】"); if (devRunStatus.IsNullOrEmpty()) { bool bSet = _redisService.Set("fanyibox_devRunStatus_" + (string)ala["id"], nowDevStatus); if (!bSet) continue; //devstore.C_Status = Math.Abs(Convert.ToDouble(ala["value"])) > 0.01 ? ((int)DevStatusEnum.Start).ToString() : ((int)DevStatusEnum.Stop).ToString(); dbContext.TDEV_DevStore.Update(devstore); await dbContext.SaveChangesAsync(); } if (devRunStatus?.Replace("\"", "") != nowDevStatus) { _logger.LogInformation($"-设备点开关机开始-进入状态不相等【设备ID={devstore.C_ID},nowDevStatus={nowDevStatus},devRunStatus={devRunStatus}】"); bool bSet = _redisService.Set("fanyibox_devRunStatus_" + (string)ala["id"], nowDevStatus); if (!bSet) continue; //devstore.C_Status = Math.Abs(Convert.ToDouble(ala["value"])) > 0.01 ? ((int)DevStatusEnum.Start).ToString() : ((int)DevStatusEnum.Stop).ToString(); HttpClient httpClient = httpClientFactory.CreateClient(); DateTime time = DateTime.Now; var msgData = new TpushMsgModel { C_DevStoreCode = devstore.C_ID, C_MsgTypeCode = "MSG_TYPE_011", Msg = strMsg, Subject = "设备开启关闭报警", DevNumber = devstore.C_NumberCode, DevName = devstore.C_Name, CreateOn = time.ToString(), UserName = "设备", GenerationType = 1, msgStatus = 4, }; await SnedAlarmRabbitMQ(JsonConvert.SerializeObject(msgData));//发送RabbitMQ消息-设备开关机报警 #region 原设备开关机报警代码【2025-2-24】 //try //{ // var httpRequestMessage = new HttpRequestMessage // { // Method = HttpMethod.Post, // RequestUri = new Uri(_aPIUrlData.PublicPushMessageAPI), // Content = new StringContent(JsonConvert.SerializeObject(msgData), Encoding.UTF8, "application/json") // }; // var response = await httpClient.SendAsync(httpRequestMessage); // string responseResult = await response.Content.ReadAsStringAsync(); // _logger.LogInformation($"-设备点开关机开始-进入状态不相等-调用接口【设备ID={devstore.C_ID},参数={JsonConvert.SerializeObject(msgData)},接口返回结果={response.StatusCode}】"); // if (response.StatusCode != HttpStatusCode.OK) // { // } // else // { // //todo // } //} //catch (Exception ex) //{ // _logger.LogInformation($"-设备点开关机开始-进入状态不相等-调用接口异常【设备ID={devstore.C_ID},参数={JsonConvert.SerializeObject(msgData)} ,异常信息={ex.Message}】"); //} #endregion log.Info($"-设备点开关机开始-进入状态不相等【设备ID={devstore.C_ID},ala[value]={Math.Abs(Convert.ToDouble(ala["value"]))}】"); if (Math.Abs(Convert.ToDouble(ala["value"])) > 0.01) _redisService.Set("fanyibox_devStartRun_" + (string)ala["id"], DateTime.Now); if (Math.Abs(Convert.ToDouble(ala["value"])) <= 0.01) { _redisService.Set("fanyibox_devEndRun_" + (string)ala["id"], DateTime.Now); var msg = new { devStoreCode = devstore.C_ID, devRunSpot = (string)ala["id"], time = DateTime.Now }; string msgStr = JsonConvert.SerializeObject(msg); log.Info($"{msgStr};发送RabbitMQ消息"); await SnedRabbitMQ(msgStr); //await DevStatusChange("0", devstore.C_ID, (string)ala["id"], DateTime.Now); //设备运行状态 } dbContext.TDEV_DevStore.Update(devstore); await dbContext.SaveChangesAsync(); _logger.LogInformation($"-设备点开关机开始-进入状态不相等结束【设备ID={devstore.C_ID}】"); } //_logger.LogInformation($"-设备点开关机开始-进入-End【设备ID={devstore.C_ID}】"); } //_logger.LogInformation($"-设备点开关机结束【设备ID={devstore.C_ID},strDotName={strDotName},strDotRun={strDotRun}】"); string strAlaColour = (string)ala["changecolour"]; string sendmsg = _redisService.Get("fanyibox_devspot_" + (string)ala["id"]); string devspotColour = _redisService.Get("fanyibox_devspotColour_" + (string)ala["id"])?.Replace("\"", ""); string redisAlaColour = strAlaColour; //_logger.LogInformation($"-设备点预警报警开始【设备ID={devstore.C_ID},strAlaColour={strAlaColour},sendmsg={sendmsg},devspotColour={devspotColour}】"); if (strAlaColour != null && (strAlaColour == "red" || strAlaColour == "yellow") && ((sendmsg == "true" && devspotColour != strAlaColour) || sendmsg != "true" || sendmsg == null)) { log.Info($"1log-设备点预警报警-进入报警-Begin【设备ID={devstore.C_ID};ala[id]={(string)ala["id"]};strAlaColour={strAlaColour};sendmsg={sendmsg};devspotColour={devspotColour}】---"); _redisService.Set("fanyibox_devspot_" + (string)ala["id"], true); HttpClient httpClient = httpClientFactory.CreateClient(); TpushMsgModel msgData = null; int updResult = 0; if (strAlaColour == "red") { msgData = new TpushMsgModel { C_DevStoreCode = devstore.C_ID, C_MsgTypeCode = "MSG_TYPE_012", Msg = devstore.C_Name + "的" + (string)ala["name"] + "设备点报警" + " 设备点值:" + (string)ala["value"], Subject = "设备点报警", DevNumber = devstore.C_NumberCode, DevName = devstore.C_Name, CreateOn = DateTime.Now.ToString(), UserName = "设备", GenerationType = 1, msgStatus = 1, }; //updResult = await _tdevDevStoreRepository.UpdateDevStoreStatus(devstore.C_ID, "4"); devstore.C_Status = "4"; dbContext.TDEV_DevStore.Update(devstore); await dbContext.SaveChangesAsync(); } if (strAlaColour == "yellow") { msgData = new TpushMsgModel { C_DevStoreCode = devstore.C_ID, C_MsgTypeCode = "MSG_TYPE_017", Msg = devstore.C_Name + "的" + (string)ala["name"] + "设备点预警" + " 设备点值:" + (string)ala["value"], Subject = "设备点预警", DevNumber = devstore.C_NumberCode, DevName = devstore.C_Name, CreateOn = DateTime.Now.ToString(), UserName = "设备", GenerationType = 1, msgStatus = 1, }; //updResult = await _tdevDevStoreRepository.UpdateDevStoreStatus(devstore.C_ID, "6"); devstore.C_Status = "6"; dbContext.TDEV_DevStore.Update(devstore); await dbContext.SaveChangesAsync(); } //_logger.LogInformation($"-设备点预警报警-进入报警-修改设备状态【设备ID={devstore.C_ID},修改结果:{updResult}】"); _logger.LogInformation($"1logger-设备点预警报警-发送RabbitMQ消息-设备报警【设备ID={devstore.C_ID};ala[id]={(string)ala["id"]};strAlaColour={strAlaColour};sendmsg={sendmsg};devspotColour={devspotColour};msgData={JsonConvert.SerializeObject(msgData)}】---"); log.Info($"1log-设备点预警报警-发送RabbitMQ消息-设备报警【设备ID={devstore.C_ID};ala[id]={(string)ala["id"]};strAlaColour={strAlaColour};sendmsg={sendmsg};devspotColour={devspotColour};msgData={JsonConvert.SerializeObject(msgData)}】---"); await SnedAlarmRabbitMQ(JsonConvert.SerializeObject(msgData));//发送RabbitMQ消息-设备报警 #region 原发送设备报警数据【2024-12-31】 //try //{ // var httpRequestMessage = new HttpRequestMessage // { // Method = HttpMethod.Post, // RequestUri = new Uri(_aPIUrlData.PublicPushMessageAPI), // Content = new StringContent(JsonConvert.SerializeObject(msgData), Encoding.UTF8, "application/json") // }; // var response = await httpClient.SendAsync(httpRequestMessage); // string responseResult = await response.Content.ReadAsStringAsync(); // _logger.LogInformation($"-设备点预警报警-进入报警-发送数据【设备ID={devstore.C_ID},发送数据={JsonConvert.SerializeObject(msgData)},返回消息结果={response.StatusCode}】"); // if (response.StatusCode != HttpStatusCode.OK) // { // } // else // { // //todo // } // } // catch (Exception ex) // { // redisAlaColour = null; // _redisService.Set("fanyibox_devspot_" + (string)ala["id"], false); // _logger.LogInformation($"-设备点预警报警-进入报警-发送数据异常【设备ID={devstore.C_ID},异常信息={ex.Message}】"); // throw; // } #endregion await AddDevAlarmData(devstore.C_ID); } if (strAlaColour != null && (strAlaColour != "red" && strAlaColour != "yellow") && sendmsg == "true") { log.Info($"2log-设备点预警报警-【fanyibox_devspot{ (string)ala["id"]}】修改为false【设备ID={devstore.C_ID};ala[id]={(string)ala["id"]};strAlaColour={strAlaColour};sendmsg={sendmsg};devspotColour={devspotColour}】---"); _redisService.Set("fanyibox_devspot_" + (string)ala["id"], false); } if ((strAlaColour == "red" || strAlaColour == "yellow")) { alarmCount++; } _redisService.Set("fanyibox_devspotColour_" + (string)ala["id"], redisAlaColour); //_logger.LogInformation($"-设备点预警报警结束【设备ID={devstore.C_ID},strAlaColour={strAlaColour},sendmsg={sendmsg},存储的devspotColour={_redisService.Get("fanyibox_devspotColour_" + (string)ala["id"])}】"); } if (alarmCount == 0)//FanyiHelper.alarmDic==null||FanyiHelper.alarmDic.Count==0 { //int upd = await _tdevDevStoreRepository.UpdateDevStoreStatus(devstore.C_ID, "2"); devstore.C_Status = "2"; dbContext.TDEV_DevStore.Update(devstore); await dbContext.SaveChangesAsync(); } //await AddData(devValue); } await Task.Delay(10); //1000 } //await dbContext.SaveChangesAsync(); } } })); } await Task.WhenAll(tasks); //Task.WaitAll(); } private async Task SendInterval(IEnumerable devStoresList) { List tasks = new List(); //using (var dbContext = _dbFuncContextFactory()) //{ foreach (var devstore in devStoresList) { //线程 tasks.Add(Task.Run(async () => { using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); using (var dbContext = scope.ServiceProvider.GetService()) { var predicate = PredicateBuilder.New(true);//查询条件,推荐后台使用这种方式灵活筛选 predicate = predicate.And(i => i.C_Status.Equals("1")); predicate = predicate.And(i => i.C_DevCode.Equals(devstore.C_ID)); IEnumerable items = dbContext.TDEV_WebScadaDevSpot.Where(predicate).OrderBy(x => x.I_Sort).AsEnumerable(); if (!webScadaDevSpotDic.ContainsKey(devstore.C_ID)) webScadaDevSpotDic.TryAdd(devstore.C_ID, items); else { webScadaDevSpotDic[devstore.C_ID] = items; } if (items != null && items.ToList().Any()) { //var result = await IntervalBoxnoList(devstore, items); //lock (_locker) //{ // var result = await FanyiHelper.GetWebScadaDevSpotValue(boxno, storeCode, names, unitNames, groupnames, calFormula, _nodeServices, calFormulaList); if (jObjectDic[devstore.C_ID]["device"].Any()) { await _redisService.SetAsync("fanyibox_devStore_" + devstore.C_ID, jObjectDic[devstore.C_ID]); await _redisService.SetAsync("fanyibox_alarmDic_" + devstore.C_ID, FanyiHelper.alarmDic); await _redisService.SetAsync("fanyibox_msgalarmdic", FanyiHelper.msgAlarmDic); #region 开关机 //foreach (var oc in result["device"]) //{ // string oldResult = await _redisService.GetAsync("fanyibox_devStore_" + (string)oc["id"]); // if (string.IsNullOrWhiteSpace(oldResult)) // continue; // JObject jObjectContent = JsonConvert.DeserializeObject(oldResult); // string strContent = JsonConvert.SerializeObject(jObjectContent["device"]); // string strNewContent = JsonConvert.SerializeObject(result); // if (string.IsNullOrEmpty(strContent) || string.IsNullOrEmpty(strNewContent)) // continue; // else // { // JArray ja = JsonConvert.DeserializeObject(strContent); // for (int i = 0; i < ja.Count; i++) // { // JObject jo = JObject.Parse(strContent); // if (jo["name"].ToString().Contains("风机") && jo["name"].ToString().Contains("主机")) // { // JArray jaNew = JsonConvert.DeserializeObject(strNewContent); // var jt = jaNew.FirstOrDefault(x => x.Value("name").Contains("风机") && x.Value("name").Contains("主机")); // var oldFenjiValue = jt.Value("value"); // if (string.IsNullOrWhiteSpace(oldFenjiValue) || oldFenjiValue == jo["value"].ToString()) // { // break; // } // HttpClient httpClient = httpClientFactory.CreateClient(); // var msgData = new DevOperateCreateModel // { // C_DevStoreCode = devstore.C_ID, // C_LogMsg = "设备开启关闭", // C_Remark = jo["value"].ToString() == "1" ? "开启" : "关闭", // C_Type = jo["value"].ToString() == "1" ? "2" : "3", // }; // var httpRequestMessage = new HttpRequestMessage // { // Method = HttpMethod.Post, // RequestUri = new Uri("http://www.dgt.net.cn:93/api/TdevDevStore/DevOperateByQRCodeAsync"), // Content = new StringContent(JsonConvert.SerializeObject(msgData), Encoding.UTF8, "application/json") // }; // var response = await httpClient.SendAsync(httpRequestMessage); // string responseResult = await response.Content.ReadAsStringAsync(); // if (response.StatusCode != HttpStatusCode.OK) // { // } // else // { // //todo // } // } // } // } //} #endregion //await _redisService.SetAsync("fanyibox_devStore_" + devstore.C_ID, result); await AddData(jObjectDic[devstore.C_ID]); //string sChange = await _redisService.GetAsync("fanyibox_devStoreChange_" + devstore.C_ID); //ceshi //DateTime startTime = await _redisService.GetAsync("fanyibox_devStartRun_" + "224873679711261516"); //DateTime endTime = await _redisService.GetAsync("fanyibox_devEndRun_" + "224873679711261516"); //await GetMeanData("224873679711261516", DateTime.UtcNow.AddMinutes(-5), DateTime.UtcNow); //if (!startTime.IsNotEmptyOrNull()&& !endTime.IsNotEmptyOrNull()) //await GetMeanData("224873679711261516", startTime, endTime); //设备点报警推送 foreach (var ala in jObjectDic[devstore.C_ID]["device"]) { string strDotName = (string)ala["name"]; if (strDotName.Contains("风机") && strDotName.Contains("主机")) { string devRunStatus = await _redisService.GetAsync("fanyibox_devRunStatus_" + (string)ala["id"]); if (devRunStatus.IsNullOrEmpty()) { await _redisService.SetAsync("fanyibox_devRunStatus_" + (string)ala["id"], (string)ala["value"]); devstore.C_Status = (string)ala["value"] == "1" ? ((int)DevStatusEnum.Start).ToString() : ((int)DevStatusEnum.Stop).ToString(); dbContext.TDEV_DevStore.Update(devstore); await dbContext.SaveChangesAsync(); } if (devRunStatus?.Replace("\"", "") != (string)ala["value"]) { //await AddDevAlarmData(devstore.C_ID);//测试 await _redisService.SetAsync("fanyibox_devRunStatus_" + (string)ala["id"], (string)ala["value"]); devstore.C_Status = (string)ala["value"] == "1" ? ((int)DevStatusEnum.Start).ToString() : ((int)DevStatusEnum.Stop).ToString(); dbContext.TDEV_DevStore.Update(devstore); await dbContext.SaveChangesAsync(); if ((string)ala["value"] == "1") await _redisService.SetAsync("fanyibox_devStartRun_" + (string)ala["id"], DateTime.Now); if ((string)ala["value"] == "0") { await _redisService.SetAsync("fanyibox_devEndRun_" + (string)ala["id"], DateTime.Now); //await this._dispatcher.Broadcast(new DevEvent("devrunend", (string)ala["id"])); //var tdevDevStoreUpdateModel = new TdevDevStoreUpdateModel //{ // C_Status = devstore.C_Status, //}; //var httpRequestMessage = new HttpRequestMessage //{ // Method = HttpMethod.Put, // RequestUri = new Uri("http://www.dgt.net.cn:93/api/Account/UpdateDevStoreAsync" + devstore.C_ID), // Content = new StringContent(JsonConvert.SerializeObject(tdevDevStoreUpdateModel), Encoding.UTF8, "application/json") //}; //await httpClient.SendAsync(httpRequestMessage); await DevStatusChange((string)ala["value"], devstore.C_ID, (string)ala["id"], DateTime.Now); } HttpClient httpClient = httpClientFactory.CreateClient(); //var msgData = new DevOperateCreateModel //{ // C_DevStoreCode = devstore.C_ID, // C_LogMsg = "设备开启关闭", // C_Remark = (string)ala["value"] == "1" ? "开启" : "关闭", // C_Type = (string)ala["value"] == "1" ? "2" : "3", //}; #region 开启关闭报警 #endregion var msgData = new TpushMsgModel { C_DevStoreCode = devstore.C_ID, C_MsgTypeCode = "MSG_TYPE_011", Msg = (string)ala["value"] == "1" ? "开启" : "关闭", Subject = "设备开启关闭报警", DevNumber = devstore.C_NumberCode, DevName = devstore.C_Name, CreateOn = DateTime.Now.ToString(), UserName = "设备", GenerationType = 1, msgStatus = 4, }; var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(_aPIUrlData.PublicPushMessageAPI), Content = new StringContent(JsonConvert.SerializeObject(msgData), Encoding.UTF8, "application/json") }; var response = await httpClient.SendAsync(httpRequestMessage); string responseResult = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { } else { //todo } //var doData = new DevOperateCreateModel //{ // C_DevStoreCode = devstore.C_ID, // C_Type = (string)ala["value"] == "1" ? "1" : "2", // C_LogMsg = (string)ala["value"] == "1" ? "开启" : "关闭", // C_Remark = "设备开关机", //}; //var dohttpRequestMessage = new HttpRequestMessage //{ // Method = HttpMethod.Post, // RequestUri = new Uri("http://www.dgt.net.cn:93/api/TdevDevStore/DevOperateByQRCodeAsync"), // Content = new StringContent(JsonConvert.SerializeObject(doData), Encoding.UTF8, "application/json") //}; //var responseTwo = await httpClient.SendAsync(dohttpRequestMessage); //await responseTwo.Content.ReadAsStringAsync(); } } string strAlaColour = (string)ala["changecolour"]; string sendmsg = await _redisService.GetAsync("fanyibox_devspot_" + (string)ala["id"]); if ((string)ala["id"] == "224870650814550567") { int a = 1; } if (strAlaColour != null && strAlaColour == "red" && sendmsg != "true") { await _redisService.SetAsync("fanyibox_devspot_" + (string)ala["id"], true); HttpClient httpClient = httpClientFactory.CreateClient(); var msgData = new TpushMsgModel { C_DevStoreCode = devstore.C_ID, C_MsgTypeCode = "MSG_TYPE_012", Msg = devstore.C_Name + "的" + (string)ala["name"] + "设备点报警" + " 设备点值:" + (string)ala["value"], Subject = "设备点报警", DevNumber = devstore.C_NumberCode, DevName = devstore.C_Name, CreateOn = DateTime.Now.ToString(), UserName = "设备", GenerationType = 1, msgStatus = 1, }; var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(_aPIUrlData.PublicPushMessageAPI), Content = new StringContent(JsonConvert.SerializeObject(msgData), Encoding.UTF8, "application/json") }; var response = await httpClient.SendAsync(httpRequestMessage); string responseResult = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { } else { //todo } await AddDevAlarmData(devstore.C_ID); } if (strAlaColour != null && strAlaColour != "red" && sendmsg == "true") { await _redisService.SetAsync("fanyibox_devspot_" + (string)ala["id"], false); } } #region 放到设备点中了 //bool bChange = false; //string bAlaColour = "black"; //foreach (var ala in result["alarmlight"]) //{ // string strAlaColour = (string)ala["alarmcolour"]; // if (strAlaColour == "red") // { // bAlaColour = "red"; // } //} //if (bAlaColour == "red" && !bChange) //{ // devstore.C_Status = "4"; // dbContext.TDEV_DevStore.Update(devstore); // await dbContext.SaveChangesAsync(); // bChange = true; // HttpClient httpClient = httpClientFactory.CreateClient(); // var msgData = new TpushMsgModel // { // C_DevStoreCode = devstore.C_ID, // C_MsgTypeCode = "MSG_TYPE_012", // Msg = "设备点报警", // Subject = devstore.C_Name + "的设备点报警", // DevNumber = devstore.C_NumberCode, // DevName = devstore.C_Name, // CreateOn = DateTime.Now.ToString(), // UserName = "设备", // }; // var httpRequestMessage = new HttpRequestMessage // { // Method = HttpMethod.Post, // RequestUri = new Uri("http://www.dgt.net.cn:93/api/Account/PublicPushMessage"), // Content = new StringContent(JsonConvert.SerializeObject(msgData), Encoding.UTF8, "application/json") // }; // var response = await httpClient.SendAsync(httpRequestMessage); // string responseResult = await response.Content.ReadAsStringAsync(); // if (response.StatusCode != HttpStatusCode.OK) // { // } // else // { // //todo // } //} //else if (bAlaColour == "black" && bChange) //{ // devstore.C_Status = "1"; //2 后期通过TDEV_DevStore_Log取设备是否报警 // dbContext.TDEV_DevStore.Update(devstore); // await dbContext.SaveChangesAsync(); // bChange = false; // HttpClient httpClient = httpClientFactory.CreateClient(); // var msgData = new TpushMsgModel // { // C_DevStoreCode = devstore.C_ID, // C_MsgTypeCode = "MSG_TYPE_013", // Msg = "设备点报警已消除", // Subject = devstore.C_Name + "的设备点报警已消除", // DevNumber = devstore.C_NumberCode, // DevName = devstore.C_Name, // CreateOn = DateTime.Now.ToString(), // UserName = "设备", // }; // var httpRequestMessage = new HttpRequestMessage // { // Method = HttpMethod.Post, // RequestUri = new Uri("http://www.dgt.net.cn:93/api/Account/PublicPushMessage"), // Content = new StringContent(JsonConvert.SerializeObject(msgData), Encoding.UTF8, "application/json") // }; // var response = await httpClient.SendAsync(httpRequestMessage); // string responseResult = await response.Content.ReadAsStringAsync(); // if (response.StatusCode != HttpStatusCode.OK) // { // } // else // { // //todo // } //} #endregion //} } // await Task.Delay(4000); } } } })); } //} await Task.WhenAll(tasks); //Task.WaitAll(); } //声明InfluxDbClient private async Task SendAlarmMsg(string devStoreId) { Dictionary alarmDic = null; using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); if (await _redisService.ExistsAsync("fanyibox_alarmDic_" + devStoreId)) { string sAlarmDic = await _redisService.GetAsync("fanyibox_alarmDic_" + devStoreId); if (string.IsNullOrWhiteSpace(sAlarmDic)) { Console.WriteLine("队列中数据不存在!"); } else { alarmDic = JsonConvert.DeserializeObject>(sAlarmDic); if (alarmDic != null) { foreach (var alarm in alarmDic) { } } } } } } private void IniInflux() { //连接InfluxDb的API地址、账号、密码 var infuxUrl = _IniInfluxData.infuxUrl;// "http://60.204.212.71:8085/"; var infuxUser = _IniInfluxData.infuxUser;// "admin"; var infuxPwd = _IniInfluxData.infuxPwd;// "123456"; //创建InfluxDbClient实例 clientDb = new InfluxDbClient(infuxUrl, infuxUser, infuxPwd, InfluxDbVersion.Latest); } /// /// 从InfluxDB中读取数据 /// public async Task GetData() { //传入查询命令,支持多条 var queries = new[] { " SELECT * FROM fanyidev WHERE time> now() - 24h " }; var dbName = "fanyidb"; //从指定库中查询数据 var response = await clientDb.Client.QueryAsync(queries, dbName); //得到Serie集合对象(返回执行多个查询的结果) var series = response.ToList(); //取出第一条命令的查询结果,是一个集合 var list = series[0].Values; //从集合中取出第一条数据 var info_model = list.FirstOrDefault(); } public async Task GetMeanData(string id, DateTime start, DateTime end) { //传入查询命令,支持多条 var queries = new[] { //"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") + "'" "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')" //"SELECT mean(Val) FROM fanyidev where (Id ='224873679711261516') and time > now() - 5m and time < now()" }; var dbName = "fanyidb"; //从指定库中查询数据 var response = await clientDb.Client.QueryAsync(queries, dbName); if (!response.Any()) return "0"; //得到Serie集合对象(返回执行多个查询的结果) var series = response.ToList(); //取出第一条命令的查询结果,是一个集合 var list = series[0].Values; //从集合中取出第一条数据 var info_model = list.FirstOrDefault(); Console.WriteLine($"GetMeanData from DevEvent: ${info_model[1]}"); using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); await _redisService.SetAsync("fanyibox_devspot_mean_" + id, info_model[1]); } return info_model[1]?.ToString(); } public async Task GetDataMax(string id, DateTime start, DateTime end) { //传入查询命令,支持多条 var queries = new[] { "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')" }; var dbName = "fanyidb"; //从指定库中查询数据 var response = await clientDb.Client.QueryAsync(queries, dbName); if (!response.Any()) return "0"; //得到Serie集合对象(返回执行多个查询的结果) var series = response.ToList(); //取出第一条命令的查询结果,是一个集合 var list = series[0].Values; //从集合中取出第一条数据 var info_model = list.FirstOrDefault(); Console.WriteLine($"GetMeanData from DevEvent: ${info_model[1]}"); using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); await _redisService.SetAsync("fanyibox_devspot_max_" + id, info_model[1]); } return info_model[1]?.ToString(); } public async Task GetDataMin(string id, DateTime start, DateTime end) { //传入查询命令,支持多条 var queries = new[] { "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')" }; var dbName = "fanyidb"; //从指定库中查询数据 var response = await clientDb.Client.QueryAsync(queries, dbName); if (!response.Any()) return "0"; //得到Serie集合对象(返回执行多个查询的结果) var series = response.ToList(); //取出第一条命令的查询结果,是一个集合 var list = series[0].Values; //从集合中取出第一条数据 var info_model = list.FirstOrDefault(); Console.WriteLine($"GetMeanData from DevEvent: ${info_model[1]}"); using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); await _redisService.SetAsync("fanyibox_devspot_min_" + id, info_model[1]); } return info_model[1]?.ToString(); } public async Task GetDevAlarmData(string id, DateTime start, DateTime end) { //传入查询命令,支持多条 var queries = new[] { //"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") + "'" "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')" //"SELECT mean(Val) FROM fanyidev where (Id ='224873679711261516') and time > now() - 5m and time < now()" }; var dbName = "fanyidb"; //从指定库中查询数据 var response = await clientDb.Client.QueryAsync(queries, dbName); if (!response.Any()) return 0; //得到Serie集合对象(返回执行多个查询的结果) var series = response.ToList(); //取出第一条命令的查询结果,是一个集合 var list = series[0].Values; //从集合中取出第一条数据 var info_model = list.FirstOrDefault(); if (!info_model.Any()) return 0; Console.WriteLine($"GetMeanData from DevEvent: ${info_model[1]}"); return await Task.FromResult(Convert.ToInt32(info_model[1])); } /// /// 往InfluxDB中写入数据 /// public async Task AddData(JObject jsonObject) { IList points = new List(); var dbName = "fanyidb"; foreach (var dev in jsonObject["device"]) { try { if (string.IsNullOrEmpty((string)dev["id"]) || string.IsNullOrEmpty((string)dev["value"]) || (string)dev["value"] == "null") continue; bool isDecimal = Regex.IsMatch((string)dev["value"], @"^\d+(\.\d+)?$");//true是非负数的整数和小数 if ((string)dev["value"] == "NaN" || !isDecimal) { continue; } string strId = (string)dev["id"]; string strDevSpotCode = (string)dev["devSpotCode"]; float dValue = Convert.ToSingle((string)dev["value"]); string strName = (string)dev["name"]; //string unitName = (string)dev["unitName"]; var point_model = new Point() { Name = "fanyidev",//表名 Tags = new Dictionary() { { "Id", strDevSpotCode }, //{ "Id", strId + "-" + strDevSpotCode }, //{ "code", strDevSpotCode }, { "name", strName } // , //{ "unitName", unitName } }, Fields = new Dictionary() { { "Val",dValue } }, Timestamp = DateTime.UtcNow //DateTime.Now }; points.Add(point_model); //从指定库中写入数据,支持传入多个对象的集合 //var response = await clientDb.Client.WriteAsync(point_model, dbName); } catch (Exception ex) { continue; } } if (points.Any()) await clientDb.Client.WriteAsync(points, dbName); } public async Task AddDevAlarmData(string devId) { var point_model = new Point() { Name = "fanyidevalarm",//表名 Tags = new Dictionary() { { "Id", devId } }, Fields = new Dictionary() { { "Val",1 } }, Timestamp = DateTime.UtcNow }; var dbName = "fanyidb"; //从指定库中写入数据,支持传入多个对象的集合 var response = await clientDb.Client.WriteAsync(point_model, dbName); } /// /// 运行台账-【固定的实体字段】 /// /// /// /// /// private async Task DevStatusChange0(string devStatus, string devStoreCode, string devRunSpot) { try { //运行台账 if (devStatus == "0") { using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); using (var dbContext = scope.ServiceProvider.GetService()) { //using (var dbContext = _dbFuncContextFactory()) //{ //var devStoreLogSet = dbContext.GetDbSet().AsNoTracking(); //var devStoreStartLog = devStoreLogSet.Where(x => x.C_Type == ((int)DevStatusEnum.Start).ToString()).OrderByDescending(x => x.D_CreateOn).Take(1).FirstOrDefault(); //if (devStoreStartLog == null) goto next; //var devstore_log_datas = devStoreLogSet.Where(t => t.C_DeviceCode == devStoreCode && t.D_CreateOn > devStoreStartLog.D_CreateOn).OrderByDescending(x => x.D_CreateOn);//.Take(5) //bool isAlarm = devstore_log_datas.Where(t => t.C_Type == ((int)DevStatusEnum.Alarm).ToString()).Any() ? true : false; bool isAlarm = false; var devOpeAccountS = dbContext.GetDbSet(); //读取特性,属性名 //PropertyInfo[] peroperties = typeof(TdevDevOpeContentViewModel).GetProperties(BindingFlags.Public | BindingFlags.Instance); //foreach (PropertyInfo property in peroperties) //{ // object[] objs = property.GetCustomAttributes(typeof(DescriptionAttribute), true); // if (objs.Length > 0) // { // Console.WriteLine("{0}: {1}", property.Name, ((DescriptionAttribute)objs[0]).Description); // } //} //var result = await FanyiHelper.GetWebScadaDevSpotValue(boxno, storeCode, names, unitNames, groupnames, calFormula, _nodeServices, calFormulaList); var devStore = await _tdevDevStoreRepository.GetByConditionAsync(x => x.C_ID == devStoreCode); string sRunSpotConfig = devStore.FirstOrDefault().C_RunSpotConfig; if (string.IsNullOrEmpty(sRunSpotConfig)) return; TdevDevStoreRunSpotConfigViewModel runSpotConfig = JsonConvert.DeserializeObject(sRunSpotConfig); if (!runSpotConfig.RunSpotConfigList.Any()) return; var devSpotGroupNames = runSpotConfig?.RunSpotConfigList?.Where(x => x.BReadDevSpot == true).Select(y => y.DevSpotGroupName).ToList(); var devSpotNames = runSpotConfig?.RunSpotConfigList?.Where(x => x.BReadDevSpot == true).Select(y => y.DevSpotName).ToList(); var devSpotBoxNos = runSpotConfig?.RunSpotConfigList?.Where(x => x.BReadDevSpot == true).Select(y => y.DevSpotBoxNo).ToList(); //if(devSpotBoxNos.Any()) var devSpotValues = await FanyiHelper.GetDevSpotValue(devSpotBoxNos.FirstOrDefault(), devSpotNames, devSpotGroupNames); string fSpotId = devSpotValues?.Where(x => x.name == devSpotNames.FirstOrDefault()).FirstOrDefault()?.id.ToString(); string sSpotId = devSpotValues?.Where(x => x.name == devSpotNames.ElementAtOrDefault(1)).FirstOrDefault()?.id.ToString(); DateTime startTime = await _redisService.GetAsync("fanyibox_devStartRun_" + devRunSpot); DateTime endTime = await _redisService.GetAsync("fanyibox_devEndRun_" + devRunSpot); if (startTime.IsNotEmptyOrNull() && endTime.IsNotEmptyOrNull()) { isAlarm = await GetDevAlarmData(devStoreCode, startTime, endTime) >= 1; if (!string.IsNullOrEmpty(fSpotId)) await GetMeanData(fSpotId, startTime, endTime); if (!string.IsNullOrEmpty(sSpotId)) await GetMeanData(sSpotId, startTime, endTime); } var solidWasteRecordItems = await _tmtnDevOpsRecordRepository.GetRecordsConditionAsync(new TmtnDevOpsRecordDetailSearchModel { bSolidWaste = true, C_DevStoreCode = devStoreCode, IsPagination = false, Start = startTime, End = endTime }); List DevOpsRecordSolidWaste = new List(); if (solidWasteRecordItems.Any() && solidWasteRecordItems.FirstOrDefault() != null) foreach (var item in solidWasteRecordItems.ToList()) { if (item.C_Status == "7") { if (!string.IsNullOrWhiteSpace(item.C_SolidWaste)) DevOpsRecordSolidWaste.Add(JsonConvert.DeserializeObject(item.C_SolidWaste)); } } //DevOpsRecordSolidWaste.ForEach(x => { // if (x.RoleName.Contains("设备管理员")) // vm.DevManager += x.C_Name + " " + x.C_Mobile + " "; // if (x.RoleName.Contains("设备运维员")) // vm.DevOpser += x.C_Name + " " + x.C_Mobile + " "; //}); TdevDevOpeContentViewModel devOpeContent = new TdevDevOpeContentViewModel { Date = DateTime.Now,//.ToString("yyyy-MM-dd HH:mm:ss.fff") DrainOutletNumber = runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "DrainOutletNumber").FirstOrDefault().Value, DevStoreName = devStore.FirstOrDefault().C_Name,// runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "DevStoreName").FirstOrDefault().Value, DevStoreType = runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "DevStoreType").FirstOrDefault().Value, SpecificationsParameterName = runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "SpecificationsParameterName").FirstOrDefault().Value, SpecificationsDesignValue = runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "SpecificationsDesignValue").FirstOrDefault().Value, SpecificationsUnit = runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "SpecificationsUnit").FirstOrDefault().Value, RunStartTime = startTime, RunEndTime = DateTime.Now, RunWhetherNormal = !isAlarm, FlueGasVolume = await _redisService.GetAsync("fanyibox_devspot_mean_" + fSpotId),// devSpotValues?.Where(x => x.name == devSpotNames.FirstOrDefault()).FirstOrDefault()?.value.ToString(), PollutionFactor = runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "PollutionFactor").FirstOrDefault().Value, GovernanceEfficiency = await _redisService.GetAsync("fanyibox_devspot_mean_" + sSpotId),// devSpotValues?.Where(x => x.name == devSpotNames.ElementAtOrDefault(1)).FirstOrDefault()?.value.ToString(), DataSources = runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "DataSources").FirstOrDefault().Value, HeightOfFlue = runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "HeightOfFlue").FirstOrDefault().Value, DischargeTemperature = runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "DischargeTemperature").FirstOrDefault().Value, Pressure = runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "Pressure").FirstOrDefault().Value, DischargeTime = (DateTime.Now - startTime).TotalHours.ToString("F2"), ConsumablePowerConsumption = runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "ConsumablePowerConsumption").FirstOrDefault().Value, ConsumableName = DevOpsRecordSolidWaste.Any() ? string.Join(",", DevOpsRecordSolidWaste.Select(x => x.NameSpecification).ToList().ToArray()) : "/" , // runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "ConsumableName").FirstOrDefault().Value, ConsumableReplacementQuantity = DevOpsRecordSolidWaste.Any() ? string.Join(",", DevOpsRecordSolidWaste.Select(x => x.SpecificationNumber).ToList().ToArray()) : "/",//runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "ConsumableReplacementQuantity").FirstOrDefault().Value, WasteName = DevOpsRecordSolidWaste.Any() ? string.Join(",", DevOpsRecordSolidWaste.Select(x => x.SolidWasteUnit).ToList().ToArray()) : "/", //runSpotConfig?.RunSpotConfigList?.Where(x=>x.Name == "WasteName").FirstOrDefault().Value, WasteProduction = DevOpsRecordSolidWaste.Any() ? string.Join(",", DevOpsRecordSolidWaste.Select(x => x.SolidWasteNumber).ToList().ToArray()) : "/", //runSpotConfig?.RunSpotConfigList?.Where(x => x.Name == "WasteProduction").FirstOrDefault().Value, //C_Content = "", //C_Remark = "", //C_CreateBy = _claims.ApiUserId, //D_CreateOn = DateTime.Now }; await devOpeAccountS.AddRangeAsync(new TDEV_DevOpeAccount { C_ID = Guid.NewGuid().ToString(), C_DevStoreCode = devStoreCode, C_Content = JsonConvert.SerializeObject(devOpeContent), C_Remark = "", C_CreateBy = Guid.Parse("6e864cbc-5252-11ec-8681-fa163e02b3e4"), D_CreateOn = DateTime.Now }); var qty = await dbContext.SaveChangesAsync(); //} } } //next: await _tdevDevStoreLogRepository.CreateOneAsync(new TDEV_DevStoreLog { C_ID = Guid.NewGuid().ToString(), C_DeviceCode = devStoreCode, C_Type = devStatus == "1" ? ((int)DevStatusEnum.Start).ToString() : ((int)DevStatusEnum.Stop).ToString(), C_LogMsg = devStatus == "1" ? "开启" : "关闭", C_CreateBy = Guid.Parse("6e864cbc-5252-11ec-8681-fa163e02b3e4"), D_CreateOn = DateTime.Now }); await _tdevDevStoreLogRepository.SaveAsync(); } } catch (Exception ex) { _logger.LogInformation(ex.Message); } } /// /// 运行台账-【动态】 /// /// /// /// /// private async Task DevStatusChange(string devStatus, string devStoreCode, string devRunSpot, DateTime time) { try { using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); DateTime startTime = await _redisService.GetAsync("fanyibox_devStartRun_" + devRunSpot); DateTime endTime = await _redisService.GetAsync("fanyibox_devEndRun_" + devRunSpot); var _tmtnDevOpsRecordRepository = scope.ServiceProvider.GetService(); var solidWasteRecordItems = await _tmtnDevOpsRecordRepository.GetRecordsConditionAsync(new TmtnDevOpsRecordDetailSearchModel { bSolidWaste = true, C_DevStoreCode = devStoreCode, IsPagination = false, Start = startTime, End = endTime }); var devAccountConfig = await _devDevOpeAccountConfigService.GetByConditionAsync(t => t.C_DevStoreCode == devStoreCode); using (var dbContext = scope.ServiceProvider.GetService()) { //运行台账 if (devStatus == "0") { //using (var dbContext = _dbFuncContextFactory()) //{ bool isAlarm = false; var devOpeAccountS = dbContext.GetDbSet(); //var devStore = await _tdevDevStoreRepository.GetByConditionAsync(x => x.C_ID == devStoreCode); var devStore = await dbContext.TDEV_DevStore.Where(x => x.C_ID == devStoreCode).FirstOrDefaultAsync(); //var devAccountConfig = await _devDevOpeAccountConfigService.GetByConditionAsync(t => t.C_DevStoreCode == devStoreCode); //var devAccountConfig = await dbContext.TDEV_DevOpeAccountConfig.Where(t => t.C_DevStoreCode == devStoreCode).FirstOrDefaultAsync(); var devAccountConfigModel = devAccountConfig.OrderByDescending(t => t.D_CreateOn).FirstOrDefault(); if (devAccountConfigModel != null) { if (!string.IsNullOrEmpty(devAccountConfigModel.C_Config)) { TdevDevOpeAccountConfigViewModel configList = JsonConvert.DeserializeObject(devAccountConfigModel.C_Config); if (configList != null) { var devSpotGroupNames = configList.RunSpotConfigList?.Where(x => x.BReadDevSpot == true).Select(y => y.DevSpotGroupName).ToList(); var devSpotNames = configList.RunSpotConfigList?.Where(x => x.BReadDevSpot == true).Select(y => y.DevSpotName).ToList(); var devSpotBoxNos = configList.RunSpotConfigList?.Where(x => x.BReadDevSpot == true).Select(y => y.DevSpotBoxNo).ToList(); //var devSpotValues = await FanyiHelper.GetDevSpotValue(devSpotBoxNos.FirstOrDefault(), devSpotNames, devSpotGroupNames); IEnumerable items = _redisService.Get>("fanyibox_devStore_" + devStoreCode + "_spot"); //DateTime startTime = await _redisService.GetAsync("fanyibox_devStartRun_" + devRunSpot); //DateTime endTime = await _redisService.GetAsync("fanyibox_devEndRun_" + devRunSpot); if (startTime.IsNotEmptyOrNull() && endTime.IsNotEmptyOrNull() && startTime != DateTime.MinValue && endTime != DateTime.MinValue) { isAlarm = await GetDevAlarmData(devStoreCode, startTime, endTime) >= 1; } //var solidWasteRecordItems = await _tmtnDevOpsRecordRepository.GetRecordsConditionAsync(new TmtnDevOpsRecordDetailSearchModel { bSolidWaste = true, C_DevStoreCode = devStoreCode, IsPagination = false, Start = startTime, End = endTime }); List DevOpsRecordSolidWaste = new List(); if (solidWasteRecordItems.Any() && solidWasteRecordItems.FirstOrDefault() != null) foreach (var item in solidWasteRecordItems.ToList()) { if (item.C_Status == "4") { if (!string.IsNullOrWhiteSpace(item.C_SolidWaste)) DevOpsRecordSolidWaste.Add(JsonConvert.DeserializeObject(item.C_SolidWaste)); } } Dictionary datas = new Dictionary(); #region datas.Add("Date", time); foreach (Inspection.Model.ViewModel.DEV.RunSpotConfig item in configList.RunSpotConfigList) { if (item.Name == "DevStoreName") { datas.Add(item.Name, devStore.C_Name); } else if (item.Name == "RunStartTime") { datas.Add(item.Name, startTime); } else if (item.Name == "RunEndTime") { datas.Add(item.Name, DateTime.Now); } else if (item.Name == "RunWhetherNormal") { datas.Add(item.Name, isAlarm); } else if (item.Name == "DischargeTime") { datas.Add(item.Name, (DateTime.Now - startTime).TotalHours.ToString("F2")); } else if (item.Name == "ConsumableName" || item.Name == "WasteName") { datas.Add(item.Name, DevOpsRecordSolidWaste.Any() ? string.Join(",", DevOpsRecordSolidWaste.Select(x => x.NameSpecification).ToList().ToArray()) : "/"); } else if (item.Name == "ConsumableReplacementQuantity") { int number = DevOpsRecordSolidWaste.Any() ? DevOpsRecordSolidWaste.Sum(x => (string.IsNullOrEmpty(x.SolidWasteNumber) ? 0 : Convert.ToInt32(x.SolidWasteNumber))) : 0; datas.Add(item.Name, number); } else if (item.Name == "WasteProduction") { //string.Join(",", DevOpsRecordSolidWaste.Select(x => x.DropNumber).ToList().ToArray()) int number = DevOpsRecordSolidWaste.Any() ? DevOpsRecordSolidWaste.Sum(x => (string.IsNullOrEmpty(x.DropNumber) ? 0 : Convert.ToInt32(x.DropNumber))) : 0; datas.Add(item.Name, number); } //"DrainOutletNumber"|| "DevStoreType"||"SpecificationsParameterName"||"SpecificationsDesignValue"||"SpecificationsUnit"||"PollutionFactor"||"DataSources"||"HeightOfFlue"||"DischargeTemperature"||"Pressure"||"ConsumablePowerConsumption"||"FlueGasVolume"||"GovernanceEfficiency" else { if (item.BReadDevSpot) { string vals = "0"; string valsMax = "0"; string valsMin = "0"; //string SpotId = devSpotValues?.Where(x => x.name == item.DevSpotName).FirstOrDefault()?.id.ToString(); TDEV_WebScadaDevSpot webScadaDevSpot = items?.Where(x => x.C_Name == item.DevSpotName).FirstOrDefault(); if (webScadaDevSpot == null) { datas.Add(item.Name, vals); datas.Add(item.Name + "_Max", valsMax); datas.Add(item.Name + "_Min", valsMin); continue; } string SpotId = webScadaDevSpot.C_DevSpotCode.ToString(); if (!string.IsNullOrEmpty(SpotId) && startTime.IsNotEmptyOrNull() && endTime.IsNotEmptyOrNull() && startTime != DateTime.MinValue && endTime != DateTime.MinValue) { endTime = DateTime.Now; vals = await GetMeanData(SpotId, startTime, endTime); valsMax = await GetDataMax(SpotId, startTime, endTime); valsMin = await GetDataMin(SpotId, startTime, endTime); if (vals == null) { SpotId = webScadaDevSpot.C_ID.ToString(); vals = await GetMeanData(SpotId, startTime, endTime); valsMax = await GetDataMax(SpotId, startTime, endTime); valsMin = await GetDataMin(SpotId, startTime, endTime); } } vals = string.IsNullOrEmpty(vals) ? "0" : Convert.ToDouble(vals).ToString("0.0"); valsMax = string.IsNullOrEmpty(valsMax) ? "0" : Convert.ToDouble(valsMax).ToString("0.0"); valsMin = string.IsNullOrEmpty(valsMin) ? "0" : Convert.ToDouble(valsMin).ToString("0.0"); datas.Add(item.Name, vals); datas.Add(item.Name + "_Max", valsMax); datas.Add(item.Name + "_Min", valsMin); } else { var itemData = configList.RunSpotConfigList?.Where(x => x.Name == item.Name).FirstOrDefault(); datas.Add(item.Name, itemData?.Value); } } } #endregion await devOpeAccountS.AddRangeAsync(new TDEV_DevOpeAccount { C_ID = Guid.NewGuid().ToString(), C_DevStoreCode = devStoreCode, C_Content = JsonConvert.SerializeObject(datas), C_Remark = "", C_DevOpeAccountConfigCode = devAccountConfigModel.C_ID, C_CreateBy = Guid.Parse("6e864cbc-5252-11ec-8681-fa163e02b3e4"), D_CreateOn = DateTime.Now }); var qty = await dbContext.SaveChangesAsync(); } } } //} } //var devStoreLog = dbContext.GetDbSet(); //await devStoreLog.AddAsync(new TDEV_DevStoreLog //{ // C_ID = Guid.NewGuid().ToString(), // C_DeviceCode = devStoreCode, // C_Type = devStatus == "1" ? ((int)DevStatusEnum.Start).ToString() : ((int)DevStatusEnum.Stop).ToString(), // C_LogMsg = devStatus == "1" ? "开启" : "关闭", // C_CreateBy = Guid.Parse("6e864cbc-5252-11ec-8681-fa163e02b3e4"), // D_CreateOn = DateTime.Now //}); ////await _tdevDevStoreLogRepository.CreateOneAsync(new TDEV_DevStoreLog ////{ //// C_ID = Guid.NewGuid().ToString(), //// C_DeviceCode = devStoreCode, //// C_Type = devStatus == "1" ? ((int)DevStatusEnum.Start).ToString() : ((int)DevStatusEnum.Stop).ToString(), //// C_LogMsg = devStatus == "1" ? "开启" : "关闭", //// C_CreateBy = Guid.Parse("6e864cbc-5252-11ec-8681-fa163e02b3e4"), //// D_CreateOn = DateTime.Now ////}); ////await _tdevDevStoreLogRepository.SaveAsync(); //await dbContext.SaveChangesAsync(); } } } catch (Exception ex) { _logger.LogInformation(ex.Message); } } private void _fbox_DataMonitorValueChanged(object sender, IList e) { using (var scope = _provider.GetRequiredService().CreateScope()) { var _redisService = scope.ServiceProvider.GetService(); _redisService.ListLeftPushAsync("fanyibox", e); } //AddData(); } #region RabbitMQ消息 /// /// 发送RabbitMQ消息-台账 /// /// /// public async Task SnedRabbitMQ(string msgStr) { try { Ropin.Inspection.Common.Helper.RabbitMQModel rabbit = new Ropin.Inspection.Common.Helper.RabbitMQModel(); rabbit.HostName = _rabbitMQModel.HostName;// "60.204.212.71",//IP地址 rabbit.Port = _rabbitMQModel.Port;// 5672,//端口号 rabbit.UserName = _rabbitMQModel.UserName;//"guest",//用户账号 rabbit.VirtualHost = _rabbitMQModel.VirtualHost;// "/", rabbit.Password = _rabbitMQModel.Password;//"guest"//用户密码 rabbit.msgStr = msgStr; rabbit.QueueName = "rabbit@rabbitmq01"; bool bol = await RabbitMQHelper.SnedRabbitMQ_ExchangeDirect(rabbit); if (!bol) { log.Info($"【{msgStr}】【设备台账数据发送失败-RabbitMQ】"); } } catch (Exception ex) { log.Info($"【{msgStr}】【设备台账数据发送异常-RabbitMQ】" + ex.Message); throw; } } /// /// 发送RabbitMQ消息-设备报警 /// /// /// public async Task SnedAlarmRabbitMQ(string msgStr) { try { Ropin.Inspection.Common.Helper.RabbitMQModel rabbit = new Ropin.Inspection.Common.Helper.RabbitMQModel(); rabbit.HostName = _rabbitMQModel.HostName;// "60.204.212.71",//IP地址 rabbit.Port = _rabbitMQModel.Port;// 5672,//端口号 rabbit.UserName = _rabbitMQModel.UserName;//"guest",//用户账号 rabbit.VirtualHost = _rabbitMQModel.VirtualHost;// "/", rabbit.Password = _rabbitMQModel.Password;//"guest"//用户密码 rabbit.msgStr = msgStr; rabbit.QueueName = "rabbit.alarmDevice"; bool bol = await RabbitMQHelper.SnedRabbitMQ_ExchangeDirect(rabbit); if (!bol) { log.Info($"【{msgStr}】【设备报警发送失败-RabbitMQ】"); } } catch (Exception ex) { log.Info($"【{msgStr}】【设备报警发送异常-RabbitMQ】" + ex.Message); throw; } } #endregion public Task StopAsync(CancellationToken cancellationToken) { Dispose(); _logger.LogInformation("内部任务计划结束"); return Task.CompletedTask; } public void Dispose() { fanyi?.Dispose(); //t?.Dispose(); } } }