黄学彪
2020-09-22 ade5917841b0fdcb1df7353ef7c56b1a1bdc9282
ZigbeeApp/Shared/Phone/UserCenter/CommonBase/Logic/HdlGatewayLogic.cs
@@ -15,11 +15,11 @@
        #region ■ 变量声明___________________________
        /// <summary>
        /// 备份业务的逻辑
        /// 网关业务的逻辑类
        /// </summary>
        private static HdlGatewayLogic m_Current = null;
        /// <summary>
        /// 备份业务的逻辑
        /// 网关业务的逻辑类
        /// </summary>
        public static HdlGatewayLogic Current
        {
@@ -69,8 +69,7 @@
                        continue;
                    }
                    //添加缓存
                    string gwID = HdlGatewayLogic.Current.GetGatewayId(gateway);
                    dicGateway[gwID] = gateway;
                    dicGateway[gateway.GwId] = gateway;
                }
            }
        }
@@ -117,10 +116,20 @@
            {
                return;
            }
            List<string> listBackupGwId = new List<string>();
            var fileData = Global.ReadFileByDirectory(DirNameResourse.LocalMemoryDirectory, DirNameResourse.BackupGatewayIdFile);
            if (fileData != null)
            {
                //新增:虽然概率低,但是确实发生了。如果有网络时,App重新绑定记录的网关失败的话
                //不应该删除它
                listBackupGwId = JsonConvert.DeserializeObject<List<string>>(System.Text.Encoding.UTF8.GetString(fileData));
            }
            List<string> listDelete = new List<string>();
            foreach (var gatewayId in this.dicGateway.Keys)
            {
                if (result.ContainsKey(gatewayId) == false)
                if (result.ContainsKey(gatewayId) == false && listBackupGwId.Contains(gatewayId) == false)
                {
                    //本地存在云端不存在的网关,则删除
                    listDelete.Add(gatewayId);
@@ -132,8 +141,10 @@
                List<CommonDevice> list = Common.LocalDevice.Current.GetDeviceByGatewayID(gatewayId);
                foreach (var device in list)
                {
                    //删除设备,不删除房间信息
                    Common.LocalDevice.Current.DeleteMemmoryDevice(device, false);
                    //删除一般设备
                    Common.LocalDevice.Current.DeleteMemmoryDevice(device, true);
                    //删除Ota设备
                    Common.LocalDevice.Current.DeleteMemmoryOtaDevice(device.DeviceAddr);
                }
                //删除网关文件
                this.DeleteGatewayFile(gatewayId);
@@ -168,10 +179,28 @@
        /// <returns></returns>
        private ZbGateway GetGatewayFromFile(string file)
        {
            byte[] filebyte = Global.ReadFileByHomeId(file);
            string strvalue = System.Text.Encoding.UTF8.GetString(filebyte);
            var gateway = JsonConvert.DeserializeObject<ZbGateway>(strvalue);
            return gateway;
            try
            {
                byte[] filebyte = Global.ReadFileByHomeId(file);
                string strvalue = System.Text.Encoding.UTF8.GetString(filebyte);
                var gateway = JsonConvert.DeserializeObject<ZbGateway>(strvalue);
                if (gateway.GwId == string.Empty)
                {
                    //这是旧数据,需要特殊处理
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(strvalue);
                    string gwInfo = jobject["getGwInfo"].ToString();
                    var result = JsonConvert.DeserializeObject<ZbGatewayData.GetGwData>(gwInfo);
                    //将网关的数据设置到本地缓存中
                    this.SetGatewayDataToLocalMemmory(gateway, result);
                }
                return gateway;
            }
            catch (Exception ex)
            {
                HdlLogLogic.Current.WriteLog(ex);
                return null;
            }
        }
        #endregion
@@ -179,20 +208,43 @@
        #region ■ 添加网关___________________________
        /// <summary>
        /// 添加新网关(仅限追加新的网关  1:正常  -1:异常  0:当前的网关绑定在了当前账号下的不同住宅里面)
        /// 添加新网关(仅限追加新的网关)
        /// </summary>
        /// <param name="zbGateway">网关</param>
        /// <param name="mode">是否显示错误</param>
        public async Task<int> AddNewGateway(ZbGateway zbGateway, ShowErrorMode mode)
        {
        public async Task<bool> AddNewGateway(ZbGateway zbGateway, ShowErrorMode mode)
        {
            //设置网关的经纬度
            bool falge = this.SetGatewaySite(zbGateway, Common.Config.Instance.Home.Longitude, Common.Config.Instance.Home.Latitude, ShowErrorMode.NO);
            if (falge == false)
            {
                return falge;
            }
            //执行添加网关到内存
            var result = await this.DoAddGatewayToMemory(zbGateway, mode);
            if (result != 1)
            //前的网关绑定在了当前账号下的不同住宅里面
            if (result == 0)
            {
                return result;
                if (mode == ShowErrorMode.YES)
                {
                    //网关绑定在当前账号下的其他住宅里\r\n请解除绑定后再试
                    string msg = Language.StringByID(R.MyInternationalizationString.uTheGatewayInOtherResidenceMsg);
                    if (msg.Contains("{0}") == true)
                    {
                        msg = string.Format(msg, "\r\n");
                    }
                    this.ShowTipMsg(msg);
                }
                return false;
            }
            if (result == -1)
            {
                return false;
            }
            //添加网关的话,强制主页刷新
            UserView.UserPage.Instance.RefreshForm = true;
            return 1;
            return true;
        }
        /// <summary>
@@ -202,8 +254,8 @@
        public void AddVirtualGateway(string gatewayId)
        {
            var gateWay = new ZbGateway { IsVirtual = true };
            gateWay.getGatewayBaseInfo.gwID = gatewayId;
            gateWay.getGatewayBaseInfo.HomeId = Shared.Common.Config.Instance.HomeId;
            gateWay.GwId = gatewayId;
            gateWay.HomeId = Shared.Common.Config.Instance.HomeId;
            gateWay.ReSave();
            this.dicGateway[gatewayId] = gateWay;
        }
@@ -229,7 +281,7 @@
            //获取网关的信息
            var result = await zbGateway.GetZbGwInfoAsync();
            //检测网关返回的共通错误状态码
            string error = UserCenterLogic.CheckCommonErrorCode(result);
            string error = HdlCheckLogic.Current.CheckCommonErrorCode(result);
            if (error != null)
            {
                if (mode == ShowErrorMode.YES)
@@ -262,7 +314,7 @@
            }
            //设置住宅ID到网关
            bool flage2 = await this.SetHomeIdToGateway(zbGateway, Common.Config.Instance.HomeId);
            bool flage2 = await this.SetHomeIdToGateway(zbGateway, Common.Config.Instance.HomeId, mode);
            if (flage2 == false)
            {
                if (mode == ShowErrorMode.YES)
@@ -275,7 +327,7 @@
            }
            //更新云端数据库
            int flage1 = await this.SetGatewayIdToDataBase(zbGateway);
            int flage1 = this.SetGatewayIdToDataBase(zbGateway);
            //异常也不鸟它,0是特殊含义
            if (flage1 == 0)
            {
@@ -284,12 +336,12 @@
            if (flage1 == -1)
            {
                //备份失败的网关ID
                HdlGatewayLogic.Current.BackupGatewayIdOnNotNetwork(zbGateway);
                this.BackupGatewayIdOnNotNetwork(zbGateway);
            }
            //是否已经存在
            string gwID = HdlGatewayLogic.Current.GetGatewayId(zbGateway);
            bool isEsist = HdlGatewayLogic.Current.IsGatewayExist(zbGateway);
            string gwID = zbGateway.GwId;
            bool isEsist = this.IsGatewayExist(zbGateway);
            if (isEsist == false)
            {
                //新建一个虚拟的网关出来
@@ -300,11 +352,11 @@
            //刷新的是缓存,不刷新真实物理网关
            this.dicGateway[gwID].GatewayOnlineFlage = zbGateway.GatewayOnlineFlage;
            this.dicGateway[gwID].getGwInfo = result.getGwData;
            this.dicGateway[gwID].getGatewayBaseInfo.GwName = result.getGwData.GwName;
            this.dicGateway[gwID].getGatewayBaseInfo.IpAddress = result.getGwData.GwIP;
            this.dicGateway[gwID].getGatewayBaseInfo.HomeId = Common.Config.Instance.HomeId;
            this.dicGateway[gwID].ReSave();
            //将网关的数据设置到本地缓存中
            this.SetGatewayDataToLocalMemmory(this.dicGateway[gwID], result.getGwData);
            //顺便这个变量也设置一下
            this.SetGatewayDataToLocalMemmory(zbGateway, result.getGwData, false);
            if (isEsist == false)
            {
                //添加备份
@@ -320,9 +372,21 @@
        /// <param name="zbGateway"></param>
        /// <param name="HomeId"></param>
        /// <returns></returns>
        public async Task<bool> SetHomeIdToGateway(ZbGateway zbGateway, string HomeId)
        public async Task<bool> SetHomeIdToGateway(ZbGateway zbGateway, string HomeId, ShowErrorMode mode)
        {
            var info = await zbGateway.GwSetHomeIdAsync(HomeId);
            ZbGateway realWay = null;
            if (this.GetRealGateway(ref realWay, zbGateway) == false)
            {
                if (mode == ShowErrorMode.YES)
                {
                    //错误:网关对象丢失
                    string msg = Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg);
                    this.ShowTipMsg(msg);
                }
                return false;
            }
            var info = await realWay.GwSetHomeIdAsync(HomeId);
            if (info != null && info.gwSetHomeIdData != null)
            {
                return true;
@@ -335,19 +399,16 @@
        /// </summary>
        /// <param name="zbGateway">网关对象</param>
        /// <returns></returns>
        private async Task<int> SetGatewayIdToDataBase(ZbGateway zbGateway)
        private int SetGatewayIdToDataBase(ZbGateway zbGateway)
        {
            //调用接口,绑定网关(即使失败,也返回true往下走)
            var bindGateway = new BindGatewayPra();
            string gwID = this.GetGatewayId(zbGateway);
            bindGateway.BindGateways.Add(gwID);
            bindGateway.BindGateways.Add(zbGateway.GwId);
            //获取控制主人账号的Token
            bindGateway.LoginAccessToken = UserCenterLogic.GetConnectMainToken();
            //不显示已经被绑定过的信息,NotSetAgain:假如断网时,不二次发送
            List<string> listNotShow = new List<string>() { "NotSetAgain" };
            var result = await UserCenterLogic.GetResultCodeByRequestHttps("App/BindGatewayToHome", true, bindGateway, listNotShow);
            if (result == "Error" || result == "ErrorEx")
            var result = UserCenterLogic.GetResultCodeByRequestHttps("App/BindGatewayToHome", true, bindGateway);
            if (result == "Error")
            {
                return -1;
            }
@@ -366,7 +427,7 @@
        /// <returns></returns>
        public bool HomeIdIsEmpty(ZbGateway zbGateway)
        {
            return this.HomeIdIsEmpty(zbGateway.getGatewayBaseInfo.HomeId);
            return this.HomeIdIsEmpty(zbGateway.HomeId);
        }
        /// <summary>
@@ -391,7 +452,8 @@
        /// 重新绑定网关(1:正常  -1:异常  0:当前的网关绑定在了当前账号下的不同住宅里面)
        /// </summary>
        /// <param name="zbGateway">网关</param>
        public async Task<int> ReBindNewGateway(ZbGateway zbGateway)
        /// <param name="btnMsg">消息控件</param>
        public async Task<int> ReBindNewGateway(ZbGateway zbGateway, NormalViewControl btnMsg = null)
        {
            if (zbGateway == null)
            {
@@ -400,9 +462,15 @@
                this.ShowTipMsg(msg);
                return -1;
            }
            //设置网关的经纬度
            bool falge = this.SetGatewaySite(zbGateway, Common.Config.Instance.Home.Longitude, Common.Config.Instance.Home.Latitude, ShowErrorMode.YES);
            if (falge == false)
            {
                return -1;
            }
            //设置住宅ID到网关
            bool flage2 = await this.SetHomeIdToGateway(zbGateway, Common.Config.Instance.HomeId);
            bool flage2 = await this.SetHomeIdToGateway(zbGateway, Common.Config.Instance.HomeId, ShowErrorMode.YES);
            if (flage2 == false)
            {
                //向网关设置住宅ID失败
@@ -412,7 +480,7 @@
            }
            //更新云端数据库
            int flage1 = await this.SetGatewayIdToDataBase(zbGateway);
            int flage1 = this.SetGatewayIdToDataBase(zbGateway);
            //异常也不鸟它,0是特殊含义
            if (flage1 == 0)
            {
@@ -424,30 +492,44 @@
                HdlGatewayLogic.Current.BackupGatewayIdOnNotNetwork(zbGateway);
            }
            //网关内部数据变更中,请稍后
            ProgressBar.SetValue(Language.StringByID(R.MyInternationalizationString.uGatewayDataIsChangingPleaseWhait));
            await System.Threading.Tasks.Task.Delay(8000);
            if (btnMsg == null)
            {
                //网关内部数据变更中,请稍后
                ProgressBar.SetValue(Language.StringByID(R.MyInternationalizationString.uGatewayDataIsChangingPleaseWhait));
            }
            else
            {
                HdlThreadLogic.Current.RunMain(() =>
                {
                    //网关内部数据变更中,请稍后
                    btnMsg.TextID = R.MyInternationalizationString.uGatewayDataIsChangingPleaseWhait;
                });
            }
            await Task.Delay(8000);
            //获取网关的信息
            var result = await zbGateway.GetZbGwInfoAsync();
            ZbGatewayData.GetGwAllData result = null;
            int count = 5;
            while (count >= 0)
            {
                result = await zbGateway.GetZbGwInfoAsync();
                if (result != null && result.getGwData != null)
                {
                    break;
                }
                count--;
                //最多再等20秒
                await Task.Delay(4000);
            }
            //检测网关返回的共通错误状态码
            string error = UserCenterLogic.CheckCommonErrorCode(result);
            string error = HdlCheckLogic.Current.CheckCommonErrorCode(result);
            if (error != null)
            {
                this.ShowTipMsg(error);
                return -1;
            }
            if (result == null)
            {
                //获取网关信息失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetGatewayInfoFail);
                this.ShowTipMsg(msg);
                return -1;
            }
            if (result.getGwData == null)
            if (result == null || result.getGwData == null)
            {
                //获取网关信息失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetGatewayInfoFail);
@@ -456,7 +538,7 @@
            }
            //是否已经存在
            string gwID = HdlGatewayLogic.Current.GetGatewayId(zbGateway);
            string gwID = zbGateway.GwId;
            bool isEsist = HdlGatewayLogic.Current.IsGatewayExist(zbGateway);
            if (isEsist == false)
            {
@@ -468,16 +550,20 @@
            //刷新的是缓存,不刷新真实物理网关
            this.dicGateway[gwID].GatewayOnlineFlage = zbGateway.GatewayOnlineFlage;
            this.dicGateway[gwID].getGwInfo = result.getGwData;
            this.dicGateway[gwID].getGatewayBaseInfo.GwName = result.getGwData.GwName;
            this.dicGateway[gwID].getGatewayBaseInfo.IpAddress = result.getGwData.GwIP;
            this.dicGateway[gwID].getGatewayBaseInfo.HomeId = Common.Config.Instance.HomeId;
            this.dicGateway[gwID].ReSave();
            //将网关的数据设置到本地缓存中
            this.SetGatewayDataToLocalMemmory(this.dicGateway[gwID], result.getGwData);
            //顺便这个变量也设置一下
            this.SetGatewayDataToLocalMemmory(zbGateway, result.getGwData, false);
            if (isEsist == false)
            {
                //添加备份
                HdlAutoBackupLogic.AddOrEditorFile(this.dicGateway[gwID].FilePath);
            }
            //添加网关的话,强制主页刷新
            UserView.UserPage.Instance.RefreshForm = true;
            return 1;
        }
@@ -503,7 +589,7 @@
            var result = await realWay.GwReNameAsync(gatewayName);
            //检测网关返回的共通错误状态码
            string error = UserCenterLogic.CheckCommonErrorCode(result);
            string error = HdlCheckLogic.Current.CheckCommonErrorCode(result);
            if (error != null)
            {
                this.ShowErrorMsg(error);
@@ -530,16 +616,115 @@
            }
            //修改缓存
            string gwID = this.GetGatewayId(zbGateway);
            this.dicGateway[gwID].getGatewayBaseInfo.GwName = gatewayName;
            string gwID = zbGateway.GwId;
            this.dicGateway[gwID].GwName = gatewayName;
            this.dicGateway[gwID].ReSave();
            //添加自动备份
            HdlAutoBackupLogic.AddOrEditorFile(zbGateway.FilePath);
            return true;
        }
        }
        #endregion
        #region ■ 网关切换___________________________
        /// <summary>
        /// 执行切换网关操作
        /// </summary>
        /// <param name="gatewayId"></param>
        public async Task<bool> DoSwitchGateway(string gatewayId)
        {
            var zbGateway = this.GetLocalGateway(gatewayId);
            if (this.CheckGatewayOnlineByFlag(zbGateway) == true)
            {
                //重新获取在线网关的信息
                var result = await this.GetOnlineGatewayInfo(gatewayId);
                if (result == false)
                {
                    return false;
                }
            }
            //切换网关,保存缓存
            this.SaveGatewayIdToLocation(gatewayId);
            //切换网关的话,主页需要重新刷新
            UserView.UserPage.Instance.RefreshForm = true;
            return true;
        }
        /// <summary>
        /// 获取在线网关信息
        /// </summary>
        /// <param name="gatewayId"></param>
        /// <returns></returns>
        private async Task<bool> GetOnlineGatewayInfo(string gatewayId)
        {
            //显示进度条
            ProgressBar.Show();
            //检测广播到的这个网关是否拥有住宅ID
            ZbGateway realWay = null;
            bool getGatewayInfo = true;
            if (this.GetRealGateway(ref realWay, gatewayId) == true)
            {
                //重新设置住宅ID(这个应该是不经过APP,直接把网关恢复了出厂设置)
                if (this.HomeIdIsEmpty(realWay.HomeId) == true)
                {
                    int result2 = await this.ReBindNewGateway(realWay);
                    if (result2 == 0)
                    {
                        //出现未知错误,请稍后再试
                        this.ShowTipMsg(Language.StringByID(R.MyInternationalizationString.uUnKnowErrorAndResetAgain));
                        //关闭进度条
                        ProgressBar.Close();
                    }
                    else if (result2 == -1)
                    {
                        //关闭进度条
                        ProgressBar.Close();
                        return false;
                    }
                    //重新绑定网关里面已经重新获取了网关信息
                    getGatewayInfo = false;
                }
            }
            if (getGatewayInfo == true)
            {
                //获取网关信息
                var info = this.GetGatewayInfo(realWay);
                if (info == null)
                {
                    //关闭进度条
                    ProgressBar.Close();
                    return false;
                }
            }
            //获取全部设备
            int result = LocalDevice.Current.SetDeviceToMemmoryByGateway(realWay);
            //关闭进度条
            ProgressBar.Close();
            if (result == -1)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 保存选择的网关ID到本地
        /// </summary>
        /// <param name="gatewayId"></param>
        public void SaveGatewayIdToLocation(string gatewayId)
        {
            GatewayResourse.AppOldSelectGatewayId = gatewayId;
            byte[] data = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(GatewayResourse.AppOldSelectGatewayId));
            Global.WriteFileToDirectoryByBytes(DirNameResourse.LocalMemoryDirectory, DirNameResourse.AppOldSelectGatewayFile, data);
        }
        #endregion
        #region ■ 删除网关___________________________
@@ -550,9 +735,8 @@
        /// <param name="zbGateway"></param>
        public async Task<bool> DeleteGateway(ZbGateway zbGateway)
        {
            string gwID = this.GetGatewayId(zbGateway);
            //移除本地网关信息
            return await this.DeleteGateway(gwID);
            return await this.DeleteGateway(zbGateway.GwId);
        }
        /// <summary>
@@ -568,26 +752,26 @@
            if (hadReal == true && realWay.GatewayOnlineFlage == true)
            {
                //清空网关的住宅ID
                bool result = await this.SetHomeIdToGateway(realWay, string.Empty);
                bool result = await this.SetHomeIdToGateway(realWay, string.Empty, ShowErrorMode.YES);
                if (result == false)
                {
                    //网关解绑失败
                    //网关解绑失败  不理它,因为网关可以按按键强制搜索得到
                    string msg = Language.StringByID(R.MyInternationalizationString.uGatewayUnBindFail);
                    this.ShowErrorMsg(msg);
                    return false;
                    //this.ShowErrorMsg(msg);
                    //return false;
                }
            }
            //删除云端的网关
            await Phone.UserCenter.HdlGatewayLogic.Current.DeleteDataBaseGateway(zbGatewayID);
            this.DeleteDataBaseGateway(zbGatewayID);
            //删除网关文件
            this.DeleteGatewayFile(zbGatewayID);
            //移除
            ZbGateway.GateWayList.RemoveAll((obj) => this.GetGatewayId(obj) == zbGatewayID);
            ZbGateway.GateWayList.RemoveAll((obj) => obj.GwId == zbGatewayID);
            //断开mqtt连接
            realWay.DisConnect("GD");
            realWay.DisConnectLocalMqttClient("GD");
            return true;
        }
@@ -620,18 +804,21 @@
            {
                //删除设备文件
                Common.LocalDevice.Current.DeleteMemmoryDevice(device, true);
                //删除Ota设备
                Common.LocalDevice.Current.DeleteMemmoryOtaDevice(device.DeviceAddr);
            }
            //如果是主网关
            if (this.IsMainGateway(zbGatewayID) == 1)
            {
                foreach (var room in Shared.Common.Room.Lists)
                var listAllRoom = UserCenter.HdlRoomLogic.Current.GetAllListRooms();
                foreach (var room in listAllRoom)
                {
                    //删除场景文件
                    foreach (var scene in room.SceneUIFilePathList)
                    foreach (var sceneId in room.ListSceneId)
                    {
                        if (Global.IsExistsByHomeId(scene) == true)
                        if (Global.IsExistsByHomeId($"Scene_{sceneId}.json") == true)
                        {
                            Global.DeleteFilebyHomeId(scene);
                            Global.DeleteFilebyHomeId($"Scene_{sceneId}.json");
                        }
                    }
                }
@@ -646,9 +833,8 @@
        /// 刷新网关的在线状态(注意,刷新的是缓存,请调用CheckGatewayOnlineByFlag来判断是否在线)
        /// </summary>
        /// <param name="listGateway"></param>
        /// <param name="waitTime">局域网的时候,时候等待3秒延迟</param>
        /// <returns></returns>
        public void RefreshGatewayOnlineStatu(List<ZbGateway> listGateway, bool waitTime = true)
        public void RefreshGatewayOnlineStatu(List<ZbGateway> listGateway)
        {
            var listRealWay = new List<ZbGateway>();
            for (int i = 0; i < listGateway.Count; i++)
@@ -663,41 +849,29 @@
                {
                    //虚拟物理网关
                    listRealWay.Add(listGateway[i]);
                    if (waitTime == false)
                    {
                        //不等待的话,标识指定网关为不在线
                        this.SetGatewayNotOnLineFlag(listRealWay[i]);
                    }
                }
                if (waitTime == true)
                {
                    //只有等待的时候,才标识指定网关为不在线
                    this.SetGatewayNotOnLineFlag(listRealWay[i]);
                }
                //标识指定网关为不在线
                listRealWay[i].GatewayOnlineFlage = false;
            }
            if (waitTime == true)
            //这是第一道坎,强制检查WIFI:等待2秒(因为wifi的时候,它会自动去刷新flage)
            System.Threading.Thread.Sleep(2000);
            //检查是否拥有网关存在于WIFi下
            if (this.CheckHadGatewayInWifi(listRealWay) == false)
            {
                //这是第一道坎,强制检查WIFI:等待3秒(因为wifi的时候,它会自动去刷新flage)
                System.Threading.Thread.Sleep(3000);
                //检查是否拥有网关存在于WIFi下
                if (this.CheckHadGatewayInWifi(listRealWay) == false)
                {
                    //第二道坎:在远程的情况下刷新网关的在线状态
                    this.RefreshGatewayOnlineOnRemode(listRealWay);
                }
                //第二道坎:在远程的情况下刷新网关的在线状态
                this.RefreshGatewayOnlineOnRemode(listRealWay);
            }
            //刷新缓存的在线标识
            foreach (var zbway in listRealWay)
            {
                string gwID = this.GetGatewayId(zbway);
                string gwID = zbway.GwId;
                if (this.dicGateway.ContainsKey(gwID) == false)
                {
                    continue;
                }
                this.dicGateway[gwID].GatewayOnlineFlage = zbway.GatewayOnlineFlage;
                this.dicGateway[gwID].ReSave();
            }
        }
@@ -734,31 +908,16 @@
            }
            foreach (var way in listGateway)
            {
                if (way == null || way.getGatewayBaseInfo == null)
                if (way == null)
                {
                    continue;
                }
                string strId = this.GetGatewayId(way);
                if (dicDbGateway.ContainsKey(strId) == true //如果云端上面有这个网关
                    && dicDbGateway[strId].MqttOnlineStatus == true //如果云端上面这个网关是在线的
                    )
                string strId = way.GwId;
                if (dicDbGateway.ContainsKey(strId) == true) //如果云端上面有这个网关
                {
                    way.GatewayOnlineFlage = true;
                    way.GatewayOnlineFlage = dicDbGateway[strId].MqttOnlineStatus;
                }
            }
        }
        /// <summary>
        /// 标识指定网关为不在线
        /// </summary>
        /// <param name="zbGateway"></param>
        public void SetGatewayNotOnLineFlag(ZbGateway zbGateway)
        {
            if (zbGateway == null)
            {
                return;
            }
            zbGateway.GatewayOnlineFlage = false;
        }
        /// <summary>
@@ -773,7 +932,7 @@
                return false;
            }
            //使用缓存的,因为刷新在线状态的时候,刷新的就是缓存,而不是真实物理网关
            string gwID = this.GetGatewayId(zbGateway);
            string gwID = zbGateway.GwId;
            if (this.dicGateway.ContainsKey(gwID) == true)
            {
                return this.dicGateway[gwID].GatewayOnlineFlage;
@@ -799,12 +958,12 @@
            List<ZbGateway> newlist = new List<ZbGateway>();
            foreach (var way in list)
            {
                if (Config.Instance.HomeId != way.getGatewayBaseInfo.HomeId)
                if (Config.Instance.HomeId != way.HomeId)
                {
                    //如果不是当前住宅
                    continue;
                }
                string gwID = this.GetGatewayId(way);
                string gwID = way.GwId;
                if (this.dicGateway.ContainsKey(gwID) == false)
                {
                    //如果本地并没有这个网关
@@ -874,11 +1033,11 @@
        /// <returns></returns>
        public bool GetRealGateway(ref ZbGateway zbGateway, ZbGateway tagartWay)
        {
            if (tagartWay == null || tagartWay.getGatewayBaseInfo == null)
            if (tagartWay == null)
            {
                return false;
            }
            return this.GetRealGateway(ref zbGateway, this.GetGatewayId(tagartWay));
            return this.GetRealGateway(ref zbGateway, tagartWay.GwId);
        }
        /// <summary>
@@ -891,14 +1050,14 @@
        {
            var realWay = ZbGateway.GateWayList.Find((obj) =>
            {
                return this.GetGatewayId(obj) == gwId;
                return obj.GwId == gwId;
            });
            if (realWay == null)
            {
                //如果网关对象丢失了,则创建个新的
                realWay = new ZbGateway { IsVirtual = true, };
                realWay.getGatewayBaseInfo.gwID = gwId;
                realWay.getGatewayBaseInfo.HomeId = Shared.Common.Config.Instance.HomeId;
                realWay.GwId = gwId;
                realWay.HomeId = Shared.Common.Config.Instance.HomeId;
                ZbGateway.GateWayList.Add(realWay);
            }
            zbGateway = realWay;
@@ -907,97 +1066,264 @@
        #endregion
        #region ■ 获取网关GwInfo里面的属性___________
        #region ■ 获取协调器当前信道_________________
        /// <summary>
        /// 获取网关GwInfo里面的属性
        /// 获取协调器当前信道(会有等待延迟,返回-1代表错误)
        /// </summary>
        /// <param name="zbGateway">网关对象</param>
        /// <param name="attributeName">getGwInfo里面属性的名字</param>
        /// <param name="defult">如果获取不到时,设置的默认值</param>
        /// <param name="zbGateway"></param>
        /// <returns></returns>
        public object GetGwInfoAttribute(ZbGateway zbGateway, string attributeName, string defult = "")
        public int GetGatewayChannelId(ZbGateway zbGateway)
        {
            string gwID = this.GetGatewayId(zbGateway);
            var localWay = this.GetLocalGateway(gwID);
            object objValue = null;
            if (localWay == null || localWay.getGwInfo == null)
            ZbGateway realWay = null;
            if (this.GetRealGateway(ref realWay, zbGateway) == false)
            {
                //本地没有记录有这个东西,则直接返回参数的数据
                if (zbGateway.getGwInfo != null)
                //错误:网关对象丢失
                this.ShowTipMsg(Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg));
                return -1;
            }
            int data = -1;
            Action<string, string> action = (topic, message) =>
            {
                var gatewayID = topic.Split('/')[0];
                if (topic == gatewayID + "/" + "ZbGw/GetChannel_Respon")
                {
                    objValue = zbGateway.getGwInfo.GetType().InvokeMember(attributeName, System.Reflection.BindingFlags.GetField, null, zbGateway.getGwInfo, null);
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    data = Convert.ToInt32(jobject["Data"]["Channel"].ToString());
                }
                else
                {
                    return defult;
                }
            }
            else
            };
            realWay.Actions += action;
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 64512 }, { "Command", 8 } };
            realWay.Send("ZbGw/GetChannel", jObject.ToString());
            int TimeOut = 0;
            while (data == -1 && TimeOut < 30)
            {
                //获取本地的属性
                objValue = localWay.getGwInfo.GetType().InvokeMember(attributeName, System.Reflection.BindingFlags.GetField, null, localWay.getGwInfo, null);
                System.Threading.Thread.Sleep(100);
                TimeOut++;
            }
            if (objValue == null)
            realWay.Actions -= action;
            if (data == -1)
            {
                return defult;
            }
            return objValue;
        }
        /// <summary>
        /// 获取网关GatewayBaseInfo里面的属性
        /// </summary>
        /// <param name="zbGateway">网关对象</param>
        /// <param name="attributeName">GatewayBaseInfo里面属性的名字</param>
        /// <param name="defult">如果获取不到时,设置的默认值</param>
        /// <returns></returns>
        public object GetGatewayBaseInfoAttribute(ZbGateway zbGateway, string attributeName, string defult = "")
        {
            string gwID = this.GetGatewayId(zbGateway);
            var localWay = this.GetLocalGateway(gwID);
            object objValue = null;
            if (localWay == null || localWay.getGatewayBaseInfo == null)
            {
                //本地没有记录有这个东西,则直接返回参数的数据
                if (zbGateway.getGatewayBaseInfo != null)
                {
                    objValue = zbGateway.getGatewayBaseInfo.GetType().InvokeMember(attributeName, System.Reflection.BindingFlags.GetField, null, zbGateway.getGatewayBaseInfo, null);
                }
                else
                {
                    return defult;
                }
            }
            else
            {
                //获取本地属性
                objValue = localWay.getGatewayBaseInfo.GetType().InvokeMember(attributeName, System.Reflection.BindingFlags.GetField, null, localWay.getGatewayBaseInfo, null);
                //获取协调器信道失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetGatewayChannelIdFail);
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                this.ShowTipMsg(msg);
            }
            if (objValue == null)
            {
                return defult;
            }
            return objValue;
            return data;
        }
        #endregion
        #region ■ 获取网关ID(有特殊意义)_____________
        #region ■ 获取协调器MAC______________________
        /// <summary>
        /// 获取网关对象里面的网关ID(封装这个方法有特殊意义)
        /// 获取协调器MAC地址(会有等待延迟,返回null代表错误)
        /// </summary>
        /// <param name="zbGateway">网关对象</param>
        /// <param name="zbGateway"></param>
        /// <returns></returns>
        public string GetGatewayId(ZbGateway zbGateway)
        public string GetGatewayCoordinatorMac(ZbGateway zbGateway)
        {
            //这个东西不会为空
            return zbGateway.getGatewayBaseInfo.gwID;
            ZbGateway realWay = null;
            if (this.GetRealGateway(ref realWay, zbGateway) == false)
            {
                //错误:网关对象丢失
                this.ShowTipMsg(Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg));
                return null;
            }
            string data = null;
            Action<string, string> action = (topic, message) =>
            {
                var gatewayID = topic.Split('/')[0];
                if (topic == gatewayID + "/" + "ZbGw/GetMac_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    data = jobject["Data"]["MacAddr"].ToString();
                }
            };
            realWay.Actions += action;
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 64512 }, { "Command", 13 } };
            realWay.Send("ZbGw/GetMac", jObject.ToString());
            int TimeOut = 0;
            while (data == null && TimeOut < 30)
            {
                System.Threading.Thread.Sleep(100);
                TimeOut++;
            }
            realWay.Actions -= action;
            if (data == null)
            {
                //获取协调器Mac失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetGatewayCoordinatorMacFail);
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                this.ShowTipMsg(msg);
            }
            return data;
        }
        #endregion
        #region ■ 获取协调器PanID____________________
        /// <summary>
        /// 获取协调器PanID(会有等待延迟,返回-1代表错误)
        /// </summary>
        /// <param name="zbGateway"></param>
        /// <returns></returns>
        public int GetGatewayPanId(ZbGateway zbGateway)
        {
            ZbGateway realWay = null;
            if (this.GetRealGateway(ref realWay, zbGateway) == false)
            {
                //错误:网关对象丢失
                this.ShowTipMsg(Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg));
                return -1;
            }
            int panId = -1;
            Action<string, string> action = (topic, message) =>
            {
                var gatewayID = topic.Split('/')[0];
                if (topic == gatewayID + "/" + "ZbGw/GetPanId_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    panId = Convert.ToInt32(jobject["Data"]["PANID"].ToString());
                }
            };
            realWay.Actions += action;
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 64512 }, { "Command", 12 } };
            realWay.Send("ZbGw/GetPanId", jObject.ToString());
            int TimeOut = 0;
            while (panId == -1 && TimeOut < 30)
            {
                System.Threading.Thread.Sleep(100);
                TimeOut++;
            }
            realWay.Actions -= action;
            if (panId == -1)
            {
                //获取协调器PanID失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetGatewayPanIDFail);
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                this.ShowTipMsg(msg);
            }
            return panId;
        }
        #endregion
        #region ■ 网关自动备份设置___________________
        /// <summary>
        /// 获取网关自动备份设置(-1:异常 0:关闭 1:打开)
        /// </summary>
        /// <param name="zbGateway"></param>
        /// <returns></returns>
        public int GetGatewayAutoBackupStatu(ZbGateway zbGateway)
        {
            ZbGateway realWay = null;
            if (this.GetRealGateway(ref realWay, zbGateway) == false)
            {
                //错误:网关对象丢失
                this.ShowTipMsg(Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg));
                return -1;
            }
            int statu = -1;
            Action<string, string> action = (topic, message) =>
            {
                var gatewayID = topic.Split('/')[0];
                if (topic == gatewayID + "/GatewayAutoBackup_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    statu = Convert.ToInt32(jobject["Data"]["AutoBackupStatus"].ToString());
                }
            };
            realWay.Actions += action;
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 6205 } };
            var data = new Newtonsoft.Json.Linq.JObject { { "AutoBackup", 1 } };
            jObject.Add("Data", data);
            realWay.Send("GatewayAutoBackup", jObject.ToString());
            int TimeOut = 0;
            while (statu == -1 && TimeOut < 60)
            {
                System.Threading.Thread.Sleep(100);
                TimeOut++;
            }
            realWay.Actions -= action;
            if (statu == -1)
            {
                //获取网关自动备份设置失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetGatewayAutoBackupStatuFail);
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                this.ShowTipMsg(msg);
            }
            return statu;
        }
        /// <summary>
        /// 设置网关自动备份设置
        /// </summary>
        /// <param name="zbGateway"></param>
        /// <param name="statu"></param>
        /// <returns></returns>
        public bool SetGatewayAutoBackupStatu(ZbGateway zbGateway, bool statu)
        {
            ZbGateway realWay = null;
            if (this.GetRealGateway(ref realWay, zbGateway) == false)
            {
                //错误:网关对象丢失
                this.ShowTipMsg(Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg));
                return false;
            }
            int result = -1;
            Action<string, string> action = (topic, message) =>
            {
                var gatewayID = topic.Split('/')[0];
                if (topic == gatewayID + "/GatewayAutoBackup_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    result = Convert.ToInt32(jobject["Data"]["AutoBackupStatus"].ToString());
                }
            };
            realWay.Actions += action;
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 6205 } };
            var data = new Newtonsoft.Json.Linq.JObject { { "AutoBackup", statu == true ? 2 : 3 } };
            jObject.Add("Data", data);
            realWay.Send("GatewayAutoBackup", jObject.ToString());
            int TimeOut = 0;
            while (result == -1 && TimeOut < 60)
            {
                System.Threading.Thread.Sleep(100);
                TimeOut++;
            }
            realWay.Actions -= action;
            if (result == -1)
            {
                //设置网关自动备份失败
                string msg = Language.StringByID(R.MyInternationalizationString.uSetGatewayAutoBackupStatuFail);
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                this.ShowTipMsg(msg);
                return false;
            }
            return true;
        }
        #endregion
