XYZU_Robot.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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) => false;
  446. public Task<bool> CalibOutIOAsync(bool state) => Task.FromResult(false);
  447. public bool CalibParame(PickInfo Pick, int Speed, int Accel, bool Power, int WaitSuction, int WaitBlow)
  448. {
  449. return false;
  450. }
  451. public async Task<bool> CalibParameAsync(PickInfo Pick, int Speed, int Accel, bool Power, int WaitSuction, int WaitBlow)
  452. {
  453. if (Plc == null || !Plc.IsConnected) return false;
  454. try
  455. {
  456. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  457. foreach (var axis in Axes)
  458. {
  459. if (string.IsNullOrWhiteSpace(axis.Parameter.ManuVelocityNode)) continue;
  460. string nodeid = axis.Parameter.ManuVelocityNode;
  461. float value = Speed;
  462. keyValues.Add(nodeid, value);
  463. }
  464. // 2. 写入速度给所有轴
  465. if (!Plc.WriteNodes(keyValues))
  466. {
  467. return false;
  468. }
  469. return true;
  470. }
  471. catch (Exception ex)
  472. {
  473. LogHelper.WriteLogError("为XYZU平台设置速度时出错!", ex);
  474. return false;
  475. }
  476. }
  477. /// <summary>
  478. /// 阻塞式等待运动完成
  479. /// </summary>
  480. /// <param name="position"></param>
  481. /// <returns></returns>
  482. private bool WaitMoveFinished(RPoint position)
  483. {
  484. if (Plc == null || !Plc.IsConnected) return false;
  485. try
  486. {
  487. CanExecute = false;
  488. Motor(true);
  489. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  490. // 1. 写入目标位置到各轴的 ManuPositionNode
  491. keyValues = new Dictionary<string, object>();
  492. foreach (var axis in Axes)
  493. {
  494. if (string.IsNullOrWhiteSpace(axis.Parameter.ManuPositionNode)) continue;
  495. string nodeid = axis.Parameter.ManuPositionNode;
  496. float value = 0;
  497. switch (axis.Name)
  498. {
  499. case "X": value = position.X; break;
  500. case "Y": value = position.Y; break;
  501. case "Z": value = position.Z; break;
  502. case "U": value = position.U; break;
  503. default: value = 0; break;
  504. }
  505. keyValues.Add(nodeid, value);
  506. }
  507. // 2. 写入位置给所有轴
  508. if (!Plc.WriteNodes(keyValues))
  509. {
  510. return false;
  511. }
  512. // 3. 写入开始移动命令给所有轴
  513. if (!StartMove())
  514. {
  515. return false;
  516. }
  517. // 准备停滞检测:收集所有实际位置节点
  518. var actNodes = Axes.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode))
  519. .Select(a => a.State.ActPositionNode)
  520. .Distinct()
  521. .ToArray();
  522. // lastPos 存储上一次读取到的位置,lastChange 存储上次发生“实质性”变化的时间
  523. Dictionary<string, float> lastPos = new Dictionary<string, float>();
  524. Dictionary<string, DateTime> lastChange = new Dictionary<string, DateTime>();
  525. foreach (var node in actNodes)
  526. {
  527. lastPos[node] = float.NaN;
  528. lastChange[node] = DateTime.UtcNow;
  529. }
  530. const float movementThreshold = 0.01f; // 判断位置变化的阈值,避免噪声
  531. Stopwatch sw = new Stopwatch();
  532. sw.Start();
  533. while (true)
  534. {
  535. // 先读取各轴的实际位置,用于停滞检测
  536. Dictionary<string, object> posRead = new Dictionary<string, object>();
  537. try
  538. {
  539. if (actNodes.Length > 0)
  540. {
  541. posRead = Plc.ReadNodes(actNodes);
  542. }
  543. }
  544. catch
  545. {
  546. // 如果读取失败,继续让 CheckMoveFinished 来处理状态或超时
  547. }
  548. var now = DateTime.UtcNow;
  549. // 更新每个节点的变化时间:只要任意一个轴在最近 Timeout 时间内有变化,就视为系统仍在运动
  550. foreach (var node in actNodes)
  551. {
  552. float actual = 0;
  553. if (posRead != null && posRead.ContainsKey(node))
  554. {
  555. var raw = posRead[node];
  556. if (raw != null)
  557. {
  558. try { actual = Convert.ToSingle(raw); } catch { /* 保持 actual = 0 */ }
  559. }
  560. }
  561. if (float.IsNaN(lastPos[node]))
  562. {
  563. lastPos[node] = actual;
  564. lastChange[node] = now;
  565. }
  566. else
  567. {
  568. if (Math.Abs(actual - lastPos[node]) > movementThreshold)
  569. {
  570. // 有实质性变化,更新记录时间和值
  571. lastPos[node] = actual;
  572. lastChange[node] = now;
  573. }
  574. // 否则保持 lastChange 不变(表示该轴最近一次变化的时间)
  575. }
  576. }
  577. // 判断是否至少有一个轴在最近 Timeout 时间内发生过变化(即认为还在运动)
  578. bool anyAxisMovedRecently = actNodes.Any(node => (now - lastChange[node]).TotalMilliseconds <= 1000);
  579. // 如果没有任何轴在最近 Timeout 时间内发生变化,则认为出现停滞异常
  580. if (!anyAxisMovedRecently && actNodes.Length > 0)
  581. {
  582. StopMove();
  583. LogHelper.WriteLogInfo($"轴停滞超时(整体判定),目标位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U},超时阈值(ms)={Timeout}");
  584. return false;
  585. }
  586. // 检查是否整体到位或有错误(保留原有逻辑)
  587. var (isFinished, isError) = CheckMoveFinished(position);
  588. if (isFinished)
  589. {
  590. StopMove();
  591. if (isError)
  592. {
  593. LogHelper.WriteLogInfo($"机器人执行移动时发生错误,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  594. return false;
  595. }
  596. return true;
  597. }
  598. // 检查整体超时(防止一直有抖动导致 anyAxisMovedRecently 一直为 true)
  599. if (sw.ElapsedMilliseconds > 60000) // 保守超时,一分钟,可根据需求调整
  600. {
  601. LogHelper.WriteLogInfo($"机器人执行移动超时,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  602. StopMove();
  603. return false;
  604. }
  605. Thread.Sleep(10);
  606. }
  607. }
  608. catch (Exception ex)
  609. {
  610. LogHelper.WriteLogError("执行XYZU平台,阻塞式等待运动完成时出错!", ex);
  611. CanExecute = true;
  612. return false;
  613. }
  614. finally
  615. {
  616. CanExecute = true;
  617. }
  618. }
  619. /// <summary>
  620. /// 开始运动
  621. /// </summary>
  622. /// <returns></returns>
  623. private bool StartMove()
  624. {
  625. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  626. // 1. 复位所有轴的开始移动命令
  627. foreach (var axis in Axes)
  628. {
  629. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  630. {
  631. keyValues.Add(axis.Command.ManuPositionNode, true);
  632. }
  633. }
  634. return Plc.WriteNodes(keyValues);
  635. }
  636. /// <summary>
  637. /// 停止运动
  638. /// </summary>
  639. /// <returns></returns>
  640. private bool StopMove()
  641. {
  642. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  643. // 1. 复位所有轴的开始移动命令
  644. foreach (var axis in Axes)
  645. {
  646. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  647. {
  648. keyValues.Add(axis.Command.ManuPositionNode, false);
  649. }
  650. if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  651. {
  652. keyValues.Add(axis.Command.StopNode, true);
  653. }
  654. }
  655. bool result = Plc.WriteNodes(keyValues);
  656. // 异步等待100ms后复位停止命令
  657. //Task.Run(async () =>
  658. //{
  659. // await Task.Delay(100);
  660. Thread.Sleep(50);
  661. Dictionary<string, object> resetValues = new Dictionary<string, object>();
  662. foreach (var axis in Axes)
  663. {
  664. if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  665. {
  666. resetValues.Add(axis.Command.StopNode, false);
  667. }
  668. }
  669. Plc.WriteNodes(resetValues);
  670. //});
  671. return result;
  672. }
  673. /// <summary>
  674. /// 检查运动是否结束,返回是否停止、是否有错误
  675. /// </summary>
  676. /// <param name="position"></param>
  677. /// <returns></returns>
  678. private (bool isFinished, bool isError) CheckMoveFinished(RPoint position)
  679. {
  680. //检查各轴是否到位和目标位置一致
  681. //批量获取所有轴的定位状态和位置、是否错误
  682. var nodeIds = new List<string>();
  683. foreach (var axis in Axes)
  684. {
  685. if (!string.IsNullOrWhiteSpace(axis.State.PosOKNode))
  686. {
  687. nodeIds.Add(axis.State.PosOKNode);
  688. }
  689. if (!string.IsNullOrWhiteSpace(axis.State.ActPositionNode))
  690. {
  691. nodeIds.Add(axis.State.ActPositionNode);
  692. }
  693. if (!string.IsNullOrWhiteSpace(axis.State.ErrorNode))
  694. {
  695. nodeIds.Add(axis.State.ErrorNode);
  696. }
  697. if (!string.IsNullOrWhiteSpace(axis.State.PausedNode))
  698. {
  699. nodeIds.Add(axis.State.PausedNode);
  700. }
  701. }
  702. var res = Plc.ReadNodes(nodeIds.ToArray());
  703. bool allOk = true;
  704. bool isAnyError = false;
  705. foreach (var axis in Axes)
  706. {
  707. bool posOk = false;
  708. float actualPos = 0;
  709. bool isError = false;
  710. //获取此轴的定位状态、实际位置、错误状态
  711. if (res.ContainsKey(axis.State.PosOKNode))
  712. {
  713. posOk = (bool)res[axis.State.PosOKNode];
  714. }
  715. if (res.ContainsKey(axis.State.ActPositionNode))
  716. {
  717. try { actualPos = Convert.ToSingle(res[axis.State.ActPositionNode]); } catch { }
  718. }
  719. if (res.ContainsKey(axis.State.ErrorNode))
  720. {
  721. isError = (bool)res[axis.State.ErrorNode];
  722. }
  723. if (res.ContainsKey(axis.State.PausedNode))
  724. {
  725. isError = (bool)res[axis.State.PausedNode];
  726. }
  727. if (isError)
  728. {
  729. isAnyError = true;
  730. break;
  731. }
  732. //检查是否到位和位置一致
  733. float targetPos = 0;
  734. switch (axis.Name)
  735. {
  736. case "X": targetPos = position.X; break;
  737. case "Y": targetPos = position.Y; break;
  738. case "Z": targetPos = position.Z; break;
  739. case "U": targetPos = position.U; break;
  740. default: targetPos = 0; break;
  741. }
  742. //如果定位完成且位置一致,则此轴完成,如果有错误则失败
  743. if (!(posOk && Math.Abs(actualPos - targetPos) < 0.02))
  744. {
  745. if (isError)
  746. {
  747. isAnyError = true;
  748. break;
  749. }
  750. allOk = false;
  751. break;
  752. }
  753. }
  754. return (allOk, isAnyError);
  755. }
  756. /// <summary>
  757. /// 检查单个附加轴是否结束,返回是否停止、是否有错误
  758. /// </summary>
  759. /// <param name="axis"></param>
  760. /// <param name="targetPos"></param>
  761. /// <returns></returns>
  762. private (bool isFinished, bool isError) CheckAdditionalAxisMoveFinished(AxisExtended axis, double targetPos)
  763. {
  764. //读取实际位置和到位状态
  765. bool posOk = false;
  766. float actualPos = 0;
  767. bool isError = false;
  768. var res = Plc.ReadNodes(new string[] { axis.State.PosOKNode, axis.State.ActPositionNode, axis.State.ErrorNode, axis.State.PausedNode });
  769. if (res.ContainsKey(axis.State.PosOKNode))
  770. {
  771. posOk = (bool)res[axis.State.PosOKNode];
  772. }
  773. if (res.ContainsKey(axis.State.ActPositionNode))
  774. {
  775. try { actualPos = Convert.ToSingle(res[axis.State.ActPositionNode]); } catch { }
  776. }
  777. if (res.ContainsKey(axis.State.ErrorNode))
  778. {
  779. isError = (bool)res[axis.State.ErrorNode];
  780. }
  781. if (res.ContainsKey(axis.State.PausedNode))
  782. {
  783. isError = (bool)res[axis.State.PausedNode];
  784. }
  785. //检查是否到位和位置一致
  786. if (isError)
  787. {
  788. return (true, true);
  789. }
  790. if (posOk && Math.Abs(actualPos - targetPos) < 0.02)
  791. {
  792. return (true, false);
  793. }
  794. return (false, false);
  795. }
  796. /// <summary>
  797. /// 附加轴使能操作
  798. /// </summary>
  799. /// <param name="axisName"></param>
  800. /// <param name="state"></param>
  801. /// <returns></returns>
  802. public bool AdditionalAxisMotor(string axisName, bool state)
  803. {
  804. var axis = AdditionalAxisList.FirstOrDefault(a => a.Name.Equals(axisName, StringComparison.OrdinalIgnoreCase));
  805. if (axis == null) return false;
  806. if (Plc == null || !Plc.IsConnected) return false;
  807. try
  808. {
  809. if (!string.IsNullOrWhiteSpace(axis.Command.PowerNode))
  810. {
  811. return Plc.WriteNode(axis.Command.PowerNode, state);
  812. }
  813. return false;
  814. }
  815. catch (Exception ex)
  816. {
  817. LogHelper.WriteLogError("执行附加轴使能操作时出错!", ex);
  818. return false;
  819. }
  820. }
  821. //附加轴使能操作,异步方法
  822. public Task<bool> AdditionalAxisMotorAsync(string axisName, bool state)
  823. {
  824. return Task.Run(() => AdditionalAxisMotor(axisName, state));
  825. }
  826. /// <summary>
  827. /// 附加轴,阻塞式等待运动完成
  828. /// </summary>
  829. /// <param name="axisName"></param>
  830. /// <param name="targetPos"></param>
  831. /// <returns></returns>
  832. public bool AdditionalAxisMove(string axisName, double targetPos)
  833. {
  834. var axis = AdditionalAxisList.FirstOrDefault(a => a.Name.Equals(axisName, StringComparison.OrdinalIgnoreCase));
  835. if (axis == null) return false;
  836. if (Plc == null || !Plc.IsConnected) return false;
  837. try
  838. {
  839. CanExecute = false;
  840. AdditionalAxisMotor(axis.Name, true);
  841. //写入目标位置
  842. if (!string.IsNullOrWhiteSpace(axis.Parameter.ManuPositionNode))
  843. {
  844. Plc.WriteNode(axis.Parameter.ManuPositionNode, (float)targetPos);
  845. }
  846. //开始移动
  847. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  848. {
  849. Plc.WriteNode(axis.Command.ManuPositionNode, true);
  850. }
  851. //准备停滞检测:收集所有实际位置节点
  852. float lastPos = float.NaN;
  853. DateTime lastChange = DateTime.UtcNow;
  854. const float movementThreshold = 0.01f; // 判断位置变化的阈值,避免噪声
  855. Stopwatch sw = new Stopwatch();
  856. sw.Start();
  857. while (true)
  858. {
  859. var now = DateTime.UtcNow;
  860. // 先读取轴的实际位置,用于停滞检测
  861. var actual = Plc.ReadNode<float>(axis.State.ActPositionNode);
  862. if (float.IsNaN(lastPos))
  863. {
  864. lastPos = actual;
  865. lastChange = now;
  866. }
  867. else
  868. {
  869. if (Math.Abs(actual - lastPos) > movementThreshold)
  870. {
  871. // 有实质性变化,更新记录时间和值
  872. lastPos = actual;
  873. lastChange = now;
  874. }
  875. // 否则保持 lastChange 不变(表示该轴最近一次变化的时间)
  876. }
  877. // 判断是否至少有一个轴在最近 Timeout 时间内发生过变化(即认为还在运动)
  878. bool anyAxisMovedRecently = (now - lastChange).TotalMilliseconds <= 1000;
  879. // 如果没有任何轴在最近 Timeout 时间内发生变化,则认为出现停滞异常
  880. if (!anyAxisMovedRecently)
  881. {
  882. //停止移动
  883. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  884. {
  885. Plc.WriteNode(axis.Command.ManuPositionNode, false);
  886. }
  887. return false;
  888. }
  889. // 检查是否整体到位或有错误(保留原有逻辑)
  890. var (isFinished, isError) = CheckAdditionalAxisMoveFinished(axis, targetPos);
  891. if (isFinished)
  892. {
  893. //停止移动
  894. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  895. {
  896. Plc.WriteNode(axis.Command.ManuPositionNode, false);
  897. }
  898. if (isError)
  899. {
  900. return false;
  901. }
  902. return true;
  903. }
  904. // 检查整体超时(防止一直有抖动导致 anyAxisMovedRecently 一直为 true)
  905. if (sw.ElapsedMilliseconds > 60000) // 保守超时,一分钟,可根据需求调整
  906. {
  907. //停止移动
  908. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  909. {
  910. Plc.WriteNode(axis.Command.ManuPositionNode, false);
  911. }
  912. return false;
  913. }
  914. Thread.Sleep(10);
  915. }
  916. }
  917. catch (Exception ex)
  918. {
  919. LogHelper.WriteLogError("执行附加轴移动时出错!", ex);
  920. return false;
  921. }
  922. finally
  923. {
  924. CanExecute = true;
  925. }
  926. }
  927. /// <summary>
  928. /// 附加轴,阻塞式等待运动完成,异步方法
  929. /// </summary>
  930. /// <param name="axisName"></param>
  931. /// <param name="targetPos"></param>
  932. /// <returns></returns>
  933. public Task<bool> AdditionalAxisMoveAsync(string axisName, double targetPos)
  934. {
  935. return Task.Run(() => AdditionalAxisMove(axisName, targetPos));
  936. }
  937. /// <summary>
  938. /// 附加轴Jog+点动
  939. /// </summary>
  940. /// <param name="axisName"></param>
  941. /// <param name="distance"></param>
  942. /// <returns></returns>
  943. public bool AdditionalAxisJog(string axisName, double distance)
  944. {
  945. var axis = AdditionalAxisList.FirstOrDefault(a => a.Name.Equals(axisName, StringComparison.OrdinalIgnoreCase));
  946. if (axis == null) return false;
  947. if (Plc == null || !Plc.IsConnected) return false;
  948. try
  949. {
  950. CanExecute = false;
  951. // 先读取轴的实际位置,用于停滞检测
  952. var actual = Plc.ReadNode<float>(axis.State.ActPositionNode);
  953. //计算目标位置
  954. double targetPos = actual + distance;
  955. AdditionalAxisMotor(axis.Name, true);
  956. return AdditionalAxisMove(axis.Name, targetPos);
  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. /// 附加轴Jog-点动
  970. /// </summary>
  971. /// <param name="axisName"></param>
  972. /// <param name="distance"></param>
  973. /// <returns></returns>
  974. public bool AdditionalAxisJogNeg(string axisName, double distance)
  975. {
  976. return AdditionalAxisJog(axisName, -distance);
  977. }
  978. /// <summary>
  979. /// 附加轴异步 Jog+点动
  980. /// </summary>
  981. /// <param name="axisName"></param>
  982. /// <param name="distance"></param>
  983. /// <returns></returns>
  984. public Task<bool> AdditionalAxisJogAsync(string axisName, double distance)
  985. {
  986. return Task.Run(() => AdditionalAxisJog(axisName, distance));
  987. }
  988. /// <summary>
  989. /// 附加轴异步 Jog-点动
  990. /// </summary>
  991. /// <param name="axisName"></param>
  992. /// <param name="distance"></param>
  993. /// <returns></returns>
  994. public Task<bool> AdditionalAxisJogNegAsync(string axisName, double distance)
  995. {
  996. return Task.Run(() => AdditionalAxisJogNeg(axisName, distance));
  997. }
  998. #endregion
  999. #region 收发数据
  1000. public string SendAndReceive(string send) => string.Empty;
  1001. public Task<string> SendAndReceiveAsync(string send) => Task.FromResult(string.Empty);
  1002. public string SendAndReceive(ITcpSessionClient client, string send) => string.Empty;
  1003. public Task<string> SendAndReceiveAsync(ITcpSessionClient client, string send) => Task.FromResult(string.Empty);
  1004. public void Send(string send) { }
  1005. public Task SendAsync(string send) => Task.CompletedTask;
  1006. public void Send(ITcpSessionClient client, string send) { }
  1007. public Task SendAsync(ITcpSessionClient client, string send) => Task.CompletedTask;
  1008. public Encoding GetEncoding() => Encoding.Default;
  1009. #endregion
  1010. #region 属性通知
  1011. public event PropertyChangedEventHandler PropertyChanged;
  1012. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  1013. {
  1014. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  1015. storage = value;
  1016. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  1017. return true;
  1018. }
  1019. protected void OnPropertyChanged(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args);
  1020. #endregion
  1021. #region IRobot SetTool/SelectTool stubs
  1022. public bool SetTool(int index, double x, double y) => true;
  1023. public Task<bool> SetToolAsync(int index, double x, double y) => Task.FromResult(true);
  1024. public bool SelectTool(int index) => true;
  1025. public Task<bool> SelectToolAsync(int index) => Task.FromResult(true);
  1026. #endregion
  1027. }
  1028. }