XYZU_Robot.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  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. if (robot.PlcRobotParameter.AxixList.Count >= 5)
  87. {
  88. var au = new Axis();
  89. au.Name = "V";
  90. au.Index = 5;
  91. au.Command = robot.PlcRobotParameter.AxixList[4].Command;
  92. au.Parameter = robot.PlcRobotParameter.AxixList[4].Parameter;
  93. au.State = robot.PlcRobotParameter.AxixList[4].State;
  94. Axes.Add(au);
  95. Brand = RobotBrand.XYZU_Platform;
  96. }
  97. if (robot.PlcRobotParameter.AxixList.Count >= 6)
  98. {
  99. var au = new Axis();
  100. au.Name = "W";
  101. au.Index = 6;
  102. au.Command = robot.PlcRobotParameter.AxixList[5].Command;
  103. au.Parameter = robot.PlcRobotParameter.AxixList[5].Parameter;
  104. au.State = robot.PlcRobotParameter.AxixList[5].State;
  105. Axes.Add(au);
  106. Brand = RobotBrand.XYZU_Platform;
  107. }
  108. if (Plc.IsConnected)
  109. {
  110. try
  111. {
  112. //所有轴的位置节点
  113. var nodeIds = Axes.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode)).Select(a => a.State.ActPositionNode).ToArray();
  114. List<string> positionNodes = new List<string>(nodeIds);
  115. pLC.SubscribeNodes("AxisPosition", positionNodes, (res) =>
  116. {
  117. if (res.key != "AxisPosition") return;
  118. for (int i = 0; i < Axes.Count; i++)
  119. {
  120. var axis = Axes[i];
  121. if (axis.State.ActPositionNode.Contains(res.nodeId))
  122. {
  123. float v = Convert.ToSingle(res.value);
  124. switch (axis.Name)
  125. {
  126. case "X": CurrentPosition.X = v; break;
  127. case "Y": CurrentPosition.Y = v; break;
  128. case "Z": CurrentPosition.Z = v; break;
  129. case "U": CurrentPosition.U = v; break;
  130. case "V": CurrentPosition.V = v; break;
  131. case "W": CurrentPosition.W = v; break;
  132. }
  133. }
  134. }
  135. });
  136. }
  137. catch (Exception)
  138. {
  139. }
  140. }
  141. }
  142. private void Plc_ConnectChangedEvent(object arg1, bool arg2)
  143. {
  144. CanExecute = arg2;
  145. if (arg2)
  146. ConnectedEvent?.Invoke(Id, this, null);
  147. else
  148. DisconnectedEvent?.Invoke(Id, this, null);
  149. }
  150. #region 属性
  151. public TcpClient TcpClient { get; private set; }
  152. public TcpService TcpService { get; private set; }
  153. public Guid Id { get; set; }
  154. public string Name { get; set; }
  155. /// <summary>
  156. /// 机器人编号
  157. /// </summary>
  158. public int RobotNo { get; set; }
  159. public int RobotPort { get; private set; }
  160. public string RobotIp { get; private set; }
  161. public TCPConnectType ConnectType { get; private set; }
  162. public Terminator Terminator { get; private set; }
  163. public DataEncoding DataEncoding { get; private set; }
  164. public bool IsConnected
  165. {
  166. get
  167. {
  168. if (Plc != null)
  169. {
  170. return Plc.IsConnected;
  171. }
  172. else
  173. {
  174. return false;
  175. }
  176. }
  177. }
  178. public int Timeout { get; set; } = 5000;
  179. private bool _CanExecute = true;
  180. public bool CanExecute
  181. {
  182. get { return _CanExecute; }
  183. set { SetProperty(ref _CanExecute, value); }
  184. }
  185. public int SelectedTool { get; private set; } = 0;
  186. public RobotBrand Brand { get; private set; }
  187. public OpcUaClientPLC Plc { get; private set; }
  188. public RobotInfo RobotInfo { get; private set; }
  189. public List<Axis> Axes { get; private set; }
  190. /// <summary>
  191. /// 进入调试模式
  192. /// </summary>
  193. /// <returns></returns>
  194. public bool EnterDebugMode { get; set; }
  195. private RPoint _CurrentPosition = new RPoint();
  196. /// <summary>
  197. /// 当前位置
  198. /// </summary>
  199. public RPoint CurrentPosition
  200. {
  201. get { return _CurrentPosition; }
  202. set { SetProperty(ref _CurrentPosition, value); }
  203. }
  204. #endregion
  205. #region 连接
  206. public void Connect()
  207. {
  208. if (Plc.IsConnected)
  209. {
  210. StopMove();
  211. ConnectedEvent?.Invoke(Id, this, null);
  212. }
  213. }
  214. public Task ConnectAsync()
  215. {
  216. if (Plc.IsConnected)
  217. {
  218. StopMove();
  219. ConnectedEvent?.Invoke(Id, this, null);
  220. }
  221. return Task.CompletedTask;
  222. }
  223. public void Disconnect()
  224. {
  225. }
  226. public void Dispose()
  227. {
  228. }
  229. #endregion
  230. #region 控制
  231. public bool Reset() => true;
  232. public Task<bool> ResetAsync() { return Task.Run(() => Reset()); }
  233. public bool Motor(bool state)
  234. {
  235. //遍历所有轴,设置电机状态
  236. //获取所有轴的Poer节点,组成一个集合,一次性写入
  237. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  238. foreach (var axis in Axes)
  239. {
  240. if (!string.IsNullOrWhiteSpace(axis.Command.PowerNode))
  241. {
  242. nodesToWrite[axis.Command.PowerNode] = state;
  243. }
  244. }
  245. if (Plc == null || !Plc.IsConnected) return false;
  246. return Plc.WriteNodes(nodesToWrite);
  247. }
  248. public async Task<bool> MotorAsync(bool state)
  249. {
  250. //遍历所有轴,设置电机状态
  251. //获取所有轴的Poer节点,组成一个集合,一次性写入
  252. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  253. foreach (var axis in Axes)
  254. {
  255. if (!string.IsNullOrWhiteSpace(axis.Command.PowerNode))
  256. {
  257. nodesToWrite[axis.Command.PowerNode] = state;
  258. }
  259. }
  260. if (Plc == null || !Plc.IsConnected) return false;
  261. return await Plc.WriteNodesAsync(nodesToWrite);
  262. }
  263. public bool Power(bool state) => true;
  264. public Task<bool> PowerAsync(bool state) => Task.FromResult(true);
  265. public bool Speed(int value)
  266. {
  267. return true;
  268. }
  269. public Task<bool> SpeedAsync(int value) => Task.FromResult(true);
  270. public bool Speedfactor(int value) => true;
  271. public Task<bool> SpeedfactorAsync(int value) => Task.FromResult(true);
  272. public bool Speeds(double value)
  273. {
  274. //遍历所有轴,设置电机状态
  275. //获取所有轴的Poer节点,组成一个集合,一次性写入
  276. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  277. foreach (var axis in Axes)
  278. {
  279. if (!string.IsNullOrWhiteSpace(axis.Parameter.ManuVelocityNode))
  280. {
  281. nodesToWrite[axis.Command.PowerNode] = (float)value;
  282. }
  283. }
  284. if (Plc == null || !Plc.IsConnected) return false;
  285. return Plc.WriteNodes(nodesToWrite);
  286. }
  287. public async Task<bool> SpeedsAsync(double value)
  288. {
  289. //遍历所有轴,设置电机状态
  290. //获取所有轴的Poer节点,组成一个集合,一次性写入
  291. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  292. foreach (var axis in Axes)
  293. {
  294. if (!string.IsNullOrWhiteSpace(axis.Parameter.ManuVelocityNode))
  295. {
  296. nodesToWrite[axis.Command.PowerNode] = (float)value;
  297. }
  298. }
  299. if (Plc == null || !Plc.IsConnected) return false;
  300. return await Plc.WriteNodesAsync(nodesToWrite);
  301. }
  302. public bool Accel(int value) => true;
  303. public Task<bool> AccelAsync(int value) => Task.FromResult(true);
  304. public bool Accels(double value) => true;
  305. public Task<bool> AccelsAsync(double value) => Task.FromResult(true);
  306. public RPoint GetRobotPos()
  307. {
  308. if (Plc == null || !Plc.IsConnected) return null;
  309. try
  310. {
  311. var nodeIds = Axes.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode)).Select(a => a.State.ActPositionNode).ToArray();
  312. var data = Plc.ReadNodes(nodeIds);
  313. if (data == null || data.Count == 0) return null;
  314. //获取所有的值
  315. var values = data.Values.ToArray();
  316. RPoint point = new RPoint();
  317. for (int i = 0; i < Axes.Count && i < values.Length; i++)
  318. {
  319. var val = values[i];
  320. float v = 0;
  321. if (val != null)
  322. {
  323. try { v = Convert.ToSingle(val); } catch { }
  324. }
  325. switch (Axes[i].Name)
  326. {
  327. case "X": point.X = v; break;
  328. case "Y": point.Y = v; break;
  329. case "Z": point.Z = v; break;
  330. case "U": point.U = v; break;
  331. case "V": point.V = v; break;
  332. case "W": point.W = v; break;
  333. default: break;
  334. }
  335. }
  336. return point;
  337. }
  338. catch (Exception ex)
  339. {
  340. LogHelper.WriteLogError("获取机器人位置出错", ex);
  341. throw;
  342. }
  343. }
  344. public Task<RPoint> GetRobotPosAsync()
  345. {
  346. return Task.Run(() => GetRobotPos());
  347. }
  348. public bool Go(RPoint position)
  349. {
  350. return WaitMoveFinished(position);
  351. }
  352. public Task<bool> GoAsync(RPoint position)
  353. {
  354. return Task.Run(() => Go(position));
  355. }
  356. public bool Move(RPoint position) => Go(position);
  357. public Task<bool> MoveAsync(RPoint position) => GoAsync(position);
  358. public bool Jump(RPoint position, double? LimZ)
  359. {
  360. return CalibMotion(position, LimZ);
  361. }
  362. public Task<bool> JumpAsync(RPoint position, double? LimZ) => CalibMotionAsync(position, LimZ);
  363. public bool Jog(string axis, double distance)
  364. {
  365. //获取当前机器人坐标
  366. var currentPos = GetRobotPos();
  367. if (currentPos == null) return false;
  368. switch (axis.ToUpper())
  369. {
  370. case "X":
  371. currentPos.X += (float)distance;
  372. break;
  373. case "Y":
  374. currentPos.Y += (float)distance;
  375. break;
  376. case "Z":
  377. currentPos.Z += (float)distance;
  378. break;
  379. case "U":
  380. currentPos.U += (float)distance;
  381. break;
  382. case "V":
  383. currentPos.V += (float)distance;
  384. break;
  385. case "W":
  386. currentPos.W += (float)distance;
  387. break;
  388. default:
  389. return false;
  390. }
  391. return Go(currentPos);
  392. }
  393. public Task<bool> JogAsync(string axis, double distance)
  394. {
  395. return Task.Run(() => Jog(axis, distance));
  396. }
  397. public bool Joint(int joint, double distance)
  398. {
  399. return false;
  400. }
  401. public Task<bool> JointAsync(int joint, double distance) => Task.FromResult(false);
  402. public bool SFree()
  403. {
  404. return Motor(false);
  405. }
  406. public Task<bool> SFreeAsync() => Task.Run(() => SFree());
  407. public bool SLock() => Motor(true);
  408. public Task<bool> SLockAsync() => Task.Run(() => SLock());
  409. public bool CalibMotion(RPoint position, double? LimZ)
  410. {
  411. //先Z轴到安全高度
  412. var currentPos = GetRobotPos();
  413. if (currentPos == null) return false;
  414. if (LimZ.HasValue)
  415. {
  416. currentPos.Z = (float)LimZ.Value;
  417. if (!Go(currentPos)) return false;
  418. }
  419. //再XYU轴到位
  420. currentPos.X = position.X;
  421. currentPos.Y = position.Y;
  422. currentPos.U = position.U;
  423. if (!Go(currentPos)) return false;
  424. //最后Z轴到目标高度
  425. currentPos.Z = position.Z;
  426. return Go(currentPos);
  427. }
  428. public Task<bool> CalibMotionAsync(RPoint position, double? LimZ) => Task.Run(() => CalibMotion(position, LimZ));
  429. public bool CalibOutIO(bool state) => false;
  430. public Task<bool> CalibOutIOAsync(bool state) => Task.FromResult(false);
  431. public bool CalibParame(PickInfo Pick, int Speed, int Accel, bool Power, int WaitSuction, int WaitBlow)
  432. {
  433. return false;
  434. }
  435. public async Task<bool> CalibParameAsync(PickInfo Pick, int Speed, int Accel, bool Power, int WaitSuction, int WaitBlow)
  436. {
  437. if (Plc == null || !Plc.IsConnected) return false;
  438. try
  439. {
  440. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  441. foreach (var axis in Axes)
  442. {
  443. if (string.IsNullOrWhiteSpace(axis.Parameter.ManuVelocityNode)) continue;
  444. string nodeid = axis.Parameter.ManuVelocityNode;
  445. float value = Speed;
  446. keyValues.Add(nodeid, value);
  447. }
  448. // 2. 写入速度给所有轴
  449. if (!Plc.WriteNodes(keyValues))
  450. {
  451. return false;
  452. }
  453. return true;
  454. }
  455. catch (Exception ex)
  456. {
  457. LogHelper.WriteLogError("为XYZU平台设置速度时出错!", ex);
  458. return false;
  459. }
  460. }
  461. /// <summary>
  462. /// 阻塞式等待运动完成
  463. /// </summary>
  464. /// <param name="position"></param>
  465. /// <returns></returns>
  466. private bool WaitMoveFinished(RPoint position)
  467. {
  468. if (Plc == null || !Plc.IsConnected) return false;
  469. try
  470. {
  471. CanExecute = false;
  472. Motor(true);
  473. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  474. // 1. 写入目标位置到各轴的 ManuPositionNode
  475. keyValues = new Dictionary<string, object>();
  476. foreach (var axis in Axes)
  477. {
  478. if (string.IsNullOrWhiteSpace(axis.Parameter.ManuPositionNode)) continue;
  479. string nodeid = axis.Parameter.ManuPositionNode;
  480. float value = 0;
  481. switch (axis.Name)
  482. {
  483. case "X": value = position.X; break;
  484. case "Y": value = position.Y; break;
  485. case "Z": value = position.Z; break;
  486. case "U": value = position.U; break;
  487. case "V": value = position.V; break;
  488. case "W": value = position.W; break;
  489. default: value = 0; break;
  490. }
  491. keyValues.Add(nodeid, value);
  492. }
  493. // 2. 写入位置给所有轴
  494. if (!Plc.WriteNodes(keyValues))
  495. {
  496. return false;
  497. }
  498. // 3. 写入开始移动命令给所有轴
  499. if (!StartMove())
  500. {
  501. return false;
  502. }
  503. // 准备停滞检测:收集所有实际位置节点
  504. var actNodes = Axes.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode))
  505. .Select(a => a.State.ActPositionNode)
  506. .Distinct()
  507. .ToArray();
  508. // lastPos 存储上一次读取到的位置,lastChange 存储上次发生“实质性”变化的时间
  509. Dictionary<string, float> lastPos = new Dictionary<string, float>();
  510. Dictionary<string, DateTime> lastChange = new Dictionary<string, DateTime>();
  511. foreach (var node in actNodes)
  512. {
  513. lastPos[node] = float.NaN;
  514. lastChange[node] = DateTime.UtcNow;
  515. }
  516. const float movementThreshold = 0.01f; // 判断位置变化的阈值,避免噪声
  517. Stopwatch sw = new Stopwatch();
  518. sw.Start();
  519. while (true)
  520. {
  521. // 先读取各轴的实际位置,用于停滞检测
  522. Dictionary<string, object> posRead = new Dictionary<string, object>();
  523. try
  524. {
  525. if (actNodes.Length > 0)
  526. {
  527. posRead = Plc.ReadNodes(actNodes);
  528. }
  529. }
  530. catch
  531. {
  532. // 如果读取失败,继续让 CheckMoveFinished 来处理状态或超时
  533. }
  534. var now = DateTime.UtcNow;
  535. // 更新每个节点的变化时间:只要任意一个轴在最近 Timeout 时间内有变化,就视为系统仍在运动
  536. foreach (var node in actNodes)
  537. {
  538. float actual = 0;
  539. if (posRead != null && posRead.ContainsKey(node))
  540. {
  541. var raw = posRead[node];
  542. if (raw != null)
  543. {
  544. try { actual = Convert.ToSingle(raw); } catch { /* 保持 actual = 0 */ }
  545. }
  546. }
  547. if (float.IsNaN(lastPos[node]))
  548. {
  549. lastPos[node] = actual;
  550. lastChange[node] = now;
  551. }
  552. else
  553. {
  554. if (Math.Abs(actual - lastPos[node]) > movementThreshold)
  555. {
  556. // 有实质性变化,更新记录时间和值
  557. lastPos[node] = actual;
  558. lastChange[node] = now;
  559. }
  560. // 否则保持 lastChange 不变(表示该轴最近一次变化的时间)
  561. }
  562. }
  563. // 判断是否至少有一个轴在最近 Timeout 时间内发生过变化(即认为还在运动)
  564. bool anyAxisMovedRecently = actNodes.Any(node => (now - lastChange[node]).TotalMilliseconds <= 1000);
  565. // 如果没有任何轴在最近 Timeout 时间内发生变化,则认为出现停滞异常
  566. if (!anyAxisMovedRecently && actNodes.Length > 0)
  567. {
  568. StopMove();
  569. LogHelper.WriteLogInfo($"轴停滞超时(整体判定),目标位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U},超时阈值(ms)={Timeout}");
  570. return false;
  571. }
  572. // 检查是否整体到位或有错误(保留原有逻辑)
  573. var (isFinished, isError) = CheckMoveFinished(position);
  574. if (isFinished)
  575. {
  576. StopMove();
  577. if (isError)
  578. {
  579. LogHelper.WriteLogInfo($"机器人执行移动时发生错误,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  580. return false;
  581. }
  582. return true;
  583. }
  584. // 检查整体超时(防止一直有抖动导致 anyAxisMovedRecently 一直为 true)
  585. if (sw.ElapsedMilliseconds > 60000) // 保守超时,一分钟,可根据需求调整
  586. {
  587. LogHelper.WriteLogInfo($"机器人执行移动超时,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  588. StopMove();
  589. return false;
  590. }
  591. Thread.Sleep(10);
  592. }
  593. }
  594. catch (Exception ex)
  595. {
  596. LogHelper.WriteLogError("执行XYZU平台,阻塞式等待运动完成时出错!", ex);
  597. CanExecute = true;
  598. return false;
  599. }
  600. finally
  601. {
  602. CanExecute = true;
  603. }
  604. }
  605. /// <summary>
  606. /// 开始运动
  607. /// </summary>
  608. /// <returns></returns>
  609. private bool StartMove()
  610. {
  611. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  612. // 1. 复位所有轴的开始移动命令
  613. foreach (var axis in Axes)
  614. {
  615. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  616. {
  617. keyValues.Add(axis.Command.ManuPositionNode, true);
  618. }
  619. }
  620. return Plc.WriteNodes(keyValues);
  621. }
  622. /// <summary>
  623. /// 停止运动
  624. /// </summary>
  625. /// <returns></returns>
  626. private bool StopMove()
  627. {
  628. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  629. // 1. 复位所有轴的开始移动命令
  630. foreach (var axis in Axes)
  631. {
  632. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  633. {
  634. keyValues.Add(axis.Command.ManuPositionNode, false);
  635. }
  636. if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  637. {
  638. keyValues.Add(axis.Command.StopNode, true);
  639. }
  640. }
  641. bool result = Plc.WriteNodes(keyValues);
  642. // 异步等待100ms后复位停止命令
  643. //Task.Run(async () =>
  644. //{
  645. // await Task.Delay(100);
  646. Thread.Sleep(50);
  647. Dictionary<string, object> resetValues = new Dictionary<string, object>();
  648. foreach (var axis in Axes)
  649. {
  650. if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  651. {
  652. resetValues.Add(axis.Command.StopNode, false);
  653. }
  654. }
  655. Plc.WriteNodes(resetValues);
  656. //});
  657. return result;
  658. }
  659. /// <summary>
  660. /// 检查运动是否结束,返回是否停止、是否有错误
  661. /// </summary>
  662. /// <param name="position"></param>
  663. /// <returns></returns>
  664. private (bool isFinished, bool isError) CheckMoveFinished(RPoint position)
  665. {
  666. //检查各轴是否到位和目标位置一致
  667. //批量获取所有轴的定位状态和位置、是否错误
  668. var nodeIds = new List<string>();
  669. foreach (var axis in Axes)
  670. {
  671. if (!string.IsNullOrWhiteSpace(axis.State.PosOKNode))
  672. {
  673. nodeIds.Add(axis.State.PosOKNode);
  674. }
  675. if (!string.IsNullOrWhiteSpace(axis.State.ActPositionNode))
  676. {
  677. nodeIds.Add(axis.State.ActPositionNode);
  678. }
  679. if (!string.IsNullOrWhiteSpace(axis.State.ErrorNode))
  680. {
  681. nodeIds.Add(axis.State.ErrorNode);
  682. }
  683. if (!string.IsNullOrWhiteSpace(axis.State.PausedNode))
  684. {
  685. nodeIds.Add(axis.State.PausedNode);
  686. }
  687. }
  688. var res = Plc.ReadNodes(nodeIds.ToArray());
  689. bool allOk = true;
  690. bool isAnyError = false;
  691. foreach (var axis in Axes)
  692. {
  693. bool posOk = false;
  694. float actualPos = 0;
  695. bool isError = false;
  696. //获取此轴的定位状态、实际位置、错误状态
  697. if (res.ContainsKey(axis.State.PosOKNode))
  698. {
  699. posOk = (bool)res[axis.State.PosOKNode];
  700. }
  701. if (res.ContainsKey(axis.State.ActPositionNode))
  702. {
  703. try { actualPos = Convert.ToSingle(res[axis.State.ActPositionNode]); } catch { }
  704. }
  705. if (res.ContainsKey(axis.State.ErrorNode))
  706. {
  707. isError = (bool)res[axis.State.ErrorNode];
  708. }
  709. if (res.ContainsKey(axis.State.PausedNode))
  710. {
  711. isError = (bool)res[axis.State.PausedNode];
  712. }
  713. if (isError)
  714. {
  715. isAnyError = true;
  716. break;
  717. }
  718. //检查是否到位和位置一致
  719. float targetPos = 0;
  720. switch (axis.Name)
  721. {
  722. case "X": targetPos = position.X; break;
  723. case "Y": targetPos = position.Y; break;
  724. case "Z": targetPos = position.Z; break;
  725. case "U": targetPos = position.U; break;
  726. default: targetPos = 0; break;
  727. }
  728. //如果定位完成且位置一致,则此轴完成,如果有错误则失败
  729. if (!(posOk && Math.Abs(actualPos - targetPos) < 0.02))
  730. {
  731. if (isError)
  732. {
  733. isAnyError = true;
  734. break;
  735. }
  736. allOk = false;
  737. break;
  738. }
  739. }
  740. return (allOk, isAnyError);
  741. }
  742. #endregion
  743. #region 收发数据
  744. public string SendAndReceive(string send) => string.Empty;
  745. public Task<string> SendAndReceiveAsync(string send) => Task.FromResult(string.Empty);
  746. public string SendAndReceive(ITcpSessionClient client, string send) => string.Empty;
  747. public Task<string> SendAndReceiveAsync(ITcpSessionClient client, string send) => Task.FromResult(string.Empty);
  748. public void Send(string send) { }
  749. public Task SendAsync(string send) => Task.CompletedTask;
  750. public void Send(ITcpSessionClient client, string send) { }
  751. public Task SendAsync(ITcpSessionClient client, string send) => Task.CompletedTask;
  752. public Encoding GetEncoding() => Encoding.Default;
  753. #endregion
  754. #region 属性通知
  755. public event PropertyChangedEventHandler PropertyChanged;
  756. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  757. {
  758. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  759. storage = value;
  760. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  761. return true;
  762. }
  763. protected void OnPropertyChanged(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args);
  764. #endregion
  765. #region IRobot SetTool/SelectTool stubs
  766. public bool SetTool(int index, double x, double y) => true;
  767. public Task<bool> SetToolAsync(int index, double x, double y) => Task.FromResult(true);
  768. public bool SelectTool(int index) => true;
  769. public Task<bool> SelectToolAsync(int index) => Task.FromResult(true);
  770. #endregion
  771. }
  772. }