RobotManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using TeamAAS.Robot.Core.Robots;
  8. using TeamAAS.Robot.Interfaces;
  9. using TeamAAS.Robot.Models;
  10. using System.Reflection;
  11. using TeamAAS.Robot.Attributes;
  12. using TeamAAS.Robot.Enums;
  13. namespace TeamAAS.Robot
  14. {
  15. /// <summary>
  16. /// 机器人生命周期管理器。懒汉单例:<c>RobotManager.Instance</c>。
  17. /// 整合:设备创建/连接/运动/配置持久化 + 反射发现品牌类型 + IDisposable。
  18. /// 管理类按架构规则保留在根命名空间 TeamAAS.Robot。
  19. /// </summary>
  20. public class RobotManager : IRobotManager, IDisposable
  21. {
  22. #region 单例
  23. private static readonly Lazy<RobotManager> _instance =
  24. new Lazy<RobotManager>(() => new RobotManager(), isThreadSafe: true);
  25. /// <summary>
  26. /// 懒汉单例入口。首次访问时初始化,线程安全。
  27. /// </summary>
  28. public static RobotManager Instance => _instance.Value;
  29. #endregion
  30. private readonly Dictionary<Guid, IRobot> _robotCollection;
  31. private readonly object _sync = new object();
  32. private List<RobotTypeInfo> _scannedTypes;
  33. private readonly object _scanLock = new object();
  34. public RobotManager()
  35. {
  36. _robotCollection = new Dictionary<Guid, IRobot>();
  37. }
  38. #region 机器人 CRUD
  39. public bool CreateRobot(Guid id, RobotInfo robotInfo)
  40. {
  41. if (robotInfo == null) throw new ArgumentNullException(nameof(robotInfo));
  42. var robot = CreateRobotInstance(robotInfo);
  43. robot.Id = id;
  44. IRobot replaced = null;
  45. lock (_sync)
  46. {
  47. _robotCollection.TryGetValue(id, out replaced);
  48. _robotCollection[id] = robot;
  49. }
  50. if (replaced != null && !ReferenceEquals(replaced, robot))
  51. {
  52. try { replaced.Dispose(); } catch { }
  53. }
  54. return true;
  55. }
  56. public Task<bool> CreateRobotAsync(Guid id, RobotInfo robotInfo)
  57. {
  58. return Task.Run(() => CreateRobot(id, robotInfo));
  59. }
  60. public IRobot GetRobot(Guid id)
  61. {
  62. lock (_sync)
  63. {
  64. return _robotCollection.TryGetValue(id, out var robot) ? robot : null;
  65. }
  66. }
  67. public Task<IRobot> GetRobotAsync(Guid id)
  68. {
  69. return Task.Run(() => GetRobot(id));
  70. }
  71. public void UnRegisterRobot(Guid id)
  72. {
  73. IRobot robot = null;
  74. lock (_sync)
  75. {
  76. if (_robotCollection.TryGetValue(id, out robot))
  77. _robotCollection.Remove(id);
  78. }
  79. if (robot != null)
  80. {
  81. try { robot.Dispose(); } catch { }
  82. }
  83. }
  84. public Task UnRegisterRobotAsync(Guid id)
  85. {
  86. return Task.Run(() => UnRegisterRobot(id));
  87. }
  88. public IReadOnlyCollection<IRobot> GetAllRobots()
  89. {
  90. lock (_sync)
  91. {
  92. return _robotCollection.Values.ToList().AsReadOnly();
  93. }
  94. }
  95. public Task<IReadOnlyCollection<IRobot>> GetAllRobotsAsync()
  96. {
  97. return Task.Run(() => GetAllRobots());
  98. }
  99. public bool TryGetRobot(Guid id, out IRobot robot)
  100. {
  101. lock (_sync)
  102. {
  103. return _robotCollection.TryGetValue(id, out robot);
  104. }
  105. }
  106. public Task<(bool found, IRobot robot)> TryGetRobotAsync(Guid id)
  107. {
  108. return Task.Run(() =>
  109. {
  110. IRobot robot;
  111. bool found;
  112. lock (_sync)
  113. {
  114. found = _robotCollection.TryGetValue(id, out robot);
  115. }
  116. return (found, robot);
  117. });
  118. }
  119. public System.Collections.Generic.IReadOnlyList<IRobot> Devices
  120. {
  121. get
  122. {
  123. lock (_sync)
  124. {
  125. return _robotCollection.Values.ToList().AsReadOnly();
  126. }
  127. }
  128. }
  129. public bool ContainsRobot(Guid id)
  130. {
  131. lock (_sync)
  132. {
  133. return _robotCollection.ContainsKey(id);
  134. }
  135. }
  136. public Task<bool> ContainsRobotAsync(Guid id)
  137. {
  138. return Task.Run(() => ContainsRobot(id));
  139. }
  140. public bool RemoveRobot(Guid id)
  141. {
  142. IRobot robot = null;
  143. lock (_sync)
  144. {
  145. if (_robotCollection.TryGetValue(id, out robot))
  146. _robotCollection.Remove(id);
  147. }
  148. if (robot != null)
  149. {
  150. try { robot.Dispose(); } catch { }
  151. return true;
  152. }
  153. return false;
  154. }
  155. public Task<bool> RemoveRobotAsync(Guid id)
  156. {
  157. return Task.Run(() => RemoveRobot(id));
  158. }
  159. public IRobot GetRobotByNumber(int robotNo)
  160. {
  161. return TryFindRobotByNumber(robotNo, out _, out var robot) ? robot : null;
  162. }
  163. public Task<IRobot> GetRobotByNumberAsync(int robotNo)
  164. {
  165. return Task.Run(() => GetRobotByNumber(robotNo));
  166. }
  167. public Task UnRegisterRobotByNumberAsync(int robotNo)
  168. {
  169. return Task.Run(() => UnRegisterRobotByNumber(robotNo));
  170. }
  171. public void UnRegisterRobotByNumber(int robotNo)
  172. {
  173. if (TryFindRobotByNumber(robotNo, out var id, out _))
  174. UnRegisterRobot(id);
  175. }
  176. public void RemoveAllRobots()
  177. {
  178. List<Guid> robotIds;
  179. lock (_sync)
  180. {
  181. robotIds = _robotCollection.Keys.ToList();
  182. }
  183. foreach (var id in robotIds)
  184. {
  185. RemoveRobot(id);
  186. }
  187. }
  188. public (bool IsSucceed, string Message) InitializeAllRobots(RobotInfo[] robots)
  189. {
  190. RemoveAllRobots();
  191. foreach (var robotInfo in robots)
  192. {
  193. var robot = CreateRobotInstance(robotInfo);
  194. lock (_sync)
  195. {
  196. _robotCollection[robot.Id] = robot;
  197. }
  198. }
  199. bool allConnected = true;
  200. StringBuilder errorMessages = new StringBuilder();
  201. var allRobots = GetAllRobots();
  202. foreach (var robot in allRobots)
  203. {
  204. try { robot.Connect(); } catch { }
  205. if (!robot.IsConnected)
  206. {
  207. allConnected = false;
  208. errorMessages.AppendLine($"机器人[{robot.Name}]连接失败。");
  209. }
  210. }
  211. return allConnected ? (true, "所有机器人初始化并连接成功。") : (false, errorMessages.ToString());
  212. }
  213. public Task<(bool IsSucceed, string Message)> InitializeAllRobotsAsync(RobotInfo[] robots)
  214. {
  215. return Task.Run(() => InitializeAllRobots(robots));
  216. }
  217. public void UpdateRobotNumber(Guid id, int newNumber)
  218. {
  219. lock (_sync)
  220. {
  221. if (_robotCollection.TryGetValue(id, out var robot))
  222. robot.RobotNo = newNumber;
  223. }
  224. }
  225. private bool TryFindRobotByNumber(int robotNo, out Guid id, out IRobot robot)
  226. {
  227. lock (_sync)
  228. {
  229. foreach (var kvp in _robotCollection)
  230. {
  231. if (kvp.Value == null) continue;
  232. if (kvp.Value.RobotNo == robotNo)
  233. {
  234. id = kvp.Key;
  235. robot = kvp.Value;
  236. return true;
  237. }
  238. }
  239. }
  240. id = Guid.Empty;
  241. robot = null;
  242. return false;
  243. }
  244. #endregion
  245. #region 配置持久化
  246. public static string DefaultConfigPath
  247. {
  248. get
  249. {
  250. return Path.Combine(TeamAAS.PathHelper.ConfigDirectory, "Robots.json");
  251. }
  252. }
  253. public bool SaveConfig(string path = null)
  254. {
  255. path = path ?? DefaultConfigPath;
  256. var infos = new List<RobotInfo>();
  257. lock (_sync)
  258. {
  259. foreach (var robot in _robotCollection.Values)
  260. {
  261. infos.Add(new RobotInfo
  262. {
  263. Id = robot.Id,
  264. RobotNo = robot.RobotNo,
  265. RobotName = robot.Name,
  266. RobotBrand = robot.Brand,
  267. IP = robot.RobotIp,
  268. Port = robot.RobotPort,
  269. ConnectType = robot.ConnectType,
  270. Terminator = robot.Terminator,
  271. DataEncoding = robot.DataEncoding,
  272. });
  273. }
  274. }
  275. return TeamAAS.JsonFileStore.Save(path, infos);
  276. }
  277. public IReadOnlyList<RobotInfo> GetAllRobotInfos()
  278. {
  279. var infos = new List<RobotInfo>();
  280. lock (_sync)
  281. {
  282. foreach (var robot in _robotCollection.Values)
  283. {
  284. infos.Add(new RobotInfo
  285. {
  286. Id = robot.Id,
  287. RobotNo = robot.RobotNo,
  288. RobotName = robot.Name,
  289. RobotBrand = robot.Brand,
  290. IP = robot.RobotIp,
  291. Port = robot.RobotPort,
  292. ConnectType = robot.ConnectType,
  293. Terminator = robot.Terminator,
  294. DataEncoding = robot.DataEncoding,
  295. });
  296. }
  297. }
  298. return infos.AsReadOnly();
  299. }
  300. public void LoadConfig(string path = null)
  301. {
  302. path = path ?? DefaultConfigPath;
  303. if (!File.Exists(path)) return;
  304. var infos = TeamAAS.JsonFileStore.Load<List<RobotInfo>>(path);
  305. if (infos == null || infos.Count == 0) return;
  306. InitializeAllRobots(infos.ToArray());
  307. }
  308. #endregion
  309. #region 反射扫描 + 工厂
  310. public IReadOnlyList<RobotTypeInfo> GetAvailableTypes()
  311. {
  312. if (_scannedTypes != null) return _scannedTypes.AsReadOnly();
  313. lock (_scanLock)
  314. {
  315. if (_scannedTypes != null) return _scannedTypes.AsReadOnly();
  316. _scannedTypes = ScanTypes();
  317. return _scannedTypes.AsReadOnly();
  318. }
  319. }
  320. private List<RobotTypeInfo> ScanTypes()
  321. {
  322. var result = new List<RobotTypeInfo>();
  323. // 通用模块扫描:收集全部 IRobot 实现(含 Runtime\Plugins 里的插件 DLL)
  324. foreach (var type in TeamAAS.Modularity.AssemblyScanner.FindImplementations<IRobot>())
  325. {
  326. var attrs = type.GetCustomAttributes<RobotAttribute>();
  327. foreach (var attr in attrs)
  328. {
  329. result.Add(new RobotTypeInfo
  330. {
  331. TypeKey = type.FullName,
  332. DisplayName = attr.DisplayName,
  333. Brand = attr.Brand,
  334. Description = attr.Description,
  335. Type = type
  336. });
  337. }
  338. }
  339. return result
  340. .GroupBy(t => t.TypeKey + "|" + t.Brand)
  341. .Select(g => g.First())
  342. .OrderBy(t => t.DisplayName)
  343. .ToList();
  344. }
  345. private IRobot CreateRobotInstance(RobotInfo robotInfo)
  346. {
  347. if (robotInfo == null) throw new ArgumentNullException(nameof(robotInfo));
  348. var types = GetAvailableTypes();
  349. var match = types.FirstOrDefault(t => t.Brand == robotInfo.RobotBrand);
  350. if (match == null)
  351. {
  352. // fallback 到 EPSON 实现(兼容未注册的品牌占位)
  353. return new EpsonRobot(robotInfo);
  354. }
  355. return (IRobot)Activator.CreateInstance(match.Type, robotInfo);
  356. }
  357. #endregion
  358. #region IDisposable
  359. public void Dispose()
  360. {
  361. List<IRobot> robots;
  362. lock (_sync)
  363. {
  364. robots = _robotCollection.Values.ToList();
  365. _robotCollection.Clear();
  366. }
  367. foreach (var r in robots)
  368. {
  369. try { r.Dispose(); } catch { }
  370. }
  371. GC.SuppressFinalize(this);
  372. }
  373. #endregion
  374. }
  375. }