FeederManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using Newtonsoft.Json;
  8. using TeamAAS.Feeder.Attributes;
  9. using TeamAAS.Feeder.Devices;
  10. using TeamAAS.Feeder.Interfaces;
  11. using TeamAAS.Feeder.Models;
  12. using TeamAAS.Feeder.Enums;
  13. using TeamAAS.Feeder.Models;
  14. namespace TeamAAS.Feeder
  15. {
  16. /// <summary>
  17. /// 供料器管理器。懒汉单例:<c>FeederManager.Instance</c>。
  18. /// 整合:设备 CRUD + 配方管理 + 反射发现设备类型 + 配置持久化。
  19. /// 管理类按架构规则保留在根命名空间 TeamAAS.Feeder。
  20. /// </summary>
  21. public class FeederManager : IFeederManager
  22. {
  23. #region 单例
  24. private static readonly Lazy<FeederManager> _instance =
  25. new Lazy<FeederManager>(() => new FeederManager(), isThreadSafe: true);
  26. /// <summary>
  27. /// 懒汉单例入口。首次访问时初始化,线程安全。
  28. /// </summary>
  29. public static FeederManager Instance => _instance.Value;
  30. #endregion
  31. private readonly object _sync = new object();
  32. private readonly Dictionary<Guid, FeederInfo> _feeders = new Dictionary<Guid, FeederInfo>();
  33. private readonly Dictionary<Guid, IFeeder> _devices = new Dictionary<Guid, IFeeder>();
  34. private List<FeederRecipe> _recipes = new List<FeederRecipe>();
  35. private List<FeederTypeInfo> _scannedTypes;
  36. private readonly object _scanLock = new object();
  37. public static string DefaultConfigPath => TeamAAS.PathHelper.FeedersConfigFile;
  38. private static string DefaultRecipeFilePath => TeamAAS.PathHelper.FeederRecipesFile;
  39. public event EventHandler FeederListChanged;
  40. public FeederManager()
  41. {
  42. _recipes = LoadAllRecipesInternal();
  43. }
  44. #region 设备配置 CRUD
  45. public void LoadConfig(string path = null)
  46. {
  47. path = path ?? DefaultConfigPath;
  48. if (!File.Exists(path)) return;
  49. try
  50. {
  51. var list = TeamAAS.JsonFileStore.Load<List<FeederInfo>>(path);
  52. if (list == null) return;
  53. lock (_sync)
  54. {
  55. _feeders.Clear();
  56. foreach (var info in list)
  57. {
  58. if (!_feeders.ContainsKey(info.Id))
  59. _feeders.Add(info.Id, info);
  60. }
  61. }
  62. FeederListChanged?.Invoke(this, EventArgs.Empty);
  63. }
  64. catch (Exception ex)
  65. {
  66. Trace.WriteLine($"FeederManager.LoadConfig 失败: {ex.Message}");
  67. }
  68. }
  69. public bool SaveConfig(string path = null)
  70. {
  71. path = path ?? DefaultConfigPath;
  72. try
  73. {
  74. List<FeederInfo> list;
  75. lock (_sync) { list = _feeders.Values.ToList(); }
  76. return TeamAAS.JsonFileStore.Save(path, list);
  77. }
  78. catch (Exception ex)
  79. {
  80. Trace.WriteLine($"FeederManager.SaveConfig 失败: {ex.Message}");
  81. return false;
  82. }
  83. }
  84. public FeederInfo Add(FeederInfo info)
  85. {
  86. if (info == null) throw new ArgumentNullException(nameof(info));
  87. lock (_sync)
  88. {
  89. if (_feeders.ContainsKey(info.Id))
  90. _feeders[info.Id] = info;
  91. else
  92. _feeders.Add(info.Id, info);
  93. }
  94. FeederListChanged?.Invoke(this, EventArgs.Empty);
  95. return info;
  96. }
  97. public bool Remove(Guid id)
  98. {
  99. bool removed;
  100. lock (_sync)
  101. {
  102. removed = _feeders.Remove(id);
  103. if (_devices.TryGetValue(id, out var dev))
  104. {
  105. dev.Dispose();
  106. _devices.Remove(id);
  107. }
  108. }
  109. if (removed) FeederListChanged?.Invoke(this, EventArgs.Empty);
  110. return removed;
  111. }
  112. public FeederInfo Get(Guid id)
  113. {
  114. lock (_sync) { return _feeders.TryGetValue(id, out var f) ? f : null; }
  115. }
  116. public IReadOnlyList<FeederInfo> GetAll()
  117. {
  118. lock (_sync) { return _feeders.Values.ToList().AsReadOnly(); }
  119. }
  120. #endregion
  121. #region 设备实例管理
  122. public IFeeder GetDevice(Guid id)
  123. {
  124. lock (_sync) { return _devices.TryGetValue(id, out var d) ? d : null; }
  125. }
  126. public IFeeder GetOrCreateDevice(FeederInfo info)
  127. {
  128. if (info == null) return null;
  129. lock (_sync)
  130. {
  131. if (_devices.TryGetValue(info.Id, out var existing))
  132. {
  133. try { existing.Dispose(); } catch { }
  134. _devices.Remove(info.Id);
  135. }
  136. var device = CreateDeviceInstance(info);
  137. _devices[info.Id] = device;
  138. return device;
  139. }
  140. }
  141. #endregion
  142. #region 配方管理
  143. public IReadOnlyList<FeederRecipe> GetRecipes()
  144. {
  145. lock (_sync) { return _recipes.ToList().AsReadOnly(); }
  146. }
  147. public FeederRecipe GetRecipe(string name)
  148. {
  149. lock (_sync) { return _recipes.FirstOrDefault(r => r.RecipeName == name); }
  150. }
  151. public bool SaveRecipe(FeederRecipe recipe)
  152. {
  153. if (recipe == null || string.IsNullOrWhiteSpace(recipe.RecipeName)) return false;
  154. var ok = SaveRecipeInternal(recipe);
  155. if (ok)
  156. {
  157. lock (_sync)
  158. {
  159. var existing = _recipes.FirstOrDefault(r => r.RecipeName == recipe.RecipeName);
  160. if (existing != null)
  161. _recipes[_recipes.IndexOf(existing)] = recipe;
  162. else
  163. _recipes.Add(recipe);
  164. }
  165. }
  166. return ok;
  167. }
  168. public bool DeleteRecipe(string name)
  169. {
  170. var ok = DeleteRecipeInternal(name);
  171. if (ok)
  172. {
  173. lock (_sync)
  174. {
  175. var r = _recipes.FirstOrDefault(x => x.RecipeName == name);
  176. if (r != null) _recipes.Remove(r);
  177. }
  178. }
  179. return ok;
  180. }
  181. public FeederRecipe LoadRecipe(string path)
  182. {
  183. var recipe = LoadRecipeInternal(path);
  184. if (recipe != null)
  185. {
  186. lock (_sync)
  187. {
  188. var existing = _recipes.FirstOrDefault(r => r.RecipeName == recipe.RecipeName);
  189. if (existing != null)
  190. _recipes[_recipes.IndexOf(existing)] = recipe;
  191. else
  192. _recipes.Add(recipe);
  193. }
  194. }
  195. return recipe;
  196. }
  197. private static List<FeederRecipe> LoadAllRecipesInternal()
  198. {
  199. try
  200. {
  201. if (!File.Exists(DefaultRecipeFilePath)) return new List<FeederRecipe>();
  202. var json = File.ReadAllText(DefaultRecipeFilePath);
  203. var list = JsonConvert.DeserializeObject<List<FeederRecipe>>(json);
  204. return list ?? new List<FeederRecipe>();
  205. }
  206. catch (Exception ex)
  207. {
  208. Trace.WriteLine($"FeederManager.LoadAllRecipes 失败: {ex.Message}");
  209. return new List<FeederRecipe>();
  210. }
  211. }
  212. private static bool SaveAllRecipesInternal(List<FeederRecipe> recipes)
  213. {
  214. try
  215. {
  216. var json = JsonConvert.SerializeObject(recipes, Formatting.Indented);
  217. File.WriteAllText(DefaultRecipeFilePath, json);
  218. return true;
  219. }
  220. catch (Exception ex)
  221. {
  222. Trace.WriteLine($"FeederManager.SaveAllRecipes 失败: {ex.Message}");
  223. return false;
  224. }
  225. }
  226. private static bool SaveRecipeInternal(FeederRecipe recipe)
  227. {
  228. try
  229. {
  230. recipe.UpdatedAt = DateTime.Now;
  231. var list = LoadAllRecipesInternal();
  232. var idx = list.FindIndex(r => r.RecipeName == recipe.RecipeName);
  233. if (idx >= 0) list[idx] = recipe;
  234. else list.Add(recipe);
  235. return SaveAllRecipesInternal(list);
  236. }
  237. catch (Exception ex)
  238. {
  239. Trace.WriteLine($"FeederManager.SaveRecipe 失败: {ex.Message}");
  240. return false;
  241. }
  242. }
  243. private static bool DeleteRecipeInternal(string recipeName)
  244. {
  245. try
  246. {
  247. var list = LoadAllRecipesInternal();
  248. var removed = list.RemoveAll(r => r.RecipeName == recipeName);
  249. if (removed > 0) return SaveAllRecipesInternal(list);
  250. return false;
  251. }
  252. catch (Exception ex)
  253. {
  254. Trace.WriteLine($"FeederManager.DeleteRecipe 失败: {ex.Message}");
  255. return false;
  256. }
  257. }
  258. private static FeederRecipe LoadRecipeInternal(string path)
  259. {
  260. try
  261. {
  262. if (!File.Exists(path)) return null;
  263. var json = File.ReadAllText(path);
  264. return JsonConvert.DeserializeObject<FeederRecipe>(json);
  265. }
  266. catch (Exception ex)
  267. {
  268. Trace.WriteLine($"FeederManager.LoadRecipe 失败: {ex.Message}");
  269. return null;
  270. }
  271. }
  272. #endregion
  273. #region 反射扫描 + 工厂
  274. public IReadOnlyList<FeederTypeInfo> GetAvailableTypes()
  275. {
  276. if (_scannedTypes != null) return _scannedTypes.AsReadOnly();
  277. lock (_scanLock)
  278. {
  279. if (_scannedTypes != null) return _scannedTypes.AsReadOnly();
  280. _scannedTypes = ScanTypes();
  281. return _scannedTypes.AsReadOnly();
  282. }
  283. }
  284. private List<FeederTypeInfo> ScanTypes()
  285. {
  286. var result = new List<FeederTypeInfo>();
  287. // 通用模块扫描:收集全部 IFeeder 实现(含 Runtime\Plugins 里的插件 DLL)
  288. foreach (var type in TeamAAS.Modularity.AssemblyScanner.FindImplementations<IFeeder>())
  289. {
  290. var attrs = type.GetCustomAttributes<FeederAttribute>();
  291. foreach (var attr in attrs)
  292. {
  293. result.Add(new FeederTypeInfo
  294. {
  295. TypeKey = type.FullName,
  296. DisplayName = attr.DisplayName,
  297. Brand = attr.Brand,
  298. Description = attr.Description,
  299. Type = type
  300. });
  301. }
  302. }
  303. // fallback:如果反射没扫到品牌特性,注册内置 TeamFeeder(兼容旧代码)
  304. if (!result.Any(t => t.Brand == FeederBrand.Team))
  305. {
  306. result.Add(new FeederTypeInfo
  307. {
  308. TypeKey = typeof(TeamFeeder).FullName,
  309. DisplayName = "Team 供料器",
  310. Brand = FeederBrand.Team,
  311. Description = "内置 Team 品牌供料器实现",
  312. Type = typeof(TeamFeeder)
  313. });
  314. }
  315. return result
  316. .GroupBy(t => t.TypeKey + "|" + t.Brand)
  317. .Select(g => g.First())
  318. .OrderBy(t => t.DisplayName)
  319. .ToList();
  320. }
  321. private IFeeder CreateDeviceInstance(FeederInfo info)
  322. {
  323. if (info == null) throw new ArgumentNullException(nameof(info));
  324. var types = GetAvailableTypes();
  325. var match = types.FirstOrDefault(t => t.Brand == info.FeederBrand);
  326. if (match == null)
  327. throw new NotSupportedException($"暂不支持的供料器品牌: {info.FeederBrand}");
  328. return (IFeeder)Activator.CreateInstance(
  329. match.Type,
  330. info.Id, info.FeederNo, info.FeederName, info.IP, info.Port);
  331. }
  332. #endregion
  333. }
  334. public class FeederTypeInfo
  335. {
  336. public string TypeKey { get; set; }
  337. public string DisplayName { get; set; }
  338. public FeederBrand Brand { get; set; }
  339. public string Description { get; set; }
  340. public Type Type { get; set; }
  341. public override string ToString() => DisplayName;
  342. }
  343. }