黄学彪
2020-12-16 0d9f64668fd7350d6a21fd157e32009a96d98134
ZigbeeApp/Shared/Phone/Common/Logic/HdlGatewayBackupLogic.cs
File was renamed from ZigbeeApp/Shared/Phone/UserCenter/CommonBase/Logic/HdlGatewayBackupLogic.cs
@@ -3,7 +3,7 @@
using System.Text;
using ZigBee.Device;
namespace Shared.Phone.UserCenter
namespace Shared.Phone
{
    /// <summary>
    /// 网关备份业务的逻辑
@@ -38,9 +38,9 @@
        /// <summary>
        /// 网关执行备份
        /// </summary>
        /// <param name="realGateway">真实物理网关对象</param>
        /// <param name="gatewayId">网关ID</param>
        /// <param name="backupName">需要创建的备份的名字</param>
        public void DoBackupGateway(ZbGateway realGateway, string backupName)
        public void DoBackupGateway(string gatewayId, string backupName)
        {
            //展开进度条
            ProgressFormBar.Current.Start();
@@ -48,8 +48,8 @@
            ProgressFormBar.Current.SetMsg(Language.StringByID(R.MyInternationalizationString.uCreatBackupFile));
            System.Threading.Thread.Sleep(1000);
            //创建一个备份名字
            string backupClassId = HdlBackupLogic.Current.CreatNewBackupNameToDB(backupName, 2, realGateway.GwId);
            //创建一个备份
            string backupClassId = this.CreatGatewayBackup(gatewayId, backupName);
            if (backupClassId == null)
            {
                //关闭进度条
@@ -80,17 +80,516 @@
            //}
            //开始上传数据
            bool result = this.StartUpLoadData(realGateway, backupClassId);
            bool result = this.StartUpLoadData(gatewayId, backupClassId);
            if (result == false)
            {
                //如果上传失败的话,就把它删除
                HdlBackupLogic.Current.DeleteDbBackupData(backupClassId);
                this.DeleteGatewayBackup(gatewayId, backupClassId);
                //关闭进度条
                ProgressFormBar.Current.Close();
                return;
            }
            //关闭进度条
            ProgressFormBar.Current.Close();
        }
        /// <summary>
        /// 删除网关备份
        /// </summary>
        /// <param name="i_gwId">网关id</param>
        /// <param name="i_backupId">备份的主键</param>
        /// <param name="mode">失败时是否显示tip消息</param>
        /// <returns></returns>
        public bool DeleteGatewayBackup(string i_gwId, string i_backupId, ShowNetCodeMode mode = ShowNetCodeMode.YES)
        {
            var pra = new { gatewayId = i_gwId, folderId = i_backupId };
            var result = HdlHttpLogic.Current.RequestResponseFromZigbeeHttps("home-wisdom/gateway/folder/delete", RestSharp.Method.POST, pra, null, null, CheckMode.A账号权限);
            //检测状态码
            if (HdlCheckLogic.Current.CheckNetCode(result, mode) == false)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 创建网关备份(返回备份主键,返回null代表失败)
        /// </summary>
        /// <param name="gwId">网关id</param>
        /// <param name="i_backName">备份名字</param>
        /// <returns></returns>
        private string CreatGatewayBackup(string gwId, string i_backName)
        {
            //创建一个备份名字
            var pra = new { backupClassify = "USER_DEFINED_BACKUP", backupDataType = "ZIGBEE", folderName = i_backName, gatewayId = gwId };
            var result = HdlHttpLogic.Current.RequestResponseFromZigbeeHttps("home-wisdom/gateway/folder/add", RestSharp.Method.POST, pra, null, null, CheckMode.A账号权限);
            //检测状态码
            if (HdlCheckLogic.Current.CheckNetCode(result, ShowNetCodeMode.YES) == false)
            {
                return null;
            }
            var info = Newtonsoft.Json.JsonConvert.DeserializeObject<IdInfoClass>(result.Data.ToString());
            return info.Id;
        }
        #endregion
        #region ■ 开始网关数据备份___________________
        /// <summary>
        /// 开始上传数据
        /// </summary>
        /// <param name="gatewayId"></param>
        /// <param name="backupClassId"></param>
        private bool StartUpLoadData(string gatewayId, string backupClassId)
        {
            //开始备份网关数据
            ProgressFormBar.Current.SetMsg(Language.StringByID(R.MyInternationalizationString.uStartBackupgatewayData));
            ProgressFormBar.Current.SetValue(0);
            System.Threading.Thread.Sleep(1000);
            bool threadAction = true;
            bool success = false;
            //等待时间
            int waitime = 60;
            //计时时间
            int TimeOut = 0;
            HdlGatewayReceiveLogic.Current.AddGatewayReceiveEvent(gatewayId, (topic, message) =>
            {
                if (topic == gatewayId + "/BackupGwDataFile_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var statu = Convert.ToInt32(jobject["Data"]["Status"].ToString());
                    if (statu == 1)
                    {
                        threadAction = false;
                        //网关数据备份失败
                        HdlMessageLogic.Current.ShowMassage(ShowMsgType.Error, Language.StringByID(R.MyInternationalizationString.uBackupgatewayDataFail));
                        return;
                    }
                    if (statu == 2)
                    {
                        threadAction = false;
                        success = true;
                        //上传数据成功
                        string msg2 = Language.StringByID(R.MyInternationalizationString.uUploadDataSuccess);
                        HdlMessageLogic.Current.ShowMassage(ShowMsgType.Tip, msg2);
                    }
                    //将时间刷新,然后等待时间变更为30秒
                    TimeOut = 0;
                    waitime = 300;
                }
                else if (topic == gatewayId + "/BackupGwDataFileProgress_Respon")
                {
                    //刷新等待时间
                    TimeOut = 0;
                    //上传进度百分比
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var statu = Convert.ToInt32(jobject["Data"]["Status"].ToString());
                    if (statu != 0)
                    {
                        threadAction = false;
                        //网关数据备份失败
                        HdlMessageLogic.Current.ShowMassage(ShowMsgType.Error, Language.StringByID(R.MyInternationalizationString.uBackupgatewayDataFail));
                        return;
                    }
                    //设置进度百分比
                    var persent = Convert.ToInt32(jobject["Data"]["BackupPercent"].ToString());
                    ProgressFormBar.Current.SetValue(persent, 100);
                }
            });
            //发送数据
            var fullUrl = HdlHttpLogic.Current.RequestHttpsHost + @"home-wisdom/gateway/file/create";
            string authorization = Common.Config.Instance.HeaderPrefix + HdlHttpLogic.Current.GetHttpToken(CheckMode.A账号权限);
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 6200 } };
            var data = new Newtonsoft.Json.Linq.JObject {
                { "url", fullUrl },{ "authorization", authorization },{ "folderId", backupClassId }};
            jObject.Add("Data", data);
            HdlGatewayLogic.Current.SendJobjectData(gatewayId, "BackupGwDataFile", jObject.ToString());
            while (threadAction == true && TimeOut < waitime)
            {
                System.Threading.Thread.Sleep(100);
                TimeOut++;
            }
            //清除事件
            HdlGatewayReceiveLogic.Current.RemoveGatewayReceiveEvent();
            if (TimeOut >= waitime)
            {
                //响应超时,网关数据备份失败
                string msg = Language.StringByID(R.MyInternationalizationString.uResponseTimeoutsAndBackupgatewayDataFail);
                HdlMessageLogic.Current.ShowMassage(ShowMsgType.Error, msg);
                return false;
            }
            System.Threading.Thread.Sleep(1000);
            return success;
        }
        #endregion
        #region ■ 从云端获取备份文件列表_____________
        /// <summary>
        /// 从云端获取网关的备份列表
        /// </summary>
        /// <param name="gatewayId">网关di</param>
        /// <param name="backMode">获取的备份类型</param>
        /// <param name="mode">失败时是否显示tip消息</param>
        public List<BackupListNameInfo> GetGatewayBackupListFromDb(string gatewayId, BackUpMode backMode, ShowNetCodeMode mode = ShowNetCodeMode.YES)
        {
            var pra = new { mac = gatewayId };
            var result = HdlHttpLogic.Current.RequestResponseFromZigbeeHttps("home-wisdom/gateway/folder/findAll", RestSharp.Method.POST, pra, null, null, CheckMode.A账号权限);
            //检测状态码
            if (HdlCheckLogic.Current.CheckNetCode(result, mode) == false)
            {
                return null;
            }
            var listTemp = Newtonsoft.Json.JsonConvert.DeserializeObject<List<BackupListNameInfo>>(result.Data.ToString());
            var strDiv = HdlBackupLogic.Current.GetBackUpModeText(backMode);
            var listData = new List<BackupListNameInfo>();
            foreach (var info in listTemp)
            {
                if (info.BackupClassify != strDiv || info.BackupDataType != "ZIGBEE")
                {
                    //不是指定的备份
                    continue;
                }
                listData.Add(info);
            }
            return listData;
        }
        /// <summary>
        /// 发送从云端获取备份文件列表的命令给网关
        /// </summary>
        /// <param name="gatewayId"></param>
        /// <param name="backupClassId"></param>
        /// <returns></returns>
        private bool SendGetGatewayFileListComandToGateway(string gatewayId, string backupClassId)
        {
            //正在获取备份文件列表
            ProgressFormBar.Current.SetMsg(Language.StringByID(R.MyInternationalizationString.uBackupFileListGetting));
            ProgressFormBar.Current.SetValue(0);
            System.Threading.Thread.Sleep(1000);
            int result = -1;
            HdlGatewayReceiveLogic.Current.AddGatewayReceiveEvent(gatewayId, (topic, message) =>
            {
                if (topic == gatewayId + "/GetDataFileList_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    result = Convert.ToInt32(jobject["Data"]["Status"].ToString());
                    if (result != 0)
                    {
                        //获取备份文件列表失败
                        HdlMessageLogic.Current.ShowMassage(ShowMsgType.Error, Language.StringByID(R.MyInternationalizationString.uGetBackupFileListFail));
                        return;
                    }
                }
            });
            //发送数据
            var fullUrl = HdlHttpLogic.Current.RequestHttpsHost + @"home-wisdom/backup/file/findAll";
            string authorization = Common.Config.Instance.HeaderPrefix + HdlHttpLogic.Current.GetHttpToken(CheckMode.A账号权限);
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 6202 } };
            var data = new Newtonsoft.Json.Linq.JObject {
                { "url", fullUrl },{ "authorization", authorization },{ "folderId", backupClassId }};
            jObject.Add("Data", data);
            HdlGatewayLogic.Current.SendJobjectData(gatewayId, "GetDataFileList", jObject.ToString());
            int timeOut = 0;
            while (result == -1 && timeOut < 30)
            {
                System.Threading.Thread.Sleep(1000);
                timeOut++;
            }
            //移除事件
            HdlGatewayReceiveLogic.Current.RemoveGatewayReceiveEvent();
            if (result != 0)
            {
                string msg = Language.StringByID(R.MyInternationalizationString.uGetBackupFileListFail);
                if (result == -1)
                {
                    //响应超时,获取备份文件列表失败
                    msg = Language.StringByID(R.MyInternationalizationString.uResponseTimeoutsAndGetBackupFileListFail);
                }
                HdlMessageLogic.Current.ShowMassage(ShowMsgType.Error, msg);
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 从云端下载备份文件_________________
        /// <summary>
        /// 发送从云端下载备份文件的命令到网关
        /// </summary>
        /// <param name="gatewayId"></param>
        /// <param name="backupClassId"></param>
        /// <returns></returns>
        private bool SendDownloadGatewayFileComandToGateway(string gatewayId, string backupClassId)
        {
            //正在下载备份文件
            ProgressFormBar.Current.SetMsg(Language.StringByID(R.MyInternationalizationString.uBackupFileDownloading));
            ProgressFormBar.Current.SetValue(0);
            System.Threading.Thread.Sleep(1000);
            bool threadAction = true;
            bool success = false;
            int timeOut = 0;
            HdlGatewayReceiveLogic.Current.AddGatewayReceiveEvent(gatewayId, (topic, message) =>
            {
                if (topic == gatewayId + "/RestoreDataFileProgress_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var result = Convert.ToInt32(jobject["Data"]["Status"].ToString());
                    if (result == 1 || result == 3)
                    {
                        //下载备份文件失败
                        HdlMessageLogic.Current.ShowMassage(ShowMsgType.Error, Language.StringByID(R.MyInternationalizationString.uDownloadBackupFileFail));
                        threadAction = false;
                        return;
                    }
                    else if (result == 2)
                    {
                        //下载成功
                        success = true;
                        threadAction = false;
                        return;
                    }
                    else if (result == 0)
                    {
                        //刷新等待时间
                        timeOut = 0;
                        //设置进度百分比
                        var persent = Convert.ToInt32(jobject["Data"]["RestoreDataPercent"].ToString());
                        //网关下载完成之后,它自己会卡一会,才会发送2过来
                        ProgressFormBar.Current.SetValue(persent - 1, 100);
                    }
                }
            });
            //发送数据
            var fullUrl = HdlHttpLogic.Current.RequestHttpsHost + @"home-wisdom/gateway/file/downOne";
            string authorization = Common.Config.Instance.HeaderPrefix + HdlHttpLogic.Current.GetHttpToken(CheckMode.A账号权限);
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 6203 } };
            var data = new Newtonsoft.Json.Linq.JObject {
                { "url", fullUrl },{ "authorization", authorization },{ "folderId", backupClassId }};
            jObject.Add("Data", data);
            HdlGatewayLogic.Current.SendJobjectData(gatewayId, "GetDataFileList", jObject.ToString());
            while (threadAction == true && timeOut < 30)
            {
                System.Threading.Thread.Sleep(1000);
                timeOut++;
            }
            //移除事件
            HdlGatewayReceiveLogic.Current.RemoveGatewayReceiveEvent();
            if (timeOut >= 30)
            {
                //响应超时,下载备份文件失败
                string msg = Language.StringByID(R.MyInternationalizationString.uResponseTimeoutsAndDownloadBackupFileFail);
                HdlMessageLogic.Current.ShowMassage(ShowMsgType.Error, msg);
                return false;
            }
            return success;
        }
        #endregion
        #region ■ 编辑网关备份名称___________________
        /// <summary>
        /// 编辑网关备份名称
        /// </summary>
        /// <param name="i_backId">备份的主键</param>
        /// <param name="i_newName">备份的新名称</param>
        /// <param name="mode">失败时是否显示tip消息</param>
        /// <returns></returns>
        public bool EditorGatewayBackupName(string i_backId, string i_newName, ShowNetCodeMode mode = ShowNetCodeMode.YES)
        {
            var pra = new { gatewayFolderId = i_backId, folderName = i_newName, homeId = Common.Config.Instance.Home.Id };
            var result = HdlHttpLogic.Current.RequestResponseFromZigbeeHttps("home-wisdom/gateway/folder/update", RestSharp.Method.POST, pra, null, null, CheckMode.A账号权限);
            //检测状态码
            if (HdlCheckLogic.Current.CheckNetCode(result, mode) == false)
            {
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 网关还原___________________________
        /// <summary>
        /// 执行网关还原操作
        /// </summary>
        /// <param name="gatewayId">网关ID</param>
        /// <param name="backupId">备份主键</param>
        public bool RecoverGateway(string gatewayId, string backupId)
        {
            //展开进度条
            ProgressFormBar.Current.Start();
            //发送从云端获取备份文件列表的命令给网关
            var result = this.SendGetGatewayFileListComandToGateway(gatewayId, backupId);
            if (result == false)
            {
                //关闭进度条
                ProgressFormBar.Current.Close();
                return false;
            }
            //发送从云端下载备份文件的命令到网关
            result = this.SendDownloadGatewayFileComandToGateway(gatewayId, backupId);
            if (result == false)
            {
                //关闭进度条
                ProgressFormBar.Current.Close();
                return false;
            }
            ////恢复协调器nv分区的组网信息
            //result = this.RestoreGatewayNV(realGateway);
            //if (result == false)
            //{
            //    //关闭进度条
            //    ProgressFormBar.Current.Close();
            //    return false;
            //}
            //打开协调器串口发送功能
            //result = this.OpenZbMsComSend(realGateway);
            //if (result == false)
            //{
            //    //关闭进度条
            //    ProgressFormBar.Current.Close();
            //    return false;
            //}
            //重启网关系统
            result = this.GatewayReboot(gatewayId);
            //关闭进度条
            ProgressFormBar.Current.Close();
            return result;
        }
        #endregion
        #region ■ 重启网关系统_______________________
        /// <summary>
        /// 重启网关系统
        /// </summary>
        /// <param name="gatewayId"></param>
        /// <returns></returns>
        private bool GatewayReboot(string gatewayId)
        {
            //正在重启网关系统
            ProgressFormBar.Current.SetMsg(Language.StringByID(R.MyInternationalizationString.uGatewayRerooting));
            ProgressFormBar.Current.SetValue(0);
            System.Threading.Thread.Sleep(1000);
            int result = -1;
            HdlGatewayReceiveLogic.Current.AddGatewayReceiveEvent(gatewayId, (topic, message) =>
            {
                if (topic == gatewayId + "/" + "GwReboot_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    result = Convert.ToInt32(jobject["Data"]["Result"].ToString());
                }
            });
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 83 } };
            HdlGatewayLogic.Current.SendJobjectData(gatewayId, "GwReboot", jObject.ToString());
            int timeOut = 0;
            while (result == -1 && timeOut < 30)
            {
                System.Threading.Thread.Sleep(1000);
                timeOut++;
            }
            //移除事件
            HdlGatewayReceiveLogic.Current.RemoveGatewayReceiveEvent();
            if (result != 0)
            {
                //重启网关系统失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGatewayRerootFail);
                if (result == -1)
                {
                    msg = HdlCommonLogic.Current.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                }
                HdlMessageLogic.Current.ShowMassage(ShowMsgType.Error, msg);
                return false;
            }
            //网关已经接收到重启命令,接下来去判断网关是否重启完成
            bool gatewatAction = false;
            bool threadAction = true;
            HdlThreadLogic.Current.RunThread(() =>
            {
                timeOut = 0;
                while (gatewatAction == false)
                {
                    //大概网关重启要60秒
                    if (timeOut >= 65 && timeOut % 5 == 0)
                    {
                        //5秒一次,去获取版本
                        var data = HdlGatewayLogic.Current.RefreshGatewayInfo(gatewayId, false, ShowErrorMode.NO);
                        if (data != null)
                        {
                            gatewatAction = true;
                            threadAction = false;
                            break;
                        }
                    }
                    System.Threading.Thread.Sleep(1000);
                    timeOut++;
                    //设置进度值
                    ProgressFormBar.Current.SetValue(timeOut, 180);
                    if (timeOut >= 180)
                    {
                        //180秒还等不到的话,网关应该出问题了
                        threadAction = false;
                        break;
                    }
                }
            });
            while (threadAction == true)
            {
                System.Threading.Thread.Sleep(4000);
            }
            if (gatewatAction == true)
            {
                //设置进度值:100%
                ProgressFormBar.Current.SetValue(1, 1);
                System.Threading.Thread.Sleep(1000);
                //网关数据恢复成功!
                string msg = Language.StringByID(R.MyInternationalizationString.uRestoreGatewayDataSuccess);
                HdlMessageLogic.Current.ShowMassage(ShowMsgType.Tip, msg);
                return true;
            }
            else
            {
                //响应超时,重启网关系统失败
                string msg = Language.StringByID(R.MyInternationalizationString.uResponseTimeoutsAndGatewayRerootFail);
                HdlMessageLogic.Current.ShowMassage(ShowMsgType.Error, msg);
                return false;
            }
        }
        #endregion
