wxr
2020-12-01 a2927467ebfa938a420f392deb6882b35570fd33
HDL_ON/DAL/Mqtt/MqttClient.cs
@@ -1,7 +1,6 @@
/*
更新了EMQ连接方式
*/
using System.Collections.Generic;
using System;
using MQTTnet.Client;
using System.Threading.Tasks;
@@ -9,12 +8,12 @@
using MQTTnet;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using HDL_ON.DriverLayer;
using HDL_ON.Entity;
namespace HDL_ON.DAL.Mqtt
{
    public static class MqttCommon
    public static class MqttClient
    {
        /// <summary>
        /// 加密通讯KEY
@@ -51,11 +50,10 @@
        /// </summary>
        public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient();
        /// <summary>
        /// 推送标识
        /// </summary>
        static string PushSignStr = System.DateTime.Now.Ticks.ToString();
        static string PushSignStr = DateTime.Now.Ticks.ToString();
        /// <summary>
        /// 断开远程Mqtt的链接
@@ -74,11 +72,7 @@
                    if (Control.Ins.IsRemote)
                    {
                        //不是无网络
                        if (OnAppConfig.Instance.internetStatus != 0)
                        {
                            Control.Ins.GatewayOnline = false;
                        }
                        Control.Ins.GatewayOnline = false;
                    }
                }
            }
@@ -95,21 +89,16 @@
        {
            try
            {
                //if (remoteIsConnected) {
                remoteIsConnected = false;
                isSubscribeSuccess = false;
                Utlis.WriteLine($"RemoteStart主动断开_{s}");
                await RemoteMqttClient.DisconnectAsync();
                //}
            }
            catch (Exception e)
            {
                Utlis.WriteLine($"RemoteStart断开通讯连接出异常:{e.Message}");
            }
        }
        /// <summary>
        /// 断开mqtt连接
@@ -121,21 +110,18 @@
        {
            if (reset)
            {
                bNeedStartTip = true;
                bNeedConnectTip = true;
                MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
            }
            await DisConnectRemoteMqttClient(s);
        }
        //static DateTime dateTime = DateTime.MinValue;
        /// <summary>
        /// 外网的MQTT是否正在连接
        /// </summary>
        public static bool remoteMqttIsConnecting;
        static bool remoteIsConnected;
        static MqttCommon()
        static MqttClient()
        {
            InitMqtt();
        }
@@ -150,13 +136,7 @@
                    try
                    {
                        System.Threading.Thread.Sleep(500);
                        //if (!UserInfo.Current.IsLogin) {
                        //    continue;
                        //}
                        if (!Control.Ins.IsRemote) continue;
                        //if (BusSocket.IsEnterBackground) continue;
                        await StartCloudMqtt();
                        await SubscribeTopics();
@@ -183,10 +163,6 @@
            {
                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()
                    {
@@ -212,10 +188,8 @@
                        MqttRemoteSend(new byte[] { 0 }, 3);
                        //连接成功后检测是否需要通过远程获取Key
                        CheckIfNeedGetLocalPasswordFromRemote();
                        //CheckIfNeedGetLocalPasswordFromRemote();
                    }
                }
                catch (Exception ex)
                {
@@ -224,9 +198,6 @@
            }
        }
        static DateTime mFlagDateTime;
        //static readonly object SendLocker = new object ();
        /// <summary>
        /// 启动远程Mqtt
        /// </summary>
