SimulatedMotionCard.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. using HandyControl.Controls;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading;
  6. using TeamAAS.Motion.Interfaces;
  7. using TeamAAS.Motion.Models;
  8. using static TeamAAS.Motion.Enums.MotionEnums;
  9. using static TeamAAS.Motion.Events.CardAxisEventArgs;
  10. namespace TeamAAS.Motion.Motions
  11. {
  12. /// <summary>
  13. /// 仿真运动卡:无硬件环境下的全功能实现(联调/演示/单元测试用)。
  14. /// 轴位置按指令速度渐变逼近目标(后台定时器推进),IO 点内存模拟。
  15. /// 品牌适配器(雷赛/固高/IMC60G)实现 IMotionCard 时可直接参照本类的状态机结构。
  16. /// </summary>
  17. public class SimulatedMotionCard : IMotionControl
  18. {
  19. private readonly MotionDeviceConfig _cfg;
  20. private readonly int _maxAxisCount;
  21. private readonly SimulatedAxis[] _axes;
  22. private readonly bool [] SimulatedDI=new bool[100];
  23. private readonly bool [] SimulatedDO=new bool[100];
  24. private Timer _updateTimer;
  25. private bool _isConnected = false;
  26. private readonly object _lock = new object();
  27. private const double UPDATE_INTERVAL_MS = 10; // 10ms 更新一次
  28. public string CardName => _cfg.Name;
  29. public bool IsConnected { get; private set; }
  30. public int MaxAxisCount => _cfg.AxisCount;
  31. public event EventHandler<ConnectionStateChangedEventArgs> ConnectionStateChanged;
  32. public event EventHandler<ErrorOccurredEventArgs> ErrorOccurred;
  33. public SimulatedMotionCard(MotionDeviceConfig cfg)
  34. {
  35. _cfg = cfg ?? new MotionDeviceConfig();
  36. _axes= new SimulatedAxis[ MaxAxisCount ];
  37. for ( int i = 0; i < MaxAxisCount; i++ )
  38. _axes[ i ] = new SimulatedAxis(i);
  39. for ( int i = 0; i < SimulatedDI.Length; i++ )
  40. SimulatedDI[ i ] = ( i % 2 == 0 );
  41. }
  42. protected virtual void OnConnectionStateChanged(ConnectionStateChangedEventArgs e)
  43. {
  44. ConnectionStateChanged?.Invoke(this, e);
  45. }
  46. protected virtual void OnErrorOccurred(ErrorOccurredEventArgs e)
  47. {
  48. ErrorOccurred?.Invoke(this, e);
  49. }
  50. public bool Connect(string connectionString)
  51. {
  52. lock ( _lock )
  53. {
  54. if ( _isConnected ) return true;
  55. // 模拟连接成功
  56. _isConnected = true;
  57. // 启动定时器更新轴状态
  58. _updateTimer = new Timer(UpdateAxes, null, 0, ( int ) UPDATE_INTERVAL_MS);
  59. OnConnectionStateChanged(new ConnectionStateChangedEventArgs(true));
  60. return true;
  61. }
  62. }
  63. public void Disconnect()
  64. {
  65. lock ( _lock )
  66. {
  67. if ( !_isConnected ) return;
  68. _isConnected = false;
  69. _updateTimer?.Dispose();
  70. _updateTimer = null;
  71. OnConnectionStateChanged(new ConnectionStateChangedEventArgs(false));
  72. }
  73. }
  74. public IAxis GetAxis(int axisNo)
  75. {
  76. if ( axisNo < 0 || axisNo >= _maxAxisCount )
  77. throw new ArgumentOutOfRangeException(nameof(axisNo), "轴号超出范围");
  78. return _axes[ axisNo ];
  79. }
  80. public IList<IAxis> GetAxes()
  81. {
  82. return _axes.Cast<IAxis>().ToList();
  83. }
  84. public void MoveLinear(double[] targetPositions, double velocity)
  85. {
  86. if ( !_isConnected ) throw new InvalidOperationException("控制卡未连接");
  87. if ( targetPositions.Length > _maxAxisCount )
  88. throw new ArgumentException("目标位置数组长度超过轴数");
  89. // 模拟:简单逐个轴移动(实际插补需协调)
  90. for ( int i = 0; i < targetPositions.Length; i++ )
  91. {
  92. var axis = _axes[i];
  93. if ( axis != null )
  94. axis.MoveTo(targetPositions[ i ]);
  95. }
  96. }
  97. public void MoveArc(double[] centerPoint, double[] targetPositions, double velocity)
  98. {
  99. if ( !_isConnected ) throw new InvalidOperationException("控制卡未连接");
  100. if ( targetPositions.Length > _maxAxisCount )
  101. throw new ArgumentException("目标位置数组长度超过轴数");
  102. // 模拟:简单逐个轴移动(实际插补需协调)
  103. for ( int i = 0; i < targetPositions.Length; i++ )
  104. {
  105. var axis = _axes[i];
  106. if ( axis != null )
  107. axis.MoveTo(targetPositions[ i ]);
  108. }
  109. }
  110. public void EmergencyStop()
  111. {
  112. if ( !_isConnected ) return;
  113. foreach ( var axis in _axes )
  114. axis.Stop();
  115. }
  116. public bool ReadDI(int portIndex)
  117. {
  118. return SimulatedDI[ portIndex ];
  119. }
  120. public void WriteDO(int portIndex, bool value)
  121. {
  122. SimulatedDO[ portIndex ] = value;
  123. }
  124. // 定时更新所有轴
  125. private void UpdateAxes(object state)
  126. {
  127. lock ( _lock )
  128. {
  129. if ( !_isConnected ) return;
  130. double deltaTime = UPDATE_INTERVAL_MS / 1000.0;
  131. foreach ( var axis in _axes )
  132. axis.Update(deltaTime);
  133. }
  134. }
  135. public void Dispose()
  136. {
  137. Disconnect();
  138. }
  139. }
  140. public class SimulatedAxis : IAxis
  141. {
  142. private readonly object _lock = new object();
  143. private AxisState _state = AxisState.Off;
  144. private bool _isEnabled = false;
  145. private bool _isMoving = false;
  146. private bool _isHomed = false;
  147. private double _commandPos = 0.0;
  148. private double _actualPos = 0.0;
  149. private double _actualVel = 0.0;
  150. private double _targetPos = 0.0;
  151. private double _velocity = 100.0; // 单位/秒
  152. private double _accel = 500.0;
  153. private double _decel = 500.0;
  154. private double _jerk = 1000.0;
  155. private double _jogVelocity = 0.0; // 0表示不点动
  156. public int AxisNo { get; }
  157. public string Name { get; set; }
  158. public AxisState State => _state;
  159. public bool IsEnabled => _isEnabled;
  160. public bool IsMoving => _isMoving;
  161. public bool IsHomed => _isHomed;
  162. public double CommandPosition => _commandPos;
  163. public double ActualPosition => _actualPos;
  164. public double ActualVelocity => _actualVel;
  165. public double Velocity { get => _velocity; set => _velocity = value; }
  166. public double Acceleration { get => _accel; set => _accel = value; }
  167. public double Deceleration { get => _decel; set => _decel = value; }
  168. public double Jerk { get => _jerk; set => _jerk = value; }
  169. public event EventHandler<AxisMotionEventArgs> MotionStarted;
  170. public event EventHandler<AxisMotionEventArgs> MotionCompleted;
  171. public event EventHandler<AxisStateChangedEventArgs> StateChanged;
  172. public event EventHandler<AxisErrorEventArgs> ErrorOccurred;
  173. public SimulatedAxis(int axisNo)
  174. {
  175. AxisNo = axisNo;
  176. Name = $"Axis-{axisNo}";
  177. }
  178. // 由控制卡的定时器调用,更新轴状态(模拟位置变化)
  179. internal void Update(double deltaTime)
  180. {
  181. lock ( _lock )
  182. {
  183. if ( !_isEnabled || _state == AxisState.Error || _state == AxisState.Off )
  184. return;
  185. // 如果处于点动状态(连续运动)
  186. if ( _state == AxisState.ContinuousMotion && Math.Abs(_jogVelocity) > 0.0001 )
  187. {
  188. double delta = _jogVelocity * deltaTime;
  189. _commandPos += delta;
  190. _actualPos += delta; // 无误差模拟
  191. _actualVel = _jogVelocity;
  192. return;
  193. }
  194. // 如果处于点位运动状态(离散运动)
  195. if ( _state == AxisState.DiscreteMotion )
  196. {
  197. double remaining = _targetPos - _actualPos;
  198. double distance = Math.Abs(remaining);
  199. if ( distance < 0.0001 )
  200. {
  201. // 到达目标
  202. _actualPos = _targetPos;
  203. _commandPos = _targetPos;
  204. _actualVel = 0;
  205. SetState(AxisState.StandStill);
  206. _isMoving = false;
  207. OnMotionCompleted(new AxisMotionEventArgs(AxisNo, _targetPos, _actualPos));
  208. return;
  209. }
  210. // 简单匀速运动(为模拟可加入加减速,但此处保持简单)
  211. double speed = Math.Sign(remaining) * _velocity;
  212. double step = speed * deltaTime;
  213. // 防止过冲
  214. if ( Math.Abs(step) > Math.Abs(remaining) )
  215. step = remaining;
  216. _actualPos += step;
  217. _commandPos = _actualPos; // 指令位置跟随
  218. _actualVel = step / deltaTime;
  219. }
  220. }
  221. }
  222. // 启动点位运动(内部调用)
  223. private void StartMoveTo(double target)
  224. {
  225. lock ( _lock )
  226. {
  227. if ( !_isEnabled )
  228. {
  229. OnError("轴未使能,无法运动");
  230. return;
  231. }
  232. if ( _state == AxisState.Error )
  233. {
  234. OnError("轴处于错误状态");
  235. return;
  236. }
  237. _targetPos = target;
  238. SetState(AxisState.DiscreteMotion);
  239. _isMoving = true;
  240. _jogVelocity = 0; // 取消点动
  241. OnMotionStarted(new AxisMotionEventArgs(AxisNo, target, _actualPos));
  242. }
  243. }
  244. #region IAxis 方法实现
  245. public void Enable()
  246. {
  247. lock ( _lock )
  248. {
  249. if ( _isEnabled ) return;
  250. _isEnabled = true;
  251. if ( _state == AxisState.Off ) SetState(AxisState.StandStill);
  252. }
  253. }
  254. public void Disable()
  255. {
  256. lock ( _lock )
  257. {
  258. if ( !_isEnabled ) return;
  259. // 停止运动
  260. _isMoving = false;
  261. _jogVelocity = 0;
  262. SetState(AxisState.Off);
  263. _isEnabled = false;
  264. }
  265. }
  266. public void MoveTo(double position)
  267. {
  268. StartMoveTo(position);
  269. }
  270. public void MoveBy(double distance)
  271. {
  272. double target = _actualPos + distance;
  273. StartMoveTo(target);
  274. }
  275. public void Jog(double velocity)
  276. {
  277. lock ( _lock )
  278. {
  279. if ( !_isEnabled )
  280. {
  281. OnError("轴未使能,无法点动");
  282. return;
  283. }
  284. if ( _state == AxisState.Error )
  285. {
  286. OnError("轴处于错误状态");
  287. return;
  288. }
  289. _jogVelocity = velocity;
  290. SetState(AxisState.ContinuousMotion);
  291. _isMoving = true;
  292. _actualVel = velocity;
  293. // 触发运动开始事件(带一个虚拟目标,因为点动无终点)
  294. OnMotionStarted(new AxisMotionEventArgs(AxisNo, double.NaN, _actualPos));
  295. }
  296. }
  297. public void Stop()
  298. {
  299. lock ( _lock )
  300. {
  301. if ( !_isMoving ) return;
  302. _jogVelocity = 0;
  303. if ( _state == AxisState.DiscreteMotion )
  304. {
  305. // 对于点位运动,停止后当前位置即为最终位置(但未到达目标,触发停止完成事件?可以触发完成但标记未到位)
  306. // 简单处理:立即停止,触发完成事件并报告未到达目标
  307. _actualVel = 0;
  308. SetState(AxisState.StandStill);
  309. _isMoving = false;
  310. OnMotionCompleted(new AxisMotionEventArgs(AxisNo, _targetPos, _actualPos));
  311. }
  312. else if ( _state == AxisState.ContinuousMotion )
  313. {
  314. // 点动停止
  315. _actualVel = 0;
  316. SetState(AxisState.StandStill);
  317. _isMoving = false;
  318. OnMotionCompleted(new AxisMotionEventArgs(AxisNo, double.NaN, _actualPos));
  319. }
  320. }
  321. }
  322. public void Home(HomeMode mode = HomeMode.Default)
  323. {
  324. lock ( _lock )
  325. {
  326. if ( !_isEnabled )
  327. {
  328. OnError("轴未使能,无法回零");
  329. return;
  330. }
  331. // 模拟回零:将当前位置设为0
  332. _actualPos = 0;
  333. _commandPos = 0;
  334. _isHomed = true;
  335. SetState(AxisState.StandStill);
  336. // 触发回零完成事件?可以用MotionCompleted,但不设目标位置
  337. OnMotionCompleted(new AxisMotionEventArgs(AxisNo, 0, 0));
  338. }
  339. }
  340. public void SetPosition(double position)
  341. {
  342. lock ( _lock )
  343. {
  344. _actualPos = position;
  345. _commandPos = position;
  346. }
  347. }
  348. public void SetMotionParams(MotionParams parameters)
  349. {
  350. lock ( _lock )
  351. {
  352. if ( parameters != null )
  353. {
  354. _velocity = parameters.Velocity;
  355. _accel = parameters.Acceleration;
  356. _decel = parameters.Deceleration;
  357. _jerk = parameters.Jerk;
  358. }
  359. }
  360. }
  361. #endregion
  362. // 内部状态变更辅助
  363. private void SetState(AxisState newState)
  364. {
  365. if ( _state != newState )
  366. {
  367. var old = _state;
  368. _state = newState;
  369. OnStateChanged(new AxisStateChangedEventArgs(AxisNo, old, newState));
  370. }
  371. }
  372. // 事件触发辅助
  373. protected virtual void OnMotionStarted(AxisMotionEventArgs e) => MotionStarted?.Invoke(this, e);
  374. protected virtual void OnMotionCompleted(AxisMotionEventArgs e) => MotionCompleted?.Invoke(this, e);
  375. protected virtual void OnStateChanged(AxisStateChangedEventArgs e) => StateChanged?.Invoke(this, e);
  376. protected virtual void OnError(string message) => ErrorOccurred?.Invoke(this, new AxisErrorEventArgs(AxisNo, message));
  377. }
  378. /// <summary>仿真 IO 卡(16进/16出,内存模拟,批量接口齐全)。</summary>
  379. public class SimulatedIOCard : Global.Devices.IIOCard
  380. {
  381. private readonly MotionDeviceConfig _cfg;
  382. private readonly bool[] _inputs;
  383. private readonly bool[] _outputs;
  384. public string Name => _cfg.Name;
  385. public int InputCount => _inputs.Length;
  386. public int OutputCount => _outputs.Length;
  387. public bool IsConnected { get; private set; }
  388. public SimulatedIOCard(MotionDeviceConfig cfg)
  389. {
  390. _cfg = cfg ?? new MotionDeviceConfig();
  391. _inputs = new bool[ Math.Max(1, _cfg.InputCount) ];
  392. _outputs = new bool[ Math.Max(1, _cfg.OutputCount) ];
  393. }
  394. public bool Open() { IsConnected = true; return true; }
  395. public void Close() { IsConnected = false; }
  396. public bool[] ReadAllInputs()
  397. {
  398. lock ( _inputs ) { return ( bool[] ) _inputs.Clone(); }
  399. }
  400. public bool[] ReadAllOutputs()
  401. {
  402. lock ( _outputs ) { return ( bool[] ) _outputs.Clone(); }
  403. }
  404. public bool WriteOutput(int index, bool value)
  405. {
  406. if ( index < 0 || index >= _outputs.Length ) return false;
  407. lock ( _outputs ) { _outputs[ index ] = value; }
  408. return true;
  409. }
  410. public bool WriteOutputs(bool[] values)
  411. {
  412. if ( values == null ) return false;
  413. lock ( _outputs )
  414. {
  415. int n = Math.Min(values.Length, _outputs.Length);
  416. for ( int i = 0; i < n; i++ ) _outputs[ i ] = values[ i ];
  417. }
  418. return true;
  419. }
  420. }
  421. }