From 0d9f64668fd7350d6a21fd157e32009a96d98134 Mon Sep 17 00:00:00 2001
From: 黄学彪 <hxb@hdlchina.com.cn>
Date: 星期三, 16 十二月 2020 13:09:08 +0800
Subject: [PATCH] 新云端代码Ver1.2

---
 ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs | 1165 ++++++++++++++++++++++++++-------------------------------
 1 files changed, 535 insertions(+), 630 deletions(-)

diff --git a/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs
index 376af66..db67a6f 100755
--- a/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs
+++ b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs
@@ -21,30 +21,30 @@
     /// </summary>
     [System.Serializable]
     public class ZbGateway : ZbGatewayData
-    {
+    {
         #region 涓�鍫嗗彉閲�
         /// <summary>
         /// 涓荤綉鍏�
         /// </summary>
-        /// <value>The main gate way.</value>
+        [Newtonsoft.Json.JsonIgnore]
         public static ZbGateway MainGateWay
         {
             get
-            {
+            {
                 ZbGateway mainWay = null;
-                for (int i = 0; i < GateWayList.Count; i++)
-                {
-                    if (GateWayList[i].HomeId == Config.Instance.HomeId)
-                    {
-                        //2020.07.16鍙樻洿:鍒閭d箞澶�,濡傛灉浣忓畢ID涓�鏍�,鍏堢‘瀹氬氨鏄畠浜�(涓嶇劧鏈夋椂鍊欑粡甯歌繑鍥瀗ull,鏈夊彲鑳芥槸鍒锋柊涓嶅埌)
-                        mainWay = GateWayList[i];
-                        if (mainWay.IsMainGateWay == true)
-                        {
-                            //鐒跺悗濡傛灉瀹冪‘瀹炴槸涓荤綉鍏�,鐩存帴break
-                            break;
-                        }
-                    }
-                }
+                for (int i = 0; i < GateWayList.Count; i++)
+                {
+                    if (GateWayList[i].HomeId == Config.Instance.HomeId)
+                    {
+                        //2020.07.16鍙樻洿:鍒閭d箞澶�,濡傛灉浣忓畢ID涓�鏍�,鍏堢‘瀹氬氨鏄畠浜�(涓嶇劧鏈夋椂鍊欑粡甯歌繑鍥瀗ull,鏈夊彲鑳芥槸鍒锋柊涓嶅埌)
+                        mainWay = GateWayList[i];
+                        if (mainWay.IsMainGateWay == true)
+                        {
+                            //鐒跺悗濡傛灉瀹冪‘瀹炴槸涓荤綉鍏�,鐩存帴break
+                            break;
+                        }
+                    }
+                }
                 return mainWay;
             }
         }
@@ -52,14 +52,8 @@
         /// <summary>
         /// 鏄惁浣跨敤杩滅▼杩炴帴妯″紡
         /// </summary>
-        /// <value><c>true</c> if is remote; otherwise, <c>false</c>.</value>
-        public static bool IsRemote;
-
-        /// <summary>
-        /// 鏄惁鎷ユ湁杩滅▼杩炴帴鐨勬潈闄�
-        /// </summary>
         [Newtonsoft.Json.JsonIgnore]
-        public static bool AllowRemoteCtrl = true;
+        public static bool IsRemote;
 
         /// <summary>
         /// 缃戝叧淇濆瓨璺緞
@@ -113,7 +107,13 @@
                 }
                 return password;
             }
-        }
+        }
+
+        /// <summary>
+        /// 缃戝叧杩滅▼杩炴帴鐨勪竴涓爣璇咺D,鑾峰彇鍒颁簡灏变笉鍐嶆敼鍙�
+        /// </summary>
+        [Newtonsoft.Json.JsonIgnore]
+        private static string RemoteClientId = new Random().Next(10, 99).ToString();
 
         /// <summary>
         /// 缃戝叧鏄惁鍔犲瘑
@@ -301,7 +301,7 @@
 
                 return data;
             });
-        }
+        }
         #endregion
 
         #region 璇诲彇鍗忚皟鍣∕AC鍦板潃.
@@ -501,17 +501,9 @@
                 {
                     //璐﹀彿ID
                     string accountId = string.Empty;
-                    if (homeId != string.Empty)
+                    if (homeId != string.Empty)
                     {
-                        if (Shared.Phone.UserCenter.UserCenterResourse.UserInfo.AuthorityNo == 1)
-                        {
-                            //涓昏处鍙�
-                            accountId = Config.Instance.Guid;
-                        }
-                        else
-                        {
-                            accountId = Config.Instance.Home.MainUserDistributedMark;
-                        }
+                        accountId = Config.Instance.Guid;
                     }
                     var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 82 } };
                     var data = new JObject { { "HomeId", homeId }, { "AccountId", accountId } };
@@ -1069,7 +1061,7 @@
         /// </summary>
         public async System.Threading.Tasks.Task<Panel.PanelSwitchLevelInfo> ClientDataPassthroughBytesAsync(string deviceAddr, int devicePoint, long dataLength, byte[] passData)
         {
-            var myDevice = Shared.Common.LocalDevice.Current.GetDevice(deviceAddr, devicePoint);
+            var myDevice = Shared.Phone.HdlDeviceCommonLogic.Current.GetDevice(deviceAddr, devicePoint);
 
             Panel.PanelSwitchLevelInfo result = null;
 
@@ -2335,48 +2327,54 @@
             }
         }
         #endregion
-
-        #region 閫氳杩炴帴
+
+        #region 鏈湴閫氳杩炴帴
+        /// <summary>
+        /// 鏈湴杩炴帴鏄惁杩炴帴鎴愬姛
+        /// </summary>
+        [Newtonsoft.Json.JsonIgnore]
+        public bool LocalIsConnected;
         /// <summary>
         /// 灞�鍩熺綉鐨凪QTT
         /// </summary>
-        IMqttClient localMqttClient = new MqttFactory().CreateMqttClient();
-        bool localMqttIsConnecting;
-        [Newtonsoft.Json.JsonIgnore]
-        public bool localIsConnected;
-        /// <summary>
-        /// 鎵嬫満鏍囪瘑
+        private IMqttClient localMqttClient = new MqttFactory().CreateMqttClient();
+        /// <summary>
+        /// 鏈湴mqtt鏄惁姝e湪杩炴帴涓�
         /// </summary>
-        static Guid currentGuid = Guid.NewGuid();
+        private bool localMqttIsConnecting;
+        /// <summary>
+        /// 鏈湴杩炴帴鐨勪竴涓鎴风ID(app鍚姩涔嬪悗灏变笉鍙樹簡)
+        /// </summary>
+        private static Guid LocalConnectGuid = Guid.NewGuid();
 
