From 5174e95a428876018ce3372f3dbc24b2861ea472 Mon Sep 17 00:00:00 2001
From: 黄学彪 <hxb@hdlchina.com.cn>
Date: 星期三, 20 十一月 2019 16:11:54 +0800
Subject: [PATCH] 11.20

---
 ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs |  670 +++++++++++++++++++++++++++----------------------------
 1 files changed, 328 insertions(+), 342 deletions(-)

diff --git a/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs
old mode 100755
new mode 100644
index a600b98..fb5ce73
--- a/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs
+++ b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs
@@ -8,10 +8,11 @@
 using System.Net.Sockets;
 using System.Net;
 using Newtonsoft.Json.Linq;
-using MQTTnet.Core.Client;
 using MQTTnet;
 using Shared.Common;
 using Shared.Phone.UserView;
+using MQTTnet.Client;
+using System.Threading.Tasks;
 
 namespace ZigBee.Device
 {
@@ -25,6 +26,8 @@
         {
             this.Type = DeviceType.ZbGateway;
         }
+
+
 
         #region 缃戝叧鐗规畩淇℃伅澶勭悊
         /// <summary>
@@ -52,16 +55,10 @@
         }
 
         /// <summary>
-        /// 杩滅▼缃戝叧
+        /// 鏄惁浣跨敤杩滅▼杩炴帴妯″紡
         /// </summary>
         /// <value><c>true</c> if is remote; otherwise, <c>false</c>.</value>
-        public static bool IsRemote
-        {
-            get
-            {
-                return ZigBee.Device.ZbGateway.RemoteMqttClient != null && ZigBee.Device.ZbGateway.RemoteMqttClient.IsConnected;
-            }
-        }
+        public static bool IsRemote;
 
         /// <summary>
         /// 缃戝叧淇濆瓨璺緞
@@ -3077,15 +3074,12 @@
         /// <summary>
         /// 灞�鍩熺綉鐨凪QTT
         /// </summary>
-        IMqttClient mqttClient;
+        IMqttClient localMqttClient = new MqttFactory().CreateMqttClient();
+        bool localMqttIsConnecting;
         /// <summary>
         /// 鎵嬫満鏍囪瘑
         /// </summary>
         static Guid currentGuid = Guid.NewGuid();
-        /// <summary>
-        /// 灞�鍩熺綉鐨凪QTT鏄惁姝e湪杩炴帴
-        /// </summary>
-        object mqttIsConnecting = false.ToString();
 
         public async System.Threading.Tasks.Task StartLocalMqtt(string brokerName)
         {
@@ -3093,39 +3087,45 @@
             {
                 try
                 {
-                    lock (mqttIsConnecting)
+                    lock (localMqttClient)
                     {
-                        if (mqttIsConnecting.ToString() == true.ToString() || brokerName == null)
+                        if (localMqttIsConnecting
+                        || !Shared.Common.Config.Instance.IsLogin
+                        || Shared.Common.Config.Instance.HomeId == ""
+                        || localMqttClient.IsConnected)
                         {
                             return;
                         }
-                        mqttIsConnecting = true.ToString();
 
-                        if (mqttClient == null)
+                        //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺�
+                        localMqttIsConnecting = true;
+
+                        //(3)褰揫杩炴帴Mqtt鎴愬姛鍚嶿鎴栬�匸Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒版暟鎹寘鍝嶅簲鏃跺湪mqttClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
+                        if (localMqttClient.ApplicationMessageReceivedHandler == null)
                         {
-                            //(2)鍒涘缓Mqtt瀹㈡埛绔�
-                            mqttClient = new MqttClientFactory().CreateMqttClient();
-                            //(3)褰揫杩炴帴Mqtt鎴愬姛鍚嶿鎴栬�匸Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒版暟鎹寘鍝嶅簲鏃跺湪mqttClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
-                            mqttClient.ApplicationMessageReceived += (sender, e) =>
-                            {
-                                if (mqttClient == null || !mqttClient.IsConnected)
+                            localMqttClient.UseApplicationMessageReceivedHandler((e) =>
                                 {
-                                    return;
-                                }
-                                mqttClient_MqttMsgPublishReceived(sender, e);
-                            };
-                            mqttClient.Disconnected += (sender, e) =>
+                                    if (!localMqttClient.IsConnected)
+                                    {
+                                        return;
+                                    }
+                                    mqttClient_MqttMsgPublishReceived(e);
+                                });
+                        }
+
+                        if (localMqttClient.DisconnectedHandler == null)
+                        {
+                            localMqttClient.UseDisconnectedHandler((e) =>
                             {
                                 IsEncry = false;
-#if DEBUG
-                                DebugPrintLog($" 鏈湴杩炴帴鏂紑_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}_{System.DateTime.Now.ToString()}");
-#endif
-                            };
-                            mqttClient.Connected += async (sender, e) =>
+                                DebugPrintLog($" 鏈湴杩炴帴鏂紑_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}");
+                            });
+                        }
+                        if (localMqttClient.ConnectedHandler == null)
+                        {
+                            localMqttClient.UseConnectedHandler(async (e) =>
                             {
-#if DEBUG
-                                DebugPrintLog($" 鏈湴杩炴帴鎴愬姛_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}_褰撳墠瀵嗙爜:{Password}_{System.DateTime.Now.ToString()}");
-#endif
+                                DebugPrintLog($" 鏈湴杩炴帴鎴愬姛_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}_褰撳墠瀵嗙爜:{Password}");
 
                                 if (PubKey != null)
                                 {
@@ -3142,57 +3142,128 @@
                                 }
                                 Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.WIFI);
                                 System.Console.WriteLine($"褰撳墠鏄綉鍏砏i-Fi鍦ㄩ�氳_{System.DateTime.Now.ToString()}");
-
-                            };
-                        }
-
-                        if (RemoteMqttClient != null && RemoteMqttClient.IsConnected == true)
-                        {
-                            RemoteMqttClient?.DisconnectAsync();
-                            System.Console.WriteLine($"鏀跺埌灞�鍩熺綉缃戝叧锛岃繙绋嬭繛鎺ヤ富鍔ㄦ柇寮�_{System.DateTime.Now.ToString()}");
-                            RemoteMqttClient = null;
-                        }
-
-                        if (mqttClient.IsConnected)
-                        {
-                            return;
+                            });
                         }
                     }
