From ea8b4514e67e3b28a903a317887adcdd8ce812f0 Mon Sep 17 00:00:00 2001 From: fyf Date: Thu, 5 May 2022 16:13:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0iot=E5=A4=A7=E5=B1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ALY_ProcessServer.cs | 6 +- DataVAPI.Tools/IOT/IOTDevServer.cs | 30 +++ DataVAPI.Tools/IOT/ScreenMonitorModel.cs | 8 +- DataVAPI/Controllers/UserController.cs | 10 +- DataVAPI/Startup.cs | 4 + DataVAPI/UpAndDown/ProcessServer.cs | 237 ++++++++++++++++++ 6 files changed, 281 insertions(+), 14 deletions(-) create mode 100644 DataVAPI/UpAndDown/ProcessServer.cs diff --git a/DataVAPI.ProcessServices/阿里云处理流程One/ALY_ProcessServer.cs b/DataVAPI.ProcessServices/阿里云处理流程One/ALY_ProcessServer.cs index c182390..44746f4 100644 --- a/DataVAPI.ProcessServices/阿里云处理流程One/ALY_ProcessServer.cs +++ b/DataVAPI.ProcessServices/阿里云处理流程One/ALY_ProcessServer.cs @@ -62,13 +62,13 @@ namespace DataVAPI.ProcessServices.阿里云处理流程One devModel = new ScreenMonitorModel(); devModel.operatingDeviceStatus = new OperatingDeviceStatus(); devModel.operatingDeviceStatus.data = new List();//现场设备于状态 devModel.infoMessage = new InfoMessage(); devModel.infoMessage.data = new List();//通知消息 - devModel.TotalSales = "0"; + //devModel.TotalSales = "0"; //加载店铺信息 LoadingShopInformation(); //MQTT 数据接收处理 ConsoleHelper.WriteInfoLine("尝试连接阿里云."); IOTDevServer.GetInstance().SetUrl(APIurl); - if (IOTDevServer.GetInstance().CreateLinks(0, out device)) + if (IOTDevServer.GetInstance().CreateLinks(10, out device)) { ConsoleHelper.WriteSuccessLine("连接阿里云成功!"); } @@ -183,7 +183,7 @@ namespace DataVAPI.ProcessServices.阿里云处理流程One })); } } - devModel.TotalSales = devModel.operatingDeviceStatus.data.Count.ToString(); + //devModel.TotalSales = devModel.operatingDeviceStatus.data.Count.ToString(); ScreenMonitorModel screen1Monitor = Tools.JsonToObjectTools(devModel.ToJSON()); #region 1.设置data默认值 diff --git a/DataVAPI.Tools/IOT/IOTDevServer.cs b/DataVAPI.Tools/IOT/IOTDevServer.cs index 17b85e0..207a22b 100644 --- a/DataVAPI.Tools/IOT/IOTDevServer.cs +++ b/DataVAPI.Tools/IOT/IOTDevServer.cs @@ -193,6 +193,36 @@ namespace DataVAPI.Tool.IOT } } + public bool CreateLinks(string key, string name, string secret) + { + try + { + Set(key, name, secret); + IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); + string clientId = host.AddressList.FirstOrDefault( + ip => ip.AddressFamily == AddressFamily.InterNetwork).ToString(); + string t = Convert.ToString(DateTimeOffset.Now.ToUnixTimeMilliseconds()); + string signmethod = "hmacmd5"; + + Dictionary dict = new Dictionary(); + dict.Add("productKey", ProductKey); + dict.Add("deviceName", DeviceName); + dict.Add("clientId", clientId); + dict.Add("timestamp", t); + + mqttUserName = DeviceName + "&" + ProductKey; + mqttPassword = IotSignUtils.sign(dict, DeviceSecret, signmethod); + mqttClientId = clientId + "|securemode=3,signmethod=" + signmethod + ",timestamp=" + t + "|"; + targetServer = ProductKey + ".iot-as-mqtt." + RegionId + ".aliyuncs.com"; + ConnectMqtt(targetServer, mqttClientId, mqttUserName, mqttPassword); + return true; + } + catch (Exception ex) + { + return false; + } + } + /// /// 获取连接状态 /// diff --git a/DataVAPI.Tools/IOT/ScreenMonitorModel.cs b/DataVAPI.Tools/IOT/ScreenMonitorModel.cs index 21933f4..fd6d3fe 100644 --- a/DataVAPI.Tools/IOT/ScreenMonitorModel.cs +++ b/DataVAPI.Tools/IOT/ScreenMonitorModel.cs @@ -12,10 +12,6 @@ namespace DataVAPI.Tool.IOT /// public class ScreenMonitorModel { - /// - /// 服务商家数 - /// - public string TotalSales { get; set; } /// /// 现场运营设备状态 /// @@ -263,6 +259,10 @@ namespace DataVAPI.Tool.IOT /// 客户端ID /// public string clientId { get; set; } + /// + /// 设备ID + /// + public string deviceId { get; set; } public DevBase() { diff --git a/DataVAPI/Controllers/UserController.cs b/DataVAPI/Controllers/UserController.cs index 039d5ae..7272239 100644 --- a/DataVAPI/Controllers/UserController.cs +++ b/DataVAPI/Controllers/UserController.cs @@ -1,6 +1,7 @@ using DataVAPI.Model; using DataVAPI.Tool.IOT; using DataVAPI.Tool.控制台显示; +using DataVAPI.UpAndDown; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Net.Http; @@ -51,9 +52,7 @@ namespace DataVAPI.Controllers string st = System.Reflection.MethodBase.GetCurrentMethod().Name; try { - HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(Tools.JsonConvertTools(usersModel), Encoding.GetEncoding("UTF-8"), "application/json") }; - if (usersModel == null || string.IsNullOrEmpty(usersModel.deviceName)) { return JsonMsg.Error(null, st, "设备名称不能为空"); ; @@ -61,9 +60,7 @@ namespace DataVAPI.Controllers else { string PubTopic = "/broadcast/" + "grgpECHSL7q" + "/" + usersModel.deviceName + "_SetDevice"; - ConsoleHelper.WriteWarningLine("发送数据 " + PubTopic + Tools.JsonConvertTools(usersModel)); - - IOTDevServer.GetInstance().IOT_Publish(PubTopic, Tools.JsonConvertTools(usersModel)); + ProcessServer.Instance.Publish(PubTopic, usersModel); return JsonMsg.OK(usersModel, st); } @@ -99,8 +96,7 @@ namespace DataVAPI.Controllers Dictionary keyValuePair = new Dictionary(); keyValuePair.Add(CommandKey, CommandValue); CommandModel command = new CommandModel() { CommandName = CommandName, deviceName = deviceName, CommandValue = keyValuePair }; - ConsoleHelper.WriteWarningLine("发送数据 " + PubTopic + Tools.JsonConvertTools(command)); - IOTDevServer.GetInstance().IOT_Publish(PubTopic, Tools.JsonConvertTools(command)); + ProcessServer.Instance.Publish(PubTopic, command); return JsonMsg.OK(command, st); } } diff --git a/DataVAPI/Startup.cs b/DataVAPI/Startup.cs index 8257ee3..a43b4d1 100644 --- a/DataVAPI/Startup.cs +++ b/DataVAPI/Startup.cs @@ -1,8 +1,11 @@ using DataVApi.Order; using DataVAPI.AppConfig; using DataVAPI.ConfigureSwagger; +using DataVAPI.Model; using DataVAPI.ModelDataBus; +using DataVAPI.Tool.IOT; using DataVAPI.Tool.控制台显示; +using DataVAPI.UpAndDown; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; @@ -28,6 +31,7 @@ namespace DataVAPI SugarDb.Conn = Configuration["DbConnectionstring"].ToString(); DataBus.connStr = Configuration["mongoDB.connStr"].ToString(); DataBus.dbName = Configuration["mongoDB.dbName"].ToString(); + ProcessServer.Instance.Initialize(); //注册swagger服务 services.AddSwaggerUp(); services.AddControllers(); diff --git a/DataVAPI/UpAndDown/ProcessServer.cs b/DataVAPI/UpAndDown/ProcessServer.cs new file mode 100644 index 0000000..31b2d8d --- /dev/null +++ b/DataVAPI/UpAndDown/ProcessServer.cs @@ -0,0 +1,237 @@ +using DataVAPI.Controllers; +using DataVAPI.Model; +using DataVAPI.Tool; +using DataVAPI.Tool.IOT; +using DataVAPI.Tool.控制台显示; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace DataVAPI.UpAndDown +{ + /// + /// 上下线通知 + /// + public class ProcessServer + { + /// + /// 上报大屏总Model + /// + public ScreenMonitorModel devModel { get; set; } + + public DeviceController deviceController { get; set; } + public LogController logController { get; set; } + public ScreenController screenController { get; set; } + + + #region 不需要监听 + private static ProcessServer _instance; + public static ProcessServer Instance + { + get + { + if (_instance == null) + _instance = new ProcessServer(); + return _instance; + } + } + public ProcessServer() + { + deviceController = new DeviceController(); + logController = new LogController(); + screenController = new ScreenController(); + + } + #endregion + /// + /// 初始化 + /// + public void Initialize() + { + devModel = new ScreenMonitorModel(); + devModel.operatingDeviceStatus = new OperatingDeviceStatus(); devModel.operatingDeviceStatus.data = new List();//现场设备于状态 + devModel.infoMessage = new InfoMessage(); devModel.infoMessage.data = new List();//通知消息 + //加载店铺信息 //加载店铺信息 + LoadingShopInformation(); + //MQTT 数据接收处理 + ConsoleHelper.WriteInfoLine("尝试连接阿里云."); + if (IOTDevServer.GetInstance().CreateLinks("grgpECHSL7q", "Transit", "562dcc779b918a54c2d6589ec30ee230")) + ConsoleHelper.WriteSuccessLine($"阿里云【Transit】连接成功"); + else + { + ConsoleHelper.WriteSuccessLine($"阿里云【Transit】连接失败"); + return; + } + + IOTDevServer.UNConnectMqtt += new Action((o) => { ConsoleHelper.WriteSuccessLine(o); }); + + Subscribe(IOTDevServer.HeartbeatSubTopic); + + IOTDevServer.DevIOTAction += DevIOTActionHandler; + + ConsoleHelper.WriteSuccessLine("开始接收数据,执行队列任务!"); + } + + /// + /// 加载店铺信息 + /// + /// + public void LoadingShopInformation(string clientId = "") + { + try + { + ConsoleHelper.WriteSuccessLine("加载店铺集合中."); + JsonMsg> jsonMsg = deviceController.Query("", "",DateTime.MinValue,DateTime.MinValue); + jsonMsg?.obj?.data?.ForEach(par => + { + int chid = 0; + try + { + chid = int.Parse(par.ClientId); + } + catch (Exception ex) + { + chid = 0; + } + if (chid>0) + { + DevStatus devStatus = new DevStatus() + { + deviceName = par.devicename, + gmtCreate = par.devicesecret, + productKey = par.productkey, + DeviceMC = par.devtype, + DeviceMS = par.remark, + DeviceSJ = par.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"), + DeviceZT = "离线", + clientId = par.ClientId, + deviceId = par.DeviceId + }; + if (devModel.operatingDeviceStatus.data.Find(o => o.gmtCreate == par.devicesecret) == null) + { + ConsoleHelper.WriteSuccessLine($"加载设备.{par.devtype} {par.remark}"); + devModel.operatingDeviceStatus.data.Add(devStatus); + } + } + }); + ConsoleHelper.WriteSuccessLine($"加载设备数[ {jsonMsg?.obj?.data?.Count} ]台..."); + } + catch (Exception ex) + { + ConsoleHelper.WriteErrorLine($"错误{ex.Message}"); + + } + + } + + /// + /// 订阅主题 + /// + /// + public void Subscribe(string subscribe) + { + IOTDevServer.GetInstance().IOT_Subscribe(subscribe); + ConsoleHelper.WriteSuccessLine("订阅主题: " + subscribe); + } + + public void Publish(string PubTopic, CommandModel command) + { + ConsoleHelper.WriteWarningLine("发送数据 " + PubTopic + Tools.JsonConvertTools(command)); + IOTDevServer.GetInstance().IOT_Publish(PubTopic, Tools.JsonConvertTools(command)); + } + + + /// + /// 更新内存集合 + /// + /// + public void SentData(ReceiveModel receiveModel) + { + try + { + if (receiveModel?.deviceContext != null && receiveModel?.status != null)//状态变更消息 + { + devModel?.operatingDeviceStatus.data?.Find(par => par.deviceName == receiveModel.deviceContext.deviceName)?.SetStatus(receiveModel.status.value); + devModel?.infoMessage?.data?.Add(new DeviceBase { DeviceMC = receiveModel.deviceContext.deviceName, DeviceMS = $"设备{receiveModel.status.value}了!", DeviceSJ = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }); + + DevStatus dev = devModel?.operatingDeviceStatus.data?.Find(par => par.deviceName == receiveModel.deviceContext.deviceName); + if (dev != null) + { + logController.Create(new LogTable + { + devicename = receiveModel.deviceContext.deviceName, + ClientId = dev.clientId, + LogTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), + LogType = "1", + LogMessage = $"设备{receiveModel.status.value}了!", + LogVla = "上下线通知" + }); + } + else + { + LoadingShopInformation(); + } + } + ScreenMonitorModel screen1Monitor = Tools.JsonToObjectTools(devModel.ToJSON()); + #region 1.设置data默认值 + if (screen1Monitor.operatingDeviceStatus.data.Count == 0) + { + screen1Monitor.operatingDeviceStatus.data.Add(new DevStatus { DeviceMC = "", DeviceMS = "", DeviceSJ = "", deviceName = "", DeviceZT = "", gmtCreate = "" }); + } + if (screen1Monitor.infoMessage.data.Count == 0) + { + screen1Monitor.infoMessage.data.Add(new DeviceBase { DeviceMC = "", DeviceMS = "", DeviceSJ = "" }); + } + #endregion + + string JSON = screen1Monitor.ToJSON(); + if (!string.IsNullOrEmpty(JSON)) + { + screenController.CreateOrUpdate(new LargeScreenTable() { json = JSON, devicename = "Transit",ClientId = "-10",DeviceId="-10" }); + IOTDevServer.GetInstance().IOT_Publish(IOTDevServer.ScreenShowPubTopic, JSON); + } + + if (devModel.infoMessage.data != null && devModel.infoMessage.data.Count > 0) + { + List bases = devModel.infoMessage.data.ToList(); + bases?.ForEach(par => + { + if (string.IsNullOrEmpty(par.DeviceMC)) devModel.infoMessage.data.Remove(par); + if (!string.IsNullOrEmpty(par.DeviceSJ) && DateTime.Now.AddSeconds(-5) > DateTime.Parse(par.DeviceSJ)) + { + devModel.infoMessage.data.Remove(par); + } + }); + } + } + catch (Exception ex) + { + ConsoleHelper.WriteErrorLine($"错误{ex.Message}"); + + } + } + + /// + /// MQTT 消息 + /// + /// + /// + private void DevIOTActionHandler(string topic, string message) + { + if (string.IsNullOrEmpty(topic)) return; + if (topic == IOTDevServer.HeartbeatSubTopic)//上下线订阅主题 + { + ReceiveModel receiveModel = Tools.JsonToObjectTools(message); + if (receiveModel != null && receiveModel.status != null)//上下线通知 + { + if (receiveModel.deviceContext.deviceName != "Transit") + { + ConsoleHelper.WriteWarningLine("接收数据 " + topic + " 数据 " + message); + SentData(receiveModel); + } + } + } + } + } +}