XYZU_Robot.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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.Collections.ObjectModel;
  8. using System.ComponentModel;
  9. using System.Diagnostics;
  10. using System.Linq;
  11. using System.Runtime.CompilerServices;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. using TeamAAS_VP.Core.PLCs;
  16. using TeamAAS_VP.Enums;
  17. using TeamAAS_VP.Interfaces;
  18. using TeamAAS_VP.Models;
  19. using TouchSocket.Core;
  20. using TouchSocket.Sockets;
  21. using static OpenCvSharp.ML.DTrees;
  22. using static System.Windows.Forms.AxHost;
  23. namespace TeamAAS_VP.Core.Robots
  24. {
  25. /// <summary>
  26. /// Generic multi-axis robot that composes axis objects and uses PLC nodes configured in RobotInfo.PlcRobotParameter
  27. /// to perform coordinated moves (Go/Move/CalibMotion) for 3 or 4 axes.
  28. /// This implementation maps X/Y/Z/(U) axes by name and writes their position nodes then triggers ExecuteMove node.
  29. /// </summary>
  30. public class XYZU_Robot : IRobot, INotifyPropertyChanged
  31. {
  32. public event Action<Guid, object, ConnectedEventArgs> ConnectedEvent;
  33. public event Action<Guid, object, ClosedEventArgs> DisconnectedEvent;
  34. public event Action<Guid, object, ReceivedDataEventArgs> ReceivedEvent;
  35. public event Action<Guid, object, string> SendEvent;
  36. public XYZU_Robot(RobotInfo robot, OpcUaClientPLC pLC)
  37. {
  38. RobotInfo = robot;
  39. Name = robot.RobotName;
  40. Id = robot.Id;
  41. RobotNo = robot.RobotNo;
  42. RobotIp = robot.IP;
  43. RobotPort = robot.Port;
  44. ConnectType = robot.ConnectType;
  45. Terminator = robot.Terminator;
  46. DataEncoding = robot.DataEncoding;
  47. Brand = RobotBrand.XYZ_Platform;
  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. //附加轴集合
  89. if(robot.PlcRobotParameter.AdditionalAxisList!=null && robot.PlcRobotParameter.AdditionalAxisList.Count>0)
  90. {
  91. AdditionalAxisList = new ObservableCollection<AxisExtended>();
  92. foreach(var addAxis in robot.PlcRobotParameter.AdditionalAxisList)
  93. {
  94. AxisExtended axisExt = new AxisExtended()
  95. {
  96. Name = addAxis.Name,
  97. Index = addAxis.Index,
  98. Command = addAxis.Command,
  99. Parameter = addAxis.Parameter,
  100. State = addAxis.State
  101. };
  102. AdditionalAxisList.Add(axisExt);
  103. }
  104. }
  105. if (Plc.IsConnected)
  106. {
  107. try
  108. {
  109. //所有轴的位置节点
  110. var nodeIds = Axes.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode)).Select(a => a.State.ActPositionNode).ToArray();
  111. List<string> positionNodes = new List<string>(nodeIds);
  112. pLC.SubscribeNodes("AxisPosition", positionNodes, (res) =>
  113. {
  114. if (res.key != "AxisPosition") return;
  115. for (int i = 0; i < Axes.Count; i++)
  116. {
  117. var axis = Axes[i];
  118. if (axis.State.ActPositionNode.Contains(res.nodeId))
  119. {
  120. float v = Convert.ToSingle(res.value);
  121. switch (axis.Name)
  122. {
  123. case "X": CurrentPosition.X = v; break;
  124. case "Y": CurrentPosition.Y = v; break;
  125. case "Z": CurrentPosition.Z = v; break;
  126. case "U": CurrentPosition.U = v; break;
  127. }
  128. }
  129. }
  130. });
  131. //所有附加轴的位置节点
  132. if (AdditionalAxisList != null && AdditionalAxisList.Count > 0)
  133. {
  134. var addNodeIds = AdditionalAxisList
  135. .Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode))
  136. .Select(a => a.State.ActPositionNode)
  137. .ToArray();
  138. List<string> addPositionNodes = new List<string>(addNodeIds);
  139. pLC.SubscribeNodes("AdditionalAxisPosition", addPositionNodes, (res) =>
  140. {
  141. if (res.key != "AdditionalAxisPosition") return;
  142. for (int i = 0; i < AdditionalAxisList.Count; i++)
  143. {
  144. var axis = AdditionalAxisList[i];
  145. if (axis.State.ActPositionNode.Contains(res.nodeId))
  146. {
  147. axis.CurrentPosition = Convert.ToSingle(res.value);
  148. }
  149. }
  150. });
  151. }
  152. }
  153. catch (Exception)
  154. {
  155. }
  156. }
  157. }
  158. private void Plc_ConnectChangedEvent(object arg1, bool arg2)
  159. {
  160. CanExecute = arg2;
  161. if (arg2)
  162. ConnectedEvent?.Invoke(Id, this, null);
  163. else
  164. DisconnectedEvent?.Invoke(Id, this, null);
  165. }
  166. #region 属性
  167. public TcpClient TcpClient { get; private set; }
  168. public TcpService TcpService { get; private set; }
  169. public Guid Id { get; set; }
  170. public string Name { get; set; }
  171. /// <summary>
  172. /// 机器人编号
  173. /// </summary>
  174. public int RobotNo { get; set; }
  175. public int RobotPort { get; private set; }
  176. public string RobotIp { get; private set; }
  177. public TCPConnectType ConnectType { get; private set; }
  178. public Terminator Terminator { get; private set; }
  179. public DataEncoding DataEncoding { get; private set; }
  180. public bool IsConnected
  181. {
  182. get
  183. {
  184. if (Plc != null)
  185. {
  186. return Plc.IsConnected;
  187. }
  188. else
  189. {
  190. return false;
  191. }
  192. }
  193. }
  194. public int Timeout { get; set; } = 5000;
  195. private bool _CanExecute = true;
  196. public bool CanExecute
  197. {
  198. get { return _CanExecute; }
  199. set { SetProperty(ref _CanExecute, value); }
  200. }
  201. public int SelectedTool { get; private set; } = 0;
  202. public RobotBrand Brand { get; private set; }
  203. public OpcUaClientPLC Plc { get; private set; }
  204. public RobotInfo RobotInfo { get; private set; }
  205. public List<Axis> Axes { get; private set; }
  206. private ObservableCollection<AxisExtended> _AdditionalAxisList;
  207. public ObservableCollection<AxisExtended> AdditionalAxisList
  208. {
  209. get { return _AdditionalAxisList; }
  210. set { SetProperty(ref _AdditionalAxisList, value); }
  211. }
  212. /// <summary>
  213. /// 进入调试模式
  214. /// </summary>
  215. /// <returns></returns>
  216. public bool EnterDebugMode { get; set; }
  217. private RPoint _CurrentPosition = new RPoint();
  218. /// <summary>
  219. /// 当前位置
  220. /// </summary>
  221. public RPoint CurrentPosition
  222. {
  223. get { return _CurrentPosition; }
  224. set { SetProperty(ref _CurrentPosition, value); }
  225. }
  226. #endregion
  227. #region 连接
  228. public void Connect()
  229. {
  230. if (Plc.IsConnected)
  231. {
  232. StopMove();
  233. ConnectedEvent?.Invoke(Id, this, null);
  234. }
  235. }
  236. public Task ConnectAsync()
  237. {
  238. if (Plc.IsConnected)
  239. {
  240. StopMove();
  241. ConnectedEvent?.Invoke(Id, this, null);
  242. }
  243. return Task.CompletedTask;
  244. }
  245. public void Disconnect()
  246. {
  247. }
  248. public void Dispose()
  249. {
  250. }
  251. #endregion
  252. #region 控制
  253. public bool Reset() => true;
  254. public Task<bool> ResetAsync() { return Task.Run(() => Reset()); }
  255. public bool Motor(bool state)
  256. {
  257. //遍历所有轴,设置电机状态
  258. //获取所有轴的Poer节点,组成一个集合,一次性写入
  259. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  260. foreach (var axis in Axes)
  261. {
  262. if (!string.IsNullOrWhiteSpace(axis.Command.PowerNode))
  263. {
  264. nodesToWrite[axis.Command.PowerNode] = state;
  265. }
  266. }
  267. if (Plc == null || !Plc.IsConnected) return false;
  268. return Plc.WriteNodes(nodesToWrite);
  269. }
  270. public async Task<bool> MotorAsync(bool state)
  271. {
  272. //遍历所有轴,设置电机状态
  273. //获取所有轴的Poer节点,组成一个集合,一次性写入
  274. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  275. foreach (var axis in Axes)
  276. {
  277. if (!string.IsNullOrWhiteSpace(axis.Command.PowerNode))
  278. {
  279. nodesToWrite[axis.Command.PowerNode] = state;
  280. }
  281. }
  282. if (Plc == null || !Plc.IsConnected) return false;
  283. return await Plc.WriteNodesAsync(nodesToWrite);
  284. }
  285. public bool Power(bool state) => true;
  286. public Task<bool> PowerAsync(bool state) => Task.FromResult(true);
  287. public bool Speed(int value)
  288. {
  289. return true;
  290. }
  291. public Task<bool> SpeedAsync(int value) => Task.FromResult(true);
  292. public bool Speedfactor(int value) => true;
  293. public Task<bool> SpeedfactorAsync(int value) => Task.FromResult(true);
  294. public bool Speeds(double value)
  295. {
  296. //遍历所有轴,设置电机状态
  297. //获取所有轴的Poer节点,组成一个集合,一次性写入
  298. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  299. foreach (var axis in Axes)
  300. {
  301. if (!string.IsNullOrWhiteSpace(axis.Parameter.ManuVelocityNode))
  302. {
  303. nodesToWrite[axis.Command.PowerNode] = (float)value;
  304. }
  305. }
  306. if (Plc == null || !Plc.IsConnected) return false;
  307. return Plc.WriteNodes(nodesToWrite);
  308. }
  309. public async Task<bool> SpeedsAsync(double value)
  310. {
  311. //遍历所有轴,设置电机状态
  312. //获取所有轴的Poer节点,组成一个集合,一次性写入
  313. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  314. foreach (var axis in Axes)
  315. {
  316. if (!string.IsNullOrWhiteSpace(axis.Parameter.ManuVelocityNode))
  317. {
  318. nodesToWrite[axis.Command.PowerNode] = (float)value;
  319. }
  320. }
  321. if (Plc == null || !Plc.IsConnected) return false;
  322. return await Plc.WriteNodesAsync(nodesToWrite);
  323. }
  324. public bool Accel(int value) => true;
  325. public Task<bool> AccelAsync(int value) => Task.FromResult(true);
  326. public bool Accels(double value) => true;
  327. public Task<bool> AccelsAsync(double value) => Task.FromResult(true);
  328. public RPoint GetRobotPos()
  329. {
  330. if (Plc == null || !Plc.IsConnected) return null;
  331. try
  332. {
  333. var nodeIds = Axes.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode)).Select(a => a.State.ActPositionNode).ToArray();
  334. var data = Plc.ReadNodes(nodeIds);
  335. if (data == null || data.Count == 0) return null;
  336. //获取所有的值
  337. var values = data.Values.ToArray();
  338. RPoint point = new RPoint();
  339. for (int i = 0; i < Axes.Count && i < values.Length; i++)
  340. {
  341. var val = values[i];
  342. float v = 0;
  343. if (val != null)
  344. {
  345. try { v = Convert.ToSingle(val); } catch { }
  346. }
  347. switch (Axes[i].Name)
  348. {
  349. case "X": point.X = v; break;
  350. case "Y": point.Y = v; break;
  351. case "Z": point.Z = v; break;
  352. case "U": point.U = v; break;
  353. default: break;
  354. }
  355. }
  356. return point;
  357. }
  358. catch (Exception ex)
  359. {
  360. LogHelper.WriteLogError("获取机器人位置出错", ex);
  361. throw;
  362. }
  363. }
  364. public Task<RPoint> GetRobotPosAsync()
  365. {
  366. return Task.Run(() => GetRobotPos());
  367. }
  368. public bool Go(RPoint position)
  369. {
  370. return WaitMoveFinished(position);
  371. }
  372. public Task<bool> GoAsync(RPoint position)
  373. {
  374. return Task.Run(() => Go(position));
  375. }
  376. public bool Move(RPoint position) => Go(position);
  377. public Task<bool> MoveAsync(RPoint position) => GoAsync(position);
  378. public bool Jump(RPoint position, double? LimZ)
  379. {
  380. return CalibMotion(position,LimZ);
  381. }
  382. public Task<bool> JumpAsync(RPoint position, double? LimZ) => CalibMotionAsync(position,LimZ);
  383. public bool Jog(string axis, double distance)
  384. {
  385. //获取当前机器人坐标
  386. var currentPos = GetRobotPos();
  387. if (currentPos == null) return false;
  388. switch (axis.ToUpper())
  389. {
  390. case "X":
  391. currentPos.X += (float)distance;
  392. break;
  393. case "Y":
  394. currentPos.Y += (float)distance;
  395. break;
  396. case "Z":
  397. currentPos.Z += (float)distance;
  398. break;
  399. case "U":
  400. currentPos.U += (float)distance;
  401. break;
  402. default:
  403. return false;
  404. }
  405. return Go(currentPos);
  406. }
  407. public Task<bool> JogAsync(string axis, double distance)
  408. {
  409. return Task.Run(() => Jog(axis, distance));
  410. }
  411. public bool Joint(int joint, double distance)
  412. {
  413. return false;
  414. }
  415. public Task<bool> JointAsync(int joint, double distance) => Task.FromResult(false);
  416. public bool SFree()
  417. {
  418. return Motor(false);
  419. }
  420. public Task<bool> SFreeAsync() => Task.Run(() => SFree());
  421. public bool SLock() => Motor(true);
  422. public Task<bool> SLockAsync() => Task.Run(() => SLock());
  423. public bool CalibMotion(RPoint position, double? LimZ)
  424. {
  425. //先Z轴到安全高度
  426. var currentPos = GetRobotPos();
  427. if (currentPos == null) return false;
  428. if (LimZ.HasValue)
  429. {
  430. currentPos.Z = (float)LimZ.Value;
  431. if (!Go(currentPos)) return false;
  432. }
  433. //再XYU轴到位
  434. currentPos.X = position.X;
  435. currentPos.Y = position.Y;
  436. currentPos.U = position.U;
  437. if (!Go(currentPos)) return false;
  438. //最后Z轴到目标高度
  439. currentPos.Z = position.Z;
  440. var isSucceed = Go(currentPos);
  441. Thread.Sleep(150);
  442. return isSucceed;
  443. }
  444. public Task<bool> CalibMotionAsync(RPoint position, double? LimZ) => Task.Run(() => CalibMotion(position, LimZ));
  445. public bool CalibOutIO(bool state)
  446. {
  447. if (Plc == null || !Plc.IsConnected) return false;
  448. string openNodeId = "ns=4;s=DB_DriveControl|VacCtrl[{0}].Cmd.ManuToWork";
  449. string closeNodeId = "ns=4;s=DB_DriveControl|VacCtrl[{0}].Cmd.ManuToHome";
  450. try
  451. {
  452. if (state)
  453. {
  454. string node = string.Format(openNodeId, _PickInfo.Inhal);
  455. if (!Plc.WriteNode<bool>(node,true))
  456. {
  457. return false;
  458. }
  459. Thread.Sleep(_WaitSuction);
  460. return true;
  461. }
  462. else
  463. {
  464. string node = string.Format(closeNodeId, _PickInfo.Blow);
  465. if (!Plc.WriteNode<bool>(node, true))
  466. {
  467. return false;
  468. }
  469. Thread.Sleep(_WaitBlow);
  470. return true;
  471. }
  472. }
  473. catch (Exception ex)
  474. {
  475. LogHelper.WriteLogError("执行XYZU平台,真空操作时出错!", ex);
  476. return false;
  477. }
  478. }
  479. public Task<bool> CalibOutIOAsync(bool state)
  480. {
  481. return Task.Run(() => CalibOutIO(state));
  482. }
  483. public bool CalibParame(PickInfo Pick, int Speed, int Accel, bool Power, int WaitSuction, int WaitBlow)
  484. {
  485. return false;
  486. }
  487. private PickInfo _PickInfo = new PickInfo();
  488. private int _WaitSuction=100, _WaitBlow=100;
  489. public async Task<bool> CalibParameAsync(PickInfo Pick, int Speed, int Accel, bool Power, int WaitSuction, int WaitBlow)
  490. {
  491. if (Plc == null || !Plc.IsConnected) return false;
  492. try
  493. {
  494. _PickInfo = Pick;
  495. _WaitSuction = WaitSuction;
  496. _WaitBlow=WaitBlow;
  497. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  498. foreach (var axis in Axes)
  499. {
  500. if (string.IsNullOrWhiteSpace(axis.Parameter.ManuVelocityNode)) continue;
  501. string nodeid = axis.Parameter.ManuVelocityNode;
  502. float value = Speed;
  503. keyValues.Add(nodeid, value);
  504. }
  505. // 2. 写入速度给所有轴
  506. if (!Plc.WriteNodes(keyValues))
  507. {
  508. return false;
  509. }
  510. return true;
  511. }
  512. catch (Exception ex)
  513. {
  514. LogHelper.WriteLogError("为XYZU平台设置速度时出错!", ex);
  515. return false;
  516. }
  517. }
  518. /// <summary>
  519. /// 阻塞式等待运动完成
  520. /// </summary>
  521. /// <param name="position"></param>
  522. /// <returns></returns>
  523. private bool WaitMoveFinished(RPoint position)
  524. {
  525. if (Plc == null || !Plc.IsConnected) return false;
  526. try
  527. {
  528. CanExecute = false;
  529. Motor(true);
  530. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  531. // 1. 写入目标位置到各轴的 ManuPositionNode
  532. keyValues = new Dictionary<string, object>();
  533. foreach (var axis in Axes)
  534. {
  535. if (string.IsNullOrWhiteSpace(axis.Parameter.ManuPositionNode)) continue;
  536. string nodeid = axis.Parameter.ManuPositionNode;
  537. float value = 0;
  538. switch (axis.Name)
  539. {
  540. case "X": value = position.X; break;
  541. case "Y": value = position.Y; break;
  542. case "Z": value = position.Z; break;
  543. case "U": value = position.U; break;
  544. default: value = 0; break;
  545. }
  546. keyValues.Add(nodeid, value);
  547. }
  548. // 2. 写入位置给所有轴
  549. if (!Plc.WriteNodes(keyValues))
  550. {
  551. return false;
  552. }
  553. // 3. 写入开始移动命令给所有轴
  554. if (!StartMove())
  555. {
  556. return false;
  557. }
  558. // 准备停滞检测:收集所有实际位置节点
  559. var actNodes = Axes.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode))
  560. .Select(a => a.State.ActPositionNode)
  561. .Distinct()
  562. .ToArray();
  563. // lastPos 存储上一次读取到的位置,lastChange 存储上次发生“实质性”变化的时间
  564. Dictionary<string, float> lastPos = new Dictionary<string, float>();
  565. Dictionary<string, DateTime> lastChange = new Dictionary<string, DateTime>();
  566. foreach (var node in actNodes)
  567. {
  568. lastPos[node] = float.NaN;
  569. lastChange[node] = DateTime.UtcNow;
  570. }
  571. const float movementThreshold = 0.01f; // 判断位置变化的阈值,避免噪声
  572. Stopwatch sw = new Stopwatch();
  573. sw.Start();
  574. while (true)
  575. {
  576. // 先读取各轴的实际位置,用于停滞检测
  577. Dictionary<string, object> posRead = new Dictionary<string, object>();
  578. try
  579. {
  580. if (actNodes.Length > 0)
  581. {
  582. posRead = Plc.ReadNodes(actNodes);
  583. }
  584. }
  585. catch
  586. {
  587. // 如果读取失败,继续让 CheckMoveFinished 来处理状态或超时
  588. }
  589. var now = DateTime.UtcNow;
  590. // 更新每个节点的变化时间:只要任意一个轴在最近 Timeout 时间内有变化,就视为系统仍在运动
  591. foreach (var node in actNodes)
  592. {
  593. float actual = 0;
  594. if (posRead != null && posRead.ContainsKey(node))
  595. {
  596. var raw = posRead[node];
  597. if (raw != null)
  598. {
  599. try { actual = Convert.ToSingle(raw); } catch { /* 保持 actual = 0 */ }
  600. }
  601. }
  602. if (float.IsNaN(lastPos[node]))
  603. {
  604. lastPos[node] = actual;
  605. lastChange[node] = now;
  606. }
  607. else
  608. {
  609. if (Math.Abs(actual - lastPos[node]) > movementThreshold)
  610. {
  611. // 有实质性变化,更新记录时间和值
  612. lastPos[node] = actual;
  613. lastChange[node] = now;
  614. }
  615. // 否则保持 lastChange 不变(表示该轴最近一次变化的时间)
  616. }
  617. }
  618. // 判断是否至少有一个轴在最近 Timeout 时间内发生过变化(即认为还在运动)
  619. bool anyAxisMovedRecently = actNodes.Any(node => (now - lastChange[node]).TotalMilliseconds <= 1000);
  620. // 如果没有任何轴在最近 Timeout 时间内发生变化,则认为出现停滞异常
  621. if (!anyAxisMovedRecently && actNodes.Length > 0)
  622. {
  623. StopMove();
  624. LogHelper.WriteLogInfo($"轴停滞超时(整体判定),目标位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U},超时阈值(ms)={Timeout}");
  625. return false;
  626. }
  627. // 检查是否整体到位或有错误(保留原有逻辑)
  628. var (isFinished, isError) = CheckMoveFinished(position);
  629. if (isFinished)
  630. {
  631. StopMove();
  632. if (isError)
  633. {
  634. LogHelper.WriteLogInfo($"机器人执行移动时发生错误,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  635. return false;
  636. }
  637. return true;
  638. }
  639. // 检查整体超时(防止一直有抖动导致 anyAxisMovedRecently 一直为 true)
  640. if (sw.ElapsedMilliseconds > 60000) // 保守超时,一分钟,可根据需求调整
  641. {
  642. LogHelper.WriteLogInfo($"机器人执行移动超时,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  643. StopMove();
  644. return false;
  645. }
  646. Thread.Sleep(10);
  647. }
  648. }
  649. catch (Exception ex)
  650. {
  651. LogHelper.WriteLogError("执行XYZU平台,阻塞式等待运动完成时出错!", ex);
  652. CanExecute = true;
  653. return false;
  654. }
  655. finally
  656. {
  657. CanExecute = true;
  658. }
  659. }
  660. /// <summary>
  661. /// 开始运动
  662. /// </summary>
  663. /// <returns></returns>
  664. private bool StartMove()
  665. {
  666. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  667. // 1. 复位所有轴的开始移动命令
  668. foreach (var axis in Axes)
  669. {
  670. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  671. {
  672. keyValues.Add(axis.Command.ManuPositionNode, true);
  673. }
  674. }
  675. return Plc.WriteNodes(keyValues);
  676. }
  677. /// <summary>
  678. /// 停止运动
  679. /// </summary>
  680. /// <returns></returns>
  681. private bool StopMove()
  682. {
  683. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  684. // 1. 复位所有轴的开始移动命令
  685. foreach (var axis in Axes)
  686. {
  687. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  688. {
  689. keyValues.Add(axis.Command.ManuPositionNode, false);
  690. }
  691. if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  692. {
  693. keyValues.Add(axis.Command.StopNode, true);
  694. }
  695. }
  696. bool result = Plc.WriteNodes(keyValues);
  697. // 异步等待100ms后复位停止命令
  698. //Task.Run(async () =>
  699. //{
  700. // await Task.Delay(100);
  701. Thread.Sleep(50);
  702. Dictionary<string, object> resetValues = new Dictionary<string, object>();
  703. foreach (var axis in Axes)
  704. {
  705. if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  706. {
  707. resetValues.Add(axis.Command.StopNode, false);
  708. }
  709. }
  710. Plc.WriteNodes(resetValues);
  711. //});
  712. return result;
  713. }
  714. /// <summary>
  715. /// 检查运动是否结束,返回是否停止、是否有错误
  716. /// </summary>
  717. /// <param name="position"></param>
  718. /// <returns></returns>
  719. private (bool isFinished, bool isError) CheckMoveFinished(RPoint position)
  720. {
  721. //检查各轴是否到位和目标位置一致
  722. //批量获取所有轴的定位状态和位置、是否错误
  723. var nodeIds = new List<string>();
  724. foreach (var axis in Axes)
  725. {
  726. if (!string.IsNullOrWhiteSpace(axis.State.PosOKNode))
  727. {
  728. nodeIds.Add(axis.State.PosOKNode);
  729. }
  730. if (!string.IsNullOrWhiteSpace(axis.State.ActPositionNode))
  731. {
  732. nodeIds.Add(axis.State.ActPositionNode);
  733. }
  734. if (!string.IsNullOrWhiteSpace(axis.State.ErrorNode))
  735. {
  736. nodeIds.Add(axis.State.ErrorNode);
  737. }
  738. if (!string.IsNullOrWhiteSpace(axis.State.PausedNode))
  739. {
  740. nodeIds.Add(axis.State.PausedNode);
  741. }
  742. }
  743. var res = Plc.ReadNodes(nodeIds.ToArray());
  744. bool allOk = true;
  745. bool isAnyError = false;
  746. foreach (var axis in Axes)
  747. {
  748. bool posOk = false;
  749. float actualPos = 0;
  750. bool isError = false;
  751. //获取此轴的定位状态、实际位置、错误状态
  752. if (res.ContainsKey(axis.State.PosOKNode))
  753. {
  754. posOk = (bool)res[axis.State.PosOKNode];
  755. }
  756. if (res.ContainsKey(axis.State.ActPositionNode))
  757. {
  758. try { actualPos = Convert.ToSingle(res[axis.State.ActPositionNode]); } catch { }
  759. }
  760. if (res.ContainsKey(axis.State.ErrorNode))
  761. {
  762. isError = (bool)res[axis.State.ErrorNode];
  763. }
  764. if (res.ContainsKey(axis.State.PausedNode))
  765. {
  766. isError = (bool)res[axis.State.PausedNode];
  767. }
  768. if (isError)
  769. {
  770. isAnyError = true;
  771. break;
  772. }
  773. //检查是否到位和位置一致
  774. float targetPos = 0;
  775. switch (axis.Name)
  776. {
  777. case "X": targetPos = position.X; break;
  778. case "Y": targetPos = position.Y; break;
  779. case "Z": targetPos = position.Z; break;
  780. case "U": targetPos = position.U; break;
  781. default: targetPos = 0; break;
  782. }
  783. //如果定位完成且位置一致,则此轴完成,如果有错误则失败
  784. if (!(posOk && Math.Abs(actualPos - targetPos) < 0.02))
  785. {
  786. if (isError)
  787. {
  788. isAnyError = true;
  789. break;
  790. }
  791. allOk = false;
  792. break;
  793. }
  794. }
  795. return (allOk, isAnyError);
  796. }
  797. /// <summary>
  798. /// 检查单个附加轴是否结束,返回是否停止、是否有错误
  799. /// </summary>
  800. /// <param name="axis"></param>
  801. /// <param name="targetPos"></param>
  802. /// <returns></returns>
  803. private (bool isFinished, bool isError) CheckAdditionalAxisMoveFinished(AxisExtended axis, double targetPos)
  804. {
  805. //读取实际位置和到位状态
  806. bool posOk = false;
  807. float actualPos = 0;
  808. bool isError = false;
  809. var res = Plc.ReadNodes(new string[] { axis.State.PosOKNode, axis.State.ActPositionNode, axis.State.ErrorNode, axis.State.PausedNode });
  810. if (res.ContainsKey(axis.State.PosOKNode))
  811. {
  812. posOk = (bool)res[axis.State.PosOKNode];
  813. }
  814. if (res.ContainsKey(axis.State.ActPositionNode))
  815. {
  816. try { actualPos = Convert.ToSingle(res[axis.State.ActPositionNode]); } catch { }
  817. }
  818. if (res.ContainsKey(axis.State.ErrorNode))
  819. {
  820. isError = (bool)res[axis.State.ErrorNode];
  821. }
  822. if (res.ContainsKey(axis.State.PausedNode))
  823. {
  824. isError = (bool)res[axis.State.PausedNode];
  825. }
  826. //检查是否到位和位置一致
  827. if (isError)
  828. {
  829. return (true, true);
  830. }
  831. if (posOk && Math.Abs(actualPos - targetPos) < 0.02)
  832. {
  833. return (true, false);
  834. }
  835. return (false, false);
  836. }
  837. /// <summary>
  838. /// 附加轴使能操作
  839. /// </summary>
  840. /// <param name="axisName"></param>
  841. /// <param name="state"></param>
  842. /// <returns></returns>
  843. public bool AdditionalAxisMotor(string axisName, bool state)
  844. {
  845. var axis = AdditionalAxisList.FirstOrDefault(a => a.Name.Equals(axisName, StringComparison.OrdinalIgnoreCase));
  846. if (axis == null) return false;
  847. if (Plc == null || !Plc.IsConnected) return false;
  848. try
  849. {
  850. if (!string.IsNullOrWhiteSpace(axis.Command.PowerNode))
  851. {
  852. return Plc.WriteNode(axis.Command.PowerNode, state);
  853. }
  854. return false;
  855. }
  856. catch (Exception ex)
  857. {
  858. LogHelper.WriteLogError("执行附加轴使能操作时出错!", ex);
  859. return false;
  860. }
  861. }
  862. //附加轴使能操作,异步方法
  863. public Task<bool> AdditionalAxisMotorAsync(string axisName, bool state)
  864. {
  865. return Task.Run(() => AdditionalAxisMotor(axisName, state));
  866. }
  867. /// <summary>
  868. /// 附加轴,阻塞式等待运动完成
  869. /// </summary>
  870. /// <param name="axisName"></param>
  871. /// <param name="targetPos"></param>
  872. /// <returns></returns>
  873. public bool AdditionalAxisMove(string axisName, double targetPos)
  874. {
  875. var axis = AdditionalAxisList.FirstOrDefault(a => a.Name.Equals(axisName, StringComparison.OrdinalIgnoreCase));
  876. if (axis == null) return false;
  877. if (Plc == null || !Plc.IsConnected) return false;
  878. try
  879. {
  880. CanExecute = false;
  881. AdditionalAxisMotor(axis.Name, true);
  882. //写入目标位置
  883. if (!string.IsNullOrWhiteSpace(axis.Parameter.ManuPositionNode))
  884. {
  885. Plc.WriteNode(axis.Parameter.ManuPositionNode, (float)targetPos);
  886. }
  887. //开始移动
  888. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  889. {
  890. Plc.WriteNode(axis.Command.ManuPositionNode, true);
  891. }
  892. //准备停滞检测:收集所有实际位置节点
  893. float lastPos = float.NaN;
  894. DateTime lastChange = DateTime.UtcNow;
  895. const float movementThreshold = 0.01f; // 判断位置变化的阈值,避免噪声
  896. Stopwatch sw = new Stopwatch();
  897. sw.Start();
  898. while (true)
  899. {
  900. var now = DateTime.UtcNow;
  901. // 先读取轴的实际位置,用于停滞检测
  902. var actual = Plc.ReadNode<float>(axis.State.ActPositionNode);
  903. if (float.IsNaN(lastPos))
  904. {
  905. lastPos = actual;
  906. lastChange = now;
  907. }
  908. else
  909. {
  910. if (Math.Abs(actual - lastPos) > movementThreshold)
  911. {
  912. // 有实质性变化,更新记录时间和值
  913. lastPos = actual;
  914. lastChange = now;
  915. }
  916. // 否则保持 lastChange 不变(表示该轴最近一次变化的时间)
  917. }
  918. // 判断是否至少有一个轴在最近 Timeout 时间内发生过变化(即认为还在运动)
  919. bool anyAxisMovedRecently = (now - lastChange).TotalMilliseconds <= 1000;
  920. // 如果没有任何轴在最近 Timeout 时间内发生变化,则认为出现停滞异常
  921. if (!anyAxisMovedRecently)
  922. {
  923. //停止移动
  924. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  925. {
  926. Plc.WriteNode(axis.Command.ManuPositionNode, false);
  927. }
  928. return false;
  929. }
  930. // 检查是否整体到位或有错误(保留原有逻辑)
  931. var (isFinished, isError) = CheckAdditionalAxisMoveFinished(axis, targetPos);
  932. if (isFinished)
  933. {
  934. //停止移动
  935. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  936. {
  937. Plc.WriteNode(axis.Command.ManuPositionNode, false);
  938. }
  939. if (isError)
  940. {
  941. return false;
  942. }
  943. return true;
  944. }
  945. // 检查整体超时(防止一直有抖动导致 anyAxisMovedRecently 一直为 true)
  946. if (sw.ElapsedMilliseconds > 60000) // 保守超时,一分钟,可根据需求调整
  947. {
  948. //停止移动
  949. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  950. {
  951. Plc.WriteNode(axis.Command.ManuPositionNode, false);
  952. }
  953. return false;
  954. }
  955. Thread.Sleep(10);
  956. }
  957. }
  958. catch (Exception ex)
  959. {
  960. LogHelper.WriteLogError("执行附加轴移动时出错!", ex);
  961. return false;
  962. }
  963. finally
  964. {
  965. CanExecute = true;
  966. }
  967. }
  968. /// <summary>
  969. /// 附加轴,阻塞式等待运动完成,异步方法
  970. /// </summary>
  971. /// <param name="axisName"></param>
  972. /// <param name="targetPos"></param>
  973. /// <returns></returns>
  974. public Task<bool> AdditionalAxisMoveAsync(string axisName, double targetPos)
  975. {
  976. return Task.Run(() => AdditionalAxisMove(axisName, targetPos));
  977. }
  978. /// <summary>
  979. /// 附加轴Jog+点动
  980. /// </summary>
  981. /// <param name="axisName"></param>
  982. /// <param name="distance"></param>
  983. /// <returns></returns>
  984. public bool AdditionalAxisJog(string axisName, double distance)
  985. {
  986. var axis = AdditionalAxisList.FirstOrDefault(a => a.Name.Equals(axisName, StringComparison.OrdinalIgnoreCase));
  987. if (axis == null) return false;
  988. if (Plc == null || !Plc.IsConnected) return false;
  989. try
  990. {
  991. CanExecute = false;
  992. // 先读取轴的实际位置,用于停滞检测
  993. var actual = Plc.ReadNode<float>(axis.State.ActPositionNode);
  994. //计算目标位置
  995. double targetPos = actual + distance;
  996. AdditionalAxisMotor(axis.Name, true);
  997. return AdditionalAxisMove(axis.Name, targetPos);
  998. }
  999. catch (Exception ex)
  1000. {
  1001. LogHelper.WriteLogError("执行附加轴点动时出错!", ex);
  1002. return false;
  1003. }
  1004. finally
  1005. {
  1006. CanExecute = true;
  1007. }
  1008. }
  1009. /// <summary>
  1010. /// 附加轴Jog-点动
  1011. /// </summary>
  1012. /// <param name="axisName"></param>
  1013. /// <param name="distance"></param>
  1014. /// <returns></returns>
  1015. public bool AdditionalAxisJogNeg(string axisName, double distance)
  1016. {
  1017. return AdditionalAxisJog(axisName, -distance);
  1018. }
  1019. /// <summary>
  1020. /// 附加轴异步 Jog+点动
  1021. /// </summary>
  1022. /// <param name="axisName"></param>
  1023. /// <param name="distance"></param>
  1024. /// <returns></returns>
  1025. public Task<bool> AdditionalAxisJogAsync(string axisName, double distance)
  1026. {
  1027. return Task.Run(() => AdditionalAxisJog(axisName, distance));
  1028. }
  1029. /// <summary>
  1030. /// 附加轴异步 Jog-点动
  1031. /// </summary>
  1032. /// <param name="axisName"></param>
  1033. /// <param name="distance"></param>
  1034. /// <returns></returns>
  1035. public Task<bool> AdditionalAxisJogNegAsync(string axisName, double distance)
  1036. {
  1037. return Task.Run(() => AdditionalAxisJogNeg(axisName, distance));
  1038. }
  1039. #endregion
  1040. #region 收发数据
  1041. public string SendAndReceive(string send) => string.Empty;
  1042. public Task<string> SendAndReceiveAsync(string send) => Task.FromResult(string.Empty);
  1043. public string SendAndReceive(ITcpSessionClient client, string send) => string.Empty;
  1044. public Task<string> SendAndReceiveAsync(ITcpSessionClient client, string send) => Task.FromResult(string.Empty);
  1045. public void Send(string send) { }
  1046. public Task SendAsync(string send) => Task.CompletedTask;
  1047. public void Send(ITcpSessionClient client, string send) { }
  1048. public Task SendAsync(ITcpSessionClient client, string send) => Task.CompletedTask;
  1049. public Encoding GetEncoding() => Encoding.Default;
  1050. #endregion
  1051. #region 属性通知
  1052. public event PropertyChangedEventHandler PropertyChanged;
  1053. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  1054. {
  1055. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  1056. storage = value;
  1057. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  1058. return true;
  1059. }
  1060. protected void OnPropertyChanged(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args);
  1061. #endregion
  1062. #region IRobot SetTool/SelectTool stubs
  1063. public bool SetTool(int index, double x, double y) => true;
  1064. public Task<bool> SetToolAsync(int index, double x, double y) => Task.FromResult(true);
  1065. public bool SelectTool(int index) => true;
  1066. public Task<bool> SelectToolAsync(int index) => Task.FromResult(true);
  1067. #endregion
  1068. }
  1069. }