wxr
2023-08-04 20f70e3446df19bf5d0faaae9f7bd58fd0fc4bcc
Crabtree/SmartHome/UI/SimpleControl/Phone/Register/MigrationServer.cs
@@ -18,8 +18,12 @@
        /// </summary>
        private bool finish = false;
        private string SeverAddr = "https://bahrain-gateway.hdlcontrol.com";
#if DEBUG
        //private string SeverAddr = "https://test-gz.hdlcontrol.com";
        private string SeverAddr = "https://bahrain-gateway.hdlcontrol.com";
#else
        private string SeverAddr = "https://bahrain-gateway.hdlcontrol.com";
#endif
        FrameLayout contentView;
@@ -31,15 +35,32 @@
        EditText etPwd;
        string pwd;
        string newUserId;
        string newHomeId;
        Button btnSave;
        Button btnClose;
        Alert sssAlert = new Alert ("", "Please press the PROG button on Gateway for 3 sec.", "Confirm");
        Action tipLockedAction;
        bool showedLockedTip = false;
        public MigrationServer ()
        {
            loading = new Loading ();
            loading = new Loading ();
            tipLockedAction = () => {
                Application.RunOnMainThread (() => {
                    if (!showedLockedTip) {
                        sssAlert.Show ();
                        showedLockedTip = true;
                        sssAlert.ResultEventHandler += (sd, dd) => {
                            showedLockedTip = false;
                        };
                    }
                });
            };
            Packet.lockedAction = tipLockedAction;
        }
