From f500e14c0a994487070380c50c85e0929cbc8e63 Mon Sep 17 00:00:00 2001
From: JLChen <551775569@qq.com>
Date: 星期二, 05 一月 2021 10:48:04 +0800
Subject: [PATCH] 2021-01-05 1.更新

---
 Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs |  711 +++++++++++++++++++++++++++++++----------------------------
 1 files changed, 372 insertions(+), 339 deletions(-)

diff --git a/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs b/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
index 0d6fb64..18c142a 100644
--- a/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
+++ b/Crabtree/SmartHome/UI/SimpleControl/MqttCommon.cs
@@ -17,6 +17,11 @@
 {
     public static class MqttCommon
     {
+        /// <summary>
+        /// 鏄惁鎻愮ず 杩滅▼杩炴帴鐨勯敊璇俊鎭� 
+        /// </summary>
+        public static bool IfDEBUG = false;
+
         static string mqttEncryptKey = "";
         static string checkGatewayTopicBase64 = "";
         static RemoteMACInfo CurRemoteMACInfo = null;
@@ -45,7 +50,7 @@
         static MqttCommon ()
         {
             InitMqtt ();
-            InitCheckGateway ();
+            //InitCheckGateway ();
         }
 
         /// <summary>
@@ -57,8 +62,10 @@
             new System.Threading.Thread (async () => {
                 while (true) {
                     try {
-                        System.Threading.Thread.Sleep (100);
+                        System.Threading.Thread.Sleep (200);
                         if (!CommonPage.IsRemote) continue;
+
+                        if (Control.IsEnterBackground) continue;
 
                         await StartCloudMqtt ();
                         await CheckingSubscribeTopics ();
@@ -67,6 +74,15 @@
                 }
             }) { IsBackground = true }.Start ();
         }
+
+        public static void InitState ()
+        {
+            IfNeedReadAllDeviceStatus = true;
+            bNeedStartTip = true;
+            IsGatewayOnline = false;
+            StartCloudMqtt ();
+        }
+
 
         /// <summary>
         /// 鏄惁璁㈤槄鎴愬姛
@@ -83,6 +99,7 @@
             }
             try {
                 if (!isSubscribeTopicSuccess) {
+
 
                     var topicFilterCommon = new TopicFilter () {
                         Topic = $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/Common/#",
@@ -107,19 +124,36 @@
                         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 e) {
-               
+            } catch (Exception ex) {
+
+              
             }
         }
-
 
 
         /// <summary>
@@ -136,7 +170,7 @@
                     if (CommonPage.IsRemote) {
                         Utlis.ShowAppLinkStatus (AppLinkStatus.CloudUnlink);
                     }
-                    Utlis.WriteLine ($"============>MqttRemoteDisConnectRemoteMqttClient");
+                    //Utlis.WriteLine ($"============>MqttRemoteDisConnectRemoteMqttClient");
 
                 }
             } catch (Exception e) {
@@ -151,13 +185,10 @@
         static string PushSignStr = System.DateTime.Now.Ticks.ToString ();
 
 
-
-
-
         /// <summary>
         /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
         /// </summary>
-        static bool remoteMqttIsConnecting;
+        public static bool remoteMqttIsConnecting;
         static bool remoteIsConnected;
         /// <summary>
         /// 鍚姩杩滅▼Mqtt
@@ -177,169 +208,210 @@
             await System.Threading.Tasks.Task.Factory.StartNew (async () => {
                 try {
                     //lock (RemoteMqttClient) {
-                        //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺�
+                    //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺�
 
-                        #region 鍒濆鍖栬繙绋婱qtt
-                        //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
-                        if (RemoteMqttClient.ApplicationMessageReceivedHandler == null) {
-                            RemoteMqttClient.UseApplicationMessageReceivedHandler (async (e) => {
-                                try {
-                                    if (!RemoteMqttClient.IsConnected || !CommonPage.IsRemote) {
-                                        return;
+                    #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") {//缃戝叧鎺夌嚎                                                                                                                    //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
+                                    ReceiveNotifyGateWayOffline ();
+                                } else if (aesDecryptTopic == $"/BusGateWayToClient/{mMqttInfo.connEmqClientId}/Push/NotifySqueeze") {//璁㈤槄鎸や笅绾块棶棰�
+                                    await ReceiveNotifySqueezeAsync (aesDecryptPayload);
+                                } else if (aesDecryptTopic == $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/Common/CheckGateway") {
+                                    ReceiveCheckGatewayTopic ();
+                                } else {
+                                    SetGatewayOnlineResetCheck ();
+
+                                    if (!string.IsNullOrEmpty (mqttEncryptKey)) {
+                                        aesDecryptPayload = Shared.Securitys.EncryptionService.AesDecryptPayload (e.ApplicationMessage.Payload, mqttEncryptKey);
                                     }
-                                    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") {//缃戝叧鎺夌嚎                                                                                                                    //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
-                                        ReceiveNotifyGateWayOffline ();
-                                    } else if (aesDecryptTopic == $"/BusGateWayToClient/{mMqttInfo.connEmqClientId}/Push/NotifySqueeze") {//璁㈤槄鎸や笅绾块棶棰�
-                                        await ReceiveNotifySqueezeAsync (aesDecryptPayload);
-                                    }else if (aesDecryptTopic == $"/BusGateWayToClient/{CurRemoteMACInfo.macMark}/Common/CheckGateway") {
-                                        ReceiveCheckGatewayTopic ();
-                                    } else {
-                                        SetGatewayOnlineResetCheck ();
+                                    var packet = new Packet ();
+                                    packet.IsLocal = false;
+                                    packet.Bytes = aesDecryptPayload;
+                                    packet.Manager ();
 
-                                        if (!string.IsNullOrEmpty (mqttEncryptKey)) {
-                                            aesDecryptPayload = Shared.Securitys.EncryptionService.AesDecryptPayload (e.ApplicationMessage.Payload, mqttEncryptKey);
-                                        }
-
-                                        var packet = new Packet ();
-                                        packet.IsLocal = false;
-                                        packet.Bytes = aesDecryptPayload;
-                                        packet.Manager ();
-
-                                    }
-                                   
-                                } catch { }
-                            });
-                        }
-
-                        if (RemoteMqttClient.DisconnectedHandler == null) {
-                            RemoteMqttClient.UseDisconnectedHandler (async (e) => {
-                                Utlis.WriteLine ($"============>Mqtt杩滅▼杩炴帴鏂紑");
-                                isSubscribeTopicSuccess = false;
-                                await DisConnectRemoteMqttClient ("StartRemoteMqtt.DisconnectedHandler");
-                                //await StartRemoteMqtt();
-                                //if (thisShowTip) {
-                                //    if (CommonPage.IsRemote) {
-                                //        Application.RunOnMainThread (() => {
-                                //            MainPage.Loading.Hide ();
-                                //        });
-                                //    }
-                                //} else {
-                                //    thisShowTip = true;
-                                //}
-                            });
-                        }
-                        if (RemoteMqttClient.ConnectedHandler == null) {
-                            RemoteMqttClient.UseConnectedHandler (async (e) => {
-                                IfNeedReadAllDeviceStatus = true;
-
-                                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 {
-                                        //缃戝叧鍦ㄧ嚎
+                            } catch { }
+                        });
+                    }
 
-                                        //閲嶆柊涓�娆℃墍鏈夎澶囩姸鎬�
-                                        IfNeedReadAllDeviceStatus = false;
-                                        Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus ();
-                                        //
-                                        MqttRemoteSend (new byte [] { 0 }, 3);
+                    if (RemoteMqttClient.DisconnectedHandler == null) {
+                        RemoteMqttClient.UseDisconnectedHandler (async (e) => {
+                            Utlis.WriteLine ($"============>Mqtt杩滅▼杩炴帴鏂紑");
+                            isSubscribeTopicSuccess = false;
+                            await DisConnectRemoteMqttClient ("StartRemoteMqtt.DisconnectedHandler");
+                        });
+                    }
+                    if (RemoteMqttClient.ConnectedHandler == null) {
+                        RemoteMqttClient.UseConnectedHandler (async (e) => {
+                            //IfNeedReadAllDeviceStatus = true;
+                            mCheckGatewayTime = DateTime.Now;
+                            CheckGatewayCount = 0;
+                            bNeedStartTip = true;
+
+                            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 (CurRemoteMACInfo.isValid == "InValid") {
-                                    //    MainPage.AddTip ("Remote failed,gateway offline");
-                                    //} else {
-                                    //    MqttRemoteSend (new byte [] { 0 }, 3);
-                                    //}
+                                    if (CommonPage.IsRemote) {
+                                        MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
+                                    }
                                 }
-
-
-                            });
-                        }
-                        #endregion
+                            }
+                        });
+                    }
+                    #endregion
                     //}
