终端一体化运控平台
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

376 satır
15 KiB

  1. using BPA.Message.Enum;
  2. using BPA.Message.IOT;
  3. using BPASmartClient.Business;
  4. using BPASmartClient.Device;
  5. using BPASmartClient.Helper;
  6. using BPASmartClient.IoT.Model;
  7. using BPASmartClient.Message;
  8. using BPASmartDatavDeviceClient.IoT;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Threading;
  13. namespace BPASmartClient.IoT
  14. {
  15. /// <summary>
  16. /// DataV客户端数据中心
  17. /// </summary>
  18. public class DataVClient
  19. {
  20. #region 单例模式
  21. public static DataVClient init = null;
  22. public static DataVClient GetInstance()
  23. {
  24. if (init == null)
  25. {
  26. init = new DataVClient();
  27. }
  28. return init;
  29. }
  30. /// <summary>
  31. /// 显示定义构造函数为私有,表示只允许自己实例化自己
  32. /// </summary>
  33. public DataVClient()
  34. {
  35. DataVApiAddress = System.Configuration.ConfigurationManager.AppSettings["DataVServiceUri"].ToString();
  36. ClientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"].ToString();
  37. DeviceName = System.Configuration.ConfigurationManager.AppSettings["DeviceName"].ToString();
  38. ProductKey = System.Configuration.ConfigurationManager.AppSettings["ProductKey"].ToString();
  39. DeviceSecret = System.Configuration.ConfigurationManager.AppSettings["DeviceSecret"].ToString();
  40. StartupMode = System.Configuration.ConfigurationManager.AppSettings["StartupMode"].ToString();
  41. BroadcastPubTopic = System.Configuration.ConfigurationManager.AppSettings["BroadcastPubTopic"].ToString();
  42. }
  43. #endregion
  44. #region 公有变量
  45. public string StartupMode { set; get; }
  46. public string DeviceName { set; get; }
  47. public string ProductKey { set; get; }
  48. public string DeviceSecret { set; get; }
  49. public string BroadcastPubTopic { set; get; }
  50. /// <summary>
  51. /// DataV 服务地址
  52. /// </summary>
  53. public string DataVApiAddress { set; get; }
  54. /// <summary>
  55. /// 客户端ID
  56. /// </summary>
  57. public string ClientId { set; get; }
  58. /// <summary>
  59. /// MQTT上报集合
  60. /// </summary>
  61. public DataVReport DeviceDataV = new DataVReport();
  62. /// <summary>
  63. /// 大屏上报Model
  64. /// </summary>
  65. public DataVAPI.Tool.IOT.IOTDevSXModel iOTDevSXModel = new DataVAPI.Tool.IOT.IOTDevSXModel() { };
  66. /// <summary>
  67. /// key值
  68. /// </summary>
  69. public Dictionary<string, string> keyValues = new Dictionary<string, string>();
  70. #endregion
  71. #region API调用
  72. /// <summary>
  73. /// 增加告警信息
  74. /// </summary>
  75. /// <param name="alarmTable"></param>
  76. /// <returns>返回ID</returns>
  77. public string HttpAddAlarm(AlarmTable alarmTable)
  78. {
  79. try
  80. {
  81. if (DeviceDataV != null && DeviceDataV.GetIsConnected() && DeviceDataV.deviceTable != null)
  82. {
  83. alarmTable.ClientId = ClientId;
  84. alarmTable.devicename = DeviceDataV.deviceTable.devicename;
  85. DeviceDataV.IOT_Publish(BroadcastPubTopic, Tools.JsonConvertTools(alarmTable));
  86. }
  87. }
  88. catch (Exception ex)
  89. {
  90. MessageLog.GetInstance.Show(ex.Message);
  91. }
  92. return alarmTable.KeyID;
  93. }
  94. /// <summary>
  95. /// 增加日志信息
  96. /// </summary>
  97. /// <param name="alarmTable"></param>
  98. /// <returns>返回ID</returns>
  99. public string HttpAddLog(LogTable logTable)
  100. {
  101. string id = string.Empty;
  102. try
  103. {
  104. if (DeviceDataV != null && DeviceDataV.GetIsConnected() && DeviceDataV.deviceTable != null)
  105. {
  106. logTable.ClientId = ClientId;
  107. logTable.devicename = DeviceDataV.deviceTable.devicename;
  108. DeviceDataV.IOT_Publish(BroadcastPubTopic, Tools.JsonConvertTools(logTable));
  109. }
  110. }
  111. catch (Exception ex)
  112. {
  113. MessageLog.GetInstance.Show(ex.Message);
  114. }
  115. return id;
  116. }
  117. #endregion
  118. #region 公用
  119. /// <summary>
  120. /// 释放
  121. /// </summary>
  122. public void Dispose()
  123. {
  124. ThreadManage.GetInstance().StopTask("DataV数据上报");
  125. }
  126. /// <summary>
  127. /// 初始化
  128. /// </summary>
  129. public void Initialize()
  130. {
  131. string message = string.Empty;
  132. if (StartupMode == "API")
  133. {
  134. if (DeviceDataV.Initialize(DataVApiAddress, ClientId, "", ref message))
  135. {
  136. ProductKey = DeviceDataV.deviceTable.productkey;
  137. DeviceName = DeviceDataV.deviceTable.devicename;
  138. DeviceSecret = DeviceDataV.deviceTable.devicesecret;
  139. DeviceDataV.DataVMessageAction += DevIOTActionHandler;
  140. MessageLog.GetInstance.Show($"客户端:【{ClientId}】,设备名称{DeviceName}阿里云连接成功");
  141. UpDataFile();
  142. }
  143. else
  144. {
  145. MessageLog.GetInstance.ShowEx(message);
  146. }
  147. }
  148. else
  149. {
  150. if (DeviceDataV.InitializeNo(ProductKey, DeviceName, DeviceSecret, ref message))
  151. {
  152. MessageLog.GetInstance.Show($"客户端:【{ClientId}】,设备名称{DeviceName}阿里云连接成功");
  153. UpDataFile();
  154. }
  155. else
  156. MessageLog.GetInstance.ShowEx(message);
  157. }
  158. Plugin.GetInstance()?.GetPlugin<DeviceMgr>()?.GetDevices()?.ForEach(device =>
  159. {
  160. device.AddErrorAction += AddErrorAction;
  161. device.DeleteErrorAction += DeleteErrorAction;
  162. });
  163. }
  164. /// <summary>
  165. /// 启动DataV数据上报
  166. /// </summary>
  167. public void Start()
  168. {
  169. ThreadManage.GetInstance().StartLong(new Action(() =>
  170. {
  171. if (DeviceDataV != null && DeviceDataV.GetIsConnected() && DeviceDataV.deviceTable != null)
  172. {
  173. iOTDevSXModel.Device1=String.Empty;iOTDevSXModel.Device2=String.Empty;iOTDevSXModel.Device3 = String.Empty;
  174. List<object> dataVNode = new List<object>();
  175. Plugin.GetInstance()?.GetPlugin<DeviceMgr>()?.GetDevices()?.ForEach(device =>
  176. {
  177. var obj = new
  178. {
  179. DeviceId = device.DeviceId.ToString(),
  180. devicename = DeviceDataV.deviceTable.devicename,
  181. Name = device.Name,
  182. DeviceType = device.DeviceType.ToString(),
  183. IsBusy = device.IsBusy ? "忙碌" : "空闲",
  184. IsBusyColor = device.IsBusy ? new ALYColor { r = 255, g = 0, b = 0, a = 1 } : new ALYColor { r = 51, g = 232, b = 34, a = 1 },
  185. IsHealth = device.IsHealth ? "健康" : "故障",
  186. IsHealthColor = !device.IsHealth ? new ALYColor { r = 255, g = 0, b = 0, a = 1 } : new ALYColor { r = 51, g = 232, b = 34, a = 1 },
  187. Status = device.Status.GetIOTStatus(),
  188. gjxx = device.GetError(),
  189. rzxx = device.GetLog(),
  190. VariableMonitor = device.GetVariableMonitor(),
  191. };
  192. dataVNode.Add(obj);
  193. if (string.IsNullOrEmpty(iOTDevSXModel.Device1)) iOTDevSXModel.Device1 = $"[{device.Name}]:{(device.IsBusy ? "忙碌" : "空闲")}-{(device.IsHealth ? "健康" : "故障")}";
  194. else if (string.IsNullOrEmpty(iOTDevSXModel.Device2)) iOTDevSXModel.Device2 = $"[{device.Name}]:{(device.IsBusy ? "忙碌" : "空闲")}-{(device.IsHealth ? "健康" : "故障")}";
  195. else if (string.IsNullOrEmpty(iOTDevSXModel.Device3)) iOTDevSXModel.Device3 = $"[{device.Name}]:{(device.IsBusy ? "忙碌" : "空闲")}-{(device.IsHealth ? "健康" : "故障")}";
  196. });
  197. if (dataVNode.Count > 0)
  198. {
  199. iOTDevSXModel.NodeStatus = Tools.JsonConvertTools(new { data = dataVNode });
  200. DeviceDataV.IOT_Publish(DeviceDataV.PubTopic, iOTDevSXModel.Tojson());
  201. }
  202. }
  203. Thread.Sleep(3000);
  204. }), "DataV数据上报", true);
  205. }
  206. /// <summary>
  207. /// 文件上传请求
  208. /// </summary>
  209. public void UpDataFile()
  210. {
  211. try
  212. {
  213. if (DeviceDataV != null && DeviceDataV.GetIsConnected() && DeviceDataV.deviceTable != null)
  214. {
  215. FileUpload.FileRequest(DeviceDataV);
  216. }
  217. }
  218. catch (Exception ex)
  219. {
  220. MessageLog.GetInstance.Show(ex.Message);
  221. }
  222. }
  223. #endregion
  224. #region 私有
  225. /// <summary>
  226. /// 增加告警
  227. /// </summary>
  228. /// <param name="obj"></param>
  229. private void AddErrorAction(int Devid, object obj)
  230. {
  231. string id = Guid.NewGuid().ToString();
  232. HttpAddAlarm(new AlarmTable
  233. {
  234. AlarmTime = GetPropertyValue(obj, "Time").ToString(),
  235. AlarmType = GetPropertyValue(obj, "Type").ToString(),
  236. AlarmMessage = GetPropertyValue(obj, "Text").ToString(),
  237. AlarmVla = "告警",
  238. DeviceId = Devid.ToString(),
  239. KeyID = id,
  240. });
  241. keyValues[GetPropertyValue(obj, "Time").ToString() + GetPropertyValue(obj, "Type").ToString() + GetPropertyValue(obj, "Text").ToString()] = id;
  242. //MessageLog.GetInstance.AddDeviceAlarmLogShow(GetPropertyValue(obj, "Time").ToString() + GetPropertyValue(obj, "Type").ToString() + GetPropertyValue(obj, "Text").ToString(),id);
  243. }
  244. /// <summary>
  245. /// 删除告警
  246. /// </summary>
  247. /// <param name="obj"></param>
  248. private void DeleteErrorAction(int Devid, object obj)
  249. {
  250. string message = GetPropertyValue(obj, "Time").ToString() + GetPropertyValue(obj, "Type").ToString() + GetPropertyValue(obj, "Text").ToString();
  251. if (keyValues.ContainsKey(message))
  252. {
  253. HttpAddAlarm(new AlarmTable
  254. {
  255. AlarmTime = GetPropertyValue(obj, "Time").ToString(),
  256. AlarmType = GetPropertyValue(obj, "Type").ToString(),
  257. AlarmMessage = GetPropertyValue(obj, "Text").ToString(),
  258. AlarmVla = "告警",
  259. DeviceId = Devid.ToString(),
  260. KeyID = keyValues[message],
  261. State = "n"
  262. });
  263. //MessageLog.GetInstance.DeleteDeviceAlarmLogShow(message, keyValues[message]);
  264. }
  265. }
  266. /// <summary>
  267. /// 接收云端消息
  268. /// </summary>
  269. /// <param name="topic"></param>
  270. /// <param name="message"></param>
  271. private void DevIOTActionHandler(string deviceId, string topic, string message)
  272. {
  273. if (DeviceDataV.BroadcastTopic == topic && !string.IsNullOrEmpty(message))//广播主题消息,将广播消息发送到相应客户端
  274. {
  275. IOTCommandModel iOTCommand = Tools.JsonToObjectTools<IOTCommandModel>(message);
  276. if (iOTCommand.deviceName == DeviceDataV.deviceTable.devicename)
  277. ActionManage.GetInstance.Send("IotBroadcast", iOTCommand);
  278. }
  279. else if (DeviceDataV.FileUpLoadReplyTopic == topic)//文件请求上传响应Topic
  280. {
  281. FileUploadModelResult result = Tools.JsonToObjectTools<FileUploadModelResult>(message);
  282. if (result.code == 200)
  283. {
  284. string FileName = result.data?.fileName;
  285. string uploadId = result.data?.uploadId;
  286. FileUpload.SetUploadData(result.id,uploadId);
  287. FileUpload.FileSend(DeviceDataV, uploadId);
  288. MessageLog.GetInstance.Show($"请求上传【阿里云】成功,准备上传日志文件【HBL.LogDir{DateTime.Now.ToString("yyyy_M_d")}.log】");
  289. }
  290. else
  291. MessageLog.GetInstance.Show($"【HBL.LogDir{DateTime.Now.ToString("yyyy_M_d")}.log】请求上传【阿里云】失败,{result.message}");
  292. }
  293. else if (DeviceDataV.FileUpLoadSendReplyTopic == topic)//文件上传Topic
  294. {
  295. FileUploadModelResult result = Tools.JsonToObjectTools<FileUploadModelResult>(message);
  296. if (result.code == 200)
  297. {
  298. MessageLog.GetInstance.Show($"今日日志文件“HBL.LogDir{DateTime.Now.ToString("yyyy_M_d")}.log”更新上传【阿里云】成功");
  299. bool complete = result.data.complete;
  300. string uploadId = result.data?.uploadId;
  301. }else
  302. MessageLog.GetInstance.Show($"今日日志文件“HBL.LogDir{DateTime.Now.ToString("yyyy_M_d")}.log”更新上传【阿里云】失败,{result.message}");
  303. }
  304. else if (DeviceDataV.CancelFileUpLoadSendReplyTopic == topic)//取消文件上传Topic
  305. {
  306. FileUploadModelResult result = Tools.JsonToObjectTools<FileUploadModelResult>(message);
  307. }
  308. }
  309. /// <summary>
  310. /// 获取某个对象中的属性值
  311. /// </summary>
  312. /// <param name="info"></param>
  313. /// <param name="field"></param>
  314. public object GetPropertyValue(object info, string field)
  315. {
  316. if (info == null) return null;
  317. Type t = info.GetType();
  318. IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
  319. return property.First().GetValue(info, null);
  320. }
  321. #endregion
  322. }
  323. //命令实体类
  324. public class IOTCommandModel
  325. {
  326. /// <summary>
  327. /// 设备名称
  328. /// </summary>
  329. public string deviceName
  330. {
  331. get;
  332. set;
  333. }
  334. /// <summary>
  335. /// 命令名称:0 控制类 1 设置属性 2 通知信息类
  336. /// </summary>
  337. public int CommandName
  338. {
  339. get;
  340. set;
  341. }
  342. /// <summary>
  343. /// 命令变量:执行变量 key为属性或时间 value为值或者消息
  344. /// </summary>
  345. public Dictionary<string, string> CommandValue
  346. {
  347. get;
  348. set;
  349. }
  350. }
  351. }