-        public async Task SendAesKey()
-        {
-            if (PubKey != null)
-            {
-                IsEncry = false;
-                var rsaString = ZigBee.Common.SecuritySet.RSAEncrypt(PubKey, Password);
-                var resultVerityfy = await SendAesKeyAsync(rsaString);
-                if (resultVerityfy == null)
-                {
-                    resultVerityfy = await SendAesKeyAsync(rsaString);
-                }
-
-                if (resultVerityfy != null && resultVerityfy.Result == 0)
-                {
-                    IsEncry = true;
-                }
+        public async Task SendAesKey()
+        {
+            if (PubKey != null)
+            {
+                IsEncry = false;
+                var rsaString = ZigBee.Common.SecuritySet.RSAEncrypt(PubKey, Password);
+                var resultVerityfy = await SendAesKeyAsync(rsaString);
+                if (resultVerityfy == null)
+                {
+                    resultVerityfy = await SendAesKeyAsync(rsaString);
+                }
+
+                if (resultVerityfy != null && resultVerityfy.Result == 0)
+                {
+                    IsEncry = true;
+                }
             }
         }
 
         public async Task StartLocalMqtt(string brokerName)
-        {
-            if (localMqttIsConnecting
-                || Shared.Common.Config.Instance.HomeId == ""
-                || localIsConnected)
-            {
-                return;
+        {
+            if (localMqttIsConnecting
+                || Shared.Common.Config.Instance.HomeId == ""
+                || LocalIsConnected)
+            {
+                return;
             }
-            await System.Threading.Tasks.Task.Factory.StartNew(async () =>
+            await Task.Factory.StartNew(async () =>
             {
                 try
                 {
@@ -2401,7 +2399,7 @@
                         if (localMqttClient.DisconnectedHandler == null)
                         {
                             localMqttClient.UseDisconnectedHandler(async (e) =>
-                            {
+                            {
                                 DebugPrintLog($" 鏈湴杩炴帴鏂紑_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}");
                                 await DisConnectLocalMqttClient("StartLocalMqtt.DisconnectedHandler");
                                 //await StartLocalMqtt("ReConnect");
@@ -2409,59 +2407,59 @@
                         }
                         if (localMqttClient.ConnectedHandler == null)
                         {
-                            localMqttClient.UseConnectedHandler(async (e) =>
-                            {
-                                DebugPrintLog($" 鏈湴杩炴帴鎴愬姛_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}_褰撳墠瀵嗙爜:{Password}");
-                                IsRemote = false;
-                                //Log鍐欏叆(璋冭瘯鐢�)
-                                if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
-                                {
-                                    Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, "鏈湴杩炴帴鎴愬姛");
-                                }
+                            localMqttClient.UseConnectedHandler(async (e) =>
+                            {
+                                DebugPrintLog($" 鏈湴杩炴帴鎴愬姛_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}_褰撳墠瀵嗙爜:{Password}");
+                                IsRemote = false;
+                                //Log鍐欏叆(璋冭瘯鐢�)
+                                if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
+                                {
+                                    Shared.Phone.HdlLogLogic.Current.WriteLog(2, "鏈湴杩炴帴鎴愬姛");
+                                }
                             });
-                        }
-
-                        var dateTime = DateTime.Now;
-
-                        new System.Threading.Thread(async () =>
-                        {
-                            try
-                            {
-                                if (localMqttClient.Options == null)
-                                {
-                                    var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()//MQTT杩炴帴鍙傛暟濉厖
-                                    .WithClientId(currentGuid.ToString())//瀹㈡埛绔疘D
-                                    .WithTcpServer(brokerName, 1883)//TCP鏈嶅姟绔�  1883  锛屽嵆MQTT鏈嶅姟绔�
-                                    .WithCredentials("", "")//"", "")//鍑瘉  甯愬彿 瀵嗙爜
-                                    .WithCommunicationTimeout(new TimeSpan(0, 0, 60)) //閲嶈繛瓒呮椂鏃堕棿锛岄粯璁�5s
-                                    .WithKeepAlivePeriod(new TimeSpan(0, 0, 15)) //淇濇寔杩炴帴鏃堕棿锛岄粯璁�5s锛屽績璺冲寘
-                                    .Build();//
-                                    await localMqttClient.ConnectAsync(options);
-                                }
-                                else
-                                {
-                                    await DisConnectLocalMqttClient("StartLocalMqtt");
-                                    await localMqttClient.ReconnectAsync();
-                                }
-                                localIsConnected = true;
-                                await SendAesKey();
-                            }
-                            catch { }
-                            dateTime = DateTime.MinValue;
-                        })
-                        { IsBackground = true }.Start();
-                        while (dateTime != DateTime.MinValue)
-                        {
-                            System.Threading.Thread.Sleep(100);
-                        }
-                    }
+                        }
+
+                        var dateTime = DateTime.Now;
+
+                        new System.Threading.Thread(async () =>
+                        {
+                            try
+                            {
+                                if (localMqttClient.Options == null)
+                                {
+                                    var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()//MQTT杩炴帴鍙傛暟濉厖
+                                    .WithClientId(LocalConnectGuid.ToString())//瀹㈡埛绔疘D
+                                    .WithTcpServer(brokerName, 1883)//TCP鏈嶅姟绔�  1883  锛屽嵆MQTT鏈嶅姟绔�
+                                    .WithCredentials("", "")//"", "")//鍑瘉  甯愬彿 瀵嗙爜
+                                    .WithCommunicationTimeout(new TimeSpan(0, 0, 60)) //閲嶈繛瓒呮椂鏃堕棿锛岄粯璁�5s
+                                    .WithKeepAlivePeriod(new TimeSpan(0, 0, 15)) //淇濇寔杩炴帴鏃堕棿锛岄粯璁�5s锛屽績璺冲寘
+                                    .Build();//
+                                    await localMqttClient.ConnectAsync(options);
+                                }
+                                else
+                                {
+                                    await DisConnectLocalMqttClient("StartLocalMqtt");
+                                    await localMqttClient.ReconnectAsync();
+                                }
+                                LocalIsConnected = true;
+                                await SendAesKey();
+                            }
+                            catch { }
+                            dateTime = DateTime.MinValue;
+                        })
+                        { IsBackground = true }.Start();
+                        while (dateTime != DateTime.MinValue)
+                        {
+                            System.Threading.Thread.Sleep(100);
+                        }
+                    }
                 }
                 catch (Exception ex)
-                {
-                    //Log鍐欏叆(璋冭瘯鐢�)
-                    if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
-                    {
-                        Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, "鏈湴杩炴帴寮傚父:\r\n" + ex.Message);
+                {
+                    //Log鍐欏叆(璋冭瘯鐢�)
+                    if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
+                    {
+                        Shared.Phone.HdlLogLogic.Current.WriteLog(2, "鏈湴杩炴帴寮傚父:\r\n" + ex.Message);
                     }
                     DebugPrintLog($"灞�鍩熺綉閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
                 }
@@ -2473,421 +2471,328 @@
         }
 
         /// <summary>
-        /// 褰撳墠鏈夊笎鍙蜂笅鎵�鏈夌殑缃戝叧鍒楄〃鍙婁俊鎭�
-        /// </summary>
-        public static Dictionary<string, Shared.Phone.UserCenter.GatewayResult> GateWayBaseInfomations = new Dictionary<string, Shared.Phone.UserCenter.GatewayResult> { };
-        /// <summary>
-        /// 鑾峰彇褰撳墠甯愬彿鎵�鏈夌殑缃戝叧淇℃伅
-        /// </summary>
-        /// <returns></returns>
-        static async Task initGateWayBaseInfomation()
-        {
-            if (AllowRemoteCtrl == false)
-            {
-                //娌℃湁杩滅▼杩炴帴鐨勬潈闄�
-                return;
-            }
-            string loginToken = Config.Instance.Token;
-            if (Config.Instance.Home.IsOthreShare == true)
-            {
-                //鑾峰彇鎴愬憳鐨勭壒娈奣oken
-                var pra = new
-                {
-                    CommonPage.RequestVersion,
-                    LoginAccessToken = Config.Instance.Token,
-                    MainAccountId = Config.Instance.Home.MainUserDistributedMark,
-                    SharedHid = Config.Instance.Home.Id
-                };
-                var resultData = Shared.Phone.UserCenter.UserCenterLogic.GetByteResponseDataByRequestHttps("App/GetSharedHomeApiControl", false, pra, new List<string> { "NotCheck" });
-                if (resultData == null)
-                {
-                    return;
-                }
-                var revertObj = Newtonsoft.Json.JsonConvert.DeserializeObject<Shared.Common.ResponseEntity.ResponsePack>(Encoding.UTF8.GetString(resultData));
-                //鍒嗕韩閾炬帴
-                var info = Newtonsoft.Json.JsonConvert.DeserializeObject<Shared.Phone.UserCenter.MemberAdministratorResult>(revertObj.ResponseData.ToString());
-                loginToken = info.RequestToken;
-            }
-
-            try
-            {
-                //璁剧疆璁块棶鎺ュ彛鐨勫弬鏁�
-                var pra2 = new Shared.Phone.UserCenter.GetGatewayPra();
-                pra2.IsOtherAccountCtrl = Config.Instance.Home.IsOthreShare;
-                pra2.ReqDto.PageSetting.Page = 1;
-                pra2.ReqDto.PageSetting.PageSize = 20;
-                pra2.ReqDto.LoginAccessToken = loginToken;
-                var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(pra2));
-
-                var result = CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/App/GetSingleHomeGatewayPagger", bytes, loginToken);
-                if (result != null)
-                {
-                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(Encoding.UTF8.GetString(result));
-
-                    var statuCode = jobject["StateCode"].ToString();
-                    if (statuCode != "Success")
-                    {
-                        //搴忓垪鍖栧璞�
-                        var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject(pra2);
-                        //Log鍑哄姏
-                        string errorMsg = "鎺ュ彛璁块棶澶辫触鈽咃細App/GetSingleHomeGatewayPagger " + statuCode + "\r\n";
-                        errorMsg += "鍙傛暟锛歕r\n" + requestJson;
-                        Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(-1, errorMsg);
-                        return;
-                    }
-
-                    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 Shared.Phone.UserCenter.GatewayResult { 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 (Exception ex)
-            {
-                Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(ex);
-            }
-        }
-
-        /// <summary>
-        /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
-        /// </summary>
-        static bool remoteMqttIsConnecting;
-
-        /// <summary>
-        /// 杩滅▼MqttClient
-        /// </summary>
-        public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient();
-        static bool remoteIsConnected;
-
-        /// <summary>
-        /// 杩滅▼寮�濮嬭繛鎺ョ殑鏃堕棿鐐�
-        /// </summary>
-        private static DateTime RemoteConnectTime = DateTime.Now;
-        /// <summary>
-        /// 鍚姩杩滅▼Mqtt
-        /// </summary>
-        /// <returns>The start.</returns>
-        /// <param name="brokerName">Broker name.</param>
-        public static async Task StartRemoteMqtt()
-        {
-            //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺
-            if (AllowRemoteCtrl == false
-               || Shared.Common.Config.Instance.HomeId == ""
-               || remoteIsConnected)
-            {
-                return;
-            }
-            //濡傛灉杩滅▼杩樺湪杩炴帴涓�
-            if (remoteMqttIsConnecting == true)
-            {
-                //濡傛灉杩欎釜鍙橀噺涓�鐩村浜庤繛鎺ヤ腑鐨勭姸鎬�,浣嗘槸宸茬粡杩囧幓浜�10绉掍簡,杩樻槸true鐨勮瘽,璇存槑杩欓噷鏄湁鐐归棶棰樼殑,闇�瑕侀噸鏂板垱寤�
-                if ((DateTime.Now - RemoteConnectTime).TotalMilliseconds < 10 * 1000)
-                {
-                    return;
-                }
-            }
-            //璁板綍璧疯繖娆¤繙绋嬭繛鎺ョ殑鏃堕棿鐐�
-            RemoteConnectTime = DateTime.Now;
-
-            await Task.Factory.StartNew(async () =>
-            {
-                try
-                {
-                    lock (RemoteMqttClient)
-                    {
-                        //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺�
-                        remoteMqttIsConnecting = true;
-
-                        #region 鍒濆鍖栬繙绋婱qtt
-                        //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
-                        if (RemoteMqttClient.ApplicationMessageReceivedHandler == null)
-                        {
-                            RemoteMqttClient.UseApplicationMessageReceivedHandler((e) =>
-                            {
-                                //杩欓噷鏄壒娈婄殑涓婚
-                                if (e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.ConnEmqClientId + "/Push/NotifySqueeze"//韪汉涓嬬嚎
-                                   || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/Deleted"//鍒嗕韩鍒犻櫎
-                                   || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/DeletedShareData"//鍒嗕韩鍒犻櫎
-                                   || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/Update"//鎴愬憳鏉冮檺鍙樻洿
-                                   || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Home.Id + "_" + Config.Instance.Guid + "/PrimaryUserDelYou")//瀛愯处鍙疯鍒犻櫎
-                                {
-                                    mqttRemoteClient_MqttMsgPublishReceived(e);
-                                    return;
-                                }
-                                if (!RemoteMqttClient.IsConnected || !IsRemote)
-                                {
-                                    return;
-                                }
-                                mqttRemoteClient_MqttMsgPublishReceived(e);
-                            });
-                        }
-
-                        if (RemoteMqttClient.DisconnectedHandler == null)
-                        {
-                            RemoteMqttClient.UseDisconnectedHandler(async (e) =>
-                            {
-                                DebugPrintLog($"杩滅▼杩炴帴鏂紑");
-                                await DisConnectRemoteMqttClient("StartRemoteMqtt.DisconnectedHandler");
-                                //await StartRemoteMqtt();
-                            });
-                        }
-                        if (RemoteMqttClient.ConnectedHandler == null)
-                        {
-                            RemoteMqttClient.UseConnectedHandler(async (e) =>
-                            {
-                                DebugPrintLog($"杩滅▼杩炴帴鎴愬姛");
-
-                                if (Config.Instance.Home.IsOthreShare == true)
-                                {
-                                    //璁㈤槄涓�涓垚鍛樿鍒犻櫎鐨勪富棰�
-                                    string myGuid = Config.Instance.Guid;
-                                    await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/Deleted");
-                                    //璁㈤槄涓�涓垎浜暟鎹凡缁忓彉鏇寸殑涓婚
-                                    await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/DeletedShareData");
-                                    //璁㈤槄涓�涓瓙璐﹀彿琚垹闄ょ殑涓婚
-                                    await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + Config.Instance.Home.Id + "_" + myGuid + "/PrimaryUserDelYou");
-                                    //璁㈤槄涓�涓垚鍛樻潈闄愬凡缁忓彉鏇寸殑涓婚
-                                    await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/Update");
-                                }
-                                //璁㈤槄涓�涓尋涓嬬嚎鐨勪富棰�
-                                await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + Config.Instance.ConnEmqClientId + "/Push/NotifySqueeze");
-
-                                //濡傛灉杩欎釜鍑芥暟鍗′箙浜嗙殑璇濓紝浼氭帴鏀跺埌浜戠鎺ㄩ�佺殑鎸や笅绾夸富棰橈紝涓嶇煡閬撲负浠�涔�
-                                new Thread(async () =>
-                                {
-                                    await initGateWayBaseInfomation();
-
-                                    //娌℃湁涓荤綉鍏虫椂涓诲姩璇诲彇锛岃幏鍙栦富缃戝叧淇℃伅
-                                    var gateWayList = GateWayList.FindAll(obj => obj.HomeId == Shared.Common.Config.Instance.HomeId);
-                                    if (gateWayList.Find(obj => obj.IsMainGateWay == true) == null)
-                                    {
-                                        if (gateWayList.Count == 1)
-                                        {
-                                            gateWayList[0].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)
-                                                {
-                                                    for (int j = 0; j < gateWayList.Count; j++)
-                                                    {
-                                                        if (gateWayList[i].GwId == info.getGwData.GwId)
-                                                        {
-                                                            gateWayList[i].IsMainGateWay = true;
-                                                        }
-                                                        else
-                                                        {
-                                                            gateWayList[i].IsMainGateWay = false;
-                                                        }
-                                                    }
-                                                    break;
-                                                }
-                                            }
-                                        }
-                                    }
-                                })
-                                { IsBackground = true }.Start();
-                                
-                            });
-                        }
-                        #endregion
-                    }
-
-                    try
-                    {
-                        byte[] result = null;
-                        if (Config.Instance.Home.IsOthreShare == false)
-                        {
-                            //涓讳汉
-                            var jsonData = new Dictionary<string, object>
-                            {
-                                ["RequestVersion"] = CommonPage.RequestVersion,
-                                ["RequestSource"] = 0,
-                                ["LoginAccessToken"] = Config.Instance.Token,
-                                ["RequestProtocolType"] = 0,
-                                ["PlatformStr"] = "h",//杩欎袱涓�煎鏋滀笉璁剧疆,鍒欎簯绔笉鍙戝竷涓婚
-                                ["PublishPayloadJsonStr"] = "1"
-                            };
-                            var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData));
-                            result = CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/GetConnMqttInfo", bytes, Config.Instance.Token);
-                        }
-                        else
-                        {
-                            //鍒嗕韩鐨�
-                            var jsonData = new Dictionary<string, object>
-                            {
-                                ["RequestVersion"] = CommonPage.RequestVersion,
-                                ["RequestSource"] = 0,
-                                ["LoginAccessToken"] = Config.Instance.Token,
-                                ["RequestProtocolType"] = 0,
-                                ["MainUserDistributedMark"] = Config.Instance.Home.MainUserDistributedMark,
-                                ["HomeId"] = Config.Instance.Home.Id,
-                                ["PlatformStr"] = "h",//杩欎袱涓�煎鏋滀笉璁剧疆,鍒欎簯绔笉鍙戝竷涓婚
-                                ["PublishPayloadJsonStr"] = "1"
-                            };
-                            var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData));
-                            result = CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/ShareMemberConnMqttInfo", bytes, Config.Instance.Token);
-                        }
-                        if (result != null)
-                        {
-                            var jobject = Newtonsoft.Json.Linq.JObject.Parse(Encoding.UTF8.GetString(result));
-                            if (jobject["StateCode"].ToString() == "NotAllowRemoteCtrl")
-                            {
-                                //娌℃湁杩滅▼杩炴帴鐨勬潈闄�
-                                AllowRemoteCtrl = false;
-                                return;
-                            }
-
-                            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();
-                                //璁板綍璧峰綋鍓嶇殑瀹㈡埛绔疘D
-                                Config.Instance.ConnEmqClientId = connEmqClientId;
-
-                                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()
-           //.WithCommunicationTimeout(TimeSpan.FromSeconds(10))
-           .Build();
-                                await DisConnectRemoteMqttClient("StartRemoteMqtt");
-                                await RemoteMqttClient.ConnectAsync(options, CancellationToken.None);
-
-                                remoteIsConnected = true;
-                            }
-                        }
-                    }
-                    catch { }
-                    finally
-                    {
-                        //鏈�缁堣閲婃斁杩炴帴鐘舵��
-                        remoteMqttIsConnecting = false;
-                    }
-                }
-                catch (Exception ex)
-                {
-                    DebugPrintLog($"杩滅▼杩炴帴閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
-                }
-            });
-        }
-
-        /// <summary>
         /// 鏂紑鏈嶅姟鍣ㄨ繛鎺�
         /// </summary>
         public async Task DisConnectLocalMqttClient(string s)
         {
             try
             {
-                if (localIsConnected)
-                {
-                    localIsConnected = false;
-                    //杩欎釜涓滆タ涔熻寮�
-                    localMqttIsConnecting = false;
-                    DebugPrintLog($"Local涓诲姩鏂紑_{s}");
-                    //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions {  }, CancellationToken.None);
-                    await localMqttClient.DisconnectAsync();
-                }
+                if (LocalIsConnected)
+                {
+                    LocalIsConnected = false;
+                    //杩欎釜涓滆タ涔熻寮�
+                    localMqttIsConnecting = false;
+                    DebugPrintLog($"Local涓诲姩鏂紑_{s}");
+                    //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions {  }, CancellationToken.None);
+                    await localMqttClient.DisconnectAsync();
+                }
             }
             catch (Exception ex)
             {
                 DebugPrintLog($"Local鏂紑閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
             }
-        }
-
+        }
+
         /// <summary>
         /// 寮哄埗鏂紑鏈湴鐨勭綉鍏宠繛鎺�
         /// </summary>
         public async Task CloseLocalConnectionOnForce()
         {
             try
-            {
-                await localMqttClient.DisconnectAsync();
+            {
+                await localMqttClient.DisconnectAsync();
             }
             catch { }
             finally
-            {
-                localIsConnected = false;
-                //杩欎釜涓滆タ涔熻寮�
-                localMqttIsConnecting = false;
+            {
+                LocalIsConnected = false;
+                //杩欎釜涓滆タ涔熻寮�
+                localMqttIsConnecting = false;
             }
         }
-
-        /// <summary>
-        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
+
+        #endregion
+
+        #region 杩滅▼閫氳杩炴帴
+
+        /// <summary>
+        /// 褰撳墠鏈夊笎鍙蜂笅鎵�鏈夌殑浜戠缃戝叧鍒楄〃鍙婁俊鎭�
         /// </summary>
-        public static async Task DisConnectRemoteMqttClient(string s = "")
-        {
-            try
-            {
-                if (remoteIsConnected)
-                {
-                    remoteIsConnected = false;
-                    //杩欎釜涓滆タ涔熻寮�
-                    remoteMqttIsConnecting = false;
-                    DebugPrintLog($"Remote涓诲姩鏂紑_{s}");
-                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
-                    await RemoteMqttClient.DisconnectAsync();
-                }
-            }
-            catch (Exception e)
-            {
-                DebugPrintLog($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
-            }
-        }
-
+        public static Dictionary<string, Shared.Phone.GatewayResult> DicGatewayBaseInfo = new Dictionary<string, Shared.Phone.GatewayResult> { };
+        /// <summary>
+        /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
+        /// </summary>
+        private static bool remoteMqttIsConnecting;
+        /// <summary>
+        /// 杩滅▼MqttClient
+        /// </summary>
+        public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient();
         /// <summary>
-        /// 寮哄埗鏂紑杩滅▼Mqtt鐨勯摼鎺�
-        /// </summary>
-        /// <returns></returns>
-        public static async Task CloseRemoteConnectionOnForce()
-        {
+        /// 杩滅▼杩炴帴鏄惁瀹屾垚
+        /// </summary>
+        private static bool remoteIsConnected;
+        /// <summary>
+        /// 杩滅▼寮�濮嬭繛鎺ョ殑鏃堕棿鐐�
+        /// </summary>
+        private static DateTime RemoteConnectTime = DateTime.Now;
+
+        /// <summary>
+        /// 鍚姩杩滅▼Mqtt
+        /// </summary>
+        public static async Task StartRemoteMqtt()
+        {
+            //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺
+            if (Config.Instance.Home.IsRemoteControl == false
+               || Config.Instance.Home.Id == ""
+               || remoteIsConnected)
+            {
+                return;
+            }
+            //濡傛灉杩滅▼杩樺湪杩炴帴涓�
+            if (remoteMqttIsConnecting == true)
+            {
+                //濡傛灉杩欎釜鍙橀噺涓�鐩村浜庤繛鎺ヤ腑鐨勭姸鎬�,浣嗘槸宸茬粡杩囧幓浜�10绉掍簡,杩樻槸true鐨勮瘽,璇存槑杩欓噷鏄湁鐐归棶棰樼殑,闇�瑕侀噸鏂板垱寤�
+                if ((DateTime.Now - RemoteConnectTime).TotalMilliseconds < 10 * 1000)
+                {
+                    return;
+                }
+            }
+            //璁板綍璧疯繖娆¤繙绋嬭繛鎺ョ殑鏃堕棿鐐�
+            RemoteConnectTime = DateTime.Now;
+
+            //鍒濆鍖栬繙绋媘qtt浜嬩欢
+            InitRemoteMqttEvent();
+
             try
             {
-                await RemoteMqttClient.DisconnectAsync();
+                //鑾峰彇杩滅▼mqtt閾炬帴淇℃伅
+                var pra = new { attachClientId = RemoteClientId, homeType = "ZIGBEE" };
+                var result = Shared.Phone.HdlHttpLogic.Current.RequestResponseFromZigbeeHttps("home-wisdom/mqtt/getRemoteInfo", RestSharp.Method.POST, pra);
+                if (result != null && result.Code == Shared.Phone.HttpMessageEnum.A鎴愬姛)
+                {
+                    var jobject = JObject.Parse(result.Data.ToString());
+
+                    var connEmqClientId = jobject["clientId"]?.ToString();
+                    var connEmqUserName = jobject["userName"]?.ToString();
+                    var connEmqPwd = jobject["passWord"]?.ToString();
+                    //璁板綍璧峰綋鍓嶇殑瀹㈡埛绔疘D
+                    Config.Instance.ConnEmqClientId = connEmqClientId;
+
+                    var connEmqDomainPorts = jobject["url"].ToString().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 DisConnectRemoteMqttClient("StartRemoteMqtt");
+                    await RemoteMqttClient.ConnectAsync(options, CancellationToken.None);
+
+                    remoteIsConnected = true;
+                }
             }
             catch { }
             finally
             {
-                remoteIsConnected = false;
-                //杩欎釜涓滆タ涔熻寮�
+                //鏈�缁堣閲婃斁杩炴帴鐘舵��
                 remoteMqttIsConnecting = false;
+            }
+        }
+
+        /// <summary>
+        /// 鍒濆鍖栬繙绋媘qtt浜嬩欢
+        /// </summary>
+        private static void InitRemoteMqttEvent()
+        {
+            lock (RemoteMqttClient)
+            {
+                //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺�
+                remoteMqttIsConnecting = true;
+
+                //(3)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
+                if (RemoteMqttClient.ApplicationMessageReceivedHandler == null)
+                {
+                    RemoteMqttClient.UseApplicationMessageReceivedHandler((e) =>
+                    {
+                        //杩欓噷鏄壒娈婄殑涓婚
+                        if (e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.ConnEmqClientId + "/Push/NotifySqueeze"//韪汉涓嬬嚎
+                           || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/Deleted"//鍒嗕韩鍒犻櫎
+                           || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/DeletedShareData"//鍒嗕韩鍒犻櫎
+                           || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/Update"//鎴愬憳鏉冮檺鍙樻洿
+                           || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Home.Id + "_" + Config.Instance.Guid + "/PrimaryUserDelYou")//瀛愯处鍙疯鍒犻櫎
+                        {
+                            mqttRemoteClient_MqttMsgPublishReceived(e);
+                            return;
+                        }
+                        if (!RemoteMqttClient.IsConnected || !IsRemote)
+                        {
+                            return;
+                        }
+                        mqttRemoteClient_MqttMsgPublishReceived(e);
+                    });
+                }
+
+                if (RemoteMqttClient.DisconnectedHandler == null)
+                {
+                    RemoteMqttClient.UseDisconnectedHandler(async (e) =>
+                    {
+                        DebugPrintLog($"杩滅▼杩炴帴鏂紑");
+                        await DisConnectRemoteMqttClient("StartRemoteMqtt.DisconnectedHandler");
+                    });
+                }
+
+                if (RemoteMqttClient.ConnectedHandler == null)
+                {
+                    RemoteMqttClient.UseConnectedHandler(async (e) =>
+                    {
+                        DebugPrintLog($"杩滅▼杩炴帴鎴愬姛");
+
+                        if (Config.Instance.Home.IsOtherShare == true)
+                        {
+                            //璁㈤槄涓�涓垚鍛樿鍒犻櫎鐨勪富棰�
+                            string myGuid = Config.Instance.Guid;
+                            await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/Deleted");
+                            //璁㈤槄涓�涓垎浜暟鎹凡缁忓彉鏇寸殑涓婚
+                            await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/DeletedShareData");
+                            //璁㈤槄涓�涓瓙璐﹀彿琚垹闄ょ殑涓婚
+                            await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + Config.Instance.Home.Id + "_" + myGuid + "/PrimaryUserDelYou");
+                            //璁㈤槄涓�涓垚鍛樻潈闄愬凡缁忓彉鏇寸殑涓婚
+                            await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/Update");
+                        }
+                        //璁㈤槄涓�涓尋涓嬬嚎鐨勪富棰�
+                        await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + Config.Instance.ConnEmqClientId + "/Push/NotifySqueeze");
+
+                        //濡傛灉杩欎釜鍑芥暟鍗′箙浜嗙殑璇濓紝浼氭帴鏀跺埌浜戠鎺ㄩ�佺殑鎸や笅绾夸富棰橈紝涓嶇煡閬撲负浠�涔�
+                        new System.Threading.Thread(async () =>
+                        {
+                            await InitGateWayBaseInfomation();
+
+                            //娌℃湁涓荤綉鍏虫椂涓诲姩璇诲彇锛岃幏鍙栦富缃戝叧淇℃伅
+                            var gateWayList = GateWayList.FindAll(obj => obj.HomeId == Shared.Common.Config.Instance.HomeId);
+                            if (gateWayList.Find(obj => obj.IsMainGateWay == true) == null)
+                            {
+                                if (gateWayList.Count == 1)
+                                {
+                                    gateWayList[0].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)
+                                        {
+                                            for (int j = 0; j < gateWayList.Count; j++)
+                                            {
+                                                if (gateWayList[i].GwId == info.getGwData.GwId)
+                                                {
+                                                    gateWayList[i].IsMainGateWay = true;
+                                                }
+                                                else
+                                                {
+                                                    gateWayList[i].IsMainGateWay = false;
+                                                }
+                                            }
+                                            break;
+                                        }
+                                    }
+                                }
+                            }
+                        })
+                        { IsBackground = true }.Start();
+                    });
+                }
             }
+        }
+
+        /// <summary>
+        /// 鍒濆鍖栧綋鍓嶅笎鍙锋墍鏈夌殑浜戠缃戝叧淇℃伅
+        /// </summary>
+        /// <returns></returns>
+        private static async Task InitGateWayBaseInfomation()
+        {
+            if (Config.Instance.Home.IsRemoteControl == false)
+            {
+                //娌℃湁杩滅▼杩炴帴鐨勬潈闄�
+                return;
+            }
+            //鑾峰彇浜戠缃戝叧淇℃伅
+            var listGatewayInfo = Shared.Phone.HdlGatewayLogic.Current.GetGateWayListFromDataBase(Config.Instance.Home.Id);
+            if (listGatewayInfo == null) { return; }
+
+            foreach (var info in listGatewayInfo.Values)
+            {
+                try
+                {
+                    //鏈夊彲鑳戒簯绔槸杩欎箞澶勭悊:濡傛灉娌℃湁杩滅▼鏉冮檺,鍒欎笉缁橝esKey
+                    if (string.IsNullOrEmpty(info.AesKey) == true) { continue; }
+                    //淇濆瓨缂撳瓨
+                    DicGatewayBaseInfo[info.Mac] = info;
+                    //鎴戜篃涓嶇煡閬撹繖涓槸骞插槢鐨�
+                    await RemoteMqttClient.SubscribeAsync($"/ZigbeeGateWayToClient/" + info.Id + "/#", MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
+                }
+                catch (Exception ex)
+                {
+                    Shared.Phone.HdlLogLogic.Current.WriteLog(ex);
+                }
+            }
+        }
+
+        /// <summary>
+        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
+        /// </summary>
+        public static async Task DisConnectRemoteMqttClient(string s = "")
+        {
+            try
+            {
+                if (remoteIsConnected)
+                {
+                    remoteIsConnected = false;
+                    //杩欎釜涓滆タ涔熻寮�
+                    remoteMqttIsConnecting = false;
+                    DebugPrintLog($"Remote涓诲姩鏂紑_{s}");
+                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
+                    await RemoteMqttClient.DisconnectAsync();
+                }
+            }
+            catch (Exception e)
+            {
+                DebugPrintLog($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
+            }
+        }
+
+        /// <summary>
+        /// 寮哄埗鏂紑杩滅▼Mqtt鐨勯摼鎺�
+        /// </summary>
+        /// <returns></returns>
+        public static async Task CloseRemoteConnectionOnForce()
+        {
+            try
+            {
+                await RemoteMqttClient?.DisconnectAsync();
+            }
+            catch { }
+            finally
+            {
+                remoteIsConnected = false;
+                //杩欎釜涓滆タ涔熻寮�
+                remoteMqttIsConnecting = false;
+            }
         }
 
         #endregion
-
+
         #region 鏁版嵁鍙戦��
-
+
         /// <summary>
         /// 鍙戦�佹秷鎭埌鏈嶅姟鍣�
         /// </summary>
@@ -2916,35 +2821,35 @@
         /// </summary>
         async System.Threading.Tasks.Task SendRemoteMsg(string topicName, byte[] message, bool retain = false)
         {
-            try
-            {
-                if (this.GwId == string.Empty || !GateWayBaseInfomations.ContainsKey(this.GwId))
-                {
-                    return;
-                }
-                var gateWayBaseInfomation = GateWayBaseInfomations[this.GwId];
-                message = SecuritySet.AesEncryptBytes(message, gateWayBaseInfomation.AesKey);
-                var topicEncStr = $"/ClientToZigbeeGateWay/{gateWayBaseInfomation.MacMark}/Common/{topicName}";
-                //(6)鏋勫缓Mqtt闇�瑕佸彂甯冪殑鏁版嵁鍖�,鍙戝竷缁欎簯绔殑MqttBroker
-                if (remoteIsConnected)
-                {
-                    try
-                    {
-                        await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce });
-                    }
-                    catch (Exception e)
-                    {
-                        await DisConnectRemoteMqttClient(e.Message);
-                        await StartRemoteMqtt();
-                        if (remoteIsConnected)
-                        {
-                            await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce });
-                        }
-                    }
+            try
+            {
+                if (this.GwId == string.Empty || !DicGatewayBaseInfo.ContainsKey(this.GwId))
+                {
+                    return;
                 }
-            }
-            catch
-            {
+                var gateWayBaseInfomation = DicGatewayBaseInfo[this.GwId];
+                message = SecuritySet.AesEncryptBytes(message, gateWayBaseInfomation.AesKey);
+                var topicEncStr = $"/ClientToZigbeeGateWay/{gateWayBaseInfomation.Id}/Common/{topicName}";
+                //(6)鏋勫缓Mqtt闇�瑕佸彂甯冪殑鏁版嵁鍖�,鍙戝竷缁欎簯绔殑MqttBroker
+                if (remoteIsConnected)
+                {
+                    try
+                    {
+                        await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce });
+                    }
+                    catch (Exception e)
+                    {
+                        await DisConnectRemoteMqttClient(e.Message);
+                        await StartRemoteMqtt();
+                        if (remoteIsConnected)
+                        {
+                            await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce });
+                        }
+                    }
+                }
+            }
+            catch
+            {
             }
         }
 