@@ -1012,10 +1338,10 @@
        /// <returns></returns>
        public string GetGatewayName(ZbGateway zbGateway, GetNameMode mode = GetNameMode.SpecialGateway)
        {
            string gwId = this.GetGatewayId(zbGateway);
            string gwId = zbGateway.GwId;
            if (this.dicGateway.ContainsKey(gwId) == false)
            {
                return zbGateway.getGatewayBaseInfo.GwName == null ? string.Empty : zbGateway.getGatewayBaseInfo.GwName;
                return zbGateway.GwName;
            }
            var localWay = this.dicGateway[gwId];
@@ -1025,13 +1351,13 @@
                return name;
            }
            if (mode == GetNameMode.SpecialGateway && localWay.getGwInfo != null)
            if (mode == GetNameMode.SpecialGateway)
            {
                string keyName = Common.LocalDevice.deviceModelIdName + this.GetGwInfoAttribute(localWay, "LinuxImageType").ToString();
                if (Common.LocalDevice.Current.dicDeviceDefultNameID.ContainsKey(keyName) == true)
                string keyName = Common.LocalDevice.deviceModelIdName + localWay.LinuxImageType;
                if (LocalDevice.Current.dicDeviceAllNameID.ContainsKey(keyName) == true)
                {
                    //没有名称时,则使用R文件里面设置的东西
                    return Language.StringByID(Common.LocalDevice.Current.dicDeviceDefultNameID[keyName]);
                    //没有名称时,则使用R文件里面设置的默认设备名称
                    return Language.StringByID(LocalDevice.Current.dicDeviceAllNameID[keyName] + 20000);
                }
            }
