Properties and state machine
Build entry points (create / setENI / build / validate / BuildResult) are covered in Initialization; this page covers only the runtime properties and the state machine.
Properties
The table below lists every available entry point (slaveCount() and so on). state() / errorCode() and the like return enums (EcState / EcALState), not raw integers.
| Category | Property | Type | R/W | Description |
|---|---|---|---|---|
| Basic information | MasterIndex | short (public final) | read-only | Master index (fixed after construction) |
| masterNumber() | short | read-only | Master index (alias of MasterIndex) | |
| slaveCount() | int | read-only | Number of slaves detected on the network | |
| slaves() | List<Slave> | read-only | Slave list (immutable); built only when setNetwork(...) scans the NICs, and the DENI one-step initialization path leaves an empty list | |
| isDisposed() | boolean | read-only | Whether the master has been disposed | |
| isStarted() | boolean | read-only | Whether the PDO cycle has started | |
| Runtime | aggregatedState() | EcState.Status | read-only | System aggregate state: the lowest base state across all real slaves plus the aggregated Error bit; returns NONE (unknown) when no slave takes part and never falls back to the master-state cache |
| Network and link | primaryNicName() | String | read-only | Primary NIC name |
| redundantNicName() | String | read-only | Redundant NIC name | |
| linkState() | EcLinkState | read-only | Link state enum value | |
| Error codes | errorCode() | EcALState | read-only | Automatic alarm error code on a fault (AL Status Code) |
| errorCnt() | int | read-only | Error count | |
| WKC | WKC() | short | read-only | Actual working counter of the last PDO exchange cycle |
| expectedWKC() | short | read-only | Expected working counter (fixed after mapping) | |
| expectedWKC(short) | void | write-only | Override the expected WKC (advanced use) | |
| Slave grouping | activeGroupCount() | byte | read-only | Number of active groups (valid after mapping) |
| I/O mapping | obytes() / ibytes() | int | read-only | Total output/input bytes |
| obits() / ibits() | short | read-only | Total output/input bits | |
| DC | hasDC() | boolean | read-only | Whether any slave in the network supports DC |
| dcTime() | long | read-only | DC timestamp (nanoseconds) |
EcLinkState enum
Nested enum inside com.darra.ethercat.data.EtherCATTypes (written as EtherCATTypes.EcLinkState):
public enum EcLinkState {
DISCONNECTED(0), // confirmed down: both configured ports are explicitly DOWN
CONNECTED(1), // both the primary and the redundant NIC are connected
PRIMARY_ONLY(3), // only the primary NIC is connected
SECONDARY_ONLY(4), // only the redundant NIC is connected
UNKNOWN(5); // unknown: not initialized / runtime process image not observable / the PHY has not reported a state yet
}
DISCONNECTED means only "confirmed down"; when the physical link cannot be read, UNKNOWN is returned. It does not mean disconnected, so the UI should show "unknown" rather than "link down".
EcALState enum
Nested enum inside com.darra.ethercat.data.EtherCATTypes (written as EtherCATTypes.EcALState):
public enum EcALState {
NO_ERROR(0x0000), // no error
UNSPECIFIED_ERROR(0x0001), // unspecified error
NO_MEMORY(0x0002), // out of memory
INVALID_DEVICE_SETUP(0x0003), // invalid device setup (for example a bus coupler with no physical module connected)
INVALID_REVISION(0x0004), // output/input mapping does not match the hardware or software revision
SII_EEPROM_MISMATCH(0x0006), // SII/EEPROM information (process data description or revision number) does not match the firmware
FIRMWARE_UPDATE_FAILED(0x0007), // firmware update did not succeed, the old firmware is still running (re-enter the BOOT state for the FoE download)
LICENSE_ERROR(0x000E), // license error (contact the slave vendor to activate the function license)
INVALID_STATE_CHANGE(0x0011), // invalid state change
UNKNOWN_REQUESTED_STATE(0x0012), // unknown state requested
BOOTSTRAP_NOT_SUPPORTED(0x0013), // Bootstrap not supported
NO_VALID_FIRMWARE(0x0014), // no valid firmware
INVALID_MAILBOX_CONFIG(0x0015), // ETG.1020: invalid mailbox configuration in BOOT state
INVALID_MAILBOX_CONFIG2(0x0016), // ETG.1020: invalid mailbox configuration in PreOp state
INVALID_SYNC_MANAGER_CONFIG(0x0017), // invalid Sync Manager configuration
NO_VALID_INPUTS(0x0018), // no valid inputs
NO_VALID_OUTPUTS(0x0019), // no valid outputs
SYNC_ERROR(0x001A), // synchronization error
SYNC_MANAGER_WATCHDOG(0x001B), // Sync Manager watchdog
INVALID_SYNC_MANAGER_TYPES(0x001C), // invalid Sync Manager types
INVALID_OUTPUT_CONFIG(0x001D), // invalid output configuration
INVALID_INPUT_CONFIG(0x001E), // invalid input configuration
INVALID_WATCHDOG_CONFIG(0x001F), // invalid watchdog configuration
NEEDS_COLD_START(0x0020), // cold start required
NEEDS_INIT(0x0021), // Init state required
NEEDS_PREOP(0x0022), // PreOp state required
NEEDS_SAFEOP(0x0023), // SafeOp state required
INVALID_INPUT_MAPPING(0x0024), // invalid input mapping
INVALID_OUTPUT_MAPPING(0x0025), // invalid output mapping
INCONSISTENT_SETTINGS(0x0026), // inconsistent settings
FREERUN_NOT_SUPPORTED(0x0027), // free run not supported
SYNC_NOT_SUPPORTED(0x0028), // synchronization not supported
FREERUN_NEEDS_3BUFFER(0x0029), // free run needs triple buffering
BACKGROUND_WATCHDOG(0x002A), // background watchdog
NO_VALID_IO(0x002B), // no valid I/O
FATAL_SYNC_ERROR(0x002C), // fatal synchronization error
NO_SYNC_ERROR(0x002D), // sync not received (SAFEOP waits for the first Sync0/Sync1 and refuses SO→OP); the literal name "No sync error" does not mean error-free
CYCLE_TIME_TOO_SMALL(0x002E), // cycle time too small (master cycle < the minimum cycle time the slave supports)
INVALID_DC_SYNC_CONFIG(0x0030), // invalid DC synchronization configuration
INVALID_DC_LATCH(0x0031), // invalid DC latch
PLL_ERROR(0x0032), // PLL error
DC_SYNC_IO_ERROR(0x0033), // DC synchronization I/O error
DC_SYNC_TIMEOUT(0x0034), // DC synchronization timeout
INVALID_DC_SYNC_CYCLE(0x0035), // invalid DC synchronization cycle
INVALID_SYNC0_CYCLE(0x0036), // invalid SYNC0 cycle
INVALID_SYNC1_CYCLE(0x0037), // invalid SYNC1 cycle
MAILBOX_AOE(0x0041), // mailbox AoE error
MAILBOX_EOE(0x0042), // mailbox EoE error
MAILBOX_COE(0x0043), // mailbox CoE error
MAILBOX_FOE(0x0044), // mailbox FoE error
MAILBOX_SOE(0x0045), // mailbox SoE error
MAILBOX_VOE(0x004F), // mailbox VoE error
EEPROM_NO_ACCESS(0x0050), // no access permission for the EEPROM
EEPROM_ERROR(0x0051), // EEPROM error
EXTERNAL_HARDWARE_NOT_READY(0x0052), // external hardware not ready (the slave refuses the state change because an external connection or signal is missing)
SLAVE_RESTARTED(0x0060), // slave restarted
DEVICE_ID_UPDATED(0x0061), // device ID updated
MODULE_IDENT_LIST_MISMATCH(0x0070), // module identification list mismatch
SUPPLY_VOLTAGE_TOO_LOW(0x0080), // supply voltage too low
SUPPLY_VOLTAGE_TOO_HIGH(0x0081), // supply voltage too high
TEMPERATURE_TOO_LOW(0x0082), // temperature too low
TEMPERATURE_TOO_HIGH(0x0083), // temperature too high
APP_CONTROLLER_AVAILABLE(0x00F0), // application controller available
UNKNOWN(0xFFFF); // unknown error
}
Java can filter a slave collection as a stream with master.slaves().stream().filter(...). Together with the MasterStreams sugar it provides null-safe filters and index views such as slavesInState / slavesByVendor / slavesByName / slavesAsMap / stateCounts, which are shorter and safer than a hand-written for loop.
State machine control
state()
EtherCAT current state (read-only). To change the state, call setState(...). When it cannot be read (the underlying call returns a null pointer or throws), it returns EcState.NONE and logs a WARNING; it does not degrade silently.
Related structures:
public enum EcState {
NONE(0x00), // no state
INIT(0x01), // initialization
PRE_OP(0x02), // pre-operational
BOOT(0x03), // bootstrap
SAFE_OP(0x04), // safe-operational
OP(0x08), // operational
ACK(0x10), // acknowledge
ERROR(0x10); // error
}
Example:
if (master.state() == EcState.OP) {
System.out.println("主站处于运行状态"); // The master is running
}
- Every state machine switching method in the SDK follows the standard EtherCAT state machine sequence; the protocol layer handles it automatically.
- Import or set the correct configuration before starting.
- If a switch fails, iterate
master.slaves()and readslave.errorCode()on each slave to locate the blocker, or callnew State(master.MasterIndex).verifyStartupConfiguration()to get the failure details in Chinese (see Initialization).
setState(EcState state)
public boolean setState(EcState state)
Switch the master to the target state. Internally it follows the ETG state machine chain (INIT↔PRE_OP↔SAFE_OP↔OP) automatically, crossing several levels in one call, and applies the startup parameters of each step. After entering SAFE_OP/OP the PDO cycle exchange starts automatically.
The per-step timeout is computed from the startup parameter workload, not a fixed 5s: 4s 握手余量 + Σ(startup SDO 条数 × 2.5s), floor max(4s, 站数×5s) (at least 30s when the target is OP), ceiling 45s.
Parameters:
state(EcState) — target state
Return value:
boolean—trueon success,falseon failure
Failure is never silent: the SDK logs a WARNING (with the target state), and State.setState also refreshes the state cache of every slave before returning false, so a subsequent slave.state() / slave.errorCode() read returns the current value, not a snapshot taken before the transition. To find out which slave is blocking, iterate master.slaves() and read state() / errorCode().
The SDK retries transient failures that are not timeouts (such as link jitter) automatically. You do not need to wrap retry logic yourself.
If a step really times out (this attempt has already used up the budget above), that step fails immediately and no remaining retries are stacked on top.
When switching to SAFE_OP, the SDK automatically configures the synchronization cycle-count threshold and the SyncManager synchronization type (FreeRun as fallback) for non-DC slaves per the ETG standard; the application layer does not need to write them.
DC slaves skip this automatic configuration (to avoid a conflict with the DC time base). If you need a custom synchronization policy, override it after switching to SAFE_OP. Write failures are tolerated and do not block the SAFE_OP transition.
Example:
if (!master.setState(EcState.OP)) {
System.out.println("状态切换失败"); // State switch failed
}
Async variant (does not block the calling thread)
public CompletableFuture<Boolean> setStateAsync(EcState state)
public CompletableFuture<Boolean> setStateAsync(EcState state, Consumer<String> progress)
Returns a CompletableFuture<Boolean> that completes with true (success) / false (failure). The call is queued behind the master's serial gate and runs strictly in sequence with build, other SDOs and state transitions on the same master, so the bus is never hit concurrently; cancel(true) aborts the state machine transition that is currently blocking. The overload with a progress callback hands progress text to progress during long sequences; the return value semantics are unchanged.
Parameters:
state(EcState) — target stateprogress(Consumer<String>) — optional progress text callback, may benull
Retry and the automatic SAFE_OP synchronization behave the same as in setState(...).
Timeout semantics: these two overloads have no timeout parameter and no default wait ceiling — the future completes only when the state machine transition has really finished, and the internal setState carries its own timeout and transient retries. "Returning false after the wait elapses while the underlying transition is still running" applies only to the MasterAsync.setStateAsync(master, state, Duration) overload: it completes false when the given Duration expires, the underlying transition continues, and the SDK logs a WARNING stating that only this wait timed out. Use that overload when you need a time limit; the timeout must cover the worst-case duration of the whole state transition (a single transition can take tens of seconds), and you can poll master.state() as a fallback.
master.setStateAsync(EcState.OP).thenAccept(ok -> {
if (!ok) System.out.println("状态切换失败"); // State switch failed
});
// blocking wait for the result
boolean ok = master.setStateAsync(EcState.OP).get();
stop()
public void stop()
Stop the PDO cycle and state monitoring, without changing the EtherCAT state — the slaves keep their current state and are not switched to PRE_OP; call setState(...) separately to change the state. If not all threads have been reclaimed it logs an ERROR and keeps isStarted() at true; the call can be retried.
start()
public void start()
Start the PDO cycle. setState(SAFE_OP) and setState(OP) already start it internally, so an explicit call is usually not needed.
State.abort()
public static void abort()
Abort all blocking operations in the protocol layer (such as setState(...), or setNetwork inside build()). Safe to call from any thread.
Example:
import com.darra.ethercat.master.State;
// interrupt an in-progress state transition when the user clicks Cancel
State.abort();
State.waitForState(EcState target, int timeoutMs, int pollIntervalMs)
public boolean waitForState(EcState target, int timeoutMs, int pollIntervalMs)
public boolean waitForState(EcState target) // default timeoutMs=10000, pollIntervalMs=50
A method on the State submodule. Poll until the master reaches the given state. It does not initiate a state transition; it only waits for an already requested transition to complete, or confirms that the PDO stream is stable. Typical uses are the confirmation window after setStateAsync was triggered asynchronously, or a short wait for OP to settle after the PDO starts.
Parameters:
target(EcState) — target statetimeoutMs(int) — maximum wait time (ms), default 10000mspollIntervalMs(int) — polling interval (ms), default 50ms
Return value:
boolean—trueif the target state is reached before the timeout
Example:
master.setState(EcState.OP);
// wait up to 5s for the master to enter OP
State stateMgr = new State(master.MasterIndex);
if (!stateMgr.waitForState(EcState.OP, 5000, 50)) {
System.out.println("主站未在 5s 内进入 OP"); // The master did not reach OP within 5s
}
State.waitForSlaveState(int slaveIndex, EcState target, int timeoutMs, int pollIntervalMs)
public boolean waitForSlaveState(int slaveIndex, EcState target, int timeoutMs, int pollIntervalMs)
A method on the State submodule. Poll until a single slave reaches the given state. Useful for confirming the state of critical slaves after the PDO starts.
Parameters:
slaveIndex(int) — slave index (1-based)target(EcState) — target statetimeoutMs(int) — maximum wait time (ms)pollIntervalMs(int) — polling interval (ms)
Return value:
boolean—trueif the target state is reached before the timeout and the Error bit is not set
The criterion is that the base state equals the target state (state & 0x0F) and AL Status bit4 (Error) = 0. The same base state with the Error bit set does not count as reached. If the state is not reached before the timeout, a WARNING is logged with the last measured state and AL status code (when it cannot be read, UNKNOWN(...) is written, never folded to 0 to pass as no error).
Example:
// wait up to 3s for slave 3 to enter OP
State stateMgr = new State(master.MasterIndex);
if (!stateMgr.waitForSlaveState(3, EcState.OP, 3000, 50)) {
System.out.println("从站 3 当前: " + master.getSlave(3).state()); // Slave 3 currently: {master.getSlave(3).state()}
}
Java can compose state transitions asynchronously, in series or in parallel, with master.setStateAsync(state).orTimeout(30, TimeUnit.SECONDS). The MasterAsync sugar further provides bootToOpAsync for boot, scanAsync for parallel multi-NIC scanning and configureDCAllAsync for asynchronous DC configuration; it uses a 4-thread daemon pool internally and does not block the PDO cycle.
Process data watchdog
setAllSlaveWatchdog(int timeoutMs)
public int setAllSlaveWatchdog(int timeoutMs)
Set the process data watchdog timeout for all slaves in one call.
Parameters:
timeoutMs(int) — timeout (ms); 0 = disabled; maximum 6553ms
Return value: int — the number of slaves written successfully (not a boolean). The lower layer reports what it actually did, so the returned count only answers "how many slaves were actually written", not "all of them were sent the requested value"; the Java side folds the lower-layer last-error verdict into the visible behaviour below:
| Case | Lower-layer verdict (last-error) | Java-side behaviour |
|---|---|---|
| All written with the requested value | slave count >0 + 0 | returns the slave count |
| Some slaves in this batch are raised by the topology safety floor (branch slaves 5000 ms / PDO slaves on a ring 400 ms) and are written with the raised actual value | slave count >0 + 0x20000011 | returns the slave count (and logs a WARNING); the actual value ≠ the requested value — read the actual milliseconds back per slave with getWatchdogConfig() |
| The whole batch exceeds the 6553 ms register limit (0x0420 = u16 × 0.1 ms), the whole batch is rejected, not a single byte written | slave count 0 + 87 (ERROR_INVALID_PARAMETER) | throws IllegalArgumentException (the Java entry point validates 0..6553 first; it does not truncate and does not quietly change the value to 6553) |
| Nothing written: invalid master index / no slaves / register write failed (an invalid index falls into the 0 bucket, not the 87 bucket) | slave count 0 + 0 | returns 0 |
| The SDK is not ready (runtime not loaded, no actual write took place) | -1, last-error pinned to 0 | returns -1 |
0+0x20000011cannot occur (0 = nothing was written, so "written after being raised" does not exist).0x20000011is not a failure: it means "written but raised by the safety floor". Slaves written with the raised actual value are also counted in the returned slave count, so do not skip them as failures in later processing.- Do not count a batch with the per-slave
setWatchdog()return values: a per-slave call throwsIllegalStateExceptionas-is when the value was "written after being raised", which would be miscounted as not configured.
Exceptions: a negative timeoutMs, or one greater than 6553, throws IllegalArgumentException; the previous value is left unchanged.
For the watchdog configuration of a single slave, use slave.setWatchdog().
Example:
int count = master.setAllSlaveWatchdog(100);
// count = number of slaves written (including slaves written after the safety floor raised the value); read the actual milliseconds back per slave with getWatchdogConfig()
System.out.println("已写入 " + count + " 站看门狗配置"); // Wrote watchdog configuration for {count} slaves
setAllSlavePdiWatchdog(int timeoutMs)
public int setAllSlavePdiWatchdog(int timeoutMs)
Set the PDI watchdog timeout for all slaves in one call.
Parameters:
timeoutMs(int) — timeout (ms); 0 = disabled; maximum 6553ms
Return value: int — the number of slaves written successfully (not a boolean). The PDI channel has no topology safety-floor raise, so 0x20000011 never occurs:
| Case | Lower-layer verdict (last-error) | Java-side behaviour |
|---|---|---|
| All written with the requested value | slave count >0 (for a PDI batch, last-error is always 0 when the count is >0) | returns the slave count |
| The whole batch exceeds the 6553 ms register limit (0x0410 = u16 × 0.1 ms), the whole batch is rejected, not a single byte written | slave count 0 + 87 (ERROR_INVALID_PARAMETER) | throws IllegalArgumentException (the Java entry point validates 0..6553 first) |
| Nothing written: invalid master index / no slaves / register write failed | slave count 0 + 0 | returns 0 |
| The SDK is not ready (runtime not loaded, no actual write took place) | -1, last-error pinned to 0 | returns -1 |
Exceptions: a negative timeoutMs, or one greater than 6553, throws IllegalArgumentException; the previous value is left unchanged.
For the watchdog configuration of a single slave, use slave.setPdiWatchdog().
Example:
int count = master.setAllSlavePdiWatchdog(100);
// count = number of slaves written (the PDI channel has no safety-floor raise, so the actual value == the requested value)
System.out.println("已写入 " + count + " 站 PDI 看门狗配置"); // Wrote PDI watchdog configuration for {count} slaves
Hot-plug self-repair
When a slave is powered off and replugged, or replaced, the SDK detects the identity mismatch automatically and enters a protected state, so a wrong device is never pulled into the control cycle by mistake.
acknowledgeSlaveReplacement(int slaveNum)
public boolean acknowledgeSlaveReplacement(int slaveNum)
Confirm that the slave replacement is finished; this triggers the EtherCAT identification state machine to probe that slave again.
When to call: after subscribing to master.events().addSlaveIdentityMismatchListener and receiving the identity-mismatch alarm, once the operator has finished checking or replacing the device, call this method so the SDK probes again.
Behaviour:
- If the identity is now correct (the right device is back, or the same model with an upgraded revision) → it recovers automatically and raises the
SlaveOnlineevent - If the identity still does not match →
SlaveIdentityMismatchis raised again and the slave returns to theIDENT_REJECTEDstate
Parameters:
slaveNum(int) — slave index (1-based, matching the configuration)
Return value:
boolean—true= accepted and the FSM reset;false= the argument is invalid, or the slave is not currently inIDENT_REJECTED/FAILED
Calling this method before the SlaveIdentityMismatch event fires has no effect. While the slave has not entered the protected state the SDK keeps probing normally; no manual confirmation is needed.
Example:
master.events().addSlaveIdentityMismatchListener((args) -> {
System.out.printf("从站 %d 身份不符: 期望 Vendor=0x%08X, 实际 Vendor=0x%08X%n", // Slave %d identity mismatch: expected Vendor=0x%08X, actual Vendor=0x%08X%n
args.slaveIndex, args.expectedVendor, args.actualVendor);
// UI dialog: "check the device of slave N; click confirm once the correct model is back"
if (showReplacementDialog(args.slaveIndex)) {
boolean ok = master.acknowledgeSlaveReplacement(args.slaveIndex);
if (!ok) {
System.out.println("确认失败: 从站不在 IDENT_REJECTED 状态"); // Acknowledge failed: slave is not in the IDENT_REJECTED state
}
}
});
SlaveOffline— the slave lost power or the cable (identity still matches); recovery is automatic and raisesSlaveOnlineSlaveIdentityMismatch— the slave identity changed (wrong device, i.e. Vendor + Product do not match the configuration; the revision is not part of the identity check); callacknowledgeSlaveReplacementmanually
Topology diagnostics
rebuildTopology()
public void rebuildTopology()
Rebuild the topology view held by the master (re-resolve slave[i].topology / parentport / activeports to build the parent-child relationships).
When to call:
- After hot-plug / SlaveIdentityMismatch recovery, to confirm that the lists returned by
topologyRoots()/topologyChildren(parent)match the current link - After switching the redundancy mode (ring ↔ line)
Example:
master.rebuildTopology();
List<Integer> roots = master.topologyRoots();
System.out.println("拓扑根: " + roots); // Topology roots: {roots}
topology() / topologyChildren(int parent) / topologyRoots()
var nodes = master.topology() // complete topology node list
var children = master.topologyChildren(parent)
var roots = master.topologyRoots()
Read the topology tree held by the master. For the root node count use master.slaveTopology().count() (entry port type MII, or parentStation()==0), not master.slaveCount().
topology()— returns the complete topology node list (each node carries the slave index and the parent/child port relationships)topologyChildren(parent)— returns the child node numbers of the given slave indextopologyRoots()— returns the topology root node numbersmaster.slaveTopology().count()— root node count (EBUS modules do not count as roots; the per-slaveslave.topology().count()returns 0)
These entry points are the current public API (topology() / topologyChildren() / topologyRoots()).
Example:
for (var node : master.topology()) {
List<Integer> children = master.topologyChildren(node.SlaveIndex);
System.out.printf("从站 %d 的子节点: %s%n", node.SlaveIndex, children); // Slave %d children: %s%n
}
ESM state timeouts
com.darra.ethercat.data.EtherCATTypes.EsmTimeouts provides the ETG.1020 default state transition timeouts (milliseconds). The named methods return the standard table values from the runtime; 0 = illegal transition / unavailable, not a valid timeout.
| Category | Member | Returns | Purpose |
|---|---|---|---|
| State transition | initToPreOp() / preOpToSafeOp() / safeOpToOp() | int | Init→PreOp / PreOp→SafeOp / SafeOp→OP |
| opToSafeOp() / safeOpToPreOp() / preOpToInit() | int | OP→SafeOp / SafeOp→PreOp / PreOp→Init | |
| toBoot() / bootToInit() | int | any→Boot / Boot→Init | |
| Any transition | getTransitionTimeout(int currentState, int targetState) | int | queried by EcState.getValue(); 0 = illegal / unknown |
| Communication constants | SDO_TIMEOUT / MAILBOX_TIMEOUT / STATE_STABILIZE_DELAY | int | 3000 / 5000 / 100 ms |
Setting a custom timeout on a single slave:
slave.setEsmTimeouts(
EsmTimeouts.initToPreOp(), EsmTimeouts.preOpToSafeOp(), EsmTimeouts.safeOpToOp(),
EsmTimeouts.opToSafeOp(), EsmTimeouts.safeOpToPreOp(), EsmTimeouts.preOpToInit(),
EsmTimeouts.toBoot(), EsmTimeouts.bootToInit());
Lifecycle and safe shutdown
This group covers controlled shutdown, process-wide emergency release and deconstruction. Routine release still goes through close() (or try-with-resources); close() first performs one controlled stop of this master, then reclaims threads and resources.
safeStop()
public void safeStop()
Issues a CiA 402 Shutdown (0x0006) to the slaves of this master and then freezes it; the call affects this master only. When several masters run in one process and you shut down a single instance, you must use this method rather than safeStopAll().
A failed stop does not throw; it only logs a WARNING (the caller is not blocked). Because the stop command cannot be sent once the cyclic frames stop, close() calls the same entry point before it stops the cycle thread — for a manual stop, call it before stopping the cycle.
Example:
master.safeStop();
master.close();
safeStopAll()
public static void safeStopAll()
Process-wide safe stop: issues a safe stop to every master in this process. It affects other master instances, so do not use it to close a single master when several masters coexist. A failure does not throw; it only logs a WARNING.
emergencyCloseNics()
public static void emergencyCloseNics()
Emergency release of all NIC handles, for crash recovery, process exit, or any situation where the normal close() cannot be used. It does no protocol-layer wind-down and sends no stop command; use close() for a normal shutdown.
finalize()
protected void finalize()
Called by the JVM before the object is reclaimed; it runs close() as a fallback and swallows any RuntimeException raised during release. It exists only to stop a NIC from being held long term when someone forgot to close, and is no substitute for an explicit close: prefer try-with-resources or an explicit close(), and do not rely on when the collector runs.
deconstruct()
public BuildResult deconstruct()
Packs the current master state into a BuildResult and returns it, for destructuring assignment.
Return value:
BuildResult—success= the master is not yet disposed;slaveCount= the current local slave list size;masterIndex= the master index;message="成功"(SDK output, = success) /"失败"(SDK output, = failure); themasterfield is alwaysnull(the destructuring result carries state only and does not carry the instance again).
slaveCount comes from the local slave list; that list may be empty when the master was initialized in one step from an ENI, so take the real slave count from the count returned by build() or from slaveCount().
Example:
EtherCATMaster.BuildResult r = master.deconstruct();
System.out.printf("success=%s, slaves=%d, index=%d%n", r.success, r.slaveCount, r.masterIndex);
Slave configuration snapshot and direct PDO access
This group is the low-level direct path, for reading SyncManager configuration and moving PDO data byte by byte. For routine cyclic access prefer the struct mapping view of slave.PDO() (see ../slave/pdo-io); direct reads and writes suit diagnostics, tools, and migrations that already have a byte buffer.
Every instance method in this section throws IllegalStateException once the master has been disposed.
slaveSmLength(int slaveIndex, int smIdx)
public Integer slaveSmLength(int slaveIndex, int smIdx)
Read the length of one SyncManager on the given slave (bytes, host byte order). SM2 = output PDO, SM3 = input PDO.
Parameters:
slaveIndex(int) — slave index (1-based)smIdx(int) — SyncManager index (0..7)
Return value: Integer — the length expanded as unsigned (0..65535); null = the argument is out of range or the length is unavailable (smIdx out of range, slaveIndex < 1, read failed). 0 means not configured, a bad argument, or no such slave (the three cannot be told apart); it is not a valid length.
Example:
Integer sm2 = master.slaveSmLength(1, 2);
if (sm2 != null && sm2 > 0) {
System.out.println("从站 1 输出 PDO 长度: " + sm2 + " 字节"); // Slave 1 output PDO length: {sm2} bytes
}
pdoReadDirect(short slaveIndex, short pdoIndex, Pointer dataBuffer, int bufferSize, IntByReference bytesRead)
public boolean pdoReadDirect(short slaveIndex, short pdoIndex,
Pointer dataBuffer, int bufferSize, IntByReference bytesRead)
Read one block of input data from the given slave straight into the caller's buffer, addressed by PDO index.
Parameters:
slaveIndex(short) — slave index (1-based)pdoIndex(short) — target PDO indexdataBuffer(Pointer) — target buffer allocated by the callerbufferSize(int) — buffer size in bytes; must not be smaller than the length of that PDObytesRead(IntByReference) — out-parameter, the number of bytes actually read
Return value: boolean — true = read succeeded; false = invalid argument / the slave is not in a readable state / the read failed.
Pointer and IntByReference are the Java-side pointer and out-parameter types supplied with the SDK dependencies. The buffer is owned by the caller, who is responsible for its lifetime.
Example:
import com.sun.jna.Memory;
import com.sun.jna.ptr.IntByReference;
Memory buf = new Memory(64);
IntByReference read = new IntByReference();
if (master.pdoReadDirect((short) 1, (short) 0x1A00, buf, (int) buf.size(), read)) {
System.out.println("读到 " + read.getValue() + " 字节"); // Read {read.getValue()} bytes
}
pdoWriteDirect(short slaveIndex, short pdoIndex, Pointer dataBuffer, int dataSize)
@Deprecated
public boolean pdoWriteDirect(short slaveIndex, short pdoIndex,
Pointer dataBuffer, int dataSize)
Deprecated. This entry point always returns false and writes no output: the legacy entry point offers neither a per-slave write transaction nor conflict detection, so it cannot safely express which items a given write actually applied.
Parameters:
slaveIndex(short) — slave index (1-based)pdoIndex(short) — target PDO indexdataBuffer(Pointer) — buffer holding the data to writedataSize(int) — data size in bytes
Return value: boolean — always false.
Alternatives (all with versioned read-modify-write transactions): the slave.PDO().outputsMapping(...) golden-path overlay, slave.PDO().writeFromTyped(data, offset), slave.PDO().out().get(offset).asUInt8(v).
pdoBatchRead(short[] slaveIndices, int slaveCount, Pointer[] dataBuffers, int[] bufferSizes, int[] bytesRead)
public int pdoBatchRead(short[] slaveIndices, int slaveCount,
Pointer[] dataBuffers, int[] bufferSizes, int[] bytesRead)
Read input snapshots for a list of slaves in one call, copying each slave into a buffer held by the caller. This is a snapshot interface for diagnostics and tools, not a channel for cyclic data synchronization; use struct mapping for cyclic data.
Parameters:
slaveIndices(short[]) — slave indices (1-based)slaveCount(int) — number of valid entries; must not exceed the length of any of the arraysdataBuffers(Pointer[]) — target buffer for each slavebufferSizes(int[]) — buffer size in bytes for each slavebytesRead(int[]) — out-parameter, the number of bytes actually read for each slave
Return value: int — the number of slaves read successfully (0 = none read).
Example:
import com.sun.jna.Memory;
short[] slaves = {1, 2};
Pointer[] bufs = {new Memory(64), new Memory(64)};
int[] sizes = {64, 64};
int[] read = new int[2];
int ok = master.pdoBatchRead(slaves, 2, bufs, sizes, read);
System.out.println("成功读取 " + ok + " 站"); // Successfully read {ok} slaves
pdoBatchWrite(short[] slaveIndices, int slaveCount, Pointer[] dataBuffers, int[] dataSizes)
@Deprecated
public int pdoBatchWrite(short[] slaveIndices, int slaveCount,
Pointer[] dataBuffers, int[] dataSizes)
Deprecated. This entry point always returns 0 and writes no output: the legacy cross-slave batch write cannot provide per-slave transaction or conflict semantics.
Parameters:
slaveIndices(short[]) — slave indices (1-based)slaveCount(int) — number of valid entriesdataBuffers(Pointer[]) — buffer holding the data to write for each slavedataSizes(int[]) — data size in bytes for each slave
Return value: int — always 0.
Alternatives: slave.PDO().batchWrite(int[] offsets, byte[][] data) (one transaction on a single slave, returning the number of items applied), or the element view slave.PDO().out().get(offset).asUInt8(v).
PDO monitoring
enablePDOMonitoring(boolean enable)
public static void enablePDOMonitoring(boolean enable)
Process-wide PDO monitoring switch. true = enabled, false = disabled. When the runtime library is not loaded the call is silently ignored (no exception is thrown), so the switch can be registered before the environment is ready.
Example:
EtherCATMaster.enablePDOMonitoring(true);
isPDOMonitoringEnabled()
public static boolean isPDOMonitoringEnabled()
Returns whether PDO monitoring is currently enabled. Returns false when the runtime library is not loaded (treated as "not enabled", no exception is thrown).
Frame loss and communication statistics
Frame-loss counters are tracked per group 0..7; the common entry points read group 0 by default. The underlying counter is a 32-bit unsigned value; on the Java side it is carried in a long (the getPdoFrameLossStats family) or returned as an int (the pdoLostFrames family, to be read as unsigned when compared).
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| Frame loss counters | pdoLostFrames() | int | call | Total lost frames for group 0 |
| pdoConsecutiveLost() | int | call | Current consecutive lost frames for group 0 | |
| pdoMaxConsecutiveLost() | int | call | Maximum consecutive lost frames for group 0 so far | |
| getPdoFrameLossStats(byte group) / getPdoFrameLossStats() | PDOFrameLossStats | call | Recommended entry point; returns a three-field snapshot | |
| getPDOFrameLossStats(byte, IntByReference, IntByReference, IntByReference) | void (out-parameter) | call | Deprecated; use the return-value style | |
| resetPDOFrameLossStats() | void | call | Clears all groups (0..7) | |
| Communication statistics | communicationStats() | Pointer | call | Pointer to the communication statistics block |
| resetCommunicationStats() | void | call | Resets the communication statistics | |
| PDO statistics | pdoStats(short slaveIndex) | Pointer | call | Pointer to the PDO statistics block of a single slave |
| resetPDOStats(short slaveIndex) | void | call | Resets the PDO statistics of a single slave |
pdoLostFrames()
public int pdoLostFrames()
Total lost frames for group 0.
Return value: int — the low 32 bits of a 32-bit unsigned counter; for an unsigned comparison use Integer.toUnsignedLong(master.pdoLostFrames()).
pdoConsecutiveLost()
public int pdoConsecutiveLost()
Current consecutive lost frames for group 0 (reset to zero once frames are received again).
pdoMaxConsecutiveLost()
public int pdoMaxConsecutiveLost()
Maximum consecutive lost frames for group 0 so far (reset to zero when the statistics are reset).
getPdoFrameLossStats(byte group)
public PDOFrameLossStats getPdoFrameLossStats(byte group)
public PDOFrameLossStats getPdoFrameLossStats() // Equivalent to group = 0
Recommended entry point: returns the complete frame-loss snapshot of the group in one call.
Parameters:
group(byte) — group number (0..7); the no-argument overload always reads group 0
Return value: PDOFrameLossStats — an immutable snapshot whose fields are totalLost (total), consecutiveLost (current consecutive) and maxConsecutiveLost (maximum consecutive so far), each carried in a long as a 32-bit unsigned count; getTotalLost() / getConsecutiveLost() / getMaxConsecutiveLost() are provided as well.
Example:
EtherCATMaster.PDOFrameLossStats s = master.getPdoFrameLossStats((byte) 0);
System.out.printf("累计=%d, 连续=%d, 最大连续=%d%n", // cumulative=%d, consecutive=%d, max consecutive=%d%n
s.totalLost, s.consecutiveLost, s.maxConsecutiveLost);
getPDOFrameLossStats(byte group, IntByReference totalLost, IntByReference consecutiveLost, IntByReference maxConsecutiveLost)
@Deprecated
public void getPDOFrameLossStats(byte group, IntByReference totalLost,
IntByReference consecutiveLost,
IntByReference maxConsecutiveLost)
Deprecated out-parameter style; the field semantics match the recommended entry point. New code should use getPdoFrameLossStats(byte).
Parameters:
group(byte) — group number (0..7)totalLost(IntByReference) — out-parameter, total lost framesconsecutiveLost(IntByReference) — out-parameter, current consecutive lost framesmaxConsecutiveLost(IntByReference) — out-parameter, maximum consecutive lost frames so far
resetPDOFrameLossStats()
public void resetPDOFrameLossStats()
Clears the frame-loss statistics of all groups (0..7), including the total, the current consecutive count and the maximum consecutive count.
communicationStats()
public Pointer communicationStats()
Returns a pointer to the master communication statistics block (read-only). The block is owned by the runtime library and stays valid for the lifetime of the master; the caller must not release it. When the master is not ready or the value cannot be read it may return null or a null pointer, so check for null before use.
resetCommunicationStats()
public void resetCommunicationStats()
Resets the master communication statistics counters.
pdoStats(short slaveIndex)
public Pointer pdoStats(short slaveIndex)
Returns a pointer to the PDO statistics block of the given slave (read-only); the block is owned by the runtime library and the caller must not release it.
Parameters:
slaveIndex(short) — slave index (1-based)
resetPDOStats(short slaveIndex)
public void resetPDOStats(short slaveIndex)
Resets the PDO statistics counters of the given slave.
Parameters:
slaveIndex(short) — slave index (1-based)
Callback registration
This group holds the callback slots that correspond directly to the runtime library, for migrating existing callback-style code and for embedded integration. For the recommended entry points of the event model see events().add*Listener(...) in ./events; the two coexist, and the same event is dispatched to the listener list and then to the slot here.
Behaviour conventions:
- Each slot keeps only the last registered callback; registering again replaces it, and passing
nullunregisters. - Callbacks run on the event dispatch thread, and the SDK swallows exceptions thrown by a callback so other subscribers are unaffected; do not block or run long computations inside a callback.
- After the master is closed the slots are cleared and no longer fire.
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| Initialization progress | setInitProgressListener(...) | void | call | Progress text for long sequences |
| Master state | setStateChangedListener(...) | void | call | Legacy single-slot state listener |
| PDO cycle | registerPdoCyclicCallbackSync(...) | void | call | Synchronous callback every cycle |
| Slave state | registerStateChangeCallbackSync(...) / registerStateChangeCallbackAsync(...) | void | call | Two independent slots |
| Emergency events | registerEmergencyEventCallback(...) | void | call | CiA 301 emergency messages |
| Slave discovery | registerDiscoveryCallbackSync(...) / registerDiscoveryCallbackAsync(...) | void | call | Online / offline notification |
| Frame loss | registerPDOFrameLossCallback(...) | void | call | Consecutive frame-loss notification |
| FoE progress | setFoEProgressHook(...) / clearFoEProgressHook() | boolean | call | File transfer progress hook |
setInitProgressListener(InitProgressListener listener)
public void setInitProgressListener(InitProgressListener listener)
Set the initialization progress listener to receive progress text (such as "scanning / configuring / entering OP") while long sequences such as buildAsync / setStateAsync run. The callback fires on the asynchronous execution thread, not on the caller's main thread; updating the UI means switching back to the UI thread yourself (with SwingUtilities.invokeLater in Swing, Platform.runLater in JavaFX). Passing null unregisters.
Listener interface:
public interface InitProgressListener {
void onProgress(String message);
}
Example:
master.setInitProgressListener(msg ->
SwingUtilities.invokeLater(() -> statusLabel.setText(msg)));
setStateChangedListener(StateChangedListener listener)
public synchronized void setStateChangedListener(StateChangedListener listener)
Legacy single-slot master state change listener. The callback arguments are base state values (0x01 INIT / 0x02 PRE_OP / 0x03 BOOT / 0x04 SAFE_OP / 0x08 OP), the same source as events().addStateChangedListener(...).
Listener interface:
public interface StateChangedListener {
void onStateChanged(byte oldState, byte newState);
}
Parameters:
listener(StateChangedListener) — the new listener;null= unregister the listener registered earlier through this method (noNullPointerExceptionis thrown)
Setting it again replaces the old listener; there is no duplicate subscription. Registering a new listener after the master has been disposed or while it is closing throws IllegalStateException; unregistering after close is still safe (it only drops the local reference).
Example:
master.setStateChangedListener((oldState, newState) ->
System.out.printf("主站状态: 0x%02X -> 0x%02X%n", oldState, newState)); // Master state: 0x%02X -> 0x%02X%n
registerPdoCyclicCallbackSync(DarraCore.ProcessDataCyclicCallback callback)
public void registerPdoCyclicCallbackSync(DarraCore.ProcessDataCyclicCallback callback)
Register a synchronous PDO cycle callback, fired once per PDO cycle, for processing that must stay in lockstep with the cycle (such as a safety protocol answering in the same cycle). There is a single synchronous slot at any time; registering again replaces it, and passing null unregisters.
Callback signature:
void invoke(short masterIndex)
The callback runs on the cycle dispatch thread; blocking it directly hurts cycle stability. Hand heavy work to a worker thread.
registerStateChangeCallbackSync(DarraCore.SlaveStateChangeCallback callback)
public void registerStateChangeCallbackSync(DarraCore.SlaveStateChangeCallback callback)
Register a slave state change callback (synchronous slot). The oldState / newState arguments are base state codes (INIT / PRE_OP / BOOT / SAFE_OP / OP), not the full AL Status.
Callback signature:
void invoke(short masterIndex, short slaveIndex, int oldState, int newState)
registerStateChangeCallbackAsync(DarraCore.SlaveStateChangeCallback callback)
public void registerStateChangeCallbackAsync(DarraCore.SlaveStateChangeCallback callback)
A second, independent slot for slave state change callbacks; it does not overwrite registerStateChangeCallbackSync(...). For one state change both slots are called once each, both on the event dispatch thread.
Callback signature:
void invoke(short masterIndex, short slaveIndex, int oldState, int newState)
registerEmergencyEventCallback(DarraCore.EmergencyEventCallback callback)
public void registerEmergencyEventCallback(DarraCore.EmergencyEventCallback callback)
Register an emergency event (mailbox Emergency) callback. The arguments are the content of the CiA 301 emergency message: error code, error register and vendor data.
Callback signature:
void invoke(short masterIndex, short slaveIndex, short errorCode,
short errorReg, byte b1, short w1, short w2)
registerDiscoveryCallbackSync(DarraCore.SlaveDiscoveryCallback callback)
public void registerDiscoveryCallbackSync(DarraCore.SlaveDiscoveryCallback callback)
Register a slave online / offline discovery callback (synchronous slot).
Callback signature:
void invoke(short masterIndex, short slaveIndex, boolean isFound)
isFound = true = the slave came online, false = it went offline.
registerDiscoveryCallbackAsync(DarraCore.SlaveDiscoveryCallback callback)
public void registerDiscoveryCallbackAsync(DarraCore.SlaveDiscoveryCallback callback)
A second, independent slot for slave discovery callbacks; it does not overwrite the synchronous slot. For one discovery event both slots are called once each.
Callback signature:
void invoke(short masterIndex, short slaveIndex, boolean isFound)
registerPDOFrameLossCallback(DarraCore.PDOFrameLossCallback callback)
public void registerPDOFrameLossCallback(DarraCore.PDOFrameLossCallback callback)
Register a PDO consecutive frame-loss callback, for raising an alarm or entering degraded logic when frame loss exceeds a limit.
Callback signature:
void invoke(short masterIndex, byte group, int consecutive, int total)
consecutive = current consecutive lost frames, total = total lost frames.
setFoEProgressHook(DarraCore.FoEProgressCallback callback)
public boolean setFoEProgressHook(DarraCore.FoEProgressCallback callback)
Register a FoE file transfer progress hook. A master has a single FoE progress slot; registering again replaces it.
Callback signature:
void invoke(short slave, int packetNumber, int dataSize)
Parameters:
callback(DarraCore.FoEProgressCallback) — progress callback;null= clear the hook
Return value: boolean — true = registered; false = rejected by the runtime library or not ready.
Example:
master.setFoEProgressHook((slave, packet, size) ->
System.out.printf("从站 %d: 第 %d 包, %d 字节%n", slave, packet, size)); // Slave %d: packet %d, %d bytes%n
clearFoEProgressHook()
public boolean clearFoEProgressHook()
Clear the FoE transfer progress hook.
Return value: boolean — true = cleared; false = rejected by the runtime library or not ready.
Identity and integrity checks
verifyAllSlaveIdentities(DarraCore.SlaveIdentity[] expectedIdentities, int slaveCount, boolean checkRevision, boolean checkSerial, long[] mismatchMask)
public boolean verifyAllSlaveIdentities(DarraCore.SlaveIdentity[] expectedIdentities,
int slaveCount, boolean checkRevision,
boolean checkSerial, long[] mismatchMask)
Verify the identity of every slave on the network in one call (Vendor / ProductCode, optionally Revision / Serial). Commonly used before start-up to confirm that the devices on site match the configuration.
Parameters:
expectedIdentities(DarraCore.SlaveIdentity[]) — array of expected identities, in slave-number order; each item carriesVendorId/ProductCode/RevisionNo/SerialNoslaveCount(int) — number of slaves to verify; must not exceed the array lengthcheckRevision(boolean) — whether to compare the revision numbercheckSerial(boolean) — whether to compare the serial numbermismatchMask(long[]) — out-parameter, at least 1 long;mismatchMask[0]marks mismatching slaves by bit position (slave 1..64 maps to bit0..63)
Return value: boolean — true when everything matches; false if any slave mismatches or a query fails.
Example:
DarraCore.SlaveIdentity[] expected = new DarraCore.SlaveIdentity[2];
expected[0] = new DarraCore.SlaveIdentity();
expected[0].VendorId = 0x00000002;
expected[0].ProductCode = 0x044C2C52;
expected[1] = new DarraCore.SlaveIdentity();
expected[1].VendorId = 0x00000002;
expected[1].ProductCode = 0x044C2C52;
long[] mask = new long[1];
boolean allOk = master.verifyAllSlaveIdentities(expected, 2, true, false, mask);
if (!allOk) {
System.out.println("不匹配掩码: 0x" + Long.toHexString(mask[0])); // Mismatch mask: 0x{Long.toHexString(mask[0])}
}
checkBufferIntegrity()
public boolean checkBufferIntegrity()
Verify the integrity of the runtime environment buffer pool (tamper detection).
Return value: boolean — true = the check passed; false = the content was modified or the runtime library is not ready.
This entry point only answers "has the buffer pool been modified"; it is a different entry point from the authorization status query (com.darra.ethercat.statics.Authorization), and the two must not be used in place of each other.
Topology, port errors and scanning
topoP1FoldbackMode()
public int topoP1FoldbackMode()
P1 foldback requirement mode.
Return value: int — 0 = NONE (no foldback required, or not calibrated in this run), 1 = SINGLE_NIC (single NIC, no foldback window), 2 = DUAL_RING_BRANCH (dual-NIC ring plus branch, foldback required); -1 = invalid master index.
topoP1Mode()
public int topoP1Mode()
Compatibility alias of topoP1FoldbackMode(); the return value and the semantics are identical.
topoP1RingEndAdp()
public int topoP1RingEndAdp()
The ADP (Auto Increment address) of the P1 foldback window.
Return value: int — the foldback window address; -1 = unavailable (not calibrated / not a dual-NIC ring plus branch).
topoMeasuredRingCount()
public int topoMeasuredRingCount()
Number of slaves on the ring measured in this run. The branch count can be derived with topoP1FullWkc() - topoMeasuredRingCount().
Return value: int — the measured slave count on the ring (0 is a valid measured value); -1 = unavailable.
topoP1Measured()
public int topoP1Measured()
Whether an actual on-site topology measurement was performed in this run.
Return value: int — 1 = measured; 0 = not measured; -1 = invalid master index.
getRingSlaveCount()
public static int getRingSlaveCount()
Returns the number of slaves on the ring measured by the last on-site topology calibration (the foldback position measurement taken during Build / Apply).
Return value: int — the slave count on the ring; 0 = not calibrated yet. A read-only scan does not update this value.
quickFindRedundantPairBatch(String[] adapterNames)
public static int[] quickFindRedundantPairBatch(String[] adapterNames)
Probe redundant pairs in a batch, to determine which two NICs form a ring before a master is created.
Parameters:
adapterNames(String[]) — array of NIC names to probe; withnullor fewer than 2 entries it returns{0, -1, -1, 0, 0}immediately
Return value: int[5] — {slaveCount, primaryIdx, secondaryIdx, ringCount, totalCount}:
| Category | Property | Type | R/W | Description |
|---|---|---|---|---|
| Returned value | slaveCount (index 0) | int | read-only | Working counter total along the ring-pair path |
| primaryIdx (index 1) | int | read-only | Index of the primary port in adapterNames; -1 = not found | |
| secondaryIdx (index 2) | int | read-only | Index of the secondary port; -1 = not found | |
| ringCount (index 3) | int | read-only | Working counter total along the same ring-pair path; not the number of slaves on the ring | |
| totalCount (index 4) | int | read-only | Ring-pair path total plus the slaves every other NIC found on its own port (whole-machine figure); not "ring + branch" |
totalCount - ringCount does not yield the branch slave count: the difference comes from the contribution of other NICs and has nothing to do with branches inside the ring. How many slaves the ring covers, and whether there is a branch inside it, can only be determined from the topology model after the master is created (see rebuildTopology() and master.slaveTopology()).
Example:
int[] pair = EtherCATMaster.quickFindRedundantPairBatch(
new String[]{"\\Device\\NPF_{AAA}", "\\Device\\NPF_{BBB}"});
System.out.printf("主口=%d, 副口=%d, 环计数=%d, 整机计数=%d%n", // primary port=%d, secondary port=%d, ring count=%d, device-wide count=%d%n
pair[1], pair[2], pair[3], pair[4]);
getBreakPoints(short[] outSlaves, byte[] outPorts, byte[] outTypes, short maxResults)
public int getBreakPoints(short[] outSlaves, byte[] outPorts,
byte[] outTypes, short maxResults)
Detect all current fault points, covering both classes of physical fault: link break (the physical link on a port is lost) and CRC fault (port-level RX errors / invalid frames keep growing). The three arrays are allocated by the caller and filled up to maxResults.
Parameters:
outSlaves(short[]) — out-parameter, the slave index where the fault point isoutPorts(byte[]) — out-parameter, the fault port number (0..3 maps to P0..P3)outTypes(byte[]) — out-parameter, fault type:0= link break,1= CRC faultmaxResults(short) — maximum number of fault points to return; must not exceed the length of any of the arrays
Return value: int — >= 0 = the number of fault points (0 = the diagnostic cache has not been built yet, or there really is no fault); -1 = invalid argument / master (query failed, not to be treated as "no fault").
To distinguish strictly between "query failed" and "really no fault", use diagnostics().getAllBreakPoints(): null = query failed, an empty array = the query succeeded and there is no fault.
Example:
short[] slaves = new short[16];
byte[] ports = new byte[16];
byte[] types = new byte[16];
int n = master.getBreakPoints(slaves, ports, types, (short) 16);
if (n < 0) {
System.out.println("故障点查询失败"); // Fault point query failed
} else if (n == 0) {
System.out.println("未发现故障点"); // No fault point found
} else {
for (int i = 0; i < n; i++) {
System.out.printf("从站 %d 端口 P%d: %s%n", // Slave %d port P%d: %s%n
slaves[i], ports[i], types[i] == 0 ? "断线" : "CRC 故障"); // cable break / CRC fault
}
}
slaveLinkQuality(short slaveIndex)
public short slaveLinkQuality(short slaveIndex)
Read the link quality percentage of a slave (computed from RX errors, invalid frames and WKC anomalies).
Parameters:
slaveIndex(short) — slave index (1-based)
Return value: short — 0..100 = link quality percentage; -1 = unknown (do not pass 0 off as 0%).
readSlavePortErrorCounters(short slaveIndex, byte[] rxError, byte[] invalidFrame, byte[] lostLink)
public boolean readSlavePortErrorCounters(short slaveIndex,
byte[] rxError, byte[] invalidFrame, byte[] lostLink)
Read the port error counters of each port on a single slave.
Parameters:
slaveIndex(short) — slave index (1-based)rxError(byte[]) — out-parameter, each 4 bytes correspond to the RX error count of P0..P3invalidFrame(byte[]) — out-parameter, each 4 bytes correspond to the invalid frame count of P0..P3lostLink(byte[]) — out-parameter, each 4 bytes correspond to the lost link count of P0..P3
Return value: boolean — true = read succeeded; false = invalid argument / no such slave / the read failed.
readAllSlavePortErrorCounters()
public int readAllSlavePortErrorCounters()
Read the port error counters of all slaves in one call.
Return value: int — the number of slaves read successfully; -1 = query failed.
resetSlavePortErrorCounters(short slaveIndex)
public boolean resetSlavePortErrorCounters(short slaveIndex)
Reset the port error counters of the given slave.
Parameters:
slaveIndex(short) — slave index (1-based)
Return value: boolean — true = reset; false = invalid argument / no such slave / the reset failed.
slavePortErrorStats(short slaveIndex)
public Pointer slavePortErrorStats(short slaveIndex)
Returns a pointer to the port error statistics block of the given slave (read-only, including the forwarded RX error count). The block is owned by the runtime library and the caller must not release it.
Parameters:
slaveIndex(short) — slave index (1-based)
CPU, cycle and propagation delay
setCpuAffinity(int cpuCore)
public boolean setCpuAffinity(int cpuCore)
Bind the cyclic task of the master to the given CPU core, to keep cycle processing apart from other application load.
Parameters:
cpuCore(int) — CPU core number (starting at 0); should be less than the value returned bygetAvailableCpuCores()
Return value: boolean — true = bound; false = rejected by the runtime library (index out of range / no permission / master not ready).
Example:
int cores = EtherCATMaster.getAvailableCpuCores();
if (cores > 1 && !master.setCpuAffinity(1)) {
System.out.println("CPU 绑定失败"); // CPU binding failed
}
applySoftRealtime()
public SoftRealtimeStatus applySoftRealtime()
Apply user-mode PDO soft real-time scheduling: bind the PDO thread of this master to a reserved real-time core and raise the thread base priority (a thread-level adjustment; the process priority class is left unchanged by default). Equivalent to SoftRealtime.applyFor(masterNumber()).
The method throws no exception (including when the master has been disposed); the failure reason is expressed by the returned status snapshot. When the real-time runtime has already taken over cycle processing, no process state is changed.
Return value: SoftRealtimeStatus — an immutable status snapshot:
| Category | Property | Type | R/W | Description |
|---|---|---|---|---|
| Mode | mode | SoftRealtimeMode | read-only | UNSUPPORTED (conditions not met) / INACTIVE (conditions met but not enabled) / ACTIVE (enabled) / KERNEL_OFFLOAD (the cycle is carried by the real-time runtime) |
| Conditions | supported | boolean | read-only | Whether this machine meets the soft real-time conditions (Windows + valid reserved cores + the privilege to raise priority); independent of whether this call succeeded |
| reservedCoreCount | int | read-only | Number of reserved real-time cores | |
| reservedMask | String | read-only | Reserved-core mask text (such as 0x000000C000000000); "(无)" (SDK output, = (none)) when it cannot be read | |
| Process | processRealtime | boolean | read-only | Whether the current process is in a real-time priority class (read live, cached values are not trusted) |
| appliedBySdk | boolean | read-only | Whether the real-time priority was set by this SDK (decides whether the original value is restored on disable) | |
| PDO thread | pdoCore | int | read-only | Bound PDO core; -1 = not bound |
| pdoThreadId | int | read-only | ID of the PDO thread whose priority was raised; 0 = unknown | |
| pdoBasePriority | int | read-only | Effective thread priority; 0 = unknown | |
| threadPriorityApplied | boolean | read-only | Whether the thread priority was raised and passed the read-back check | |
| Policy | policy | int | read-only | Scheduling policy: 0 = auto, 1 = off (hard off), 2 = on |
| Diagnostic | reason | String | read-only | Reason text in Chinese, ready to show to the user, never null |
Example:
SoftRealtimeStatus srt = master.applySoftRealtime();
System.out.println("模式=" + srt.mode + ", 原因=" + srt.reason); // mode={srt.mode}, reason={srt.reason}
getAvailableCpuCores()
public static int getAvailableCpuCores()
Returns the number of available CPU cores on this machine, used to determine the valid index range for setCpuAffinity(int) (0 .. getAvailableCpuCores()-1).
updatePropagationDelays()
public int updatePropagationDelays()
Measure and update the DC propagation delay again.
Return value: int — >= 0 = measured successfully (result code); < 0 = failure.
On success the source of this measurement is recorded; the propagation delay and its source can be queried in the DC diagnostics entry points.
Performance export
exportPerfCsv(String filepath)
public int exportPerfCsv(String filepath)
Export the master performance statistics to a CSV file, for offline analysis of cycle jitter and communication load.
Parameters:
filepath(String) — full path of the target CSV file; the directory must already exist and be writable, and the file name is chosen by the caller (a.csvsuffix is recommended)
Return value: int — >= 0 = export succeeded (result code); < 0 = failure.
On failure, first check that the target directory exists, that you have write permission, and that the master has not been disposed.
Example:
int rc = master.exportPerfCsv("D:\\logs\\ethercat-perf.csv");
if (rc < 0) {
System.out.println("性能导出失败, 结果码: " + rc); // Performance export failed, result code: {rc}
}
Device and instance information
These entry points are for checking the device identity, the environment integrity and the master instance capacity on site. All of them are read-only queries.
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| Device identity | getSerialNumber() | String | call | Device serial number; an empty string when it cannot be read |
| getDeviceName() | String | call | Device name; an empty string when it cannot be read | |
| getDriverList() | String | call | Text list of the loaded driver names | |
| Instance capacity | getMaxMasterInstances() / getMaxInstanceCount() | int | call | Maximum number of master instances supported |
| getActiveInstanceCount() | int | call | Number of live master instances | |
| Master identity | getMasterIdentity() | DarraCore.MasterIdentity | call | Identity information of ETG.1510 object 0x1018 |
getSerialNumber()
public static String getSerialNumber()
Returns the device serial number text of this machine. An empty string is returned when it cannot be read (null is never returned, so the caller does not need a null check).
getDeviceName()
public static String getDeviceName()
Returns the device name text of this machine. An empty string is returned when it cannot be read.
getDriverList()
public static String getDriverList()
Returns a text list of the driver names loaded in the runtime environment, for checking the environment integrity on site. An empty string is returned when it cannot be read.
getMasterIdentity()
public DarraCore.MasterIdentity getMasterIdentity()
Read the master identity information (ETG.1510 object 0x1018): VendorId, ProductCode, RevisionNo, SerialNo, plus the three fixed-length text fields DeviceName / HwVersion / SwVersion. Read the text fields with getDeviceNameString() / getHwVersionString() / getSwVersionString().
Return value: DarraCore.MasterIdentity — the identity structure; null when the read fails.
Example:
DarraCore.MasterIdentity id = master.getMasterIdentity();
if (id != null) {
System.out.printf("Vendor=0x%08X, Product=0x%08X, 设备=%s%n", // Vendor=0x%08X, Product=0x%08X, device=%s%n
id.VendorId, id.ProductCode, id.getDeviceNameString());
}
getMaxMasterInstances()
public static int getMaxMasterInstances()
Returns the maximum number of master instances supported by this runtime library. Master numbers are 1-based; 0 is invalid.
getMaxInstanceCount()
public static int getMaxInstanceCount()
Returns the master instance limit, the same value as getMaxMasterInstances(), kept for naming compatibility across SDK versions.
getActiveInstanceCount()
public static int getActiveInstanceCount()
Returns the number of live master instances: the larger of the in-process master registration count and the runtime library's active instance count, so that several coexisting masters are not under-reported. When the runtime library's active-instance entry point is unavailable it falls back to the in-process count.
UDP communication mode
setUdpMode(boolean enable)
public boolean setUdpMode(boolean enable)
Switch the UDP frame transmission mode (ETG.1500 5.3.7).
Parameters:
enable(boolean) —true= enable UDP mode;false= use the default link-layer frame transmission
Return value: boolean — true = issued; false = rejected by the runtime library (not supported in the current environment / master not ready). After switching, confirm with udpMode().
udpMode()
public boolean udpMode()
Returns whether the UDP frame transmission mode is currently enabled.