-
-                        mqttRequestParToken = MainPage.LoginUser.LoginTokenString;
-                        //--绗竴姝ワ細鑾峰彇mqtt閾炬帴鍙傛暟
-                        var mqttInfoRequestResult = new ResponsePack () { StateCode = "" };
-                        //--鍒ゆ柇鏄綋鍓嶆槸鍚﹀垎浜殑浣忓畢
-                        if (!UserConfig.Instance.CurrentRegion.IsOthreShare) {
-                            var mqttInfoUrl = $"{MainPage.RequestHttpsHost}/EmqMqtt/GetConnMqttInfo";//鑾峰彇杩炴帴杩滅▼浜戠Emq Mqtt 鏈嶅姟鍣ㄨ繛鎺ヤ俊鎭�
-                            var mqttInfoRequestPar = new GetConnMqttInfoObj () {
-                                LoginAccessToken = mqttRequestParToken,
-                                PlatformStr = "L1",
-                                PublishPayloadJsonStr = PushSignStr,
-                            };
-                            mqttInfoRequestResult = MainPage.RequestHttps ("", Newtonsoft.Json.JsonConvert.SerializeObject (mqttInfoRequestPar), mqttInfoUrl);
-                            if (mqttInfoRequestResult != null && mqttInfoRequestResult.ResponseData != null) {
-                                var mqttInfoRequestResult_info = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttInfo> (mqttInfoRequestResult.ResponseData.ToString ());
-                                if (mqttInfoRequestResult_info != null) {
-                                    mMqttInfo = mqttInfoRequestResult_info;
-                                    //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
-                                    var gatewayListUrl = $"{MainPage.RequestHttpsHostMqtt}/Center/Center/GetGatewayPagger"; //App銆丅uspro杞欢鐧诲綍鍚庤幏鍙栫綉鍏冲垪琛� http 璇锋眰
-                                    var gatewayListRequestPar = new RemoteRequestParameters () { LoginAccessToken = mqttRequestParToken, RequestVersion = "RequestVersion1", RequestProtocolType = 0, RequestSource = 1 };
-                                    var gatewayListRequestResult = MainPage.RequestHttps ("", Newtonsoft.Json.JsonConvert.SerializeObject (gatewayListRequestPar), gatewayListUrl);
-                                    var gatewayListRequestResult_Obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttRemoteInfo> (gatewayListRequestResult.ResponseData.ToString ());
-                                    //--鎵惧嚭鏄惁瀛樺湪鍖归厤褰撳墠浣忓畢鐨刴ac锛屽瓨鍦ㄥ啀杩涜杩滅▼銆�
-                                    if (UserConfig.Instance.CheckHomeGatewaysNotEmpty ()) {
-                                        CurRemoteMACInfo = gatewayListRequestResult_Obj.pageData.Find ((obj) => obj.mac == UserConfig.Instance.CurrentRegion.HomeGateways [0].GatewayUniqueId);
-                                        //CurRemoteMACInfo = gatewayListRequestResult_Obj.pageData [0];
-                                        await MQTTConnectAsync ();
-
-                                    } else {
-                                        Utlis.WriteLine ("============>Mqtt 鍙栨秷杩炴帴锛屽綋鍓嶄綇瀹呮病缁戝畾缃戝叧");
-                                    }
-
-                                }
-
-                            }
-                        } else {
-                            //濡傛灉鏄垎浜繃鏉ョ殑浣忓畢 璧颁笅闈㈡祦绋�
-                            var mqttInfoRequestPar = new ShareMemberConnMqttInfoObj () {
-                                LoginAccessToken = mqttRequestParToken,
-                                PlatformStr = "L1",
-                                PublishPayloadJsonStr = PushSignStr,
-                                MainUserDistributedMark = UserConfig.Instance.CurrentRegion.MainUserDistributedMark,
-                                HomeId = UserConfig.Instance.CurrentRegion.Id
-                            };
-                            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 ();
-
-                                }
-
-                            }
-                        }
+                    //鎻愮ず姝e湪鑾峰彇杩炴帴鍙傛暟..."
+                    ShowStartTip ();
+                    mqttRequestParToken = MainPage.LoginUser.LoginTokenString;
+                    //--鍒ゆ柇鏄綋鍓嶆槸鍚﹀垎浜殑浣忓畢
+                    if (!UserConfig.Instance.CurrentRegion.IsOthreShare) {
+                        //涓昏处鍙疯幏鍙朚QTT 杩滅▼閾炬帴淇℃伅锛屽苟杩炴帴
+                        await GetMqttInfoAndMQTTConnectAsync ();
+                    } else {
+                        //濡傛灉鏄垎浜繃鏉ョ殑浣忓畢 璧颁笅闈㈡祦绋�
+                        await GetShareMqttInfoAndMQTTConnectAsync ();
+                    }
 
                 } catch (Exception ex) {
-                    Utlis.WriteLine ($"============>Mqtt 杩滅▼杩炴帴閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
+                    //Utlis.WriteLine ($"============>Mqtt 杩滅▼杩炴帴閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
+
+                    MainPage.LoadingTipShow ("Connect error, trying to reconnect.");
+
+                    if (IfDEBUG) {
+                        MainPage.ShowAlertOnMainThread ("error: " + ex.Message);
+                    }
+
                 } finally {
                     //鏈�缁堣閲婃斁杩炴帴鐘舵��
                     remoteMqttIsConnecting = false;
+
+                    MainPage.LoadingTipHide ();
+
+                    //MainPage.LoadingHide ();
                 }
             });
