类 MasterScope

java.lang.Object
com.darra.ethercat.sugar.MasterScope
所有已实现的接口:
AutoCloseable

public final class MasterScope extends Object implements AutoCloseable
try-with-resources 友好的 EtherCATMaster 生命周期 scope.

主线 EtherCATMaster 已实现 AutoCloseable, try-with-resources 已经 work. 但有几个常见的"扩展释放" 需求, 主线 close() 不覆盖:

  • 退出前自动切回 INIT 状态 (避免硬件保持 OP 状态导致下次启动撞 PDI watchdog)
  • 退出前先 stop() PDO 周期, 再 close() — 主线 close() 已做, 但有些版本需显式
  • 同时 close 一组挂在 master 上的子资源 (DiagnosticQueue 等)

典型用法:

 try (MasterScope scope = MasterScope.of(master).resetToInitOnClose()) {
     scope.attach(DiagnosticQueue.attach(master, 1024));
     master.setState(EcState.OP);
     master.start();
     ...
 } // close 顺序: 先 close 子资源, 再 stop+setInit+master.close()
 

不持有原生资源 — 失败/double close 都安全幂等.

从以下版本开始:
2026-05
  • 方法详细资料

    • of

      public static MasterScope of(EtherCATMaster master)
      包装一个已经 build 完成的 master.
    • resetToInitOnClose

      public MasterScope resetToInitOnClose()
      退出 scope 时把 master 切回 INIT 状态 (推荐 — 硬件干净退出).
    • stopBeforeClose

      public MasterScope stopBeforeClose(boolean stop)
      关闭前是否先 stop() PDO. 默认 true, 极少需要关掉.
    • attach

      public <T extends AutoCloseable> T attach(T resource)
      附加一个子资源, 与 scope 同生命周期. close 时按 LIFO 顺序释放, 异常被压制 但不阻断后续释放.
    • master

      public EtherCATMaster master()
      返回包装的 master 引用.
    • close

      public void close()
      指定者:
      close 在接口中 AutoCloseable