Properties and state machine
NIC enumeration and scanning (NIC selection / quick scan / full scan / cancel) are covered in Initialization § NICs and scanning. This page covers the state machine and runtime control only.
Properties
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| Basic information | index() | u16 | read-only | Master instance index |
| master_number() | u16 | read-only | Alias of index() | |
| slave_count() | u16 | read-only | Number of slaves detected on the network | |
| slaves() | Vec<Slave> | read-only | List of slave handles | |
| slave(n) | Slave | read-only | Gets the slave handle at the given index (1-based) | |
| Network and link | primary_network_info() | Option<NetworkInfo> | read-only | Primary network adapter information |
| redundant_network_info() | Option<NetworkInfo> | read-only | Redundant network adapter information | |
| link_state() | LinkState | read-only | Network link state | |
| link_status() | LinkState | read-only | Alias of link_state() | |
| IO mapping | obytes() | Option<u32> | read-only | Total output bytes (None = the master structure cannot be read, as distinct from reading 0 bytes) |
| ibytes() | Option<u32> | read-only | Total input bytes (None = the master structure cannot be read, as distinct from reading 0 bytes) | |
| obits() | u16 | read-only | Total output bits | |
| ibits() | u16 | read-only | Total input bits | |
| DC and cycle | has_dc() | Option<bool> | read-only | Whether the network contains slaves that support DC (None = the master structure cannot be read, which is not the same as no DC) |
| Runtime | state() | EcState | read-only | Current EtherCAT state of the master |
| Runtime | aggregated_state() | EcSlaveStatus | read-only | System aggregate state: the lowest base state across all real slaves plus the aggregated Error bit; returns Unknown(0) (unknown) when no slave takes part and never falls back to the master-state cache |
| expected_wkc() / set_expected_wkc(u16) | u16 / Result<()> | read-only / written once at configuration time | Expected working counter (set once before startup) |
Group-related properties (group_slave_count() / active_group_count() and others) are covered in Slave groups.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkState {
Disconnected = 0, // confirmed down: both configured ports are explicitly DOWN
Connected = 1, // link is up
PrimaryOnly = 3, // primary port only
SecondaryOnly = 4, // redundant port only
Unknown = 5, // unknown: not initialized / real-time process image not observable / PHY has not reported yet
}
LinkState::Disconnected only means "confirmed down"; when the physical link cannot be read the call returns LinkState::Unknown, which does not mean disconnected — show it as "unknown" in the UI rather than "link down".
In Rust you can filter with the chain master.slaves().by_state(EcState::Operational).by_group(0).collect() (SlaveIterExt), and you can also index with master.indexable()[1].
Group access
group_accessor() is the single entry point for working group by group; for the business configuration and semantics of groups see Slave groups.
SlaveGroupAccessor<'_> is not exported at the crate root; its public path is darra_ethercat::master::core::SlaveGroupAccessor. Instances come from master.group_accessor(), so you never construct one yourself.
| Method | Returns | Description |
|---|---|---|
master.group_accessor() | SlaveGroupAccessor<'_> | Accessor for group-by-group access |
accessor.count() | usize | Number of currently active groups |
accessor.slaves(group) | Vec<Slave<'_>> | Slave handles of that group; an empty Vec when the group has no slaves |
accessor.divider(group) / accessor.set_divider(group, div) | u8 / () | Reads / sets the cycle divider of that group; div == 0 is not applied |
accessor.group_slave_count(group) / accessor.group_expected_wkc(group) | u16 / u16 | Slave count of that group / expected WKC of that group |
for g in &accessor { .. } | u8 | Iterates group numbers; yields only groups with more than 0 slaves |
Instances and lifecycle
| Method | Returns | Description |
|---|---|---|
EtherCATMaster::active_instance_count() | i32 | Master slots currently occupied in the process (not the limit) |
EtherCATMaster::max_instance_count() | i32 | Maximum number of master instances that can be created in the process |
master.deconstruct() | (bool, u16, u16) | Read-only triple: whether this instance still holds ownership of the underlying master / slave count / master index; it does not release resources |
master.close() | () | Extension trait MasterCloseExt: stops the PDO cycle thread first, then consumes and releases the instance |
deconstruct() sounds like teardown but only performs a read-only export — releasing resources is still handled by Drop (stop the thread and reclaim the master). A first element of false in the triple means this instance no longer holds ownership of the underlying master (construction-failure cleanup or asynchronous release has completed), so it can no longer be used as a live instance.
close() lives on an extension trait, which requires importing the prelude first:
use darra_ethercat::sugar::prelude::*;
use darra_ethercat::{EtherCATMaster, EcState};
let mut master = EtherCATMaster::new()?;
master.set_state(EcState::Operational)?;
master.close(); // Stop the PDO thread and release it; the instance is unusable afterwards
State machine control
The main entry points for master state changes are the synchronous set_state and the asynchronous set_state_async (the serialized async / cancellable variant set_state_async_isolated is described below; for waiting there is also wait_for_state and similar). Both run the standard ETG state machine chain (Init → PreOp → SafeOp → OP) internally, switch across levels in one chained pass, apply the startup parameters per transition, and start the PDO thread automatically when switching to SafeOp / Operational. The timeout of each step is calculated automatically from the number of startup SDOs and the number of slaves (5 s floor per slave, at least 30 s to enter OP, capped at 45 s). Failure causes are returned through Result::Err.
state()
pub fn state(&self) -> EcState
Reads the current EtherCAT state of the master.
Related enums:
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcState {
None = 0x00,
Init = 0x01,
PreOp = 0x02,
Boot = 0x03,
SafeOp = 0x04,
Operational = 0x08,
}
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcALState {
NoError = 0x0000, // no error
UnspecifiedError = 0x0001, // unspecified error
NoMemory = 0x0002, // out of memory
InvalidDeviceSetup = 0x0003, // invalid device setup
InvalidRevision = 0x0004, // revision mismatch
SiiEepromMismatch = 0x0006, // SII/EEPROM information does not match the firmware
FirmwareUpdateFailed = 0x0007, // firmware update did not succeed (the old firmware is still running)
LicenseError = 0x000E, // license error
InvalidStateChange = 0x0011, // invalid state change
UnknownRequestedState = 0x0012, // unknown requested state
BootstrapNotSupported = 0x0013, // Bootstrap not supported
NoValidFirmware = 0x0014, // no valid firmware
InvalidBootstrapMailboxConfig = 0x0015, // SM0/SM1 mailbox address or length is invalid in BOOT state
InvalidPreOpMailboxConfig = 0x0016, // SM0/SM1 mailbox configuration is invalid in PreOp state
InvalidSyncManagerConfig = 0x0017, // invalid sync manager configuration
NoValidInputs = 0x0018, // no valid inputs
NoValidOutputs = 0x0019, // no valid outputs
SyncError = 0x001A, // synchronization error
SyncManagerWatchdog = 0x001B, // SM watchdog
InvalidSyncManagerTypes = 0x001C, // invalid sync manager types
InvalidOutputConfig = 0x001D, // invalid output configuration
InvalidInputConfig = 0x001E, // invalid input configuration
InvalidWatchdogConfig = 0x001F, // invalid watchdog configuration
NeedsColdStart = 0x0020, // cold start required
NeedsInit = 0x0021, // Init required
NeedsPreOp = 0x0022, // PreOp required
NeedsSafeOp = 0x0023, // SafeOp required
InvalidInputMapping = 0x0024, // invalid input mapping
InvalidOutputMapping = 0x0025, // invalid output mapping
InconsistentSettings = 0x0026, // inconsistent settings
FreerunNotSupported = 0x0027, // free run not supported
SyncNotSupported = 0x0028, // synchronization not supported
FreerunNeeds3Buffer = 0x0029, // free run requires 3 buffers
BackgroundWatchdog = 0x002A, // background watchdog
NoValidIO = 0x002B, // no valid inputs or outputs
FatalSyncError = 0x002C, // fatal synchronization error
NoSyncError = 0x002D, // sync not received (SAFEOP waits for the first Sync0/Sync1 and refuses SO→OP); the literal name "No sync error" does not mean error-free
CycleTimeTooSmall = 0x002E, // cycle time too small (ETG.1020 additional code; 0x002F is undefined in all tables and is not listed)
InvalidDcSyncConfig = 0x0030, // invalid DC synchronization configuration
InvalidDcLatch = 0x0031, // invalid DC latch
PllError = 0x0032, // PLL error
DcSyncIOError = 0x0033, // DC synchronization IO error
DcSyncTimeout = 0x0034, // DC synchronization timeout
InvalidDcSyncCycle = 0x0035, // invalid DC synchronization cycle
InvalidSync0Cycle = 0x0036, // invalid SYNC0 cycle
InvalidSync1Cycle = 0x0037, // invalid SYNC1 cycle
MailboxAoe = 0x0041, // AoE mailbox error
MailboxEoe = 0x0042, // EoE mailbox error
MailboxCoe = 0x0043, // CoE mailbox error
MailboxFoe = 0x0044, // FoE mailbox error
MailboxSoe = 0x0045, // SoE mailbox error
MailboxVoe = 0x004F, // VoE mailbox error
EepromNoAccess = 0x0050, // EEPROM cannot be accessed
EepromError = 0x0051, // EEPROM error
ExternalHardwareNotReady = 0x0052, // external hardware not ready
SlaveRestarted = 0x0060, // slave restarted
DeviceIdUpdated = 0x0061, // device ID updated
ModuleIdentListMismatch = 0x0070, // module identity list mismatch
SupplyVoltageTooLow = 0x0080, // supply voltage too low
SupplyVoltageTooHigh = 0x0081, // supply voltage too high
TemperatureTooLow = 0x0082, // temperature too low
TemperatureTooHigh = 0x0083, // temperature too high
AppControllerAvailable = 0x00F0, // application controller available
Unknown = 0xFFFF, // unknown error
}
set_state()
pub fn set_state(&mut self, state: EcState) -> Result<(), DarraError>
Switches the master to the target state synchronously, blocking the current thread until the switch completes or fails.
Parameters:
state(EcState) — target state (Init / PreOp / SafeOp / Operational)
Returns:
Ok(())—statehas been reached; if the target isSafeOp/Operational, the PDO thread has been startedErr(DarraError::StateChangeFailed { target, actual_master_state, al_status_code, unreached_slaves })— the switch failed, carrying the measured master state / AL Status Code / the list of slaves that did not reach the target; the error description can be printed directly withDisplay
obytes() / ibytes() / has_dc() return None when the master structure cannot be read (master not created / invalid index), which is strictly distinct from Some(0) / Some(false). When you assess capability, do not treat None as "no IO / no DC".
Example:
master.set_state(EcState::Operational)?;
if master.state() == EcState::Operational {
println!("主站已进入 OP"); // Master has entered OP
}
- The protocol layer handles intermediate states automatically per the standard EtherCAT state machine sequence (across levels in one pass).
- Complete the network configuration / startup parameter import / IO mapping build before switching.
- Automatic internal retry: the SDK retries internally within each state transition step to absorb transient faults such as hardware PHY/PLL jitter; application code does not need its own
for/loopretry wrapper. - Automatic sync configuration in SafeOp: when switching to
SafeOp, the SDK automatically configures the sync cycle counter threshold and the SyncManager sync type for non-DC slaves per the ETG standard (with FreeRun as the fallback), which improves the success rate of reaching OP in large networks and mixed-vendor setups; you do not need to write these objects manually. If you need a custom sync strategy, override it after switching toSafeOp. - SDO timing: once in PreOp you can already call
slave.sdo_read/slave.sdo_write; there is no need to wait for SafeOp. Startup parameters are also usually attached beforePS(PreOp → SafeOp).
Asynchronous variants (do not block the calling thread)
pub fn set_state_async(&self, state: EcState) -> JoinHandle<Result<(), DarraError>>
// async-tokio feature:
pub async fn set_state_async_isolated(
&mut self,
state: EcState,
progress: Option<ProgressFn>,
cancel: Option<CancelToken>,
) -> Result<()>
set_state_async()runs the same state machine chain on a new thread and returns a standard-libraryJoinHandle; call.join()at a suitable point to get the innerResultback. It is a single attempt and does not have the internal retry and resume logic ofset_state.set_state_async_isolated()shares a single serial gate with the other asynchronous operations on the same master: submissions are queued and executed in order, so the bus is never hit concurrently; progress callbacks and cancellation throughCancelTokenare supported; failures are returned faithfully asResultand exceptions are never swallowed.
Example:
let handle = master.set_state_async(EcState::Operational);
// keep refreshing the UI / processing other events on the main thread
ui_tick();
// collect the result at a suitable point
match handle.join() {
Ok(Ok(())) => println!("主站已进入 OP"), // Master has entered OP
Ok(Err(e)) => eprintln!("状态切换失败: {}", e), // State switch failed: {}
Err(p) => eprintln!("状态切换线程异常退出: {}", p), // thread panic reported faithfully
}
start() / stop()
pub fn start(&mut self)
pub fn stop(&mut self)
start() / stop() start/stop the PDO cycle thread; start() requires &mut self,
and after stop() returns the master switches to the PRE_OP state.
Example:
master.start();
// ... PDO communication running
master.stop();
wait_for_slave_state()
pub fn wait_for_slave_state(
&self,
slave_index: u16,
target: EcState,
timeout_ms: u32,
poll_interval_ms: u32,
) -> bool
Polls until a single slave reaches the target state (it compares the low 4 bits of the state and reads the value one last time when the timeout expires).
true— the target state was reached before the timeout (including at the moment it expires)false— the timeout expired without reaching it, or the slave index is invalid, or the state cannot be read- Blocks the current thread; a
poll_interval_msof0is treated as 1 ms
if master.wait_for_slave_state(3, EcState::Operational, 5000, 10) {
println!("从站 3 已进入 OP"); // Slave 3 has entered OP
}
execute_with_state_management()
pub fn execute_with_state_management<F>(
&self,
slave_index: u16,
target_state: EcState,
operation: F,
timeout_ms: i32,
) -> Result<()>
where
F: FnOnce(&Slave) -> Result<()>
Collapses "switch to the target state → run the operation that needs that state → switch back" into a single call:
- Read the current state of the slave (a state that cannot be read is treated as
EcState::None) - If the current state != the target state, switch to the target state within
timeout_ms; on failure it returnsErr(DarraError::StateChangeFailed { .. })(with the measured state and the AL code) and does not runoperation - Run
operation(&slave)and return its result unchanged - Whatever the outcome of step 3, switch the slave back to the state read in step 1; the switch back is best effort, and a failed switch back does not override the result of
operation
Passing an invalid target state such as EcState::None → Err(DarraError::InvalidParameter).
// Write the startup parameters in PreOp, automatically returning to the original state when done
master.execute_with_state_management(2, EcState::PreOp, |slave| {
slave.sdo_write(0x1C12, 0, false, &[0x00])
}, 5000)?;
The cancellation entry point for scans / the build process is in Initialization § Scan entry details.
Process data watchdog
set_all_slave_watchdog()
pub fn set_all_slave_watchdog(&self, timeout_ms: u32) -> Result<BatchWatchdogOutcome>
Sets the process data watchdog timeout of all slaves in one batch.
Returns: Result<BatchWatchdogOutcome>, where:
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BatchWatchdogOutcome {
/// Number of slaves written successfully in this batch (`> 0`, otherwise the caller gets `Err`).
pub written: u32,
/// Whether any slave in this batch was raised to the safe lower bound (never occurs when `written == 0`).
pub raised: bool,
}
written: number of slaves written successfully in this batch.raised: whether any slave in this batch was raised to the safe lower bound. Whenraised == trueyou must readslave.watchdog_config()per slave to get the actual milliseconds — branch slaves may be raised to 5000ms and PDO slaves on the ring may be raised to 400ms (required by the topology protocol); the actual values differ from the requested values, so do not treat it as "everything took effect as requested".- If the whole batch exceeds the 6553ms limit (error code
87), the entire batch returnsErr; values are never silently clamped.
To configure the watchdog of a single slave, use slave.set_watchdog().
Example:
match master.set_all_slave_watchdog(100) { // 100ms timeout
Ok(outcome) => {
println!("本批写上 {} 个从站, 被安全下限抬升={}", outcome.written, outcome.raised); // {} slaves written in this batch, raised to the safety lower limit={}
if outcome.raised {
// read the actual milliseconds per slave: master.slave(i).watchdog_config()
}
}
Err(e) => eprintln!("批量设置看门狗失败: {}", e), // Batch watchdog configuration failed: {}
}
set_all_slave_pdi_watchdog()
pub fn set_all_slave_pdi_watchdog(&self, timeout_ms: u32) -> Result<BatchWatchdogOutcome>
Sets the PDI watchdog timeout of all slaves in one batch. The return value is the same BatchWatchdogOutcome (see above), but for the PDI batch raised is always false (the PDI path has no safe lower-bound raise step).
To configure the watchdog of a single slave, use slave.set_pdi_watchdog().
Example:
match master.set_all_slave_pdi_watchdog(100) { // 100ms timeout
Ok(outcome) => println!("本批写上 {} 个从站", outcome.written), // {} slaves written in this batch
Err(e) => eprintln!("批量设置 PDI 看门狗失败: {}", e), // Batch PDI watchdog configuration failed: {}
}
Per-byte process data writes
| Method | Returns | Description |
|---|---|---|
master.write_slave_output_byte(slave_index, offset, value) | Result<()> | Rewrites byte offset of the slave output process image to value |
The implementation is a version-token read-modify-write: take a snapshot of the whole frame → rewrite the given byte → commit the whole frame. When it collides with the cycle thread it retries a limited number of times and returns Err once the budget is exhausted (a concurrency conflict is reported faithfully and never silently treated as a successful write); an offset beyond the output frame length of that slave → Err (size mismatch).
// Set byte 0 of slave 2's output process image to 0x01 (an enable bit, for example)
master.write_slave_output_byte(2, 0, 0x01)?;
For block writes and typed writes see PDO inputs and outputs.
PDO frame loss statistics and monitoring
Counts cycle frame loss per group, and optionally runs a per-slave PDO performance monitor alongside it.
| Method | Returns | Description |
|---|---|---|
master.pdo_frame_loss_stats(group) | (u32, u32, u32) | Returns (累计丢帧, 当前连续丢帧, 历史最大连续丢帧) in one call |
master.pdo_lost_frames(group) | u32 | Total number of lost frames |
master.pdo_consecutive_lost(group) | u32 | Current number of consecutive lost frames (back to zero once frames recover) |
master.pdo_max_consecutive_lost(group) | u32 | Historic maximum number of consecutive lost frames |
master.reset_pdo_frame_loss_stats(group) | () | Clears the three frame loss statistics of that group |
EtherCATMaster::set_pdo_monitoring(enable) | () | Process-wide switch; turning it off also clears the per-slave PDO statistics |
EtherCATMaster::is_pdo_monitoring_enabled() | bool | Reads that switch |
master.reset_pdo_stats(slave_index) | () | Clears the PDO statistics of the given slave; slave_index == 0 = clear all |
EtherCATMaster::register_pdo_frame_loss_callback(callback) | () | Registers the frame loss callback globally (replaces the previous registration) |
For a group number out of range (>= 8) the three statistics read back as 0 and no error is reported. The frame loss callback is an extern "C" fn function pointer and cannot capture anything:
use darra_ethercat::{EtherCATMaster, PDOFrameLossCallback};
extern "C" fn on_frame_loss(master_index: u16, group: u8, consecutive_lost: u32, total_lost: u32) {
eprintln!("主站 {} 组 {}: 连续丢帧 {}, 累计丢帧 {}", master_index, group, consecutive_lost, total_lost); // Master {} group {}: consecutive frame loss {}, total frame loss {}
}
EtherCATMaster::register_pdo_frame_loss_callback(on_frame_loss as PDOFrameLossCallback);
CPU affinity and the PDO thread
| Method | Returns | Description |
|---|---|---|
EtherCATMaster::available_cpu_cores() | i32 | Number of CPU cores available on this machine |
master.set_cpu_affinity(cpu_core) | bool | Sets the base core and distributes affinity to the PDO thread and diagnostic threads by policy; -1 = not configured (cores picked by the automatic rule), < -1 is invalid; true = accepted and applied |
master.set_pdo_thread_cpu_affinity(cpu_core) | bool | Sets only the target core of the PDO cycle thread: -1 = not configured (automatic rule), 0..=可用核数-1 = explicit binding; takes effect immediately if the thread is already running, otherwise at startup; out of range → false |
master.pdo_thread_cpu_affinity() | i32 | Configured value of the PDO thread; -1 = not configured |
master.pdo_thread_cpu_effective_core() | i32 | Measured core the PDO thread is bound to; -1 = not bound / multi-core mask / thread not started / cannot be read |
EtherCATMaster::validate_timer_accuracy(expected_usec, tolerance_usec) | bool | Measures one real timer wait; inside the tolerance → true |
pdo_thread_cpu_affinity() is the configured value, while pdo_thread_cpu_effective_core() is a reading of the real thread mask, so the two can differ (the system may reject a setting). To judge "is it actually bound", look only at the latter.
validate_timer_accuracy blocks the calling thread for about expected_usec microseconds to perform one real wait measurement; do not call it from a cycle task.
println!("可用核数: {}", EtherCATMaster::available_cpu_cores()); // Available CPU cores: {}
if master.set_pdo_thread_cpu_affinity(2) {
// Take the measured value as the truth, not the configured one
println!("PDO 线程实际核: {}", master.pdo_thread_cpu_effective_core()); // PDO thread effective core: {}
}
Port error counters and link quality
Port errors come from ESC registers (RX Error / Invalid Frame / Lost Link), with array indices P0..P3.
| Method | Returns | Description |
|---|---|---|
master.slave_link_quality(slave_index) | i16 | Link quality percentage 0..=100; -1 = unknown (not sampled yet / invalid index), not "worst" |
master.read_slave_port_error_counters(slave_index) | Option<([u8; 4], [u8; 4], [u8; 4])> | Some((rx_error, invalid_frame, lost_link)) = per-port register snapshot; None = read failed / invalid index |
master.read_all_slave_port_error_counters() | i32 | Reads every slave once and returns the number of slaves read successfully; -1 = master unavailable |
master.slave_port_error_stats(slave_index) | Result<PortErrorStats> | Register snapshot plus an own copy of the lifetime accumulators; cannot be read → Err(DarraError::RegisterFailed) |
master.break_points(max_results) | Option<Vec<(u16, u8, u8)>> | List of fault points (从站号, 端口, 类型); None = the query failed, or max_results == 0 |
master.reset_communication_stats() | () | Clears the communication statistics of this master (total / successful / failed / timed-out cycles, average / maximum / minimum cycle time) |
The type codes of break_points: 0 = broken line, 1 = CRC fault, 0xFF = unknown. Some(vec![]) means "there really is no fault point" whereas None means "the check did not succeed"; the two must not be mixed — squeezing a failure into an empty list yields a false healthy verdict.
Public fields of PortErrorStats:
pub struct PortErrorStats {
pub rx_error: [u8; 4], // Per-port RX Error register snapshot
pub invalid_frame: [u8; 4], // Per-port Invalid Frame register snapshot
pub lost_link: [u8; 4], // Per-port Lost Link register snapshot
pub fwd_rx_error: [u8; 4], // Per-port Forwarded RX Error register snapshot
pub acc_rx_error: [u32; 4], // Lifetime accumulation (wrap-aware)
pub acc_invalid_frame: [u32; 4],
pub acc_lost_link: [u32; 4],
}
acc_baseline_valid() returning false means the accumulation baseline has not been established yet (the first read only builds the baseline), so the acc_* counters have not started accumulating at that point.
if let Some((rx, invalid, lost)) = master.read_slave_port_error_counters(1) {
println!("从站 1 P0: rx_error={} invalid_frame={} lost_link={}", rx[0], invalid[0], lost[0]); // Slave 1 P0: rx_error={} invalid_frame={} lost_link={}
}
if let Some(points) = master.break_points(16) {
for (slave, port, kind) in points {
println!("故障点: 从站 {} 端口 P{} 类型 {}", slave, port, kind); // Fault point: slave {} port P{} type {}
}
}
Hot-plug self-repair
When a slave is powered off and reconnected or replaced, the SDK detects an identity mismatch automatically and enters a protected state, so that the wrong device is not admitted into the control loop.
acknowledge_slave_replacement(slave_num)
pub fn acknowledge_slave_replacement(&self, slave_num: u16) -> Result<bool>
The user confirms that the slave replacement is complete, which triggers the EtherCAT identification state machine to probe that slave again.
When to call: after subscribing to on_slave_identity_mismatch and receiving an identity mismatch alarm, once the operator has finished inspecting or replacing the device, call this method so that the SDK detects it again.
Behaviour:
- If the identity is now correct (the right device is back / the same model with an updated Revision) → it recovers automatically and the
on_slave_onlineevent fires - If the identity still does not match →
on_slave_identity_mismatchfires again and the slave returns to theIDENT_REJECTEDstate
Parameters:
slave_num(u16) — slave index (1-based, matching the configuration)
Returns:
Result<bool>—Ok(true)= accepted and the FSM was reset;Ok(false)= invalid parameter, or the slave is currently not in theIDENT_REJECTED/FAILEDstate (calling before theon_slave_identity_mismatchevent arrives returnsOk(false));Err(...)= the underlying call failed
Calling this method before the on_slave_identity_mismatch event fires has no effect. While a slave has not entered the protected state the SDK keeps probing normally, so no manual confirmation is needed.
Example:
use std::sync::Arc;
// EtherCATMaster itself is not Clone (RAII + Drop). The callback must be 'static and still needs access to master,
// so put master into a shared Arc. Arc dereferences EtherCATMaster automatically, so master.events() still works as usual.
let master: Arc<EtherCATMaster> = Arc::new(EtherCATMaster::new()?);
let master_handle = Arc::clone(&master); // clone the Arc, not the master
master.events().on_slave_identity_mismatch(move |args| {
println!("从站 {} 身份不符: 期望 Vendor=0x{:08X}, 实际 Vendor=0x{:08X}", // Slave {} identity mismatch: expected Vendor=0x{:08X}, actual Vendor=0x{:08X}
args.slave_index, args.expected_vendor, args.actual_vendor);
// UI dialog: "check the device of slave N and click confirm after restoring the correct model"
if show_replacement_dialog(args.slave_index) {
match master_handle.acknowledge_slave_replacement(args.slave_index) {
Ok(true) => println!("已接受, FSM 复位重新探测"), // Accepted; FSM reset and re-probing
Ok(false) => println!("确认失败: 从站不在 IDENT_REJECTED 状态"), // Acknowledgement failed: the slave is not in the IDENT_REJECTED state
Err(e) => eprintln!("确认调用失败: {}", e), // Acknowledgement call failed: {}
}
}
});
on_slave_offline— the slave lost power or was disconnected (identity still matches) → it recovers automatically andon_slave_onlinefireson_slave_identity_mismatch— the slave identity changed (wrong device, i.e. Vendor + Product do not match the configuration; the revision is not part of the identity check) → callacknowledge_slave_replacementmanually
Iteration and lookup by name
The methods below come from extension traits (MasterIterExt / MasterTrySlaveExt), so the prelude must be imported first:
use darra_ethercat::sugar::prelude::*;
| Method | Returns | Description |
|---|---|---|
master.iter_slaves() | SlaveIter<'_> | Iterates slave handles in the order 1..=n; implements DoubleEndedIterator + ExactSizeIterator + FusedIterator, so .rev() works |
master.first_slave() | Option<Slave<'_>> | The 1st slave; no slaves → None |
master.last_slave() | Option<Slave<'_>> | Last slave; no slaves → None |
master.try_first_slave() | Result<Slave<'_>> | The 1st slave; no slaves → Err(DarraError::NoSlaves) |
master.try_slave_by_name(name) | Result<Slave<'_>> | Exact match on Slave::name(); not found → Err(DarraError::InvalidParameter) |
master.try_slave_by_config_addr(config_addr) | Result<Slave<'_>> | Exact match on the configured station address Slave::config_addr() (linear scan over all slaves); not found → Err(DarraError::InvalidParameter) |
The Option versions suit branch decisions on "is it there", the Result versions suit throwing directly with ?; neither does fuzzy matching. try_slave_by_config_addr() is equivalent to iter_slaves().find(|s| s.config_addr() == addr); only the return value differs — the former gives an Err carrying the address when nothing is found, the latter gives None. To pick "the n-th slave" use the index version try_slave(index) (1-based, bound to the topology order); the station address version is unaffected by changes in station order. The iterator you get can be chained further with SlaveIterExt filters (by_state / by_group / by_vendor / by_product / with_dc / online_only / with_protocol / filter_slave); see Syntax sugar.
use darra_ethercat::sugar::prelude::*;
for slave in master.iter_slaves() {
println!("{}: {}", slave.index(), slave.name());
}
let first = master.try_first_slave()?;
let axis = master.try_slave_by_name("Drive_X")?;
let _ = (first, axis);
Multi-slave SDO batch read
pub fn get_multi_slave_sdo_list(
&self,
slave_indices: &[u16],
) -> Vec<Option<crate::slave::coe::OdList>>
Reads the object dictionary list of several slaves in one batch and returns an array of the same length as the input, with Some(OdList) / None per item (the objects of an OdList live in objects: Vec<OdObject>).
- Empty slice → empty
Vec - At most 16 slaves per call; above that limit, with the master unavailable, or when the whole batch fails → everything is
None - A single slave that is not ready / does not support CoE / fails to read → that item is
Noneand the other items are unaffected - Blocking call: it goes through the object dictionary batch read pipeline and takes noticeably longer with many slaves and many objects, so do not put it on the cycle thread
let lists = master.get_multi_slave_sdo_list(&[1, 2, 3]);
for (i, od) in lists.iter().enumerate() {
match od {
Some(od) => println!("从站 {}: {} 个对象", i + 1, od.objects.len()), // Slave {}: {} objects
None => println!("从站 {}: 未就绪或读取失败", i + 1), // Slave {}: not ready or read failed
}
}
Scan cache
| Method | Returns | Description |
|---|---|---|
EtherCATMaster::ring_slave_count() | i32 | Number of slaves on the ring measured by the last on-site topology calibration; 0 = not calibrated; a read-only scan does not update this value |
Configuration and validation
The methods below cover configuration loading, configuration validation, the working counter and related scenarios; for the lifecycle see Initialization, for redundancy see Redundancy, and for group configuration see Slave groups.
load_config_json()
pub fn load_config_json(&self, json: &str) -> Result<()>
Loads the master / slave configuration from a JSON string in one call, including the startup parameters (Startup Parameter, writes to the 0x1C12 / 0x1C13 PDO mapping, startup SDO writes, and so on). Suited to exporting the configuration on the engineer's PC and loading it uniformly on the site service side.
Parameters:
json(&str) — configuration JSON string, UTF-8 encoded
Returns:
Result<()>—Ok(())on success; on failureErr(DarraError::ConfigLoadFailed(code)), wherecodecomes from the underlying call
JSON top-level structure:
// field semantics (illustrative code block; the real file is JSON):
// {
// "master": {
// "loop_cycle_ns": 1000000, // PDO cycle (nanoseconds)
// "frame_repeat_count": 1, // frame repeat count 1~3
// "scan_revision_match": 2 // 0=exact / 1=compatible / 2=ignore
// },
// "slaves": [
// {
// "slave_num": 1, // slave index, 1-based
// "group": 0, // group number 0~7
// "is_optional": false, // optional slave
// "startup_parameters": [
// {
// "od_index": 6010, // SDO index (decimal or hexadecimal)
// "sub_index": 0,
// "data": [15, 0], // byte array (little-endian)
// "transition": "PS", // transition point: IP/PS/PI/SP/SO/OS
// "timing": "before", // before / after
// "complete_access": false
// }
// ]
// }
// ]
// }
Example:
let json = std::fs::read_to_string("config.json")?;
master.load_config_json(&json)?;
master.set_state(EcState::Operational)?;
add_startup_parameterThis method is the batch, persistable form of slave.add_startup_parameter() — each startup_parameters entry in the JSON is equivalent to one add_startup_parameter() call. Suited to configurations that are deployed repeatedly.
auto_configure_sm(&self, slave_index: u16) -> Result<i32> — configures the SM of the specified slave automatically,
it is normally called internally after the configuration is loaded and does not need to be called manually.
validate_config()
pub fn validate_config(&self) -> Result<i32>
Validates whether the current master configuration is complete and usable. The checks are: the network is set up / the ENI is loaded (if used) / at least one slave has been scanned / the IO mapping layout is ready. It is usually called once before set_state(EcState::Operational), to catch configuration gaps quickly before entering the real-time phase.
Parameters: none
Returns:
Ok(n)— validation passed;nis the number of slaves that took part in the validationErr(DarraError::Other)— validation failed; the error message carries the underlying return code
Example:
match master.validate_config() {
Ok(n) => println!("配置校验通过, 共 {} 个从站", n), // Configuration verification passed, {} slaves in total
Err(e) => {
eprintln!("配置校验失败: {}", e); // Configuration verification failed: {}
return Err(e.into());
}
}
master.set_state(EcState::Operational)?;
verify_all_slave_identities()
pub fn verify_all_slave_identities(
&self,
expected: &[SlaveIdentity],
check_revision: bool,
check_serial: bool,
) -> Result<u64>
Compares the online slaves one by one against the expected identity array on VendorID / ProductID / RevisionID / SerialNumber. Used for a hardware inventory check before commissioning and after maintenance, to prevent the wrong slave from being connected.
Parameters:
expected(&[SlaveIdentity]) — expected identity array; index 0 corresponds to slave 1, index 1 to slave 2, and so oncheck_revision(bool) — whether to compare RevisionIDcheck_serial(bool) — whether to compare SerialNumber
Returns:
Ok(0)— all matchOk(mask)— bit N = 1 means slave N (1-based) does not matchErr(DarraError::Other)— the call itself failed (invalid index / slave not online, etc.)
Related struct:
The SlaveIdentity accepted by verify_all_slave_identities comes from darra_ethercat::SlaveIdentity
(re-exported at the crate root), and its fields are product_code / revision_no /
serial_no (note: not product_id / revision_id / serial_number):
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct SlaveIdentity {
pub vendor_id: u32,
pub product_code: u32,
pub revision_no: u32,
pub serial_no: u32,
}
Example:
use darra_ethercat::SlaveIdentity;
let expected = vec![
SlaveIdentity { vendor_id: 0x00000002, product_code: 0x044C2C52, revision_no: 0x00120000, serial_no: 0 },
SlaveIdentity { vendor_id: 0x00000002, product_code: 0x07D43052, revision_no: 0x00110000, serial_no: 0 },
];
let mismatch = master.verify_all_slave_identities(&expected, true, false)?;
if mismatch == 0 {
println!("硬件清单一致"); // Hardware inventory matches
} else {
// mismatch is a u64 bitmask; bit N corresponds to slave N (1-based);
// a u64 only has bits 0..=63, so slaves 1..=63 can be covered by the bitmask
for i in 1u32..=63 {
if (mismatch >> i) & 1 == 1 {
eprintln!("从站 {} 身份不匹配", i); // Slave {} identity mismatch
}
}
}
When verify_all_slave_identities() reports an identity mismatch and the corresponding slave subsequently fires the on_slave_identity_mismatch event, call acknowledge_slave_replacement() after the operator replaces the device so that the SDK probes it again.
expected_wkc() / set_expected_wkc()
pub fn expected_wkc(&self) -> u16
pub fn set_expected_wkc(&self, expected_wkc: u16) -> Result<()>
Reads / sets the global Expected Working Counter of the master. The WKC returned by every EtherCAT PDO cycle should equal this value; a mismatch means that some slaves are not responding or that the mailbox is busy.
set_expected_wkc is a one-shot channel at configuration time: it may be called only once, before startup. Once the master has started (including startup with the configuration embedded in from_json*) or this instance has already been configured, any further call returns Err and is not passed to the underlying layer. expected_wkc is a fixed, true value determined at configuration time; rewriting it at runtime is prohibited, and lowering it to accommodate a degraded bus is prohibited as well.
Implementation notes:
- After the IO mapping (
build()) is complete, the master computes and writesexpected_wkcautomatically using the ETG.1500 rule "read ×1 + write ×2 + read-write ×3"; manual setting is usually unnecessary. - Only in special cases that do not use LRW (for example a custom degraded mode / diagnostics only) is a manual override needed, and only before startup.
- The actual WKC is read through
master.diagnostics_info().wkc(), or a deviation is detected through theon_pdo_frame_lossevent.
Example:
// override as needed before startup (one call only; a call after configuration or startup returns Err)
master.set_expected_wkc(expected)?;
// after startup, verify the automatically computed result read-only
master.set_state(EcState::Operational)?;
let expected = master.expected_wkc();
println!("Expected WKC = {}", expected);
Startup validation and scan cancellation
| Method | Returns | Purpose |
|---|---|---|
master.verify_startup_configuration() / state::verify_startup_configuration(master_index) | StartupVerifyResult | Link + per-slave AL status code + one-pass configuration check, so gaps are found before advancing to Operational |
EtherCATMaster::abort_scan() | () | Cancels a scan that is running; safe across threads (details in Initialization) |
StartupVerifyResult has three fields: valid (whether the whole result is valid) / slave_count (number of online slaves) / issues (list of problems; empty = all checks passed). validate_config() looks only at master-level configuration, whereas this entry point also checks the AL Status Code of every slave.
UDP mode
| Method | Returns | Description |
|---|---|---|
master.set_udp_mode(enable) | Result<()> | Switches whether this master sends and receives over UDP; Err(DarraError::UdpFailed) = master not initialized / UDP socket unavailable, and the change did not take effect |
master.udp_mode() | bool | Whether UDP mode is currently active |
AoE notification listener
Each master has its own AoE notification listener thread; starting and stopping it affect only that master and do not interfere with the others.
| Method | Returns | Description |
|---|---|---|
master.aoe_start_notification_listener() | Result<()> | Starts the listener thread of this master; on failure → Err(DarraError::AoeFailed) |
master.aoe_stop_notification_listener() | Result<()> | Stops the listener thread of this master without affecting other masters |
master.aoe_is_notification_listening() | bool | Whether the listener thread of this master is running |
For the protocol frame format see AoE.
Runtime information and performance export
| Method | Returns | Description |
|---|---|---|
master.master_identity() | Result<MasterIdentity> | Master identity (VendorID / ProductCode / RevisionNo / SerialNo plus name and hardware and software versions); cannot be read → Err(DarraError::DiagnosticsFailed) |
EtherCATMaster::driver_list() | String | Names of the driver services registered on this machine; the first call enumerates once and caches the result, and later calls return the same list; cannot be read → empty string |
master.export_perf_csv(filepath) | Result<()> | Exports the current performance samples to CSV; a path containing a null byte → Err(DarraError::InvalidParameter); monitoring not initialized / already stopped / file write failed → Err(DarraError::Other(..)), and no empty file is produced |
EtherCATMaster::check_buffer_integrity() | Result<bool> | Triggers one integrity self-check (the first one may take a while; it is fast when the cached result is hit) |
The MasterIdentity struct:
pub struct MasterIdentity {
pub vendor_id: u32,
pub product_code: u32,
pub revision_no: u32,
pub serial_no: u32,
pub device_name: [u8; 64],
pub hw_version: [u8; 32],
pub sw_version: [u8; 32],
}
The last three are fixed-length byte arrays (not String); truncate them to the actual length and decode them yourself.
check_buffer_integrity() is implemented as Ok(ret != 0), where ret is the self-check result code (0 = passed); that is, Ok(true) means the self-check returned a code other than 0. Interpret the return value by this definition and do not guess from the method name.
Crash notification and emergency close
| Method | Returns | Description |
|---|---|---|
EtherCATMaster::set_crash_callback(callback) | () | Registers a crash notification callback globally (replaces the previous registration) |
EtherCATMaster::emergency_close_nics() | () | Last resort before the process exits: sets the process-wide abort flag, safely stops all masters and closes the NIC handle of each master directly; the internal state cannot be recovered after the call |
use darra_ethercat::CrashNotifyCallback;
use std::os::raw::{c_char, c_int};
extern "C" fn on_crash(exception_code: c_int, message: *const c_char) {
eprintln!("崩溃通知: code=0x{:08X}", exception_code); // Crash notification: code=0x{:08X}
}
EtherCATMaster::set_crash_callback(on_crash as CrashNotifyCallback);
emergency_close_nics() is only for when the process is about to exit or as an exception fallback: it skips waiting for threads to exit, and no master handle may be used after the call. For a normal shutdown use close() or let the instance Drop.
Topology
topology_build()
pub fn topology_build(&self) -> Result<Vec<TopologyNode>>
Scans again and forces a rebuild of the network topology (use it to force a refresh of the cache after a hot-plug event).
slave_topology()
pub fn slave_topology(&self) -> crate::slave::topology::SlaveTopology
Gets the slave topology tree. For node traversal see Slave § Topology queries.
redundancy_verdict() / unreachable_slave()
pub fn redundancy_verdict(&self) -> RedunVerdict
pub fn unreachable_slave(&self, ordinal: u16) -> Option<u16>
| Method | Returns | Description |
|---|---|---|
master.redundancy_verdict() | RedunVerdict | Verdict of the redundancy engine for the current cycle |
master.unreachable_slave(ordinal) | Option<u16> | Station number of the ordinal-th unreachable slave; out of range or no such entry → None |
pub enum RedunVerdict {
Unknown,
Healthy,
PrimaryLinkDown,
SecondaryLinkDown,
MiddleBroken,
TotalLost,
Unrecognized(i32), // Codes outside the table keep their raw value
}
RedunVerdict is exported from darra_ethercat::master. Unrecognized(i32) keeps the raw code so that it can be traced per version; do not fold it into Unknown. For redundancy configuration and switchover procedures see Redundancy.
max_propagation_delay() / update_propagation_delays()
| Method | Returns | Description |
|---|---|---|
master.max_propagation_delay() | i32 | Maximum propagation delay among all DC slaves (ns); -1 = cannot be read |
master.update_propagation_delays() | Result<i32> | Re-measures the propagation delays; Ok(n) = number of slaves measured / updated in this pass, Err = master unavailable or the current state does not allow measuring |
max_propagation_delay() computes the value once if it has not been computed yet, so the first call is slower than later ones; the value is not refreshed on every cycle.
Error types
The Rust SDK uses Result<T, DarraError> for operations that can fail.
Variant overview
| Variant | Scenario |
|---|---|
AlreadyInitialized / NotInitialized | Initialization order error |
Timeout / NoSlaves | Operation timeout / no slaves on the bus |
NetworkFailed(i32) / NetworkFailedWithLastError { ret, last_error } | NIC binding / network configuration failed |
StateChangeFailed { target, actual_master_state, al_status_code, unreached_slaves } | State transition did not reach the target; carries the measured master state / AL code / list of slaves that did not arrive |
SdoReadFailed { index, subindex, abort_code, raw_abort_code } / SdoWriteFailed { .. } | SDO read or write failed (abort_code is a classified enum; raw_abort_code is the abort code returned verbatim by the device, and is 0 on transport-level failure when the device does not reply) |
CoEInfoFailed { index, subindex, abort_code, wkc } | Reading the OD list / object description / subitem description failed |
SoeFailed(u16) / FoeFailed(String) / EoeFailed / AoeFailed / VoeFailed | The corresponding mailbox protocol failed |
InvalidParameter(String) / ConfigLoadFailed(i32) | Invalid parameter / configuration load failed |
CiA402Failed(String) / EmcyFailed | CiA 402 / EMCY failed |
PdoFailed(String) / TopologyFailed / RedundancyFailed / RegisterFailed / DiagnosticsFailed | Process data / topology / redundancy / register / diagnostics failed |
WdkFailed(String) / UdpFailed / Cancelled(String) | Real-time driver / UDP / cancellation |
NullPointer / Other(String) | Null pointer / unclassified |
When last_error of NetworkFailedWithLastError is 170 (device busy), four driver-instance LastError values can come back: 30 = RT real-time channels exhausted; 2 = the instance is still held by a live handle; 23 = the NIC is occupied by another master instance; 22 = the polling thread failed to start/rebuild. In addition, 20 = driver network initialization failure (the underlying NTSTATUS is passed through as-is) and 31 = the admission quota was exhausted, set by the polling thread after StartRT succeeded — neither of these is a 170 reply. This SDK only passes the Windows error code through and does not classify it kernel-side.
DarraError implements the Display trait, so the error description can be formatted directly with {}.
Accessors and construction
| Method / type | Returns | Purpose |
|---|---|---|
state_change_failed(target, actual_master_state, al_status_code, unreached_slaves) | DarraError | Constructs a state transition error carrying the measured values; pass None / an empty Vec for fields you do not know |
sdo_abort_code() | Option<u32> | Gets the device's raw abort code for an SDO failure (codes outside the table / vendor-private codes are returned unchanged); None = communication-level failure |
state_change_target() | Option<u8> | Gets the target state of a failed state transition; returns None for anything other than StateChangeFailed |
SlaveStateFailure | struct | Element type of unreached_slaves: slave_index / state_raw / al_status_code; construct it with new() |
actual_master_state: None means there is no reading (not initialized / cannot be read), not 「the master state is 0」; raw_abort_code == 0 means the device returned no abort code (transport-level failure), in which case abort_code is Some(SDOProtocolTimeout) — it is not abort 0.
SdoReadFailed / SdoWriteFailed use the 32-bit SDO Abort Code (CiA 301 / ETG.1020); CoEInfoFailed uses the 16-bit SDO Info ErrorCode (ETG.1000.6 table 48). The two cannot be interpreted as each other's codes; CoEInfoFailed.wkc indicates whether the innermost mailbox transaction succeeded (false = transport-level failure or the transaction was never executed).
For the meaning of the error codes and on-site troubleshooting steps see Error codes and troubleshooting.