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 |  177 +++++++++++++++++++++++++++++++++++++++-------------------
 1 files changed, 119 insertions(+), 58 deletions(-)

diff --git a/HDL_ON/DAL/Mqtt/MqttClient.cs b/HDL_ON/DAL/Mqtt/MqttClient.cs
index dba1acf..405c696 100644
--- a/HDL_ON/DAL/Mqtt/MqttClient.cs
+++ b/HDL_ON/DAL/Mqtt/MqttClient.cs
@@ -1,7 +1,6 @@
 锘�/*
 鏇存柊浜咵MQ杩炴帴鏂瑰紡
 */
-using System.Collections.Generic;
 using System;
 using MQTTnet.Client;
 using System.Threading.Tasks;
@@ -9,9 +8,9 @@
 using MQTTnet;
 using System.Text;
 using System.Security.Cryptography;
-using System.IO;
 using HDL_ON.DriverLayer;
 using HDL_ON.Entity;
+using HDL_ON.UI;
 
 namespace HDL_ON.DAL.Mqtt
 {
@@ -21,8 +20,9 @@
         /// 鍔犲瘑閫氳KEY
         /// </summary>
         static string mqttEncryptKey = "";
+        static string tuyaEncryptKey = "";
         //static string checkGatewayTopicBase64 = "";
-
+        static bool hadGateway = true;
         /// <summary>
         /// 鎸や笅绾夸富棰�
         /// </summary>
@@ -33,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>
@@ -57,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
             {
@@ -98,7 +98,7 @@
             }
             catch (Exception e)
             {
-                Utlis.WriteLine($"RemoteStart鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
+                Utlis.WriteLine($"RemoteStart鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
             }
         }
 
@@ -120,7 +120,7 @@
         /// <summary>
         /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
         /// </summary>
-        public static bool remoteMqttIsConnecting;
+        public static bool RemoteMqttIsConnecting;
         static bool remoteIsConnected;
 
         static MqttClient()
@@ -139,6 +139,8 @@
                     {
                         System.Threading.Thread.Sleep(500);
                         if (!Control.Ins.IsRemote) continue;
+                        //杩涘叆鍚庡彴涓嶅鐞�
+                        if (MainPage.IsEnterBackground) continue;
 
                         await StartCloudMqtt();
                         await SubscribeTopics();
@@ -159,6 +161,10 @@
         }
 
         static bool isSubscribeSuccess;
+        /// <summary>
+        /// 璁㈤槄涓婚
+        /// </summary>
+        /// <returns></returns>
         static async Task SubscribeTopics()
         {
             if (remoteIsConnected && !isSubscribeSuccess)
@@ -168,7 +174,7 @@
                     //2020-05-14 璁㈤槄涓婚璐ㄩ噺鏀逛负0
                     var topicFilterBusGateWayToClient = new MqttTopicFilter()
                     {
-                        Topic = $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.id}/#",
+                        Topic = $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/#",
                         QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
                         //QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
                     };
@@ -179,11 +185,27 @@
                         QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce,
                         //QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
                     };
+                    var topicAlinkStatus = new MqttTopicFilter()
+                    {
+                        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 });
+                    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("璁㈤槄鎴愬姛锛�");
 
@@ -205,8 +227,7 @@
         /// </summary>
         public static async Task StartCloudMqtt()
         {
-
-            if (OnAppConfig.Instance.internetStatus == 0)
+            if (MainPage.InternetStatus == 0)
             {
                 return;
             }
@@ -217,7 +238,7 @@
             }
 
             //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺
-            if (remoteMqttIsConnecting || remoteIsConnected)
+            if (RemoteMqttIsConnecting || remoteIsConnected)
             {
                 return;
             }
@@ -228,7 +249,7 @@
                 try
                 {
                     #region 鍒濆鍖栬繙绋婱qtt
-
+                    RemoteMqttIsConnecting = true;
                     RemoteMqttClient = new MqttFactory().CreateMqttClient();
 
 
@@ -246,25 +267,36 @@
                                     //鏂版尋涓嬬嚎涓婚鏂规 鏀跺埌鎸や笅绾夸富棰�
                                     ReceiveNotifySqueezeAsync(mMes);
                                 }