@@ -1049,42 +1375,66 @@
            {
                return string.Empty;
            }
            return zbGateway.getGatewayBaseInfo.GwName;
            return zbGateway.GwName;
        }
        /// <summary>
        /// 获取网关镜像类型的翻译名字
        /// 设置网关镜像类型的翻译名字
        /// </summary>
        /// <param name="button"></param>
        /// <param name="zbGateway"></param>
        /// <returns></returns>
        public string GetGatewayImageText(ZbGateway zbGateway)
        public void SetGatewayImageText(Button button, ZbGateway zbGateway)
        {
            string gwId = this.GetGatewayId(zbGateway);
            int imageType = -1;
            if (this.dicGateway.ContainsKey(gwId) == false || this.dicGateway[gwId].getGwInfo == null)
            //初始值:无法识别的网关设备
            button.TextID = R.MyInternationalizationString.uUnDistinguishTheGatewayDevice;
            string gwId = zbGateway.GwId;
            if (this.dicGateway.ContainsKey(gwId) == false)
            {
                //如果这个网关没有信息,则从新获取
                var result = this.GetGatewayNewInfo(zbGateway, ShowErrorMode.NO);
                if (result == null)
                if (zbGateway.LinuxImageType != -1)
                {
                    //无法识别的网关设备
                    return Language.StringByID(R.MyInternationalizationString.uUnDistinguishTheGatewayDevice);
                    string keyName = Common.LocalDevice.deviceModelIdName + zbGateway.LinuxImageType;
                    if (Common.LocalDevice.Current.dicDeviceAllNameID.ContainsKey(keyName) == true)
                    {
                        //使用R文件里面设置的东西
                        button.TextID = LocalDevice.Current.dicDeviceAllNameID[keyName];
                    }
                }
                imageType = result.LinuxImageType;
                else
                {
                    //给一个线程去获取它的镜像类型
                    HdlThreadLogic.Current.RunThread(() =>
                    {
                        var result = this.GetGatewayInfo(zbGateway, ShowErrorMode.NO);
                        if (result != null)
                        {
                            //将网关的数据设置到本地缓存中
                            this.SetGatewayDataToLocalMemmory(zbGateway, result, false);
                            HdlThreadLogic.Current.RunMain(() =>
                            {
                                string keyName = Common.LocalDevice.deviceModelIdName + zbGateway.LinuxImageType;
                                if (Common.LocalDevice.Current.dicDeviceAllNameID.ContainsKey(keyName) == true)
                                {
                                    //使用R文件里面设置的东西
                                    button.TextID = LocalDevice.Current.dicDeviceAllNameID[keyName];
                                }
                            });
                        }
                    });
                }
            }
            else
            {
                imageType = Convert.ToInt32(this.GetGwInfoAttribute(this.dicGateway[gwId], "LinuxImageType"));
                string keyName = Common.LocalDevice.deviceModelIdName + this.dicGateway[gwId].LinuxImageType;
                if (Common.LocalDevice.Current.dicDeviceAllNameID.ContainsKey(keyName) == true)
                {
                    //使用R文件里面设置的东西
                    button.TextID = Common.LocalDevice.Current.dicDeviceAllNameID[keyName];
                }
            }
            string keyName = Common.LocalDevice.deviceModelIdName + imageType;
            if (Common.LocalDevice.Current.dicDeviceDefultNameID.ContainsKey(keyName) == true)
            {
                //使用R文件里面设置的东西
                return Language.StringByID(Common.LocalDevice.Current.dicDeviceDefultNameID[keyName]);
            }
            //无法识别的网关设备
            return Language.StringByID(R.MyInternationalizationString.uUnDistinguishTheGatewayDevice);
        }
        #endregion
