wei
2021-02-01 8da70e1a39328e1769b02bb1e05303916bb30eb5
HDL_ON/DAL/Mqtt/MqttClient.cs
@@ -20,6 +20,7 @@
        /// 加密通讯KEY
        /// </summary>
        static string mqttEncryptKey = "";
        static string tuyaEncryptKey = "";
        //static string checkGatewayTopicBase64 = "";
        static bool hadGateway = true;
        /// <summary>
@@ -56,37 +57,37 @@
        /// </summary>
        static string PushSignStr = DateTime.Now.Ticks.ToString();
        /// <summary>
        /// 断开远程Mqtt的链接
        /// <summary>
        /// 断开远程Mqtt的链接
        /// </summary>
        static async Task DisConnectRemoteMqttClient(string s = "")
        {
        static async Task DisConnectRemoteMqttClient(string s = "")
        {
            try
            {
            {
                if (remoteIsConnected)
                {
                    remoteIsConnected = false;
                    isSubscribeSuccess = false;
                    Utlis.WriteLine($"Remote主动断开_{s}");
                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
                    Utlis.WriteLine($"Remote主动断开_{s}");
                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
                    await RemoteMqttClient.DisconnectAsync();
                    if (Control.Ins.IsRemote)
                    {
                        Control.Ins.GatewayOnline = false;
                    }
                }
                }
            }
            catch (Exception e)
            {
                Utlis.WriteLine($"Remote断开通讯连接出异常:{e.Message}");
            }
                Utlis.WriteLine($"Remote断开通讯连接出异常:{e.Message}");
            }
        }
        /// <summary>
        /// 断开远程Mqtt的链接
        /// <summary>
        /// 断开远程Mqtt的链接
        /// </summary>
        static async Task DisConnectRemoteMqttClientWhenStart(string s = "")
        static async Task DisConnectRemoteMqttClientWhenStart(string s = "")
        {
            try
            {
@@ -97,7 +98,7 @@
            }
            catch (Exception e)
            {
                Utlis.WriteLine($"RemoteStart断开通讯连接出异常:{e.Message}");
                Utlis.WriteLine($"RemoteStart断开通讯连接出异常:{e.Message}");
            }
        }
@@ -160,6 +161,10 @@
        }
        static bool isSubscribeSuccess;
        /// <summary>
        /// 订阅主题
        /// </summary>
        /// <returns></returns>
        static async Task SubscribeTopics()
        {
            if (remoteIsConnected && !isSubscribeSuccess)
@@ -180,10 +185,14 @@
                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce,
                        //QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce
                    };
                    var topicAlinkStatus = new MqttTopicFilter()
                    {
                        Topic = $"/user/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/app/thing/property/send",
                        Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.RegionID}/app/thing/property/send",
                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
                    };
                    var topicAlinkGatewayStatus = new MqttTopicFilter()
                    {
                        Topic = $"/user/{DB_ResidenceData.Instance.HomeGateway.gatewayId}/app/thing/property/send",
                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
                    };
                    //var topicBusStatus = new MqttTopicFilter()
