|
- using DataVAPI.Model;
- using DataVAPI.ProcessServices.AppConfig;
- using DataVAPI.Tool;
- using DataVAPI.Tool.API请求;
- using DataVAPI.Tool.IOT;
- using DataVAPI.Tool.控制台显示;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading;
-
- namespace DataVAPI.ProcessServices.阿里云处理流程One
- {
- /// <summary>
- /// 老服务代码
- /// </summary>
- public class ALY_ProcessServer
- {
- #region 上报总大屏数据
- /// <summary>
- /// 上报大屏总Model
- /// </summary>
- public ScreenMonitorModel devModel { get; set; }
- ///// <summary>
- ///// 缓存所有设备实时状态列表
- ///// </summary>
- //public Dictionary<string,ReceiveModel> DataVstatus { get; set; }
- /// <summary>
- /// 设备查询信息
- /// </summary>
- public DeviceTable device;
- /// <summary>
- /// API URL 地址
- /// </summary>
- public string APIurl = "http://124.222.238.75:6002";
- #endregion
-
- #region 不需要监听
- private static ALY_ProcessServer _instance;
- public static ALY_ProcessServer Instance
- {
- get
- {
- if (_instance == null)
- _instance = new ALY_ProcessServer();
- return _instance;
- }
- }
- public ALY_ProcessServer()
- {
-
- }
- #endregion
-
- #region 执行函数
- /// <summary>
- /// 初始化
- /// </summary>
- public void Initialize()
- {
- APIurl = AppConfigurtaionServices.Configuration.GetSection("APIurl").Value;
- devModel = new ScreenMonitorModel();
- devModel.operatingDeviceStatus = new OperatingDeviceStatus(); devModel.operatingDeviceStatus.data = new List<DevStatus>();//现场设备于状态
- devModel.infoMessage = new InfoMessage(); devModel.infoMessage.data = new List<DeviceBase>();//通知消息
- //devModel.TotalSales = "0";
- //加载店铺信息
- LoadingShopInformation();
- //MQTT 数据接收处理
- ConsoleHelper.WriteInfoLine("尝试连接阿里云.");
- IOTDevServer.GetInstance().SetUrl(APIurl);
- if (IOTDevServer.GetInstance().CreateLinks(10, out device))
- {
- ConsoleHelper.WriteSuccessLine("连接阿里云成功!");
- }
- else
- {
- ConsoleHelper.WriteErrorLine("连接阿里云失败"); return;
- }
- IOTDevServer.UNConnectMqtt += new Action<string>((o) => { ConsoleHelper.WriteSuccessLine(o); });
- Subscribe(IOTDevServer.AlarmSubTopic);
- Subscribe(IOTDevServer.LogsSubTopic);
- Subscribe(IOTDevServer.HeartbeatSubTopic);
- Subscribe(IOTDevServer.TargetStatusSubTopic);
-
- IOTDevServer.DevIOTAction += DevIOTActionHandler;
- //执行队列任务
- QueueTask();
- ConsoleHelper.WriteSuccessLine("开始接收数据,执行队列任务!");
- }
-
- /// <summary>
- /// 订阅主题
- /// </summary>
- /// <param name="subscribe"></param>
- public void Subscribe(string subscribe)
- {
- IOTDevServer.GetInstance().IOT_Subscribe(subscribe);
- ConsoleHelper.WriteSuccessLine("订阅主题: " + subscribe);
- }
-
- /// <summary>
- /// 加载店铺信息
- /// </summary>
- /// <param name="clientId"></param>
- public void LoadingShopInformation(string clientId = "")
- {
- try
- {
- ConsoleHelper.WriteSuccessLine("加载店铺集合中.");
- string url = $"{APIurl}/api/Device/Query?clientId={clientId}";
- if (string.IsNullOrEmpty(clientId)) url = $"{APIurl}/api/Device/Query";
- string json = HttpRequestHelper.HttpGetRequest(url);
- JsonMsg<List<DeviceTable>> jsonMsg = Tools.JsonToObjectTools<JsonMsg<List<DeviceTable>>>(json);
- jsonMsg?.obj?.data?.ForEach(par =>
- {
-
- if (par.ClientId != "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
- };
- 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?.FindAll(o => o.ClientId != "0")?.Count()} ]台...");
- }
- catch (Exception ex)
- {
- ConsoleHelper.WriteErrorLine($"错误{ex.Message}");
-
- }
-
- }
-
- public void FindDataAlarm()
- {
- devModel?.operatingDeviceStatus.data?.ForEach(par =>
- {
-
- if (!string.IsNullOrEmpty(par.clientId))
- {
- par.IsAlarm = ApiGetAlarm(par.clientId);
- }
- });
- }
-
- /// <summary>
- /// 更新内存集合
- /// </summary>
- /// <param name="receive"></param>
- 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)
- {
- ApiAddLog(Tools.JsonConvertTools(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 = "上下线"
- }));
- }
- }
- //devModel.TotalSales = devModel.operatingDeviceStatus.data.Count.ToString();
-
- ScreenMonitorModel screen1Monitor = Tools.JsonToObjectTools<ScreenMonitorModel>(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))
- {
- AddScreenCreateOrUpdate(JSON);
- IOTDevServer.GetInstance().IOT_Publish(IOTDevServer.ScreenShowPubTopic, JSON);
- }
-
- if (devModel.infoMessage.data != null && devModel.infoMessage.data.Count > 0)
- {
- List<DeviceBase> 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}");
-
- }
- }
-
- /// <summary>
- /// 队列任务
- /// </summary>
- private void QueueTask()
- {
- Executer.GetInstance().Start(new Action(() =>
- {
- while (true)
- {
- try
- {
- if (IOTDevServer.GetInstance().GetIsConnected())
- {
-
- SentData(null);
-
- FindDataAlarm();
-
- Thread.Sleep(3000);
- }
-
- }
- catch (Exception ex)
- {
- ConsoleHelper.WriteErrorLine(ex.Message);
- }
- }
-
- }), "队列任务执行");
- }
-
- /// <summary>
- /// MQTT 消息
- /// </summary>
- /// <param name="topic"></param>
- /// <param name="message"></param>
- private void DevIOTActionHandler(string topic, string message)
- {
- if (string.IsNullOrEmpty(topic)) return;
-
-
- if (topic == IOTDevServer.AlarmSubTopic)//告警订阅主题
- {
- if (message.Contains("UpdateTime") && message.Contains("ClientId") && message.Contains("CreateTime"))
- {
- ApiAddAlarm(message);
- }
- }
- else if (topic == IOTDevServer.LogsSubTopic)//日志订阅主题
- {
- if (message.Contains("UpdateTime") && message.Contains("ClientId") && message.Contains("CreateTime"))
- {
- ApiAddLog(message);
- }
- }
- else if (topic == IOTDevServer.HeartbeatSubTopic)//上下线订阅主题
- {
- ReceiveModel receiveModel = Tools.JsonToObjectTools<ReceiveModel>(message);
- if (receiveModel != null && receiveModel.status != null)//上下线通知
- {
- if (receiveModel.deviceContext.deviceName == "hbldev") return;
- ConsoleHelper.WriteWarningLine("接收数据 " + topic + " 数据 " + message);
- SentData(receiveModel);
- }
- }
- else if (topic == IOTDevServer.TargetStatusSubTopic)//属性状态主题
- {
-
- }
-
-
-
-
- }
- #endregion
-
- #region API 函数操作
- /// <summary>
- /// 增加或者更新
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- public bool AddScreenCreateOrUpdate(string json)
- {
- try
- {
- ///api/Screen/CreateOrUpdate
- string url = APIurl + "/api/Screen/CreateOrUpdate";
- HttpRequestHelper.HttpPostRequest(url, Tools.JsonConvertTools(new LargeScreen() { json = json, devicename = device.devicename, clientId = device.ClientId })); return true;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- /// <summary>
- /// 查询告警信息
- /// </summary>
- /// <param name="clientId"></param>
- public bool ApiGetAlarm(string clientId)
- {
- try
- {
- //http://124.222.238.75:6002/api/Alarm/QueryClientId?clientId=9
- string url = APIurl + "/api/Alarm/QueryClientId?clientId=" + clientId;
- string json = HttpRequestHelper.HttpGetRequest(url);
- if (json != null && json.Contains("alarmMessage"))
- return true;
- else
- return false;
- }
- catch (Exception ex)
- {
- ConsoleHelper.WriteErrorLine(ex.Message); return false;
- }
- }
-
-
- /// <summary>
- /// 增加告警信息
- /// </summary>
- /// <param name="alarm"></param>
- public void ApiAddAlarm(string alarm)
- {
- try
- {
- AlarmTable al = Tools.JsonToObjectTools<AlarmTable>(alarm);
- if (al != null)
- {
- if (string.IsNullOrEmpty(al.devicename))
- {
- al.devicename = devModel?.operatingDeviceStatus.data?.Find(par => par.clientId == al.ClientId)?.deviceName;
- }
- string url = APIurl + "/api/Alarm/Create";
- HttpRequestHelper.HttpPostRequest(url, Tools.JsonConvertTools(al));
- }
-
- }
- catch (Exception ex)
- {
- ConsoleHelper.WriteErrorLine(ex.Message);
- }
- }
-
- /// <summary>
- /// 增加日志信息
- /// </summary>
- /// <param name="logTable"></param>
- public void ApiAddLog(string logTable)
- {
- try
- {
- LogTable lo = Tools.JsonToObjectTools<LogTable>(logTable);
- if (lo != null)
- {
- if (string.IsNullOrEmpty(lo.devicename))
- {
- lo.devicename = devModel?.operatingDeviceStatus.data?.Find(par => par.clientId == lo.ClientId)?.deviceName;
- }
- string url = APIurl + "/api/Log/Create";
- HttpRequestHelper.HttpPostRequest(url, Tools.JsonConvertTools(lo));
- }
- }
- catch (Exception ex)
- {
- ConsoleHelper.WriteErrorLine(ex.Message);
- }
- }
- #endregion
- }
- public class LargeScreen
- {
- public string json { get; set; }
- public string devicename { get; set; }
- public string clientId { get; set; }
- }
- }
|