From 4e6dfedede622d018b0aec0fb85c130d47cf45ba Mon Sep 17 00:00:00 2001
From: JLChen <551775569@qq.com>
Date: 星期三, 25 十一月 2020 16:14:39 +0800
Subject: [PATCH] 2020-11-25 1.增加服务器信息、关于ON、功能介绍、投诉、检测更新。

---
 HDL_ON/DAL/Net/MqttCommon.cs | 1574 ++++++++++++++++++++++++++++++++++++++++++++-------------
 1 files changed, 1,201 insertions(+), 373 deletions(-)

diff --git a/HDL_ON/DAL/Net/MqttCommon.cs b/HDL_ON/DAL/Net/MqttCommon.cs
index 279056c..5a3594e 100644
--- a/HDL_ON/DAL/Net/MqttCommon.cs
+++ b/HDL_ON/DAL/Net/MqttCommon.cs
@@ -1,398 +1,1226 @@
 锘縰sing System.Collections.Generic;
 using System;
-using MQTTnet.Client;
 using System.Text;
 using System.Security.Cryptography;
+using MQTTnet.Client;
 using MQTTnet;
-using MQTTnet.Client.Options;
-using System.Net.Sockets;
 using System.Threading.Tasks;
-//using System.Net;
-//using Newtonsoft.Json.Linq;
-//using HDL_ON.DAL;
-//using Newtonsoft.Json;
+using Shared;
+using HDL_ON.DAL.Server;
 
 namespace HDL_ON.DAL.Net
 {
-    public static class MqttCommon
+
+//    public static class MqttCommon
+//    {
+//        /// <summary>
+//        /// 鏄惁鎻愮ず 杩滅▼杩炴帴鐨勯敊璇俊鎭� 
+//        /// </summary>
+//        public static bool IfDEBUG = false;
+
+//        /// <summary>
+//        /// 鍔犲瘑閫氳KEY
+//        /// </summary>
+//        static string mqttEncryptKey = "";
+//        //static string checkGatewayTopicBase64 = "";
+
+//        /// <summary>
+//        /// 鎸や笅绾夸富棰�
+//        /// </summary>
+//        static readonly string PushNotifySqueeze = "/Push/NotifySqueeze";
+
+//        ///// <summary>
+//        ///// 鎸や笅绾夸富棰�
+//        ///// </summary>
+//        //static readonly string TopicToApp = "/Push/NotifySqueeze";
+
+
+//        /// <summary>
+//        /// 闅忔満Key
+//        /// </summary>
+//        static string RandomKey = "";
+
+//        static string GetRandomKey()
+//        {
+//            if (string.IsNullOrEmpty(RandomKey))
+//            {
+//                //闅忔満2浣嶅瓧绗︿覆
+//                RandomKey = Utlis.CreateRandomString(2);
+//            }
+
+//            return RandomKey;
+
+//        }
+
+//        /// <summary>
+//        /// 杩滅▼MqttClient
+//        /// </summary>
+//        public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient();
+
+
+//        /// <summary>
+//        /// 鎺ㄩ�佹爣璇�
+//        /// </summary>
+//        static string PushSignStr = System.DateTime.Now.Ticks.ToString();
+
+//        /// <summary>
+//        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
+//        /// </summary>
+//        static async System.Threading.Tasks.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 (MainPage.IsRemote)
+//                    {
+//                        ////涓嶆槸鏃犵綉缁�
+//                        //if (UserConfig.Instance.internetStatus != 0)
+//                        //{
+//                        //    Utlis.ShowAppLinkStatus(AppLinkStatus.CloudUnlink);
+//                        //}
+//                    }
+//                }
+//            }
+//            catch (Exception e)
+//            {
+//                Utlis.WriteLine($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
+//            }
+//        }
+
+//        /// <summary>
+//        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
+//        /// </summary>
+//        static async Task DisConnectRemoteMqttClientWhenStart(string s = "")
+//        {
+//            try
+//            {
+//                //if (remoteIsConnected) {
+//                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)
+//            {
+//                bNeedStartTip = true;
+//                bNeedConnectTip = true;
+//                MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
+//            }
+//            await DisConnectRemoteMqttClient(s);
+//        }
+
+//        //static DateTime dateTime = DateTime.MinValue;
+//        /// <summary>
+//        /// 澶栫綉鐨凪QTT鏄惁姝e湪杩炴帴
+//        /// </summary>
+//        public static bool remoteMqttIsConnecting;
+//        static bool remoteIsConnected;
+
+//        static MqttCommon()
+//        {
+//            InitMqtt();
+//        }
+
+//        public static bool IsInitMqtt = false;
+
+
+
+//        static void InitMqtt()
+//        {
+//            new System.Threading.Thread(async () =>
+//            {
+//                while (true)
+//                {
+//                    try
+//                    {
+//                        System.Threading.Thread.Sleep(500);
+
+//                        if (!MainPage.IsRemote) continue;
+
+//                        //if (BusSocket.IsEnterBackground) continue;
+
+//                        await StartCloudMqtt();
+//                        await SubscribeTopics();
+//                    }
+//                    catch { }
+//                }
+//            })
+//            { IsBackground = true }.Start();
+//        }
+
+//        /// <summary>
+//        /// 鍒濆鍖栫姸鎬�
+//        /// </summary>
+//        public static void InitState()
+//        {
+//            IfNeedReadAllDeviceStatus = true;
+//            bNeedStartTip = true;
+//            bNeedConnectTip = true;
+//            IsGatewayOnline = false;
+//            StartCloudMqtt();
+
+//        }
+
+//        static bool isSubscribeSuccess;
+//        static async Task SubscribeTopics()
+//        {
+//            if (remoteIsConnected && !isSubscribeSuccess)
+//            {
+//                try
+//                {
+
+//                    //var topicFilterPush = new TopicFilter { QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce,
+//                    //    Topic = $"/BusGateWayToClient/{MqttInfoConfig.Instance.CurRemoteMACInfo.clientId}/Push/NotifySqueeze" };
+
+//                    //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/{MainPage.LoginUser.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);
+
+//                        //璇诲彇鎼滅储缃戝叧锛屽垽鏂綉鍏虫槸鍚﹀湪绾�
+//                        CheckGatewaysIfOnline();
+
+//                        //杩炴帴鎴愬姛鍚庢娴嬫槸鍚﹂渶瑕侀�氳繃杩滅▼鑾峰彇Key
+//                        CheckIfNeedGetLocalPasswordFromRemote();
+//                    }
+
+
+//                }
+//                catch (Exception ex)
+//                {
+//                    Console.WriteLine("璁㈤槄catch:" + ex.Message.ToString());
+//                }
+//            }
+//        }
+
+//        static DateTime mFlagDateTime;
+
+//        //static readonly object SendLocker = new object ();
+//        /// <summary>
+//        /// 鍚姩杩滅▼Mqtt
+//        /// </summary>
+//        public static async Task StartCloudMqtt()
+//        {
+
+//            if (UserConfig.Instance.internetStatus == 0)
+//            {
+//                return;
+//            }
+
+//            if (!UserInfo.Current.IsLogin)
+//            {
+//                return;
+//            }
+
+//            //杩藉姞锛氭病鏈夎繙绋嬭繛鎺ョ殑鏉冮檺
+//            if (remoteMqttIsConnecting || remoteIsConnected)
+//            {
+//                return;
+//            }
+
+//            //lock (SendLocker) {
+//            //    remoteMqttIsConnecting = true;
+//            //}
+//            remoteMqttIsConnecting = true;
+//#if DEBUG
+//            Utlis.WriteLine($"StartCloudMqtt: 寮�濮�");
+//#endif
+
+//            await Task.Factory.StartNew(async () =>
+//            {
+//                try
+//                {
+//                    //lock (RemoteMqttClient) {
+//                    //    //琛ㄧず鍚庨潰灏嗚繘琛岃繛鎺�
+//                    //    remoteMqttIsConnecting = true;
+
+//                    #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 = CommonPage.MyEncodingUTF8.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 = CommonPage.MyEncodingUTF8.GetString(e.ApplicationMessage.Payload);
+//                                    ReceiveCheckGateway(ss);
+//                                }
+//                                else
+//                                {
+
+//                                    SetGatewayOnlineResetCheck();
+
+//                                    var packet = new Packet();
+
+//                                    if (!string.IsNullOrEmpty(mqttEncryptKey))
+//                                    {
+//                                        packet.Bytes = Shared.Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
+//                                    }
+//                                    else
+//                                    {
+//                                        packet.Bytes = e.ApplicationMessage.Payload;
+//                                    }
+//                                    packet.IsLocal = false;
+//                                    packet.Manager();
+//                                }
+//                            }
+//                            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;
+//                            bNeedStartTip = true;//
+//                            bNeedConnectTip = true;
+//                            Utlis.WriteLine($"============>Mqtt杩滅▼杩炴帴鎴愬姛");
+//                            SendPushSignOut();
+
+//                            //if (CommonPage.IsRemote) {
+//                            //    //Utlis.ShowAppLinkStatus (AppLinkStatus.CloudLink);
+//                            //    MainPage.AddTip (Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
+//                            //}
+//                        });
+//                    }
+//                    #endregion
+//                    //}
+
+//                    //(4)===========寮�濮嬭繛鎺ヨ繃绋�==========
+//                    //涔嬪墠宸茬粡鑾峰彇鍙傛暟鎴愬姛杩�
+//                    if (MqttInfoConfig.Current.IfGetMqttInfoSuccess)
+//                    {
+//                        //鍒ゆ柇鏄惁闇�瑕侀噸鏂拌幏鍙�
+//                        await CheckMQTTConnectAsync();
+//                    }
+//                    else
+//                    {
+//                        //寮�濮嬭幏鍙栬繙绋嬭繛鎺ュ弬鏁�
+//                        await StartMQTTGetInfo();
+//                    }
+
+//                }
+//                catch (Exception ex)
+//                {
+//                    Utlis.WriteLine($"error:" + ex.Message);
+//                    if (IfDEBUG)
+//                    {
+//                        Utlis.ShowAlertOnMainThread("error: " + ex.Message);
+//                    }
+//                }
+//                finally
+//                {
+//                    //鏈�缁堣閲婃斁杩炴帴鐘舵��
+//                    remoteMqttIsConnecting = false;
+
+//                    //lock (SendLocker) {
+//                    //    remoteMqttIsConnecting = false;
+//                    //}
+
+//                    //杩炴帴鎴愬姛鎵嶅叧闂璍oading
+//                    if (remoteIsConnected)
+//                    {
+//                        //MainPage.LoadingTipHide();
+//                        ERRORCount = 0;
+//                    }
+//                    else
+//                    {
+//                        ERRORCount++;
+//                        //姣�5娆¢噸鏂版彁绀轰竴娆�
+//                        if (ERRORCount > 5)
+//                        {
+//                            ERRORCount = 0;
+//                            //MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.RemoteFailure));
+//                            //MainPage.LoadingTipHide();
+
+//                        }
+//                    }
+
+//#if DEBUG
+//                    Utlis.WriteLine($"StartCloudMqtt: 缁撴潫");
+//#endif
+//                }
+
+//            });
+//        }
+
+//        //static bool 
+
+
+//        /// <summary>
+//        /// 妫�鏌ョ綉鍏虫槸鍚﹀湪绾跨嚎绋�
+//        /// </summary>
+//        static System.Threading.Thread CheckGatewaysThead;
+
+//        /// <summary>
+//        /// 妫�鏌ョ綉鍏虫槸鍚﹀湪绾�
+//        /// </summary>
+//        static void CheckGatewaysIfOnline()
+//        {
+//            if (GatewayCommon == null) return;
+
+//            try
+//            {
+//                //鎻愮ず鎼滅储缃戝叧涓�
+//                //MainPage.LoadingTipShow(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.SubscriptionSuccessful));
+
+//                if (CheckGatewaysThead != null)
+//                    CheckGatewaysThead.Abort();
+
+//                //CheckGatewaysThead = new System.Threading.Thread(() => {
+//                //    var returnBytes = Control.ControlBytesSendHasReturn(Command.ReadGateway, GatewayCommon.SubnetID, GatewayCommon.DeviceID, new byte[] { (byte)new Random().Next(255), (byte)new Random().Next(255) });
+//                //    //闅愯棌鎻愮ず
+//                //    MainPage.LoadingTipHide();
+//                //    if (CommonPage.IsRemote)
+//                //    {
+//                //        if (returnBytes == null)
+//                //        {
+//                //            Application.RunOnMainThread(() => {
+//                //                IsGatewayOnline = false;
+//                //                Utlis.ShowAppLinkStatus(AppLinkStatus.CloudOffline);
+//                //                MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.RemoteFailedGatewayOffline));
+//                //                //鍙戦�佷竴娆heckGateway涓婚
+//                //                MqttRemoteSend(new byte[] { 0 }, 3);
+//                //            });
+//                //        }
+//                //        else
+//                //        {
+//                //            MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
+
+//                //            IsGatewayOnline = true;
+//                //            Utlis.ShowAppLinkStatus(AppLinkStatus.CloudLink);
+//                //            Console.WriteLine("ReadGateway success");
+//                //            CheckIfNeedReadAllDeviceStatus();
+//                //        }
+//                //    }
+//                //})
+//                //{ IsBackground = true };
+
+//                //CheckGatewaysThead.Start();
+//            }
+//            catch
+//            {
+
+//            }
+//        }
+
+
+//        /// <summary>
+//        /// 妫�娴嬫槸鍚﹂渶瑕佸彂閫佸埛鏂拌幏鍙栨墍鏈夎澶囩殑鍛戒护
+//        /// </summary>
+//        static void CheckIfNeedReadAllDeviceStatus()
+//        {
+//            if (IfNeedReadAllDeviceStatus)
+//            {
+//                Utlis.WriteLine("ReadAllDeviceStatus");
+//                IfNeedReadAllDeviceStatus = false;
+//                //Shared.SimpleControl.Phone.UserMiddle.ReadAllDeviceStatus();
+//            }
+
+//        }
+
+
+
+//        //杩炴帴閿欒娆℃暟缁熻
+//        static int ERRORCount = 0;
+
+//        /// <summary>
+//        /// 鏄惁闇�瑕佹彁绀�
+//        /// </summary>
+//        static bool bNeedConnectTip = true;
+
+//        /// <summary>
+//        /// 浠庡紑濮嬪埌杩炴帴鎴愬姛锛屽彧鎻愮ず1娆�
+//        /// </summary>
+//        static bool bNeedStartTip = true;
+//        /// <summary>
+//        /// 姝e湪鑾峰彇杩炴帴鍙傛暟...
+//        /// </summary>
+//        static void ShowStartTip()
+//        {
+//            if (bNeedStartTip)
+//            {
+//                bNeedStartTip = false;
+//                if (MainPage.IsRemote)
+//                {
+//                    //MainPage.LoadingTipShow(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.GettingRemoteConnectionInfo));
+//                }
+//            }
+
+//        }
+
+//        /// <summary>
+//        /// 妫�娴嬩箣鍓嶈幏鍙栫殑Mac涓庡綋鍓嶄綇瀹匨AC鏄惁涓�鑷� 涓嶄竴鑷翠粠鏂拌幏鍙�
+//        /// </summary>
+//        /// <returns></returns>
+//        static async Task CheckMQTTConnectAsync()
+//        {
+//            //try
+//            //{
+//            //    if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.HomeGatewayInfo.mac == UserConfig.Instance.GatewayMAC)
+//            //    {
+//            //        await MQTTConnectAsync();
+//            //    }
+//            //    else
+//            //    {
+//            //        //Mac 鍙樺寲浜嗛噸鏂拌幏鍙栧弬鏁�
+//            //        await StartMQTTGetInfo();
+//            //    }
+//            //}
+//            //catch
+//            //{
+//            //    MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
+//            //}
+
+//        }
+
+//        /// <summary>
+//        /// 寮�濮嬭幏鍙朚qtt 杩滅▼鍙傛暟
+//        /// </summary>
+//        /// <returns></returns>
+//        static async Task StartMQTTGetInfo()
+//        {
+//            ShowStartTip();
+
+//            if (!MainPage.IsRemote)
+//            {
+//                return;
+//            }
+
+//            await GetMqttInfoAndMQTTConnectAsync();
+
+//            ////--鍒ゆ柇鏄綋鍓嶆槸鍚﹀垎浜殑浣忓畢
+//            //if (!UserConfig.Instance.CurrentRegion.IsOthreShare) {
+//            //    //涓昏处鍙疯幏鍙朚QTT 杩滅▼閾炬帴淇℃伅锛屽苟杩炴帴
+//            //    await GetMqttInfoAndMQTTConnectAsync ();
+//            //} else {
+//            //    //濡傛灉鏄垎浜繃鏉ョ殑浣忓畢 璧颁笅闈㈡祦绋�
+//            //    //--绗竴姝ワ細鑾峰彇褰撳墠浣忓垎浜畢缃戝叧淇℃伅骞惰繛鎺QTT
+//            //    await GetSingleHomeGatewayPaggerAndMQTTConnectAsync ();
+//            //}
+//        }
+
+
+//        /// <summary>
+//        /// 杩炴帴MQTT
+//        /// </summary>
+//        static async Task MQTTConnectAsync()
+//        {
+
+//            if (!MainPage.IsRemote)
+//            {
+//                return;
+//            }
+
+//            //if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.mMqttInfo != null)
+//            //{
+//            //    if (bNeedConnectTip)
+//            //    {
+//            //        bNeedConnectTip = false;
+//            //        MainPage.LoadingTipShow(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.GetSuccessfullyStartConnecting));
+//            //    }
+
+//            //    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;
+//            //            UnsupportedProtocolVersionCount = 0;
+//            //        }
+//            //        else
+//            //        {
+//            //            //閲嶆柊涓績鏈嶅姟鍣ㄨ幏鍙栧弬鏁版爣璁�
+//            //            MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
+//            //        }
+
+//            //    }
+//            //    catch (Exception ex)
+//            //    {
+
+//            //        if (ex.Message == MqttCommunicationTimedOutException)
+//            //        {
+//            //            Console.WriteLine("Connect error TimedOut: " + ex.Message);
+//            //        }
+//            //        else
+//            //        {
+//            //            //閲嶆柊涓績鏈嶅姟鍣ㄨ幏鍙栧弬鏁版爣璁�
+//            //            MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
+//            //            Console.WriteLine("Connect error: " + ex.Message);
+//            //        }
+
+//            //        //Console.WriteLine ("Connect error: " + ex.Message);
+//            //        if (IfDEBUG)
+//            //        {
+//            //            MainPage.ShowAlertOnMainThread("Connect error: " + ex.Message);
+//            //        }
+//            //    }
+//            //    finally
+//            //    {
+
+//            //    }
+
+//            //}
+//            //else
+//            //{
+//            //    MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
+//            //}
+
+//        }
+
+//        static int UnsupportedProtocolVersionCount = 0;
+//        static readonly string MqttCommunicationTimedOutException = "Exception of type 'MQTTnet.Exceptions.MqttCommunicationTimedOutException' was thrown.";
+//        //
+//        static readonly string UnsupportedProtocolVersion = "Connecting with MQTT server failed (UnsupportedProtocolVersion).";
+
+
+
+//        /// <summary>
+//        /// 鏀跺埌缃戝叧涓婄嚎娑堟伅
+//        /// </summary>
+//        static void ReceiveNotifyBusGateWayInfoChange()
+//        {
+//            try
+//            {
+//                SetGatewayOnlineResetCheck();
+//                if (MainPage.IsRemote)
+//                {
+//                    //#if DEBUG
+//                    //MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.GatewayLoginOnline));
+//                    //#endif
+//                    CheckIfNeedReadAllDeviceStatus();
+//                }
+
+//                GetSingleHomeGatewayPaggerAndMQTTConnectAsync(false);
+
+//            }
+//            catch { }
+//        }
+
+//        /// <summary>
+//        /// 鏀跺埌缃戝叧鎺夌嚎淇℃伅
+//        /// </summary>
+//        static void ReceiveNotifyGateWayOffline()
+//        {
+//            Utlis.WriteLine("============>Mqtt GateWayOffline");
+//            IsGatewayOnline = false;
+//            if (MainPage.IsRemote)
+//            {
+//                //Utlis.ShowAppLinkStatus(AppLinkStatus.CloudOffline);
+//                //MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.GatewayOffline));
+
+//            }
+//        }
+
+
+//        /// <summary>
+//        /// 鏀跺埌鎸や笅绾挎帹閫�
+//        /// </summary>
+//        static void ReceiveNotifySqueezeAsync(string mMes)
+//        {
+
+//            if (mMes == PushSignStr) return;//鏄嚜宸辩殑鐧诲綍鎺ㄩ�佷笉澶勭悊
+
+//            //鏂紑杩滅▼杩炴帴
+//            MainPage.IsRemote = false;
+//            if (!UserInfo.Current.IsLogin)
+//            {
+//                return;
+//            }
+
+//            DisConnectRemoteMqttClient("鎸や笅绾�");
+
+//            UserInfo.Current.lastTime = DateTime.MinValue;
+//            UserInfo.Current.SaveUserInfo();
+//            //Room.Lists.Clear();
+
+//            Application.RunOnMainThread(() =>
+//            {
+//                //Utlis.ShowAppLinkStatus(AppLinkStatus.WiFi);
+//                //new Shared.SimpleControl.Phone.AccountLogin(MainPage.LoginUser.AccountString, "").Show();
+//                //SharedMethod.SharedMethod.CurPageLayout = null;
+//                ////CommonPage.IsRemote = false;
+
+//                //MainPage.LoadingTipHide();
+//                //MainPage.Loading.Hide();
+
+//                //new Alert(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.Tip), Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.LoggedOnOtherDevices),
+//                //    Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.Close)).Show();
+//            });
+
+//            //2020-08-11 鍒犻櫎鎺ㄩ�佹暟鎹�
+//            //HDLRequest.Current.PushserivceSignOut ();
+
+//            //#if HDL
+//            //            if (!String.IsNullOrEmpty (MainPage.LoginUser.AllVisionRegisterDevUserNameGuid)) {
+//            //                com.freeview.global.Video.Logout ();
+//            //            }///BusGateWayToClient/320c1fea-1866-4708-8277-e2321a4dd236/NotifyGateWayInfoChange
+//            //#endif
+
+
+//        }
+
+//        /// <summary>
+//        /// 鏀跺埌CheckGateway涓婚
+//        /// </summary>
+//        static void ReceiveCheckGateway(string mMes)
+//        {
+//            if (!MainPage.IsRemote) return;
+
+//            Utlis.WriteLine("ReceiveCheckGateway锛�");
+
+//            //CheckIfNeedReadAllDeviceStatus ();
+
+//            var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponsePack>(mMes);
+//            if (obj == null)
+//            {
+//                //SetGatewayOnlineResetCheck ();
+//                return;
+//            }
+
+//            //switch (obj.StateCode)
+//            //{
+//            //    case "HDLUdpDataForwardServerMqttClientNoOnLine":
+//            //    case "NoOnline":
+//            //    case "NetworkAnomaly"://涓嶅湪绾�
+//            //        IsGatewayOnline = false;
+//            //        MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.RemoteFailedGatewayOffline));
+//            //        Utlis.ShowAppLinkStatus(AppLinkStatus.CloudOffline);
+
+//            //        break;
+//            //    case "NoRecord"://MAC涓嶆纭�
+//            //        IsGatewayOnline = false;
+//            //        MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.MACError));
+//            //        Utlis.ShowAppLinkStatus(AppLinkStatus.CloudOffline);
+//            //        break;
+//            //    case "Success":
+//            //        SetGatewayOnlineResetCheck();
+//            //        IsGatewayOnline = true;
+//            //        //MainPage.AddTip (UserConfig.Instance.CurrentRegion.Name + ":" + Language.StringByID (Shared.SimpleControl.R.MyInternationalizationString.LinkSuccess));
+//            //        break;
+//            //    default:
+//            //        IsGatewayOnline = false;
+//            //        MainPage.AddTip(Language.StringByID(Shared.SimpleControl.R.MyInternationalizationString.LinkLoser));
+//            //        Utlis.ShowAppLinkStatus(AppLinkStatus.CloudOffline);
+//            //        break;
+//            //}
+
+//        }
+
+//        /// <summary>
+//        /// 鎺ㄩ�佹尋涓嬬嚎涓婚
+//        /// </summary>
+//        static void SendPushSignOut()
+//        {
+//            byte[] message = CommonPage.MyEncodingUTF8.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 = Shared.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";
+//                        Shared.Utlis.WriteLine("CheckGateway");
+//                        await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicName, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
+//                        break;
+//                    case 4://鍙戝竷鏂版柟妗堢殑鎸や笅绾夸富棰�
+//                        topicName = $"/BusGateWayToClient/{MainPage.LoginUser.ID}" + PushNotifySqueeze;
+//                        //message = CommonPage.MyEncodingUTF8.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;
+//        //static int CheckGatewayCount = 0;
+//        //static DateTime mCheckGatewayTime;
+
+
+//        /// <summary>
+//        /// 璁剧疆缃戝叧鍦ㄧ嚎鏍囧織锛屽苟閲嶇疆CheckGateway鍙傛暟
+//        /// </summary>
+//        static void SetGatewayOnlineResetCheck()
+//        {
+
+//            //mCheckGatewayTime = DateTime.Now;
+//            //CheckGatewayCount = 0;
+//            if (MainPage.IsRemote)
+//            {
+//                if (!IsGatewayOnline)
+//                {
+//                    IsGatewayOnline = true;
+//                    //Utlis.ShowAppLinkStatus(AppLinkStatus.CloudLink);
+//                }
+//            }
+//        }
+
+
+//        /// <summary>
+//        /// 涓昏处鍙疯幏鍙朚QTT 杩滅▼閾炬帴淇℃伅锛屽苟杩炴帴
+//        /// </summary>
+//        /// <returns></returns>
+//        static async Task GetMqttInfoAndMQTTConnectAsync()
+//        {
+//            var mqttInfoRequestResult_Obj = new HttpServerRequest().GetMqttRemoteInfo(GetRandomKey());
+//            if (mqttInfoRequestResult_Obj != null)
+//            {
+//                //MqttInfoConfig.Current.mMqttInfo = mqttInfoRequestResult_Obj;
+//                //if (UserConfig.Instance.GatewayList != null && UserConfig.Instance.GatewayList.Count > 0)
+//                //{
+//                //    //----绗簩姝ユ壘鍑烘槸鍚﹀瓨鍦ㄥ尮閰嶅綋鍓嶄綇瀹呯殑mac锛屽瓨鍦ㄥ啀杩涜杩滅▼銆�
+//                //    MqttInfoConfig.Current.HomeGatewayInfo = UserConfig.Instance.GatewayList[0];
+//                //    if (MqttInfoConfig.Current.HomeGatewayInfo != null)
+//                //    {
+//                //        //----绗笁姝� 寮�濮嬭繛鎺�
+//                //        await MQTTConnectAsync();
+//                //    }
+//                //}
+//                //else
+//                //{
+//                //    Utlis.WriteLine("============>杩樻病缁戝畾缃戝叧");
+//                //}
+
+//            }
+//            else
+//            {
+//                Utlis.WriteLine("============>MqttInfo null");
+//            }
+
+//        }
+
+
+//        /// <summary>
+//        /// 鍒嗕韩浣忓畢 鑾峰彇褰撳墠浣忓畢缃戝叧淇℃伅骞朵笖杩炴帴MQTT 鎴栬�呭埛鏂�  
+//        /// 2020-03-17
+//        /// </summary>
+//        static async Task GetSingleHomeGatewayPaggerAndMQTTConnectAsync(bool bNeedConnect = true)
+//        {
+//            ////--绗竴姝ワ細璇锋眰褰撳墠浣忓畢鍒扮綉鍏充俊鎭�
+//            //var requestObj3 = new GetSingleHomeGatewayPaggerObj ();
+//            //requestObj3.ReqDto.LoginAccessToken = MainPage.LoginUser.LoginTokenString;
+//            //requestObj3.ReqDto.HomeId = UserConfig.Instance.CurrentRegion.Id;
+//            //requestObj3.ReqDto.PageSetting.Page = 1;
+//            //requestObj3.ReqDto.PageSetting.PageSize = 10;
+//            //string urlHead = MainPage.RequestHttpsHostZigbee;
+//            //if (requestObj3.IsOtherAccountCtrl) {
+//            //    urlHead = UserConfig.Instance.MasterAccountRequestBaseUrl;
+//            //    requestObj3.ReqDto.LoginAccessToken = UserConfig.Instance.MasterAccountToken;
+//            //}
+
+//            ////urlHead = MainPage.RequestHttpsHostZigbee;
+
+//            //var requestJson3 = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj3);
+//            //var revertObj3 = MainPage.RequestHttpsNew (API.GetSingleHomeGatewayPagger, requestJson3, urlHead);
+//            //if (revertObj3.StateCode.ToUpper () == HttpUtil.SUCCESS_CODE) {
+//            //    var infoResult = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGatewayResult> (revertObj3.ResponseData.ToString ());
+//            //    if (bNeedConnect) {
+//            //        UserConfig.Instance.SetNowHomeGateways (infoResult.PageData);
+
+//            //        //var gatewayListRequestResult_Obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttRemoteInfo> (revertObj3.ResponseData.ToString ());
+//            //        //--鎵惧嚭鏄惁瀛樺湪鍖归厤褰撳墠浣忓畢鐨刴ac锛屽瓨鍦ㄥ啀杩涜杩滅▼銆�
+//            //        if (UserConfig.Instance.CheckHomeGatewaysNotEmpty ()) {
+//            //            var mGatewayRes = infoResult.PageData.Find ((obj) => obj.GatewayUniqueId == UserConfig.Instance.CurrentRegion.HomeGateways [0].GatewayUniqueId);
+//            //            if (mGatewayRes != null) {
+//            //                MqttInfoConfig.Instance.CurRemoteMACInfo = new RemoteMACInfo ();
+//            //                MqttInfoConfig.Instance.CurRemoteMACInfo.aesKey = mGatewayRes.AesKey;
+//            //                MqttInfoConfig.Instance.CurRemoteMACInfo.mac = mGatewayRes.GatewayUniqueId;
+//            //                MqttInfoConfig.Instance.CurRemoteMACInfo.macMark = mGatewayRes.MacMark;
+//            //                MqttInfoConfig.Instance.CurRemoteMACInfo.isValid = mGatewayRes.MqttOnlineStatus ? "Valid" : "InValid";
+//            //                //await MQTTConnectAsync ();
+
+//            //                var mqttInfoRequestPar = new ShareMemberConnMqttInfoObj () {
+//            //                    LoginAccessToken = MainPage.LoginUser.LoginTokenString,
+//            //                    PlatformStr = GetRandomKey(),
+//            //                    PublishPayloadJsonStr = PushSignStr,
+//            //                    MainUserDistributedMark = UserConfig.Instance.CurrentRegion.MainUserDistributedMark,
+//            //                    HomeId = UserConfig.Instance.CurrentRegion.Id,
+//            //                    IsRedirectSelectEmqServer = mGatewayRes.ExtensionPara//鏄惁鏄柊缃戝叧锛屾槸鍚﹁嚜鍔ㄩ�夋嫨鏈嶅姟鍣�
+//            //                };
+//            //                var mqttInfoRequestResult = MainPage.RequestHttpsNew (API.ShareMemberConnMqttInfo, Newtonsoft.Json.JsonConvert.SerializeObject (mqttInfoRequestPar));
+//            //                //--绗簩姝ワ細鑾峰彇mqtt閾炬帴鍙傛暟
+//            //                if (mqttInfoRequestResult != null && mqttInfoRequestResult.ResponseData != null) {
+//            //                    var mqttInfoRequestResult_info = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttInfo> (mqttInfoRequestResult.ResponseData.ToString ());
+//            //                    if (mqttInfoRequestResult_info != null) {
+//            //                        MqttInfoConfig.Instance.mMqttInfo = mqttInfoRequestResult_info;
+
+//            //                        //--绗笁姝ワ細杩炴帴mqtt
+//            //                        await MQTTConnectAsync ();
+//            //                    }
+
+//            //                } else {
+//            //                    //Utlis.WriteLine ("============>Mqtt 鍙栨秷杩炴帴锛宮qttInfoRequestResult");
+//            //                }
+
+
+//            //            }
+
+
+//            //        } else {
+//            //            Shared.Utlis.WriteLine ("============>Mqtt 鍙栨秷杩炴帴锛屽綋鍓嶄綇瀹呮病缁戝畾缃戝叧");
+//            //        }
+//            //    } else {
+//            //        var mGatewayRes = infoResult.PageData.Find ((obj) => obj.GatewayUniqueId == UserConfig.Instance.CurrentRegion.HomeGateways [0].GatewayUniqueId);
+//            //        if (mGatewayRes != null) {
+//            //            MqttInfoConfig.Instance.CurRemoteMACInfo.aesKey = mGatewayRes.AesKey;
+//            //            mqttEncryptKey = MqttInfoConfig.Instance.CurRemoteMACInfo.isNewBusproGateway ? MqttInfoConfig.Instance.CurRemoteMACInfo.aesKey : "";
+//            //            //鑾峰彇AesKey鎴愬姛鍚庢洿鏂板苟淇濆瓨鍒版湰鍦�
+//            //            MqttInfoConfig.Instance.Save ();
+//            //        }
+
+//            //    }
+
+
+//            //} else {
+//            //    //鑾峰彇涓讳汉token
+//            //    if (revertObj3.StateCode.ToUpper () == "HomeIdAndTokenNoConsistent") {
+//            //        UserConfig.Instance.CheckIfNeedGetMasterAccountToken ();
+//            //    }
+//            //}
+
+//        }
+//        //}
+
+
+
+//    }
+
+
+    public class RemoteRequestParameters
     {
+        public string RequestVersion;
+        public int RequestSource;
+        public string LoginAccessToken;
+        public int RequestProtocolType;
+
+        public int HdlGatewayGatewayType = 0;
+        public bool IsRedirectSelectEmqServer = false;
         /// <summary>
-        /// MqttClient
+        /// 骞冲彴绫诲瀷瀛楃涓�
         /// </summary>
-        public static IMqttClient mqttClient_A;
-        public static string mqttClientIP;
-        public static string mqttGatewayMAC;
-        static bool remoteIsConnected;
-
-        static bool onConnection = false;
-
-        static MqttCommon()
-        {
-            InitMqtt();
-        }
-
-        /// <summary>
-        /// 鏂紑杩滅▼Mqtt鐨勯摼鎺�
-        /// </summary>
-        public static async Task DisConnectRemoteMqttClient(string s = "")
-        {
-            try
-            {
-                if (remoteIsConnected)
-                {
-                    remoteIsConnected = false;
-                    System.Console.WriteLine($"Remote涓诲姩鏂紑_{s}");
-                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
-                    await mqttClient_A.DisconnectAsync();
-                }
-            }
-            catch (Exception e)
-            {
-                Console.WriteLine($"Remote鏂紑閫氳杩炴帴鍑哄紓甯�:{e.Message}");
-            }
-        }
-
-        static bool isSubscribeSuccess;
-        static async Task SubscribeTopics()
-        {
-            if (remoteIsConnected && !isSubscribeSuccess)
-            {
-                try
-                {
-                    var Topic1 = $"/BusGateWayToApp/{mqttGatewayMAC}/Common/Json";
-                    try
-                    {
-                        await mqttClient_A.SubscribeAsync(Topic1);
-                    }
-                    catch (Exception ex)
-                    {
-                        await DisConnectRemoteMqttClient(ex.Message);
-                        await StartMqtt();
-                        if (remoteIsConnected)
-                        {
-                            await mqttClient_A.SubscribeAsync(Topic1);
-                        }
-                    }
-                }
-                catch { }
-            }
-        }
-
-        static void InitMqtt()
-        {
-            new System.Threading.Thread(async () => {
-                while (true)
-                {
-                    try
-                    {
-                        System.Threading.Thread.Sleep(1000);
-                        //if (!CommonPage.IsRemote)
-                        //    continue;
-                        if (remoteIsConnected)
-                            continue;
-                        await StartMqtt();
-                        await SubscribeTopics();
-                    }
-                    catch { }
-                }
-            })
-            { IsBackground = true }.Start();
-        }
-
+        public string PlatformStr;
         /// <summary>
-        /// 鍚姩A鍗忚Mqtt
+        /// 鍙戝竷涓婚璐熻浇
         /// </summary>
-        public static async Task StartMqtt()
-        {
-            try
-            {
-                if (remoteIsConnected)
-                    return;
-                if (onConnection)
-                    return;
-                onConnection = true;
-                new System.Threading.Thread(async () =>
-                {
-                    if (remoteIsConnected)
-                        return;
-                    try
-                    {
-                        if (mqttClient_A == null)
-                        {
-                            mqttClient_A = new MqttFactory().CreateMqttClient();
-                            mqttClient_A.UseApplicationMessageReceivedHandler(async e =>
-                            {
-                                var aesDecryptTopic = e.ApplicationMessage.Topic;
-                                var aesDecryptPayload = e.ApplicationMessage.Payload;
-                                MainPage.Log(aesDecryptTopic);
-                                MainPage.Log($"Des Topic={aesDecryptTopic}");
-                            });
+        public string PublishPayloadJsonStr;
 
-                            mqttClient_A.UseConnectedHandler(async (e) => {
-                                MainPage.Log("mqtt connected !!");
-                                onConnection = false;
-                            });
-                        }
-                        try
-                        {
-                            int readCount = 0;
-                            BusSocket.Stop();
-                            System.Threading.Thread.Sleep(1000);
-                            BusSocket.Start(6688);
-                            System.Threading.Thread.Sleep(1000);
-                            Control.ReadGatewayIPAddress();
-                            while(true)
-                            {
-                                if (!string.IsNullOrEmpty(mqttClientIP))
-                                {
-                                    break;
-                                }
-                                else if (readCount > 10)
-                                {
-                                    onConnection = false;
-                                    return;
-                                }
-                                else
-                                {
-                                    Control.ReadGatewayIPAddress();
-                                    System.Threading.Thread.Sleep(200);
-                                }
-                            }
-                            BusSocket.Stop();
-                            System.Threading.Thread.Sleep(1000);
-                            BusSocket.Start(6000);
-                            System.Threading.Thread.Sleep(1000);
-
-                            var options = new MqttClientOptionsBuilder()//MQTT杩炴帴鍙傛暟濉厖
-                                .WithClientId(Guid.NewGuid().ToString().Substring(0, 5))//瀹㈡埛绔疘D
-                                .WithTcpServer(mqttClientIP, 1883)//MQTTServerIP.Text, Int32.Parse(MQTTServerPort.Text.ToString()))//TCP鏈嶅姟绔�  1883  锛屽嵆MQTT鏈嶅姟绔�
-                                .WithCredentials("", "")//"", "")//鍑瘉  甯愬彿 瀵嗙爜
-                                .WithCommunicationTimeout(new TimeSpan(0, 0, 60)) //閲嶈繛瓒呮椂鏃堕棿锛岄粯璁�5s
-                                .WithKeepAlivePeriod(new TimeSpan(0, 0, 15)) //淇濇寔杩炴帴鏃堕棿锛岄粯璁�5s锛屽績璺冲寘
-                                .Build();
-                            await mqttClient_A.ConnectAsync(options);
-                            remoteIsConnected = true;
-                        }
-                        catch { }
-                    }
-                    catch (Exception ex)
-                    {
-                    }
-                    finally
-                    {
-                        onConnection = false;
-                    }
-                })
-                { IsBackground = true }.Start();
-            }
-            catch (Exception ex)
-            {
-                MainPage.Log("============>" + ex.Message);
-            }
-        }
-
-
-
-
-        /// <summary>
-        /// 
-        /// </summary>
-        /// <param name="message">闄勫姞鏁版嵁鍖�</param>
-        /// <param name="optionType">鎿嶄綔绫诲瀷锛�0=缃戝叧鎺у埗锛�1=璁㈤槄缃戝叧鏁版嵁;2=璁㈤槄缃戝叧涓婄嚎鏁版嵁</param>
-        /// <returns></returns>
-        public static async Task MqttRemoteSend(byte[] message)
-        {
-            try
-            {
-                if (mqttClient_A == null || !mqttClient_A.IsConnected)
-                {
-                    await StartMqtt();
-                }
-                if (!mqttClient_A.IsConnected)
-                {
-                    return;
-                }
-                var topicName = $"/AppToBusGateWay/{mqttGatewayMAC}/Common/Json";
-                var m = new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce };
-                await mqttClient_A?.PublishAsync(m);
-            }
-            catch (Exception e)
-            {
-            }
-        }
+        public string Mac = "";
+        public string GroupName = "";
     }
