From 944b87b6bcccb095cd73f13f4410fb20faf48f74 Mon Sep 17 00:00:00 2001
From: gxc <guoxuecheng@guoxuechengdeMacBook-Pro.local>
Date: 星期三, 25 十二月 2019 11:21:06 +0800
Subject: [PATCH] 2019.12.25

---
 ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs |  350 ++++++++++++++++++++++++++++++++++-----------------------
 1 files changed, 208 insertions(+), 142 deletions(-)

diff --git a/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs
index 48fbf24..7d98f3d 100755
--- a/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs
+++ b/ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs
@@ -95,7 +95,7 @@
             }
         }
 
-        #region variable 
+        #region variable
         /// <summary>
         /// 杩滅▼杩炴帴鎴愬姛鏃剁殑鏃堕棿
         /// </summary>
@@ -218,6 +218,7 @@
         /// <para>绗竴涓弬鏁帮細濡傛灉涓� DDevice/IsGetEpointInfo:鏈夋柊璁惧鍔犲叆zigbee缃戠粶鍙嶉</para>璁惧璇锋眰APP鑾峰彇鍗囩骇鏁版嵁
         /// <para>绗竴涓弬鏁帮細濡傛灉涓� Device/DeviceJoinZbNet:鑾峰彇鏂拌澶囨墍鏈夌鐐逛俊鎭槸鍚︽垚鍔熷弽棣�</para>
         /// <para>绗竴涓弬鏁帮細濡傛灉涓� DeviceRequestAcUpdateData: 璁惧璇锋眰绌鸿皟鍙戝崌绾ф暟鎹�</para>
+        /// "宸茬粡閫氱煡");//宸茬粡閫氱煡");
         /// </summary>
         [Newtonsoft.Json.JsonIgnore]
         public Action<string, object> ReportAction;
@@ -3090,27 +3091,46 @@
         /// </summary>
         IMqttClient localMqttClient = new MqttFactory().CreateMqttClient();
         bool localMqttIsConnecting;
+        public bool localIsConnected;
         /// <summary>
         /// 鎵嬫満鏍囪瘑
         /// </summary>
         static Guid currentGuid = Guid.NewGuid();
 
+        public async System.Threading.Tasks.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 System.Threading.Tasks.Task StartLocalMqtt(string brokerName)
-        {
+        {
+            if (localMqttIsConnecting
+                       || !Shared.Common.Config.Instance.IsLogin
+                       || Shared.Common.Config.Instance.HomeId == ""
+                       || localIsConnected)
+            {
+                return;
+            }
             await System.Threading.Tasks.Task.Factory.StartNew(async () =>
             {
                 try
                 {
                     lock (localMqttClient)
                     {
-                        if (localMqttIsConnecting
-                        || !Shared.Common.Config.Instance.IsLogin
-                        || Shared.Common.Config.Instance.HomeId == ""
-                        || localMqttClient.IsConnected)
-                        {
-                            return;
-                        }
-
                         //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺�
                         localMqttIsConnecting = true;
 
@@ -3129,10 +3149,11 @@
 
                         if (localMqttClient.DisconnectedHandler == null)
                         {
-                            localMqttClient.UseDisconnectedHandler((e) =>
-                            {
-                                IsEncry = false;
+                            localMqttClient.UseDisconnectedHandler(async (e) =>
+                            {
                                 DebugPrintLog($" 鏈湴杩炴帴鏂紑_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}");
+                                await DisConnectLocalMqttClient("StartLocalMqtt.DisconnectedHandler");
+                                //await StartLocalMqtt("ReConnect");
                             });
                         }
                         if (localMqttClient.ConnectedHandler == null)
@@ -3141,33 +3162,44 @@
                             {
                                 DebugPrintLog($" 鏈湴杩炴帴鎴愬姛_缃戝叧IP:{brokerName}_缃戝叧鏄惁鍔�:{IsEncry}_褰撳墠瀵嗙爜:{Password}");
                                 IsRemote = false;
-                                if (PubKey != null)
-                                {
-                                    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;
-                                    }
-                                }
                                 Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.WIFI);
-                                System.Console.WriteLine($"褰撳墠鏄綉鍏砏i-Fi鍦ㄩ�氳_{System.DateTime.Now.ToString()}");
                             });
-                        }
-                    }
-
-                    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);
+                        }
+
+                        var dateTime = DateTime.Now;
+
+                        new System.Threading.Thread(async () =>
+                        {
+                            try
+                            {
+                                if (localMqttClient.Options == null)
+                                {
+                                    var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder().WithClientId(currentGuid.ToString())
+                       .WithTcpServer(brokerName, 1883)
+                       .WithKeepAlivePeriod(TimeSpan.FromSeconds(20))
+                       .WithCleanSession()
+                        //.WithCommunicationTimeout(TimeSpan.FromSeconds(10))
+                       .WithCredentials("", "")
+                       .Build();
+                                    await localMqttClient.ConnectAsync(options, CancellationToken.None);
+                                }
+                                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)
                 {
@@ -3279,6 +3311,7 @@
         /// 杩滅▼MqttClient
         /// </summary>
         public static IMqttClient RemoteMqttClient= new MqttFactory().CreateMqttClient();
+        static bool remoteIsConnected;
         private int IsLogin = 0;
         [Newtonsoft.Json.JsonIgnore]
         static Action actionTemp;
@@ -3288,22 +3321,21 @@
         /// </summary>
         /// <returns>The start.</returns>
         /// <param name="brokerName">Broker name.</param>
-        public static async System.Threading.Tasks.Task StartCloudMqtt()
-        {
+        public static async System.Threading.Tasks.Task StartRemoteMqtt()
+        {
+            if (remoteMqttIsConnecting
+                       || !Shared.Common.Config.Instance.IsLogin
+                       || Shared.Common.Config.Instance.HomeId == ""
+                       || remoteIsConnected)
+            {
+                return;
+            }
             await System.Threading.Tasks.Task.Factory.StartNew(async () =>
             {
                 try
                 {
                     lock (RemoteMqttClient)
                     {
-                        if (remoteMqttIsConnecting
-                        || !Shared.Common.Config.Instance.IsLogin
-                        || Shared.Common.Config.Instance.HomeId == ""
-                        || RemoteMqttClient.IsConnected)
-                        {
-                            return;
-                        }
-
                         //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺�
                         remoteMqttIsConnecting = true;
 
@@ -3323,9 +3355,11 @@
 
                         if (RemoteMqttClient.DisconnectedHandler == null)
                         {
-                            RemoteMqttClient.UseDisconnectedHandler((e) =>
+                            RemoteMqttClient.UseDisconnectedHandler(async (e) =>
                             {
                                 DebugPrintLog($"杩滅▼杩炴帴鏂紑");
+                                await DisConnectRemoteMqttClient("StartRemoteMqtt.DisconnectedHandler");
+                                //await StartRemoteMqtt();
                             });
                         }
                         if (RemoteMqttClient.ConnectedHandler == null)
@@ -3378,21 +3412,35 @@
 
                     try
                     {
-                        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"
-                        //}
-                        //}
+                        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
+                            };
+                            var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData));
+                            result = await 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
+                            };
+                            var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData));
+                            result = await 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));
@@ -3406,18 +3454,20 @@
 
                                 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);
-                                
+                                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;
                             }
                         }
                     }