+        }
+
+        /// <summary>
+        /// 涓昏处鍙疯幏鍙朚QTT 杩滅▼閾炬帴淇℃伅锛屽苟杩炴帴
+        /// </summary>
+        /// <returns></returns>
+        static async Task GetMqttInfoAndMQTTConnectAsync ()
+        {
+            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 (mqttInfoRequestResult != null && mqttInfoRequestResult.ResponseData != null) {
+                try {
+                    var mqttInfoRequestResult_Obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttInfo> (mqttInfoRequestResult.ResponseData.ToString ());
+
+                    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");
+
+                                MainPage.LoadingTipShow ("Please wait, failed to get gateway parameters.");
+                            }
+                        }
+
+                    } 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 {
+
+                }
+            } else {
+                //Utlis.WriteLine ("============>Mqtt GetInfo 澶辫触");
+                MainPage.AddTip ("Please wait, failed to get parameters.");
+                //MainPage.LoadingTipShow ("Please wait, failed to get parameters.");
+            }
+
+        }
+
+        /// <summary>
+        /// 瀛愯处鍙疯幏鍙朚QTT 杩滅▼閾炬帴淇℃伅锛屽苟杩炴帴
+        /// </summary>
+        /// <returns></returns>
+        static async Task GetShareMqttInfoAndMQTTConnectAsync ()
+        {
+            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.");
+                }
+            }
         }
 
         /// <summary>