@@ -140,9 +639,9 @@
                string msg = Language.StringByID(R.MyInternationalizationString.uSaveGatewayNVFileFail);
                if (result == -1)
                {
                    msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                    msg = HdlCommonLogic.Current.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                }
                this.ShowErrorMsg(msg);
                HdlMessageLogic.Current.ShowMassage(ShowMsgType.Error, msg);
                return false;
            }
@@ -193,366 +692,13 @@
                string msg = Language.StringByID(R.MyInternationalizationString.uOpenZbMsComSendFail);
                if (result == -1)
                {
                    msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                    msg = HdlCommonLogic.Current.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                }
                this.ShowErrorMsg(msg);
                HdlMessageLogic.Current.ShowMassage(ShowMsgType.Error, msg);
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 开始网关数据备份___________________
        /// <summary>
        /// 开始上传数据
        /// </summary>
        /// <param name="realGateway"></param>
        /// <param name="backupClassId"></param>
        private bool StartUpLoadData(ZbGateway realGateway, string backupClassId)
        {
            //开始备份网关数据
            ProgressFormBar.Current.SetMsg(Language.StringByID(R.MyInternationalizationString.uStartBackupgatewayData));
            ProgressFormBar.Current.SetValue(0);
            System.Threading.Thread.Sleep(1000);
            bool threadAction = true;
            bool success = false;
            //等待时间
            int waitime = 60;
            //计时时间
            int TimeOut = 0;
            Action<string, string> action = (topic, message) =>
            {
                var gatewayID = topic.Split('/')[0];
                if (topic == gatewayID + "/BackupGwDataFile_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var statu = Convert.ToInt32(jobject["Data"]["Status"].ToString());
                    if (statu == 1)
                    {
                        threadAction = false;
                        //网关数据备份失败
                        this.ShowErrorMsg(Language.StringByID(R.MyInternationalizationString.uBackupgatewayDataFail));
                        return;
                    }
                    if (statu == 2)
                    {
                        threadAction = false;
                        success = true;
                        //上传数据成功
                        string msg2 = Language.StringByID(R.MyInternationalizationString.uUploadDataSuccess);
                        this.ShowTipMsg(msg2);
                    }
                    //将时间刷新,然后等待时间变更为30秒
                    TimeOut = 0;
                    waitime = 300;
                }
                else if (topic == gatewayID + "/BackupGwDataFileProgress_Respon")
                {
                    //刷新等待时间
                    TimeOut = 0;
                    //上传进度百分比
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var statu = Convert.ToInt32(jobject["Data"]["Status"].ToString());
                    if (statu != 0)
                    {
                        threadAction = false;
                        //网关数据备份失败
                        this.ShowErrorMsg(Language.StringByID(R.MyInternationalizationString.uBackupgatewayDataFail));
                        return;
                    }
                    //设置进度百分比
                    var persent = Convert.ToInt32(jobject["Data"]["BackupPercent"].ToString());
                    ProgressFormBar.Current.SetValue(persent, 100);
                }
            };
            realGateway.Actions += action;
            //获取接口的连接模式
            string fullUrl = string.Empty;
            var connectMode = UserCenterLogic.GetHttpConnectMode(true);
            if (connectMode == HttpConnectMode.Normal)
            {
                //普通访问
                fullUrl = $"{Common.CommonPage.RequestHttpsHost}/{"App/UploadHomeAppGatewaySubFiles"}";
            }
            else if (connectMode == HttpConnectMode.Admin)
            {
                //以管理员的身份访问,自身是成员
                fullUrl = $"{Common.Config.Instance.AdminRequestBaseUrl}/{"App/UploadHomeAppGatewaySubFiles"}";
            }
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 6200 } };
            var data = new Newtonsoft.Json.Linq.JObject {
                { "url", fullUrl }, { "RequestVersion", Common.CommonPage.RequestVersion },
                { "LoginAccessToken", UserCenterLogic.GetConnectMainToken() }, { "BackupClassId", backupClassId },
                { "ManualBackupType", 2 },{ "IsOtherAccountCtrl",connectMode == HttpConnectMode.Admin?1:0}
            };
            jObject.Add("Data", data);
            realGateway.Send("BackupGwDataFile", jObject.ToString());
            while (threadAction == true && TimeOut < waitime)
            {
                System.Threading.Thread.Sleep(100);
                TimeOut++;
            }
            realGateway.Actions -= action;
            if (TimeOut >= waitime)
            {
                //响应超时,网关数据备份失败
                string msg = Language.StringByID(R.MyInternationalizationString.uResponseTimeoutsAndBackupgatewayDataFail);
                this.ShowErrorMsg(msg);
                return false;
            }
            System.Threading.Thread.Sleep(1000);
            return success;
        }
        #endregion
        #region ■ 网关还原___________________________
        /// <summary>
        /// 执行网关还原操作
        /// </summary>
        /// <param name="realGateway">真实物理网关对象</param>
        /// <param name="backupId">备份主键</param>
        /// <param name="isAutoBack">0:获取网关手动备份文件列表 1:获取网关自动备份文件列表</param>
        /// <param name="closeBar">是否关闭进度条</param>
        public bool RecoverGateway(ZbGateway realGateway, string backupId, int isAutoBack, bool closeBar = true)
        {
            //展开进度条
            ProgressFormBar.Current.Start();
            //从云端获取备份文件列表
            var result = this.GetGatewayFileList(realGateway, backupId, isAutoBack);
            if (result == false)
            {
                //关闭进度条
                ProgressFormBar.Current.Close();
                return false;
            }
            //从云端下载备份文件
            result = this.DownloadGatewayFile(realGateway, backupId, isAutoBack);
            if (result == false)
            {
                //关闭进度条
                ProgressFormBar.Current.Close();
                return false;
            }
            ////恢复协调器nv分区的组网信息
            //result = this.RestoreGatewayNV(realGateway);
            //if (result == false)
            //{
            //    //关闭进度条
            //    ProgressFormBar.Current.Close();
            //    return false;
            //}
            //打开协调器串口发送功能
            //result = this.OpenZbMsComSend(realGateway);
            //if (result == false)
            //{
            //    //关闭进度条
            //    ProgressFormBar.Current.Close();
            //    return false;
            //}
            //重启网关系统
            result = this.GatewayReboot(realGateway);
            if (result == true)
            {
                //刷新全部场景
                HdlSceneLogic.Current.RefreshSceneUIList(false);
                //获取全部设备
                Common.LocalDevice.Current.SetDeviceToMemmoryByGateway(realGateway.GwId, false);
            }
            if (closeBar == true)
            {
                //关闭进度条
                ProgressFormBar.Current.Close();
            }
            return result;
        }
        #endregion
        #region ■ 从云端获取备份文件列表_____________
        /// <summary>
        /// 从云端获取备份文件列表
        /// </summary>
        /// <param name="realGateway"></param>
        /// <param name="backupClassId"></param>
        /// <returns></returns>
        private bool GetGatewayFileList(ZbGateway realGateway, string backupClassId, int isAutoBack)
        {
            //正在获取备份文件列表
            ProgressFormBar.Current.SetMsg(Language.StringByID(R.MyInternationalizationString.uBackupFileListGetting));
            System.Threading.Thread.Sleep(1000);
            int result = -1;
            Action<string, string> action = (topic, message) =>
            {
                var gatewayID = topic.Split('/')[0];
                if (topic == gatewayID + "/GetDataFileList_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    result = Convert.ToInt32(jobject["Data"]["Status"].ToString());
                    if (result != 0)
                    {
                        //获取备份文件列表失败
                        this.ShowErrorMsg(Language.StringByID(R.MyInternationalizationString.uGetBackupFileListFail));
                        return;
                    }
                }
            };
            realGateway.Actions += action;
            //获取接口的连接模式
            string fullUrl = string.Empty;
            var connectMode = UserCenterLogic.GetHttpConnectMode(true);
            if (connectMode == HttpConnectMode.Normal)
            {
                //普通访问
                fullUrl = $"{Common.CommonPage.RequestHttpsHost}/{"App/GetHomeDataBackupUploadListPagger"}";
            }
            else if (connectMode == HttpConnectMode.Admin)
            {
                //以管理员的身份访问,自身是成员
                fullUrl = $"{Common.Config.Instance.AdminRequestBaseUrl}/{"App/GetHomeDataBackupUploadListPagger"}";
            }
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 6202 } };
            var data = new Newtonsoft.Json.Linq.JObject {
                { "url", fullUrl }, { "RequestVersion", Common.CommonPage.RequestVersion },
                { "LoginAccessToken", UserCenterLogic.GetConnectMainToken() }, { "IsGatewayAutoBackup", isAutoBack },
                { "BackupClassId", backupClassId },{ "GatewayUniqueId",realGateway.GwId},
                { "IsOtherAccountCtrl",connectMode == HttpConnectMode.Admin?1:0}
            };
            jObject.Add("Data", data);
            realGateway.Send("GetDataFileList", jObject.ToString());
            int timeOut = 0;
            while (result == -1 && timeOut < 30)
            {
                System.Threading.Thread.Sleep(1000);
                timeOut++;
            }
            realGateway.Actions -= action;
            if (result != 0)
            {
                string msg = Language.StringByID(R.MyInternationalizationString.uGetBackupFileListFail);
                if (result == -1)
                {
                    //响应超时,获取备份文件列表失败
                    msg = Language.StringByID(R.MyInternationalizationString.uResponseTimeoutsAndGetBackupFileListFail);
                }
                this.ShowErrorMsg(msg);
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 从云端下载备份文件_________________
        /// <summary>
        /// 从云端下载备份文件
        /// </summary>
        /// <param name="realGateway"></param>
        /// <param name="backupClassId"></param>
        /// <returns></returns>
        private bool DownloadGatewayFile(ZbGateway realGateway, string backupClassId, int isAutoBack)
        {
            //正在下载备份文件
            ProgressFormBar.Current.SetMsg(Language.StringByID(R.MyInternationalizationString.uBackupFileDownloading));
            ProgressFormBar.Current.ResetProgressBar();
            System.Threading.Thread.Sleep(1000);
            bool threadAction = true;
            bool success = false;
            int timeOut = 0;
            Action<string, string> action = (topic, message) =>
            {
                var gatewayID = topic.Split('/')[0];
                if (topic == gatewayID + "/RestoreDataFileProgress_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var result = Convert.ToInt32(jobject["Data"]["Status"].ToString());
                    if (result == 1 || result == 3)
                    {
                        //下载备份文件失败
                        this.ShowErrorMsg(Language.StringByID(R.MyInternationalizationString.uDownloadBackupFileFail));
                        threadAction = false;
                        return;
                    }
                    else if (result == 2)
                    {
                        //下载成功
                        success = true;
                        threadAction = false;
                        return;
                    }
                    else if (result == 0)
                    {
                        //刷新等待时间
                        timeOut = 0;
                        //设置进度百分比
                        var persent = Convert.ToInt32(jobject["Data"]["RestoreDataPercent"].ToString());
                        //网关下载完成之后,它自己会卡一会,才会发送2过来
                        ProgressFormBar.Current.SetValue(persent - 1, 100);
                    }
                }
            };
            realGateway.Actions += action;
            //获取接口的连接模式
            string fullUrl = string.Empty;
            var connectMode = UserCenterLogic.GetHttpConnectMode(true);
            if (connectMode == HttpConnectMode.Normal)
            {
                //普通访问
                fullUrl = $"{Common.CommonPage.RequestHttpsHost}/{"App/DownloadSomeDataBackup"}";
            }
            else if (connectMode == HttpConnectMode.Admin)
            {
                //以管理员的身份访问,自身是成员
                fullUrl = $"{Common.Config.Instance.AdminRequestBaseUrl}/{"App/DownloadSomeDataBackup"}";
            }
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 6203 } };
            var data = new Newtonsoft.Json.Linq.JObject {
                { "url", fullUrl }, { "RequestVersion", Common.CommonPage.RequestVersion },
                { "LoginAccessToken", UserCenterLogic.GetConnectMainToken() }, { "IsGatewayAutoBackup", isAutoBack },
                { "BackupClassId", backupClassId },{ "GatewayUniqueId",realGateway.GwId},
                { "IsOtherAccountCtrl",connectMode == HttpConnectMode.Admin?1:0}
            };
            jObject.Add("Data", data);
            realGateway.Send("GetDataFileList", jObject.ToString());
            while (threadAction == true && timeOut < 30)
            {
                System.Threading.Thread.Sleep(1000);
                timeOut++;
            }
            realGateway.Actions -= action;
            if (timeOut >= 30)
            {
                //响应超时,下载备份文件失败
                string msg = Language.StringByID(R.MyInternationalizationString.uResponseTimeoutsAndDownloadBackupFileFail);
                this.ShowErrorMsg(msg);
                return false;
            }
            return success;
        }
        #endregion
