wei
2021-09-26 dd3fecc3a8b92b377febfcf92d32ec22a07724f6
HDL_ON/DAL/Mqtt/MqttClient.cs
@@ -11,6 +11,7 @@
using HDL_ON.DriverLayer;
using HDL_ON.Entity;
using HDL_ON.UI;
using HDL_ON.DAL.Server;
namespace HDL_ON.DAL.Mqtt
{
@@ -19,7 +20,7 @@
        /// <summary>
        /// 加密通讯KEY
        /// </summary>
        static string mqttEncryptKey = "";
        //static string mqttEncryptKey = "";
        static string tuyaEncryptKey = "";
        //static string checkGatewayTopicBase64 = "";
        static bool hadGateway = true;
@@ -132,7 +133,7 @@
                {
                    try
                    {
                        System.Threading.Thread.Sleep(500);
                        System.Threading.Thread.Sleep(2000);
                        //进入后台不处理
                        if (MainPage.IsEnterBackground) continue;
                        if (MqttInfoConfig.Current.HomeGatewayInfo == null)
@@ -188,27 +189,71 @@
                    };
                    var topicAlinkStatus = new MqttTopicFilter()
                    {
                        Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.RegionID}/app/thing/property/send",
                        Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/property/send",
                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
                    };
                    //App订阅红外宝 / 网关遥控器添加成功通知
                    var pirStatus = new MqttTopicFilter()
                    {
                        Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.RegionID}/app/thing/topo/found",
                        Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/topo/found",
                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
                    };
                    //App订阅遥控器自学按键学习成功通知
                    var study = new MqttTopicFilter()
                    var pirStudy = new MqttTopicFilter()
                    {
                        Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.RegionID}/app/thing/event/irCodeStudyDone/up",
                        Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/irCodeStudyDone/up",
                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
                    };
                    #region 数据更新推送主题
                    //appHomeRefresh:住宅数据刷新通知--杨涛
                    var appHomeRefresh = new MqttTopicFilter()
                    {
                        Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/appHomeRefresh/up",
                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
                    };
                    //住宅消息变更推送--豆豆
                    var residenceChange = new MqttTopicFilter()
                    {
                        Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/appDeviceRefresh/up",
                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
                    };
                    //appRoomRefresh:房间数据刷新通知
                    var appRoomRefresh = new MqttTopicFilter()
                    {
                        Topic = $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/appRoomRefresh/up",
                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
                    };
                    //appDeviceRefresh:设备数据刷新通知
                    var appDeviceRefresh = new MqttTopicFilter()
                    {
                        Topic = $"/user/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/app/thing/event/appHomeRefresh/up",
                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
                    };
                    //一端口密钥更新通知
                    var mqttkeyChange = new MqttTopicFilter()
                    {
                        Topic = $"/user/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/custom/mqtt/secret/change",
                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
                    };
                    //安防状态变化
                    var securityStatusChange = new MqttTopicFilter()
                    {
                        Topic = $"/user/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/custom/security/status/up",
                        QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce
                    };
                    #endregion
                    Utlis.WriteLine("开始订阅!");
                    var result = await RemoteMqttClient.SubscribeAsync(new MqttTopicFilter[] {
                        pirStatus,
                         study,
                        topicFilterPush2, topicAlinkStatus });
                        pirStatus,pirStudy,
                        appDeviceRefresh,appHomeRefresh,appRoomRefresh,residenceChange,
                        topicFilterPush2, topicAlinkStatus ,mqttkeyChange,
                        securityStatusChange});
                    if (result.Items[0].ResultCode == MQTTnet.Client.Subscribing.MqttClientSubscribeResultCode.GrantedQoS0)
                    {
                        isSubscribeSuccess = true;
@@ -233,6 +278,10 @@
            }
            if (!UserInfo.Current.IsLogin)
            {
                return;
            }
            if (DB_ResidenceData.Instance.CurrentRegion == null || DB_ResidenceData.Instance.CurrentRegion.id == null)
            {
                return;
            }