-}
 
-public class RemoteRequestParameters
-{
-    public string RequestVersion;
-    public int RequestSource;
-    public string LoginAccessToken;
-    public int RequestProtocolType;
-
-    public string Mac = "";
-    public string GroupName = "";
-}
-
-public class MqttRemoteInfo
-{
-    public List<RemoteMACInfo> pageData;
-
-    public int pageIndex = 0;
-    public int pageSize = 10;
-    public int totalCount = 3;
-    public int totalPages = 1;
-    public bool hasPreviousPage = false;
-    public bool hasNextPage = false;
-}
-
-public class MqttInfo
-{
-    public string connEmqDomainPort;
-    public string connEmqClientId;
-    public string connEmqUserName;
-    public string connEmqPwd;
-}
-
-public class RemoteMACInfo
-{
-    public string mac;
-    public string macMark;
-    public string isValid;
-    public string aesKey;
-    public bool isNewBusproGateway;
-    public string groupName;
-    public string projectName;
-    public string userName;
-
-    //app鑷畾涔夋暟鎹�
-    public string md5_mac_string;
-    public string LoginAccessToken;
-}
-
-namespace Shared.Securitys
-{
-    public partial class EncryptionService
+    public class MqttRemoteInfo
     {
+        public List<RemoteMACInfo> pageData;
 
-        #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);
+        public int pageIndex = 0;
+        public int pageSize = 10;
+        public int totalCount = 3;
+        public int totalPages = 1;
+        public bool hasPreviousPage = false;
+        public bool hasNextPage = false;
+    }
 
-            //閰嶇疆AES鍔犲瘑Key(瀵嗛挜銆佸悜閲忋�佹ā寮忋�佸~鍏�)
-            RijndaelManaged rm = new RijndaelManaged
-            {
-                Key = Encoding.UTF8.GetBytes(key),
-                IV = Encoding.UTF8.GetBytes(key),
-                Mode = CipherMode.CBC,
-                Padding = PaddingMode.PKCS7
-            };
+    public class MqttInfo
+    {
+        public string connEmqDomainPort;
+        public string connEmqClientId;
+        public string connEmqUserName;
+        public string connEmqPwd;
 
-            //鍒涘缓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
-
+        public List<RemoteMACInfo> AccountAllGateways;
 
     }
-}
+
+    public class RemoteMACInfo
+    {
+        public string mac;
+        public string macMark;
+        public string isValid;
+        public string aesKey;
+        public bool isNewBusproGateway;
+        public string groupName;
+        public string projectName;
+        public string userName;
+
+        public string clientId;
+
+        //app鑷畾涔夋暟鎹�
+        public string md5_mac_string;
+        public string LoginAccessToken;
+    }
+
+    namespace Shared.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
+
+
+        }
+    }
+}
\ No newline at end of file

--
Gitblit v1.8.0