@@ -262,6 +233,7 @@
                    //(1)当[连接云端的Mqtt成功后]或者[以及后面App通过云端Mqtt转发数据给网关成功后],处理接收到云端数据包响应时在mqttServerClient_ApplicationMessageReceived这个方法处理
                    if (RemoteMqttClient.ApplicationMessageReceivedHandler == null)
                    {
                        //处理接收到的数据
                        RemoteMqttClient.UseApplicationMessageReceivedHandler((e) => {
                            try
                            {
@@ -278,7 +250,8 @@
                                    ReceiveNotifyBusGateWayInfoChange();
                                }
                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.id}/NotifyGateWayOffline")
                                {//网关掉线                                                                                                                    //----第二步:读取账号下面的网关列表
                                {//网关掉线
                                    //----第二步:读取账号下面的网关列表
                                    ReceiveNotifyGateWayOffline();
                                }
                                else if (topic == $"/BusGateWayToClient/{MqttInfoConfig.Current.HomeGatewayInfo.id}/Common/CheckGateway")
@@ -288,21 +261,25 @@
                                }
                                else
                                {
                                    SetGatewayOnlineResetCheck();
                                    var packet = new Packet();
                                    if (!string.IsNullOrEmpty(mqttEncryptKey))
                                    if (Entity.DB_ResidenceData.residenceData.GatewayType == 0)
                                    {
                                        packet.Bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
                                        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
                                    {
                                        packet.Bytes = e.ApplicationMessage.Payload;
                                        //A协议数据处理
                                    }
                                    packet.IsLocal = false;
                                    packet.Manager();
                                }
                            }
                            catch { }
@@ -316,7 +293,6 @@
                            Utlis.WriteLine($"远程连接断开");
                            isSubscribeSuccess = false;
                            await DisConnectRemoteMqttClient("UseDisconnectedHandler");
                        });
                    }
                    //(3)ConnectedHandler
@@ -441,12 +417,6 @@
            if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.mMqttInfo != null)
            {
                if (bNeedConnectTip)
                {
                    bNeedConnectTip = false;
                    MainPage.LoadingTipShow(Language.StringByID(SimpleControl.R.MyInternationalizationString.GetSuccessfullyStartConnecting));
                }
                try
                {
@@ -485,7 +455,6 @@
                    {
                        remoteIsConnected = true;
                        IsDisConnectingWithSendCatch = false;
                        UnsupportedProtocolVersionCount = 0;
                    }
                    else
                    {
@@ -497,22 +466,9 @@
                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);
                    }
                    //重新中心服务器获取参数标记
                    MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
                    Console.WriteLine("Connect error: " + ex.Message);
                }
                finally
                {
@@ -684,35 +640,25 @@
        /// <returns></returns>
        static async Task GetMqttInfoAndMQTTConnectAsync()
        {
            var mqttInfoRequestResult_Obj =new Server.HttpServerRequest().GetMqttRemoteInfo(GetRandomKey());
            var mqttInfoRequestResult_Obj = new Server.HttpServerRequest().GetMqttRemoteInfo(GetRandomKey());
            if (mqttInfoRequestResult_Obj != null)
            {
                MqttInfoConfig.Current.mMqttInfo = mqttInfoRequestResult_Obj;
                if (UserConfig.Instance.GatewayList != null && UserConfig.Instance.GatewayList.Count > 0)
                await MQTTConnectAsync();
                //1.判断是否绑定了网关,获取网关远程连接的加密KEY
                if (DB_ResidenceData.residenceData.CheckWhetherGatewayIsBound())
                {
                    //----第二步找出是否存在匹配当前住宅的mac,存在再进行远程。
                    MqttInfoConfig.Current.HomeGatewayInfo = UserConfig.Instance.GatewayList[0];
                    if (MqttInfoConfig.Current.HomeGatewayInfo != null)
                    {
                        //----第三步 开始连接
                        await MQTTConnectAsync();
                    }
                    //2.找出是否存在匹配当前住宅的mac,存在再进行远程。
                    MqttInfoConfig.Current.HomeGatewayInfo = DB_ResidenceData.residenceData.HomeGateway;
                    //3.开始连接
                    await MQTTConnectAsync();
                }
                else
                {
                    Utlis.WriteLine("============>还没绑定网关");
                }
            }
            else
            {
                Utlis.WriteLine("============>MqttInfo null");
            }
        }
    }
}