黄学彪
2020-12-17 9f326f4000847e6167d8166fa2f6a66f53cb3734
ZigbeeApp/Shared/Phone/ZigBee/Device/ZbGateway.cs
@@ -21,70 +21,78 @@
    /// </summary>
    [System.Serializable]
    public class ZbGateway : ZbGatewayData
    {
        public ZbGateway()
        {
            this.Type = DeviceType.ZbGateway;
        }
        #region 网关特殊信息处理
        /// <summary>
        /// 主网关
        /// </summary>
        /// <value>The main gate way.</value>
        public static ZbGateway MainGateWay
        {
            get
            {
                return GateWayList.Find((obj) => { return obj.getGatewayBaseInfo.HomeId == Shared.Common.Config.Instance.HomeId && obj.getGatewayBaseInfo.IsMainGateWay; });
            }
        }
    {
        #region 一堆变量
        /// <summary>
        /// 主网关
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public bool IsMainGateWay
        public static ZbGateway MainGateWay
        {
            get
            {
                return getGatewayBaseInfo != null && getGatewayBaseInfo.IsMainGateWay;
                ZbGateway mainWay = null;
                for (int i = 0; i < GateWayList.Count; i++)
                {
                    if (GateWayList[i].HomeId == Config.Instance.HomeId)
                    {
                        //2020.07.16变更:别管那么多,如果住宅ID一样,先确定就是它了(不然有时候经常返回null,有可能是刷新不到)
                        mainWay = GateWayList[i];
                        if (mainWay.IsMainGateWay == true)
                        {
                            //然后如果它确实是主网关,直接break
                            break;
                        }
                    }
                }
                return mainWay;
            }
        }
        /// <summary>
        /// 是否使用远程连接模式
        /// </summary>
        /// <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;
        public static bool IsRemote;
        /// <summary>
        /// 网关保存路径
        /// </summary>
        /// <value>The file path.</value>
        [Newtonsoft.Json.JsonIgnore]
        public override string FilePath
        public string FilePath
        {
            get
            {
                var deviceType = Type.ToString();
                var fileName = "Gateway_" + deviceType + "_" + this.getGatewayBaseInfo?.gwID;
                var fileName = "Gateway_" + DeviceType.ZbGateway.ToString() + "_" + this.GwId;
                return fileName;
            }
        }
        /// <summary>
        /// 等待从网关接收数据的时间
        /// </summary>
        /// <value>The wait receive data time.</value>
        [Newtonsoft.Json.JsonIgnore]
        public int WaitReceiveDataTime
        {
            get
            {
                if (Device.ZbGateway.RemoteMqttClient != null && Device.ZbGateway.RemoteMqttClient.IsConnected)
                {
                    return 10000;
                }
                else
                {
                    return 3000;
                }
            }
        }
        /// <summary>
        /// 局域网加密密码
        /// </summary>
        string password;
        private string password;
        /// <summary>
        /// 局域网加密密钥
        /// </summary>
@@ -99,29 +107,14 @@
                }
                return password;
            }
        }
        #region variable
        }
        /// <summary>
        /// 远程连接成功时的时间
        /// 网关远程连接的一个标识ID,获取到了就不再改变
        /// </summary>
        public static DateTime LoginRemoteDateTime = DateTime.Now;
        [Newtonsoft.Json.JsonIgnore]
        private static string RemoteClientId = new Random().Next(10, 99).ToString();
        /// <summary>
        /// 同步到远程的当前时间戳
        /// </summary>Re
        public static ulong CurrentTimeStamp
        {
            get
            {
                return RemoteTimeStamp + (ulong)(DateTime.Now - LoginRemoteDateTime).TotalSeconds;
            }
        }
        /// <summary>
        /// 远程连接成功时的时间戳
        /// </summary>
        public static ulong RemoteTimeStamp;
        /// <summary>
        /// 网关是否加密
        /// </summary>
@@ -138,37 +131,6 @@
        [Newtonsoft.Json.JsonIgnore]
        public static List<ZbGateway> GateWayList = new List<ZbGateway>();
        //当前网关中的设备列表
        [Newtonsoft.Json.JsonIgnore]
        public List<CommonDevice> DeviceList = new List<CommonDevice>();
        /// <summary>
        /// 网关中场景列表
        /// 一个场景中包含所有信息,包括场景设备信息
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public static List<Scene.GetSceneAllInfo> AllSceneList = new List<Scene.GetSceneAllInfo>();
        /// <summary>
        /// 网关中场景的设备列表
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public List<Scene.GetSceneDeviceListInfo> SceneDeviceList = new List<Scene.GetSceneDeviceListInfo>();
        #region action variable
        /// <summary>
        /// 接收数据后回调
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        Action<object> action;
        /// <summary>
        /// 设置数据回调
        /// </summary>
        public void SetAction(Action<object> action, int timeOut = 1000)
        {
            this.action = action;
        }
        /// <summary>
        /// 网关推送数据
        /// <para>第一个参数:如果为 DeviceInComingRespon:设备新上报</para>
@@ -183,24 +145,15 @@
        /// <para>第一个参数:如果为 ZoneTriggerReport:防区被触发时报告</para>
        /// <para>第一个参数:如果为 LogicExecuteReport:逻辑被调用反馈</para>
        /// <para>第一个参数:如果为 TimingWillArrive:时间点条件推迟执行</para>
        /// para>第一个参数: 如果为 ModeTriggerReport:模式安防动作被最终激活时发送报警信息</para>
        /// <para>第一个参数: 如果为 ModeTriggerReport:模式安防动作被最终激活时发送报警信息</para>
        /// <para>第一个参数:如果为 EnOrWithdrawSucceedReport:通过外部方式布防撤防成功时报告息</para>
        /// <para>第一个参数:如果为 PushTargetInfoReport:胁迫密码撤防时短信推送</para>
        /// <para>第一个参数:如果为 DeviceDefaultAck:节点设备默认反馈</para>
        /// <para>第一个参数:如果为 DDevice/IsGetEpointInfo:有新设备加入zigbee网络反馈</para>设备请求APP获取升级数据
        /// <para>第一个参数:如果为 Device/DeviceJoinZbNet:获取新设备所有端点信息是否成功反馈</para>
        /// <para>第一个参数:如果为 DeviceRequestAcUpdateData: 设备请求空调发升级数据</para>
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public Action<string, object> ReportAction;
        /// <summary>
        /// 云端通讯错误数据上报
        ///<para>"ForwardGatewayNoOnLine", "当前操作的网关不在线"</para>
        ///<para>"AppTimeOut", "从云端获取数据超时,请重新获取"</para>
        ///<para>"AppNoLogin", "登录过期,请重新登录"</para>
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public Action<string, string> CloudErrorAction;
        /// <summary>
        /// 网关文件流内容通知
@@ -219,8 +172,7 @@
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public Action<string, string> Actions;
        #endregion
        #endregion
        #endregion
        #region 网关API
@@ -241,8 +193,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -250,24 +201,21 @@
                        }
                        else
                        {
                            d = new GetGwVersionAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new GetGwVersionAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "GetZbGwVersionRespon")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        gatewayTemp.getGwVersion = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGwVersionData>(jobject["Data"].ToString());
                        var getGwVersion = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGwVersionData>(jobject["Data"].ToString());
                        if (gatewayTemp.getGwVersion == null)
                        if (getGwVersion == null)
                        {
                            d = new GetGwVersionAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new GetGwVersionAllData { getGwVersion = gatewayTemp.getGwVersion };
                            AppVersion = gatewayTemp.getGwVersion.AppVersion;
                            ZigbeeVersion = gatewayTemp.getGwVersion.ZigbeeVersion;
                            d = new GetGwVersionAllData { getGwVersion = getGwVersion };
                            //Save();
                            DebugPrintLog($"UI收到通知后的主题_{topic}");
                        }
@@ -319,16 +267,15 @@
                    if (topic == gatewayID + "/" + "GetZbGwInfo_Respon")
                    {
                        var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID };
                        gatewayTemp.getGwInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGwData>(jobject["Data"].ToString());
                        var getGwInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGwData>(jobject["Data"].ToString());
                        if (gatewayTemp.getGwInfo == null)
                        if (getGwInfo == null)
                        {
                            data = new GetGwAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            data = new GetGwAllData { getGwData = gatewayTemp.getGwInfo };
                            data = new GetGwAllData { getGwData = getGwInfo };
                            DebugPrintLog($"UI收到通知后的主题_{topic}");
                        }
                    }
@@ -354,7 +301,7 @@
                return data;
            });
        }
        }
        #endregion
        #region 读取协调器MAC地址.
