终端一体化运控平台
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

493 rindas
17 KiB

  1. //using BPA.Helper;
  2. //using BPASmartClient.IoT;
  3. //using Newtonsoft.Json;
  4. //using System;
  5. //using System.Collections.Generic;
  6. //using System.IO;
  7. //using System.Linq;
  8. //using System.Net;
  9. //using System.Net.Sockets;
  10. //using System.Security.Cryptography;
  11. //using System.Text;
  12. //using System.Threading;
  13. //using uPLibrary.Networking.M2Mqtt;
  14. //using uPLibrary.Networking.M2Mqtt.Messages;
  15. //namespace DataVAPI.Tool.IOT
  16. //{
  17. // /// <summary>
  18. // /// add fengyoufu
  19. // /// 黑菠萝科技有限公司
  20. // /// IOT设备上报消息类
  21. // /// </summary>
  22. // public class IOTDevServer
  23. // {
  24. // #region 私有IOT连接变量
  25. // private static string ProductKey = "grgpECHSL7q";
  26. // private static string DeviceName = "hbldev";
  27. // private static string DeviceSecret = "4ec120de0c866199183b22e2e3135aeb";
  28. // private static string RegionId = "cn-shanghai";
  29. // private static string mqttUserName = string.Empty;
  30. // private static string mqttPassword = string.Empty;
  31. // private static string mqttClientId = string.Empty;
  32. // private static string targetServer = string.Empty;
  33. // #endregion
  34. // #region 公有变量
  35. // /// <summary>
  36. // /// 设备消息数据回调
  37. // /// </summary>
  38. // public static Action<string, string> DevIOTAction { get; set; }
  39. // /// <summary>
  40. // /// 重连事件
  41. // /// </summary>
  42. // public static Action<string> UNConnectMqtt { get; set; }
  43. // /// <summary>
  44. // /// 客户端
  45. // /// </summary>
  46. // public static MqttClient client { get; set; }
  47. // #endregion
  48. // #region 发布或订阅主题或URL地址
  49. // /// <summary>
  50. // /// API 服务
  51. // /// </summary>
  52. // private static string APIurl = "http://124.222.238.75:6002";
  53. // /// <summary>
  54. // /// 属性发布消息主题
  55. // /// </summary>
  56. // public static string PubTopic = "/" + ProductKey + "/" + DeviceName + "/user/update";
  57. // /// <summary>
  58. // /// 属性接收消息主题
  59. // /// </summary>
  60. // public static string SubTopic = "/" + ProductKey + "/" + DeviceName + "/user/get";
  61. // /// <summary>
  62. // /// 自定义发布消息主题
  63. // /// </summary>
  64. // public static string UserPubTopic = "/" + ProductKey + "/" + DeviceName + "/user/update";
  65. // /// <summary>
  66. // /// 自定义接收消息主题
  67. // /// </summary>
  68. // public static string UserSubTopic = "/" + ProductKey + "/" + DeviceName + "/user/get";
  69. // /// <summary>
  70. // /// 告警订阅主题
  71. // /// </summary>
  72. // public static string AlarmSubTopic = "/" + ProductKey + "/" + DeviceName + "/user/AlarmMessage";
  73. // /// <summary>
  74. // /// 日志订阅主题
  75. // /// </summary>
  76. // public static string LogsSubTopic = "/" + ProductKey + "/" + DeviceName + "/user/ExceptionLogs";
  77. // /// <summary>
  78. // /// 上下线订阅主题
  79. // /// </summary>
  80. // public static string HeartbeatSubTopic = "/" + ProductKey + "/" + DeviceName + "/user/HeartbeatAndState";
  81. // /// <summary>
  82. // /// 属性状态主题
  83. // /// </summary>
  84. // public static string TargetStatusSubTopic = "/" + ProductKey + "/" + DeviceName + "/user/TargetStatus";
  85. // /// <summary>
  86. // /// 大屏展示发布主题
  87. // /// </summary>
  88. // public static string ScreenShowPubTopic = "/" + ProductKey + "/" + DeviceName + "/user/ScreenShow";
  89. // /// <summary>
  90. // /// 广播主题
  91. // /// </summary>
  92. // public static string BroadcastTopic = "/broadcast/" + "grgpECHSL7q" + "/" + DeviceName + "_SetDevice";
  93. // /// <summary>
  94. // /// 订阅主题集合
  95. // /// </summary>
  96. // public static List<string> SubTopicList = new List<string>();
  97. // #endregion
  98. // #region 单例模式
  99. // private static IOTDevServer iot = null;
  100. // public static IOTDevServer GetInstance
  101. // {
  102. // if (iot == null) { iot = new IOTDevServer();
  103. // }
  104. // return iot;
  105. // }
  106. //#endregion
  107. //#region 公共调用阿里云连接或检测
  108. ///// <summary>
  109. ///// 设置URL
  110. ///// </summary>
  111. ///// <param name="url"></param>
  112. //public void SetUrl(string url = "http://124.222.238.75:6002")
  113. //{
  114. // APIurl = url;
  115. //}
  116. ///// <summary>
  117. ///// 设置变量
  118. ///// </summary>
  119. ///// <param name="_ProductKey"></param>
  120. ///// <param name="_DeviceName"></param>
  121. ///// <param name="_DeviceSecret"></param>
  122. ///// <param name="_RegionId"></param>
  123. //public void Set(string _ProductKey, string _DeviceName, string _DeviceSecret, string _RegionId = "cn-shanghai")
  124. //{
  125. // ProductKey = _ProductKey;
  126. // DeviceName = _DeviceName;
  127. // DeviceSecret = _DeviceSecret;
  128. // RegionId = _RegionId;
  129. // PubTopic = "/sys/" + ProductKey + "/" + DeviceName + "/thing/event/property/post";
  130. // SubTopic = "/sys/" + ProductKey + "/" + DeviceName + "/thing/event/property/set";
  131. // UserPubTopic = "/" + ProductKey + "/" + DeviceName + "/user/update";
  132. // UserSubTopic = "/" + ProductKey + "/" + DeviceName + "/user/get";
  133. // BroadcastTopic = "/broadcast/" + ProductKey + "/" + DeviceName + "_SetDevice";
  134. // AlarmSubTopic = "/" + ProductKey + "/" + DeviceName + "/user/AlarmMessage";
  135. // LogsSubTopic = "/" + ProductKey + "/" + DeviceName + "/user/ExceptionLogs";
  136. // HeartbeatSubTopic = "/" + ProductKey + "/" + DeviceName + "/user/HeartbeatAndState";
  137. // TargetStatusSubTopic = "/" + ProductKey + "/" + DeviceName + "/user/TargetStatus";
  138. // ScreenShowPubTopic = "/" + ProductKey + "/" + DeviceName + "/user/ScreenShow";
  139. //}
  140. ///// <summary>
  141. ///// 创建连接
  142. ///// </summary>
  143. ///// <returns></returns>
  144. //public bool CreateLinks(int ClientId, out DeviceTable device)
  145. //{
  146. // try
  147. // {
  148. // //http://localhost:9092/api/Device/Query?chid=2
  149. // //string json = APIHelper.GetInstance.GetRequest($"{APIurl}/api/Device/Query?clientId={ClientId}");
  150. // string json = APIHelper.GetInstance.GetRequest($"{APIurl}/api/Device/Query?clientId={ClientId}");
  151. // JsonMsg<List<DeviceTable>> jsonMsg = Tools.JsonToObjectTools<JsonMsg<List<DeviceTable>>>(json);
  152. // if (jsonMsg.obj != null && jsonMsg.obj.data != null)
  153. // {
  154. // device = jsonMsg.obj.data.FirstOrDefault();
  155. // if (device == null) return false;
  156. // Set(device.productkey, device.devicename, device.devicesecret);
  157. // IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
  158. // string clientId = host.AddressList.FirstOrDefault(
  159. // ip => ip.AddressFamily == AddressFamily.InterNetwork).ToString();
  160. // string t = Convert.ToString(DateTimeOffset.Now.ToUnixTimeMilliseconds());
  161. // string signmethod = "hmacmd5";
  162. // Dictionary<string, string> dict = new Dictionary<string, string>();
  163. // dict.Add("productKey", ProductKey);
  164. // dict.Add("deviceName", DeviceName);
  165. // dict.Add("clientId", clientId);
  166. // dict.Add("timestamp", t);
  167. // mqttUserName = DeviceName + "&" + ProductKey;
  168. // mqttPassword = IotSignUtils.sign(dict, DeviceSecret, signmethod);
  169. // mqttClientId = clientId + "|securemode=3,signmethod=" + signmethod + ",timestamp=" + t + "|";
  170. // targetServer = ProductKey + ".iot-as-mqtt." + RegionId + ".aliyuncs.com";
  171. // ConnectMqtt(targetServer, mqttClientId, mqttUserName, mqttPassword);
  172. // return true;
  173. // }
  174. // else
  175. // {
  176. // device = null;
  177. // return false;
  178. // }
  179. // }
  180. // catch (Exception ex)
  181. // {
  182. // device = null;
  183. // return false;
  184. // }
  185. //}
  186. ///// <summary>
  187. ///// 获取连接状态
  188. ///// </summary>
  189. //public bool GetIsConnected()
  190. //{
  191. // try
  192. // {
  193. // if (client == null || !client.IsConnected)
  194. // return false;
  195. // else return true;
  196. // }
  197. // catch (Exception ex)
  198. // {
  199. // return false;
  200. // throw;
  201. // }
  202. //}
  203. ///// <summary>
  204. ///// 断开连接
  205. ///// </summary>
  206. //public void Disconnect()
  207. //{
  208. // if (client != null)
  209. // {
  210. // client.Disconnect();
  211. // }
  212. //}
  213. //#endregion
  214. //#region 公共发布或订阅函数
  215. ///// <summary>
  216. ///// 发布消息
  217. ///// </summary>
  218. ///// <param name="topic"></param>
  219. ///// <param name="message"></param>
  220. //public void IOT_Publish(string topic, string message)
  221. //{
  222. // var id = client.Publish(topic, Encoding.UTF8.GetBytes(message));
  223. //}
  224. ///// <summary>
  225. ///// 订阅主题
  226. ///// </summary>
  227. ///// <param name="topic"></param>
  228. //public void IOT_Subscribe(string topic)
  229. //{
  230. // if (SubTopicList.Contains(topic))
  231. // {
  232. // SubTopicList.Add(topic);
  233. // }
  234. // client.Subscribe(new string[] { topic }, new byte[] { 0 });
  235. //}
  236. //#endregion
  237. //#region 私有函数
  238. ///// <summary>
  239. ///// mQTT创建连接
  240. ///// </summary>
  241. ///// <param name="targetServer"></param>
  242. ///// <param name="mqttClientId"></param>
  243. ///// <param name="mqttUserName"></param>
  244. ///// <param name="mqttPassword"></param>
  245. //private void ConnectMqtt(string targetServer, string mqttClientId, string mqttUserName, string mqttPassword)
  246. //{
  247. // client = new MqttClient(targetServer);
  248. // client.ProtocolVersion = MqttProtocolVersion.Version_3_1_1;
  249. // client.Connect(mqttClientId, mqttUserName, mqttPassword, false, 60);
  250. // client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
  251. // client.ConnectionClosed += Client_ConnectionClosed;
  252. //}
  253. ///// <summary>
  254. ///// MQTT 断开事件
  255. ///// </summary>
  256. ///// <param name="sender"></param>
  257. ///// <param name="e"></param>
  258. //private static void Client_ConnectionClosed(object sender, EventArgs e)
  259. //{
  260. // // 尝试重连
  261. // _TryContinueConnect();
  262. //}
  263. ///// <summary>
  264. ///// 订阅数据接收
  265. ///// </summary>
  266. ///// <param name="sender"></param>
  267. ///// <param name="e"></param>
  268. //private static void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
  269. //{
  270. // string topic = e.Topic;
  271. // string message = Encoding.UTF8.GetString(e.Message);
  272. // if (DevIOTAction != null)
  273. // {
  274. // DevIOTAction.Invoke(topic, message);
  275. // }
  276. //}
  277. ///// <summary>
  278. ///// 自动重连主体
  279. ///// </summary>
  280. //private static void _TryContinueConnect()
  281. //{
  282. // Thread retryThread = new Thread(new ThreadStart(delegate
  283. // {
  284. // while (client == null || !client.IsConnected)
  285. // {
  286. // if (client.IsConnected) break;
  287. // if (client == null)
  288. // {
  289. // client = new MqttClient(targetServer);
  290. // client.ProtocolVersion = MqttProtocolVersion.Version_3_1_1;
  291. // client.Connect(mqttClientId, mqttUserName, mqttPassword, false, 60);
  292. // client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
  293. // client.ConnectionClosed += Client_ConnectionClosed;
  294. // if (client.IsConnected)
  295. // {
  296. // SubTopicList.ForEach(par =>
  297. // {
  298. // client.Subscribe(new string[] { par }, new byte[] { 0 });
  299. // });
  300. // }
  301. // Thread.Sleep(3000);
  302. // continue;
  303. // }
  304. // try
  305. // {
  306. // client.Connect(mqttClientId, mqttUserName, mqttPassword, false, 60);
  307. // if (client.IsConnected)
  308. // {
  309. // SubTopicList.ForEach(par =>
  310. // {
  311. // client.Subscribe(new string[] { par }, new byte[] { 0 });
  312. // });
  313. // UNConnectMqtt?.Invoke("重新连接阿里云MQTT成功!");
  314. // }
  315. // }
  316. // catch (Exception ce)
  317. // {
  318. // UNConnectMqtt?.Invoke("重新连接阿里云MQTT失败!");
  319. // }
  320. // // 如果还没连接不符合结束条件则睡2秒
  321. // if (!client.IsConnected)
  322. // {
  323. // Thread.Sleep(2000);
  324. // }
  325. // }
  326. // }));
  327. // retryThread.Start();
  328. //}
  329. //#endregion
  330. ///// <summary>
  331. ///// Iot 设备上报
  332. ///// </summary>
  333. //public class IotSignUtils
  334. //{
  335. // public static string sign(Dictionary<string, string> param,
  336. // string deviceSecret, string signMethod)
  337. // {
  338. // string[] sortedKey = param.Keys.ToArray();
  339. // Array.Sort(sortedKey);
  340. // StringBuilder builder = new StringBuilder();
  341. // foreach (var i in sortedKey)
  342. // {
  343. // builder.Append(i).Append(param[i]);
  344. // }
  345. // byte[] key = Encoding.UTF8.GetBytes(deviceSecret);
  346. // byte[] signContent = Encoding.UTF8.GetBytes(builder.ToString());
  347. // //这里根据signMethod动态调整,本例子硬编码了: 'hmacmd5'
  348. // var hmac = new HMACMD5(key);
  349. // byte[] hashBytes = hmac.ComputeHash(signContent);
  350. // StringBuilder signBuilder = new StringBuilder();
  351. // foreach (byte b in hashBytes)
  352. // signBuilder.AppendFormat("{0:x2}", b);
  353. // return signBuilder.ToString();
  354. // }
  355. // /// <summary>
  356. // /// 工具
  357. // /// </summary>
  358. // public class Tools
  359. // {
  360. // /// <summary>
  361. // /// 对象Json序列
  362. // /// </summary>
  363. // /// <typeparam name="T">对象类型</typeparam>
  364. // /// <param name="obj">对象实例</param>
  365. // /// <returns></returns>
  366. // public static string JsonConvertTools<T>(T obj)
  367. // {
  368. // string strvalue = JsonConvert.SerializeObject(obj);
  369. // return strvalue;
  370. // }
  371. // /// <summary>
  372. // /// 对象反Json序列
  373. // /// </summary>
  374. // /// <typeparam name="T">对象类型</typeparam>
  375. // /// <param name="jsonstring">对象序列化json字符串</param>
  376. // /// <returns>返回对象实例</returns>
  377. // public static T JsonToObjectTools<T>(string jsonstring)
  378. // {
  379. // T obj = JsonConvert.DeserializeObject<T>(jsonstring);
  380. // return obj;
  381. // }
  382. // /// <summary>
  383. // /// DateTime --> long
  384. // /// </summary>
  385. // /// <param name="dt"></param>
  386. // /// <returns></returns>
  387. // public static long ConvertDateTimeToLong(DateTime dt)
  388. // {
  389. // DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  390. // TimeSpan toNow = dt.Subtract(dtStart);
  391. // long timeStamp = toNow.Ticks;
  392. // timeStamp = long.Parse(timeStamp.ToString().Substring(0, timeStamp.ToString().Length - 4));
  393. // return timeStamp;
  394. // }
  395. // /// <summary>
  396. // /// long --> DateTime
  397. // /// </summary>
  398. // /// <param name="d"></param>
  399. // /// <returns></returns>
  400. // public static DateTime ConvertLongToDateTime(long d)
  401. // {
  402. // DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  403. // long lTime = long.Parse(d + "0000");
  404. // TimeSpan toNow = new TimeSpan(lTime);
  405. // DateTime dtResult = dtStart.Add(toNow);
  406. // return dtResult;
  407. // }
  408. // /// <summary>
  409. // /// 获取IP 地址
  410. // /// </summary>
  411. // /// <returns></returns>
  412. // public static string GetLocalIp()
  413. // {
  414. // //得到本机名
  415. // string hostname = Dns.GetHostName();
  416. // //解析主机名称或IP地址的system.net.iphostentry实例。
  417. // IPHostEntry localhost = Dns.GetHostEntry(hostname);
  418. // if (localhost != null)
  419. // {
  420. // foreach (IPAddress item in localhost.AddressList)
  421. // {
  422. // //判断是否是内网IPv4地址
  423. // if (item.AddressFamily == AddressFamily.InterNetwork)
  424. // {
  425. // return item.MapToIPv4().ToString();
  426. // }
  427. // }
  428. // }
  429. // return "192.168.1.124";
  430. // }
  431. // /// <summary>
  432. // /// Http下载文件
  433. // /// </summary>
  434. // public static string HttpDownloadFile(string url, string path)
  435. // {
  436. // // 设置参数
  437. // HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  438. // //发送请求并获取相应回应数据
  439. // HttpWebResponse response = request.GetResponse() as HttpWebResponse;
  440. // //直到request.GetResponse()程序才开始向目标网页发送Post请求
  441. // Stream responseStream = response.GetResponseStream();
  442. // //创建本地文件写入流
  443. // Stream stream = new FileStream(path, FileMode.Create);
  444. // byte[] bArr = new byte[1024];
  445. // int size = responseStream.Read(bArr, 0, (int)bArr.Length);
  446. // while (size > 0)
  447. // {
  448. // stream.Write(bArr, 0, size);
  449. // size = responseStream.Read(bArr, 0, (int)bArr.Length);
  450. // }
  451. // stream.Close();
  452. // responseStream.Close();
  453. // return path;
  454. // }
  455. // }
  456. //}