@@ -2962,16 +2867,16 @@
                 if (Shared.Common.Config.Instance.HomeId == "")
                 {
                     return;
-                }
-
-                //Log鍐欏叆(璋冭瘯鐢�)
-                if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
-                {
-                    string text = "杩滅▼鍙戦��:";
-                    if (IsRemote == false) { text = "鏈湴鍙戦��:"; }
-                    text += topic + "\r\n";
-                    text += Encoding.UTF8.GetString(message) + "\r\n";
-                    Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, text);
+                }
+
+                //Log鍐欏叆(璋冭瘯鐢�)
+                if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
+                {
+                    string text = "杩滅▼鍙戦��:";
+                    if (IsRemote == false) { text = "鏈湴鍙戦��:"; }
+                    text += topic + "\r\n";
+                    text += Encoding.UTF8.GetString(message) + "\r\n";
+                    Shared.Phone.HdlLogLogic.Current.WriteLog(2, text);
                 }
 
                 if (IsRemote)
@@ -2981,8 +2886,8 @@
                 }
                 else
                 {
-                    DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_鏄惁鍔犲瘑:{IsEncry}");
-
+                    DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_鏄惁鍔犲瘑:{IsEncry}");
+
                     if (IsEncry)
                     {
                         //鏂囦欢娴佷笉鐢ㄥ姞瀵�
@@ -2990,30 +2895,30 @@
                         {
                             message = SecuritySet.AesEncryptBytes(message, password);
                         }
-                    }
-                    if (localIsConnected)
-                    {
-                        try
-                        {
-                            await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
-                        }
-                        catch (Exception e)
+                    }
+                    if (LocalIsConnected)
+                    {
+                        try
                         {
-                            DebugPrintLog($"Local涓诲姩鏂紑_{e.Message}");
+                            await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
+                        }
+                        catch (Exception e)
+                        {
+                            DebugPrintLog($"Local涓诲姩鏂紑_{e.Message}");
                             await DisConnectLocalMqttClient(e.Message);
-                            await StartLocalMqtt("ReConnect");
-                            if (localIsConnected)
-                            {
-                                DebugPrintLog($"灞�鍩熺綉鈥斺�斾簩娆″彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_鏄惁鍔犲瘑:{IsEncry}");
-                                await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
-                            }
-                            //Log鍐欏叆(璋冭瘯鐢�)
-                            if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
-                            {
-                                Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, "鏈湴杩炴帴寮傚父鏂紑");
+                            await StartLocalMqtt("ReConnect");
+                            if (LocalIsConnected)
+                            {
+                                DebugPrintLog($"灞�鍩熺綉鈥斺�斾簩娆″彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_鏄惁鍔犲瘑:{IsEncry}");
+                                await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                             }
-                        }
-                    }
+                            //Log鍐欏叆(璋冭瘯鐢�)
+                            if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
+                            {
+                                Shared.Phone.HdlLogLogic.Current.WriteLog(2, "鏈湴杩炴帴寮傚父鏂紑");
+                            }
+                        }
+                    }
                 }
             }
             catch (Exception ex)
