using System;
using System.Collections.Generic;
namespace Shared.SimpleControl.Phone
{
public class MigrateBean
{
public MigrateBean ()
{
}
#region 恢复备份
///
/// 获取迁移备份
///
///
public BackupListNameInfoRes GetMigrateBackupBean ()
{
BackupListNameInfoRes lostBackup = new BackupListNameInfoRes () {
backupUtcTime = "12312312",
};
var revertObj = HttpServerRequest.Current.GetHomeDataBackupList ();
if (revertObj.Code == StateCode.SUCCESS) {
var data = Newtonsoft.Json.JsonConvert.DeserializeObject> (revertObj.Data.ToString ());
if (data == null) return null;
var migrateBackupList = new List ();
foreach (var folder in data) {
if (folder.folderName.StartsWith ("迁移备份") || folder.folderName.StartsWith ("MigrateBackup")) {
if (Convert.ToDouble (folder.backupUtcTime) > Convert.ToDouble (lostBackup.backupUtcTime)) {
lostBackup = folder;
}
}
}
return lostBackup.backupUtcTime != "12312312" ? lostBackup : null;
} else {
//提示错误
IMessageCommon.Current.ShowErrorInfoAlter (revertObj.Code);
}
return null;
}
///
/// 用户恢复文件
///
public void UserBakeupFileDetailedInformation (string folderId)
{
//是否确定恢复该文件数据信息
Application.RunOnMainThread (() => {
MainPage.Loading.Start ("Download...");
});
try {
ReadFilesAndDelete ();
var revertObj = HttpServerRequest.Current.GetBackupFolderAllFileList (folderId);
if (revertObj.Code == StateCode.SUCCESS) {
var fileListData = Newtonsoft.Json.JsonConvert.DeserializeObject> (revertObj.Data.ToString ());
MultiThreadDownload (fileListData, folderId);
} else {
//提示错误
IMessageCommon.Current.ShowErrorInfoAlter (revertObj.Code);
}
} catch (Exception ex) {
Shared.Utlis.WriteLine (ex.ToString ());
} finally {
}
}
///
/// 删除本地文件
///
void ReadFilesAndDelete ()
{
var fileNames = IO.FileUtils.ReadFiles ();
foreach (var fileName in fileNames) {
if (fileName == UserInfo.GlobalRegisterFile || fileName == UserConfig.configFile) {
continue;
}
IO.FileUtils.DeleteFile (fileName);
}
}
object DownloadLocker = new object ();
object SendLocker = new object ();
///
/// 多线程下载
///
void MultiThreadDownload (List dataList, string folderId, int maxThreads = 5)
{
int index = 0;
int indexCount = 0;
var mFileList = dataList.FindAll ((obj) => obj.fileName != "null" && obj.fileName != UserConfig.configFile && obj.fileName != UserInfo.GlobalRegisterFile && obj.fileName != "AccountListDB" && obj.fileName != CommonConfig.ConfigFile);
if (maxThreads > mFileList.Count) {
maxThreads = mFileList.Count;
}
if (mFileList.Count <= 0) return;
int resultCount = mFileList.Count / maxThreads;
//int residue = mFileList.Count % maxThreads;
/*开启若干线程,分别下载对应的资源*/
for (int i = 1; i <= maxThreads; i++) {
int startIndex = ((i - 1) * resultCount + 0);
int endIndex = resultCount * i - 1;
if (i == maxThreads) {
/*
* 最后一个线程
* */
endIndex = mFileList.Count - 1;
}
var id = i;
var startIndex1 = startIndex;
var endIndex1 = endIndex;
//Utlis.WriteLine ($"下载线程:{id} startIndex1:{startIndex1} endIndex1:{endIndex1}");
new System.Threading.Thread (() => {
for (var j = startIndex1; j <= endIndex1; j++) {
try {
var result = DownloadSomeDataBackup (folderId, mFileList [j]);
if (result) {
lock (DownloadLocker) {
index++;
}
//index++;
Application.RunOnMainThread (() => {
int pro = (int)(index * 1.0 / mFileList.Count * 100);
MainPage.Loading.Text = pro.ToString () + "%";
});
}
} catch { } finally {
lock (SendLocker) {
indexCount++;
}
}
//Utlis.WriteLine ($"下载线程:{id} 完成index:{j} indexCount: {indexCount}");
}
}) { IsBackground = true }.Start ();
System.Threading.Thread.Sleep (100);
}
while (indexCount < mFileList.Count) {
System.Threading.Thread.Sleep (200);
}
Utlis.WriteLine ($"下载完成");
if (index != mFileList.Count) {
//删除已经下载的文件个数错误
ReadFilesAndDelete ();
Application.RunOnMainThread (() => {
new Alert (Language.StringByID (R.MyInternationalizationString.Tip), Language.StringByID (R.MyInternationalizationString.DownloadFailed),
Language.StringByID (R.MyInternationalizationString.Close)).Show ();
});
return;
}
MainPage.LoginUser.SaveUserInfo ();
Room.InitAllRoom ();
//2.转换link数据
//3.上传link数据
HDLLinkUtlis.Current.OneclickUpload (true);
//4.上传音响数据
//try {
// var revertObj = HttpServerRequest.Current.GetSpeakerList ();
// if (revertObj.Code == StateCode.SUCCESS) {
// var speakerListRes = Newtonsoft.Json.JsonConvert.DeserializeObject (revertObj.Data.ToString ());
// if (speakerListRes != null && speakerListRes.list != null && speakerListRes.list.Count > 0) {
// //5.上传智能音响控制目标
// var tarList = new List ();
// foreach (var function in CommonConfig.Current.FunctionList) {
// var tar = new TargetInfo ();
// tar.isDevice = true;
// tar.targetId = function.deviceId;
// tar.targetName = function.name;
// tarList.Add (tar);
// }
// foreach (var scene in CommonConfig.Current.SceneList) {
// var tar = new TargetInfo ();
// tar.isDevice = true;
// tar.targetId = scene.userSceneId;
// tar.targetName = scene.name;
// tarList.Add (tar);
// }
// foreach (var ss in speakerListRes.list) {
// AddDevicesSceneList (ss.homeId, ss.tokenId, tarList);
// }
// }
// } else {
// //提示错误
// IMessageCommon.Current.ShowErrorInfoAlter (revertObj.Code);
// }
//} catch {
//} finally {
// Application.RunOnMainThread (() => {
// MainPage.Loading.Hide ();
// });
//}
bool sss = false;
#if DEBUG
sss = true;
#endif
if (!getTimerList () || sss) {
var dd = GetTimerBackupBean ();
if (dd != null) {
TimerBakeupFileDetailedInformation (dd.id);
}
}
//6.标记迁移数据完成
HttpServerRequest.Current.Mark (UserConfig.Instance.CurrentRegion.Id);
Application.RunOnMainThread (() => {
//if (CommonPage.IsRemote) {
// SmartHome.MqttCommon.DisConnectRemote("UserBakeupFileDetailedInformation");
//}
UserMiddle.Init (true, true);
EquipmentPublicClass.CheckLinkRemote (UserConfig.Instance.internetStatus);
//new Alert (Language.StringByID (R.MyInternationalizationString.Tip), Language.StringByID (R.MyInternationalizationString.RestoreFileIsSuccessfull),
//Language.StringByID (R.MyInternationalizationString.Close)).Show ();
});
}
///
/// 下载单个备份文件
///
///
///
///
///
bool DownloadSomeDataBackup (string folderId, BackupFileInfoRes file)
{
var requestJson = HttpUtil.GetSignRequestJson (new BackupFileDownObj () {
folderId = folderId,
fileId = file.id,
homeId = UserConfig.Instance.CurrentRegion.Id
});
var revertObj = HttpUtil.RequestHttpsDownload (NewAPI.API_POST_File_Down, requestJson, null, UserConfig.Instance.CurrentRegion.regionUrl);
if (revertObj != null && revertObj.Length > 0) {
Utlis.WriteLine ("DownloadSomeDataBackup: " + file.fileName);
IO.FileUtils.WriteFileByBytes (file.fileName, revertObj);
return true;
} else {
return false;
}
}
///
/// 下载1.0定时器数据
///
///
///
void DownloadTimerBackup (string folderId, BackupFileInfoRes file)
{
var requestJson = HttpUtil.GetSignRequestJson (new BackupFileDownObj () {
folderId = folderId,
fileId = file.id,
homeId = UserConfig.Instance.CurrentRegion.Id
});
var revertObj = HttpUtil.RequestHttpsDownload (NewAPI.API_POST_File_Down, requestJson, null, UserConfig.Instance.CurrentRegion.regionUrl);
if (revertObj != null && revertObj.Length > 0) {
var data = System.Text.Encoding.UTF8.GetString (revertObj);
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject (data);
//旧对象要转成新对象
var timerTemp = new Timer ();
var perio = obj.Periodicity.Split (",");
foreach(var p in perio) {
int wd = 1;
int.TryParse (p, out wd);
timerTemp.whichDay.Add (wd);
}
timerTemp.timerType = obj.TimerType;
timerTemp.timerName = obj.TimerName;
timerTemp.RoomName = obj.RoomName;
timerTemp.executeUtcTime = obj.ExecutionTime;
DeviceDate deviceDate = new DeviceDate ();
deviceDate.gatewayId = SmartHome.Send.GatewayId;
deviceDate.homeId = SmartHome.Send.HomeId;
List selectedDeviceList = new List ();
var objControlDeviceList = Newtonsoft.Json.JsonConvert.DeserializeObject> (obj.ControlDeviceData);
foreach(var cd in objControlDeviceList) {
var cloudTimerDevcie = CommonConfig.Current.FunctionList.Find ((cloudFunction) => cloudFunction.bus.SubnetID == cd.SubnetID
&& cloudFunction.bus.DeviceID == cd.DeviceID && cloudFunction.bus.LoopId == cd.LoopID);
if (cloudTimerDevcie != null) {
//var oldSendBytes = System.Text.Encoding.UTF8.GetBytes (cd.SendBytes);
string keyValue = "";
string oldValue = "";
switch (cloudTimerDevcie.spk) {
case SPK.CurtainTrietex:
case SPK.CurtainRoller:
case SPK.LightSwitch:
case SPK.CurtainSwitch:
case SPK.ElectricSocket: {
keyValue = "on_off";
if (cd.SendBytes.Length > 0) {
oldValue = cd.SendBytes [1].ToString () == "0" ? "off" : "on";
}
}
break;
case SPK.LightDimming: {
keyValue = "brightness";
if (cd.SendBytes.Length > 1) {
oldValue = cd.SendBytes [1].ToString ();
}
}
break;
case SPK.ElectricFan: {
keyValue = "fan_speed_percent";
if (cd.SendBytes.Length > 1) {
oldValue = cd.SendBytes [1].ToString ();
}
}
break;
}
Fun fun = new Fun ();
fun.deviceId = Int64.Parse (cloudTimerDevcie.deviceId);
fun.spk = cloudTimerDevcie.spk;
fun.attributes.Add (new Attributes { key = keyValue, value = oldValue });
fun.bus.addresses = cloudTimerDevcie.bus.addresses;
fun.bus.loopId = cloudTimerDevcie.bus.loopId;
switch (fun.spk) {
case SPK.LightDimming: {
//调光做了一个特殊处理;
if (fun.attributes.Count == 1) {
var dic = fun.attributes [0];
if (dic.key == "brightness") {
Attributes attributes = new Attributes ();
attributes.key = "on_off";
if (dic.value == "0") {
attributes.value = "off";
} else {
attributes.value = "on";
}
fun.attributes.Add (attributes);
}
}
break;
}
case SPK.ElectricFan: {
if (fun.attributes.Count == 1) {
var dic = fun.attributes [0];
if (dic.key == "fan_speed_percent") {
Attributes attributes = new Attributes ();
attributes.key = "on_off";
if (dic.value == "0") {
attributes.value = "off";
} else {
attributes.value = "on";
}
fun.attributes.Add (attributes);
}
}
}
break;
}
selectedDeviceList.Add (fun);
}
}
deviceDate.actions.AddRange (selectedDeviceList);
timerTemp.controlData = deviceDate;
var dd = SmartHome.Send.AddTimer (timerTemp);
Console.WriteLine ("迁移定时器");
}
}
#endregion
/////
/////
/////
/////
//void AddDevicesSceneList (string homeId, string tokenId, List lsit)
//{
// try {
// bool result = UpdateSpeakerDeviceList (homeId, tokenId, lsit);
// } catch { } finally {
// Application.RunOnMainThread (() => {
// MainPage.Loading.Hide ();
// });
// }
//}
/////
///// 添加或者更新设备和场景设备列表
/////
//bool UpdateSpeakerDeviceList (string homeId,string tokenId, List mList)
//{
// var updateSpeakerDeviceListObj = new UpdateSpeakerDeviceListObj () {
// homeId = homeId,
// tokenId = tokenId,
// targetInfos = mList
// };
// var revertObj = HttpServerRequest.Current.UpdateSpeakerDeviceList (updateSpeakerDeviceListObj);
// if (revertObj.Code == StateCode.SUCCESS) {
// return true;
// } else {
// //登录失败
// IMessageCommon.Current.ShowErrorInfoAlter (revertObj.Code);
// }
// return false;
//}
///
/// 获取迁移备份
///
///
public BackupListNameInfoRes GetTimerBackupBean ()
{
BackupListNameInfoRes lostBackup = new BackupListNameInfoRes () {
backupUtcTime = "12312312",
};
var revertObj = HttpServerRequest.Current.GetHomeDataBackupList ();
if (revertObj.Code == StateCode.SUCCESS) {
var data = Newtonsoft.Json.JsonConvert.DeserializeObject> (revertObj.Data.ToString ());
if (data == null) return null;
var migrateBackupList = new List ();
foreach (var folder in data) {
if (folder.backupClassify == "CUSTOM_PROJECT_BACKUP" && folder.folderName.StartsWith ("ScheduleBackup")) {
if (Convert.ToDouble (folder.backupUtcTime) > Convert.ToDouble (lostBackup.backupUtcTime)) {
lostBackup = folder;
}
}
}
return lostBackup.backupUtcTime != "12312312" ? lostBackup : null;
} else {
//提示错误
IMessageCommon.Current.ShowErrorInfoAlter (revertObj.Code);
}
return null;
}
///
/// 定时器恢复文件
///
public void TimerBakeupFileDetailedInformation (string folderId)
{
//是否确定恢复该文件数据信息
Application.RunOnMainThread (() => {
MainPage.Loading.Start ("Download...");
});
try {
var revertObj = HttpServerRequest.Current.GetBackupFolderAllFileList (folderId);
if (revertObj.Code == StateCode.SUCCESS) {
var fileListData = Newtonsoft.Json.JsonConvert.DeserializeObject> (revertObj.Data.ToString ());
for (int i = 0; i < fileListData.Count; i++) {
DownloadTimerBackup (folderId, fileListData [i]);
}
} else {
//提示错误
IMessageCommon.Current.ShowErrorInfoAlter (revertObj.Code);
}
} catch (Exception ex) {
Shared.Utlis.WriteLine (ex.ToString ());
} finally {
}
}
///
/// 获取新平台定时器列表
///
bool getTimerList ()
{
var revertObj = SmartHome.Send.GetTimerList ();
if (revertObj.Code == StateCode.SUCCESS) {
if (revertObj.Data == null) {
return false;
}
if (string.IsNullOrEmpty (revertObj.Data.ToString ())) {
return false;
}
var jsonDate = Newtonsoft.Json.Linq.JObject.Parse (revertObj.Data.ToString ());
var array = jsonDate ["list"].ToString ();
var jArray = Newtonsoft.Json.Linq.JArray.Parse (array);
if (jArray.Count > 0) {
return true;
}
}
return false;
}
///
/// 完成操作
///
public void showFinish ()
{
Application.RunOnMainThread (() => {
UserMiddle.Init (true, true);
EquipmentPublicClass.CheckLinkRemote (UserConfig.Instance.internetStatus);
new Alert (Language.StringByID (R.MyInternationalizationString.Tip), Language.StringByID (R.MyInternationalizationString.RestoreFileIsSuccessfull),
Language.StringByID (R.MyInternationalizationString.Close)).Show ();
});
}
}
}