using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json.Linq; using Shared; namespace Shared.SimpleControl.Phone { public class DeviceSecret { public string deviceSecret; } public class MigrationServer { /// /// 标记完成迁移 /// private bool finish = false; #if DEBUG private string SeverAddr = "https://test-gz.hdlcontrol.com"; #else private string SeverAddr = "https://bahrain-gateway.hdlcontrol.com"; #endif FrameLayout contentView; Button btnTipTitle; Button btnTipMsg; Loading loading; EditText etPwd; string pwd; string newUserId; 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 (); tipLockedAction = () => { Application.RunOnMainThread (() => { if (!showedLockedTip) { sssAlert.Show (); showedLockedTip = true; sssAlert.ResultEventHandler += (sd, dd) => { showedLockedTip = false; }; } }); }; Packet.lockedAction = tipLockedAction; } public void ShowDialog() { #region 弹窗 Dialog dialog = new Dialog (); FrameLayout dialogBodyView = new FrameLayout () { Gravity = Gravity.Center, Width = Application.GetRealWidth (500), Height = Application.GetRealHeight (500), BackgroundColor = SkinStyle.Current.DialogColor, Radius = 5, BorderColor = SkinStyle.Current.Transparent, BorderWidth = 0, }; dialog.AddChidren (dialogBodyView); Button btnTitle = new Button () { Height = Application.GetRealHeight (80), BackgroundColor = SkinStyle.Current.DialogTitle, TextAlignment = TextAlignment.Center, TextID = R.MyInternationalizationString.Tip, TextColor = SkinStyle.Current.DialogTextColor }; dialogBodyView.AddChidren (btnTitle); contentView = new FrameLayout () { Y = Application.GetRealHeight (80), Height = Application.GetRealHeight (340), BackgroundColor = SkinStyle.Current.DialogColor, }; dialogBodyView.AddChidren (contentView); btnTipTitle = new Button () { Gravity = Gravity.CenterHorizontal, Y = Application.GetRealHeight (20), Width = Application.GetRealWidth (400), Height = Application.GetRealHeight (80), Text = "Please enter the password to confirm the migration", TextAlignment = TextAlignment.CenterLeft, TextColor = SkinStyle.Current.TextColor, IsMoreLines = true, }; contentView.AddChidren (btnTipTitle); etPwd = new EditText () { Gravity = Gravity.CenterHorizontal, Y = btnTipTitle.Bottom, Width = Application.GetRealWidth (400), Height = Application.GetRealHeight (80), TextAlignment = TextAlignment.Center, Radius = 5, BorderColor = SkinStyle.Current.BorderColor, BorderWidth = 1, TextColor = SkinStyle.Current.TextColor, SecureTextEntry = true }; contentView.AddChidren (etPwd); etPwd.EditorEnterAction += (obj) => { Application.HideSoftInput (); }; btnTipMsg = new Button () { Gravity = Gravity.CenterHorizontal, Y = etPwd.Bottom, Width = Application.GetRealWidth (400), Height = Application.GetRealHeight (120), TextAlignment = TextAlignment.CenterLeft, TextColor = SkinStyle.Current.DelColor, IsMoreLines = true, }; contentView.AddChidren (btnTipMsg); dialogBodyView.AddChidren (loading); FrameLayout bottomView = new FrameLayout () { Y = Application.GetRealHeight (420), Height = Application.GetRealHeight (85), BackgroundColor = SkinStyle.Current.DialogTitle }; dialogBodyView.AddChidren (bottomView); btnClose = new Button () { Width = Application.GetRealWidth (249), TextID = R.MyInternationalizationString.Close, TextAlignment = TextAlignment.Center }; bottomView.AddChidren (btnClose); btnClose.MouseUpEventHandler += (send2er, e2) => { dialog.Close (); Packet.lockedAction = null; }; Button btnBottomLine = new Button () { X = btnClose.Right, Width = 1, BackgroundColor = SkinStyle.Current.Black50Transparent, }; bottomView.AddChidren (btnBottomLine); btnSave = new Button () { X = btnBottomLine.Right, Width = Application.GetRealWidth (249), TextID = R.MyInternationalizationString.Confrim, TextAlignment = TextAlignment.Center }; bottomView.AddChidren (btnSave); etPwd.TextChangeEventHandler = (sender, e) => { btnTipMsg.Text = ""; }; btnSave.MouseUpEventHandler += (sender2, e2) => { if (finish) { dialog.Close (); Packet.lockedAction = null; return; } #if DEBUG //var moveAccontResult = Account2New ("12345678"); //var newHomeId = Home2New (); ////迁移网关 //var moveGatewayResult = Gateway2New ("4D59383553502243", newHomeId, 0); #endif if (etPwd.Text.Trim() == "") { btnTipMsg.Text = "Please input a password"; return; } loading.Start (""); pwd = etPwd.Text.Trim (); //验证密码 new System.Threading.Thread (() => { try { var verResult = AcountVer (pwd); if (verResult) { Application.RunOnMainThread (() => { btnTipMsg.Text = "Verification passed, detecting gateway configuration"; btnTipMsg.TextColor = SkinStyle.Current.TextColor; CheckGateway (); }); } else { Application.RunOnMainThread (() => { btnTipMsg.Text = "Password error, verification failed, please try again."; loading.Hide (); }); } } catch { Application.RunOnMainThread (() => { loading.Hide (); }); } finally { } }) { IsBackground = true }.Start (); }; dialog.Show (); if (MainPage.WiFiStatus != "CrabtreeAdd/WiFi.png") { //status = btnSave.Text = "ReCheck"; btnTipMsg.Text = "Please connect the gateway device in the LAN."; etPwd.Visible = false; btnSave.MouseUpEventHandler = (sender2, e2) => { dialog.Close (); Packet.lockedAction = null; }; } else { } //2.进入网关升级模式 //3.接收升级文件获取请求 //迁移账号 #endregion } #region 云端 /// /// 账号登录验证 /// /// /// private bool AcountVer(string pwd) { var requestObj = new LoginObj () { Account = MainPage.LoginUser.AccountString, Password = pwd, Company = MainPage.SoftSmsType }; var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj); var revertObj = MainPage.RequestHttps ("Login", requestJson, false); if (revertObj.StateCode == "SUCCESS") { return true; } else { return false; } } /// /// 账号迁移 /// /// /// public bool Account2New (string pwd) { Dictionary dicAccount = new Dictionary (); dicAccount.Add ("email", MainPage.LoginUser.AccountString); dicAccount.Add ("language", "ENGLISH"); dicAccount.Add ("appCode", "HDL-HOME-IND-APP"); dicAccount.Add ("pwd", pwd); dicAccount.Add ("tenantId", "202106"); var requestJson = HttpUtil.GetSignRequestJson (dicAccount);// Newtonsoft.Json.JsonConvert.SerializeObject (dicAccount); var revertObj2 = MainPage.RequestHttps ("/home-wisdom/data/move/user/save", requestJson, false, false, SeverAddr); if (revertObj2.code == "0") { var info = Newtonsoft.Json.JsonConvert.DeserializeObject (revertObj2.data.ToString ()); if (info != null) { newUserId = info.memberId; } return true; } else { return false; } } /// /// 住宅迁移 /// /// new homeId private string Home2New () { Dictionary dic = new Dictionary (); dic.Add ("homeName", UserConfig.Instance.CurrentRegion.RegionName); dic.Add ("userId", newUserId); dic.Add ("homeType", "BUSPRO"); dic.Add ("tenantId", "202106"); var requestJson = HttpUtil.GetSignRequestJson (dic);// Newtonsoft.Json.JsonConvert.SerializeObject (dic); var revertObj = MainPage.RequestHttps ("/home-wisdom/data/move/home/save", requestJson, false, false, SeverAddr); if (revertObj != null) { if (revertObj.data != null) { var newHomeInfo = Newtonsoft.Json.JsonConvert.DeserializeObject (revertObj.data.ToString ()); return newHomeInfo.homeId; } } return ""; } /// /// 迁移网关 /// /// /// 新平台的住宅id /// private bool Gateway2New (string mac,string newHomeId,int subnetId) { Dictionary dic = new Dictionary (); dic.Add ("mac", mac); dic.Add ("homeId", newHomeId); dic.Add ("userId", newUserId); dic.Add ("subnetId",subnetId); dic.Add ("gatewayType", 0); dic.Add ("tenantId", "202106"); var requestJson = HttpUtil.GetSignRequestJson (dic); var revertObj = MainPage.RequestHttps ("/home-wisdom/data/move/gateway/save", requestJson, false, false, SeverAddr); if (revertObj!= null && revertObj.code == "0") { return true; } return false; } /// /// 获取上网密秘钥 /// /// private string GetInternetAccessKey (string mac) { Dictionary dic = new Dictionary (); dic.Add ("supplier", "HDL"); dic.Add ("mac", mac); dic.Add ("spk", "BUSUDPGATEWAY"); var requestJson = HttpUtil.GetSignRequestJson (dic); //var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (dic); var revertObj = MainPage.RequestHttps ("/home-wisdom/program/device/secret/applyDeviceSecret", requestJson, false, false, SeverAddr); //var revertObj = MainPage.RequestHttps ("/smart-open/third/device/authByMac", requestJson, false, false, SeverAddr); if (revertObj.code == "0") { return revertObj.data.ToString (); } else { } return ""; } /// /// 迁移备份 /// /// /// private string moveFolder2New (string newHomeId) { Dictionary dic = new Dictionary (); 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 (revertObj.data.ToString ()); return resultObj.id; } } return ""; } private string MoveFile2New(string newHomeId,string backupId) { Dictionary dic = new Dictionary (); dic.Add ("backupId", backupId);//1534728347497418754//1534728860322385922 dic.Add ("homeId", newHomeId); dic.Add ("userId", newUserId); dic.Add ("backupClassify", "USER_DEFINED_BACKUP"); dic.Add ("tenantId", "202106"); List fileObjs = new List (); var backuplist = IO.FileUtils.ReadFiles (); int index = 0; foreach (var fileName in backuplist) { index++; /// /// 如果是特殊的注册登陆文件,则不需要备份到服务器 /// if (fileName == UserInfo.GlobalRegisterFile) { continue; } BackupFileObj backupFileObj = new BackupFileObj () { fileName = fileName, content = IO.FileUtils.ReadFile (fileName) }; 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); //} else { // dic ["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 ""; } /// /// 获取定时器列表 /// /// private List GetTimer (string newHomeId) { var requestObj = new Timer () { RegionID = UserConfig.Instance.CurrentRegion.RegionID }; var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject (requestObj); var revertObj = MainPage.RequestHttps ("GetTimerList", requestJson); if (revertObj.StateCode == "SUCCESS") { var timers = Newtonsoft.Json.JsonConvert.DeserializeObject> (revertObj.ResponseData.ToString ()); if(timers.Count > 0) { List backups = new List (); foreach (var timer in timers) { var timerContent = System.Text.Encoding.UTF8.GetBytes (Newtonsoft.Json.JsonConvert.SerializeObject (timer)); BackupFileObj backupFileObj = new BackupFileObj () { fileName = timer.TimerName, content = timerContent }; backups.Add (backupFileObj); } return backups; } } else { return null; } return new List (); } /// /// 定时器备份 /// /// private string BackupSchedule (string newHomeId, List backups) { Dictionary dic = new Dictionary (); dic.Add ("backupDataType", "HDL_ON"); dic.Add ("homeId", newHomeId); dic.Add ("userId", newUserId); dic.Add ("backupClassify", "CUSTOM_PROJECT_BACKUP"); dic.Add ("folderName", "ScheduleBackup" + 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 (revertObj.data.ToString ()); var ddd = MoveTimerFileData (newHomeId,resultObj.id, backups); return ddd; } } return ""; } /// /// 保存定时器数据 /// /// /// /// /// private string MoveTimerFileData (string newHomeId, string backupId, List fileObjs) { Dictionary dic = new Dictionary (); dic.Add ("backupId", backupId); dic.Add ("homeId", newHomeId); dic.Add ("userId", newUserId); dic.Add ("backupClassify", "CUSTOM_PROJECT_BACKUP"); dic.Add ("tenantId", "202106"); 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 ""; } #endregion /// /// 检测一端口信息 /// /// /// public void CheckGateway() { Application.RunOnMainThread (() => { loading.Start (""); }); new System.Threading.Thread (() => { //1.检测一端口固件 var localFileList = IO.FileUtils.ReadFiles (); var gateWayList = localFileList.FindAll ((obj) => { return (obj.StartsWith ("Equipment_")) && ( obj.Split ('_') [1].ToString () == DeviceType.OnePortBus.ToString () || obj.Split ('_') [1].ToString () == DeviceType.RCU.ToString () || obj.Split ('_') [1].ToString () == DeviceType.OnePortWirelessFR.ToString ()); }); List linkList = new List (); 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 () || tempStrings [1].ToString () == DeviceType.OnePortWirelessFR.ToString ()) { gateWayString = CommonPage.MyEncodingUTF8.GetString (IO.FileUtils.ReadFile (gatewayFileName)); common = Newtonsoft.Json.JsonConvert.DeserializeObject (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) { Application.RunOnMainThread (() => { btnTipMsg.Text = "The gateway cannot be searched. Please make sure it is on the same network as the gateway."; btnTipMsg.TextColor = SkinStyle.Current.DelColor; loading.Hide (); }); return; } else { Application.RunOnMainThread (() => { btnTipMsg.Text = "Gateway connection succeeded. Checking gateway firmware."; btnTipMsg.TextColor = SkinStyle.Current.TextColor; }); } var visionString = Encoding.GetEncoding ("gb2312").GetString (bytes); int result = -99; if (visionString.Contains ("Ind_C03.02U_2022/06/22")) { Application.RunOnMainThread (() => { btnTipMsg.Text = "Gateway firmware has been upgraded, initializing gateway."; 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 { Application.RunOnMainThread (() => { btnTipMsg.Text = "Upgrading gateway."; btnTipMsg.TextColor = SkinStyle.Current.TextColor; }); //需要升级一端口 List> upgradeData = ReadUpgradeData (); for (int i = 0; i < 7; i++) { Control.ControlBytesSend (Command.enjoyUpgrade, common.SubnetID, common.DeviceID, new byte [] { }); } byte [] arrayTemp = new byte [4]; arrayTemp [0] = Convert.ToByte ((upgradeData.Count & 0xFF000000) >> 24); arrayTemp [1] = Convert.ToByte ((upgradeData.Count & 0xFF0000) >> 16); arrayTemp [2] = Convert.ToByte ((upgradeData.Count & 0xFF00) >> 8); arrayTemp [3] = Convert.ToByte (upgradeData.Count & 0xFF); while (true) { var ub = MainPage.GatewayStatus.Split ("_"); if (ub.Length > 1) { result = Convert.ToInt32 (ub [1]); //if (result < result0 && result0 < 100) { //result = result0; Application.RunOnMainThread (() => { btnTipMsg.Text = "Upgrading gateway " + result + "/" + upgradeData.Count; }); } } if (MainPage.GatewayStatus.Contains ("upgrading") && result == 0) { SendUpgradeData (common.SubnetID, common.DeviceID, arrayTemp); Application.RunOnMainThread (() => { btnTipMsg.Text = "Upgrading gateway " + result + "/" + upgradeData.Count; }); } else if (result == -99) { System.Threading.Thread.Sleep (100); continue; } else if (result == 100) { Application.RunOnMainThread (() => { btnTipMsg.Text = "Gateway upgrade succeeded. Initializing gateway."; btnTipMsg.TextColor = SkinStyle.Current.TextColor; }); //初始化标记 MainPage.GatewayStatus = ""; break; } else { if (upgradeData.Count >= result) { var listPack = upgradeData [result - 1];// byte [] packData = new byte [2 + listPack.Count]; packData [0] = Convert.ToByte (result / 256); packData [1] = Convert.ToByte (result % 256); Array.Copy (listPack.ToArray (), 0, packData, 2, listPack.Count); Console.WriteLine ("packId" + result); SendUpgradeData (common.SubnetID, common.DeviceID, packData); } } } } //重新设置一下子网号 SetSubnetId (common); System.Threading.Thread.Sleep (1000); if (result == 100) { //初始化网关 var initialBytes = new byte [12]; initialBytes [0] = 0x00; initialBytes [1] = 0x00; string [] mac = common.MAC.Split ('.'); for (int i = 0; i < mac.Length; i++) initialBytes [i + 2] = Convert.ToByte (mac [i], 16); initialBytes [10] = Convert.ToByte (common.SubnetID); initialBytes [11] = 0x00; //初始化网关命令发送 InitializationGateway (common.SubnetID, common.DeviceID, initialBytes); int initiaIndex = 0; while (true) { if (MainPage.GatewayStatus != "Initialization_complete") { System.Threading.Thread.Sleep (100); } else if (initiaIndex == 0) { //初始化标记 MainPage.GatewayStatus = ""; Application.RunOnMainThread (() => { btnTipMsg.Text = "Successfully initialized the gateway. Opening the gateway remote configuration."; btnTipMsg.TextColor = SkinStyle.Current.TextColor; }); break; } initiaIndex++; if(initiaIndex > 200) { break; } } //开启网关远程 var setRemoteResult = SetGatewayRemote (common.SubnetID, common.DeviceID); if (setRemoteResult) { Application.RunOnMainThread (() => { btnTipMsg.Text = "The gateway remote has been enabled, and the account information is being migrated."; btnTipMsg.TextColor = SkinStyle.Current.TextColor; }); } else { Application.RunOnMainThread (() => { btnTipMsg.Text = "Gateway remote opening failed. Please try again."; btnTipMsg.TextColor = SkinStyle.Current.DelColor; loading.Hide (); }); return; } //迁移账号 var moveAccontResult = Account2New (pwd); if (moveAccontResult) { Application.RunOnMainThread (() => { btnTipMsg.Text = "The account information is migrated successfully. The account is being migrated."; btnTipMsg.TextColor = SkinStyle.Current.TextColor; }); } else { Application.RunOnMainThread (() => { btnTipMsg.Text = "Account migration failed. Please try again."; btnTipMsg.TextColor = SkinStyle.Current.DelColor; loading.Hide (); }); return; } //迁移住宅,获取新的homeid var newHomeId = Home2New (); if (newHomeId == "") { Application.RunOnMainThread (() => { btnTipMsg.Text = "Home migration failed. Please try again."; btnTipMsg.TextColor = SkinStyle.Current.DelColor; loading.Hide (); }); return; } else { btnTipMsg.Text = "Residence migration succeeded. Gateway residence information is being configured."; btnTipMsg.TextColor = SkinStyle.Current.TextColor; } //写入homeId var writeHomeIdResult = SetGateWayAdminInfo (common.SubnetID, newHomeId); if (writeHomeIdResult) { Application.RunOnMainThread (() => { btnTipMsg.Text = "The gateway home information is configured successfully, and the Internet access key is being obtained."; btnTipMsg.TextColor = SkinStyle.Current.TextColor; }); } else { Application.RunOnMainThread (() => { btnTipMsg.Text = "Gateway home information configuration failed. Please try again."; btnTipMsg.TextColor = SkinStyle.Current.DelColor; loading.Hide (); return; }); } //获取上网秘钥 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."; btnTipMsg.TextColor = SkinStyle.Current.TextColor; }); var deviceSecret = Newtonsoft.Json.JsonConvert.DeserializeObject (netKet); var secretkeyByte = Encoding.UTF8.GetBytes (deviceSecret.deviceSecret); var secretkeySendBytes = new byte [secretkeyByte.Length + 1]; secretkeySendBytes [0] = 1; Array.Copy (secretkeyByte, 0, secretkeySendBytes, 1, secretkeyByte.Length); //for (int i = 0; i < netKet.Length; i++) { // secretkeyByte [i] = Convert.ToByte (netKet [i].ToString (), 16); //} //Array.Copy (secretkeyByte, 0, secretkeySendBytes, 1, secretkeyByte.Length); //secretkeySendBytes [0] = 1; System.Threading.Thread.Sleep (10000); //写入上网秘钥 var writeSecretKeyResult = WriteSecretKey (common.SubnetID, common.DeviceID, secretkeySendBytes); if (writeSecretKeyResult) { Application.RunOnMainThread (() => { btnTipMsg.Text = "The Internet access key was written successfully. The gateway is being migrated."; }); } else { Application.RunOnMainThread (() => { btnTipMsg.Text = "Failed to write Internet secret key. Please try again."; btnTipMsg.TextColor = SkinStyle.Current.DelColor; loading.Hide (); return; }); } } else { Application.RunOnMainThread (() => { btnTipMsg.Text = "Failed to obtain the Internet secret key. Please try again."; btnTipMsg.TextColor = SkinStyle.Current.DelColor; return; }); } //写入mqtt域名信息 SetGateWayMqttUrlAddress (common.SubnetID, common.DeviceID); //迁移网关 var moveGatewayResult = Gateway2New (common.MAC.Replace (".", ""), newHomeId, common.SubnetID); if (moveGatewayResult) { Application.RunOnMainThread (() => { btnTipMsg.Text = "Gateway migration succeeded. The backup data is being migrated."; btnTipMsg.TextColor = SkinStyle.Current.TextColor; }); } else { Application.RunOnMainThread (() => { btnTipMsg.Text = "Gateway migration failed. Please try again."; btnTipMsg.TextColor = SkinStyle.Current.DelColor; loading.Hide (); }); return; } //创建迁移备份文件夹 var backId = moveFolder2New (newHomeId); //迁移备份文件 var moveFileResult = MoveFile2New (newHomeId, backId); if (moveFileResult == "true") { Application.RunOnMainThread (() => { btnTipMsg.Text = "Migration backup succeeded, migrating Schedule data."; btnTipMsg.TextColor = SkinStyle.Current.TextColor; }); //迁移定时器 var timerList = GetTimer (newHomeId); if (timerList == null) { Application.RunOnMainThread (() => { btnTipMsg.Text = "Schedule migration failed. Please try again."; btnTipMsg.TextColor = SkinStyle.Current.DelColor; loading.Hide (); return; }); } else { if (timerList.Count > 0) { var backupTimerResult = BackupSchedule (newHomeId, timerList); if (string.IsNullOrEmpty (backupTimerResult)) { btnTipMsg.Text = "Schedule migration failed.. Please try again."; btnTipMsg.TextColor = SkinStyle.Current.DelColor; loading.Hide (); return; } } } //标记流程完成 //var markResult = Mark (newHomeId); //if (markResult) { Application.RunOnMainThread (() => { btnTipTitle.Text = "The backup data migration is successful, and the platform migration is completed."; btnTipTitle.Height = Application.GetRealHeight (150); //btnTipMsg.TextColor = SkinStyle.Current.TextColor; btnTipMsg.Text = ""; etPwd.Visible = false; loading.Hide (); btnSave.Visible = false; btnClose.Width = Application.GetRealWidth (500); }); } else { Application.RunOnMainThread (() => { btnTipMsg.Text = "Backup data migration failed. Please try again."; btnTipMsg.TextColor = SkinStyle.Current.DelColor; loading.Hide (); }); } //} } break;//只升级一个 } } } else { //没有网关 Application.RunOnMainThread (() => { btnTipMsg.Text = "No gateway detected, please check local data"; btnTipMsg.TextColor = SkinStyle.Current.DelColor; loading.Hide (); }); return; } }) { IsBackground = true }.Start (); //Control.ControlBytesSend (Command.enjoyUpgrade2, common.SubnetID, common.DeviceID, new byte [] { }); } /// /// 读取固件数据 /// /// private static List> ReadUpgradeData () { byte [] buffer = new byte [1024]; List> upgradeData = new List> (); System.IO.Stream stream = Application.Activity.Assets.Open ("india_beta.bin"); //System.IO.Stream stream = Application.Activity.Assets.Open ("india_test.bin"); int length = 0; try { while ((length = stream.Read (buffer, 0, buffer.Length)) != 0) { List bbb = new List (); for (int i = 0; i < length; i++) { bbb.Add (buffer [i]); } upgradeData.Add (bbb); } } catch { } finally { stream.Close (); } return upgradeData; } /// /// 发送网关固件数据 /// /// /// /// /// public void SendUpgradeData (byte subnetId,byte deviceId,byte[] sendByets) { var resutl = Control.ControlBytesSendHasReturn (Command.enjoyUpgrade2, subnetId, deviceId, sendByets); //if(resutl == null) { // return -2; //} //if (resutl.Length == 0) { // return -1; //} //if (resutl [0] == 0xF8) { // return 999999; //} else { // if (resutl.Length > 1) { // var packId = resutl [0] * 256 + resutl [1]; // Console.WriteLine ("packId:"+packId); // return packId; // } // return 1; //} } /// /// 初始化网关 /// /// /// private void InitializationGateway(byte subnetId, byte deviceId, byte [] sendByets) { Control.ControlBytesSend (Command.InitializationGateway, subnetId, deviceId, sendByets); } /// /// 设置子网号 /// /// 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); } /// /// 设备网关开启远程 /// private bool SetGatewayRemote(byte subnetId, byte deviceId) { var sendByte = new byte [67]; sendByte [0] = 4; var result = Control.ControlBytesSendHasReturn (Command.SetGateWayModelInfo, subnetId, deviceId, sendByte); if (result != null) { return true; } return false; } ///// ///// 写入homeId ///// ///// ///// ///// //private bool WriteHomeId (byte subnetId, byte deviceId, byte [] sendByets) //{ // //var result = Control.ControlBytesSendHasReturn (Command.WriteHomeId, subnetId, deviceId, sendByets); // //if (result == null) // // return false; // //if (result.Length == 3) { // // if (result [2] == 0xF8) { // // return true; // // } // //} else if (result.Length == 1) { // // if (result [0] == 0xF8) { // // return true; // // } // //} // //return false; // return SetGateWayAdminInfo (subnetId, homeId); //} /// /// 写入上网秘钥 /// /// /// /// /// private bool WriteSecretKey (byte subnetId, byte deviceId, byte [] sendByets) { var result = Control.ControlBytesSendHasReturn (Command.WriteSecretKey, subnetId, deviceId, sendByets); if (result!= null ) { return true; //if (result.Length > 26) { // if (result [26] == 0xF8) { // return true; // } //} else { // if (result.Length > 3) { // if (result [1] == 0xF8) { // return true; // } // } //} } return false; } /// /// /// /// /// private byte GetCheckSum (byte [] bytes) { //byte checksum = 0x00; //foreach (byte bt in bytes) { // checksum ^= bt; //} int iSum = 0; for (int i = 0; i < bytes.Length; i++) { iSum += bytes [i]; } return (byte)(0xff & (0x100 - iSum)); } /// /// 修改Mqtt域名地址 /// /// void SetGateWayMqttUrlAddress (byte subnetId,byte deviceId) { byte [] utlBytes = new byte [65]; var url = new Uri (SeverAddr); var host = ""; if (url != null) { host = url.Host; } byte [] hostBytes = CommonPage.MyEncodingGB2312.GetBytes (host); Array.Copy (hostBytes, 0, utlBytes, 0, 64 < hostBytes.Length ? 64 : hostBytes.Length); var sum = GetCheckSum (hostBytes); utlBytes [64] = sum;//校验位 byte [] backBytes = Control.ControlBytesSendHasReturn (Command.SetGateWayMqttURLAddress, subnetId, deviceId, utlBytes); //return CheckIsSuccessfulWithBytes (backBytes, "Failed to modify gateway remote address!"); } /// /// 修改管理员信息 /// /// /// private bool SetGateWayAdminInfo (byte subnetId,string homeId) { //byte [] name = CommonPage.MyEncodingGB2312.GetBytes (MainPage.LoginUser.AccountString); byte [] currentRegionIdBytes = CommonPage.MyEncodingGB2312.GetBytes (homeId); byte [] adminBytes = new byte [73]; adminBytes [36] = 1;//住宅标志位 Array.Copy (currentRegionIdBytes, 0, adminBytes, 37, 36 < currentRegionIdBytes.Length ? 36 : currentRegionIdBytes.Length); byte [] result = Control.ControlBytesSendHasReturn (Command.WriteHomeId, subnetId, 0, adminBytes); if (result == null) return false; if (result.Length == 3) { if (result [2] == 0xF8) { return true; } } else if (result.Length == 1) { if (result [0] == 0xF8) { return true; } } return false; } } }