@@ -3032,12 +2937,12 @@
         public async System.Threading.Tasks.Task Send(string topic, string message, bool retain = false)
         {
             if (string.IsNullOrEmpty(message))
-            {
+            {
                 return;
             }
             await Send(topic, System.Text.Encoding.UTF8.GetBytes(message), retain);
-        }
-
+        }
+
         /// <summary>
         /// 寮哄埗鎸囧畾浣跨敤鏈湴灞�鍩熺綉鍙戦�佹秷鎭埌鏈嶅姟鍣�
         /// </summary>
@@ -3052,35 +2957,35 @@
                 if (Shared.Common.Config.Instance.HomeId == "")
                 {
                     return;
-                }
-
-                DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_鏄惁鍔犲瘑:{IsEncry}");
-
-                if (IsEncry)
-                {
-                    //鏂囦欢娴佷笉鐢ㄥ姞瀵�
-                    if (topic != "FileTransfer/SendFile")
-                    {
-                        message = SecuritySet.AesEncryptBytes(message, password);
-                    }
-                }
-                if (localIsConnected)
-                {
-                    try
-                    {
-                        await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
-                    }
-                    catch (Exception e)
-                    {
-                        DebugPrintLog($"Local涓诲姩鏂紑_{e.Message}");
-                        await DisConnectLocalMqttClient(e.Message);
-                        await StartLocalMqtt("ReConnect");
-                        if (localIsConnected)
-                        {
-                            DebugPrintLog($"灞�鍩熺綉鈥斺�斾簩娆″彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_鏄惁鍔犲瘑:{IsEncry}");
-                            await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
-                        }
-                    }
+                }
+
+                DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_鏄惁鍔犲瘑:{IsEncry}");
+
+                if (IsEncry)
+                {
+                    //鏂囦欢娴佷笉鐢ㄥ姞瀵�
+                    if (topic != "FileTransfer/SendFile")
+                    {
+                        message = SecuritySet.AesEncryptBytes(message, password);
+                    }
+                }
+                if (LocalIsConnected)
+                {
+                    try
+                    {
+                        await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
+                    }
+                    catch (Exception e)
+                    {
+                        DebugPrintLog($"Local涓诲姩鏂紑_{e.Message}");
+                        await DisConnectLocalMqttClient(e.Message);
+                        await StartLocalMqtt("ReConnect");
+                        if (LocalIsConnected)
+                        {
+                            DebugPrintLog($"灞�鍩熺綉鈥斺�斾簩娆″彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_鏄惁鍔犲瘑:{IsEncry}");
+                            await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
+                        }
+                    }
                 }
             }
             catch (Exception ex)
