Slave events
Two channels: master.events() filtered by slave index, or a single-station subscription through slave.events().
Slave events are routed automatically by the master event system to that slave's SlaveEvents at delivery time; no manual DLL callback registration is needed. Routing does not depend on whether anyone subscribed at the master level: the same event is delivered both to the slave-level listeners of master.events() and to the same-named listeners of slave.events(), and the two channels each fire once.
Repeating add*Listener with the same listener object registers it only once; one event is delivered exactly once to each subscriber. Slave-level events accept only valid slave indices 1..N: slave_index == 0 (master aggregate state) and negative numbers are not delivered to slave-level subscribers — Emergency / SlaveOffline / DCSyncLost / SlavePortLinkChanged are dropped and a DEBUG log is written; SlaveStateChanged is redirected to the master-level addStateChangedListener instead.
FSoE safety events are subscribed through slave.fsoe().
Feature overview
| Category | Event | Registration method | Read/write | Description |
|---|---|---|---|---|
| Slave state | SlaveStateChanged | addSlaveStateChangedListener | write-only | Slave EtherCAT state change |
| SlaveStateChangedWithAl | addSlaveStateChangedWithAlListener | write-only | Slave state change, carrying the AL code at the moment of the change (16-bit raw code + whether it is trustworthy) | |
| EmergencyEvent | addEmergencyEventListener | write-only | CoE Emergency message | |
| SlaveOffline | addSlaveOfflineListener | write-only | Slave offline (hot-plug disconnect) | |
| SlaveOnline | addSlaveOnlineListener | write-only | Slave online (hot-plug recovery) | |
| DCSyncLost | addDCSyncLostListener | write-only | DC synchronization lost |
The InputDataChanged input PDO data change event has been removed. The lower layer no longer does a memcmp every cycle. To detect input changes, take copyInputPdo yourself (or a SlavePdo.inputs() snapshot) and compare it with the previous cycle.
Slave state events
SlaveStateChanged
master.events().addSlaveStateChangedListener((masterIndex, slaveIndex, oldState, newState) -> {
// ...
});
Triggered when the slave EtherCAT state changes.
Callback parameters: (interface MasterEvents.SlaveStateChangedListener.onSlaveStateChanged)
masterIndex(short) — master indexslaveIndex(short) — slave indexoldState(EcState) — old statenewState(EcState) — new state
Example:
master.events().addSlaveStateChangedListener((mi, si, oldState, newState) -> {
System.out.printf("从站 %d 状态: %s -> %s%n", si, oldState, newState); // Slave %d state: %s -> %s%n
});
SlaveStateChangedWithAl
// Master level (filter by masterIndex / slaveIndex yourself)
master.events().addSlaveStateChangedWithAlListener(
(oldState, newState, alStatusCode, alStatusCodeKnown) -> { });
// Slave level (already filtered to this slave)
slave.events().addStateChangedWithAlListener(
(oldState, newState, alStatusCode, alStatusCodeKnown) -> { });
Delivered on the same tick, side by side with SlaveStateChanged, not replacing the old event. alStatusCode is the full 16-bit AL Status Code "at the moment of the change", taken from a zero-frame cached field with no extra bus frame — so even after the slave has dropped out of OP and recovered, you still get the reason code from the moment it dropped.
Callback parameters: (MasterEvents.SlaveStateChangedWithAlListener / SlaveEvents.StateChangedWithAlListener, both with the same signature)
oldState(EcState) — old statenewState(EcState) — new statealStatusCode(int) — AL Status Code at the moment of the change; meaningless whenalStatusCodeKnown=falsealStatusCodeKnown(boolean) — whether the AL code is trustworthy
alStatusCodeKnown=false conditions: slave index < 1 (the master aggregate state does not go through this channel) / master closed / null slave pointer / read failure / isLost() is true / value == 0xFFFF. In that case alStatusCode must not be read as "no error"; for the live truth "right now", use alStatusCodeLiveRead().
Remove a subscription with removeSlaveStateChangedWithAlListener(...) / removeStateChangedWithAlListener(...).
Example:
master.events().addSlaveStateChangedWithAlListener((oldState, newState, alCode, known) -> {
if (known) {
System.out.printf("状态: %s -> %s, AL=0x%04X%n", oldState, newState, alCode); // State: %s -> %s, AL=0x%04X%n
} else {
System.out.printf("状态: %s -> %s, AL 码不可信%n", oldState, newState); // State: %s -> %s, AL code unreliable%n
}
});
EmergencyEvent
master.events().addEmergencyEventListener((masterIndex, slaveIndex, errorCode, errorReg, b1, w1, w2) -> {
// ...
});
CoE Emergency message.
Callback parameters: (interface MasterEvents.EmergencyEventListener.onEmergency)
masterIndex(short) — master indexslaveIndex(short) — slave indexerrorCode(short) — error code (CANopen Emergency Error Code)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)
Example:
master.events().addEmergencyEventListener((mi, si, ec, er, b, w1, w2) -> {
System.out.printf("从站 %d 紧急消息: 错误码=0x%04X%n", si, ec); // Slave %d emergency message: error code=0x%04X%n
});
SlaveOffline
master.events().addSlaveOfflineListener((slaveIndex) -> {
// ...
});
Slave offline (hot-plug disconnect).
Callback parameters: (interface MasterEvents.SlaveOfflineListener.onSlaveOffline)
slaveIndex(short) — slave index
Example:
master.events().addSlaveOfflineListener((si) -> {
System.out.println("从站 " + si + " 离线"); // Slave {slaveIndex} offline
});
SlaveOnline
master.events().addSlaveOnlineListener((slaveIndex) -> {
// ...
});
Slave online (hot-plug recovery).
Callback parameters: (interface MasterEvents.SlaveOnlineListener.onSlaveOnline)
slaveIndex(short) — slave index
Example:
master.events().addSlaveOnlineListener((si) -> {
System.out.println("从站 " + si + " 上线"); // Slave {slaveIndex} online
});
DCSyncLost
master.events().addDCSyncLostListener((masterIndex, slaveIndex, diffNs) -> {
// ...
});
DC synchronization lost.
Callback parameters: (interface MasterEvents.DCSyncLostListener.onDCSyncLost)
masterIndex(short) — master indexslaveIndex(short) — slave indexdiffNs(int) — DC deviation (ns)
Example:
master.events().addDCSyncLostListener((mi, si, d) -> {
System.out.println("从站 " + si + " DC 同步丢失: " + d + "ns"); // Slave {si} DC sync lost: {d}ns
});
Input data change (removed)
The InputDataChanged input data change event has been removed. That event originally relied on a per-cycle memcmp of the input PDO in the lower layer.
How to detect input changes: start your own application thread that calls copyInputPdo periodically (or takes a SlavePdo.inputs() snapshot) and compare it with the previous cycle.
byte[] prev = null;
while (running) {
byte[] cur = master.getSlave(1).slavePdo().inputs(); // Whole input frame snapshot for this cycle
if (prev != null && !java.util.Arrays.equals(prev, cur)) {
System.out.println("从站 1 输入变化: " + java.util.Arrays.toString(cur)); // Slave 1 input change:
}
prev = cur;
Thread.sleep(1);
}
slave.events() single-station subscription
slave.events() returns this slave's own SlaveEvents, which is master.events()delivered in parallel** with the slave-level listeners of ** (the same event fires once on each channel, and neither replaces the other). The master event object filters by slaveIndex; SlaveEvents is already bound to this one slave, so callbacks no longer carry the master/slave index.
| Category | Event | Registration method | Unregistration method | Callback parameters | Read/write |
|---|---|---|---|---|---|
| Slave events | State change | addStateChangedListener | removeStateChangedListener | (EcState oldState, EcState newState) | write-only |
| CoE Emergency | addEmergencyListener | removeEmergencyListener | (short errorCode, short errorReg, byte b1, short w1, short w2) | write-only | |
| DC synchronization lost | addDCSyncLostListener | removeDCSyncLostListener | (int diffNs) | write-only | |
| Offline | addOfflineListener | removeOfflineListener | () | write-only | |
| Online | addOnlineListener | removeOnlineListener | () | write-only |
SlaveEvents se = slave.events();
SlaveEvents.StateChangedListener onState = (oldState, newState) ->
System.out.printf("从站 %d: %s -> %s%n", slave.SlaveNum, oldState, newState); // Slave %d: %s -> %s%n
se.addStateChangedListener(onState);
se.removeStateChangedListener(onState); // Unregister with the same listener reference
Clear all subscriptions
clearAll()
slave.events().clearAll()
Clear all event subscriptions at the slave level to prevent memory leaks.
Example:
slave.events().clearAll();
Unregistration paths summary: for a single subscription use remove*Listener from the table above (removed by the same listener reference); for a full cleanup use clearAll(); both only clear Java-side references and involve no bus access. SlaveEvents has no addInputChangedListener / removeInputChangedListener (that event has been removed).
Thread safety
Event callbacks fire on a non-UI thread. Updating the UI requires thread synchronization:
// Swing
SwingUtilities.invokeLater(() -> label.setText("位置: " + position)); // Position:
// JavaFX
Platform.runLater(() -> label.setText("位置: " + position)); // Position:
Avoid long-running work in event callbacks. If you need to process a large amount of data, put it in a queue and process it asynchronously:
// Use ConcurrentLinkedQueue for asynchronous processing (EMCY / state change and other event callbacks)
ConcurrentLinkedQueue<short[]> dataQueue = new ConcurrentLinkedQueue<>();
master.events().addEmergencyEventListener((mi, si, ec, er, b, w1, w2) -> {
dataQueue.add(new short[]{(short) si, (short) ec}); // Fast enqueue
});
Offline event injection and detailed listeners
Offline reporting comes in two levels: the plain addSlaveOfflineListener(slaveIndex) gives only the slave index; the detailed listeners give the full context, and split into two mutually exclusive delivery paths depending on whether the delivery-time evidence contradicts offline — a single judgement reaches only one of them, and subscribing to both still fires each only once.
| Category | Method | Type/return | Read/write | Description |
|---|---|---|---|---|
| Offline detail | onSlaveOfflineDetailed(SlaveOfflineEventArgs) | void | call | Delivered when offline has already been announced (real offline / unknown) |
| onSlaveOfflineDisputed(SlaveOfflineEventArgs) | void | call | Delivered when the slave loss marking contradicts the delivery-time evidence (no offline event is delivered in that case) | |
| Event injection | triggerOffline() | void | call | Delivers one offline event locally to this slave's OfflineListener |
| triggerOnline() | void | call | Delivers one online event locally to this slave's OnlineListener |
onSlaveOfflineDetailed(SlaveOfflineEventArgs args)
void onSlaveOfflineDetailed(SlaveOfflineEventArgs args)
Interface MasterEvents.SlaveOfflineDetailedListener (a functional interface). Register with master.events().addSlaveOfflineDetailedListener(listener) and unregister with removeSlaveOfflineDetailedListener(listener).
Delivered on the same tick as addSlaveOfflineListener, but the payload carries the full context: the subscriber does not have to read back or poll to show the time, the reason category and the delivery-time evidence. Delivered only when offline has already been announced (real offline / unknown); when the evidence contradicts offline, the contradiction event is delivered instead and this event is not.
Parameters:
args(SlaveOfflineEventArgs) — read-only payload:masterIndex(short) /slaveIndex(short) — master index / slave index (1-based)timestampUtc(Instant) — event time (UTC), which is also the read time of the evidence in this payloadreason(SlaveOfflineReason) — reason category: real offline / not confirmed / unknownprobe(SlaveProbeState) — probe tri-state at delivery timecontribution(EcatSlaveDiag.EcWcContributed) — process data contribution tri-state at delivery time
Returns:
- None (
void)
Example:
master.events().addSlaveOfflineDetailedListener(args ->
System.out.printf("[%s] 从站 %d 离线, 原因=%s, 探针=%s, PD贡献=%s%n", // [%s] Slave %d offline, reason=%s, probe=%s, PD contribution=%s%n
args.timestampUtc, args.slaveIndex, args.reason, args.probe, args.contribution));
onSlaveOfflineDisputed(SlaveOfflineEventArgs args)
void onSlaveOfflineDisputed(SlaveOfflineEventArgs args)
Interface MasterEvents.SlaveOfflineDisputedListener (a functional interface). Register with master.events().addSlaveOfflineDisputedListener(listener) and unregister with removeSlaveOfflineDisputedListener(listener).
Trigger condition: the slave loss marking has already been registered (the system has judged the slave lost, reason = SlaveOfflineReason.Unreachable), but the evidence read at delivery time shows process data confirmed still contributing. In that case the SDK does not deliver the offline-semantics event — neither addSlaveOfflineListener nor onSlaveOfflineDetailed fires; this event is delivered instead, so the same moment never produces two records that contradict each other.
The evidence is read at delivery time (the probe tri-state = a real-response window of ≤2.52 s; the process data contribution bit = this cycle's image), not the reading at the moment of the decision, so do not call the event text "same-tick evidence".
Parameters:
args(SlaveOfflineEventArgs) — read-only payload, fields as above
Returns:
- None (
void)
Example:
master.events().addSlaveOfflineDisputedListener(args ->
System.out.printf("从站 %d 掉站标记与证据矛盾: 探针=%s, PD贡献=%s%n", // Slave %d slave-loss flag conflicts with the evidence: probe=%s, PD contribution=%s%n
args.slaveIndex, args.probe, args.contribution));
triggerOffline()
public void triggerOffline()
Delivers one offline event to the SlaveEvents.OfflineListener registered on this slave. A local delivery: it does not read the bus and does not send frames; use it for self-tests and assertions. Real events are still routed in by the master event system at delivery time.
Returns:
- None (
void)
Example:
slave.events().addOfflineListener(() -> System.out.println("从站 " + slave.SlaveNum + " 离线")); // Slave {slaveIndex} offline
slave.events().triggerOffline();
triggerOnline()
public void triggerOnline()
Delivers one online event to the SlaveEvents.OnlineListener registered on this slave. This is also a local delivery, used for self-tests and assertions.
Returns:
- None (
void)
Example:
slave.events().addOnlineListener(() -> System.out.println("从站 " + slave.SlaveNum + " 上线")); // Slave {slaveIndex} online
slave.events().triggerOnline();
Full example
// ===== Slave state events =====
master.events().addSlaveStateChangedListener((mi, si, oldState, newState) -> {
System.out.printf("从站 %d 状态: %s -> %s%n", si, oldState, newState); // Slave %d state: %s -> %s%n
// Check the error code when the state is abnormal
if (newState == EcState.SAFE_OP && oldState == EcState.OP) {
Slave slave = master.getSlave(si);
EtherCATTypes.EcALState errorCode = slave.errorCode();
if (errorCode != EtherCATTypes.EcALState.NO_ERROR) {
EtherCATTypes.ALErrorCategory category =
EtherCATTypes.classifyALError(errorCode.value);
System.out.printf(" 错误 %s (0x%04X): %s%n", // Error %s (0x%04X): %s%n
errorCode, errorCode.value, category);
}
}
});
master.events().addEmergencyEventListener((mi, si, ec, er, b, w1, w2) -> {
System.out.printf("从站 %d 紧急消息: 错误码=0x%04X, 寄存器=0x%04X%n", si, ec, er); // Slave %d emergency message: error code=0x%04X, register=0x%04X%n
});
master.events().addSlaveOfflineListener((si) -> {
System.out.println("从站 " + si + " 离线(热插拔断开)"); // Slave N offline (hot-plug disconnect)
});
master.events().addSlaveOnlineListener((si) -> {
System.out.println("从站 " + si + " 上线(热插拔恢复)"); // Slave N online (hot-plug recovery)
});
master.events().addDCSyncLostListener((mi, si, d) -> {
System.out.printf("从站 %d DC 同步丢失: 偏差 %dns%n", si, d); // Slave %d DC sync lost: deviation %dns%n
});
// ===== Input data: start your own thread polling the SlavePdo snapshot =====
new Thread(() -> {
byte[] prev = null;
while (running) {
byte[] cur = master.getSlave(1).slavePdo().inputs();
if (prev != null && !java.util.Arrays.equals(prev, cur)) {
System.out.println("从站 1 输入变化: " + java.util.Arrays.toString(cur)); // Slave 1 input change:
}
prev = cur;
try { Thread.sleep(1); } catch (InterruptedException e) { break; }
}
}).start();
// ===== PDO frame loss events =====
master.events().addPDOFrameLossListener((mi, group, consecutive, total) -> {
System.out.printf("组 %d PDO 丢帧: 连续=%d, 累计=%d%n", // Group %d PDO frame loss: consecutive=%d, total=%d%n
group, consecutive, total);
});
// ===== FSoE safety events (if the slave supports it) =====
// The slave.fsoe() sub-object is created lazily and always returns an instance (never null);
// judge FSoE support with isCapable(), do not do a != null check
Slave slave = master.getSlave(1);
if (slave.fsoe().isCapable()) {
// FSoE cyclic data listener (DataExchanged is currently the only open event entry)
slave.fsoe().addDataExchangedListener(ev -> {
System.out.printf("FSoE 周期 %d: 状态=%s, 失效安全=%b%n", // FSoE cycle %d: state=%s, failsafe=%b%n
ev.CycleCount, ev.CurrentState, ev.InFailsafe);
});
}