@@ -47,7 +68,7 @@
        public void ShowDialog()
        {
            #region 弹窗
#region 弹窗
            Dialog dialog = new Dialog ();
            FrameLayout dialogBodyView = new FrameLayout () {
@@ -135,6 +156,8 @@
            bottomView.AddChidren (btnClose);
            btnClose.MouseUpEventHandler += (send2er, e2) => {
                dialog.Close ();
                Packet.lockedAction = null;
            };
            Button btnBottomLine = new Button () {
@@ -158,19 +181,24 @@
            btnSave.MouseUpEventHandler += (sender2, e2) => {
                if (finish) {
                    dialog.Close ();
                    Packet.lockedAction = null;
                    return;
                }
#if DEBUG
                //SetGateWayMqttUrlAddress (1, 0);
                //WriteSecretKey (1, 0, new byte [] {1,1,2,3,2,3,4,5,2,3,5,6 });
                //CheckGateway ();
                //var newHomeId = Home2New ();
                //if (newHomeId == "") { } else { }
                //Account2New (etPwd.Text.Trim());
                //return;
                //Account2New ("12345678");
                //Home2New ();
                ////迁移云端其他备份
                //var moveCloudDataResult = MoveCloudBackup ();
                //Application.RunOnMainThread (() => {
                //    btnTipMsg.Text = $"Failed to migrate cloud backup list.{moveCloudDataResult}";
                //    btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                //    loading.Hide ();
                //    return;
                //});
#endif
                if (etPwd.Text.Trim() == "") {
@@ -218,6 +246,7 @@
                etPwd.Visible = false;
                btnSave.MouseUpEventHandler = (sender2, e2) => {
                    dialog.Close ();
                    Packet.lockedAction = null;
                };
            } else {
@@ -231,13 +260,13 @@
            //3.接收升级文件获取请求
            //迁移账号
            #endregion
#endregion
        }
        #region 云端
#region 云端
        /// <summary>
        /// 账号登录验证
        /// </summary>
@@ -295,6 +324,7 @@
            if (revertObj != null) {
                if (revertObj.data != null) {
                    var newHomeInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<Move_HomeInfo> (revertObj.data.ToString ());
                    newHomeId = newHomeInfo.homeId;
                    return newHomeInfo.homeId;
                }
            }
@@ -351,32 +381,36 @@
        /// </summary>
        /// <param name="newHomeId"></param>
        /// <returns></returns>
        private string moveFolder2New (string newHomeId)
        private string moveFolder2New (string newHomeId,string folderName = "")
        {
            Dictionary<string, object> dic = new Dictionary<string, object> ();
            dic.Add ("backupDataType", "HDL_ON");
            dic.Add ("homeId",newHomeId);
            dic.Add ("userId",newUserId);
            dic.Add ("backupClassify", "USER_DEFINED_BACKUP");
            dic.Add ("folderName", "MigrateBackup" + DateTime.Now.ToString ());
            dic.Add ("tenantId", "202106");
            var requestJson = HttpUtil.GetSignRequestJson (dic);
            var revertObj = MainPage.RequestHttps ("/home-wisdom/data/move/folder/save", requestJson, false, false, SeverAddr);
            if(revertObj!= null) {
                if(revertObj.code == "0") {
                    var resultObj = Newtonsoft.Json.JsonConvert.DeserializeObject<FolderObj> (revertObj.data.ToString ());
                    return resultObj.id;
            try {
                Dictionary<string, object> dic = new Dictionary<string, object> ();
                dic.Add ("backupDataType", "HDL_ON");
                dic.Add ("homeId", newHomeId);
                dic.Add ("userId", newUserId);
                dic.Add ("backupClassify", "USER_DEFINED_BACKUP");
                dic.Add ("folderName", folderName == "" ? "MigrateBackup" + DateTime.Now.ToString () : folderName);
                dic.Add ("tenantId", "202106");
                var requestJson = HttpUtil.GetSignRequestJson (dic);
                var revertObj = MainPage.RequestHttps ("/home-wisdom/data/move/folder/save", requestJson, false, false, SeverAddr);
                if (revertObj != null) {
                    if (revertObj.code == "0") {
                        var resultObj = Newtonsoft.Json.JsonConvert.DeserializeObject<FolderObj> (revertObj.data.ToString ());
                        return resultObj.id;
                    }
                }
                return "";
            } catch {
                return "";
            }
            return "";
        }
        private string MoveFile2New(string newHomeId,string backupId)
        private string MoveFile2New(string backupId)
        {
            Dictionary<string, object> dic = new Dictionary<string, object> ();
            dic.Add ("backupId", backupId);//1534728347497418754//1534728860322385922
            dic.Add ("backupId", backupId);
            dic.Add ("homeId", newHomeId);
            dic.Add ("userId", newUserId);
            dic.Add ("backupClassify", "USER_DEFINED_BACKUP");
@@ -409,7 +443,7 @@
                            continue;
                        }
                    }
                }
                }
            }
            if (!dic.ContainsKey ("list")) {
                dic.Add ("list", fileObjs);
@@ -425,6 +459,128 @@
            }
            return "";
        }
        /// <summary>
        /// 迁移旧云端备份列表到新云端
        /// </summary>
        /// <returns></returns>
        private void MoveOldBackupList ()
        {
            try {
                GetUserFolderObj requestObj = new GetUserFolderObj () { LevelID = UserConfig.Instance.CurrentRegion.RegionID };
                var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj);
                var revertObj = MainPage.RequestHttps ("GetUserFolder", requestJson, true, false);//获取旧服务器备份列表
                if (revertObj.StateCode == "SUCCESS") {
                    var responseDataObj = Newtonsoft.Json.JsonConvert.DeserializeObject<List<FolderRes>> (revertObj.ResponseData.ToString ());
                    int index = 1;
                    foreach (var folder in responseDataObj) {
                        Application.RunOnMainThread (() => {
                            try {
                                btnTipMsg.Text = $"Migrating server backup {index} / {responseDataObj.Count + 1}.";
                                btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                            } catch { }
                        });
                        try {
                            var requestObj2 = new UserBackupListObj () { LevelID = folder.FolderID };
                            var requestJson2 = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj2);
                            var revertObj2 = MainPage.RequestHttps ("UserBackupList", requestJson2);//下载旧服务器的备份文件列表
                            if (revertObj2.StateCode == "SUCCESS") {
                                var newFolderId = moveFolder2New (newHomeId, folder.FolderName);//在新服务器创建新的备份,获取备份ID
                                if (string.IsNullOrEmpty (newFolderId)) {//如果新服务器备份ID为空,可能报错了,新服务器可能已经存在这个备份
                                    var backupInfoRes = Newtonsoft.Json.JsonConvert.DeserializeObject<List<BackupInfoRes>> (revertObj2.ResponseData.ToString ());
                                    MoveOldBackupFile2New (newFolderId, backupInfoRes);
                                }
                            }
                        } catch { }
                    }
                }
            } catch {
            }
        }
        /// <summary>
        /// 迁移旧服务器备份文件到新服务器
        /// </summary>
        /// <param name="backupId"></param>
        /// <returns></returns>
        private string MoveOldBackupFile2New ( string backupId, List<BackupInfoRes> responseDataObj)
        {
            Dictionary<string, object> dic = new Dictionary<string, object> ();
            dic.Add ("backupId", backupId);
            dic.Add ("homeId", newHomeId);
            dic.Add ("userId", newUserId);
            dic.Add ("backupClassify", "USER_DEFINED_BACKUP");
            dic.Add ("tenantId", "202106");
            List<BackupFileObj> fileObjs = new List<BackupFileObj> ();
            int index = 0;
            foreach (var file in responseDataObj) {
                var fileName = file.FileName;
                if (fileName == "null" || "UserConfig" == fileName || fileName == UserInfo.GlobalRegisterFile) {
                    continue;
                }
                index++;
                var requestObj3 = new BackupDetailObj () { Id = file.Id };
                var requestJson3 = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj3);
                var revertObj3 = MainPage.RequestHttps ("BackupDetail", requestJson3);//下载旧服务器的备份文件
                if (revertObj3.StateCode == "SUCCESS") {
                    var jsonBytes = Newtonsoft.Json.JsonConvert.SerializeObject (revertObj3.ResponseData);
                    var byresss = Newtonsoft.Json.JsonConvert.DeserializeObject<byte []> (jsonBytes);
                    BackupFileObj backupFileObj = new BackupFileObj () { fileName = fileName, content = byresss };
                    fileObjs.Add (backupFileObj);
                    if (fileObjs.Count > 9) {
                        if (!dic.ContainsKey ("list")) {
                            dic.Add ("list", fileObjs);
                        }
                        var json = HttpUtil.GetSignRequestJson (dic);
                        var revertObj_foreach = MainPage.RequestHttps ("/home-wisdom/data/move/file/save", json, false, false, SeverAddr);
                        if (revertObj_foreach != null) {
                            if (revertObj_foreach.code == "0") {
                                fileObjs.Clear ();
                                continue;
                            }
                        }
                    }
                }
            }
            if (!dic.ContainsKey ("list")) {
                dic.Add ("list", fileObjs);
            }
            var requestJson = HttpUtil.GetSignRequestJson (dic);
            var revertObj = MainPage.RequestHttps ("/home-wisdom/data/move/file/save", requestJson, false, false, SeverAddr);
            if (revertObj != null) {
                if (revertObj.code == "0") {
                    return "true";
                }
            }
            return "";
        }
        /// 迁移服务器全部备份
        /// </summary>
        private string MoveCloudBackup ()
        {
            var dic = new Dictionary<string, object> ();
            dic.Add ("oldPlatformToken", MainPage.LoginUser.LoginTokenString);//旧平台token
            dic.Add ("oldPlatformHomeId", UserConfig.Instance.CurrentRegion.RegionID);//旧平台住宅id
            dic.Add ("homeId", newHomeId);//新平台住宅id
            dic.Add ("userId", newUserId);//新平台用户id
            dic.Add ("tenantId", "202106");//租户id
            var requestJson = HttpUtil.GetSignRequestJson (dic);
            var revertObj = MainPage.RequestHttps ("/home-wisdom/data/move/backup/all", requestJson, false, false, SeverAddr);
            if (revertObj != null) {
                if (revertObj.code == "0") {
                }
                return revertObj.code;
            }
            return "-99";
        }
        /// <summary>
        /// 获取定时器列表
        /// </summary>
