黄学彪
2020-09-18 c7df85937f73fb347ee0b19e9c052d2d00a6df6c
ZigbeeApp/Shared/Phone/TemplateData/TemplateCommonLogic.cs
@@ -130,7 +130,7 @@
            //读取模板Bin文件
            if (templateBinFile != string.Empty)
            {
                bool hadRoom = HdlRoomLogic.Current.GetAllListRooms().Count > 1;
                bool hadRoom = HdlRoomLogic.Current.GetAllListRooms().Count > 1 && Common.Config.Instance.Home.FloorDics.Count == 0;
                //开始读取文件内容
                this.ReadTemplateFileMethord((strData, saveDiv, deviceType) =>
                {
@@ -171,7 +171,7 @@
        /// </summary>
        /// <param name="strData">模板文件中的行数据</param>
        /// <param name="hadRoom">是否已经有了房间</param>
        private bool AdjustTemplateBinFileContentOnLoadMemory(string strData,bool hadRoom)
        private bool AdjustTemplateBinFileContentOnLoadMemory(string strData, bool hadRoom)
        {
            //场景对象
            if (strData == "#SceneTemplate END#")
@@ -192,6 +192,7 @@
                {
                    //只初始化一次,有房间时代表已经不是第一次加载了
                    Common.Config.Instance.Home.FloorDics = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(this.strTempContentData);
                    Common.Config.Instance.Home.Save(false);
                }
                this.strTempContentData = string.Empty;
                return true;
@@ -265,6 +266,16 @@
            //再次初始化房间
            HdlRoomLogic.Current.InitAllRoom();
            //无模板模式时,恢复备份的时候,把备份文件删除
            if (Common.Config.Instance.Home.TemplateMode != 2)
            {
                //存放的路径
                string fullFile = System.IO.Path.Combine(DirNameResourse.LocalTemplateDirectory, TemplateFileName);
                HdlFileLogic.Current.DeleteFile(fullFile);
            }
            //覆盖物理设备所在的房间数据
            HdlFileLogic.Current.SaveFileContent(DirNameResourse.DeviceRoomIdFile, this.modelData.dicDeviceTemplateRealRoom);
        }
        /// <summary>
@@ -285,6 +296,7 @@
            else if (strData == "#FloorInfo END#")
            {
                Common.Config.Instance.Home.FloorDics = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(this.strTempContentData);
                Common.Config.Instance.Home.Save(false);
                this.strTempContentData = string.Empty;
                return true;
            }
@@ -498,9 +510,17 @@
            {
                modelData = Newtonsoft.Json.JsonConvert.DeserializeObject<ModelDeviceBindData>(fileData);
            }
            else if (saveDiv == ModelDeviceSaveEnum.A面板背光灯)
            else if (saveDiv == ModelDeviceSaveEnum.A面板亮度调节)
            {
                modelData = Newtonsoft.Json.JsonConvert.DeserializeObject<ModelPanelBackLightInfo>(fileData);
                modelData = Newtonsoft.Json.JsonConvert.DeserializeObject<ModelPanelBrightnessAdjustInfo>(fileData);
            }
            else if (saveDiv == ModelDeviceSaveEnum.A面板节能模式)
            {
                modelData = Newtonsoft.Json.JsonConvert.DeserializeObject<ModelPanelEnergyModeInfo>(fileData);
            }
            else if (saveDiv == ModelDeviceSaveEnum.A面板指示灯)
            {
                modelData = Newtonsoft.Json.JsonConvert.DeserializeObject<ModelPanelIndicatorLightInfo>(fileData);
            }
            else if (saveDiv == ModelDeviceSaveEnum.A面板震动功能)
            {
@@ -569,7 +589,7 @@
                {
                    fileName = model.FileName;
                    //备份数据已经存在,是否覆盖?
                    this.ShowMassage(ShowMsgType.Confirm, "备份数据已经存在,是否覆盖?", () =>
                    this.ShowMassage(ShowMsgType.Confirm, Language.StringByID(R.MyInternationalizationString.BackUpDataIsEsixtAndPickUp), () =>
                    {
                        //将模板数据保存到到指定的文件夹中
                        this.SaveTemplateDataToLocation2(fileName, backupName);
@@ -605,7 +625,7 @@
                else
                {
                    //本地备份保存成功
                    this.ShowMassage(ShowMsgType.Tip, "本地备份保存成功");
                    this.ShowMassage(ShowMsgType.Tip, Language.StringByID(R.MyInternationalizationString.SaveLocalBackDataSuccess));
                }
            });
        }
@@ -649,6 +669,9 @@
                TemplateDeviceDataLogic.Current.ReDeviceEpointName(device, Common.LocalDevice.Current.GetDeviceEpointName(device));
            }
        }
        #endregion
        #region ■ 获取模板对象相关___________________
        /// <summary>
        /// 获取本地全部的模板列表的基本信息
@@ -704,12 +727,265 @@
        }
        /// <summary>
        /// 获取云端全部的模板列表的基本信息
        /// </summary>
        /// <returns></returns>
        public List<CloundModelBaseInfo> GetCloundAllModelList()
        {
            var pra = new
            {
                RequestVersion = Common.CommonPage.RequestVersion,
                RequestSource = 5,
                LoginAccessToken = Common.Config.Instance.Token
            };
            var result = UserCenterLogic.GetResponseDataByRequestHttps("ProjectTemplate/GetProTemplateList", false, pra);
            if (result == null) { return new List<CloundModelBaseInfo>(); }
            var dicData = new Dictionary<string, List<CloundModelBaseInfo>>();
            var listTime = new List<string>();
            var listCloundData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CloundModelBaseInfo>>(result);
            foreach (var data in listCloundData)
            {
                //变更时间格式
                data.CreatedOnUtc = UserCenterLogic.ConvertUtcTimeToLocalTime(data.CreatedOnUtc).ToString("yyyy.MM.dd HH:mm");
                if (dicData.ContainsKey(data.CreatedOnUtc) == false)
                {
                    dicData[data.CreatedOnUtc] = new List<CloundModelBaseInfo>();
                    listTime.Add(data.CreatedOnUtc);
                }
                dicData[data.CreatedOnUtc].Add(data);
            }
            //按时间排序
            listTime.Sort();
            var listData = new List<CloundModelBaseInfo>();
            for (int i = listTime.Count - 1; i >= 0; i--)
            {
                listData.AddRange(dicData[listTime[i]]);
            }
            return listData;
        }
        /// <summary>
        /// 获取一个新的模板保存文件名
        /// </summary>
        /// <returns></returns>
        public string GetNewTemplateFileName()
        {
            return "ModelData_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".bin";
            return "ModelData_Local_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".bin";
        }
        #endregion
        #region ■ 上传模板备份_______________________
        /// <summary>
        /// 上传模板备份(内部使用线程来执行,有转圈的界面)
        /// </summary>
        /// <param name="i_localTemplate">本地模板信息</param>
        /// <param name="i_saveName">备份名字</param>
        public void UpLoadTemplateData(LocalModelBaseInfo i_localTemplate, string i_saveName)
        {
            HdlThreadLogic.Current.RunThread(() =>
            {
                ProgressBar.Show();
                //获取云端的模板列表
                var listTemplate = this.GetCloundAllModelList();
                foreach (var data in listTemplate)
                {
                    if (data.TemplateName == i_saveName)
                    {
                        //模板名字已经存在
                        this.ShowMassage(ShowMsgType.Tip, Language.StringByID(R.MyInternationalizationString.TheTemplateNameIsEsixt));
                        ProgressBar.Close();
                        return;
                    }
                }
                //这里修改掉模板文件里面记载的模板名称
                string templateFile = System.IO.Path.Combine(DirNameResourse.AllResidenceTemplateDirectory, i_localTemplate.FileName);
                string binFileData = HdlFileLogic.Current.ReadFileTextContent(templateFile);
                var arryBinFile = binFileData.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                //替换目标 这里是模板基本信息的json数据
                string strFileData = arryBinFile[1];
                var templateBaseInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<LocalModelBaseInfo>(strFileData);
                templateBaseInfo.ModelName = i_saveName;//更改掉名字
                templateBaseInfo.EditorTime = DateTime.Now.ToString("yyyy.MM.dd HH:mm");//更改掉时间
                //替换对象
                string replaceDta = Newtonsoft.Json.JsonConvert.SerializeObject(templateBaseInfo);
                binFileData = binFileData.Replace(strFileData, replaceDta);
                var pra = new
                {
                    RequestVersion = Common.CommonPage.RequestVersion,
                    RequestSource = 5,
                    LoginAccessToken = Common.Config.Instance.Token,
                    ProTemplateName = i_saveName,
                    ProTemplateDetails = new List<TemplateDetailsInfo>()
                };
                var detailsInfo = new TemplateDetailsInfo();
                detailsInfo.DetailName = "ModelData_Cloud_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".bin";
                detailsInfo.DetailContent = Encoding.UTF8.GetBytes(binFileData);
                pra.ProTemplateDetails.Add(detailsInfo);
                //清掉这个字符串缓存
                binFileData = null;
                var result = UserCenterLogic.GetResultStatuByRequestHttps("ProjectTemplate/AddProTemplate", false, pra);
                if (result == true)
                {
                    //上传模板成功
                    this.ShowMassage(ShowMsgType.Tip, Language.StringByID(R.MyInternationalizationString.UploadTemplateSuccess));
                }
                else
                {
                    //上传模板失败
                    this.ShowMassage(ShowMsgType.Tip, Language.StringByID(R.MyInternationalizationString.UploadTemplateFail));
                }
                ProgressBar.Close();
            });
        }
        /// <summary>
        /// 上传模板文件的信息
        /// </summary>
        private class TemplateDetailsInfo
        {
            /// <summary>
            /// 文件名字
            /// </summary>
            public string DetailName = string.Empty;
            /// <summary>
            /// 模板内容
            /// </summary>
            public byte[] DetailContent = null;
        }
        #endregion
        #region ■ 下载模板备份_______________________
        /// <summary>
        /// 下载模板备份(内部是使用线程执行,有界面型进度条)
        /// </summary>
        /// <param name="i_templateId">数据库主键</param>
        /// <param name="i_SuccessAction">下载完全成功之后的回调事件,参数为保存模板的全路径(参数null代表失败)</param>
        public void DownLoadTemplate(string i_templateId, Action<string> i_SuccessAction = null)
        {
            HdlThreadLogic.Current.RunThread(() =>
            {
                ProgressFormBar.Current.Start();
                ProgressFormBar.Current.SetMsg("正在下载模板数据");
                System.Threading.Thread.Sleep(1500);
                var pra = new
                {
                    RequestVersion = Common.CommonPage.RequestVersion,
                    RequestSource = 5,
                    LoginAccessToken = Common.Config.Instance.Token,
                    ProTemplateId = i_templateId
                };
                var result = UserCenterLogic.GetResponseDataByRequestHttps("ProjectTemplate/GetProTemplateDetailList", false, pra);
                if (result == null)
                {
                    //下载模板失败
                    this.ShowMassage(ShowMsgType.Tip, Language.StringByID(R.MyInternationalizationString.DownloadTemplateFail));
                    ProgressFormBar.Current.Close();
                    i_SuccessAction?.Invoke(null);
                    return;
                }
                var fileListData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<DownloadTemplateData>>(result);
                if (fileListData.Count == 0)
                {
                    //下载模板失败
                    this.ShowMassage(ShowMsgType.Tip, Language.StringByID(R.MyInternationalizationString.DownloadTemplateFail));
                    ProgressFormBar.Current.Close();
                    i_SuccessAction?.Invoke(null);
                    return;
                }
                //解析这个模板的名字
                var strFileData = this.GetDataFromFileContent(Encoding.UTF8.GetString(fileListData[0].DetailContent), "#START#", "#TemplateData END#");
                var templateBaseInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<LocalModelBaseInfo>(strFileData);
                //检测本地的模板是否有同名的
                var listLocal = this.GetLocalAllModelList();
                string fileName = fileListData[0].DetailName;
                foreach (var localData in listLocal)
                {
                    if (localData.ModelName == templateBaseInfo.ModelName)
                    {
                        //替换,直接使用本地的模板文件名字
                        fileName = localData.FileName;
                        break;
                    }
                }
                //存成文件
                string fileFullName = System.IO.Path.Combine(DirNameResourse.AllResidenceTemplateDirectory, fileName);
                HdlFileLogic.Current.SaveByteToFile(fileFullName, fileListData[0].DetailContent);
                //获取升级固件文件
                var result2 = HdlFirmwareUpdateLogic.DownLoadTemplateDeviceFirmware(fileFullName, "正在获取升级固件数据");
                if (result2 == -1)
                {
                    this.ShowMassage(ShowMsgType.Tip, "获取升级固件数据失败");
                    ProgressFormBar.Current.Close();
                    i_SuccessAction?.Invoke(null);
                    return;
                }
                ProgressFormBar.Current.Close();
                i_SuccessAction?.Invoke(fileFullName);
            });
        }
        /// <summary>
        /// 下载模板
        /// </summary>
        private class DownloadTemplateData
        {
            /// <summary>
            /// 模板文件名字
            /// </summary>
            public string DetailName = string.Empty;
            /// <summary>
            /// 模板数据
            /// </summary>
            public byte[] DetailContent = null;
        }
        #endregion
        #region ■ 删除模板备份_______________________
        /// <summary>
        /// 删除云端模板备份
        /// </summary>
        /// <param name="i_templateId">模板主键</param>
        /// <returns></returns>
        public bool DeleteTemplateFromDb(string i_templateId)
        {
            var pra = new
            {
                RequestVersion = Common.CommonPage.RequestVersion,
                RequestSource = 5,
                LoginAccessToken = Common.Config.Instance.Token,
                ProTemplateId = i_templateId
            };
            var result = UserCenterLogic.GetResultStatuByRequestHttps("ProjectTemplate/DeleteProTemplate", false, pra);
            return result;
        }
        /// <summary>
        /// 删除本地模板备份
        /// </summary>
        /// <param name="i_baseInfo">本地模板的基本信息</param>
        /// <returns></returns>
        public void DeleteLocalTemplate(LocalModelBaseInfo i_baseInfo)
        {
            var fullFile = System.IO.Path.Combine(DirNameResourse.AllResidenceTemplateDirectory, i_baseInfo.FileName);
            HdlFileLogic.Current.DeleteFile(fullFile);
        }
        #endregion
@@ -909,13 +1185,10 @@
            var listRoom = HdlRoomLogic.Current.GetAllListRooms();
            foreach (var room in listRoom)
            {
                if (room.IsLove == false)
                {
                    writeText += "#START#\r\n";
                    string dataInfo2 = Newtonsoft.Json.JsonConvert.SerializeObject(room);
                    writeText += dataInfo2 + "\r\n";
                    writeText += "#RoomInfo END#\r\n\r\n";
                }
                writeText += "#START#\r\n";
                string dataInfo2 = Newtonsoft.Json.JsonConvert.SerializeObject(room);
                writeText += dataInfo2 + "\r\n";
                writeText += "#RoomInfo END#\r\n\r\n";
            }
            //物理网关所在的房间
            var dicRealRoom = new Dictionary<string, string>();
@@ -1044,7 +1317,7 @@
                    }
                }
                //不管如何,都需要则重新保存成文件
                this.SaveDeviceMemmoryData(device);
                this.SaveDeviceMemmoryData(device.DeviceAddr, device.DeviceEpoint);
                //还原及变更场景的执行目标
                //this.RecoverAndChangedSceneAdjustTarget(device, targetMac);
            }