-                    //(1)杩炴帴鍒癕qtt瀹㈡埛绔繛鎺ュ弬鏁�
-                    var connectCloudMqttClientOptions = new MqttClientTcpOptions
-                    {
-                        Server = brokerName,    //ip鍦板潃
-                        ClientId = currentGuid.ToString(),
-                        CleanSession = true,// 璁剧疆鏄惁娓呯┖session,杩欓噷濡傛灉璁剧疆涓篺alse琛ㄧず鏈嶅姟鍣ㄤ細淇濈暀瀹㈡埛绔殑杩炴帴璁板綍锛岃繖閲岃缃负true琛ㄧず姣忔杩炴帴鍒版湇鍔″櫒閮戒互鏂扮殑韬唤杩炴帴
-                        KeepAlivePeriod = new TimeSpan(0, 5, 0),//璁剧疆蹇冭烦鏃堕棿锛堟渶澶у�硷紝2^16-1 = 65535绉� = 18灏忔椂銆傛渶灏忓�煎彲浠ヤ负0锛岃〃绀哄鎴风涓嶆柇寮�銆備竴鑸涓哄嚑鍒嗛挓锛屾瘮濡傚井淇″績璺冲懆鏈熶负300绉掋�傦級
-                        DefaultCommunicationTimeout = new TimeSpan(0, 0, 100),//璁剧疆瓒呮椂鏃堕棿
-                    };
-                    await mqttClient.ConnectAsync(connectCloudMqttClientOptions);
+
+                    var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()
+                                   .WithClientId(currentGuid.ToString())
+               .WithTcpServer(brokerName, 1883)
+               .WithKeepAlivePeriod(TimeSpan.FromSeconds(20))
+               .WithCleanSession()
+               .WithCredentials("", "")
+               .Build();
+                    await localMqttClient.ConnectAsync(options, CancellationToken.None);
                 }
                 catch (Exception ex)
                 {
-#if DEBUG
                     DebugPrintLog($"灞�鍩熺綉閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
-#endif
                 }
                 finally
                 {
-                    mqttIsConnecting = false.ToString();
+                    localMqttIsConnecting = false;
                 }
             });
