using System; using System.Collections.Generic; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace StandardScene.Signal { /// /// 信号插件 JSON 的路径解析与读写。 /// /// /// 只使用 SimpleLite 工作目录 Config/Signal/*.json,不读、不拷 plugins/Config/Signal。 /// 文件不存在时 Load 返回空表;Save 会创建目录。 /// 迷毂数据中心走同一套文件;保存后需在本进程点「重新加载配置」。 /// 枚举按名字序列化(),与样例里 "上线机构" 一致。 /// public static class SignalConfigStore { /// 保存时串行写盘,避免 CycleGUI 与迷毂 API 同时 Save 互相覆盖一半。 private static readonly object FileLock = new object(); private static readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, Converters = { new StringEnumConverter() } }; /// /// 相对路径固定落到工作目录(SimpleLite.exe 所在目录)下的 Config/Signal。 /// 已是绝对路径则原样返回。文件不存在也返回该路径,不回退插件目录。 /// public static string Resolve(string configuredPath) { if (string.IsNullOrWhiteSpace(configuredPath)) configuredPath = Path.Combine("Config", "Signal", "stations.json"); if (Path.IsPathRooted(configuredPath)) return configuredPath; return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configuredPath); } /// /// 反序列化为列表。文件不存在、空、或 JSON 损坏时返回空列表,不抛给启动流程。 /// public static List Load(string path) where T : class { try { if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) return new List(); var json = File.ReadAllText(path); if (string.IsNullOrWhiteSpace(json)) return new List(); return JsonConvert.DeserializeObject>(json, JsonSettings) ?? new List(); } catch { return new List(); } } /// 缩进写入;自动建目录。与 Load 共用枚举按名序列化。 public static void Save(string path, IReadOnlyList items) { var json = JsonConvert.SerializeObject(items ?? Array.Empty(), JsonSettings); var dir = Path.GetDirectoryName(path); if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); lock (FileLock) File.WriteAllText(path, json); } } }