Skip to main content

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.

Design principles
  • 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 null master, 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​

CategoryMethodsTypeR/WDescription
Fluent constructionMasterBuilder.create, network, redundant, eni, esiFile, esiFolder, autoStartup, targetState, startPdoAfterOp, masterNumber, buildEtherCATMasterWrite-onlyDeclarative master construction; build() returns the master directly, and on failure it throws IllegalStateException and reclaims the half-built instance
ScopeMasterScope.of, resetToInitOnClose, stopBeforeClose, attach, master, closeAutoCloseableWrite-onlyWraps 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 streamsMasterStreams.slaves, slavesInState, slavesNotInState, slavesByVendor, slavesByName, lostSlaves, dcCapableSlavesStream<Slave>Read-onlyNull-safe slave streams; returns an empty Stream when the master is null, released or has no slaves
LookupMasterStreams.slaveOpt, findByName, findByConfigAddr, findByIdentityOptional<Slave>Read-onlySingle-slave lookup wrapped in Optional; an out-of-range index or a miss returns an empty Optional
Collection viewsMasterStreams.slavesAsMap, slavesAsNavigableMap, slavesByGroup, slavesByState, slavesByVendorId, stateCountsMap / NavigableMapRead-onlyGrouping and counting by index, group, state and vendor; indices start at 1 and the result is an immutable snapshot
Collection algebraSlaveListExt.toArray, sortedBySlaveNum, sortedByConfigAddr, sortedByVendorThenIndex, countByState, lostCount, dcCapableCount, allInState, anyInState, hasLostSlave, identitiesSlave[] / List / long / booleanRead-onlySnapshots, sorting, counting and whole-network checks; a snapshot can be used across threads
Immutable identitySlaveIdentity constructor, snapshot, matchesIdentity, equalsExactSlaveIdentityRead-onlyTakes 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 operationsMasterAsync.executor, setStateAsync, setNetworkAsync, scanAsync, scanRedundantAsync, configureDCAllAsync, applyStartupParametersAsync, bootToOpAsyncCompletableFutureRead-writeAsynchronous wrappers that return a CompletableFuture; executor returns the reused daemon thread pool
Diagnostic streamsDiagnosticStream.emergencies, emergenciesByCode, emergenciesByRegister, recentEmergencies, emergencyCount, diagnostics, diagnosticsByCode, diagnosticsBySeverity, latestDiagnosticsStreamRead-onlyCovers only the CoE emergency history and the 0x10F3 diagnostic history
Diagnostic queueDiagnosticQueue.attach, attachStrict, take, poll, pollNow, size, isStrict, queue, closeDiagnosticQueueRead-onlyTurns the emergency event callback into a blocking queue; attach drops the oldest event when full, attachStrict blocks the callback when full
State queueSlaveStateQueue.attach, take, poll, pollNow, size, streamUntilClosed, closeSlaveStateQueueRead-onlyTurns state changes into a blocking queue that can also be consumed as a Stream; streamUntilClosed blocks until the queue is closed
Return types of MasterAsync
  • setStateAsync / 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()
MethodParametersDefaultDescription
ofEtherCATMaster master—Wraps a master that has already been built; a null master throws IllegalArgumentException
resetToInitOnClosenoneOffSwitches the master back to EcState.INIT when the scope exits
stopBeforeCloseboolean stoptrueWhether to call master.stop() first to stop the PDO cycle before closing; there is rarely a reason to turn it off
attachT extends AutoCloseable—Attaches a sub-resource and returns the same instance (handy for direct assignment); a null resource is ignored and not attached
masternone—Returns the wrapped master reference

MasterScope.close()​

Releases in a fixed order; a failure in one step does not interrupt the following steps:

  1. close() every sub-resource registered through attach, in reverse attachment order (last in, first out);
  2. if resetToInitOnClose() is enabled and the master is not released, call master.setState(EcState.INIT); a return value of false also counts as a failure;
  3. if stopBeforeClose(true) (the default) applies and the master is not released, call master.stop();
  4. 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)
