From 0a8ec482a5ad10bf3cd7010c89630b42ecaca741 Mon Sep 17 00:00:00 2001
From: JLChen <551775569@qq.com>
Date: 星期五, 05 二月 2021 10:19:31 +0800
Subject: [PATCH] Merge branch 'NewFilePath' into CJL

---
 HDL_ON/DAL/Mqtt/MqttClient.cs |  190 ++++++++++++++++++++++++----------------------
 1 files changed, 99 insertions(+), 91 deletions(-)

diff --git a/HDL_ON/DAL/Mqtt/MqttClient.cs b/HDL_ON/DAL/Mqtt/MqttClient.cs
index 2a95958..8c97e15 100644
--- a/HDL_ON/DAL/Mqtt/MqttClient.cs
+++ b/HDL_ON/DAL/Mqtt/MqttClient.cs
@@ -20,6 +20,7 @@
         /// 鍔犲瘑閫氳KEY
         /// </summary>
         static string mqttEncryptKey = "";
+        static string tuyaEncryptKey = "";
         //static string checkGatewayTopicBase64 = "";
         static bool hadGateway = true;
         /// <summary>
@@ -56,37 +57,37 @@
         /// </summary>
         static string PushSignStr = DateTime.Now.Ticks.ToString();
 
-        /// <summary>
-        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
+        /// <summary>
+        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
         /// </summary>
