using System; using Shared.Common; using Newtonsoft.Json; using Shared.Common.ResponseEntity; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.Collections.Generic; namespace Shared.Phone.UserCenter { /// /// 个人中心逻辑类 /// public class UserCenterLogic { #region ■ 变量声明___________________________ /// /// 锁 /// private static object objLock = new object(); #endregion #region ■ 云端接口访问_______________________ /// /// 访问指定接口,返回是否成功 /// /// 是否成功 /// 访问地址 /// 一个类 /// /// 不需要显示错误的错误类别(接口返回的错误类别),如果包含,则会返回【true】 /// 如果指定有NotSetAgain,则不二次发送(比如断网),然后返回【false】 /// public static async Task GetResultStatuByRequestHttps(string RequestName, object obj, List listNotShowError = null) { string nowFormId = UserCenterResourse.NowActionFormID; //获取从接口那里取到的ResponsePack var revertObj = await GetResponsePack(RequestName, obj); if (revertObj == null) { if (listNotShowError != null && listNotShowError.Contains("NotSetAgain") == true) { return false; } revertObj = await ResetRequestHttps(RequestName, obj, nowFormId); if (revertObj == null) { return false; } } //检测是否存在错误信息 return CheckNotEorrorMsg(revertObj, RequestName, listNotShowError); } /// /// 访问指定接口,返回状态码(出现异常时,返回 Error) /// /// 接口的状态码(出现异常时,返回 Error) /// 访问地址 /// 一个类 /// /// 不需要显示错误的错误类别(接口返回的错误类别),如果包含,则会返回【Success】 /// 如果指定有NotSetAgain,则不二次发送(比如断网),然后返回【ErrorEx】 /// public static async Task GetResultCodeByRequestHttps(string RequestName, object obj, List listNotShowError = null) { string nowFormId = UserCenterResourse.NowActionFormID; //获取从接口那里取到的ResponsePack var revertObj = await GetResponsePack(RequestName, obj); if (revertObj == null) { if (listNotShowError != null && listNotShowError.Contains("NotSetAgain") == true) { return "ErrorEx"; } revertObj = await ResetRequestHttps(RequestName, obj, nowFormId); if (revertObj == null) { return "Error"; } } return revertObj.StateCode; } /// /// 访问指定接口,并返回接口把对象已经序列化了的字符串,存在错误信息时,返回null /// /// 返回:接口把对象已经序列化了的字符串,存在错误信息时,返回null /// 访问地址 /// 一个类 /// /// 不需要显示错误的错误类别(接口返回的错误类别),如果包含,则会返回空字符串 /// 如果指定有NotSetAgain,则不二次发送(比如断网),然后返回空字符串 /// public static async Task GetResponseDataByRequestHttps(string RequestName, object obj, List listNotShowError = null) { string nowFormId = UserCenterResourse.NowActionFormID; //获取从接口那里取到的ResponsePack var revertObj = await GetResponsePack(RequestName, obj); if (revertObj == null) { if (listNotShowError != null && listNotShowError.Contains("NotSetAgain") == true) { return string.Empty; } revertObj = await ResetRequestHttps(RequestName, obj, nowFormId); if (revertObj == null) { return null; } } //检测错误 bool notError = CheckNotEorrorMsg(revertObj, RequestName, listNotShowError); if (notError == false) { return null; } if (revertObj == null || revertObj.ResponseData == null) { return string.Empty; } return revertObj.ResponseData.ToString(); } /// /// 访问指定接口,并直接返回接口返回的比特,存在错误信息时,返回null /// /// 返回:并直接返回接口返回的比特,存在错误信息时,返回null /// 访问地址 /// 一个类 /// /// 不需要显示错误的错误类别(接口返回的错误类别),如果包含,则会返回空字符串 /// 如果指定有NotSetAgain,则不二次发送(比如断网),然后返回null /// public static async Task GetByteResponseDataByRequestHttps(string RequestName, object obj, List listNotShowError = null) { string nowFormId = UserCenterResourse.NowActionFormID; //获取从接口那里取到的ResponsePack var revertObj = await GettByteResponsePack(RequestName, obj); if (revertObj == null) { if (listNotShowError != null && listNotShowError.Contains("NotSetAgain") == true) { return null; } //重新发送 revertObj = await ResetByteRequestHttps(RequestName, obj, nowFormId); if (revertObj == null) { return null; } } if (revertObj != null && revertObj.Length > 0) { if (revertObj[0] == '{' && revertObj[revertObj.Length - 1] == '}') { string data2 = System.Text.Encoding.UTF8.GetString(revertObj); var data = JsonConvert.DeserializeObject(data2); if (data != null && string.IsNullOrEmpty(data.StateCode) == false) { bool notError = CheckNotEorrorMsg(data, RequestName, listNotShowError); if (notError == false) { return null; } } } } return revertObj; } /// /// 私有类型:从新发送(懂的人自然懂,很难解释清楚) /// /// 访问地址 /// 一个类 /// 那一瞬间的画面ID /// private static async Task ResetRequestHttps(string RequestName, object obj, string actionFormId) { if (actionFormId == string.Empty) { //主界面特殊,不需要考虑 return null; } ResponsePack responsePack = null; int count = 0; while (actionFormId == UserCenterResourse.NowActionFormID) { await Task.Delay(2000); //调用接口 responsePack = await GetResponsePack(RequestName, obj); if (responsePack != null) { break; } count++; if (count == 3) { Application.RunOnMainThread(() => { //网络不稳定,请稍后再试 string msg = Language.StringByID(R.MyInternationalizationString.uNetIsUnStabilityAndDoAgain); var tipView = new TipViewControl(msg); tipView.ShowView(); }); break; } } return responsePack; } /// /// 私有类型:从新发送(懂的人自然懂,很难解释清楚) /// /// 访问地址 /// 一个类 /// 那一瞬间的画面ID /// private static async Task ResetByteRequestHttps(string RequestName, object obj, string actionFormId) { if (actionFormId == string.Empty) { //主界面特殊,不需要考虑 return null; } byte[] responsePack = null; int count = 0; while (actionFormId == UserCenterResourse.NowActionFormID) { await Task.Delay(2000); //调用接口 responsePack = await GettByteResponsePack(RequestName, obj); if (responsePack != null) { break; } count++; if (count == 5) { Application.RunOnMainThread(() => { //网络不稳定,请稍后再试 string msg = Language.StringByID(R.MyInternationalizationString.uNetIsUnStabilityAndDoAgain); var tipView = new TipViewControl(msg); tipView.ShowView(); }); break; } } return responsePack; } /// /// 获取从接口那里取到的ResponsePack /// /// 获取从接口那里取到的ResponsePack /// 访问地址 /// 一个类 private static async Task GetResponsePack(string RequestName, object obj) { try { //序列化对象 var requestJson = JsonConvert.SerializeObject(obj); //访问接口 var result = await CommonPage.Instance.RequestHttpsZigbeeAsync(RequestName, System.Text.Encoding.UTF8.GetBytes(requestJson)); return result; } catch (Exception ex) { Console.WriteLine(ex.Message); return null; } } /// /// 获取从接口那里取到的内容 /// /// 获取从接口那里取到的文本内容 /// 访问地址 /// 一个类 private static async Task GettByteResponsePack(string RequestName, object obj) { try { //序列化对象 var requestJson = JsonConvert.SerializeObject(obj); //访问接口 var result = await CommonPage.Instance.RequestHttpsZigbeeBytesResultAsync(RequestName, System.Text.Encoding.UTF8.GetBytes(requestJson)); return result; } catch (Exception ex) { Console.WriteLine(ex.Message); return null; } } /// /// 检测是否存在错误信息,并显示错误 /// /// 是否存在错误信息 /// 从接口接收到的数据 /// 请求接口 /// 不需要显示错误的错误类别(接口返回的错误类别) public static bool CheckNotEorrorMsg(ResponsePack revertObj, string RequestName, List listNotShowError = null) { if (revertObj == null) { Application.RunOnMainThread(() => { //网络不稳定,请稍后再试 string msg = Language.StringByID(R.MyInternationalizationString.uNetIsUnStabilityAndDoAgain); var tipView = new TipViewControl(msg); tipView.ShowView(); }); return false; } if (revertObj.StateCode.ToUpper() != "SUCCESS") { if (listNotShowError != null && listNotShowError.Contains(revertObj.StateCode) == true) { //不显示错误,然后返回true return true; } Application.RunOnMainThread(() => { string msg = IMessageCommon.Current.GetMsgByRequestName(RequestName, revertObj.StateCode); var tipView = new TipViewControl(msg); tipView.ShowView(); //无效登录Token if (revertObj.StateCode == "NoLogin") { new System.Threading.Thread(() => { System.Threading.Thread.Sleep(1000); Application.RunOnMainThread(() => { //1秒后重新登录 UserCenterLogic.ReLoginAgain(Config.Instance.Account); }); }) { IsBackground = true }.Start(); } }); return false; } return true; } #endregion #region ■ 添加界面相关_______________________ /// /// 检测能否添加画面 /// /// true:可以追加 false:不可追加 /// Form public static bool CheckCanAddForm(UserCenterCommonForm form) { //lock (objLock) { //获取画面英文名字 string formName = GetFormName(form); //二重追加不可 if (UserCenterResourse.DicActionForm.ContainsKey(formName) == false) { return true; } //暂时这样弄看看,如果重复,则关闭掉原来的界面 var formTemp = UserCenterResourse.DicActionForm[formName]; formTemp.CloseForm(); UserCenterResourse.DicActionForm.Remove(formName); return true; } } /// /// 把打开的画面添加到内存中 /// /// Form. public static void AddActionForm(UserCenterCommonForm form) { //lock (objLock) { //获取画面英文名字 string formName = GetFormName(form); //二重追加不可 if (UserCenterResourse.DicActionForm.ContainsKey(formName) == false) { form.FormID = formName; //内存添加 UserCenterResourse.DicActionForm[formName] = form; //添加画面时,它自身就是激活的界面 UserCenterResourse.NowActionFormID = form.FormID; UserCenterResourse.listActionFormId.Add(form.FormID); } } } /// /// 从列表中移除画面 /// /// Form public static void RemoveActionForm(UserCenterCommonForm form) { //lock (objLock) { //获取画面英文名字 string formName = GetFormName(form); if (UserCenterResourse.DicActionForm.ContainsKey(formName) == true) { //刷新当前正在操作的画面ID if (UserCenterResourse.NowActionFormID == UserCenterResourse.DicActionForm[formName].FormID) { //向后推一位即为下一个激活的界面 int index = UserCenterResourse.listActionFormId.IndexOf(UserCenterResourse.NowActionFormID) - 1; //初始值 UserCenterResourse.NowActionFormID = string.Empty; if (index >= 0) { //设置当前激活的画面ID UserCenterResourse.NowActionFormID = UserCenterResourse.listActionFormId[index]; if (UserCenterResourse.DicActionForm.ContainsKey(UserCenterResourse.NowActionFormID) == true) { new System.Threading.Thread(() => { System.Threading.Thread.Sleep(100); Application.RunOnMainThread(() => { //触发界面再次激活的事件 UserCenterResourse.DicActionForm[UserCenterResourse.NowActionFormID].FormActionAgainEvent(); }); }) { IsBackground = true }.Start(); } } } //移除ID UserCenterResourse.listActionFormId.Remove(UserCenterResourse.DicActionForm[formName].FormID); //移除画面 UserCenterResourse.DicActionForm.Remove(formName); } } } /// /// 获取画面英文名字 /// /// The form name. /// Form. public static string GetFormName(UserCenterCommonForm form) { //将命名空间去掉 string[] Arry = form.ToString().Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries); string formName = Arry[Arry.Length - 1].Trim(); return formName; } /// /// 获取当前正在激活的画面 /// /// public static UserCenterCommonForm GetNowActionForm() { foreach (UserCenterCommonForm form in UserCenterResourse.DicActionForm.Values) { if (form.FormID == UserCenterResourse.NowActionFormID) { return form; } } return null; } #endregion #region ■ 刷新本地缓存_______________________ /// /// 刷新本地所有缓存 /// public static void RefreshAllMemory() { //刷新本地网关文件 Common.LocalGateway.Current.ReFreshByLocal(); //刷新本地设备 Common.LocalDevice.Current.ReFreshByLocal(); //需优先于刷新房间,同步云端的网关id,如果本地拥有云端不存在的id,则表示应该被换绑了,直接删除 Common.LocalGateway.Current.SynchronizeDbGateway(); //从本地重新加载全部的房间 Common.Room.RefreshAllRoomByLocation(); } #endregion #region ■ 删除本地文件_______________________ /// /// 删除本地所有文件 /// /// true:全部删除(用于住宅删除) false:重要的文件不删除 public static void DeleteAllLocationFile(bool all = true) { string dPath = UserCenterResourse.LocalRootPath; if (System.IO.Directory.Exists(dPath) == false) { return; } //然后获取全部的文件 List listFile = Global.FileListByHomeId(); foreach (string file in listFile) { if (all == false && IsNotDeleteFile(file) == true) { //这是不能删除的文件 continue; } //删除文件 Global.DeleteFilebyHomeId(file); } //如果是把文件全部删除的话,那么文件夹也一起删除掉 if (all == true) { //删除文件夹 System.IO.Directory.Delete(dPath, true); } } /// /// 判断是不是不应该删除的文件 /// /// /// public static bool IsNotDeleteFile(string fileName) { if (fileName == "Config.json") { //不能删除Config文件 return true; } else if (fileName.StartsWith("DeviceUI_") == true) { //不能删除设备UI文件 return true; } else if (fileName.StartsWith("House_") == true) { //不能删除住宅文件 return true; } return false; } #endregion #region ■ 各种正确检测_______________________ /// /// 判断是否包含大写字母 /// /// true, if contain upper was checked, false otherwise. /// Value. public static bool CheckContainUpper(string value) { return true; } /// /// 判断是否包含小写字母 /// /// true, if contain lower was checked, false otherwise. /// Value. public static bool CheckContainLower(string value) { return true; } /// /// 判断是否包含数字 /// /// true, if contain lower was checked, false otherwise. /// Value. public static bool CheckContainNum(string value) { return true; } /// /// 判断是否包含符号 /// /// true, if contain lower was checked, false otherwise. /// Value. public static bool CheckContainSymbol(string value) { return true; } /// /// 检测邮箱是否合法 /// /// /// public static bool CheckEmail(string email) { Regex reg = new Regex(CommonPage.EmailRegexStr); return reg.IsMatch(email); } /// /// 检测手机号是否合法 /// /// 手机号 /// 地区代码 /// public static bool CheckPhoneNumber(string phoneNumber, string areaCode) { //校验外国手机号 if (areaCode != "86") { Regex reg = new Regex(CommonPage.PhoneForForeignRegexStr); return reg.IsMatch(phoneNumber); } //校验国内手机号 if (phoneNumber.Length > 11) { return false; } else if (phoneNumber.Length == 11) { Regex reg = new Regex(CommonPage.PhoneRegexStr); return reg.IsMatch(phoneNumber); } else { //正则表达式判断是否数字 Regex reg = new Regex("^[0-9]*$"); return reg.IsMatch(phoneNumber); } } #endregion #region ■ 从新登录___________________________ /// /// 从新登录 /// /// 账号 public static void ReLoginAgain(string account = "") { //复原管理员权限 Common.Config.Instance.isAdministrator = false; UserCenterResourse.oldAccountId = string.Empty; //关闭所有接收 DeviceAttributeLogic.Current.RemoveAllEvent(); //关闭监听网关变化 Common.LocalGateway.Current.StopListenNetWork(); //清除升级列表 FirmwareUpdateResourse.dicDeviceUpdateList.Clear(); FirmwareUpdateResourse.dicGatewayUpdateList.Clear(); //设定一个时间 Config.Instance.LoginDateTime = new DateTime(1970, 1, 1); Config.Instance.Save(); //清空当前住宅id Shared.Common.Config.Instance.HomeId = string.Empty; Common.LocalGateway.Current.ClearAllRealGateway(); //通知云端,已经退出登陆 CommonPage.Instance.SignOutClearData(); Application.RunOnMainThread(() => { //关闭所有打开了的界面 CloseAllOpenForm(); //显示登陆画面 var formLogin = new Shared.Phone.Device.Account.AccountLogin(); Shared.Common.CommonPage.Instance.AddChidren(formLogin); formLogin.Show(account); }); } /// /// 关闭所有打开了的界面 /// public static void CloseAllOpenForm() { var listForm = new List(); foreach (UserCenterCommonForm form in UserCenterResourse.DicActionForm.Values) { listForm.Insert(0, form); } UserCenterResourse.DicActionForm.Clear(); //关闭所有画面 foreach (UserCenterCommonForm form in listForm) { form.CloseForm(); } } #endregion #region ■ 子控件的Y轴坐标____________________ /// /// 指定位置类型获取Rowlayout的子控件的Y轴坐标(请确保子控件不大于父容器) /// /// 父控件的真实高度 /// 子控件的真实高度 /// 位置对齐方式 /// 上下间的空白间距,省略时,取行控件共通变量的值。设置为-1时,不计算空白间距 /// public static int GetControlChidrenYaxis(int fatherCtrHeight, int ctrHeight, UViewAlignment alignment, int Space = 0) { if (Space == 0) { //获取行控件的间距 if (fatherCtrHeight == ControlCommonResourse.ListViewRowHeight) { Space = ControlCommonResourse.ListViewRowSpace; } } if (Space < 0) { //不计算间距值 Space = 0; } if (alignment == UViewAlignment.Center) { return fatherCtrHeight / 2 - ctrHeight / 2; } else if (alignment == UViewAlignment.Top) { return (fatherCtrHeight / 2 - Space / 2) / 2 - ctrHeight / 2; } else { int top = fatherCtrHeight / 2 + Space / 2; return top + (fatherCtrHeight - top) / 2 - ctrHeight / 2; } } #endregion #region ■ 拼接信息___________________________ /// /// 拼接路径(全路径),以住宅ID的文件夹为起点,当没有指定参数时,则返回【住宅ID的文件夹】的全路径 /// /// 要拼接的路径 /// public static string CombinePath(params object[] listNames) { string rootPath = UserCenterResourse.LocalRootPath; if (listNames == null || listNames.Length == 0) { return rootPath; } foreach (var file in listNames) { if (file == null) { continue; } rootPath = System.IO.Path.Combine(rootPath, file.ToString()); } return rootPath; } /// /// 拼接网关回复超时的信息 /// /// 错误信息 /// 接口回复的东西 /// 是否添加括号 /// public static string CombineGatewayTimeOutMsg(string errorMsg, string errorMsgBase, bool addBrackets = true) { if (errorMsgBase != null && errorMsgBase.Contains("回复超时") == false) { //只有回复超时的时候才会加上 return errorMsg; } errorMsg += "\r\n"; if (addBrackets == true) { //(网关回复超时,请稍后再试) return errorMsg + "(" + Language.StringByID(R.MyInternationalizationString.uGatewayResponseTimeOut) + ")"; } else { //网关回复超时,请稍后再试 return errorMsg + Language.StringByID(R.MyInternationalizationString.uGatewayResponseTimeOut); } } #endregion #region ■ 检测网关共通错误状态码_____________ /// /// 检测网关返回的共通错误状态码(返回null则代表没有错误),支持状态码为 /// 1:网关无法解析命令数据。 /// 2:协调器正在升级或备份/恢复数据 /// 3:操作设备/组/场景不存在 /// 4:其他错误 /// 5:数据传输错误(在某次客户端向网关发送数据的过程中,网关在合理时间范围内接收客户端数据不完整导致该错误发生。如客户端向网关一次发送100个字节的数据,但网关等待接收了一秒只接收了80个字节。发生该错误,网关将主动关闭客户端连接) /// /// 网关返回的resultData,里面有【errorResponData】这个东西的那种对象 /// public static string CheckCommonErrorCode(object resultData) { if (resultData == null) { return null; } Type myType = resultData.GetType(); object errorObj = myType.InvokeMember("errorResponData", System.Reflection.BindingFlags.GetField, null, resultData, null); if (errorObj == null) { return null; } Type type = errorObj.GetType(); var code = type.InvokeMember("Error", System.Reflection.BindingFlags.GetField, null, errorObj, null); int errorCode = Convert.ToInt32(code); return CheckCommonErrorCode(errorCode); } /// /// 检测网关返回的共通错误状态码(返回null则代表没有错误),支持状态码为 /// 1:网关无法解析命令数据。 /// 2:协调器正在升级或备份/恢复数据 /// 3:操作设备/组/场景不存在 /// 4:其他错误 /// 5:数据传输错误(在某次客户端向网关发送数据的过程中,网关在合理时间范围内接收客户端数据不完整导致该错误发生。如客户端向网关一次发送100个字节的数据,但网关等待接收了一秒只接收了80个字节。发生该错误,网关将主动关闭客户端连接) /// /// 错误代码 /// public static string CheckCommonErrorCode(int errorCode) { if (errorCode == 1) { //网关无法解析命令数据 return Language.StringByID(R.MyInternationalizationString.uGatewayCannotResolveCommand); } else if (errorCode == 2) { //协调器正在升级或备份或恢复数据中 string msg = Language.StringByID(R.MyInternationalizationString.uCoordinatorIsUpOrBackupOrRecovering); } else if (errorCode == 3) { //目标设备不存在 string msg = Language.StringByID(R.MyInternationalizationString.uTargetDeviceIsNotExsit); } else if (errorCode == 4) { //出现未知错误,请稍后再试 string msg = Language.StringByID(R.MyInternationalizationString.uUnKnowErrorAndResetAgain); } else if (errorCode == 5) { //数据传输错误,请稍后再试 string msg = Language.StringByID(R.MyInternationalizationString.uDataTransmissionFailAndResetAgain); } return null; } #endregion #region ■ 刷新个人中心的内存及线程___________ /// /// 异步方法执行(仅限切换住宅时调用),刷新个人中心的内存及线程 /// public async static Task InitUserCenterMenmoryAndThread() { //强制指定不关闭进度条 ProgressBar.SetCloseBarFlag(true); //只有在住宅ID不一样的时候才做这个操作 if (Common.Config.Instance.HomeId != UserCenterResourse.oldHomeStringId || Common.Config.Instance.Account != UserCenterResourse.oldAccountId) { //变更根目录路径 UserCenterResourse.LocalRootPath = System.IO.Path.Combine(Shared.IO.FileUtils.RootPath, Config.Instance.Guid, Config.Instance.Home.Id); //复原管理员标识 Config.Instance.isAdministrator = false; //重新发送命令去绑定断网情况下备份的网关 HdlGatewayLogic.Current.ResetComandToBindBackupGateway(); //初始化登陆账号的信息 await InitUserAccoutInfo(); //预创建个人中心全部的文件夹 CreatAllUserCenterDirectory(); //关闭所有接收 DeviceAttributeLogic.Current.RemoveAllEvent(); //刷新安防上报信息 Common.LocalSafeguard.Current.RefreshAlarmInfo(); //添加保存安防设备报警的事件(不需要再执行任何操作,并且永久存在) DeviceAttributeLogic.Current.AddSaveSafetyAlarmInfoEvent(); //保存用户的登陆信息到本地 SaveUserInformationToLocation(); //初始化管理员权限信息 await InitAdministratorInfo(); UserCenterResourse.oldHomeStringId = Common.Config.Instance.HomeId; UserCenterResourse.oldAccountId = Common.Config.Instance.Account; //同步数据(二次调用没关系) var result = await HdlAutoBackupLogic.SynchronizeDbAutoBackupData(); //初始化本地的网关信息 Common.LocalGateway.Current.ReFreshByLocal(); //初始化本地的设备信息 Common.LocalDevice.Current.ReFreshByLocal(); //同步云端的网关id,如果本地拥有云端不存在的id,则表示应该被换绑了,直接删除 Common.LocalGateway.Current.SynchronizeDbGateway(); //初始化房间(郭雪城那边不做处理,需要这里特殊执行一步) Room.RefreshAllRoomByLocation(); //刷新APP前一次选择的网关ID(可以反复调用,需要在网关初始化完了之后才能调用) Common.LocalGateway.Current.RefreshAppOldSelectGatewayId(); //开启监听网关线程(二次调用没关系) ★★废弃★★ //Common.LocalGateway.Current.StartListenNetWork(); //清空强制指定文本的附加信息 ProgressBar.SetAppendText(string.Empty); //0:已经同步过,不需要同步,这个时候需要提示备份 if (result == 0) { //开启自动备份提示 HdlAutoBackupLogic.ShowAutoBackupPromptedForm(); } } //恢复可关闭进度条 ProgressBar.SetCloseBarFlag(false); return true; } #endregion #region ■ 初始化登陆账号的信息_______________ /// /// 初始化登陆账号的信息 /// /// private async static Task InitUserAccoutInfo() { //获取本地记录的用户信息 UserCenterResourse.UserInfo = GetUserInformationFromLocation(); //获取登录账号的信息 var pra = new AccountInfoPra(); var listNotShow = new List() { "NotSetAgain" }; string result = await UserCenterLogic.GetResponseDataByRequestHttps("ZigbeeUsers/GetAccountInfo", pra, listNotShow); if (result == null) { return false; } var userInfo = Newtonsoft.Json.JsonConvert.DeserializeObject(result); userInfo.Account = Common.Config.Instance.Account; if (string.IsNullOrEmpty(userInfo.UserName) == true) { //没有昵称的时候,把账号作为昵称 userInfo.UserName = Common.Config.Instance.Account; } if (Common.Config.Instance.Home.IsOthreShare == false) { //身份:管理员 userInfo.AuthorityNo = 1; userInfo.AuthorityText = Language.StringByID(R.MyInternationalizationString.Administrator); } else if (Common.Config.Instance.Home.AccountType == 1) { //身份:成员(拥有管理员权限) userInfo.AuthorityNo = 2; userInfo.AuthorityText = Language.StringByID(R.MyInternationalizationString.uMemberHadActionAuthority); } else { //身份:成员 userInfo.AuthorityNo = 3; userInfo.AuthorityText = Language.StringByID(R.MyInternationalizationString.uMember); } if (UserCenterResourse.UserInfo.AuthorityNo != userInfo.AuthorityNo) { //如果登陆的账号的权限和上一次的不一样,则删除本地这个住宅全部的文件,从头再来 string dirPath = CombinePath(); if (System.IO.Directory.Exists(dirPath) == true) { //先记录起住宅的一些信息 var house = Config.Instance.Home; //删除整个文件夹 System.IO.Directory.Delete(dirPath, true); //创建住宅文件夹 Global.CreateHomeDirectory(Config.Instance.HomeId); var newHouse = new House(); newHouse.Id = house.Id; newHouse.Name = house.Name; newHouse.IsOthreShare = house.IsOthreShare; newHouse.AccountType = house.AccountType; newHouse.MainUserDistributedMark = house.MainUserDistributedMark; newHouse.Save(); } } UserCenterResourse.UserInfo = userInfo; return true; } /// /// 从本地获取用户的登陆信息 /// /// private static UserInformation GetUserInformationFromLocation() { string fileName = CombinePath(DirNameResourse.LocalMemoryDirectory, DirNameResourse.UserInfoFile); if (System.IO.File.Exists(fileName) == false) { return new UserInformation(); } var varByte = Shared.IO.FileUtils.ReadFile(fileName); var info = Newtonsoft.Json.JsonConvert.DeserializeObject(System.Text.Encoding.UTF8.GetString(varByte)); return info; } /// /// 保存用户的登陆信息到本地 /// private static void SaveUserInformationToLocation() { var data = Newtonsoft.Json.JsonConvert.SerializeObject(UserCenterResourse.UserInfo); var byteData = System.Text.Encoding.UTF8.GetBytes(data); string fullName = UserCenterLogic.CombinePath(DirNameResourse.LocalMemoryDirectory, DirNameResourse.UserInfoFile); //写入内容 Shared.IO.FileUtils.WriteFileByBytes(fullName, byteData); } #endregion #region ■ 预创建个人中心全部的文件夹_________ /// /// 预创建个人中心全部的文件夹 /// private static void CreatAllUserCenterDirectory() { //本地缓存的根目录 string LocalDirectory = UserCenterLogic.CombinePath(DirNameResourse.LocalMemoryDirectory); Global.CreateEmptyDirectory(LocalDirectory); //自动备份【文件夹】(编辑,追加) string directory = System.IO.Path.Combine(LocalDirectory, DirNameResourse.AutoBackupDirectory); Global.CreateEmptyDirectory(directory); //自动备份【文件夹】(删除) directory = System.IO.Path.Combine(LocalDirectory, DirNameResourse.AutoBackupdeleteDirectory); Global.CreateEmptyDirectory(directory); //下载备份的时候所使用的临时【文件夹】 directory = System.IO.Path.Combine(LocalDirectory, DirNameResourse.DownLoadBackupTempDirectory); Global.CreateEmptyDirectory(directory); //保存安防记录的【文件夹】 directory = System.IO.Path.Combine(LocalDirectory, DirNameResourse.SafeguardAlarmDirectory); Global.CreateEmptyDirectory(directory); //上传网关备份文件到云端的临时【文件夹】 directory = System.IO.Path.Combine(LocalDirectory, DirNameResourse.GatewayBackupDirectory); Global.CreateEmptyDirectory(directory); //下载分享文件的临时【文件夹】 directory = System.IO.Path.Combine(LocalDirectory, DirNameResourse.DownLoadShardDirectory); Global.CreateEmptyDirectory(directory); } #endregion #region ■ 初始化管理员权限信息_______________ /// /// 初始化管理员权限信息 /// /// public static async Task InitAdministratorInfo() { //先清空 Config.Instance.isAdministrator = false; Config.Instance.AdminRequestBaseUrl = string.Empty; Config.Instance.AdminRequestToken = string.Empty; if (UserCenterResourse.UserInfo.AuthorityNo != 2) { //拥有管理员权限的成员才能这样搞 return true; } var pra = new { CommonPage.RequestVersion, LoginAccessToken = Config.Instance.Token, MainAccountId = Config.Instance.Home.MainUserDistributedMark, SharedHid = Config.Instance.Home.Id }; var listNotShow = new List() { "NotSetAgain" }; var result = await GetResponseDataByRequestHttps("App/GetSharedHomeApiControl", pra, listNotShow); if (result == null) { return false; } var praMqtt = new { CommonPage.RequestVersion, LoginAccessToken = Config.Instance.Token, Config.Instance.Home.MainUserDistributedMark, HomeId = Config.Instance.Home.Id }; var result2 = await GetResponseDataByRequestHttps("App/GetConnectMainUserMqttInfo", praMqtt, listNotShow); if (result2 == null) { return false; } Config.Instance.isAdministrator = true; //分享链接 var info = JsonConvert.DeserializeObject(result); Config.Instance.AdminRequestBaseUrl = info.RequestBaseUrl; Config.Instance.AdminRequestToken = info.RequestToken; //远程Mqtt var info2 = JsonConvert.DeserializeObject(result2); Config.Instance.AdminConnectZigbeeMqttBrokerPwd = info2.ConnectZigbeeMqttBrokerPwd; Config.Instance.AdminConnectZigbeeMqttClientId = info2.ConnectZigbeeMqttClientId; Config.Instance.AdminMqttKey = info2.MqttKey; Config.Instance.AdminZigbeeMqttBrokerLoadSubDomain = info2.ZigbeeMqttBrokerLoadSubDomain; Config.Instance.AdminConnectZigbeeMqttBrokerName = info2.ConnectZigbeeMqttBrokerName; //断开远程mqtt链接 try { if (ZigBee.Device.ZbGateway.RemoteMqttClient != null && ZigBee.Device.ZbGateway.RemoteMqttClient.IsConnected == true) { await ZigBee.Device.ZbGateway.RemoteMqttClient.DisconnectAsync(); ZigBee.Device.ZbGateway.RemoteMqttClient = null; } } catch { } return true; } #endregion #region ■ 16进制转化_________________________ /// /// 将16进制的文本翻译为正常文本 /// /// 16进制的文本 /// 以多少个字节为一组 /// public static string TranslateHexadecimalIntoText(string hexText, int count = 2) { string textValue = string.Empty; while (hexText.Length > 0) { string temp = hexText.Substring(0, count); hexText = hexText.Substring(count); int value = Convert.ToInt32(temp, 16); textValue += ((char)value).ToString(); } return textValue; } /// /// 将文本翻译为16进制的文本 /// /// 指定文本 /// public static string TranslateTextIntoHexadecimal(string text) { string textValue = string.Empty; foreach (char c in text) { int value = Convert.ToInt32(c); textValue += Convert.ToString(value, 16); } return textValue; } #endregion } }