MotionPluginHelper.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using TeamAAS.Global.Devices;
  5. using TeamAAS.Motion;
  6. namespace Plugins.Motion
  7. {
  8. internal static class MotionPluginHelper
  9. {
  10. public static IMotionCard GetCard(MotionManager mgr, string name, out string error)
  11. {
  12. error = null;
  13. if (string.IsNullOrWhiteSpace(name))
  14. {
  15. error = "未选择运动卡";
  16. return null;
  17. }
  18. if (mgr == null)
  19. {
  20. error = "MotionManager 未初始化";
  21. return null;
  22. }
  23. var card = mgr.GetMotion(name);
  24. if (card == null)
  25. error = $"找不到运动卡: {name}";
  26. return card;
  27. }
  28. public static string EnsureConnected(IMotionCard card, bool autoConnect)
  29. {
  30. if (card.IsConnected) return null;
  31. if (!autoConnect) return $"运动卡未连接: {card.Name}";
  32. return card.Open() ? null : $"自动连接失败: {card.Name}";
  33. }
  34. public static string EnsureEnabled(IMotionCard card, int axis, bool autoEnable)
  35. {
  36. if (axis < 0)
  37. {
  38. if (!autoEnable) return "未使能且未勾选自动使能";
  39. return card.SetEnable(-1, true) ? null : "全部轴自动使能失败";
  40. }
  41. var st = card.GetAxisStatus(axis);
  42. if (st == null) return $"轴号超出范围: {axis}";
  43. if (st.IsEnabled) return null;
  44. if (!autoEnable) return $"轴 {axis} 未使能(可勾选「未使能时自动使能」,或在流程中加入轴使能节点)";
  45. return card.SetEnable(axis, true) ? null : $"轴 {axis} 自动使能失败";
  46. }
  47. public static string WaitIdle(IMotionCard card, int axis, int timeoutMs, CancellationToken token)
  48. {
  49. var start = DateTime.UtcNow;
  50. while (true)
  51. {
  52. token.ThrowIfCancellationRequested();
  53. var st = card.GetAxisStatus(axis);
  54. if (st == null) return $"无法读取轴 {axis} 状态";
  55. if (st.Alarm) return $"轴 {axis} 报警";
  56. if (!st.IsMoving) return null;
  57. if (timeoutMs > 0 && (DateTime.UtcNow - start).TotalMilliseconds > timeoutMs)
  58. return $"等待到位超时 {timeoutMs}ms(轴 {axis})";
  59. Thread.Sleep(20);
  60. }
  61. }
  62. public static void FillStatus(Dictionary<string, object> res, AxisStatus st)
  63. {
  64. if (st == null) return;
  65. res["最终位置"] = st.Position;
  66. res["使能"] = st.IsEnabled;
  67. res["已回零"] = st.IsHomed;
  68. res["运动中"] = st.IsMoving;
  69. }
  70. }
  71. }