XYZU_Robot.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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. /// <summary>
  1040. /// 获取附加轴的当前坐标
  1041. /// </summary>
  1042. /// <param name="axisName"></param>
  1043. /// <returns></returns>
  1044. public float GetAdditionalAxisCurrentPos(string axisName)
  1045. {
  1046. var axis = AdditionalAxisList.FirstOrDefault(x => x.Name == axisName);
  1047. if (axis==null)
  1048. {
  1049. return 0;
  1050. }
  1051. return Plc.ReadNode<float>(axis.State.ActPositionNode);
  1052. }
  1053. /// <summary>
  1054. /// 获取附加轴的当前坐标
  1055. /// </summary>
  1056. /// <param name="axisName"></param>
  1057. /// <returns></returns>
  1058. public Task<float> GetAdditionalAxisCurrentPosAsync(string axisName)
  1059. {
  1060. return Task.Run(()=> GetAdditionalAxisCurrentPos(axisName));
  1061. }
  1062. #endregion
  1063. #region 收发数据
  1064. public string SendAndReceive(string send) => string.Empty;
  1065. public Task<string> SendAndReceiveAsync(string send) => Task.FromResult(string.Empty);
  1066. public string SendAndReceive(ITcpSessionClient client, string send) => string.Empty;
  1067. public Task<string> SendAndReceiveAsync(ITcpSessionClient client, string send) => Task.FromResult(string.Empty);
  1068. public void Send(string send) { }
  1069. public Task SendAsync(string send) => Task.CompletedTask;
  1070. public void Send(ITcpSessionClient client, string send) { }
  1071. public Task SendAsync(ITcpSessionClient client, string send) => Task.CompletedTask;
  1072. public Encoding GetEncoding() => Encoding.Default;
  1073. #endregion
  1074. #region 属性通知
  1075. public event PropertyChangedEventHandler PropertyChanged;
  1076. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  1077. {
  1078. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  1079. storage = value;
  1080. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  1081. return true;
  1082. }
  1083. protected void OnPropertyChanged(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args);
  1084. #endregion
  1085. #region IRobot SetTool/SelectTool stubs
  1086. public bool SetTool(int index, double x, double y) => true;
  1087. public Task<bool> SetToolAsync(int index, double x, double y) => Task.FromResult(true);
  1088. public bool SelectTool(int index) => true;
  1089. public Task<bool> SelectToolAsync(int index) => Task.FromResult(true);
  1090. #endregion
  1091. }
  1092. }