From 8da70e1a39328e1769b02bb1e05303916bb30eb5 Mon Sep 17 00:00:00 2001
From: wei <kaede@kaededeMacBook-Air.local>
Date: 星期一, 01 二月 2021 13:55:31 +0800
Subject: [PATCH] 水阀功能

---
 HDL_ON/DAL/Mqtt/MqttClient.cs |  150 ++++++++++++++++++++++++++++++-------------------
 1 files changed, 92 insertions(+), 58 deletions(-)

diff --git a/HDL_ON/DAL/Mqtt/MqttClient.cs b/HDL_ON/DAL/Mqtt/MqttClient.cs
index 4ddfc8e..405c696 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>
@@ -32,18 +33,18 @@
         /// </summary>
         static string RandomKey = "";
 
+        /// <summary>
+        /// 闅忔満鐢熸垚瀛楃
+        /// </summary>
+        /// <returns></returns>
         static string GetRandomKey()
         {
             if (string.IsNullOrEmpty(RandomKey))
             {
                 //闅忔満2浣嶅瓧绗︿覆
-                Random random = new Random(Guid.NewGuid().GetHashCode());
-                int num = random.Next(65, 91);
-                RandomKey = Convert.ToChar(num).ToString();
+                RandomKey = Utlis.CreateRandomString(2);
             }
-
             return RandomKey;
-
         }
 
         /// <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}");
             }
         }
 
@@ -119,7 +120,7 @@
         /// <summary>
         /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
         /// </summary>
-        public static bool remoteMqttIsConnecting;
+        public static bool RemoteMqttIsConnecting;
         static bool remoteIsConnected;
 
         static MqttClient()