@@ -3119,7 +3024,7 @@
                 }
                 if (topics[2] == "NotifyGateWayInfoChange")
                 {
-                    initGateWayBaseInfomation();
+                    InitGateWayBaseInfomation();
                     return;
                 }
                 if (topics[2] == "Common")
@@ -3132,10 +3037,10 @@
                     }
                     else
                     {
-                        foreach (var key in GateWayBaseInfomations.Keys)
+                        foreach (var key in DicGatewayBaseInfo.Keys)
                         {
-                            var value = GateWayBaseInfomations[key];
-                            if (value.MacMark == macMark)
+                            var value = DicGatewayBaseInfo[key];
+                            if (value.Id == macMark)
                             {
                                 topic = $"{key}/{topic}";
                                 message = System.Text.Encoding.UTF8.GetString(ZigBee.Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, value.AesKey));
@@ -3185,9 +3090,9 @@
                         payloadString = System.Text.Encoding.UTF8.GetString(Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, Password));
                     }
                 }
-                else
-                {
-                    payloadString = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
+                else
+                {
+                    payloadString = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                 }
                 DebugPrintLog($"缃戝叧杩斿洖鐨勪富棰�:{topic}_缃戝叧杩斿洖鐨勮礋杞�:{payloadString}");
                 ReceiveMessage(topic, payloadString, e.ApplicationMessage.Payload);
@@ -3225,18 +3130,18 @@
                     epoint = topic.Split('/')[3];
                     cluID = topic.Split('/')[4];
                     attrId = topic.Split('/')[5];
-                }
-
-                //Log鍐欏叆(璋冭瘯鐢�)
-                if (Shared.Phone.UserCenter.UserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
-                {
-                    string text = "缃戝叧鍥炲:" + topic + "\r\n";
-                    text += message + "\r\n";
-                    Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(2, text);
-                }
-
-                //鍏ㄥ眬鎺ユ敹缃戝叧鎺ㄩ�佺殑鐨勯�昏緫(涓轰簡鎵ц閫熷害,灏藉彲鑳界殑鍒姞鑰楁椂鐨勬搷浣�)
-                Shared.Phone.UserCenter.HdlGatewayReceiveLogic.Current.GatewayOverallMsgReceive(gatewayID, topic, reportStatus, message);
+                }
+
+                //Log鍐欏叆(璋冭瘯鐢�)
+                if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
+                {
+                    string text = "缃戝叧鍥炲:" + topic + "\r\n";
+                    text += message + "\r\n";
+                    Shared.Phone.HdlLogLogic.Current.WriteLog(2, text);
+                }
+
+                //鍏ㄥ眬鎺ユ敹缃戝叧鎺ㄩ�佺殑鐨勯�昏緫(涓轰簡鎵ц閫熷害,灏藉彲鑳界殑鍒姞鑰楁椂鐨勬搷浣�)
+                Shared.Phone.HdlGatewayReceiveLogic.Current.GatewayOverallMsgReceive(gatewayID, topic, reportStatus, message);
 
                 var gwa = GateWayList.Find(obj => obj.GwId == gatewayID);
                 if (gwa == null)