+        }
+
+        class GateWayBaseInfomation
+        {
+            //public string GatewayUniqueId;//"Emq缃戝叧1",   <!-- 缃戝叧Mac -->
+            public bool MqttOnlineStatus;//: true,  <!-- 缃戝叧鍦ㄤ簯绔疎mq鏄惁鍦ㄧ嚎 -->
+            public string AesKey;// : "a5d8da8a-ddea-48",  <!-- 涓庢缃戝叧鍦ㄤ簯绔疎mq閫氫俊鏃讹紝璐熻浇鍔犺В鐨�16浣岮es瀵嗛挜 -->
+            public string MacMark;//: "61eaa0ea-4812-4a7a-86d6-3098c61e64ed"   <!-- 缃戝叧瀵瑰簲鐨勫敮涓�鐮� -->
+        }
+        /// <summary>
+        /// 褰撳墠鏈夊笎鍙蜂笅鎵�鏈夌殑缃戝叧鍒楄〃鍙婁俊鎭�
+        /// </summary>
+        static Dictionary<string, GateWayBaseInfomation> GateWayBaseInfomations = new Dictionary<string, GateWayBaseInfomation> { };
+        /// <summary>
+        /// 鑾峰彇褰撳墠甯愬彿鎵�鏈夌殑缃戝叧淇℃伅
+        /// </summary>
+        /// <returns></returns>
+        static async System.Threading.Tasks.Task initGateWayBaseInfomation()
+        {
+            try
+            {
+
+                var jsonData = new Dictionary<string, object>
+                {
+                    ["RequestVersion"] = "RequestVersion",
+                    //["RequestSource"] = 0,
+                    ["ReqDto.LoginAccessToken"] = Shared.Phone.UserCenter.UserCenterLogic.GetConnectMainToken(),
+                    ["ReqDto.HomeId"] = Config.Instance.Home.Id,
+                    ["ReqDto.PageSetting.PageSize"] = 30,
+                    ["IsOtherAccountCtrl "] = Shared.Phone.UserCenter.UserCenterResourse.UserInfo.AuthorityNo != 1
+                };
+                var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData));
+
+                var result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/App/GetSingleHomeGatewayPagger", bytes, Config.Instance.Token);
+                {
+                    //  "ResponseVersion": "RequestVersion1",
+                    //  "StateCode": "Success",
+                    //  "ErrorInfo": null,
+                    //  "ResponseData": {
+                    //  "PageData": [
+                    //  {   <!-- Emq鏂扮綉鍏� -->
+                    //        "GatewayUniqueId": "Emq缃戝叧1",   <!-- 缃戝叧Mac -->
+                    //        "MqttOnlineStatus": true,  <!-- 缃戝叧鍦ㄤ簯绔疎mq鏄惁鍦ㄧ嚎 -->
+                    //        "AesKey": "a5d8da8a-ddea-48",  <!-- 涓庢缃戝叧鍦ㄤ簯绔疎mq閫氫俊鏃讹紝璐熻浇鍔犺В鐨�16浣岮es瀵嗛挜 -->
+                    //        "MacMark": "61eaa0ea-4812-4a7a-86d6-3098c61e64ed"   <!-- 缃戝叧瀵瑰簲鐨勫敮涓�鐮� -->
+                    //      },
+                    //      {  <!-- 鏃qtt缃戝叧,璇峰崌绾х‖浠讹紝濡傛灉涓嶅崌绾э紝鎺у埗杩樻槸璧拌�佺殑 -->
+                    //        "GatewayUniqueId": "鏃х綉鍏�1",
+                    //        "MqttOnlineStatus": false,
+                    //        "AesKey": null,
+                    //        "MacMark": null
+                    //      }
+                    //    ],
+                    //    "PageIndex": 0,
+                    //    "PageSize": 15,
+                    //    "TotalCount": 2,
+                    //    "TotalPages": 1,
+                    //    "HasPreviousPage": false,
+                    //    "HasNextPage": false
+                    //  }
+                    //}
+                    if (result != null)
+                    {
+                        var jobject = Newtonsoft.Json.Linq.JObject.Parse(Encoding.UTF8.GetString(result));
+                        var responseData = jobject["ResponseData"];
+                        if (responseData != null)
+                        {
+                            if (responseData["PageData"] != null)
+                            {
+                                var list = JArray.Parse(responseData["PageData"].ToString());
+                                foreach (var v in list)
+                                {
+                                    GateWayBaseInfomations[v["GatewayUniqueId"].ToString()] = new GateWayBaseInfomation { AesKey = v["AesKey"].ToString(), MacMark = v["MacMark"].ToString(), MqttOnlineStatus = bool.Parse(v["MqttOnlineStatus"].ToString()) };
+                                    if (RemoteMqttClient.IsConnected)
+                                    {
+                                        await RemoteMqttClient.SubscribeAsync($"/ZigbeeGateWayToClient/{v["MacMark"].ToString()}/#", MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
+                                    }
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+            catch { }
+
         }
 
         /// <summary>
         /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
         /// </summary>
-        static bool remoteMqttIsConnecting; static bool IsLoginAgain;
+        static bool remoteMqttIsConnecting;
+        static bool IsLoginAgain;
         /// <summary>
         /// 杩滅▼MqttClient
         /// </summary>
-        public static IMqttClient RemoteMqttClient;
+        public static IMqttClient RemoteMqttClient= new MqttFactory().CreateMqttClient();
         private int IsLogin = 0;
         [Newtonsoft.Json.JsonIgnore]
         static Action actionTemp;
+
         /// <summary>
         /// 鍚姩杩滅▼Mqtt
         /// </summary>
@@ -3204,133 +3275,137 @@
             {
                 try
                 {
-                    if (remoteMqttIsConnecting || Shared.Common.Config.Instance.HomeId == "")
+                    lock (RemoteMqttClient)
                     {
-                        return;
-                    }
-                    remoteMqttIsConnecting = true;
-
-                    var url = Shared.Common.Config.Instance.ZigbeeMqttBrokerLoadSubDomain;//.Replace("6688","6689");
-                    if (string.IsNullOrEmpty(url) || !url.StartsWith("tcp://") || url.Split(':').Length != 3)
-                    {
-                        remoteMqttIsConnecting = false;
-                        return;
-                    }
-                    if (RemoteMqttClient == null)
-                    {
-                        //(2)鍒涘缓Mqtt瀹㈡埛绔�
-                        RemoteMqttClient = new MqttClientFactory().CreateMqttClient();
-                        //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
-                        RemoteMqttClient.ApplicationMessageReceived += (sender, e) =>
+                        if (remoteMqttIsConnecting
+                        || !Shared.Common.Config.Instance.IsLogin
+                        || Shared.Common.Config.Instance.HomeId == ""
+                        || RemoteMqttClient.IsConnected)
                         {
-                            if (RemoteMqttClient == null || !RemoteMqttClient.IsConnected)
-                            {
-                                return;
-                            }
-                            mqttRemoteClient_MqttMsgPublishReceived(sender, e);
-                        };
-                        RemoteMqttClient.Disconnected += (sender, e) =>
-                        {
-#if DEBUG
-                            DebugPrintLog($"杩滅▼杩炴帴鏂紑_{System.DateTime.Now.ToString()}");
-#endif
-                        };
-                        RemoteMqttClient.Connected += async (sender, e) =>
-                        {
-#if DEBUG
-                            DebugPrintLog($"杩滅▼杩炴帴鎴愬姛_{System.DateTime.Now.ToString()}");
-#endif
-                            Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.Remote);
-                            //娌℃湁涓荤綉鍏虫椂涓诲姩璇诲彇锛岃幏鍙栦富缃戝叧淇℃伅
-                            var gateWayList = GateWayList.FindAll(obj => obj.getGatewayBaseInfo.HomeId == Shared.Common.Config.Instance.HomeId);
-                            if (gateWayList.Find(obj => obj.getGatewayBaseInfo.IsMainGateWay == true) == null)
-                            {
-                                if (gateWayList.Count == 1)
-                                {
-                                    gateWayList[0].getGatewayBaseInfo.IsMainGateWay = true;
-                                }
-                                else
-                                {
-                                    for (int i = 0; i < gateWayList.Count; i++)
-                                    {
-                                        var gateWay = gateWayList[i];
-                                        var info = await gateWay.GetZbGwInfoAsync();
-                                        if (info == null || info.getGwData == null)
-                                        {
-                                            continue;
-                                        }
-                                        if (info.getGwData.IsDominant == 1)
-                                        {
-                                            gateWay.getGatewayBaseInfo.IsMainGateWay = true;
-                                            for (int j = i + 1; j < gateWayList.Count; j++)
-                                            {
-                                                gateWayList[j].getGatewayBaseInfo.IsMainGateWay = false;
-                                            }
-                                            break;
-                                        }
-                                    }
-                                }
-                            }
-                        };
-                    }
-
-                    if (RemoteMqttClient.IsConnected)
-                    {
-                        //褰撶綉鍏崇殑杩炴帴鏂瑰紡鏀瑰彉鏃�,妫�娴嬬綉鍏�,鐒跺悗鏄剧ず鐗规晥(鍙噸澶嶈皟鐢�)
-                        return;
-                    }
-                    for (int i = 0; i < GateWayList.Count; i++)
-                    {
-                        var gateWay = GateWayList[i];
-                        try
-                        {
-                            gateWay.IsVirtual = true;
-                            await gateWay.DisConnect("鏈湴鎼滅礌涓嶅埌缃戝叧锛屽噯澶囪皟鐢ㄨ繙绋嬶紝鍏抽棴褰撳墠灞�鍩熺綉涓墍鏈夌綉鍏�");
+                            return;
                         }
-                        catch { }
-                    }
-                    //鏂紑鍚庨噸鏂伴摼鎺ラ渶瑕侀噸鏂扮櫥褰曡幏鍙栬繛鎺ョ殑瀵嗙爜
-                    var tempResult = await Shared.Phone.UserView.HomePage.Instance.LoginByPWDAsync(Shared.Common.Config.Instance.Account, Shared.Common.Config.Instance.Password);
-                    if (tempResult != 1)
-                    {
-#if DEBUG
-                        DebugPrintLog($"閲嶆柊杩炴帴杩滅▼閫氳澶辫触锛屽洜涓鸿幏鍙栨柊鐨凨EY澶辫触");
-#endif
-                        return;
+
+                        //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺�
+                        remoteMqttIsConnecting = true;
+
+                        #region 鍒濆鍖栬繙绋婱qtt
+                        //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
+                        if (RemoteMqttClient.ApplicationMessageReceivedHandler == null)
+                        {
+                            RemoteMqttClient.UseApplicationMessageReceivedHandler((e) =>
+                            {
+                                if (!RemoteMqttClient.IsConnected || !IsRemote)
+                                {
+                                    return;
+                                }
+                                mqttRemoteClient_MqttMsgPublishReceived(e);
+                            });
+                        }
+
+                        if (RemoteMqttClient.DisconnectedHandler == null)
+                        {
+                            RemoteMqttClient.UseDisconnectedHandler((e) =>
+                            {
+                                DebugPrintLog($"杩滅▼杩炴帴鏂紑");
+                            });
+                        }
+                        if (RemoteMqttClient.ConnectedHandler == null)
+                        {
+                            RemoteMqttClient.UseConnectedHandler(async (e) =>
+                            {
+                                DebugPrintLog($"杩滅▼杩炴帴鎴愬姛");
+                                await initGateWayBaseInfomation();
+                                Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.Remote);
+                                //娌℃湁涓荤綉鍏虫椂涓诲姩璇诲彇锛岃幏鍙栦富缃戝叧淇℃伅
+                                var gateWayList = GateWayList.FindAll(obj => obj.getGatewayBaseInfo.HomeId == Shared.Common.Config.Instance.HomeId);
+                                if (gateWayList.Find(obj => obj.getGatewayBaseInfo.IsMainGateWay == true) == null)
+                                {
+                                    if (gateWayList.Count == 1)
+                                    {
+                                        gateWayList[0].getGatewayBaseInfo.IsMainGateWay = true;
+                                    }
+                                    else
+                                    {
+                                        for (int i = 0; i < gateWayList.Count; i++)
+                                        {
+                                            var gateWay = gateWayList[i];
+                                            var info = await gateWay.GetZbGwInfoAsync();
+                                            if (info == null || info.getGwData == null)
+                                            {
+                                                continue;
+                                            }
+                                            if (info.getGwData.IsDominant == 1)
+                                            {
+                                                gateWay.getGatewayBaseInfo.IsMainGateWay = true;
+                                                for (int j = i + 1; j < gateWayList.Count; j++)
+                                                {
+                                                    gateWayList[j].getGatewayBaseInfo.IsMainGateWay = false;
+                                                }
+                                                break;
+                                            }
+                                        }
+                                    }
+                                }
+                            });
+                        }
+                        #endregion
                     }
 
-                    //杩樻湁绉嶆儏鍐垫槸鍚屼竴涓狪D 鏈夊涓澶囩敤杩欎釜id杩炴帴锛堜細瀵艰嚧涓柇锛�
-                    string clientId = Shared.Common.Config.Instance.ConnectZigbeeMqttClientId;
-                    string username = Shared.Common.Config.Instance.ConnectGuid;
-                    string passwordRemote = Shared.Common.Config.Instance.ConnectZigbeeMqttBrokerPwd;
-                    //(1)杩炴帴鍒颁簯绔殑Mqtt瀹㈡埛绔繛鎺ュ弬鏁�
-                    var connectCloudMqttClientOptions = new MqttClientTcpOptions
+                    try
                     {
-                        Server = url.Split(':')[1].Substring("//".Length),    //114.215.173.87 鍏堝啓ip鍚э紝杩欎釜鍦板潃鍙兘鍚庨潰浼氭崲鎴愬煙鍚�
-                        Port = int.Parse(url.Split(':')[2]),
-                        ClientId = clientId,
-                        UserName = username,//杩炴帴鐨勭敤鎴峰悕
-                        Password = passwordRemote,//杩炴帴鐨勫瘑鐮侊紙App鐧诲綍鍚庤幏鍙栧埌鐨勮繛鎺ヤ簯绔疢qtt瀵嗙爜鍙兘杩炴帴涓�娆℃垚鍔熶箣鍚庝笉鑳藉啀浣跨敤鐩稿悓鐨勫瘑鐮佽繘琛岃繛鎺qtt鍚﹀垯浼氭彁绀虹敤鎴峰悕瀵嗙爜澶辫触锛岃繛鎺ヤ笉涓婁簯绔�;锛�
-                        CleanSession = true,// 璁剧疆鏄惁娓呯┖session,杩欓噷濡傛灉璁剧疆涓篺alse琛ㄧず鏈嶅姟鍣ㄤ細淇濈暀瀹㈡埛绔殑杩炴帴璁板綍锛岃繖閲岃缃负true琛ㄧず姣忔杩炴帴鍒版湇鍔″櫒閮戒互鏂扮殑韬唤杩炴帴
-                        KeepAlivePeriod = new TimeSpan(0, 5, 0),//璁剧疆蹇冭烦鏃堕棿锛堟渶澶у�硷紝2^16-1 = 65535绉� = 18灏忔椂銆傛渶灏忓�煎彲浠ヤ负0锛岃〃绀哄鎴风涓嶆柇寮�銆備竴鑸涓哄嚑鍒嗛挓锛屾瘮濡傚井淇″績璺冲懆鏈熶负300绉掋�傦級
-                        DefaultCommunicationTimeout = new TimeSpan(0, 0, 100),//璁剧疆瓒呮椂鏃堕棿
-                    };
-                    //杩滅▼閫氳杩炴帴锛岃繛鎺ヤ簯绔湇鍔″櫒 
-                    if (RemoteMqttClient != null)
-                    {
-                        await RemoteMqttClient.ConnectAsync(connectCloudMqttClientOptions);
-                    }
+                        var jsonData = new Dictionary<string, object> { ["RequestVersion"] = "RequestVersion", ["RequestSource"] = 0, ["LoginAccessToken"] = Config.Instance.Token, ["RequestProtocolType"] = 0 };
+                        var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData));
 
+                        var result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/GetConnMqttInfo", bytes, Config.Instance.Token);
+                        //{
+                        //"ResponseVersion": "RequestVersion1",
+                        //"StateCode": "Success",
+                        //"ErrorInfo": null,
+                        //"ResponseData": { < !--濡備笅淇℃伅鍙兘浣跨敤涓�娆★紝鍗充究浣犺繛鎺ュけ璐�!-- >
+                        //   "ConnEmqDomainPort": "tcp://developer.hdlcontrol.com:1883",
+                        //  "ConnEmqClientId": "ZigbeeClientTcp_33094de8-34ba-4e38-93c2-ac8da16d0e68_Zigbee",
+                        //  "ConnEmqUserName": "33094de8-34ba-4e38-93c2-ac8da16d0e68",
+                        //  "ConnEmqPwd": "4a265b65-d6cc-4a"
+                        //}
+                        //}
+                        if (result != null)
+                        {
+                            var jobject = Newtonsoft.Json.Linq.JObject.Parse(Encoding.UTF8.GetString(result));
+                            var responseData = jobject["ResponseData"];
+                            if (responseData != null)
+                            {
+                                var connEmqDomainPort = responseData["ConnEmqDomainPort"]?.ToString();
+                                var connEmqClientId = responseData["ConnEmqClientId"]?.ToString();
+                                var connEmqUserName = responseData["ConnEmqUserName"]?.ToString();
+                                var connEmqPwd = responseData["ConnEmqPwd"]?.ToString();
+
+                                var connEmqDomainPorts = connEmqDomainPort.Replace("//", "").Split(':');
+                                var domain = connEmqDomainPorts[1];
+                                var port = connEmqDomainPorts[2];
+
+
+                                var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()
+                                    .WithClientId(connEmqClientId)
+                .WithTcpServer(domain, int.Parse(port))
+                .WithCredentials(connEmqUserName, connEmqPwd)
+                .WithKeepAlivePeriod(TimeSpan.FromSeconds(20))
+                .WithCleanSession()
+                .Build();
+                                await RemoteMqttClient.ConnectAsync(options, CancellationToken.None);
+                                
+                            }
+                        }
+                    }
+                    catch { }
+                    finally
+                    {
+                        //鏈�缁堣閲婃斁杩炴帴鐘舵��
+                        remoteMqttIsConnecting = false;
+                    }
                 }
                 catch (Exception ex)
                 {
-#if DEBUG
                     DebugPrintLog($"杩滅▼杩炴帴閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
-#endif
-                }
-                finally
-                {
-                    remoteMqttIsConnecting = false;
                 }
             });
         }
