陈嘉乐
2020-04-28 3272ca5b51e19f7f8a827b0f68400570a547fe60
ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs
@@ -60,6 +60,12 @@
        /// <value><c>true</c> if is remote; otherwise, <c>false</c>.</value>
        public static bool IsRemote;
        /// <summary>
        /// 是否拥有远程连接的权限
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public static bool AllowRemoteCtrl = true;
        /// <summary>
        /// 网关保存路径
        /// </summary>
@@ -137,12 +143,6 @@
        public List<CommonDevice> DeviceList = new List<CommonDevice>();
        /// <summary>
        /// 所有网关中的设备列表
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public List<CommonDevice> AllGatewayDeviceList = new List<CommonDevice>();
        /// <summary>
        /// 网关中场景列表
        /// 一个场景中包含所有信息,包括场景设备信息
        /// </summary>
@@ -154,34 +154,6 @@
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public List<Scene.GetSceneDeviceListInfo> SceneDeviceList = new List<Scene.GetSceneDeviceListInfo>();
        /// <summary>
        /// 网关中逻辑列表
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public static List<Logic.GetLogicInfoResponseData> LogicList = new List<Logic.GetLogicInfoResponseData>();
        /// <summary>
        /// 网关中hdl私有按键绑定列表
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public List<HDLbutton> HdlButtonList = new List<HDLbutton>();
        //网关中新的设备列表
        [Newtonsoft.Json.JsonIgnore]
        public List<CommonDevice> ListNewDeviceInfoData = new List<CommonDevice>();
        /// <summary>
        /// 私有按键信息列表
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public System.Collections.Generic.Dictionary<string, HDLbutton> hdlButtonInfoList = new Dictionary<string, HDLbutton>();
        /// <summary>
        /// 传感器信息列表
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public System.Collections.Generic.Dictionary<string, Scene.TaskListInfo> sceneTaskInfoList = new Dictionary<string, Scene.TaskListInfo>();
        #region action variable
        /// <summary>
@@ -3048,22 +3020,6 @@
        public static readonly System.Collections.Generic.List<IStatus> StatusList = new System.Collections.Generic.List<IStatus>();
        /// <summary>
        /// 设备状态更新
        /// </summary>
        /// <param name="commonDevice">Common device.</param>
        public static void UpdateDeviceStatus(CommonDevice commonDevice)
        {
            if (commonDevice == null)
            {
                return;
            }
            for (int i = 0; i < StatusList.Count; i++)
            {
                StatusList[i].Changed(commonDevice);
            }
        }
        /// <summary>
        /// 设备信息变化
        /// <para>type:如果为 DeviceInComingRespon:设备新上报</para>
        /// <para>type:如果为 IASInfoReport:RemoveDeviceRespon</para>