-        static async Task DisConnectRemoteMqttClient(string s = "")
-        {
+        static async Task DisConnectRemoteMqttClient(string s = "")
+        {
             try
-            {
+            {
                 if (remoteIsConnected)
                 {
                     remoteIsConnected = false;
                     isSubscribeSuccess = false;
-                    Utlis.WriteLine($"Remote涓诲姩鏂紑_{s}");
-                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
+                    Utlis.WriteLine($"Remote涓诲姩鏂紑_{s}");
+                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
                     await RemoteMqttClient.DisconnectAsync();
 
                     if (Control.Ins.IsRemote)
                     {
                         Control.Ins.GatewayOnline = false;
                     }
-                }
+                }
             }
             catch (Exception e)
             {
-                Utlis.WriteLine($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
-            }
+                Utlis.WriteLine($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
+            }
         }
 
-        /// <summary>
-        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
+        /// <summary>
+        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
         /// </summary>
-        static async Task DisConnectRemoteMqttClientWhenStart(string s = "")
+        static async Task DisConnectRemoteMqttClientWhenStart(string s = "")
         {
             try
             {
@@ -97,7 +98,7 @@
             }
             catch (Exception e)
             {
-                Utlis.WriteLine($"RemoteStart鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
+                Utlis.WriteLine($"RemoteStart鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
             }
         }
 
@@ -137,7 +138,7 @@
                     try
                     {
                         System.Threading.Thread.Sleep(500);
-                        if (!Control.Ins.IsRemote) continue;
+                        //if (!Control.Ins.IsRemote) continue;
                         //杩涘叆鍚庡彴涓嶅鐞�
                         if (MainPage.IsEnterBackground) continue;
 
@@ -170,34 +171,31 @@
             {
                 try
                 {
-                    //2020-05-14 璁㈤槄涓婚璐ㄩ噺鏀逛负0
-                    var topicFilterBusGateWayToClient = new MqttTopicFilter()
+                    if (DB_ResidenceData.Instance.GatewayType == 0 && !DB_ResidenceData.Instance.CheckWhetherGatewayIdIsNull())
                     {
-                        Topic = $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/#",
-                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
-                        //QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
-                    };
-
+                        Utlis.WriteLine("寮�濮嬭闃呬竴绔彛閫氱敤涓婚锛�");
+                        //2020-05-14 璁㈤槄涓婚璐ㄩ噺鏀逛负0
+                        var topicFilterBusGateWayToClient = new MqttTopicFilter()
+                        {
+                            Topic = $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/#",
+                            QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
+                        };
+                        await RemoteMqttClient.SubscribeAsync(topicFilterBusGateWayToClient);
+                    }
+                    //鎸や笅绾夸富棰�
                     var topicFilterPush2 = new MqttTopicFilter
                     {
                         Topic = $"/BusGateWayToClient/{UserInfo.Current.ID}/#",
                         QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce,
-                        //QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
                     };
-
                     var topicAlinkStatus = new MqttTopicFilter()
                     {
-                        Topic = $"/user/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/app/thing/property/send",
+                        Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.RegionID}/app/thing/property/send",
                         QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
                     };
-                    //var topicBusStatus = new MqttTopicFilter()
-                    //{
-                    //    Topic = $"/BusGateWayToClient/{}/Common",
-                    //    QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
-                    //};
 
                     Utlis.WriteLine("寮�濮嬭闃咃紒");
-                    var result = await RemoteMqttClient.SubscribeAsync(new MqttTopicFilter[] { topicFilterBusGateWayToClient, topicFilterPush2, topicAlinkStatus });
+                    var result = await RemoteMqttClient.SubscribeAsync(new MqttTopicFilter[] {  topicFilterPush2, topicAlinkStatus });
                     if (result.Items[0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS0)
                     {
                         Control.Ins.GatewayOnline = true;
@@ -205,9 +203,6 @@
                         Utlis.WriteLine("璁㈤槄鎴愬姛锛�");
 
                         MqttRemoteSend(new byte[] { 0 }, 3);
-
-                        //杩炴帴鎴愬姛鍚庢娴嬫槸鍚﹂渶瑕侀�氳繃杩滅▼鑾峰彇Key
-                        //CheckIfNeedGetLocalPasswordFromRemote();
                     }
                 }
                 catch (Exception ex)
@@ -256,63 +251,61 @@
                             try
                             {
                                 var topic = e.ApplicationMessage.Topic;
+                                //涓�绔彛涓婚澶勭悊
+                                if (DB_ResidenceData.Instance.GatewayType == 0 && !DB_ResidenceData.Instance.CheckWhetherGatewayIdIsNull())
+                                {
+                                    if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/NotifyBusGateWayInfoChange")
+                                    {
+                                        //缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey
+                                        //鏀跺埌缃戝叧涓婄嚎娑堟伅涓婚
+                                        ReceiveNotifyBusGateWayInfoChange();
+                                        return;
+                                    }
+                                    else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/NotifyGateWayOffline")
+                                    {
+                                        //缃戝叧鎺夌嚎
+                                        //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
+                                        ReceiveNotifyGateWayOffline();
+                                        return;
+                                    }
+                                    else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/Common/CheckGateway")
+                                    {
+                                        var ss = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
+                                        ReceiveCheckGateway(ss);
+                                        return;
+                                    }
+                                }
+
                                 if (topic == $"/BusGateWayToClient/{UserInfo.Current.ID}" + PushNotifySqueeze)
                                 {
                                     var mMes = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                                     //鏂版尋涓嬬嚎涓婚鏂规 鏀跺埌鎸や笅绾夸富棰�
                                     ReceiveNotifySqueezeAsync(mMes);
                                 }
-                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/NotifyBusGateWayInfoChange")
-                                {//缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey
-                                    //鏀跺埌缃戝叧涓婄嚎娑堟伅涓婚
-                                    ReceiveNotifyBusGateWayInfoChange();
-                                }
-                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/NotifyGateWayOffline")
-                                {//缃戝叧鎺夌嚎
-                                    //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
-                                    ReceiveNotifyGateWayOffline();
-                                }
-                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/Common/CheckGateway")
+                                //A缃戝叧璁惧鐘舵��-鍖呭惈娑傞甫璁惧
+                                else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.RegionID}/app/thing/property/send")
                                 {
-                                    
-                                    var ss = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
-                                    ReceiveCheckGateway(ss);
+                                    var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, tuyaEncryptKey);
+                                    var revString = Encoding.UTF8.GetString(bytes);
+                                    Control.Ins.UpdataFunctionStatus(revString, null);
                                 }
+                                //涓�绔彛鏁版嵁瑙f瀽
                                 else
                                 {
                                     SetGatewayOnlineResetCheck();
-                                    var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, DB_ResidenceData.Instance.HomeGateway.aesKey);
-                                    
+                                    var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
                                     //bus鏁版嵁瑙f瀽
-                                    if (DB_ResidenceData.Instance.GatewayType == 0)
-                                    {
-                                        var packet = new Packet();
+                                    var packet = new Packet();
 
-                                        if (!string.IsNullOrEmpty(mqttEncryptKey))
-                                        {
-                                            packet.Bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
-                                        }
-                                        else
-                                        {
-                                            packet.Bytes = e.ApplicationMessage.Payload;
-                                        }
-#if DEBUG
-                                        //string ddd = "";
-                                        //foreach (var bb in packet.Bytes)
-                                        //{
-                                        //    ddd += bb + ",";
-                                        //}
-                                        //MainPage.Log($"mqtt bus data:{ddd}");
-#endif
-                                        packet.Manager();
+                                    if (!string.IsNullOrEmpty(mqttEncryptKey))
+                                    {
+                                        packet.Bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
                                     }
                                     else
                                     {
-                                        MainPage.Log($"mqtt A-Link data");
-                                        //A鍗忚鏁版嵁澶勭悊
-                                        var revString = Encoding.UTF8.GetString(bytes);
-                                        Control.Ins.UpdataFunctionStatus(revString,null);
+                                        packet.Bytes = e.ApplicationMessage.Payload;
                                     }
+                                    packet.Manager();
                                 }
                             }
                             catch { }
@@ -339,7 +332,6 @@
                         });
                     }
                     #endregion
