RobotService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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
  348. {
  349. robot = new EpsonRobot(robotInfo);
  350. }
  351. return robot;
  352. }
  353. /// <summary>
  354. /// 更新机器人编号
  355. /// </summary>
  356. /// <param name="id"></param>
  357. /// <param name="newNumber"></param>
  358. public void UpdateRobotNumber(Guid id, int newNumber)
  359. {
  360. IRobot robot;
  361. lock (_sync)
  362. {
  363. if (_robotCollection.TryGetValue(id, out robot))
  364. {
  365. robot.RobotNo = newNumber;
  366. }
  367. }
  368. }
  369. // 私有帮助方法:通过机器人编号查找字典中的条目(线程安全)
  370. private bool TryFindRobotByNumber(int robotNo, out Guid id, out IRobot robot)
  371. {
  372. lock (_sync)
  373. {
  374. foreach (var kvp in _robotCollection)
  375. {
  376. var r = kvp.Value;
  377. if (r == null) continue;
  378. object rawValue = null;
  379. var type = r.GetType();
  380. // 1. 直接在机器人对象上查找常见编号属性
  381. var prop = type.GetProperty("RobotNo") ??
  382. type.GetProperty("RobotNumber") ??
  383. type.GetProperty("Number") ??
  384. type.GetProperty("No");
  385. if (prop != null)
  386. {
  387. try
  388. {
  389. rawValue = prop.GetValue(r);
  390. }
  391. catch
  392. {
  393. rawValue = null;
  394. }
  395. }
  396. // 2. 如果未找到,尝试从 RobotInfo / Info 属性中获取编号
  397. if (rawValue == null)
  398. {
  399. var infoProp = type.GetProperty("RobotInfo") ?? type.GetProperty("Info");
  400. if (infoProp != null)
  401. {
  402. try
  403. {
  404. var infoObj = infoProp.GetValue(r);
  405. if (infoObj != null)
  406. {
  407. var infoType = infoObj.GetType();
  408. var numberProp = infoType.GetProperty("RobotNo") ??
  409. infoType.GetProperty("RobotNumber") ??
  410. infoType.GetProperty("Number") ??
  411. infoType.GetProperty("No");
  412. if (numberProp != null)
  413. {
  414. try
  415. {
  416. rawValue = numberProp.GetValue(infoObj);
  417. }
  418. catch
  419. {
  420. rawValue = null;
  421. }
  422. }
  423. }
  424. }
  425. catch
  426. {
  427. // 忽略反射读取错误
  428. rawValue = null;
  429. }
  430. }
  431. }
  432. if (rawValue != null)
  433. {
  434. int parsed;
  435. try
  436. {
  437. if (rawValue is int) parsed = (int)rawValue;
  438. else parsed = Convert.ToInt32(rawValue);
  439. }
  440. catch
  441. {
  442. // 不能转换则跳过
  443. continue;
  444. }
  445. if (parsed == robotNo)
  446. {
  447. id = kvp.Key;
  448. robot = r;
  449. return true;
  450. }
  451. }
  452. }
  453. }
  454. id = Guid.Empty;
  455. robot = null;
  456. return false;
  457. }
  458. // 实现 IDisposable,释放所有机器人并清空集合
  459. public void Dispose()
  460. {
  461. List<IRobot> robots;
  462. lock (_sync)
  463. {
  464. robots = _robotCollection.Values.ToList();
  465. _robotCollection.Clear();
  466. }
  467. foreach (var r in robots)
  468. {
  469. try
  470. {
  471. r.Dispose();
  472. }
  473. catch
  474. {
  475. // 忽略单个释放异常
  476. }
  477. }
  478. GC.SuppressFinalize(this);
  479. }
  480. }
  481. }