@@ -3342,19 +3417,15 @@
         {
             try
             {
-#if DEBUG
-                DebugPrintLog($"涓诲姩鏂紑_{System.DateTime.Now.ToString()}_{s}");
-#endif
-                if (mqttClient != null && mqttClient.IsConnected == true)
+                DebugPrintLog($"涓诲姩鏂紑_{s}");
+                if (localMqttClient.IsConnected == true)
                 {
-                    await mqttClient.DisconnectAsync();
+                    await localMqttClient.DisconnectAsync();
                 }
             }
             catch (Exception ex)
             {
-#if DEBUG
                 DebugPrintLog($"鏂紑閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
-#endif
             }
         }
         #endregion
@@ -3387,30 +3458,36 @@
         /// </summary>
         async System.Threading.Tasks.Task SendRemoteMsg(string topicName, byte[] message, MQTTnet.Core.Protocol.MqttQualityOfServiceLevel qosLevel = MQTTnet.Core.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, bool retain = false)
         {
-            //(1)鐢熸垚[鐢ㄦ埛鍚�:瀵嗙爜]
-            var userNameAndPwdStr = string.Concat(Shared.Common.Config.Instance.Guid, RemoteOperatorConsts.CAP_NUMBER, Shared.Common.Config.Instance.MD5PWD);
-            DebugPrintLog($"userNameAndPwdStr锛歿userNameAndPwdStr} ");
+            if (this.getGatewayBaseInfo?.gwID == null || !GateWayBaseInfomations.ContainsKey(this.getGatewayBaseInfo?.gwID))
+            {
+                return;
+            }
+            var gateWayBaseInfomation = GateWayBaseInfomations[this.getGatewayBaseInfo?.gwID];
+            ////(1)鐢熸垚[鐢ㄦ埛鍚�:瀵嗙爜]
+            //var userNameAndPwdStr = string.Concat(Shared.Common.Config.Instance.Guid, RemoteOperatorConsts.CAP_NUMBER, Shared.Common.Config.Instance.MD5PWD);
+            //DebugPrintLog($"userNameAndPwdStr锛歿userNameAndPwdStr} ");
 
-            //(2)灏�(1)杞垚Base64瀛楃涓�,鐢熸垚鏍煎紡[Base64(鐢ㄦ埛鍚�:瀵嗙爜)]
-            var userNameAndPwdStrBaseSexFour = Convert.ToBase64String(ZigBee.Common.CommonInfo.EncodingUTF8.GetBytes(userNameAndPwdStr));
+            ////(2)灏�(1)杞垚Base64瀛楃涓�,鐢熸垚鏍煎紡[Base64(鐢ㄦ埛鍚�:瀵嗙爜)]
+            //var userNameAndPwdStrBaseSexFour = Convert.ToBase64String(ZigBee.Common.CommonInfo.EncodingUTF8.GetBytes(userNameAndPwdStr));
 
-            //(3)灏�(2)缁х画鐢熸垚鏍煎紡[Base64(鐢ㄦ埛鍚�:瀵嗙爜):Timestamp]
-            var userNameAndPwdStrBaseSexFourAndTimestamp = string.Concat(userNameAndPwdStrBaseSexFour, RemoteOperatorConsts.CAP_NUMBER, CurrentTimeStamp.ToString());
+            ////(3)灏�(2)缁х画鐢熸垚鏍煎紡[Base64(鐢ㄦ埛鍚�:瀵嗙爜):Timestamp]
+            //var userNameAndPwdStrBaseSexFourAndTimestamp = string.Concat(userNameAndPwdStrBaseSexFour, RemoteOperatorConsts.CAP_NUMBER, CurrentTimeStamp.ToString());
 
-            //[Zigbee.Buspro]App/id(甯愬彿Id)/Base64(DES[Base64(鐢ㄦ埛鍚�:瀵嗙爜):Timestamp ]/缃戝叧鍞竴Id/杞彂缁欑綉鍏崇殑涓婚/XX/XX
-            //(4)鐢熸垚涓婃姤涓婚锛屼富棰樻ā寮忛渶瑕佷负  /ZigbeeApp/id(涓诲瓙璋冭瘯甯愬彿Id)/Base64(DES[Base64(鐢ㄦ埛鍚�:瀵嗙爜):Timestamp ]/缃戝叧鍞竴Id/topicName "000204022022"   GateWayId  000204022022
-            var reportTopic = string.Format("/{0}/{1}/{2}/{3}/{4}", RemoteOperatorConsts.ZIGBEE_APP_STARTS_WITH, Shared.Common.Config.Instance.Guid, userNameAndPwdStrBaseSexFourAndTimestamp, this.getGatewayBaseInfo?.gwID, topicName);
-            var aa = System.Text.Encoding.UTF8.GetString(message);
+            ////[Zigbee.Buspro]App/id(甯愬彿Id)/Base64(DES[Base64(鐢ㄦ埛鍚�:瀵嗙爜):Timestamp ]/缃戝叧鍞竴Id/杞彂缁欑綉鍏崇殑涓婚/XX/XX
+            ////(4)鐢熸垚涓婃姤涓婚锛屼富棰樻ā寮忛渶瑕佷负  /ZigbeeApp/id(涓诲瓙璋冭瘯甯愬彿Id)/Base64(DES[Base64(鐢ㄦ埛鍚�:瀵嗙爜):Timestamp ]/缃戝叧鍞竴Id/topicName "000204022022"   GateWayId  000204022022
+            //var reportTopic = string.Format("/{0}/{1}/{2}/{3}/{4}", RemoteOperatorConsts.ZIGBEE_APP_STARTS_WITH, Shared.Common.Config.Instance.Guid, userNameAndPwdStrBaseSexFourAndTimestamp, this.getGatewayBaseInfo?.gwID, topicName);
 
-            string topicEncStr = reportTopic;
-            //鏂囦欢娴佷笉鐢ㄥ姞瀵�
-            topicEncStr = ZigBee.Common.SecuritySet.AesEncrypt(System.Text.Encoding.UTF8.GetBytes(topicEncStr), Shared.Common.Config.Instance.MqttKey);
-            topicEncStr = topicEncStr.Replace("/", "[[$-MQTT_TILT_SYMBOL_REPLACE-$]]").Replace("+", "[[$-MQTT_PLUS_SYMBOL_REPLACE-$]]");
-            message = System.Text.Encoding.UTF8.GetBytes(SecuritySet.AesEncrypt(message, Shared.Common.Config.Instance.MqttKey));
-            var bb = System.Text.Encoding.UTF8.GetString(message);
-
+            ////鏂囦欢娴佷笉鐢ㄥ姞瀵�
+            //var topicEncStr = ZigBee.Common.SecuritySet.AesEncrypt(System.Text.Encoding.UTF8.GetBytes(reportTopic), gateWayBaseInfomation.AesKey);
+            //topicEncStr = topicEncStr.Replace("/", "[[$-MQTT_TILT_SYMBOL_REPLACE-$]]").Replace("+", "[[$-MQTT_PLUS_SYMBOL_REPLACE-$]]");
+            //message = System.Text.Encoding.UTF8.GetBytes(SecuritySet.AesEncrypt(message, gateWayBaseInfomation.AesKey));
+            message = SecuritySet.AesEncryptBytes(message, gateWayBaseInfomation.AesKey);
+            var topicEncStr = $"/ClientToZigbeeGateWay/{gateWayBaseInfomation.MacMark}/Common/{topicName}";
             //(6)鏋勫缓Mqtt闇�瑕佸彂甯冪殑鏁版嵁鍖�,鍙戝竷缁欎簯绔殑MqttBroker
-            await RemoteMqttClient.PublishAsync(new MQTTnet.Core.MqttApplicationMessage(topicEncStr, message, qosLevel, retain));
+            if (RemoteMqttClient.IsConnected)
+            {
+                await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce });
+            }
         }
 
         /// <summary>