@@ -3438,28 +3488,40 @@
         /// <summary>
         /// 鏂紑鏈嶅姟鍣ㄨ繛鎺�
         /// </summary>
-        public async System.Threading.Tasks.Task DisConnect(string s)
+        public async System.Threading.Tasks.Task DisConnectLocalMqttClient(string s)
         {
             try
             {
-                DebugPrintLog($"涓诲姩鏂紑_{s}");
-                if (localMqttClient.IsConnected == true)
+                if (localIsConnected)
                 {
-                    await localMqttClient.DisconnectAsync();
-                }
+                    localIsConnected = false;
+                    DebugPrintLog($"Local涓诲姩鏂紑_{s}");
+                    await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions {  }, CancellationToken.None);
+                }
             }
             catch (Exception ex)
             {
-                DebugPrintLog($"鏂紑閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
+                DebugPrintLog($"Local鏂紑閫氳杩炴帴鍑哄紓甯�:{ex.Message}");
             }
         }
 
         /// <summary>
         /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
         /// </summary>
-        public static void DisRemoteMqttClientConnect()
+        public static async System.Threading.Tasks.Task DisConnectRemoteMqttClient(string s="")
         {
-            RemoteMqttClient.DisconnectAsync();
+            try
+            {
+                if (remoteIsConnected)
+                {
+                    remoteIsConnected = false;
+                    DebugPrintLog($"Remote涓诲姩鏂紑_{s}");
+                    await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
+                }
+            }
+            catch(Exception e) {
+                DebugPrintLog($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
+            }
         }
 
         #endregion
@@ -3492,35 +3554,35 @@
         /// </summary>
         async System.Threading.Tasks.Task SendRemoteMsg(string topicName, byte[] message, bool retain = false)
         {
-            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));
-
-            ////(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 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
-            if (RemoteMqttClient.IsConnected)
-            {
-                await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce });
+            try
+            {
+                if (this.getGatewayBaseInfo?.gwID == null || !GateWayBaseInfomations.ContainsKey(this.getGatewayBaseInfo?.gwID))
+                {
+                    return;
+                }
+                var gateWayBaseInfomation = GateWayBaseInfomations[this.getGatewayBaseInfo?.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 });
+                        }
+                    }
+                }
+            }
+            catch
+            {
             }
         }
 