@@ -605,131 +751,11 @@
                    //响应超时,恢复协调器nv分区失败
                    msg = Language.StringByID(R.MyInternationalizationString.uResponseTimeoutsAndRestoreGatewayNVFail);
                }
                this.ShowErrorMsg(msg);
                HdlMessageLogic.Current.ShowMassage(ShowMsgType.Error, msg);
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 重启网关系统_______________________
        /// <summary>
        /// 重启网关系统
        /// </summary>
        /// <param name="realGateway"></param>
        /// <returns></returns>
        private bool GatewayReboot(ZbGateway realGateway)
        {
            //正在重启网关系统
            ProgressFormBar.Current.SetMsg(Language.StringByID(R.MyInternationalizationString.uGatewayRerooting));
            ProgressFormBar.Current.ResetProgressBar();
            System.Threading.Thread.Sleep(1000);
            int result = -1;
            Action<string, string> action = (topic, message) =>
            {
                var gatewayID = topic.Split('/')[0];
                if (topic == gatewayID + "/" + "GwReboot_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    result = Convert.ToInt32(jobject["Data"]["Result"].ToString());
                }
            };
            realGateway.Actions += action;
            var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 83 } };
            realGateway.Send("GwReboot", jObject.ToString());
            int timeOut = 0;
            while (result == -1 && timeOut < 30)
            {
                System.Threading.Thread.Sleep(1000);
                timeOut++;
            }
            realGateway.Actions -= action;
            if (result != 0)
            {
                //重启网关系统失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGatewayRerootFail);
                if (result == -1)
                {
                    msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                }
                this.ShowErrorMsg(msg);
                return false;
            }
            //网关已经接收到重启命令,接下来去判断网关是否重启完成
            timeOut = 0;
            while (true)
            {
                //大概网关重启要60秒
                if (timeOut >= 65 && timeOut % 5 == 0)
                {
                    //5秒一次,去获取版本
                    var data = HdlGatewayLogic.Current.GetGatewayInfo(realGateway, false, ShowErrorMode.NO);
                    if (data != null)
                    {
                        break;
                    }
                }
                System.Threading.Thread.Sleep(1000);
                timeOut++;
                //设置进度值
                ProgressFormBar.Current.SetValue(timeOut, 180);
                if (timeOut >= 180)
                {
                    //180秒还等不到的话,网关应该出问题了
                    break;
                }
            }
            if (timeOut < 180)
            {
                //设置进度值:100%
                ProgressFormBar.Current.SetValue(1, 1);
                System.Threading.Thread.Sleep(1000);
                return true;
            }
            else
            {
                //响应超时,重启网关系统失败
                string msg = Language.StringByID(R.MyInternationalizationString.uResponseTimeoutsAndGatewayRerootFail);
                this.ShowErrorMsg(msg);
                return false;
            }
        }
        #endregion
        #region ■ 一般方法___________________________
        /// <summary>
        /// 显示错误信息窗口
        /// </summary>
        /// <param name="msg"></param>
        private void ShowErrorMsg(string msg)
        {
            Application.RunOnMainThread(() =>
            {
                var contr = new ShowMsgControl(ShowMsgType.Error, msg);
                contr.Show();
            });
        }
        /// <summary>
        /// 显示Tip信息窗口
        /// </summary>
        /// <param name="msg"></param>
        private void ShowTipMsg(string msg)
        {
            Application.RunOnMainThread(() =>
            {
                var contr = new ShowMsgControl(ShowMsgType.Tip, msg);
                contr.Show();
            });
        }
        #endregion