@@ -287,6 +336,9 @@
                                    }
                                }
                                //一些特殊的主题处理(为了执行速度,尽可能的别加耗时的操作 true:执行了特殊处理 false:没有执行特殊处理)
                                Stan.HdlCloudReceiveLogic.Current.CloudOverallMsgReceiveEx(topic, e.ApplicationMessage.Payload, DB_ResidenceData.Instance.HomeGateway.aesKey, tuyaEncryptKey);
                                if (topic == $"/BusGateWayToClient/{UserInfo.Current.ID}" + PushNotifySqueeze)
                                {
                                    var mMes = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
@@ -294,41 +346,155 @@
                                    ReceiveNotifySqueezeAsync(mMes);
                                }
                                //App订阅红外宝/网关遥控器添加成功通知
                                else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.RegionID}/app/thing/topo/found")
                                else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/topo/found")
                                {
                                    var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, tuyaEncryptKey);
                                    var revString = Encoding.UTF8.GetString(bytes);
                                    HDL_ON.UI.UI2.PersonalCenter.PirDevice.Method.mqttdata = revString;
                                    //ReceiveCheckGateway(ss);
                                    //return;
                                    HDL_ON.UI.UI2.PersonalCenter.PirDevice.PirMethod.controldata = revString;
                                }
                                //App订阅遥控器自学按键学习成功通知
                                else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.RegionID}/app/thing/event/irCodeStudyDone/up")
                                else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/irCodeStudyDone/up")
                                {
                                    var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, tuyaEncryptKey);
                                    var revString = Encoding.UTF8.GetString(bytes);
                                    HDL_ON.UI.UI2.PersonalCenter.PirDevice.Method.mqttdata = revString;
                                    //ReceiveCheckGateway(ss);
                                    //return;
                                    UI.UI2.PersonalCenter.PirDevice.PirMethod.buttondata = revString;
                                }
                                #region 数据更新推送主题
                                //appHomeRefresh:住宅数据刷新通知
                                else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/appHomeRefresh/up"
                                        || topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/appDeviceRefresh/up")
                                {
                                    MainPage.Log("住宅数据刷新通知");
                                    new HttpServerRequest().GetHomePager();
                                }
                                //appRoomRefresh:房间数据刷新通知
                                else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/appRoomRefresh/up")
                                {
                                    MainPage.Log("房间数据刷新通知");
                                    var roomResult = new HttpServerRequest().GetRoomList();
                                    if (roomResult.Code == StateCode.SUCCESS)
                                    {
                                        MainPage.Log($"读取房间信息成功");
                                        var revData = Newtonsoft.Json.JsonConvert.DeserializeObject<SpatialApiPack>(roomResult.Data.ToString());
                                        if (revData == null)
                                        {
                                            revData = new SpatialApiPack();
                                        }
                                        {
                                            SpatialInfo.CurrentSpatial.UpdateSpatialList(revData.list);
                                        }
                                    }
                                    else
                                    {
                                        MainPage.Log($"读取房间数据失败:Code:{roomResult.Code}; msg:{roomResult.message}");
                                    }
                                }
                                //appDeviceRefresh:设备数据刷新通知
                                else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/event/appDeviceRefresh/up")
                                {
                                    MainPage.Log("设备数据刷新通知");
                                    var deviceResult = new HttpServerRequest().GetDeviceList();
                                    if (deviceResult.Code == StateCode.SUCCESS)
                                    {
                                        MainPage.Log($"读取设备信息成功");
                                        var deviceList = Newtonsoft.Json.JsonConvert.DeserializeObject<DevcieApiPack>(deviceResult.Data.ToString());
                                        if (deviceList == null)
                                        {
                                            deviceList = new DevcieApiPack();
                                        }
                                        string delFile = "";
                                        if (FunctionList.List.GetDeviceFunctionList().Count > 0)
                                        {
                                            for (int i = 0; i < FunctionList.List.GetDeviceFunctionList().Count;)
                                            {
                                                var localFunction = FunctionList.List.GetDeviceFunctionList()[i];
                                                if (SPK.MusicSpkList().Contains(localFunction.spk))
                                                {
                                                    i++;
                                                    continue;
                                                }
                                                var newFunction = deviceList.list.Find((obj) => obj.deviceId == localFunction.deviceId);
                                                if (delFile == localFunction.savePath)
                                                {
                                                    i++;
                                                    continue;
                                                }
                                                delFile = localFunction.savePath;
                                                FunctionList.List.DeleteFunction(localFunction);
                                            }
                                        }
                                        //处理剩下的新增功能
                                        foreach (var newFunction in deviceList.list)
                                        {
                                            newFunction.SaveFunctionFile();
                                            FunctionList.List.IniFunctionList(newFunction.savePath);
                                        }
                                    }
                                    else
                                    {
                                        MainPage.Log($"读取云端设备数据失败:Code:{deviceResult.Code};  Msg:{deviceResult.message}");
                                    }
                                }
                                //网关密钥变化
                                else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/custom/mqtt/secret/change")
                                {
                                    var pm = new HttpServerRequest();
                                    pm.GetHomeGatewayList();
                                    MainPage.Log($"网关密钥变更.新密钥:{DB_ResidenceData.Instance.HomeGateway.aesKey}");
                                }
                                //安防状态变化
                                else if (topic == $"/user/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/custom/security/status/up")
                                {
                                    if (!string.IsNullOrEmpty(DB_ResidenceData.Instance.HomeGateway.aesKey))
                                    {
                                        try
                                        {
                                            var securityBytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, DB_ResidenceData.Instance.HomeGateway.aesKey);
                                            var securityString = Encoding.UTF8.GetString(securityBytes);
                                            var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<SecurityStatusObj>(securityString);
                                            MainPage.Log($"安防状态变化:{securityString}");
                                            if (temp != null)
                                            {
                                                Control_Udp.ReceiveRepeatManager(temp.id, null);
                                                foreach (var updataSecurity in temp.objects)
                                                {
                                                    var updataLocalSecurity = FunctionList.List.securities.Find((obj) => obj.sid == updataSecurity.sid);
                                                    if (updataLocalSecurity != null)
                                                    {
                                                        updataLocalSecurity.status = updataSecurity.status;
                                                        updataLocalSecurity.alarm = updataSecurity.alarm;
                                                        ArmCenterPage.LoadEvent_RefreshSecurityStatus(updataLocalSecurity);
                                                    }
                                                }
                                                HomePage.LoadEvent_RefreshSecurityStatus();
                                            }
                                        }catch(Exception ex)
                                        {
                                            MainPage.Log($"安防远程信息异常:{ex.Message}");
                                        }
                                    }
                                }
                                #endregion
                                //A网关设备状态-包含涂鸦设备
                                else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.RegionID}/app/thing/property/send")
                                else if (topic == $"/user/{DB_ResidenceData.Instance.CurrentRegion.id}/app/thing/property/send")
                                {
                                    var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, tuyaEncryptKey);
                                    var revString = Encoding.UTF8.GetString(bytes);
                                    Control.Ins.UpdataFunctionStatus(revString, null,true);
                                    Control.Ins.UpdataFunctionStatus(revString, null, true);
                                }
                                //一端口数据解析
                                else
                                {
                                    //SetGatewayOnlineResetCheck();
                                    var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
                                    //var bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
                                    //bus数据解析
                                    var packet = new Packet();
                                    if (!string.IsNullOrEmpty(mqttEncryptKey))
                                    if (!string.IsNullOrEmpty(DB_ResidenceData.Instance.HomeGateway.aesKey))
                                    {
                                        packet.Bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, mqttEncryptKey);
                                        packet.Bytes = Securitys.EncryptionService.AesDecryptPayload(e.ApplicationMessage.Payload, DB_ResidenceData.Instance.HomeGateway.aesKey);
                                    }
                                    else
                                    {
@@ -364,6 +530,25 @@
                    #endregion
                    //(4)===========开始连接过程==========
                    ////一端口每次都要刷新密钥
                    //if (DB_ResidenceData.Instance.HomeGateway != null && DB_ResidenceData.Instance.HomeGateway.gatewayType == "BUSUDPGATEWAY") {
                    //    var pm = new HttpServerRequest();
                    //    var result = pm.GetHomeGatewayList();
                    //    if(result == StateCode.SUCCESS)
                    //    {
                    //        MainPage.Log($"刷新一端口密钥");
                    //        MainPage.Log($"旧密钥:{mqttEncryptKey}");
                    //        mqttEncryptKey = MqttInfoConfig.Current.HomeGatewayInfo.aesKey;
                    //        MainPage.Log($"新密钥:{mqttEncryptKey}");
                    //    }else
                    //    {
                    //        return;
                    //    }
                    //}
                    //之前已经获取参数成功过
                    if (MqttInfoConfig.Current.IfGetMqttInfoSuccess)
                    {
@@ -380,6 +565,8 @@
                catch (Exception ex)
                {
                    Utlis.WriteLine($"error:" + ex.Message);
                    //mqtt连接异常,清空本地mqtt信息,可能需要重新获取:wxr
                    MqttInfoConfig.Current.Refresh();
                }
                finally
                {
@@ -476,13 +663,13 @@
                    MqttInfoConfig.Current.Save();
                    mqttEncryptKey = MqttInfoConfig.Current.HomeGatewayInfo.aesKey;
                    //mqttEncryptKey = MqttInfoConfig.Current.HomeGatewayInfo.aesKey;
                    //解密密钥规则:已现有的住宅ID为基准,从右边一一获取值,最后如果不够16位,则往右补零
                    string aesKey = string.Empty;
                    for (int i = DB_ResidenceData.Instance.CurrentRegion.RegionID.Length - 1; i >= 0; i--)
                    for (int i = DB_ResidenceData.Instance.CurrentRegion.id.Length - 1; i >= 0; i--)
                    {
                        aesKey += DB_ResidenceData.Instance.CurrentRegion.RegionID[i].ToString();
                        aesKey += DB_ResidenceData.Instance.CurrentRegion.id[i].ToString();
                        if (aesKey.Length == 16) { break; }
                    }
                    aesKey = aesKey.PadRight(16, '0');
@@ -495,8 +682,6 @@
                                        .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");
@@ -521,6 +706,8 @@
                    //重新中心服务器获取参数标记
                    MqttInfoConfig.Current.IfGetMqttInfoSuccess = false;
                    Console.WriteLine("Connect error: " + ex.Message);
                    //mqtt连接异常,清空本地mqtt信息,可能需要重新获取:wxr
                    MqttInfoConfig.Current.Refresh();
                }
                finally
                {
@@ -564,22 +751,12 @@
        /// </summary>
        static void ReceiveNotifySqueezeAsync(string mMes)
        {
            if (mMes == PushSignStr ) return;//是自己的登录推送不处理//或者当前不是远程链接状态
            if (mMes == PushSignStr) return;//是自己的登录推送不处理//或者当前不是远程链接状态
            //测试账号,不挤下线
            switch (UserInfo.Current.AccountString)
            switch (UserInfo.Current.userMobileInfo)
            {
                case "13415629083":
                case "18316120654":
                case "15622703419":
                case "18824864143":
                case "15626203746":
                case "464027401@qq.com":
                case "2791308028@qq.com":
                case "13697499568":
                case "18666455392":
                case "13375012446":
                case "13602944661":
                case "18778381374":
                case "18316672920":
                    return;
            }
@@ -648,9 +825,9 @@
                {
                    case 0:
                        topicName = $"/ClientToBusGateWay/{MqttInfoConfig.Current.HomeGatewayInfo.gatewayId}/Common/ON";
                        if (!string.IsNullOrEmpty(mqttEncryptKey))
                        if (!string.IsNullOrEmpty(DB_ResidenceData.Instance.HomeGateway.aesKey))
                        {
                            message = Securitys.EncryptionService.AesEncryptPayload(message, mqttEncryptKey);
                            message = Securitys.EncryptionService.AesEncryptPayload(message, DB_ResidenceData.Instance.HomeGateway.aesKey);
                        }
                        await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicName, Payload = message, Retain = false, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
                        break;
@@ -711,9 +888,12 @@
        /// <returns></returns>
        static async Task GetMqttInfoAndMQTTConnectAsync()
        {
            var mqttInfoRequestResult_Obj = new Server.HttpServerRequest().GetMqttRemoteInfo(GetRandomKey());
            var mqttInfoRequestResult_Obj = new HttpServerRequest().GetMqttRemoteInfo(GetRandomKey());
            if (mqttInfoRequestResult_Obj != null)
            {
                MainPage.Log($"获取mqtt info 成功 /r/n clientId:{mqttInfoRequestResult_Obj.clientId}/r/n passWord:{mqttInfoRequestResult_Obj.passWord} /r/n url:{mqttInfoRequestResult_Obj.url}/r/n userName:{mqttInfoRequestResult_Obj.userName}");
                MqttInfoConfig.Current.mMqttInfo = mqttInfoRequestResult_Obj;
                await MQTTConnectAsync();
                //1.判断是否绑定了网关,获取网关远程连接的加密KEY
@@ -882,4 +1062,4 @@
    }
}
}