@@ -508,7 +664,7 @@
        #endregion
#endregion
        /// <summary>
        /// 检测一端口信息
@@ -533,8 +689,6 @@
                GatewayBase common = null;
                string gateWayString = "";
                if (gateWayList.Count > 0) {
                    foreach (var gatewayFileName in gateWayList) {
                        var tempStrings = gatewayFileName.Split ('_');
                        if (tempStrings [1].ToString () == DeviceType.OnePortBus.ToString () || tempStrings [1].ToString () == DeviceType.RCU.ToString () ||
@@ -542,6 +696,9 @@
                            gateWayString = CommonPage.MyEncodingUTF8.GetString (IO.FileUtils.ReadFile (gatewayFileName));
                            common = Newtonsoft.Json.JsonConvert.DeserializeObject<GatewayBase> (gateWayString);
                            //bool
                            CommonPage.IsRemote = false;
                            Control.ControlBytesSendHasReturn (Command.ReadGateway, common.SubnetID, common.DeviceID, new byte [] { CommonPage.RandomHigh, CommonPage.RandomLow });
                            var bytes = Control.ControlBytesSendHasReturn (Command.readGatewayVision, common.SubnetID, common.DeviceID, new byte [] { });
                            if(bytes == null) {
@@ -567,18 +724,18 @@
                                    btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                });
                                result = 100;
                            } else if (!visionString.Contains ("Ind_V02.35U_2019/06/25")) {//目前只允许升级这个固件的网关
                                Application.RunOnMainThread (() => {
                                    btnTipTitle.Text = "The gateway does not support automatic migration. Please contact technical support.";
                                    btnTipTitle.Height = Application.GetRealHeight (150);
                                    btnTipTitle.TextColor = SkinStyle.Current.DelColor;
                                    btnTipMsg.Text = "";
                                    etPwd.Visible = false;
                                    loading.Hide ();
                                    btnSave.Visible = false;
                                    btnClose.Width = Application.GetRealWidth (500);
                                });
                                return;
                            //} else if (!visionString.Contains ("Ind_V02.35U_2019/06/25")) {//目前只允许升级这个固件的网关
                            //    Application.RunOnMainThread (() => {
                            //        btnTipTitle.Text = "The gateway does not support automatic migration. Please contact technical support.";
                            //        btnTipTitle.Height = Application.GetRealHeight (150);
                            //        btnTipTitle.TextColor = SkinStyle.Current.DelColor;
                            //        btnTipMsg.Text = "";
                            //        etPwd.Visible = false;
                            //        loading.Hide ();
                            //        btnSave.Visible = false;
                            //        btnClose.Width = Application.GetRealWidth (500);
                            //    });
                            //    return;
                            } else {
                                Application.RunOnMainThread (() => {
                                    btnTipMsg.Text = "Upgrading gateway.";
@@ -638,8 +795,9 @@
                                    }
                                }
                            }
                            //重新设置一下子网号
                            SetSubnetId (common);
                            System.Threading.Thread.Sleep (1000);
                            if (result == 100) {
@@ -707,7 +865,7 @@
                                    return;
                                }
                                //迁移住宅,获取新的homeid
                                var newHomeId = Home2New ();
                                newHomeId = Home2New ();
                                if (newHomeId == "") {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "Home migration failed. Please try again.";
@@ -739,6 +897,8 @@
                                //获取上网秘钥
                                var netKet = GetInternetAccessKey (common.MAC.Replace (".", ""));
                                if (!string.IsNullOrEmpty (netKet)) {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "The Internet access key was obtained successfully. It is being written.";
@@ -769,6 +929,110 @@
                                            return;
                                        });
                                    }
