Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

338 righe
14 KiB

  1. using DataVApi.Order;
  2. using DataVAPI.Controllers;
  3. using DataVAPI.Model;
  4. using DataVAPI.Tool;
  5. using DataVAPI.Tool.IOT;
  6. using DataVAPI.Tool.控制台显示;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Threading;
  11. namespace DataVAPI.UpAndDown
  12. {
  13. /// <summary>
  14. /// 上下线通知
  15. /// </summary>
  16. public class ProcessServer
  17. {
  18. /// <summary>
  19. /// 上报大屏总Model
  20. /// </summary>
  21. public ScreenMonitorModel devModel { get; set; }
  22. public DeviceController deviceController { get; set; }
  23. public LogController logController { get; set; }
  24. public ScreenController screenController { get; set; }
  25. public AlarmController alarmController { get; set; }
  26. public OrderProvider orderProvider { get; set; }
  27. #region 不需要监听
  28. private static ProcessServer _instance;
  29. public static ProcessServer Instance
  30. {
  31. get
  32. {
  33. if (_instance == null)
  34. _instance = new ProcessServer();
  35. return _instance;
  36. }
  37. }
  38. public ProcessServer()
  39. {
  40. deviceController = new DeviceController();
  41. logController = new LogController();
  42. alarmController = new AlarmController();
  43. screenController = new ScreenController();
  44. orderProvider = new OrderProvider();
  45. }
  46. #endregion
  47. /// <summary>
  48. /// 初始化
  49. /// </summary>
  50. public void Initialize()
  51. {
  52. devModel = new ScreenMonitorModel();
  53. devModel.operatingDeviceStatus = new OperatingDeviceStatus(); devModel.operatingDeviceStatus.data = new List<DevStatus>();//现场设备于状态
  54. devModel.infoMessage = new InfoMessage(); devModel.infoMessage.data = new List<DeviceBase>();//通知消息
  55. //加载店铺信息 //加载店铺信息
  56. LoadingShopInformation();
  57. //MQTT 数据接收处理
  58. ConsoleHelper.WriteInfoLine("尝试连接阿里云.");
  59. if (IOTDevServer.GetInstance().CreateLinks("grgpECHSL7q", "Transit", "562dcc779b918a54c2d6589ec30ee230"))
  60. {
  61. ConsoleHelper.WriteSuccessLine($"阿里云【Transit】连接成功");
  62. }
  63. else
  64. {
  65. ConsoleHelper.WriteSuccessLine($"阿里云【Transit】连接失败");
  66. }
  67. //属性状态变更
  68. Subscribe(IOTDevServer.TargetStatusSubTopic);
  69. //订阅上下线
  70. Subscribe(IOTDevServer.HeartbeatSubTopic);
  71. //订阅主播消息
  72. Subscribe(IOTDevServer.BroadcastTopic);
  73. IOTDevServer.UNConnectMqtt += new Action<string>((o) => { ConsoleHelper.WriteSuccessLine(o); });
  74. IOTDevServer.DevIOTAction += DevIOTActionHandler;
  75. QueueTask();
  76. ConsoleHelper.WriteSuccessLine("开始接收数据,执行队列任务!");
  77. }
  78. /// <summary>
  79. /// 队列任务
  80. /// </summary>
  81. private void QueueTask()
  82. {
  83. Executer.GetInstance().Start(new Action(() =>
  84. {
  85. while (true)
  86. {
  87. try
  88. {
  89. if (IOTDevServer.GetInstance().GetIsConnected())
  90. {
  91. SentData(null);
  92. FindDataAlarm();
  93. Thread.Sleep(3000);
  94. }
  95. }
  96. catch (Exception ex)
  97. {
  98. ConsoleHelper.WriteErrorLine(ex.Message);
  99. }
  100. }
  101. }), "队列任务执行");
  102. }
  103. public void FindDataAlarm()
  104. {
  105. devModel?.operatingDeviceStatus.data?.ForEach(par =>
  106. {
  107. if (!string.IsNullOrEmpty(par.clientId))
  108. {
  109. JsonMsg<List<AlarmTable>> jsonMsg = alarmController.QueryClientId(par.clientId);
  110. par.IsAlarm = (jsonMsg.obj != null && jsonMsg.obj.data != null && jsonMsg.obj.data.Count > 0)?true:false;
  111. }
  112. });
  113. }
  114. /// <summary>
  115. /// 加载店铺信息
  116. /// </summary>
  117. /// <param name="clientId"></param>
  118. public void LoadingShopInformation(string clientId = "")
  119. {
  120. try
  121. {
  122. ConsoleHelper.WriteSuccessLine("加载店铺集合中.");
  123. JsonMsg<List<DeviceTable>> jsonMsg = deviceController.Query("", "",DateTime.MinValue,DateTime.MinValue);
  124. jsonMsg?.obj?.data?.ForEach(par =>
  125. {
  126. int chid = 0;
  127. try
  128. {
  129. chid = int.Parse(par.ClientId);
  130. }
  131. catch (Exception ex)
  132. {
  133. chid = 0;
  134. }
  135. if (chid>0)
  136. {
  137. DevStatus devStatus = new DevStatus()
  138. {
  139. deviceName = par.devicename,
  140. gmtCreate = par.devicesecret,
  141. productKey = par.productkey,
  142. DeviceMC = par.devtype,
  143. DeviceMS = par.remark,
  144. DeviceSJ = par.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
  145. DeviceZT = "离线",
  146. clientId = par.ClientId,
  147. deviceId = par.DeviceId
  148. };
  149. if (devModel.operatingDeviceStatus.data.Find(o => o.gmtCreate == par.devicesecret) == null)
  150. {
  151. ConsoleHelper.WriteSuccessLine($"加载设备.{par.devtype} {par.remark}");
  152. devModel.operatingDeviceStatus.data.Add(devStatus);
  153. }
  154. }
  155. });
  156. ConsoleHelper.WriteSuccessLine($"加载设备数[ {jsonMsg?.obj?.data?.Count} ]台...");
  157. }
  158. catch (Exception ex)
  159. {
  160. ConsoleHelper.WriteErrorLine($"错误{ex.Message}");
  161. }
  162. }
  163. /// <summary>
  164. /// 订阅主题
  165. /// </summary>
  166. /// <param name="subscribe"></param>
  167. public void Subscribe(string subscribe)
  168. {
  169. IOTDevServer.GetInstance().IOT_Subscribe(subscribe);
  170. ConsoleHelper.WriteSuccessLine("订阅主题: " + subscribe);
  171. }
  172. public void Publish(string PubTopic, CommandModel command)
  173. {
  174. ConsoleHelper.WriteWarningLine("发送数据 " + PubTopic + Tools.JsonConvertTools<CommandModel>(command));
  175. IOTDevServer.GetInstance().IOT_Publish(PubTopic, Tools.JsonConvertTools<CommandModel>(command));
  176. }
  177. /// <summary>
  178. /// 更新内存集合
  179. /// </summary>
  180. /// <param name="receive"></param>
  181. public void SentData(ReceiveModel receiveModel)
  182. {
  183. try
  184. {
  185. if (receiveModel?.deviceContext != null && receiveModel?.status != null)//状态变更消息
  186. {
  187. devModel?.operatingDeviceStatus.data?.Find(par => par.deviceName == receiveModel.deviceContext.deviceName)?.SetStatus(receiveModel.status.value);
  188. devModel?.infoMessage?.data?.Add(new DeviceBase { DeviceMC = receiveModel.deviceContext.deviceName, DeviceMS = $"设备{receiveModel.status.value}了!", DeviceSJ = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") });
  189. DevStatus dev = devModel?.operatingDeviceStatus.data?.Find(par => par.deviceName == receiveModel.deviceContext.deviceName);
  190. if (dev != null)
  191. {
  192. logController.Create(new LogTable
  193. {
  194. devicename = receiveModel.deviceContext.deviceName,
  195. ClientId = dev.clientId,
  196. LogTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  197. LogType = "提示",
  198. LogMessage = $"设备{receiveModel.status.value}了!",
  199. LogVla = "通知"
  200. });
  201. int index = 0;
  202. if (receiveModel.status.value == "离线") index = devModel.operatingDeviceStatus.data.Count - 1;
  203. int now = devModel.operatingDeviceStatus.data.IndexOf(dev);
  204. Swap(devModel.operatingDeviceStatus.data, index, now);
  205. }
  206. else
  207. {
  208. LoadingShopInformation();
  209. }
  210. }
  211. devModel.OrderLine = orderProvider.OrderLine(new DataVApi.Order.RequestModel.FullScreenBasic());
  212. devModel.OrderDataState = orderProvider.GetAllOrderDataState(new DataVApi.Order.RequestModel.FullScreenInput());
  213. devModel.LocSale = orderProvider.GetLocSale();
  214. object obj = orderProvider.OrderNumber(new DataVApi.Order.RequestModel.FullScreenBasic());
  215. devModel.OrderNumber = Tools.JsonToObjectTools<OrderCount>(Tools.JsonConvertTools(obj));
  216. ScreenMonitorModel screen1Monitor = Tools.JsonToObjectTools<ScreenMonitorModel>(devModel.ToJSON());
  217. #region 1.设置data默认值
  218. if (screen1Monitor.operatingDeviceStatus.data.Count == 0)
  219. {
  220. screen1Monitor.operatingDeviceStatus.data.Add(new DevStatus { DeviceMC = "", DeviceMS = "", DeviceSJ = "", deviceName = "", DeviceZT = "", gmtCreate = "" });
  221. }
  222. if (screen1Monitor.infoMessage.data.Count == 0)
  223. {
  224. screen1Monitor.infoMessage.data.Add(new DeviceBase { DeviceMC = "", DeviceMS = "", DeviceSJ = "" });
  225. }
  226. #endregion
  227. string JSON = screen1Monitor.ToJSON();
  228. if (!string.IsNullOrEmpty(JSON))
  229. {
  230. screenController.CreateOrUpdate(new LargeScreenTable() { json = JSON, devicename = "Transit",ClientId = "-10",DeviceId="-10" });
  231. IOTDevServer.GetInstance().IOT_Publish(IOTDevServer.ScreenShowPubTopic, JSON);
  232. }
  233. if (devModel.infoMessage.data != null && devModel.infoMessage.data.Count > 0)
  234. {
  235. List<DeviceBase> bases = devModel.infoMessage.data.ToList();
  236. bases?.ForEach(par =>
  237. {
  238. if (string.IsNullOrEmpty(par.DeviceMC)) devModel.infoMessage.data.Remove(par);
  239. if (!string.IsNullOrEmpty(par.DeviceSJ) && DateTime.Now.AddSeconds(-5) > DateTime.Parse(par.DeviceSJ))
  240. {
  241. devModel.infoMessage.data.Remove(par);
  242. }
  243. });
  244. }
  245. }
  246. catch (Exception ex)
  247. {
  248. ConsoleHelper.WriteErrorLine($"错误{ex.Message}");
  249. }
  250. }
  251. /// <summary>
  252. /// list 位置交换
  253. /// </summary>
  254. /// <typeparam name="T"></typeparam>
  255. /// <param name="list"></param>
  256. /// <param name="index1"></param>
  257. /// <param name="index2"></param>
  258. /// <returns></returns>
  259. private static List<T> Swap<T>(List<T> list, int index1, int index2)
  260. {
  261. var temp = list[index1];
  262. list[index1] = list[index2];
  263. list[index2] = temp;
  264. return list;
  265. }
  266. /// <summary>
  267. /// MQTT 消息
  268. /// </summary>
  269. /// <param name="topic"></param>
  270. /// <param name="message"></param>
  271. private void DevIOTActionHandler(string topic, string message)
  272. {
  273. if (string.IsNullOrEmpty(topic)) return;
  274. if (topic == IOTDevServer.HeartbeatSubTopic)//上下线订阅主题
  275. {
  276. ReceiveModel receiveModel = Tools.JsonToObjectTools<ReceiveModel>(message);
  277. if (receiveModel != null && receiveModel.status != null)//上下线通知
  278. {
  279. if (receiveModel.deviceContext.deviceName != "Transit")
  280. {
  281. ConsoleHelper.WriteWarningLine("接收数据 " + topic + " 数据 " + message);
  282. SentData(receiveModel);
  283. }
  284. }
  285. }
  286. else if (topic == IOTDevServer.BroadcastTopic)//广播主题
  287. {
  288. if (message.Contains("AlarmType"))
  289. {
  290. alarmController.Create(Tools.JsonToObjectTools<AlarmTable>(message));
  291. }
  292. else if (message.Contains("LogType"))
  293. {
  294. logController.Create(Tools.JsonToObjectTools<LogTable>(message));
  295. }
  296. } else if (topic == IOTDevServer.TargetStatusSubTopic)//属性变更
  297. {
  298. ReceiveModel rEmodel = Tools.JsonToObjectTools<ReceiveModel>(message);
  299. string name= rEmodel.deviceContext.deviceName;
  300. string status = rEmodel.props.NodeStatus.value;
  301. string id = deviceController.QueryDeviceName(name)?.obj?.data?.ClientId;
  302. screenController.CreateOrUpdate(new LargeScreenTable() { json = status, devicename = name, ClientId = id, DeviceId = "" });
  303. }
  304. }
  305. }
  306. }