@@ -3266,8 +3171,8 @@
                 else
                 {
                     jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
-                }
-
+                }
+
                 #region 杩滅▼,涓荤綉鍏充笂鎶ラ�氱煡
                 if (IsRemote)
                 {
@@ -3279,13 +3184,13 @@
                             var gwList = GateWayList.FindAll(obj => obj.HomeId == Shared.Common.Config.Instance.HomeId);
                             for (int i = 0; i < gwList.Count; i++)
                             {
-                                if (gwList[i].GwId == gatewayID)
-                                {
-                                    gwList[i].IsMainGateWay = true;
+                                if (gwList[i].GwId == gatewayID)
+                                {
+                                    gwList[i].IsMainGateWay = true;
                                 }
-                                else
-                                {
-                                    gwList[i].IsMainGateWay = false;
+                                else
+                                {
+                                    gwList[i].IsMainGateWay = false;
                                 }
                             }
                         }
@@ -3308,8 +3213,8 @@
                     var tempEpoint = jobject.Value<int>("Epoint");
                     var dataId = jobject.Value<int>("Data_ID");
 
-                    var tempDevice = new CommonDevice { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint };
-                    tempDevice.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DeviceStatusReportData>(jobject["Data"].ToString());
+                    var tempDevice = new CommonDevice { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint };
+                    tempDevice.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DeviceStatusReportData>(jobject["Data"].ToString());
                     UpdateDeviceInfo(tempDevice, "DeviceStatusReport");
                 }
                 #endregion
@@ -3357,12 +3262,12 @@
                             UpdateDeviceInfo(doorLock, "DoorLockProgrammingEventNotificationCommand");
                             break;
                     }