MethodParametersDescription
slavesEtherCATMaster masterA Stream<Slave> of all slaves, equivalent to master.slaves().stream()
slavesInStatemaster, EcState stateKeeps only slaves whose state equals state; a null state returns an empty Stream
slavesNotInStatemaster, EcState stateThe complement of slavesInState; a null state returns all slaves
slavesByVendormaster, int vendorIdFilters by vendor ID; a vendorId of 0 is equivalent to slaves
slavesByNamemaster, String namePartSlave names that contain namePart (case-sensitive); a null or empty namePart returns all slaves
lostSlavesmasterSlaves that have been lost / dropped offline (Slave.isLost() is true)
dcCapableSlavesmasterSlaves that support DC (Slave.hasDC() is true)
slaveOptmaster, int slaveIndexGets a single slave by its 1-based index and returns an Optional<Slave>
findByNamemaster, String nameThe first slave whose name is exactly equal; a null name returns an empty Optional
findByConfigAddrmaster, short configAddrThe first slave with an equal configured address
findByIdentitymaster, int vendorId, int productCodeThe 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);
MethodReturnsDescription
slavesAsMapMap<Integer, Slave>1-based index → slave, inserted in index order, suitable for O(1) random access
slavesAsNavigableMapNavigableMap<Integer, Slave>As above but ordered by key, supporting firstKey / lastKey / floor / ceiling
slavesByGroupMap<Byte, List<Slave>>Grouped by the Group byte, usually 0..7; group 0 / 1 can be used to separate fast and slow tasks
slavesByStateMap<EcState, List<Slave>>Grouped by state, commonly used by diagnostic dashboards
stateCountsMap<EcState, Long>Number of slaves in each state
slavesByVendorIdMap<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)
MethodParametersReturnsDescription
toArraymasterSlave[]A slave array snapshot that can be passed across threads; a null master, a released master or no slaves returns a 0-length array
sortedBySlaveNummasterList<Slave>A new list sorted ascending by 1-based index
sortedByConfigAddrmasterList<Slave>Sorted ascending by configured address, suitable for enumerating in physical topology order
sortedByVendorThenIndexmasterList<Slave>By vendor ID first, then by index, so slaves from the same vendor sit together
countByStatemaster, EcState statelongNumber of slaves in state; a null state returns 0
lostCountmasterlongNumber of lost slaves
dcCapableCountmasterlongNumber of slaves that support DC
allInStatemaster, EcState statebooleantrue only when every slave is in state; false when state is null or the network has no slaves
anyInStatemaster, EcState statebooleantrue when any slave is in state; false when state is null
hasLostSlavemasterbooleanWhether any slave is lost
identitiesmasterList<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) or master.slaves().stream()
  • Multiple filters plus collection — MasterStreams.slavesInState(master, EcState.OP).filter(...).collect(...)
  • O(1) random access — MasterStreams.slavesAsMap()
  • Freezing across threads — SlaveListExt.toArray() or SlaveListExt.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)
MethodParametersReturnsDescription
executornoneExecutorThe daemon thread pool reused by asynchronous chains; can be handed to thenApplyAsync(..., MasterAsync.executor())
setStateAsyncmaster, EcState stateCompletableFuture<Boolean>Equivalent to master.setStateAsync(state), without wrapping another layer
setStateAsyncmaster, EcState state, Duration timeoutCompletableFuture<Boolean>The version with a wait limit; completes with false when the timeout expires
setNetworkAsyncmaster, String primary, String secondaryCompletableFuture<Boolean>Binds the NIC and scans asynchronously; a null or empty secondary means no redundancy
scanAsyncString adapterNameCompletableFuture<Integer>Asynchronously scans the number of slaves on a single NIC; a static method that needs no master
scanRedundantAsyncString primary, String secondaryCompletableFuture<Integer>Asynchronously scans a redundant NIC pair; a static method
configureDCAllAsyncmaster, int sync0Ns, int sync1NsCompletableFuture<Integer>Asynchronously configures synchronisation for every DC slave in the network
applyStartupParametersAsyncmaster, byte transition, byte timingCompletableFuture<Integer>Asynchronously applies the startup parameters to all slaves; the parameters have the same meaning as in applyStartupParametersAll
bootToOpAsyncmaster, String primary, String secondaryCompletableFuture<Boolean>One-call startup: bind the NIC → enter EcState.OP → start the PDO cycle

