Java-specific sugar
The com.darra.ethercat.sugar package provides a set of helper classes that only add, never change. They bridge the main SDK with the Java 8/11 standard library (Stream / Optional / CompletableFuture / BlockingQueue / record-style), so common patterns are shorter to write, error handling is lighter, and integration with the modern Java ecosystem is smoother.
- The main API stays completely unchanged — your existing code keeps working, and no migration is needed
- All sugar classes live in the
com.darra.ethercat.sugar.*package, in static-factory style - A
nullmaster, a released master or an out-of-range index always yields an empty Stream/Optional/Map; no exception is thrown - Decoupled from GC, from the underlying callbacks and from the PDO cycle; no new memory-leak risk is introduced
Method overview
| Category | Methods | Type | R/W | Description |
|---|---|---|---|---|
| Fluent construction | MasterBuilder.create, network, redundant, eni, esiFile, esiFolder, autoStartup, targetState, startPdoAfterOp, masterNumber, build | EtherCATMaster | Write-only | Declarative master construction; build() returns the master directly, and on failure it throws IllegalStateException and reclaims the half-built instance |
| Scope | MasterScope.of, resetToInitOnClose, stopBeforeClose, attach, master, close | AutoCloseable | Write-only | Wraps try-with-resources; on exit it releases the attached sub-resources in last-in-first-out order and can optionally switch back to INIT |
| Slave streams | MasterStreams.slaves, slavesInState, slavesNotInState, slavesByVendor, slavesByName, lostSlaves, dcCapableSlaves | Stream<Slave> | Read-only | Null-safe slave streams; returns an empty Stream when the master is null, released or has no slaves |
| Lookup | MasterStreams.slaveOpt, findByName, findByConfigAddr, findByIdentity | Optional<Slave> | Read-only | Single-slave lookup wrapped in Optional; an out-of-range index or a miss returns an empty Optional |
| Collection views | MasterStreams.slavesAsMap, slavesAsNavigableMap, slavesByGroup, slavesByState, slavesByVendorId, stateCounts | Map / NavigableMap | Read-only | Grouping and counting by index, group, state and vendor; indices start at 1 and the result is an immutable snapshot |
| Collection algebra | SlaveListExt.toArray, sortedBySlaveNum, sortedByConfigAddr, sortedByVendorThenIndex, countByState, lostCount, dcCapableCount, allInState, anyInState, hasLostSlave, identities | Slave[] / List / long / boolean | Read-only | Snapshots, sorting, counting and whole-network checks; a snapshot can be used across threads |
| Immutable identity | SlaveIdentity constructor, snapshot, matchesIdentity, equalsExact | SlaveIdentity | Read-only | Takes an identity snapshot of a slave that can be passed across threads or used as a Map key; matchesIdentity validates the configuration, equalsExact also compares the serial number |
| Asynchronous operations | MasterAsync.executor, setStateAsync, setNetworkAsync, scanAsync, scanRedundantAsync, configureDCAllAsync, applyStartupParametersAsync, bootToOpAsync | CompletableFuture | Read-write | Asynchronous wrappers that return a CompletableFuture; executor returns the reused daemon thread pool |
| Diagnostic streams | DiagnosticStream.emergencies, emergenciesByCode, emergenciesByRegister, recentEmergencies, emergencyCount, diagnostics, diagnosticsByCode, diagnosticsBySeverity, latestDiagnostics | Stream | Read-only | Covers only the CoE emergency history and the 0x10F3 diagnostic history |
| Diagnostic queue | DiagnosticQueue.attach, attachStrict, take, poll, pollNow, size, isStrict, queue, close | DiagnosticQueue | Read-only | Turns the emergency event callback into a blocking queue; attach drops the oldest event when full, attachStrict blocks the callback when full |
| State queue | SlaveStateQueue.attach, take, poll, pollNow, size, streamUntilClosed, close | SlaveStateQueue | Read-only | Turns state changes into a blocking queue that can also be consumed as a Stream; streamUntilClosed blocks until the queue is closed |
MasterAsyncsetStateAsync/setNetworkAsync/bootToOpAsync→CompletableFuture<Boolean>scanAsync/scanRedundantAsync/configureDCAllAsync/applyStartupParametersAsync→CompletableFuture<Integer>
try-with-resources (RAII)
Standard API
The main EtherCATMaster already implements AutoCloseable, so leaving the try block calls close() automatically:
try (EtherCATMaster master = EtherCATMaster.create()) {
master.setNetwork("\\Device\\NPF_{xxx}");
master.setState(EcState.OP);
master.start();
// ... application code ...
} // Automatically calls close() - stops the PDO cycle + releases the communication resources + unregisters the callback
close() may be called repeatedly: once a complete release has succeeded, further calls return immediately; if a call did not release everything, the master stays in the "closing" state and calling close() again continues the release until it really finishes.
Sugar: MasterScope
The main close() does not:
- switch the hardware back to INIT before exiting (which avoids leaving the hardware in OP and hitting the slave watchdog on the next start)
- release sub-resources attached by the application (for example
DiagnosticQueue)
MasterScope wraps a layer of try-with-resources and does these two extra things:
import com.darra.ethercat.sugar.MasterScope;
import com.darra.ethercat.sugar.DiagnosticQueue;
EtherCATMaster master = EtherCATMaster.create();
master.setNetwork(nic);
try (MasterScope scope = MasterScope.of(master).resetToInitOnClose()) {
// Sub-resources also hang off the scope and are released LIFO on exit
DiagnosticQueue dq = scope.attach(DiagnosticQueue.attach(master, 1024));
master.setState(EcState.OP);
master.start();
// ... application code ...
}
// Exit order: close DiagnosticQueue first -> switch the master back to INIT -> stop the PDO -> master.close()
MasterScope methods
public static MasterScope of(EtherCATMaster master)
public MasterScope resetToInitOnClose()
public MasterScope stopBeforeClose(boolean stop)
public <T extends AutoCloseable> T attach(T resource)
public EtherCATMaster master()
public void close()
| Method | Parameters | Default | Description |
|---|---|---|---|
| of | EtherCATMaster master | — | Wraps a master that has already been built; a null master throws IllegalArgumentException |
| resetToInitOnClose | none | Off | Switches the master back to EcState.INIT when the scope exits |
| stopBeforeClose | boolean stop | true | Whether to call master.stop() first to stop the PDO cycle before closing; there is rarely a reason to turn it off |
| attach | T extends AutoCloseable | — | Attaches a sub-resource and returns the same instance (handy for direct assignment); a null resource is ignored and not attached |
| master | none | — | Returns the wrapped master reference |
MasterScope.close()
Releases in a fixed order; a failure in one step does not interrupt the following steps:
close()every sub-resource registered throughattach, in reverse attachment order (last in, first out);- if
resetToInitOnClose()is enabled and the master is not released, callmaster.setState(EcState.INIT); a return value offalsealso counts as a failure; - if
stopBeforeClose(true)(the default) applies and the master is not released, callmaster.stop(); - call
master.close().
Exceptions: a failure in any step is logged and thrown at the end of close() — a single failure keeps its original exception type (checked exceptions are wrapped in RuntimeException), while several failures are aggregated into one RuntimeException (the first failure becomes the cause, the rest can be found through getSuppressed()). Under try-with-resources the business exception takes precedence and the release exception is attached to it as suppressed, so neither is swallowed.
Idempotent: repeated close() calls do not release twice; once closed, further calls return immediately.
When to use
- Simple demo / unit test — plain
try (EtherCATMaster m = ...) - Long-running service —
MasterScope+resetToInitOnClose() - Several event queues attached by the application — manage them together with
MasterScope.attach() - Several master instances — nest try-with-resources; the JVM guarantees release in reverse order
Stream API
Standard API
EtherCATMaster implements Iterable<Slave> and slaves() returns List<Slave>, so .stream() works directly:
master.slaves().stream()
.filter(s -> s.state() == EcState.OP)
.forEach(s -> System.out.println(s.name()));
Sugar: MasterStreams
MasterStreams adds defensive behaviour and common filters on top of master.slaves().stream():
import com.darra.ethercat.sugar.MasterStreams;
// 1. Null-safe: return an empty Stream when the master is not built yet / already disposed / Slaves is null
MasterStreams.slaves(master).forEach(s -> ...);
// 2. Filter by state
MasterStreams.slavesInState(master, EcState.PRE_OP)
.forEach(s -> System.err.println("Stuck: " + s.name()));
// 3. Group by vendor
MasterStreams.slavesByVendor(master, 0x00000002) // Beckhoff
.map(Slave::name)
.forEach(System.out::println);
// 4. Filter by name containment
MasterStreams.slavesByName(master, "EL2008")
.forEach(s -> s.PDO().out().get(0).asUInt8((byte) 0xFF));
// 5. Already offline
MasterStreams.lostSlaves(master).count();
// 6. Slaves that support DC
MasterStreams.dcCapableSlaves(master).count();
MasterStreams slave streams and lookup
public static Stream<Slave> slaves(EtherCATMaster master)
public static Optional<Slave> slaveOpt(EtherCATMaster master, int slaveIndex)
| Method | Parameters | Description |
|---|---|---|
| slaves | EtherCATMaster master | A Stream<Slave> of all slaves, equivalent to master.slaves().stream() |
| slavesInState | master, EcState state | Keeps only slaves whose state equals state; a null state returns an empty Stream |
| slavesNotInState | master, EcState state | The complement of slavesInState; a null state returns all slaves |
| slavesByVendor | master, int vendorId | Filters by vendor ID; a vendorId of 0 is equivalent to slaves |
| slavesByName | master, String namePart | Slave names that contain namePart (case-sensitive); a null or empty namePart returns all slaves |
| lostSlaves | master | Slaves that have been lost / dropped offline (Slave.isLost() is true) |
| dcCapableSlaves | master | Slaves that support DC (Slave.hasDC() is true) |
| slaveOpt | master, int slaveIndex | Gets a single slave by its 1-based index and returns an Optional<Slave> |
| findByName | master, String name | The first slave whose name is exactly equal; a null name returns an empty Optional |
| findByConfigAddr | master, short configAddr | The first slave with an equal configured address |
| findByIdentity | master, int vendorId, int productCode | The first slave whose vendor ID and product ID both match |
Return values: every method returns an empty Stream / empty Optional when the master is null, the master has been released or there are no slaves — no exception is thrown. slaveOpt likewise returns an empty Optional when the index is out of range (less than 1 or greater than master.slaveCount()).
Slaves whose state cannot be read (the read fails or returns null) take part in filtering and grouping as EcState.NONE, so slavesInState(master, EcState.NONE) finds them; they never make the method throw.
Collection views
// 1. 1-based index -> Slave dictionary
Map<Integer, Slave> idx = MasterStreams.slavesAsMap(master);
Slave s3 = idx.get(3); // Returns null when there is no #3
// 2. Cursor support (firstKey/lastKey/floor/ceiling)
NavigableMap<Integer, Slave> nav = MasterStreams.slavesAsNavigableMap(master);
Map.Entry<Integer, Slave> next = nav.ceilingEntry(currentSlave + 1);
// 3. Group by the Group byte
Map<Byte, List<Slave>> byGrp = MasterStreams.slavesByGroup(master);
List<Slave> group0 = byGrp.getOrDefault((byte) 0, Collections.emptyList());
// 4. Group by state (the core of the diagnostics dashboard)
Map<EcState, List<Slave>> byState = MasterStreams.slavesByState(master);
Map<EcState, Long> stateCounts = MasterStreams.stateCounts(master);
// stateCounts → {OP=8, SAFE_OP=0, PRE_OP=1, INIT=0}
// 5. Group by VendorId
Map<Integer, List<Slave>> byVendor = MasterStreams.slavesByVendorId(master);
| Method | Returns | Description |
|---|---|---|
| slavesAsMap | Map<Integer, Slave> | 1-based index → slave, inserted in index order, suitable for O(1) random access |
| slavesAsNavigableMap | NavigableMap<Integer, Slave> | As above but ordered by key, supporting firstKey / lastKey / floor / ceiling |
| slavesByGroup | Map<Byte, List<Slave>> | Grouped by the Group byte, usually 0..7; group 0 / 1 can be used to separate fast and slow tasks |
| slavesByState | Map<EcState, List<Slave>> | Grouped by state, commonly used by diagnostic dashboards |
| stateCounts | Map<EcState, Long> | Number of slaves in each state |
| slavesByVendorId | Map<Integer, List<Slave>> | Grouped by vendor ID, for diagnosing networks with mixed vendors |
These views are all snapshots: a null master, a released master or no slaves yields an empty Map, and later topology changes are not reflected in a Map you already hold — call again if you need live data. The returned Map cannot be modified at the outer level; the inner List of a grouped view is an ordinary list.
SlaveListExt — collection algebra
import com.darra.ethercat.sugar.SlaveListExt;
// Take a snapshot into an array (safe to cross threads)
Slave[] all = SlaveListExt.toArray(master);
// Sort
List<Slave> ordered = SlaveListExt.sortedByConfigAddr(master);
List<Slave> mixed = SlaveListExt.sortedByVendorThenIndex(master);
// Count
long opCount = SlaveListExt.countByState(master, EcState.OP);
long lost = SlaveListExt.lostCount(master);
long dc = SlaveListExt.dcCapableCount(master);
// Full boolean
if (SlaveListExt.allInState(master, EcState.OP)) {
enableMotion();
}
if (SlaveListExt.anyInState(master, EcState.PRE_OP)) {
raiseAlarm("发现 PreOp 从站"); // PreOp slave found
}
SlaveListExt methods
public static Slave[] toArray(EtherCATMaster master)
public static List<SlaveIdentity> identities(EtherCATMaster master)
| Method | Parameters | Returns | Description |
|---|---|---|---|
| toArray | master | Slave[] | A slave array snapshot that can be passed across threads; a null master, a released master or no slaves returns a 0-length array |
| sortedBySlaveNum | master | List<Slave> | A new list sorted ascending by 1-based index |
| sortedByConfigAddr | master | List<Slave> | Sorted ascending by configured address, suitable for enumerating in physical topology order |
| sortedByVendorThenIndex | master | List<Slave> | By vendor ID first, then by index, so slaves from the same vendor sit together |
| countByState | master, EcState state | long | Number of slaves in state; a null state returns 0 |
| lostCount | master | long | Number of lost slaves |
| dcCapableCount | master | long | Number of slaves that support DC |
| allInState | master, EcState state | boolean | true only when every slave is in state; false when state is null or the network has no slaves |
| anyInState | master, EcState state | boolean | true when any slave is in state; false when state is null |
| hasLostSlave | master | boolean | Whether any slave is lost |
| identities | master | List<SlaveIdentity> | An identity snapshot of the whole network: an immutable list in index order |
The sorting methods return new List<Slave> copies; modifying them does not affect the master. allInState returns false when there are no slaves — an empty network must not be treated as "whole network ready".
When to use
- Simple forEach — plain
for (Slave s : master)ormaster.slaves().stream() - Multiple filters plus collection —
MasterStreams.slavesInState(master, EcState.OP).filter(...).collect(...) - O(1) random access —
MasterStreams.slavesAsMap() - Freezing across threads —
SlaveListExt.toArray()orSlaveListExt.identities() - Collection algebra (all/any/count) —
SlaveListExt.*
Optional<Slave>
Standard API
The main master.getSlave(idx) throws IndexOutOfBoundsException when the index is out of range:
try {
Slave s = master.getSlave(99); // May throw
} catch (IndexOutOfBoundsException e) { ... }
Sugar: slaveOpt
import com.darra.ethercat.sugar.MasterStreams;
MasterStreams.slaveOpt(master, 99).ifPresent(s -> {
System.out.println(s.name());
});
// With defaults
String name = MasterStreams.slaveOpt(master, 99)
.map(Slave::name)
.orElse("(missing)");
// Chained query
Optional<Slave> el2008 = MasterStreams.findByName(master, "EL2008");
Optional<Slave> ek1100 = MasterStreams.findByConfigAddr(master, (short) 0x1001);
Optional<Slave> match = MasterStreams.findByIdentity(master, 0x00000002, 0x07D03052);
When to use
- The index is always valid —
master.getSlave(idx)(main API), simple and direct - The index may be out of range / the master is not built yet —
slaveOpt - Lookup by name / address / identity —
findByName/findByConfigAddr/findByIdentity - A default value when nothing is found —
orElse/orElseGet
Iterable for-each
The main EtherCATMaster already implements Iterable<Slave>, so for-each works directly:
for (Slave s : master) {
System.out.println(s.name());
}
iterator() returns Collections.unmodifiableList(slaves).iterator(); structural modification is not allowed during iteration, but reading any property (Name/State/...) is safe.
No extra sugar is needed — the standard Java Iterable is good enough.
CompletableFuture async
Standard API
The main API already has:
CompletableFuture<Boolean> f = master.setStateAsync(EcState.OP);
boolean ok = f.join();
But the main API covers only two entry points, the state switch and the NIC binding; other long-running operations (scan / configureDC / applyStartupParameters) have to be wrapped by the application itself.
Sugar: MasterAsync
import com.darra.ethercat.sugar.MasterAsync;
// 1. Serial chain
MasterAsync.setNetworkAsync(master, primary, secondary)
.thenCompose(ok -> MasterAsync.setStateAsync(master, EcState.OP, Duration.ofSeconds(30)))
.thenAccept(ok -> System.out.println("OP=" + ok));
// 2. boot
boolean ok = MasterAsync.bootToOpAsync(master, primary, secondary).join();
// 3. Scan several NICs in parallel
CompletableFuture<Integer> a = MasterAsync.scanAsync(nicA);
CompletableFuture<Integer> b = MasterAsync.scanAsync(nicB);
CompletableFuture<Integer> c = MasterAsync.scanAsync(nicC);
CompletableFuture.allOf(a, b, c)
.thenRun(() -> {
System.out.printf("A=%d B=%d C=%d%n", a.join(), b.join(), c.join());
});
// 4. Async DC configuration
MasterAsync.configureDCAllAsync(master, 1_000_000, 0)
.whenComplete((rc, ex) -> {
if (ex != null) log.error("DC failed", ex);
else log.info("DC rc={}", rc);
});
// 5. Expose the shared guardian thread pool; later callbacks run on the same pool
master.setStateAsync(EcState.SAFE_OP)
.thenApplyAsync(ok -> save(ok), MasterAsync.executor());
MasterAsync methods
public static Executor executor()
public static CompletableFuture<Boolean> setStateAsync(EtherCATMaster master, EcState state)
public static CompletableFuture<Boolean> setStateAsync(EtherCATMaster master, EcState state, Duration timeout)
public static CompletableFuture<Boolean> setNetworkAsync(EtherCATMaster master, String primary, String secondary)
public static CompletableFuture<Integer> scanAsync(String adapterName)
public static CompletableFuture<Integer> scanRedundantAsync(String primary, String secondary)
public static CompletableFuture<Integer> configureDCAllAsync(EtherCATMaster master, int sync0Ns, int sync1Ns)
public static CompletableFuture<Integer> applyStartupParametersAsync(EtherCATMaster master, byte transition, byte timing)
public static CompletableFuture<Boolean> bootToOpAsync(EtherCATMaster master, String primary, String secondary)
| Method | Parameters | Returns | Description |
|---|---|---|---|
| executor | none | Executor | The daemon thread pool reused by asynchronous chains; can be handed to thenApplyAsync(..., MasterAsync.executor()) |
| setStateAsync | master, EcState state | CompletableFuture<Boolean> | Equivalent to master.setStateAsync(state), without wrapping another layer |
| setStateAsync | master, EcState state, Duration timeout | CompletableFuture<Boolean> | The version with a wait limit; completes with false when the timeout expires |
| setNetworkAsync | master, String primary, String secondary | CompletableFuture<Boolean> | Binds the NIC and scans asynchronously; a null or empty secondary means no redundancy |
| scanAsync | String adapterName | CompletableFuture<Integer> | Asynchronously scans the number of slaves on a single NIC; a static method that needs no master |
| scanRedundantAsync | String primary, String secondary | CompletableFuture<Integer> | Asynchronously scans a redundant NIC pair; a static method |
| configureDCAllAsync | master, int sync0Ns, int sync1Ns | CompletableFuture<Integer> | Asynchronously configures synchronisation for every DC slave in the network |
| applyStartupParametersAsync | master, byte transition, byte timing | CompletableFuture<Integer> | Asynchronously applies the startup parameters to all slaves; the parameters have the same meaning as in applyStartupParametersAll |
| bootToOpAsync | master, String primary, String secondary | CompletableFuture<Boolean> | One-call startup: bind the NIC → enter EcState.OP → start the PDO cycle |
Completion value semantics:
- When
masterisnull,setStateAsync/setNetworkAsync/bootToOpAsyncreturn an already-completedfalse, andconfigureDCAllAsync/applyStartupParametersAsyncreturn an already-completed-1. - The completion value of
scanAsync/scanRedundantAsyncis a return code:>= 0is the number of slaves found (0 = an empty bus, which is a normal result),< 0is the raw error code; when the scan call itself throws, the future completes with-1. Anullor empty primary NIC name throwsIllegalArgumentException. - The completion value of
configureDCAllAsyncequals the return value ofmaster.configureDCAll(...): the number of DC stations that were applied and accepted (armed plus prepared in PRE_OP), not the number that were armed;< 0means failure. bootToOpAsynccompletes withfalsewhen any step fails; whenmaster.start()throws (for example because the master has been released) the future completes exceptionally rather than swallowing the exception and still reportingtrue.
setNetworkAsync does not hold todaysetNetworkAsync treats 「setNetwork returns 0」 as success, while the return value of setNetwork means the number of slaves found (-1 is the only failure). So as soon as any slave is found on the NIC this yields false, and bootToOpAsync fails early along with it. Until the criterion is fixed, judge by the return value of master.setNetwork(...) yourself (>= 0 means success). This issue is still to be fixed.
Executor
MasterAsync.executor() returns the executor reused by asynchronous chains:
- Daemon threads, so it never prevents the JVM from exiting
- Isolated from the application's other tasks, so behaviour is more predictable
When to use
- A single state switch where you wait for the result — the main
master.setState()(synchronous, simple) - Several steps in sequence —
MasterAsync.bootToOpAsyncorthenCompose - Scanning several NICs in parallel —
MasterAsync.scanAsync+allOf - Spring/Reactor integration — the
CompletableFuturereturned bysetStateAsync()is itself aCompletionStage - A strict timeout —
MasterAsync.setStateAsync(m, s, Duration.ofSeconds(30))
Waiting timeout semantics
setStateAsync(master, state, timeout) completes with false and writes a WARNING log when timeout expires, but the state switch keeps going; false only means "this wait timed out" and does not mean the switch failed. If the switch or the wait throws, the future likewise completes with false and logs it (the reason for the failure is not swallowed). A timeout of null, zero or a negative value degrades to the two-argument version without a timeout.
The state switch has its own timeout and transient retries, and a single switch can take tens of seconds; timeout must cover the worst case, otherwise you get "the future reports false while the state reaches the target later". To judge the result strictly, poll master.state() as a fallback and do not rely on this false alone.
Diagnostic history streams (DiagnosticStream)
DiagnosticStream wraps the history records of a single slave into a Stream: the CoE emergency history and the 0x10F3 diagnostic history. It is read-only and holds no state; a null slave or a failed read always returns an empty Stream and never throws.
public static Stream<CoE.EmergencyMessage> emergencies(Slave slave)
public static Stream<CoE.DiagnosticMessage> diagnostics(Slave slave)
Emergency message stream
| Method | Parameters | Returns | Description |
|---|---|---|---|
| emergencies | Slave slave | Stream<CoE.EmergencyMessage> | All emergency messages (the CoE emergency history) |
| emergenciesByCode | slave, short errorCode | Stream<CoE.EmergencyMessage> | Emergency messages with an equal error code (CiA-301 error code, e.g. 0x8130 = SYNC error) |
| emergenciesByRegister | slave, byte registerMask | Stream<CoE.EmergencyMessage> | Emergency messages whose error register ANDed with the mask is not 0 (CiA-301 error register bit flags) |
| recentEmergencies | slave, int limit | Stream<CoE.EmergencyMessage> | The first limit entries in reverse time order; limit <= 0 returns an empty Stream |
| emergencyCount | slave | long | Total number of emergency messages, suitable for a dashboard counter |
recentEmergencies only limits the number of entries returned; how many you actually get depends on how many entries the CoE emergency history holds.
CoE.EmergencyMessage fields:
| Field | Type | Description |
|---|---|---|
| ErrorCode | short | Error code |
| ErrorRegister | byte | Error register |
| Data | byte[] | Additional data |
| SlaveIndex | short | Index of the originating slave |
| Timestamp | long | Timestamp |
0x10F3 diagnostic stream
| Method | Parameters | Returns | Description |
|---|---|---|---|
| diagnostics | Slave slave | Stream<CoE.DiagnosticMessage> | All 0x10F3 diagnostic messages |
| diagnosticsByCode | slave, int diagCode | Stream<CoE.DiagnosticMessage> | Filters by DiagCode being equal |
| diagnosticsBySeverity | slave, short severityMask | Stream<CoE.DiagnosticMessage> | Filters by Flags ANDed with the mask being not 0 |
| latestDiagnostics | slave, int limit | Stream<CoE.DiagnosticMessage> | The first limit entries in descending SubIndex order; limit <= 0 returns an empty Stream |
CoE.DiagnosticMessage fields: SubIndex (byte, message sequence number) / DiagCode (int) / Flags (short) / TextIndex (short) / RawData (byte[], the raw bytes of the 0x10F3 message).
readDiagnosticMessages() fills the fields in message byte order: the first 4 bytes go into DiagCode, the next 2 bytes into Flags and the following 2 bytes into TextIndex, which is not aligned with the meaning of those three field names. So diagnosticsByCode / diagnosticsBySeverity currently compare the shifted values rather than the semantic diagnostic code and severity; to filter semantically, parse RawData yourself. See CoE diagnostic history. This mismatch is still to be fixed.
BlockingQueue event queues
Standard API
The main API subscribes to events with callbacks:
master.events().addEmergencyEventListener((mi, si, ec, er, b1, w1, w2) -> {
saveToDb(ec); // Slow operation - runs on the PDO thread and blocks the EtherCAT cycle!
});
The callback fires directly on the underlying PDO thread, so IO, database work or locking on the application side slows the whole network down.
Sugar: DiagnosticQueue
Register the callback once and turn it into a thread-safe BlockingQueue<EmergencyEvent>:
import com.darra.ethercat.sugar.DiagnosticQueue;
try (DiagnosticQueue dq = DiagnosticQueue.attach(master, 1024)) {
// Background consumer thread
Thread consumer = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
DiagnosticQueue.EmergencyEvent ev = dq.take();
saveToDb(ev); // Slow operation - no longer blocks the PDO
} catch (InterruptedException e) {
break;
}
}
});
consumer.setDaemon(true);
consumer.start();
master.start();
Thread.sleep(60_000);
} // close unregisters the callback automatically and clears the queue
Behaviour when the queue is full
DiagnosticQueue offers two modes:
attach(master, cap)— drops the oldest event when full, no blocking. Recommended — it protects the PDO threadattachStrict(master, cap)— blocks the callback thread when full. Use with care, and only when events absolutely must not be lost
DiagnosticQueue methods
public static DiagnosticQueue attach(EtherCATMaster master, int capacity)
public static DiagnosticQueue attachStrict(EtherCATMaster master, int capacity)
| Method | Parameters | Returns | Description |
|---|---|---|---|
| attach | master, int capacity | DiagnosticQueue | Creates the queue and registers the callback; capacity <= 0 is treated as 1024; drops the oldest event when full |
| attachStrict | master, int capacity | DiagnosticQueue | As above, but blocks the event callback thread until space is available when full; capacity <= 0 is treated as 1024 |
| take | none | EmergencyEvent | Takes one entry, blocking, with no timeout |
| poll | long timeout, TimeUnit unit | EmergencyEvent | Takes one entry with a timeout; returns null on timeout |
| pollNow | none | EmergencyEvent | Takes one entry without blocking; returns null when the queue is empty |
| size | none | int | Current queue length |
| isStrict | none | boolean | Whether strict mode is on (blocks the callback when full) |
| queue | none | BlockingQueue<EmergencyEvent> | Exposes the raw queue, for drainTo / iterator and so on |
| close | none | void | Unregisters the callback and clears the queue; may be called repeatedly |
Exceptions: a null master in attach / attachStrict throws IllegalArgumentException. take / poll throw InterruptedException when interrupted while waiting.
EmergencyEvent fields:
| Field | Type | Description |
|---|---|---|
| masterIndex | short | Master index |
| slaveIndex | short | Slave index |
| errorCode | short | Emergency error code |
| errorReg | byte | Error register |
| b1 / w1 / w2 | byte / short / short | The three additional parameters of the emergency frame |
| enqueueMs | long | Enqueue time (System.currentTimeMillis()) |
SlaveStateQueue — the state-change version
import com.darra.ethercat.sugar.SlaveStateQueue;
// Wait for the whole network to reach OP, 30 s timeout
try (SlaveStateQueue q = SlaveStateQueue.attach(master, 256)) {
master.setState(EcState.OP);
long deadline = System.currentTimeMillis() + 30_000;
while (System.currentTimeMillis() < deadline) {
SlaveStateQueue.StateChangeEvent ev = q.poll(500, TimeUnit.MILLISECONDS);
if (ev != null && ev.newState == EcState.OP) {
if (SlaveListExt.allInState(master, EcState.OP)) break;
}
}
}
// Or Stream style (runs on its own thread, blocks until close)
SlaveStateQueue q = SlaveStateQueue.attach(master, 256);
new Thread(() -> q.streamUntilClosed()
.filter(ev -> ev.newState == EcState.PRE_OP)
.forEach(ev -> log.warn("从站 {} 跌回 PreOp", ev.slaveIndex)) // Slave {} fell back to PreOp
).start();
SlaveStateQueue methods
public static SlaveStateQueue attach(EtherCATMaster master, int capacity)
public Stream<StateChangeEvent> streamUntilClosed()
| Method | Parameters | Returns | Description |
|---|---|---|---|
| attach | master, int capacity | SlaveStateQueue | Creates the queue and registers the state-change callback; capacity <= 0 is treated as 256; drops the oldest event when full and never blocks the callback |
| take | none | StateChangeEvent | Takes one entry, blocking, with no timeout |
| poll | long timeout, TimeUnit unit | StateChangeEvent | Takes one entry with a timeout; returns null on timeout |
| pollNow | none | StateChangeEvent | Takes one entry without blocking; returns null when the queue is empty |
| size | none | int | Current queue length |
| streamUntilClosed | none | Stream<StateChangeEvent> | A blocking Stream that keeps taking until close(), suitable for forEach-style consumption |
| close | none | void | Unregisters the callback and clears the queue; may be called repeatedly |
Exceptions: a null master in attach throws IllegalArgumentException; take / poll throw InterruptedException when interrupted while waiting.
StateChangeEvent fields:
| Field | Type | Description |
|---|---|---|
| masterIndex | short | Master index |
| slaveIndex | short | Slave index |
| oldState | EcState | State before the change; EcState.NONE when it cannot be read |
| newState | EcState | State after the change; EcState.NONE when it cannot be read |
| enqueueMs | long | Enqueue time (System.currentTimeMillis()) |
streamUntilClosed must run on its own threadThis Stream advances one entry at a time, so the calling thread blocks until an event arrives or the queue is closed. After close() no new elements are produced; a thread already blocked on taking an event has to leave through interruption, so remember to interrupt() that consumer thread before you shut down.
When to use
- Logging a single event as it arrives — plain
addXxxListener, short and quick - Slow consumption (writing to a database, pushing to MQ) —
DiagnosticQueue - State machine decisions (waiting for OP) —
SlaveStateQueue.poll - Stream-style subscription (forEach style) —
SlaveStateQueue.streamUntilClosed
The record (Java 14+) equivalent
Standard API
The record keyword from Java 14+:
public record SlaveIdentity(
int slaveNum, long vendorId, long productId, long revisionId,
long serialNumber, String name, String deviceName) {}
But this SDK targets Java 11, so record cannot be used.
Sugar: SlaveIdentity
com.darra.ethercat.sugar.SlaveIdentity is a hand-written record equivalent — immutable, with accessors plus equals/hashCode/toString:
import com.darra.ethercat.sugar.SlaveIdentity;
// 1. Take a snapshot from a live Slave
SlaveIdentity id = SlaveIdentity.snapshot(master.getSlave(3));
// 2. record-style accessors (the field name is the method name, no get prefix)
System.out.println("V=0x" + Long.toHexString(id.vendorId()));
System.out.println("P=0x" + Long.toHexString(id.productId()));
// 3. Cross-thread handoff - does not lock the master lifetime
executor.submit(() -> report(id));
// 4. As a HashMap key
Map<SlaveIdentity, Long> lastSeen = new HashMap<>();
lastSeen.put(id, System.currentTimeMillis());
// 5. Configuration check (Hot-plug)
SlaveIdentity expected = new SlaveIdentity(
3, 0x00000002L, 0x044C2C52L, 0x00100000L, 0L, "EL2008", "");
if (!actual.matchesIdentity(expected)) {
raiseAlarm("从站身份不符"); // Slave identity mismatch
}
// 6. Exact match (including Serial)
if (!actual.equalsExact(expected)) {
rebindCalibration();
}
SlaveIdentity fields and accessors
public SlaveIdentity(int slaveNum, long vendorId, long productId, long revisionId,
long serialNumber, String name, String deviceName)
public static SlaveIdentity snapshot(Slave slave)
| Field | Accessor | Type | Description |
|---|---|---|---|
| slaveNum | slaveNum() | int | 1-based slave index |
| vendorId | vendorId() | long | Vendor ID (32-bit unsigned) |
| productId | productId() | long | Product ID (32-bit unsigned) |
| revisionId | revisionId() | long | Revision number (32-bit unsigned) |
| serialNumber | serialNumber() | long | Serial number (32-bit unsigned) |
| name | name() | String | Slave name (EEPROM); an empty string when it cannot be read |
| deviceName | deviceName() | String | Device name (SDO 0x1008); an empty string when it cannot be read |
At construction the four 32-bit fields are normalised to long as unsigned values, and a null string is treated as an empty string, so once an instance exists its fields are never null and never negative. equals / hashCode cover all seven fields, and toString outputs SlaveIdentity[slave=.. V=.. P=.. R=.. S=.. name=.. drive=..].
snapshot(slave)
Takes an identity snapshot from a live Slave. A null slave returns an all-zero identity (index 0, empty strings); when a single field cannot be read, that field is filled with 0 / an empty string without affecting the others. Once created, the snapshot no longer depends on the lifetime of the master or of the slave object.
matchesIdentity(expected)
Parameters: expected is the expected identity; a null value returns false.
Return value: true when the vendor ID and product ID are exactly equal and revisionId >= expected.revisionId. The revision is compared with ETG's backward-compatibility semantics (an actual revision no lower than the expected one counts as a match), which suits configuration validation after hot-plug.
equalsExact(other)
Parameters: other is the other identity; a null value returns false.
Return value: true only when the vendor ID, product ID, revision number and serial number are all equal; it decides whether this is "exactly the same piece of hardware". Unlike matchesIdentity, the revision is not relaxed and the serial number is compared as well; the slave index and the two names take no part in the comparison (those are only compared in equals / hashCode).
Whole-network snapshot
// Grab the immutable identity of every slave in one pass
List<SlaveIdentity> all = SlaveListExt.identities(master);
// Persist to disk (for cross-process comparison)
saveToJson("snapshot.json", all);
Upgrading to Java 14+
If the project moves to Java 14+ in future, replace SlaveIdentity with a real record:
public record SlaveIdentity(int slaveNum, long vendorId, long productId,
long revisionId, long serialNumber, String name, String deviceName) {
public static SlaveIdentity snapshot(Slave s) { ... }
public boolean matchesIdentity(SlaveIdentity expected) { ... }
}
The calling code does not change at all — the accessor names are the same and the constructor parameters are in the same order.
When to use
- Reading the latest state live — use the
Slaveobject directly (it has themastercontext) - Passing across threads —
SlaveIdentity.snapshot(slave) - Caching / HashMap key —
SlaveIdentity(the mainSlavehas no suitable equals) - Serialisation (JSON / DB) —
SlaveIdentityhas fixed fields and serialises easily - Configuration validation —
SlaveIdentity.matchesIdentity()
Functional listener (lambda)
Every listener interface inside the main MasterEvents is marked @FunctionalInterface, so a lambda can be passed directly — no extra sugar is needed:
master.events().addEmergencyEventListener(
(mi, si, errorCode, errorReg, b1, w1, w2) ->
System.out.printf("Slave %d Emcy 0x%04X%n", si, errorCode & 0xFFFF));
master.events().addSlaveStateChangedListener(
(mi, si, oldState, newState) ->
log.info("Slave {} {}->{}", si, oldState, newState));
master.events().addPDOFrameLossListener(
(mi, group, consec, total) ->
alarm.raise("Group %d 连丢 %d, 累计 %d", group, consec, total)); // Group %d consecutive losses %d, cumulative %d
Note that one EmergencyEventListener callback has 7 parameters; the lambda form is short, but you have to look up what the parameters mean. Combining it with DiagnosticQueue to turn the callback into an event object is recommended (the field names are clear).
Builder pattern
Standard API
The main API already has fluent construction:
EtherCATMaster m = EtherCATMaster.create()
.setENI("config.deni")
.enableAutoStartup();
m.setNetwork(primary);
m.build();
But it requires create() first and then the chained calls — the order is less natural, and create() has already allocated the master number (on failure you need close() to release it).
Sugar: MasterBuilder
import com.darra.ethercat.sugar.MasterBuilder;
EtherCATMaster m = MasterBuilder.create()
.network(primary)
.redundant(secondary)
.esiFolder("C:/Esi")
.eni("C:/cfg/ec.deni")
.autoStartup()
.targetState(EcState.OP)
.startPdoAfterOp()
.masterNumber((short) 0)
.build();
MasterBuilder methods
public static MasterBuilder create()
public EtherCATMaster build()
Each method on the construction chain only records a parameter and returns this; before build() no master instance is created, no master number is taken and no communication resources are held, so you can call them repeatedly or overwrite earlier values freely.
| Method | Parameters | Default | Description |
|---|---|---|---|
| network | String primaryNic | none | Device path of the primary NIC (\\Device\\NPF_{...}, or the NIC name on Linux); required |
| redundant | String secondaryNic | none | Redundant standby NIC; optional |
| eni | String path | none | Path of the ENI / DENI configuration file; it is only parsed at build() after being recorded |
| esiFile | String path | none | A single ESI file; repeated calls append one after another; null or an empty string is ignored |
| esiFolder | String path | none | An ESI directory; every *.xml in it is loaded as well; null or an empty string is ignored |
| autoStartup | none | Off | Turns on automatic application of the startup parameters |
| targetState | EcState state | No switch | Switches the master to that state at the end of build() |
| startPdoAfterOp | none | Off | Starts the PDO cycle after switching to the target state; only takes effect when targetState is EcState.OP or EcState.SAFE_OP |
| masterNumber | short index | Allocated automatically | Sets the master number |
build() runs in a fixed order: bind the NIC and scan → load the ESI files one after another → load the ENI → apply the startup parameters (if autoStartup()) → build the master → switch to the target state (if targetState was set) → start the PDO cycle (if startPdoAfterOp()).
Rollback on failure
Any step that fails throws IllegalStateException and automatically close()s the half-initialised master, leaving nothing behind:
try {
EtherCATMaster m = MasterBuilder.create()
.network("\\Device\\NPF_BOGUS") // A NIC that does not exist
.build();
} catch (IllegalStateException e) {
// master is already closed, no manual cleanup needed
log.error("Build failed: {}", e.getMessage());
}
Exceptions:
| Exception | Triggered when |
|---|---|
NullPointerException | build() is called without calling network(...) first |
IllegalStateException | NIC binding or scanning failed; ENI loading or master construction failed (the message carries BuildResult.message); the targetState switch returned false; any other unexpected exception (wrapped uniformly, with the original exception as the cause) |
On failure build() automatically close()s the half-initialised master, so the caller does not have to clean up. If the release itself fails, it is logged and the master stays in a retryable closing state where close() can be called again; the original failure is still thrown with its original type.
build() does not hold todaybuild() treats 「setNetwork returns 0」 as a successful bind, while the return value of setNetwork means the number of slaves found (-1 is the only failure). So as soon as any slave is found on the NIC, build() throws IllegalStateException (message setNetwork 失败 rc=<从站数> (SDK output, = setNetwork failed rc=<slave count>)) and reclaims the master. Until the criterion is fixed, use the main API when the bus has slaves: EtherCATMaster.create() → setNetwork(...) → build(). This issue is still to be fixed.
When to use
- One-off configuration at program start —
MasterBuilder(declarative, with automatic rollback on failure) - Adjusting mid-run (adding an ESI dynamically) — the main fluent API (
master.setEsiFile().build()) - Mocking a master in a unit test — plain
EtherCATMaster.create()
Complete example: automatic entry to OP plus diagnostic streams
Putting all the sugar together:
The example uses both MasterBuilder.build() and MasterAsync.bootToOpAsync, and both are affected by the criterion issues described above: they report failure when the bus has slaves. Follow the practice in the "Failures and handling" section instead — use the main construction path and judge by master.setNetwork(...) yourself.
import com.darra.ethercat.master.EtherCATMaster;
import com.darra.ethercat.data.EcState;
import com.darra.ethercat.slave.Slave;
import com.darra.ethercat.sugar.*;
public class Demo {
public static void main(String[] args) throws Exception {
// 1. Builder-style streaming construction
EtherCATMaster master = MasterBuilder.create()
.network("\\Device\\NPF_{xxx}")
.esiFolder("C:/Esi")
.eni("C:/cfg/ec.deni")
.autoStartup()
.build();
// 2. MasterScope + sub-resources
try (MasterScope scope = MasterScope.of(master).resetToInitOnClose()) {
DiagnosticQueue dq = scope.attach(DiagnosticQueue.attach(master, 1024));
SlaveStateQueue sq = scope.attach(SlaveStateQueue.attach(master, 256));
// 3. Background consumer thread: persist EMCY to the database
Thread emcyWorker = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
DiagnosticQueue.EmergencyEvent ev = dq.take();
saveToDb(ev);
} catch (InterruptedException e) { break; }
}
}, "emcy-worker");
emcyWorker.setDaemon(true);
emcyWorker.start();
// 4. Async boot: NIC -> OP -> PDO
boolean ok = MasterAsync.bootToOpAsync(master,
"\\Device\\NPF_{xxx}", null).get(30, TimeUnit.SECONDS);
if (!ok) throw new IllegalStateException("Boot failed");
// 5. Report the network state with the Stream API
Map<EcState, Long> counts = MasterStreams.stateCounts(master);
System.out.println("State distribution: " + counts);
// 6. Take a whole-network snapshot with SlaveIdentity and persist it across threads
List<SlaveIdentity> ids = SlaveListExt.identities(master);
CompletableFuture.runAsync(() -> saveSnapshot(ids));
// 7. Main loop - wait until the whole network reaches OP, with a 30 s timeout
long deadline = System.currentTimeMillis() + 30_000;
while (System.currentTimeMillis() < deadline) {
if (SlaveListExt.allInState(master, EcState.OP)) {
System.out.println("全网 OP, 可以启动运动控制"); // Whole network in OP, motion control can be started
break;
}
Thread.sleep(100);
}
// 8. Run the application for 60 s
Thread.sleep(60_000);
} // Automatic: close DiagnosticQueue/SlaveStateQueue -> master switches to INIT -> stop the PDO -> master.close()
}
}
Design decision record
Reactor interoperability — the CompletableFuture returned by MasterAsync.scanAsync(...) is itself a CompletionStage and can be handed straight to Reactor:
import reactor.core.publisher.Mono;
Mono<Integer> count = Mono.fromCompletionStage(
MasterAsync.scanAsync(nic));
No event loss — DiagnosticQueue drops the oldest event by default; for "absolutely no loss" use DiagnosticQueue.attachStrict(master, capacity) and accept the performance impact yourself.
Failures and handling
| Symptom | Cause | Action |
|---|---|---|
MasterBuilder.build() throws IllegalStateException with the message setNetwork 失败 rc=<从站数> | The current criterion treats the number of slaves found as a failure code | Use the main path EtherCATMaster.create() → setNetwork(...) → build(); go back to MasterBuilder once the criterion is fixed |
MasterAsync.setNetworkAsync / bootToOpAsync complete with false while the NIC is fine | The same criterion issue as above | Judge by the return value of master.setNetwork(...) yourself (>= 0 means success) |
| The slave streams and collection views are all empty | The master is null, has been released, or no slaves have been scanned yet | Finish building first and check that master.slaveCount() > 0 |
allInState stays false | The network has no slaves (an empty network really is false), or some slave has not reached the target state | Use stateCounts / slavesNotInState to see which slaves have not arrived |
The timeout version of setStateAsync completes with false, but the state reaches the target later | The wait timed out while the state switch kept going | Increase timeout and poll master.state() as a fallback |
MasterScope.close() throws | One of the steps failed: releasing a sub-resource, switching to INIT, stop() or close() | Check the failing step name in the log; for several failures look at getSuppressed(); the master can be retried with another close() |
streamUntilClosed() will not stop | The Stream is blocked waiting for an event | Run it on its own thread and interrupt that thread before shutting down |
The network slows down after using attachStrict | The event callback is blocked when the queue is full | Switch to attach, or raise capacity / consume faster |
diagnosticsByCode / diagnosticsBySeverity filter the wrong entries | The diagnostic message field names and contents do not line up | Parse RawData yourself and filter semantically |
recentEmergencies(limit) returns fewer entries | The history simply holds that many | To get a message at the moment of the fault, subscribe with addEmergencyEventListener or DiagnosticQueue |
Index
All classes live in the com.darra.ethercat.sugar package; a single import com.darra.ethercat.sugar.*; makes them available.
| Class | Purpose |
|---|---|
MasterBuilder | Fluent master construction |
MasterScope | Extended try-with-resources that releases sub-resources together |
MasterStreams | Slave Stream / Optional / Map views |
SlaveListExt | Snapshots, sorting, counting and whole-network checks |
SlaveIdentity | Immutable slave identity |
MasterAsync | CompletableFuture asynchronous wrappers |
DiagnosticStream | Streams over the emergency history and the 0x10F3 diagnostic history |
DiagnosticQueue | Turns the emergency event callback into a BlockingQueue |
SlaveStateQueue | Turns state changes into a BlockingQueue / Stream |
MasterStreams / SlaveListExt / SlaveIdentity / MasterAsync / DiagnosticStream are static factories plus immutable value objects — they hold no resources, so repeated calls cost next to nothing. MasterScope / DiagnosticQueue / SlaveStateQueue have an explicit lifetime; call close() when you are done.