XYZU_Robot.cs 30 KB

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