xm
2020-05-06 fffd8afca5b69a592e9ba8913204f83f478e2f17
ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs
old mode 100755 new mode 100644
@@ -143,12 +143,6 @@
        public List<CommonDevice> DeviceList = new List<CommonDevice>();
        /// <summary>
        /// 所有网关中的设备列表
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public List<CommonDevice> AllGatewayDeviceList = new List<CommonDevice>();
        /// <summary>
        /// 网关中场景列表
        /// 一个场景中包含所有信息,包括场景设备信息
        /// </summary>
@@ -160,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>
@@ -3054,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>
@@ -3180,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
                                {
@@ -3323,8 +3273,8 @@
        /// <summary>
        /// 远程MqttClient
        /// </summary>
        public static IMqttClient RemoteMqttClient= new MqttFactory().CreateMqttClient();
        static bool remoteIsConnected;
        public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient();
        static bool remoteIsConnected;
        private int IsLogin = 0;
        [Newtonsoft.Json.JsonIgnore]
        static Action actionTemp;
@@ -3359,23 +3309,19 @@
                        if (RemoteMqttClient.ApplicationMessageReceivedHandler == null)
                        {
                            RemoteMqttClient.UseApplicationMessageReceivedHandler((e) =>
                            {
                                if (!RemoteMqttClient.IsConnected || !IsRemote)
                                {
                                    if (e.ApplicationMessage.Topic != "/ZigbeeGateWayToClient/" + Config.Instance.ConnEmqClientId + "/Push/NotifySqueeze")
                                    {
                                        return;
                                    }
                                }
                                //如果当前使用的是内网模式
                                if (IsRemote == false)
                            {
                                //这里是特殊的主题
                                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")//子账号被删除
                                {
                                    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")
                                    {
                                        mqttRemoteClient_MqttMsgPublishReceived(e);
                                    }
                                    mqttRemoteClient_MqttMsgPublishReceived(e);
                                    return;
                                }
                                if (!RemoteMqttClient.IsConnected || !IsRemote)
                                {
                                    return;
                                }
                                mqttRemoteClient_MqttMsgPublishReceived(e);
@@ -3404,6 +3350,10 @@
                                    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");
@@ -3495,6 +3445,9 @@
                                AllowRemoteCtrl = false;
                                return;
                            }
                            //虽然不知道对挤下线那一块有没有用,不过先这么弄
                            await System.Threading.Tasks.Task.Delay(1500);
                            var responseData = jobject["ResponseData"];
                            if (responseData != null)
                            {
@@ -3514,8 +3467,8 @@
           .WithTcpServer(domain, int.Parse(port))
           .WithCredentials(connEmqUserName, connEmqPwd)
           .WithKeepAlivePeriod(TimeSpan.FromSeconds(20))
           .WithCleanSession()
           //.WithCommunicationTimeout(TimeSpan.FromSeconds(10))
           .WithCleanSession()
           //.WithCommunicationTimeout(TimeSpan.FromSeconds(10))
           .Build();
                                await DisConnectRemoteMqttClient("StartRemoteMqtt");
                                await RemoteMqttClient.ConnectAsync(options, CancellationToken.None);
@@ -3550,7 +3503,7 @@
                    localIsConnected = false;
                    DebugPrintLog($"Local主动断开_{s}");
                    //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions {  }, CancellationToken.None);
                    await localMqttClient.DisconnectAsync();
                    await localMqttClient.DisconnectAsync();
                }
            }
            catch (Exception ex)
@@ -3562,7 +3515,7 @@
        /// <summary>
        /// 断开远程Mqtt的链接
        /// </summary>
        public static async System.Threading.Tasks.Task DisConnectRemoteMqttClient(string s="")
        public static async System.Threading.Tasks.Task DisConnectRemoteMqttClient(string s = "")
        {
            try
            {
@@ -3574,7 +3527,8 @@
                    await RemoteMqttClient.DisconnectAsync();
                }
            }
            catch(Exception e) {
            catch (Exception e)
            {
                DebugPrintLog($"Remote断开通讯连接出异常:{e.Message}");
            }
        }
@@ -3680,7 +3634,7 @@
                        {
                            await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                        }
                        catch(Exception e)
                        catch (Exception e)
                        {
                            DebugPrintLog($"Local主动断开_{e.Message}");
                            await DisConnectLocalMqttClient(e.Message);
@@ -3799,7 +3753,8 @@
                {
                    return;
                }
                if (topics[2]== "NotifyGateWayInfoChange") {
                if (topics[2] == "NotifyGateWayInfoChange")
                {
                    initGateWayBaseInfomation();
                    return;
                }
@@ -3885,7 +3840,7 @@
        /// <param name="topic">Topic.</param>
        /// <param name="message">Message.</param>
        /// <param name="e">E.</param>
        static void ReceiveMessage(string topic, string message, byte []payload)
        static void ReceiveMessage(string topic, string message, byte[] payload)
        {
            try
            {
@@ -4013,8 +3968,7 @@
                        DebugPrintLog("DeviceInComingRespon已经通知");
                        gwa.ReportAction("DeviceInComingRespon", tempDevice.getNewDeviceInfo);
                    }
                    UpdateDeviceInfo(tempDevice, "DeviceInComingRespon");
                    UpdateDeviceStatus(gwa);
                    UpdateDeviceInfo(tempDevice, "DeviceInComingRespon");
                }
                #endregion
                #region 设备在线状态更新反馈
@@ -4032,7 +3986,6 @@
                    if (infoTempDevice == null)
                    {
                        gwa.DeviceList.Add(tempDevice);
                        UpdateDeviceStatus(tempDevice);
                        UpdateDeviceInfo(tempDevice, "OnlineStatusChange");
                    }
                    else
@@ -4042,7 +3995,6 @@
                            infoTempDevice.DeviceInfo.IsOnline = infoTempDevice.IsOnline;
                        }
                        UpdateDeviceInfo(infoTempDevice, "OnlineStatusChange");
                        UpdateDeviceStatus(infoTempDevice);
                    }
                }
                #endregion
@@ -4068,7 +4020,6 @@
                                    }
                                    else
                                    {
                                        UpdateDeviceStatus(tempDevice);
                                        UpdateDeviceInfo(tempDevice, "RemoveDeviceRespon");
                                        if (tempDevice.removeDeviceResponseData.Result == 0)
                                        {
@@ -4096,7 +4047,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
@@ -4118,7 +4068,6 @@
                                DebugPrintLog("DoorLockProgrammingEventNotificationCommand已经通知");
                                gwa.ReportAction("DoorLockProgrammingEventNotificationCommand", doorLock);
                            }
                            UpdateDeviceStatus(doorLock);
                            UpdateDeviceInfo(doorLock, "DoorLockProgrammingEventNotificationCommand");
                            break;
                    }
@@ -4142,7 +4091,6 @@
                                DebugPrintLog("DoorLockProgrammingEventNotificationCommand已经通知");
                                gwa.ReportAction("DoorLockProgrammingEventNotificationCommand", doorLock);
                            }
                            UpdateDeviceStatus(doorLock);
                            UpdateDeviceInfo(doorLock, "DoorLockProgrammingEventNotificationCommand");
                            break;
                    }
@@ -4164,8 +4112,6 @@
                                //ias.Save();
                                gwa.ReportAction("IASInfoReport", ias.iASInfo);
                            }
                            UpdateDeviceStatus(ias);
                            UpdateDeviceInfo(ias, "IASInfoReport");
                            break;
                    }
@@ -4280,37 +4226,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 模式安防动作被最终激活时发送报警信息