-                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.id}/NotifyBusGateWayInfoChange")
+                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/NotifyBusGateWayInfoChange")
                                 {//缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey
                                     //鏀跺埌缃戝叧涓婄嚎娑堟伅涓婚
                                     ReceiveNotifyBusGateWayInfoChange();
                                 }
-                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.id}/NotifyGateWayOffline")
+                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/NotifyGateWayOffline")
                                 {//缃戝叧鎺夌嚎
                                     //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
                                     ReceiveNotifyGateWayOffline();
                                 }
-                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.id}/Common/CheckGateway")
+                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/Common/CheckGateway")
                                 {
                                     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();
-                                    if (Entity.DB_ResidenceData.residenceData.GatewayType == 0)
+                                    var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
+                                    //bus鏁版嵁瑙f瀽
+                                    if (DB_ResidenceData.Instance.GatewayType == 0)
                                     {
                                         var packet = new Packet();
 
@@ -280,7 +312,10 @@
                                     }
                                     else
                                     {
+                                        MainPage.Log($"mqtt A-Link data");
                                         //A鍗忚鏁版嵁澶勭悊
+                                        var revString = Encoding.UTF8.GetString(bytes);
+                                        Control.Ins.UpdataFunctionStatus(revString, null);
                                     }
                                 }
                             }
