Events
All master-level events are subscribed through master.events().
All underlying callbacks are registered automatically when the first master instance is created; no manual calls are required.
Events marked O in the "Auto logging" column below are logged automatically by the Java event layer before delivery (whether or not they are subscribed), so these states are never lost silently; events marked -- are not logged by the Java event layer - write your own log entry in the callback if you need a trace.
The PDO cycle callback (ProcessDataCyclicSync) is a high-frequency callback and is not logged.
Feature overview
| Category | Registration method | R/W | Description | Auto logging |
|---|---|---|---|---|
| PDO cycle callback | addProcessDataCyclicSyncListener | Write-only | PDO cycle callback (synchronous; for same-cycle real-time control such as FSoE) | -- |
| State events | addStateChangedListener | Write-only | Master EtherCAT state change | -- |
| addSlaveStateChangedListener | Write-only | Slave EtherCAT state change | -- | |
| Hot-plug events | addSlaveOfflineListener | Write-only | Slave offline (disconnected) | O |
| addSlaveOfflineDetailedListener | Write-only | Slave offline with rich context (same tick as addSlaveOfflineListener; the payload carries time + reason + evidence) | O | |
| addSlaveOnlineListener | Write-only | Slave online (recovered) | O | |
| addSlaveOfflineDisputedListener | Write-only | Slave loss marking contradicts the delivery-time evidence (no offline event is delivered; this event is delivered instead) | O | |
| addSlaveIdentityMismatchListener | Write-only | Slave identity mismatch (wrong model swapped in; the revision number takes no part in the check) | -- | |
| Exception events | addEmergencyEventListener | Write-only | CoE Emergency message | -- |
| addPDOFrameLossListener | Write-only | Consecutive PDO frame loss (tracked independently per group) | -- | |
| addDCSyncLostListener | Write-only | DC synchronization lost | -- | |
| addSdoErrorListener | Write-only | SDO read/write failure (not fired on success) | O | |
| DC events | addDcEventRaisedListener | Write-only | Unified DC state event stream (arming / sync window / reference clock / propagation delay / hot-plug / convergence) | O |
| addDCSyncRestoredListener | Write-only | DC lock-loss recovery edge (same edge as the sync window recovery event; includes lock-loss duration) | O | |
| Diagnostic events | addWkcShortageOccurredListener | Write-only | Group WKC shortage (measured < expected, edge-triggered) | O |
| addNicLinkChangedListener | Write-only | Master NIC link up/down edge (primary / redundant) | O | |
| Redundancy events | addRedundancyModeChangedListener | Write-only | Redundancy mode change | -- |
| addSlavePortLinkChangedListener | Write-only | Slave port link change (P0-P3 down/recovered) | -- | |
| Clear subscriptions | clearAll() | Write-only | Clear all event subscriptions | -- |
The following logical events have no corresponding listener entry point in the Java SDK; this page does not invent APIs:
- Slave PreOp reconfiguration event:
MasterEventsdoes not expose this listener (the legacyEtherCATMasterregistration entry point belongs to another layer and is outside this event matrix). - Mailbox transaction error event: Java has no per-transaction terminal-state observability surface, so this listener has been removed from the SDK.
- Generic error / generic warning callbacks: not provided in Java.
- Placeholder slave re-read recovery event: not provided in Java.
The Java SDK uses the add/remove listener model and supports multiple listeners. The matching removal method is remove*Listener.
Registering the same listener object with add*Listener more than once registers it only once; one event is delivered to each subscriber exactly once (duplicate registration does not double-fire). Registering null throws NullPointerException.
Slave-level events (Emergency / SlaveOffline / SlaveOnline / DCSyncLost / SlavePortLinkChanged and so on) accept only valid slave indices 1..N. Internally, slave index 0 represents the master aggregate state; that value (and negative numbers) is never delivered to slave-level subscribers: Emergency / SlaveOffline / DCSyncLost / SlavePortLinkChanged are dropped and a DEBUG log entry is written; SlaveStateChanged is redirected to addStateChangedListener (the master aggregate channel) when slaveIndex < 1, without being dropped and without being delivered twice to slave-level subscribers. Master aggregate state changes are still authoritative through addStateChangedListener.
PDO cycle callback
PDO process data is exchanged by the real-time runtime. The recommended path is to map once after entering OP through inputsMapping / outputsMapping, so the Structure maps directly onto the process image (Java fields are cached: call read() for the latest values, and write() to change outputs). copyInputPdo / writeOutputPdo are snapshot alternatives. addProcessDataCyclicSyncListener is for application logic that must align with the cycle (including FSoE). This SDK does not provide an asynchronous cycle callback, addProcessDataCyclicAsyncListener.
addProcessDataCyclicSyncListener
master.events().addProcessDataCyclicSyncListener((masterIndex) -> {
// ...
});
Fires once per PDO cycle (synchronous mode). The callback runs directly on the real-time thread: latency is lowest, but the callback must return quickly.
Do not perform time-consuming work in the synchronous callback (such as SDO reads or writes, file I/O, or waiting on locks); it blocks the real-time thread and causes frame loss.
Callback parameters:
masterIndex(short) -- master index
The code below shows the PDO write only. 0x000F must only be held after the sequence 0x06→0x07→0x0F has completed and (statusWord & 0x6F) == 0x27; when not enabled / faulted / NotReady, write 0x0006 with target = actual. Do not write 0x001F in CSP; with multiple axes, issue per axis in the same callback. See CiA 402 for the complete state machine.
Example (direct mapping, zero-copy; mapping is done only once outside the callback):
PDO pdo = master.getSlave(1).PDO();
InPdo inputs = pdo.inputsMapping(InPdo.class);
OutPdo outputs = pdo.outputsMapping(OutPdo.class);
master.events().addProcessDataCyclicSyncListener((masterIndex) -> {
inputs.read();
outputs.controlWord = 0x000F;
outputs.targetPosition = inputs.actualPosition;
outputs.write();
});
Snapshot alternative (copy on every cycle; the copied byte[] does not change by itself):
master.events().addProcessDataCyclicSyncListener((masterIndex) -> {
PDO pdo = master.getSlave(1).PDO();
byte[] in = new byte[inBytes];
int[] copied = new int[1];
int[] required = new int[1];
pdo.copyInputPdo(in, copied, required);
byte[] out = new byte[outBytes];
int[] written = new int[1];
pdo.writeOutputPdo(out, written, required);
});
State events
addStateChangedListener
master.events().addStateChangedListener((oldState, newState) -> {
// ...
});
Fires when the master EtherCAT state changes (including commanded transitions and fault degradation).
Callback parameters:
oldState(EcState) -- state before the changenewState(EcState) -- state after the change
Example:
master.events().addStateChangedListener((oldState, newState) -> {
System.out.println("主站状态: " + oldState + " -> " + newState); // Master state: {oldState} -> {newState}
});
addSlaveStateChangedListener
master.events().addSlaveStateChangedListener((masterIndex, slaveIndex, oldState, newState) -> {
// ...
});
Fires when a slave EtherCAT state changes. An SDK background thread monitors the state and invokes the callback.
Callback parameters:
masterIndex(short) -- master indexslaveIndex(short) -- slave index (1-based)oldState(EcState) -- state before the changenewState(EcState) -- state after the change
Example:
master.events().addSlaveStateChangedListener((masterIndex, slaveIndex, oldState, newState) -> {
System.out.println("从站 " + slaveIndex + ": " + oldState + " -> " + newState); // Slave {slaveIndex}: {oldState} -> {newState}
Slave slave = master.getSlave(slaveIndex);
EtherCATTypes.EcALState errorCode = slave.errorCode();
if (errorCode != EtherCATTypes.EcALState.NO_ERROR) {
System.out.println(" 错误码: " + errorCode); // Error code: {errorCode}
}
});
slave.errorCode() reads the AL Status Code and returns the specific reason a state transition failed.
Hot-plug events
addSlaveOfflineListener
master.events().addSlaveOfflineListener((slaveIndex) -> {
// ...
});
Slave offline event. Fires when a hot-plug slave disconnects; the recovery state machine built into the PDO thread recovers the slave automatically.
Callback parameters:
slaveIndex(short) -- slave index
Example:
master.events().addSlaveOfflineListener((slaveIndex) -> {
System.out.println("从站 " + slaveIndex + " 离线"); // Slave {slaveIndex} offline
});
addSlaveOnlineListener
master.events().addSlaveOnlineListener((slaveIndex) -> {
// ...
});
Slave online event. Fires when a hot-plug slave recovers.
Callback parameters:
slaveIndex(short) -- slave index
Example:
master.events().addSlaveOnlineListener((slaveIndex) -> {
System.out.println("从站 " + slaveIndex + " 上线"); // Slave {slaveIndex} online
});
addSlaveOfflineDetailedListener
master.events().addSlaveOfflineDetailedListener((args) -> {
// ...
});
Slave offline listener with rich context, delivered on the same tick as addSlaveOfflineListener. The payload type is the same as for addSlaveOfflineDisputedListener (SlaveOfflineEventArgs), and the event name distinguishes the semantics: this listener is delivered only when offline has already been announced (real offline / unknown); when the evidence contradicts offline, only the contradiction listener is delivered.
Callback parameters (SlaveOfflineEventArgs):
masterIndex(short) -- master indexslaveIndex(short) -- slave index (1-based)timestampUtc(java.time.Instant) -- event time (UTC)reason(SlaveOfflineReason) -- offline reason categoryprobe(SlaveProbeState) -- slave response determination state at delivery timecontribution(EcatSlaveDiag.EcWcContributed) -- process data contribution at delivery time
master.events().addSlaveOfflineDetailedListener(args ->
System.out.printf("从站 %d 离线: 原因=%s 响应=%s PD贡献=%s%n", // Slave %d offline: reason=%s response=%s PD contribution=%s%n
args.slaveIndex, args.reason, args.probe, args.contribution));
Slave loss events and contradiction notices (SlaveOfflineDisputed)
When a slave is judged lost, the SDK reports the offline reason at delivery time together with the event; the classification result is SlaveOfflineReason.
Related structures:
public enum SlaveOfflineReason {
Unknown, // cannot be determined
RealOffline, // confirmed offline - process data not contributed
Unreachable // not confirmed - process data still contributing
}
SlaveProbeState is the three-state response determination at delivery time:
public enum SlaveProbeState {
NotResponding, // not responding
Responding, // responding
Unknown // cannot be determined
}
Process data contribution EcatSlaveDiag.EcWcContributed (this-cycle mirror): CONTRIBUTED = confirmed contributing WKC this cycle; NOT_CONTRIBUTED = confirmed not contributing; UNKNOWN = no conclusion yet.
- Process data confirmed still contributing -> no offline listener delivery;
addSlaveOfflineDisputedListeneris delivered instead - Process data confirmed not contributing ->
RealOffline - Contribution cannot be determined: no response ->
RealOffline, otherwise ->Unknown
When the slave loss marking contradicts the process data at delivery time (process data confirmed still contributing), the SDK does not deliver the offline listener registered through addSlaveOfflineListener; addSlaveOfflineDisputedListener is delivered instead. The event semantics and the payload stay consistent: it never says "offline" while carrying "process data still contributing".
master.events().addSlaveOfflineDisputedListener(e -> { ... });
Callback parameters (SlaveOfflineEventArgs):
masterIndex(short) -- master indexslaveIndex(short) -- slave index (1-based)timestampUtc(java.time.Instant) -- event time (UTC)reason(SlaveOfflineReason) -- offline reason categoryprobe(SlaveProbeState) -- slave response determination state at delivery timecontribution(EcatSlaveDiag.EcWcContributed) -- process data contribution at delivery time
Consumers use it to flag a "suspected transient interruption / slave loss marking inconsistent with the evidence"; do not use it to raise a red alarm or stop the line. Confirmed offline still goes through addSlaveOfflineListener.
Reason queries:
public SlaveOfflineReason tryGetSlaveOfflineReason(int slaveIndex)
public Map<Integer, SlaveOfflineReason> getSlaveOfflineReasons()
tryGetSlaveOfflineReason lets a UI that starts after the offline event, or that re-subscribes midway, fetch the reason category (returns null when unavailable); getSlaveOfflineReasons fetches all reasons at once. The semantics of isSlaveOffline and of the slave loss counters are unchanged.
Example:
master.events().addSlaveOfflineDisputedListener(e -> {
System.out.printf("从站 %d 掉站标记与证据不符: 原因=%s%n", // Slave %d slave-loss flag does not match the evidence: reason=%s%n
e.slaveIndex, e.reason);
// Only flag a "suspected transient interruption"; do not raise a red alarm or stop the line
});
SlaveOfflineReason reason = master.events().tryGetSlaveOfflineReason(2);
if (reason == SlaveOfflineReason.RealOffline) {
System.out.println("从站 2 确证离线"); // Slave 2 confirmed offline
}
isSlaveOffline
public boolean isSlaveOffline(int slaveIndex)
Queries whether the slave has been confirmed offline by the event system.
Parameters:
slaveIndex(int) -- slave index
Returns:
boolean--trueif the slave is offline
getOfflineSlaves
public Set<Integer> getOfflineSlaves()
Returns the set of all offline slave indices (read-only copy).
Example:
if (master.events().isSlaveOffline(2)) {
System.out.println("从站 2 处于离线状态"); // Slave 2 is offline
}
Set<Integer> offlines = master.events().getOfflineSlaves();
System.out.println("离线从站: " + offlines); // Offline slaves: {offlines}
addSlaveIdentityMismatchListener
master.events().addSlaveIdentityMismatchListener((args) -> {
// ...
});
Fires when a slave is power-cycled and reinserted with a mismatched identity: the Vendor/Product read by the identity check do not match the configuration. In the current version the identity check only looks at Vendor + Product — the revision number (Revision) does not take part in rejection. MasterConfig.scanRevisionMatch() is always IGNORE_REVISION; EXACT (exact revision match) and COMPATIBLE_HIGHER (scanned revision number ≥ the configured value) are declared values of MasterConfig.RevisionMatch, but the current version offers no entry point that sets them and doing so throws UnsupportedOperationException. The Java event layer does not log before delivery; write your own log entry in the callback if you need a trace.
After firing, the slave enters the IDENT_REJECTED state and is not re-probed automatically (to prevent a wrong device from flooding the log). After the operator checks or replaces the device, call master.acknowledgeSlaveReplacement so the SDK probes again.
Callback parameters (SlaveIdentityMismatchEventArgs):
masterIndex(int) -- master indexslaveIndex(int) -- slave index (1-based)expectedVendor(long) -- vendor ID expected by the configuration (unsigned 32-bit)expectedProduct(long) -- product code expected by the configuration (unsigned 32-bit)expectedRevision(long) -- revision number expected by the configuration (unsigned 32-bit; for reference only, not part of the identity check)actualVendor(long) -- current actual vendor ID (unsigned 32-bit)actualProduct(long) -- current actual product code (unsigned 32-bit)actualRevision(long) -- current actual revision (unsigned 32-bit)
The Java language has no unsigned int type; the SDK carries the C uint32 in a long to avoid negative values. Use %08X or Long.toHexString when formatting for output.
Example:
master.events().addSlaveIdentityMismatchListener((args) -> {
System.out.printf("从站 %d 身份不符:%n", args.slaveIndex); // Slave %d identity mismatch:%n
System.out.printf(" 期望: Vendor=0x%08X, Product=0x%08X, Rev=0x%08X%n", // Expected: Vendor=0x%08X, Product=0x%08X, Rev=0x%08X%n
args.expectedVendor, args.expectedProduct, args.expectedRevision);
System.out.printf(" 实际: Vendor=0x%08X, Product=0x%08X, Rev=0x%08X%n", // Actual: Vendor=0x%08X, Product=0x%08X, Rev=0x%08X%n
args.actualVendor, args.actualProduct, args.actualRevision);
// Show a UI dialog asking the user to swap back the correct device; after confirmation call master.acknowledgeSlaveReplacement(args.slaveIndex)
});
A slave entering the IDENT_REJECTED state fires the event only once. Calling acknowledgeSlaveReplacement resets the probe, and a still-mismatched identity fires it again.
Exception events
The cycle is set by DENI/LoopCycle with a minimum of 125 µs; it is not hard-coded to 1ms. diagnostics().getRTcnt() should align with 1e9/LoopCycleNs. If the cycle deviates from the setting by ±20% continuously, or max jitter exceeds 25% of the cycle, you must write a log entry and raise a UI alarm. Also check PDOFrameLoss and DCSyncLost. Without effective isolation only jitter may grow; it is not acceptable to let the cycle drift without reporting it. Do not do alarm I/O on the PDO hot path.
addEmergencyEventListener
master.events().addEmergencyEventListener(
(masterIndex, slaveIndex, errorCode, errorReg, b1, w1, w2) -> {
// ...
});
CoE Emergency message event. Sent by the slave firmware when it detects an error; the data format follows the CANopen Emergency protocol (CiA 301).
Callback parameters:
masterIndex(short) -- master indexslaveIndex(short) -- slave index (1-based)errorCode(short) -- error code (CANopen Emergency Error Code, object 0x603F)errorReg(short) -- error register (object 0x1001)b1(byte) -- manufacturer-specific data (byte 3)w1(short) -- manufacturer-specific data (bytes 4-5)w2(short) -- manufacturer-specific data (bytes 6-7)
addErrorListener / removeErrorListener are convenience aliases for addEmergencyEventListener / removeEmergencyEventListener; the listener interface and the payload are identical.
Common Emergency Error Codes:
0x0000-- error reset0x1000-- generic error0x2000-- current error0x3000-- voltage error0x4000-- temperature error0x5000-- device hardware error0x7000-- additional module error0x8000-- monitoring error (communication)
Example:
master.events().addEmergencyEventListener(
(masterIndex, slaveIndex, errorCode, errorReg, b1, w1, w2) -> {
System.out.printf("从站 %d 紧急消息: 错误码=0x%04X, 寄存器=0x%02X%n", // Slave %d emergency message: error code=0x%04X, register=0x%02X%n
slaveIndex, errorCode, errorReg);
});
addPDOFrameLossListener
master.events().addPDOFrameLossListener(
(masterIndex, group, consecutiveLostCount, totalLostCount) -> {
// ...
});
Consecutive PDO frame loss event. Fires when consecutive lost frames reach the threshold; a single lost frame is only counted, not fired. Each group is tracked independently.
Callback parameters:
masterIndex(short) -- master indexgroup(byte) -- group number where the frame loss occurred (0-7), corresponding to slave groupingconsecutiveLostCount(int) -- consecutive lost frames for this grouptotalLostCount(int) -- cumulative lost frames for this group
Example:
master.events().addPDOFrameLossListener(
(masterIndex, group, consecutiveLostCount, totalLostCount) -> {
System.out.printf("组 %d 丢帧: 连续=%d, 累计=%d%n", // Group %d frame loss: consecutive=%d, cumulative=%d%n
group, consecutiveLostCount, totalLostCount);
});
addDCSyncLostListener
master.events().addDCSyncLostListener((masterIndex, slaveIndex, diffNs) -> {
// ...
});
DC synchronization loss event. Fires once when a slave goes from synchronized to unsynchronized (beyond the threshold); continuing to exceed the threshold does not fire it again.
Callback parameters:
masterIndex(short) -- master indexslaveIndex(short) -- index of the slave that lost synchronization (1-based)diffNs(int) -- current time difference from the reference clock (nanoseconds)
Example:
master.diagnostics().setSyncWindowThreshold(500); // 500ns
master.events().addDCSyncLostListener((masterIndex, slaveIndex, diffNs) -> {
System.out.println("从站 " + slaveIndex + " DC 同步丢失: 偏差 " + diffNs + "ns"); // Slave {slaveIdx} DC sync lost: deviation {diffNs}ns
});
Java can use a BlockingQueue<EmergencyEvent> to turn event callbacks such as EMCY / state changes into a thread-safe queue, moving slow consumption (database writes / MQ publishing) off the PDO thread so the real-time cycle is not blocked.
addSdoErrorListener
master.events().addSdoErrorListener((args) -> {
// ...
});
Fires when an SDO read/write fails: WKC=0 with no response, a slave Abort, and a timeout all count as failures; success does not fire it.
The data source is the failure report from CoE.sdoRead / CoE.sdoWrite: it is reported once after each failed call, before returning. The read path also reports when it hits a locally known failure cache (such as a nonexistent object); the cache holds the Abort Code from that time, so it is reported even though no bus traffic was sent. On the write path, passing null / an empty array is an immediate local failure and goes through the same exit.
Callback parameters (SdoErrorEventArgs):
slaveIndex(int) -- slave index (1-based)index(int) -- object index that failed (already normalized with& 0xFFFFat construction)subIndex(int) -- object subindex that failed (already normalized with& 0xFF)isWrite(boolean) --true= write failure,false= read failureerror(SDOError) -- error enum mapped from the Abort Code; transport-level failures withabortCode0 are normalized toSDOError.SDO_PROTOCOL_TIMEOUT, and codes outside the enum table areSDOError.UNKNOWN_ERRORabortCode(long) -- raw Abort Code (unsigned 32-bit, carried in along, already normalized with& 0xFFFFFFFFL);0means it is not an Abort-type failure (WKC=0 / timeout). Note: the two local / transport failure exits - the read path WKC<=0 and "empty data write" - put the SDK-normalized code0x05040000(SDO_PROTOCOL_TIMEOUT) intoabortCode; it is non-zero then but is not an Abort sent by the slave, so checkerrorwhen you need to distinguish.timestampUtc(java.time.Instant) -- the time the SDK produced this event (UTC), not the time the slave sent the Abort
Triggering and deduplication: each failed public SDO call delivers exactly once; there is no cross-call deduplication - repeated failures on the same object are reported every time. When the master is unregistered / closed, the report is dropped silently (this is not an error).
Thread: the callback runs synchronously on the thread that initiated this SDO call (inside that sdoRead / sdoWrite return path), not on an underlying callback thread and not on the PDO worker. Callback time adds directly to this SDO call.
The Java SDK has no listener entry point named MailboxError: the Java side has no per-transaction terminal-state observability surface (mailbox protocol classes only record getLastErrorCode() and statistics on their own instances, so an observable event cannot be guaranteed exactly once per "transaction"). This listener has been removed from the SDK to avoid leaving a fake event that never fires.
Alternative: for SDO-level failures subscribe to addSdoErrorListener; for mailbox protocol instance-level errors, check getLastErrorCode() of the corresponding protocol (CoE / FoE / SoE / AoE / EoE / VoE / FSoE).
reportSdoError(short masterIndex, int slaveIndex, int index, int subIndex, boolean isWrite, long abortCode)
public static void reportSdoError(short masterIndex, int slaveIndex, int index, int subIndex,
boolean isWrite, long abortCode)
The reporting exit point for SDO read/write failures. Called by the protocol layer on the failure path of CoE.sdoRead / CoE.sdoWrite to deliver the failure to subscribers of addSdoErrorListener. Application code does not need to call this method; subscribing to the listener is enough.
Parameters:
masterIndex(short) -- master indexslaveIndex(int) -- slave index (1-based)index(int) -- object index that failed (normalized with& 0xFFFFbefore delivery)subIndex(int) -- object subindex that failed (normalized with& 0xFFbefore delivery)isWrite(boolean) --true= write failure,false= read failureabortCode(long) -- raw Abort Code (normalized as unsigned 32-bit);0= a non-Abort failure (no response / timeout)
Returns: none
Behaviour:
- Does not throw: a fault in the event layer never changes or masks the semantics of the SDO failure.
- When the master index cannot be resolved (unregistered / closed), the report is dropped silently and is not counted as an error.
- The payload semantics are exactly the same as
addSdoErrorListener: transport-level failures withabortCode0 are normalized toSDOError.SDO_PROTOCOL_TIMEOUT, and codes outside the enum table are normalized toSDOError.UNKNOWN_ERROR.
Typical usage: do not call it directly; subscribe instead -
master.events().addSdoErrorListener((args) ->
System.out.printf("SDO %s失败 从站%d 0x%04X:%02X abort=0x%08X%n", // SDO %s failed, slave %d 0x%04X:%02X abort=0x%08X%n
args.isWrite ? "写" : "读", args.slaveIndex,
args.index, args.subIndex, args.abortCode));
DC state events (arming / sync window / reference clock / propagation delay / hot-plug / convergence)
DC arming, entering and leaving the window, reference clock switching / freezing, propagation delay remeasurement / reuse / invalidation, hot-plug recovery and slow convergence all enter a unified event stream; there is no need to dig through logs and guess. The consumption channel can be the underlying log callback:
master.setLogCallback((level, message) -> {
// DC state events arrive through the log callback; message contains the event description and payload
System.out.println("[" + level + "] " + message);
});
addDCSyncLostListener stays unchanged and the two do not replace each other: the latter is responsible only for the strongly typed "synchronized -> unsynchronized" subscription; this channel covers DC state changes across the whole lifecycle. For a strongly typed callback keep using addDCSyncLostListener; for the complete event stream use the log callback.
The same event surface has two more strongly typed channels: addDcEventRaisedListener (all DC state events) and addDCSyncRestoredListener (recovery edge only). The three channels do not replace each other and can be subscribed at the same time.
| Category | Event | Level | Trigger and debounce | Key payload | R/W |
|---|---|---|---|---|---|
| DC events | Arming success | Message | Fires only when the published arming mask changes; the same mask does not repeat | Written / read-back 0x0980, 0x09A0, ESI preset, required mask, evidence strength | Read-only |
| DC events | Arming failure / rollback | Warning | Always fires the first time; while it keeps failing, at most one per 10 seconds | Reason, whether rolled back, AL state / code, write WKC, read-back 0x0980 | Read-only |
| DC events | No SYNC0 cycle unit | Message | Once per (master, slave) | Evidence of three consecutive attempts with no response to 0x0980 | Read-only |
| DC events | Sync window exceeded | Warning | Reports once on entry; while it persists, at most one per 10 seconds | Current difference, threshold, elapsed duration, cycle count | Read-only |
| DC events | Sync window recovered | Message | Reports once per recovery (pairs with sync window exceeded) | Current difference, threshold | Read-only |
| DC events | Reference clock established / switched / lost | Message; Warning with warning=1 | One entry per switch, minimum interval 1 second | Old / new reference clock, preset, reason | Read-only |
| DC events | Reference clock frozen | Warning | At most one per slave per 60 seconds | 1:1 ramp slope (ppm), reason | Read-only |
| DC events | Propagation delay remeasured | Message | Minimum interval 1 second | Reason, slave count, maximum pdelay on the whole bus, session generation | Read-only |
| DC events | Propagation delay reused | Debug | Minimum interval 10 seconds; the same generation does not repeat | Reason, slave count, maximum pdelay, generation | Read-only |
| DC events | Propagation delay baseline invalidated | Message | Minimum interval 1 second | Reason; the next update must remeasure the whole bus | Read-only |
| DC events | Recovery after hot-plug | Message; Warning with warning=1 | Minimum interval 2 seconds per slave | Arming result, 0x0980 read-back, AL state / code, pdelay | Read-only |
| DC events | Slow convergence (over 5 seconds) | Warning | At most one per episode per 60 seconds; hard lower bound of 5 seconds between any two entries | Elapsed duration, cycle count, difference | Read-only |
| DC events | Convergence severely overdue (over 30 seconds) | Error | Same as slow convergence | Elapsed duration, cycle count, difference | Read-only |
The events themselves are read-only consumption; setLogCallback(...), which registers a consumption channel, counts as a write (registration): it only affects callback attachment and does not change event content.
Semantics:
- Level mapping:
Message= Info;Warning= warning;Error= severe (convergence over 30 seconds);Debug= reuse-type details, not output in Release builds. - Debounce is claimed independently per (master, slave) slot; reference clock and propagation delay events are rate-limited separately, and sharing one timestamp would make them suppress each other. Convergence events are gated per episode.
- Master-level events (reference clock / propagation delay) use the slave index 0 slot and do not take space from slave-level events; a slave-level event delivered with slave index 0 by mistake is rejected and only leaves a Debug trace.
- This channel is read-only consumption with very low cost (low-frequency table lookup + formatting) and does not affect the real-time cycle.
addDcEventRaisedListener
master.events().addDcEventRaisedListener((args) -> {
// ...
});
DC state event unified stream: covers arming success / arming failure rollback, no SYNC0 unit, window exceeded / recovered, reference clock switching / freezing, propagation delay remeasurement / reuse / invalidation, hot-plug recovery, slow convergence / severe timeout. It and the log channel do not replace each other; both can be subscribed, and each channel delivers independently.
Trigger conditions:
- Delivers once per DC state event produced; the emitting side has already debounced and rate-limited by event type (see "Trigger and debounce" in the table above), so the SDK side does not debounce again.
- For a sync window recovery event, this event is delivered first within the same dispatch round, then
addDCSyncRestoredListener. - If no matching master is found (closed / unregistered), it is skipped silently.
A custom log callback takes over log output; in that case use the DC event API directly.
Callback parameters (DcEventArgs):
masterIndex(int) -- master index;0when unknownslaveIndex(int) -- slave index (1-based); always0for master-level events (reference clock / propagation delay)code(DcEventCode) -- event type enum (members are frozen and values must not be reordered;getValue()returns the raw numeric value). Enum member names are the event names:ArmSuccess(1) /ArmFailed(2) /NoSync0Unit(3) /WindowExceeded(4) /WindowRecovered(5) /RefClockSwitch(6) /RefClockFrozen(7) /PdelayRemeasured(8) /PdelayReused(9) /PdelayInvalidated(10) /HotplugRecovered(11) /ConvergenceSlow(12) /ConvergenceSevere(13)params(String) -- raw event parameter text (not parsed, not trimmed;nullis normalized to an empty string)timestampUtc(java.time.Instant) -- the time the SDK produced this event (UTC), not the time the bus event occurred
Thread: runs synchronously on the underlying log callback thread. Implementations must return quickly and must not write to LogManager from the callback (it re-enters the log dispatch chain). The automatic log level reflects the event type faithfully: severe convergence timeout is logged as Error; arming failure / window exceeded / reference clock frozen / slow convergence as Warning; the rest as Message.
addDCSyncRestoredListener
master.events().addDCSyncRestoredListener((args) -> {
// ...
});
DC lock-loss recovery edge: a slave recovers from unsynchronized back into the sync window. It is on the same edge as the sync window recovery event - within the same dispatch round, addDcEventRaisedListener is delivered first, then this event.
Trigger conditions:
- Delivered only for sync window recovery events; other DC state events are not delivered.
- Not delivered when
slaveIndex < 1(including the master-level slot 0 and events that carry no slave index); only one DEBUG log entry is left - valid slave indices are always 1..N. - When the event carries no lock-loss duration it is still delivered, with
lostDurationset toDuration.ZERO(honestly meaning "no duration provided", not invented).
Callback parameters (DCSyncRestoredEventArgs):
masterIndex(int) -- master indexslaveIndex(int) -- index of the recovered slave (1-based)timestampUtc(java.time.Instant) -- the time the SDK produced this event (UTC)lostDuration(java.time.Duration) -- lock-loss duration (constructed from microseconds converted to nanoseconds); zero when the event carries no duration, andnullis normalized toDuration.ZERO
Thread: same thread as addDcEventRaisedListener (the underlying log callback thread); it runs immediately after the unified stream within the same dispatch round.
Diagnostic events
Diagnostic events are produced by the SDK diagnostic polling thread: background polling starts on the first WKC / NIC subscription (one per master) and samples diagnostic data once per second; it stops when the last subscription is removed, on clearAll(), or when the master closes. No subscriptions = no thread and no cost (likewise no thread is created when there is no master object).
Polling does not read the PDO hot path and does not occupy the PDO worker: a slow callback only delays the next sampling instant and does not affect the bus cycle.
addWkcShortageOccurredListener
master.events().addWkcShortageOccurredListener((args) -> {
// ...
});
Group WKC shortage: delivered when the measured WKC of a group is less than the expected WKC (a mapped slave in that group is not contributing). The first subscription starts 1-second edge polling.
Triggering and edges (groups 0-7 are judged independently):
- Reads the expected and the measured WKC of the group; both are normalized with
& 0xFFFF. - Unused groups with an expected value of 0 are skipped: nothing is delivered and the group baseline is not updated.
- The criterion is
actualWkc < expectedWkc(strictly less; equal does not count as a shortage). - Entering a shortage (previously not short, or no baseline) delivers once; if either
actualWkcorexpectedWkcchanges during the shortage, it delivers again. - The shortage persists with both values unchanged -> no repeat (no flooding).
- Recovery (
actualWkc >= expectedWkc) only updates the baseline and does not deliver a "recovered" event; entering the shortage again delivers anew. - On a read failure (capability unavailable / master not ready), that group warns once and is skipped for this round; other groups keep sampling.
Callback parameters (WkcShortageEventArgs):
masterIndex(int) -- master indexgroup(int) -- group number (0-7)actualWkc(int) -- measured WKC of the group (unsigned 16-bit, normalized with& 0xFFFFat construction; callers never see negative values)expectedWkc(int) -- expected WKC of the group (a fixed true value determined at configuration time, also normalized with& 0xFFFF; never lowered because of a shortage)timestampUtc(java.time.Instant) -- the time polling detected this edge (UTC)
Thread: runs on the diagnostic polling daemon thread, not on the PDO cycle thread. Polling decisions run serially (re-subscribing on a different thread does not cause concurrent decisions), and a slow callback only delays the next sample.
expectedWkc comes from the group expected value determined at configuration time; the SDK only reports the gap honestly - it does not modify the expectation and does not bend it to the measurement. After slaves recover, actualWkc rises naturally and the shortage events stop.
addNicLinkChangedListener
master.events().addNicLinkChangedListener((args) -> {
// ...
});
Master NIC link up/down edge: the primary port (primary) and the redundancy port (redundant) judge edges independently. The first subscription starts 1-second edge polling (sharing the same diagnostic polling thread as WKC).
Triggering and edges:
- Reads the primary / secondary port link status; value semantics:
0=DOWN,1=UP, any other value = UNKNOWN (insufficient evidence). - The first observation only establishes a baseline and delivers nothing; after that only a status flip delivers (UP->DOWN or DOWN->UP). The link leg is distinguished by
primary/redundant. - UNKNOWN delivers nothing and does not update the baseline - an unreadable value is never written as down.
- On a read failure (capability unavailable / that leg unavailable), each leg warns once and is skipped for this round.
- No sampling while there are no subscribers.
Callback parameters (NicLinkChangedEventArgs):
masterIndex(int) -- master indexadapterName(String) -- NIC name from the master configuration (primaryNicName()/redundantNicName()); empty string when not configured (for example, configured through the ENI only, without callingsetNetwork);nullis normalized to an empty string. This field is not a link leg identifier.mac(String) -- always an empty string: the Java SDK has no MAC query surface that avoids an external process; it is left empty honestly, not inventedisUp(boolean) --true= link up (recovered),false= link down (disconnected)timestampUtc(java.time.Instant) -- the time polling detected this edge (UTC)
Thread: same diagnostic polling daemon thread as addWkcShortageOccurredListener.
Input data changes (removed)
The addInputDataChangedListener input data change event has been removed. It previously detected changes by comparing the input PDO every cycle in the underlying layer.
How to detect input changes: call copyInputPdo yourself (or take a SlavePdo.inputs() snapshot) and compare it with the previous cycle.
byte[] prev = null;
while (running) {
PDO pdo = master.getSlave(1).PDO();
int[] copied = new int[1];
int[] required = new int[1];
pdo.copyInputPdo(null, copied, required);
byte[] cur = new byte[required[0]];
if (pdo.copyInputPdo(cur, copied, required) == PDO.PdoIoStatus.Success
&& prev != null && !java.util.Arrays.equals(prev, cur)) {
// input changed
}
prev = cur;
Thread.sleep(1);
}
Redundancy events
addRedundancyModeChangedListener
master.events().addRedundancyModeChangedListener((masterIndex, oldMode, newMode) -> {
// ...
});
Fires when the redundancy operating mode changes. oldMode / newMode correspond to RingMode values (0=Inactive, 1=Dual, 2=Degraded).
Callback parameters:
masterIndex(short) -- master indexoldMode(int) -- redundancy mode before the changenewMode(int) -- redundancy mode after the change
Example:
master.events().addRedundancyModeChangedListener((masterIndex, oldMode, newMode) -> {
System.out.println("冗余模式: " + oldMode + " -> " + newMode); // Redundancy mode: {diag.getRingMode()}
});
addSlavePortLinkChangedListener
master.events().addSlavePortLinkChangedListener((masterIndex, slaveIndex, port, isUp) -> {
// ...
});
Fires when the physical link of a slave ESC port changes (one of P0-P3 down or recovered). The 1-second diagnostic cycle checks the link bit of the DL Status register; 1->0 fires "down" and 0->1 fires "recovered". The Java event layer does not log before delivery; write your own log entry in the callback if you need a trace.
Use it to pinpoint the faulty cable segment (if the facing ports of adjacent slaves report down at the same time, the cable between them is the problem).
Callback parameters:
masterIndex(short) -- master indexslaveIndex(short) -- slave index (1-based)port(byte) -- port number0-3, corresponding toP0/P1/P2/P3isUp(boolean) --true= link recovered,false= link down
Example:
master.events().addSlavePortLinkChangedListener((masterIndex, slaveIndex, port, isUp) -> {
String state = isUp ? "恢复" : "断开"; // restored / disconnected
System.out.printf("从站 %d 端口 P%d link %s%n", slaveIndex, port, state); // Slave %d port P%d link %s%n
});
master.diagnostics().getAllBreakPoints() provides an aggregated view of fault points (broken line + CRC faults). SlavePortLinkChanged is the raw event source and suits real-time alarms.
Clear all subscriptions
clearAll()
public void clearAll()
Clears all event subscriptions to prevent memory leaks. Call it before destroying or re-initializing the master. It also clears the offline slave tracking state.
Example:
// cleanup before destroying
master.events().clearAll();
master.close();
// slave-level events also support ClearAll
slave.events().clearAll();
SlaveEvents also provides a clearAll() method that clears all slave-level event subscriptions.
removeXxxListener(...)
Besides clearAll(), every add*Listener has a same-signature remove*Listener unregistration entry point that removes by the same listener reference:
removeProcessDataCyclicSyncListener / removeStateChangedListener / removeSlaveStateChangedListener / removeEmergencyEventListener (alias removeErrorListener) / removeSlaveOfflineListener / removeSlaveOfflineDetailedListener / removeSlaveOfflineDisputedListener / removeSlaveOnlineListener / removeSlaveIdentityMismatchListener / removePDOFrameLossListener / removeDCSyncLostListener / removeSdoErrorListener / removeDcEventRaisedListener / removeDCSyncRestoredListener / removeWkcShortageOccurredListener / removeNicLinkChangedListener / removeRedundancyModeChangedListener / removeSlavePortLinkChangedListener.
MasterEvents events = master.events();
MasterEvents.SlaveOfflineListener onOffline = idx -> System.out.println("从站 " + idx + " 离线"); // Slave {slaveIndex} offline
events.addSlaveOfflineListener(onOffline);
// unregister by the same reference when no longer needed
events.removeSlaveOfflineListener(onOffline);
Unregistering removes only that subscription and does not affect other subscribers; calling it after the master has been released is a valid cleanup (it only clears Java-side references and makes no calls into the underlying layer).
Callback lifecycle
| Category | Method | Type/return | R/W | Description |
|---|---|---|---|---|
| Callback lifecycle | initializeCallbacks() | void | Call | Registers all event callbacks (idempotent; already called automatically when the master is created) |
| shutdownCallbacks() | void | Call | Unregisters all event callbacks (pairs with initializeCallbacks) |
initializeCallbacks()
public static void initializeCallbacks()
Registers all event callbacks for this process. Idempotent: repeated calls register only once; it has already been called automatically when the first master instance is created in the process, so normal application code does not need to call it manually.
Returns: none
Example (only needed when you control the startup order yourself):
MasterEvents.initializeCallbacks(); // Idempotent, repeated calls do not register twice
shutdownCallbacks()
public static void shutdownCallbacks()
Unregisters all event callbacks registered by initializeCallbacks(); the two are a pair. When masters are created / released repeatedly within a process, call it after the last master is released to avoid accumulation of registered resources.
- Idempotent: calling it when nothing has been registered is a no-op.
- Unregisters one by one; a single failed unregistration does not block the rest (when the corresponding capability is missing it is treated as a no-op), and no exception is propagated.
- Only unregisters the callbacks that
initializeCallbacks()actually registered; callbacks that were not registered are never touched.
Returns: none
Example:
master.close();
MasterEvents.shutdownCallbacks(); // Finish up when no more masters will be created in this process
Thread safety
Event callbacks fire on non-UI threads. With Swing/JavaFX, update the UI by marshalling back to the UI thread:
// Swing
master.events().addSlaveOfflineListener((idx) ->
SwingUtilities.invokeLater(() ->
labelStatus.setText("从站 " + idx + " 离线"))); // Slave {slaveIndex} offline
// JavaFX
master.events().addSlaveOfflineListener((idx) ->
Platform.runLater(() ->
statusLabel.setText("从站 " + idx + " 离线"))); // Slave {slaveIndex} offline
Synchronization semantics:
- Listeners are held in a
CopyOnWriteArrayList: registration / unregistration can run concurrently with event delivery, iteration takes a snapshot, andConcurrentModificationExceptionis never thrown. - Registering the same listener object with
add*Listenerrepeatedly registers it only once; one event is delivered to each subscriber exactly once (duplicate registration does not double-fire).contains+addis not atomic, so under concurrent registration races the same object may at worst be registered twice; registration happens during application startup, not on the event hot path. - Registering
nullthrowsNullPointerException; registering after the master has been released (closing / closed) throwsIllegalStateException. - Callbacks run synchronously on the event dispatch thread; the SDK does not dispatch through a thread pool: SDO failures run on the thread that initiated that
sdoRead/sdoWrite; the DC unified stream / recovery edge runs on the thread that writes logs (usually the underlying log callback thread); WKC shortage / NIC link run on the diagnostic polling daemon thread. None of them is a UI thread. - Do not perform blocking operations in callbacks (SDO reads or writes, file I/O, waiting on locks, long sleeps). Occupying the event thread delays subsequent events; occupying the DC log thread slows the log path.
- Per-subscriber isolation: an exception thrown by one listener does not affect other listeners of the same event and does not change the event semantics. Counting and rate-limited logging cover only some events:
SlaveOfflineDetailed/SdoError/DcEventRaised/DCSyncRestored/WkcShortageOccurred/NicLinkChangedgo through the unified dispatch, and exceptions are logged and counted (rate-limited per event name to one per 60 seconds; the counts are not affected by the rate limit and can be read withMasterEvents.getSubscriberFailureTotal()/MasterEvents.getSubscriberFailureCounts()); for the remaining events (StateChanged/SlaveStateChanged/Emergency/SlaveOffline/SlaveOnline/SlaveOfflineDisputed/PDOFrameLoss/DCSyncLost/RedundancyModeChanged/SlaveIdentityMismatch/SlavePortLinkChanged), subscriber exceptions are swallowed silently - not counted and not logged. clearAll()clears all subscriptions, stops diagnostic polling and clears the WKC / NIC edge baselines; re-subscribing starts from a fresh baseline and old edges are not replayed.
Full example
MasterEvents events = master.events();
// ===== Master state =====
events.addStateChangedListener((oldState, newState) ->
System.out.println("主站: " + oldState + " -> " + newState)); // Master: {oldState} -> {newState}
// ===== Slave state =====
events.addSlaveStateChangedListener((mi, si, os, ns) -> {
System.out.println("从站 " + si + ": " + os + " -> " + ns); // Slave {slaveIndex}: {oldState} -> {newState}
Slave slave = master.getSlave(si);
EtherCATTypes.EcALState errorCode = slave.errorCode();
if (errorCode != EtherCATTypes.EcALState.NO_ERROR) {
System.out.println(" 错误码: " + errorCode); // Error code: {errorCode}
}
});
// ===== Hot-plug =====
events.addSlaveOfflineListener((si) ->
System.out.println("从站 " + si + " 离线")); // Slave {slaveIndex} offline
events.addSlaveOnlineListener((si) ->
System.out.println("从站 " + si + " 上线")); // Slave {slaveIndex} online
// ===== Exception events =====
events.addEmergencyEventListener((mi, si, ec, er, b, w1, w2) ->
System.out.printf("从站 %d 紧急消息: 0x%04X%n", si, ec)); // Slave %d emergency message: 0x%04X%n
events.addPDOFrameLossListener((mi, g, c, t) ->
System.out.printf("组 %d 丢帧: 连续=%d, 累计=%d%n", g, c, t)); // Group %d frame loss: consecutive=%d, cumulative=%d%n
events.addDCSyncLostListener((mi, si, d) ->
System.out.println("从站 " + si + " DC 同步丢失: " + d + "ns")); // Slave {si} DC sync lost: {d}ns
// ===== Redundancy events =====
events.addRedundancyModeChangedListener((mi, om, nm) ->
System.out.println("冗余模式变化: " + om + " -> " + nm)); // Redundancy mode change: {om} -> {nm}
events.addSlavePortLinkChangedListener((mi, si, port, isUp) ->
System.out.printf("从站 %d P%d link %s%n", si, port, isUp ? "恢复" : "断开")); // Slave %d P%d link %s%n (restored / disconnected)
// ===== Hot-plug identity mismatch =====
events.addSlaveIdentityMismatchListener((args) ->
System.out.printf("从站 %d 身份不符, 换设备后调用 acknowledgeSlaveReplacement(%d)%n", // Slave %d identity mismatch, call acknowledgeSlaveReplacement(%d) after replacing the device%n
args.slaveIndex, args.slaveIndex));
// ===== Diagnostic events =====
events.addSdoErrorListener((args) ->
System.out.printf("SDO %s失败 从站%d 0x%04X:%02X abort=0x%08X %s%n", // SDO %s failed, slave %d 0x%04X:%02X abort=0x%08X %s%n
args.isWrite ? "写" : "读", args.slaveIndex,
args.index, args.subIndex, args.abortCode, args.error));
events.addDcEventRaisedListener((args) ->
System.out.printf("DC 事件 %d 从站 %d: %s%n", // DC event %d slave %d: %s%n
args.code.getValue(), args.slaveIndex, args.params));
events.addDCSyncRestoredListener((args) ->
System.out.printf("从站 %d DC 同步恢复, 失锁 %d ms%n", // Slave %d DC sync restored, lock lost for %d ms%n
args.slaveIndex, args.lostDuration.toMillis()));
events.addWkcShortageOccurredListener((args) ->
System.out.printf("组 %d WKC 短缺: 实测=%d 期望=%d%n", // Group %d WKC shortfall: measured=%d expected=%d%n
args.group, args.actualWkc, args.expectedWkc));
events.addNicLinkChangedListener((args) ->
System.out.printf("NIC %s 链路 %s%n", args.adapterName, args.isUp ? "恢复" : "断开")); // NIC %s link %s%n (restored / disconnected)
// ===== PDO cycle callback (synchronous, for same-cycle real-time control such as FSoE) =====
events.addProcessDataCyclicSyncListener((masterIndex) -> {
// same-cycle real-time control; for ordinary reads/writes use the mapped structures (inputsMapping / outputsMapping)
});
This SDK does not provide an asynchronous PDO cycle callback or an input data change event. The main application path is to map inputsMapping / outputsMapping once after entering OP, so the Structure maps directly onto the process image; copyInputPdo / writeOutputPdo are whole-frame snapshot alternatives. If you need per-cycle processing of inputs/outputs, run your own application thread that polls (calling read() / write() on the mapped structures, or taking copyInputPdo snapshots).