XYZU_Robot.cs 30 KB

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