Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

404 linhas
15 KiB

  1. using DataVAPI.Model;
  2. using DataVAPI.ProcessServices.AppConfig;
  3. using DataVAPI.Tool;
  4. using DataVAPI.Tool.API请求;
  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.ProcessServices.阿里云处理流程One
  12. {
  13. /// <summary>
  14. /// 老服务代码
  15. /// </summary>
  16. public class ALY_ProcessServer
  17. {
  18. #region 上报总大屏数据
  19. /// <summary>
  20. /// 上报大屏总Model
  21. /// </summary>
  22. public ScreenMonitorModel devModel { get; set; }
  23. ///// <summary>
  24. ///// 缓存所有设备实时状态列表
  25. ///// </summary>
  26. //public Dictionary<string,ReceiveModel> DataVstatus { get; set; }
  27. /// <summary>
  28. /// 设备查询信息
  29. /// </summary>
  30. public DeviceTable device;
  31. /// <summary>
  32. /// API URL 地址
  33. /// </summary>
  34. public string APIurl = "http://124.222.238.75:6002";
  35. #endregion
  36. #region 不需要监听
  37. private static ALY_ProcessServer _instance;
  38. public static ALY_ProcessServer Instance
  39. {
  40. get
  41. {
  42. if (_instance == null)
  43. _instance = new ALY_ProcessServer();
  44. return _instance;
  45. }
  46. }
  47. public ALY_ProcessServer()
  48. {
  49. }
  50. #endregion
  51. #region 执行函数
  52. /// <summary>
  53. /// 初始化
  54. /// </summary>
  55. public void Initialize()
  56. {
  57. APIurl = AppConfigurtaionServices.Configuration.GetSection("APIurl").Value;
  58. devModel = new ScreenMonitorModel();
  59. devModel.operatingDeviceStatus = new OperatingDeviceStatus(); devModel.operatingDeviceStatus.data = new List<DevStatus>();//现场设备于状态
  60. devModel.infoMessage = new InfoMessage(); devModel.infoMessage.data = new List<DeviceBase>();//通知消息
  61. //devModel.TotalSales = "0";
  62. //加载店铺信息
  63. LoadingShopInformation();
  64. //MQTT 数据接收处理
  65. ConsoleHelper.WriteInfoLine("尝试连接阿里云.");
  66. IOTDevServer.GetInstance().SetUrl(APIurl);
  67. if (IOTDevServer.GetInstance().CreateLinks(10, out device))
  68. {
  69. ConsoleHelper.WriteSuccessLine("连接阿里云成功!");
  70. }
  71. else
  72. {
  73. ConsoleHelper.WriteErrorLine("连接阿里云失败"); return;
  74. }
  75. IOTDevServer.UNConnectMqtt += new Action<string>((o) => { ConsoleHelper.WriteSuccessLine(o); });
  76. Subscribe(IOTDevServer.AlarmSubTopic);
  77. Subscribe(IOTDevServer.LogsSubTopic);
  78. Subscribe(IOTDevServer.HeartbeatSubTopic);
  79. Subscribe(IOTDevServer.TargetStatusSubTopic);
  80. IOTDevServer.DevIOTAction += DevIOTActionHandler;
  81. //执行队列任务
  82. QueueTask();
  83. ConsoleHelper.WriteSuccessLine("开始接收数据,执行队列任务!");
  84. }
  85. /// <summary>
  86. /// 订阅主题
  87. /// </summary>
  88. /// <param name="subscribe"></param>
  89. public void Subscribe(string subscribe)
  90. {
  91. IOTDevServer.GetInstance().IOT_Subscribe(subscribe);
  92. ConsoleHelper.WriteSuccessLine("订阅主题: " + subscribe);
  93. }
  94. /// <summary>
  95. /// 加载店铺信息
  96. /// </summary>
  97. /// <param name="clientId"></param>
  98. public void LoadingShopInformation(string clientId = "")
  99. {
  100. try
  101. {
  102. ConsoleHelper.WriteSuccessLine("加载店铺集合中.");
  103. string url = $"{APIurl}/api/Device/Query?clientId={clientId}";
  104. if (string.IsNullOrEmpty(clientId)) url = $"{APIurl}/api/Device/Query";
  105. string json = HttpRequestHelper.HttpGetRequest(url);
  106. JsonMsg<List<DeviceTable>> jsonMsg = Tools.JsonToObjectTools<JsonMsg<List<DeviceTable>>>(json);
  107. jsonMsg?.obj?.data?.ForEach(par =>
  108. {
  109. if (par.ClientId != "0")
  110. {
  111. DevStatus devStatus = new DevStatus()
  112. {
  113. deviceName = par.devicename,
  114. gmtCreate = par.devicesecret,
  115. productKey = par.productkey,
  116. DeviceMC = par.devtype,
  117. DeviceMS = par.remark,
  118. DeviceSJ = par.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
  119. DeviceZT = "离线",
  120. clientId = par.ClientId
  121. };
  122. if (devModel.operatingDeviceStatus.data.Find(o => o.gmtCreate == par.devicesecret) == null)
  123. {
  124. ConsoleHelper.WriteSuccessLine($"加载设备.{par.devtype} {par.remark}");
  125. devModel.operatingDeviceStatus.data.Add(devStatus);
  126. }
  127. }
  128. });
  129. ConsoleHelper.WriteSuccessLine($"加载设备数[ {jsonMsg?.obj?.data?.FindAll(o => o.ClientId != "0")?.Count()} ]台...");
  130. }
  131. catch (Exception ex)
  132. {
  133. ConsoleHelper.WriteErrorLine($"错误{ex.Message}");
  134. }
  135. }
  136. public void FindDataAlarm()
  137. {
  138. devModel?.operatingDeviceStatus.data?.ForEach(par =>
  139. {
  140. if (!string.IsNullOrEmpty(par.clientId))
  141. {
  142. par.IsAlarm = ApiGetAlarm(par.clientId);
  143. }
  144. });
  145. }
  146. /// <summary>
  147. /// 更新内存集合
  148. /// </summary>
  149. /// <param name="receive"></param>
  150. public void SentData(ReceiveModel receiveModel)
  151. {
  152. try
  153. {
  154. if (receiveModel?.deviceContext != null && receiveModel?.status != null)//状态变更消息
  155. {
  156. devModel?.operatingDeviceStatus.data?.Find(par => par.deviceName == receiveModel.deviceContext.deviceName)?.SetStatus(receiveModel.status.value);
  157. devModel.infoMessage.data.Add(new DeviceBase { DeviceMC = receiveModel.deviceContext.deviceName, DeviceMS = $"设备{receiveModel.status.value}了!", DeviceSJ = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") });
  158. DevStatus dev = devModel?.operatingDeviceStatus.data?.Find(par => par.deviceName == receiveModel.deviceContext.deviceName);
  159. if (dev != null)
  160. {
  161. ApiAddLog(Tools.JsonConvertTools(new LogTable
  162. {
  163. devicename = receiveModel.deviceContext.deviceName,
  164. ClientId = dev.clientId,
  165. LogTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  166. LogType = "1",
  167. LogMessage = $"设备{receiveModel.status.value}了!",
  168. LogVla = "上下线"
  169. }));
  170. }
  171. }
  172. //devModel.TotalSales = devModel.operatingDeviceStatus.data.Count.ToString();
  173. ScreenMonitorModel screen1Monitor = Tools.JsonToObjectTools<ScreenMonitorModel>(devModel.ToJSON());
  174. #region 1.设置data默认值
  175. if (screen1Monitor.operatingDeviceStatus.data.Count == 0)
  176. {
  177. screen1Monitor.operatingDeviceStatus.data.Add(new DevStatus { DeviceMC = "", DeviceMS = "", DeviceSJ = "", deviceName = "", DeviceZT = "", gmtCreate = "" });
  178. }
  179. if (screen1Monitor.infoMessage.data.Count == 0)
  180. {
  181. screen1Monitor.infoMessage.data.Add(new DeviceBase { DeviceMC = "", DeviceMS = "", DeviceSJ = "" });
  182. }
  183. #endregion
  184. string JSON = screen1Monitor.ToJSON();
  185. if (!string.IsNullOrEmpty(JSON))
  186. {
  187. AddScreenCreateOrUpdate(JSON);
  188. IOTDevServer.GetInstance().IOT_Publish(IOTDevServer.ScreenShowPubTopic, JSON);
  189. }
  190. if (devModel.infoMessage.data != null && devModel.infoMessage.data.Count > 0)
  191. {
  192. List<DeviceBase> bases = devModel.infoMessage.data.ToList();
  193. bases?.ForEach(par =>
  194. {
  195. if (string.IsNullOrEmpty(par.DeviceMC)) devModel.infoMessage.data.Remove(par);
  196. if (!string.IsNullOrEmpty(par.DeviceSJ) && DateTime.Now.AddSeconds(-5) > DateTime.Parse(par.DeviceSJ))
  197. {
  198. devModel.infoMessage.data.Remove(par);
  199. }
  200. });
  201. }
  202. }
  203. catch (Exception ex)
  204. {
  205. ConsoleHelper.WriteErrorLine($"错误{ex.Message}");
  206. }
  207. }
  208. /// <summary>
  209. /// 队列任务
  210. /// </summary>
  211. private void QueueTask()
  212. {
  213. Executer.GetInstance().Start(new Action(() =>
  214. {
  215. while (true)
  216. {
  217. try
  218. {
  219. if (IOTDevServer.GetInstance().GetIsConnected())
  220. {
  221. SentData(null);
  222. FindDataAlarm();
  223. Thread.Sleep(3000);
  224. }
  225. }
  226. catch (Exception ex)
  227. {
  228. ConsoleHelper.WriteErrorLine(ex.Message);
  229. }
  230. }
  231. }), "队列任务执行");
  232. }
  233. /// <summary>
  234. /// MQTT 消息
  235. /// </summary>
  236. /// <param name="topic"></param>
  237. /// <param name="message"></param>
  238. private void DevIOTActionHandler(string topic, string message)
  239. {
  240. if (string.IsNullOrEmpty(topic)) return;
  241. if (topic == IOTDevServer.AlarmSubTopic)//告警订阅主题
  242. {
  243. if (message.Contains("UpdateTime") && message.Contains("ClientId") && message.Contains("CreateTime"))
  244. {
  245. ApiAddAlarm(message);
  246. }
  247. }
  248. else if (topic == IOTDevServer.LogsSubTopic)//日志订阅主题
  249. {
  250. if (message.Contains("UpdateTime") && message.Contains("ClientId") && message.Contains("CreateTime"))
  251. {
  252. ApiAddLog(message);
  253. }
  254. }
  255. else if (topic == IOTDevServer.HeartbeatSubTopic)//上下线订阅主题
  256. {
  257. ReceiveModel receiveModel = Tools.JsonToObjectTools<ReceiveModel>(message);
  258. if (receiveModel != null && receiveModel.status != null)//上下线通知
  259. {
  260. if (receiveModel.deviceContext.deviceName == "hbldev") return;
  261. ConsoleHelper.WriteWarningLine("接收数据 " + topic + " 数据 " + message);
  262. SentData(receiveModel);
  263. }
  264. }
  265. else if (topic == IOTDevServer.TargetStatusSubTopic)//属性状态主题
  266. {
  267. }
  268. }
  269. #endregion
  270. #region API 函数操作
  271. /// <summary>
  272. /// 增加或者更新
  273. /// </summary>
  274. /// <param name="json"></param>
  275. /// <returns></returns>
  276. public bool AddScreenCreateOrUpdate(string json)
  277. {
  278. try
  279. {
  280. ///api/Screen/CreateOrUpdate
  281. string url = APIurl + "/api/Screen/CreateOrUpdate";
  282. HttpRequestHelper.HttpPostRequest(url, Tools.JsonConvertTools(new LargeScreen() { json = json, devicename = device.devicename, clientId = device.ClientId })); return true;
  283. }
  284. catch (Exception ex)
  285. {
  286. return false;
  287. }
  288. }
  289. /// <summary>
  290. /// 查询告警信息
  291. /// </summary>
  292. /// <param name="clientId"></param>
  293. public bool ApiGetAlarm(string clientId)
  294. {
  295. try
  296. {
  297. //http://124.222.238.75:6002/api/Alarm/QueryClientId?clientId=9
  298. string url = APIurl + "/api/Alarm/QueryClientId?clientId=" + clientId;
  299. string json = HttpRequestHelper.HttpGetRequest(url);
  300. if (json != null && json.Contains("alarmMessage"))
  301. return true;
  302. else
  303. return false;
  304. }
  305. catch (Exception ex)
  306. {
  307. ConsoleHelper.WriteErrorLine(ex.Message); return false;
  308. }
  309. }
  310. /// <summary>
  311. /// 增加告警信息
  312. /// </summary>
  313. /// <param name="alarm"></param>
  314. public void ApiAddAlarm(string alarm)
  315. {
  316. try
  317. {
  318. AlarmTable al = Tools.JsonToObjectTools<AlarmTable>(alarm);
  319. if (al != null)
  320. {
  321. if (string.IsNullOrEmpty(al.devicename))
  322. {
  323. al.devicename = devModel?.operatingDeviceStatus.data?.Find(par => par.clientId == al.ClientId)?.deviceName;
  324. }
  325. string url = APIurl + "/api/Alarm/Create";
  326. HttpRequestHelper.HttpPostRequest(url, Tools.JsonConvertTools(al));
  327. }
  328. }
  329. catch (Exception ex)
  330. {
  331. ConsoleHelper.WriteErrorLine(ex.Message);
  332. }
  333. }
  334. /// <summary>
  335. /// 增加日志信息
  336. /// </summary>
  337. /// <param name="logTable"></param>
  338. public void ApiAddLog(string logTable)
  339. {
  340. try
  341. {
  342. LogTable lo = Tools.JsonToObjectTools<LogTable>(logTable);
  343. if (lo != null)
  344. {
  345. if (string.IsNullOrEmpty(lo.devicename))
  346. {
  347. lo.devicename = devModel?.operatingDeviceStatus.data?.Find(par => par.clientId == lo.ClientId)?.deviceName;
  348. }
  349. string url = APIurl + "/api/Log/Create";
  350. HttpRequestHelper.HttpPostRequest(url, Tools.JsonConvertTools(lo));
  351. }
  352. }
  353. catch (Exception ex)
  354. {
  355. ConsoleHelper.WriteErrorLine(ex.Message);
  356. }
  357. }
  358. #endregion
  359. }
  360. public class LargeScreen
  361. {
  362. public string json { get; set; }
  363. public string devicename { get; set; }
  364. public string clientId { get; set; }
  365. }
  366. }