@@ -3174,14 +3130,14 @@
                            {
                                if (localMqttClient.Options == null)
                                {
                                    var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder().WithClientId(currentGuid.ToString())
                       .WithTcpServer(brokerName, 1883)
                       .WithKeepAlivePeriod(TimeSpan.FromSeconds(20))
                       .WithCleanSession()
                        //.WithCommunicationTimeout(TimeSpan.FromSeconds(10))
                       .WithCredentials("", "")
                       .Build();
                                    await localMqttClient.ConnectAsync(options, CancellationToken.None);
                                    var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()//MQTT连接参数填充
                                    .WithClientId(currentGuid.ToString())//客户端ID
                                    .WithTcpServer(brokerName, 1883)//TCP服务端  1883  ,即MQTT服务端
                                    .WithCredentials("", "")//"", "")//凭证  帐号 密码
                                    .WithCommunicationTimeout(new TimeSpan(0, 0, 60)) //重连超时时间,默认5s
                                    .WithKeepAlivePeriod(new TimeSpan(0, 0, 15)) //保持连接时间,默认5s,心跳包
                                    .Build();//
                                    await localMqttClient.ConnectAsync(options);
                                }
                                else
                                {
@@ -3229,6 +3185,11 @@
        /// <returns></returns>
        static async System.Threading.Tasks.Task initGateWayBaseInfomation()
        {
            if (AllowRemoteCtrl == false)
            {
                //没有远程连接的权限
                return;
            }
            string loginToken = Config.Instance.Token;
            if (Config.Instance.Home.IsOthreShare == true)
            {
@@ -3271,11 +3232,13 @@
                    var statuCode = jobject["StateCode"].ToString();
                    if (statuCode != "Success")
                    {
                        //Log出力
                        Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(-1, "接口访问失败★:App/GetSingleHomeGatewayPagger " + statuCode);
                        //序列化对象
                        var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject(pra2);
                        Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(-1, "参数:\r\n" + requestJson);
                        //Log出力
                        string errorMsg = "接口访问失败★:App/GetSingleHomeGatewayPagger " + statuCode + "\r\n";
                        errorMsg += "参数:\r\n" + requestJson;
                        Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(-1, errorMsg);
                        return;
                    }
                    var responseData = jobject["ResponseData"];
@@ -3323,10 +3286,12 @@
        /// <param name="brokerName">Broker name.</param>
        public static async System.Threading.Tasks.Task StartRemoteMqtt()
        {
            if (remoteMqttIsConnecting
                       || !Shared.Common.Config.Instance.IsLogin
                       || Shared.Common.Config.Instance.HomeId == ""
                       || remoteIsConnected)
            //追加:没有远程连接的权限
            if (AllowRemoteCtrl == false
               || remoteMqttIsConnecting
               || !Shared.Common.Config.Instance.IsLogin
               || Shared.Common.Config.Instance.HomeId == ""
               || remoteIsConnected)
            {
                return;
            }
@@ -3344,10 +3309,20 @@
                        if (RemoteMqttClient.ApplicationMessageReceivedHandler == null)
                        {
                            RemoteMqttClient.UseApplicationMessageReceivedHandler((e) =>
                            {
                                if (!RemoteMqttClient.IsConnected || !IsRemote)
                                {
                                    return;
                            {
                                //这里是特殊的主题
                                if (e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.ConnEmqClientId + "/Push/NotifySqueeze"//踢人下线
                                   || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/Deleted"//分享删除
                                   || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/DeletedShareData"//分享删除
                                   || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Guid + "/Push/Update"//成员权限变更
                                   || e.ApplicationMessage.Topic == "/ZigbeeGateWayToClient/" + Config.Instance.Home.Id + "_" + Config.Instance.Guid + "/PrimaryUserDelYou")//子账号被删除
                                {
                                    mqttRemoteClient_MqttMsgPublishReceived(e);
                                    return;
                                }
                                if (!RemoteMqttClient.IsConnected || !IsRemote)
                                {
                                    return;
                                }
                                mqttRemoteClient_MqttMsgPublishReceived(e);
                            });
@@ -3367,6 +3342,22 @@
                            RemoteMqttClient.UseConnectedHandler(async (e) =>
                            {
                                DebugPrintLog($"远程连接成功");
                                if (Config.Instance.Home.IsOthreShare == true)
                                {
                                    //订阅一个成员被删除的主题
                                    string myGuid = Config.Instance.Guid;
                                    await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/Deleted");
                                    //订阅一个分享数据已经变更的主题
                                    await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/DeletedShareData");
                                    //订阅一个子账号被删除的主题
                                    await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + Config.Instance.Home.Id + "_" + myGuid + "/PrimaryUserDelYou");
                                    //订阅一个成员权限已经变更的主题
                                    await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + myGuid + "/Push/Update");
                                }
                                //订阅一个挤下线的主题
                                await RemoteMqttClient.SubscribeAsync("/ZigbeeGateWayToClient/" + Config.Instance.ConnEmqClientId + "/Push/NotifySqueeze");
                                await initGateWayBaseInfomation();
                                Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.Remote);
                                //没有主网关时主动读取,获取主网关信息
@@ -3421,7 +3412,9 @@
                                ["RequestVersion"] = CommonPage.RequestVersion,
                                ["RequestSource"] = 0,
                                ["LoginAccessToken"] = Config.Instance.Token,
                                ["RequestProtocolType"] = 0
                                ["RequestProtocolType"] = 0,
                                ["PlatformStr"] = "h",//这两个值如果不设置,则云端不发布主题
                                ["PublishPayloadJsonStr"] = "1"
                            };
                            var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData));
                            result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/GetConnMqttInfo", bytes, Config.Instance.Token);
@@ -3436,7 +3429,9 @@
                                ["LoginAccessToken"] = Config.Instance.Token,
                                ["RequestProtocolType"] = 0,
                                ["MainUserDistributedMark"] = Config.Instance.Home.MainUserDistributedMark,
                                ["HomeId"] = Config.Instance.Home.Id
                                ["HomeId"] = Config.Instance.Home.Id,
                                ["PlatformStr"] = "h",//这两个值如果不设置,则云端不发布主题
                                ["PublishPayloadJsonStr"] = "1"
                            };
                            var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(jsonData));
                            result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/EmqMqtt/ShareMemberConnMqttInfo", bytes, Config.Instance.Token);
@@ -3444,6 +3439,15 @@
                        if (result != null)
                        {
                            var jobject = Newtonsoft.Json.Linq.JObject.Parse(Encoding.UTF8.GetString(result));
                            if (jobject["StateCode"].ToString() == "NotAllowRemoteCtrl")
                            {
                                //没有远程连接的权限
                                AllowRemoteCtrl = false;
                                return;
                            }
                            //虽然不知道对挤下线那一块有没有用,不过先这么弄
                            await System.Threading.Tasks.Task.Delay(1500);
                            var responseData = jobject["ResponseData"];
                            if (responseData != null)
                            {
@@ -3451,6 +3455,8 @@
                                var connEmqClientId = responseData["ConnEmqClientId"]?.ToString();
                                var connEmqUserName = responseData["ConnEmqUserName"]?.ToString();
                                var connEmqPwd = responseData["ConnEmqPwd"]?.ToString();
                                //记录起当前的客户端ID
                                Config.Instance.ConnEmqClientId = connEmqClientId;
                                var connEmqDomainPorts = connEmqDomainPort.Replace("//", "").Split(':');
                                var domain = connEmqDomainPorts[1];
@@ -3496,7 +3502,8 @@
                {
                    localIsConnected = false;
                    DebugPrintLog($"Local主动断开_{s}");
                    await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions {  }, CancellationToken.None);
                    //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions {  }, CancellationToken.None);
                    await localMqttClient.DisconnectAsync();
                }
            }
            catch (Exception ex)
@@ -3516,7 +3523,8 @@
                {
                    remoteIsConnected = false;
                    DebugPrintLog($"Remote主动断开_{s}");
                    await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
                    await RemoteMqttClient.DisconnectAsync();
                }
            }
            catch(Exception e) { 
@@ -3851,7 +3859,10 @@
                    epoint = topic.Split('/')[3];
                    cluID = topic.Split('/')[4];
                    attrId = topic.Split('/')[5];
                }
                }
                //全局接收网关推送的的逻辑(为了执行速度,尽可能的别加耗时的操作)
                Shared.Phone.UserCenter.HdlGatewayReceiveLogic.Current.GatewayOverallMsgReceive(gatewayID, topic, reportStatus, message);
                var gwa = GateWayList.Find(obj => obj.getGatewayBaseInfo.gwID == gatewayID);
                if (gwa == null)