@@ -3547,25 +3609,33 @@
                 }
                 else
                 {
-                    DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId}");
-                    if (!localMqttClient.IsConnected)
-                    {
-                        await StartLocalMqtt(getGatewayBaseInfo.IpAddress);
-                    }
-
+                    DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰�:{topic}_鍙戦�佸埌缃戝叧鐨勬暟鎹�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId} 鏄惁鍔犲瘑:{IsEncry}");
+
                     if (IsEncry)
                     {
                         //鏂囦欢娴佷笉鐢ㄥ姞瀵�
                         if (topic != "FileTransfer/SendFile")
                         {
-                            topic = ZigBee.Common.SecuritySet.AesEncrypt(System.Text.Encoding.UTF8.GetBytes(topic), Password);
-                            topic = topic.Replace("/", "[[$-MQTT_TILT_SYMBOL_REPLACE-$]]").Replace("+", "[[$-MQTT_PLUS_SYMBOL_REPLACE-$]]");
-                            message = System.Text.Encoding.UTF8.GetBytes(SecuritySet.AesEncrypt(message, password));
-                            DebugPrintLog($"灞�鍩熺綉鈥斺�斿彂閫佸埌缃戝叧鐨勪富棰橈紙绉樻枃锛�:{topic}_褰撳墠绉橀挜{Password}_鍙戦�佸埌缃戝叧鐨勬暟鎹紙绉樻枃锛�:{System.Text.Encoding.UTF8.GetString(message)}_褰撳墠缃戝叧{CurrentGateWayId}_{System.DateTime.Now.ToString()}");
+                            message = SecuritySet.AesEncryptBytes(message, password);
                         }
-                    }
-                    
-                    await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
+                    }
+                    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)
+                            {
+                                await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
+                            }
+                        }
+                    }
                 }
             }
             catch (Exception ex)
@@ -3608,8 +3678,7 @@
         {
             try
             {
-                var topic = e.ApplicationMessage.Topic.TrimStart('/');
-                topic = topic.Replace("[[$-MQTT_TILT_SYMBOL_REPLACE-$]]", "/").Replace("[[$-MQTT_PLUS_SYMBOL_REPLACE-$]]", "+");
+                var topic = e.ApplicationMessage.Topic.TrimStart('/');
                 var payload = e.ApplicationMessage.Payload;
 
                 var message = string.Empty;
@@ -3624,7 +3693,7 @@
                 {
                     return;
                 }
-                if (topics[2]== "NotifyGateWayInfoChagne") {
+                if (topics[2]== "NotifyGateWayInfoChange") {
                     initGateWayBaseInfomation();
                     return;
                 }
@@ -3671,39 +3740,36 @@
         {
             try
             {
-                var topic = e.ApplicationMessage.Topic;
-                topic = topic.Replace("[[$-MQTT_TILT_SYMBOL_REPLACE-$]]", "/").Replace("[[$-MQTT_PLUS_SYMBOL_REPLACE-$]]", "+");
-                var message = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
+                var topic = e.ApplicationMessage.Topic;
+                string payloadString = "";
 
                 if (IsEncry)
                 {
                     //涓婚
-                    topic = Common.SecuritySet.AesDecrypt(System.Text.Encoding.UTF8.GetBytes(topic), Password);
                     //涓嬭浇鐨勫瓧鑺傛祦涓嶉渶瑕佽В瀵�
                     if (topic.Split('/')[0] + "/" + topic.Split('/')[1] == topic.Split('/')[0] + "/" + "FileTransfer")
                     {
                         if (topic.Split('/')[2] != "DownloadFile")
                         {
-                            message = Common.SecuritySet.AesDecrypt(e.ApplicationMessage.Payload, Password);
+                            payloadString = System.Text.Encoding.UTF8.GetString(Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, Password));
                         }
                     }
                     else if (topic == topic.Split('/')[0] + "/" + "SendAESKey_Respon") { }//鍥炲涓婚鏄鏂囷紝鏁版嵁鏄槑鏂�
                     else
                     {
-                        message = Common.SecuritySet.AesDecrypt(e.ApplicationMessage.Payload, Password);
+                        payloadString = System.Text.Encoding.UTF8.GetString(Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, Password));
                     }
                 }
-
-#if DEBUG
-                DebugPrintLog($"缃戝叧杩斿洖鐨勪富棰�:{topic}_缃戝叧杩斿洖鐨勮礋杞�:{message}_{System.DateTime.Now.ToString()}");
-#endif
-                ReceiveMessage(topic, message, e.ApplicationMessage.Payload);
+                else
+                {
+                    payloadString = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
+                }
+                DebugPrintLog($"缃戝叧杩斿洖鐨勪富棰�:{topic}_缃戝叧杩斿洖鐨勮礋杞�:{payloadString}");
+                ReceiveMessage(topic, payloadString, e.ApplicationMessage.Payload);
             }
             catch (Exception ex)
             {
-#if DEBUG
                 DebugPrintLog($"鎺ユ敹缃戝叧鏁版嵁寮傚父:{ex.Message}");
-#endif
             }
         }
 

--
Gitblit v1.8.0