@@ -300,15 +335,11 @@
                     //(3)ConnectedHandler
                     if (RemoteMqttClient.ConnectedHandler == null)
                     {
-                        RemoteMqttClient.UseConnectedHandler(async (e) => {
+                        RemoteMqttClient.UseConnectedHandler(async (e) =>
+                        {
                             IfNeedReadAllDeviceStatus = true;
                             Utlis.WriteLine($"============>Mqtt杩滅▼杩炴帴鎴愬姛");
                             SendPushSignOut();
-
-                            //if (Control.Ins.IsRemote) {
-                            //    //Utlis.ShowAppLinkStatus (AppLinkStatus.CloudLink);
-                            //    MainPage.AddTip (Language.StringByID (SimpleControl.R.MyInternationalizationString.LinkSuccess));
-                            //}
                         });
                     }
                     #endregion
@@ -335,7 +366,7 @@
                 finally
                 {
                     //鏈�缁堣閲婃斁杩炴帴鐘舵��
-                    remoteMqttIsConnecting = false;
+                    RemoteMqttIsConnecting = false;
 
                     Utlis.WriteLine($"StartCloudMqtt: 缁撴潫");
                 }
@@ -365,7 +396,7 @@
         {
             try
             {
-                if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.HomeGatewayInfo.mac == Entity.DB_ResidenceData.residenceData.residenceGatewayMAC)
+                if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.HomeGatewayInfo.mac == Entity.DB_ResidenceData.Instance.residenceGatewayMAC)
                 {
                     await MQTTConnectAsync();
                 }
@@ -417,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
                 {
@@ -426,8 +459,7 @@
 
                     //url = HttpUtil.GetProxyEMQUrl (url);
                     //#if DEBUG
-                    //                   url = HttpUtil.GetProxyEMQUrl (url);
-
+                    //url = HttpUtil.GetProxyEMQUrl (url);
                     //#endif
                     var clientId = MqttInfoConfig.Current.mMqttInfo.clientId;
                     var username = MqttInfoConfig.Current.mMqttInfo.userName;
@@ -437,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)
@@ -519,7 +565,6 @@
         /// </summary>
         static void ReceiveNotifySqueezeAsync(string mMes)
         {
-
             if (mMes == PushSignStr) return;//鏄嚜宸辩殑鐧诲綍鎺ㄩ�佷笉澶勭悊
 
             //鏂紑杩滅▼杩炴帴
@@ -531,13 +576,20 @@
 
             DisConnectRemoteMqttClient("鎸や笅绾�");
 
-            UserInfo.Current.LastTime = DateTime.MinValue;
-            UserInfo.Current.SaveUserInfo();
-
-            Application.RunOnMainThread(() => {
-                MainPage.GoLoginPage(UserInfo.Current);
+            Application.RunOnMainThread(() =>
+            {
                 //寮圭獥鎻愮ず琚尋涓嬬嚎
+                HDLCommon.Current.CheckLogout();
             });
+
+
+            //UserInfo.Current.LastTime = DateTime.MinValue;
+            //UserInfo.Current.SaveUserInfo();
+
+            //Application.RunOnMainThread(() => {
+            //    MainPage.GoLoginPage(UserInfo.Current);
+            //    //寮圭獥鎻愮ず琚尋涓嬬嚎
+            //});
 
             //2020-08-11 鍒犻櫎鎺ㄩ�佹暟鎹�
             //HDLRequest.Current.PushserivceSignOut ();
@@ -575,15 +627,13 @@
         /// <returns></returns>
         public static async Task MqttRemoteSend(byte[] message, int optionType = 0)
         {
-            //return;
-
             try
             {
                 string topicName;
                 switch (optionType)
                 {
                     case 0:
-                        topicName = $"/ClientToBusGateWay/{MqttInfoConfig.Current.HomeGatewayInfo.id}/Common/ON";
+                        topicName = $"/ClientToBusGateWay/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/Common/ON";
                         if (!string.IsNullOrEmpty(mqttEncryptKey))
                         {
                             message = Securitys.EncryptionService.AesEncryptPayload(message, mqttEncryptKey);
@@ -591,7 +641,7 @@
                         await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
                         break;
                     case 3:
-                        topicName = $"/ClientToBusGateWay/{MqttInfoConfig.Current.HomeGatewayInfo.id}/Common/CheckGateway";
+                        topicName = $"/ClientToBusGateWay/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/Common/CheckGateway";
                         Utlis.WriteLine("CheckGateway");
                         await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicName, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
                         break;
@@ -622,7 +672,6 @@
         /// 鏄惁闇�瑕佽鍙栦竴娆℃墍鏈夎澶囩姸鎬�
         /// </summary>
         static bool IfNeedReadAllDeviceStatus = true;
-        //public static bool IsGatewayOnline = true;
 
         /// <summary>
         /// 璁剧疆缃戝叧鍦ㄧ嚎鏍囧織锛屽苟閲嶇疆CheckGateway鍙傛暟
@@ -631,7 +680,18 @@
         {
             if (Control.Ins.IsRemote)
             {
-                Control.Ins.GatewayOnline = true;
+                if (!Control.Ins.GatewayOnline)
+                {
+                    try
+                    {
+                        if (DB_ResidenceData.Instance.HomeGateway != null)
+                        {
+                            DB_ResidenceData.Instance.HomeGateway.gatewayStatus = true;
+                        }
+                        Control.Ins.GatewayOnline = true;
+                    }
+                    catch { }
+                }
             }
         }
 
@@ -648,16 +708,17 @@
                 MqttInfoConfig.Current.mMqttInfo = mqttInfoRequestResult_Obj;
                 await MQTTConnectAsync();
                 //1.鍒ゆ柇鏄惁缁戝畾浜嗙綉鍏筹紝鑾峰彇缃戝叧杩滅▼杩炴帴鐨勫姞瀵咾EY
-                if (DB_ResidenceData.residenceData.CheckWhetherGatewayIsBound())
+                if (DB_ResidenceData.Instance.CheckWhetherGatewayIsBound())
                 {
                     //2.鎵惧嚭鏄惁瀛樺湪鍖归厤褰撳墠浣忓畢鐨刴ac锛屽瓨鍦ㄥ啀杩涜杩滅▼銆�
-                    MqttInfoConfig.Current.HomeGatewayInfo = DB_ResidenceData.residenceData.HomeGateway;
+                    MqttInfoConfig.Current.HomeGatewayInfo = DB_ResidenceData.Instance.HomeGateway;
                     //3.寮�濮嬭繛鎺�
                     await MQTTConnectAsync();
                 }
                 else
                 {
                     Utlis.WriteLine("============>杩樻病缁戝畾缃戝叧");
+                    hadGateway = false;
                 }
             }
         }

--
Gitblit v1.8.0