RobotService.cs 16 KB

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