RobotService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Team.FFFeederService;
  7. using Team.FFFeederService.Interfaces;
  8. using TeamAAS_VP.Core.PLCs;
  9. using TeamAAS_VP.Core.Robots;
  10. using TeamAAS_VP.Interfaces;
  11. using TeamAAS_VP.Models;
  12. using TeamAAS_VP.Resources.Languages;
  13. using TouchSocket.Core;
  14. using TouchSocket.Sockets;
  15. namespace TeamAAS_VP.Services
  16. {
  17. public class RobotService : IRobotService, IDisposable
  18. {
  19. private readonly IPlcService _plcService;
  20. private readonly Dictionary<Guid, IRobot> _robotCollection;
  21. private readonly object _sync = new object();
  22. public RobotService(IPlcService plcService)
  23. {
  24. _robotCollection = new Dictionary<Guid, IRobot>();
  25. _plcService = plcService;
  26. }
  27. /// <summary>
  28. /// 创建机器人
  29. /// </summary>
  30. /// <param name="id"></param>
  31. /// <param name="robotInfo"></param>
  32. /// <returns></returns>
  33. /// <exception cref="ArgumentNullException"></exception>
  34. public bool CreateRobot(Guid id, RobotInfo robotInfo)
  35. {
  36. if (robotInfo == null) throw new ArgumentNullException(nameof(robotInfo));
  37. var robot = CreateRobotInstance(robotInfo);
  38. robot.Id = id;
  39. lock (_sync)
  40. {
  41. if (_robotCollection.ContainsKey(id))
  42. {
  43. var currentRobot = _robotCollection[id];
  44. try
  45. {
  46. currentRobot.Dispose();
  47. }
  48. catch
  49. {
  50. // 忽略单个机器人 Dispose 异常,继续替换
  51. }
  52. }
  53. _robotCollection[id] = robot;
  54. }
  55. return true;
  56. }
  57. /// <summary>
  58. /// 创建机器人
  59. /// </summary>
  60. /// <param name="id"></param>
  61. /// <param name="robotInfo"></param>
  62. /// <returns></returns>
  63. public Task<bool> CreateRobotAsync(Guid id, RobotInfo robotInfo)
  64. {
  65. return Task.Run(() =>
  66. {
  67. return CreateRobot(id, robotInfo);
  68. });
  69. }
  70. public IRobot GetRobot(Guid id)
  71. {
  72. lock (_sync)
  73. {
  74. if (_robotCollection.TryGetValue(id, out var robot))
  75. {
  76. return robot;
  77. }
  78. }
  79. return null;
  80. }
  81. public Task<IRobot> GetRobotAsync(Guid id)
  82. {
  83. return Task.Run(() =>
  84. {
  85. return GetRobot(id);
  86. });
  87. }
  88. public void UnRegisterRobot(Guid id)
  89. {
  90. IRobot robot = null;
  91. lock (_sync)
  92. {
  93. if (_robotCollection.TryGetValue(id, out robot))
  94. {
  95. _robotCollection.Remove(id);
  96. }
  97. }
  98. if (robot != null)
  99. {
  100. try
  101. {
  102. robot.Dispose();
  103. }
  104. catch
  105. {
  106. // 忽略释放异常
  107. }
  108. }
  109. }
  110. public Task UnRegisterRobotAsync(Guid id)
  111. {
  112. return Task.Run(()=> UnRegisterRobot(id));
  113. }
  114. /// <summary>
  115. /// 获取所有机器人
  116. /// </summary>
  117. /// <returns></returns>
  118. public IReadOnlyCollection<IRobot> GetAllRobots()
  119. {
  120. lock (_sync)
  121. {
  122. return _robotCollection.Values.ToList().AsReadOnly();
  123. }
  124. }
  125. public Task<IReadOnlyCollection<IRobot>> GetAllRobotsAsync()
  126. {
  127. return Task.Run(() =>
  128. {
  129. return GetAllRobots();
  130. });
  131. }
  132. /// <summary>
  133. /// 尝试获取机器人
  134. /// </summary>
  135. /// <param name="id"></param>
  136. /// <param name="robot"></param>
  137. /// <returns></returns>
  138. public bool TryGetRobot(Guid id, out IRobot robot)
  139. {
  140. lock (_sync)
  141. {
  142. return _robotCollection.TryGetValue(id, out robot);
  143. }
  144. }
  145. public Task<(bool found, IRobot robot)> TryGetRobotAsync(Guid id)
  146. {
  147. return Task.Run(() =>
  148. {
  149. IRobot robot;
  150. bool found;
  151. lock (_sync)
  152. {
  153. found = _robotCollection.TryGetValue(id, out robot);
  154. }
  155. return (found, robot);
  156. });
  157. }
  158. /// <summary>
  159. /// 检查是否存在
  160. /// </summary>
  161. /// <param name="id"></param>
  162. /// <returns></returns>
  163. public bool ContainsRobot(Guid id)
  164. {
  165. lock (_sync)
  166. {
  167. return _robotCollection.ContainsKey(id);
  168. }
  169. }
  170. public Task<bool> ContainsRobotAsync(Guid id)
  171. {
  172. return Task.Run(() =>
  173. {
  174. return ContainsRobot(id);
  175. });
  176. }
  177. /// <summary>
  178. /// 移除机器人并释放资源,返回是否成功移除
  179. /// </summary>
  180. /// <param name="id"></param>
  181. /// <returns></returns>
  182. public bool RemoveRobot(Guid id)
  183. {
  184. IRobot robot = null;
  185. lock (_sync)
  186. {
  187. if (_robotCollection.TryGetValue(id, out robot))
  188. {
  189. _robotCollection.Remove(id);
  190. }
  191. }
  192. if (robot != null)
  193. {
  194. try
  195. {
  196. robot.Dispose();
  197. }
  198. catch
  199. {
  200. // 忽略释放异常
  201. }
  202. return true;
  203. }
  204. return false;
  205. }
  206. public Task<bool> RemoveRobotAsync(Guid id)
  207. {
  208. return Task.Run(() =>
  209. {
  210. return RemoveRobot(id);
  211. });
  212. }
  213. public IRobot GetRobotByNumber(int robotNo)
  214. {
  215. if (TryFindRobotByNumber(robotNo, out _, out var robot))
  216. {
  217. return robot;
  218. }
  219. return null;
  220. }
  221. public Task<IRobot> GetRobotByNumberAsync(int robotNo)
  222. {
  223. return Task.Run(() =>
  224. {
  225. return GetRobotByNumber(robotNo);
  226. });
  227. }
  228. public Task UnRegisterRobotByNumberAsync(int robotNo)
  229. {
  230. return Task.Run(() => UnRegisterRobotByNumber(robotNo));
  231. }
  232. public void UnRegisterRobotByNumber(int robotNo)
  233. {
  234. if (TryFindRobotByNumber(robotNo, out var id, out var robot))
  235. {
  236. // 复用已有的方法以保持行为一致(线程安全、异常处理)
  237. UnRegisterRobot(id);
  238. }
  239. }
  240. /// <summary>
  241. /// 移除所有机器人
  242. /// </summary>
  243. public void RemoveAllRobots()
  244. {
  245. //依次移除每个机器人,确保资源释放
  246. List<Guid> robotIds;
  247. lock (_sync)
  248. {
  249. robotIds = _robotCollection.Keys.ToList();
  250. }
  251. foreach (var id in robotIds)
  252. {
  253. RemoveRobot(id);
  254. }
  255. }
  256. /// <summary>
  257. /// 初始化所有机器人
  258. /// </summary>
  259. /// <param name="robots"></param>
  260. /// <returns></returns>
  261. public (bool IsSucceed, string Message) InitializeAllRobots(RobotInfo[] robots)
  262. {
  263. //清除现有机器人集合
  264. RemoveAllRobots();
  265. //根据传入的机器人信息数组,依次创建并注册机器人实例
  266. foreach (var robotInfo in robots)
  267. {
  268. var robot = CreateRobotInstance(robotInfo);
  269. lock (_sync)
  270. {
  271. _robotCollection[robot.Id] = robot;
  272. }
  273. }
  274. bool allConnected = true;
  275. StringBuilder errorMessages = new StringBuilder();
  276. //获取所有机器人并连接
  277. var allRobots = GetAllRobots();
  278. foreach (var robot in allRobots)
  279. {
  280. try
  281. {
  282. robot.Connect();
  283. }
  284. catch
  285. {
  286. //忽略单个机器人连接异常,继续连接其他机器人
  287. }
  288. if (!robot.IsConnected)
  289. {
  290. allConnected = false;
  291. errorMessages.AppendLine(string.Format(Lang.机器人0连接失败, robot.Name));
  292. // "机器人[{robot.Name}]连接失败。");
  293. }
  294. }
  295. if (allConnected)
  296. {
  297. return (true, Lang.所有机器人初始化并连接成功);
  298. }
  299. else
  300. {
  301. return (false, errorMessages.ToString());
  302. }
  303. }
  304. /// <summary>
  305. /// 初始化所有机器人 (异步)
  306. /// </summary>
  307. /// <param name="robots"></param>
  308. /// <returns></returns>
  309. public Task<(bool IsSucceed, string Message)> InitializeAllRobotsAsync(RobotInfo[] robots)
  310. {
  311. return Task.Run(() =>
  312. {
  313. return InitializeAllRobots(robots);
  314. });
  315. }
  316. // 私有工厂方法,避免重复代码
  317. private IRobot CreateRobotInstance(RobotInfo robotInfo)
  318. {
  319. if (robotInfo == null) throw new ArgumentNullException(nameof(robotInfo));
  320. IRobot robot;
  321. if (robotInfo.RobotBrand == Enums.RobotBrand.EPSON)
  322. {
  323. robot = new EpsonRobot(robotInfo);
  324. }
  325. else if (robotInfo.RobotBrand == Enums.RobotBrand.FANUC)
  326. {
  327. robot = new FanucRobot(robotInfo);
  328. }
  329. else if (robotInfo.RobotBrand == Enums.RobotBrand.Schneider)
  330. {
  331. robot = new SchneiderRobot(robotInfo);
  332. }
  333. else if (robotInfo.RobotBrand == Enums.RobotBrand.XYZ_Platform || robotInfo.RobotBrand == Enums.RobotBrand.XYZU_Platform)
  334. {
  335. var plc= _plcService.GetPlc(robotInfo.PLC) as OpcUaClientPLC;
  336. if (robotInfo.PlcRobotParameter == null)
  337. robotInfo.PlcRobotParameter = new Models.PLC.PlcRobotParameter();
  338. if (robotInfo.PlcRobotParameter.AxixList == null)
  339. {
  340. robotInfo.PlcRobotParameter.AxixList = new List<Axis>();
  341. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index=1,Name="X", Command=new AxisCommand(),Parameter=new AxisParameter(),State=new AxisState()});
  342. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index = 2, Name = "Y", Command = new AxisCommand(), Parameter = new AxisParameter(), State = new AxisState() });
  343. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index = 3, Name = "Z", Command = new AxisCommand(), Parameter = new AxisParameter(), State = new AxisState() });
  344. }
  345. robot = new XYZU_Robot(robotInfo, plc);
  346. }
  347. else if (robotInfo.RobotBrand == Enums.RobotBrand.XYZUR_Platform )
  348. {
  349. var plc = _plcService.GetPlc(robotInfo.PLC) as OpcUaClientPLC;
  350. if (robotInfo.PlcRobotParameter == null)
  351. robotInfo.PlcRobotParameter = new Models.PLC.PlcRobotParameter();
  352. if (robotInfo.PlcRobotParameter.AxixList == null)
  353. {
  354. robotInfo.PlcRobotParameter.AxixList = new List<Axis>();
  355. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index = 1, Name = "X", Command = new AxisCommand(), Parameter = new AxisParameter(), State = new AxisState() });
  356. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index = 2, Name = "Y", Command = new AxisCommand(), Parameter = new AxisParameter(), State = new AxisState() });
  357. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index = 3, Name = "Z", Command = new AxisCommand(), Parameter = new AxisParameter(), State = new AxisState() });
  358. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index = 4, Name = "U", Command = new AxisCommand(), Parameter = new AxisParameter(), State = new AxisState() });
  359. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index = 5, Name = "R", Command = new AxisCommand(), Parameter = new AxisParameter(), State = new AxisState() });
  360. }
  361. robot = new XYZUR_Platform(robotInfo, plc);
  362. }
  363. else if (robotInfo.RobotBrand == Enums.RobotBrand.XYZURWV_Platform)
  364. {
  365. var plc = _plcService.GetPlc(robotInfo.PLC) as OpcUaClientPLC;
  366. if (robotInfo.PlcRobotParameter == null)
  367. robotInfo.PlcRobotParameter = new Models.PLC.PlcRobotParameter();
  368. if (robotInfo.PlcRobotParameter.AxixList == null)
  369. {
  370. robotInfo.PlcRobotParameter.AxixList = new List<Axis>();
  371. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index = 1, Name = "X", Command = new AxisCommand(), Parameter = new AxisParameter(), State = new AxisState() });
  372. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index = 2, Name = "Y", Command = new AxisCommand(), Parameter = new AxisParameter(), State = new AxisState() });
  373. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index = 3, Name = "Z", Command = new AxisCommand(), Parameter = new AxisParameter(), State = new AxisState() });
  374. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index = 4, Name = "U", Command = new AxisCommand(), Parameter = new AxisParameter(), State = new AxisState() });
  375. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index = 5, Name = "R", Command = new AxisCommand(), Parameter = new AxisParameter(), State = new AxisState() });
  376. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index = 6, Name = "W", Command = new AxisCommand(), Parameter = new AxisParameter(), State = new AxisState() });
  377. robotInfo.PlcRobotParameter.AxixList.Add(new Axis() { Index = 7, Name = "V", Command = new AxisCommand(), Parameter = new AxisParameter(), State = new AxisState() });
  378. }
  379. robot = new XYZURWV_Platform(robotInfo, plc);
  380. }
  381. else
  382. {
  383. robot = new EpsonRobot(robotInfo);
  384. }
  385. return robot;
  386. }
  387. /// <summary>
  388. /// 更新机器人编号
  389. /// </summary>
  390. /// <param name="id"></param>
  391. /// <param name="newNumber"></param>
  392. public void UpdateRobotNumber(Guid id, int newNumber)
  393. {
  394. IRobot robot;
  395. lock (_sync)
  396. {
  397. if (_robotCollection.TryGetValue(id, out robot))
  398. {
  399. robot.RobotNo = newNumber;
  400. }
  401. }
  402. }
  403. // 私有帮助方法:通过机器人编号查找字典中的条目(线程安全)
  404. private bool TryFindRobotByNumber(int robotNo, out Guid id, out IRobot robot)
  405. {
  406. lock (_sync)
  407. {
  408. foreach (var kvp in _robotCollection)
  409. {
  410. var r = kvp.Value;
  411. if (r == null) continue;
  412. object rawValue = null;
  413. var type = r.GetType();
  414. // 1. 直接在机器人对象上查找常见编号属性
  415. var prop = type.GetProperty("RobotNo") ??
  416. type.GetProperty("RobotNumber") ??
  417. type.GetProperty("Number") ??
  418. type.GetProperty("No");
  419. if (prop != null)
  420. {
  421. try
  422. {
  423. rawValue = prop.GetValue(r);
  424. }
  425. catch
  426. {
  427. rawValue = null;
  428. }
  429. }
  430. // 2. 如果未找到,尝试从 RobotInfo / Info 属性中获取编号
  431. if (rawValue == null)
  432. {
  433. var infoProp = type.GetProperty("RobotInfo") ?? type.GetProperty("Info");
  434. if (infoProp != null)
  435. {
  436. try
  437. {
  438. var infoObj = infoProp.GetValue(r);
  439. if (infoObj != null)
  440. {
  441. var infoType = infoObj.GetType();
  442. var numberProp = infoType.GetProperty("RobotNo") ??
  443. infoType.GetProperty("RobotNumber") ??
  444. infoType.GetProperty("Number") ??
  445. infoType.GetProperty("No");
  446. if (numberProp != null)
  447. {
  448. try
  449. {
  450. rawValue = numberProp.GetValue(infoObj);
  451. }
  452. catch
  453. {
  454. rawValue = null;
  455. }
  456. }
  457. }
  458. }
  459. catch
  460. {
  461. // 忽略反射读取错误
  462. rawValue = null;
  463. }
  464. }
  465. }
  466. if (rawValue != null)
  467. {
  468. int parsed;
  469. try
  470. {
  471. if (rawValue is int) parsed = (int)rawValue;
  472. else parsed = Convert.ToInt32(rawValue);
  473. }
  474. catch
  475. {
  476. // 不能转换则跳过
  477. continue;
  478. }
  479. if (parsed == robotNo)
  480. {
  481. id = kvp.Key;
  482. robot = r;
  483. return true;
  484. }
  485. }
  486. }
  487. }
  488. id = Guid.Empty;
  489. robot = null;
  490. return false;
  491. }
  492. // 实现 IDisposable,释放所有机器人并清空集合
  493. public void Dispose()
  494. {
  495. List<IRobot> robots;
  496. lock (_sync)
  497. {
  498. robots = _robotCollection.Values.ToList();
  499. _robotCollection.Clear();
  500. }
  501. foreach (var r in robots)
  502. {
  503. try
  504. {
  505. r.Dispose();
  506. }
  507. catch
  508. {
  509. // 忽略单个释放异常
  510. }
  511. }
  512. GC.SuppressFinalize(this);
  513. }
  514. }
  515. }