@@ -1097,32 +1447,13 @@
        /// <param name="zbGateway"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public async Task<ZbGatewayData.GetGwData> GetGatewayNewInfoAsync(ZbGateway zbGateway, ShowErrorMode mode = ShowErrorMode.YES)
        public ZbGatewayData.GetGwData GetGatewayInfo(ZbGateway zbGateway, ShowErrorMode mode = ShowErrorMode.YES)
        {
            ZbGateway realWay = null;
            if (this.GetRealGateway(ref realWay, zbGateway) == false)
            {
                if (mode == ShowErrorMode.YES)
                {
                    string msg = Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg);
                    this.ShowTipMsg(msg);
                }
                return null;
            }
            //获取网关版本信息
            var imageTypeResult = await realWay.GetZbGwInfoAsync();
            //检测网关返回的共通错误状态码
            string error = UserCenterLogic.CheckCommonErrorCode(imageTypeResult);
            if (error != null)
            {
                if (mode == ShowErrorMode.YES)
                {
                    this.ShowTipMsg(error);
                }
                return null;
            }
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 95 } };
            var result = this.SendJobjectDataToGateway(zbGateway, "GetZbGwInfo", jObject.ToString(), "GetZbGwInfo_Respon");
            if (imageTypeResult == null || imageTypeResult.getGwData == null)
            if (result.ErrorMsgDiv != 1)
            {
                if (mode == ShowErrorMode.YES)
                {
@@ -1134,44 +1465,91 @@
                }
                return null;
            }
            string gwID = this.GetGatewayId(zbGateway);
            var getGwInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<ZbGatewayData.GetGwData>(result.ReceiptData);
            string gwID = zbGateway.GwId;
            if (this.dicGateway.ContainsKey(gwID) == true)
            {
                //刷新缓存
                ZbGateway localWay = this.dicGateway[gwID];
                localWay.getGwInfo = imageTypeResult.getGwData;
                localWay.getGatewayBaseInfo.GwName = imageTypeResult.getGwData.GwName;
                localWay.getGatewayBaseInfo.IpAddress = imageTypeResult.getGwData.GwIP;
                localWay.ReSave();
                //将网关的数据设置到本地缓存中
                this.SetGatewayDataToLocalMemmory(localWay, getGwInfo);
            }
            //顺便这个变量也设置一下
            this.SetGatewayDataToLocalMemmory(zbGateway, getGwInfo, false);
            return imageTypeResult.getGwData;
            return getGwInfo;
        }
        /// <summary>
        /// 获取网关信息,非异步,会等待(版本信息,镜像类型,基本信息等。只刷新本地网关的缓存)
        /// 将网关的数据设置到本地缓存中
        /// </summary>
        /// <param name="zbGateway"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public ZbGatewayData.GetGwData GetGatewayNewInfo(ZbGateway zbGateway, ShowErrorMode mode = ShowErrorMode.YES)
        /// <param name="localWay">本地网关</param>
        /// <param name="data">网关数据</param>
        /// <param name="saveFile">是否保存文件</param>
        private void SetGatewayDataToLocalMemmory(ZbGateway localWay, ZbGatewayData.GetGwData data, bool saveFile = true)
        {
            bool bolBreak = false;
            ZbGatewayData.GetGwData result = null;
            new System.Threading.Thread(async () =>
            localWay.GwId = data.GwId;
            localWay.GwName = data.GwName;
            localWay.GwSerialNum = data.GWSN;
            localWay.IsMainGateWay = data.IsDominant == 1 ? true : false;
            localWay.GwIP = data.GwIP;
            localWay.LinuxImageType = data.LinuxImageType;
            localWay.LinuxHardVersion = data.LinuxHWVersion;
            localWay.LinuxFirmwareVersion = data.LinuxFWVersion;
            localWay.CoordinatorHardVersion = data.ZbHWVersion;
            localWay.CoordinatorFirmwareVersion = data.ZbFWVersion;
            localWay.CoordinatorImageId = data.ZbImageType;
            localWay.DriveCodeList = data.DriveCodeList;
            if (saveFile == true)
            {
                result = await this.GetGatewayNewInfoAsync(zbGateway, mode);
                bolBreak = true;
            })
            { IsBackground = true }.Start();
            while (bolBreak == false)
            {
                System.Threading.Thread.Sleep(500);
                localWay.ReSave();
            }
            return result;
        }
        #endregion
        #region ■ 网关房间相关_______________________
        /// <summary>
        /// 获取网关所在的房间
        /// </summary>
        /// <param name="zbGateway">网关对象</param>
        /// <returns></returns>
        public Room GetRoomByGateway(ZbGateway zbGateway)
        {
            return this.GetRoomByGateway(zbGateway.GwId);
        }
        /// <summary>
        /// 获取网关所在的房间
        /// </summary>
        /// <param name="gatewayId">网关ID</param>
        /// <returns></returns>
        public Room GetRoomByGateway(string gatewayId)
        {
            var localGateway = this.GetLocalGateway(gatewayId);
            if (localGateway == null)
            {
                return null;
            }
            return HdlRoomLogic.Current.GetRoomById(localGateway.RoomId);
        }
        /// <summary>
        /// 变更网关房间
        /// </summary>
        /// <param name="zbGateway">网关对象</param>
        /// <param name="roomId">房间ID</param>
        public void ChangedGatewayRoom(ZbGateway zbGateway, string roomId)
        {
            var localGateway = this.GetLocalGateway(zbGateway.GwId);
            if (localGateway != null)
            {
                localGateway.RoomId = roomId;
                localGateway.ReSave();
                //添加备份
                HdlAutoBackupLogic.AddOrEditorFile(localGateway.FilePath);
            }
        }
        #endregion
@@ -1191,7 +1569,7 @@
            //最后再断开mqtt连接
            for (int i = 0; i < list.Count; i++)
            {
                list[i].DisConnect("G");
                list[i].DisConnectLocalMqttClient("G");
            }
            list.Clear();
        }