@@ -347,94 +419,109 @@
         /// </summary>
         static async Task MQTTConnectAsync ()
         {
-
             if (CurRemoteMACInfo != null && mMqttInfo != null) {
-                var url = mMqttInfo.connEmqDomainPort;
-                var clientId = mMqttInfo.connEmqClientId;
-                var username = mMqttInfo.connEmqUserName;
-                var passwordRemote = mMqttInfo.connEmqPwd;
 
-                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 ();
+             
+                //鑾峰彇鍙傛暟鎴愬姛锛屽紑濮嬭繛鎺�...
+                //MainPage.AddTip ("Successfully obtained parameters, starting to connect...");
 
-                await DisConnectRemoteMqttClient ("StartRemoteMqtt");
-                await RemoteMqttClient.ConnectAsync (options1);
-                remoteIsConnected = true;
-                IsDisConnectingWithSendCatch = false;
-                //await MqttRemoteSend (new byte [] { 0 }, 1);
-                //await MqttRemoteSend (new byte [] { 0 }, 2);
-                //await MqttRemoteSend (new byte [] { 0 }, 4);
+                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);
+                }
 
             }
         }
 
-
-        ///// <summary>
-        ///// 
-        ///// </summary>
-        ///// <param name="message">闄勫姞鏁版嵁鍖�</param>
-        ///// <param name="optionType">鎿嶄綔绫诲瀷锛�0=缃戝叧鎺у埗锛�1=璁㈤槄缃戝叧鏁版嵁;2=璁㈤槄缃戝叧涓婄嚎鏁版嵁;3=璁㈤槄缃戝叧鏄惁鍦ㄧ嚎涓婚  4=璁㈤槄鎸や笅绾夸富棰� </param>
-        ///// <returns></returns>
-        //public static async Task MqttRemoteSend (byte [] message, int optionType = 0)
-        //{
-        //    try {
-        //        if (!remoteIsConnected) {
-        //            Utlis.WriteLine ($"============>Mqtt 鏈繛鎺� 鍙栨秷鍙戦��");
-        //            return;
-        //        }
-
-        //        var topicName = @"/" + MainPage.LoginUser.AccountString.ToLower () + @"/" + UserConfig.Instance.GatewayMAC.Replace (".", "") + @"/" + currentGuid;
-        //        switch (optionType) {
-        //        case 0:
-        //            var messageSend = message;
-        //            if (string.IsNullOrEmpty (mqttEncryptKey)) {
-        //                topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/OldON";
-        //            } else {
-        //                topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/NewON";
-        //                messageSend = Shared.Securitys.EncryptionService.AesEncryptPayload (message, mqttEncryptKey);
-        //            }
-        //            //base64鍔犲瘑
-        //            var m = new MqttApplicationMessage { Topic = topicName, Payload = messageSend, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
-        //            //if (remoteIsConnected) {
-        //            try {
-        //                RemoteMqttClient.PublishAsync (m);
-        //            } catch (Exception e) {
-        //                //await DisConnectRemoteMqttClient (e.Message);
-        //                //await StartCloudMqtt ();
-        //                //if (remoteIsConnected) {
-        //                //    RemoteMqttClient.PublishAsync (m);
-        //                //}
-        //            }
-        //            //}
-        //            break;
-        //        case 3:
-        //            topicName = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/CheckGateway";
-
-        //            var m1 = new MqttApplicationMessage { Topic = topicName, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
-
-        //            try {
-        //                Utlis.WriteLine ("CheckGateway");
-        //                RemoteMqttClient.PublishAsync (m1);
-        //            } catch (Exception e) {
-        //                Utlis.WriteLine ($"CheckGateway Fail:{e.Message}");
-        //                //await DisConnectRemoteMqttClient (e.Message);
-        //                //await StartCloudMqtt ();
-        //            }
-        //            break;
-        //        }
-
-
-        //    } catch (Exception e) {
-
-        //    }
-        //}
+        /// <summary>
+        /// 浠庡紑濮嬪埌杩炴帴鎴愬姛锛屽彧鎻愮ず1娆�
+        /// </summary>
+        static bool bNeedStartTip = true;
+        /// <summary>
+        /// 姝e湪鑾峰彇杩炴帴鍙傛暟...
+        /// </summary>
+        static void ShowStartTip ()
+        {
+            if (bNeedStartTip) {
+                bNeedStartTip = false;
+                if (CommonPage.IsRemote) {
+                    //MainPage.AddTip ("Getting remote connection parameters...");
+                    MainPage.LoadingTipShow ("Please wait, getting connection parameters...");
+                }
+            }
+        }
 
         /// <summary>
         /// 
