From 5a5a2b696866f947b6025d26c3302e8ffef46435 Mon Sep 17 00:00:00 2001
From: JLChen <551775569@qq.com>
Date: 星期一, 11 一月 2021 16:11:20 +0800
Subject: [PATCH] 2021-01-11 1.更新MQTT连接和本地搜索网关方法。2.子账号相关接口完善

---
 Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs | 1830 +++++++++++++++++++++-------------------------------------
 1 files changed, 676 insertions(+), 1,154 deletions(-)

diff --git a/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs b/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
index d6bf05b..761d256 100644
--- a/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
+++ b/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
@@ -11,7 +11,6 @@
 using System.Text;
 using System.Security.Cryptography;
 using System.IO;
-using Shared.SimpleControl.Phone;
 
 namespace SmartHome
 {
@@ -22,488 +21,482 @@
         /// </summary>
         public static bool IfDEBUG = false;
 
+        /// <summary>
+        /// 鍔犲瘑閫氳KEY
+        /// </summary>
         static string mqttEncryptKey = "";
-        static string checkGatewayTopicBase64 = "";
-        static RemoteMACInfo CurRemoteMACInfo = null;
-        static MqttInfo mMqttInfo = null;
-        public static bool IsGatewayOnline = true;
+        //static string checkGatewayTopicBase64 = "";
 
         /// <summary>
-        /// 鎵嬫満鏍囪瘑
+        /// 鎸や笅绾夸富棰�
         /// </summary>
-        static Guid currentGuid = Guid.NewGuid ();
+        static readonly string PushNotifySqueeze = "/Push/NotifySqueeze";
+
+        ///// <summary>
+        ///// 鎸や笅绾夸富棰�
+        ///// </summary>
+        //static readonly string TopicToApp = "/Push/NotifySqueeze";
+
 
         /// <summary>
-        /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
+        /// 闅忔満Key
         /// </summary>
-        /// <summary>
-        /// 杩滅▼MqttClient
-        /// </summary>
+        static string RandomKey = "";
+
+        static string GetRandomKey ()
+        {
+            if (string.IsNullOrEmpty (RandomKey)) {
+                //闅忔満2浣嶅瓧绗︿覆
+                RandomKey = Utlis.CreateRandomString (2);
+            }
+
+            return RandomKey;
+
+        }
+
         /// <summary>
         /// 杩滅▼MqttClient
         /// </summary>
         public static IMqttClient RemoteMqttClient = new MqttFactory ().CreateMqttClient ();
 
-        //static bool thisShowTip = true;
-        static string mqttRequestParToken = "";
-
-        static MqttCommon ()
-        {
-            InitMqtt ();
-            //InitCheckGateway ();
-        }
-
-        /// <summary>
-        /// 淇濇椿閲嶈繛鍜岄噸璁㈤槄 绾跨▼
-        /// </summary>
-        /// <returns></returns>
-        public static async System.Threading.Tasks.Task InitMqtt ()
-        {
-            new System.Threading.Thread (async () => {
-                while (true) {
-                    try {
-                        System.Threading.Thread.Sleep (200);
-                        if (!CommonPage.IsRemote) continue;
-
-                        if (Control.IsEnterBackground) continue;
-
-                        await StartCloudMqtt ();
-                        await CheckingSubscribeTopics ();
-                    } catch { }
-
-                }
-            }) { IsBackground = true }.Start ();
-        }
-
-        public static void InitState ()
-        {
-            IfNeedReadAllDeviceStatus = true;
-            bNeedStartTip = true;
-            IsGatewayOnline = false;
-            StartCloudMqtt ();
-        }
-
-
-        /// <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 topicFilterNotifyGateWayOffline = new TopicFilter () {
-                        Topic = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyGateWayOffline",
-                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
-                    };
-
-
-                    var topicFilters = new TopicFilter [] { topicFilterCommon, topicFilterGateWayInfoChange, topicFilterNotifySqueeze, topicFilterNotifyGateWayOffline };
-                    var result = await RemoteMqttClient.SubscribeAsync (topicFilters);
-                    if (result.Items [0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS2) {
-                        isSubscribeTopicSuccess = true;
-                    }
-
-                    ////2020-06-22 閫氱敤涓婚
-                    //var topicFilterMacMark = new TopicFilter () {
-                    //    Topic = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/#",
-                    //    QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
-                    //};
-
-                    ////鎸や笅绾夸富棰�
-                    //var topicFilterNotifySqueeze = new TopicFilter () {
-                    //    Topic = $"/BusGateWayToClient/{mMqttInfo.connEmqClientId}/Push/NotifySqueeze",
-                    //    QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
-                    //};
-
-                    //var topicFilters = new TopicFilter [] { topicFilterMacMark, topicFilterNotifySqueeze };
-                    //var result = await RemoteMqttClient.SubscribeAsync (topicFilters);
-                    //if (result.Items [0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS2) {
-                    //    isSubscribeTopicSuccess = true;
-                    //}
-                }
-            } catch (Exception ex) {
-
-              
-            }
-        }
-
-
-        /// <summary>
-        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
-        /// </summary>
-        public static async System.Threading.Tasks.Task DisConnectRemoteMqttClient (string s = "")
-        {
-            try {
-                if (remoteIsConnected) {
-                    remoteIsConnected = false;
-                    Utlis.WriteLine ($"============>MqttRemote涓诲姩鏂紑_{s}");
-                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
-                    await RemoteMqttClient.DisconnectAsync ();
-                    if (CommonPage.IsRemote) {
-                        Utlis.ShowAppLinkStatus (AppLinkStatus.CloudUnlink);
-                    }
-                    //Utlis.WriteLine ($"============>MqttRemoteDisConnectRemoteMqttClient");
-
-                }
-            } catch (Exception e) {
-                Utlis.WriteLine ($"============>MqttRemote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
-            }
-        }
-        static DateTime dateTime = DateTime.MinValue;
 
         /// <summary>
         /// 鎺ㄩ�佹爣璇�
         /// </summary>
         static string PushSignStr = System.DateTime.Now.Ticks.ToString ();
 
+        /// <summary>
+        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
+        /// </summary>
+        static async System.Threading.Tasks.Task DisConnectRemoteMqttClient (string s = "")
+        {
+            try {
+                if (remoteIsConnected) {
+                    remoteIsConnected = false;
+                    isSubscribeSuccess = false;
+                    Shared.Utlis.WriteLine ($"Remote涓诲姩鏂紑_{s}");
+                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
+                    await RemoteMqttClient.DisconnectAsync ();
 
+                    if (CommonPage.IsRemote) {
+                        //涓嶆槸鏃犵綉缁�
+                        if (UserConfig.Instance.internetStatus != 0) {
+                            Utlis.ShowAppLinkStatus (AppLinkStatus.CloudUnlink);
+                        }
+                    }
+                }
+            } catch (Exception e) {
+                Shared.Utlis.WriteLine ($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
+            }
+        }
+
+        /// <summary>
+        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
+        /// </summary>
+        static async Task DisConnectRemoteMqttClientWhenStart (string s = "")
+        {
+            try {
+                //if (remoteIsConnected) {
+                remoteIsConnected = false;
+                isSubscribeSuccess = false;
+                Shared.Utlis.WriteLine ($"RemoteStart涓诲姩鏂紑_{s}");
+                await RemoteMqttClient.DisconnectAsync ();
+
+                //}
+            } catch (Exception e) {
+                Shared.Utlis.WriteLine ($"RemoteStart鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
+            }
+
+        }
+
+
+        /// <summary>
+        /// 鏂紑mqtt杩炴帴
+        /// </summary>
+        /// <param name="s">鏂紑鍘熷洜</param>
+        /// <param name="reset">鏄惁闇�瑕佸幓涓績鏈嶅姟鍣� 閲嶆柊鑾峰彇鍙傛暟</param>
+        /// <returns></returns>
+        public static async Task DisConnectRemote (string s = "", bool reset = true)
+        {
+            if (reset) {
+                bNeedStartTip = true;
+                bNeedConnectTip = true;
+                CommonConfig.Current.IfGetMqttInfoSuccess = false;
+            }
+            await DisConnectRemoteMqttClient (s);
+        }
+
+        //static DateTime dateTime = DateTime.MinValue;
         /// <summary>
         /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
         /// </summary>
         public static bool remoteMqttIsConnecting;
         static bool remoteIsConnected;
+
+        static MqttCommon ()
+        {
+            InitMqtt ();
+        }
+
+        public static bool IsInitMqtt = false;
+
+        ///// <summary>
+        ///// 娴嬭瘯
+        ///// 瀹氭椂鍙戦�� 000E
+        ///// </summary>
+        ///// <returns></returns>
+        //static void InitCheckGateway ()
+        //{
+        //    new System.Threading.Thread (async () => {
+        //        while (true) {
+        //            try {
+
+        //                if (!CommonPage.IsRemote) {
+        //                    if (GatewayCommon != null) {
+        //                        Control.ControlBytesSend (Command.ReadRemark, GatewayCommon.SubnetID, GatewayCommon.DeviceID, new byte [] { });
+        //                        Console.WriteLine ("鍙戦��000E ");
+        //                    }
+        //                }
+        //                System.Threading.Thread.Sleep (55000);
+        //            } catch { }
+
+        //        }
+        //    }) { IsBackground = true }.Start ();
+        //}
+
+
+        //static Thread MQTTThread;
+
+        //static void InitMqtt ()
+        //{
+
+        //    remoteMqttIsConnecting = false;
+        //    if (MQTTThread != null)
+        //        MQTTThread.Abort ();
+
+        //    MQTTThread = new System.Threading.Thread (async () => {
+        //        while (true) {
+        //            try {
+        //                System.Threading.Thread.Sleep (200);
+        //                //if (!MainPage.LoginUser.IsLogin) {
+        //                //    continue;
+        //                //}
+        //                if (!CommonPage.IsRemote) continue;
+
+        //                await StartCloudMqtt ();
+        //                await SubscribeTopics ();
+        //            } catch { }
+        //        }
+        //    }) { IsBackground = true };
+
+        //    MQTTThread.Start ();
+        //}
+
+        static void InitMqtt ()
+        {
+            new System.Threading.Thread (async () => {
+                while (true) {
+                    try {
+                        System.Threading.Thread.Sleep (500);
+                        //if (!MainPage.LoginUser.IsLogin) {
+                        //    continue;
+                        //}
+
+                        if (!CommonPage.IsRemote) continue;
+
+                        if (Control.IsEnterBackground) continue;
+
+                        await StartCloudMqtt ();
+                        await SubscribeTopics ();
+                    } catch { }
+                }
+            }) { IsBackground = true }.Start ();
+        }
+
+        /// <summary>
+        /// 鍒濆鍖栫姸鎬�
+        /// </summary>
+        public static void InitState ()
+        {
+            IfNeedReadAllDeviceStatus = true;
+            bNeedStartTip = true;
+            bNeedConnectTip = true;
+            IsGatewayOnline = false;
+            StartCloudMqtt ();
+
+        }
+
+        static bool isSubscribeSuccess;
+        static async Task SubscribeTopics ()
+        {
+            if (remoteIsConnected && !isSubscribeSuccess) {
+                try {
+
+                    //var topicFilterPush = new TopicFilter { QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce,
+                    //    Topic = $"/BusGateWayToClient/{CommonConfig.Instance.CurRemoteMACInfo.clientId}/Push/NotifySqueeze" };
+
+                    //2020-05-14 璁㈤槄涓婚璐ㄩ噺鏀逛负0
+                    var topicFilterBusGateWayToClient = new MqttTopicFilter () {
+                        Topic = $"/BusGateWayToClient/{CommonConfig.Current.HomeGatewayInfo.gatewayId}/#",
+                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
+                        //QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
+                    };
+
+                    var topicFilterPush2 = new MqttTopicFilter {
+                        Topic = $"/BusGateWayToClient/{MainPage.LoginUser.ID}/#",
+                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce,
+                        //QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
+                    };
+
+                    Utlis.WriteLine ("寮�濮嬭闃咃紒");
+                    var result = await RemoteMqttClient.SubscribeAsync (new MqttTopicFilter [] { topicFilterBusGateWayToClient, topicFilterPush2 });
+                    if (result.Items [0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS0) {
+                        isSubscribeSuccess = true;
+                        Utlis.WriteLine ("璁㈤槄鎴愬姛锛�");
+
+                        MqttRemoteSend (new byte [] { 0 }, 3);
+
+                        //璇诲彇鎼滅储缃戝叧锛屽垽鏂綉鍏虫槸鍚﹀湪绾�
+                        CheckGatewaysIfOnline ();
+
+                        ////杩炴帴鎴愬姛鍚庢娴嬫槸鍚﹂渶瑕侀�氳繃杩滅▼鑾峰彇Key
+                        //CheckIfNeedGetLocalPasswordFromRemote ();
+                    }
+
+
+                } catch (Exception ex) {
+                    Console.WriteLine ("璁㈤槄catch:" + ex.Message.ToString ());
+                }
+            }
+        }
+
+        static DateTime mFlagDateTime;
+
+        //static readonly object SendLocker = new object ();
         /// <summary>
         /// 鍚姩杩滅▼Mqtt
         /// </summary>
-        public static async System.Threading.Tasks.Task StartCloudMqtt ()
+        public static async Task StartCloudMqtt ()
         {
+
+            if (UserConfig.Instance.internetStatus == 0) {
+                return;
+            }
 
             if (!MainPage.LoginUser.IsLogin) {
                 return;
             }
+
             //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺
             if (remoteMqttIsConnecting || remoteIsConnected) {
                 return;
             }
 
+            //lock (SendLocker) {
+            //    remoteMqttIsConnecting = true;
+            //}
             remoteMqttIsConnecting = true;
-            await System.Threading.Tasks.Task.Factory.StartNew (async () => {
+#if DEBUG
+            Shared.Utlis.WriteLine ($"StartCloudMqtt: 寮�濮�");
+#endif
+
+            await Task.Factory.StartNew (async () => {
                 try {
                     //lock (RemoteMqttClient) {
-                    //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺�
+                    //    //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺�
+                    //    remoteMqttIsConnecting = true;
 
                     #region 鍒濆鍖栬繙绋婱qtt
-                    //2020-06-22 澧炲姞
+
                     RemoteMqttClient = new MqttFactory ().CreateMqttClient ();
 
-                    //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
-                    if (RemoteMqttClient.ApplicationMessageReceivedHandler == null) {
-                        RemoteMqttClient.UseApplicationMessageReceivedHandler (async (e) => {
-                            try {
-                                if (!RemoteMqttClient.IsConnected || !CommonPage.IsRemote) {
-                                    return;
-                                }
-                                var aesDecryptTopic = e.ApplicationMessage.Topic;
-                                var aesDecryptPayload = e.ApplicationMessage.Payload;
-                                //Utlis.WriteLine ("Topic={0}", aesDecryptTopic);
 
-                                //if (aesDecryptTopic == $"NotifyBusGateWayInfoChagne/{CurRemoteMACInfo.md5_mac_string}") {//缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey
-                                //2020-01-11 淇敼璁㈤槄涓婚鍦板潃
-                                if (aesDecryptTopic == $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyBusGateWayInfoChange") {//缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey                                                                                                                     //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
-                                    await ReceiveNotifyBusGateWayInfoChange ();
-                                } else if (aesDecryptTopic == $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/NotifyGateWayOffline") {//缃戝叧鎺夌嚎                                                                                                                    //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
+                    //(1)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
+                    if (RemoteMqttClient.ApplicationMessageReceivedHandler == null) {
+                        RemoteMqttClient.UseApplicationMessageReceivedHandler ((e) => {
+                            try {
+                                var topic = e.ApplicationMessage.Topic;
+                                if (topic == $"/BusGateWayToClient/{MainPage.LoginUser.ID}" + PushNotifySqueeze) {
+                                    var mMes = CommonPage.MyEncodingUTF8.GetString (e.ApplicationMessage.Payload);
+                                    //鏂版尋涓嬬嚎涓婚鏂规 鏀跺埌鎸や笅绾夸富棰�
+                                    ReceiveNotifySqueezeAsync (mMes);
+                                } else if (topic == $"/BusGateWayToClient/{CommonConfig.Current.HomeGatewayInfo.gatewayId}/NotifyBusGateWayInfoChange") {//缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey
+                                    //鏀跺埌缃戝叧涓婄嚎娑堟伅涓婚
+                                    ReceiveNotifyBusGateWayInfoChange ();
+                                } else if (topic == $"/BusGateWayToClient/{CommonConfig.Current.HomeGatewayInfo.gatewayId}/NotifyGateWayOffline") {//缃戝叧鎺夌嚎                                                                                                                    //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
                                     ReceiveNotifyGateWayOffline ();
-                                } else if (aesDecryptTopic == $"/BusGateWayToClient/{mMqttInfo.connEmqClientId}/Push/NotifySqueeze") {//璁㈤槄鎸や笅绾块棶棰�
-                                    await ReceiveNotifySqueezeAsync (aesDecryptPayload);
-                                } else if (aesDecryptTopic == $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/Common/CheckGateway") {
-                                    ReceiveCheckGatewayTopic ();
+                                } else if (topic == $"/BusGateWayToClient/{CommonConfig.Current.HomeGatewayInfo.gatewayId}/Common/CheckGateway") {
+                                    var ss = CommonPage.MyEncodingUTF8.GetString (e.ApplicationMessage.Payload);
+                                    ReceiveCheckGateway (ss);
                                 } else {
+
                                     SetGatewayOnlineResetCheck ();
 
-                                    if (!string.IsNullOrEmpty (mqttEncryptKey)) {
-                                        aesDecryptPayload = Shared.Securitys.EncryptionService.AesDecryptPayload (e.ApplicationMessage.Payload, mqttEncryptKey);
-                                    }
-
                                     var packet = new Packet ();
+
+                                    if (!string.IsNullOrEmpty (mqttEncryptKey)) {
+                                        packet.Bytes = Shared.Securitys.EncryptionService.AesDecryptPayload (e.ApplicationMessage.Payload, mqttEncryptKey);
+                                    } else {
+                                        packet.Bytes = e.ApplicationMessage.Payload;
+                                    }
                                     packet.IsLocal = false;
-                                    packet.Bytes = aesDecryptPayload;
                                     packet.Manager ();
-
                                 }
-
                             } catch { }
                         });
                     }
 
+                    //(2)DisconnectedHandler
                     if (RemoteMqttClient.DisconnectedHandler == null) {
                         RemoteMqttClient.UseDisconnectedHandler (async (e) => {
-                            Utlis.WriteLine ($"============>Mqtt杩滅▼杩炴帴鏂紑");
-                            isSubscribeTopicSuccess = false;
-                            await DisConnectRemoteMqttClient ("StartRemoteMqtt.DisconnectedHandler");
+                            Shared.Utlis.WriteLine ($"杩滅▼杩炴帴鏂紑");
+                            isSubscribeSuccess = false;
+                            await DisConnectRemoteMqttClient ("UseDisconnectedHandler");
+
                         });
                     }
+                    //(3)ConnectedHandler
                     if (RemoteMqttClient.ConnectedHandler == null) {
                         RemoteMqttClient.UseConnectedHandler (async (e) => {
-                            //IfNeedReadAllDeviceStatus = true;
-                            mCheckGatewayTime = DateTime.Now;
-                            CheckGatewayCount = 0;
-                            bNeedStartTip = true;
+                            IfNeedReadAllDeviceStatus = true;
+                            bNeedStartTip = true;//
+                            bNeedConnectTip = true;
+                            Shared.Utlis.WriteLine ($"============>Mqtt杩滅▼杩炴帴鎴愬姛");
+                            SendPushSignOut ();
 
-                            Utlis.WriteLine ($"============>Mqtt杩滅▼杩炴帴鎴愬姛");
-                            if (CommonPage.IsRemote) {
-                                Utlis.ShowAppLinkStatus (AppLinkStatus.CloudLink);
-                            }
-
-                            if (CurRemoteMACInfo != null) {
-                                IsGatewayOnline = CurRemoteMACInfo.isValid != "InValid";
-                                if (!IsGatewayOnline) {
-                                    //缃戝叧涓嶅湪绾�
-                                    if (CommonPage.IsRemote) {
-                                        Utlis.ShowAppLinkStatus (AppLinkStatus.CloudOffline);
-                                    }
-                                    MainPage.AddTip ("Remote failed,gateway offline");
-                                } else {
-                                    //Remote Connection Succeeded
-                                    //缃戝叧鍦ㄧ嚎
-                                    //閲嶆柊涓�娆℃墍鏈夎澶囩姸鎬�
-                                    IfNeedReadAllDeviceStatus = false;
-                                    Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus ();
-                                    //
-                                    MqttRemoteSend (new byte [] { 0 }, 3);
-
-                                    if (CommonPage.IsRemote) {
-                                        MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
-                                    }
-                                }
-                            }
+                            //if (CommonPage.IsRemote) {
+                            //    //Utlis.ShowAppLinkStatus (AppLinkStatus.CloudLink);
+                            //    MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
+                            //}
                         });
                     }
                     #endregion
                     //}
-                    //鎻愮ず姝e湪鑾峰彇杩炴帴鍙傛暟..."
-                    ShowStartTip ();
-                    mqttRequestParToken = MainPage.LoginUser.LoginTokenString;
-                    //--鍒ゆ柇鏄綋鍓嶆槸鍚﹀垎浜殑浣忓畢
-                    if (!UserConfig.Instance.CurrentRegion.IsOthreShare) {
-                        //涓昏处鍙疯幏鍙朚QTT 杩滅▼閾炬帴淇℃伅锛屽苟杩炴帴
-                        await GetMqttInfoAndMQTTConnectAsync ();
+
+                    //(4)===========寮�濮嬭繛鎺ヨ繃绋�==========
+                    //涔嬪墠宸茬粡鑾峰彇鍙傛暟鎴愬姛杩�
+                    if (CommonConfig.Current.IfGetMqttInfoSuccess) {
+                        //鍒ゆ柇鏄惁闇�瑕侀噸鏂拌幏鍙�
+                        await CheckMQTTConnectAsync ();
                     } else {
-                        //濡傛灉鏄垎浜繃鏉ョ殑浣忓畢 璧颁笅闈㈡祦绋�
-                        await GetShareMqttInfoAndMQTTConnectAsync ();
+                        //寮�濮嬭幏鍙栬繙绋嬭繛鎺ュ弬鏁�
+                        await StartMQTTGetInfo ();
                     }
 
                 } catch (Exception ex) {
-                    //Utlis.WriteLine ($"============>Mqtt 杩滅▼杩炴帴閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
-
-                    MainPage.LoadingTipShow ("Connect error, trying to reconnect.");
-
+                    Shared.Utlis.WriteLine ($"error:" + ex.Message);
                     if (IfDEBUG) {
                         MainPage.ShowAlertOnMainThread ("error: " + ex.Message);
                     }
-
                 } finally {
                     //鏈�缁堣閲婃斁杩炴帴鐘舵��
                     remoteMqttIsConnecting = false;
 
-                    MainPage.LoadingTipHide ();
+                    //lock (SendLocker) {
+                    //    remoteMqttIsConnecting = false;
+                    //}
 
-                    //MainPage.LoadingHide ();
+                    //杩炴帴鎴愬姛鎵嶅叧闂璍oading
+                    if (remoteIsConnected) {
+                        MainPage.LoadingTipHide ();
+                        ERRORCount = 0;
+                    } else {
+                        ERRORCount++;
+                        //姣�5娆¢噸鏂版彁绀轰竴娆�
+                        if (ERRORCount > 5) {
+                            ERRORCount = 0;
+                            MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.RemoteFailure));
+                            MainPage.LoadingTipHide ();
+
+                        }
+                    }
+
+#if DEBUG
+                    Shared.Utlis.WriteLine ($"StartCloudMqtt: 缁撴潫");
+#endif
                 }
+
             });
         }
 
+        //static bool 
+
+
         /// <summary>
-        /// 涓昏处鍙疯幏鍙朚QTT 杩滅▼閾炬帴淇℃伅锛屽苟杩炴帴
+        /// 妫�鏌ョ綉鍏虫槸鍚﹀湪绾跨嚎绋�
         /// </summary>
-        /// <returns></returns>
-        static async Task GetMqttInfoAndMQTTConnectAsync ()
+        static System.Threading.Thread CheckGatewaysThead;
+        /// <summary>
+        /// 缃戝叧瀵硅薄
+        /// </summary>
+        public static Common GatewayCommon;
+        /// <summary>
+        /// 妫�鏌ョ綉鍏虫槸鍚﹀湪绾�
+        /// </summary>
+        static void CheckGatewaysIfOnline ()
         {
-            var mqttInfoRequestPar = new GetConnMqttInfoObj () {
-                LoginAccessToken = MainPage.LoginUser.LoginTokenString,
-                PlatformStr = "L1",
-                PublishPayloadJsonStr = PushSignStr,
-                Mac = UserConfig.Instance.GatewayMAC,
-            };
-            //----绗竴姝ワ細鑾峰彇mqtt閾炬帴鍙傛暟
-            var mqttInfoRequestResult = MainPage.RequestHttps (API.GetConnMqttInfo, Newtonsoft.Json.JsonConvert.SerializeObject (mqttInfoRequestPar));
+            if (GatewayCommon == null) return;
 
-            if (mqttInfoRequestResult != null && mqttInfoRequestResult.ResponseData != null) {
-                try {
-                    var mqttInfoRequestResult_Obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttInfo> (mqttInfoRequestResult.ResponseData.ToString ());
+            try {
+                //鎻愮ず鎼滅储缃戝叧涓�
+                MainPage.LoadingTipShow (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.CheckingGatewayIsOnline));
 
-                    if (mqttInfoRequestResult_Obj != null) {
-                        mMqttInfo = mqttInfoRequestResult_Obj;
-                        string url = mqttInfoRequestResult_Obj.connEmqDomainPort;
-                        string clientId = mqttInfoRequestResult_Obj.connEmqClientId;
-                        string username = mqttInfoRequestResult_Obj.connEmqUserName;
-                        string passwordRemote = mqttInfoRequestResult_Obj.connEmqPwd;
-                        if (mqttInfoRequestResult_Obj.AccountAllGateways != null && mqttInfoRequestResult_Obj.AccountAllGateways.Count > 0) {
-                            //----绗簩姝ユ壘鍑烘槸鍚﹀瓨鍦ㄥ尮閰嶅綋鍓嶄綇瀹呯殑mac锛屽瓨鍦ㄥ啀杩涜杩滅▼銆�
-                            CurRemoteMACInfo = mqttInfoRequestResult_Obj.AccountAllGateways.Find ((obj) => obj.mac == UserConfig.Instance.GatewayMAC);
-                            if (CurRemoteMACInfo != null) {
-                                CurRemoteMACInfo.LoginAccessToken = MainPage.LoginUser.LoginTokenString;
-                                CurRemoteMACInfo.clientId = clientId;
-                                //----绗笁姝� 寮�濮嬭繛鎺�
-                                await MQTTConnectAsync ();
-                            } else {
-                                //Utlis.WriteLine ("============>Mqtt CurRemoteMACInfo null");
+                if (CheckGatewaysThead != null)
+                    CheckGatewaysThead.Abort ();
 
-                                MainPage.LoadingTipShow ("Please wait, failed to get gateway parameters.");
-                            }
+                CheckGatewaysThead = new System.Threading.Thread (() => {
+                    var returnBytes = Control.ControlBytesSendHasReturn (Command.ReadGateway, GatewayCommon.SubnetID, GatewayCommon.DeviceID, new byte [] { (byte)new Random ().Next (255), (byte)new Random ().Next (255) });
+                    //闅愯棌鎻愮ず
+                    MainPage.LoadingTipHide ();
+                    if (CommonPage.IsRemote) {
+                        if (returnBytes == null) {
+                            Application.RunOnMainThread (() => {
+                                IsGatewayOnline = false;
+                                Utlis.ShowAppLinkStatus (AppLinkStatus.CloudOffline);
+                                MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.RemoteFailedGatewayOffline));
+                                //鍙戦�佷竴娆heckGateway涓婚
+                                MqttRemoteSend (new byte [] { 0 }, 3);
+                            });
+                        } else {
+                            MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
+
+                            IsGatewayOnline = true;
+                            Utlis.ShowAppLinkStatus (AppLinkStatus.CloudLink);
+                            Console.WriteLine ("ReadGateway success");
+                            CheckIfNeedReadAllDeviceStatus ();
                         }
-
-                    } else {
-                        //Utlis.WriteLine ("============>Mqtt mqttInfoRequestResult_Obj null");
-
-                        MainPage.LoadingTipShow ("Please wait, failed to get user parameters.");
-                        //MainPage.LoadingTipShow ("Please wait, failed to get parameters.");
                     }
-                } catch {
+                }) { IsBackground = true };
 
-                }
-            } else {
-                //Utlis.WriteLine ("============>Mqtt GetInfo 澶辫触");
-                MainPage.AddTip ("Please wait, failed to get parameters.");
-                //MainPage.LoadingTipShow ("Please wait, failed to get parameters.");
+                CheckGatewaysThead.Start ();
+            } catch {
+
             }
-
         }
+
 
         /// <summary>
-        /// 瀛愯处鍙疯幏鍙朚QTT 杩滅▼閾炬帴淇℃伅锛屽苟杩炴帴
+        /// 妫�娴嬫槸鍚﹂渶瑕佸彂閫佸埛鏂拌幏鍙栨墍鏈夎澶囩殑鍛戒护
         /// </summary>
-        /// <returns></returns>
-        static async Task GetShareMqttInfoAndMQTTConnectAsync ()
+        static void CheckIfNeedReadAllDeviceStatus ()
         {
-            var mqttInfoRequestPar = new ShareMemberConnMqttInfoObj () {
-                LoginAccessToken = mqttRequestParToken,
-                PlatformStr = "L1",
-                PublishPayloadJsonStr = PushSignStr,
-                //MainUserDistributedMark = UserConfig.Instance.CurrentRegion.MainUserDistributedMark,
-                HomeId = UserConfig.Instance.CurrentRegion.Id
-            };
-            var mqttInfoRequestResult = MainPage.RequestHttps (API.ShareMemberConnMqttInfo, Newtonsoft.Json.JsonConvert.SerializeObject (mqttInfoRequestPar));
-            //--绗竴姝ワ細鑾峰彇mqtt閾炬帴鍙傛暟
-            if (mqttInfoRequestResult != null && mqttInfoRequestResult.ResponseData != null) {
-                var mqttInfoRequestResult_info = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttInfo> (mqttInfoRequestResult.ResponseData.ToString ());
-                if (mqttInfoRequestResult_info != null) {
-                    mMqttInfo = mqttInfoRequestResult_info;
-                    //--绗簩姝ワ細鑾峰彇褰撳墠浣忓垎浜畢缃戝叧淇℃伅骞惰繛鎺QTT
-                    await GetSingleHomeGatewayPaggerAndMQTTConnectAsync ();
-                } else {
-                    MainPage.LoadingTipShow ("Please wait, failed to get user parameters.");
-                }
+            if (IfNeedReadAllDeviceStatus) {
+                Utlis.WriteLine ("ReadAllDeviceStatus");
+                IfNeedReadAllDeviceStatus = false;
+                Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus ();
             }
+
         }
+
+
+
+        //杩炴帴閿欒娆℃暟缁熻
+        static int ERRORCount = 0;
 
         /// <summary>
-        /// 杩炴帴MQTT
+        /// 鏄惁闇�瑕佹彁绀�
         /// </summary>
-        static async Task MQTTConnectAsync ()
-        {
-            if (CurRemoteMACInfo != null && mMqttInfo != null) {
-
-             
-                //鑾峰彇鍙傛暟鎴愬姛锛屽紑濮嬭繛鎺�...
-                //MainPage.AddTip ("Successfully obtained parameters, starting to connect...");
-
-                MainPage.LoadingTipShow ("Please wait, connecting remotely...");
-
-                //try {
-                //    var url = mMqttInfo.connEmqDomainPort;
-                //    var clientId = mMqttInfo.connEmqClientId;
-                //    var username = mMqttInfo.connEmqUserName;
-                //    var passwordRemote = mMqttInfo.connEmqPwd;
-                //    CurRemoteMACInfo.clientId = clientId;
-                //    CurRemoteMACInfo.LoginAccessToken = MainPage.LoginUser.LoginTokenString;
-                //    mqttEncryptKey = CurRemoteMACInfo.isNewBusproGateway ? CurRemoteMACInfo.aesKey : "";
-                //    //mqttEncryptKey = CurRemoteMACInfo.aesKey;
-                //    var options1 = new MQTTnet.Client.Options.MqttClientOptionsBuilder ()
-                //                        .WithClientId (clientId)
-                //                        .WithTcpServer (url.Split (':') [1].Substring ("//".Length), int.Parse (url.Split (':') [2]))
-                //                        .WithCredentials (username, passwordRemote)
-                //                        .WithCleanSession ()
-                //                        // .WithCommunicationTimeout (new TimeSpan (0, 0, 20))
-                //                        .Build ();
-
-                //    await DisConnectRemoteMqttClient ("StartRemoteMqtt");
-                //    await RemoteMqttClient.ConnectAsync (options1);
-                //    remoteIsConnected = true;
-                //    IsDisConnectingWithSendCatch = false;
-                //} catch (Exception ex) {
-                //    Console.WriteLine ("Connect error: " + ex.Message);
-                //}
-
-                //string mes = "";
-                try {
-
-                    var url = mMqttInfo.connEmqDomainPort;
-                    var clientId = mMqttInfo.connEmqClientId;
-                    var username = mMqttInfo.connEmqUserName;
-                    var passwordRemote = mMqttInfo.connEmqPwd;
-
-                    //mes = "step1.Set Data";
-                    CurRemoteMACInfo.LoginAccessToken = MainPage.LoginUser.LoginTokenString;
-                    mqttEncryptKey = CurRemoteMACInfo.aesKey;
-                    var options1 = new MQTTnet.Client.Options.MqttClientOptionsBuilder ()
-                                        .WithClientId (clientId)
-                                        .WithTcpServer (url.Split (':') [1].Substring ("//".Length), int.Parse (url.Split (':') [2]))
-                                        .WithCredentials (username, passwordRemote)
-                                        .WithCleanSession ()
-                                        // .WithCommunicationTimeout (new TimeSpan (0, 0, 20))
-                                        .Build ();
-
-                    //mes = "step2.DisConnect";
-                    await DisConnectRemoteMqttClient ("StartRemoteMqtt");
-                    //MainPage.AddTip ("Start to connect...");
-                    //mes = "step3.Start to connect";
-                    await RemoteMqttClient.ConnectAsync (options1);
-                    //mes = "step4.Connected Success";
-                    remoteIsConnected = true;
-                    IsDisConnectingWithSendCatch = false;
-
-                    MainPage.LoadingTipShow ("Remote connection succeeded.");
-
-                    //MainPage.AddTip ("Connection succeeded!");
-                    //await MqttRemoteSend (new byte [] { 0 }, 1);
-                    //await MqttRemoteSend (new byte [] { 0 }, 2);
-                    //await MqttRemoteSend (new byte [] { 0 }, 4);
-
-                } catch (Exception ex) {
-                    //mes = ex.Message;
-                    //options1 寮傚父鎻愮ず
-                    //Console.WriteLine ("Connect error: " + ex.Message);
-
-                    MainPage.LoadingTipShow ("Connect error.");
-
-                    if (IfDEBUG) {
-                        MainPage.ShowAlertOnMainThread ("Connect error: " + ex.Message);
-                    }
-                } finally {
-                    //MainPage.ShowAlertOnMainThread ("finally: " + mes);
-                    //MainPage.AddTip ("finally: " + mes);
-                }
-
-            }
-        }
+        static bool bNeedConnectTip = true;
 
         /// <summary>
         /// 浠庡紑濮嬪埌杩炴帴鎴愬姛锛屽彧鎻愮ず1娆�
@@ -517,10 +510,247 @@
             if (bNeedStartTip) {
                 bNeedStartTip = false;
                 if (CommonPage.IsRemote) {
-                    //MainPage.AddTip ("Getting remote connection parameters...");
-                    MainPage.LoadingTipShow ("Please wait, getting connection parameters...");
+                    MainPage.LoadingTipShow (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.GettingRemoteConnectionInfo));
                 }
             }
+
+            //if (CommonPage.IsRemote) {
+            //    //MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.GettingRemoteConnectionInfo));
+            //    MainPage.LoadingTipShow (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.GettingRemoteConnectionInfo));
+            //}
+        }
+
+        /// <summary>
+        /// 妫�娴嬩箣鍓嶈幏鍙栫殑Mac涓庡綋鍓嶄綇瀹匨AC鏄惁涓�鑷� 涓嶄竴鑷翠粠鏂拌幏鍙�
+        /// </summary>
+        /// <returns></returns>
+        static async Task CheckMQTTConnectAsync ()
+        {
+            try {
+                if (CommonConfig.Current.HomeGatewayInfo != null && CommonConfig.Current.HomeGatewayInfo.mac == UserConfig.Instance.GatewayMAC) {
+                    await MQTTConnectAsync ();
+                } else {
+                    //Mac 鍙樺寲浜嗛噸鏂拌幏鍙栧弬鏁�
+                    await StartMQTTGetInfo ();
+                }
+            } catch {
+                CommonConfig.Current.IfGetMqttInfoSuccess = false;
+            }
+
+        }
+
+        /// <summary>
+        /// 寮�濮嬭幏鍙朚qtt 杩滅▼鍙傛暟
+        /// </summary>
+        /// <returns></returns>
+        static async Task StartMQTTGetInfo ()
+        {
+            ShowStartTip ();
+
+            if (!CommonPage.IsRemote) {
+                return;
+            }
+
+            await GetMqttInfoAndMQTTConnectAsync ();
+
+            ////--鍒ゆ柇鏄綋鍓嶆槸鍚﹀垎浜殑浣忓畢
+            //if (!UserConfig.Instance.CurrentRegion.IsOthreShare) {
+            //    //涓昏处鍙疯幏鍙朚QTT 杩滅▼閾炬帴淇℃伅锛屽苟杩炴帴
+            //    await GetMqttInfoAndMQTTConnectAsync ();
+            //} else {
+            //    //濡傛灉鏄垎浜繃鏉ョ殑浣忓畢 璧颁笅闈㈡祦绋�
+            //    //--绗竴姝ワ細鑾峰彇褰撳墠浣忓垎浜畢缃戝叧淇℃伅骞惰繛鎺QTT
+            //    await GetSingleHomeGatewayPaggerAndMQTTConnectAsync ();
+            //}
+        }
+
+
+        /// <summary>
+        /// 杩炴帴MQTT
+        /// </summary>
+        static async Task MQTTConnectAsync ()
+        {
+
+            if (!CommonPage.IsRemote) {
+                return;
+            }
+
+            if (CommonConfig.Current.HomeGatewayInfo != null && CommonConfig.Current.mMqttInfo != null) {
+                if (bNeedConnectTip) {
+                    bNeedConnectTip = false;
+                    MainPage.LoadingTipShow (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.GetSuccessfullyStartConnecting));
+                }
+
+                try {
+
+                    var url = CommonConfig.Current.mMqttInfo.url;
+
+                    //url = HttpUtil.GetProxyEMQUrl (url);
+                    //#if DEBUG
+                    //                   url = HttpUtil.GetProxyEMQUrl (url);
+
+                    //#endif
+                    var clientId = CommonConfig.Current.mMqttInfo.clientId;
+                    var username = CommonConfig.Current.mMqttInfo.userName;
+                    var passwordRemote = CommonConfig.Current.mMqttInfo.passWord;
+                    //鑾峰彇鍙傛暟鎴愬姛锛屼繚瀛樺埌鏈湴骞舵爣璁颁负true
+                    CommonConfig.Current.IfGetMqttInfoSuccess = true;
+                    CommonConfig.Current.Save ();
+
+                    mqttEncryptKey = CommonConfig.Current.HomeGatewayInfo.aesKey;
+
+                    var options1 = new MQTTnet.Client.Options.MqttClientOptionsBuilder ()
+                                        .WithClientId (clientId)
+                                        .WithTcpServer (url.Split (':') [1].Substring ("//".Length), int.Parse (url.Split (':') [2]))
+                                        .WithCredentials (username, passwordRemote)
+                                        .WithCleanSession ()
+                                        .WithProtocolVersion (MQTTnet.Formatter.MqttProtocolVersion.V311)
+                                        .WithCommunicationTimeout (new TimeSpan (0, 0, 10))
+                                        //.WithCommunicationTimeout (new TimeSpan (0, 0, 5))
+                                        //.WithCommunicationTimeout (new TimeSpan (0, 1, 0))
+                                        .Build ();
+
+                    await DisConnectRemoteMqttClient ("StartRemoteMqtt");
+
+                    var mResult = await RemoteMqttClient.ConnectAsync (options1);
+
+                    if (mResult.ResultCode == MQTTnet.Client.Connecting.MqttClientConnectResultCode.Success) {
+                        remoteIsConnected = true;
+                        IsDisConnectingWithSendCatch = false;
+                        UnsupportedProtocolVersionCount = 0;
+                    } else {
+                        //閲嶆柊涓績鏈嶅姟鍣ㄨ幏鍙栧弬鏁版爣璁�
+                        CommonConfig.Current.IfGetMqttInfoSuccess = false;
+                    }
+
+                } catch (Exception ex) {
+
+                    if (ex.Message == MqttCommunicationTimedOutException) {
+                        Console.WriteLine ("Connect error TimedOut: " + ex.Message);
+                    } else {
+                        //閲嶆柊涓績鏈嶅姟鍣ㄨ幏鍙栧弬鏁版爣璁�
+                        CommonConfig.Current.IfGetMqttInfoSuccess = false;
+                        Console.WriteLine ("Connect error: " + ex.Message);
+                    }
+
+                    //Console.WriteLine ("Connect error: " + ex.Message);
+                    if (IfDEBUG) {
+                        MainPage.ShowAlertOnMainThread ("Connect error: " + ex.Message);
+                    }
+                } finally {
+
+                }
+
+            } else {
+                CommonConfig.Current.IfGetMqttInfoSuccess = false;
+            }
+
+        }
+
+        static int UnsupportedProtocolVersionCount = 0;
+        static readonly string MqttCommunicationTimedOutException = "Exception of type 'MQTTnet.Exceptions.MqttCommunicationTimedOutException' was thrown.";
+        //
+        static readonly string UnsupportedProtocolVersion = "Connecting with MQTT server failed (UnsupportedProtocolVersion).";
+
+
+
+        /// <summary>
+        /// 鏀跺埌缃戝叧涓婄嚎娑堟伅
+        /// </summary>
+        static void ReceiveNotifyBusGateWayInfoChange ()
+        {
+            try {
+                SetGatewayOnlineResetCheck ();
+                if (CommonPage.IsRemote) {
+                    //#if DEBUG
+                    MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.GatewayLoginOnline));
+                    //#endif
+                    CheckIfNeedReadAllDeviceStatus ();
+                }
+
+                GetSingleHomeGatewayPaggerAndMQTTConnectAsync (false);
+
+            } catch { }
+        }
+
+        /// <summary>
+        /// 鏀跺埌缃戝叧鎺夌嚎淇℃伅
+        /// </summary>
+        static void ReceiveNotifyGateWayOffline ()
+        {
+            Shared.Utlis.WriteLine ("============>Mqtt GateWayOffline");
+            IsGatewayOnline = false;
+            if (CommonPage.IsRemote) {
+                Utlis.ShowAppLinkStatus (AppLinkStatus.CloudOffline);
+                MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.GatewayOffline));
+
+            }
+        }
+
+
+        /// <summary>
+        /// 鏀跺埌鎸や笅绾挎帹閫�
+        /// </summary>
+        static void ReceiveNotifySqueezeAsync (string mMes)
+        {
+
+            if (mMes == PushSignStr) return;//鏄嚜宸辩殑鐧诲綍鎺ㄩ�佷笉澶勭悊
+
+            //鏂紑杩滅▼杩炴帴
+            CommonPage.IsRemote = false;
+            if (!MainPage.LoginUser.IsLogin) {
+                return;
+            }
+
+            DisConnectRemoteMqttClient ("鎸や笅绾�");
+
+            MainPage.LoginUser.LastTime = DateTime.MinValue;
+            MainPage.LoginUser.SaveUserInfo ();
+            Room.Lists.Clear ();
+
+            Application.RunOnMainThread (() => {
+                Utlis.ShowAppLinkStatus (AppLinkStatus.WiFi);
+                new Shared.SimpleControl.Phone.AccountLogin (MainPage.LoginUser.AccountString, "").Show ();
+                SharedMethod.SharedMethod.CurPageLayout = null;
+                //CommonPage.IsRemote = false;
+
+                MainPage.LoadingTipHide ();
+                MainPage.Loading.Hide ();
+
+                new Alert (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.Tip), Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LoggedOnOtherDevices),
+                    Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.Close)).Show ();
+            });
+
+            //2020-08-11 鍒犻櫎鎺ㄩ�佹暟鎹�
+            //HDLRequest.Current.PushserivceSignOut ();
+
+            //#if HDL
+            //            if (!String.IsNullOrEmpty (MainPage.LoginUser.AllVisionRegisterDevUserNameGuid)) {
+            //                com.freeview.global.Video.Logout ();
+            //            }///BusGateWayToClient/320c1fea-1866-4708-8277-e2321a4dd236/NotifyGateWayInfoChange
+            //#endif
+
+
+        }
+
+        /// <summary>
+        /// 鏀跺埌CheckGateway涓婚
+        /// </summary>
+        static void ReceiveCheckGateway (string mMes)
+        {
+            if (!CommonPage.IsRemote) return;
+
+            Utlis.WriteLine ("ReceiveCheckGateway锛�");
+            SetGatewayOnlineResetCheck ();
+        }
+
+        /// <summary>
+        /// 鎺ㄩ�佹尋涓嬬嚎涓婚
+        /// </summary>
+        static void SendPushSignOut ()
+        {
+            byte [] message = CommonPage.MyEncodingUTF8.GetBytes (PushSignStr);
+            MqttRemoteSend (message, 4);
         }
 
         /// <summary>
@@ -531,338 +761,127 @@
         /// <returns></returns>
         public static async Task MqttRemoteSend (byte [] message, int optionType = 0)
         {
-            try {
-                //if (!remoteIsConnected) {
-                //    Utlis.WriteLine ($"============>Mqtt 鏈繛鎺� 鍙栨秷鍙戦��");
-                //    return;
-                //}
+            //return;
 
+            try {
                 string topicName;
                 switch (optionType) {
                 case 0:
-                    topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/ON";
+                    topicName = $"/ClientToBusGateWay/{CommonConfig.Current.HomeGatewayInfo.gatewayId}/Common/ON";
                     if (!string.IsNullOrEmpty (mqttEncryptKey)) {
                         message = Shared.Securitys.EncryptionService.AesEncryptPayload (message, mqttEncryptKey);
                     }
                     await RemoteMqttClient.PublishAsync (new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
                     break;
                 case 3:
-                    topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/CheckGateway";
-                    //Utlis.WriteLine ("CheckGateway");
+                    topicName = $"/ClientToBusGateWay/{CommonConfig.Current.HomeGatewayInfo.gatewayId}/Common/CheckGateway";
+                    Shared.Utlis.WriteLine ("CheckGateway");
                     await RemoteMqttClient.PublishAsync (new MqttApplicationMessage { Topic = topicName, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
+                    break;
+                case 4://鍙戝竷鏂版柟妗堢殑鎸や笅绾夸富棰�
+                    topicName = $"/BusGateWayToClient/{MainPage.LoginUser.ID}" + PushNotifySqueeze;
+                    //message = CommonPage.MyEncodingUTF8.GetBytes (PushSignStr);
+                    await RemoteMqttClient.PublishAsync (new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
                     break;
                 }
             } catch (Exception e) {
-                // Utlis.WriteLine ($"============>Mqtt MqttRemoteSend catch");
-                 if (!IsDisConnectingWithSendCatch) {
+                //Utlis.WriteLine ($"============>Mqtt MqttRemoteSend catch");
+                if (!IsDisConnectingWithSendCatch) {
                     IsDisConnectingWithSendCatch = true;
-                    await DisConnectRemoteMqttClient ("MqttRemoteSendCatch");
+                    await DisConnectRemoteMqttClient ("SendCatch");
                 }
-
             }
         }
-
         /// <summary>
         /// SendCatch 鍚庢墽琛屼竴娆℃柇寮�鎿嶄綔
         /// </summary>
         static bool IsDisConnectingWithSendCatch = false;
 
-        /// <summary>
-        /// 鍒嗕韩浣忓畢 鑾峰彇褰撳墠浣忓畢缃戝叧淇℃伅骞朵笖杩炴帴MQTT 鎴栬�呭埛鏂�  
-        /// 2020-01-11
-        /// </summary>
-        static async Task GetSingleHomeGatewayPaggerAndMQTTConnectAsync (bool bNeedConnect = true)
-        {
 
-            var requestObj3 = new GetSingleHomeGatewayPaggerObj ();
-            requestObj3.ReqDto.LoginAccessToken = MainPage.LoginUser.LoginTokenString;
-            requestObj3.ReqDto.HomeId = UserConfig.Instance.CurrentRegion.Id;
-            requestObj3.ReqDto.PageSetting.Page = 1;
-            requestObj3.ReqDto.PageSetting.PageSize = 10;
-            string urlHead = MainPage.RequestHttpsHost;
-            if (requestObj3.IsOtherAccountCtrl) {
-                urlHead = UserConfig.Instance.MasterAccountRequestBaseUrl;
-                requestObj3.ReqDto.LoginAccessToken = UserConfig.Instance.MasterAccountToken;
-            }
-
-            var requestJson3 = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj3);
-            var revertObj3 = MainPage.RequestHttps (API.GetSingleHomeGatewayPagger, requestJson3, urlHead);
-            if (revertObj3.StateCode.ToUpper () == StateCode.SUCCESS) {
-                var infoResult = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGatewayResult> (revertObj3.ResponseData.ToString ());
-                if (bNeedConnect) {
-                    //2020-01-11
-                    UserConfig.Instance.SetNowHomeGateways (infoResult.PageData);
-
-                    //var gatewayListRequestResult_Obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttRemoteInfo> (revertObj3.ResponseData.ToString ());
-                    //--鎵惧嚭鏄惁瀛樺湪鍖归厤褰撳墠浣忓畢鐨刴ac锛屽瓨鍦ㄥ啀杩涜杩滅▼銆�
-                    if (UserConfig.Instance.CheckHomeGatewaysNotEmpty ()) {
-                        var mGatewayRes = infoResult.PageData.Find ((obj) => obj.GatewayUniqueId == UserConfig.Instance.HomeGateway.mac);
-                        if (mGatewayRes != null) {
-                            CurRemoteMACInfo = new RemoteMACInfo ();
-                            CurRemoteMACInfo.aesKey = mGatewayRes.AesKey;
-                            CurRemoteMACInfo.mac = mGatewayRes.GatewayUniqueId;
-                            CurRemoteMACInfo.macMark = mGatewayRes.MacMark;
-                            CurRemoteMACInfo.isValid = mGatewayRes.MqttOnlineStatus ? "Valid" : "InValid";
-
-                            await MQTTConnectAsync ();
-                        }
-
-
-                    } else {
-                        Utlis.WriteLine ("============>Mqtt 鍙栨秷杩炴帴锛屽綋鍓嶄綇瀹呮病缁戝畾缃戝叧");
-                    }
-                } else {
-                    var mGatewayRes = infoResult.PageData.Find ((obj) => obj.GatewayUniqueId == UserConfig.Instance.HomeGateway.mac);
-                    if (mGatewayRes != null) {
-                        CurRemoteMACInfo.aesKey = mGatewayRes.AesKey;
-                        mqttEncryptKey = CurRemoteMACInfo.aesKey;
-                    } else {
-                        MainPage.LoadingTipShow ("Please wait, failed to get gateway parameters.");
-                    }
-
-                }
-
-
-            }
-
-           
-        }
         /// <summary>
         /// 鏄惁闇�瑕佽鍙栦竴娆℃墍鏈夎澶囩姸鎬�
         /// </summary>
         static bool IfNeedReadAllDeviceStatus = true;
-        /// <summary>
-        /// 鏀跺埌缃戝叧涓婄嚎娑堟伅
-        /// </summary>
-        static async Task ReceiveNotifyBusGateWayInfoChange ()
-        {
-            Utlis.WriteLine ("============>Mqtt 缃戝叧涓婄嚎");
-            SetGatewayOnlineResetCheck ();
-            if (CommonPage.IsRemote) {
+        public static bool IsGatewayOnline = true;
+        //static int CheckGatewayCount = 0;
+        //static DateTime mCheckGatewayTime;
 
-//#if DEBUG
-                MainPage.AddTip ("Gateway login online");
-//#endif
-                if (IfNeedReadAllDeviceStatus) {
-                    IfNeedReadAllDeviceStatus = false;
-                    Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus ();
-                }
-            }
-            //璇锋眰鍒锋柊涓�娆� 缃戝叧鍔犲瘑Key
-            await GetSingleHomeGatewayPaggerAndMQTTConnectAsync (false);
-        }
-        /// <summary>
-        /// 鏀跺埌缃戝叧鎺夌嚎淇℃伅
-        /// </summary>
-        static void ReceiveNotifyGateWayOffline ()
-        {
-            Utlis.WriteLine ("============>Mqtt GateWayOffline");
-            IsGatewayOnline = false;
-            if (CommonPage.IsRemote) {
-                Utlis.ShowAppLinkStatus (AppLinkStatus.CloudOffline);
-                MainPage.AddTip ("Remote failed,gateway offline");
-                //if (MainPage.WiFiStatus != "CrabtreeAdd/CloudUnlink.png") {
-                //    Utlis.ShowAppLinkStatus (AppLinkStatus.CloudUnlink);
-                //}
-
-            }
-        }
-
-      
-        static int CheckGatewayCount = 0;
-        static DateTime mCheckGatewayTime;
 
         /// <summary>
         /// 璁剧疆缃戝叧鍦ㄧ嚎鏍囧織锛屽苟閲嶇疆CheckGateway鍙傛暟
         /// </summary>
         static void SetGatewayOnlineResetCheck ()
         {
-            IsGatewayOnline = true;
-            mCheckGatewayTime = DateTime.Now;
-            CheckGatewayCount = 0;
+
+            //mCheckGatewayTime = DateTime.Now;
+            //CheckGatewayCount = 0;
             if (CommonPage.IsRemote) {
-                if (MainPage.WiFiStatus != "CrabtreeAdd/CloudLink.png") {
+                if (!IsGatewayOnline) {
+                    IsGatewayOnline = true;
                     Utlis.ShowAppLinkStatus (AppLinkStatus.CloudLink);
                 }
             }
         }
 
-        //static void TipGatewayOffline () {
 
-        //}
-
-//        /// <summary>
-//        /// 瀹氭椂妫�娴嬬綉鍏虫槸鍚﹀湪绾�
-//        /// 1.绾跨▼浼戠湢闂撮殧5s
-//        /// 2.鍙戦�丆heckGateway闂撮殧涓�9S锛屾敹鍒颁富棰樺埛鏂拌鏃堕棿锛岄噸缃彂閫佹鏁�
-//        /// 3.鍙戦�佹鏁板埌杈�3娆′互涓婏紝鍒欏垽瀹氱綉鍏充负绂荤嚎鐘舵��
-//        /// </summary>
-//        /// <returns></returns>
-//        static void InitCheckGateway ()
-//        {
-//            new System.Threading.Thread (async () => {
-//                while (true) {
-//                    try {
-
-//                        if (CommonPage.IsRemote && remoteIsConnected) {
-//                            if (CheckGatewayCount >= 3) {
-//                                //杩炵画3娆℃病鍥炲锛屽垽瀹氱綉鍏宠秴鏃�
-//                                if (MainPage.WiFiStatus == "CrabtreeAdd/CloudLink.png") {
-//                                    //IsGatewayOnline = false;
-//                                    Utlis.ShowAppLinkStatus (AppLinkStatus.CloudOffline);
-//                                    MainPage.AddTip ("Gateway offline!");
-//                                }
-//                            }
-
-//                            if (mCheckGatewayTime.AddSeconds (10).Ticks <= System.DateTime.Now.Ticks) {
-//                                mCheckGatewayTime = DateTime.Now;
-//                                //CheckGateway
-//                                MqttRemoteSend (new byte [] { }, 3);
-//                                CheckGatewayCount++;
-//#if DEBUG
-//                                Utlis.WriteLine ("CheckGateway");
-//#endif
-
-
-//                            }
-//                        }
-
-//                        System.Threading.Thread.Sleep (5500);
-//                    } catch { }
-
-//                }
-//            }) { IsBackground = true }.Start ();
-//        }
-
-       
         /// <summary>
-        /// 鏀跺埌CheckGateway涓婚
+        /// 涓昏处鍙疯幏鍙朚QTT 杩滅▼閾炬帴淇℃伅锛屽苟杩炴帴
         /// </summary>
-        static void ReceiveCheckGatewayTopic () {
-            //Utlis.WriteLine ("============>Mqtt CheckGateway缃戝叧鍥炲");
-            SetGatewayOnlineResetCheck ();
-        }
-        
-        /// <summary>
-        /// 鏀跺埌鎸や笅绾挎帹閫�
-        /// </summary>
-        static async Task ReceiveNotifySqueezeAsync (byte [] mes)
+        /// <returns></returns>
+        static async Task GetMqttInfoAndMQTTConnectAsync ()
         {
-            Utlis.WriteLine ($"============>MqttNotifySqueeze: {ErrorCode.LoginInAnotherDevice}");
-            var mMes = CommonPage.MyEncodingUTF8.GetString (mes);
-            if (mMes == PushSignStr) return;//鏄嚜宸辩殑鐧诲綍鎺ㄩ�佷笉澶勭悊
+            var mqttInfoRequestResult_Obj = HttpServerRequest.Current.GetMqttRemoteInfo (GetRandomKey ());
+            if (mqttInfoRequestResult_Obj != null) {
+                CommonConfig.Current.mMqttInfo = mqttInfoRequestResult_Obj;
+                if (UserConfig.Instance.CheckHomeGatewaysNotEmpty()) {
+                    //----绗簩姝ユ壘鍑烘槸鍚﹀瓨鍦ㄥ尮閰嶅綋鍓嶄綇瀹呯殑mac锛屽瓨鍦ㄥ啀杩涜杩滅▼銆�
+                    CommonConfig.Current.HomeGatewayInfo = UserConfig.Instance.HomeGateway;
+                    if (CommonConfig.Current.HomeGatewayInfo != null) {
+                        //----绗笁姝� 寮�濮嬭繛鎺�
+                        await MQTTConnectAsync ();
+                    }
+                } else {
+                    Utlis.WriteLine ("============>杩樻病缁戝畾缃戝叧");
+                }
 
-            CommonPage.IsRemote = false;
-
-            //if (MainPage.IsOtherDevicesLogin) return;
-
-            if (!MainPage.LoginUser.IsLogin) {
-                return;
+            } else {
+                Utlis.WriteLine ("============>MqttInfo null");
             }
-
-            MainPage.LoginUser.LastTime = DateTime.Now.AddDays (-30);
-            MainPage.LoginUser.SaveUserInfo ();
-
-            DisConnectRemoteMqttClient ("鎸や笅绾�");
-
-            MainPage.ShowAlertOnMainThread (ErrorCode.LoginInAnotherDevice);
-
-            Application.RunOnMainThread (() => {
-                MainPage.WiFiStatus = "CrabtreeAdd/WiFi.png";
-                UserMiddle.btnLinkStatus.UnSelectedImagePath = MainPage.WiFiStatus;
-                new AccountLogin ().Show ();
-            });
-
         }
+
+
+        /// <summary>
+        /// 鍒嗕韩浣忓畢 鑾峰彇褰撳墠浣忓畢缃戝叧淇℃伅骞朵笖杩炴帴MQTT 鎴栬�呭埛鏂�  
+        /// 2020-03-17
+        /// </summary>
+        static async Task GetSingleHomeGatewayPaggerAndMQTTConnectAsync (bool bNeedConnect = true)
+        {
+          
+        }
+
 
     }
 }
 
-public class ShareMemberConnMqttInfoObj : GetConnMqttInfoObj
-{
-    /// <summary>
-    /// 涓讳汉鐢ㄦ埛Id 
-    /// </summary>
-    public string MainUserDistributedMark;
-
-    /// <summary>
-    /// 鍒嗕韩鑰呬綇瀹匢d
-    /// </summary>
-    public string HomeId;
-
-}
-
-public class GetConnMqttInfoObj : BaseRequestObj
-{
-    /// <summary>
-    /// HdlGatewayGatewayType 缃戝叧绫诲瀷(0:涓�绔彛銆�1:BusproLinux 缃戝叧銆�2:Zigbee 缃戝叧銆�3:Knx缃戝叧)
-    /// </summary>
-    public int HdlGatewayGatewayType = 0;
-    /// <summary>
-    /// 璁惧绫诲瀷瀛楁
-    /// </summary>
-    public string PlatformStr = "";
-    /// <summary>
-    /// 
-    /// </summary>
-    public string PublishPayloadJsonStr = "";
-    /// <summary>
-    /// Mac
-    /// </summary>
-    public string Mac = "";
-}
-
-public class RemoteRequestParameters
-{
-    public string RequestVersion;
-    public int RequestSource;
-    public string LoginAccessToken;
-    public int RequestProtocolType;
-
-  
-    public string Mac = "";
-    public string GroupName = "";
-
-}
-
-public class MqttRemoteInfo
-{
-    public List<RemoteMACInfo> pageData;
-
-    public int pageIndex = 0;
-    public int pageSize = 10;
-    public int totalCount = 3;
-    public int totalPages = 1;
-    public bool hasPreviousPage = false;
-    public bool hasNextPage = false;
-}
 
 public class MqttInfo
 {
-    public string connEmqDomainPort;
-    public string connEmqClientId;
-    public string connEmqUserName;
-    public string connEmqPwd;
-
-    public List<RemoteMACInfo> AccountAllGateways;
-}
-
-public class RemoteMACInfo
-{
-    public string mac;
-    public string macMark;
-    public string isValid;
-    public string aesKey;
-    public bool isNewBusproGateway;
-    public string groupName;
-    public string projectName;
-    public string userName;
-
+    /// <summary>
+    /// 
+    /// </summary>
+    public string url;
+    /// <summary>
+    /// 
+    /// </summary>
     public string clientId;
-
-    //app鑷畾涔夋暟鎹�
-    public string md5_mac_string;
-    public string LoginAccessToken;
+    /// <summary>
+    /// 
+    /// </summary>
+    public string userName;
+    /// <summary>
+    /// 
+    /// </summary>
+    public string passWord;
 }
 
 namespace Shared.Securitys
@@ -983,503 +1002,6 @@
         #endregion
 
 
-    }
-}
-
-/*
-using System.Collections.Generic;
-using System;
-using MQTTnet.Client;
-using System.Threading.Tasks;
-using Shared;
-using Shared.SimpleControl;
-using MQTTnet;
-using System.Text;
-using System.Security.Cryptography;
-
-namespace SmartHome
-{
-    public static class MqttCommon
-    {
-        static string mqttEncryptKey = "";
-        static string checkGatewayTopicBase64 = "";
-
-        /// <summary>
-        /// 鎵嬫満鏍囪瘑
-        /// </summary>
-        static Guid currentGuid = Guid.NewGuid ();
-
-        /// <summary>
-        /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
-        /// </summary>
-        static object isConnecting = false.ToString ();
-        /// <summary>
-        /// 杩滅▼MqttClient
-        /// </summary>
-        public static IMqttClient RemoteMqttClient;
-
-        static bool thisShowTip = true;
-
-        public static async Task Close (bool RemoveRemoteMqttClient = false)
-        {
-            try {
-                if (RemoteMqttClient != null) {
-                    //thisShowTip = true;
-                    await RemoteMqttClient.DisconnectAsync ();
-                }
-                if (RemoveRemoteMqttClient) {
-                    RemoteMqttClient = null;
-                }
-                CommonPage.IsRemote = false;
-                Utlis.WriteLine ("Close Mqtt!!!");
-            } catch { }
-        }
-
-        static DateTime dateTime = DateTime.MinValue;
-        static int startCount = 0;
-
-        //public static async Task ReSatart ()
-        //{
-        //    await Close ();
-        //    await RemoteMqttClient.ConnectAsync (options);
-        //}
-
-        /// <summary>
-        /// 鍚姩杩滅▼Mqtt
-        /// </summary>
-        public static async System.Threading.Tasks.Task StartCloudMqtt ()
-        {
-
-
-            Application.RunOnMainThread (() => {
-                if (5 < (DateTime.Now - dateTime).TotalSeconds) {
-                    return;
-                }
-                dateTime = DateTime.Now;
-            });
-            if (!MainPage.LoginUser.IsLogin) {
-                isConnecting = false.ToString ();
-                return;
-            }
-            while (isConnecting.ToString () == true.ToString ()) {
-                if (5 < (DateTime.Now - dateTime).TotalSeconds) {
-                    break;
-                }
-                await System.Threading.Tasks.Task.Delay (500);
-            }
-            lock (isConnecting) {
-                if (isConnecting.ToString () == true.ToString ()) {
-                    return;
-                }
-                isConnecting = true.ToString ();
-                if (RemoteMqttClient != null && RemoteMqttClient.IsConnected) {
-                    MqttCheckGateway ();
-                    return;
-                }
-            }
-            new System.Threading.Thread (async () => {
-                try {
-                    if (RemoteMqttClient == null) {
-                        var requestObj3 = new GatewayByRegionListObj () { RegionID = UserConfig.Instance.CurrentRegion.RegionID };
-                        var requestJson3 = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj3);
-                        var revertObj3 = MainPage.RequestHttps ("GatewayByRegionList", requestJson3, true, false);
-                        if (revertObj3.StateCode.ToUpper() == StateCode.SUCCESS) {
-                            var responseDataObj = Newtonsoft.Json.JsonConvert.DeserializeObject<List<GatewayRes>> (revertObj3.ResponseData.ToString ());
-                            var gatewayList = responseDataObj;
-                            if (gatewayList != null && gatewayList.Count > 0) {
-                                UserConfig.Instance.CurrentRegion.MAC = gatewayList [0].MAC;
-                                UserConfig.Instance.SaveUserConfig ();
-                            }
-                        } else {
-                        }
-
-                        //(2)鍒涘缓Mqtt瀹㈡埛绔�
-                        RemoteMqttClient = new MqttFactory ().CreateMqttClient ();
-                        //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
-                        RemoteMqttClient.UseApplicationMessageReceivedHandler (async e => {
-                            if (isConnecting.ToString () == true.ToString ())
-                                isConnecting = false.ToString ();
-                            var aesDecryptTopic = e.ApplicationMessage.Topic;
-                            var aesDecryptPayload = e.ApplicationMessage.Payload;
-                            if (aesDecryptTopic == "YouIpAndPortNoRecord" || aesDecryptTopic == "DecryptFail") {// -->   浣犲綋鍓嶇殑IP鍙婄鍙e湪浜戠涓嶅瓨鍦�,璇烽噸鏂扮櫥褰曡繛鎺ヤ笅!
-                                await Close (true);
-                                await MqttCheckGateway ();
-                            } else if (aesDecryptTopic == @"/BeingSqueezedOffline") {
-                                try {
-                                    Application.RunOnMainThread (() => {
-                                        MainPage.Loading.Start ("");
-                                        MainPage.LoginUser.LastTime = DateTime.MinValue;
-                                        MainPage.LoginUser.SaveUserInfo ();
-                                        Room.Lists.Clear ();
-                                        new Shared.SimpleControl.Phone.AccountLogin (MainPage.LoginUser.AccountString.ToLower (), "").Show ();
-                                        MainPage.LoginUser.LastTime = System.DateTime.MinValue;
-                                        Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.LinkStatusTipColor;
-                                        if (CommonPage.IsRemote) {
-                                            SmartHome.MqttCommon.Close (true);
-                                        }
-                                        var webPush = new service.hdlcontrol.com_push.WebServicePush ();
-                                        webPush.DeleteToken_Push (UserConfig.Instance.tokenID);
-                                    });
-                                } catch (Exception ex) {
-                                    Utlis.WriteLine (ex.Message);
-                                } finally {
-                                    Application.RunOnMainThread (() => {
-                                        Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.LinkStatusTipColor;
-                                        MainPage.Loading.Hide ();
-                                        new Alert (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.Tip), Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LoggedOnOtherDevices),
-                                            Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.Close)).Show ();
-                                    });
-                                }
-#if HDL
-                                if (!String.IsNullOrEmpty (MainPage.LoginUser.AllVisionRegisterDevUserNameGuid)) {
-                                    com.freeview.global.Video.Logout ();
-                                }
-#endif
-                            } else {
-                                aesDecryptTopic = Shared.Securitys.EncryptionService.AesDecryptTopic (e.ApplicationMessage.Topic, mqttEncryptKey);
-                                aesDecryptPayload = Shared.Securitys.EncryptionService.AesDecryptPayload (e.ApplicationMessage.Payload, mqttEncryptKey);
-                            }
-                            if (aesDecryptTopic == @"/" + MainPage.LoginUser.AccountString.ToLower () + @"/CheckGateway/" + UserConfig.Instance.GatewayMAC.Replace (".", "")) {
-                                var ss = CommonPage.MyEncodingUTF8.GetString (aesDecryptPayload);
-                                var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponsePack> (ss);
-                                if (obj == null) {
-                                    return;
-                                }
-                                switch (obj.StateCode) {
-                                case "HDLUdpDataForwardServerMqttClientNoOnLine":
-                                case "NoOnline":
-                                case "NetworkAnomaly"://涓嶅湪绾�
-                                    MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.RemoteFailedGatewayOffline));
-                                    Application.RunOnMainThread (() => {
-                                        MainPage.Loading.Hide ();
-                                        Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
-                                    });
-                                    break;
-                                case "NoRecord"://MAC涓嶆纭�
-                                    MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.MACError));
-                                    Application.RunOnMainThread (() => {
-                                        MainPage.Loading.Hide ();
-                                        Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
-                                    });
-                                    break;
-                                case StateCode.SUCCESS:
-                                    CommonPage.IsRemote = true;
-                                    Application.RunOnMainThread (() => {
-                                        MainPage.Loading.Hide ();
-                                        Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = 0xAA69E64A;
-                                        Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus ();
-                                    });
-                                    MainPage.AddTip (UserConfig.Instance.CurrentRegion.RegionName + ":" + Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
-                                    break;
-                                default:
-                                    MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkLoser));
-                                    Application.RunOnMainThread (() => {
-                                        MainPage.Loading.Hide ();
-                                        Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
-                                    });
-                                    break;
-                                }
-                            } else {
-                                var packet = new Packet ();
-                                packet.Bytes = aesDecryptPayload;
-                                packet.Manager ();
-                            }
-                        });
-
-                        RemoteMqttClient.UseDisconnectedHandler (e => {
-                            //Utlis.WriteLine ("RemoteMqttClient UseDisconnectedHandler");
-                            if (thisShowTip) {
-                                if (CommonPage.IsRemote) {
-                                    //MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.RemoteConnectionDisconnected));
-                                    Application.RunOnMainThread (() => {
-                                        MainPage.Loading.Hide ();
-                                        Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
-                                    });
-                                }
-                            } else {
-                                thisShowTip = true;
-                            }
-                        });
-                        RemoteMqttClient.UseConnectedHandler (async e => {
-                            //Utlis.WriteLine ("RemoteMqttClient IsRemote");
-                            await MqttCheckGateway ();
-                        });
-                    }
-
-                    var requestObj = new LoginObj () { Account = MainPage.LoginUser.AccountString.ToLower (), Password = MainPage.LoginUser.Password, Company = MainPage.SoftSmsType };
-                    var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj);
-                    var tempResult = MainPage.RequestHttps ("Login", requestJson, false);
-                    if (tempResult == null) {
-                        Application.RunOnMainThread (() => {
-                            MainPage.Loading.Hide ();
-                            Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
-                        });
-                        Utlis.WriteLine ($"閲嶆柊杩炴帴杩滅▼閫氳澶辫触锛屽洜涓鸿幏鍙栨柊鐨凨EY澶辫触");
-                        return;
-                    }
-                    //var messgae = System.Text.Encoding.UTF8.GetString (tempResult);
-
-                    var responsePack = tempResult.ResponseData;// Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>> (messgae);
-                    //if (responsePack == null || responsePack ["ResponseData"] == null) {
-                    //    Utlis.WriteLine ("鏂紑鍚庨噸鏂伴摼鎺ラ渶瑕侀噸鏂扮櫥褰曡幏鍙栬繛鎺ョ殑瀵嗙爜澶辫触");
-                    //    return;
-                    //}
-                    var dictrionaryResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>> (tempResult.ResponseData.ToString ());
-                    //var dictrionaryResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>> (responsePack ["ResponseData"].ToString ());
-                    //////杩樻湁绉嶆儏鍐垫槸鍚屼竴涓狪D 鏈夊涓澶囩敤杩欎釜id杩炴帴锛堜細瀵艰嚧涓柇锛�
-                    mqttEncryptKey = dictrionaryResult ["HdlOnMqttKey"]?.ToString ();
-                    var url = dictrionaryResult ["ConnectMqttBrokerLoadSubDomain"]?.ToString ();
-                    var clientId = dictrionaryResult ["ConnectMqttClientId"]?.ToString ();
-                    var username = dictrionaryResult ["ConnectMqttBrokerUserName"]?.ToString ();
-                    var passwordRemote = dictrionaryResult ["ConnectMqttBrokerPwd"]?.ToString ();
-
-                    if (clientId == null || username == null || passwordRemote == null) {
-                        return;
-                    }
-
-                    ////(1)杩炴帴鍒颁簯绔殑Mqtt瀹㈡埛绔繛鎺ュ弬鏁�
-                    var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder ()
-                                 .WithClientId (clientId)
-                                 .WithTcpServer (url.Split (':') [1].Substring ("//".Length), int.Parse (url.Split (':') [2]))//
-                                 .WithCredentials (username, passwordRemote)
-                                 .WithCleanSession ()
-                                 .WithCommunicationTimeout (new TimeSpan (0, 0, 10))
-                                 .Build ();
-
-                    await Close ();
-                    await RemoteMqttClient.ConnectAsync (options);
-                } catch (Exception ex) {
-                    Utlis.WriteLine ("============>" + ex.Message);
-                    Application.RunOnMainThread (() => {
-                        MainPage.Loading.Hide ();
-                        isConnecting = false.ToString ();
-
-                        Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
-#if DEBUG
-                        Alert a = new Alert (isConnecting.ToString (), ex.Message, "Close");
-                        a.Show ();
-#endif
-                        if (MqttCommon.RemoteMqttClient != null) {
-                            MqttCommon.RemoteMqttClient.Dispose ();
-                        }
-                        if (MqttCommon.RemoteMqttClient != null) {
-                            MqttCommon.RemoteMqttClient = null;
-                        }
-                    });
-                } finally {
-                    isConnecting = false.ToString ();
-                    Application.RunOnMainThread (() => {
-                        MainPage.Loading.Hide ();
-                    });
-                }
-            }) { IsBackground = true }.Start ();
-        }
-
-        /// <summary>
-        /// Logins the by PWDA sync.
-        /// </summary>
-        public static async System.Threading.Tasks.Task<byte []> LoginByPWDAsync (string account, string password, string source = "", int company = 0)
-        {
-            try {
-                var result = await MainPage.RequestHttpsResultAsync ("Login",
-                System.Text.Encoding.UTF8.GetBytes (Newtonsoft.Json.JsonConvert.SerializeObject (new Dictionary<string, object> {
-                    ["Account"] = account,
-                    ["Password"] = password,
-                    ["Source"] = source,
-                    ["Company"] = company
-                })));
-                return result;
-            } catch {
-                return null;
-            }
-        }
-
-        /// <summary>
-        /// 灏咮ase64瀛楃涓诧紝杞崲鎴愬悎娉曠殑Mqtt涓婚
-        /// </summary>
-        /// <param name="baseSexFourEncStr"></param>
-        /// <returns></returns>
-        public static string BaseSexFourStrToMqttTopic (string baseSexFourEncStr)
-        {
-            baseSexFourEncStr = baseSexFourEncStr.Replace ("+", "[[$-MQTT_PLUS_SYMBOL_REPLACE-$]]");
-            baseSexFourEncStr = baseSexFourEncStr.Replace ("/", "[[$-MQTT_TILT_SYMBOL_REPLACE-$]]");
-            return baseSexFourEncStr;
-        }
-
-        public static async System.Threading.Tasks.Task MqttRemoteSend (byte [] message)
-        {
-            try {
-                if (RemoteMqttClient == null || !RemoteMqttClient.IsConnected) {
-                    await StartCloudMqtt ();
-                }
-                if (!RemoteMqttClient.IsConnected) {
-                    return;
-                }
-                var topicName = @"/" + MainPage.LoginUser.AccountString.ToLower () + @"/" + UserConfig.Instance.GatewayMAC.Replace (".", "") + @"/" + currentGuid;
-
-                //base64鍔犲瘑涓婚
-                checkGatewayTopicBase64 = Shared.Securitys.EncryptionService.AesEncryptTopic (topicName, mqttEncryptKey);
-
-                //BaseSexFourStrToMqttTopic
-                var topicNameSend = BaseSexFourStrToMqttTopic (checkGatewayTopicBase64);
-
-                //base64鍔犲瘑涓讳綋
-                var messageSend = Shared.Securitys.EncryptionService.AesEncryptPayload (message, mqttEncryptKey);
-
-                var m = new MqttApplicationMessage { Topic = topicNameSend, Payload = messageSend, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
-                await RemoteMqttClient?.PublishAsync (m);
-            } catch (Exception e) {
-                isConnecting = false.ToString ();
-            }
-        }
-
-        public static async Task MqttCheckGateway ()
-        {
-            try {
-                if (RemoteMqttClient == null || !RemoteMqttClient.IsConnected) {
-                    await StartCloudMqtt ();
-                }
-                if (!RemoteMqttClient.IsConnected) {
-                    return;
-                }
-                var topicName = @"/" + MainPage.LoginUser.AccountString.ToLower () + @"/CheckGateway/" + UserConfig.Instance.GatewayMAC.Replace (".", "");
-                Utlis.WriteLine ("MqttCheckGateway : " + topicName);
-                //base64鍔犲瘑涓婚
-                var topicNameBase64 = Shared.Securitys.EncryptionService.AesEncryptTopic (topicName, mqttEncryptKey);
-
-                //BaseSexFourStrToMqttTopic
-                var topicNameSend = BaseSexFourStrToMqttTopic (topicNameBase64);
-
-                //base64鍔犲瘑涓婚
-                var messageSend = Shared.Securitys.EncryptionService.AesEncryptPayload (new byte [] { 2, 1 }, mqttEncryptKey);
-
-                var m = new MqttApplicationMessage { Topic = topicNameSend, Payload = messageSend, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
-                await RemoteMqttClient?.PublishAsync (m);
-            } catch (Exception e) {
-                isConnecting = false.ToString ();
-            }
-        }
-    }
-}
-
-
-
-namespace Shared.Securitys
-{
-    public partial class EncryptionService
-    {
-
-        #region 鍔犲瘑
-        /// <summary>
-        /// 鍔犲瘑涓婚涓築ase64
-        /// </summary>
-        /// <param name="pToEncrypt"></param>
-        /// <param name="key"></param>
-        /// <returns></returns>
-        public static string AesEncryptTopic (string pToEncrypt, string key)
-        {
-            if (string.IsNullOrEmpty (pToEncrypt)) return null;
-            //闇�瑕佸姞瀵嗗唴瀹圭殑鏄庢枃娴�
-            Byte [] toEncryptArray = Encoding.UTF8.GetBytes (pToEncrypt);
-
-            //閰嶇疆AES鍔犲瘑Key(瀵嗛挜銆佸悜閲忋�佹ā寮忋�佸~鍏�)
-            RijndaelManaged rm = new RijndaelManaged {
-                Key = Encoding.UTF8.GetBytes (key),
-                IV = Encoding.UTF8.GetBytes (key),
-                Mode = CipherMode.CBC,
-                Padding = PaddingMode.PKCS7
-            };
-
-            //鍒涘缓AES鍔犲瘑鍣ㄥ璞�
-            ICryptoTransform cTransform = rm.CreateEncryptor ();
-
-            //浣跨敤AES灏嗘槑鏂囨祦杞垚瀵嗘枃瀛楄妭鏁扮粍
-            Byte [] resultArray = cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length);
-
-            //灏咥ES鐢熸垚鐨勫瘑鏂囧瓧鑺傛暟缁勮浆鎴怋ase64瀛楃涓�
-            return Convert.ToBase64String (resultArray, 0, resultArray.Length);
-        }
-
-
-        /// <summary>
-        /// 鍔犲瘑璐熻浇涓轰簩杩涘埗娴�
-        /// </summary>
-        /// <param name="toEncryptArray"></param>
-        /// <param name="key"></param>
-        /// <returns></returns>
-        public static byte [] AesEncryptPayload (byte [] toEncryptArray, string key)
-        {
-            //閰嶇疆AES鍔犲瘑Key(瀵嗛挜銆佸悜閲忋�佹ā寮忋�佸~鍏�)
-            var rm = new RijndaelManaged {
-                Key = Encoding.UTF8.GetBytes (key),
-                IV = Encoding.UTF8.GetBytes (key),
-                Mode = CipherMode.CBC,
-                Padding = PaddingMode.PKCS7
-            };
-
-            //鍒涘缓AES鍔犲瘑鍣ㄥ璞�
-            var cTransform = rm.CreateEncryptor ();
-            //浣跨敤AES灏嗘槑鏂囨祦杞垚瀵嗘枃瀛楄妭鏁扮粍
-            return cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length);
-        }
-        #endregion
-
-
-        #region 瑙e瘑
-        /// <summary>
-        /// 瑙e瘑涓婚鏁版嵁
-        /// </summary>
-        /// <param name="pToDecrypt"></param>
-        /// <param name="key"></param>
-        /// <returns></returns>
-        public static string AesDecryptTopic (string pToDecrypt, string key)
-        {
-            //AES瀵嗘枃Base64杞垚瀛楃涓�
-            Byte [] toEncryptArray = Convert.FromBase64String (pToDecrypt);
-
-            //閰嶇疆AES鍔犲瘑Key(瀵嗛挜銆佸悜閲忋�佹ā寮忋�佸~鍏�)
-            RijndaelManaged rm = new RijndaelManaged {
-                Key = Encoding.UTF8.GetBytes (key),
-                IV = Encoding.UTF8.GetBytes (key),
-                Mode = CipherMode.CBC,
-                Padding = PaddingMode.PKCS7
-            };
-
-            //鍒涘缓AES瑙e瘑鍣ㄥ璞�
-            ICryptoTransform cTransform = rm.CreateDecryptor ();
-
-            //浣跨敤AES灏嗗瘑鏂囨祦杞垚鏄庢枃鐨勫瓧鑺傛暟缁�
-            Byte [] resultArray = cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length);
-
-            //杞垚瀛楃涓�
-            return Encoding.UTF8.GetString (resultArray);
-        }
-
-        /// <summary>
-        /// 閲囩敤Aes瑙e瘑璐熻浇鏁版嵁
-        /// </summary>
-        /// <param name="toEncryptArray"></param>
-        /// <param name="key"></param>
-        /// <returns></returns>
-        public static byte [] AesDecryptPayload (byte [] toEncryptArray, string key)
-        {
-            //閰嶇疆AES鍔犲瘑Key(瀵嗛挜銆佸悜閲忋�佹ā寮忋�佸~鍏�)
-            var rm = new RijndaelManaged {
-                Key = Encoding.UTF8.GetBytes (key),
-                IV = Encoding.UTF8.GetBytes (key),
-                Mode = CipherMode.CBC,
-                Padding = PaddingMode.PKCS7
-            };
-
-            //鍒涘缓AES瑙e瘑鍣ㄥ璞�
-            var cTransform = rm.CreateDecryptor ();
-
-            //浣跨敤AES灏嗗瘑鏂囨祦杞垚鏄庢枃鐨勫瓧鑺傛暟缁�
-            return cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length);
-        }
-        #endregion
-
 
     }
 }
-*/

--
Gitblit v1.8.0