XYZU_Robot.cs 29 KB

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