From 6c8946b21635246355ec41f216426783685a14b2 Mon Sep 17 00:00:00 2001 From: wxr <464027401@qq.com> Date: 星期三, 14 十月 2020 09:14:09 +0800 Subject: [PATCH] 20201013 --- HDL_ON/DAL/Net/Mqtt_A_Protocol.cs | 412 +++++++++++++++++++++++++++++----------------------------- 1 files changed, 206 insertions(+), 206 deletions(-) diff --git a/HDL_ON/DAL/Net/Mqtt_A_Protocol.cs b/HDL_ON/DAL/Net/Mqtt_A_Protocol.cs index 369efb8..6410de4 100644 --- a/HDL_ON/DAL/Net/Mqtt_A_Protocol.cs +++ b/HDL_ON/DAL/Net/Mqtt_A_Protocol.cs @@ -1,219 +1,219 @@ -锘�//using System; -//using MQTTnet.Client; -//using MQTTnet; -//using MQTTnet.Client.Options; -//using System.Net.Sockets; -//using System.Threading.Tasks; +锘縰sing System; +using MQTTnet.Client; +using MQTTnet; +using MQTTnet.Client.Options; +using System.Net.Sockets; +using System.Threading.Tasks; -//namespace HDL_ON.DAL.Net -//{ -// public static class Mqtt_A_Protocol -// { -// /// <summary> -// /// MqttClient -// /// </summary> -// public static IMqttClient mqttClient_A; -// public static string mqttClientIP; -// public static string mqttGatewayMAC; -// static bool remoteIsConnected; +namespace HDL_ON.DAL.Net +{ + public static class Mqtt_A_Protocol + { + /// <summary> + /// MqttClient + /// </summary> + public static IMqttClient mqttClient_A; + public static string mqttClientIP; + public static string mqttGatewayMAC; + static bool remoteIsConnected; -// static bool onConnection = false; + static bool onConnection = false; -// static Mqtt_A_Protocol() -// { -// InitMqtt(); -// } + static Mqtt_A_Protocol() + { + InitMqtt(); + } -// /// <summary> -// /// 鏂紑杩滅▼Mqtt鐨勯摼鎺� -// /// </summary> -// public static async Task DisConnectRemoteMqttClient(string s = "") -// { -// try -// { -// if (remoteIsConnected) -// { -// remoteIsConnected = false; -// System.Console.WriteLine($"Remote涓诲姩鏂紑_{s}"); -// //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); -// await mqttClient_A.DisconnectAsync(); -// } -// } -// catch (Exception e) -// { -// Console.WriteLine($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}"); -// } -// } + /// <summary> + /// 鏂紑杩滅▼Mqtt鐨勯摼鎺� + /// </summary> + public static async Task DisConnectRemoteMqttClient(string s = "") + { + try + { + if (remoteIsConnected) + { + remoteIsConnected = false; + System.Console.WriteLine($"Remote涓诲姩鏂紑_{s}"); + //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None); + await mqttClient_A.DisconnectAsync(); + } + } + catch (Exception e) + { + Console.WriteLine($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}"); + } + } -// static bool isSubscribeSuccess; -// static async Task SubscribeTopics() -// { -// if (remoteIsConnected && !isSubscribeSuccess) -// { -// try -// { -// var Topic1 = $"/BusGateWayToApp/{mqttGatewayMAC}/Common/Json"; -// try -// { -// await mqttClient_A.SubscribeAsync(Topic1); -// } -// catch (Exception ex) -// { -// await DisConnectRemoteMqttClient(ex.Message); -// await StartMqtt(); -// if (remoteIsConnected) -// { -// await mqttClient_A.SubscribeAsync(Topic1); -// } -// } -// } -// catch { } -// } -// } + static bool isSubscribeSuccess; + static async Task SubscribeTopics() + { + if (remoteIsConnected && !isSubscribeSuccess) + { + try + { + var Topic1 = $"/BusGateWayToApp/{mqttGatewayMAC}/Common/Json"; + try + { + await mqttClient_A.SubscribeAsync(Topic1); + } + catch (Exception ex) + { + await DisConnectRemoteMqttClient(ex.Message); + await StartMqtt(); + if (remoteIsConnected) + { + await mqttClient_A.SubscribeAsync(Topic1); + } + } + } + catch { } + } + } -// static void InitMqtt() -// { -// new System.Threading.Thread(async () => -// { -// while (true) -// { -// try -// { -// System.Threading.Thread.Sleep(1000); -// //if (!CommonPage.IsRemote) -// // continue; -// if (remoteIsConnected) -// continue; -// await StartMqtt(); -// await SubscribeTopics(); -// } -// catch { } -// } -// }) -// { IsBackground = true }.Start(); -// } + static void InitMqtt() + { + new System.Threading.Thread(async () => + { + while (true) + { + try + { + System.Threading.Thread.Sleep(1000); + //if (!CommonPage.IsRemote) + // continue; + if (remoteIsConnected) + continue; + await StartMqtt(); + await SubscribeTopics(); + } + catch { } + } + }) + { IsBackground = true }.Start(); + } -// /// <summary> -// /// 鍚姩A鍗忚Mqtt -// /// </summary> -// public static async Task StartMqtt() -// { -// try -// { -// if (remoteIsConnected) -// return; -// if (onConnection) -// return; -// onConnection = true; -// new System.Threading.Thread(async () => -// { -// if (remoteIsConnected) -// return; -// try -// { -// if (mqttClient_A == null) -// { -// mqttClient_A = new MqttFactory().CreateMqttClient(); -// mqttClient_A.UseApplicationMessageReceivedHandler(async e => -// { -// var aesDecryptTopic = e.ApplicationMessage.Topic; -// var aesDecryptPayload = e.ApplicationMessage.Payload; -// MainPage.Log(aesDecryptTopic); -// MainPage.Log($"Des Topic={aesDecryptTopic}"); -// }); + /// <summary> + /// 鍚姩A鍗忚Mqtt + /// </summary> + public static async Task StartMqtt() + { + try + { + if (remoteIsConnected) + return; + if (onConnection) + return; + onConnection = true; + new System.Threading.Thread(async () => + { + if (remoteIsConnected) + return; + try + { + if (mqttClient_A == null) + { + mqttClient_A = new MqttFactory().CreateMqttClient(); + mqttClient_A.UseApplicationMessageReceivedHandler(async e => + { + var aesDecryptTopic = e.ApplicationMessage.Topic; + var aesDecryptPayload = e.ApplicationMessage.Payload; + MainPage.Log(aesDecryptTopic); + MainPage.Log($"Des Topic={aesDecryptTopic}"); + }); -// mqttClient_A.UseConnectedHandler(async (e) => -// { -// MainPage.Log("mqtt connected !!"); -// onConnection = false; -// }); -// } -// try -// { -// int readCount = 0; -// BusSocket.Stop(); -// System.Threading.Thread.Sleep(1000); -// BusSocket.Start(6688); -// System.Threading.Thread.Sleep(1000); -// Control.ReadGatewayIPAddress(); -// while (true) -// { -// if (!string.IsNullOrEmpty(mqttClientIP)) -// { -// break; -// } -// else if (readCount > 10) -// { -// onConnection = false; -// return; -// } -// else -// { -// Control.ReadGatewayIPAddress(); -// System.Threading.Thread.Sleep(200); -// } -// } -// BusSocket.Stop(); -// System.Threading.Thread.Sleep(1000); -// BusSocket.Start(6000); -// System.Threading.Thread.Sleep(1000); + mqttClient_A.UseConnectedHandler(async (e) => + { + MainPage.Log("mqtt connected !!"); + onConnection = false; + }); + } + try + { + int readCount = 0; + BusSocket.Stop(); + System.Threading.Thread.Sleep(1000); + BusSocket.Start(6688); + System.Threading.Thread.Sleep(1000); + Control.ReadGatewayIPAddress(); + while (true) + { + if (!string.IsNullOrEmpty(mqttClientIP)) + { + break; + } + else if (readCount > 10) + { + onConnection = false; + return; + } + else + { + Control.ReadGatewayIPAddress(); + System.Threading.Thread.Sleep(200); + } + } + BusSocket.Stop(); + System.Threading.Thread.Sleep(1000); + BusSocket.Start(6000); + System.Threading.Thread.Sleep(1000); -// var options = new MqttClientOptionsBuilder()//MQTT杩炴帴鍙傛暟濉厖 -// .WithClientId(Guid.NewGuid().ToString().Substring(0, 5))//瀹㈡埛绔疘D -// .WithTcpServer(mqttClientIP, 1883)//MQTTServerIP.Text, Int32.Parse(MQTTServerPort.Text.ToString()))//TCP鏈嶅姟绔� 1883 锛屽嵆MQTT鏈嶅姟绔� -// .WithCredentials("", "")//"", "")//鍑瘉 甯愬彿 瀵嗙爜 -// .WithCommunicationTimeout(new TimeSpan(0, 0, 60)) //閲嶈繛瓒呮椂鏃堕棿锛岄粯璁�5s -// .WithKeepAlivePeriod(new TimeSpan(0, 0, 15)) //淇濇寔杩炴帴鏃堕棿锛岄粯璁�5s锛屽績璺冲寘 -// .Build(); -// await mqttClient_A.ConnectAsync(options); -// remoteIsConnected = true; -// } -// catch { } -// } -// catch (Exception ex) -// { -// } -// finally -// { -// onConnection = false; -// } -// }) -// { IsBackground = true }.Start(); -// } -// catch (Exception ex) -// { -// MainPage.Log("============>" + ex.Message); -// } -// } + var options = new MqttClientOptionsBuilder()//MQTT杩炴帴鍙傛暟濉厖 + .WithClientId(Guid.NewGuid().ToString().Substring(0, 5))//瀹㈡埛绔疘D + .WithTcpServer(mqttClientIP, 1883)//MQTTServerIP.Text, Int32.Parse(MQTTServerPort.Text.ToString()))//TCP鏈嶅姟绔� 1883 锛屽嵆MQTT鏈嶅姟绔� + .WithCredentials("", "")//"", "")//鍑瘉 甯愬彿 瀵嗙爜 + .WithCommunicationTimeout(new TimeSpan(0, 0, 60)) //閲嶈繛瓒呮椂鏃堕棿锛岄粯璁�5s + .WithKeepAlivePeriod(new TimeSpan(0, 0, 15)) //淇濇寔杩炴帴鏃堕棿锛岄粯璁�5s锛屽績璺冲寘 + .Build(); + await mqttClient_A.ConnectAsync(options); + remoteIsConnected = true; + } + catch { } + } + catch (Exception ex) + { + } + finally + { + onConnection = false; + } + }) + { IsBackground = true }.Start(); + } + catch (Exception ex) + { + MainPage.Log("============>" + ex.Message); + } + } -// /// <summary> -// /// -// /// </summary> -// /// <param name="message">闄勫姞鏁版嵁鍖�</param> -// /// <param name="optionType">鎿嶄綔绫诲瀷锛�0=缃戝叧鎺у埗锛�1=璁㈤槄缃戝叧鏁版嵁;2=璁㈤槄缃戝叧涓婄嚎鏁版嵁</param> -// /// <returns></returns> -// public static async Task MqttRemoteSend(byte[] message) -// { -// try -// { -// if (mqttClient_A == null || !mqttClient_A.IsConnected) -// { -// await StartMqtt(); -// } -// if (!mqttClient_A.IsConnected) -// { -// return; -// } -// var topicName = $"/AppToBusGateWay/{mqttGatewayMAC}/Common/Json"; -// var m = new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce }; -// await mqttClient_A?.PublishAsync(m); -// } -// catch (Exception e) -// { -// } -// } -// } -//} + /// <summary> + /// + /// </summary> + /// <param name="message">闄勫姞鏁版嵁鍖�</param> + /// <param name="optionType">鎿嶄綔绫诲瀷锛�0=缃戝叧鎺у埗锛�1=璁㈤槄缃戝叧鏁版嵁;2=璁㈤槄缃戝叧涓婄嚎鏁版嵁</param> + /// <returns></returns> + public static async Task MqttRemoteSend(byte[] message) + { + try + { + if (mqttClient_A == null || !mqttClient_A.IsConnected) + { + await StartMqtt(); + } + if (!mqttClient_A.IsConnected) + { + return; + } + var topicName = $"/AppToBusGateWay/{mqttGatewayMAC}/Common/Json"; + var m = new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce }; + await mqttClient_A?.PublishAsync(m); + } + catch (Exception e) + { + } + } + } +} -- Gitblit v1.8.0