XYZU_Robot.cs 44 KB

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