-                    //}
 
                     //(4)===========寮�濮嬭繛鎺ヨ繃绋�==========
                     //涔嬪墠宸茬粡鑾峰彇鍙傛暟鎴愬姛杩�
@@ -415,10 +407,10 @@
         /// <returns></returns>
         static async Task StartMQTTGetInfo()
         {
-            if (!Control.Ins.IsRemote)
-            {
-                return;
-            }
+            //if (!Control.Ins.IsRemote)
+            //{
+            //    return;
+            //}
 
             await GetMqttInfoAndMQTTConnectAsync();
 
@@ -439,12 +431,14 @@
         static async Task MQTTConnectAsync()
         {
 
-            if (!Control.Ins.IsRemote)
-            {
-                return;
-            }
+            //if (!Control.Ins.IsRemote)
+            //{
+            //    return;
+            //}
 
-            if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.mMqttInfo != null)
+            //if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.mMqttInfo != null)
+            //娌℃湁缃戝叧鎯呭喌涓嬶紝涔熼渶瑕佽繛鎺qtt锛屾秱楦︾涓夋柟璁惧涓嶉渶瑕佺綉鍏�
+            if (MqttInfoConfig.Current.mMqttInfo != null)
             {
                 try
                 {
@@ -462,7 +456,21 @@
                     MqttInfoConfig.Current.IfGetMqttInfoSuccess = true;
                     MqttInfoConfig.Current.Save();
 
+
+                    if (MqttInfoConfig.Current.HomeGatewayInfo == null)
+                    {
+                        MqttInfoConfig.Current.HomeGatewayInfo = new Server.HomeGatewayInfo();
+                    }
                     mqttEncryptKey = MqttInfoConfig.Current.HomeGatewayInfo.aesKey;
+                    //瑙e瘑瀵嗛挜瑙勫垯锛氬凡鐜版湁鐨勪綇瀹匢D涓哄熀鍑�,浠庡彸杈逛竴涓�鑾峰彇鍊�,鏈�鍚庡鏋滀笉澶�16浣�,鍒欏線鍙宠ˉ闆�
+                    string aesKey = string.Empty;
+                    for (int i = DB_ResidenceData.Instance.CurrentRegion.RegionID.Length - 1; i >= 0; i--)
+                    {
+                        aesKey += DB_ResidenceData.Instance.CurrentRegion.RegionID[i].ToString();
+                        if (aesKey.Length == 16) { break; }
+                    }
+                    aesKey = aesKey.PadRight(16, '0');
+                    tuyaEncryptKey = aesKey;
 
                     var options1 = new MQTTnet.Client.Options.MqttClientOptionsBuilder()
                                         .WithClientId(clientId)
@@ -561,7 +569,7 @@
                 //寮圭獥鎻愮ず琚尋涓嬬嚎
                 HDLCommon.Current.CheckLogout();
             });
-           
+
 
             //UserInfo.Current.LastTime = DateTime.MinValue;
             //UserInfo.Current.SaveUserInfo();
@@ -688,18 +696,18 @@
                 MqttInfoConfig.Current.mMqttInfo = mqttInfoRequestResult_Obj;
                 await MQTTConnectAsync();
                 //1.鍒ゆ柇鏄惁缁戝畾浜嗙綉鍏筹紝鑾峰彇缃戝叧杩滅▼杩炴帴鐨勫姞瀵咾EY
-                if (DB_ResidenceData.Instance.CheckWhetherGatewayIsBound())
+                //if (DB_ResidenceData.Instance.CheckWhetherGatewayIsBound())
                 {
                     //2.鎵惧嚭鏄惁瀛樺湪鍖归厤褰撳墠浣忓畢鐨刴ac锛屽瓨鍦ㄥ啀杩涜杩滅▼銆�
                     MqttInfoConfig.Current.HomeGatewayInfo = DB_ResidenceData.Instance.HomeGateway;
                     //3.寮�濮嬭繛鎺�
                     await MQTTConnectAsync();
                 }
-                else
-                {
-                    Utlis.WriteLine("============>杩樻病缁戝畾缃戝叧");
-                    hadGateway = false;
-                }
+                //else
+                //{
+                //    Utlis.WriteLine("============>杩樻病缁戝畾缃戝叧");
+                //    hadGateway = false;
+                //}
             }
         }
 

--
Gitblit v1.8.0