@@ -1197,12 +1470,12 @@
                HdlGatewayLogic.Current.ChangedGatewayRoom(sourceGwid, this.modelData.dicDeviceTemplateRealRoom[targetGwid]);
            }
            //变更网关名字
            if (this.modelData.dicGatewayInfo.ContainsKey(targetGwid) == true)
            {
                var localGateway = HdlGatewayLogic.Current.GetLocalGateway(sourceGwid);
                string gwName = HdlGatewayLogic.Current.GetGatewayName(this.modelData.dicGatewayInfo[targetGwid]);
                HdlGatewayLogic.Current.ReName(localGateway, gwName);
            }
            //if (this.modelData.dicGatewayInfo.ContainsKey(targetGwid) == true)
            //{
            //    var localGateway = HdlGatewayLogic.Current.GetLocalGateway(sourceGwid);
            //    string gwName = HdlGatewayLogic.Current.GetGatewayName(this.modelData.dicGatewayInfo[targetGwid]);
            //    HdlGatewayLogic.Current.ReName(localGateway, gwName);
            //}
        }
        /// <summary>
@@ -1403,12 +1676,13 @@
        #region ■ 保存设备缓存_______________________
        /// <summary>
        /// 保存设备缓存
        /// 保存设备缓存(考虑有的设备用的是200端点,所以这里最好不用设备对象作为参数)
        /// </summary>
        /// <param name="device">设备对象</param>
        public void SaveDeviceMemmoryData(CommonDevice device)
        /// <param name="deviceMac">设备mac</param>
        /// <param name="deviceEpoint">设备Epoint</param>
        public void SaveDeviceMemmoryData(string deviceMac, int deviceEpoint)
        {
            string mainkey = Common.LocalDevice.Current.GetDeviceMainKeys(device);
            string mainkey = Common.LocalDevice.Current.GetDeviceMainKeys(deviceMac, deviceEpoint);
            if (this.modelData.dicDeviceTemplateData.ContainsKey(mainkey) == false)
            {
                return;
@@ -1416,7 +1690,7 @@
            //保存路径
            string saveFile = DirNameResourse.LocalTemplateDirectory;
            saveFile = System.IO.Path.Combine(saveFile, device.FilePath);
            saveFile = System.IO.Path.Combine(saveFile, mainkey);
            var listData = this.modelData.dicDeviceTemplateData[mainkey];
            if (listData.Count == 0)
@@ -1493,9 +1767,9 @@
        /// 获取需要升级的网关对象(key:本地网关的id value:升级固件地址,第一位是Linux,第二位是协调器,之后都是虚拟驱动)
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, List<string>> GetNeedToUpdateGateway()
        public Dictionary<string, List<GatewayNeedUpdateInfo>> GetNeedToUpdateGateway()
        {
            var dicGateway = new Dictionary<string, List<string>>();
            var dicGateway = new Dictionary<string, List<GatewayNeedUpdateInfo>>();
            //循环网关匹配的模板
            foreach (var localId in this.modelData.dicGatewayTemplateSelect.Keys)
            {
@@ -1514,8 +1788,9 @@
                }
                var tempGateway = this.modelData.dicGatewayInfo[tempId];
                //初始化容器
                dicGateway[localId] = new List<string>() { null, null };
                var listUpdateInfo = new List<GatewayNeedUpdateInfo>() { null, null };
                bool needUpdate = false;
                //Linux版本比较
                if (tempGateway.LinuxFirmwareVersion != localGateway.LinuxFirmwareVersion)
                {
@@ -1524,7 +1799,11 @@
                    if (System.IO.File.Exists(updateFile) == true)
                    {
                        //如果存在的话
                        dicGateway[localId][0] = updateFile;
                        var info = new GatewayNeedUpdateInfo();
                        info.Div = 1;
                        info.FullFileName = updateFile;
                        listUpdateInfo[0] = info;
                        needUpdate = true;
                    }
                }
                //协调器版本比较
@@ -1535,7 +1814,11 @@
                    if (System.IO.File.Exists(updateFile) == true)
                    {
                        //如果存在的话
                        dicGateway[localId][1] = updateFile;
                        var info = new GatewayNeedUpdateInfo();
                        info.Div = 2;
                        info.FullFileName = updateFile;
                        listUpdateInfo[1] = info;
                        needUpdate = true;
                    }
                }
                //虚拟驱动比较
@@ -1546,18 +1829,28 @@
                        foreach (var tempCode in tempGateway.DriveCodeList)
                        {
                            //防止它放的顺序不样
                            if (localCode.DriveId == tempCode.DriveId && localCode.DriveFwVersion != tempCode.DriveFwVersion)
                            if (localCode.DriveCode == tempCode.DriveCode && localCode.DriveFwVersion != tempCode.DriveFwVersion)
                            {
                                //虚拟驱动升级固件文件全路径
                                string updateFile = HdlFirmwareUpdateLogic.GetGatewayDriveCodeFirmwareFile(tempCode);
                                if (System.IO.File.Exists(updateFile) == true)
                                {
                                    //如果存在的话
                                    dicGateway[localId].Add(updateFile);
                                    var info = new GatewayNeedUpdateInfo();
                                    info.Div = 3;
                                    info.DriveCode = tempCode.DriveCode;
                                    info.FullFileName = updateFile;
                                    listUpdateInfo.Add(info);
                                    needUpdate = true;
                                }
                            }
                        }
                    }
                }
                //添加目标缓存
                if (needUpdate == true)
                {
                    dicGateway[localId] = listUpdateInfo;
                }
            }
