using S7.Net; using System.Xml.Linq; namespace xicheji { public class ConfigHelper { private const string configFileName = "config.xml"; private static Config? _config; public static Config GetConfig() { _config ??= LoadConfig(); return _config; } private static Config LoadConfig() { if (!File.Exists(configFileName)) { return new Config(); } var xdoc = XDocument.Load(configFileName); if (xdoc.Root == null) { return new Config(); } var config = new Config(); var platform = xdoc.Root!.Element("Platform"); config.Server = platform?.Attribute("Server")?.Value ?? ""; var device = xdoc.Root!.Element("Device"); config.PLCIP = device?.Attribute("IP")?.Value ?? ""; config.PLCPort = device?.Attribute("Port")?.Value ?? ""; config.PLCType = Enum.Parse(device?.Attribute("Type")?.Value ?? "S7200"); config.PLCReceiveInterval = int.Parse(device?.Attribute("ReceiveInterval")?.Value ?? "2"); var camera = xdoc.Root!.Element("Camera"); config.CameraIP = camera?.Attribute("IP")?.Value ?? ""; config.CameraPort = camera?.Attribute("Port")?.Value ?? ""; config.CameraUserName = camera?.Attribute("UserName")?.Value ?? ""; config.CameraPassword = camera?.Attribute("Password")?.Value ?? ""; var variablesRoot = xdoc.Root!.Element("Variables"); if (variablesRoot != null) { config.DBName = variablesRoot.Attribute("DBName")?.Value ?? "DB1"; var variables = variablesRoot.Elements("Variable"); foreach (XElement item in variables) { var variable = new Variable(); variable.Name = item.Attribute("Name")?.Value ?? ""; variable.Key = item.Attribute("Key")?.Value ?? ""; variable.Desc = item.Attribute("Desc")?.Value ?? ""; if (string.IsNullOrEmpty(variable.Name) || string.IsNullOrEmpty(variable.Key)) { continue; } config.Variables.Add(variable); } } return config; } public static void SaveConfig(Config config) { _config = config; } public static Variable? FindVariable(string variableName) { var config = GetConfig(); var variable = config.Variables.Find(x => x.Name == variableName); return variable; } } public class Config { public string Server { get; set; } = string.Empty; public string PLCIP { get; set; } = string.Empty; public string PLCPort { get; set; } = string.Empty; public CpuType PLCType { get; set; } = CpuType.S7200; public int PLCReceiveInterval { get; set; } = 2; public string CameraIP { get; set; } = string.Empty; public string CameraPort { get; set; } = string.Empty; public string CameraUserName { get; set; } = string.Empty; public string CameraPassword { get; set; } = string.Empty; public string DBName { get; set; } = string.Empty; public List Variables { get; set; } = new(); } public class Variable { public string Name { get; set; } = string.Empty; public string Key { get; set; } = string.Empty; public string Desc { get; set; } = string.Empty; } }