#if DEBUG
                                    System.Threading.Thread.Sleep (5000);
#endif
                                    CommonPage.FindGateway = true;
                                    try {
                                        #region 搜索设备
                                        CommonPage.LocalPhoneFindDevice = true;
                                        CommonPage.RandomHigh = (byte)new Random ().Next (255);
                                        CommonPage.RandomLow = (byte)new Random ().Next (255);
                                        CommonPage.GateWayList.Clear ();
                                        CommonPage.FindGateway = true;
                                        //如果两次都没有数据反馈,就不读取
                                        int readCount = 2;
                                        while (0 < readCount) {
                                            readCount--;
                                            System.IO.MemoryStream ms = new System.IO.MemoryStream ();
                                            ms.WriteByte (CommonPage.RandomHigh);
                                            ms.WriteByte (CommonPage.RandomLow);
                                            List<Common> list = CommonPage.GateWayList;
                                            int tempCount = list.Count;
                                            string s = ";";
                                            for (int i = 0; i < list.Count; i++) {
                                                Common common2 = list [i];
                                                if (s.Contains (";" + common2.SubnetID.ToString () + ":" + common2.DeviceID.ToString ()))
                                                    continue;
                                                s += common2.SubnetID.ToString () + ":" + common2.DeviceID.ToString () + ";";
                                                ms.WriteByte (common2.SubnetID);
                                                ms.WriteByte (common2.DeviceID);
                                            }
                                            Control control = new Control ();
                                            Console.WriteLine ("组播搜索网关,搜索地址是:" + CommonPage.EndPoint.ToString () + "    " + CommonPage.GateWayList.Count);
                                            control.Send (new Target () {
                                                IPEndPoint = CommonPage.EndPoint,
                                                Command = Command.ReadGateway,
                                                SubnetID = 0xFF,
                                                DeviceID = 0xFF,
                                                AddData = ms.ToArray ()
                                            }, SendCount.Zero, false);
                                            Console.WriteLine ("广播搜索网关,搜索地址是:" + new Net.NetWiFi ().BroadcastIpAddress.ToString () + "    " + CommonPage.GateWayList.Count);
                                            control.Send (new Target () {
                                                IPEndPoint = new System.Net.IPEndPoint (new Net.NetWiFi ().BroadcastIpAddress, 6000),
                                                Command = Command.ReadGateway,
                                                SubnetID = 0xFF,
                                                DeviceID = 0xFF,
                                                AddData = ms.ToArray ()
                                            }, SendCount.Zero, false);
                                            System.Threading.Thread.Sleep (800);
                                            //如果数量不相等,就重置次数
                                            if (tempCount != CommonPage.GateWayList.Count) {
                                                readCount = 2;
                                            }
                                        }
                                        CommonPage.FindGateway = false;
                                        CommonPage.LocalPhoneFindDevice = false;
                                        #endregion
                                    } catch (Exception ex) {
                                        Console.WriteLine (ex.ToString ());
                                    } finally {
                                        if (CommonPage.GateWayList.Count > 0) {
                                            foreach (var gateway1 in CommonPage.GateWayList) {
                                                var bingResidenceIdBytes = Control.ControlBytesSendHasReturn (Command.Read_APP_Data_STORE_1D5C_CMD, common.SubnetID, common.DeviceID, new byte [] { });
                                                if (bingResidenceIdBytes == null) {
                                                    continue;
                                                }
                                                int bingResideceId = 0;
                                                for (int i = 0; i < bingResidenceIdBytes.Length; i++) {
                                                    bingResideceId += (int)(bingResidenceIdBytes [i] * Math.Pow (256, 3 - i));
                                                }
                                                if (bingResideceId != UserConfig.Instance.CurrentRegion.RegionID && bingResideceId != 0) {
                                                } else {
                                                    //写入上网秘钥
                                                    writeSecretKeyResult = WriteSecretKey (gateway1.SubnetID, gateway1.DeviceID, secretkeySendBytes);
                                                    if (writeSecretKeyResult) {
                                                        Application.RunOnMainThread (() => {
                                                            btnTipMsg.Text = "The Internet access key was written successfully.";
                                                        });
                                                    } else {
                                                        Application.RunOnMainThread (() => {
                                                            btnTipMsg.Text = "Failed to write Internet secret key.";
                                                            btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                                        });
                                                    }
#if DEBUG
                                                    System.Threading.Thread.Sleep (5000);
#endif
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "Failed to obtain the Internet secret key. Please try again.";
@@ -778,7 +1042,6 @@
                                }
                                //写入mqtt域名信息
                                SetGateWayMqttUrlAddress (common.SubnetID, common.DeviceID);
                                //迁移网关
                                var moveGatewayResult = Gateway2New (common.MAC.Replace (".", ""), newHomeId, common.SubnetID);
@@ -795,10 +1058,25 @@
                                    });
                                    return;
                                }
                                //迁移云端其他备份
                                var moveCloudDataResult = MoveCloudBackup ();
                                if (moveCloudDataResult != "0") {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = $"Failed to migrate cloud backup list.{moveCloudDataResult}";
                                        btnTipMsg.TextColor = SkinStyle.Current.DelColor;
                                        loading.Hide ();
                                        return;
                                    });
                                }
                                //创建迁移备份文件夹
                                var backId = moveFolder2New (newHomeId);
                                //迁移备份文件
                                var moveFileResult = MoveFile2New (newHomeId, backId);
                                var moveFileResult = MoveFile2New (backId);
                                // Application.RunOnMainThread (() => {
                                //     btnTipMsg.Text = "Migrating server backup.";
                                //     btnTipMsg.TextColor = SkinStyle.Current.TextColor;
                                // });
                                // MoveOldBackupList ();
                                if (moveFileResult == "true") {
                                    Application.RunOnMainThread (() => {
                                        btnTipMsg.Text = "Migration backup succeeded, migrating Schedule data.";
@@ -933,6 +1211,28 @@
        }
        /// <summary>
        /// 设置子网号
        /// </summary>
        /// <param name="gatewayDevice"></param>
        private void SetSubnetId (GatewayBase gatewayDevice)
        {
            string [] macAddress = gatewayDevice.MAC.Split ('.');
                byte [] Musics = new byte [10];
                for (int i = 0; i < macAddress.Length; i++) {
                    Musics [i] = Convert.ToByte (macAddress [i], 16);
                }
                try {
                    Musics [8] = Convert.ToByte (Convert.ToInt32 (gatewayDevice.SubnetID));
                    if (Musics [8] < 0 || Musics [8] > 255) {
                        throw new Exception ();
                    }
                } catch {
                    return;
                }
                Control.ControlBytesSend (Command.SetDeviceSubnetID, gatewayDevice.SubnetID, gatewayDevice.DeviceID, Musics);
        }
        /// <summary>
        /// 设备网关开启远程
        /// </summary>
        private bool SetGatewayRemote(byte subnetId, byte deviceId)