@@ -1763,14 +2056,14 @@
        }
        /// <summary>
        /// 获取设备保存的模板对象
        /// 获取设备保存的模板对象(考虑有的设备用的是200端点,所以这里最好不用设备对象作为参数)
        /// </summary>
        /// <param name="device"></param>
        /// <param name="saveEnum"></param>
        /// <returns></returns>
        public TemplateDeviceDataCommon GetDeviceModelDataClass(CommonDevice device, ModelDeviceSaveEnum saveEnum, TemplateDeviceDataCommon newClass)
        public TemplateDeviceDataCommon GetDeviceModelDataClass(string deviceMac, int deviceEpoint, ModelDeviceSaveEnum saveEnum, TemplateDeviceDataCommon newClass)
        {
            string mainkey = Common.LocalDevice.Current.GetDeviceMainKeys(device);
            string mainkey = Common.LocalDevice.Current.GetDeviceMainKeys(deviceMac, deviceEpoint);
            //创建存储空间
            if (this.modelData.dicDeviceTemplateData.ContainsKey(mainkey) == false)
@@ -1787,8 +2080,8 @@
            }
            //新建一个新的对象
            newClass.DataSaveDiv = saveEnum;
            newClass.DeviceEpoint = device.DeviceEpoint;
            newClass.DeviceMac = device.DeviceAddr;
            newClass.DeviceEpoint = deviceEpoint;
            newClass.DeviceMac = deviceMac;
            //默认创建一个索引位
            newClass.ListReceiveResult.Add(string.Empty);
@@ -1809,36 +2102,7 @@
        /// <param name="buttonText">按钮的文本</param>
        private void ShowMassage(ShowMsgType msgType, string msg, Action action = null, string buttonText = null)
        {
            //空对象时,不显示
            if (string.IsNullOrEmpty(msg))
            {
                return;
            }
            Application.RunOnMainThread(() =>
            {
                var alert = new ShowMsgControl(msgType, msg, buttonText);
                if (action != null)
                {
                    alert.ConfirmClickEvent += () =>
                    {
                        try
                        {
                            //回调函数
                            action?.Invoke();
                        }
                        catch (Exception ex)
                        {
                            //出现未知错误,数据丢失
                            this.ShowMassage(ShowMsgType.Error, Language.StringByID(R.MyInternationalizationString.uUnKnownError));
                            //Log出力
                            HdlLogLogic.Current.WriteLog(ex);
                        }
                        action = null;
                    };
                }
                alert.Show();
            });
            HdlMessageLogic.Current.ShowMassage(msgType, msg, action, buttonText);
        }
        #endregion