XYZU_Robot.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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 TeamAAS_VP.Resources.Languages;
  19. using TouchSocket.Core;
  20. using TouchSocket.Sockets;
  21. using static System.Windows.Forms.AxHost;
  22. namespace TeamAAS_VP.Core.Robots
  23. {
  24. /// <summary>
  25. /// Generic multi-axis robot that composes axis objects and uses PLC nodes configured in RobotInfo.PlcRobotParameter
  26. /// to perform coordinated moves (Go/Move/CalibMotion) for 3 or 4 axes.
  27. /// This implementation maps X/Y/Z/(U) axes by name and writes their position nodes then triggers ExecuteMove node.
  28. /// </summary>
  29. public class XYZU_Robot : IRobot, INotifyPropertyChanged
  30. {
  31. public event Action<Guid, object, ConnectedEventArgs> ConnectedEvent;
  32. public event Action<Guid, object, ClosedEventArgs> DisconnectedEvent;
  33. public event Action<Guid, object, ReceivedDataEventArgs> ReceivedEvent;
  34. public event Action<Guid, object, string> SendEvent;
  35. public XYZU_Robot(RobotInfo robot, OpcUaClientPLC pLC)
  36. {
  37. RobotInfo = robot;
  38. Name = robot.RobotName;
  39. Id = robot.Id;
  40. RobotNo = robot.RobotNo;
  41. RobotIp = robot.IP;
  42. RobotPort = robot.Port;
  43. ConnectType = robot.ConnectType;
  44. Terminator = robot.Terminator;
  45. DataEncoding = robot.DataEncoding;
  46. Brand = RobotBrand.XYZ_Platform;
  47. SafeZ = robot.SafeZ;
  48. Plc = pLC;
  49. Plc.ConnectChangedEvent += Plc_ConnectChangedEvent;
  50. // build axis list from known RobotInfo.PlcRobotParameter nodes (best-effort)
  51. Axes = new List<Axis>();
  52. // X
  53. var ax = new Axis();
  54. ax.Name = "X";
  55. ax.Index = 1;
  56. ax.Command = robot.PlcRobotParameter.AxixList[0].Command;
  57. ax.Parameter = robot.PlcRobotParameter.AxixList[0].Parameter;
  58. ax.State = robot.PlcRobotParameter.AxixList[0].State;
  59. Axes.Add(ax);
  60. // Y
  61. var ay = new Axis();
  62. ay.Name = "Y";
  63. ay.Index = 2;
  64. ay.Command = robot.PlcRobotParameter.AxixList[1].Command;
  65. ay.Parameter = robot.PlcRobotParameter.AxixList[1].Parameter;
  66. ay.State = robot.PlcRobotParameter.AxixList[1].State;
  67. Axes.Add(ay);
  68. // Z
  69. var az = new Axis();
  70. az.Name = "Z";
  71. az.Index = 3;
  72. az.Command = robot.PlcRobotParameter.AxixList[2].Command;
  73. az.Parameter = robot.PlcRobotParameter.AxixList[2].Parameter;
  74. az.State = robot.PlcRobotParameter.AxixList[2].State;
  75. Axes.Add(az);
  76. // U optional
  77. if (robot.PlcRobotParameter.AxixList.Count >= 4)
  78. {
  79. var au = new Axis();
  80. au.Name = "U";
  81. au.Index = 4;
  82. au.Command = robot.PlcRobotParameter.AxixList[3].Command;
  83. au.Parameter = robot.PlcRobotParameter.AxixList[3].Parameter;
  84. au.State = robot.PlcRobotParameter.AxixList[3].State;
  85. Axes.Add(au);
  86. Brand = RobotBrand.XYZU_Platform;
  87. }
  88. // R optional
  89. if (robot.PlcRobotParameter.AxixList.Count >= 5)
  90. {
  91. var au = new Axis();
  92. au.Name = "R";
  93. au.Index = 5;
  94. au.Command = robot.PlcRobotParameter.AxixList[4].Command;
  95. au.Parameter = robot.PlcRobotParameter.AxixList[4].Parameter;
  96. au.State = robot.PlcRobotParameter.AxixList[4].State;
  97. Axes.Add(au);
  98. Brand = RobotBrand.XYZU_Platform;
  99. }
  100. if (Plc.IsConnected)
  101. {
  102. try
  103. {
  104. //所有轴的位置节点
  105. var nodeIds = Axes.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode)).Select(a => a.State.ActPositionNode).ToArray();
  106. List<string> positionNodes = new List<string>(nodeIds);
  107. pLC.SubscribeNodes("AxisPosition", positionNodes, (res) =>
  108. {
  109. if (res.key != "AxisPosition") return;
  110. for (int i = 0; i < Axes.Count; i++)
  111. {
  112. var axis = Axes[i];
  113. if (axis.State.ActPositionNode.Contains(res.nodeId))
  114. {
  115. float v = Convert.ToSingle(res.value);
  116. switch (axis.Name)
  117. {
  118. case "X": CurrentPosition.X = v; break;
  119. case "Y": CurrentPosition.Y = v; break;
  120. case "Z": CurrentPosition.Z = v; break;
  121. case "U": CurrentPosition.U = v; break;
  122. case "R": CurrentPosition.V = v; break;
  123. }
  124. }
  125. }
  126. });
  127. }
  128. catch (Exception)
  129. {
  130. }
  131. }
  132. }
  133. private void Plc_ConnectChangedEvent(object arg1, bool arg2)
  134. {
  135. CanExecute = arg2;
  136. if (arg2)
  137. ConnectedEvent?.Invoke(Id, this, null);
  138. else
  139. DisconnectedEvent?.Invoke(Id, this, null);
  140. }
  141. #region 属性
  142. public TcpClient TcpClient { get; private set; }
  143. public TcpService TcpService { get; private set; }
  144. public Guid Id { get; set; }
  145. public string Name { get; set; }
  146. /// <summary>
  147. /// 机器人编号
  148. /// </summary>
  149. public int RobotNo { get; set; }
  150. public int RobotPort { get; private set; }
  151. public string RobotIp { get; private set; }
  152. public TCPConnectType ConnectType { get; private set; }
  153. public Terminator Terminator { get; private set; }
  154. public DataEncoding DataEncoding { get; private set; }
  155. public bool IsConnected
  156. {
  157. get
  158. {
  159. if (Plc != null)
  160. {
  161. return Plc.IsConnected;
  162. }
  163. else
  164. {
  165. return false;
  166. }
  167. }
  168. }
  169. public int Timeout { get; set; } = 5000;
  170. private bool _CanExecute = true;
  171. public bool CanExecute
  172. {
  173. get { return _CanExecute; }
  174. set { SetProperty(ref _CanExecute, value); }
  175. }
  176. public int SelectedTool { get; private set; } = 0;
  177. public RobotBrand Brand { get; private set; }
  178. public OpcUaClientPLC Plc { get; private set; }
  179. public RobotInfo RobotInfo { get; private set; }
  180. public List<Axis> Axes { get; private set; }
  181. /// <summary>
  182. /// 进入调试模式
  183. /// </summary>
  184. /// <returns></returns>
  185. public bool EnterDebugMode { get; set; }
  186. private RPoint _CurrentPosition = new RPoint();
  187. /// <summary>
  188. /// 当前位置
  189. /// </summary>
  190. public RPoint CurrentPosition
  191. {
  192. get { return _CurrentPosition; }
  193. set { SetProperty(ref _CurrentPosition, value); }
  194. }
  195. private double _SafeZ;
  196. /// <summary>
  197. /// Z轴的安全高度
  198. /// </summary>
  199. public double SafeZ
  200. {
  201. get { return _SafeZ; }
  202. set { SetProperty(ref _SafeZ, 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 "R": point.V = v; break;
  332. default: break;
  333. }
  334. }
  335. return point;
  336. }
  337. catch (Exception ex)
  338. {
  339. LogHelper.WriteLogError(Lang.获取机器人位置出错, ex);
  340. throw;
  341. }
  342. }
  343. public Task<RPoint> GetRobotPosAsync()
  344. {
  345. return Task.Run(() => GetRobotPos());
  346. }
  347. public bool Go(RPoint position)
  348. {
  349. return WaitMoveFinished(position);
  350. }
  351. public Task<bool> GoAsync(RPoint position)
  352. {
  353. return Task.Run(() => Go(position));
  354. }
  355. public bool Move(RPoint position) => Go(position);
  356. public Task<bool> MoveAsync(RPoint position) => GoAsync(position);
  357. public bool Jump(RPoint position, double? LimZ)
  358. {
  359. return CalibMotion(position,LimZ);
  360. }
  361. public Task<bool> JumpAsync(RPoint position, double? LimZ) => CalibMotionAsync(position,LimZ);
  362. public bool Jog(string axis, double distance)
  363. {
  364. //获取当前机器人坐标
  365. var currentPos = GetRobotPos();
  366. if (currentPos == null) return false;
  367. switch (axis.ToUpper())
  368. {
  369. case "X":
  370. currentPos.X += (float)distance;
  371. break;
  372. case "Y":
  373. currentPos.Y += (float)distance;
  374. break;
  375. case "Z":
  376. currentPos.Z += (float)distance;
  377. break;
  378. case "U":
  379. currentPos.U += (float)distance;
  380. break;
  381. case "R":
  382. currentPos.V += (float)distance;
  383. break;
  384. default:
  385. return false;
  386. }
  387. return Go(currentPos);
  388. }
  389. public Task<bool> JogAsync(string axis, double distance)
  390. {
  391. return Task.Run(() => Jog(axis, distance));
  392. }
  393. public bool Joint(int joint, double distance)
  394. {
  395. return false;
  396. }
  397. public Task<bool> JointAsync(int joint, double distance) => Task.FromResult(false);
  398. public bool SFree()
  399. {
  400. return Motor(false);
  401. }
  402. public Task<bool> SFreeAsync() => Task.Run(() => SFree());
  403. public bool SLock() => Motor(true);
  404. public Task<bool> SLockAsync() => Task.Run(() => SLock());
  405. public bool CalibMotion(RPoint position, double? LimZ)
  406. {
  407. //先Z轴到安全高度
  408. var currentPos = GetRobotPos();
  409. if (currentPos == null) return false;
  410. if (LimZ.HasValue)
  411. {
  412. currentPos.Z = (float)LimZ.Value;
  413. if (!Go(currentPos)) return false;
  414. }
  415. else
  416. {
  417. currentPos.Z = (float)SafeZ;
  418. if (!Go(currentPos)) return false;
  419. }
  420. //再XYU轴到位
  421. currentPos.X = position.X;
  422. currentPos.Y = position.Y;
  423. currentPos.U = position.U;
  424. if (!Go(currentPos)) return false;
  425. //最后Z轴到目标高度
  426. currentPos.Z = position.Z;
  427. var isSucceed = Go(currentPos);
  428. Thread.Sleep(150);
  429. return isSucceed;
  430. }
  431. public Task<bool> CalibMotionAsync(RPoint position, double? LimZ) => Task.Run(() => CalibMotion(position, LimZ));
  432. public bool CalibOutIO(bool state) => false;
  433. public Task<bool> CalibOutIOAsync(bool state) => Task.FromResult(false);
  434. public bool CalibParame(PickInfo Pick, int Speed, int Accel, bool Power, int WaitSuction, int WaitBlow)
  435. {
  436. return false;
  437. }
  438. public async Task<bool> CalibParameAsync(PickInfo Pick, int Speed, int Accel, bool Power, int WaitSuction, int WaitBlow)
  439. {
  440. if (Plc == null || !Plc.IsConnected) return false;
  441. try
  442. {
  443. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  444. foreach (var axis in Axes)
  445. {
  446. if (string.IsNullOrWhiteSpace(axis.Parameter.ManuVelocityNode)) continue;
  447. string nodeid = axis.Parameter.ManuVelocityNode;
  448. float value = Speed;
  449. keyValues.Add(nodeid, value);
  450. }
  451. // 2. 写入速度给所有轴
  452. if (!Plc.WriteNodes(keyValues))
  453. {
  454. return false;
  455. }
  456. return true;
  457. }
  458. catch (Exception ex)
  459. {
  460. LogHelper.WriteLogError(Lang.为XYZU平台设置速度时出错, ex);
  461. return false;
  462. }
  463. }
  464. /// <summary>
  465. /// 阻塞式等待运动完成
  466. /// </summary>
  467. /// <param name="position"></param>
  468. /// <returns></returns>
  469. private bool WaitMoveFinished(RPoint position)
  470. {
  471. if (Plc == null || !Plc.IsConnected) return false;
  472. try
  473. {
  474. CanExecute = false;
  475. Motor(true);
  476. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  477. // 1. 写入目标位置到各轴的 ManuPositionNode
  478. keyValues = new Dictionary<string, object>();
  479. foreach (var axis in Axes)
  480. {
  481. if (string.IsNullOrWhiteSpace(axis.Parameter.ManuPositionNode)) continue;
  482. string nodeid = axis.Parameter.ManuPositionNode;
  483. float value = 0;
  484. switch (axis.Name)
  485. {
  486. case "X": value = position.X; break;
  487. case "Y": value = position.Y; break;
  488. case "Z": value = position.Z; break;
  489. case "U": value = position.U; break;
  490. case "R": value = position.V; break;
  491. default: value = 0; break;
  492. }
  493. keyValues.Add(nodeid, value);
  494. }
  495. // 2. 写入位置给所有轴
  496. if (!Plc.WriteNodes(keyValues))
  497. {
  498. return false;
  499. }
  500. // 3. 写入开始移动命令给所有轴
  501. if (!StartMove())
  502. {
  503. return false;
  504. }
  505. // 准备停滞检测:收集所有实际位置节点
  506. var actNodes = Axes.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode))
  507. .Select(a => a.State.ActPositionNode)
  508. .Distinct()
  509. .ToArray();
  510. // lastPos 存储上一次读取到的位置,lastChange 存储上次发生“实质性”变化的时间
  511. Dictionary<string, float> lastPos = new Dictionary<string, float>();
  512. Dictionary<string, DateTime> lastChange = new Dictionary<string, DateTime>();
  513. foreach (var node in actNodes)
  514. {
  515. lastPos[node] = float.NaN;
  516. lastChange[node] = DateTime.Now;
  517. }
  518. const float movementThreshold = 0.01f; // 判断位置变化的阈值,避免噪声
  519. Stopwatch sw = new Stopwatch();
  520. sw.Start();
  521. while (true)
  522. {
  523. // 先读取各轴的实际位置,用于停滞检测
  524. Dictionary<string, object> posRead = new Dictionary<string, object>();
  525. try
  526. {
  527. if (actNodes.Length > 0)
  528. {
  529. posRead = Plc.ReadNodes(actNodes);
  530. }
  531. }
  532. catch
  533. {
  534. // 如果读取失败,继续让 CheckMoveFinished 来处理状态或超时
  535. }
  536. var now = DateTime.Now;
  537. // 更新每个节点的变化时间:只要任意一个轴在最近 Timeout 时间内有变化,就视为系统仍在运动
  538. foreach (var node in actNodes)
  539. {
  540. float actual = 0;
  541. if (posRead != null && posRead.ContainsKey(node))
  542. {
  543. var raw = posRead[node];
  544. if (raw != null)
  545. {
  546. try { actual = Convert.ToSingle(raw); } catch { /* 保持 actual = 0 */ }
  547. }
  548. }
  549. if (float.IsNaN(lastPos[node]))
  550. {
  551. lastPos[node] = actual;
  552. lastChange[node] = now;
  553. }
  554. else
  555. {
  556. if (Math.Abs(actual - lastPos[node]) > movementThreshold)
  557. {
  558. // 有实质性变化,更新记录时间和值
  559. lastPos[node] = actual;
  560. lastChange[node] = now;
  561. }
  562. // 否则保持 lastChange 不变(表示该轴最近一次变化的时间)
  563. }
  564. }
  565. // 判断是否至少有一个轴在最近 Timeout 时间内发生过变化(即认为还在运动)
  566. bool anyAxisMovedRecently = actNodes.Any(node => (now - lastChange[node]).TotalMilliseconds <= 500);
  567. // 如果没有任何轴在最近 Timeout 时间内发生变化,则认为出现停滞异常
  568. if (!anyAxisMovedRecently && actNodes.Length > 0)
  569. {
  570. StopMove();
  571. LogHelper.WriteLogInfo(string.Format(Lang.轴停滞超时整体判定目标位置X0Y1Z2U3超时阈值ms4,position.X, position.Y, position.Z, position.U, Timeout));
  572. return false;
  573. }
  574. // 检查是否整体到位或有错误(保留原有逻辑)
  575. var (isFinished, isError) = CheckMoveFinished(position);
  576. if (isFinished)
  577. {
  578. StopMove();
  579. if (isError)
  580. {
  581. LogHelper.WriteLogInfo(string.Format(Lang.机器人执行移动时发生错误位置X0Y1Z2U3,position.X,position.Y, position.Z, position.U));
  582. return false;
  583. }
  584. return true;
  585. }
  586. if (isError)
  587. {
  588. StopMove();
  589. LogHelper.WriteLogInfo($"机器人执行移动时发生错误,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  590. return false;
  591. }
  592. // 检查整体超时(防止一直有抖动导致 anyAxisMovedRecently 一直为 true)
  593. if (sw.ElapsedMilliseconds > 60000) // 保守超时,一分钟,可根据需求调整
  594. {
  595. LogHelper.WriteLogInfo(string.Format(Lang.机器人执行移动超时位置X0Y1Z2U3,position.X, position.Y, position.Z, position.U));
  596. StopMove();
  597. return false;
  598. }
  599. Thread.Sleep(10);
  600. }
  601. }
  602. catch (Exception ex)
  603. {
  604. LogHelper.WriteLogError(Lang.执行XYZU平台阻塞式等待运动完成时出错, ex);
  605. CanExecute = true;
  606. return false;
  607. }
  608. finally
  609. {
  610. CanExecute = true;
  611. }
  612. }
  613. /// <summary>
  614. /// 开始运动
  615. /// </summary>
  616. /// <returns></returns>
  617. private bool StartMove()
  618. {
  619. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  620. // 1. 复位所有轴的开始移动命令
  621. foreach (var axis in Axes)
  622. {
  623. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  624. {
  625. keyValues.Add(axis.Command.ManuPositionNode, true);
  626. }
  627. }
  628. return Plc.WriteNodes(keyValues);
  629. }
  630. /// <summary>
  631. /// 停止运动
  632. /// </summary>
  633. /// <returns></returns>
  634. private bool StopMove()
  635. {
  636. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  637. // 1. 复位所有轴的开始移动命令
  638. foreach (var axis in Axes)
  639. {
  640. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  641. {
  642. keyValues.Add(axis.Command.ManuPositionNode, false);
  643. }
  644. //if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  645. //{
  646. // keyValues.Add(axis.Command.StopNode, true);
  647. //}
  648. }
  649. bool result = Plc.WriteNodes(keyValues);
  650. // 异步等待100ms后复位停止命令
  651. //Task.Run(async () =>
  652. //{
  653. // await Task.Delay(100);
  654. //Thread.Sleep(50);
  655. //Dictionary<string, object> resetValues = new Dictionary<string, object>();
  656. //foreach (var axis in Axes)
  657. //{
  658. // if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  659. // {
  660. // resetValues.Add(axis.Command.StopNode, false);
  661. // }
  662. //}
  663. //Plc.WriteNodes(resetValues);
  664. //});
  665. return result;
  666. }
  667. /// <summary>
  668. /// 检查运动是否结束,返回是否停止、是否有错误
  669. /// </summary>
  670. /// <param name="position"></param>
  671. /// <returns></returns>
  672. private (bool isFinished, bool isError) CheckMoveFinished(RPoint position)
  673. {
  674. //检查各轴是否到位和目标位置一致
  675. //批量获取所有轴的定位状态和位置、是否错误
  676. var nodeIds = new List<string>();
  677. foreach (var axis in Axes)
  678. {
  679. if (!string.IsNullOrWhiteSpace(axis.State.PosOKNode))
  680. {
  681. nodeIds.Add(axis.State.PosOKNode);
  682. }
  683. if (!string.IsNullOrWhiteSpace(axis.State.ActPositionNode))
  684. {
  685. nodeIds.Add(axis.State.ActPositionNode);
  686. }
  687. if (!string.IsNullOrWhiteSpace(axis.State.ErrorNode))
  688. {
  689. nodeIds.Add(axis.State.ErrorNode);
  690. }
  691. if (!string.IsNullOrWhiteSpace(axis.State.PausedNode))
  692. {
  693. nodeIds.Add(axis.State.PausedNode);
  694. }
  695. }
  696. var res = Plc.ReadNodes(nodeIds.ToArray());
  697. bool allOk = true;
  698. bool isAnyError = false;
  699. foreach (var axis in Axes)
  700. {
  701. bool posOk = false;
  702. float actualPos = 0;
  703. bool isError = false;
  704. //获取此轴的定位状态、实际位置、错误状态
  705. if (res.ContainsKey(axis.State.PosOKNode))
  706. {
  707. posOk = (bool)res[axis.State.PosOKNode];
  708. }
  709. if (res.ContainsKey(axis.State.ActPositionNode))
  710. {
  711. try { actualPos = Convert.ToSingle(res[axis.State.ActPositionNode]); } catch { }
  712. }
  713. if (res.ContainsKey(axis.State.ErrorNode))
  714. {
  715. isError = (bool)res[axis.State.ErrorNode];
  716. }
  717. if (res.ContainsKey(axis.State.PausedNode))
  718. {
  719. isError = (bool)res[axis.State.PausedNode];
  720. }
  721. //if (isError)
  722. //{
  723. // isAnyError = true;
  724. // break;
  725. //}
  726. //检查是否到位和位置一致
  727. float targetPos = 0;
  728. switch (axis.Name)
  729. {
  730. case "X": targetPos = position.X; break;
  731. case "Y": targetPos = position.Y; break;
  732. case "Z": targetPos = position.Z; break;
  733. case "U": targetPos = position.U; break;
  734. case "R": targetPos = position.V; break;
  735. default: targetPos = 0; break;
  736. }
  737. //如果定位完成且位置一致,则此轴完成,如果有错误则失败
  738. if (!(Math.Abs(actualPos - targetPos) < 0.02))
  739. {
  740. //if (isError)
  741. //{
  742. // isAnyError = true;
  743. // break;
  744. //}
  745. allOk = false;
  746. break;
  747. }
  748. }
  749. return (allOk, isAnyError);
  750. }
  751. #endregion
  752. #region 收发数据
  753. public string SendAndReceive(string send) => string.Empty;
  754. public Task<string> SendAndReceiveAsync(string send) => Task.FromResult(string.Empty);
  755. public string SendAndReceive(ITcpSessionClient client, string send) => string.Empty;
  756. public Task<string> SendAndReceiveAsync(ITcpSessionClient client, string send) => Task.FromResult(string.Empty);
  757. public void Send(string send) { }
  758. public Task SendAsync(string send) => Task.CompletedTask;
  759. public void Send(ITcpSessionClient client, string send) { }
  760. public Task SendAsync(ITcpSessionClient client, string send) => Task.CompletedTask;
  761. public Encoding GetEncoding() => Encoding.Default;
  762. #endregion
  763. #region 属性通知
  764. public event PropertyChangedEventHandler PropertyChanged;
  765. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  766. {
  767. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  768. storage = value;
  769. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  770. return true;
  771. }
  772. protected void OnPropertyChanged(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args);
  773. #endregion
  774. #region IRobot SetTool/SelectTool stubs
  775. public bool SetTool(int index, double x, double y) => true;
  776. public Task<bool> SetToolAsync(int index, double x, double y) => Task.FromResult(true);
  777. public bool SelectTool(int index) => true;
  778. public Task<bool> SelectToolAsync(int index) => Task.FromResult(true);
  779. #endregion
  780. }
  781. }