@@ -479,8 +566,6 @@
         /// SendCatch 鍚庢墽琛屼竴娆℃柇寮�鎿嶄綔
         /// </summary>
         static bool IsDisConnectingWithSendCatch = false;
-
-     
 
         /// <summary>
         /// 鍒嗕韩浣忓畢 鑾峰彇褰撳墠浣忓畢缃戝叧淇℃伅骞朵笖杩炴帴MQTT 鎴栬�呭埛鏂�  
@@ -531,6 +616,8 @@
                     if (mGatewayRes != null) {
                         CurRemoteMACInfo.aesKey = mGatewayRes.AesKey;
                         mqttEncryptKey = CurRemoteMACInfo.aesKey;
+                    } else {
+                        MainPage.LoadingTipShow ("Please wait, failed to get gateway parameters.");
                     }
 
                 }
@@ -561,25 +648,8 @@
                     Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus ();
                 }
             }
-
-            //褰撳墠浣忓畢涓嶆槸鍒嗕韩鏉�
-            if (!UserConfig.Instance.CurrentRegion.IsOthreShare) {
-
-                var gatewayListUrl = $"{MainPage.RequestHttpsHostMqtt}/Center/Center/GetGatewayPagger"; //App銆丅uspro杞欢鐧诲綍鍚庤幏鍙栫綉鍏冲垪琛� http 璇锋眰
-                var gatewayListRequestPar = new RemoteRequestParameters () { Mac = CurRemoteMACInfo.mac, LoginAccessToken = mqttRequestParToken, RequestVersion = "RequestVersion1", RequestProtocolType = 0, RequestSource = 1 };
-                var gatewayListRequestResult = MainPage.RequestHttps ("", Newtonsoft.Json.JsonConvert.SerializeObject (gatewayListRequestPar), gatewayListUrl);
-                var gatewayListRequestResult_Obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttRemoteInfo> (gatewayListRequestResult.ResponseData.ToString ());
-                if (gatewayListRequestResult_Obj != null && gatewayListRequestResult_Obj.pageData.Count > 0) {
-                    var mData = gatewayListRequestResult_Obj.pageData.Find ((obj) => obj.mac == UserConfig.Instance.CurrentRegion.HomeGateways [0].GatewayUniqueId);
-                    if (mData != null) {
-                        CurRemoteMACInfo.aesKey = mData.aesKey;
-                        mqttEncryptKey = CurRemoteMACInfo.aesKey;
-                    }
-                }
-            } else {
-                GetSingleHomeGatewayPaggerAndMQTTConnectAsync (false);
-            }
-
+            //璇锋眰鍒锋柊涓�娆� 缃戝叧鍔犲瘑Key
+            await GetSingleHomeGatewayPaggerAndMQTTConnectAsync (false);
         }
         /// <summary>
         /// 鏀跺埌缃戝叧鎺夌嚎淇℃伅