@@ -3883,9 +3894,6 @@
                {
                    jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                }
                //全局接收网关推送的的逻辑(为了执行速度,尽可能的别加耗时的操作)
                Shared.Phone.UserCenter.HdlGatewayReceiveLogic.Current.GatewayOverallMsgReceive(gatewayID, topic, reportStatus, jobject);
                #region 远程,主网关上报通知
                if (IsRemote)
@@ -3958,8 +3966,7 @@
                        DebugPrintLog("DeviceInComingRespon已经通知");
                        gwa.ReportAction("DeviceInComingRespon", tempDevice.getNewDeviceInfo);
                    }
                    UpdateDeviceInfo(tempDevice, "DeviceInComingRespon");
                    UpdateDeviceStatus(gwa);
                    UpdateDeviceInfo(tempDevice, "DeviceInComingRespon");
                }
                #endregion
                #region 设备在线状态更新反馈
@@ -3977,7 +3984,6 @@
                    if (infoTempDevice == null)
                    {
                        gwa.DeviceList.Add(tempDevice);
                        UpdateDeviceStatus(tempDevice);
                        UpdateDeviceInfo(tempDevice, "OnlineStatusChange");
                    }
                    else
@@ -3987,7 +3993,6 @@
                            infoTempDevice.DeviceInfo.IsOnline = infoTempDevice.IsOnline;
                        }
                        UpdateDeviceInfo(infoTempDevice, "OnlineStatusChange");
                        UpdateDeviceStatus(infoTempDevice);
                    }
                }
                #endregion
