XYZU_Robot.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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)
  333. {
  334. return CalibMotion(position,LimZ);
  335. }
  336. public Task<bool> JumpAsync(RPoint position, double? LimZ) => CalibMotionAsync(position,LimZ);
  337. public bool Jog(string axis, double distance)
  338. {
  339. //获取当前机器人坐标
  340. var currentPos = GetRobotPos();
  341. if (currentPos == null) return false;
  342. switch (axis.ToUpper())
  343. {
  344. case "X":
  345. currentPos.X += (float)distance;
  346. break;
  347. case "Y":
  348. currentPos.Y += (float)distance;
  349. break;
  350. case "Z":
  351. currentPos.Z += (float)distance;
  352. break;
  353. case "U":
  354. currentPos.U += (float)distance;
  355. break;
  356. default:
  357. return false;
  358. }
  359. return Go(currentPos);
  360. }
  361. public Task<bool> JogAsync(string axis, double distance)
  362. {
  363. return Task.Run(() => Jog(axis, distance));
  364. }
  365. public bool Joint(int joint, double distance)
  366. {
  367. return false;
  368. }
  369. public Task<bool> JointAsync(int joint, double distance) => Task.FromResult(false);
  370. public bool SFree()
  371. {
  372. return Motor(false);
  373. }
  374. public Task<bool> SFreeAsync() => Task.Run(() => SFree());
  375. public bool SLock() => Motor(true);
  376. public Task<bool> SLockAsync() => Task.Run(() => SLock());
  377. public bool CalibMotion(RPoint position, double? LimZ)
  378. {
  379. //先Z轴到安全高度
  380. var currentPos = GetRobotPos();
  381. if (currentPos == null) return false;
  382. if (LimZ.HasValue)
  383. {
  384. currentPos.Z = (float)LimZ.Value;
  385. if (!Go(currentPos)) return false;
  386. }
  387. //再XYU轴到位
  388. currentPos.X = position.X;
  389. currentPos.Y = position.Y;
  390. currentPos.U = position.U;
  391. if (!Go(currentPos)) return false;
  392. //最后Z轴到目标高度
  393. currentPos.Z = position.Z;
  394. return Go(currentPos);
  395. }
  396. public Task<bool> CalibMotionAsync(RPoint position, double? LimZ) => Task.Run(() => CalibMotion(position, LimZ));
  397. public bool CalibOutIO(bool state) => false;
  398. public Task<bool> CalibOutIOAsync(bool state) => Task.FromResult(false);
  399. public bool CalibParame(PickInfo Pick, int Speed, int Accel, bool Power, int WaitSuction, int WaitBlow)
  400. {
  401. return false;
  402. }
  403. public async Task<bool> CalibParameAsync(PickInfo Pick, int Speed, int Accel, bool Power, int WaitSuction, int WaitBlow)
  404. {
  405. if (Plc == null || !Plc.IsConnected) return false;
  406. try
  407. {
  408. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  409. foreach (var axis in Axes)
  410. {
  411. if (string.IsNullOrWhiteSpace(axis.Parameter.ManuVelocityNode)) continue;
  412. string nodeid = axis.Parameter.ManuVelocityNode;
  413. float value = Speed;
  414. keyValues.Add(nodeid, value);
  415. }
  416. // 2. 写入速度给所有轴
  417. if (!Plc.WriteNodes(keyValues))
  418. {
  419. return false;
  420. }
  421. return true;
  422. }
  423. catch (Exception ex)
  424. {
  425. LogHelper.WriteLogError("为XYZU平台设置速度时出错!", ex);
  426. return false;
  427. }
  428. }
  429. /// <summary>
  430. /// 阻塞式等待运动完成
  431. /// </summary>
  432. /// <param name="position"></param>
  433. /// <returns></returns>
  434. private bool WaitMoveFinished(RPoint position)
  435. {
  436. if (Plc == null || !Plc.IsConnected) return false;
  437. try
  438. {
  439. CanExecute = false;
  440. Motor(true);
  441. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  442. // 1. 写入目标位置到各轴的 ManuPositionNode
  443. keyValues = new Dictionary<string, object>();
  444. foreach (var axis in Axes)
  445. {
  446. if (string.IsNullOrWhiteSpace(axis.Parameter.ManuPositionNode)) continue;
  447. string nodeid = axis.Parameter.ManuPositionNode;
  448. float value = 0;
  449. switch (axis.Name)
  450. {
  451. case "X": value = position.X; break;
  452. case "Y": value = position.Y; break;
  453. case "Z": value = position.Z; break;
  454. case "U": value = position.U; break;
  455. default: value = 0; break;
  456. }
  457. keyValues.Add(nodeid, value);
  458. }
  459. // 2. 写入位置给所有轴
  460. if (!Plc.WriteNodes(keyValues))
  461. {
  462. return false;
  463. }
  464. // 3. 写入开始移动命令给所有轴
  465. if (!StartMove())
  466. {
  467. return false;
  468. }
  469. // 准备停滞检测:收集所有实际位置节点
  470. var actNodes = Axes.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode))
  471. .Select(a => a.State.ActPositionNode)
  472. .Distinct()
  473. .ToArray();
  474. // lastPos 存储上一次读取到的位置,lastChange 存储上次发生“实质性”变化的时间
  475. Dictionary<string, float> lastPos = new Dictionary<string, float>();
  476. Dictionary<string, DateTime> lastChange = new Dictionary<string, DateTime>();
  477. foreach (var node in actNodes)
  478. {
  479. lastPos[node] = float.NaN;
  480. lastChange[node] = DateTime.UtcNow;
  481. }
  482. const float movementThreshold = 0.01f; // 判断位置变化的阈值,避免噪声
  483. Stopwatch sw = new Stopwatch();
  484. sw.Start();
  485. while (true)
  486. {
  487. // 先读取各轴的实际位置,用于停滞检测
  488. Dictionary<string, object> posRead = new Dictionary<string, object>();
  489. try
  490. {
  491. if (actNodes.Length > 0)
  492. {
  493. posRead = Plc.ReadNodes(actNodes);
  494. }
  495. }
  496. catch
  497. {
  498. // 如果读取失败,继续让 CheckMoveFinished 来处理状态或超时
  499. }
  500. var now = DateTime.UtcNow;
  501. // 更新每个节点的变化时间:只要任意一个轴在最近 Timeout 时间内有变化,就视为系统仍在运动
  502. foreach (var node in actNodes)
  503. {
  504. float actual = 0;
  505. if (posRead != null && posRead.ContainsKey(node))
  506. {
  507. var raw = posRead[node];
  508. if (raw != null)
  509. {
  510. try { actual = Convert.ToSingle(raw); } catch { /* 保持 actual = 0 */ }
  511. }
  512. }
  513. if (float.IsNaN(lastPos[node]))
  514. {
  515. lastPos[node] = actual;
  516. lastChange[node] = now;
  517. }
  518. else
  519. {
  520. if (Math.Abs(actual - lastPos[node]) > movementThreshold)
  521. {
  522. // 有实质性变化,更新记录时间和值
  523. lastPos[node] = actual;
  524. lastChange[node] = now;
  525. }
  526. // 否则保持 lastChange 不变(表示该轴最近一次变化的时间)
  527. }
  528. }
  529. // 判断是否至少有一个轴在最近 Timeout 时间内发生过变化(即认为还在运动)
  530. bool anyAxisMovedRecently = actNodes.Any(node => (now - lastChange[node]).TotalMilliseconds <= 1000);
  531. // 如果没有任何轴在最近 Timeout 时间内发生变化,则认为出现停滞异常
  532. if (!anyAxisMovedRecently && actNodes.Length > 0)
  533. {
  534. StopMove();
  535. LogHelper.WriteLogInfo($"轴停滞超时(整体判定),目标位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U},超时阈值(ms)={Timeout}");
  536. return false;
  537. }
  538. // 检查是否整体到位或有错误(保留原有逻辑)
  539. var (isFinished, isError) = CheckMoveFinished(position);
  540. if (isFinished)
  541. {
  542. StopMove();
  543. if (isError)
  544. {
  545. LogHelper.WriteLogInfo($"机器人执行移动时发生错误,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  546. return false;
  547. }
  548. return true;
  549. }
  550. // 检查整体超时(防止一直有抖动导致 anyAxisMovedRecently 一直为 true)
  551. if (sw.ElapsedMilliseconds > 60000) // 保守超时,一分钟,可根据需求调整
  552. {
  553. LogHelper.WriteLogInfo($"机器人执行移动超时,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  554. StopMove();
  555. return false;
  556. }
  557. Thread.Sleep(10);
  558. }
  559. }
  560. catch (Exception ex)
  561. {
  562. LogHelper.WriteLogError("执行XYZU平台,阻塞式等待运动完成时出错!", ex);
  563. CanExecute = true;
  564. return false;
  565. }
  566. finally
  567. {
  568. CanExecute = true;
  569. }
  570. }
  571. /// <summary>
  572. /// 开始运动
  573. /// </summary>
  574. /// <returns></returns>
  575. private bool StartMove()
  576. {
  577. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  578. // 1. 复位所有轴的开始移动命令
  579. foreach (var axis in Axes)
  580. {
  581. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  582. {
  583. keyValues.Add(axis.Command.ManuPositionNode, true);
  584. }
  585. }
  586. return Plc.WriteNodes(keyValues);
  587. }
  588. /// <summary>
  589. /// 停止运动
  590. /// </summary>
  591. /// <returns></returns>
  592. private bool StopMove()
  593. {
  594. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  595. // 1. 复位所有轴的开始移动命令
  596. foreach (var axis in Axes)
  597. {
  598. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  599. {
  600. keyValues.Add(axis.Command.ManuPositionNode, false);
  601. }
  602. if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  603. {
  604. keyValues.Add(axis.Command.StopNode, true);
  605. }
  606. }
  607. bool result = Plc.WriteNodes(keyValues);
  608. // 异步等待100ms后复位停止命令
  609. //Task.Run(async () =>
  610. //{
  611. // await Task.Delay(100);
  612. Thread.Sleep(50);
  613. Dictionary<string, object> resetValues = new Dictionary<string, object>();
  614. foreach (var axis in Axes)
  615. {
  616. if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  617. {
  618. resetValues.Add(axis.Command.StopNode, false);
  619. }
  620. }
  621. Plc.WriteNodes(resetValues);
  622. //});
  623. return result;
  624. }
  625. /// <summary>
  626. /// 检查运动是否结束,返回是否停止、是否有错误
  627. /// </summary>
  628. /// <param name="position"></param>
  629. /// <returns></returns>
  630. private (bool isFinished, bool isError) CheckMoveFinished(RPoint position)
  631. {
  632. //检查各轴是否到位和目标位置一致
  633. //批量获取所有轴的定位状态和位置、是否错误
  634. var nodeIds = new List<string>();
  635. foreach (var axis in Axes)
  636. {
  637. if (!string.IsNullOrWhiteSpace(axis.State.PosOKNode))
  638. {
  639. nodeIds.Add(axis.State.PosOKNode);
  640. }
  641. if (!string.IsNullOrWhiteSpace(axis.State.ActPositionNode))
  642. {
  643. nodeIds.Add(axis.State.ActPositionNode);
  644. }
  645. if (!string.IsNullOrWhiteSpace(axis.State.ErrorNode))
  646. {
  647. nodeIds.Add(axis.State.ErrorNode);
  648. }
  649. if (!string.IsNullOrWhiteSpace(axis.State.PausedNode))
  650. {
  651. nodeIds.Add(axis.State.PausedNode);
  652. }
  653. }
  654. var res = Plc.ReadNodes(nodeIds.ToArray());
  655. bool allOk = true;
  656. bool isAnyError = false;
  657. foreach (var axis in Axes)
  658. {
  659. bool posOk = false;
  660. float actualPos = 0;
  661. bool isError = false;
  662. //获取此轴的定位状态、实际位置、错误状态
  663. if (res.ContainsKey(axis.State.PosOKNode))
  664. {
  665. posOk = (bool)res[axis.State.PosOKNode];
  666. }
  667. if (res.ContainsKey(axis.State.ActPositionNode))
  668. {
  669. try { actualPos = Convert.ToSingle(res[axis.State.ActPositionNode]); } catch { }
  670. }
  671. if (res.ContainsKey(axis.State.ErrorNode))
  672. {
  673. isError = (bool)res[axis.State.ErrorNode];
  674. }
  675. if (res.ContainsKey(axis.State.PausedNode))
  676. {
  677. isError = (bool)res[axis.State.PausedNode];
  678. }
  679. if (isError)
  680. {
  681. isAnyError = true;
  682. break;
  683. }
  684. //检查是否到位和位置一致
  685. float targetPos = 0;
  686. switch (axis.Name)
  687. {
  688. case "X": targetPos = position.X; break;
  689. case "Y": targetPos = position.Y; break;
  690. case "Z": targetPos = position.Z; break;
  691. case "U": targetPos = position.U; break;
  692. default: targetPos = 0; break;
  693. }
  694. //如果定位完成且位置一致,则此轴完成,如果有错误则失败
  695. if (!(posOk && Math.Abs(actualPos - targetPos) < 0.02))
  696. {
  697. if (isError)
  698. {
  699. isAnyError = true;
  700. break;
  701. }
  702. allOk = false;
  703. break;
  704. }
  705. }
  706. return (allOk, isAnyError);
  707. }
  708. #endregion
  709. #region 收发数据
  710. public string SendAndReceive(string send) => string.Empty;
  711. public Task<string> SendAndReceiveAsync(string send) => Task.FromResult(string.Empty);
  712. public string SendAndReceive(ITcpSessionClient client, string send) => string.Empty;
  713. public Task<string> SendAndReceiveAsync(ITcpSessionClient client, string send) => Task.FromResult(string.Empty);
  714. public void Send(string send) { }
  715. public Task SendAsync(string send) => Task.CompletedTask;
  716. public void Send(ITcpSessionClient client, string send) { }
  717. public Task SendAsync(ITcpSessionClient client, string send) => Task.CompletedTask;
  718. public Encoding GetEncoding() => Encoding.Default;
  719. #endregion
  720. #region 属性通知
  721. public event PropertyChangedEventHandler PropertyChanged;
  722. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  723. {
  724. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  725. storage = value;
  726. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  727. return true;
  728. }
  729. protected void OnPropertyChanged(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args);
  730. #endregion
  731. #region IRobot SetTool/SelectTool stubs
  732. public bool SetTool(int index, double x, double y) => true;
  733. public Task<bool> SetToolAsync(int index, double x, double y) => Task.FromResult(true);
  734. public bool SelectTool(int index) => true;
  735. public Task<bool> SelectToolAsync(int index) => Task.FromResult(true);
  736. #endregion
  737. }
  738. }