@@ -1206,75 +1584,83 @@
        /// <param name="zbGateway">网关对象</param>
        /// <param name="mode">错误时,是否显示错误</param>
        /// <returns></returns>
        public async Task<List<FirmwareVersionInfo>> GetGatewayAllNewVersion(ZbGateway zbGateway, ShowErrorMode mode = ShowErrorMode.YES)
        public List<FirmwareVersionInfo> GetGatewayAllNewVersion(ZbGateway zbGateway, ShowErrorMode mode = ShowErrorMode.YES)
        {
            //获取网关版本信息
            var result = await HdlGatewayLogic.Current.GetGatewayNewInfoAsync(zbGateway, mode);
            var result = this.GetGatewayInfo(zbGateway, mode);
            if (result == null)
            {
                return null;
            }
            //使用本地缓存对象
            string gwID = this.GetGatewayId(zbGateway);
            var localWay = this.GetLocalGateway(gwID);
            var localWay = this.GetLocalGateway(zbGateway.GwId);
            if (localWay == null)
            {
                return null;
            }
            //添加网关的升级固件(成不成功都无所谓)
            var flage = await HdlFirmwareUpdateLogic.AddFirmwareVersionInfo(FirmwareLevelType.Linux,
                this.GetGwInfoAttribute(localWay, "LinuxHWVersion").ToString(),
                this.GetGwInfoAttribute(localWay, "LinuxImageType").ToString());
            var flage = HdlFirmwareUpdateLogic.AddFirmwareVersionInfo(FirmwareLevelType.Linux,
                localWay.LinuxHardVersion.ToString(),
                localWay.LinuxImageType.ToString());
            //添加协调器的升级固件(成不成功都无所谓)
            flage = await HdlFirmwareUpdateLogic.AddFirmwareVersionInfo(FirmwareLevelType.Coordinator,
                this.GetGwInfoAttribute(localWay, "ZbHWVersion").ToString(),
                this.GetGwInfoAttribute(localWay, "ZbImageType").ToString());
            //添加协调器的升级固件(成不成功都无所谓) 必须能够联网才行
            if (flage == 1)
            {
                //没网的时候不再处理
                HdlFirmwareUpdateLogic.AddFirmwareVersionInfo(FirmwareLevelType.Coordinator,
                    localWay.CoordinatorHardVersion.ToString(),
                    localWay.CoordinatorImageId.ToString());
            }
            //网关的版本
            var gatewayFirmware = HdlFirmwareUpdateLogic.GetFirmwareMostVersionInfo(FirmwareLevelType.Linux,
                this.GetGwInfoAttribute(localWay, "LinuxHWVersion").ToString(),
                this.GetGwInfoAttribute(localWay, "LinuxImageType").ToString(),
                Convert.ToInt32(this.GetGwInfoAttribute(localWay, "LinuxFWVersion")));
                localWay.LinuxHardVersion.ToString(),
                localWay.LinuxImageType.ToString(),
                localWay.LinuxFirmwareVersion);
            //协调器版本
            var coordinatorFirmware = HdlFirmwareUpdateLogic.GetFirmwareMostVersionInfo(FirmwareLevelType.Coordinator,
                this.GetGwInfoAttribute(localWay, "ZbHWVersion").ToString(),
                this.GetGwInfoAttribute(localWay, "ZbImageType").ToString(),
                Convert.ToInt32(this.GetGwInfoAttribute(localWay, "ZbFWVersion")));
                localWay.CoordinatorHardVersion.ToString(),
                localWay.CoordinatorImageId.ToString(),
                localWay.CoordinatorFirmwareVersion);
            //这个网关需要有虚拟驱动这个东西才行
            FirmwareVersionInfo virtualFirmware = null;
            string linImage = this.GetGwInfoAttribute(localWay, "LinuxImageType").ToString();
            if (linImage != "6")
            {
                //虚拟驱动号
                var listvVode = await HdlGatewayLogic.Current.GetListVDDriveCode(localWay);
                if (listvVode != null && listvVode.Count > 0)
                {
                    //添加虚拟驱动的升级固件(成不成功都无所谓)
                    flage = await HdlFirmwareUpdateLogic.AddFirmwareVersionInfo(FirmwareLevelType.VirtualDevice,
                        listvVode[0].DriveHwVersion.ToString(),
                        listvVode[0].DriveImageType.ToString());
                    //虚拟驱动
                    virtualFirmware = HdlFirmwareUpdateLogic.GetFirmwareMostVersionInfo(FirmwareLevelType.VirtualDevice,
                        listvVode[0].DriveHwVersion.ToString(),
                        listvVode[0].DriveImageType.ToString(),
                        listvVode[0].DriveFwVersion);
                    if (virtualFirmware != null)
                    {
                        virtualFirmware.VirtualCode = listvVode[0].DriveCode;
                    }
                }
            }
            var list = new List<FirmwareVersionInfo>();
            list.Add(gatewayFirmware);
            list.Add(coordinatorFirmware);
            list.Add(virtualFirmware);
            //这个网关需要有虚拟驱动这个东西才行
            if (localWay.LinuxImageType != 6)
            {
                //虚拟驱动号
                foreach (var data in localWay.DriveCodeList)
                {
                    //添加虚拟驱动的升级固件(成不成功都无所谓) 必须能够联网才行
                    if (flage == 1)
                    {
                        HdlFirmwareUpdateLogic.AddFirmwareVersionInfo(FirmwareLevelType.VirtualDevice,
                           data.DriveHwVersion.ToString(),
                           data.DriveImageType.ToString());
                    }
                    //虚拟驱动
                    var virtualFirmware = HdlFirmwareUpdateLogic.GetFirmwareMostVersionInfo(FirmwareLevelType.VirtualDevice,
                        data.DriveHwVersion.ToString(),
                        data.DriveImageType.ToString(),
                        data.DriveFwVersion);
                    if (virtualFirmware != null)
                    {
                        virtualFirmware.VirtualCode = data.DriveCode;
                        list.Add(virtualFirmware);
                    }
                }
            }
            if (list.Count == 2)
            {
                //虚拟驱动如果没有新版本的话,固定添加一个空的
                list.Add(null);
            }
            return list;
        }
@@ -1283,31 +1669,20 @@
        /// </summary>
        /// <param name="zbGateway"></param>
        /// <returns></returns>
        public async Task<List<ZbGatewayData.DriveCodeObj>> GetListVDDriveCode(ZbGateway zbGateway)
        public List<ZbGatewayData.DriveCodeObj> GetListVDDriveCode(ZbGateway zbGateway)
        {
            ZbGateway zbTemp = null;
            if (this.GetRealGateway(ref zbTemp, zbGateway) == false)
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 505 } };
            var result = this.SendJobjectDataToGateway(zbGateway, "VirtualDrive/CatDriveCode", jObject.ToString(), "VirtualDrive/CatDriveCode_Respon");
            if (result.ErrorMsg != null)
            {
                this.ShowTipMsg(result.ErrorMsg);
            }
            if (result.ErrorMsgDiv == 0)
            {
                return null;
            }
            var result = await zbTemp.CheckVDDriveCodeAsync();
            //检测网关返回的共通错误状态码
            string error = UserCenterLogic.CheckCommonErrorCode(result);
            if (error != null)
            {
                this.ShowTipMsg(error);
                return null;
            }
            if (result == null || result.vDriveDriveCodeResponData == null || result.vDriveDriveCodeResponData.DriveCodeList == null)
            {
                return null;
            }
            if (result.vDriveDriveCodeResponData.DriveCodeList.Count > 0)
            {
                return result.vDriveDriveCodeResponData.DriveCodeList;
            }
            return null;
            var dataInfo = JsonConvert.DeserializeObject<ZbGatewayData.VDriveDriveCodeResponData>(result.ReceiptData);
            return dataInfo.DriveCodeList;
        }
        #endregion
@@ -1315,18 +1690,17 @@
        #region ■ 主网关判定_________________________
        /// <summary>
        /// 判断是否主网关(1:主网关 0:不在线 -1:远程模式,不存在啥主网关的说法)
        /// 判断是否主网关(1:主网关 0:不在线 2:子网关)
        /// </summary>
        /// <param name="zbGateway">网关对象</param>
        /// <returns></returns>
        public int IsMainGateway(ZbGateway zbGateway)
        {
            string gwID = this.GetGatewayId(zbGateway);
            return this.IsMainGateway(gwID);
            return this.IsMainGateway(zbGateway.GwId);
        }
        /// <summary>
        /// 判断是否主网关(1:主网关 0:不在线 -1:远程模式,不存在啥主网关的说法)
        /// 判断是否主网关(1:主网关 0:不在线 2:子网关)
        /// </summary>
        /// <param name="waiID">网关id</param>
        /// <returns></returns>
@@ -1337,7 +1711,7 @@
            {
                return 0;
            }
            return zbGateway.IsMainGateWay == true ? 1 : 0;
            return zbGateway.IsMainGateWay == true ? 1 : 2;
        }
        #endregion
@@ -1345,73 +1719,78 @@
        #region ■ 设置网关图片_______________________
        /// <summary>
        /// 设置真实网关的图片,规格:915X492
        /// 设置真实网关的图片
        /// </summary>
        /// <param name="button"></param>
        /// <param name="zbGateway"></param>
        public void SetRealGatewayPictrue(Button button, ZbGateway zbGateway)
        {
            string gwID = this.GetGatewayId(zbGateway);
            var localWay = this.GetLocalGateway(gwID);
            if (localWay == null || localWay.getGwInfo == null)
            var localWay = this.GetLocalGateway(zbGateway.GwId);
            if (localWay == null)
            {
                //给一个线程去获取它的镜像类型
                new System.Threading.Thread(async () =>
                if (zbGateway.LinuxImageType != -1)
                {
                    var result = await this.GetGatewayNewInfoAsync(zbGateway, ShowErrorMode.NO);
                    if (result != null)
                    button.UnSelectedImagePath = "Gateway/RealGateway" + zbGateway.LinuxImageType + ".png";
                }
                else
                {
                    //给一个线程去获取它的镜像类型
                    HdlThreadLogic.Current.RunThread(() =>
                    {
                        Application.RunOnMainThread(() =>
                        var result = this.GetGatewayInfo(zbGateway, ShowErrorMode.NO);
                        if (result != null)
                        {
                            if (button != null)
                            //将网关的数据设置到本地缓存中
                            this.SetGatewayDataToLocalMemmory(zbGateway, result, false);
                            HdlThreadLogic.Current.RunMain(() =>
                            {
                                button.UnSelectedImagePath = "Gateway/RealGateway" + result.LinuxImageType + ".png";
                            }
                        });
                    }
                })
                { IsBackground = true }.Start();
                            });
                        }
                    });
                }
            }
            else
            {
                button.UnSelectedImagePath = "Gateway/RealGateway" + this.GetGwInfoAttribute(localWay, "LinuxImageType").ToString() + ".png";
                button.UnSelectedImagePath = "Gateway/RealGateway" + localWay.LinuxImageType + ".png";
            }
        }
        /// <summary>
        /// 设置网关图标,规格:110X110
        /// 设置网关图标
        /// </summary>
        /// <param name="button"></param>
        /// <param name="zbGateway"></param>
        public void SetGatewayIcon(Button button, ZbGateway zbGateway)
        {
            string gwID = this.GetGatewayId(zbGateway);
            var localWay = this.GetLocalGateway(gwID);
            if (localWay == null || localWay.getGwInfo == null)
            var localWay = this.GetLocalGateway(zbGateway.GwId);
            if (localWay == null)
            {
                //给一个线程去获取它的镜像类型
                new System.Threading.Thread(async () =>
                if (zbGateway.LinuxImageType != -1)
                {
                    var result = await this.GetGatewayNewInfoAsync(zbGateway, ShowErrorMode.NO);
                    if (result != null)
                    button.UnSelectedImagePath = "Gateway/GatewayIcon" + zbGateway.LinuxImageType + ".png";
                }
                else
                {
                    //给一个线程去获取它的镜像类型
                    HdlThreadLogic.Current.RunThread(() =>
                    {
                        Application.RunOnMainThread(() =>
                        var result = this.GetGatewayInfo(zbGateway, ShowErrorMode.NO);
                        if (result != null)
                        {
                            if (button != null)
                            //将网关的数据设置到本地缓存中
                            this.SetGatewayDataToLocalMemmory(zbGateway, result, false);
                            HdlThreadLogic.Current.RunMain(() =>
                            {
                                button.UnSelectedImagePath = "Gateway/GatewayIcon" + result.LinuxImageType + ".png";
                                button.SelectedImagePath = "Gateway/GatewayIcon" + result.LinuxImageType + "Selected.png";
                            }
                        });
                    }
                })
                { IsBackground = true }.Start();
                            });
                        }
                    });
                }
            }
            else
            {
                string linType = this.GetGwInfoAttribute(localWay, "LinuxImageType").ToString();
                button.UnSelectedImagePath = "Gateway/GatewayIcon" + linType + ".png";
                button.SelectedImagePath = "Gateway/GatewayIcon" + linType + "Selected.png";
                button.UnSelectedImagePath = "Gateway/GatewayIcon" + localWay.LinuxImageType + ".png";
            }
        }
@@ -1426,8 +1805,7 @@
        /// <returns></returns>
        public bool IsGatewayExist(ZbGateway zbGateway)
        {
            string gwID = this.GetGatewayId(zbGateway);
            return this.IsGatewayExist(gwID);
            return this.IsGatewayExist(zbGateway.GwId);
        }
        /// <summary>