-                }
+                }
                 #endregion
                 #region IAS瀹夐槻淇℃伅涓婃姤
-
-                //2020.05.11 鍒犻櫎
-
+
+                //2020.05.11 鍒犻櫎
+
                 #endregion
                 #region 涓嬭浇杩涘害涓婃姤
                 else if (topic == gatewayID + "/" + "DownloadFile_Progress")
@@ -3553,12 +3458,12 @@
                 {
                     //涓婃姤绫诲瀷閫氱煡
                     if (gwa.ReportAction != null)
-                    {
-                        var clientDataPassthrough = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ClientDataPassthroughResponseData>(jobject["Data"].ToString());
-                        if (clientDataPassthrough != null)
-                        {
-                            DebugPrintLog("DeviceRequestAcUpdateData");
-                            gwa.ReportAction("DeviceRequestAcUpdateData", clientDataPassthrough);
+                    {
+                        var clientDataPassthrough = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ClientDataPassthroughResponseData>(jobject["Data"].ToString());
+                        if (clientDataPassthrough != null)
+                        {
+                            DebugPrintLog("DeviceRequestAcUpdateData");
+                            gwa.ReportAction("DeviceRequestAcUpdateData", clientDataPassthrough);
                         }
                     }
                 }

--
Gitblit v1.8.0