@@ -193,7 +202,7 @@
                    //};
                    Utlis.WriteLine("开始订阅!");
                    var result = await RemoteMqttClient.SubscribeAsync(new MqttTopicFilter[] { topicFilterBusGateWayToClient, topicFilterPush2, topicAlinkStatus });
                    var result = await RemoteMqttClient.SubscribeAsync(new MqttTopicFilter[] { topicFilterBusGateWayToClient, topicFilterPush2, topicAlinkStatus, topicAlinkGatewayStatus });
                    if (result.Items[0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS0)
                    {
                        Control.Ins.GatewayOnline = true;
@@ -273,11 +282,19 @@
                                    var ss = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                                    ReceiveCheckGateway(ss);
                                }
                                //涂鸦设备状态
                                else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.RegionID}/app/thing/property/send")
                                {
                                    var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, tuyaEncryptKey);
                                    MainPage.Log($"tuya mqtt A-Link data");
                                    //A协议数据处理
                                    var revString = Encoding.UTF8.GetString(bytes);
                                    Control.Ins.UpdataFunctionStatus(revString, null);
                                }
                                else
                                {
                                    SetGatewayOnlineResetCheck();
                                    var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, DB_ResidenceData.Instance.HomeGateway.aesKey);
                                    var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
                                    //bus数据解析
                                    if (DB_ResidenceData.Instance.GatewayType == 0)
                                    {
@@ -291,14 +308,6 @@
                                        {
                                            packet.Bytes = e.ApplicationMessage.Payload;
                                        }
#if DEBUG
                                        //string ddd = "";
                                        //foreach (var bb in packet.Bytes)
                                        //{
                                        //    ddd += bb + ",";
                                        //}
                                        //MainPage.Log($"mqtt bus data:{ddd}");
#endif
                                        packet.Manager();
                                    }
                                    else
@@ -306,7 +315,7 @@
                                        MainPage.Log($"mqtt A-Link data");
                                        //A协议数据处理
                                        var revString = Encoding.UTF8.GetString(bytes);
                                        Control.Ins.UpdataFunctionStatus(revString,null);
                                        Control.Ins.UpdataFunctionStatus(revString, null);
                                    }
                                }
                            }
@@ -439,7 +448,9 @@
                return;
            }
            if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.mMqttInfo != null)
            //if (MqttInfoConfig.Current.HomeGatewayInfo != null && MqttInfoConfig.Current.mMqttInfo != null)
            //没有网关情况下,也需要连接mqtt,涂鸦第三方设备不需要网关
            if (MqttInfoConfig.Current.mMqttInfo != null)
            {
                try
                {
@@ -458,6 +469,20 @@
                    MqttInfoConfig.Current.Save();
                    mqttEncryptKey = MqttInfoConfig.Current.HomeGatewayInfo.aesKey;
                    if (MqttInfoConfig.Current.HomeGatewayInfo == null)
                    {
                        MqttInfoConfig.Current.HomeGatewayInfo = new Server.HomeGatewayInfo();
                    }
                    //解密密钥规则:已现有的住宅ID为基准,从右边一一获取值,最后如果不够16位,则往右补零
                    string aesKey = string.Empty;
                    for (int i = DB_ResidenceData.Instance.CurrentRegion.RegionID.Length - 1; i >= 0; i--)
                    {
                        aesKey += DB_ResidenceData.Instance.CurrentRegion.RegionID[i].ToString();
                        if (aesKey.Length == 16) { break; }
                    }
                    aesKey = aesKey.PadRight(16, '0');
                    tuyaEncryptKey = aesKey;
                    var options1 = new MQTTnet.Client.Options.MqttClientOptionsBuilder()
                                        .WithClientId(clientId)
@@ -540,9 +565,6 @@
        /// </summary>
        static void ReceiveNotifySqueezeAsync(string mMes)
        {
#if DEBUG
            return;
#endif
            if (mMes == PushSignStr) return;//是自己的登录推送不处理
            //断开远程连接
@@ -559,7 +581,7 @@
                //弹窗提示被挤下线
                HDLCommon.Current.CheckLogout();
            });
            //UserInfo.Current.LastTime = DateTime.MinValue;
            //UserInfo.Current.SaveUserInfo();
@@ -659,7 +681,17 @@
            if (Control.Ins.IsRemote)
            {
                if (!Control.Ins.GatewayOnline)
                    Control.Ins.GatewayOnline = true;
                {
                    try
                    {
                        if (DB_ResidenceData.Instance.HomeGateway != null)
                        {
                            DB_ResidenceData.Instance.HomeGateway.gatewayStatus = true;
                        }
                        Control.Ins.GatewayOnline = true;
                    }
                    catch { }
                }
            }
        }