XYZU_Robot.cs 23 KB

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