Completion value semantics:

  • When master is null, setStateAsync / setNetworkAsync / bootToOpAsync return an already-completed false, and configureDCAllAsync / applyStartupParametersAsync return an already-completed -1.
  • The completion value of scanAsync / scanRedundantAsync is a return code: >= 0 is the number of slaves found (0 = an empty bus, which is a normal result), < 0 is the raw error code; when the scan call itself throws, the future completes with -1. A null or empty primary NIC name throws IllegalArgumentException.
  • The completion value of configureDCAllAsync equals the return value of master.configureDCAll(...): the number of DC stations that were applied and accepted (armed plus prepared in PRE_OP), not the number that were armed; < 0 means failure.
  • bootToOpAsync completes with false when any step fails; when master.start() throws (for example because the master has been released) the future completes exceptionally rather than swallowing the exception and still reporting true.
The success criterion of setNetworkAsync does not hold today

setNetworkAsync 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.bootToOpAsync or thenCompose
  • Scanning several NICs in parallel — MasterAsync.scanAsync + allOf
  • Spring/Reactor integration — the CompletableFuture returned by setStateAsync() is itself a CompletionStage
  • 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.

warning

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​

MethodParametersReturnsDescription
emergenciesSlave slaveStream<CoE.EmergencyMessage>All emergency messages (the CoE emergency history)
emergenciesByCodeslave, short errorCodeStream<CoE.EmergencyMessage>Emergency messages with an equal error code (CiA-301 error code, e.g. 0x8130 = SYNC error)
emergenciesByRegisterslave, byte registerMaskStream<CoE.EmergencyMessage>Emergency messages whose error register ANDed with the mask is not 0 (CiA-301 error register bit flags)
recentEmergenciesslave, int limitStream<CoE.EmergencyMessage>The first limit entries in reverse time order; limit <= 0 returns an empty Stream
emergencyCountslavelongTotal 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:

FieldTypeDescription
ErrorCodeshortError code
ErrorRegisterbyteError register
Databyte[]Additional data
SlaveIndexshortIndex of the originating slave
TimestamplongTimestamp

0x10F3 diagnostic stream​

MethodParametersReturnsDescription
diagnosticsSlave slaveStream<CoE.DiagnosticMessage>All 0x10F3 diagnostic messages
diagnosticsByCodeslave, int diagCodeStream<CoE.DiagnosticMessage>Filters by DiagCode being equal
diagnosticsBySeverityslave, short severityMaskStream<CoE.DiagnosticMessage>Filters by Flags ANDed with the mask being not 0
latestDiagnosticsslave, int limitStream<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).

Field names and contents do not match today

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 thread
  • attachStrict(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)
MethodParametersReturnsDescription
attachmaster, int capacityDiagnosticQueueCreates the queue and registers the callback; capacity <= 0 is treated as 1024; drops the oldest event when full
attachStrictmaster, int capacityDiagnosticQueueAs above, but blocks the event callback thread until space is available when full; capacity <= 0 is treated as 1024
takenoneEmergencyEventTakes one entry, blocking, with no timeout
polllong timeout, TimeUnit unitEmergencyEventTakes one entry with a timeout; returns null on timeout
pollNownoneEmergencyEventTakes one entry without blocking; returns null when the queue is empty
sizenoneintCurrent queue length
isStrictnonebooleanWhether strict mode is on (blocks the callback when full)
queuenoneBlockingQueue<EmergencyEvent>Exposes the raw queue, for drainTo / iterator and so on
closenonevoidUnregisters 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:

FieldTypeDescription
masterIndexshortMaster index
slaveIndexshortSlave index
errorCodeshortEmergency error code
errorRegbyteError register
b1 / w1 / w2byte / short / shortThe three additional parameters of the emergency frame
enqueueMslongEnqueue 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()
MethodParametersReturnsDescription
attachmaster, int capacitySlaveStateQueueCreates 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
takenoneStateChangeEventTakes one entry, blocking, with no timeout
polllong timeout, TimeUnit unitStateChangeEventTakes one entry with a timeout; returns null on timeout
pollNownoneStateChangeEventTakes one entry without blocking; returns null when the queue is empty
sizenoneintCurrent queue length
streamUntilClosednoneStream<StateChangeEvent>A blocking Stream that keeps taking until close(), suitable for forEach-style consumption
closenonevoidUnregisters 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:

FieldTypeDescription
masterIndexshortMaster index
slaveIndexshortSlave index
oldStateEcStateState before the change; EcState.NONE when it cannot be read
newStateEcStateState after the change; EcState.NONE when it cannot be read
enqueueMslongEnqueue time (System.currentTimeMillis())
streamUntilClosed must run on its own thread

This 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)
FieldAccessorTypeDescription
slaveNumslaveNum()int1-based slave index
vendorIdvendorId()longVendor ID (32-bit unsigned)
productIdproductId()longProduct ID (32-bit unsigned)
revisionIdrevisionId()longRevision number (32-bit unsigned)
serialNumberserialNumber()longSerial number (32-bit unsigned)
namename()StringSlave name (EEPROM); an empty string when it cannot be read
deviceNamedeviceName()StringDevice 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 Slave object directly (it has the master context)
  • Passing across threads — SlaveIdentity.snapshot(slave)
  • Caching / HashMap key — SlaveIdentity (the main Slave has no suitable equals)
  • Serialisation (JSON / DB) — SlaveIdentity has 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.

MethodParametersDefaultDescription
networkString primaryNicnoneDevice path of the primary NIC (\\Device\\NPF_{...}, or the NIC name on Linux); required
redundantString secondaryNicnoneRedundant standby NIC; optional
eniString pathnonePath of the ENI / DENI configuration file; it is only parsed at build() after being recorded
esiFileString pathnoneA single ESI file; repeated calls append one after another; null or an empty string is ignored
esiFolderString pathnoneAn ESI directory; every *.xml in it is loaded as well; null or an empty string is ignored
autoStartupnoneOffTurns on automatic application of the startup parameters
targetStateEcState stateNo switchSwitches the master to that state at the end of build()
startPdoAfterOpnoneOffStarts the PDO cycle after switching to the target state; only takes effect when targetState is EcState.OP or EcState.SAFE_OP
masterNumbershort indexAllocated automaticallySets 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:

ExceptionTriggered when
NullPointerExceptionbuild() is called without calling network(...) first
IllegalStateExceptionNIC 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.

The success criterion of build() does not hold today

build() 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:

caution

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​

SymptomCauseAction
MasterBuilder.build() throws IllegalStateException with the message setNetwork 失败 rc=<从站数>The current criterion treats the number of slaves found as a failure codeUse 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 fineThe same criterion issue as aboveJudge by the return value of master.setNetwork(...) yourself (>= 0 means success)
The slave streams and collection views are all emptyThe master is null, has been released, or no slaves have been scanned yetFinish building first and check that master.slaveCount() > 0
allInState stays falseThe network has no slaves (an empty network really is false), or some slave has not reached the target stateUse stateCounts / slavesNotInState to see which slaves have not arrived
The timeout version of setStateAsync completes with false, but the state reaches the target laterThe wait timed out while the state switch kept goingIncrease timeout and poll master.state() as a fallback
MasterScope.close() throwsOne 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 stopThe Stream is blocked waiting for an eventRun it on its own thread and interrupt that thread before shutting down
The network slows down after using attachStrictThe event callback is blocked when the queue is fullSwitch to attach, or raise capacity / consume faster
diagnosticsByCode / diagnosticsBySeverity filter the wrong entriesThe diagnostic message field names and contents do not line upParse RawData yourself and filter semantically
recentEmergencies(limit) returns fewer entriesThe history simply holds that manyTo 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.

ClassPurpose
MasterBuilderFluent master construction
MasterScopeExtended try-with-resources that releases sub-resources together
MasterStreamsSlave Stream / Optional / Map views
SlaveListExtSnapshots, sorting, counting and whole-network checks
SlaveIdentityImmutable slave identity
MasterAsyncCompletableFuture asynchronous wrappers
DiagnosticStreamStreams over the emergency history and the 0x10F3 diagnostic history
DiagnosticQueueTurns the emergency event callback into a BlockingQueue
SlaveStateQueueTurns state changes into a BlockingQueue / Stream
tip

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.