@@ -3432,18 +3509,13 @@
 
                 if (IsRemote)
                 {
-
                     await SendRemoteMsg(topic, message, qosLevel, retain);
-#if DEBUG
-                    DebugPrintLog($"杩滅▼ 鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId}_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")
-#endif            
+                    DebugPrintLog($"杩滅▼鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")
                 }
                 else
                 {
-#if DEBUG
-                    DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId}_{System.DateTime.Now.ToString()}");
-#endif
-                    if (mqttClient == null || !mqttClient.IsConnected)
+                    DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId}");
+                    if (!localMqttClient.IsConnected)
                     {
                         await StartLocalMqtt(getGatewayBaseInfo.IpAddress);
                     }
@@ -3456,22 +3528,15 @@
                             topic = ZigBee.Common.SecuritySet.AesEncrypt(System.Text.Encoding.UTF8.GetBytes(topic), Password);
                             message = System.Text.Encoding.UTF8.GetBytes(SecuritySet.AesEncrypt(message, password));
                             DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰橈紙绉樻枃锛�:{topic}_褰撳墠绉橀挜{Password}_鍙戦�佸埌缃戝叧鐨勬暟鎹紙绉樻枃锛�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId}_{System.DateTime.Now.ToString()}");
-
                         }
-
-                        await mqttClient.PublishAsync(new MQTTnet.Core.MqttApplicationMessage(topic, message, qosLevel, retain));
                     }