@@ -1446,13 +1824,13 @@
        #endregion
        #region ■ 测试网关___________________________
        #region ■ 网关定位___________________________
        /// <summary>
        /// 发送测试指令到设备(网关LED闪烁识别)
        /// 发送指令到网关进行定位(网关LED闪烁识别)
        /// </summary>
        /// <param name="zbGateway"></param>
        public void SetTestCommand(ZbGateway zbGateway)
        public void SetFixedPositionCommand(ZbGateway zbGateway)
        {
            ZbGateway realWay = null;
            if (this.GetRealGateway(ref realWay, zbGateway) == false)
@@ -1460,26 +1838,568 @@
                return;
            }
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 85 } };
            realWay.Send("GwLinuxLocate_Respon", jObject.ToString());
            if (this.IsGatewayExist(zbGateway) == true)
            {
                realWay.Send("GwLinuxLocate_Respon", jObject.ToString());
            }
            else
            {
                //如果这个网关还没有绑定的话,则强制使用本地连接
                realWay.SendLocation("GwLinuxLocate_Respon", System.Text.Encoding.UTF8.GetBytes(jObject.ToString()));
            }
        }
        #endregion
        #region ■ 一般方法___________________________
        #region ■ 从云端获取全部网关列表ID___________
        /// <summary>
        /// 从云端获取全部网关列表ID
        /// </summary>
        /// <returns>从云端获取全部网关列表ID</returns>
        public Dictionary<string, GatewayResult> GetGateWayListFromDataBase()
        {
            Dictionary<string, GatewayResult> dicDbGateway = null;
            if (UserCenterResourse.UserInfo.AuthorityNo == 3)
            {
                //成员
                return dicDbGateway;
            }
            bool canBreak = false;
            HdlThreadLogic.Current.RunThread(() =>
            {
                List<string> list = new List<string>() { "NotCheck" };
                //设置访问接口的参数
                var pra = new GetGatewayPra();
                pra.ReqDto.PageSetting.Page = 1;
                pra.ReqDto.PageSetting.PageSize = 999;
                //获取控制主人账号的Token
                pra.ReqDto.LoginAccessToken = UserCenterLogic.GetConnectMainToken();
                var result = UserCenterLogic.GetResponseDataByRequestHttps("App/GetSingleHomeGatewayPagger", true, pra, list);
                if (string.IsNullOrEmpty(result) == true)
                {
                    canBreak = true;
                    return;
                }
                var infoResult = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGatewayResult>(result);
                Dictionary<string, GatewayResult> dic = new Dictionary<string, GatewayResult>();
                foreach (var data in infoResult.PageData)
                {
                    dic[data.GatewayUniqueId] = data;
                }
                dicDbGateway = dic;
                canBreak = true;
            });
            int count = 0;
            while (canBreak == false)
            {
                System.Threading.Thread.Sleep(200);
                count++;
                if (count == 25)
                {
                    //如果5秒还不能获取得到数据,则中断此次操作
                    break;
                }
            }
            return dicDbGateway;
        }
        #endregion
        #region ■ 设置网关经纬度_____________________
        /// <summary>
        /// 弹出网关不在线的
        /// </summary>
        private void ShowGatewayNotOnlineMsg()
        /// 设置网关经纬度
        /// </summary>
        /// <param name="gateway">网关对象</param>
        /// <param name="Longitude">经度</param>
        /// <param name="Latitude">维度</param>
        /// <param name="mode">显示错误</param>
        /// <returns></returns>
        public bool SetGatewaySite(ZbGateway gateway, double Longitude, double Latitude, ShowErrorMode mode)
        {
            Application.RunOnMainThread(() =>
            ZbGateway realWay = null;
            if (this.GetRealGateway(ref realWay, gateway) == false)
            {
                //网关连接失败,请确认网络
                string msg = Language.StringByID(R.MyInternationalizationString.uGatewayIsNotLinkAndCheckNetwork);
                var control = new ShowMsgControl(ShowMsgType.Tip, msg);
                control.Show();
                if (mode == ShowErrorMode.YES)
                {
                    //错误:网关对象丢失
                    string msg = Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg);
                    this.ShowTipMsg(msg);
                }
                return false;
            }
            int result = -1;
            Action<string, string> action = (topic, message) =>
            {
                var gatewayID = topic.Split('/')[0];
                if (topic == gatewayID + "/" + "Logic/SetSite_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    result = Convert.ToInt32(jobject["Data"]["Result"].ToString());
                }
            };
            realWay.Actions += action;
            //两位小数
            Longitude = Math.Round(Longitude, 2);
            Latitude = Math.Round(Latitude, 2);
            int intLongitude = Convert.ToInt32(Longitude.ToString().Replace(".", string.Empty));
            int intLatitude = Convert.ToInt32(Latitude.ToString().Replace(".", string.Empty));
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 2013 } };
            var data = new Newtonsoft.Json.Linq.JObject { { "Longitude", intLongitude }, { "Latitude", intLatitude } };
            jObject.Add("Data", data);
            if (this.IsGatewayExist(gateway) == true)
            {
                realWay.Send("Logic/SetSite", jObject.ToString());
            }
            else
            {
                //如果这个网关还没有绑定的话,则强制使用本地连接
                realWay.SendLocation("Logic/SetSite", System.Text.Encoding.UTF8.GetBytes(jObject.ToString()));
            }
            int TimeOut = 0;
            while (result == -1 && TimeOut < 30)
            {
                System.Threading.Thread.Sleep(100);
                TimeOut++;
            }
            realWay.Actions -= action;
            if (result != 0)
            {
                if (mode == ShowErrorMode.YES)
                {
                    //设置网关经纬度失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uSetGatewaySiteFail);
                    if (result == -1)
                    {
                        msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                    }
                    this.ShowTipMsg(msg);
                }
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 解绑云端网关_______________________
        /// <summary>
        /// 解绑云端绑定的网关
        /// </summary>
        /// <param name="strWayId"></param>
        public bool DeleteDataBaseGateway(string strWayId)
        {
            var Pra = new DeleteGatewayPra();
            Pra.BindGateways.Add(strWayId);
            //获取控制主人账号的Token
            Pra.LoginAccessToken = UserCenterLogic.GetConnectMainToken();
            List<string> listNotShowError = new List<string>() { "NoExist", "NoBind", "NoRecord" };
            bool result = UserCenterLogic.GetResultStatuByRequestHttps("App/ReleaseGatewayToHome", true, Pra, listNotShowError);
            if (result == false)
            {
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 断网备份及绑定网关ID_______________
        /// <summary>
        /// 在没网的情况下备份网关ID
        /// </summary>
        /// <param name="zbGateway"></param>
        public void BackupGatewayIdOnNotNetwork(ZbGateway zbGateway)
        {
            var strId = zbGateway.GwId;
            if (listBackupGwId.Contains(strId) == false)
            {
                listBackupGwId.Add(strId);
                //备份
                var strData = Newtonsoft.Json.JsonConvert.SerializeObject(listBackupGwId);
                var byteData = System.Text.Encoding.UTF8.GetBytes(strData);
                Global.WriteFileToDirectoryByBytes(DirNameResourse.LocalMemoryDirectory, DirNameResourse.BackupGatewayIdFile, byteData);
            }
        }
        /// <summary>
        /// 重新发送命令去绑定断网情况下备份的网关
        /// </summary>
        public void ResetComandToBindBackupGateway()
        {
            HdlThreadLogic.Current.RunThread(() =>
            {
                var fileData = Global.ReadFileByDirectory(DirNameResourse.LocalMemoryDirectory, DirNameResourse.BackupGatewayIdFile);
                if (fileData == null)
                {
                    return;
                }
                this.listBackupGwId = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(System.Text.Encoding.UTF8.GetString(fileData));
                var listTempId = new List<string>();
                listTempId.AddRange(this.listBackupGwId);
                //调用接口,绑定网关
                var bindGateway = new BindGatewayPra();
                //获取控制主人账号的Token
                bindGateway.LoginAccessToken = UserCenterLogic.GetConnectMainToken();
                foreach (var gwId in listTempId)
                {
                    bindGateway.BindGateways.Clear();
                    bindGateway.BindGateways.Add(gwId);
                    var result = UserCenterLogic.GetResultCodeByRequestHttps("App/BindGatewayToHome", true, bindGateway);
                    if (result == "Success")
                    {
                        this.listBackupGwId.Remove(gwId);
                    }
                    if (result == "Error")
                    {
                        break;
                    }
                }
                if (this.listBackupGwId.Count == 0)
                {
                    //如果没有了内容,则删除文件
                    string file = UserCenterLogic.CombinePath(DirNameResourse.LocalMemoryDirectory, DirNameResourse.BackupGatewayIdFile);
                    if (System.IO.File.Exists(file) == true)
                    {
                        System.IO.File.Delete(file);
                    }
                }
                else
                {
                    //备份
                    var strData = Newtonsoft.Json.JsonConvert.SerializeObject(listBackupGwId);
                    var byteData = System.Text.Encoding.UTF8.GetBytes(strData);
                    Global.WriteFileToDirectoryByBytes(DirNameResourse.LocalMemoryDirectory, DirNameResourse.BackupGatewayIdFile, byteData);
                }
            });
        }
        #endregion
        #region ■ 发送网关命令给网关_________________
        /// <summary>
        /// 发送数据到网关,并接受网关返回的数据(ReceiptData为返回值)
        /// </summary>
        /// <param name="gateway">网关对象</param>
        /// <param name="sendTopic">发送的主题</param>
        /// <param name="sendData">需要发送的数据  JObject.ToString()的东西</param>
        /// <param name="receiptTopic">指定接收哪个主题</param>
        /// <param name="waitTime">超时时间(秒)</param>
        /// <returns>网关返回的数据</returns>
        public ReceiptGatewayResult SendJobjectDataToGateway(ZbGateway gateway, string sendTopic, string sendData, string receiptTopic, int waitTime = 5)
        {
            var reResult = new ReceiptGatewayResult();
            ZbGateway myGateway = null;
            if (this.GetRealGateway(ref myGateway, gateway) == false)
            {
                //获取网关对象失败
                reResult.ErrorMsg = Language.StringByID(R.MyInternationalizationString.uGetGatewayTagartFail);
                reResult.ErrorMsgDiv = -1;
                return reResult;
            }
            //网关ID
            string gatewayID = gateway.GwId;
            //错误主题
            string errorTopic = gatewayID + "/" + "Error_Respon";
            //检测对象的主题
            string checkTopic = gatewayID + "/" + receiptTopic;
            Action<string, string> receiptAction = (topic, message) =>
            {
                var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                //网关回复错误
                if (topic == errorTopic)
                {
                    var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                    reResult.ErrorMsg = HdlCheckLogic.Current.CheckCommonErrorCode(temp.Error);
                }
                //如果是指定的主题
                if (topic == checkTopic)
                {
                    reResult.ReceiptData = jobject["Data"].ToString();
                }
            };
            myGateway.Actions += receiptAction;
            //发送数据
            myGateway.Send(sendTopic, sendData);
            //超时时间
            int TimeOut = 0;
            waitTime = 20 * waitTime;
            while (reResult.ReceiptData == null && TimeOut < waitTime)
            {
                //全部接收才退出
                System.Threading.Thread.Sleep(50);
                TimeOut++;
            }
            myGateway.Actions -= receiptAction;
            receiptAction = null;
            if (reResult.ReceiptData == null)
            {
                reResult.ErrorMsgDiv = 0;
            }
            return reResult;
        }
        #endregion
        #region ■ 网关监视___________________________
        /// <summary>
        /// 当前的网络连接模式
        /// </summary>
        private GatewayConnectMode nowGwConnectMode = GatewayConnectMode.None;
        /// <summary>
        /// 是否存在网关正在升级
        /// </summary>
        private bool hadGatewayUpdate = false;
        /// <summary>
        /// 当网关的连接方式改变时,记录当前的连接方式
        /// </summary>
        /// <param name="connectMode">网关变更后的连接方式</param>
        public void CheckGatewayByConnectChanged(GatewayConnectMode connectMode)
        {
            this.nowGwConnectMode = connectMode;
        }
        /// <summary>
        /// 开启检测网关在线状态的线程(此方法是给设备列表界面用的)
        /// </summary>
        /// <param name="frameLayout">界面对象</param>
        public void StartCheckGatewayOnlineThread(EditorCommonForm frameLayout)
        {
            HdlThreadLogic.Current.RunThread(() =>
            {
                int waitCount = 0;
                //如果住宅ID变更了,则不再处理
                while (frameLayout.Parent != null && Config.Instance.HomeId != string.Empty)
                {
                    System.Threading.Thread.Sleep(1000);
                    if (this.hadGatewayUpdate == true)
                    {
                        //网关正在升级,不需要操作
                        continue;
                    }
                    waitCount++;
                    if (this.nowGwConnectMode == GatewayConnectMode.Remote)
                    {
                        //远程每20秒检测一次
                        if (waitCount < 20) { continue; }
                    }
                    else if (this.nowGwConnectMode == GatewayConnectMode.WIFI)
                    {
                        //局域网每5秒检测一次
                        if (waitCount < 5) { continue; }
                    }
                    waitCount = 0;
                    //获取前回网关的在线状态
                    Dictionary<string, bool> dicOldOnline = this.GetOldGatewayOnlineStatu();
                    if (dicOldOnline == null)
                    {
                        //则不处理
                        continue;
                    }
                    //可以叫4G
                    if (this.nowGwConnectMode == GatewayConnectMode.Remote)
                    {
                        //在远程的条件下,检查网关的在线状态
                        this.CheckGatewayStatuByRemote(dicOldOnline);
                    }
                    //WIFI
                    else if (this.nowGwConnectMode == GatewayConnectMode.WIFI)
                    {
                        //在WIFI的条件下,检查网关的在线状态
                        this.CheckGatewayStatuByWIFI(dicOldOnline);
                    }
                }
            }, ShowErrorMode.NO);
        }
        /// <summary>
        /// 在WIFI的条件下,检查网关的在线状态
        /// </summary>
        private void CheckGatewayStatuByWIFI(Dictionary<string, bool> dicOldOnline)
        {
            //从网关获取全部的网关
            List<ZbGateway> list = this.GetAllGatewayFromGateway();
            foreach (var way in list)
            {
                //将标识置为false
                way.GatewayOnlineFlage = false;
            }
            //等个2秒
            System.Threading.Thread.Sleep(2000);
            //2020.05.25追加:此住宅是否拥有网关在线
            var hadGwOnline = false;
            foreach (var way in list)
            {
                if (dicOldOnline.ContainsKey(way.GwId) == true)
                {
                    if (way.GatewayOnlineFlage == true)
                    {
                        //有一个网关在线,即在线
                        hadGwOnline = true;
                        break;
                    }
                }
            }
            foreach (var way in list)
            {
                string gwId = way.GwId;
                if (dicOldOnline.ContainsKey(gwId) == true)
                {
                    //网关也不多,直接推送吧
                    this.PushGatewayOnlineStatuToForm(gwId, way.GatewayOnlineFlage, hadGwOnline);
                }
                else
                {
                    //没有包含,默认为false
                    this.PushGatewayOnlineStatuToForm(gwId, false, hadGwOnline);
                }
            }
        }
        /// <summary>
        /// 在远程的条件下,检查网关的在线状态
        /// </summary>
        private void CheckGatewayStatuByRemote(Dictionary<string, bool> dicOldOnline)
        {
            //获取云端上面的网关
            Dictionary<string, GatewayResult> dicDbGateway = HdlGatewayLogic.Current.GetGateWayListFromDataBase();
            if (dicDbGateway == null)
            {
                //如果网络不通,则也往下走
                dicDbGateway = new Dictionary<string, GatewayResult>();
            }
            //2020.05.25追加:此住宅是否拥有网关在线
            var hadGwOnline = false;
            foreach (var gwId in dicOldOnline.Keys)
            {
                //如果云端上面有这个网关
                if (dicDbGateway.ContainsKey(gwId) == true
                    && dicDbGateway[gwId].MqttOnlineStatus == true)
                {
                    //有一个网关在线,即在线
                    hadGwOnline = true;
                    break;
                }
            }
            foreach (var gwId in dicOldOnline.Keys)
            {
                //如果云端上面有这个网关
                if (dicDbGateway.ContainsKey(gwId) == true)
                {
                    //网关也不多,直接推送
                    this.PushGatewayOnlineStatuToForm(gwId, dicDbGateway[gwId].MqttOnlineStatus, hadGwOnline);
                }
                else
                {
                    //云端不包含的,当不在线处理
                    this.PushGatewayOnlineStatuToForm(gwId, false, hadGwOnline);
                }
            }
        }
        /// <summary>
        /// 获取前回网关的在线状态
        /// </summary>
        /// <returns></returns>
        private Dictionary<string, bool> GetOldGatewayOnlineStatu()
        {
            if (this.dicGateway.Count == 0)
            {
                //没有网关,则不处理
                return null;
            }
            try
            {
                var dicOldOnline = new Dictionary<string, bool>();
                //如果在循环的过程中,动了里面的东西,报错则不理它,下一回合
                foreach (var zbway in this.dicGateway.Values)
                {
                    //获取前回的在线状态
                    dicOldOnline[zbway.GwId] = zbway.GatewayOnlineFlage;
                }
                return dicOldOnline;
            }
            catch { return null; }
        }
        /// <summary>
        /// 将变化的网关推送到界面上
        /// </summary>
        /// <param name="gwId"></param>
        /// <param name="online"></param>
        /// <param name="hadGwOnline">2020.05.25追加:此住宅是否拥有网关在线</param>
        private void PushGatewayOnlineStatuToForm(string gwId, bool online, bool hadGwOnline)
        {
            try
            {
                for (int i = 0; i < UserCenterResourse.listActionFormId.Count; i++)
                {
                    string formId = UserCenterResourse.listActionFormId[i];
                    if (UserCenterResourse.DicActionForm.ContainsKey(formId) == false)
                    {
                        continue;
                    }
                    //网关在线推送
                    var zbway = this.GetLocalGateway(gwId);
                    if (zbway != null)
                    {
                        //切换住宅时,这个东西有可能是null
                        zbway.GatewayOnlineFlage = online;
                        UserCenterResourse.DicActionForm[formId]?.GatewayOnlinePush(zbway, online, hadGwOnline);
                    }
                }
            }
            catch { }
        }
        /// <summary>
        /// 设置存在网关正在升级的标识
        /// </summary>
        /// <param name="update">是否有网关在升级</param>
        public void SetHadGatewayUpdateFlage(bool update)
        {
            this.hadGatewayUpdate = update;
        }
        #endregion
        #region ■ 一般方法___________________________
        /// <summary>
        /// 显示错误信息窗口
@@ -1505,648 +2425,6 @@
                var contr = new ShowMsgControl(ShowMsgType.Tip, msg);
                contr.Show();
            });
        }
        #endregion
        #region ■ 网关监视___________________________
        #region ■ 变量声明___________________________
        /// <summary>
        /// 当前的网络连接模式
        /// </summary>
        private GatewayConnectMode nowGwConnectMode = GatewayConnectMode.None;
        /// <summary>
        /// 是否存在网关正在升级
        /// </summary>
        private bool hadGatewayUpdate = false;
        #endregion
        #region ■ 网关连接方式变更___________________
        /// <summary>
        /// 当网关的连接方式改变时,检测网关,然后显示特效
        /// </summary>
        /// <param name="connectMode">网关变更后的连接方式</param>
        public void CheckGatewayByConnectChanged(GatewayConnectMode connectMode)
        {
            if (this.nowGwConnectMode == connectMode || this.hadGatewayUpdate == true)
            {
                //相同的连接模式,或者有网关正在升级,则不需要操作
                return;
            }
            //没有网络
            if (connectMode == GatewayConnectMode.NoLine)
            {
                nowGwConnectMode = GatewayConnectMode.NoLine;
                //在远程的条件下,检查网关的在线状态(网络变更时触发)
            }
            //可以叫4G
            else if (connectMode == GatewayConnectMode.Remote)
            {
                nowGwConnectMode = GatewayConnectMode.Remote;
                //在远程的条件下,检查网关的在线状态(网络变更时触发)
                this.CheckGatewayStatuByRemote();
            }
            //WIFI
            else if (connectMode == GatewayConnectMode.WIFI)
            {
                nowGwConnectMode = GatewayConnectMode.WIFI;
                //在WIFI的条件下,检查网关的在线状态(网络变更时触发)
                this.CheckGatewayStatuByWIFI();
            }
        }
        #endregion
        #region ■ 检查网关(WIFI)_____________________
        /// <summary>
        /// 在WIFI的条件下,检查网关的在线状态(网络变更时触发)
        /// </summary>
        private void CheckGatewayStatuByWIFI()
        {
            if (this.dicGateway.Count == 0)
            {
                //如果本地都没有网关的话,不需要处理
                return;
            }
            new System.Threading.Thread(() =>
            {
                var dicStatu = this.GetNowOnlineStatuBeforeCheck();
                //等个3秒,准备一下
                System.Threading.Thread.Sleep(3000);
                if (nowGwConnectMode != GatewayConnectMode.WIFI)
                {
                    //网络临时变更??
                    return;
                }
                //从网关获取全部的网关
                List<ZbGateway> list = this.GetAllGatewayFromGateway();
                foreach (var way in list)
                {
                    string gwId = this.GetGatewayId(way);
                    if (this.dicGateway.ContainsKey(gwId) == true)
                    {
                        //刷新一下缓存
                        this.dicGateway[gwId].GatewayOnlineFlage = way.GatewayOnlineFlage;
                    }
                    if (this.CheckGatewayOnlineByFlag(way) == true)
                    {
                        //网关在线
                        dicStatu[gwId] = true;
                    }
                }
                //将变化的网关推送到界面上
                this.PushGatewayOnlineStatuToForm(dicStatu);
            })
            { IsBackground = true }.Start();
        }
        #endregion
        #region ■ 检查网关(4G)_______________________
        /// <summary>
        /// 在远程的条件下,检查网关的在线状态(网络变更时触发)
        /// </summary>
        private void CheckGatewayStatuByRemote()
        {
            if (this.dicGateway.Count == 0)
            {
                //如果本地都没有网关的话,不需要处理
                return;
            }
            new System.Threading.Thread(() =>
            {
                //先获取现在全部的网关,初期値设置为不在线
                var dicStatu = this.GetNowOnlineStatuBeforeCheck();
                //获取云端上面的网关
                Dictionary<string, GatewayResult> dicDbGateway = HdlGatewayLogic.Current.GetGateWayListFromDataBase();
                if (nowGwConnectMode != GatewayConnectMode.Remote || dicDbGateway == null)
                {
                    //网络临时变更??
                    return;
                }
                bool hadOnline = false;
                lock (dicGateway)
                {
                    foreach (var way in this.dicGateway.Values)
                    {
                        //循环处理本地全部的网关列表
                        string gwId = this.GetGatewayId(way);
                        if (dicDbGateway.ContainsKey(gwId) == true//如果云端上面有这个网关
                            && dicDbGateway[gwId].MqttOnlineStatus == true//如果云端上面这个网关是在线的
                            )
                        {
                            dicGateway[gwId].GatewayOnlineFlage = true;
                            //它是在线的
                            dicStatu[gwId] = true;
                            hadOnline = true;
                        }
                    }
                }
                //将变化的网关推送到界面上
                this.PushGatewayOnlineStatuToForm(dicStatu);
                //如果没有网关在线
                if (hadOnline == false)
                {
                    //远程连接超时,没有网关在线
                    string msg = Language.StringByID(R.MyInternationalizationString.uRemoteTimeOutAndNotGatewaiOnline);
                    //this.ShowTipMsg(msg);
                }
            })
            { IsBackground = true }.Start();
        }
        #endregion
        #region ■ 检查网关(无网络)___________________
        /// <summary>
        /// 在远程的条件下,检查网关的在线状态(网络变更时触发)
        /// </summary>
        private void CheckGatewayStatuByNotNet()
        {
            //当前无网络连接,请确认网络
            string msg = Language.StringByID(R.MyInternationalizationString.uNowIsDonotNetworkAndCheckNetwork);
            this.ShowTipMsg(msg);
        }
        #endregion
        #region ■ 网关推送___________________________
        /// <summary>
        /// 将变化的网关推送到界面上
        /// </summary>
        /// <param name="dicStatu"></param>
        private void PushGatewayOnlineStatuToForm(Dictionary<string, bool> dicStatu)
        {
            List<ZbGateway> listChange = new List<ZbGateway>();
            List<bool> listChangeStatu = new List<bool>();
            foreach (string gwid in dicStatu.Keys)
            {
                //网关不多,直接推送,不判断是否改变了
                ZbGateway zbGateway = this.GetLocalGateway(gwid);
                if (zbGateway != null)
                {
                    listChange.Add(zbGateway);
                    listChangeStatu.Add(dicStatu[gwid]);
                    zbGateway.GatewayOnlineFlage = dicStatu[gwid];
                }
            }
            if (listChange.Count == 0)
            {
                return;
            }
            //获取当前接受在线状态推送的界面
            var listForm = new List<CommonFormBase>();
            listForm.AddRange(UserCenterResourse.listGatewayOnlinePushForm);
            if (listForm.Count > 0)
            {
                for (int i = 0; i < listChange.Count; i++)
                {
                    foreach (var form in listForm)
                    {
                        form?.GatewayOnlinePush(listChange[i], listChangeStatu[i]);
                    }
                }
            }
        }
        #endregion
        #region ■ 一般方法___________________________
        /// <summary>
        /// 设置存在网关正在升级的标识
        /// </summary>
        /// <param name="update">是否有网关在升级</param>
        public void SetHadGatewayUpdateFlage(bool update)
        {
            this.hadGatewayUpdate = update;
        }
        /// <summary>
        /// 在网络连接变更之后,网关连接检测之前,设置全部网关为离线状态(以本地网关为标准)
        /// </summary>
        /// <returns></returns>
        private Dictionary<string, bool> GetNowOnlineStatuBeforeCheck()
        {
            //先获取现在全部的网关
            List<ZbGateway> listOldGateway = this.GetAllGatewayFromGateway();
            var dicOldZb = new Dictionary<string, ZbGateway>();
            foreach (var zb in listOldGateway)
            {
                string gwID = this.GetGatewayId(zb);
                dicOldZb[gwID] = zb;
            }
            var dicStatu = new Dictionary<string, bool>();
            lock (dicGateway)
            {
                foreach (string gwId in this.dicGateway.Keys)
                {
                    if (dicOldZb.ContainsKey(gwId) == true)
                    {
                        //标记为不在线
                        this.SetGatewayNotOnLineFlag(dicOldZb[gwId]);
                    }
                    dicStatu[gwId] = false;
                }
            }
            return dicStatu;
        }
        #endregion
        #endregion
        #region ■ 从云端获取全部网关列表ID___________
        /// <summary>
        /// 从云端获取全部网关列表ID
        /// </summary>
        /// <returns>从云端获取全部网关列表ID</returns>
        public Dictionary<string, GatewayResult> GetGateWayListFromDataBase()
        {
            Dictionary<string, GatewayResult> dicDbGateway = null;
            if (UserCenterResourse.UserInfo.AuthorityNo == 3)
            {
                //成员
                return dicDbGateway;
            }
            bool canBreak = false;
            new System.Threading.Thread(async () =>
            {
                List<string> list = new List<string>() { "NotSetAgain" };
                //设置访问接口的参数
                var pra = new GetGatewayPra();
                pra.ReqDto.PageSetting.Page = 1;
                pra.ReqDto.PageSetting.PageSize = 999;
                //获取控制主人账号的Token
                pra.ReqDto.LoginAccessToken = UserCenterLogic.GetConnectMainToken();
                var result = await UserCenterLogic.GetResponseDataByRequestHttps("App/GetSingleHomeGatewayPagger", true, pra, list);
                if (string.IsNullOrEmpty(result) == true)
                {
                    canBreak = true;
                    return;
                }
                var infoResult = Newtonsoft.Json.JsonConvert.DeserializeObject<GetGatewayResult>(result);
                Dictionary<string, GatewayResult> dic = new Dictionary<string, GatewayResult>();
                foreach (var data in infoResult.PageData)
                {
                    dic[data.GatewayUniqueId] = data;
                }
                dicDbGateway = dic;
                canBreak = true;
            })
            { IsBackground = true }.Start();
            int count = 0;
            while (canBreak == false)
            {
                System.Threading.Thread.Sleep(200);
                count++;
                if (count == 25)
                {
                    //如果5秒还不能获取得到数据,则中断此次操作
                    break;
                }
            }
            return dicDbGateway;
        }
        #endregion
        #region ■ 解绑云端网关_______________________
        /// <summary>
        /// 解绑云端绑定的网关
        /// </summary>
        /// <param name="strWayId"></param>
        public async Task<bool> DeleteDataBaseGateway(string strWayId)
        {
            var Pra = new DeleteGatewayPra();
            Pra.BindGateways.Add(strWayId);
            //获取控制主人账号的Token
            Pra.LoginAccessToken = UserCenterLogic.GetConnectMainToken();
            List<string> listNotShowError = new List<string>() { "NoExist", "NoBind", "NoRecord" };
            bool result = await UserCenterLogic.GetResultStatuByRequestHttps("App/ReleaseGatewayToHome", true, Pra, listNotShowError);
            if (result == false)
            {
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 断网备份及绑定网关ID_______________
        /// <summary>
        /// 在没网的情况下备份网关ID
        /// </summary>
        /// <param name="zbGateway"></param>
        public void BackupGatewayIdOnNotNetwork(ZbGateway zbGateway)
        {
            var strId = HdlGatewayLogic.Current.GetGatewayId(zbGateway);
            if (listBackupGwId.Contains(strId) == false)
            {
                listBackupGwId.Add(strId);
                //备份
                var strData = Newtonsoft.Json.JsonConvert.SerializeObject(listBackupGwId);
                var byteData = System.Text.Encoding.UTF8.GetBytes(strData);
                Global.WriteFileToDirectoryByBytes(DirNameResourse.LocalMemoryDirectory, DirNameResourse.BackupGatewayIdFile, byteData);
            }
        }
        /// <summary>
        /// 重新发送命令去绑定断网情况下备份的网关
        /// </summary>
        public void ResetComandToBindBackupGateway()
        {
            new System.Threading.Thread(async () =>
            {
                var fileData = Global.ReadFileByDirectory(DirNameResourse.LocalMemoryDirectory, DirNameResourse.BackupGatewayIdFile);
                if (fileData == null)
                {
                    return;
                }
                this.listBackupGwId = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(System.Text.Encoding.UTF8.GetString(fileData));
                var listTempId = new List<string>();
                listTempId.AddRange(this.listBackupGwId);
                //不显示已经被绑定过的信息,NotSetAgain:假如断网时,不二次发送
                List<string> listNotShow = new List<string>() { "NotSetAgain" };
                //调用接口,绑定网关
                var bindGateway = new BindGatewayPra();
                //获取控制主人账号的Token
                bindGateway.LoginAccessToken = UserCenterLogic.GetConnectMainToken();
                foreach (var gwId in listTempId)
                {
                    bindGateway.BindGateways.Clear();
                    bindGateway.BindGateways.Add(gwId);
                    var result = await UserCenterLogic.GetResultCodeByRequestHttps("App/BindGatewayToHome", true, bindGateway, listNotShow);
                    if (result == "Success")
                    {
                        this.listBackupGwId.Remove(gwId);
                    }
                    if (result == "Error" || result == "ErrorEx")
                    {
                        break;
                    }
                }
                if (this.listBackupGwId.Count == 0)
                {
                    //如果没有了内容,则删除文件
                    string file = UserCenterLogic.CombinePath(DirNameResourse.LocalMemoryDirectory, DirNameResourse.BackupGatewayIdFile);
                    if (System.IO.File.Exists(file) == true)
                    {
                        System.IO.File.Delete(file);
                    }
                }
                else
                {
                    //备份
                    var strData = Newtonsoft.Json.JsonConvert.SerializeObject(listBackupGwId);
                    var byteData = System.Text.Encoding.UTF8.GetBytes(strData);
                    Global.WriteFileToDirectoryByBytes(DirNameResourse.LocalMemoryDirectory, DirNameResourse.BackupGatewayIdFile, byteData);
                }
            })
            { IsBackground = true }.Start();
        }
        #endregion
        #region ■ 上传设备备份到网关_________________
        /// <summary>
        /// 上传设备备份到网关(最好不要去理它的返回结果)
        /// </summary>
        /// <param name="device">设备对象</param>
        /// <param name="backupEnum">备份类型</param>
        /// <param name="upLaodData">备份的数据</param>
        /// <returns></returns>
        public async Task<bool> UpLoadDeviceBackupDataToGateway(CommonDevice device, GatewayBackupEnum backupEnum, object upLaodData)
        {
            ZbGateway realWay = null;
            if (HdlGatewayLogic.Current.GetRealGateway(ref realWay, device.CurrentGateWayId) == false)
            {
                //没有找到真实物理网关
                return false;
            }
            string fileName = device.FilePath + ((int)backupEnum).ToString().PadLeft(5, '0');
            //创建文件对象
            var result = await realWay.CreateFileAsync(fileName);
            if (result == null || result.Result != 0)
            {
                return false;
            }
            //发送数据流
            var data = Newtonsoft.Json.JsonConvert.SerializeObject(upLaodData);
            var byteData = System.Text.Encoding.UTF8.GetBytes(data);
            var result2 = await realWay.SendFileAsync(byteData);
            if (result2 == null || result2.Result != 0)
            {
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 恢复网关___________________________
        /// <summary>
        /// 恢复网关配置
        /// </summary>
        /// <param name="zbGateway">网关对象</param>
        /// <param name="listGatewayFile">网关里面拥有的文件</param>
        /// <param name="backDirectory">云端下载的备份数据的文件夹名字</param>
        /// <returns></returns>
        public async Task<bool> RecoverGatewaySettion(ZbGateway zbGateway, List<string> listGatewayFile, string backDirectory)
        {
            //获取从云端那里得来的全部文件
            var listBackFile = HdlAutoBackupLogic.GetFileFromDirectory(UserCenterLogic.CombinePath(backDirectory));
            //添加附加情报:还原设备配置
            ProgressBar.SetAppendText(Language.StringByID(R.MyInternationalizationString.uRecoverDeviceSettion));
            ProgressBar.SetMaxValue(listBackFile.Count);
            ProgressBar.Show();
            var listSaveFile = new HashSet<string>();
            foreach (string fileName in listBackFile)
            {
                if (fileName.Length < 10 || fileName.StartsWith(Common.LocalDevice.deviceFirstName) == false)
                {
                    //不是设备备份文件
                    continue;
                }
                //恢复设备配置
                var result = await this.RecoverDeviceSettion(backDirectory, fileName);
                if (result == -1)
                {
                    ProgressBar.Close();
                    return false;
                }
                if (result == 1 || result == 2)
                {
                    listSaveFile.Add(fileName);
                }
                ProgressBar.SetValue(1);
                listGatewayFile.Remove(fileName);
            }
            //添加附加情报:覆盖网关备份中
            ProgressBar.SetAppendText(Language.StringByID(R.MyInternationalizationString.uGatewayBackupDataIsCovering));
            foreach (var file in listSaveFile)
            {
                //创建文件对象
                var result = await zbGateway.CreateFileAsync(file);
                if (result == null || result.Result != 0)
                {
                    Application.RunOnMainThread(() =>
                    {
                        //覆盖网关备份失败
                        string msg = Language.StringByID(R.MyInternationalizationString.uCoverGatewayBackupDataFail);
                        var control = new ShowMsgControl(ShowMsgType.Tip, msg);
                        control.Show();
                    });
                    ProgressBar.Close();
                    return false;
                }
                //发送数据流
                var byteData = Shared.Common.Global.ReadFileByDirectory(backDirectory, file);
                var result2 = await zbGateway.SendFileAsync(byteData);
                if (result2 == null || result2.Result != 0)
                {
                    Application.RunOnMainThread(() =>
                    {
                        //覆盖网关备份失败
                        string msg = Language.StringByID(R.MyInternationalizationString.uCoverGatewayBackupDataFail);
                        var control = new ShowMsgControl(ShowMsgType.Tip, msg);
                        control.Show();
                    });
                    ProgressBar.Close();
                    return false;
                }
            }
            //删除多余的文件
            foreach (var deleteFile in listGatewayFile)
            {
                if (deleteFile.Length > 12)
                {
                    string deviceFileName = deleteFile.Substring(5);
                    if (deviceFileName.StartsWith(Common.LocalDevice.deviceFirstName) == false)
                    {
                        //不是设备文件
                        continue;
                    }
                    string[] strArry = deviceFileName.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
                    if (strArry.Length < 4 || listSaveFile.Contains(deleteFile) == true)
                    {
                        //我也不知道它是什么文件,或者这个文件是覆盖的
                        continue;
                    }
                    //这个或许可以不理他
                    var result = await zbGateway.DelFileOrDirAsync("/etc/hdlDat/" + deleteFile);
                }
            }
            ProgressBar.Close();
            return true;
        }
        /// <summary>
        /// 恢复设备配置
        /// </summary>
        /// <param name="backDirectory">云端下载的备份数据的文件夹名字</param>
        /// <param name="backFileName">网关的设备备份名字</param>
        /// <returns></returns>
        private async Task<int> RecoverDeviceSettion(string backDirectory, string backFileName)
        {
            string deviceFileName = backFileName.Substring(0, backFileName.Length - 5);
            string[] strArry = deviceFileName.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
            if (strArry.Length < 4)
            {
                //我也不知道它是什么文件
                return 0;
            }
            var device = Common.LocalDevice.Current.GetDevice(strArry[2], Convert.ToInt32(strArry[3]));
            if (device == null)
            {
                //这个设备不见了
                return 2;
            }
            var byteData = Shared.Common.Global.ReadFileByDirectory(backDirectory, backFileName);
            var backType = (GatewayBackupEnum)Convert.ToInt32(backFileName.Substring(backFileName.Length - 5, 5));
            bool result = true;
            if (backType == GatewayBackupEnum.AMac名称)
            {
                var recoverData = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(System.Text.Encoding.UTF8.GetString(byteData));
                result = await Common.LocalDevice.Current.ReMacName(new List<CommonDevice>() { device }, recoverData);
            }
            else if (backType == GatewayBackupEnum.A端点名称)
            {
                var recoverData = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(System.Text.Encoding.UTF8.GetString(byteData));
                result = await Common.LocalDevice.Current.ReName(device, recoverData);
            }
            else if (backType == GatewayBackupEnum.APir灯光配置)
            {
                var recoverData = Newtonsoft.Json.JsonConvert.DeserializeObject<IASZone.ConfigureParamates>(System.Text.Encoding.UTF8.GetString(byteData));
                result = await HdlPirSensorLogic.Current.SetPirSensorLightSettion((IASZone)device, recoverData);
            }
            else if (backType == GatewayBackupEnum.A干接点颜色调节)
            {
                var recoverData = Newtonsoft.Json.JsonConvert.DeserializeObject<Panel.KeyColorData>(System.Text.Encoding.UTF8.GetString(byteData));
                result = await HdlPanelLogic.Current.SetPanelEpointColorInfo((Panel)device, recoverData);
            }
            else if (backType == GatewayBackupEnum.A干接点亮度调节)
            {
                var recoverData = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(System.Text.Encoding.UTF8.GetString(byteData));
                int directionsLevel = Convert.ToInt32(recoverData["directionsLevel"]);
                int backlightLevel = Convert.ToInt32(recoverData["backlightLevel"]);
                result = await HdlPanelLogic.Current.SetDeviceLightSettion((Panel)device, directionsLevel, backlightLevel);
            }
            else if (backType == GatewayBackupEnum.A干接点节能模式)
            {
                var recoverData = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(System.Text.Encoding.UTF8.GetString(byteData));
                bool modeEnable = Convert.ToBoolean(recoverData["modeEnable"]);
                int modeTime = Convert.ToInt32(recoverData["modeTime"]);
                int level = Convert.ToInt32(recoverData["level"]);
                result = await HdlPanelLogic.Current.SetDeviceEnergyConservationMode((Panel)device, modeEnable, modeTime, level);
            }
            else if (backType == GatewayBackupEnum.A干接点私有属性)
            {
                var recoverData = Newtonsoft.Json.JsonConvert.DeserializeObject<int>(System.Text.Encoding.UTF8.GetString(byteData));
                result = await HdlPanelLogic.Current.EditorDryContactFunction((Panel)device, recoverData);
            }
            return result == true ? 1 : -1;
        }
        #endregion