From 8edf8fd9f5f7c29cc6302a8d46de06d391ed3657 Mon Sep 17 00:00:00 2001
From: JLChen <551775569@qq.com>
Date: 星期四, 16 一月 2020 13:03:57 +0800
Subject: [PATCH] 2020-01-16 Version 2.50115-B3 1.优化MQTT连接。 2.增加本地通信加密。 3.增加配置网关提示语。 4.编辑定时器增加重复名字提示 5.更新规范翻译。

---
 Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs |  198 +++++++++++++++++++++++--------------------------
 1 files changed, 92 insertions(+), 106 deletions(-)

diff --git a/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs b/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
index 7d6ebf0..997458f 100644
--- a/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
+++ b/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
@@ -41,6 +41,75 @@
         //static bool thisShowTip = true;
         static string mqttRequestParToken = "";
 
+        static MqttCommon ()
+        {
+            InitMqtt ();
+        }
+
+        /// <summary>
+        /// 淇濇椿閲嶈繛鍜岄噸璁㈤槄 绾跨▼
+        /// </summary>
+        /// <returns></returns>
+        public static async System.Threading.Tasks.Task InitMqtt ()
+        {
+            new System.Threading.Thread (async () => {
+                while (true) {
+                    System.Threading.Thread.Sleep (100);
+                    if (!CommonPage.IsRemote) continue;
+
+                    await StartCloudMqtt ();
+                    await CheckingSubscribeTopics ();
+
+                }
+            }) { IsBackground = true }.Start ();
+        }
+
+        /// <summary>
+        /// 鏄惁璁㈤槄鎴愬姛
+        /// </summary>
+        static bool isSubscribeTopicSuccess = false;
+        /// <summary>
+        /// 妫�鏌ヤ富棰樻槸鍚﹁闃呭け璐�
+        /// </summary>
+        /// <returns></returns>
+        static async Task CheckingSubscribeTopics ()
+        {
+            if (!remoteIsConnected) {
+                return;
+            }
+            try {
+                if (!isSubscribeTopicSuccess) {
+
+                    var topicFilterCommon = new TopicFilter () {
+                        Topic = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/Common/#",
+                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
+                    };
+
+                    //缃戝叧閲嶆柊鐧诲綍涓婚
+                    var topicFilterGateWayInfoChange = new TopicFilter () {
+                        Topic = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyBusGateWayInfoChange",
+                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
+                    };
+
+                    //鎸や笅绾夸富棰�
+                    var topicFilterNotifySqueeze = new TopicFilter () {
+                        Topic = $"/BusGateWayToClient/{mMqttInfo.connEmqClientId}/Push/NotifySqueeze",
+                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
+                    };
+
+                    var topicFilters = new TopicFilter [] { topicFilterCommon, topicFilterGateWayInfoChange, topicFilterNotifySqueeze };
+                    var result = await RemoteMqttClient.SubscribeAsync (topicFilters);
+                    if (result.Items [0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS2) {
+                        isSubscribeTopicSuccess = true;
+                    }
+                }
+            } catch (Exception e) {
+               
+            }
+        }
+
+
+
         /// <summary>
         /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
         /// </summary>
@@ -79,29 +148,19 @@
         public static async System.Threading.Tasks.Task StartCloudMqtt ()
         {
 
-            //Application.RunOnMainThread (() => {
-            //    if (5 < (DateTime.Now - dateTime).TotalSeconds) {
-            //        return;
-            //    }
-            //    //MainPage.Loading.Start (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.Connecting));
-            //    dateTime = DateTime.Now;
-            //});
             if (!MainPage.LoginUser.IsLogin) {
                 return;
             }
             //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺
-            if (remoteMqttIsConnecting
-               || remoteIsConnected) {
-                System.Console.WriteLine ($"============>MqttremoteMqttIsConnecting:{remoteMqttIsConnecting}  remoteIsConnected:{remoteIsConnected} ");
-
+            if (remoteMqttIsConnecting || remoteIsConnected) {
                 return;
             }
 
+            remoteMqttIsConnecting = true;
             await System.Threading.Tasks.Task.Factory.StartNew (async () => {
                 try {
-                    lock (RemoteMqttClient) {
+                    //lock (RemoteMqttClient) {
                         //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺�
-                        remoteMqttIsConnecting = true;
 
                         #region 鍒濆鍖栬繙绋婱qtt
                         //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
@@ -175,6 +234,7 @@
                         if (RemoteMqttClient.DisconnectedHandler == null) {
                             RemoteMqttClient.UseDisconnectedHandler (async (e) => {
                                 System.Console.WriteLine ($"============>Mqtt杩滅▼杩炴帴鏂紑");
+                                isSubscribeTopicSuccess = false;
                                 await DisConnectRemoteMqttClient ("StartRemoteMqtt.DisconnectedHandler");
                                 //await StartRemoteMqtt();
                                 //if (thisShowTip) {
@@ -200,9 +260,6 @@
                                 if (CurRemoteMACInfo != null) {
                                     if (CurRemoteMACInfo.isValid == "InValid") {
                                         MainPage.AddTip ("Remote failed,gateway offline");
-                                        //Application.RunOnMainThread (() => {
-                                        //    MainPage.Loading.Hide ();
-                                        //});
                                     } else {
                                         MqttRemoteSend (new byte [] { 0 }, 3);
                                     }
@@ -211,8 +268,7 @@
                             });
                         }
                         #endregion
-                    }
-                    try {
+                    //}
 
                         mqttRequestParToken = MainPage.LoginUser.LoginTokenString;
                         //--绗竴姝ワ細鑾峰彇mqtt閾炬帴鍙傛暟
@@ -271,11 +327,6 @@
                             }
                         }
 
-
-
-                    } catch (Exception ex) {
-                        Console.WriteLine (ex.Message);
-                    }
                 } catch (Exception ex) {
                     System.Console.WriteLine ($"============>Mqtt 杩滅▼杩炴帴閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
                 } finally {
@@ -310,22 +361,14 @@
                 await DisConnectRemoteMqttClient ("StartRemoteMqtt");
                 await RemoteMqttClient.ConnectAsync (options1);
                 remoteIsConnected = true;
-                await MqttRemoteSend (new byte [] { 0 }, 1);
-                await MqttRemoteSend (new byte [] { 0 }, 2);
-                await MqttRemoteSend (new byte [] { 0 }, 4);
+                //await MqttRemoteSend (new byte [] { 0 }, 1);
+                //await MqttRemoteSend (new byte [] { 0 }, 2);
+                //await MqttRemoteSend (new byte [] { 0 }, 4);
 
             }
         }
 
-        //public static async System.Threading.Tasks.Task InitMqtt () {
-
-        //    while (true) {
-        //        await StartCloudMqtt ();
-        //        System.Threading.Thread.Sleep (100);
-        //    }
-        //}
-
-
+     
         /// <summary>
         /// 
         /// </summary>
@@ -335,6 +378,11 @@
         public static async Task MqttRemoteSend (byte [] message, int optionType = 0)
         {
             try {
+                if (!remoteIsConnected) {
+                    System.Console.WriteLine ($"============>Mqtt 鏈繛鎺� 鍙栨秷鍙戦��");
+                    return;
+                }
+
                 var topicName = @"/" + MainPage.LoginUser.AccountString.ToLower () + @"/" + UserConfig.Instance.GatewayMAC.Replace (".", "") + @"/" + currentGuid;
                 switch (optionType) {
                 case 0:
@@ -351,59 +399,14 @@
                     try {
                          RemoteMqttClient.PublishAsync (m);
                     } catch (Exception e) {
-                        await DisConnectRemoteMqttClient (e.Message);
-                        await StartCloudMqtt ();
-                        if (remoteIsConnected) {
-                            RemoteMqttClient.PublishAsync (m);
-                        }
+                        //await DisConnectRemoteMqttClient (e.Message);
+                        //await StartCloudMqtt ();
+                        //if (remoteIsConnected) {
+                        //    RemoteMqttClient.PublishAsync (m);
+                        //}
                     }
                     //}
                     break;
-                case 1:
-                    topicName = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/Common/#";
-                    //if (remoteIsConnected) {
-                    try {
-                        await RemoteMqttClient.SubscribeAsync (topicName);
-                    } catch (Exception e) {
-                        await DisConnectRemoteMqttClient (e.Message);
-                        await StartCloudMqtt ();
-                        if (remoteIsConnected) {
-                            await RemoteMqttClient.SubscribeAsync (topicName);
-                        }
-                    }
-                    // }
-                    break;
-                case 2:
-                    var macStr = CurRemoteMACInfo.mac.ToUpper ();
-                    char [] cArrs = macStr.ToCharArray ();
-                    Array.Reverse (cArrs);
-                    var sss = string.Join (string.Empty, cArrs);
-
-                    using (var provider = new MD5CryptoServiceProvider ()) {
-                        byte [] buffer = provider.ComputeHash (Encoding.Default.GetBytes (sss));
-                        StringBuilder builder = new StringBuilder ();
-                        for (int i = 0; i < buffer.Length; i++) {
-                            builder.Append (buffer [i].ToString ("x2"));
-                        }
-                        CurRemoteMACInfo.md5_mac_string = builder.ToString ().ToUpper ();
-                    }
-
-                    //topicName = $"/NotifyBusGateWayInfoChagne/{CurRemoteMACInfo.md5_mac_string}";
-                    //2020-01-11 淇敼璁㈤槄涓婚鍦板潃
-                    topicName = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyBusGateWayInfoChange";
-                    //if (remoteIsConnected) {
-                    try {
-                        await RemoteMqttClient.SubscribeAsync (topicName);
-                    } catch (Exception e) {
-                        await DisConnectRemoteMqttClient (e.Message);
-                        await StartCloudMqtt ();
-                        if (remoteIsConnected) {
-                            await RemoteMqttClient.SubscribeAsync (topicName);
-                        }
-                    }
-                    //}
-                    break;
-
                 case 3:
                     topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/CheckGateway";
 
@@ -411,29 +414,12 @@
 
                     try {
                         Console.WriteLine ("CheckGateway");
-                        await RemoteMqttClient.PublishAsync (m1);
+                         RemoteMqttClient.PublishAsync (m1);
                     } catch (Exception e) {
                         Console.WriteLine ($"CheckGateway Fail:{e.Message}");
-                        await DisConnectRemoteMqttClient (e.Message);
-                        await StartCloudMqtt ();
+                        //await DisConnectRemoteMqttClient (e.Message);
+                        //await StartCloudMqtt ();
                     }
-                    break;
-
-                case 4:
-                    //2020-01-13 淇敼鎸や笅绾夸富棰�
-                    topicName = $"/BusGateWayToClient/{mMqttInfo.connEmqClientId}/Push/NotifySqueeze";
-                    //if (remoteIsConnected) {
-                    try {
-                        await RemoteMqttClient.SubscribeAsync (topicName);
-                    } catch (Exception e) {
-                        await DisConnectRemoteMqttClient (e.Message);
-                        await StartCloudMqtt ();
-                        if (remoteIsConnected) {
-                            await RemoteMqttClient.SubscribeAsync (topicName);
-                        }
-                    }
-
-                    //}
                     break;
                 }
 
@@ -549,7 +535,7 @@
             MainPage.LoginUser.LastTime = DateTime.Now.AddDays (-30);
             MainPage.LoginUser.SaveUserInfo ();
 
-            DisConnectRemoteMqttClient ("LoginOut");
+            DisConnectRemoteMqttClient ("鎸や笅绾�");
 
             MainPage.ShowAlertOnMainThread (ErrorCode.LoginInAnotherDevice);
 

--
Gitblit v1.8.0