| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475 | using Aitex.Common.Util;using Aitex.Core.Common;using Aitex.Core.Common.DeviceData;using Aitex.Core.RT.DataCenter;using Aitex.Core.RT.DBCore;using Aitex.Core.RT.Device;using Aitex.Core.RT.Device.Unit;using Aitex.Core.RT.Event;using Aitex.Core.RT.IOCore;using Aitex.Core.RT.Log;using Aitex.Core.RT.OperationCenter;using Aitex.Core.RT.Routine;using Aitex.Core.RT.SCCore;using Aitex.Core.UI.Control;using Aitex.Core.Util;using Caliburn.Micro.Core;using DocumentFormat.OpenXml.Wordprocessing;using FurnaceRT.Devices;using FurnaceRT.Equipments.Boats;using FurnaceRT.Equipments.Systems;using FurnaceRT.Equipments.WaferRobots;using MECF.Framework.Common.CommonData.EnumData;using MECF.Framework.Common.DataCenter;using MECF.Framework.Common.Device.Bases;using MECF.Framework.Common.Equipment;using MECF.Framework.Common.SubstrateTrackings;using MECF.Framework.Common.Utilities;using System;using System.Collections.Generic;using System.Data;using System.IO;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Xml.Linq;using TwinCAT.Ads.Internal;using static Aitex.Core.RT.Device.Unit.IoBoat;using static log4net.Appender.RollingFileAppender;namespace FurnaceRT.Equipments.PMs{    /// <summary>    /// 分布类 定义各种方法    /// </summary>    public partial class PMModule    {        private static Dictionary<string, Dictionary<string, string>> _allWaferTypeNode = new Dictionary<string, Dictionary<string, string>>();        private void InitOtherData()        {            DATA.Subscribe($"System.CompareFileDataA", () => _compareADic, SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"System.CompareFileDataB", () => _compareBDic, SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"System.SCDataLastWriteTime", () => GetSCDataLastWriteTime(), SubscriptionAttribute.FLAG.IgnoreSaveDB);            DATA.Subscribe($"System.BackUpFileData", () => GetAllBackUpFiles(), SubscriptionAttribute.FLAG.IgnoreSaveDB);        }        private void InitOtherOP()        {            OP.Subscribe($"System.BackUpFileData", (string cmd, object[] args) =>            {                BackUpFileDataMethod();                return true;            });            OP.Subscribe($"System.CreateZIP", (string cmd, object[] args) =>            {                CreateZIPMethod();                return true;            });            OP.Subscribe($"System.CompareFileData", CompareFileDataMethod);            OP.Subscribe($"System.RollBackFileData", RollBackFileDataMethod);        }        #region 备份/ZIP        private Dictionary<string, string> _compareADic = new Dictionary<string, string>();        private Dictionary<string, string> _compareBDic = new Dictionary<string, string>();        private int _backUpFileMaxNumber = 10;        private Dictionary<string, List<string>> GetAllBackUpFiles()        {            Dictionary<string, List<string>> result = new Dictionary<string, List<string>>();            string sourcePath = $"{PathManager.GetCfgDir()}";            string backUpFolderPath = Path.Combine(sourcePath, BackUpDireEnum.BackUp.ToString());            if (!Directory.Exists(backUpFolderPath))            {                Directory.CreateDirectory(backUpFolderPath);            }            var allDires = new DirectoryInfo(backUpFolderPath).GetDirectories();            foreach (var item in allDires)            {                var direFiles = item.GetFiles().OrderByDescending(a => a.CreationTime).Select(a => a.Name).ToList();                if (result.ContainsKey(item.Name))                {                    result[item.Name] = direFiles;                }                else                {                    result.Add(item.Name, direFiles);                }            }            return result;        }        private void CreateZIPMethod()        {            _backUpFileMaxNumber = SC.GetValue<bool>("System.IsSimulatorMode") ? 3 : SC.GetValue<int>("System.BackUpFileMaxNumber");            var startupPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion;            string sourcePath = Path.GetDirectoryName(PathManager.GetAppDir());            string zipPath = $"{PathManager.GetAppDir()}\\ZIP";            if (SC.ContainsItem("System.ZIPToDesktop") && SC.GetValue<bool>("System.ZIPToDesktop"))                zipPath = $"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}\\ZIP";            string timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");            string zipAllPath = $"{zipPath}\\{timestamp}_{startupPath}.zip";            if (!Directory.Exists(zipPath))                Directory.CreateDirectory(zipPath);            var allFiles = Directory.GetFiles(zipPath).OrderBy(f => new FileInfo(f).CreationTime).ToArray();            if (allFiles.Count() >= _backUpFileMaxNumber)                File.Delete(allFiles[0]);            if (File.Exists(zipAllPath))                File.Delete(zipAllPath);            CreateZIP(sourcePath, zipAllPath);        }        private async void CreateZIP(string sourcePath, string zipAllPath)        {            await ZIPUtil.ZipAllExceptLogFolderAsync(sourcePath, zipAllPath);        }        private bool RollBackFileDataMethod(out string reason, int time, object[] param)        {            reason = string.Empty;            if (param == null || param.Length == 0)                return true;            //先备份当前数据            BackUpFileDataMethod();            //在进行RollBack            string sourcePath = $"{PathManager.GetCfgDir()}";            var scDataPath = $"{sourcePath}\\_sc.data";            var rollBackScDataPath = $"{sourcePath}\\{BackUpDireEnum.BackUp}\\{BackUpDireEnum.SC}\\{param[0]}";            if (!File.Exists(rollBackScDataPath))                return false;            if (File.Exists(scDataPath))                File.Delete(scDataPath);            File.Copy(rollBackScDataPath, scDataPath, true);            return true;        }        private bool CompareFileDataMethod(out string reason, int time, object[] param)        {            reason = string.Empty;            if (param == null || param.Count() == 0)                return true;            string sourcePath = $"{Directory.GetCurrentDirectory()}";            var dataPara = param[0].ToString().Split(',');            if (dataPara.Count() == 1)            {                var compareAPath = $"{PathManager.GetCfgDir()}\\{BackUpDireEnum.BackUp}\\{BackUpDireEnum.SC}\\{dataPara[0]}";                var compareBPath = $"{PathManager.GetCfgDir()}\\_sc.data";                _compareADic = GetScDataByFilePath(compareAPath);                _compareBDic = GetScDataByFilePath(compareBPath);            }            else if (dataPara.Count() == 2)            {                var compareAPath = $"{PathManager.GetCfgDir()}\\{BackUpDireEnum.BackUp}\\{BackUpDireEnum.SC}\\{dataPara[0]}";                var compareBPath = $"{PathManager.GetCfgDir()}\\{BackUpDireEnum.BackUp}\\{BackUpDireEnum.SC}\\{dataPara[1]}";                _compareADic = GetScDataByFilePath(compareAPath);                _compareBDic = GetScDataByFilePath(compareBPath);            }            return true;        }        private string GetSCDataLastWriteTime()        {            var compareBPath = $"{PathManager.GetCfgDir()}\\_sc.data";            return File.GetLastWriteTime(compareBPath).ToString("yyyy-MM-dd HH-mm-ss");        }        private Dictionary<string, string> GetScDataByFilePath(string filePath)        {            Dictionary<string, string> result = new Dictionary<string, string>();            try            {                // 加载XML文件                XDocument xmlDoc = XDocument.Load(filePath);                // 获取所有的scdata元素                var scDataElements = xmlDoc.Descendants("scdata");                // 遍历每个scdata元素并打印其属性                foreach (var element in scDataElements)                {                    string name = element.Attribute("name")?.Value ?? "N/A";                    string value = element.Attribute("value")?.Value ?? "N/A";                    if (result.ContainsKey(name))                    {                        result[name] = value;                    }                    else                    {                        result.Add(name, value);                    }                }            }            catch (Exception ex)            {                // 如果发生异常,捕获并显示错误消息                Console.WriteLine("Error reading file: " + ex.Message);            }            return result;        }        private async void BackUpFileDataMethod()        {            _backUpFileMaxNumber = SC.GetValue<bool>("System.IsSimulatorMode") ? 3 : SC.GetValue<int>("System.BackUpFileMaxNumber");            var dateTime = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");            string sourcePath = $"{PathManager.GetAppDir()}";            string newSourcePath = $"{PathManager.GetCfgDir()}";            string backUpFolderPath = Path.Combine(newSourcePath, $"{BackUpDireEnum.BackUp}");            string scFolderPath = Path.Combine(newSourcePath, $"{BackUpDireEnum.BackUp}\\{BackUpDireEnum.SC}");            string ioFolderPath = Path.Combine(newSourcePath, $"{BackUpDireEnum.BackUp}\\{BackUpDireEnum.IO}");            string recipeFolderPath = Path.Combine(newSourcePath, $"{BackUpDireEnum.BackUp}\\{BackUpDireEnum.Recipes}");            string gasXmlFolderPath = Path.Combine(newSourcePath, $"{BackUpDireEnum.BackUp}\\{BackUpDireEnum.GasXml}");            string objectsFolderPath = Path.Combine(newSourcePath, $"{BackUpDireEnum.BackUp}\\{BackUpDireEnum.Objects}");            string parametersFolderPath = Path.Combine(newSourcePath, $"{BackUpDireEnum.BackUp}\\{BackUpDireEnum.Parameters}");            // 检查 SC 文件夹并复制 sc.data 文件            await CheckAndCopyFile(scFolderPath, Path.Combine(newSourcePath, "_sc.data"), $"{dateTime}@", "_sc.data");            // 检查 IO 文件夹并复制 IO 文件夹内容            await CheckAndCopyFolder(ioFolderPath, Path.Combine(newSourcePath, $"{BackUpDireEnum.IO}"), dateTime);            // 检查 Recipe 文件夹并复制 Recipe 文件夹内容            await CheckAndCopyFolder(recipeFolderPath, Path.Combine(sourcePath, $"{BackUpDireEnum.Recipes}"), dateTime);            // 检查 GasXml 文件夹并复制 GasXml 文件夹内容            await CheckAndCopyFolder(gasXmlFolderPath, Path.Combine($"{newSourcePath}", $"{BackUpDireEnum.GasXml}"), dateTime);            // 检查 Objects 文件夹并复制 Objects 文件夹内容            await CheckAndCopyFolder(objectsFolderPath, Path.Combine(sourcePath, $"{BackUpDireEnum.Objects}"), dateTime);            // 检查 Parameters 文件夹并复制 Parameters 文件夹内容            await CheckAndCopyFolder(parametersFolderPath, Path.Combine(sourcePath, $"{BackUpDireEnum.Parameters}"), dateTime);            GetAllBackUpFiles();        }        private async Task CheckAndCopyFile(string targetFolderPath, string sourceFilePath, string prefixFileName, string fileName)        {            if (!Directory.Exists(targetFolderPath))                Directory.CreateDirectory(targetFolderPath);            var allpath = $"{prefixFileName}{fileName}";            string destinationFilePath = Path.Combine(targetFolderPath, allpath);            try            {                var filesWithSameName = Directory.GetFiles(targetFolderPath)                                       .Where(f => Path.GetFileName(f).Contains(fileName))                                       .OrderBy(f => new FileInfo(f).CreationTime)                                       .ToArray();                // If there are more than 10 files, delete the oldest one                if (filesWithSameName.Length >= _backUpFileMaxNumber)                {                    File.Delete(filesWithSameName[0]);                }                if (File.Exists(destinationFilePath))                    return;                await Task.Run(() => File.Copy(sourceFilePath, destinationFilePath, true));            }            catch (Exception ex)            {                Console.WriteLine($"Error copying {fileName}: {ex.Message}");            }        }        private async Task CheckAndCopyFolder(string targetFolderPath, string sourceFolderPath, string dateTime)        {            if (!Directory.Exists(targetFolderPath))                Directory.CreateDirectory(targetFolderPath);            if (!Directory.Exists(sourceFolderPath))            {                return;            }            try            {                await CopyDirectory(sourceFolderPath, targetFolderPath, dateTime);            }            catch (Exception ex)            {                Console.WriteLine($"Error copying folder {sourceFolderPath}: {ex.Message}");            }        }        private async Task CopyDirectory(string sourceDirName, string destDirName, string dateTime)        {            // Get the subdirectories for the specified directory.            DirectoryInfo dir = new DirectoryInfo(sourceDirName);            if (!dir.Exists)            {                throw new DirectoryNotFoundException(                    "Source directory does not exist or could not be found: "                    + sourceDirName);            }            DirectoryInfo[] dirs = dir.GetDirectories();            // If the destination directory doesn't exist, create it.            if (!Directory.Exists(destDirName))                Directory.CreateDirectory(destDirName);            var newFies = new DirectoryInfo(destDirName).GetFiles().OrderBy(f => f.CreationTime).Select(a => a.Name).ToList();            // Get the files in the directory and copy them to the new location.            FileInfo[] files = dir.GetFiles();            foreach (FileInfo file in files)            {                var sameFiles = newFies.Where(a => a.Contains(file.Name)).ToArray();                if (sameFiles.Length >= _backUpFileMaxNumber)                {                    File.Delete(Path.Combine(destDirName, sameFiles[0]));                }                var newName = $"{dateTime}@{file.Name}";                if (newFies.Contains(newName))                {                    continue;                }                string tempPath = Path.Combine(destDirName, newName);                await Task.Run(() => file.CopyTo(tempPath, true));            }            // Recursively call CopyDirectory on each subdirectory.            foreach (DirectoryInfo subdir in dirs)            {                string temppath = Path.Combine(destDirName, subdir.Name);                await CopyDirectory(subdir.FullName, temppath, dateTime);            }        }        #endregion        public void InitAllWaferTypeNode()        {            _allWaferTypeNode = SC.GetAllWaferTypeColor();        }        public string GetCarrierUIColor(string carrierType, CarrierStatus carrierStatus)        {            var defaultColor = "#ccc";            if (carrierType == null || !_allWaferTypeNode.ContainsKey(carrierType))                return defaultColor;            if (!_allWaferTypeNode[carrierType].ContainsKey(carrierStatus.ToString()))                return defaultColor;            return _allWaferTypeNode[carrierType][carrierStatus.ToString()];        }        private void AxisDataLoad(object[] args)        {            var trigDataLoad = DEVICE.GetDevice<IoTrigger>($"{ModuleName.PM1.ToString()}.TrigDataLoad");            var trigDataSend = DEVICE.GetDevice<IoTrigger>($"{ModuleName.PM1.ToString()}.TrigDataSend");            trigDataSend.SetTrigger(false, out _);            trigDataLoad.SetTrigger(true, out _);            Thread.Sleep(1500);            var paras = args[0].ToString().Split(',');            foreach (var item in paras)            {                var path = $"System.AxisParameters.{item}";                if (!SC.ContainsItem(path))                    continue;                var ioName = $"{ModuleName.PM1}.{item}";                var dataValue = IO.AO[ioName].FloatValue;                SC.SetItemValue(path, dataValue);            }            trigDataLoad.SetTrigger(false, out _);        }        private void AxisDataSend(object[] args)        {            var trigDataLoad = DEVICE.GetDevice<IoTrigger>($"{ModuleName.PM1.ToString()}.TrigDataLoad");            var trigDataSend = DEVICE.GetDevice<IoTrigger>($"{ModuleName.PM1.ToString()}.TrigDataSend");            trigDataSend.SetTrigger(true, out _);            trigDataLoad.SetTrigger(false, out _);            var paras = args[0].ToString().Split(',');            foreach (var item in paras)            {                var path = $"System.AxisParameters.{item}";                if (!SC.ContainsItem(path))                    continue;                var ioName = $"{ModuleName.PM1}.{item}";                var scDataValue = SC.GetValue<double>(path);                IO.AO[ioName].FloatValue = (float)scDataValue;            }            trigDataSend.SetTrigger(false, out _);        }        private Dictionary<string, string> GetHeatersData()        {            Dictionary<string, string> result = new Dictionary<string, string>();            if (_heaters == null || _heaters.Count == 0)            {                return result;            }            foreach (var item in _heaters)            {                result.Add(item.Display, item.TempFeedback.ToString("f1"));            }            return result;        }        public void TriggerJobAutoStart(string recipe, RecipeExecEntryEnum recipeExecEntryEnumValue)        {            RecipeExecEntryEnumValue = recipeExecEntryEnumValue;            CheckToPostMessage((int)MSG.RunOtherRecipe, recipe, "Process");        }        public string GetAlarmWarningMsg(ScheduleMaintenanceDataItem item, bool isJobAutoStart = false, string currentValue = "", string minValue = "", string maxValue = "")        {            string nullMessage = $"{item.Display} No recipe file associated, unable to trigger JobAutoStart";            if (!string.IsNullOrEmpty(minValue) && !string.IsNullOrEmpty(maxValue) && !string.IsNullOrEmpty(currentValue))            {                return $"{item.Item}-{item.Display} {item.AdditionInformationDisplay}  {currentValue} limit is ({minValue}~{maxValue}) {item.Unit}"; ;            }            if (isJobAutoStart && string.IsNullOrEmpty(item.AssociationProcessRecipeName))            {                return nullMessage;            }            return $"{item.Item}-{item.Display} {item.AdditionInformationDisplay}  {item.CurrentValue} limit is ({item.StartValue}~{item.LimitValue}) {item.Unit}"; ;        }    }    public enum BackUpDireEnum    {        SC,        GasXml,        IO,        Objects,        Parameters,        Recipes,        BackUp,        Config,    }}
 |