Events
Obtain MasterEvents through master.events() and subscribe to all master-level events.
All event callbacks and the logging system are registered automatically when the master is initialized; no manual call is needed.
When any event (except the PDO cycle callback) fires, the system logs it automatically, whether or not it is subscribed. This guarantees that key runtime states are not silently lost.
The PDO cycle callback (on_pdo_cyclic_sync) is a high-frequency callback and is not logged.
Exceptions (stated as they are): the four diagnostic events — SDO failure / mailbox error / WKC shortage / NIC link — do not write extra log entries (they are themselves the diagnostic stream); the unified DC stream and the DC recovery edge come from the SDK's unified DC state event stream, and the log entries are produced on the event-emitting side.
on_pdo_cyclic_async (asynchronous PDO cycle callback) and on_input_data_changed / on_input_data_changed_raw (input data change events) have been removed. The recommended path is to map inputs_mapping once. copy_slave_input_pdo / write_slave_output_pdo are snapshot alternatives. on_pdo_cyclic_sync is kept; its callback is delivered by a dedicated worker thread and only consumes the latest cycle. Real-time control that needs cycle-by-cycle alignment must not rely on this callback.
Feature overview
| Category | Method | R/W | Description | Auto logging |
|---|---|---|---|---|
| PDO cycle callback | on_pdo_cyclic_sync | Write-only | PDO cycle callback (dedicated worker thread, latest-only) | — |
| State events | on_state_changed | Write-only | Master's own (aggregated) state change | ✓ |
| on_state_changed_async | Write-only | Master's own state change (asynchronous delivery channel) | ✓ | |
| on_slave_state_changed | Write-only | Slave EtherCAT state change | ✓ | |
| on_slave_state_changed_async | Write-only | State change (underlying asynchronous delivery channel, no feature required) | ✓ | |
| Hot-plug events | on_slave_offline | Write-only | Slave offline (disconnected) | ✓ |
| on_slave_online | Write-only | Slave online (recovered) | ✓ | |
| on_slave_offline_detailed | Write-only | Slave offline with rich context (same tick as on_slave_offline) | ✓ | |
| on_slave_offline_disputed | Write-only | Slave loss marking contradicts the delivery-time evidence (no offline event is delivered; this event is delivered instead) | ✓ | |
| on_slave_discovery | Write-only | Slave discovery callback (underlying offline/online) | ✓ | |
| on_slave_discovery_async | Write-only | Slave discovery (underlying asynchronous delivery channel, no feature required) | ✓ | |
| on_preop_reconfig | Write-only | Slave PreOp reconfiguration callback | ✓ | |
| on_slave_identity_mismatch | Write-only | Slave identity mismatch (wrong model swapped in; revision is not part of the identity check) | ✓ | |
| Exception events | on_emergency | Write-only | CoE Emergency message | ✓ |
| on_pdo_frame_loss | Write-only | Consecutive PDO frame loss (tracked independently per group) | ✓ | |
| on_dc_sync_lost | Write-only | DC synchronization lost | ✓ | |
| Redundancy events | on_redundancy_mode_changed | Write-only | Redundancy mode change (Inactive/Dual/Degraded) | ✓ |
| on_slave_port_link_changed | Write-only | Slave port link change (P0-P3 disconnect/recover) | ✓ | |
| Exception events | on_sdo_error | Write-only | SDO read/write failure (not fired on success; includes rejection on a NotPresent negative-cache hit) | — |
| on_mailbox_error | Write-only | Mailbox timeout / protocol error / channel closed (observed status edge) | — | |
| DC state events | on_dc_event_raised | Write-only | Unified DC state event stream (arming / sync window / reference clock / propagation delay / hot-plug / convergence) | From log |
| on_dc_sync_restored | Write-only | DC lock-loss recovery edge (same edge as the sync window recovery event, includes lock-loss duration) | From log | |
| Diagnostic events | on_wkc_shortage_occurred | Write-only | Group WKC shortage edge (measured < expected, groups 0-7) | — |
| on_nic_link_changed | Write-only | Master NIC link up/down edge | — | |
| Clear events | clear_all | Write-only | Clear all event subscriptions | — |
The following logical events have no corresponding entry point in the Rust SDK; this documentation does not invent APIs:
- Generic error / generic warning callbacks: not provided by the Rust SDK.
- Placeholder slave re-read recovery event: not provided by the Rust SDK.
PDO cycle callback
The asynchronous PDO cycle callback on_pdo_cyclic_async has been removed. Only on_pdo_cyclic_sync remains (the callback is delivered by a dedicated worker thread and only consumes the latest cycle). Recommended path: map once outside the loop.
on_pdo_cyclic_sync()
pub fn on_pdo_cyclic_sync<F>(&self, callback: F) -> bool
where F: Fn(u16) + Send + Sync + 'static
// parameters: (master_index)
Delivered once for every PDO cycle signal (dedicated worker thread, latest-only: while the callback has not returned, intermediate cycles are coalesced and skipped). The real-time thread only publishes the latest cycle number and wakes the dedicated worker; the callback runs on a NORMAL-priority worker thread, not inside the real-time thread.
Return value:
bool—true= the subscription was installed;false= this subscription was not accepted (the event generation has expired / the worker is shutting down / the worker failed to start and the subscription was rolled back)
false must be handled as a failureWhen false is returned the subscription does not exist: the caller must retry or tell the user, and must not treat it as a successful subscription, otherwise the control law silently never runs.
Callback parameters:
master_index(u16) — master index
The callback runs on a dedicated worker thread, so a slow callback does not block the real-time thread, and the bus PDO cycle and frame-loss statistics are unaffected. However, the worker only consumes the latest cycle (latest-only): while the callback has not returned, later cycles only advance the sequence number and intermediate cycles are coalesced and skipped, so the subscriber sees the latest tick rather than every tick. Keeping the callback short is still recommended.
If you write motion targets inside the callback: 0x000F must only be held after 0x06→0x07→0x0F has completed and (statusWord & 0x6F) == 0x27; when not enabled / faulted / NotReady, write 0x0006 and set the target equal to the actual value. Do not write 0x001F for CSP; with multiple axes, issue each axis in the same callback. See CiA 402 for the full state machine.
Example (take master_idx from the callback argument and do not capture it outside the callback):
on_pdo_cyclic_sync requires Fn(u16) + Send + Sync + 'static: the mapping reference is bound to the &self borrow of SlavePdo, so capturing it in the callback is a compile-time error (E0597); a bare pointer is not Send / Sync, so capturing it directly does not compile either (E0277). Using your own logic thread is more straightforward; if a callback is required, construct a SlavePdo inside the callback from the master_idx argument (see the example below), or wrap the directly mapped bare pointer in a new type that asserts Send + Sync for itself and move the whole value in (2021 edition closures capture by field precisely, so the wrapper is bypassed).
Snapshot alternatives (take an element view / whole-frame snapshot every cycle; the copied values do not change by themselves):
use darra_ethercat::{EtherCATMaster, SlavePdo};
#[allow(deprecated)] // SlavePdo::new is a legacy entry point that does not borrow the master; kept only for 'static callbacks that have a bare index
fn main() -> darra_ethercat::Result<()> {
let master = EtherCATMaster::new()?;
let events = master.events();
let ok = events.on_pdo_cyclic_sync(|master_idx| {
// the callback requires 'static, so it cannot capture master;
// construct SlavePdo on the spot from the callback argument master_idx (its ::new takes a bare u16).
let pdo = SlavePdo::new(master_idx, 1);
let _status = pdo.in_items().get(0).and_then(|item| item.as_uint16()); // element view: one call, one snapshot
let _ = pdo.out_items().get(0).and_then(|item| item.set_uint16(0x000F));
});
if !ok { eprintln!("订阅未落地,必须重试"); } // when false is returned the subscription does not exist
Ok(())
}
State events
State events use two mutually exclusive channels: the master's own (aggregated) state goes only through on_state_changed*, and slave states go only through on_slave_state_changed*. The underlying layer uses slave_index == 0 for the master aggregate state (a valid slave index is always 1..N), so an aggregate event never lands in a slave-level callback as 「slave 0」.
on_state_changed() / on_state_changed_async()
pub fn on_state_changed(&self, callback: Arc<dyn Fn(i32, i32) + Send + Sync + 'static>)
pub fn on_state_changed_async(&self, callback: Arc<dyn Fn(i32, i32) + Send + Sync + 'static>)
// parameters: (old_state, new_state)
Master's own (aggregated) state change events, corresponding to the synchronous and asynchronous delivery channels respectively.
Registration overwrite semantics: the registration identity is the pointer of the passed Arc. Registering the same Arc again overwrites the original slot and does not deliver twice; each newly created Arc counts as two independent subscriptions (Rust closures have no stable identity, so reuse the same Arc if you need idempotence).
use std::sync::Arc;
let cb = Arc::new(|old: i32, new_state: i32| {
println!("主站状态: {} -> {}", old, new_state); // Master state: {} -> {}
});
master.events().on_state_changed(cb.clone());
master.events().on_state_changed(cb); // same Arc: overwrites, no double delivery
on_slave_state_changed()
pub fn on_slave_state_changed(
&self,
callback: Arc<dyn Fn(u16, u16, i32, i32) + Send + Sync + 'static>,
)
// parameters: (master_index, slave_index, old_state, new_state)
Fires when a slave's EtherCAT state changes (including requested transitions and abnormal downgrades). Always logged automatically.
Registration overwrite semantics: the registration identity is the pointer of the passed Arc plus the master-level scope (scope = 0, all slaves). Registering the same Arc again overwrites the original slot; each newly created Arc counts as two independent subscriptions.
Callback parameters:
master_index(u16) — master indexslave_index(u16) — slave index (1-based)old_state(i32) — state before the change (the correspondingEcStatevalue)new_state(i32) — state after the change (the correspondingEcStatevalue)
Example:
use std::sync::Arc;
// The callback requires Fn(..) + Send + Sync + 'static and cannot capture master (EtherCATMaster is not Clone and has Drop).
// old / new_state are EcState values in i32 form; use the callback arguments directly.
master.events().on_slave_state_changed(Arc::new(|_master_idx, slave_idx, old, new_state| {
println!("从站 {}: {} -> {}", slave_idx, old, new_state); // Slave {}: {} -> {}
// A state downgrade (new < old) usually means a fault
if new_state < old {
println!(" 从站 {} 状态降级, 建议在主循环中读取 AL Status Code", slave_idx); // Slave {} state degraded, read the AL Status Code in the main loop
}
}));
A Slave cannot be constructed directly inside a callback (it needs an EtherCATMaster). When you need to read the AL Status Code,
call master.slave(idx).error_code() in the main loop where master is held.
Rust can turn a callback into a receiver with mpsc::channel and consume events directly with for ev in rx; there is no need to build your own Arc<Mutex<...>> across threads.
Hot-plug events
on_slave_offline()
pub fn on_slave_offline<F>(&self, callback: F)
where F: Fn(u16) + Send + Sync + 'static
// parameters: (slave_index)
Slave offline event. Fires on a hot-plug disconnect; the recovery state machine built into the PDO thread restores the slave automatically (no PDO impact). Always logged automatically.
Callback parameters:
slave_index(u16) — index of the offline slave (1-based)
Example:
master.events().on_slave_offline(|slave_idx| {
println!("从站 {} 离线", slave_idx); // Slave {} offline
});
on_slave_online()
pub fn on_slave_online<F>(&self, callback: F)
where F: Fn(u16) + Send + Sync + 'static
// parameters: (slave_index)
Slave online event. Fires when a hot-plug connection is restored. Always logged automatically.
Callback parameters:
slave_index(u16) — index of the online slave (1-based)
Example:
master.events().on_slave_online(|slave_idx| {
println!("从站 {} 上线", slave_idx); // Slave {} online
});
on_slave_offline_detailed()
pub fn on_slave_offline_detailed<F>(&self, callback: F)
where F: Fn(SlaveOfflineEventArgs) + Send + Sync + 'static
// parameters: SlaveOfflineEventArgs struct
Slave offline rich-context event. It shares the same decision and the same instant with on_slave_offline() (two deliveries, not a second decision). The payload type is the same as for on_slave_offline_disputed() (SlaveOfflineEventArgs); the event name distinguishes the semantics: this event is delivered only when the offline state has been announced (real offline / unknown), while when the evidence contradicts offline, only the disputed event is delivered.
Payload fields (SlaveOfflineEventArgs):
master_index(u16) — master indexslave_index(u16) — slave index (1-based)timestamp_utc(std::time::SystemTime) — event time (UTC), which is also the read time of the evidence in this payloadreason(SlaveOfflineReason) — offline reason classificationprobe(SlaveProbeState) — slave response state at delivery timecontribution(WcContribution) — process data contribution at delivery time
master.events().on_slave_offline_detailed(|e| {
println!("从站 {} 离线: 原因={:?} 应答={:?} PD贡献={:?}", // Slave {} offline: reason={:?} response={:?} PD contribution={:?}
e.slave_index, e.reason, e.probe, e.contribution);
});
on_slave_discovery() / on_slave_discovery_async()
pub fn on_slave_discovery<F>(&self, callback: F)
where F: Fn(u16, u16, bool) + Send + Sync + 'static
// parameters: (master_index, slave_index, is_found)
pub fn on_slave_discovery_async<F>(&self, callback: F)
where F: Fn(u16, u16, bool) + Send + Sync + 'static
// parameters: (master_index, slave_index, is_found)
Underlying callback for slave discovery/loss: is_found == true means online, false means offline. on_slave_discovery_async is the asynchronous delivery variant of the underlying channel (registered independently from the synchronous channel; it does not require the async-tokio feature).
Callback parameters:
master_index(u16) — master indexslave_index(u16) — slave index (1-based)is_found(bool) —true=online,false=offline
Slave loss events and evidence consistency (SlaveOfflineDisputed)
When a slave is marked lost, the SDK checks the slave's response state and process data contribution at delivery time and then assigns an offline classification. The classification result is a SlaveOfflineReason.
Related structs:
pub enum SlaveOfflineReason {
Unknown, // insufficient evidence — do not invent a real offline
RealOffline, // real offline — process data confirmed not contributing, or the slave confirmed not responding
Unreachable, // unconfirmed — the slave does not respond, but process data is confirmed still contributing
}
SlaveProbeState — the slave response state at delivery time:
pub enum SlaveProbeState {
NotResponding, // slave is not responding
Responding, // slave responds (positive evidence of being online)
Unknown, // insufficient evidence (interface missing / not measured / read failed)
}
WcContribution — the process data contribution in this cycle. Contributed = confirmed contributing WKC; NotContributed = confirmed not contributing; Unknown = no data for this slave yet, cannot decide.
There are only these three classification rules; do not implement another set on the application side:
- process data confirmed contributing →
Unreachable - process data confirmed not contributing →
RealOffline - when the contribution is unknown: the slave confirmed not responding →
RealOffline, otherwise →Unknown
When the SDK has already marked a slave lost but the evidence at delivery time shows that process data is still being contributed, the SDK does not deliver on_slave_offline(), nor the slave-level slave.events().on_offline(); it delivers on_slave_offline_disputed() instead. The event semantics must match the evidence it carries; it cannot say "offline" while carrying "process data still contributing".
master.events().on_slave_offline_disputed(|e| { ... });
Callback parameters (event struct fields):
master_index(u16) — master indexslave_index(u16) — slave index (1-based)timestamp_utc(std::time::SystemTime) — event time, which is also the read time of the evidence in this payloadreason(SlaveOfflineReason) — offline reason classificationprobe(SlaveProbeState) — slave response state at delivery timecontribution(WcContribution) — process data contribution at delivery time
Consumers use it to raise a "suspected momentary disconnection / slave loss marking does not match the evidence" notice; do not turn this into a red alarm or stop the line. A real offline still goes through on_slave_offline().
reason / probe / contribution are all current values read at event delivery time, not historical evidence from the cycle in which the decision was made. Do not describe them as "same-cycle evidence" in logs or the UI.
Announcement semantics:
- The same slave announces offline only once before it comes back online.
- An already announced offline reason can be refined in one direction (
Unknown→ a definite classification) without delivering the event again. - On coming online, if no offline was ever announced for this cycle,
on_slave_online()is not delivered (online and offline stay strictly paired).
Reason queries:
try_get_slave_offline_reason(slave_index)— queries the offline reason of a single slave; returnsNonewhen not registered. Intended for a UI that starts after the offline event, or that resubscribes midwayget_slave_offline_reasons()— a read-only snapshot of all offline reasons at once
A registration exists ≠ an offline was announced — when the evidence contradicts it, only the reason is registered and only on_slave_offline_disputed is delivered; is_slave_offline() and the slave-loss counters keep the same semantics.
Example:
use darra_ethercat::master::SlaveOfflineReason;
master.events().on_slave_offline_disputed(|e| {
println!("从站 {} 掉站标记与证据不符: 应答={:?}, PD贡献={:?}, 证据时刻={:?}", // Slave {} slave-loss flag contradicts the evidence: response={:?}, PD contribution={:?}, evidence time={:?}
e.slave_index, e.probe, e.contribution, e.timestamp_utc);
// only flag a "suspected momentary disconnection"; no red alarm, do not stop the line
});
if let Some(reason) = master.events().try_get_slave_offline_reason(2) {
if reason == SlaveOfflineReason::RealOffline {
println!("从站 2 确证离线"); // Slave 2 confirmed offline
}
}
is_slave_offline()
pub fn is_slave_offline(&self, slave_index: u16) -> bool
Queries whether the event system has confirmed the slave as offline.
Parameters:
slave_index(u16) — slave index
Return value:
bool—truewhen the slave is offline
Example:
if master.events().is_slave_offline(2) {
println!("从站 2 处于离线状态"); // Slave 2 is offline
}
offline_slaves() / offline_slave_count()
pub fn offline_slaves(&self) -> Vec<u16>
pub fn offline_slave_count(&self) -> usize
Gets the list or the count of all offline slave indices.
on_preop_reconfig()
pub fn on_preop_reconfig<F>(&self, callback: F)
where F: Fn(u16, u16) + Send + Sync + 'static
// parameters: (master_index, slave_index)
Fires when the startup parameters are reapplied after a hot-plug recovery. Always logged automatically.
Callback parameters:
master_index(u16) — master indexslave_index(u16) — index of the slave being reconfigured (1-based)
on_slave_identity_mismatch()
pub fn on_slave_identity_mismatch<F>(&self, callback: F)
where F: Fn(SlaveIdentityMismatch) + Send + Sync + 'static
// parameters: SlaveIdentityMismatch struct
Fires when the identity does not match after a slave is powered off and swapped back in: the Vendor/Product read by the EtherCAT identification state machine does not match the configuration. The Revision is not part of the identity check (scan_revision_match() always returns 2, i.e. ignore Revision; set_scan_revision_match() currently has no sendable entry and a call returns an error). Always logged automatically.
After firing, the slave enters the IDENT_REJECTED state and is not probed again automatically (this prevents a wrong device from flooding messages repeatedly). After the operator checks or replaces the device, call master.acknowledge_slave_replacement so the SDK probes again.
Related struct:
pub struct SlaveIdentityMismatch {
pub master_index: u16, // master index
pub slave_index: u16, // slave index (1-based)
pub expected_vendor: u32, // vendor ID expected by the configuration
pub expected_product: u32, // product code expected by the configuration
pub expected_revision: u32, // revision expected by the configuration (reference only; not part of the identity check)
pub actual_vendor: u32, // actual current vendor ID
pub actual_product: u32, // actual current product code
pub actual_revision: u32, // actual current revision
}
Example:
master.events().on_slave_identity_mismatch(|args| {
println!("从站 {} 身份不符:", args.slave_index); // Slave {} identity mismatch:
println!(" 期望: Vendor=0x{:08X}, Product=0x{:08X}, Rev=0x{:08X}", // Expected: Vendor=0x{:08X}, Product=0x{:08X}, Rev=0x{:08X}
args.expected_vendor, args.expected_product, args.expected_revision);
println!(" 实际: Vendor=0x{:08X}, Product=0x{:08X}, Rev=0x{:08X}", // Actual: Vendor=0x{:08X}, Product=0x{:08X}, Rev=0x{:08X}
args.actual_vendor, args.actual_product, args.actual_revision);
// The UI prompts the user to swap back the correct device; call this after confirmation
// master.acknowledge_slave_replacement(args.slave_index)
});
A slave entering the IDENT_REJECTED state fires the event only once. Calling acknowledge_slave_replacement resets the probe; if the identity still does not match, the event fires again.
Exception events
The cycle is set by DENI/LoopCycle and can be as short as 125 µs; it is not hard-coded to 1ms. rt_cnt() should align with 1e9/LoopCycleNs. A deviation of ±20% from the configured value, or a maximum jitter above 25% of the cycle, must be logged and alarmed in the UI. Also check PDOFrameLoss and DCSyncLost. If isolation is not in effect, only a larger jitter is acceptable — a drifting cycle without an alarm is never acceptable. Do not do alarm I/O on the PDO hot path.
on_emergency()
pub fn on_emergency<F>(&self, callback: F)
where F: Fn(u16, u16, u16, u16, u8, u16, u16) + Send + Sync + 'static
// parameters: (master_index, slave_index, error_code, error_reg, b1, w1, w2)
CoE Emergency message event. Sent by slave firmware when it detects an error; the data format follows the CANopen Emergency protocol (CiA 301). Always logged automatically.
Callback parameters:
master_index(u16) — master indexslave_index(u16) — slave index (1-based)error_code(u16) — error code (CANopen Emergency Error Code, object 0x603F)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)
Common Emergency Error Codes:
0x0000— error reset0x1000— generic error0x2000— current error0x3000— voltage error0x4000— temperature error0x5000— device hardware error0x6000— device software error0x7000— additional module error0x8000— monitoring error0x8100— communication error0xFF00— device-specific error
Example:
master.events().on_emergency(|_master_idx, slave_idx, error_code, error_reg, b1, w1, w2| {
println!("从站 {} 紧急消息: 错误码=0x{:04X}, 寄存器=0x{:02X}", // Slave {} emergency message: error code=0x{:04X}, register=0x{:02X}
slave_idx, error_code, error_reg);
});
on_pdo_frame_loss()
pub fn on_pdo_frame_loss<F>(&self, callback: F)
where F: Fn(u16, u8, u32, u32) + Send + Sync + 'static
// parameters: (master_index, group, consecutive_lost, total_lost)
Consecutive PDO frame loss event. Fires when the consecutive frame loss reaches the threshold; a single lost frame is only counted and does not fire the event. Each group is tracked independently. Always logged automatically.
Callback parameters:
master_index(u16) — master indexgroup(u8) — group number where the frame loss occurred (0-7), corresponding to slave groupingconsecutive_lost(u32) — consecutive lost frames in this grouptotal_lost(u32) — cumulative lost frames in this group
Example:
master.events().on_pdo_frame_loss(|_master_idx, group, consecutive, total| {
println!("组 {} 丢帧: 连续={}, 累计={}", group, consecutive, total); // Group {} frame loss: consecutive={}, total={}
});
on_dc_sync_lost()
pub fn on_dc_sync_lost<F>(&self, callback: F)
where F: Fn(u16, u16, i32) + Send + Sync + 'static
// parameters: (master_index, slave_index, diff_ns)
DC sync lost event. Fires once when a slave goes from in sync → out of sync (beyond the threshold); staying beyond the threshold does not fire it again. Always logged automatically.
Callback parameters:
master_index(u16) — master indexslave_index(u16) — index of the slave that lost sync (1-based)diff_ns(i32) — current time difference from the reference clock (nanoseconds)
Example:
master.diagnostics_info().set_sync_window_threshold(500); // 500ns
master.events().on_dc_sync_lost(|_master_idx, slave_idx, diff_ns| {
println!("从站 {} DC 同步丢失: 偏差 {}ns", slave_idx, diff_ns); // Slave {} DC sync lost: deviation {}ns
});
slave.diagnostics().dc().is_in_sync() and slave.diagnostics().dc().sync_time_difference() query the slave's current sync state.
on_sdo_error()
pub fn on_sdo_error<F>(&self, callback: F)
where F: Fn(SdoErrorEventArgs) + Send + Sync + 'static
// parameters: SdoErrorEventArgs struct
Fires when an SDO read/write fails; not fired on success. One delivery per failure (N consecutive failures on the same object = N events).
Trigger points (all dispatched synchronously on the failure exit):
slave.sdo_read(...)/slave.coe().sdo_read(...)— goes through the read entry with the negative cache; a failure is always delivered (is_write = false)- the read entry is short-circuited by a NotPresent negative-cache hit (a deterministic abort latch) — this also counts as a failure;
abort_code= the latched raw device code slave.sdo_write(...)/slave.coe().sdo_write(...)failure (is_write = true) — the slave-level pass-through write entry delegates internally toCoEInstance::sdo_write, so there is a single failure exit and no double deliveryslave.coe().sdo_read_ex(...)/sdo_write_ex(...)(entries that return the raw result struct) also dispatch on failure; success is determined bydata/okin the returned structread_multiple(...)reads items serially; each failed item dispatches once- the asynchronous variant (
spawn_blockingfromasync-tokio) dispatches on a blocking thread-pool thread
Not fired (stated as it is):
- the success path (including a successful 0-byte read)
Payload (SdoErrorEventArgs):
master_index(u16) — master indexslave_index(u16) — slave index (1-based)index(u16) — object dictionary indexsub_index(u8) — object dictionary subindexis_write(bool) —true= write failure,false= read failureerror(SDOError) — enum mapped from the Abort Code; non-Abort failures (WKC=0 / timeout) map to the normalized valueSDOProtocolTimeout (0x05040000); out-of-domain abort codes map toUnknownErrorabort_code(u32) — raw Abort Code;0= non-Abort failure (a communication-level failure such as WKC=0 / timeout)timestamp_utc(SystemTime) — event time (UTC)
Example:
master.events().on_sdo_error(|args| {
println!(
"SDO {}失败 从站{} 0x{:04X}:{:02X} abort=0x{:08X} error={:?}", // SDO {} failed, slave {} 0x{:04X}:{:02X} abort=0x{:08X} error={:?}
if args.is_write { "写" } else { "读" },
args.slave_index, args.index, args.sub_index, args.abort_code, args.error
);
});
on_mailbox_error()
pub fn on_mailbox_error<F>(&self, callback: F)
where F: Fn(MailboxErrorEventArgs) + Send + Sync + 'static
// parameters: MailboxErrorEventArgs struct
The observed edge of mailbox transaction-level errors. The Rust SDK currently has no per-transaction receipt API: the only trigger surface is the status change observed when reading the mailbox status (MailboxProtocol::last_status()); one edge evaluation is performed per read.
Status → error category mapping:
Observed MailboxStatus | Dispatched kind |
|---|---|
Timeout | Timeout |
Cancelled | ChannelClosed |
MailboxError / ProtoMismatch / WkcFail | ProtocolError |
Pending / Success / NoMemory / InvalidArg / NotImplemented / NotSent | not dispatched |
NotSent(-11) = the request was never sent locally; the frame never reached the wire. There is no conclusion for this round and no bus evidence at all — it must not be used to convict a slave drop or judge link health; callers treat it as retryable.
Edge semantics:
- The first sighting only establishes a baseline: even if a given (master, slave, protocol) is observed as failing for the first time, it is not dispatched (a historical error is not treated as a new event)
- the same failure state persisting → no repeated messages
- success → failure, or the failure category changes (for example
Timeout→MailboxError) → a new edge, dispatched - a failed mailbox statistics read (underlying return
rc != 1) → treated asPending; neither is the baseline updated nor an event dispatched (a failed read is not folded into a failure)
Payload (MailboxErrorEventArgs):
master_index(u16) — master indexslave_index(u16) — slave index (1-based)protocol(MailboxType) — mailbox protocol (frame header type code):ErrorMailbox0x00 /ADSOverEtherCAT0x01 /EthernetOverEtherCAT0x02 /CANopenOverEtherCAT0x03 /FileOverEtherCAT0x04 /ServoOverEtherCAT0x05 /VendorOverEtherCAT0x0F. Out-of-domain raw values (including 0x08 for FSoE) map toErrorMailbox; the raw code is kept indetailasprotocol=0xNNkind(MailboxErrorKind) —Timeout/ProtocolError/ChannelCloseddetail(String) — readable detail: current status, previous status, last error code, master/slave/protocol numberstimestamp_utc(SystemTime) — event time (UTC)
Example:
master.events().on_mailbox_error(|args| {
println!(
"从站 {} 邮箱异常 {:?} 协议 {:?}: {}", // Slave {} mailbox error {:?} protocol {:?}: {}
args.slave_index, args.kind, args.protocol, args.detail
);
});
DC state events
DC arming, window entry/exit, reference clock switching and freezing, propagation delay remeasurement / reuse / invalidation, hot-plug recovery and slow convergence all go into the unified DC state event stream; there is no need to dig through the process log. Once published, an event type never changes meaning.
Consumption channel = the LogManager log view:
use darra_ethercat::logging::{LogManager, LogCategory};
let view = LogManager::instance().default_view();
view.set_on_updated(|entry| {
// DC state events enter log entries by category; identify them by level and text
});
view.set_filter(&[LogCategory::Error, LogCategory::Warning]);
| Category | Event | Level | R/W | Trigger and debounce | Key payload |
|---|---|---|---|---|---|
| DC event | Arming succeeded | Message | Read-only | Sent only when the published arming mask changes; the same mask is not repeated | Written / read-back 0x0980, 0x09A0, ESI preset, required mask, evidence strength |
| DC event | Arming failed / rolled back | Warning | Read-only | Always sent the first time; while it persists, at most one entry every 10 seconds | Reason, whether it was rolled back, AL status / code, write WKC, read-back 0x0980 |
| DC event | No SYNC0 cycle unit | Message | Read-only | Once per (master, slave) | Evidence from three consecutive attempts with no response to 0x0980 |
| DC event | Sync window exceeded | Warning | Read-only | Reported once on entry; while it persists, at most one entry every 10 seconds | Current difference, threshold, duration so far, sample count |
| DC event | Sync window recovered | Message | Read-only | Reported once per recovery (paired with sync window exceeded) | Current difference, threshold |
| DC event | Reference clock established / switched / lost | Message; Warning when warning=1 | Read-only | One entry per switch, minimum interval 1 second | Old / new reference clock, preset, reason |
| DC event | Reference clock frozen | Warning | Read-only | At most one entry per slave every 60 seconds | 1:1 ramp slope (ppm), reason |
| DC event | Propagation delay remeasured | Message | Read-only | Minimum interval 1 second | Reason, slave count, maximum pdelay across the bus, session generation |
| DC event | Propagation delay reused | Debug | Read-only | Minimum interval 10 seconds; not repeated within the same generation | Reason, slave count, maximum pdelay, generation |
| DC event | Propagation delay baseline invalidated | Message | Read-only | Minimum interval 1 second | Reason; the next update must remeasure the whole bus |
| DC event | Recovered after hot-plug | Message; Warning when warning=1 | Read-only | Minimum interval 2 seconds per slave | Arming result, 0x0980 read-back, AL status / code, pdelay |
| DC event | Convergence too slow (>5 s) | Warning | Read-only | One entry per episode every 60 seconds; a hard minimum of 5 seconds between any two | Duration so far, sample count, difference |
| DC event | Convergence severely overdue (>30 s) | Error | Read-only | Same as the convergence too slow event | Duration so far, sample count, difference |
Level mapping: Message = Info event level (also emitted in production); Warning = warning (also emitted in production); Error = severe (convergence >30 seconds); Debug = reuse detail, not output in Release builds. Debouncing and rate limiting are all done on the emitting side; call sites only report on the state-change edge.
Debounce semantics: the emitting side claims one slot per (master, slave) atomically, so concurrent calls produce only one entry; reference clock and propagation delay events are rate-limited independently (sharing a single timestamp would suppress each other); convergence events are gated per episode, one entry per episode every 60 seconds, with at least 5 seconds between any two. Master-level events (reference clock / propagation delay) use the slave-number-0 slot, so they do not crowd out slave-level events; a slave-level event that wrongly passes slave index 0 is rejected, leaving only a Debug trace.
This channel and on_dc_sync_lost do not replace each other: the strongly typed callback covers only the "in sync → out of sync" edge (the same edge as the sync window exceeded event), while this channel provides the unified state event stream shared by all languages. The signature and behaviour of on_dc_sync_lost are unchanged.
This channel does not change the public event API; the implementation only performs O(1) table lookups and low-frequency formatting, and must not be called on the hot path.
on_dc_event_raised()
pub fn on_dc_event_raised<F>(&self, callback: F)
where F: Fn(DcEventArgs) + Send + Sync + 'static
// parameters: DcEventArgs struct
Strongly typed projection of DC state events. The events come from the SDK's unified DC state event stream; a custom log callback takes over log output, in which case use the DC event API directly.
Trigger semantics:
- one delivery per DC state event produced; malformed events are silently ignored and no event is fabricated
slave_index: always 0 for master-level events (reference clock / propagation delay); otherwise the slave index, or 0 when not providedmaster_index: master index, 0 when unknown
Payload (DcEventArgs):
master_index(u16) — master indexslave_index(u16) — slave index (1-based; 0 for master-level events, consistent with the underlying slot convention)code(DcEventCode) — event type; the member name is the event name: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=13params(String) — the raw event parameters, neither parsed nor trimmed (for diagnostics); see the "Key payload" column of the table above for the meaning of each eventtimestamp_utc(SystemTime) — the moment the SDK produced this event (UTC), not the moment the event occurred on the bus
It does not replace on_dc_sync_lost / on_dc_sync_restored; all of them can be subscribed at the same time. Debouncing and rate limiting are done on the producing side (see the "Trigger and debounce" column above); this event does no further coalescing.
Example:
use darra_ethercat::master::DcEventCode;
master.events().on_dc_event_raised(|args| {
if args.code == DcEventCode::WindowExceeded {
println!("从站 {} DC 同步窗口超限: {}", args.slave_index, args.params); // Slave {} DC sync window exceeded: {}
}
println!("DC 事件 {:?} (主站 {}): {}", args.code, args.master_index, args.params); // DC event {:?} (master {}): {}
});
on_dc_sync_restored()
pub fn on_dc_sync_restored<F>(&self, callback: F)
where F: Fn(DcSyncRestoredEventArgs) + Send + Sync + 'static
// parameters: DcSyncRestoredEventArgs struct
DC lock-loss recovery edge — projected in the same dispatch round as the sync window recovered event (WindowRecovered): on_dc_event_raised is delivered first, then this event.
Payload (DcSyncRestoredEventArgs):
master_index(u16) — master indexslave_index(u16) — slave index (1-based)timestamp_utc(SystemTime) — recovery time (UTC, the moment the SDK produced the event)lost_duration(Duration) — duration out of sync, converted from microseconds intoDuration; when the event does not carry this field it isDuration::ZERO(reported as 0, not invented)
Not fired: non-sync-window-recovery events and malformed events are not delivered. A sync window recovered event that lacks the lost-sync duration field is still delivered, with lost_duration = Duration::ZERO.
Example:
master.events().on_dc_sync_restored(|args| {
println!(
"从站 {} DC 已恢复, 失锁 {} ms", // Slave {} DC recovered after {} ms out of lock
args.slave_index,
args.lost_duration.as_millis()
);
});
Diagnostic events
The WKC shortage and NIC link edge types are produced by the SDK by sampling at 1 Hz.
Sampling starts by establishing a baseline, so:
- NIC link: the first sample only establishes the baseline; the earliest possible dispatch is on the second sample (about 2 s later)
- WKC shortage: if it is already short on the first sample, it can be dispatched immediately (about 1 s later)
on_wkc_shortage_occurred()
pub fn on_wkc_shortage_occurred<F>(&self, callback: F)
where F: Fn(WkcShortageEventArgs) + Send + Sync + 'static
// parameters: WkcShortageEventArgs struct
Group WKC shortage edge: the group's measured WKC is less than expected (a mapped slave is not contributing). The group's measured and expected WKC are sampled at 1 Hz, group numbers 0-7.
Edge criteria:
- an unused group with expected WKC = 0 is skipped entirely: no dispatch and no baseline (when the group is enabled later, it is handled by the "first sighting" rule)
- first sighting (no baseline): dispatch when
actual < expected - with a baseline: dispatch only when
actual < expectedand (the previous sample was not short, or theactual/expectedvalues changed) - shortage persists with unchanged values → not repeated
- recovery (
actual >= expected) → not dispatched, only the baseline is updated; a later shortage counts as a new edge
Payload (WkcShortageEventArgs):
master_index(u16) — master indexgroup(u8) — group number 0-7actual_wkc(u16) — measured WKCexpected_wkc(u16) — expected WKC (a fixed value determined at configuration time; this event does not lower it)timestamp_utc(SystemTime) — event time (UTC)
Example:
master.events().on_wkc_shortage_occurred(|args| {
println!(
"组 {} WKC 短缺: 实测 {}/{} (主站 {})", // Group {} WKC shortfall: measured {}/{} (master {})
args.group, args.actual_wkc, args.expected_wkc, args.master_index
);
});
on_nic_link_changed()
pub fn on_nic_link_changed<F>(&self, callback: F)
where F: Fn(NicLinkChangedEventArgs) + Send + Sync + 'static
// parameters: NicLinkChangedEventArgs struct
Master NIC link up/down edge. Link status is sampled at 1 Hz and normalized into the three states Up / Down / Unknown.
Edge criteria:
- an unknown sample is not dispatched and does not update the baseline (a failed read is not folded into "link down")
- the first sample only establishes the baseline and is not dispatched
- afterwards dispatch only when
is_updiffers from the previous sample (up → down and down → up, once each)
Payload (NicLinkChangedEventArgs):
master_index(u16) — master indexadapter_name(String) — NIC name of the master's primary port. It may be an empty string in the current version: the Rust SDK does not yet record the primary port name on theset_networkside, so the attribution information is best-effort; the edge semantics are unaffectedmac(String) — MAC of the master's primary port (AA:BB:CC:DD:EE:FF). Same as above, it may be an empty string in the current version; do not invent it when unavailableis_up(bool) —true= link up,false= link downtimestamp_utc(SystemTime) — event time (UTC)
Example:
master.events().on_nic_link_changed(|args| {
println!(
"主站 {} NIC 链路 {} (网卡={:?}, MAC={:?})", // Master {} NIC link {} (NIC={:?}, MAC={:?})
args.master_index,
if args.is_up { "up" } else { "down" },
args.adapter_name, args.mac
);
});
Input data change events
on_input_data_changed / on_input_data_changed_raw (and the slave-level slave.events().on_input_changed()) have been removed.
The old mechanism relied on the underlying SDK comparing the input PDO byte by byte every cycle to detect changes. Once the application layer holds its own PDO process image (the recommended path is to map once and then read and write the real-time process image directly, or to copy whole-frame snapshots), the "per-cycle change detection + callback dispatch" stage is no longer driven.
Replacement: to detect input changes, compare against the previous cycle's snapshot yourself. The recommended path is to map once and then read the real-time process image every cycle; a whole-frame copy also works for snapshot scenarios:
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;
}
}
Redundancy events
on_redundancy_mode_changed()
pub fn on_redundancy_mode_changed<F>(&self, callback: F)
where F: Fn(u16, i32, i32) + Send + Sync + 'static
// parameters: (master_index, old_mode, new_mode)
Fires when the redundancy operating mode changes. old_mode / new_mode correspond to the RingMode enum values (0=Inactive, 1=Dual, 2=Degraded). Always logged automatically.
Callback parameters:
master_index(u16) — master indexold_mode(i32) — redundancy mode before the changenew_mode(i32) — redundancy mode after the change
Example:
master.events().on_redundancy_mode_changed(|_master_idx, old_mode, new_mode| {
println!("冗余模式: {} -> {}", old_mode, new_mode); // Redundancy mode: {} -> {}
});
on_slave_port_link_changed()
pub fn on_slave_port_link_changed<F>(&self, callback: F)
where F: Fn(u16, u16, u8, bool) + Send + Sync + 'static
// parameters: (master_index, slave_index, port, is_up)
Fires when the physical link of a slave ESC port changes (one of P0-P3 disconnects or recovers). The once-per-second diagnostic cycle checks the link bit of the DL Status register; 1→0 fires "disconnected" and 0→1 fires "recovered". Always logged automatically.
Used to pinpoint the faulty cable segment (when the facing ports of adjacent slaves both report a break, the cable between them is the problem).
Callback parameters:
master_index(u16) — master indexslave_index(u16) — slave index (1-based)port(u8) — port number0-3, corresponding toP0/P1/P2/P3is_up(bool) —true=link recovered,false=link disconnected
Example:
master.events().on_slave_port_link_changed(|_master_idx, slave_idx, port, is_up| {
let state = if is_up { "恢复" } else { "断开" }; // Restored / disconnected
println!("从站 {} 端口 P{} link {}", slave_idx, port, state); // Slave {} port P{} link {}
});
master.diagnostics_info().break_point() / all_break_points() provide an aggregated fault point view (broken line + CRC faults). on_slave_port_link_changed is the raw event source and is suitable for real-time alarms.
Clear event subscriptions
clear_all()
pub fn clear_all(&self)
Clears all registered event callbacks to prevent memory leaks. Use it before reinitializing the master or before the program exits.
Example:
let events = master.events();
events.on_slave_offline(|idx| println!("从站 {} 离线", idx)); // Slave {} offline
events.on_emergency(|_, slave, ec, _, _, _, _| println!("EMCY: {} 0x{:04X}", slave, ec));
// clear all callbacks before reinitializing
events.clear_all();
SlaveEvents::clear_all() is marked #[deprecated] in the Rust SDK and is currently a no-op; it clears no callbacks and only prints one line to stderr. Use MasterEvents::clear_all() for cleanup (it clears all subscriptions in this master's bucket).
Unsubscribing (subscribe_* / off_*)
Every on_* has a matching removable variant for removing a single subscription precisely (not emptying the whole master bucket). The naming rule is fixed: on_x → subscribe_x + off_x:
| Event | Subscribe (returns a handle) | Unsubscribe |
|---|---|---|
| PDO cycle | subscribe_pdo_cyclic_sync → Option<SubscriptionHandle> | off_pdo_cyclic_sync(handle) |
| Master state | subscribe_state_changed / subscribe_state_changed_async | off_state_changed / off_state_changed_async |
| Slave state | subscribe_slave_state_changed / subscribe_slave_state_changed_async | off_slave_state_changed / off_slave_state_changed_async |
| Offline/online | subscribe_slave_offline / subscribe_slave_online | off_slave_offline / off_slave_online |
| Offline rich context / disputed | subscribe_slave_offline_detailed / subscribe_slave_offline_disputed | off_slave_offline_detailed / off_slave_offline_disputed |
| Discovery | subscribe_slave_discovery / subscribe_slave_discovery_async | off_slave_discovery / off_slave_discovery_async |
| Frame loss / DC sync lost | subscribe_pdo_frame_loss / subscribe_dc_sync_lost | off_pdo_frame_loss / off_dc_sync_lost |
| Redundancy / PreOp / identity / port | subscribe_redundancy_mode_changed / subscribe_preop_reconfig / subscribe_slave_identity_mismatch / subscribe_slave_port_link_changed | off_redundancy_mode_changed / off_preop_reconfig / off_slave_identity_mismatch / off_slave_port_link_changed |
| EMCY | subscribe_emergency | off_emergency |
| DC event stream | subscribe_dc_event_raised / subscribe_dc_sync_restored | off_dc_event_raised / off_dc_sync_restored |
| Diagnostic edges | subscribe_wkc_shortage_occurred / subscribe_nic_link_changed | off_wkc_shortage_occurred / off_nic_link_changed |
| SDO / mailbox | subscribe_sdo_error / subscribe_mailbox_error | off_sdo_error / off_mailbox_error |
Handle semantics:
- a handle is valid only for the same event + the same master bucket; using it across events, unsubscribing twice, or using it after the master's
clear_all()always returnsfalse, and it never removes other subscriptions subscribe_pdo_cyclic_syncreturns anOption:Nonecovers the same three cases ason_pdo_cyclic_syncreturningfalse(event generation expired / worker rundown / worker failed to start and the subscription was rolled back)- removing the last PDO subscription follows the same underlying unsubscribe + worker shutdown flow as
clear_all; a callback already in flight is not forcibly interrupted, but it will not enter the dispatch snapshot again - unsubscribing affects only the subscription that this handle refers to; subscriptions registered directly with
on_*have no handle and can only be cleared wholesale withclear_all()(on_state_changed*/on_slave_state_changed*can also be replaced by overwriting with the sameArc)
Apart from the two families on_state_changed* and on_slave_state_changed*, which overwrite by identity, all other on_* calls are append registrations (push_cb): each call adds a subscription, and registering the same closure twice dispatches twice. Where a subscription must be removable individually after registering, use the subscribe_* + off_* pairs from the table above.
Thread safety
Event callbacks fire on non-UI threads. Rust's Send + Sync + 'static bounds keep callbacks safe when used across threads. To share state, use Arc<Mutex<T>> or atomic types:
use std::sync::{Arc, Mutex};
let shared_state = Arc::new(Mutex::new(Vec::new()));
let state_clone = shared_state.clone();
master.events().on_slave_offline(move |slave_idx| {
// recover the inner value after poisoning instead of panicking
let mut state = state_clone.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
state.push(slave_idx);
println!("从站 {} 离线, 累计离线: {}", slave_idx, state.len()); // Slave {} offline, cumulative offline: {}
});
Dispatch thread (by event category, as implemented):
| Event | Dispatch thread | Synchronization semantics |
|---|---|---|
| on_pdo_cyclic_sync | Dedicated worker thread darra-pdo-callback-worker | latest-only: the underlying layer publishes only the latest cycle number; intermediate cycles are coalesced and skipped |
| on_state_changed* / on_slave_state_changed* / on_emergency / on_slave_offline* / on_slave_online / on_slave_discovery* / on_pdo_frame_loss / on_dc_sync_lost / on_redundancy_mode_changed / on_preop_reconfig / on_slave_identity_mismatch / on_slave_port_link_changed | Underlying callback thread | Synchronous; the SDK starts no extra thread; the callback must return quickly (a slow callback occupies the underlying callback thread but does not change the bus cycle) |
| on_sdo_error | The thread that called the SDO API | Synchronous, called directly on the failure exit; asynchronous SDO dispatches on a blocking thread-pool thread |
| on_mailbox_error | The thread reading the mailbox status (MailboxProtocol::last_status()) | Synchronous, called directly when a status edge is observed |
| on_dc_event_raised / on_dc_sync_restored | Log callback thread | Synchronous, called directly after the DC event log line is parsed |
| on_wkc_shortage_occurred / on_nic_link_changed | Diagnostic polling thread (1 Hz) | Called directly after each sample |
Locks and panics:
- before dispatching, a snapshot of the master's subscriptions (a
Vec<Arc<...>>clone) is taken and the event table lock is released; user callbacks run without holding the SDK event table lock, so subscribing / unsubscribing / callingclear_all()inside a callback does not self-deadlock - each callback is wrapped individually in
catch_unwind(safe_invoke): a panicking callback is caught at the dispatch boundary and one line is written to stderr ([Darra events] callback <name> panicked (caught at dispatcher boundary)); it does not cross the underlying call boundary and does not affect later callbacks in the same dispatch - callbacks must still return quickly: SDO / mailbox callbacks occupy the caller's thread; DC callbacks occupy the log processing thread (a slow callback slows other log processing); diagnostic callbacks occupy the 1 Hz sampling cycle (a slow callback delays edge detection in the next sample)
Registration semantics: the 6 events added on this page are all append registrations (push_cb); registering the same closure repeatedly stacks multiple dispatches — different from on_state_changed / on_slave_state_changed, which overwrite by Arc pointer. To remove a single subscription precisely, use the matching subscribe_* + off_*: subscribe_* returns a SubscriptionHandle and off_* returns a bool (always false when used across events, unsubscribed twice, or after the master's clear_all, and it never removes other subscriptions).
Full example
let events = master.events();
// ===== Slave state =====
events.on_slave_state_changed(std::sync::Arc::new(|_, slave_idx, old, new_state| {
println!("从站 {}: {} -> {}", slave_idx, old, new_state); // Slave {}: {} -> {}
}));
// ===== Hot-plug =====
events.on_slave_offline(|idx| println!("从站 {} 离线", idx)); // Slave {} offline
events.on_slave_online(|idx| println!("从站 {} 上线", idx)); // Slave {} online
// ===== Exception events =====
events.on_emergency(|_, slave_idx, error_code, _, _, _, _| {
println!("从站 {} 紧急消息: 0x{:04X}", slave_idx, error_code); // Slave {} emergency message: 0x{:04X}
});
events.on_pdo_frame_loss(|_, group, consecutive, total| {
println!("组 {} 丢帧: 连续={}, 累计={}", group, consecutive, total); // Group {} frame loss: consecutive={}, total={}
});
events.on_dc_sync_lost(|_, slave_idx, diff_ns| {
println!("从站 {} DC 同步丢失: {}ns", slave_idx, diff_ns); // Slave {} DC sync lost: {}ns
});
// ===== Redundancy events =====
events.on_redundancy_mode_changed(|_, old_mode, new_mode| {
println!("冗余模式变化: {} -> {}", old_mode, new_mode); // Redundancy mode change: {} -> {}
});
events.on_slave_port_link_changed(|_, slave_idx, port, is_up| {
println!("从站 {} P{} link {}", slave_idx, port, // Slave {} P{} link {}
if is_up { "恢复" } else { "断开" }); // Restored / disconnected
});
// ===== Hot-plug identity mismatch =====
events.on_slave_identity_mismatch(|args| {
println!("从站 {} 身份不符, 换设备后调用 acknowledge_slave_replacement({})", // Slave {} identity mismatch, call acknowledge_slave_replacement({}) after replacing the device
args.slave_index, args.slave_index);
});
// ===== PDO cycle callback (dedicated worker thread, latest-only) =====
events.on_pdo_cyclic_sync(|_master_idx| {
// a slow callback does not block RT; but only the latest cycle is consumed, intermediate cycles are coalesced and skipped
});
// ===== Diagnostic events =====
events.on_sdo_error(|args| println!("SDO 失败 从站{} abort=0x{:08X}", args.slave_index, args.abort_code)); // SDO failed on slave {} abort=0x{:08X}
events.on_mailbox_error(|args| println!("邮箱异常 {:?} 从站{}", args.kind, args.slave_index)); // Mailbox error {:?} on slave {}
events.on_dc_event_raised(|args| println!("DC 事件 {:?}: {}", args.code, args.params)); // DC event {:?}: {}
events.on_dc_sync_restored(|args| println!("DC 恢复 从站{}", args.slave_index)); // DC recovered on slave {}
events.on_wkc_shortage_occurred(|args| {
println!("组{} WKC 短缺: {}/{}", args.group, args.actual_wkc, args.expected_wkc); // Group {} WKC shortfall: {}/{}
});
events.on_nic_link_changed(|args| println!("NIC 链路 {}", if args.is_up { "up" } else { "down" })); // NIC link {}
// Note: on_pdo_cyclic_async / on_input_data_changed were removed on 2026-05-21 —
// the PDO path is now real-time process-image pointer polling; to detect input changes, poll the process image and compare snapshots.
Unsubscribing: every event has a precise removal entry point via subscribe_* / off_* (clear_all() clears everything); see "Unsubscribing (subscribe_* / off_*)" above for the full table and handle semantics. SlaveEvents::clear_all() is a deprecated no-op; use MasterEvents::clear_all() for cleanup.