@@ -4013,7 +4018,6 @@
                                    }
                                    else
                                    {
                                        UpdateDeviceStatus(tempDevice);
                                        UpdateDeviceInfo(tempDevice, "RemoveDeviceRespon");
                                        if (tempDevice.removeDeviceResponseData.Result == 0)
                                        {
@@ -4041,7 +4045,6 @@
                    var tempDevice = new CommonDevice { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId };
                    tempDevice.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DeviceStatusReportData>(jobject["Data"].ToString());
                    UpdateDeviceStatus(tempDevice);
                    UpdateDeviceInfo(tempDevice, "DeviceStatusReport");
                }
                #endregion
@@ -4063,7 +4066,6 @@
                                DebugPrintLog("DoorLockProgrammingEventNotificationCommand已经通知");
                                gwa.ReportAction("DoorLockProgrammingEventNotificationCommand", doorLock);
                            }
                            UpdateDeviceStatus(doorLock);
                            UpdateDeviceInfo(doorLock, "DoorLockProgrammingEventNotificationCommand");
                            break;
                    }
@@ -4087,7 +4089,6 @@
                                DebugPrintLog("DoorLockProgrammingEventNotificationCommand已经通知");
                                gwa.ReportAction("DoorLockProgrammingEventNotificationCommand", doorLock);
                            }
                            UpdateDeviceStatus(doorLock);
                            UpdateDeviceInfo(doorLock, "DoorLockProgrammingEventNotificationCommand");
                            break;
                    }
@@ -4109,8 +4110,6 @@
                                //ias.Save();
                                gwa.ReportAction("IASInfoReport", ias.iASInfo);
                            }
                            UpdateDeviceStatus(ias);
                            UpdateDeviceInfo(ias, "IASInfoReport");
                            break;
                    }
@@ -4225,37 +4224,37 @@
                #region 逻辑被调用反馈
                else if (topic == gatewayID + "/" + "Logic/Execute_Respon")
                {
                    var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID };
                    logic.logicExecuteRespo = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.ExecuteResponse>(jobject["Data"].ToString());
                    //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID };
                    //logic.logicExecuteRespo = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.ExecuteResponse>(jobject["Data"].ToString());
                    if (logic.logicExecuteRespo == null)
                    {
                        return;
                    }
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("LogicExecuteReport已经通知");
                        gwa.ReportAction("LogicExecuteReport", logic.logicExecuteRespo);
                    }
                    //if (logic.logicExecuteRespo == null)
                    //{
                    //    return;
                    //}
                    ////上报类型通知
                    //if (gwa.ReportAction != null)
                    //{
                    //    DebugPrintLog("LogicExecuteReport已经通知");
                    //    gwa.ReportAction("LogicExecuteReport", logic.logicExecuteRespo);
                    //}
                }
                #endregion
                #region 时间点条件推迟执行
                else if (topic == gatewayID + "/" + "Logic/TimingWillArrive")
                {
                    var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID };
                    logic.timingWillArriveData = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.TimingWillArriveData>(jobject["Data"].ToString());
                    //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID };
                    //logic.timingWillArriveData = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.TimingWillArriveData>(jobject["Data"].ToString());
                    if (logic.timingWillArriveData == null)
                    {
                        return;
                    }
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("TimingWillArrive已经通知");
                        gwa.ReportAction("TimingWillArrive", logic.timingWillArriveData);
                    }
                    //if (logic.timingWillArriveData == null)
                    //{
                    //    return;
                    //}
                    ////上报类型通知
                    //if (gwa.ReportAction != null)
                    //{
                    //    DebugPrintLog("TimingWillArrive已经通知");
                    //    gwa.ReportAction("TimingWillArrive", logic.timingWillArriveData);
                    //}
                }
                #endregion
                #region 模式安防动作被最终激活时发送报警信息
@@ -4329,22 +4328,18 @@
                #region 设备请求APP获取升级数据
                else if (topic == gatewayID + "/" + "ZbDataPassthrough")
                {
                    var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                    gatewayTemp.clientDataPassthroughResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<ClientDataPassthroughResponseData>(jobject["Data"].ToString());
                    if (gatewayTemp.clientDataPassthroughResponseData == null)
                    {
                        return;
                    }
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("DeviceRequestAcUpdateData");
                        gwa.ReportAction("DeviceRequestAcUpdateData", gatewayTemp.clientDataPassthroughResponseData);
                    {
                        var clientDataPassthrough = Newtonsoft.Json.JsonConvert.DeserializeObject<ClientDataPassthroughResponseData>(jobject["Data"].ToString());
                        if (clientDataPassthrough != null)
                        {
                            DebugPrintLog("DeviceRequestAcUpdateData");
                            gwa.ReportAction("DeviceRequestAcUpdateData", clientDataPassthrough);
                        }
                    }
                }
                #endregion
                DebugPrintLog("网关返回数据通知");
            }
            catch (Exception ex)
            {