From e08a444a9d7acea0cf39f50d22d29179f6a59292 Mon Sep 17 00:00:00 2001
From: 陈嘉乐 <cjl@hdlchina.com.cn>
Date: 星期二, 01 十二月 2020 09:37:11 +0800
Subject: [PATCH] 2020-12-1

---
 HDL_ON/DAL/Mqtt/MqttClient.cs |  802 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 802 insertions(+), 0 deletions(-)

diff --git a/HDL_ON/DAL/Mqtt/MqttClient.cs b/HDL_ON/DAL/Mqtt/MqttClient.cs
new file mode 100644
index 0000000..c06c840
--- /dev/null
+++ b/HDL_ON/DAL/Mqtt/MqttClient.cs
@@ -0,0 +1,802 @@
+锘�/*
+鏇存柊浜咵MQ杩炴帴鏂瑰紡
+*/
+using System.Collections.Generic;
+using System;
+using MQTTnet.Client;
+using System.Threading.Tasks;
+using Shared;
+using MQTTnet;
+using System.Text;
+using System.Security.Cryptography;
+using System.IO;
+using HDL_ON.DriverLayer;
+
+namespace HDL_ON.DAL.Mqtt
+{
+    public static class MqttClient
+    {
+        /// <summary>
+        /// 鍔犲瘑閫氳KEY
+        /// </summary>
+        static string mqttEncryptKey = "";
+        //static string checkGatewayTopicBase64 = "";
+
+        /// <summary>
+        /// 鎸や笅绾夸富棰�
+        /// </summary>
+        static readonly string PushNotifySqueeze = "/Push/NotifySqueeze";
+
+        /// <summary>
+        /// 闅忔満Key
+        /// </summary>
+        static string RandomKey = "";
+
+        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();
+            }
+
+            return RandomKey;
+
+        }
+
+        /// <summary>
+        /// 杩滅▼MqttClient
+        /// </summary>
+        public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient();
+
+        /// <summary>
+        /// 鎺ㄩ�佹爣璇�
+        /// </summary>
+        static string PushSignStr = DateTime.Now.Ticks.ToString();
+
+        /// <summary>
+        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
+        /// </summary>
+        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);
+                    await RemoteMqttClient.DisconnectAsync();
+
+                    if (Control.Ins.IsRemote)
+                    {
+                        Control.Ins.GatewayOnline = false;
+                    }
+                }
+            }
+            catch (Exception e)
+            {
+                Utlis.WriteLine($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
+            }
+        }
+
+        /// <summary>
+        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
+        /// </summary>
+        static async Task DisConnectRemoteMqttClientWhenStart(string s = "")
+        {
+            try
+            {
+                remoteIsConnected = false;
+                isSubscribeSuccess = false;
+                Utlis.WriteLine($"RemoteStart涓诲姩鏂紑_{s}");
+                await RemoteMqttClient.DisconnectAsync();
+            }
+            catch (Exception e)
+            {
+                Utlis.WriteLine($"RemoteStart鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
+            }
+        }
+
+        /// <summary>
+        /// 鏂紑mqtt杩炴帴
+        /// </summary>
+        /// <param name="s">鏂紑鍘熷洜</param>
+        /// <param name="reset">鏄惁闇�瑕佸幓涓績鏈嶅姟鍣� 閲嶆柊鑾峰彇鍙傛暟</param>
+        /// <returns></returns>
+        public static async Task DisConnectRemote(string s = "", bool reset = true)
+        {
+            if (reset)
+            {
+                MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
+            }
+            await DisConnectRemoteMqttClient(s);
+        }
+
+        /// <summary>
+        /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
+        /// </summary>
+        public static bool remoteMqttIsConnecting;
+        static bool remoteIsConnected;
+
+        static MqttClient()
+        {
+            InitMqtt();
+        }
+
+        public static bool IsInitMqtt = false;
+
+        static void InitMqtt()
+        {
+            new System.Threading.Thread(async () => {
+                while (true)
+                {
+                    try
+                    {
+                        System.Threading.Thread.Sleep(500);
+                        if (!Control.Ins.IsRemote) continue;
+
+                        await StartCloudMqtt();
+                        await SubscribeTopics();
+                    }
+                    catch { }
+                }
+            })
+            { IsBackground = true }.Start();
+        }
+
+        /// <summary>
+        /// 鍒濆鍖栫姸鎬�
+        /// </summary>
+        public static void InitState()
+        {
+            IfNeedReadAllDeviceStatus = true;
+            StartCloudMqtt();
+        }
+
+        static bool isSubscribeSuccess;
+        static async Task SubscribeTopics()
+        {
+            if (remoteIsConnected && !isSubscribeSuccess)
+            {
+                try
+                {
+                    //2020-05-14 璁㈤槄涓婚璐ㄩ噺鏀逛负0
+                    var topicFilterBusGateWayToClient = new MqttTopicFilter()
+                    {
+                        Topic = $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.id}/#",
+                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
+                        //QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
+                    };
+
+                    var topicFilterPush2 = new MqttTopicFilter
+                    {
+                        Topic = $"/BusGateWayToClient/{UserInfo.Current.ID}/#",
+                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce,
+                        //QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
+                    };
+
+                    Utlis.WriteLine("寮�濮嬭闃咃紒");
+                    var result = await RemoteMqttClient.SubscribeAsync(new MqttTopicFilter[] { topicFilterBusGateWayToClient, topicFilterPush2 });
+                    if (result.Items[0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS0)
+                    {
+                        isSubscribeSuccess = true;
+                        Utlis.WriteLine("璁㈤槄鎴愬姛锛�");
+
+                        MqttRemoteSend(new byte[] { 0 }, 3);
+
+                        //杩炴帴鎴愬姛鍚庢娴嬫槸鍚﹂渶瑕侀�氳繃杩滅▼鑾峰彇Key
+                        //CheckIfNeedGetLocalPasswordFromRemote();
+                    }
+                }
+                catch (Exception ex)
+                {
+                    Console.WriteLine("璁㈤槄catch:" + ex.Message.ToString());
+                }
+            }
+        }
+
+        /// <summary>
+        /// 鍚姩杩滅▼Mqtt
+        /// </summary>
+        public static async Task StartCloudMqtt()
+        {
+
+            if (OnAppConfig.Instance.internetStatus == 0)
+            {
+                return;
+            }
+
+            if (!UserInfo.Current.IsLogin)
+            {
+                return;
+            }
+
+            //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺
+            if (remoteMqttIsConnecting || remoteIsConnected)
+            {
+                return;
+            }
+
+            Utlis.WriteLine($"StartCloudMqtt: 寮�濮�");
+
+            await Task.Factory.StartNew(async () => {
+                try
+                {
+                    #region 鍒濆鍖栬繙绋婱qtt
+
+                    RemoteMqttClient = new MqttFactory().CreateMqttClient();
+
+
+                    //(1)褰揫杩炴帴浜戠鐨凪qtt鎴愬姛鍚嶿鎴栬�匸浠ュ強鍚庨潰App閫氳繃浜戠Mqtt杞彂鏁版嵁缁欑綉鍏虫垚鍔熷悗],澶勭悊鎺ユ敹鍒颁簯绔暟鎹寘鍝嶅簲鏃跺湪mqttServerClient_ApplicationMessageReceived杩欎釜鏂规硶澶勭悊
+                    if (RemoteMqttClient.ApplicationMessageReceivedHandler == null)
+                    {
+                        //澶勭悊鎺ユ敹鍒扮殑鏁版嵁
+                        RemoteMqttClient.UseApplicationMessageReceivedHandler((e) => {
+                            try
+                            {
+                                var topic = e.ApplicationMessage.Topic;
+                                if (topic == $"/BusGateWayToClient/{UserInfo.Current.ID}" + PushNotifySqueeze)
+                                {
+                                    var mMes = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
+                                    //鏂版尋涓嬬嚎涓婚鏂规 鏀跺埌鎸や笅绾夸富棰�
+                                    ReceiveNotifySqueezeAsync(mMes);
+                                }
+                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.id}/NotifyBusGateWayInfoChange")
+                                {//缃戝叧涓婄嚎锛岄渶瑕佹洿鏂癮eskey
+                                    //鏀跺埌缃戝叧涓婄嚎娑堟伅涓婚
+                                    ReceiveNotifyBusGateWayInfoChange();
+                                }
+                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.id}/NotifyGateWayOffline")
+                                {//缃戝叧鎺夌嚎
+                                    //----绗簩姝ワ細璇诲彇璐﹀彿涓嬮潰鐨勭綉鍏冲垪琛�
+                                    ReceiveNotifyGateWayOffline();
+                                }
+                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.id}/Common/CheckGateway")
+                                {
+                                    var ss = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
+                                    ReceiveCheckGateway(ss);
+                                }
+                                else
+                                {
+                                    SetGatewayOnlineResetCheck();
+                                    if (Entity.DB_ResidenceData.residenceData.GatewayType == 0)
+                                    {
+                                        var packet = new Packet();
+
+                                        if (!string.IsNullOrEmpty(mqttEncryptKey))
+                                        {
+                                            packet.Bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
+                                        }
+                                        else
+                                        {
+                                            packet.Bytes = e.ApplicationMessage.Payload;
+                                        }
+                                        packet.Manager();
+                                    }
+                                    else
+                                    {
+                                        //A鍗忚鏁版嵁澶勭悊
+                                    }
+                                }
+                            }
+                            catch { }
+                        });
+                    }
+
+                    //(2)DisconnectedHandler
+                    if (RemoteMqttClient.DisconnectedHandler == null)
+                    {
+                        RemoteMqttClient.UseDisconnectedHandler(async (e) => {
+                            Utlis.WriteLine($"杩滅▼杩炴帴鏂紑");
+                            isSubscribeSuccess = false;
+                            await DisConnectRemoteMqttClient("UseDisconnectedHandler");
+                        });
+                    }
+                    //(3)ConnectedHandler
+                    if (RemoteMqttClient.ConnectedHandler == null)
+                    {
+                        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
+                    //}
+
+                    //(4)===========寮�濮嬭繛鎺ヨ繃绋�==========
+                    //涔嬪墠宸茬粡鑾峰彇鍙傛暟鎴愬姛杩�
+                    if (MqttInfoConfig.Current.IfGetMqttInfoSuccess)
+                    {
+                        //鍒ゆ柇鏄惁闇�瑕侀噸鏂拌幏鍙�
+                        await CheckMQTTConnectAsync();
+                    }
+                    else
+                    {
+                        //寮�濮嬭幏鍙栬繙绋嬭繛鎺ュ弬鏁�
+                        await StartMQTTGetInfo();
+                    }
+
+                }
+                catch (Exception ex)
+                {
+                    Utlis.WriteLine($"error:" + ex.Message);
+                }
+                finally
+                {
+                    //鏈�缁堣閲婃斁杩炴帴鐘舵��
+                    remoteMqttIsConnecting = false;
+
+                    Utlis.WriteLine($"StartCloudMqtt: 缁撴潫");
+                }
+
+            });
+        }
+
+
+        /// <summary>
+        /// 妫�娴嬫槸鍚﹂渶瑕佸彂閫佸埛鏂拌幏鍙栨墍鏈夎澶囩殑鍛戒护
+        /// </summary>
+        static void CheckIfNeedReadAllDeviceStatus()
+        {
+            if (IfNeedReadAllDeviceStatus)
+            {
+                Utlis.WriteLine("ReadAllDeviceStatus");
+                IfNeedReadAllDeviceStatus = false;
+            }
+        }
+
+
+        /// <summary>
+        /// 妫�娴嬩箣鍓嶈幏鍙栫殑Mac涓庡綋鍓嶄綇瀹匨AC鏄惁涓�鑷� 涓嶄竴鑷翠粠鏂拌幏鍙�
+        /// </summary>
+        /// <returns></returns>
+        static async Task CheckMQTTConnectAsync()
+        {
+            try
+            {
+                if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.HomeGatewayInfo.mac == Entity.DB_ResidenceData.residenceData.residenceGatewayMAC)
+                {
+                    await MQTTConnectAsync();
+                }
+                else
+                {
+                    //Mac 鍙樺寲浜嗛噸鏂拌幏鍙栧弬鏁�
+                    await StartMQTTGetInfo();
+                }
+            }
+            catch
+            {
+                MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
+            }
+
+        }
+
+        /// <summary>
+        /// 寮�濮嬭幏鍙朚qtt 杩滅▼鍙傛暟
+        /// </summary>
+        /// <returns></returns>
+        static async Task StartMQTTGetInfo()
+        {
+            if (!Control.Ins.IsRemote)
+            {
+                return;
+            }
+
+            await GetMqttInfoAndMQTTConnectAsync();
+
+            ////--鍒ゆ柇鏄綋鍓嶆槸鍚﹀垎浜殑浣忓畢
+            //if (!UserConfig.Instance.CurrentRegion.IsOthreShare) {
+            //    //涓昏处鍙疯幏鍙朚QTT 杩滅▼閾炬帴淇℃伅锛屽苟杩炴帴
+            //    await GetMqttInfoAndMQTTConnectAsync ();
+            //} else {
+            //    //濡傛灉鏄垎浜繃鏉ョ殑浣忓畢 璧颁笅闈㈡祦绋�
+            //    //--绗竴姝ワ細鑾峰彇褰撳墠浣忓垎浜畢缃戝叧淇℃伅骞惰繛鎺QTT
+            //    await GetSingleHomeGatewayPaggerAndMQTTConnectAsync ();
+            //}
+        }
+
+        /// <summary>
+        /// 杩炴帴MQTT
+        /// </summary>
+        static async Task MQTTConnectAsync()
+        {
+
+            if (!Control.Ins.IsRemote)
+            {
+                return;
+            }
+
+            if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.mMqttInfo != null)
+            {
+                try
+                {
+
+                    var url = MqttInfoConfig.Current.mMqttInfo.url;
+
+                    //url = HttpUtil.GetProxyEMQUrl (url);
+                    //#if DEBUG
+                    //                   url = HttpUtil.GetProxyEMQUrl (url);
+
+                    //#endif
+                    var clientId = MqttInfoConfig.Current.mMqttInfo.clientId;
+                    var username = MqttInfoConfig.Current.mMqttInfo.userName;
+                    var passwordRemote = MqttInfoConfig.Current.mMqttInfo.passWord;
+                    //鑾峰彇鍙傛暟鎴愬姛锛屼繚瀛樺埌鏈湴骞舵爣璁颁负true
+                    MqttInfoConfig.Current.IfGetMqttInfoSuccess = true;
+                    MqttInfoConfig.Current.Save();
+
+                    mqttEncryptKey = MqttInfoConfig.Current.HomeGatewayInfo.aesKey;
+
+                    var options1 = new MQTTnet.Client.Options.MqttClientOptionsBuilder()
+                                        .WithClientId(clientId)
+                                        .WithTcpServer(url.Split(':')[1].Substring("//".Length), int.Parse(url.Split(':')[2]))
+                                        .WithCredentials(username, passwordRemote)
+                                        .WithCleanSession()
+                                        .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V311)
+                                        .WithCommunicationTimeout(new TimeSpan(0, 0, 10))
+                                        //.WithCommunicationTimeout (new TimeSpan (0, 0, 5))
+                                        //.WithCommunicationTimeout (new TimeSpan (0, 1, 0))
+                                        .Build();
+
+                    await DisConnectRemoteMqttClient("StartRemoteMqtt");
+
+                    var mResult = await RemoteMqttClient.ConnectAsync(options1);
+
+                    if (mResult.ResultCode == MQTTnet.Client.Connecting.MqttClientConnectResultCode.Success)
+                    {
+                        remoteIsConnected = true;
+                        IsDisConnectingWithSendCatch = false;
+                    }
+                    else
+                    {
+                        //閲嶆柊涓績鏈嶅姟鍣ㄨ幏鍙栧弬鏁版爣璁�
+                        MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
+                    }
+
+                }
+                catch (Exception ex)
+                {
+
+                    //閲嶆柊涓績鏈嶅姟鍣ㄨ幏鍙栧弬鏁版爣璁�
+                    MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
+                    Console.WriteLine("Connect error: " + ex.Message);
+                }
+                finally
+                {
+
+                }
+
+            }
+            else
+            {
+                MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
+            }
+
+        }
+
+        /// <summary>
+        /// 鏀跺埌缃戝叧涓婄嚎娑堟伅
+        /// </summary>
+        static void ReceiveNotifyBusGateWayInfoChange()
+        {
+            try
+            {
+                SetGatewayOnlineResetCheck();
+                if (Control.Ins.IsRemote)
+                {
+                    CheckIfNeedReadAllDeviceStatus();
+                }
+
+            }
+            catch { }
+        }
+
+        /// <summary>
+        /// 鏀跺埌缃戝叧鎺夌嚎淇℃伅
+        /// </summary>
+        static void ReceiveNotifyGateWayOffline()
+        {
+            if (Control.Ins.IsRemote)
+            {
+                Control.Ins.GatewayOnline = false;
+            }
+        }
+
+
+        /// <summary>
+        /// 鏀跺埌鎸や笅绾挎帹閫�
+        /// </summary>
+        static void ReceiveNotifySqueezeAsync(string mMes)
+        {
+
+            if (mMes == PushSignStr) return;//鏄嚜宸辩殑鐧诲綍鎺ㄩ�佷笉澶勭悊
+
+            //鏂紑杩滅▼杩炴帴
+            Control.Ins.IsRemote = false;
+            if (!UserInfo.Current.IsLogin)
+            {
+                return;
+            }
+
+            DisConnectRemoteMqttClient("鎸や笅绾�");
+
+            UserInfo.Current.LastTime = DateTime.MinValue;
+            UserInfo.Current.SaveUserInfo();
+
+            Application.RunOnMainThread(() => {
+                MainPage.GoLoginPage(UserInfo.Current);
+                //寮圭獥鎻愮ず琚尋涓嬬嚎
+            });
+
+            //2020-08-11 鍒犻櫎鎺ㄩ�佹暟鎹�
+            //HDLRequest.Current.PushserivceSignOut ();
+        }
+
+        /// <summary>
+        /// 鏀跺埌CheckGateway涓婚
+        /// </summary>
+        static void ReceiveCheckGateway(string mMes)
+        {
+            if (!Control.Ins.IsRemote) return;
+
+            Utlis.WriteLine("ReceiveCheckGateway锛�");
+
+            //CheckIfNeedReadAllDeviceStatus ();
+
+            //var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponsePack>(mMes);
+            Control.Ins.GatewayOnline = true;
+        }
+
+        /// <summary>
+        /// 鎺ㄩ�佹尋涓嬬嚎涓婚
+        /// </summary>
+        static void SendPushSignOut()
+        {
+            byte[] message = Encoding.UTF8.GetBytes(PushSignStr);
+            MqttRemoteSend(message, 4);
+        }
+
+        /// <summary>
+        /// 
+        /// </summary>
+        /// <param name="message">闄勫姞鏁版嵁鍖�</param>
+        /// <param name="optionType">鎿嶄綔绫诲瀷锛�0=缃戝叧鎺у埗锛�1=璁㈤槄缃戝叧鏁版嵁;2=璁㈤槄缃戝叧涓婄嚎鏁版嵁</param>
+        /// <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";
+                        if (!string.IsNullOrEmpty(mqttEncryptKey))
+                        {
+                            message = Securitys.EncryptionService.AesEncryptPayload(message, mqttEncryptKey);
+                        }
+                        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";
+                        Utlis.WriteLine("CheckGateway");
+                        await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicName, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
+                        break;
+                    case 4://鍙戝竷鏂版柟妗堢殑鎸や笅绾夸富棰�
+                        topicName = $"/BusGateWayToClient/{UserInfo.Current.ID}" + PushNotifySqueeze;
+                        //message = Encoding.UTF8.GetBytes (PushSignStr);
+                        await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
+                        break;
+                }
+            }
+            catch (Exception e)
+            {
+                //Utlis.WriteLine ($"============>Mqtt MqttRemoteSend catch");
+                if (!IsDisConnectingWithSendCatch)
+                {
+                    IsDisConnectingWithSendCatch = true;
+                    await DisConnectRemoteMqttClient("SendCatch");
+                }
+            }
+        }
+        /// <summary>
+        /// SendCatch 鍚庢墽琛屼竴娆℃柇寮�鎿嶄綔
+        /// </summary>
+        static bool IsDisConnectingWithSendCatch = false;
+
+
+        /// <summary>
+        /// 鏄惁闇�瑕佽鍙栦竴娆℃墍鏈夎澶囩姸鎬�
+        /// </summary>
+        static bool IfNeedReadAllDeviceStatus = true;
+        //public static bool IsGatewayOnline = true;
+
+        /// <summary>
+        /// 璁剧疆缃戝叧鍦ㄧ嚎鏍囧織锛屽苟閲嶇疆CheckGateway鍙傛暟
+        /// </summary>
+        static void SetGatewayOnlineResetCheck()
+        {
+            if (Control.Ins.IsRemote)
+            {
+                Control.Ins.GatewayOnline = true;
+            }
+        }
+
+
+        /// <summary>
+        /// 涓昏处鍙疯幏鍙朚QTT 杩滅▼閾炬帴淇℃伅锛屽苟杩炴帴
+        /// </summary>
+        /// <returns></returns>
+        static async Task GetMqttInfoAndMQTTConnectAsync()
+        {
+            var mqttInfoRequestResult_Obj = new Server.HttpServerRequest().GetMqttRemoteInfo(GetRandomKey());
+            if (mqttInfoRequestResult_Obj != null)
+            {
+                MqttInfoConfig.Current.mMqttInfo = mqttInfoRequestResult_Obj;
+                await MQTTConnectAsync();
+            }
+        }
+
+    }
+}
+
+
+public class MqttInfo
+{
+    /// <summary>
+    /// 
+    /// </summary>
+    public string url;
+    /// <summary>
+    /// 
+    /// </summary>
+    public string clientId;
+    /// <summary>
+    /// 
+    /// </summary>
+    public string userName;
+    /// <summary>
+    /// 
+    /// </summary>
+    public string passWord;
+}
+
+
+
+namespace Securitys
+{
+    public partial class EncryptionService
+    {
+
+        #region 鍔犲瘑
+        /// <summary>
+        /// 鍔犲瘑涓婚涓築ase64
+        /// </summary>
+        /// <param name="pToEncrypt"></param>
+        /// <param name="key"></param>
+        /// <returns></returns>
+        public static string AesEncryptTopic(string pToEncrypt, string key)
+        {
+            if (string.IsNullOrEmpty(pToEncrypt)) return null;
+            if (string.IsNullOrEmpty(key)) return pToEncrypt;
+            //闇�瑕佸姞瀵嗗唴瀹圭殑鏄庢枃娴�
+            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(pToEncrypt);
+
+            //閰嶇疆AES鍔犲瘑Key(瀵嗛挜銆佸悜閲忋�佹ā寮忋�佸~鍏�)
+            RijndaelManaged rm = new RijndaelManaged
+            {
+                Key = Encoding.UTF8.GetBytes(key),
+                IV = Encoding.UTF8.GetBytes(key),
+                Mode = CipherMode.CBC,
+                Padding = PaddingMode.PKCS7
+            };
+
+            //鍒涘缓AES鍔犲瘑鍣ㄥ璞�
+            ICryptoTransform cTransform = rm.CreateEncryptor();
+
+            //浣跨敤AES灏嗘槑鏂囨祦杞垚瀵嗘枃瀛楄妭鏁扮粍
+            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
+
+            //灏咥ES鐢熸垚鐨勫瘑鏂囧瓧鑺傛暟缁勮浆鎴怋ase64瀛楃涓�
+            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
+        }
+
+
+        /// <summary>
+        /// 鍔犲瘑璐熻浇涓轰簩杩涘埗娴�
+        /// </summary>
+        /// <param name="toEncryptArray"></param>
+        /// <param name="key"></param>
+        /// <returns></returns>
+        public static byte[] AesEncryptPayload(byte[] toEncryptArray, string key)
+        {
+            if (string.IsNullOrEmpty(key)) return toEncryptArray;
+            //閰嶇疆AES鍔犲瘑Key(瀵嗛挜銆佸悜閲忋�佹ā寮忋�佸~鍏�)
+            var rm = new RijndaelManaged
+            {
+                Key = Encoding.UTF8.GetBytes(key),
+                IV = Encoding.UTF8.GetBytes(key),
+                Mode = CipherMode.CBC,
+                Padding = PaddingMode.PKCS7
+            };
+
+            //鍒涘缓AES鍔犲瘑鍣ㄥ璞�
+            var cTransform = rm.CreateEncryptor();
+            //浣跨敤AES灏嗘槑鏂囨祦杞垚瀵嗘枃瀛楄妭鏁扮粍
+            return cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
+        }
+        #endregion
+
+
+        #region 瑙e瘑
+        /// <summary>
+        /// 瑙e瘑涓婚鏁版嵁
+        /// </summary>
+        /// <param name="pToDecrypt"></param>
+        /// <param name="key"></param>
+        /// <returns></returns>
+        public static string AesDecryptTopic(string pToDecrypt, string key)
+        {
+            //AES瀵嗘枃Base64杞垚瀛楃涓�
+            Byte[] toEncryptArray = Convert.FromBase64String(pToDecrypt);
+
+            //閰嶇疆AES鍔犲瘑Key(瀵嗛挜銆佸悜閲忋�佹ā寮忋�佸~鍏�)
+            RijndaelManaged rm = new RijndaelManaged
+            {
+                Key = Encoding.UTF8.GetBytes(key),
+                IV = Encoding.UTF8.GetBytes(key),
+                Mode = CipherMode.CBC,
+                Padding = PaddingMode.PKCS7
+            };
+
+            //鍒涘缓AES瑙e瘑鍣ㄥ璞�
+            ICryptoTransform cTransform = rm.CreateDecryptor();
+
+            //浣跨敤AES灏嗗瘑鏂囨祦杞垚鏄庢枃鐨勫瓧鑺傛暟缁�
+            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
+
+            //杞垚瀛楃涓�
+            return Encoding.UTF8.GetString(resultArray);
+        }
+
+        /// <summary>
+        /// 閲囩敤Aes瑙e瘑璐熻浇鏁版嵁
+        /// </summary>
+        /// <param name="toEncryptArray"></param>
+        /// <param name="key"></param>
+        /// <returns></returns>
+        public static byte[] AesDecryptPayload(byte[] toEncryptArray, string key)
+        {
+            //閰嶇疆AES鍔犲瘑Key(瀵嗛挜銆佸悜閲忋�佹ā寮忋�佸~鍏�)
+            var rm = new RijndaelManaged
+            {
+                Key = Encoding.UTF8.GetBytes(key),
+                IV = Encoding.UTF8.GetBytes(key),
+                Mode = CipherMode.CBC,
+                Padding = PaddingMode.PKCS7
+            };
+
+            //鍒涘缓AES瑙e瘑鍣ㄥ璞�
+            var cTransform = rm.CreateDecryptor();
+
+            //浣跨敤AES灏嗗瘑鏂囨祦杞垚鏄庢枃鐨勫瓧鑺傛暟缁�
+            return cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
+        }
+        #endregion
+
+
+
+    }
+}

--
Gitblit v1.8.0