XYZU_Robot.cs 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175
  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. //相机1的移动轴
  106. if (robot.PlcRobotParameter.Camera1AxisList != null && robot.PlcRobotParameter.Camera1AxisList.Count > 0)
  107. {
  108. Camera1AxisList = new List<Axis>();
  109. foreach (var cam1Axis in robot.PlcRobotParameter.Camera1AxisList)
  110. {
  111. Axis axisExt = new Axis()
  112. {
  113. Name = cam1Axis.Name,
  114. Index = cam1Axis.Index,
  115. Command = cam1Axis.Command,
  116. Parameter = cam1Axis.Parameter,
  117. State = cam1Axis.State
  118. };
  119. Camera1AxisList.Add(axisExt);
  120. }
  121. }
  122. //相机2的移动轴
  123. if (robot.PlcRobotParameter.Camera2AxisList != null && robot.PlcRobotParameter.Camera2AxisList.Count > 0)
  124. {
  125. Camera2AxisList = new List<Axis>();
  126. foreach (var cam2Axis in robot.PlcRobotParameter.Camera2AxisList)
  127. {
  128. Axis axisExt = new Axis()
  129. {
  130. Name = cam2Axis.Name,
  131. Index = cam2Axis.Index,
  132. Command = cam2Axis.Command,
  133. Parameter = cam2Axis.Parameter,
  134. State = cam2Axis.State
  135. };
  136. Camera2AxisList.Add(axisExt);
  137. }
  138. }
  139. //相机3的移动轴
  140. if (robot.PlcRobotParameter.Camera3AxisList != null && robot.PlcRobotParameter.Camera3AxisList.Count > 0)
  141. {
  142. Camera3AxisList = new List<Axis>();
  143. foreach (var cam3Axis in robot.PlcRobotParameter.Camera3AxisList)
  144. {
  145. Axis axisExt = new Axis()
  146. {
  147. Name = cam3Axis.Name,
  148. Index = cam3Axis.Index,
  149. Command = cam3Axis.Command,
  150. Parameter = cam3Axis.Parameter,
  151. State = cam3Axis.State
  152. };
  153. Camera3AxisList.Add(axisExt);
  154. }
  155. }
  156. //相机4的移动轴
  157. if (robot.PlcRobotParameter.Camera4AxisList != null && robot.PlcRobotParameter.Camera4AxisList.Count > 0)
  158. {
  159. Camera4AxisList = new List<Axis>();
  160. foreach (var cam4Axis in robot.PlcRobotParameter.Camera4AxisList)
  161. {
  162. Axis axisExt = new Axis()
  163. {
  164. Name = cam4Axis.Name,
  165. Index = cam4Axis.Index,
  166. Command = cam4Axis.Command,
  167. Parameter = cam4Axis.Parameter,
  168. State = cam4Axis.State
  169. };
  170. Camera4AxisList.Add(axisExt);
  171. }
  172. }
  173. if (Plc.IsConnected)
  174. {
  175. try
  176. {
  177. //所有轴的位置节点
  178. var nodeIds = Axes.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode)).Select(a => a.State.ActPositionNode).ToArray();
  179. List<string> positionNodes = new List<string>(nodeIds);
  180. pLC.SubscribeNodes("AxisPosition", positionNodes, (res) =>
  181. {
  182. if (res.key != "AxisPosition") return;
  183. for (int i = 0; i < Axes.Count; i++)
  184. {
  185. var axis = Axes[i];
  186. if (axis.State.ActPositionNode.Contains(res.nodeId))
  187. {
  188. float v = Convert.ToSingle(res.value);
  189. switch (axis.Name)
  190. {
  191. case "X": CurrentPosition.X = v; break;
  192. case "Y": CurrentPosition.Y = v; break;
  193. case "Z": CurrentPosition.Z = v; break;
  194. case "U": CurrentPosition.U = v; break;
  195. }
  196. }
  197. }
  198. });
  199. //所有附加轴的位置节点
  200. if (AdditionalAxisList != null && AdditionalAxisList.Count > 0)
  201. {
  202. var addNodeIds = AdditionalAxisList
  203. .Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode))
  204. .Select(a => a.State.ActPositionNode)
  205. .ToArray();
  206. List<string> addPositionNodes = new List<string>(addNodeIds);
  207. pLC.SubscribeNodes("AdditionalAxisPosition", addPositionNodes, (res) =>
  208. {
  209. if (res.key != "AdditionalAxisPosition") return;
  210. for (int i = 0; i < AdditionalAxisList.Count; i++)
  211. {
  212. var axis = AdditionalAxisList[i];
  213. if (axis.State.ActPositionNode.Contains(res.nodeId))
  214. {
  215. axis.CurrentPosition = Convert.ToSingle(res.value);
  216. }
  217. }
  218. });
  219. }
  220. //所有相机1轴的位置节点
  221. if (Camera1AxisList != null && Camera1AxisList.Count > 0)
  222. {
  223. var cam1NodeIds = Camera1AxisList
  224. .Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode))
  225. .Select(a => a.State.ActPositionNode)
  226. .ToArray();
  227. List<string> cam1PositionNodes = new List<string>(cam1NodeIds);
  228. pLC.SubscribeNodes("Camera1AxisPosition", cam1PositionNodes, (res) =>
  229. {
  230. if (res.key != "Camera1AxisPosition") return;
  231. for (int i = 0; i < Camera1AxisList.Count; i++)
  232. {
  233. var axis = Camera1AxisList[i];
  234. if (axis.State.ActPositionNode.Contains(res.nodeId))
  235. {
  236. float v = Convert.ToSingle(res.value);
  237. switch (axis.Name)
  238. {
  239. case "X": Camera1CurrentPosition.X = v; break;
  240. case "Y": Camera1CurrentPosition.Y = v; break;
  241. }
  242. }
  243. }
  244. });
  245. }
  246. //所有相机2轴的位置节点
  247. if (Camera2AxisList != null && Camera2AxisList.Count > 0)
  248. {
  249. var cam2NodeIds = Camera2AxisList
  250. .Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode))
  251. .Select(a => a.State.ActPositionNode)
  252. .ToArray();
  253. List<string> cam2PositionNodes = new List<string>(cam2NodeIds);
  254. pLC.SubscribeNodes("Camera2AxisPosition", cam2PositionNodes, (res) =>
  255. {
  256. if (res.key != "Camera2AxisPosition") return;
  257. for (int i = 0; i < Camera2AxisList.Count; i++)
  258. {
  259. var axis = Camera2AxisList[i];
  260. if (axis.State.ActPositionNode.Contains(res.nodeId))
  261. {
  262. float v = Convert.ToSingle(res.value);
  263. switch (axis.Name)
  264. {
  265. case "X": Camera2CurrentPosition.X = v; break;
  266. case "Y": Camera2CurrentPosition.Y = v; break;
  267. }
  268. }
  269. }
  270. });
  271. }
  272. //所有相机3轴的位置节点
  273. if (Camera3AxisList != null && Camera3AxisList.Count > 0)
  274. {
  275. var cam3NodeIds = Camera3AxisList
  276. .Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode))
  277. .Select(a => a.State.ActPositionNode)
  278. .ToArray();
  279. List<string> cam3PositionNodes = new List<string>(cam3NodeIds);
  280. pLC.SubscribeNodes("Camera3AxisPosition", cam3PositionNodes, (res) =>
  281. {
  282. if (res.key != "Camera3AxisPosition") return;
  283. for (int i = 0; i < Camera3AxisList.Count; i++)
  284. {
  285. var axis = Camera3AxisList[i];
  286. if (axis.State.ActPositionNode.Contains(res.nodeId))
  287. {
  288. float v = Convert.ToSingle(res.value);
  289. switch (axis.Name)
  290. {
  291. case "X": Camera3CurrentPosition.X = v; break;
  292. case "Y": Camera3CurrentPosition.Y = v; break;
  293. }
  294. }
  295. }
  296. });
  297. }
  298. //所有相机4轴的位置节点
  299. if (Camera4AxisList != null && Camera4AxisList.Count > 0)
  300. {
  301. var cam4NodeIds = Camera4AxisList
  302. .Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode))
  303. .Select(a => a.State.ActPositionNode)
  304. .ToArray();
  305. List<string> cam4PositionNodes = new List<string>(cam4NodeIds);
  306. pLC.SubscribeNodes("Camera4AxisPosition", cam4PositionNodes, (res) =>
  307. {
  308. if (res.key != "Camera4AxisPosition") return;
  309. for (int i = 0; i < Camera4AxisList.Count; i++)
  310. {
  311. var axis = Camera4AxisList[i];
  312. if (axis.State.ActPositionNode.Contains(res.nodeId))
  313. {
  314. float v = Convert.ToSingle(res.value);
  315. switch (axis.Name)
  316. {
  317. case "X": Camera4CurrentPosition.X = v; break;
  318. case "Y": Camera4CurrentPosition.Y = v; break;
  319. }
  320. }
  321. }
  322. });
  323. }
  324. }
  325. catch (Exception)
  326. {
  327. }
  328. }
  329. }
  330. private void Plc_ConnectChangedEvent(object arg1, bool arg2)
  331. {
  332. CanExecute = arg2;
  333. if (arg2)
  334. ConnectedEvent?.Invoke(Id, this, null);
  335. else
  336. DisconnectedEvent?.Invoke(Id, this, null);
  337. }
  338. #region 属性
  339. public TcpClient TcpClient { get; private set; }
  340. public TcpService TcpService { get; private set; }
  341. public Guid Id { get; set; }
  342. public string Name { get; set; }
  343. /// <summary>
  344. /// 机器人编号
  345. /// </summary>
  346. public int RobotNo { get; set; }
  347. public int RobotPort { get; private set; }
  348. public string RobotIp { get; private set; }
  349. public TCPConnectType ConnectType { get; private set; }
  350. public Terminator Terminator { get; private set; }
  351. public DataEncoding DataEncoding { get; private set; }
  352. public bool IsConnected
  353. {
  354. get
  355. {
  356. if (Plc != null)
  357. {
  358. return Plc.IsConnected;
  359. }
  360. else
  361. {
  362. return false;
  363. }
  364. }
  365. }
  366. public int Timeout { get; set; } = 5000;
  367. private bool _CanExecute = true;
  368. public bool CanExecute
  369. {
  370. get { return _CanExecute; }
  371. set { SetProperty(ref _CanExecute, value); }
  372. }
  373. public int SelectedTool { get; private set; } = 0;
  374. public RobotBrand Brand { get; private set; }
  375. public OpcUaClientPLC Plc { get; private set; }
  376. public RobotInfo RobotInfo { get; private set; }
  377. public List<Axis> Axes { get; private set; }
  378. private ObservableCollection<AxisExtended> _AdditionalAxisList;
  379. /// <summary>
  380. /// 附加轴
  381. /// </summary>
  382. public ObservableCollection<AxisExtended> AdditionalAxisList
  383. {
  384. get { return _AdditionalAxisList; }
  385. set { SetProperty(ref _AdditionalAxisList, value); }
  386. }
  387. /// <summary>
  388. /// 相机1的移动轴
  389. /// </summary>
  390. public List<Axis> Camera1AxisList { get; private set; }
  391. /// <summary>
  392. /// 相机2的移动轴集合
  393. /// </summary>
  394. public List<Axis> Camera2AxisList { get; private set; }
  395. /// <summary>
  396. /// 相机3的移动轴集合
  397. /// </summary>
  398. public List<Axis> Camera3AxisList { get; private set; }
  399. /// <summary>
  400. /// 相机4的移动轴集合
  401. /// </summary>
  402. public List<Axis> Camera4AxisList { get; private set; }
  403. /// <summary>
  404. /// 进入调试模式
  405. /// </summary>
  406. /// <returns></returns>
  407. public bool EnterDebugMode { get; set; }
  408. private RPoint _CurrentPosition = new RPoint();
  409. /// <summary>
  410. /// 当前位置
  411. /// </summary>
  412. public RPoint CurrentPosition
  413. {
  414. get { return _CurrentPosition; }
  415. set { SetProperty(ref _CurrentPosition, value); }
  416. }
  417. private RPoint _Camera1CurrentPosition= new RPoint();
  418. /// <summary>
  419. /// 当前相机1的移动轴位置
  420. /// </summary>
  421. public RPoint Camera1CurrentPosition
  422. {
  423. get { return _Camera1CurrentPosition; }
  424. set { SetProperty(ref _Camera1CurrentPosition, value); }
  425. }
  426. private RPoint _Camera2CurrentPosition = new RPoint();
  427. /// <summary>
  428. /// 当前相机2的移动轴位置
  429. /// </summary>
  430. public RPoint Camera2CurrentPosition
  431. {
  432. get { return _Camera2CurrentPosition; }
  433. set { SetProperty(ref _Camera2CurrentPosition, value); }
  434. }
  435. private RPoint _Camera3CurrentPosition = new RPoint();
  436. /// <summary>
  437. /// 当前相机3的移动轴位置
  438. /// </summary>
  439. public RPoint Camera3CurrentPosition
  440. {
  441. get { return _Camera3CurrentPosition; }
  442. set { SetProperty(ref _Camera3CurrentPosition, value); }
  443. }
  444. private RPoint _Camera4CurrentPosition = new RPoint();
  445. /// <summary>
  446. /// 当前相机4的移动轴位置
  447. /// </summary>
  448. public RPoint Camera4CurrentPosition
  449. {
  450. get { return _Camera4CurrentPosition; }
  451. set { SetProperty(ref _Camera4CurrentPosition, value); }
  452. }
  453. #endregion
  454. #region 连接
  455. public void Connect()
  456. {
  457. if (Plc.IsConnected)
  458. {
  459. StopMove();
  460. ConnectedEvent?.Invoke(Id, this, null);
  461. }
  462. }
  463. public Task ConnectAsync()
  464. {
  465. if (Plc.IsConnected)
  466. {
  467. StopMove();
  468. ConnectedEvent?.Invoke(Id, this, null);
  469. }
  470. return Task.CompletedTask;
  471. }
  472. public void Disconnect()
  473. {
  474. }
  475. public void Dispose()
  476. {
  477. }
  478. #endregion
  479. #region 控制
  480. public bool Reset() => true;
  481. public Task<bool> ResetAsync() { return Task.Run(() => Reset()); }
  482. public bool Motor(bool state)
  483. {
  484. //遍历所有轴,设置电机状态
  485. //获取所有轴的Poer节点,组成一个集合,一次性写入
  486. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  487. foreach (var axis in Axes)
  488. {
  489. if (!string.IsNullOrWhiteSpace(axis.Command.PowerNode))
  490. {
  491. nodesToWrite[axis.Command.PowerNode] = state;
  492. }
  493. }
  494. if (Plc == null || !Plc.IsConnected) return false;
  495. return Plc.WriteNodes(nodesToWrite);
  496. }
  497. public async Task<bool> MotorAsync(bool state)
  498. {
  499. //遍历所有轴,设置电机状态
  500. //获取所有轴的Poer节点,组成一个集合,一次性写入
  501. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  502. foreach (var axis in Axes)
  503. {
  504. if (!string.IsNullOrWhiteSpace(axis.Command.PowerNode))
  505. {
  506. nodesToWrite[axis.Command.PowerNode] = state;
  507. }
  508. }
  509. if (Plc == null || !Plc.IsConnected) return false;
  510. return await Plc.WriteNodesAsync(nodesToWrite);
  511. }
  512. public bool Power(bool state) => true;
  513. public Task<bool> PowerAsync(bool state) => Task.FromResult(true);
  514. public bool Speed(int value)
  515. {
  516. return true;
  517. }
  518. public Task<bool> SpeedAsync(int value) => Task.FromResult(true);
  519. public bool Speedfactor(int value) => true;
  520. public Task<bool> SpeedfactorAsync(int value) => Task.FromResult(true);
  521. public bool Speeds(double value)
  522. {
  523. //遍历所有轴,设置电机状态
  524. //获取所有轴的Poer节点,组成一个集合,一次性写入
  525. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  526. foreach (var axis in Axes)
  527. {
  528. if (!string.IsNullOrWhiteSpace(axis.Parameter.ManuVelocityNode))
  529. {
  530. nodesToWrite[axis.Command.PowerNode] = (float)value;
  531. }
  532. }
  533. if (Plc == null || !Plc.IsConnected) return false;
  534. return Plc.WriteNodes(nodesToWrite);
  535. }
  536. public async Task<bool> SpeedsAsync(double value)
  537. {
  538. //遍历所有轴,设置电机状态
  539. //获取所有轴的Poer节点,组成一个集合,一次性写入
  540. Dictionary<string, object> nodesToWrite = new Dictionary<string, object>();
  541. foreach (var axis in Axes)
  542. {
  543. if (!string.IsNullOrWhiteSpace(axis.Parameter.ManuVelocityNode))
  544. {
  545. nodesToWrite[axis.Command.PowerNode] = (float)value;
  546. }
  547. }
  548. if (Plc == null || !Plc.IsConnected) return false;
  549. return await Plc.WriteNodesAsync(nodesToWrite);
  550. }
  551. public bool Accel(int value) => true;
  552. public Task<bool> AccelAsync(int value) => Task.FromResult(true);
  553. public bool Accels(double value) => true;
  554. public Task<bool> AccelsAsync(double value) => Task.FromResult(true);
  555. public RPoint GetRobotPos()
  556. {
  557. if (Plc == null || !Plc.IsConnected) return null;
  558. try
  559. {
  560. var nodeIds = Axes.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode)).Select(a => a.State.ActPositionNode).ToArray();
  561. var data = Plc.ReadNodes(nodeIds);
  562. if (data == null || data.Count == 0) return null;
  563. //获取所有的值
  564. var values = data.Values.ToArray();
  565. RPoint point = new RPoint();
  566. for (int i = 0; i < Axes.Count && i < values.Length; i++)
  567. {
  568. var val = values[i];
  569. float v = 0;
  570. if (val != null)
  571. {
  572. try { v = Convert.ToSingle(val); } catch { }
  573. }
  574. switch (Axes[i].Name)
  575. {
  576. case "X": point.X = v; break;
  577. case "Y": point.Y = v; break;
  578. case "Z": point.Z = v; break;
  579. case "U": point.U = v; break;
  580. default: break;
  581. }
  582. }
  583. return point;
  584. }
  585. catch (Exception ex)
  586. {
  587. LogHelper.WriteLogError("获取机器人位置出错", ex);
  588. throw;
  589. }
  590. }
  591. public Task<RPoint> GetRobotPosAsync()
  592. {
  593. return Task.Run(() => GetRobotPos());
  594. }
  595. public bool Go(RPoint position)
  596. {
  597. return WaitMoveFinished(position);
  598. }
  599. public Task<bool> GoAsync(RPoint position)
  600. {
  601. return Task.Run(() => Go(position));
  602. }
  603. public bool Move(RPoint position) => Go(position);
  604. public Task<bool> MoveAsync(RPoint position) => GoAsync(position);
  605. public bool Jump(RPoint position, double? LimZ)
  606. {
  607. return CalibMotion(position,LimZ);
  608. }
  609. public Task<bool> JumpAsync(RPoint position, double? LimZ) => CalibMotionAsync(position,LimZ);
  610. public bool Jog(string axis, double distance)
  611. {
  612. //获取当前机器人坐标
  613. var currentPos = GetRobotPos();
  614. if (currentPos == null) return false;
  615. switch (axis.ToUpper())
  616. {
  617. case "X":
  618. currentPos.X += (float)distance;
  619. break;
  620. case "Y":
  621. currentPos.Y += (float)distance;
  622. break;
  623. case "Z":
  624. currentPos.Z += (float)distance;
  625. break;
  626. case "U":
  627. currentPos.U += (float)distance;
  628. break;
  629. default:
  630. return false;
  631. }
  632. return Go(currentPos);
  633. }
  634. public Task<bool> JogAsync(string axis, double distance)
  635. {
  636. return Task.Run(() => Jog(axis, distance));
  637. }
  638. public bool Joint(int joint, double distance)
  639. {
  640. return false;
  641. }
  642. public Task<bool> JointAsync(int joint, double distance) => Task.FromResult(false);
  643. public bool SFree()
  644. {
  645. return Motor(false);
  646. }
  647. public Task<bool> SFreeAsync() => Task.Run(() => SFree());
  648. public bool SLock() => Motor(true);
  649. public Task<bool> SLockAsync() => Task.Run(() => SLock());
  650. public bool CalibMotion(RPoint position, double? LimZ)
  651. {
  652. //先Z轴到安全高度
  653. var currentPos = GetRobotPos();
  654. if (currentPos == null) return false;
  655. if (LimZ.HasValue)
  656. {
  657. currentPos.Z = (float)LimZ.Value;
  658. if (!Go(currentPos)) return false;
  659. }
  660. //再XYU轴到位
  661. currentPos.X = position.X;
  662. currentPos.Y = position.Y;
  663. currentPos.U = position.U;
  664. if (!Go(currentPos)) return false;
  665. //最后Z轴到目标高度
  666. currentPos.Z = position.Z;
  667. var isSucceed = Go(currentPos);
  668. Thread.Sleep(150);
  669. return isSucceed;
  670. }
  671. public Task<bool> CalibMotionAsync(RPoint position, double? LimZ) => Task.Run(() => CalibMotion(position, LimZ));
  672. public bool CalibOutIO(bool state)
  673. {
  674. if (Plc == null || !Plc.IsConnected) return false;
  675. string openNodeId = "ns=4;s=DB_DriveControl|VacCtrl[{0}].Cmd.ManuToWork";
  676. string closeNodeId = "ns=4;s=DB_DriveControl|VacCtrl[{0}].Cmd.ManuToHome";
  677. try
  678. {
  679. if (state)
  680. {
  681. string node = string.Format(openNodeId, _PickInfo.Inhal);
  682. if (!Plc.WriteNode<bool>(node,true))
  683. {
  684. return false;
  685. }
  686. Thread.Sleep(_WaitSuction);
  687. return true;
  688. }
  689. else
  690. {
  691. string node = string.Format(closeNodeId, _PickInfo.Blow);
  692. if (!Plc.WriteNode<bool>(node, true))
  693. {
  694. return false;
  695. }
  696. Thread.Sleep(_WaitBlow);
  697. return true;
  698. }
  699. }
  700. catch (Exception ex)
  701. {
  702. LogHelper.WriteLogError("执行XYZU平台,真空操作时出错!", ex);
  703. return false;
  704. }
  705. }
  706. public Task<bool> CalibOutIOAsync(bool state)
  707. {
  708. return Task.Run(() => CalibOutIO(state));
  709. }
  710. public bool CalibParame(PickInfo Pick, int Speed, int Accel, bool Power, int WaitSuction, int WaitBlow)
  711. {
  712. return false;
  713. }
  714. private PickInfo _PickInfo = new PickInfo();
  715. private int _WaitSuction=100, _WaitBlow=100;
  716. public async Task<bool> CalibParameAsync(PickInfo Pick, int Speed, int Accel, bool Power, int WaitSuction, int WaitBlow)
  717. {
  718. if (Plc == null || !Plc.IsConnected) return false;
  719. try
  720. {
  721. _PickInfo = Pick;
  722. _WaitSuction = WaitSuction;
  723. _WaitBlow=WaitBlow;
  724. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  725. foreach (var axis in Axes)
  726. {
  727. if (string.IsNullOrWhiteSpace(axis.Parameter.ManuVelocityNode)) continue;
  728. string nodeid = axis.Parameter.ManuVelocityNode;
  729. float value = Speed;
  730. keyValues.Add(nodeid, value);
  731. }
  732. // 2. 写入速度给所有轴
  733. if (!Plc.WriteNodes(keyValues))
  734. {
  735. return false;
  736. }
  737. return true;
  738. }
  739. catch (Exception ex)
  740. {
  741. LogHelper.WriteLogError("为XYZU平台设置速度时出错!", ex);
  742. return false;
  743. }
  744. }
  745. /// <summary>
  746. /// 阻塞式等待运动完成
  747. /// </summary>
  748. /// <param name="position"></param>
  749. /// <returns></returns>
  750. private bool WaitMoveFinished(RPoint position)
  751. {
  752. if (Plc == null || !Plc.IsConnected) return false;
  753. try
  754. {
  755. CanExecute = false;
  756. Motor(true);
  757. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  758. // 1. 写入目标位置到各轴的 ManuPositionNode
  759. keyValues = new Dictionary<string, object>();
  760. foreach (var axis in Axes)
  761. {
  762. if (string.IsNullOrWhiteSpace(axis.Parameter.ManuPositionNode)) continue;
  763. string nodeid = axis.Parameter.ManuPositionNode;
  764. float value = 0;
  765. switch (axis.Name)
  766. {
  767. case "X": value = position.X; break;
  768. case "Y": value = position.Y; break;
  769. case "Z": value = position.Z; break;
  770. case "U": value = position.U; break;
  771. default: value = 0; break;
  772. }
  773. keyValues.Add(nodeid, value);
  774. }
  775. // 2. 写入位置给所有轴
  776. if (!Plc.WriteNodes(keyValues))
  777. {
  778. return false;
  779. }
  780. // 3. 写入开始移动命令给所有轴
  781. if (!StartMove())
  782. {
  783. return false;
  784. }
  785. // 准备停滞检测:收集所有实际位置节点
  786. var actNodes = Axes.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode))
  787. .Select(a => a.State.ActPositionNode)
  788. .Distinct()
  789. .ToArray();
  790. // lastPos 存储上一次读取到的位置,lastChange 存储上次发生“实质性”变化的时间
  791. Dictionary<string, float> lastPos = new Dictionary<string, float>();
  792. Dictionary<string, DateTime> lastChange = new Dictionary<string, DateTime>();
  793. foreach (var node in actNodes)
  794. {
  795. lastPos[node] = float.NaN;
  796. lastChange[node] = DateTime.UtcNow;
  797. }
  798. const float movementThreshold = 0.01f; // 判断位置变化的阈值,避免噪声
  799. Stopwatch sw = new Stopwatch();
  800. sw.Start();
  801. while (true)
  802. {
  803. // 先读取各轴的实际位置,用于停滞检测
  804. Dictionary<string, object> posRead = new Dictionary<string, object>();
  805. try
  806. {
  807. if (actNodes.Length > 0)
  808. {
  809. posRead = Plc.ReadNodes(actNodes);
  810. }
  811. }
  812. catch
  813. {
  814. // 如果读取失败,继续让 CheckMoveFinished 来处理状态或超时
  815. }
  816. var now = DateTime.UtcNow;
  817. // 更新每个节点的变化时间:只要任意一个轴在最近 Timeout 时间内有变化,就视为系统仍在运动
  818. foreach (var node in actNodes)
  819. {
  820. float actual = 0;
  821. if (posRead != null && posRead.ContainsKey(node))
  822. {
  823. var raw = posRead[node];
  824. if (raw != null)
  825. {
  826. try { actual = Convert.ToSingle(raw); } catch { /* 保持 actual = 0 */ }
  827. }
  828. }
  829. if (float.IsNaN(lastPos[node]))
  830. {
  831. lastPos[node] = actual;
  832. lastChange[node] = now;
  833. }
  834. else
  835. {
  836. if (Math.Abs(actual - lastPos[node]) > movementThreshold)
  837. {
  838. // 有实质性变化,更新记录时间和值
  839. lastPos[node] = actual;
  840. lastChange[node] = now;
  841. }
  842. // 否则保持 lastChange 不变(表示该轴最近一次变化的时间)
  843. }
  844. }
  845. // 判断是否至少有一个轴在最近 Timeout 时间内发生过变化(即认为还在运动)
  846. bool anyAxisMovedRecently = actNodes.Any(node => (now - lastChange[node]).TotalMilliseconds <= 500);
  847. // 如果没有任何轴在最近 Timeout 时间内发生变化,则认为出现停滞异常
  848. if (!anyAxisMovedRecently && actNodes.Length > 0)
  849. {
  850. StopMove();
  851. LogHelper.WriteLogInfo($"轴停滞超时(整体判定),目标位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U},超时阈值(ms)={Timeout}");
  852. return false;
  853. }
  854. // 检查是否整体到位或有错误(保留原有逻辑)
  855. var (isFinished, isError) = CheckMoveFinished(position);
  856. if (isFinished)
  857. {
  858. StopMove();
  859. return true;
  860. }
  861. if (isError)
  862. {
  863. LogHelper.WriteLogInfo($"机器人执行移动时发生错误,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  864. return false;
  865. }
  866. // 检查整体超时(防止一直有抖动导致 anyAxisMovedRecently 一直为 true)
  867. if (sw.ElapsedMilliseconds > 60000) // 保守超时,一分钟,可根据需求调整
  868. {
  869. LogHelper.WriteLogInfo($"机器人执行移动超时,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  870. StopMove();
  871. return false;
  872. }
  873. Thread.Sleep(10);
  874. }
  875. }
  876. catch (Exception ex)
  877. {
  878. LogHelper.WriteLogError("执行XYZU平台,阻塞式等待运动完成时出错!", ex);
  879. CanExecute = true;
  880. return false;
  881. }
  882. finally
  883. {
  884. CanExecute = true;
  885. }
  886. }
  887. /// <summary>
  888. /// 开始运动
  889. /// </summary>
  890. /// <returns></returns>
  891. private bool StartMove()
  892. {
  893. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  894. // 1. 复位所有轴的开始移动命令
  895. foreach (var axis in Axes)
  896. {
  897. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  898. {
  899. keyValues.Add(axis.Command.ManuPositionNode, true);
  900. }
  901. }
  902. return Plc.WriteNodes(keyValues);
  903. }
  904. /// <summary>
  905. /// 停止运动
  906. /// </summary>
  907. /// <returns></returns>
  908. private bool StopMove()
  909. {
  910. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  911. // 1. 复位所有轴的开始移动命令
  912. foreach (var axis in Axes)
  913. {
  914. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  915. {
  916. keyValues.Add(axis.Command.ManuPositionNode, false);
  917. }
  918. //if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  919. //{
  920. // keyValues.Add(axis.Command.StopNode, true);
  921. //}
  922. }
  923. bool result = Plc.WriteNodes(keyValues);
  924. // 异步等待100ms后复位停止命令
  925. //Task.Run(async () =>
  926. //{
  927. // await Task.Delay(100);
  928. //Thread.Sleep(50);
  929. //Dictionary<string, object> resetValues = new Dictionary<string, object>();
  930. //foreach (var axis in Axes)
  931. //{
  932. // if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  933. // {
  934. // resetValues.Add(axis.Command.StopNode, false);
  935. // }
  936. //}
  937. //Plc.WriteNodes(resetValues);
  938. //});
  939. return result;
  940. }
  941. /// <summary>
  942. /// 检查运动是否结束,返回是否停止、是否有错误
  943. /// </summary>
  944. /// <param name="position"></param>
  945. /// <returns></returns>
  946. private (bool isFinished, bool isError) CheckMoveFinished(RPoint position)
  947. {
  948. //检查各轴是否到位和目标位置一致
  949. //批量获取所有轴的定位状态和位置、是否错误
  950. var nodeIds = new List<string>();
  951. foreach (var axis in Axes)
  952. {
  953. if (!string.IsNullOrWhiteSpace(axis.State.PosOKNode))
  954. {
  955. nodeIds.Add(axis.State.PosOKNode);
  956. }
  957. if (!string.IsNullOrWhiteSpace(axis.State.ActPositionNode))
  958. {
  959. nodeIds.Add(axis.State.ActPositionNode);
  960. }
  961. if (!string.IsNullOrWhiteSpace(axis.State.ErrorNode))
  962. {
  963. nodeIds.Add(axis.State.ErrorNode);
  964. }
  965. if (!string.IsNullOrWhiteSpace(axis.State.PausedNode))
  966. {
  967. nodeIds.Add(axis.State.PausedNode);
  968. }
  969. }
  970. var res = Plc.ReadNodes(nodeIds.ToArray());
  971. bool allOk = true;
  972. bool isAnyError = false;
  973. foreach (var axis in Axes)
  974. {
  975. bool posOk = false;
  976. float actualPos = 0;
  977. bool isError = false;
  978. //获取此轴的定位状态、实际位置、错误状态
  979. if (res.ContainsKey(axis.State.PosOKNode))
  980. {
  981. posOk = (bool)res[axis.State.PosOKNode];
  982. }
  983. if (res.ContainsKey(axis.State.ActPositionNode))
  984. {
  985. try { actualPos = Convert.ToSingle(res[axis.State.ActPositionNode]); } catch { }
  986. }
  987. if (res.ContainsKey(axis.State.ErrorNode))
  988. {
  989. isError = (bool)res[axis.State.ErrorNode];
  990. }
  991. if (res.ContainsKey(axis.State.PausedNode))
  992. {
  993. isError = (bool)res[axis.State.PausedNode];
  994. }
  995. if (isError)
  996. {
  997. isAnyError = true;
  998. break;
  999. }
  1000. //检查是否到位和位置一致
  1001. float targetPos = 0;
  1002. switch (axis.Name)
  1003. {
  1004. case "X": targetPos = position.X; break;
  1005. case "Y": targetPos = position.Y; break;
  1006. case "Z": targetPos = position.Z; break;
  1007. case "U": targetPos = position.U; break;
  1008. default: targetPos = 0; break;
  1009. }
  1010. //如果定位完成且位置一致,则此轴完成,如果有错误则失败
  1011. if (!(posOk && Math.Abs(actualPos - targetPos) < 0.02))
  1012. {
  1013. if (isError)
  1014. {
  1015. isAnyError = true;
  1016. break;
  1017. }
  1018. allOk = false;
  1019. break;
  1020. }
  1021. }
  1022. return (allOk, isAnyError);
  1023. }
  1024. #region 附加轴操作
  1025. /// <summary>
  1026. /// 检查单个附加轴是否结束,返回是否停止、是否有错误
  1027. /// </summary>
  1028. /// <param name="axis"></param>
  1029. /// <param name="targetPos"></param>
  1030. /// <returns></returns>
  1031. private (bool isFinished, bool isError) CheckAdditionalAxisMoveFinished(AxisExtended axis, double targetPos)
  1032. {
  1033. //读取实际位置和到位状态
  1034. bool posOk = false;
  1035. float actualPos = 0;
  1036. bool isError = false;
  1037. var res = Plc.ReadNodes(new string[] { axis.State.PosOKNode, axis.State.ActPositionNode, axis.State.ErrorNode, axis.State.PausedNode });
  1038. if (res.ContainsKey(axis.State.PosOKNode))
  1039. {
  1040. posOk = (bool)res[axis.State.PosOKNode];
  1041. }
  1042. if (res.ContainsKey(axis.State.ActPositionNode))
  1043. {
  1044. try { actualPos = Convert.ToSingle(res[axis.State.ActPositionNode]); } catch { }
  1045. }
  1046. if (res.ContainsKey(axis.State.ErrorNode))
  1047. {
  1048. isError = (bool)res[axis.State.ErrorNode];
  1049. }
  1050. if (res.ContainsKey(axis.State.PausedNode))
  1051. {
  1052. isError = (bool)res[axis.State.PausedNode];
  1053. }
  1054. //检查是否到位和位置一致
  1055. if (isError)
  1056. {
  1057. return (true, true);
  1058. }
  1059. if (posOk && Math.Abs(actualPos - targetPos) < 0.02)
  1060. {
  1061. return (true, false);
  1062. }
  1063. return (false, false);
  1064. }
  1065. /// <summary>
  1066. /// 附加轴使能操作
  1067. /// </summary>
  1068. /// <param name="axisName"></param>
  1069. /// <param name="state"></param>
  1070. /// <returns></returns>
  1071. public bool AdditionalAxisMotor(string axisName, bool state)
  1072. {
  1073. var axis = AdditionalAxisList.FirstOrDefault(a => a.Name.Equals(axisName, StringComparison.OrdinalIgnoreCase));
  1074. if (axis == null) return false;
  1075. if (Plc == null || !Plc.IsConnected) return false;
  1076. try
  1077. {
  1078. if (!string.IsNullOrWhiteSpace(axis.Command.PowerNode))
  1079. {
  1080. return Plc.WriteNode(axis.Command.PowerNode, state);
  1081. }
  1082. return false;
  1083. }
  1084. catch (Exception ex)
  1085. {
  1086. LogHelper.WriteLogError("执行附加轴使能操作时出错!", ex);
  1087. return false;
  1088. }
  1089. }
  1090. /// <summary>
  1091. /// 附加轴使能操作,异步方法
  1092. /// </summary>
  1093. /// <param name="axisName"></param>
  1094. /// <param name="state"></param>
  1095. /// <returns></returns>
  1096. public Task<bool> AdditionalAxisMotorAsync(string axisName, bool state)
  1097. {
  1098. return Task.Run(() => AdditionalAxisMotor(axisName, state));
  1099. }
  1100. /// <summary>
  1101. /// 附加轴,阻塞式等待运动完成
  1102. /// </summary>
  1103. /// <param name="axisName"></param>
  1104. /// <param name="targetPos"></param>
  1105. /// <returns></returns>
  1106. public bool AdditionalAxisMove(string axisName, double targetPos)
  1107. {
  1108. var axis = AdditionalAxisList.FirstOrDefault(a => a.Name.Equals(axisName, StringComparison.OrdinalIgnoreCase));
  1109. if (axis == null) return false;
  1110. if (Plc == null || !Plc.IsConnected) return false;
  1111. try
  1112. {
  1113. CanExecute = false;
  1114. AdditionalAxisMotor(axis.Name, true);
  1115. //写入目标位置
  1116. if (!string.IsNullOrWhiteSpace(axis.Parameter.ManuPositionNode))
  1117. {
  1118. Plc.WriteNode(axis.Parameter.ManuPositionNode, (float)targetPos);
  1119. }
  1120. //开始移动
  1121. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  1122. {
  1123. Plc.WriteNode(axis.Command.ManuPositionNode, true);
  1124. }
  1125. //准备停滞检测:收集所有实际位置节点
  1126. float lastPos = float.NaN;
  1127. DateTime lastChange = DateTime.UtcNow;
  1128. const float movementThreshold = 0.01f; // 判断位置变化的阈值,避免噪声
  1129. Stopwatch sw = new Stopwatch();
  1130. sw.Start();
  1131. while (true)
  1132. {
  1133. var now = DateTime.UtcNow;
  1134. // 先读取轴的实际位置,用于停滞检测
  1135. var actual = Plc.ReadNode<float>(axis.State.ActPositionNode);
  1136. if (float.IsNaN(lastPos))
  1137. {
  1138. lastPos = actual;
  1139. lastChange = now;
  1140. }
  1141. else
  1142. {
  1143. if (Math.Abs(actual - lastPos) > movementThreshold)
  1144. {
  1145. // 有实质性变化,更新记录时间和值
  1146. lastPos = actual;
  1147. lastChange = now;
  1148. }
  1149. // 否则保持 lastChange 不变(表示该轴最近一次变化的时间)
  1150. }
  1151. // 判断是否至少有一个轴在最近 Timeout 时间内发生过变化(即认为还在运动)
  1152. bool anyAxisMovedRecently = (now - lastChange).TotalMilliseconds <= 500;
  1153. // 如果没有任何轴在最近 Timeout 时间内发生变化,则认为出现停滞异常
  1154. if (!anyAxisMovedRecently)
  1155. {
  1156. //停止移动
  1157. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  1158. {
  1159. Plc.WriteNode(axis.Command.ManuPositionNode, false);
  1160. }
  1161. return false;
  1162. }
  1163. // 检查是否整体到位或有错误(保留原有逻辑)
  1164. var (isFinished, isError) = CheckAdditionalAxisMoveFinished(axis, targetPos);
  1165. if (isFinished)
  1166. {
  1167. //停止移动
  1168. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  1169. {
  1170. Plc.WriteNode(axis.Command.ManuPositionNode, false);
  1171. }
  1172. if (isError)
  1173. {
  1174. return false;
  1175. }
  1176. return true;
  1177. }
  1178. // 检查整体超时(防止一直有抖动导致 anyAxisMovedRecently 一直为 true)
  1179. if (sw.ElapsedMilliseconds > 60000) // 保守超时,一分钟,可根据需求调整
  1180. {
  1181. //停止移动
  1182. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  1183. {
  1184. Plc.WriteNode(axis.Command.ManuPositionNode, false);
  1185. }
  1186. return false;
  1187. }
  1188. Thread.Sleep(10);
  1189. }
  1190. }
  1191. catch (Exception ex)
  1192. {
  1193. LogHelper.WriteLogError("执行附加轴移动时出错!", ex);
  1194. return false;
  1195. }
  1196. finally
  1197. {
  1198. CanExecute = true;
  1199. }
  1200. }
  1201. /// <summary>
  1202. /// 附加轴,阻塞式等待运动完成,异步方法
  1203. /// </summary>
  1204. /// <param name="axisName"></param>
  1205. /// <param name="targetPos"></param>
  1206. /// <returns></returns>
  1207. public Task<bool> AdditionalAxisMoveAsync(string axisName, double targetPos)
  1208. {
  1209. return Task.Run(() => AdditionalAxisMove(axisName, targetPos));
  1210. }
  1211. /// <summary>
  1212. /// 附加轴Jog+点动
  1213. /// </summary>
  1214. /// <param name="axisName"></param>
  1215. /// <param name="distance"></param>
  1216. /// <returns></returns>
  1217. public bool AdditionalAxisJog(string axisName, double distance)
  1218. {
  1219. var axis = AdditionalAxisList.FirstOrDefault(a => a.Name.Equals(axisName, StringComparison.OrdinalIgnoreCase));
  1220. if (axis == null) return false;
  1221. if (Plc == null || !Plc.IsConnected) return false;
  1222. try
  1223. {
  1224. CanExecute = false;
  1225. // 先读取轴的实际位置,用于停滞检测
  1226. var actual = Plc.ReadNode<float>(axis.State.ActPositionNode);
  1227. //计算目标位置
  1228. double targetPos = actual + distance;
  1229. AdditionalAxisMotor(axis.Name, true);
  1230. return AdditionalAxisMove(axis.Name, targetPos);
  1231. }
  1232. catch (Exception ex)
  1233. {
  1234. LogHelper.WriteLogError("执行附加轴点动时出错!", ex);
  1235. return false;
  1236. }
  1237. finally
  1238. {
  1239. CanExecute = true;
  1240. }
  1241. }
  1242. /// <summary>
  1243. /// 附加轴Jog-点动
  1244. /// </summary>
  1245. /// <param name="axisName"></param>
  1246. /// <param name="distance"></param>
  1247. /// <returns></returns>
  1248. public bool AdditionalAxisJogNeg(string axisName, double distance)
  1249. {
  1250. return AdditionalAxisJog(axisName, -distance);
  1251. }
  1252. /// <summary>
  1253. /// 附加轴异步 Jog+点动
  1254. /// </summary>
  1255. /// <param name="axisName"></param>
  1256. /// <param name="distance"></param>
  1257. /// <returns></returns>
  1258. public Task<bool> AdditionalAxisJogAsync(string axisName, double distance)
  1259. {
  1260. return Task.Run(() => AdditionalAxisJog(axisName, distance));
  1261. }
  1262. /// <summary>
  1263. /// 附加轴异步 Jog-点动
  1264. /// </summary>
  1265. /// <param name="axisName"></param>
  1266. /// <param name="distance"></param>
  1267. /// <returns></returns>
  1268. public Task<bool> AdditionalAxisJogNegAsync(string axisName, double distance)
  1269. {
  1270. return Task.Run(() => AdditionalAxisJogNeg(axisName, distance));
  1271. }
  1272. /// <summary>
  1273. /// 获取附加轴的当前坐标
  1274. /// </summary>
  1275. /// <param name="axisName"></param>
  1276. /// <returns></returns>
  1277. public float GetAdditionalAxisCurrentPos(string axisName)
  1278. {
  1279. var axis = AdditionalAxisList.FirstOrDefault(x => x.Name == axisName);
  1280. if (axis==null)
  1281. {
  1282. return 0;
  1283. }
  1284. return Plc.ReadNode<float>(axis.State.ActPositionNode);
  1285. }
  1286. /// <summary>
  1287. /// 获取附加轴的当前坐标
  1288. /// </summary>
  1289. /// <param name="axisName"></param>
  1290. /// <returns></returns>
  1291. public Task<float> GetAdditionalAxisCurrentPosAsync(string axisName)
  1292. {
  1293. return Task.Run(()=> GetAdditionalAxisCurrentPos(axisName));
  1294. }
  1295. #endregion
  1296. #region 相机操作
  1297. /// <summary>
  1298. /// 获取相机1的位置
  1299. /// </summary>
  1300. /// <returns></returns>
  1301. public RPoint GetCamera1Pos()
  1302. {
  1303. if (Plc == null || !Plc.IsConnected) return null;
  1304. try
  1305. {
  1306. var nodeIds = Camera1AxisList.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode)).Select(a => a.State.ActPositionNode).ToArray();
  1307. var data = Plc.ReadNodes(nodeIds);
  1308. if (data == null || data.Count == 0) return null;
  1309. //获取所有的值
  1310. var values = data.Values.ToArray();
  1311. RPoint point = new RPoint();
  1312. for (int i = 0; i < Camera1AxisList.Count && i < values.Length; i++)
  1313. {
  1314. var val = values[i];
  1315. float v = 0;
  1316. if (val != null)
  1317. {
  1318. try { v = Convert.ToSingle(val); } catch { }
  1319. }
  1320. switch (Camera1AxisList[i].Name)
  1321. {
  1322. case "X": point.X = v; break;
  1323. case "Y": point.Y = v; break;
  1324. //case "Z": point.Z = v; break;
  1325. //case "U": point.U = v; break;
  1326. default: break;
  1327. }
  1328. }
  1329. return point;
  1330. }
  1331. catch (Exception ex)
  1332. {
  1333. LogHelper.WriteLogError("获取相机1的位置出错", ex);
  1334. throw;
  1335. }
  1336. }
  1337. /// <summary>
  1338. /// 获取相机1的位置,异步方法
  1339. /// </summary>
  1340. /// <returns></returns>
  1341. public Task<RPoint> GetCamera1PosAsync()
  1342. {
  1343. return Task.Run(() => GetCamera1Pos());
  1344. }
  1345. /// <summary>
  1346. /// 获取相机2的位置
  1347. /// </summary>
  1348. public RPoint GetCamera2Pos()
  1349. {
  1350. if (Plc == null || !Plc.IsConnected) return null;
  1351. try
  1352. {
  1353. var nodeIds = Camera2AxisList.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode)).Select(a => a.State.ActPositionNode).ToArray();
  1354. var data = Plc.ReadNodes(nodeIds);
  1355. if (data == null || data.Count == 0) return null;
  1356. //获取所有的值
  1357. var values = data.Values.ToArray();
  1358. RPoint point = new RPoint();
  1359. for (int i = 0; i < Camera2AxisList.Count && i < values.Length; i++)
  1360. {
  1361. var val = values[i];
  1362. float v = 0;
  1363. if (val != null)
  1364. {
  1365. try { v = Convert.ToSingle(val); } catch { }
  1366. }
  1367. switch (Camera2AxisList[i].Name)
  1368. {
  1369. case "X": point.X = v; break;
  1370. case "Y": point.Y = v; break;
  1371. //case "Z": point.Z = v; break;
  1372. //case "U": point.U = v; break;
  1373. default: break;
  1374. }
  1375. }
  1376. return point;
  1377. }
  1378. catch (Exception ex)
  1379. {
  1380. LogHelper.WriteLogError("获取相机2的位置出错", ex);
  1381. throw;
  1382. }
  1383. }
  1384. /// <summary>
  1385. /// 获取相机2的位置,异步方法
  1386. /// </summary>
  1387. /// <returns></returns>
  1388. public Task<RPoint> GetCamera2PosAsync()
  1389. {
  1390. return Task.Run(() => GetCamera2Pos());
  1391. }
  1392. /// <summary>
  1393. /// 获取相机3的位置
  1394. /// </summary>
  1395. /// <returns></returns>
  1396. public RPoint GetCamera3Pos()
  1397. {
  1398. if (Plc == null || !Plc.IsConnected) return null;
  1399. try
  1400. {
  1401. var nodeIds = Camera3AxisList.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode)).Select(a => a.State.ActPositionNode).ToArray();
  1402. var data = Plc.ReadNodes(nodeIds);
  1403. if (data == null || data.Count == 0) return null;
  1404. //获取所有的值
  1405. var values = data.Values.ToArray();
  1406. RPoint point = new RPoint();
  1407. for (int i = 0; i < Camera3AxisList.Count && i < values.Length; i++)
  1408. {
  1409. var val = values[i];
  1410. float v = 0;
  1411. if (val != null)
  1412. {
  1413. try { v = Convert.ToSingle(val); } catch { }
  1414. }
  1415. switch (Camera3AxisList[i].Name)
  1416. {
  1417. case "X": point.X = v; break;
  1418. case "Y": point.Y = v; break;
  1419. //case "Z": point.Z = v; break;
  1420. //case "U": point.U = v; break;
  1421. default: break;
  1422. }
  1423. }
  1424. return point;
  1425. }
  1426. catch (Exception ex)
  1427. {
  1428. LogHelper.WriteLogError("获取相机3的位置出错", ex);
  1429. throw;
  1430. }
  1431. }
  1432. /// <summary>
  1433. /// 获取相机3的位置,异步方法
  1434. /// </summary>
  1435. /// <returns></returns>
  1436. public Task<RPoint> GetCamera3PosAsync()
  1437. {
  1438. return Task.Run(() => GetCamera3Pos());
  1439. }
  1440. /// <summary>
  1441. /// 获取相机4的位置
  1442. /// </summary>
  1443. public RPoint GetCamera4Pos()
  1444. {
  1445. if (Plc == null || !Plc.IsConnected) return null;
  1446. try
  1447. {
  1448. var nodeIds = Camera4AxisList.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode)).Select(a => a.State.ActPositionNode).ToArray();
  1449. var data = Plc.ReadNodes(nodeIds);
  1450. if (data == null || data.Count == 0) return null;
  1451. //获取所有的值
  1452. var values = data.Values.ToArray();
  1453. RPoint point = new RPoint();
  1454. for (int i = 0; i < Camera4AxisList.Count && i < values.Length; i++)
  1455. {
  1456. var val = values[i];
  1457. float v = 0;
  1458. if (val != null)
  1459. {
  1460. try { v = Convert.ToSingle(val); } catch { }
  1461. }
  1462. switch (Camera4AxisList[i].Name)
  1463. {
  1464. case "X": point.X = v; break;
  1465. case "Y": point.Y = v; break;
  1466. //case "Z": point.Z = v; break;
  1467. //case "U": point.U = v; break;
  1468. default: break;
  1469. }
  1470. }
  1471. return point;
  1472. }
  1473. catch (Exception ex)
  1474. {
  1475. LogHelper.WriteLogError("获取相机4的位置出错", ex);
  1476. throw;
  1477. }
  1478. }
  1479. /// <summary>
  1480. /// 获取相机4的位置,异步方法
  1481. /// </summary>
  1482. /// <returns></returns>
  1483. public Task<RPoint> GetCamera4PosAsync()
  1484. {
  1485. return Task.Run(() => GetCamera4Pos());
  1486. }
  1487. /// <summary>
  1488. /// 获取指定相机的位置
  1489. /// </summary>
  1490. /// <param name="cameraIndex"></param>
  1491. /// <returns></returns>
  1492. public RPoint GetCameraPos(int cameraIndex)
  1493. {
  1494. switch (cameraIndex)
  1495. {
  1496. case 1: return GetCamera1Pos();
  1497. case 2: return GetCamera2Pos();
  1498. case 3: return GetCamera3Pos();
  1499. case 4: return GetCamera4Pos();
  1500. default: return null;
  1501. }
  1502. }
  1503. /// <summary>
  1504. /// 获取指定相机的位置,异步方法
  1505. /// </summary>
  1506. /// <param name="cameraIndex"></param>
  1507. /// <returns></returns>
  1508. public Task<RPoint> GetCameraPosAsync(int cameraIndex)
  1509. {
  1510. return Task.Run(() => GetCameraPos(cameraIndex));
  1511. }
  1512. /// <summary>
  1513. /// 指定相机的使能操作
  1514. /// </summary>
  1515. /// <param name="cameraIndex">相机编号</param>
  1516. /// <param name="state">使能状态</param>
  1517. /// <returns></returns>
  1518. public bool CameraMotor(int cameraIndex, bool state)
  1519. {
  1520. if (Plc == null || !Plc.IsConnected) return false;
  1521. try
  1522. {
  1523. List<Axis> cameraAxisList = null;
  1524. switch (cameraIndex)
  1525. {
  1526. case 1: cameraAxisList = Camera1AxisList; break;
  1527. case 2: cameraAxisList = Camera2AxisList; break;
  1528. case 3: cameraAxisList = Camera3AxisList; break;
  1529. case 4: cameraAxisList = Camera4AxisList; break;
  1530. default: return false;
  1531. }
  1532. if(cameraAxisList==null || cameraAxisList.Count==0)
  1533. {
  1534. return false;
  1535. }
  1536. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  1537. foreach (var axis in cameraAxisList)
  1538. {
  1539. if (!string.IsNullOrWhiteSpace(axis.Command.PowerNode))
  1540. {
  1541. keyValues.Add(axis.Command.PowerNode, state);
  1542. }
  1543. }
  1544. return Plc.WriteNodes(keyValues);
  1545. }
  1546. catch (Exception ex)
  1547. {
  1548. LogHelper.WriteLogError("执行指定相机使能操作时出错!", ex);
  1549. return false;
  1550. }
  1551. }
  1552. /// <summary>
  1553. /// 指定相机的使能操作,异步方法
  1554. /// </summary>
  1555. /// <param name="cameraIndex"></param>
  1556. /// <param name="state"></param>
  1557. /// <returns></returns>
  1558. public Task<bool> CameraMotorAsync(int cameraIndex, bool state)
  1559. {
  1560. return Task.Run(() => CameraMotor(cameraIndex, state));
  1561. }
  1562. /// <summary>
  1563. /// 指定相机开始运动
  1564. /// </summary>
  1565. /// <param name="cameraIndex"></param>
  1566. /// <returns></returns>
  1567. private bool StartCameraMove(int cameraIndex)
  1568. {
  1569. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  1570. List<Axis> cameraAxisList = null;
  1571. switch (cameraIndex)
  1572. {
  1573. case 1: cameraAxisList = Camera1AxisList; break;
  1574. case 2: cameraAxisList = Camera2AxisList; break;
  1575. case 3: cameraAxisList = Camera3AxisList; break;
  1576. case 4: cameraAxisList = Camera4AxisList; break;
  1577. default: return false;
  1578. }
  1579. if (cameraAxisList == null || cameraAxisList.Count == 0)
  1580. {
  1581. return false;
  1582. }
  1583. // 1. 复位所有轴的开始移动命令
  1584. foreach (var axis in cameraAxisList)
  1585. {
  1586. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  1587. {
  1588. keyValues.Add(axis.Command.ManuPositionNode, true);
  1589. }
  1590. }
  1591. return Plc.WriteNodes(keyValues);
  1592. }
  1593. /// <summary>
  1594. /// 指定相机停止运动
  1595. /// </summary>
  1596. /// <param name="cameraIndex"></param>
  1597. /// <returns></returns>
  1598. private bool StopCameraMove(int cameraIndex)
  1599. {
  1600. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  1601. List<Axis> cameraAxisList = null;
  1602. switch (cameraIndex)
  1603. {
  1604. case 1: cameraAxisList = Camera1AxisList; break;
  1605. case 2: cameraAxisList = Camera2AxisList; break;
  1606. case 3: cameraAxisList = Camera3AxisList; break;
  1607. case 4: cameraAxisList = Camera4AxisList; break;
  1608. default: return false;
  1609. }
  1610. if (cameraAxisList == null || cameraAxisList.Count == 0)
  1611. {
  1612. return false;
  1613. }
  1614. // 1. 复位所有轴的开始移动命令
  1615. foreach (var axis in cameraAxisList)
  1616. {
  1617. if (!string.IsNullOrWhiteSpace(axis.Command.ManuPositionNode))
  1618. {
  1619. keyValues.Add(axis.Command.ManuPositionNode, false);
  1620. }
  1621. //if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  1622. //{
  1623. // keyValues.Add(axis.Command.StopNode, true);
  1624. //}
  1625. }
  1626. bool result = Plc.WriteNodes(keyValues);
  1627. // 异步等待100ms后复位停止命令
  1628. //Task.Run(async () =>
  1629. //{
  1630. // await Task.Delay(100);
  1631. //Thread.Sleep(50);
  1632. //Dictionary<string, object> resetValues = new Dictionary<string, object>();
  1633. //foreach (var axis in cameraAxisList)
  1634. //{
  1635. // if (!string.IsNullOrWhiteSpace(axis.Command.StopNode))
  1636. // {
  1637. // resetValues.Add(axis.Command.StopNode, false);
  1638. // }
  1639. //}
  1640. //Plc.WriteNodes(resetValues);
  1641. //});
  1642. return result;
  1643. }
  1644. /// <summary>
  1645. /// 检查指定相机的运动是否结束,返回是否停止、是否有错误
  1646. /// </summary>
  1647. /// <param name="cameraIndex"></param>
  1648. /// <param name="position"></param>
  1649. /// <returns></returns>
  1650. private (bool isFinished, bool isError) CheckCameraMoveFinished(int cameraIndex, RPoint position)
  1651. {
  1652. List<Axis> cameraAxisList = null;
  1653. switch (cameraIndex)
  1654. {
  1655. case 1: cameraAxisList = Camera1AxisList; break;
  1656. case 2: cameraAxisList = Camera2AxisList; break;
  1657. case 3: cameraAxisList = Camera3AxisList; break;
  1658. case 4: cameraAxisList = Camera4AxisList; break;
  1659. default: return (false, false);
  1660. }
  1661. if (cameraAxisList == null || cameraAxisList.Count == 0)
  1662. {
  1663. return (false, false);
  1664. }
  1665. //检查各轴是否到位和目标位置一致
  1666. //批量获取所有轴的定位状态和位置、是否错误
  1667. var nodeIds = new List<string>();
  1668. foreach (var axis in cameraAxisList)
  1669. {
  1670. if (!string.IsNullOrWhiteSpace(axis.State.PosOKNode))
  1671. {
  1672. nodeIds.Add(axis.State.PosOKNode);
  1673. }
  1674. if (!string.IsNullOrWhiteSpace(axis.State.ActPositionNode))
  1675. {
  1676. nodeIds.Add(axis.State.ActPositionNode);
  1677. }
  1678. if (!string.IsNullOrWhiteSpace(axis.State.ErrorNode))
  1679. {
  1680. nodeIds.Add(axis.State.ErrorNode);
  1681. }
  1682. if (!string.IsNullOrWhiteSpace(axis.State.PausedNode))
  1683. {
  1684. nodeIds.Add(axis.State.PausedNode);
  1685. }
  1686. }
  1687. var res = Plc.ReadNodes(nodeIds.ToArray());
  1688. bool allOk = true;
  1689. bool isAnyError = false;
  1690. foreach (var axis in cameraAxisList)
  1691. {
  1692. bool posOk = false;
  1693. float actualPos = 0;
  1694. bool isError = false;
  1695. bool isPaused = false;
  1696. //获取此轴的定位状态、实际位置、错误状态
  1697. if (res.ContainsKey(axis.State.PosOKNode))
  1698. {
  1699. posOk = (bool)res[axis.State.PosOKNode];
  1700. }
  1701. if (res.ContainsKey(axis.State.ActPositionNode))
  1702. {
  1703. try { actualPos = Convert.ToSingle(res[axis.State.ActPositionNode]); } catch { }
  1704. }
  1705. if (res.ContainsKey(axis.State.ErrorNode))
  1706. {
  1707. isError = (bool)res[axis.State.ErrorNode];
  1708. }
  1709. if (res.ContainsKey(axis.State.PausedNode))
  1710. {
  1711. isPaused = (bool)res[axis.State.PausedNode];
  1712. }
  1713. // 更新状态
  1714. if (isError)
  1715. {
  1716. isAnyError = true;
  1717. break;
  1718. }
  1719. if (isPaused)
  1720. {
  1721. isAnyError = true;
  1722. break;
  1723. }
  1724. //检查是否到位和位置一致
  1725. float targetPos = 0;
  1726. switch (axis.Name)
  1727. {
  1728. case "X": targetPos = position.X; break;
  1729. case "Y": targetPos = position.Y; break;
  1730. case "Z": targetPos = position.Z; break;
  1731. case "U": targetPos = position.U; break;
  1732. default: targetPos = 0; break;
  1733. }
  1734. //如果定位完成且位置一致,则此轴完成,如果有错误则失败
  1735. if (!(posOk && Math.Abs(actualPos - targetPos) < 0.02))
  1736. {
  1737. allOk = false;
  1738. break;
  1739. }
  1740. }
  1741. return (allOk, isAnyError);
  1742. }
  1743. /// <summary>
  1744. /// 阻塞式等待指定相机位置运动完成
  1745. /// </summary>
  1746. /// <param name="cameraIndex"></param>
  1747. /// <param name="position"></param>
  1748. /// <returns></returns>
  1749. public bool WaitCameraMoveFinished(int cameraIndex, RPoint position)
  1750. {
  1751. if (Plc == null || !Plc.IsConnected) return false;
  1752. try
  1753. {
  1754. CanExecute = false;
  1755. List<Axis> cameraAxisList = null;
  1756. switch (cameraIndex)
  1757. {
  1758. case 1: cameraAxisList = Camera1AxisList; break;
  1759. case 2: cameraAxisList = Camera2AxisList; break;
  1760. case 3: cameraAxisList = Camera3AxisList; break;
  1761. case 4: cameraAxisList = Camera4AxisList; break;
  1762. default: return false;
  1763. }
  1764. if (cameraAxisList == null || cameraAxisList.Count == 0)
  1765. {
  1766. return false;
  1767. }
  1768. CameraMotor(cameraIndex,true);
  1769. Dictionary<string, object> keyValues = new Dictionary<string, object>();
  1770. // 1. 写入目标位置到各轴的 ManuPositionNode
  1771. keyValues = new Dictionary<string, object>();
  1772. foreach (var axis in cameraAxisList)
  1773. {
  1774. if (string.IsNullOrWhiteSpace(axis.Parameter.ManuPositionNode)) continue;
  1775. string nodeid = axis.Parameter.ManuPositionNode;
  1776. float value = 0;
  1777. switch (axis.Name)
  1778. {
  1779. case "X": value = position.X; break;
  1780. case "Y": value = position.Y; break;
  1781. case "Z": value = position.Z; break;
  1782. case "U": value = position.U; break;
  1783. default: value = 0; break;
  1784. }
  1785. keyValues.Add(nodeid, value);
  1786. }
  1787. // 2. 写入位置给所有轴
  1788. if (!Plc.WriteNodes(keyValues))
  1789. {
  1790. return false;
  1791. }
  1792. // 3. 写入开始移动命令给所有轴
  1793. if (!StartCameraMove(cameraIndex))
  1794. {
  1795. return false;
  1796. }
  1797. // 准备停滞检测:收集所有实际位置节点
  1798. var actNodes = cameraAxisList.Where(a => !string.IsNullOrWhiteSpace(a.State.ActPositionNode))
  1799. .Select(a => a.State.ActPositionNode)
  1800. .Distinct()
  1801. .ToArray();
  1802. // lastPos 存储上一次读取到的位置,lastChange 存储上次发生“实质性”变化的时间
  1803. Dictionary<string, float> lastPos = new Dictionary<string, float>();
  1804. Dictionary<string, DateTime> lastChange = new Dictionary<string, DateTime>();
  1805. foreach (var node in actNodes)
  1806. {
  1807. lastPos[node] = float.NaN;
  1808. lastChange[node] = DateTime.UtcNow;
  1809. }
  1810. const float movementThreshold = 0.01f; // 判断位置变化的阈值,避免噪声
  1811. Stopwatch sw = new Stopwatch();
  1812. sw.Start();
  1813. while (true)
  1814. {
  1815. // 先读取各轴的实际位置,用于停滞检测
  1816. Dictionary<string, object> posRead = new Dictionary<string, object>();
  1817. try
  1818. {
  1819. if (actNodes.Length > 0)
  1820. {
  1821. posRead = Plc.ReadNodes(actNodes);
  1822. }
  1823. }
  1824. catch
  1825. {
  1826. // 如果读取失败,继续让 CheckMoveFinished 来处理状态或超时
  1827. }
  1828. var now = DateTime.UtcNow;
  1829. // 更新每个节点的变化时间:只要任意一个轴在最近 Timeout 时间内有变化,就视为系统仍在运动
  1830. foreach (var node in actNodes)
  1831. {
  1832. float actual = 0;
  1833. if (posRead != null && posRead.ContainsKey(node))
  1834. {
  1835. var raw = posRead[node];
  1836. if (raw != null)
  1837. {
  1838. try { actual = Convert.ToSingle(raw); } catch { /* 保持 actual = 0 */ }
  1839. }
  1840. }
  1841. if (float.IsNaN(lastPos[node]))
  1842. {
  1843. lastPos[node] = actual;
  1844. lastChange[node] = now;
  1845. }
  1846. else
  1847. {
  1848. if (Math.Abs(actual - lastPos[node]) > movementThreshold)
  1849. {
  1850. // 有实质性变化,更新记录时间和值
  1851. lastPos[node] = actual;
  1852. lastChange[node] = now;
  1853. }
  1854. // 否则保持 lastChange 不变(表示该轴最近一次变化的时间)
  1855. }
  1856. }
  1857. // 判断是否至少有一个轴在最近 Timeout 时间内发生过变化(即认为还在运动)
  1858. bool anyAxisMovedRecently = actNodes.Any(node => (now - lastChange[node]).TotalMilliseconds <= 500);
  1859. // 如果没有任何轴在最近 Timeout 时间内发生变化,则认为出现停滞异常
  1860. if (!anyAxisMovedRecently && actNodes.Length > 0)
  1861. {
  1862. StopCameraMove(cameraIndex);
  1863. LogHelper.WriteLogInfo($"轴停滞超时(整体判定),目标位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U},超时阈值(ms)={Timeout}");
  1864. return false;
  1865. }
  1866. // 检查是否整体到位或有错误(保留原有逻辑)
  1867. var (isFinished, isError) = CheckCameraMoveFinished(cameraIndex, position);
  1868. if (isFinished)
  1869. {
  1870. StopCameraMove(cameraIndex);
  1871. return true;
  1872. }
  1873. if (isError)
  1874. {
  1875. StopCameraMove(cameraIndex);
  1876. LogHelper.WriteLogInfo($"相机{cameraIndex}执行移动时发生错误,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  1877. return false;
  1878. }
  1879. // 检查整体超时(防止一直有抖动导致 anyAxisMovedRecently 一直为 true)
  1880. if (sw.ElapsedMilliseconds > 60000) // 保守超时,一分钟,可根据需求调整
  1881. {
  1882. LogHelper.WriteLogInfo($"相机{cameraIndex}执行移动超时,位置:X={position.X},Y={position.Y},Z={position.Z},U={position.U}");
  1883. StopCameraMove(cameraIndex);
  1884. return false;
  1885. }
  1886. Thread.Sleep(10);
  1887. }
  1888. }
  1889. catch (Exception ex)
  1890. {
  1891. LogHelper.WriteLogError($"执行相机{cameraIndex},阻塞式等待运动完成时出错!", ex);
  1892. CanExecute = true;
  1893. return false;
  1894. }
  1895. finally
  1896. {
  1897. CanExecute = true;
  1898. }
  1899. }
  1900. /// <summary>
  1901. /// 阻塞式等待指定相机位置运动完成,异步方法
  1902. /// </summary>
  1903. /// <param name="cameraIndex"></param>
  1904. /// <param name="position"></param>
  1905. /// <returns></returns>
  1906. public Task<bool> WaitCameraMoveFinishedAsync(int cameraIndex, RPoint position)
  1907. {
  1908. return Task.Run(() => WaitCameraMoveFinished(cameraIndex, position));
  1909. }
  1910. /// <summary>
  1911. /// 指定相机的轴点动操作
  1912. /// </summary>
  1913. /// <param name="cameraIndex"></param>
  1914. /// <param name="axisName"></param>
  1915. /// <param name="distance"></param>
  1916. /// <returns></returns>
  1917. public bool CameraJog(int cameraIndex, string axisName, double distance)
  1918. {
  1919. List<Axis> cameraAxisList = null;
  1920. switch (cameraIndex)
  1921. {
  1922. case 1: cameraAxisList = Camera1AxisList; break;
  1923. case 2: cameraAxisList = Camera2AxisList; break;
  1924. case 3: cameraAxisList = Camera3AxisList; break;
  1925. case 4: cameraAxisList = Camera4AxisList; break;
  1926. default: return false;
  1927. }
  1928. if (cameraAxisList == null || cameraAxisList.Count == 0)
  1929. {
  1930. return false;
  1931. }
  1932. var axis = cameraAxisList.FirstOrDefault(a => a.Name.Equals(axisName, StringComparison.OrdinalIgnoreCase));
  1933. if (axis == null) return false;
  1934. if (Plc == null || !Plc.IsConnected) return false;
  1935. try
  1936. {
  1937. CanExecute = false;
  1938. // 获取当前指定相机轴的位置
  1939. var currentPos = GetCameraPos(cameraIndex);
  1940. CameraMotor(cameraIndex, true);
  1941. //根据轴名称计算目标位置
  1942. switch (axisName)
  1943. {
  1944. case "X":
  1945. currentPos.X += (float)distance;
  1946. break;
  1947. case "Y":
  1948. currentPos.Y += (float)distance;
  1949. break;
  1950. //case "Z":
  1951. // currentPos.Z += (float)distance;
  1952. // break;
  1953. //case "U":
  1954. // currentPos.U += (float)distance;
  1955. // break;
  1956. default:
  1957. break;
  1958. }
  1959. //阻塞式等待运动完成
  1960. return WaitCameraMoveFinished(cameraIndex, currentPos);
  1961. }
  1962. catch (Exception ex)
  1963. {
  1964. LogHelper.WriteLogError("执行指定相机轴点动时出错!", ex);
  1965. return false;
  1966. }
  1967. finally
  1968. {
  1969. CanExecute = true;
  1970. }
  1971. }
  1972. /// <summary>
  1973. /// 指定相机的轴点动操作,异步方法
  1974. /// </summary>
  1975. /// <param name="cameraIndex"></param>
  1976. /// <param name="axisName"></param>
  1977. /// <param name="distance"></param>
  1978. /// <returns></returns>
  1979. public Task<bool> CameraJogAsync(int cameraIndex, string axisName, double distance)
  1980. {
  1981. return Task.Run(() => CameraJog(cameraIndex, axisName, distance));
  1982. }
  1983. #endregion
  1984. #endregion
  1985. #region 收发数据
  1986. public string SendAndReceive(string send) => string.Empty;
  1987. public Task<string> SendAndReceiveAsync(string send) => Task.FromResult(string.Empty);
  1988. public string SendAndReceive(ITcpSessionClient client, string send) => string.Empty;
  1989. public Task<string> SendAndReceiveAsync(ITcpSessionClient client, string send) => Task.FromResult(string.Empty);
  1990. public void Send(string send) { }
  1991. public Task SendAsync(string send) => Task.CompletedTask;
  1992. public void Send(ITcpSessionClient client, string send) { }
  1993. public Task SendAsync(ITcpSessionClient client, string send) => Task.CompletedTask;
  1994. public Encoding GetEncoding() => Encoding.Default;
  1995. #endregion
  1996. #region 属性通知
  1997. public event PropertyChangedEventHandler PropertyChanged;
  1998. protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
  1999. {
  2000. if (EqualityComparer<T>.Default.Equals(storage, value)) return false;
  2001. storage = value;
  2002. OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
  2003. return true;
  2004. }
  2005. protected void OnPropertyChanged(PropertyChangedEventArgs args) => PropertyChanged?.Invoke(this, args);
  2006. #endregion
  2007. #region IRobot SetTool/SelectTool stubs
  2008. public bool SetTool(int index, double x, double y) => true;
  2009. public Task<bool> SetToolAsync(int index, double x, double y) => Task.FromResult(true);
  2010. public bool SelectTool(int index) => true;
  2011. public Task<bool> SelectToolAsync(int index) => Task.FromResult(true);
  2012. #endregion
  2013. }
  2014. }