XYZU_Robot.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. using MahApps.Metro.Controls;
  2. using Opc.Ua;
  3. using Prism;
  4. using Prism.Ioc;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.Diagnostics;
  9. using System.Linq;
  10. using System.Runtime.CompilerServices;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using TeamAAS_VP.Core.PLCs;
  15. using TeamAAS_VP.Enums;
  16. using TeamAAS_VP.Interfaces;
  17. using TeamAAS_VP.Models;
  18. using TouchSocket.Core;
  19. using TouchSocket.Sockets;
  20. using static System.Windows.Forms.AxHost;
  21. namespace TeamAAS_VP.Core.Robots
  22. {
  23. /// <summary>
  24. /// Generic multi-axis robot that composes axis objects and uses PLC nodes configured in RobotInfo.PlcRobotParameter
  25. /// to perform coordinated moves (Go/Move/CalibMotion) for 3 or 4 axes.
  26. /// This implementation maps X/Y/Z/(U) axes by name and writes their position nodes then triggers ExecuteMove node.
  27. /// </summary>
  28. public class XYZU_Robot : IRobot, INotifyPropertyChanged
  29. {
  30. public event Action<Guid, object, ConnectedEventArgs> ConnectedEvent;
  31. public event Action<Guid, object, ClosedEventArgs> DisconnectedEvent;
  32. public event Action<Guid, object, ReceivedDataEventArgs> ReceivedEvent;
  33. public event Action<Guid, object, string> SendEvent;
  34. public XYZU_Robot(RobotInfo robot, OpcUaClientPLC pLC)
  35. {
  36. RobotInfo = robot;
  37. Name = robot.RobotName;
  38. Id = robot.Id;
  39. RobotNo = robot.RobotNo;
  40. RobotIp = robot.IP;
  41. RobotPort = robot.Port;
  42. ConnectType = robot.ConnectType;
  43. Terminator = robot.Terminator;
  44. DataEncoding = robot.DataEncoding;
  45. Brand = RobotBrand.XYZ_Platform;
  46. Plc = pLC;
  47. Plc.ConnectChangedEvent += Plc_ConnectChangedEvent;
  48. // build axis list from known RobotInfo.PlcRobotParameter nodes (best-effort)
  49. Axes = new List<Axis>();
  50. // X
  51. var ax = new Axis();
  52. ax.Name = "X";
  53. ax.Index = 1;
  54. ax.Command = robot.PlcRobotParameter.AxixList[0].Command;
  55. ax.Parameter = robot.PlcRobotParameter.AxixList[0].Parameter;
  56. ax.State = robot.PlcRobotParameter.AxixList[0].State;
  57. Axes.Add(ax);
  58. // Y
  59. var ay = new Axis();
  60. ay.Name = "Y";
  61. ay.Index = 2;
  62. ay.Command = robot.PlcRobotParameter.AxixList[1].Command;
  63. ay.Parameter = robot.PlcRobotParameter.AxixList[1].Parameter;
  64. ay.State = robot.PlcRobotParameter.AxixList[1].State;
  65. Axes.Add(ay);
  66. // Z
  67. var az = new Axis();
  68. az.Name = "Z";
  69. az.Index = 3;
  70. az.Command = robot.PlcRobotParameter.AxixList[2].Command;
  71. az.Parameter = robot.PlcRobotParameter.AxixList[2].Parameter;
  72. az.State = robot.PlcRobotParameter.AxixList[2].State;
  73. Axes.Add(az);
  74. // U optional
  75. if (robot.PlcRobotParameter.AxixList.Count >= 4)
  76. {
  77. var au = new Axis();
  78. au.Name = "U";
  79. au.Index = 4;
  80. au.Command = robot.PlcRobotParameter.AxixList[3].Command;
  81. au.Parameter = robot.PlcRobotParameter.AxixList[3].Parameter;
  82. au.State = robot.PlcRobotParameter.AxixList[3].State;
  83. Axes.Add(au);
  84. Brand = RobotBrand.XYZU_Platform;
  85. }
  86. }
  87. private void Plc_ConnectChangedEvent(object arg1, bool arg2)
  88. {
  89. CanExecute = arg2;
  90. }
  91. #region 属性
  92. public TcpClient TcpClient { get; private set; }
  93. public TcpService TcpService { get; private set; }
  94. public Guid Id { get; set; }
  95. public string Name { get; set; }
  96. /// <summary>
  97. /// 机器人编号
  98. /// </summary>
  99. public int RobotNo { get; set; }
  100. public int RobotPort { get; private set; }
  101. public string RobotIp { get; private set; }
  102. public TCPConnectType ConnectType { get; private set; }
  103. public Terminator Terminator { get; private set; }
  104. public DataEncoding DataEncoding { get; private set; }
  105. public bool IsConnected
  106. {
  107. get
  108. {
  109. if (Plc != null)
  110. {
  111. return Plc.IsConnected;
  112. }
  113. else
  114. {
  115. return false;
  116. }
  117. }
  118. }
  119. public int Timeout { get; set; } = 120000;
  120. private bool _CanExecute = true;
  121. public bool CanExecute
  122. {
  123. get { return _CanExecute; }
  124. set { SetProperty(ref _CanExecute, value); }
  125. }
  126. public int SelectedTool { get; private set; } = 0;
  127. public RobotBrand Brand { get; private set; }
  128. public OpcUaClientPLC Plc { get; private set; }
  129. public RobotInfo RobotInfo { get; private set; }
  130. public List<Axis> Axes { get; private set; }
  131. /// <summary>
  132. /// 进入调试模式
  133. /// </summary>
  134. /// <returns></returns>
  135. public bool EnterDebugMode { get; set; }
  136. #endregion
  137. #region 连接
  138. public void Connect()
  139. {
  140. }
  141. public Task ConnectAsync()
  142. {
  143. return Task.CompletedTask;
  144. }
  145. public void Disconnect()
  146. {
  147. }
  148. public void Dispose()
  149. {
  150. }
  151. #endregion
  152. #region 控制
  153. public bool Reset() => true;
  154. public Task<bool> ResetAsync() { return Task.Run(() => Reset()); }
  155. public bool Motor(bool state)
  156. {
  157. //遍历所有轴,设置电机状态
  158. //获取所有轴的Poer节点,组成一个集合,一次性写入
  159. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  160. foreach (var axis in Axes)
  161. {
  162. if (!string.IsNullOrWhiteSpace(axis.Command.PowerNode))
  163. {
  164. nodesToWrite[axis.Command.PowerNode] = state;
  165. }
  166. }
  167. if (Plc == null || !Plc.IsConnected) return false;
  168. return Plc.WriteNodes(nodesToWrite);
  169. }
  170. public async Task<bool> MotorAsync(bool state)
  171. {
  172. //遍历所有轴,设置电机状态
  173. //获取所有轴的Poer节点,组成一个集合,一次性写入
  174. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  175. foreach (var axis in Axes)
  176. {
  177. if (!string.IsNullOrWhiteSpace(axis.Command.PowerNode))
  178. {
  179. nodesToWrite[axis.Command.PowerNode] = state;
  180. }
  181. }
  182. if (Plc == null || !Plc.IsConnected) return false;
  183. return await Plc.WriteNodesAsync(nodesToWrite);
  184. }
  185. public bool Power(bool state) => true;
  186. public Task<bool> PowerAsync(bool state) => Task.FromResult(true);
  187. public bool Speed(int value)
  188. {
  189. return true;
  190. }
  191. public Task<bool> SpeedAsync(int value) => Task.FromResult(true);
  192. public bool Speedfactor(int value) => true;
  193. public Task<bool> SpeedfactorAsync(int value) => Task.FromResult(true);
  194. public bool Speeds(double value)
  195. {
  196. //遍历所有轴,设置电机状态
  197. //获取所有轴的Poer节点,组成一个集合,一次性写入
  198. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  199. foreach (var axis in Axes)
  200. {
  201. if (!string.IsNullOrWhiteSpace(axis.Parameter.ManuVelocityNode))
  202. {
  203. nodesToWrite[axis.Command.PowerNode] = (float)value;
  204. }
  205. }
  206. if (Plc == null || !Plc.IsConnected) return false;
  207. return Plc.WriteNodes(nodesToWrite);
  208. }
  209. public async Task<bool> SpeedsAsync(double value)
  210. {
  211. //遍历所有轴,设置电机状态
  212. //获取所有轴的Poer节点,组成一个集合,一次性写入
  213. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  214. foreach (var axis in Axes)
  215. {
  216. if (!string.IsNullOrWhiteSpace(axis.Parameter.ManuVelocityNode))
  217. {
  218. nodesToWrite[axis.Command.PowerNode] = (float)value;
  219. }
  220. }
  221. if (Plc == null || !Plc.IsConnected) return false;
  222. return await Plc.WriteNodesAsync(nodesToWrite);
  223. }
  224. public bool Accel(int value) => true;
  225. public Task<bool> AccelAsync(int value) => Task.FromResult(true);
  226. public bool Accels(double value) => true;
  227. public Task<bool> AccelsAsync(double value) => Task.FromResult(true);
  228. public RPoint GetRobotPos()
  229. {
  230. if (Plc == null || !Plc.IsConnected) return null;
  231. try
  232. {
  233. var nodeIds = Axes.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode)).Select(a => a.State.ActPositionNode).ToArray();
  234. var data = Plc.ReadNodes(nodeIds);
  235. if (data == null || data.Count == 0) return null;
  236. //获取所有的值
  237. var values = data.Values.ToArray();
  238. RPoint point = new RPoint();
  239. for (int i = 0; i < Axes.Count && i < values.Length; i++)
  240. {
  241. var val = values[i];
  242. float v = 0;
  243. if (val != null)
  244. {
  245. try { v = Convert.ToSingle(val); } catch { }
  246. }
  247. switch (Axes[i].Name)
  248. {
  249. case "X": point.X = v; break;
  250. case "Y": point.Y = v; break;
  251. case "Z": point.Z = v; break;
  252. case "U": point.U = v; break;
  253. default: break;
  254. }
  255. }
  256. return point;
  257. }
  258. catch (Exception ex)
  259. {
  260. LogHelper.WriteLogError("获取机器人位置出错", ex);
  261. throw;
  262. }
  263. }
  264. public Task<RPoint> GetRobotPosAsync()
  265. {
  266. return Task.Run(() => GetRobotPos());
  267. }
  268. public bool Go(RPoint position) {
  269. return WaitMoveFinished(position);
  270. }
  271. public Task<bool> GoAsync(RPoint position)
  272. {
  273. return Task.Run(() => Go(position));
  274. }
  275. public bool Move(RPoint position) => Go(position);
  276. public Task<bool> MoveAsync(RPoint position) => GoAsync(position);
  277. public bool Jump(RPoint position, double? LimZ) => Go(position);
  278. public Task<bool> JumpAsync(RPoint position, double? LimZ) => GoAsync(position);
  279. public bool Jog(string axis, double distance)
  280. {
  281. //获取当前机器人坐标
  282. var currentPos = GetRobotPos();
  283. if (currentPos == null) return false;
  284. switch (axis.ToUpper())
  285. {
  286. case "X":
  287. currentPos.X += (float)distance;
  288. break;
  289. case "Y":
  290. currentPos.Y += (float)distance;
  291. break;
  292. case "Z":
  293. currentPos.Z += (float)distance;
  294. break;
  295. case "U":
  296. currentPos.U += (float)distance;
  297. break;
  298. default:
  299. return false;
  300. }
  301. return Go(currentPos);
  302. }
  303. public Task<bool> JogAsync(string axis, double distance)
  304. {
  305. return Task.Run(() => Jog(axis, distance));
  306. }
  307. public bool Joint(int joint, double distance)
  308. {
  309. return false;
  310. }
  311. public Task<bool> JointAsync(int joint, double distance) => Task.FromResult(false);
  312. public bool SFree()
  313. {
  314. return Motor(false);
  315. }
  316. public Task<bool> SFreeAsync() => Task.Run(() => SFree());
  317. public bool SLock() => Motor(true);
  318. public Task<bool> SLockAsync() => Task.Run(() => SLock());
  319. public bool CalibMotion(RPoint position, double? LimZ)
  320. {
  321. //先Z轴到安全高度
  322. var currentPos = GetRobotPos();
  323. if (currentPos == null) return false;
  324. if (LimZ.HasValue)
  325. {
  326. currentPos.Z = (float)LimZ.Value;
  327. if (!Go(currentPos)) return false;
  328. }
  329. //再XYU轴到位
  330. currentPos.X = position.X;
  331. currentPos.Y = position.Y;
  332. currentPos.U = position.U;
  333. if (!Go(currentPos)) return false;
  334. //最后Z轴到目标高度
  335. currentPos.Z = position.Z;
  336. return Go(currentPos);
  337. }
  338. public Task<bool> CalibMotionAsync(RPoint position, double? LimZ) => Task.Run(() => CalibMotion(position, LimZ));
  339. public bool CalibOutIO(bool state) => false;
  340. public Task<bool> CalibOutIOAsync(bool state) => Task.FromResult(false);
  341. public bool CalibParame(PickInfo Pick, int Speed, int Accel, bool Power, int WaitSuction, int WaitBlow)
  342. {
  343. return false;
  344. }
  345. public Task<bool> CalibParameAsync(PickInfo Pick, int Speed, int Accel, bool Power, int WaitSuction, int WaitBlow) => Task.FromResult(false);
  346. /// <summary>
  347. /// 阻塞式等待运动完成
  348. /// </summary>
  349. /// <param name="position"></param>
  350. /// <returns></returns>
  351. private bool WaitMoveFinished(RPoint position)
  352. {
  353. if (Plc == null || !Plc.IsConnected) return false;
  354. try
  355. {
  356. CanExecute = false;
  357. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  358. // 1. 复位所有轴的开始移动命令
  359. StopMove();
  360. keyValues = new Dictionary<string, object>();
  361. foreach (var axis in Axes)
  362. {
  363. if (string.IsNullOrWhiteSpace(axis.Parameter.ManuPositionNode)) continue;
  364. string nodeid = axis.Parameter.ManuPositionNode;
  365. float value = 0;
  366. switch (axis.Name)
  367. {
  368. case "X": value = position.X; break;
  369. case "Y": value = position.Y; break;
  370. case "Z": value = position.Z; break;
  371. case "U": value = position.U; break;
  372. default: value = 0; break;
  373. }
  374. keyValues.Add(nodeid, value);
  375. }
  376. // 2. 写入位置给所有轴
  377. if (!Plc.WriteNodes(keyValues))
  378. {
  379. return false;
  380. }
  381. // 3. 写入开始移动命令给所有轴
  382. if (!StartMove())
  383. {
  384. return false;
  385. }
  386. // 4. 等待移动完成
  387. Stopwatch sw = new Stopwatch();
  388. sw.Start();
  389. while (true)
  390. {
  391. //检查各轴是否到位和目标位置一致
  392. var (isFinished, isError) = CheckMoveFinished(position);
  393. if (isFinished)
  394. {
  395. StopMove();
  396. if (isError)
  397. {
  398. LogHelper.WriteLogInfo($"机器人执行移动时发生错误,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  399. return false;
  400. }
  401. return true;
  402. }
  403. if (sw.ElapsedMilliseconds > Timeout)
  404. {
  405. LogHelper.WriteLogInfo($"机器人执行移动超时,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  406. StopMove();
  407. return false;
  408. }
  409. Thread.Sleep(10);
  410. }
  411. }
  412. catch (Exception ex)
  413. {
  414. LogHelper.WriteLogError("执行XYZU平台,阻塞式等待运动完成时出错!", ex);
  415. CanExecute = true;
  416. return false;
  417. }
  418. finally
  419. {
  420. CanExecute = true;
  421. }
  422. }
  423. /// <summary>
  424. /// 开始运动
  425. /// </summary>
  426. /// <returns></returns>
  427. private bool StartMove()
  428. {
  429. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  430. // 1. 复位所有轴的开始移动命令
  431. foreach (var axis in Axes)
  432. {
  433. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  434. {
  435. keyValues.Add(axis.Command.ManuPositionNode, true);
  436. }
  437. }
  438. return Plc.WriteNodes(keyValues);
  439. }
  440. /// <summary>
  441. /// 停止运动
  442. /// </summary>
  443. /// <returns></returns>
  444. private bool StopMove()
  445. {
  446. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  447. // 1. 复位所有轴的开始移动命令
  448. foreach (var axis in Axes)
  449. {
  450. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  451. {
  452. keyValues.Add(axis.Command.ManuPositionNode, false);
  453. }
  454. if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  455. {
  456. keyValues.Add(axis.Command.StopNode, true);
  457. }
  458. }
  459. bool result = Plc.WriteNodes(keyValues);
  460. // 异步等待100ms后复位停止命令
  461. Task.Run(async () =>
  462. {
  463. await Task.Delay(100);
  464. Dictionary<string, object> resetValues = new Dictionary<string, object>();
  465. foreach (var axis in Axes)
  466. {
  467. if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  468. {
  469. resetValues.Add(axis.Command.StopNode, false);
  470. }
  471. }
  472. Plc.WriteNodes(resetValues);
  473. });
  474. return result;
  475. }
  476. /// <summary>
  477. /// 检查运动是否结束,返回是否停止、是否有错误
  478. /// </summary>
  479. /// <param name="position"></param>
  480. /// <returns></returns>
  481. private (bool isFinished, bool isError) CheckMoveFinished(RPoint position)
  482. {
  483. //检查各轴是否到位和目标位置一致
  484. //批量获取所有轴的定位状态和位置、是否错误
  485. var nodeIds = new List<string>();
  486. foreach (var axis in Axes)
  487. {
  488. if (!string.IsNullOrWhiteSpace(axis.State.PosOKNode))
  489. {
  490. nodeIds.Add(axis.State.PosOKNode);
  491. }
  492. if (!string.IsNullOrWhiteSpace(axis.State.ActPositionNode))
  493. {
  494. nodeIds.Add(axis.State.ActPositionNode);
  495. }
  496. if (!string.IsNullOrWhiteSpace(axis.State.ErrorNode))
  497. {
  498. nodeIds.Add(axis.State.ErrorNode);
  499. }
  500. }
  501. var res = Plc.ReadNodes(nodeIds.ToArray());
  502. bool allOk = true;
  503. bool isAnyError = false;
  504. foreach (var axis in Axes)
  505. {
  506. bool posOk = false;
  507. float actualPos = 0;
  508. bool isError = false;
  509. //获取此轴的定位状态、实际位置、错误状态
  510. if (res.ContainsKey(axis.State.PosOKNode))
  511. {
  512. posOk = (bool)res[axis.State.PosOKNode];
  513. }
  514. if (res.ContainsKey(axis.State.ActPositionNode))
  515. {
  516. try { actualPos = Convert.ToSingle(res[axis.State.ActPositionNode]); } catch { }
  517. }
  518. if (res.ContainsKey(axis.State.ErrorNode))
  519. {
  520. isError = (bool)res[axis.State.ErrorNode];
  521. }
  522. //检查是否到位和位置一致
  523. float targetPos = 0;
  524. switch (axis.Name)
  525. {
  526. case "X": targetPos = position.X; break;
  527. case "Y": targetPos = position.Y; break;
  528. case "Z": targetPos = position.Z; break;
  529. case "U": targetPos = position.U; break;
  530. default: targetPos = 0; break;
  531. }
  532. //如果定位完成且位置一致,则此轴完成,如果有错误则失败
  533. if (!(posOk && Math.Abs(actualPos - targetPos) < 0.02))
  534. {
  535. if (isError)
  536. {
  537. isAnyError = true;
  538. break;
  539. }
  540. allOk = false;
  541. break;
  542. }
  543. }
  544. return (allOk, isAnyError);
  545. }
  546. #endregion
  547. #region 收发数据
  548. public string SendAndReceive(string send) => string.Empty;
  549. public Task<string> SendAndReceiveAsync(string send) => Task.FromResult(string.Empty);
  550. public string SendAndReceive(ITcpSessionClient client, string send) => string.Empty;
  551. public Task<string> SendAndReceiveAsync(ITcpSessionClient client, string send) => Task.FromResult(string.Empty);
  552. public void Send(string send) { }
  553. public Task SendAsync(string send) => Task.CompletedTask;
  554. public void Send(ITcpSessionClient client, string send) { }
  555. public Task SendAsync(ITcpSessionClient client, string send) => Task.CompletedTask;
  556. public Encoding GetEncoding() => Encoding.Default;
  557. #endregion
  558. #region 属性通知
  559. public event PropertyChangedEventHandler PropertyChanged;
  560. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  561. {
  562. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  563. storage = value;
  564. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  565. return true;
  566. }
  567. protected void OnPropertyChanged(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args);
  568. #endregion
  569. #region IRobot SetTool/SelectTool stubs
  570. public bool SetTool(int index, double x, double y) => true;
  571. public Task<bool> SetToolAsync(int index, double x, double y) => Task.FromResult(true);
  572. public bool SelectTool(int index) => true;
  573. public Task<bool> SelectToolAsync(int index) => Task.FromResult(true);
  574. #endregion
  575. }
  576. }