@@ -373,8 +320,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -382,13 +328,12 @@
                        }
                        else
                        {
                            d = new GetMacResponData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new GetMacResponData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "ZbGw/GetMac_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                        var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject<MacAddrData>(jobject["Data"].ToString());
                        if (tempData == null)
@@ -443,8 +388,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -452,22 +396,21 @@
                        }
                        else
                        {
                            d = new GwReNameAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new GwReNameAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "GwReName_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        gatewayTemp.gwRename = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.GwReNameData>(jobject["Data"].ToString());
                        var gwRename = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.GwReNameData>(jobject["Data"].ToString());
                        if (gatewayTemp.gwRename == null)
                        if (gwRename == null)
                        {
                            d = new GwReNameAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new GwReNameAllData { gwReNameData = gatewayTemp.gwRename };
                            d = new GwReNameAllData { gwReNameData = gwRename };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
@@ -526,8 +469,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -535,21 +477,20 @@
                        }
                        else
                        {
                            d = new GwSetHomeIdAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new GwSetHomeIdAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "GwSetHomeId_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        gatewayTemp.gwSetHomeId = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.GwSetHomeIdData>(jobject["Data"].ToString());
                        if (gatewayTemp.gwSetHomeId == null)
                        var gwSetHomeId = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.GwSetHomeIdData>(jobject["Data"].ToString());
                        if (gwSetHomeId == null)
                        {
                            d = new GwSetHomeIdAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new GwSetHomeIdAllData { gwSetHomeIdData = gatewayTemp.gwSetHomeId };
                            d = new GwSetHomeIdAllData { gwSetHomeIdData = gwSetHomeId };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
@@ -560,17 +501,9 @@
                {
                    //账号ID
                    string accountId = string.Empty;
                    if (homeId != string.Empty)
                    if (homeId != string.Empty)
                    {
                        if (Shared.Phone.UserCenter.UserCenterResourse.UserInfo.AuthorityNo == 1)
                        {
                            //主账号
                            accountId = Config.Instance.Guid;
                        }
                        else
                        {
                            accountId = Config.Instance.Home.MainUserDistributedMark;
                        }
                        accountId = Config.Instance.Guid;
                    }
                    var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 82 } };
                    var data = new JObject { { "HomeId", homeId }, { "AccountId", accountId } };
@@ -603,82 +536,6 @@
        }
        #endregion
        #region 获取网关记录的设备属性状态
        /// <summary>
        ///获取网关记录的设备属性状态
        /// </summary>
        public async System.Threading.Tasks.Task<GetStatusRecordAllInfo> GetStatusRecordAsync(string deviceAddr, int deviceEpoint)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                GetStatusRecordAllInfo d = null;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
                            d = new GetStatusRecordAllInfo { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new GetStatusRecordAllInfo { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "GetStatusRecord_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        gatewayTemp.getStatusRecordInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.GetStatusRecordInfo>(jobject["Data"].ToString());
                        if (gatewayTemp.getStatusRecordInfo == null)
                        {
                            d = new GetStatusRecordAllInfo { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new GetStatusRecordAllInfo { getStatusRecordInfo = gatewayTemp.getStatusRecordInfo };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
                };
                Actions += action;
                DebugPrintLog("GetStatusRecord_Actions 启动" + System.DateTime.Now.ToString());
                try
                {
                    var jObject = new JObject { { "DeviceAddr", deviceAddr }, { "Epoint", deviceEpoint }, { "Cluster_ID", 0 }, { "Command", 80 } };
                    Send("GetStatusRecord", jObject.ToString());
                }
                catch { }
                var dateTime = DateTime.Now;
                while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
                {
                    await System.Threading.Tasks.Task.Delay(10);
                    if (d != null)
                    {
                        break;
                    }
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
                {
                    d = new GetStatusRecordAllInfo { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
                DebugPrintLog("GetStatusRecord_Actions 退出" + System.DateTime.Now.ToString());
                return d;
            });
        }
        #endregion
        #region 允许设备入网
        ///<summary >
        /// 搜索新入网的设备(允许设备入网)
@@ -688,7 +545,6 @@
        {
            await System.Threading.Tasks.Task.Run(async () =>
            {
                CommonDevice commonDev = null;
                Action<string, string> action1 = (topic, message) => { };
                Actions += action1;
                var jObject = new JObject { { "Cluster_ID", 0 }, { "Command", 94 } };
@@ -743,8 +599,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -752,13 +607,12 @@
                        }
                        else
                        {
                            d = new GwLinuxResetResponData { errorMessageBase = ErrorMess(temp.Error) };
                            d = new GwLinuxResetResponData { errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "GwLinuxReset_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"].ToString());
                        if (result == null)
@@ -821,8 +675,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -830,13 +683,12 @@
                        }
                        else
                        {
                            d = new GwRebootResponAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new GwRebootResponAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "GwReboot_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"].ToString());
                        if (result == null)
@@ -897,8 +749,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -906,22 +757,21 @@
                        }
                        else
                        {
                            d = new SaveNVFileResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new SaveNVFileResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "ZbGwOperation/SaveNVFile_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                        gatewayTemp.zbGwOperationSaveNVFileData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.SaveNVFileResponseData>(jobject["Data"].ToString());
                        var zbGwOperationSaveNVFileData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.SaveNVFileResponseData>(jobject["Data"].ToString());
                        if (gatewayTemp.zbGwOperationSaveNVFileData == null)
                        if (zbGwOperationSaveNVFileData == null)
                        {
                            d = new SaveNVFileResponseAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new SaveNVFileResponseAllData { saveNVFileResponseData = gatewayTemp.zbGwOperationSaveNVFileData };
                            d = new SaveNVFileResponseAllData { saveNVFileResponseData = zbGwOperationSaveNVFileData };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
@@ -975,8 +825,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -984,14 +833,13 @@
                        }
                        else
                        {
                            d = new RestoreNVAllDtta { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new RestoreNVAllDtta { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "ZbGwOperation/RestoreNV_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                        var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.RestoreNVDtta>(jobject["Data"].ToString());
                        if (tempData == null)
@@ -1055,21 +903,19 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
                            d = new GwGetChannelResponData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new GwGetChannelResponData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new GwGetChannelResponData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "ZbGw/GetChannel_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                        var channel = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Channel"].ToString());
                        d = new GwGetChannelResponData { channel = channel };
                        DebugPrintLog($"UI收到通知后的主题_{ topic}");
@@ -1123,8 +969,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -1132,13 +977,12 @@
                        }
                        else
                        {
                            d = new ChangeChannelResponAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new ChangeChannelResponAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "ZbGw/ChangeChannel_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                        var tempInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<ChangeChannelResponData>(jobject["Data"].ToString());
                        if (tempInfo == null)
@@ -1217,8 +1061,11 @@
        /// </summary>
        public async System.Threading.Tasks.Task<Panel.PanelSwitchLevelInfo> ClientDataPassthroughBytesAsync(string deviceAddr, int devicePoint, long dataLength, byte[] passData)
        {
            var myDevice = Shared.Phone.HdlDeviceCommonLogic.Current.GetDevice(deviceAddr, devicePoint);
            Panel.PanelSwitchLevelInfo result = null;
            if (Gateway == null)
            if (myDevice.Gateway == null)
            {
                result = new Panel.PanelSwitchLevelInfo { errorMessageBase = "当前没有网关" };
                return result;
@@ -1232,8 +1079,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = Gateway.getGatewayBaseInfo.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -1242,24 +1088,23 @@
                        else
                        {
                            result = new Panel.PanelSwitchLevelInfo { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            result = new Panel.PanelSwitchLevelInfo { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "ZbDataPassthrough")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                        gatewayTemp.clientDataPassthroughResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<ClientDataPassthroughResponseData>(jobject["Data"].ToString());
                        var clientDataPassthroughResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ClientDataPassthroughResponseData>(jobject["Data"].ToString());
                        if (gatewayTemp.clientDataPassthroughResponseData == null)
                        if (clientDataPassthroughResponseData == null)
                        {
                            result = new Panel.PanelSwitchLevelInfo { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            if (gatewayTemp.clientDataPassthroughResponseData?.PassData != null)
                            if (clientDataPassthroughResponseData?.PassData != null)
                            {
                                var data = gatewayTemp.clientDataPassthroughResponseData.PassData;
                                var data = clientDataPassthroughResponseData.PassData;
                                if (data.Length == 14)
                                {
                                    var command = data[4].ToString() + data[5].ToString() + data[2].ToString() + data[3].ToString();
@@ -1276,7 +1121,7 @@
                    }
                };
                Gateway.Actions += action;
                myDevice.Gateway.Actions += action;
                System.Console.WriteLine("ClientDataPassthrough_Actions 启动" + System.DateTime.Now.ToString());
                try
@@ -1317,7 +1162,7 @@
                {
                    result = new Panel.PanelSwitchLevelInfo { errorMessageBase = " 回复超时,请重新操作" };
                }
                Gateway.Actions -= action;
                myDevice.Gateway.Actions -= action;
                System.Console.WriteLine("ClientDataPassthrough_Actions 退出" + System.DateTime.Now.ToString());
                return result;
@@ -1346,8 +1191,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -1355,24 +1199,16 @@
                        }
                        else
                        {
                            d = new PassthroughAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new PassthroughAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "ZbDataPassthrough")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(jobject["Data"].ToString());
                        if (gatewayTemp.getGwVersion == null)
                        {
                            d = new PassthroughAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new PassthroughAllData { passData = temp };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                        d = new PassthroughAllData { passData = temp };
                        DebugPrintLog($"UI收到通知后的主题_{ topic}");
                    }
                };
                Actions += action;
@@ -1425,8 +1261,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = this.getGatewayBaseInfo?.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -1435,13 +1270,12 @@
                        else
                        {
                            d = new LinuxUpgradeAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new LinuxUpgradeAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "ZbGwOperation/LinuxUpgrade_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                        d = new LinuxUpgradeAllData { Result = result };
                        DebugPrintLog($"UI收到通知后的主题_{ topic}");
@@ -1502,8 +1336,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -1512,22 +1345,21 @@
                        else
                        {
                            d = new ZbGwOperationUpgradeAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new ZbGwOperationUpgradeAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "ZbGwOperation/Upgrade_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                        gatewayTemp.zbGwOperationUpgradeData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ZbGwOperationUpgradeData>(jobject["Data"].ToString());
                        zbGwOperationUpgradeData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ZbGwOperationUpgradeData>(jobject["Data"].ToString());
                        if (gatewayTemp.zbGwOperationUpgradeData == null)
                        if (zbGwOperationUpgradeData == null)
                        {
                            d = new ZbGwOperationUpgradeAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new ZbGwOperationUpgradeAllData { bGwOperationUpgradeData = gatewayTemp.zbGwOperationUpgradeData };
                            d = new ZbGwOperationUpgradeAllData { bGwOperationUpgradeData = zbGwOperationUpgradeData };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
@@ -1573,11 +1405,11 @@
        /// <returns>The file async.</returns>
        /// <param name="distributedMark">Distributed mark:固件唯一标识</param>
        /// <param name="imageName">Image name:固件版本</param>
        public async System.Threading.Tasks.Task<DownloadFileResponAllData> DownloadFileAsync(string distributedMark, string imageName)
        public async System.Threading.Tasks.Task<CommonDevice.DownloadFileResponAllData> DownloadFileAsync(string distributedMark, string imageName)
        {
            return await System.Threading.Tasks.Task.Run(async () =>
            {
                DownloadFileResponAllData d = null; ;
                CommonDevice.DownloadFileResponAllData d = null; ;
                Action<string, string> action = (topic, message) =>
                {
                    var gatewayID = topic.Split('/')[0];
@@ -1585,32 +1417,30 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
                            d = new DownloadFileResponAllData { errorMessageBase = "网关错误回复,且数据是空" };
                            d = new CommonDevice.DownloadFileResponAllData { errorMessageBase = "网关错误回复,且数据是空" };
                        }
                        else
                        {
                            d = new DownloadFileResponAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new CommonDevice.DownloadFileResponAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "DownloadFile_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                        gatewayTemp.downloadFileResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<DownloadFileResponData>(jobject["Data"].ToString());
                        var downloadFileResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DownloadFileResponData>(jobject["Data"].ToString());
                        if (gatewayTemp.downloadFileResponData == null)
                        if (downloadFileResponData == null)
                        {
                            d = new DownloadFileResponAllData { errorMessageBase = "网关返回的数据为空" };
                            d = new CommonDevice.DownloadFileResponAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new DownloadFileResponAllData { downloadFileResponData = gatewayTemp.downloadFileResponData };
                            d = new CommonDevice.DownloadFileResponAllData { downloadFileResponData = downloadFileResponData };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
@@ -1641,7 +1471,7 @@
                }
                if ((DateTime.Now - dateTime).TotalMilliseconds > 30 * 1000)
                {
                    d = new DownloadFileResponAllData { errorMessageBase = " 回复超时,请重新操作" };
                    d = new CommonDevice.DownloadFileResponAllData { errorMessageBase = " 回复超时,请重新操作" };
                }
                Actions -= action;
@@ -1668,8 +1498,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -1678,22 +1507,21 @@
                        else
                        {
                            d = new CheckVDDriveCodeResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new CheckVDDriveCodeResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "VirtualDrive/CatDriveCode_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                        gatewayTemp.vDriveDriveCodeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<VDriveDriveCodeResponData>(jobject["Data"].ToString());
                        var vDriveDriveCodeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<VDriveDriveCodeResponData>(jobject["Data"].ToString());
                        if (gatewayTemp.vDriveDriveCodeResponData == null)
                        if (vDriveDriveCodeResponData == null)
                        {
                            d = new CheckVDDriveCodeResponseAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new CheckVDDriveCodeResponseAllData { vDriveDriveCodeResponData = gatewayTemp.vDriveDriveCodeResponData };
                            d = new CheckVDDriveCodeResponseAllData { vDriveDriveCodeResponData = vDriveDriveCodeResponData };
                            DebugPrintLog($"UI收到通知后的主题_{ topic}");
                        }
                    }
@@ -1748,8 +1576,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -1758,22 +1585,21 @@
                        else
                        {
                            d = new VirtualDriveUpgradeResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            d = new VirtualDriveUpgradeResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "VirtualDrive/Upgrade_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                        gatewayTemp.virtualDriveUpgradeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<VirtualDriveUpgradeResponData>(jobject["Data"].ToString());
                        virtualDriveUpgradeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<VirtualDriveUpgradeResponData>(jobject["Data"].ToString());
                        if (gatewayTemp.virtualDriveUpgradeResponData == null)
                        if (virtualDriveUpgradeResponData == null)
                        {
                            d = new VirtualDriveUpgradeResponseAllData { errorMessageBase = "网关返回的数据为空" };
                        }
                        else
                        {
                            d = new VirtualDriveUpgradeResponseAllData { virtualDriveUpgradeResponData = gatewayTemp.virtualDriveUpgradeResponData };
                            d = new VirtualDriveUpgradeResponseAllData { virtualDriveUpgradeResponData = virtualDriveUpgradeResponData };
                            DebugPrintLog($"UI收到通知后的主题_{topic}");
                        }
                    }
@@ -1811,115 +1637,6 @@
        #endregion
        //#region 上传私有数据
        //private bool backupSuccess = false;
        /// <summary>
        /// 上传私有数据
        /// </summary>
        /// <returns>The data to gateway.</returns>
        /// <param name="fileName">File name.</param>
        /// <param name="dev">Dev.</param>
        //public async System.Threading.Tasks.Task<SendFileResponseAllData> BackupDataToGateway(string fileName, CommonDevice dev)
        //{
        //    return await System.Threading.Tasks.Task.Run(async () =>
        //    {
        //        SendFileResponseAllData backUpStatus = null;
        //        var file = await System.Threading.Tasks.Task.Factory.StartNew(() => Newtonsoft.Json.JsonConvert.SerializeObject(dev));
        //        var data = System.Text.Encoding.UTF8.GetBytes(file);
        //        //网关中创建存储数据的文件
        //        var saveFileName = await dev.Gateway.CreateFileAsync(fileName);
        //        if (saveFileName != null && saveFileName.Result == 0)
        //        {
        //            backupSuccess = false;
        //            //上传数据到网关
        //            var saveData = await dev.Gateway.SendFileAsync(data);
        //            if (saveData != null)
        //            {
        //                backUpStatus = new SendFileResponseAllData { Result = saveData.Result };
        //            }
        //        }
        //        var dateTime = DateTime.Now;
        //        while ((DateTime.Now - dateTime).TotalMilliseconds < WaitReceiveDataTime)
        //        {
        //            await System.Threading.Tasks.Task.Delay(10);
        //            if (backUpStatus != null)
        //            {
        //                break;
        //            }
        //        }
        //        if ((DateTime.Now - dateTime).TotalMilliseconds > WaitReceiveDataTime)
        //        {
        //            backUpStatus = new SendFileResponseAllData { errorMessageBase = " 回复超时,请重新操作" };
        //         };
        //        return backUpStatus;
        //    });
        //}
        /// <summary>
        /// 下载私有数据
        /// </summary>
        /// <returns>The data from gateway.</returns>
        /// <param name="fileName">File name.</param>
        /// <param name="dev">Dev.</param>
        //public async System.Threading.Tasks.Task<System.Collections.Generic.List<byte>> DownloadDataFromGateway(string fileName, CommonDevice dev)
        //{
        //    return await System.Threading.Tasks.Task.Run(async () =>
        //    {
        //        byteSource.Clear();
        //        System.Collections.Generic.List<byte> backUpData = null;
        //        var dateTime = DateTime.Now;
        //        //获取当前文件的具体信息
        //        //var getFileSize = await currentKey.Gateway.GetCurrentFileInfoAsync(fileName);
        //        //下载文件
        //        var saveFileName = await dev.Gateway.SetDownloadFileAsync(fileName);
        //        Action<string, byte[]> action = (topic, dataContent) =>
        //        {
        //            if (topic.Split('/')[0] + "/" + topic.Split('/')[1] + "/" + topic.Split('/')[2] == topic.Split('/')[0] + "/" + "FileTransfer/DownloadFile")
        //            {
        //                dateTime = DateTime.Now;
        //                byte[] fileBytes = dataContent;
        //                if (fileBytes[5] != 1)
        //                {
        //                    if (fileBytes.Length == 2056)
        //                    {
        //                        var tempBytes = new byte[2048];
        //                        System.Array.Copy(fileBytes, 8, tempBytes, 0, 2048);
        //                        byteSource.AddRange(tempBytes);
        //                    }
        //                    else
        //                    {
        //                        var tempBytes = new byte[fileBytes.Length - 8];
        //                        System.Array.Copy(fileBytes, 8, tempBytes, 0, tempBytes.Length);
        //                        byteSource.AddRange(tempBytes);
        //                    }
        //                }
        //                else
        //                {
        //                    var tempBytes = new byte[fileBytes.Length - 8];
        //                    System.Array.Copy(fileBytes, 8, tempBytes, 0, tempBytes.Length);
        //                    byteSource.AddRange(tempBytes);
        //                    if (byteSource != null )
        //                    {
        //                        backUpData = byteSource;
        //                    }
        //                }
        //            }
        //        };
        //        dev.Gateway.FileContentAction += action;
        //        while ((DateTime.Now - dateTime).TotalMilliseconds < 2000)
        //        {
        //            await System.Threading.Tasks.Task.Delay(10);
        //        }
        //        dev.Gateway.FileContentAction -= action;
        //        return byteSource;
        //    });
        //}
        //#endregion
        #region 客户端上传文件到网关.
        /// <summary>
        /// 客户端上传文件到网关
@@ -1940,8 +1657,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -1949,13 +1665,12 @@
                        }
                        else
                        {
                            dataRes = new CreateFileResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            dataRes = new CreateFileResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "FileTransfer/CreateFile_Respon")
                    {
                        var security = new ZbGateway() { DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID };
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                        dataRes = new CreateFileResponseAllData { Result = result };
                        DebugPrintLog($"UI收到通知后的主题_{ topic}");
@@ -2019,7 +1734,6 @@
                    if (topic == gatewayID + "/FileTransfer/SendFile_Respon")
                    {
                        var gateway = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                        dataRes = new SendFileResponseAllData { Result = result };
                        if (result == 0)
@@ -2109,8 +1823,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -2118,13 +1831,12 @@
                        }
                        else
                        {
                            dataRes = new FileTransferLsDiResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            dataRes = new FileTransferLsDiResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "FileTransfer/lsDir_Respon")
                    {
                        var lsDir = new ZbGateway() { DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID };
                        var resultlsDir = Newtonsoft.Json.JsonConvert.DeserializeObject<FileTransferLsDiResponseData>(jobject["Data"].ToString());
                        if (resultlsDir != null)
                        {
@@ -2187,8 +1899,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -2196,13 +1907,12 @@
                        }
                        else
                        {
                            dataRes = new FileTransferGetFileInfoResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            dataRes = new FileTransferGetFileInfoResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "FileTransfer/GetFileInfo_Respon")
                    {
                        var lsDir = new ZbGateway() { DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID };
                        var resultlsDir = Newtonsoft.Json.JsonConvert.DeserializeObject<FileTransferGetFileInfoResponseData>(jobject["Data"].ToString());
                        if (resultlsDir != null)
                        {
@@ -2267,8 +1977,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -2276,13 +1985,12 @@
                        }
                        else
                        {
                            dataRes = new SetDownloadFileResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            dataRes = new SetDownloadFileResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "FileTransfer/SetDownloadFile_Respon")
                    {
                        var lsDir = new ZbGateway() { DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = CurrentGateWayId };
                        var tempData = Newtonsoft.Json.JsonConvert.DeserializeObject<SetDownloadFileResponseData>(jobject["Data"].ToString());
                        if (tempData != null)
                        {
@@ -2290,7 +1998,7 @@
                            var tempDa = new SetDownloadFileResponseData();
                            if (tempData.Result == 0)
                            {
                                ZbGateway.byteSource.Clear();
                                this.byteSource.Clear();
                            }
                            tempDa.Result = tempData.Result;
                            dataRes.setDownloadFileResponseData = tempDa;
@@ -2338,7 +2046,7 @@
        #endregion
        #region 网关发送文件流到客户端
        static System.Collections.Generic.List<byte> byteSource = new System.Collections.Generic.List<byte>();
        private List<byte> byteSource = new List<byte>();
        ///<summary >
        /// 下载文件中的数据
        /// </summary>
@@ -2401,8 +2109,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -2410,13 +2117,12 @@
                        }
                        else
                        {
                            dataRes = new DelFileOrDirResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            dataRes = new DelFileOrDirResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "FileTransfer/DelFileOrDir_Respon")
                    {
                        var lsDir = new ZbGateway() { DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = CurrentGateWayId };
                        var resultDelFileOrDir = Newtonsoft.Json.JsonConvert.DeserializeObject<DelFileOrDirResponseData>(jobject["Data"].ToString());
                        if (resultDelFileOrDir != null)
                        {
@@ -2480,8 +2186,7 @@
                    if (topic == gatewayID + "/" + "Error_Respon")
                    {
                        var gatewayTemp = new ZbGateway() { Time = jobject.Value<int>("Time"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = getGatewayBaseInfo.gwID };
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<ErrorResponData>(jobject["Data"].ToString());
                        var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                        if (temp == null)
                        {
@@ -2489,13 +2194,12 @@
                        }
                        else
                        {
                            dataRes = new CreateDirResponseAllData { errorResponData = temp, errorMessageBase = ErrorMess(temp.Error) };
                            dataRes = new CreateDirResponseAllData { errorResponData = temp, errorMessageBase = CommonDevice.ErrorMess(temp.Error) };
                        }
                    }
                    if (topic == gatewayID + "/" + "FileTransfer/CreateDir_Respon")
                    {
                        var lsDir = new ZbGateway() { DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = CurrentGateWayId };
                        var resultCreateDir = Newtonsoft.Json.JsonConvert.DeserializeObject<CreateDirResponseData>(jobject["Data"].ToString());
                        if (resultCreateDir != null)
                        {
@@ -2556,7 +2260,6 @@
                    if (topic == gatewayID + "/" + "SendAESKey_Respon")
                    {
                        var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                        var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                        sendKeyResponData = new SendKeyResponData { Result = result };
                        DebugPrintLog($"UI收到通知后的主题_{ topic}");
@@ -2601,7 +2304,7 @@
        /// <para>进入当前界面时要添加</para>
        /// <para>退出当前界面时要关闭</para>
        /// </summary>
        public static readonly System.Collections.Generic.List<IStatus> StatusList = new System.Collections.Generic.List<IStatus>();
        public static readonly List<IStatus> StatusList = new List<IStatus>();
        /// <summary>
        /// 设备信息变化
@@ -2624,48 +2327,54 @@
            }
        }
        #endregion
        #region 通讯连接
        #region 本地通讯连接
        /// <summary>
        /// 本地连接是否连接成功
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public bool LocalIsConnected;
        /// <summary>
        /// 局域网的MQTT
        /// </summary>
        IMqttClient localMqttClient = new MqttFactory().CreateMqttClient();
        bool localMqttIsConnecting;
        public bool localIsConnected;
        /// <summary>
        /// 手机标识
        private IMqttClient localMqttClient = new MqttFactory().CreateMqttClient();
        /// <summary>
        /// 本地mqtt是否正在连接中
        /// </summary>
        static Guid currentGuid = Guid.NewGuid();
        private bool localMqttIsConnecting;
        /// <summary>
        /// 本地连接的一个客户端ID(app启动之后就不变了)
        /// </summary>
        private static Guid LocalConnectGuid = Guid.NewGuid();
        public async System.Threading.Tasks.Task SendAesKey()
        {
            if (PubKey != null)
            {
                IsEncry = false;
                var rsaString = ZigBee.Common.SecuritySet.RSAEncrypt(PubKey, Password);
                var resultVerityfy = await SendAesKeyAsync(rsaString);
                if (resultVerityfy == null)
                {
                    resultVerityfy = await SendAesKeyAsync(rsaString);
                }
                if (resultVerityfy != null && resultVerityfy.Result == 0)
                {
                    IsEncry = true;
                }
        public async Task SendAesKey()
        {
            if (PubKey != null)
            {
                IsEncry = false;
                var rsaString = ZigBee.Common.SecuritySet.RSAEncrypt(PubKey, Password);
                var resultVerityfy = await SendAesKeyAsync(rsaString);
                if (resultVerityfy == null)
                {
                    resultVerityfy = await SendAesKeyAsync(rsaString);
                }
                if (resultVerityfy != null && resultVerityfy.Result == 0)
                {
                    IsEncry = true;
                }
            }
        }
        public async System.Threading.Tasks.Task StartLocalMqtt(string brokerName)
        {
            if (localMqttIsConnecting
                       || !Shared.Common.Config.Instance.IsLogin
                       || Shared.Common.Config.Instance.HomeId == ""
                       || localIsConnected)
            {
                return;
        public async Task StartLocalMqtt(string brokerName)
        {
            if (localMqttIsConnecting
                || Shared.Common.Config.Instance.HomeId == ""
                || LocalIsConnected)
            {
                return;
            }
            await System.Threading.Tasks.Task.Factory.StartNew(async () =>
            await Task.Factory.StartNew(async () =>
            {
                try
                {
@@ -2690,7 +2399,7 @@
                        if (localMqttClient.DisconnectedHandler == null)
                        {
                            localMqttClient.UseDisconnectedHandler(async (e) =>
                            {
                            {
                                DebugPrintLog($" 本地连接断开_网关IP:{brokerName}_网关是否加:{IsEncry}");
                                await DisConnectLocalMqttClient("StartLocalMqtt.DisconnectedHandler");
                                //await StartLocalMqtt("ReConnect");
@@ -2698,51 +2407,60 @@
                        }
                        if (localMqttClient.ConnectedHandler == null)
                        {
                            localMqttClient.UseConnectedHandler(async (e) =>
                            {
                                DebugPrintLog($" 本地连接成功_网关IP:{brokerName}_网关是否加:{IsEncry}_当前密码:{Password}");
                                IsRemote = false;
                                Shared.Phone.UserCenter.HdlGatewayLogic.Current.CheckGatewayByConnectChanged(Shared.Phone.UserCenter.GatewayConnectMode.WIFI);
                            localMqttClient.UseConnectedHandler(async (e) =>
                            {
                                DebugPrintLog($" 本地连接成功_网关IP:{brokerName}_网关是否加:{IsEncry}_当前密码:{Password}");
                                IsRemote = false;
                                //Log写入(调试用)
                                if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                                {
                                    Shared.Phone.HdlLogLogic.Current.WriteLog(2, "本地连接成功");
                                }
                            });
                        }
                        var dateTime = DateTime.Now;
                        new System.Threading.Thread(async () =>
                        {
                            try
                            {
                                if (localMqttClient.Options == null)
                                {
                                    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
                                {
                                    await DisConnectLocalMqttClient("StartLocalMqtt");
                                    await localMqttClient.ReconnectAsync();
                                }
                                localIsConnected = true;
                                await SendAesKey();
                            }
                            catch { }
                            dateTime = DateTime.MinValue;
                        })
                        { IsBackground = true }.Start();
                        while (dateTime != DateTime.MinValue)
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                    }
                        }
                        var dateTime = DateTime.Now;
                        new System.Threading.Thread(async () =>
                        {
                            try
                            {
                                if (localMqttClient.Options == null)
                                {
                                    var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()//MQTT连接参数填充
                                    .WithClientId(LocalConnectGuid.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
                                {
                                    await DisConnectLocalMqttClient("StartLocalMqtt");
                                    await localMqttClient.ReconnectAsync();
                                }
                                LocalIsConnected = true;
                                await SendAesKey();
                            }
                            catch { }
                            dateTime = DateTime.MinValue;
                        })
                        { IsBackground = true }.Start();
                        while (dateTime != DateTime.MinValue)
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                    }
                }
                catch (Exception ex)
                {
                    //Log写入(调试用)
                    if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                    {
                        Shared.Phone.HdlLogLogic.Current.WriteLog(2, "本地连接异常:\r\n" + ex.Message);
                    }
                    DebugPrintLog($"局域网通讯连接出异常:{ex.Message}");
                }
                finally
@@ -2752,343 +2470,22 @@
            });
        }
        class GateWayBaseInfomation
        {
            //public string GatewayUniqueId;//"Emq网关1",   <!-- 网关Mac -->
            public bool MqttOnlineStatus;//: true,  <!-- 网关在云端Emq是否在线 -->
            public string AesKey;// : "a5d8da8a-ddea-48",  <!-- 与此网关在云端Emq通信时,负载加解的16位Aes密钥 -->
            public string MacMark;//: "61eaa0ea-4812-4a7a-86d6-3098c61e64ed"   <!-- 网关对应的唯一码 -->
        }
        /// <summary>
        /// 当前有帐号下所有的网关列表及信息
        /// </summary>
        static Dictionary<string, GateWayBaseInfomation> GateWayBaseInfomations = new Dictionary<string, GateWayBaseInfomation> { };
        /// <summary>
        /// 获取当前帐号所有的网关信息
        /// </summary>
        /// <returns></returns>
        static async System.Threading.Tasks.Task initGateWayBaseInfomation()
        {
            if (AllowRemoteCtrl == false)
            {
                //没有远程连接的权限
                return;
            }
            string loginToken = Config.Instance.Token;
            if (Config.Instance.Home.IsOthreShare == true)
            {
                //获取成员的特殊Token
                var pra = new
                {
                    CommonPage.RequestVersion,
                    LoginAccessToken = Config.Instance.Token,
                    MainAccountId = Config.Instance.Home.MainUserDistributedMark,
                    SharedHid = Config.Instance.Home.Id
                };
                var listNotShow = new List<string>() { "NotSetAgain" };
                var resultData = await Shared.Phone.UserCenter.UserCenterLogic.GetByteResponseDataByRequestHttps("App/GetSharedHomeApiControl", false, pra, listNotShow);
                if (resultData == null)
                {
                    return;
                }
                var revertObj = Newtonsoft.Json.JsonConvert.DeserializeObject<Shared.Common.ResponseEntity.ResponsePack>(Encoding.UTF8.GetString(resultData));
                //分享链接
                var info = Newtonsoft.Json.JsonConvert.DeserializeObject<Shared.Phone.UserCenter.MemberAdministratorResult>(revertObj.ResponseData.ToString());
                loginToken = info.RequestToken;
            }
            try
            {
                //设置访问接口的参数
                var pra2 = new Shared.Phone.UserCenter.GetGatewayPra();
                pra2.IsOtherAccountCtrl = Config.Instance.Home.IsOthreShare;
                pra2.ReqDto.PageSetting.Page = 1;
                pra2.ReqDto.PageSetting.PageSize = 20;
                pra2.ReqDto.LoginAccessToken = loginToken;
                var bytes = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(pra2));
                var result = await CommonPage.Instance.DoRequestZigbeeHttpsInterface("https://global.hdlcontrol.com/HangZhouHdlCloudApi/App/GetSingleHomeGatewayPagger", bytes, loginToken);
                if (result != null)
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(Encoding.UTF8.GetString(result));
                    var statuCode = jobject["StateCode"].ToString();
                    if (statuCode != "Success")
                    {
                        //序列化对象
                        var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject(pra2);
                        //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"];
                    if (responseData != null)
                    {
                        if (responseData["PageData"] != null)
                        {
                            var list = JArray.Parse(responseData["PageData"].ToString());
                            foreach (var v in list)
                            {
                                GateWayBaseInfomations[v["GatewayUniqueId"].ToString()] = new GateWayBaseInfomation { AesKey = v["AesKey"].ToString(), MacMark = v["MacMark"].ToString(), MqttOnlineStatus = bool.Parse(v["MqttOnlineStatus"].ToString()) };
                                //if (RemoteMqttClient.IsConnected)
                                {
                                    await RemoteMqttClient.SubscribeAsync($"/ZigbeeGateWayToClient/{v["MacMark"].ToString()}/#", MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Shared.Phone.UserCenter.HdlLogLogic.Current.WriteLog(ex);
            }
        }
        /// <summary>
        /// 外网的MQTT是否正在连接
        /// </summary>
        static bool remoteMqttIsConnecting;
        static bool IsLoginAgain;
        /// <summary>
        /// 远程MqttClient
        /// </summary>
        public static IMqttClient RemoteMqttClient= new MqttFactory().CreateMqttClient();
        static bool remoteIsConnected;
        private int IsLogin = 0;
        [Newtonsoft.Json.JsonIgnore]
        static Action actionTemp;
        /// <summary>
        /// 启动远程Mqtt
        /// </summary>
        /// <returns>The start.</returns>
        /// <param name="brokerName">Broker name.</param>
        public static async System.Threading.Tasks.Task StartRemoteMqtt()
        {
            //追加:没有远程连接的权限
            if (AllowRemoteCtrl == false
               || remoteMqttIsConnecting
               || !Shared.Common.Config.Instance.IsLogin
               || Shared.Common.Config.Instance.HomeId == ""
               || remoteIsConnected)
            {
                return;
            }
            await System.Threading.Tasks.Task.Factory.StartNew(async () =>
            {
                try
                {
                    lock (RemoteMqttClient)
                    {
                        //表示后面将进行连接
                        remoteMqttIsConnecting = true;
                        #region 初始化远程Mqtt
                        //(3)当[连接云端的Mqtt成功后]或者[以及后面App通过云端Mqtt转发数据给网关成功后],处理接收到云端数据包响应时在mqttServerClient_ApplicationMessageReceived这个方法处理
                        if (RemoteMqttClient.ApplicationMessageReceivedHandler == null)
                        {
                            RemoteMqttClient.UseApplicationMessageReceivedHandler((e) =>
                            {
                                //这里是特殊的主题
                                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);
                            });
                        }
                        if (RemoteMqttClient.DisconnectedHandler == null)
                        {
                            RemoteMqttClient.UseDisconnectedHandler(async (e) =>
                            {
                                DebugPrintLog($"远程连接断开");
                                await DisConnectRemoteMqttClient("StartRemoteMqtt.DisconnectedHandler");
                                //await StartRemoteMqtt();
                            });
                        }
                        if (RemoteMqttClient.ConnectedHandler == null)
                        {
                            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);
                                //没有主网关时主动读取,获取主网关信息
                                var gateWayList = GateWayList.FindAll(obj => obj.getGatewayBaseInfo.HomeId == Shared.Common.Config.Instance.HomeId);
                                if (gateWayList.Find(obj => obj.getGatewayBaseInfo.IsMainGateWay == true) == null)
                                {
                                    if (gateWayList.Count == 1)
                                    {
                                        gateWayList[0].getGatewayBaseInfo.IsMainGateWay = true;
                                    }
                                    else
                                    {
                                        for (int i = 0; i < gateWayList.Count; i++)
                                        {
                                            var gateWay = gateWayList[i];
                                            var info = await gateWay.GetZbGwInfoAsync();
                                            if (info == null || info.getGwData == null)
                                            {
                                                continue;
                                            }
                                            if (info.getGwData.IsDominant == 1)
                                            {
                                                for (int j = 0; j < gateWayList.Count; j++)
                                                {
                                                    if (gateWayList[i].getGatewayBaseInfo.gwID == info.getGwData.GwId)
                                                    {
                                                        gateWayList[i].getGatewayBaseInfo.IsMainGateWay = true;
                                                    }
                                                    else
                                                    {
                                                        gateWayList[i].getGatewayBaseInfo.IsMainGateWay = false;
                                                    }
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                            });
                        }
                        #endregion
                    }
                    try
                    {
                        byte[] result = null;
                        if (Config.Instance.Home.IsOthreShare == false)
                        {
                            //主人
                            var jsonData = new Dictionary<string, object>
                            {
                                ["RequestVersion"] = CommonPage.RequestVersion,
                                ["RequestSource"] = 0,
                                ["LoginAccessToken"] = Config.Instance.Token,
                                ["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);
                        }
                        else
                        {
                            //分享的
                            var jsonData = new Dictionary<string, object>
                            {
                                ["RequestVersion"] = CommonPage.RequestVersion,
                                ["RequestSource"] = 0,
                                ["LoginAccessToken"] = Config.Instance.Token,
                                ["RequestProtocolType"] = 0,
                                ["MainUserDistributedMark"] = Config.Instance.Home.MainUserDistributedMark,
                                ["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);
                        }
                        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)
                            {
                                var connEmqDomainPort = responseData["ConnEmqDomainPort"]?.ToString();
                                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];
                                var port = connEmqDomainPorts[2];
                                var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()
                               .WithClientId(connEmqClientId)
           .WithTcpServer(domain, int.Parse(port))
           .WithCredentials(connEmqUserName, connEmqPwd)
           .WithKeepAlivePeriod(TimeSpan.FromSeconds(20))
           .WithCleanSession()
           //.WithCommunicationTimeout(TimeSpan.FromSeconds(10))
           .Build();
                                await DisConnectRemoteMqttClient("StartRemoteMqtt");
                                await RemoteMqttClient.ConnectAsync(options, CancellationToken.None);
                                remoteIsConnected = true;
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        //最终要释放连接状态
                        remoteMqttIsConnecting = false;
                    }
                }
                catch (Exception ex)
                {
                    DebugPrintLog($"远程连接通讯连接出异常:{ex.Message}");
                }
            });
        }
        /// <summary>
        /// 断开服务器连接
        /// </summary>
        public async System.Threading.Tasks.Task DisConnectLocalMqttClient(string s)
        public async Task DisConnectLocalMqttClient(string s)
        {
            try
            {
                if (localIsConnected)
                {
                    localIsConnected = false;
                    DebugPrintLog($"Local主动断开_{s}");
                    //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions {  }, CancellationToken.None);
                    await localMqttClient.DisconnectAsync();
                }
                if (LocalIsConnected)
                {
                    LocalIsConnected = false;
                    //这个东西也要弄
                    localMqttIsConnecting = false;
                    DebugPrintLog($"Local主动断开_{s}");
                    //await localMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions {  }, CancellationToken.None);
                    await localMqttClient.DisconnectAsync();
                }
            }
            catch (Exception ex)
            {
@@ -3096,28 +2493,306 @@
            }
        }
        /// <summary>
        /// 断开远程Mqtt的链接
        /// <summary>
        /// 强制断开本地的网关连接
        /// </summary>
        public static async System.Threading.Tasks.Task DisConnectRemoteMqttClient(string s="")
        {
        public async Task CloseLocalConnectionOnForce()
        {
            try
            {
                await localMqttClient.DisconnectAsync();
            }
            catch { }
            finally
            {
                LocalIsConnected = false;
                //这个东西也要弄
                localMqttIsConnecting = false;
            }
        }
        #endregion
        #region 远程通讯连接
        /// <summary>
        /// 当前有帐号下所有的云端网关列表及信息
        /// </summary>
        public static Dictionary<string, Shared.Phone.GatewayResult> DicGatewayBaseInfo = new Dictionary<string, Shared.Phone.GatewayResult> { };
        /// <summary>
        /// 外网的MQTT是否正在连接
        /// </summary>
        private static bool remoteMqttIsConnecting;
        /// <summary>
        /// 远程MqttClient
        /// </summary>
        public static IMqttClient RemoteMqttClient = new MqttFactory().CreateMqttClient();
        /// <summary>
        /// 远程连接是否完成
        /// </summary>
        private static bool remoteIsConnected;
        /// <summary>
        /// 远程开始连接的时间点
        /// </summary>
        private static DateTime RemoteConnectTime = DateTime.Now;
        /// <summary>
        /// 启动远程Mqtt
        /// </summary>
        public static async Task StartRemoteMqtt()
        {
            //追加:没有远程连接的权限
            if (Config.Instance.Home.IsRemoteControl == false
               || Config.Instance.Home.Id == ""
               || remoteIsConnected)
            {
                return;
            }
            //如果远程还在连接中
            if (remoteMqttIsConnecting == true)
            {
                //如果这个变量一直处于连接中的状态,但是已经过去了10秒了,还是true的话,说明这里是有点问题的,需要重新创建
                if ((DateTime.Now - RemoteConnectTime).TotalMilliseconds < 10 * 1000)
                {
                    return;
                }
            }
            //记录起这次远程连接的时间点
            RemoteConnectTime = DateTime.Now;
            //初始化远程mqtt事件
            InitRemoteMqttEvent();
            try
            {
                if (remoteIsConnected)
                //获取远程mqtt链接信息
                var pra = new { attachClientId = RemoteClientId, homeType = "ZIGBEE" };
                var result = Shared.Phone.HdlHttpLogic.Current.RequestResponseFromZigbeeHttps("home-wisdom/app/mqtt/getRemoteInfo", RestSharp.Method.POST, pra);
                if (result != null && result.Code == Shared.Phone.HttpMessageEnum.A成功)
                {
                    remoteIsConnected = false;
                    DebugPrintLog($"Remote主动断开_{s}");
                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
                    await RemoteMqttClient.DisconnectAsync();
                    var jobject = JObject.Parse(result.Data.ToString());
                    var connEmqClientId = jobject["clientId"]?.ToString();
                    var connEmqUserName = jobject["userName"]?.ToString();
                    var connEmqPwd = jobject["passWord"]?.ToString();
                    //记录起当前的客户端ID
                    Config.Instance.ConnEmqClientId = connEmqClientId;
                    var connEmqDomainPorts = jobject["url"].ToString().Replace("//", "").Split(':');
                    var domain = connEmqDomainPorts[1];
                    var port = connEmqDomainPorts[2];
                    var options = new MQTTnet.Client.Options.MqttClientOptionsBuilder()
                      .WithClientId(connEmqClientId)
                      .WithTcpServer(domain, int.Parse(port))
                      .WithCredentials(connEmqUserName, connEmqPwd)
                      .WithKeepAlivePeriod(TimeSpan.FromSeconds(20))
                      .WithCleanSession()
                      .Build();
                    await DisConnectRemoteMqttClient("StartRemoteMqtt");
                    await RemoteMqttClient.ConnectAsync(options, CancellationToken.None);
                    remoteIsConnected = true;
                }
            }
            catch(Exception e) {
                DebugPrintLog($"Remote断开通讯连接出异常:{e.Message}");
            catch { }
            finally
            {
                //最终要释放连接状态
                remoteMqttIsConnecting = false;
            }
        }
        /// <summary>
        /// 初始化远程mqtt事件
        /// </summary>
        private static void InitRemoteMqttEvent()
        {
            lock (RemoteMqttClient)
            {
                //表示后面将进行连接
                remoteMqttIsConnecting = true;
                //(3)当[连接云端的Mqtt成功后]或者[以及后面App通过云端Mqtt转发数据给网关成功后],处理接收到云端数据包响应时在mqttServerClient_ApplicationMessageReceived这个方法处理
                if (RemoteMqttClient.ApplicationMessageReceivedHandler == null)
                {
                    RemoteMqttClient.UseApplicationMessageReceivedHandler((e) =>
                    {
                        //这里是特殊的主题
                        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);
                    });
                }
                if (RemoteMqttClient.DisconnectedHandler == null)
                {
                    RemoteMqttClient.UseDisconnectedHandler(async (e) =>
                    {
                        DebugPrintLog($"远程连接断开");
                        await DisConnectRemoteMqttClient("StartRemoteMqtt.DisconnectedHandler");
                    });
                }
                if (RemoteMqttClient.ConnectedHandler == null)
                {
                    RemoteMqttClient.UseConnectedHandler(async (e) =>
                    {
                        DebugPrintLog($"远程连接成功");
                        if (Config.Instance.Home.IsOtherShare == 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");
                        //如果这个函数卡久了的话,会接收到云端推送的挤下线主题,不知道为什么
                        new System.Threading.Thread(async () =>
                        {
                            await InitGateWayBaseInfomation();
                            //没有主网关时主动读取,获取主网关信息
                            var gateWayList = GateWayList.FindAll(obj => obj.HomeId == Shared.Common.Config.Instance.HomeId);
                            if (gateWayList.Find(obj => obj.IsMainGateWay == true) == null)
                            {
                                if (gateWayList.Count == 1)
                                {
                                    gateWayList[0].IsMainGateWay = true;
                                }
                                else
                                {
                                    for (int i = 0; i < gateWayList.Count; i++)
                                    {
                                        var gateWay = gateWayList[i];
                                        var info = await gateWay.GetZbGwInfoAsync();
                                        if (info == null || info.getGwData == null)
                                        {
                                            continue;
                                        }
                                        if (info.getGwData.IsDominant == 1)
                                        {
                                            for (int j = 0; j < gateWayList.Count; j++)
                                            {
                                                if (gateWayList[i].GwId == info.getGwData.GwId)
                                                {
                                                    gateWayList[i].IsMainGateWay = true;
                                                }
                                                else
                                                {
                                                    gateWayList[i].IsMainGateWay = false;
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                        })
                        { IsBackground = true }.Start();
                    });
                }
            }
        }
        /// <summary>
        /// 初始化当前帐号所有的云端网关信息
        /// </summary>
        /// <returns></returns>
        private static async Task InitGateWayBaseInfomation()
        {
            if (Config.Instance.Home.IsRemoteControl == false)
            {
                //没有远程连接的权限
                return;
            }
            //获取云端网关信息
            var listGatewayInfo = Shared.Phone.HdlGatewayLogic.Current.GetGateWayListFromDataBase(Config.Instance.Home.Id);
            if (listGatewayInfo == null) { return; }
            foreach (var info in listGatewayInfo.Values)
            {
                try
                {
                    //有可能云端是这么处理:如果没有远程权限,则不给AesKey
                    if (string.IsNullOrEmpty(info.AesKey) == true) { continue; }
                    //保存缓存
                    DicGatewayBaseInfo[info.Mac] = info;
                    //我也不知道这个是干嘛的
                    await RemoteMqttClient.SubscribeAsync($"/ZigbeeGateWayToClient/" + info.Id + "/#", MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
                }
                catch (Exception ex)
                {
                    Shared.Phone.HdlLogLogic.Current.WriteLog(ex);
                }
            }
        }
        /// <summary>
        /// 断开远程Mqtt的链接
        /// </summary>
        public static async Task DisConnectRemoteMqttClient(string s = "")
        {
            try
            {
                if (remoteIsConnected)
                {
                    remoteIsConnected = false;
                    //这个东西也要弄
                    remoteMqttIsConnecting = false;
                    DebugPrintLog($"Remote主动断开_{s}");
                    //await RemoteMqttClient.DisconnectAsync(new MQTTnet.Client.Disconnecting.MqttClientDisconnectOptions { }, CancellationToken.None);
                    await RemoteMqttClient.DisconnectAsync();
                }
            }
            catch (Exception e)
            {
                DebugPrintLog($"Remote断开通讯连接出异常:{e.Message}");
            }
        }
        /// <summary>
        /// 强制断开远程Mqtt的链接
        /// </summary>
        /// <returns></returns>
        public static async Task CloseRemoteConnectionOnForce()
        {
            try
            {
                await RemoteMqttClient?.DisconnectAsync();
            }
            catch { }
            finally
            {
                remoteIsConnected = false;
                //这个东西也要弄
                remoteMqttIsConnecting = false;
            }
        }
        #endregion
        #region 数据发送
        /// <summary>
        /// 发送消息到服务器
        /// </summary>
@@ -3146,35 +2821,35 @@
        /// </summary>
        async System.Threading.Tasks.Task SendRemoteMsg(string topicName, byte[] message, bool retain = false)
        {
            try
            {
                if (this.getGatewayBaseInfo?.gwID == null || !GateWayBaseInfomations.ContainsKey(this.getGatewayBaseInfo?.gwID))
                {
                    return;
                }
                var gateWayBaseInfomation = GateWayBaseInfomations[this.getGatewayBaseInfo?.gwID];
                message = SecuritySet.AesEncryptBytes(message, gateWayBaseInfomation.AesKey);
                var topicEncStr = $"/ClientToZigbeeGateWay/{gateWayBaseInfomation.MacMark}/Common/{topicName}";
                //(6)构建Mqtt需要发布的数据包,发布给云端的MqttBroker
                if (remoteIsConnected)
                {
                    try
                    {
                        await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce });
                    }
                    catch (Exception e)
                    {
                        await DisConnectRemoteMqttClient(e.Message);
                        await StartRemoteMqtt();
                        if (remoteIsConnected)
                        {
                            await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce });
                        }
                    }
            try
            {
                if (this.GwId == string.Empty || !DicGatewayBaseInfo.ContainsKey(this.GwId))
                {
                    return;
                }
            }
            catch
            {
                var gateWayBaseInfomation = DicGatewayBaseInfo[this.GwId];
                message = SecuritySet.AesEncryptBytes(message, gateWayBaseInfomation.AesKey);
                var topicEncStr = $"/ClientToZigbeeGateWay/{gateWayBaseInfomation.Id}/Common/{topicName}";
                //(6)构建Mqtt需要发布的数据包,发布给云端的MqttBroker
                if (remoteIsConnected)
                {
                    try
                    {
                        await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce });
                    }
                    catch (Exception e)
                    {
                        await DisConnectRemoteMqttClient(e.Message);
                        await StartRemoteMqtt();
                        if (remoteIsConnected)
                        {
                            await RemoteMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topicEncStr, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce });
                        }
                    }
                }
            }
            catch
            {
            }
        }
@@ -3194,15 +2869,25 @@
                    return;
                }
                //Log写入(调试用)
                if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                {
                    string text = "远程发送:";
                    if (IsRemote == false) { text = "本地发送:"; }
                    text += topic + "\r\n";
                    text += Encoding.UTF8.GetString(message) + "\r\n";
                    Shared.Phone.HdlLogLogic.Current.WriteLog(2, text);
                }
                if (IsRemote)
                {
                    await SendRemoteMsg(topic, message, retain);
                    DebugPrintLog($"远程——发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_当前网关{CurrentGateWayId}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")
                    DebugPrintLog($"远程——发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}");//{System.DateTime.Now.ToString()}");// DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")
                }
                else
                {
                    DebugPrintLog($"局域网——发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_当前网关{CurrentGateWayId} 是否加密:{IsEncry}");
                    DebugPrintLog($"局域网——发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_是否加密:{IsEncry}");
                    if (IsEncry)
                    {
                        //文件流不用加密
@@ -3210,25 +2895,30 @@
                        {
                            message = SecuritySet.AesEncryptBytes(message, password);
                        }
                    }
                    if (localIsConnected)
                    {
                        try
                        {
                            await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                        }
                        catch(Exception e)
                    }
                    if (LocalIsConnected)
                    {
                        try
                        {
                            DebugPrintLog($"Local主动断开_{e.Message}");
                            await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                        }
                        catch (Exception e)
                        {
                            DebugPrintLog($"Local主动断开_{e.Message}");
                            await DisConnectLocalMqttClient(e.Message);
                            await StartLocalMqtt("ReConnect");
                            if (localIsConnected)
                            {
                                DebugPrintLog($"局域网——二次发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_当前网关{CurrentGateWayId} 是否加密:{IsEncry}");
                                await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                            await StartLocalMqtt("ReConnect");
                            if (LocalIsConnected)
                            {
                                DebugPrintLog($"局域网——二次发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_是否加密:{IsEncry}");
                                await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                            }
                        }
                    }
                            //Log写入(调试用)
                            if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                            {
                                Shared.Phone.HdlLogLogic.Current.WriteLog(2, "本地连接异常断开");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
@@ -3247,12 +2937,12 @@
        public async System.Threading.Tasks.Task Send(string topic, string message, bool retain = false)
        {
            if (string.IsNullOrEmpty(message))
            {
            {
                return;
            }
            await Send(topic, System.Text.Encoding.UTF8.GetBytes(message), retain);
        }
        }
        /// <summary>
        /// 强制指定使用本地局域网发送消息到服务器
        /// </summary>
@@ -3267,35 +2957,35 @@
                if (Shared.Common.Config.Instance.HomeId == "")
                {
                    return;
                }
                DebugPrintLog($"局域网——发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_当前网关{CurrentGateWayId} 是否加密:{IsEncry}");
                if (IsEncry)
                {
                    //文件流不用加密
                    if (topic != "FileTransfer/SendFile")
                    {
                        message = SecuritySet.AesEncryptBytes(message, password);
                    }
                }
                if (localIsConnected)
                {
                    try
                    {
                        await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                    }
                    catch (Exception e)
                    {
                        DebugPrintLog($"Local主动断开_{e.Message}");
                        await DisConnectLocalMqttClient(e.Message);
                        await StartLocalMqtt("ReConnect");
                        if (localIsConnected)
                        {
                            DebugPrintLog($"局域网——二次发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_当前网关{CurrentGateWayId} 是否加密:{IsEncry}");
                            await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                        }
                    }
                }
                DebugPrintLog($"局域网——发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_是否加密:{IsEncry}");
                if (IsEncry)
                {
                    //文件流不用加密
                    if (topic != "FileTransfer/SendFile")
                    {
                        message = SecuritySet.AesEncryptBytes(message, password);
                    }
                }
                if (LocalIsConnected)
                {
                    try
                    {
                        await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                    }
                    catch (Exception e)
                    {
                        DebugPrintLog($"Local主动断开_{e.Message}");
                        await DisConnectLocalMqttClient(e.Message);
                        await StartLocalMqtt("ReConnect");
                        if (LocalIsConnected)
                        {
                            DebugPrintLog($"局域网——二次发送到网关的主题:{topic}_发送到网关的数据:{System.Text.Encoding.UTF8.GetString(message)}_是否加密:{IsEncry}");
                            await localMqttClient.PublishAsync(new MqttApplicationMessage { Topic = topic, Payload = message, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce, Retain = retain });
                        }
                    }
                }
            }
            catch (Exception ex)
@@ -3304,13 +2994,9 @@
            }
        }
        [Serializable]
        public class CloudTimeResponse
        {
            public string StateCode;
            public string Info;
            public string CloudTimestamp;
        }
        #endregion
        #region 数据接收处理
        /// <summary>
        /// 接收远程数据处理
@@ -3336,8 +3022,9 @@
                {
                    return;
                }
                if (topics[2]== "NotifyGateWayInfoChange") {
                    initGateWayBaseInfomation();
                if (topics[2] == "NotifyGateWayInfoChange")
                {
                    InitGateWayBaseInfomation();
                    return;
                }
                if (topics[2] == "Common")
@@ -3350,10 +3037,10 @@
                    }
                    else
                    {
                        foreach (var key in GateWayBaseInfomations.Keys)
                        foreach (var key in DicGatewayBaseInfo.Keys)
                        {
                            var value = GateWayBaseInfomations[key];
                            if (value.MacMark == macMark)
                            var value = DicGatewayBaseInfo[key];
                            if (value.Id == macMark)
                            {
                                topic = $"{key}/{topic}";
                                message = System.Text.Encoding.UTF8.GetString(ZigBee.Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, value.AesKey));
@@ -3403,9 +3090,9 @@
                        payloadString = System.Text.Encoding.UTF8.GetString(Common.SecuritySet.AesDecryptBytes(e.ApplicationMessage.Payload, Password));
                    }
                }
                else
                {
                    payloadString = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                else
                {
                    payloadString = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                }
                DebugPrintLog($"网关返回的主题:{topic}_网关返回的负载:{payloadString}");
                ReceiveMessage(topic, payloadString, e.ApplicationMessage.Payload);
@@ -3422,7 +3109,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
            {
@@ -3443,12 +3130,20 @@
                    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);
                //Log写入(调试用)
                if (Shared.Phone.HdlUserCenterResourse.HideOption.WriteSendAndReceveDataToFile == 1)
                {
                    string text = "网关回复:" + topic + "\r\n";
                    text += message + "\r\n";
                    Shared.Phone.HdlLogLogic.Current.WriteLog(2, text);
                }
                //全局接收网关推送的的逻辑(为了执行速度,尽可能的别加耗时的操作)
                Shared.Phone.HdlGatewayReceiveLogic.Current.GatewayOverallMsgReceive(gatewayID, topic, reportStatus, message);
                var gwa = GateWayList.Find(obj => obj.GwId == gatewayID);
                if (gwa == null)
                {
                    return;
@@ -3460,7 +3155,6 @@
                }
                gwa.GwResDataAction?.Invoke(topic, message);
                gwa.CurrentGateWayId = gatewayID;
                var jobject = new Newtonsoft.Json.Linq.JObject();
                if (topic.Split('/')[0] + "/" + topic.Split('/')[1] == topic.Split('/')[0] + "/" + "FileTransfer")
@@ -3477,8 +3171,8 @@
                else
                {
                    jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                }
                }
                #region 远程,主网关上报通知
                if (IsRemote)
                {
@@ -3487,148 +3181,40 @@
                        var gwData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.GetGwData>(jobject["Data"].ToString());
                        if (gwData != null)
                        {
                            var gwList = GateWayList.FindAll(obj => obj.getGatewayBaseInfo.HomeId == Shared.Common.Config.Instance.HomeId);
                            var gwList = GateWayList.FindAll(obj => obj.HomeId == Shared.Common.Config.Instance.HomeId);
                            for (int i = 0; i < gwList.Count; i++)
                            {
                                if (gwList[i].getGatewayBaseInfo.gwID == gatewayID)
                                {
                                    gwList[i].getGatewayBaseInfo.IsMainGateWay = true;
                                }
                                else
                                {
                                    gwList[i].getGatewayBaseInfo.IsMainGateWay = false;
                                }
                            }
                        }
                    }
                }
                #endregion
                #region 设备新上报
                //步骤1)网关告知客户端有新设备加入zigbee网络。
                if (topic == gatewayID + "/" + "Device/DeviceJoinZbNet_Respon")
                {
                    var gatewayTemp = new ZbGateway() { DeviceAddr = jobject.Value<string>("DeviceAddr"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID };
                    gatewayTemp.deviceDeviceJoinZbNetResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<DeviceDeviceJoinZbNetResponData>(jobject["Data"].ToString());
                    if (gatewayTemp.deviceDeviceJoinZbNetResponData == null)
                    {
                        return;
                    }
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("Device/DeviceJoinZbNet已经通知");
                        gatewayTemp.CurrentGateWayId = gatewayID;//这里的CurrentGateWayId是当前新new ZbGateway的值
                        gwa.ReportAction("Device/DeviceJoinZbNet", gatewayTemp);
                    }
                }
                //步骤2)网关告知客户端获取新设备所有端点信息是否成功
                if (topic == gatewayID + "/" + "Device/IsGetEpointInfo_Respon")
                {
                    var gatewayTemp = new ZbGateway() { DeviceAddr = jobject.Value<string>("DeviceAddr"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID };
                    gatewayTemp.deviceIsGetEpointInfoResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<DeviceIsGetEpointInfoResponData>(jobject["Data"].ToString());
                    if (gatewayTemp.deviceIsGetEpointInfoResponData == null)
                    {
                        return;
                    }
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("Device/IsGetEpointInfo已经通知");
                        gatewayTemp.CurrentGateWayId = gatewayID;//这里的CurrentGateWayId是当前新new ZbGateway的值
                        gwa.ReportAction("Device/IsGetEpointInfo", gatewayTemp);
                    }
                }
                //步骤3)网关上报节点设备所有端点信息
                if (topic == gatewayID + "/" + "DeviceInComingRespon")
                {
                    //新设备上报,重新发获取所有的设备
                    var tempDevice = new CommonDevice() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID };
                    tempDevice.getNewDeviceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.NewDeviceInfoData>(jobject["Data"].ToString());
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("DeviceInComingRespon已经通知");
                        gwa.ReportAction("DeviceInComingRespon", tempDevice.getNewDeviceInfo);
                    }
                    UpdateDeviceInfo(tempDevice, "DeviceInComingRespon");
                }
                #endregion
                #region 设备在线状态更新反馈
                else if (topic == gatewayID + "/" + "OnlineStatusChange_Respon")
                {
                    var tempDevice = new CommonDevice() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID };
                    tempDevice.IsOnline = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(jobject["Data"]["IsOnline"].ToString());
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("OnlineStatusChange已经通知");
                        gwa.ReportAction("OnlineStatusChange", tempDevice);
                    }
                    var infoTempDevice = gwa.DeviceList.Find(obj => obj.DeviceID == tempDevice.DeviceID && obj.DeviceAddr == tempDevice.DeviceAddr);
                    if (infoTempDevice == null)
                    {
                        gwa.DeviceList.Add(tempDevice);
                        UpdateDeviceInfo(tempDevice, "OnlineStatusChange");
                    }
                    else
                    {
                        if (infoTempDevice.DeviceInfo != null)
                        {
                            infoTempDevice.DeviceInfo.IsOnline = infoTempDevice.IsOnline;
                        }
                        UpdateDeviceInfo(infoTempDevice, "OnlineStatusChange");
                    }
                }
                #endregion
                #region 设备被删除上报
                else if (topic == gatewayID + "/" + "RemoveDeviceRespon")
                {
                    var gatewayTemp = new ZbGateway() { DeviceAddr = jobject.Value<string>("DeviceAddr"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID };
                    gatewayTemp.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGateway.RemoveDeviceResponseData>(jobject["Data"].ToString());
                    if (gatewayTemp.removeDeviceResponseData != null)
                    {
                        try
                        {
                            if (gatewayTemp.removeDeviceResponseData.Result == 0)
                            {
                                foreach (var delD in gatewayTemp.removeDeviceResponseData.DeviceList)
                                if (gwList[i].GwId == gatewayID)
                                {
                                    var tempDevice = new CommonDevice() { DeviceAddr = jobject.Value<string>("DeviceAddr"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID };
                                    tempDevice.removeDeviceResponseData = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.RemoveDeviceResponseData>(jobject["Data"].ToString());
                                    if (tempDevice.removeDeviceResponseData == null)
                                    {
                                        return;
                                    }
                                    else
                                    {
                                        UpdateDeviceInfo(tempDevice, "RemoveDeviceRespon");
                                        if (tempDevice.removeDeviceResponseData.Result == 0)
                                        {
                                            var infoTempDevice = gwa.DeviceList.Find((CommonDevice obj) => obj.DeviceID == tempDevice.DeviceID && obj.DeviceAddr == tempDevice.DeviceAddr && obj.DeviceEpoint == tempDevice.DeviceEpoint);
                                            if (infoTempDevice != null)
                                            {
                                                gwa.DeviceList.Remove(infoTempDevice);
                                            }
                                        }
                                    }
                                    gwList[i].IsMainGateWay = true;
                                }
                                else
                                {
                                    gwList[i].IsMainGateWay = false;
                                }
                            }
                        }
                        catch { }
                    }
                }
                #endregion
                #region 设备在线状态更新反馈
                //2020.05.11 删除
                #endregion
                #region 设备状态上报
                else if (topic == gatewayID + "/" + "DeviceStatusReport" + "/" + addr + "/" + epoint + "/" + cluID + "/" + attrId)
                if (topic == gatewayID + "/" + "DeviceStatusReport" + "/" + addr + "/" + epoint + "/" + cluID + "/" + attrId)
                {
                    var deviceID = jobject.Value<int>("Device_ID");
                    var deviceAddr = jobject.Value<string>("DeviceAddr");
                    var tempEpoint = jobject.Value<int>("Epoint");
                    var dataId = jobject.Value<int>("Data_ID");
                    var tempDevice = new CommonDevice { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint, DataID = dataId };
                    tempDevice.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DeviceStatusReportData>(jobject["Data"].ToString());
                    var tempDevice = new CommonDevice { DeviceID = deviceID, DeviceAddr = deviceAddr, DeviceEpoint = tempEpoint };
                    tempDevice.DeviceStatusReport = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DeviceStatusReportData>(jobject["Data"].ToString());
                    UpdateDeviceInfo(tempDevice, "DeviceStatusReport");
                }
                #endregion
@@ -3639,7 +3225,7 @@
                    switch ((DeviceType)(deviceID))
                    {
                        case DeviceType.DoorLock:
                            var doorLock = new DoorLock() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID };
                            var doorLock = new DoorLock() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), CurrentGateWayId = gwa.GwId };
                            var OperatingEventNotificationDatad = Newtonsoft.Json.JsonConvert.DeserializeObject<ZigBee.Device.DoorLock.DoorLockOperatingEventNotificationCommand>(jobject["Data"].ToString());
                            if (OperatingEventNotificationDatad != null)
                            {
@@ -3662,7 +3248,7 @@
                    switch ((DeviceType)(deviceID))
                    {
                        case DeviceType.DoorLock:
                            var doorLock = new DoorLock() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID };
                            var doorLock = new DoorLock() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), CurrentGateWayId = gwa.GwId };
                            var ProgrammingEventNotificationData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZigBee.Device.DoorLock.DoorLockProgrammingEventNotificationCommand>(jobject["Data"].ToString());
                            if (ProgrammingEventNotificationData != null)
                            {
@@ -3679,32 +3265,15 @@
                }
                #endregion
                #region IAS安防信息上报
                else if (topic == gatewayID + "/" + "IASInfoReport")
                {
                    var deviceID = jobject.Value<int>("Device_ID");
                    switch ((DeviceType)(deviceID))
                    {
                        case DeviceType.IASZone:
                            var ias = new IASZone() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID };
                            ias.iASInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<IASZone.IASInfoData>(jobject["Data"].ToString());
                            //上报类型通知,必需先调用,然后才有通知,否则是空不会通知的
                            if (gwa.ReportAction != null)
                            {
                                DebugPrintLog("IASInfoReport已经通知");
                                //ias.Save();
                                gwa.ReportAction("IASInfoReport", ias.iASInfo);
                            }
                            UpdateDeviceInfo(ias, "IASInfoReport");
                            break;
                    }
                }
                //2020.05.11 删除
                #endregion
                #region 下载进度上报
                else if (topic == gatewayID + "/" + "DownloadFile_Progress")
                {
                    var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                    gatewayTemp.downloadFileProgressResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<DownloadFileProgressResponData>(jobject["Data"].ToString());
                    if (gatewayTemp.downloadFileProgressResponData == null)
                    gwa.downloadFileProgressResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.DownloadFileProgressResponData>(jobject["Data"].ToString());
                    if (gwa.downloadFileProgressResponData == null)
                    {
                        return;
                    }
@@ -3712,15 +3281,13 @@
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("DownloadFileProgress");
                        gatewayTemp.CurrentGateWayId = gatewayID;//这里的CurrentGateWayId是当前新new ZbGateway的值
                        gwa.ReportAction("DownloadFileProgress", gatewayTemp);
                        gwa.ReportAction("DownloadFileProgress", gwa);
                    }
                }
                else if (topic == gatewayID + "/" + "ZbGwOperation/Upgrade_Respon")
                {
                    var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                    gatewayTemp.zbGwOperationUpgradeData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGwOperationUpgradeData>(jobject["Data"].ToString());
                    if (gatewayTemp.zbGwOperationUpgradeData == null)
                    gwa.zbGwOperationUpgradeData = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGwOperationUpgradeData>(jobject["Data"].ToString());
                    if (gwa.zbGwOperationUpgradeData == null)
                    {
                        return;
                    }
@@ -3728,16 +3295,14 @@
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("协调器升级百分比");
                        gatewayTemp.CurrentGateWayId = gatewayID;//这里的CurrentGateWayId是当前新new ZbGateway的值
                        gwa.ReportAction("CordinatorUpgradePercent", gatewayTemp);
                        gwa.ReportAction("CordinatorUpgradePercent", gwa);
                    }
                }
                else if (topic == gatewayID + "/" + "OTA/Schedule_Respon")
                {
                    var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                    gatewayTemp.oTAScheduleResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<OTAScheduleResponData>(jobject["Data"].ToString());
                    gwa.oTAScheduleResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.OTAScheduleResponData>(jobject["Data"].ToString());
                    if (gatewayTemp.oTAScheduleResponData == null)
                    if (gwa.oTAScheduleResponData == null)
                    {
                        return;
                    }
@@ -3746,16 +3311,14 @@
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("节点设备升级百分比");
                        gatewayTemp.CurrentGateWayId = gatewayID;//这里的CurrentGateWayId是当前新new ZbGateway的值
                        gwa.ReportAction("DeviceUpgradePercent", gatewayTemp);
                        gwa.ReportAction("DeviceUpgradePercent", gwa);
                    }
                }
                else if (topic == gatewayID + "/" + "VirtualDrive/Upgrade_Respon")
                {
                    var gatewayTemp = new ZbGateway() { DataID = jobject.Value<int>("Data_ID") };
                    gatewayTemp.virtualDriveUpgradeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<VirtualDriveUpgradeResponData>(jobject["Data"].ToString());
                    gwa.virtualDriveUpgradeResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<VirtualDriveUpgradeResponData>(jobject["Data"].ToString());
                    if (gatewayTemp.virtualDriveUpgradeResponData == null)
                    if (gwa.virtualDriveUpgradeResponData == null)
                    {
                        return;
                    }
@@ -3763,18 +3326,16 @@
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("虚拟驱动升级百分比");
                        gatewayTemp.CurrentGateWayId = gatewayID;//这里的CurrentGateWayId是当前新new ZbGateway的值
                        gwa.ReportAction("VirtualDriveUpgrade", gatewayTemp);
                        gwa.ReportAction("VirtualDriveUpgrade", gwa);
                    }
                }
                #endregion
                #region 重启网关系统
                else if (topic == gatewayID + "/" + "GwReboot_Respon")
                {
                    var gatewayTemp = new ZbGateway() { DeviceID = jobject.Value<int>("Device_ID") };
                    gatewayTemp.gwRebootResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<GwRebootResponData>(jobject["Data"].ToString());
                    var gwRebootResponData = Newtonsoft.Json.JsonConvert.DeserializeObject<GwRebootResponData>(jobject["Data"].ToString());
                    if (gatewayTemp.gwRebootResponData == null)
                    if (gwRebootResponData == null)
                    {
                        return;
                    }
@@ -3782,15 +3343,14 @@
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("GwReboot_Respon已经通知");
                        gatewayTemp.CurrentGateWayId = gatewayID;//这里的CurrentGateWayId是当前新new ZbGateway的值
                        gwa.ReportAction("GwReboot_Respon", gatewayTemp);
                        gwa.ReportAction("GwReboot_Respon", gwRebootResponData);
                    }
                }
                #endregion
                #region 防区被触发时报告
                else if (topic == gatewayID + "/" + "Security/ZoneTriggerReport")
                {
                    var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID };
                    var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId };
                    ias.zoneTriggerReportData = Newtonsoft.Json.JsonConvert.DeserializeObject<Safeguard.ZoneTriggerReportData>(jobject["Data"].ToString());
                    if (ias.zoneTriggerReportData == null)
@@ -3808,7 +3368,7 @@
                #region 逻辑被调用反馈
                else if (topic == gatewayID + "/" + "Logic/Execute_Respon")
                {
                    //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID };
                    //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId };
                    //logic.logicExecuteRespo = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.ExecuteResponse>(jobject["Data"].ToString());
                    //if (logic.logicExecuteRespo == null)
@@ -3826,7 +3386,7 @@
                #region 时间点条件推迟执行
                else if (topic == gatewayID + "/" + "Logic/TimingWillArrive")
                {
                    //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID };
                    //var logic = new Logic() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId };
                    //logic.timingWillArriveData = Newtonsoft.Json.JsonConvert.DeserializeObject<Logic.TimingWillArriveData>(jobject["Data"].ToString());
                    //if (logic.timingWillArriveData == null)
@@ -3844,7 +3404,7 @@
                #region 模式安防动作被最终激活时发送报警信息
                else if (topic == gatewayID + "/" + "Security/ModeTriggerReport")
                {
                    var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID };
                    var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId };
                    ias.modeTriggerReportData = Newtonsoft.Json.JsonConvert.DeserializeObject<Safeguard.ModeTriggerReportData>(jobject["Data"].ToString());
                    if (ias.modeTriggerReportData == null)
                    {
@@ -3861,7 +3421,7 @@
                #region 通过外部方式布防撤防成功时报告息
                else if (topic == gatewayID + "/" + "Security/EnOrWithdrawSucceedReport")
                {
                    var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID };
                    var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId };
                    ias.enOrWithdrawSucceedReportData = Newtonsoft.Json.JsonConvert.DeserializeObject<Safeguard.EnOrWithdrawSucceedReportData>(jobject["Data"].ToString());
                    if (ias.enOrWithdrawSucceedReportData == null)
                    {
@@ -3878,7 +3438,7 @@
                #region 胁迫密码撤防时短信推送
                else if (topic == gatewayID + "/" + "Security/PushTargetInfo")
                {
                    var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.getGatewayBaseInfo.gwID };
                    var ias = new Safeguard() { DataID = jobject.Value<int>("Data_ID"), GateWayId = gwa.GwId };
                    ias.coercedPWDWithdrawReportData = Newtonsoft.Json.JsonConvert.DeserializeObject<Safeguard.CoercedPWDWithdrawReportData>(jobject["Data"].ToString());
                    if (ias.coercedPWDWithdrawReportData == null)
                    {
@@ -3892,34 +3452,18 @@
                    }
                }
                #endregion
                #region 节点设备默认反馈
                else if (topic == gatewayID + "/" + "DeviceDefaultAck")
                {
                    var deviceDefaultAck = new ZbGateway() { DeviceID = jobject.Value<int>("Device_ID"), DeviceAddr = jobject.Value<string>("DeviceAddr"), DeviceEpoint = jobject.Value<int>("Epoint"), DataID = jobject.Value<int>("Data_ID"), CurrentGateWayId = gwa.getGatewayBaseInfo.gwID };
                    if (deviceDefaultAck == null)
                    {
                        return;
                    }
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        DebugPrintLog("DeviceDefaultAck");
                        gwa.ReportAction("DeviceDefaultAck", deviceDefaultAck);
                    }
                }
                #endregion
                #region 设备请求APP获取升级数据
                else if (topic == gatewayID + "/" + "ZbDataPassthrough")
                {
                    //上报类型通知
                    if (gwa.ReportAction != null)
                    {
                        var clientDataPassthrough = Newtonsoft.Json.JsonConvert.DeserializeObject<ClientDataPassthroughResponseData>(jobject["Data"].ToString());
                        if (clientDataPassthrough != null)
                        {
                            DebugPrintLog("DeviceRequestAcUpdateData");
                            gwa.ReportAction("DeviceRequestAcUpdateData", clientDataPassthrough);
                    {
                        var clientDataPassthrough = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ClientDataPassthroughResponseData>(jobject["Data"].ToString());
                        if (clientDataPassthrough != null)
                        {
                            DebugPrintLog("DeviceRequestAcUpdateData");
                            gwa.ReportAction("DeviceRequestAcUpdateData", clientDataPassthrough);
                        }
                    }
                }
@@ -3931,5 +3475,45 @@
            }
        }
        #endregion
        #region 保存缓存
        /// <summary>
        /// 重新保存设备
        /// </summary>
        public void ReSave()
        {
            if (Shared.Common.Config.Instance.Home.IsShowTemplate == true)
            {
                //展示模板时,不允许保存文件(防止属性上报用的)
                return;
            }
            Global.WriteFileByBytesByHomeId(FilePath, System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(this)));
        }
        #endregion
        #region 调试打印
        /// <summary>
        /// 调试时打开打印信息,true:打印,false:不打印
        /// </summary>
        /// <param name="msg">Message.</param>
        /// <param name="flage">If set to <c>true</c> flage.</param>
        public static void DebugPrintLog(string msg, bool flage = true)
        {
#if DEBUG
            if (flage == true)
            {
                //if (msg.Contains("DeviceInfoRespon") == true)
                {
                    System.Console.WriteLine(msg + "  " + System.DateTime.Now.ToLongTimeString() + " " + System.DateTime.Now.Millisecond);
                }
            }
#endif
        }
        #endregion
    }
}