-                    else
-                    {
-                        await mqttClient.PublishAsync(new MQTTnet.Core.MqttApplicationMessage(topic, message, qosLevel, retain));
-                    }
+                    
+                    await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                 }
             }
             catch (Exception ex)
             {
-#if DEBUG
                 DebugPrintLog($"Send:{ex.Message}");
-#endif
             }
         }
 
@@ -3506,100 +3571,59 @@
         /// </summary>
         /// <param name="sender">Sender.</param>
         /// <param name="e">E.</param>
-        static void mqttRemoteClient_MqttMsgPublishReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
+        static void mqttRemoteClient_MqttMsgPublishReceived(MQTTnet.MqttApplicationMessageReceivedEventArgs e)
         {
             try
             {
                 var topic = e.ApplicationMessage.Topic.TrimStart('/');
+                var payload = e.ApplicationMessage.Payload;
+
                 var message = string.Empty;
                 //浣犲綋鍓嶇殑IP鍙婄鍙e湪浜戠涓嶅瓨鍦�,璇烽噸鏂扮櫥褰曡繛鎺ヤ笅!
-                if (topic == "YouIpAndPortNoRecord")
+
+                var topics = topic.Split("/");
+                if (topics.Length < 3)
                 {
-                    message = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
-                }
-                else if (topic == "BeingSqueezedOffline")
-                {
-                    //浜戠涓殑褰撳墠杩炴帴琚尋涓嬬嚎锛岄渶瑕侀�氱煡app
-                    //鍏ㄥ眬鎺ユ敹缃戝叧鎺ㄩ�佺殑鐨勯�昏緫(涓轰簡鎵ц閫熷害,灏藉彲鑳界殑鍒姞鑰楁椂鐨勬搷浣�)
-                    message = "BeingSqueezedOffline";
-                    Shared.Phone.UserCenter.HdlGatewayReceiveLogic.GatewayOverallMsgReceive("", topic, null);
-                    DebugPrintLog($"琚尋涓嬬嚎閫氱煡:{ topic}_杩滅▼杩斿洖鐨勬暟鎹甠{message}_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")
                     return;
                 }
-                //閲嶆柊鐧诲綍:甯愬彿鎴栬�呭叡浜繛鎺ヤ腑鐨刐瀛愬笎鍙峰垎甯冨紡Id$Share$鍒嗗竷寮忎綇瀹匢d=XXX灏氭湭鐧诲綍,璇烽噸鏂扮櫥褰曞悗鍐嶈繛鎺ュ悗鍐嶈繘琛屽彂甯冩搷浣�,濡傛灉鎮ㄥ綋鍓嶆槸鍒汉鍏变韩缁欎綘鐨勮繛鎺�,鍒欒閲嶆柊璇锋眰鑾峰彇杩炴帴淇℃伅涓�涓�,鍐嶅垵濮嬪寲杩炴帴鍐嶆鍙戝竷杩滅▼鎺у埗鍗冲彲!!
-                else if (topic == "AppNoLogin")
+                if (topics[0] != "ZigbeeGateWayToClient")
                 {
-                    message = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
+                    return;
                 }
-                else
-                {
-                    topic = topic.Replace("[[$-MQTT_TILT_SYMBOL_REPLACE-$]]", "/");
-                    topic = topic.Replace("[[$-MQTT_PLUS_SYMBOL_REPLACE-$]]", "+");
-                    topic = ZigBee.Common.SecuritySet.AesDecrypt(System.Text.Encoding.UTF8.GetBytes(topic), Shared.Common.Config.Instance.MqttKey).TrimStart('/'); ;
-
-                    if (!message.EndsWith("}"))
-                    {
-                        message = ZigBee.Common.SecuritySet.AesDecrypt(e.ApplicationMessage.Payload, Shared.Common.Config.Instance.MqttKey);
-                    }
+                if (topics[2]== "NotifyGateWayInfoChagne") {
+                    initGateWayBaseInfomation();
+                    return;
                 }
-#if DEBUG
-                DebugPrintLog($"杩滅▼杩斿洖鐨勪富棰�:{ topic}_杩滅▼杩斿洖鐨勬暟鎹甠{message}_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")
-#endif
-                var cloudMqttResult = Newtonsoft.Json.JsonConvert.DeserializeObject<ZigBee.Common.CloudMqttResponsePack>(message);
-                if (cloudMqttResult != null)
+                if (topics[2] == "Common")
                 {
-                    if (topic == "AppConnectMqttBrokerSuccess")
+                    var macMark = topics[1];
+                    topic = topic.Substring(topics[0].Length + topics[1].Length + topics[2].Length + 3);
+                    if (payload[0] == (byte)'{' && payload[payload.Length - 1] == (byte)'}')
                     {
-                        RemoteTimeStamp = ulong.Parse(cloudMqttResult.CloudTimestamp);
-                        LoginRemoteDateTime = System.DateTime.Now;
-#if DEBUG
-                        DebugPrintLog($"杩滅▼杩斿洖涓婚:{topic}_褰撳墠鏃堕棿鎴�:_+{CurrentTimeStamp} + _+{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"   // {System.DateTime.Now.ToString()}");
-#endif
-                        return;
+                        message = System.Text.Encoding.UTF8.GetString(payload);
                     }
                     else
                     {
-                        switch (cloudMqttResult.StateCode)
+                        foreach (var key in GateWayBaseInfomations.Keys)
                         {
-                            case "GatewayIdNoIsYou":
-                                message = cloudMqttResult.StateCode + ":" + cloudMqttResult.Info;
-#if DEBUG
-                                DebugPrintLog($"杩滅▼杩斿洖杩斿洖鐨勬彁绀哄唴瀹�:{message}_褰撳墠鏃堕棿鎴�:_+{CurrentTimeStamp} + _+ {System.DateTime.Now.ToString()}");
-#endif
-                                return;
-                            case "AppTimeOut":
-                                RemoteTimeStamp = ulong.Parse(cloudMqttResult.CloudTimestamp);
-                                LoginRemoteDateTime = System.DateTime.Now;
-                                message = cloudMqttResult.StateCode + ":" + cloudMqttResult.Info;
-#if DEBUG
-                                DebugPrintLog($"杩滅▼杩斿洖杩斿洖鐨勬彁绀哄唴瀹�:{message}_褰撳墠鏃堕棿鎴�:_+{CurrentTimeStamp} + _+ {System.DateTime.Now.ToString()}");
-#endif
-                                return;
-                            case "AppReportSuccess":
-                                RemoteTimeStamp = ulong.Parse(cloudMqttResult.CloudTimestamp);
-                                LoginRemoteDateTime = System.DateTime.Now;
-                                message = cloudMqttResult.StateCode + ":" + cloudMqttResult.Info;
-#if DEBUG
-                                DebugPrintLog($"杩滅▼杩斿洖杩斿洖鐨勬彁绀哄唴瀹�:{message}_褰撳墠鏃堕棿鎴�:_+{CurrentTimeStamp} + _+ {System.DateTime.Now.ToString()}");
-#endif
-                                return;
-                            case "ForwardGatewayNoOnLine":
-                                message = cloudMqttResult.StateCode + ":" + cloudMqttResult.Info;
-#if DEBUG
-                                DebugPrintLog($"杩滅▼杩斿洖杩斿洖鐨勬彁绀哄唴瀹�:{message}_褰撳墠鏃堕棿鎴�:_+{CurrentTimeStamp} + _+ {System.DateTime.Now.ToString()}");
-#endif
-                                return;
+                            var value = GateWayBaseInfomations[key];
+                            if (value.MacMark == macMark)
+                            {
+                                topic = $"{key}/{topic}";
+                                message = System.Text.Encoding.UTF8.GetString(ZigBee.Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, value.AesKey));
+                                break;
+                            }
                         }
                     }
                 }
 
-                ReceiveMessage(topic, message, e);
+                DebugPrintLog($"杩滅▼杩斿洖鐨勪富棰�:{ topic}_杩滅▼杩斿洖鐨勬暟鎹甠{message}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")
+
+                ReceiveMessage(topic, message, payload);
             }
             catch (Exception ex)
             {
-#if DEBUG
-                DebugPrintLog($"鎺ユ敹浜戠鏁版嵁寮傚父:{ex.Message}");
-#endif
+                DebugPrintLog($"鎺ユ敹浜戠鏁版嵁寮傚父:{ex.Message} ");
             }
         }
 
@@ -3609,7 +3633,7 @@
         /// </summary>
         /// <param name="sender">Sender.</param>
         /// <param name="e">E.</param>
-        void mqttClient_MqttMsgPublishReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
+        void mqttClient_MqttMsgPublishReceived(MQTTnet.MqttApplicationMessageReceivedEventArgs e)
         {
             try
             {
@@ -3641,7 +3665,7 @@
 #if DEBUG
                 DebugPrintLog($"缃戝叧杩斿洖鐨勪富棰�:{topic}_缃戝叧杩斿洖鐨勮礋杞�:{message}_{System.DateTime.Now.ToString()}");
 #endif
-                ReceiveMessage(topic, message, e);
+                ReceiveMessage(topic, message, e.ApplicationMessage.Payload);
             }
             catch (Exception ex)
             {
@@ -3657,7 +3681,7 @@
         /// <param name="topic">Topic.</param>
         /// <param name="message">Message.</param>
         /// <param name="e">E.</param>
-        static void ReceiveMessage(string topic, string message, MqttApplicationMessageReceivedEventArgs e)
+        static void ReceiveMessage(string topic, string message, byte []payload)
         {
             try
             {
@@ -3680,7 +3704,7 @@
                     attrId = topic.Split('/')[5];
                 }
 
-                var gwa = ZigBee.Device.ZbGateway.GateWayList.Find(obj => obj.getGatewayBaseInfo.gwID == gatewayID);
+                var gwa = GateWayList.Find(obj => obj.getGatewayBaseInfo.gwID == gatewayID);
                 if (gwa == null)
                 {
                     return;
@@ -3691,24 +3715,18 @@
                     gwa?.Actions(topic, message);
                 }
 
-                if (gwa.GwResDataAction != null)
-                {
-                    gwa.GwResDataAction(topic, message);
-                }
+                gwa.GwResDataAction?.Invoke(topic, message);
                 gwa.CurrentGateWayId = gatewayID;
 
-                Newtonsoft.Json.Linq.JObject jobject = new Newtonsoft.Json.Linq.JObject();
+                var jobject = new Newtonsoft.Json.Linq.JObject();
                 if (topic.Split('/')[0] + "/" + topic.Split('/')[1] == topic.Split('/')[0] + "/" + "FileTransfer")
                 {
                     if (topic.Split('/')[2] == "DownloadFile")
                     {
-                        gwa.DownloadFileConfirmAsync(e.ApplicationMessage.Payload);
-                        message = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
-                        if (gwa.FileContentAction != null)
-                        {
-                            gwa.FileContentAction(topic, e.ApplicationMessage.Payload);
-                        }
-                        DebugPrintLog($"缃戝叧杩斿洖鏁版嵁娴乢{message}_{System.DateTime.Now.ToString()}");
+                        gwa.DownloadFileConfirmAsync(payload);
+                        message = System.Text.Encoding.UTF8.GetString(payload);
+                        gwa.FileContentAction?.Invoke(topic, payload);
+                        DebugPrintLog($"缃戝叧杩斿洖鏁版嵁娴乢{message}");
                         return;
                     }
                 }
@@ -3720,38 +3738,6 @@
                 //鍏ㄥ眬鎺ユ敹缃戝叧鎺ㄩ�佺殑鐨勯�昏緫(涓轰簡鎵ц閫熷害,灏藉彲鑳界殑鍒姞鑰楁椂鐨勬搷浣�)
                 Shared.Phone.UserCenter.HdlGatewayReceiveLogic.GatewayOverallMsgReceive(gatewayID, topic, jobject);
 
-                #region 浜戠閫氱煡
-                var cloudMqttResult = Newtonsoft.Json.JsonConvert.DeserializeObject<ZigBee.Common.CloudMqttResponsePack>(message);
-                if (cloudMqttResult != null)
-                {
-                    switch (cloudMqttResult.StateCode)
-                    {
-                        case "AppNoLogin":
-                            if (gwa.CloudErrorAction != null)
-                            {
-                                DebugPrintLog("AppNoLogin宸茬粡閫氱煡");
-                                gwa.CloudErrorAction("AppNoLogin", "鐧诲綍杩囨湡锛岃閲嶆柊鐧诲綍");
-                            }
-                            //鍏ㄥ眬鎺ユ敹缃戝叧鎺ㄩ�佺殑鐨勯�昏緫(涓轰簡鎵ц閫熷害,灏藉彲鑳界殑鍒姞鑰楁椂鐨勬搷浣�)
-                            Shared.Phone.UserCenter.HdlGatewayReceiveLogic.GatewayOverallMsgReceive(gatewayID, "AppNoLogin", jobject);
-                            break;
-                        case "AppTimeOut":
-                            if (gwa.CloudErrorAction != null)
-                            {
-                                DebugPrintLog("AppTimeOut宸茬粡閫氱煡");
-                                gwa.CloudErrorAction("AppTimeOut", "浠庝簯绔幏鍙栨暟鎹秴鏃讹紝璇烽噸鏂拌幏鍙�");
-                            }
-                            break;
-                        case "ForwardGatewayNoOnLine":
-                            if (gwa.CloudErrorAction != null)
-                            {
-                                DebugPrintLog("ForwardGatewayNoOnLine宸茬粡閫氱煡");
-                                gwa.CloudErrorAction("ForwardGatewayNoOnLine", "褰撳墠鎿嶄綔鐨勭綉鍏充笉鍦ㄧ嚎");
-                            }
-                            break;
-                    }
-                }
-                #endregion
                 #region 杩滅▼,涓荤綉鍏充笂鎶ラ�氱煡
                 if (IsRemote)
                 {

--
Gitblit v1.8.0