Slave events
Access through slave.events(). Event arguments are already filtered to the current slave, so the signatures stay simple.
Slave-level subscriptions and master-level events share the same master event table; callbacks registered through slave.events() are filtered by the current slave index at dispatch time, so their arguments carry no master_index / slave_index. Subscriptions made through the master-level master.events() are unaffected.
FSoE safety data exchange callbacks are registered through SafetyManager / add_data_exchanged_callback() on remove_data_exchanged_callback() (process_cycle() dispatches each station's safety inputs/outputs and FSoE state every cycle), and connection management also uses SafetyManager.
Feature overview
| Category | Event / method | Read/write | Description |
|---|---|---|---|
| Slave state events | slave.events().on_state_changed() | write-only | Slave EtherCAT state changes |
| master.events().on_slave_state_changed_with_al() | write-only | Master-level state change, carrying the AL code at the moment of the change (16-bit raw code + whether it is trustworthy) | |
| slave.events().on_emergency() | write-only | CoE Emergency message | |
| slave.events().on_offline() | write-only | Slave offline (hot-plug disconnect) | |
| slave.events().on_online() | write-only | Slave online (hot-plug recovery) | |
| slave.events().on_dc_sync_lost() | write-only | DC synchronization lost |
Slave state events
on_state_changed
pub fn on_state_changed(&self, callback: Arc<dyn Fn(i32, i32) + Send + Sync + 'static>)
// parameters: (old_state, new_state)
Fires when the EtherCAT state of the slave changes. It shares the same event table with master.events().on_slave_state_changed(), and this subscription is filtered by slave index.
Registration override semantics: the registration identity is the pointer of the passed Arc plus the slave index scope. Registering the same Arc repeatedly for the same slave overwrites the original slot (no double delivery); the same Arc registered to different slaves does not overwrite across them. Every newly created Arc counts as two independent subscriptions.
Example:
use std::sync::Arc;
slave.events().on_state_changed(Arc::new(|old_state, new_state| {
println!("状态变化: {:?} → {:?}", old_state, new_state); // State change: {:?} → {:?}
}));
on_slave_state_changed_with_al
pub fn on_slave_state_changed_with_al(
&self,
callback: Arc<dyn Fn(u16, u16, i32, i32, u16, bool) + Send + Sync + 'static>,
)
// parameters: (master_index, slave_index, old_state, new_state, al_status_code, al_known)
Subscribes to master-level slave state changes; the same event additionally carries the AL Status Code (lossless 16-bit) "at the moment of the change". It and on_slave_state_changed are two independent subscription tables: both are delivered on the same tick, side by side, and neither overwrites nor replaces the old channel.
The AL code is read from a cached field of the native slave structure: zero frames, no BRD/FPRD, no port lock, so it is safe to read on the native callback thread; even after the slave has dropped out of OP and recovered, you still get the reason code from the moment it dropped.
al_known == false conditions: slave index < 1 / master aggregate state (slave_index == 0 does not go through this channel) / master closed / null pointer / read failure / is_lost() is true / value == 0xFFFF. In that case al_status_code is always 0xFFFF, which only means "the AL code is unavailable at this moment" — it is not any error code and must not be read as "no error"; for the live truth "right now", use error_code_live_read().
For asynchronous delivery use on_slave_state_changed_with_al_async(...); the parameters and al_known semantics are the same.
Example:
master.events().on_slave_state_changed_with_al(Arc::new(
|mi, si, old_state, new_state, al_code, known| {
if known {
println!("[{}:{}] {:?} → {:?}, AL=0x{:04X}", mi, si, old_state, new_state, al_code);
} else {
println!("[{}:{}] {:?} → {:?}, AL 码不可信", mi, si, old_state, new_state); // [{}:{}] {:?} → {:?}, AL code unreliable
}
},
));
on_emergency
slave.events().on_emergency(|error_code, error_reg, b1, w1, w2| { });
// Fn(u16, u16, u8, u16, u16)
CoE Emergency message. It shares the same event table with master.events().on_emergency(), and this subscription is filtered by slave index.
Callback parameters:
// Fn(u16, u16, u8, u16, u16)
error_code: u16, // error code (CANopen Emergency Error Code)
error_reg: u16, // error register (object 0x1001)
b1: u8, // manufacturer-specific data (byte 3)
w1: u16, // manufacturer-specific data (bytes 4-5)
w2: u16, // manufacturer-specific data (bytes 6-7)
Example:
slave.events().on_emergency(|error_code, _error_reg, _b1, _w1, _w2| {
println!("紧急消息: 错误码=0x{:04X}", error_code); // Emergency message: error code=0x{:04X}
});
on_offline
slave.events().on_offline(|| { });
// Fn()
Slave offline (hot-plug disconnect). It shares the same event table with master.events().on_slave_offline(), and this subscription is filtered by slave index; it also goes through offline deduplication and the evidence-consistency gate.
Example:
slave.events().on_offline(|| {
println!("从站离线"); // Slave offline
});
on_online
slave.events().on_online(|| { });
// Fn()
Slave online (hot-plug recovery). It shares the same event table with master.events().on_slave_online(), and this subscription is filtered by slave index; it is delivered only after that slave's offline was announced.
Example:
slave.events().on_online(|| {
println!("从站上线"); // Slave online
});
on_dc_sync_lost
slave.events().on_dc_sync_lost(|diff_ns| { });
// Fn(i32)
DC synchronization lost. It shares the same event table with master.events().on_dc_sync_lost(), and this subscription is filtered by slave index.
Example:
slave.events().on_dc_sync_lost(|diff_ns| {
println!("DC 同步丢失: 偏差 {}ns", diff_ns); // DC sync lost: deviation {}ns
});
Input data changes
slave.events().on_input_changed() has been removed. It was the slave mirror of the master on_input_data_changed mechanism, which relied on the SDK core comparing input PDOs byte by byte every cycle to detect changes. Once the application holds the process image itself (the recommended path is to map once and then read and write the live process image directly, or copy a whole-frame snapshot), the "per-cycle change detection + callback dispatch" stage no longer drives anything.
Alternative: when you need to detect input changes, compare the previous cycle's snapshot yourself. The recommended path is to map once and then read the live process image every cycle; for snapshot scenarios a whole-frame copy also works:
let pdo = master.slave(1).pdo();
let mut last = pdo.inputs();
loop {
std::thread::sleep(std::time::Duration::from_millis(10));
let now = pdo.inputs();
if now != last {
println!("从站 1 输入数据变化, {} 字节", now.len()); // Slave 1 input data changed, {} bytes
last = now;
}
}
Thread safety
Event callbacks fire on the underlying callback thread (not the PDO cycle worker, and not the main thread). Slave-level events (state / EMCY / offline / online / DC sync lost) are all dispatched synchronously on the underlying callback thread; a slow callback occupies that thread, so keep the work fast. In Rust, callback closures must satisfy the Send + Sync + 'static bounds. Shared data needs synchronization:
use std::sync::{Arc, Mutex};
let last_state = Arc::new(Mutex::new(0i32));
let st_clone = last_state.clone();
slave.events().on_state_changed(Arc::new(move |_old, new| {
// recover the inner value after poisoning instead of panicking
*st_clone.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = new;
}));
Avoid long-running work inside callbacks. If you need to process a large amount of data, send it to a channel and handle it asynchronously:
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
slave.events().on_emergency(move |ec, _er, _b1, _w1, _w2| {
let _ = tx.send(ec); // send quickly
});
Complete example
use darra_ethercat::EcState;
use std::sync::Arc;
let slave = master.slave(1);
// ===== slave state events =====
slave.events().on_state_changed(Arc::new(|old, new| {
println!("状态: {:?} → {:?}", old, new); // State: {:?} → {:?}
}));
slave.events().on_emergency(|ec, _er, _b1, _w1, _w2| {
println!("紧急消息: 0x{:04X}", ec); // Emergency message: 0x{:04X}
});
slave.events().on_offline(|| println!("从站离线")); // Slave offline
slave.events().on_online(|| println!("从站上线")); // Slave online
slave.events().on_dc_sync_lost(|diff_ns| {
println!("DC 同步丢失: {}ns", diff_ns); // DC sync lost: {}ns
});
// note: on_input_changed was removed on 2026-05-21 — the PDO path now polls the live process image pointer,
// to detect input changes, poll the slave input pointer and compare against the previous cycle's snapshot.
Unsubscribing (subscribe_* / off_*)
Every slave-level on_* has a matching unsubscribable variant for removing a single subscription precisely:
| Event | Subscribe (returns SubscriptionHandle) | Unsubscribe (returns bool) |
|---|---|---|
| State change | subscribe_state_changed | off_state_changed |
| EMCY | subscribe_emergency | off_emergency |
| Offline | subscribe_offline | off_offline |
| Online | subscribe_online | off_online |
| DC sync lost | subscribe_dc_sync_lost | off_dc_sync_lost |
Handle semantics:
- A handle is valid only within its slave scope + its master bucket + the same event category; using it across events, unsubscribing twice, or using it after the master
clear_all()always returnsfalseand never removes other subscriptions by mistake. off_state_changedremoves by registration identity (Arcpointer + slave index scope);off_emergency/off_offline/off_online/off_dc_sync_lostremove by the callbackArcpointer.- After removal nothing is dispatched anymore; a callback already in flight is not forcibly interrupted.
Registration semantics: on_state_changed Arcoverrides** by ** pointer + slave scope (registering the same Arc for the same slave twice does not double-deliver); on_emergency / on_offline / on_online / on_dc_sync_lost append (each call adds a subscription). For precise unsubscription, use the subscribe_* + off_* pairs in the table above.
Clearing: SlaveEvents::clear_all() is marked #[deprecated] and is currently a no-op that clears no callbacks. To clean up, use MasterEvents::clear_all() (it clears the whole master and therefore all slave-level subscriptions along with it); there is currently no entry point that clears only this slave's subscriptions.