@@ -132,12 +133,14 @@
         static void InitMqtt()
         {
             new System.Threading.Thread(async () => {
-                while (hadGateway)
+                while (true)
                 {
                     try
                     {
                         System.Threading.Thread.Sleep(500);
                         if (!Control.Ins.IsRemote) continue;
+                        //杩涘叆鍚庡彴涓嶅鐞�
+                        if (MainPage.IsEnterBackground) continue;
 
                         await StartCloudMqtt();
                         await SubscribeTopics();
@@ -158,6 +161,10 @@
         }
 
         static bool isSubscribeSuccess;
+        /// <summary>
+        /// 璁㈤槄涓婚
+        /// </summary>
+        /// <returns></returns>
         static async Task SubscribeTopics()
         {
             if (remoteIsConnected && !isSubscribeSuccess)
@@ -178,17 +185,27 @@
                         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 topicAlinkGatewayStatus = new MqttTopicFilter()
+                    {
+                        Topic = $"/user/{DB_ResidenceData.Instance.HomeGateway.gatewayId}/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[] { topicFilterBusGateWayToClient, topicFilterPush2, topicAlinkStatus, topicAlinkGatewayStatus });
                     if (result.Items[0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS0)
                     {
+                        Control.Ins.GatewayOnline = true;
                         isSubscribeSuccess = true;
                         Utlis.WriteLine("璁㈤槄鎴愬姛锛�");
 
@@ -221,7 +238,7 @@
             }
 
             //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺
-            if (remoteMqttIsConnecting || remoteIsConnected)
+            if (RemoteMqttIsConnecting || remoteIsConnected)
             {
                 return;
             }
@@ -232,7 +249,7 @@
                 try
                 {
                     #region 鍒濆鍖栬繙绋婱qtt
-                    remoteMqttIsConnecting = true;
+                    RemoteMqttIsConnecting = true;
                     RemoteMqttClient = new MqttFactory().CreateMqttClient();
 
 
@@ -265,11 +282,19 @@
                                     var ss = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                                     ReceiveCheckGateway(ss);
                                 }
+                                //娑傞甫璁惧鐘舵��
+                                else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.RegionID}/app/thing/property/send")
+                                {
+                                    var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, tuyaEncryptKey);
+                                    MainPage.Log($"tuya mqtt A-Link data");
+                                    //A鍗忚鏁版嵁澶勭悊
+                                    var revString = Encoding.UTF8.GetString(bytes);
+                                    Control.Ins.UpdataFunctionStatus(revString, null);
+                                }
                                 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)
                                     {
@@ -287,9 +312,10 @@
                                     }
                                     else
                                     {
+                                        MainPage.Log($"mqtt A-Link data");
                                         //A鍗忚鏁版嵁澶勭悊
                                         var revString = Encoding.UTF8.GetString(bytes);
-                                        Control.Ins.UpdataFunctionStatus(revString,null);
+                                        Control.Ins.UpdataFunctionStatus(revString, null);
                                     }
                                 }
                             }
@@ -309,25 +335,8 @@
                     //(3)ConnectedHandler
                     if (RemoteMqttClient.ConnectedHandler == null)
                     {
-                        RemoteMqttClient.UseConnectedHandler(async (e) => {
-                            if (DB_ResidenceData.Instance.HomeGateway.gatewayStatus)
-                            {
-                                Control.Ins.GatewayOnline = true;
-                            }
-                            else
-                            {
-                                //new System.Threading.Thread(() => {
-                                //    while(true)
-                                //    {
-                                //        System.Threading.Thread.Sleep(1000);
-                                //        if (DB_ResidenceData.Instance.HomeGateway.GatewayOnline)
-                                //        {
-                                //            Control.Ins.GatewayOnline = true;
-                                //            break;
-                                //        }
-                                //    }
-                                //}) { IsBackground = true }.Start();
-                            }
+                        RemoteMqttClient.UseConnectedHandler(async (e) =>
+                        {
                             IfNeedReadAllDeviceStatus = true;
                             Utlis.WriteLine($"============>Mqtt杩滅▼杩炴帴鎴愬姛");
                             SendPushSignOut();
@@ -357,7 +366,7 @@
                 finally
                 {
                     //鏈�缁堣閲婃斁杩炴帴鐘舵��
-                    remoteMqttIsConnecting = false;
+                    RemoteMqttIsConnecting = false;
 
                     Utlis.WriteLine($"StartCloudMqtt: 缁撴潫");
                 }
@@ -439,7 +448,9 @@
                 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
                 {
@@ -458,6 +469,20 @@
                     MqttInfoConfig.Current.Save();
 
                     mqttEncryptKey = MqttInfoConfig.Current.HomeGatewayInfo.aesKey;
+
+                    if (MqttInfoConfig.Current.HomeGatewayInfo == null)
+                    {
+                        MqttInfoConfig.Current.HomeGatewayInfo = new Server.HomeGatewayInfo();
+                    }
+                    //瑙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)
@@ -540,9 +565,6 @@
         /// </summary>
         static void ReceiveNotifySqueezeAsync(string mMes)
         {
-#if DEBUG
-            return;
-#endif
             if (mMes == PushSignStr) return;//鏄嚜宸辩殑鐧诲綍鎺ㄩ�佷笉澶勭悊
 
             //鏂紑杩滅▼杩炴帴
@@ -554,7 +576,12 @@
 
             DisConnectRemoteMqttClient("鎸や笅绾�");
 
-            HDLCommon.Current.CheckLogout();
+            Application.RunOnMainThread(() =>
+            {
+                //寮圭獥鎻愮ず琚尋涓嬬嚎
+                HDLCommon.Current.CheckLogout();
+            });
+
 
             //UserInfo.Current.LastTime = DateTime.MinValue;
             //UserInfo.Current.SaveUserInfo();
@@ -600,8 +627,6 @@
         /// <returns></returns>
         public static async Task MqttRemoteSend(byte[] message, int optionType = 0)
         {
-            //return;
-
             try
             {
                 string topicName;
@@ -647,7 +672,6 @@
         /// 鏄惁闇�瑕佽鍙栦竴娆℃墍鏈夎澶囩姸鎬�
         /// </summary>
         static bool IfNeedReadAllDeviceStatus = true;
-        //public static bool IsGatewayOnline = true;
 
         /// <summary>
         /// 璁剧疆缃戝叧鍦ㄧ嚎鏍囧織锛屽苟閲嶇疆CheckGateway鍙傛暟
@@ -657,7 +681,17 @@
             if (Control.Ins.IsRemote)
             {
                 if (!Control.Ins.GatewayOnline)
-                    Control.Ins.GatewayOnline = true;
+                {
+                    try
+                    {
+                        if (DB_ResidenceData.Instance.HomeGateway != null)
+                        {
+                            DB_ResidenceData.Instance.HomeGateway.gatewayStatus = true;
+                        }
+                        Control.Ins.GatewayOnline = true;
+                    }
+                    catch { }
+                }
             }
         }
 

--
Gitblit v1.8.0