@@ -621,48 +691,48 @@
 
         //}
 
-        /// <summary>
-        /// 瀹氭椂妫�娴嬬綉鍏虫槸鍚﹀湪绾�
-        /// 1.绾跨▼浼戠湢闂撮殧5s
-        /// 2.鍙戦�丆heckGateway闂撮殧涓�9S锛屾敹鍒颁富棰樺埛鏂拌鏃堕棿锛岄噸缃彂閫佹鏁�
-        /// 3.鍙戦�佹鏁板埌杈�3娆′互涓婏紝鍒欏垽瀹氱綉鍏充负绂荤嚎鐘舵��
-        /// </summary>
-        /// <returns></returns>
-        static void InitCheckGateway ()
-        {
-            new System.Threading.Thread (async () => {
-                while (true) {
-                    try {
+//        /// <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 (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
+//                            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 { }
+//                        System.Threading.Thread.Sleep (5500);
+//                    } catch { }
 
-                }
-            }) { IsBackground = true }.Start ();
-        }
+//                }
+//            }) { IsBackground = true }.Start ();
+//        }
 
        
         /// <summary>
@@ -671,50 +741,8 @@
         static void ReceiveCheckGatewayTopic () {
             //Utlis.WriteLine ("============>Mqtt CheckGateway缃戝叧鍥炲");
             SetGatewayOnlineResetCheck ();
-          
-
-
-            //鏃х綉鍏虫柟娉�
-            //MainPage.WiFiStatus = "CrabtreeAdd/CloudUnlink.png";
-            //// = $"/ClientToBusGateWay/{CurRemoteMACInfo.macMark}/Common/OldON";
-            //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 ("Gateway offline");
-            //    //Application.RunOnMainThread (() => {
-            //    //    Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
-            //    //});
-            //    break;
-            //case "NoRecord"://MAC涓嶆纭�
-            //    MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.MACError));
-            //    //Application.RunOnMainThread (() => {
-            //    //    Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
-            //    //});
-            //    break;
-            //case "Success":
-            //    MainPage.AddTip (UserConfig.Instance.CurrentRegion.Name + ":" + Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
-            //    MainPage.WiFiStatus = "CrabtreeAdd/CloudLink.png";
-            //    break;
-            //default:
-            //    MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkLoser));
-            //    //Application.RunOnMainThread (() => {
-            //    //    Shared.SimpleControl.Phone.UserMiddle.LinkStatusTip.BackgroundColor = SkinStyle.Current.DelColor;
-            //    //});
-            //    break;
-            //}
-            //Application.RunOnMainThread (() => {
-            //    UserMiddle.btnLinkStatus.UnSelectedImagePath = MainPage.WiFiStatus;
-            //});
         }
         
-
-
         /// <summary>
         /// 鏀跺埌鎸や笅绾挎帹閫�
         /// </summary>
@@ -723,7 +751,6 @@
             Utlis.WriteLine ($"============>MqttNotifySqueeze: {ErrorCode.LoginInAnotherDevice}");
             var mMes = CommonPage.MyEncodingUTF8.GetString (mes);
             if (mMes == PushSignStr) return;//鏄嚜宸辩殑鐧诲綍鎺ㄩ�佷笉澶勭悊
-
 
             CommonPage.IsRemote = false;
 
@@ -741,7 +768,6 @@
             MainPage.ShowAlertOnMainThread (ErrorCode.LoginInAnotherDevice);
 
             Application.RunOnMainThread (() => {
-               
                 MainPage.WiFiStatus = "CrabtreeAdd/WiFi.png";
                 UserMiddle.btnLinkStatus.UnSelectedImagePath = MainPage.WiFiStatus;
                 new AccountLogin ().Show ();
@@ -754,7 +780,6 @@
 
 public class ShareMemberConnMqttInfoObj : GetConnMqttInfoObj
 {
-
     /// <summary>
     /// 涓讳汉鐢ㄦ埛Id 
     /// </summary>
@@ -781,6 +806,10 @@
     /// 
     /// </summary>
     public string PublishPayloadJsonStr = "";
+    /// <summary>
+    /// Mac
+    /// </summary>
+    public string Mac = "";
 }
 
 public class RemoteRequestParameters
@@ -814,6 +843,8 @@
     public string connEmqClientId;
     public string connEmqUserName;
     public string connEmqPwd;
+
+    public List<RemoteMACInfo> AccountAllGateways;
 }
 
 public class RemoteMACInfo
@@ -827,6 +858,8 @@
     public string projectName;
     public string userName;
 
+    public string clientId;
+
     //app鑷畾涔夋暟鎹�
     public string md5_mac_string;
     public string LoginAccessToken;

--
Gitblit v1.8.0