XYZU_Robot.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  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. return true;
  633. }
  634. if (isError)
  635. {
  636. StopMove();
  637. LogHelper.WriteLogInfo($"机器人执行移动时发生错误,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  638. return false;
  639. }
  640. // 检查整体超时(防止一直有抖动导致 anyAxisMovedRecently 一直为 true)
  641. if (sw.ElapsedMilliseconds > 60000) // 保守超时,一分钟,可根据需求调整
  642. {
  643. LogHelper.WriteLogInfo($"机器人执行移动超时,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  644. StopMove();
  645. return false;
  646. }
  647. Thread.Sleep(10);
  648. }
  649. }
  650. catch (Exception ex)
  651. {
  652. LogHelper.WriteLogError("执行XYZU平台,阻塞式等待运动完成时出错!", ex);
  653. CanExecute = true;
  654. return false;
  655. }
  656. finally
  657. {
  658. CanExecute = true;
  659. }
  660. }
  661. /// <summary>
  662. /// 开始运动
  663. /// </summary>
  664. /// <returns></returns>
  665. private bool StartMove()
  666. {
  667. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  668. // 1. 复位所有轴的开始移动命令
  669. foreach (var axis in Axes)
  670. {
  671. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  672. {
  673. keyValues.Add(axis.Command.ManuPositionNode, true);
  674. }
  675. }
  676. return Plc.WriteNodes(keyValues);
  677. }
  678. /// <summary>
  679. /// 停止运动
  680. /// </summary>
  681. /// <returns></returns>
  682. private bool StopMove()
  683. {
  684. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  685. // 1. 复位所有轴的开始移动命令
  686. foreach (var axis in Axes)
  687. {
  688. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  689. {
  690. keyValues.Add(axis.Command.ManuPositionNode, false);
  691. }
  692. //if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  693. //{
  694. // keyValues.Add(axis.Command.StopNode, true);
  695. //}
  696. }
  697. bool result = Plc.WriteNodes(keyValues);
  698. // 异步等待100ms后复位停止命令
  699. //Task.Run(async () =>
  700. //{
  701. // await Task.Delay(100);
  702. //Thread.Sleep(50);
  703. //Dictionary<string, object> resetValues = new Dictionary<string, object>();
  704. //foreach (var axis in Axes)
  705. //{
  706. // if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  707. // {
  708. // resetValues.Add(axis.Command.StopNode, false);
  709. // }
  710. //}
  711. //Plc.WriteNodes(resetValues);
  712. //});
  713. return result;
  714. }
  715. /// <summary>
  716. /// 检查运动是否结束,返回是否停止、是否有错误
  717. /// </summary>
  718. /// <param name="position"></param>
  719. /// <returns></returns>
  720. private (bool isFinished, bool isError) CheckMoveFinished(RPoint position)
  721. {
  722. //检查各轴是否到位和目标位置一致
  723. //批量获取所有轴的定位状态和位置、是否错误
  724. var nodeIds = new List<string>();
  725. foreach (var axis in Axes)
  726. {
  727. if (!string.IsNullOrWhiteSpace(axis.State.PosOKNode))
  728. {
  729. nodeIds.Add(axis.State.PosOKNode);
  730. }
  731. if (!string.IsNullOrWhiteSpace(axis.State.ActPositionNode))
  732. {
  733. nodeIds.Add(axis.State.ActPositionNode);
  734. }
  735. if (!string.IsNullOrWhiteSpace(axis.State.ErrorNode))
  736. {
  737. nodeIds.Add(axis.State.ErrorNode);
  738. }
  739. if (!string.IsNullOrWhiteSpace(axis.State.PausedNode))
  740. {
  741. nodeIds.Add(axis.State.PausedNode);
  742. }
  743. }
  744. var res = Plc.ReadNodes(nodeIds.ToArray());
  745. bool allOk = true;
  746. bool isAnyError = false;
  747. foreach (var axis in Axes)
  748. {
  749. bool posOk = false;
  750. float actualPos = 0;
  751. bool isError = false;
  752. //获取此轴的定位状态、实际位置、错误状态
  753. if (res.ContainsKey(axis.State.PosOKNode))
  754. {
  755. posOk = (bool)res[axis.State.PosOKNode];
  756. }
  757. if (res.ContainsKey(axis.State.ActPositionNode))
  758. {
  759. try { actualPos = Convert.ToSingle(res[axis.State.ActPositionNode]); } catch { }
  760. }
  761. if (res.ContainsKey(axis.State.ErrorNode))
  762. {
  763. isError = (bool)res[axis.State.ErrorNode];
  764. }
  765. if (res.ContainsKey(axis.State.PausedNode))
  766. {
  767. isError = (bool)res[axis.State.PausedNode];
  768. }
  769. //if (isError)
  770. //{
  771. // isAnyError = true;
  772. // break;
  773. //}
  774. //检查是否到位和位置一致
  775. float targetPos = 0;
  776. switch (axis.Name)
  777. {
  778. case "X": targetPos = position.X; break;
  779. case "Y": targetPos = position.Y; break;
  780. case "Z": targetPos = position.Z; break;
  781. case "U": targetPos = position.U; break;
  782. default: targetPos = 0; break;
  783. }
  784. //如果定位完成且位置一致,则此轴完成,如果有错误则失败
  785. if (!(Math.Abs(actualPos - targetPos) < 0.02))
  786. {
  787. //if (isError)
  788. //{
  789. // isAnyError = true;
  790. // break;
  791. //}
  792. allOk = false;
  793. break;
  794. }
  795. }
  796. return (allOk, isAnyError);
  797. }
  798. /// <summary>
  799. /// 检查单个附加轴是否结束,返回是否停止、是否有错误
  800. /// </summary>
  801. /// <param name="axis"></param>
  802. /// <param name="targetPos"></param>
  803. /// <returns></returns>
  804. private (bool isFinished, bool isError) CheckAdditionalAxisMoveFinished(AxisExtended axis, double targetPos)
  805. {
  806. //读取实际位置和到位状态
  807. bool posOk = false;
  808. float actualPos = 0;
  809. bool isError = false;
  810. var res = Plc.ReadNodes(new string[] { axis.State.PosOKNode, axis.State.ActPositionNode, axis.State.ErrorNode, axis.State.PausedNode });
  811. if (res.ContainsKey(axis.State.PosOKNode))
  812. {
  813. posOk = (bool)res[axis.State.PosOKNode];
  814. }
  815. if (res.ContainsKey(axis.State.ActPositionNode))
  816. {
  817. try { actualPos = Convert.ToSingle(res[axis.State.ActPositionNode]); } catch { }
  818. }
  819. if (res.ContainsKey(axis.State.ErrorNode))
  820. {
  821. isError = (bool)res[axis.State.ErrorNode];
  822. }
  823. if (res.ContainsKey(axis.State.PausedNode))
  824. {
  825. isError = (bool)res[axis.State.PausedNode];
  826. }
  827. //检查是否到位和位置一致
  828. //if (isError)
  829. //{
  830. // return (true, true);
  831. //}
  832. if (Math.Abs(actualPos - targetPos) < 0.02)
  833. {
  834. return (true, false);
  835. }
  836. return (false, false);
  837. }
  838. /// <summary>
  839. /// 附加轴使能操作
  840. /// </summary>
  841. /// <param name="axisName"></param>
  842. /// <param name="state"></param>
  843. /// <returns></returns>
  844. public bool AdditionalAxisMotor(string axisName, bool state)
  845. {
  846. var axis = AdditionalAxisList.FirstOrDefault(a => a.Name.Equals(axisName, StringComparison.OrdinalIgnoreCase));
  847. if (axis == null) return false;
  848. if (Plc == null || !Plc.IsConnected) return false;
  849. try
  850. {
  851. if (!string.IsNullOrWhiteSpace(axis.Command.PowerNode))
  852. {
  853. return Plc.WriteNode(axis.Command.PowerNode, state);
  854. }
  855. return false;
  856. }
  857. catch (Exception ex)
  858. {
  859. LogHelper.WriteLogError("执行附加轴使能操作时出错!", ex);
  860. return false;
  861. }
  862. }
  863. //附加轴使能操作,异步方法
  864. public Task<bool> AdditionalAxisMotorAsync(string axisName, bool state)
  865. {
  866. return Task.Run(() => AdditionalAxisMotor(axisName, state));
  867. }
  868. /// <summary>
  869. /// 附加轴,阻塞式等待运动完成
  870. /// </summary>
  871. /// <param name="axisName"></param>
  872. /// <param name="targetPos"></param>
  873. /// <returns></returns>
  874. public bool AdditionalAxisMove(string axisName, double targetPos)
  875. {
  876. var axis = AdditionalAxisList.FirstOrDefault(a => a.Name.Equals(axisName, StringComparison.OrdinalIgnoreCase));
  877. if (axis == null) return false;
  878. if (Plc == null || !Plc.IsConnected) return false;
  879. try
  880. {
  881. CanExecute = false;
  882. AdditionalAxisMotor(axis.Name, true);
  883. //写入目标位置
  884. if (!string.IsNullOrWhiteSpace(axis.Parameter.ManuPositionNode))
  885. {
  886. Plc.WriteNode(axis.Parameter.ManuPositionNode, (float)targetPos);
  887. }
  888. //开始移动
  889. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  890. {
  891. Plc.WriteNode(axis.Command.ManuPositionNode, true);
  892. }
  893. //准备停滞检测:收集所有实际位置节点
  894. float lastPos = float.NaN;
  895. DateTime lastChange = DateTime.UtcNow;
  896. const float movementThreshold = 0.01f; // 判断位置变化的阈值,避免噪声
  897. Stopwatch sw = new Stopwatch();
  898. sw.Start();
  899. while (true)
  900. {
  901. var now = DateTime.UtcNow;
  902. // 先读取轴的实际位置,用于停滞检测
  903. var actual = Plc.ReadNode<float>(axis.State.ActPositionNode);
  904. if (float.IsNaN(lastPos))
  905. {
  906. lastPos = actual;
  907. lastChange = now;
  908. }
  909. else
  910. {
  911. if (Math.Abs(actual - lastPos) > movementThreshold)
  912. {
  913. // 有实质性变化,更新记录时间和值
  914. lastPos = actual;
  915. lastChange = now;
  916. }
  917. // 否则保持 lastChange 不变(表示该轴最近一次变化的时间)
  918. }
  919. // 判断是否至少有一个轴在最近 Timeout 时间内发生过变化(即认为还在运动)
  920. bool anyAxisMovedRecently = (now - lastChange).TotalMilliseconds <= 1000;
  921. // 如果没有任何轴在最近 Timeout 时间内发生变化,则认为出现停滞异常
  922. if (!anyAxisMovedRecently)
  923. {
  924. //停止移动
  925. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  926. {
  927. Plc.WriteNode(axis.Command.ManuPositionNode, false);
  928. }
  929. return false;
  930. }
  931. // 检查是否整体到位或有错误(保留原有逻辑)
  932. var (isFinished, isError) = CheckAdditionalAxisMoveFinished(axis, targetPos);
  933. if (isFinished)
  934. {
  935. //停止移动
  936. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  937. {
  938. Plc.WriteNode(axis.Command.ManuPositionNode, false);
  939. }
  940. if (isError)
  941. {
  942. return false;
  943. }
  944. return true;
  945. }
  946. // 检查整体超时(防止一直有抖动导致 anyAxisMovedRecently 一直为 true)
  947. if (sw.ElapsedMilliseconds > 60000) // 保守超时,一分钟,可根据需求调整
  948. {
  949. //停止移动
  950. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  951. {
  952. Plc.WriteNode(axis.Command.ManuPositionNode, false);
  953. }
  954. return false;
  955. }
  956. Thread.Sleep(10);
  957. }
  958. }
  959. catch (Exception ex)
  960. {
  961. LogHelper.WriteLogError("执行附加轴移动时出错!", ex);
  962. return false;
  963. }
  964. finally
  965. {
  966. CanExecute = true;
  967. }
  968. }
  969. /// <summary>
  970. /// 附加轴,阻塞式等待运动完成,异步方法
  971. /// </summary>
  972. /// <param name="axisName"></param>
  973. /// <param name="targetPos"></param>
  974. /// <returns></returns>
  975. public Task<bool> AdditionalAxisMoveAsync(string axisName, double targetPos)
  976. {
  977. return Task.Run(() => AdditionalAxisMove(axisName, targetPos));
  978. }
  979. /// <summary>
  980. /// 附加轴Jog+点动
  981. /// </summary>
  982. /// <param name="axisName"></param>
  983. /// <param name="distance"></param>
  984. /// <returns></returns>
  985. public bool AdditionalAxisJog(string axisName, double distance)
  986. {
  987. var axis = AdditionalAxisList.FirstOrDefault(a => a.Name.Equals(axisName, StringComparison.OrdinalIgnoreCase));
  988. if (axis == null) return false;
  989. if (Plc == null || !Plc.IsConnected) return false;
  990. try
  991. {
  992. CanExecute = false;
  993. // 先读取轴的实际位置,用于停滞检测
  994. var actual = Plc.ReadNode<float>(axis.State.ActPositionNode);
  995. //计算目标位置
  996. double targetPos = actual + distance;
  997. AdditionalAxisMotor(axis.Name, true);
  998. return AdditionalAxisMove(axis.Name, targetPos);
  999. }
  1000. catch (Exception ex)
  1001. {
  1002. LogHelper.WriteLogError("执行附加轴点动时出错!", ex);
  1003. return false;
  1004. }
  1005. finally
  1006. {
  1007. CanExecute = true;
  1008. }
  1009. }
  1010. /// <summary>
  1011. /// 附加轴Jog-点动
  1012. /// </summary>
  1013. /// <param name="axisName"></param>
  1014. /// <param name="distance"></param>
  1015. /// <returns></returns>
  1016. public bool AdditionalAxisJogNeg(string axisName, double distance)
  1017. {
  1018. return AdditionalAxisJog(axisName, -distance);
  1019. }
  1020. /// <summary>
  1021. /// 附加轴异步 Jog+点动
  1022. /// </summary>
  1023. /// <param name="axisName"></param>
  1024. /// <param name="distance"></param>
  1025. /// <returns></returns>
  1026. public Task<bool> AdditionalAxisJogAsync(string axisName, double distance)
  1027. {
  1028. return Task.Run(() => AdditionalAxisJog(axisName, distance));
  1029. }
  1030. /// <summary>
  1031. /// 附加轴异步 Jog-点动
  1032. /// </summary>
  1033. /// <param name="axisName"></param>
  1034. /// <param name="distance"></param>
  1035. /// <returns></returns>
  1036. public Task<bool> AdditionalAxisJogNegAsync(string axisName, double distance)
  1037. {
  1038. return Task.Run(() => AdditionalAxisJogNeg(axisName, distance));
  1039. }
  1040. /// <summary>
  1041. /// 获取附加轴的当前坐标
  1042. /// </summary>
  1043. /// <param name="axisName"></param>
  1044. /// <returns></returns>
  1045. public float GetAdditionalAxisCurrentPos(string axisName)
  1046. {
  1047. var axis = AdditionalAxisList.FirstOrDefault(x => x.Name == axisName);
  1048. if (axis==null)
  1049. {
  1050. return 0;
  1051. }
  1052. return Plc.ReadNode<float>(axis.State.ActPositionNode);
  1053. }
  1054. /// <summary>
  1055. /// 获取附加轴的当前坐标
  1056. /// </summary>
  1057. /// <param name="axisName"></param>
  1058. /// <returns></returns>
  1059. public Task<float> GetAdditionalAxisCurrentPosAsync(string axisName)
  1060. {
  1061. return Task.Run(()=> GetAdditionalAxisCurrentPos(axisName));
  1062. }
  1063. #endregion
  1064. #region 收发数据
  1065. public string SendAndReceive(string send) => string.Empty;
  1066. public Task<string> SendAndReceiveAsync(string send) => Task.FromResult(string.Empty);
  1067. public string SendAndReceive(ITcpSessionClient client, string send) => string.Empty;
  1068. public Task<string> SendAndReceiveAsync(ITcpSessionClient client, string send) => Task.FromResult(string.Empty);
  1069. public void Send(string send) { }
  1070. public Task SendAsync(string send) => Task.CompletedTask;
  1071. public void Send(ITcpSessionClient client, string send) { }
  1072. public Task SendAsync(ITcpSessionClient client, string send) => Task.CompletedTask;
  1073. public Encoding GetEncoding() => Encoding.Default;
  1074. #endregion
  1075. #region 属性通知
  1076. public event PropertyChangedEventHandler PropertyChanged;
  1077. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  1078. {
  1079. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  1080. storage = value;
  1081. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  1082. return true;
  1083. }
  1084. protected void OnPropertyChanged(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args);
  1085. #endregion
  1086. #region IRobot SetTool/SelectTool stubs
  1087. public bool SetTool(int index, double x, double y) => true;
  1088. public Task<bool> SetToolAsync(int index, double x, double y) => Task.FromResult(true);
  1089. public bool SelectTool(int index) => true;
  1090. public Task<bool> SelectToolAsync(int index) => Task.FromResult(true);
  1091. #endregion
  1092. }
  1093. }