Skip to main content

Slave properties and methods

Obtained through master.slave(n) (1-based index).​

Properties​

CategoryMethodTypeRead/writeDescription
Basic identificationindex()u16read-onlySlave index (1-based)
master_index()u16read-onlyMaster index
name()Stringread-onlyDevice name (read from EEPROM group_name)
drive_name()Stringread-onlyDrive/device name (read from SDO 0x1008)
Device informationvendor_id()u32read-onlyVendor ID (read from SII EEPROM)
vendor_name()Stringread-onlyVendor name
product_id()u32read-onlyProduct ID
rev_id()u32read-onlyRevision number
serial_number()u32read-onlySerial number (native runtime identity snapshot); 0 has three meanings — 「not read / real value 0 / read failed」; use try_get_serial_number() for the real value (see SII identity area and true serial number)
has_mdp()boolread-onlyWhether modular device profiles are supported (ETG.5001)
block_lrw()boolread-onlyLRW logical read/write blocking flag
Addressconfig_addr()u16read-onlyPhysical configuration address
alias_address()u16read-onlyAlias address
Statusstate()Option<EcState>read-onlyCurrent slave state — base state only (low 4 bits, may be read from cache). Combinations such as 0x14 / 0x18 ("base state + Error") are reported as a clean SafeOp / OP; use has_error() / state_raw() / status() to test the error bit
state_raw()u8read-onlyRaw GetSlaveState byte (including the bit4 Error bit): 0x14 = SafeOp+Error, 0x18 = OP+Error; returns 0 when it cannot be read
has_error()boolread-onlyWhether bit4 of the raw byte is set (whether the slave reported an AL Error)
status()EcSlaveStatusread-onlyNamed view of base state + Error (SafeOpFault / OpFault / …; unnamed raw values are preserved as-is)
state_live()Option<EcState>read-onlyThe base state view, same as state() — forces a real-time read, bypassing the cache
state_raw_live()u8read-onlyRaw state byte from a forced real-time read (including the Error bit)
state_live_read()LiveReadread-onlyLive state read (forces one real read) plus four-state trust; value is the raw AL Status byte (low 4 bits = base state, bit4 = Error), usable as the current state only when is_valid()
has_error_live()boolread-onlyThe Error bit from a forced real-time read
error_code()EcALStateread-onlyAL Status Code error code (real read: the full 16-bit ALstatuscode in the slave structure; reads the polled cache while in OP and refreshes with one live frame otherwise; not the high byte of al_status_mirror(); may be read from the cache). Only codes in the ETG.1020 table are listed; codes outside it fall to Unknown(0xFFFF). Use error_code_raw() for the raw value
error_code_raw()u16read-onlyRaw 16-bit AL Status Code value; codes outside the table are preserved as-is (not folded to 0xFFFF)
error_code_live()EcALStateread-onlyAL Status Code — forces a real-time read, bypasses the cache
error_code_live_read()LiveReadread-onlyLive AL Status Code (lossless 16-bit) plus four-state trust. When the slave is lost / not responding native returns 0; this entry point files it as Stale and never reports it as "no error"
error_code_raw_live()u16read-onlyLive lossless AL code raw value; 0xFFFF when untrusted (not a "no error" code)
is_lost()boolread-onlyWhether the slave is lost (confirmed offline)
liveness()SlaveLivenessStateread-onlyLiveness three-state: Alive = confirmed alive / Lost = confirmed offline / Unknown = insufficient evidence. is_lost() only answers "is it confirmed lost"; use this method to tell "insufficient evidence"
offline_reason()SlaveOfflineReasonread-onlyOffline reason classification: RealOffline = truly offline / Unreachable = not confirmed by the server — the server/probe did not see it, but the process data proves it is still contributing (not a confirmed offline) / Unknown = insufficient evidence
has_entered_operational()boolread-onlyWhether it has ever successfully entered OP during this run (event-latched; falls back to the current-cycle state when the event surface is not ready)
dropped_from_operational()boolread-onlyWhether it "entered OP but is not in OP now" (dropped out of OP at runtime)
out_of_op_duration_ms()Option<u64>read-onlyMonotonic duration the slave has continuously been out of OP (ms); None = no provable start of the out-of-OP period. System clock changes do not affect this value
out_of_op_duration()Option<std::time::Duration>read-onlyHow long it has continuously been out of OP; None has the same meaning as above
out_of_op_since_utc()Option<std::time::SystemTime>read-onlyStart of the out-of-OP period (UTC, derived from "current UTC - monotonic duration"); None has the same meaning as above
Diagnostics mirrorwc_contributed()WcContributionread-onlyThis slave's contribution state to the working counter (WKC) in the current cycle (real-time read)
input_data_validity()PdoInputValidityread-onlyFour-state validity of the input process data: Valid = this cycle's data is valid; Degraded = this cycle has no full evidence (the group's inputs are incomplete for this cycle; on a single dropped frame / WKC=0 the data is the previous valid frame (last-good); when some slaves are missing, the input bytes of the absent slave and everything downstream may be the process-image initial values established at startup, do not treat it as definitely trustworthy); Stale = cannot be used as the current value; Unknown = no evidence. Use this property to decide "can this frame of data be used"; use is_lost() to decide "has the slave been confirmed offline"
al_status_mirror()SlaveAlMirrorread-onlyAL status mirror (parsed into al_state + al_status_code + raw); a cache sampled while the master is in OP, not the live truth at read time
mailbox_healthy()boolread-onlyWhether this slave's mailbox is healthy (real-time read)
free_run_demoted()boolread-onlyWhether this slave was forced to fall back from DC to FreeRun (real-time read)
health_degraded_count()u32read-onlyConsecutive cumulative count of mailbox half-failures on this slave (≈ seconds, 0 = healthy)
Topologylink_count()i32read-onlyLink count: 1..4 = measured link count, -1 = unknown or invalid parameter (a 0 placeholder from an unread DLSTAT also counts as unknown); unknown does not mean the link is down. Measured per sample (popcount of the low 4 bits of active_ports, refreshed every 200 ms, -1 = unknown); topology() is only an alias, not a structural classification
topology_type()Option<u32>read-onlyConfiguration-time structure classification snapshot: Some(0..=4) = NoLink / EndPoint / Line / Fork / Cross; None = unavailable (no master context or a value out of range; not collapsed to 0, since 0 is the valid "no link"); written once by config_init, unchanged when a cable is unplugged, not a per-sample measurement
parent_station()u16read-onlyStation address of the parent slave
parent_port()i32read-onlyParent port number: 0..3, -1 = unknown or invalid parameter; unknown does not mean P0
entry_port()u8read-onlyEntry port number
active_ports()u8read-onlyActive-port bitmask
physical_type()u8read-onlyPhysical port type
child_count()u16read-onlyNumber of child modules
PDO datainput_bits() / output_bits()u16read-onlyInput/output data bit count
input_bytes() / output_bytes()Option<u32>read-onlyInput/output data byte count (None = the slave structure could not be read, as distinct from reading 0 bytes; the aliases ibytes() / obytes() have the same semantics)
input_offset() / output_offset()u32read-onlyInput/output offset in the IOmap
input_startbit() / output_startbit()u8read-onlyInput/output start bit
ESI/configurationhas_esi()boolread-onlyWhether an ESI file has been loaded
esi_version()Stringread-onlyESI version
config_by_esi()Result<()>write-onlyConfigure the slave automatically from the ESI file (SM + DC)
EEPROMeep_8byte_addressing()boolread-onlyEEPROM addressing mode (true = 8-byte, false = 4-byte)
eep_pdi()u8read-onlyPhysical device interface (PDI) type
ebus_current()i16read-onlyE-bus current consumption (mA)
Mailboxmbx_proto()u16read-onlySupported mailbox protocol types (MailboxType bitmask)
mbx_length()u16read-onlyMailbox send buffer size
mbx_read_length()u16read-onlyMailbox receive buffer size
mbx_read_offset() / mbx_write_offset()u16read-onlyMailbox read/write offset
mbx_count()u8read-onlyMailbox protocol counter
Protocol detailscoe_details()u8read-onlyCoE protocol feature flags (EcCoEDetails bitmask)
eoe_details()u8read-onlyEoE protocol feature flags (EcEoEDetails bitmask)
foe_details()u8read-onlyFoE protocol details (from SII EEPROM)
soe_details()u8read-onlySoE protocol details (from SII EEPROM)
FMMUfmmu0_func()u8read-onlyFMMU0 function type (bit 0 = output, bit 1 = input)
fmmu1_func()u8read-onlyFMMU1 function type
fmmu2_func()u8read-onlyFMMU2 function type
fmmu3_func()u8read-onlyFMMU3 function type
sync_manager_count()u16read-onlyNumber of SyncManagers
DChas_dc()Option<bool>read-onlyWhether the ESC hardware supports DC (None = the slave structure could not be read; not the same as no DC)
dc_active()u16read-onlyLanded value of 0x0980 (0 = DC not enabled). 0x0300 is merely a common landed value, not evidence of being armed or synchronized: check dc().dc_sync0_armed() for armed state and dc().dc_sync_window().in_sync() for synchronization
dc_cycle0()i32read-onlySYNC0 cycle (ns)
dc_cycle1()i32read-onlySYNC1 cycle (ns)
dc_shift()i32read-onlyPhase shift (ns)
dc_next()u16read-onlyIndex of the next slave in the DC chain
dc_previous()u16read-onlyIndex of the previous slave in the DC chain
dc_parent_port()i32read-onlyCompatibility entry for parent_port(); same 0..3 / -1, not another DC-specific field
dc_receive_time_a()i32read-onlyDC receive time of port A (ns)
dc_receive_time_b()i32read-onlyDC receive time of port B (ns)
dc_receive_time_c()i32read-onlyDC receive time of port C (ns)
dc_receive_time_d()i32read-onlyDC receive time of port D (ns)
propagation_delay()i32read-onlyPropagation delay of a frame from the master to this slave (ns)
Topology extensionschildren()Vec<u16>read-onlyList of child slave indices (used with child_count to navigate the topology tree)
supports_frame_repeat() / set_supports_frame_repeat(bool)boolread/writeWhether the frame repeat function is supported (ETG.1500 5.4.3, read/write)
Redundancyredundancy_activated()boolread-onlyRedundancy protection running = the same master-level criterion as redundancy_ring_mode() being Dual or Degraded (raw RingMode >= 1); always false for linear / end-return topologies, not a per-slave independent conclusion
primary_link_broken()boolread-onlyWhether the primary line is broken. The flat entry is a plain single value (anything other than 0 = broken) and does not return a tri-state: an unreadable value and an unbroken line are both false, so it is not strong evidence; when you need to distinguish "read failed", use slave.diagnostics().primary_link_broken() (Option<bool>, None = read failed)
secondary_link_broken()boolread-onlyWhether the redundant line is broken. Same semantics as above: the flat entry is a bool; the tri-state entry is slave.diagnostics().secondary_link_broken()
Configurationgroup() / set_group(u8)u8read/writeSlave group number (0-7, 0 = unassigned; automatically placed in group 1 before mapping; must be set before SAFE_OP)
is_optional() / set_optional(bool)boolread/writeOptional slave marker; when absent it does not affect the WKC check and does not trigger a group offline alarm (must be set before OP)
The two link-count entries are not interchangeable

slave.link_count() = the measured link count for the current sample, refreshed from the real DLSTAT every 200 ms; unknown / invalid parameter returns -1 and never pretends there are 0 connections. For the configuration-time topology classification (0 = NoLink / 1 = EndPoint / 2 = Line / 3 = Fork / 4 = Cross, written once by config_init, not refreshed at runtime, unchanged when a cable is unplugged) use slave.topology_type(). Do not use link_count() as a structural snapshot, and do not use topology_type() to detect an unplugged cable.

EcDeviceType enum values
#[repr(u16)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcDeviceType {
Undefined = 0, // Undefined
Static = 1, // Static device, no IO mapping, e.g. the EK1100 coupler
InputNoMailbox = 2, // Input device (no mailbox)
OutputNoMailbox = 3, // Output device (no mailbox)
InputWithMailbox = 4, // Input device (with mailbox)
OutputWithMailbox = 5, // Output device (with mailbox)
IONoMailbox = 6, // Input/output device (no mailbox)
IOWithMailbox = 7, // Input/output device (with mailbox)
}
EcTopologyType / EcPortType enum values
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcTopologyType {
NoLink = 0, // No link
EndPoint = 1, // Endpoint
Line = 2, // Middle node (linear topology)
Fork = 3, // Branch point
Cross = 4, // Crossing point
}

#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcPortType {
NotUsed = 0, // Not used
MII = 1, // MII
EBUS = 2, // EBUS
EBUSEnhanced = 3, // EBUS enhanced
}
MailboxType enum values
#[repr(u16)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MailboxType {
ErrorMailbox = 0x00, // Error mailbox
ADSOverEtherCAT = 0x01, // AoE
EthernetOverEtherCAT = 0x02, // EoE
CANopenOverEtherCAT = 0x03, // CoE
FileOverEtherCAT = 0x04, // FoE
ServoOverEtherCAT = 0x05, // SoE
VendorOverEtherCAT = 0x0F, // VoE
}
EcCoEDetails bit flags

EcCoEDetails is a u8 newtype struct (not a bitflags! macro); the flags are provided as associated constants, and contains() / union() perform bit testing and merging.

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EcCoEDetails(pub u8);

impl EcCoEDetails {
pub const NONE: Self = Self(0x00);
pub const SDO: Self = Self(0x01); // Supports SDO
pub const SDO_INFO: Self = Self(0x02); // Supports SDO Info
pub const PDO_ASSIGN: Self = Self(0x04); // Supports PDO Assign
pub const PDO_CONFIG: Self = Self(0x08); // Supports PDO Config
pub const STARTUP: Self = Self(0x10); // Supports Startup
pub const COMPLETE_ACCESS: Self = Self(0x20); // Supports Complete Access

pub fn contains(self, other: Self) -> bool;
pub fn union(self, other: Self) -> Self;
}
EcEoEDetails bit flags

EcEoEDetails is likewise a u8 newtype struct (not a bitflags! macro).

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EcEoEDetails(pub u8);

impl EcEoEDetails {
pub const NONE: Self = Self(0x00);
pub const SEND_FRAME: Self = Self(0x01); // Supports sending frames
pub const RECEIVE_FRAME: Self = Self(0x02); // Supports receiving frames
pub const SET_IP_PARAM: Self = Self(0x04); // Supports setting IP parameters
pub const GET_IP_PARAM: Self = Self(0x08); // Supports getting IP parameters

pub fn contains(self, other: Self) -> bool;
pub fn union(self, other: Self) -> Self;
}
WcContribution enum values (WKC contribution state)
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WcContribution {
NotContributed = 0, // This slave did not contribute WKC this cycle (slave loss / no response)
Contributed = 1, // This slave contributes WKC normally this cycle
Unknown = 0xFF, // No data for this slave yet — never fabricated (all other non-0/1 values fall here)
}

impl WcContribution {
pub fn from_raw(raw: u8) -> Self; // 1 => Contributed, 0 => NotContributed, anything else => Unknown
}
SlaveAlMirror struct (parsed AL status mirror view)

al_status_mirror() parses the 16-bit AL status mirror into a structured view: low byte = AL State (including the Error bit), high byte = the low 8 bits of the AL Status Code (present only when the Error bit is set and the code is not 0; codes ≥0x0100 are truncated). raw == 0 means Unknown (no sample has been taken yet / the master is not currently in OP).

This value is a cache refreshed by the master only while it is in OP; it is not the live truth at read time. When the master is not currently in OP (or no sample has been taken yet) the getter returns 0 = not sampled / unknown; only a value other than 0 is a trustworthy sample. Once the master leaves OP the sampler stops and the cache keeps its last sample, so this property no longer claims realtime behaviour.

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SlaveAlMirror {
pub al_state: EcSlaveStatus, // AL State (fully named state including the Error bit; unnamed composite values fall back to None)
pub al_status_code: u16, // low 8 bits of the AL Status Code (valid only with the Error bit; >=0x0100 truncated; 0 = no error code / Unknown)
pub raw: u16, // Raw 16-bit value (for debugging / traceback)
}

impl SlaveAlMirror {
pub fn from_raw(raw: u16) -> Self;
pub fn has_fault(self) -> bool; // whether the AL State carries the Error flag (bit4 = 0x10)
pub fn is_unknown(self) -> bool; // raw == 0 (no data yet → Unknown)
}

Sub-objects​

CategoryMethodTypeRead/writeDescription
Sub-objectscia401()CiA401read-onlyCiA 401 I/O module helper instance
coe()CoEInstanceread-onlyCoE view (SDO read/write / OD listing / asynchronous SDO)
events()SlaveEventsread-onlySlave-level events
diagnostics()SlaveDiagnosticsread-onlyDiagnostics accessor
startup()StartupParameterListread-onlyStartup parameter list
sdo_read_value::<T>()Result<T>read-onlyCoE typed read
sdo_write_value()Result<()>write-onlyCoE typed write
soe()SoEInstanceread-onlyServo over EtherCAT
foe()FoEInstanceread-onlyFile over EtherCAT
eoe()EoEInstanceread-onlyEthernet over EtherCAT
aoe()AoEInstanceread-onlyADS over EtherCAT
voe()VoEInstanceread-onlyVendor over EtherCAT
dc()SlaveDCread-onlyDC synchronization configuration

Slave-level protocol passthrough entries​

Slave keeps a set of protocol passthrough methods that are not wrapped in an instance view, all taking timeout_us (microseconds). These entries are synchronous blocking calls, and the wait limit is set by timeout_us. For the protocol instance views (with state, subscriptions and richer result types) see AoE / EoE / FoE / SoE / VoE.

AoE (ADS over EtherCAT)​

MethodReturnsDescription
aoe_read_write(index_group, index_offset, read_length, write_data, timeout_us)Result<Vec<u8>>One ADS read/write: writes write_data and fetches the read data according to read_length
aoe_read_device_info(timeout_us)Result<(u8, u8, u16, String)>Device information (major, minor, build, 设备名)
aoe_read_state(timeout_us)Result<(u16, u16)>(ADS 状态, 设备状态)
aoe_write_control(ads_state, device_state, data, timeout_us)Result<()>Writes the ADS / device state control
aoe_add_notification(index_group, index_offset, length, trans_mode, max_delay, cycle_time, timeout_us)Result<u32>Registers a notification subscription and returns the subscription handle
aoe_del_notification(handle, timeout_us)Result<()>Unregisters a notification subscription by handle
aoe_set_config(target_net_id, target_port, source_net_id, source_port)Result<()>Sets the target / source NetId and port
aoe_config()Result<([u8; 6], u16, [u8; 6], u16)>Reads back (目标 NetId, 目标端口, 源 NetId, 源端口)
aoe_send_command(target_port, command_id, command_data, timeout_us)Result<Vec<u8>>Sends a raw ADS command and returns the response payload
  • Failures uniformly return Err(DarraError::AoeFailed).
  • trans_mode takes the numeric value of AoeTransMode: 0 NoTransmission / 1 Cyclic / 2 OnChange / 3 CyclicInDevice / 4 OnChangeInDevice.
  • Read-side entries return Ok(Vec::new()) when there is no response payload, strictly distinguished from "failure".

EoE (Ethernet over EtherCAT)​

MethodReturnsDescription
eoe_set_ip(port, ip, subnet, gateway, timeout_us)Result<()>Sets IP / subnet / gateway
eoe_ip(port, timeout_us)Result<(u32, u32, u32)>Reads back (ip, subnet, gateway)
eoe_set_mac(port, mac, timeout_us)Result<()>Sets the MAC (&[u8; 6])
eoe_mac(port, timeout_us)Result<[u8; 6]>Reads back the MAC
eoe_set_dns(port, dns_ip, dns_name, timeout_us)Result<()>Sets the DNS server and name
eoe_dns(port, timeout_us)Result<(u32, String)>Reads back (dns_ip, dns_name)
eoe_full_param(port, timeout_us)Result<(u32, u32, u32, [u8; 6], u32, String)>Reads all of (ip, subnet, gateway, mac, dns_ip, dns_name) in one call
eoe_set_full_param(port, ip, subnet, gateway, mac, dns_ip, dns_name, timeout_us)Result<()>Writes all of IP / MAC / DNS in one call
eoe_send_frame(port, data, timeout_us)Result<()>Sends one raw Ethernet frame
eoe_receive_frame(port, timeout_us)Result<Vec<u8>>Receives one raw Ethernet frame
eoe_set_address_filter(port, mac_filters, filter_count, timeout_us)Result<()>Sets the MAC filter table: mac_filters is a run of 6-byte entries and filter_count is the number of entries
eoe_address_filter(port, max_filters, timeout_us)Result<(u8, Vec<u8>)>Reads the filter table, returning (条数, 连续 6 字节表项)
  • Failures uniformly return Err(DarraError::EoeFailed).
  • IP / subnet / gateway / DNS addresses are u32 in host order, with the highest byte first: 192.168.1.10 = 0xC0A8_010A.
  • port is the EoE port number (starting from 0). Ok(Vec::new()) from eoe_receive_frame() means this frame has zero payload, not a failure.

FoE (File over EtherCAT)​

MethodReturnsDescription
foe_write(filename, password, data, timeout_us)Result<()>Uploads a file
foe_read_ex(filename, password, timeout_us, options)Result<Vec<u8>>Downloads a file with CRC / strict-mode options
foe_write_ex(filename, password, data, timeout_us, options)Result<()>Uploads a file with CRC / strict-mode options
Slave::foe_set_progress_hook(master_index, callback)Result<()>Registers a progress callback (associated function, registered per master, no slave handle needed)
Slave::foe_clear_progress_hook(master_index)Result<()>Unregisters the progress callback (associated function)
  • options is &mut FoEOptions; the main fields are enable_crc / strict_mode / auto_append_crc / expected_crc, plus the progress callback and its userdata.
  • A transfer failure returns Err(DarraError::FoeFailed(filename)); a filename containing a NUL byte returns Err(DarraError::InvalidParameter). Failure to register / unregister the progress callback returns Err(DarraError::Other).

SoE (Servo over EtherCAT) metadata​

MethodReturnsDescription
soe_read_name(idn, drive_no, timeout_us)Result<String>Reads the IDN name
soe_read_unit(idn, drive_no, timeout_us)Result<String>Reads the IDN unit
soe_read_min_max(idn, drive_no, timeout_us)Result<(Vec<u8>, Vec<u8>)>Reads the raw bytes of the IDN minimum / maximum
soe_read_attributes(idn, drive_no, timeout_us)Result<u32>Reads the IDN attribute bits
soe_read_idn_list(drive_no, timeout_us)Result<Vec<u16>>Reads the list of IDNs supported by that drive
  • Failures return Err(DarraError::SoeFailed(idn)); when soe_read_idn_list() fails, the IDN carried by that error is 0.
  • When the name / unit is empty or too short, an empty string is returned; when the minimum / maximum is missing, the corresponding position gives Ok(Vec::new()).

VoE (Vendor over EtherCAT)​

MethodReturnsDescription
voe_receive(timeout_us)Result<(u32, u16, Vec<u8>)>Receives one vendor frame: (vendor_id, vendor_type, 负载)

Failures return Err(DarraError::VoeFailed); for support see voe_is_supported() under "Protocol support detection", and the send side uses the slave.voe() instance.

Enum descriptions​

There are two ways to get a Chinese description of an enum: enums that implement Display can be printed directly with println!("{}", value); others provide .description() to fetch the description string explicitly. Common usage:

use darra_ethercat::EcState;
// Description helpers live in the statics module (not re-exported at the crate root)
use darra_ethercat::statics::{cia402_state_description, cia402_mode_description};

// EcState formatting
let state = slave.state().unwrap_or(EcState::None); // on read failure fall back to None instead of panicking
println!("{}", state); // Display trait: "OP"

// CiA 402 state description (standalone function)
let desc = cia402_state_description(4); // "运行使能" (the runtime returns Chinese)
let mode_desc = cia402_mode_description(8); // "周期同步位置 (CSP)" (the runtime returns Chinese)
Uniform convention

Enums that provide .description(): StateCiA402 / ModeCiA402 / Cia402ReadStatus. All other enums (EcState / EcPortType / EcDeviceType / WcContribution, etc.) use Display; EcALState's Display is supplied by the sugar module; SDOError has neither, so map the raw value yourself when you need a Chinese label.

EcSlaveStatus helper methods​

Besides the enum values, EcSlaveStatus (the parsed result of the low byte of the AL status mirror) provides three display / test helpers: Unnamed composite values are not folded: bytes such as 0x1A / 0x15 / 0x09 go into Unknown(raw) unchanged, and None only means a real read of 0x00.

impl EcSlaveStatus {
pub fn from_raw(raw: u8) -> Option<Self>; // Lossless: named variants for values in the table, Some(Unknown(raw)) for unnamed values
pub fn raw(self) -> u8; // Raw byte (including the Error bit)
pub fn base_state(self) -> EcState; // Base state with the Error bit stripped
pub fn has_fault(self) -> bool; // Whether the Error bit is set
pub fn is_op(self) -> bool; // true only in OP
pub fn pretty(self) -> &'static str; // fixed English label
}
MethodReturnsDescription
from_raw()Option<EcSlaveStatus>Named variants for the combinations in the table (0x00..0x18); unnamed values give Some(Unknown(raw)). Every input returns Some, never None (Option is only there for signature compatibility; the raw value is never lost)
raw()u8Raw AL status byte (including the bit4 Error bit); Unknown(raw) carries the raw value back
base_state()EcStateTakes the low 4 bits as the base state; InitFault → Init, OpFault → OP, and unknown combinations fall back to EcState::None
has_fault()boolraw() & 0x10 != 0; OpFault / SafeOpFault are true, a clean OP / SafeOp is false
is_op()boolReturns true only for OP; OpFault / SafeOp / other levels are all false
pretty()&'static strFixed English label; fault levels carry a suffix such as (Init+Error); Unknown(raw) is "Unknown" — use Display (which prints Unknown(0x1A)) or raw() for the raw value
let mirror = slave.al_status_mirror();
println!("{}", mirror.al_state.pretty()); // e.g. "OpFault (OP+Error)"
println!("{}", mirror.al_state.base_state()); // Base state
println!("0x{:02X}", mirror.al_state.raw()); // Raw byte, including the Error bit
if mirror.al_state.is_op() {
// Only a normal OP gets here; OpFault does not count
}

Hardware information queries​

fmmus()​

pub fn fmmus(&self) -> Vec<u8>

Get the slave's raw FMMU configuration data (fmmu_buffer in the slave structure, 4 entries x 16 bytes), for debugging or diagnosing address mapping problems.

sync_managers()​

pub fn sync_managers(&self) -> Vec<u8>

Get the slave's raw SyncManager configuration data (sm_buffer in the slave structure, 8 entries x 8 bytes).

sync_manager_types()​

pub fn sync_manager_types(&self) -> Vec<u8>

Get the slave's SyncManager type array (8 bytes, the type of each of the 8 SMs).

Returns:

  • Vec<u8> — Type array: 0 = unused, 1 = mailbox output, 2 = mailbox input, 3 = process data output, 4 = process data input

Diagnostics​

tip

Slave diagnostics (communication error rate, redundancy state, DC synchronization) are accessed through slave.diagnostics().

PdoInputValidity — input data validity​

slave.input_data_validity() answers "can this frame of input data be used as the current value", which is a different fact from "has the slave been confirmed offline" (slave.is_lost()).

ValueWhat you seeRecommended use
ValidThis cycle's PDO exchange was complete; the input image is the current valueUse normally
DegradedThis cycle has no full evidence: the group's inputs are incomplete for this cycle. On a single dropped frame / WKC=0 the data is the previous valid frame (last-good); when some slaves are missing, the input bytes of the absent slave and everything downstream may be the process-image initial values established at startup, not the last valid valueDo not treat this as "the data is definitely trustworthy": either wait for recovery, or cross-check is_lost() / offline_reason() / input_data_validity() to see which slaves are untrustworthy. It turns Stale only after N full cycles without recovery (N is computed from the group cycle and the slave watchdog)
StaleThe input image cannot be used as the current value (WKC short / no frame this cycle / slave lost / exchange stalled)Do not use as a live value; take the safe fallback
UnknownNo evidence (no input PDO / group expectation not established / never exchanged / read failed)Unknown is not valid; treat it as unavailable

A read failure / out-of-range index / an older runtime without this capability returns Unknown (fail-closed).

Note: the native-side comment still says "three-state / degradation pending", which is stale text awaiting sync in the native domain; the public SDK contract is the four states in this section.

diagnostics.stale_input_count() counts only slaves confirmed Stale; it does not count while Degraded applies.

ESI methods​

The choice of ESI file/directory is made at master build time: MasterBuilder::set_esi_file(path) (see Initialization). The Rust SDK does not expose EsiLoader / slave.esi() (the parsing surface is not part of the public contract).

config_by_esi()​

pub fn config_by_esi(&self) -> Result<()>

Configure this slave automatically from the loaded ESI (SM + DC). Failure returns Err(DarraError::Other).

Example:

slave.config_by_esi()?;

For read-only ESI state use has_esi() / esi_version() in the properties table; for DC modes see Slave DC.

configure_from_esi()​

pub fn configure_from_esi(&self) -> Result<()>

Configure this slave automatically from the loaded ESI (SyncManager mapping). It is the same call chain as config_by_esi() and both behave identically (config_by_esi() calls this method internally). Failure returns Err(DarraError::Other).

slave.configure_from_esi()?;

Process data watchdog​

set_watchdog(timeout_ms)​

pub fn set_watchdog(&self, timeout_ms: u32) -> Result<()>

Set the slave's process data watchdog timeout. The slave raises a watchdog error (ALStatusCode 0x001B) when it does not receive a process data frame within the timeout.

Parameters:

  • timeout_ms (u32) — Timeout (ms), 0 = disabled, maximum 6553 ms

Returns (reported faithfully from the underlying write result, tri-state mapping):

  • Ok(()) — Written with the requested value
  • Err(DarraError::InvalidParameter) — Request exceeds the 0–6553 ms register limit, rejected and not written (the error message states the out-of-range limit and the requested value)
  • Err(DarraError::Other) (message contains "requested Xms, actual Yms") — The requested value was raised to the safety floor and written (branch slaves 5000 ms / PDO slaves on a ring 400 ms, as required by the topology protocol); the actual value ≠ the requested value, so plan against the value actually issued
  • Other Err(DarraError::Other) — Write failed / invalid index (the message carries the GetLastError code)
Failure-cause detection is reliable

Failure-cause detection for the watchdog write binds "clear the error code before the call + read it after the call" into one atomic action with no other system call in between — the tri-state mapping above is reliable, and the error code cannot be clobbered by another call.

note

Call this in SafeOp or OP state.

set_pdi_watchdog(timeout_ms)​

pub fn set_pdi_watchdog(&self, timeout_ms: u32) -> Result<()>

Set the slave PDI watchdog timeout. The PDI watchdog monitors whether the slave's local application (microcontroller firmware) is running normally.

Parameters:

  • timeout_ms (u32) — Timeout (ms), 0 = disabled, maximum 6553 ms

Returns:

  • Ok(()) — Written with the requested value
  • Err(DarraError::InvalidParameter) — Request exceeds the 0–6553 ms register limit, rejected and not written
  • Err(DarraError::Other) — Write failed / invalid index
Different semantics from set_watchdog

The PDI channel has no safety-floor raise step: the only outcomes are 「written with the requested value / rejected and not written for exceeding the 6553 ms limit / write failed」. "Raised to the safety floor and written" never happens, so the semantics are not equivalent to set_watchdog.

Example:

slave.set_pdi_watchdog(100)?;  // PDI watchdog with a 100 ms timeout
slave.set_pdi_watchdog(0)?; // disable the PDI watchdog

watchdog_config()​

pub fn watchdog_config(&self) -> Result<WatchdogConfig>

Read the slave's current watchdog configuration. A read failure returns Err.

Returns:

  • Result<WatchdogConfig> — Watchdog configuration

Related structures:

pub struct WatchdogConfig {
pub wd_divider: u16, // Watchdog divider
pub wd_time_pdi: u16, // PDI watchdog timeout value (divider units)
pub wd_time_pd: u16, // Process data watchdog timeout value (divider units)
}

Example:

if let Ok(config) = slave.watchdog_config() {
println!("PD超时: {} × {:.2}us", config.wd_time_pd, config.wd_divider as f64 * 0.04); // PD timeout: {} × {:.2}us
}

watchdog_status()​

pub fn watchdog_status(&self) -> Option<WatchdogStatus>

Read the slave's watchdog run status. None = the whole call failed (no field was obtained).

Once you have the struct, whether each field is trustworthy depends only on valid_mask: if the corresponding bit is not set, that register failed to read this time and the struct only holds a placeholder (0 or the 0xFF sentinel), not the device's real value. Read fields individually with status_byte() / counter() / divider() / time_pd() / counter_pdi(); they return None for missing fields.

Semantics of bit0 in 0x0440: 0 = the watchdog has overflowed/expired, 1 = the watchdog is healthy or not enabled. 0x0442 / 0x0443 are watchdog overflow counters (write 0 to reset, reads do not clear), which are not the same thing as the status bit in 0x0440.

Related structures:

pub struct WatchdogStatus {
pub wd_status: u8, // 0x0440 SM watchdog status byte (0xFF sentinel written on read failure)
pub wd_counter: u8, // 0x0442 watchdog overflow counter
pub wd_divider: u16, // 0x0400 current divider value
pub wd_time_pd: u16, // 0x0420 current process data watchdog value
pub wd_counter_pdi: u8, // 0x0443 PDI watchdog overflow counter
pub valid_mask: u16, // Field validity bit set (WD_STATUS_VALID_*)
}

impl WatchdogStatus {
pub fn is_valid(&self, mask: u16) -> bool; // whether all bits in mask are set
pub fn is_complete(&self) -> bool; // whether all 5 fields were read successfully
pub fn missing_mask(&self) -> u16; // mask of fields that failed to read this time (0 = all valid)
pub fn status_byte(&self) -> Option<u8>; // 0x0440; None = read failed this time
pub fn counter(&self) -> Option<u8>; // 0x0442; None = read failed this time
pub fn divider(&self) -> Option<u16>; // 0x0400; None = read failed this time
pub fn time_pd(&self) -> Option<u16>; // 0x0420; None = read failed this time
pub fn counter_pdi(&self) -> Option<u8>; // 0x0443; None = read failed this time
}

Related constants:

  • WD_STATUS_VALID_STATUS (0x0001, Bit 0) — The 0x0440 status byte was read successfully this time
  • WD_STATUS_VALID_COUNTER (0x0002, Bit 1) — The 0x0442 counter was read successfully this time
  • WD_STATUS_VALID_DIVIDER (0x0004, Bit 2) — The 0x0400 divider was read successfully this time
  • WD_STATUS_VALID_TIME_PD (0x0008, Bit 3) — The 0x0420 process data watchdog value was read successfully this time
  • WD_STATUS_VALID_COUNTER_PDI (0x0010, Bit 4) — The 0x0443 PDI counter was read successfully this time
  • WD_STATUS_VALID_ALL (0x001F) — Combined validity bits of the five fields

WATCHDOG_STATUS_UNKNOWN (u8 = 0xFF) is the sentinel written on read failure, not a measured value. New code should decide from valid_mask rather than comparing against the sentinel.

Example:

if let Some(status) = slave.watchdog_status() {
match status.status_byte() {
Some(raw) if (raw & 0x01) == 0 => {
println!("看门狗过期! 计数: {:?}", status.counter()); // Watchdog expired! count: {:?}
}
Some(_) => println!("看门狗正常"), // Watchdog OK
None => println!("0x0440 本次读失败 (valid_mask 未置位)"), // 0x0440 read failed this time (valid_mask not set)
}
if !status.is_complete() {
println!("未读到的字段掩码: 0x{:04X}", status.missing_mask()); // Unread field mask: 0x{:04X}
}
}

watchdog_state()​

pub fn watchdog_state(&self) -> WatchdogState

Tri-state verdict for 0x0440, driven by WatchdogStatus::valid_mask:

  • The WD_STATUS_VALID_STATUS bit is not set (or the whole call failed) → WatchdogState::Unknown
  • Status byte read → verdict Healthy / Expired from bit0 (some devices also return 0 while healthy; combine with the 0x0442 counter and the AL state)

Related structures:

pub enum WatchdogState {
Healthy, // bit0 = 1: healthy or not enabled
Expired, // bit0 = 0: overflowed/expired (some devices also return 0 while healthy)
Unknown, // register unreadable (0xFF sentinel / valid_mask bit not set)
}

impl WatchdogState {
pub fn from_raw(wd_status: u8) -> Self; // byte-level entry (0xFF = unknown)
pub fn from_status(status_byte: Option<u8>) -> Self; // None = read failed → Unknown
}
match slave.watchdog_state() {
WatchdogState::Healthy => println!("看门狗正常"), // Watchdog OK
WatchdogState::Expired => println!("看门狗已过期"), // Watchdog has expired
WatchdogState::Unknown => println!("看门狗状态未知 (读不到)"), // Watchdog state unknown (could not be read)
}

State switching​

The slave state machine exposes exactly 1 public API: set_state, which performs a state transition for a single slave synchronously; the protocol layer walks the intermediate states automatically per the EtherCAT standard state machine. The failure cause is returned through Result::Err.

set_state()​

pub fn set_state(&self, state: EcState, timeout_ms: u32) -> Result<(), DarraError>

Switch a single slave to the target state, blocking the calling thread until it completes or times out. Use it to recover a single slave manually, to reconnect a slave after hot-plug, or to move a single slave to PreOp / Init for maintenance while PDO is running.

Parameters:

  • state (EcState) — Target state
  • timeout_ms (u32) — Per-step timeout (ms); 3000 ~ 5000 recommended

Returns:

  • Ok(()) — state was reached
  • Err(DarraError::StateChangeFailed { target, actual_master_state, al_status_code, unreached_slaves }) — Transition failed (timeout / AL refusal, etc.). The slave-level entry puts this slave's measured state and AL code into unreached_slaves, and actual_master_state records this slave's measured state byte; it no longer carries only the target state
note

State switching follows the standard EtherCAT state machine; the protocol layer handles the intermediate states automatically. For example, switching from Init to OP passes through PreOp → SafeOp → OP automatically.

Example:

// manually recover a single slave to OP
if slave.state() != Some(EcState::Operational) {
slave.set_state(EcState::Operational, 5000)?;
}

// switch the slave to Init (reset)
slave.set_state(EcState::Init, 5000)?;

State reads — state() / state_raw() / has_error() / status()​

pub fn state(&self) -> Option<EcState>   // Base state (low 4 bits, possibly read from cache)
pub fn state_raw(&self) -> u8 // native raw bytes, including the bit4 Error bit
pub fn has_error(&self) -> bool // raw & 0x10 != 0
pub fn status(&self) -> EcSlaveStatus // Named view of base state + Error

state() returns only the low 4-bit base state. EcState is a closed enum and cannot represent the AL Error bit, so 0x14 (SafeOp+Error) and 0x18 (OP+Error) are both reported as SafeOp / OP without the error. Whether a slave is genuinely healthy cannot be judged from state() alone:

// Approach one: look at the base state and the Error bit separately
if slave.state() == Some(EcState::Operational) && !slave.has_error() {
// Truly clean OP
}

// Approach two: take the composite state directly (unnamed raw values are kept as-is in Unknown(raw))
match slave.status() {
EcSlaveStatus::OP => { /* Clean OP*/ }
EcSlaveStatus::OpFault => {
println!("OP + Error, AL Status Code = 0x{:04X}", slave.error_code_raw());
}
other => println!("{}", other), // e.g. SafeOpFault (SafeOp+Error)
}

The AL Status Code has two entry points: error_code() is an enum view that only lists codes in the ETG.1020 table; out-of-table codes (for example a vendor-specific 0x0038) land in Unknown(0xFFFF), the same value as "no code"; error_code_raw() gives the 16-bit raw value directly (out-of-table codes kept unchanged). Use the latter for numeric comparison and logging.

All of the reads above use the cached view; for the truth "right now" use state_raw_live() / has_error_live() / error_code_live() (see the next section).

Live state reads — state_live() / error_code_live()​

pub fn state_live(&self) -> Option<EcState>
pub fn state_raw_live(&self) -> u8 // Raw byte (including the Error bit), forced live read
pub fn state_live_read(&self) -> LiveRead // Live state read (raw byte) + four-state trust
pub fn has_error_live(&self) -> bool // The Error bit read live
pub fn error_code_live(&self) -> EcALState
pub fn error_code_live_read(&self) -> LiveRead // Live AL code (lossless 16-bit) + four-state trust
pub fn error_code_raw_live(&self) -> u16 // Live lossless AL code; 0xFFFF when untrusted

state() / error_code() may read from the runtime-maintained state cache (refreshed each cycle, suitable for high-frequency UI polling). state_live() / error_code_live() bypass the cache and issue one live probe per call — for latency-sensitive cases such as confirming immediately after a state transition or detecting hot-plug.

The return types are still enums: state_live() returns Option<EcState> (base state only again — look at has_error_live() / state_raw_live() for the Error bit), and error_code_live() returns EcALState (the enum view only lists in-table codes; out-of-table codes fall to Unknown, use error_code_raw() for the raw value).

Example:

// confirm with the live API right after the transition; do not wait for the cache to refresh
slave.set_state(EcState::Operational, 5000)?;
if slave.state_live() != Some(EcState::Operational) {
println!("从站未进 OP, AL 错误码: {}", slave.error_code_live()); // Slave did not enter OP, AL error code: {}
}
When to use the live API
  • state() / error_code() — UI refresh, periodic inspection; uses the cache with zero extra frame overhead.
  • state_live() / error_code_live() — Post-transition confirmation, fault diagnostics; needs the truth "right now".
  • Check the Error bit — neither state() nor state_live() carries the Error bit; pair them with has_error() / has_error_live(), or use status() directly to get SafeOpFault / OpFault.

Live-read four states (LiveRead)​

state_live_read() / error_code_live_read() return LiveRead: the raw value plus an evidence level. Only a value that passes is_valid() (that is, validity == LiveReadValidity::Valid) may be used as the current value; the other three states must never be taken as "this is how it is right now".

ValueMeaningUsable as the current value
Unknown(0)No usable read (call failed / old library missing the entry point / invalid handle)No. Unknown != normal
Valid(1)This measurement produced a result usable as the current valueYes
Stale(2)A value was obtained, but it is confirmed not current (the lower layer uses 0 as a placeholder when the slave is lost / not responding)No, this is a residual value
Degraded(3)A value was obtained, but only partial evidence is available (liveness state / probe unreadable or unknown)Not as confirmation

Live state criterion: 0 / 0xFF / low 4 bits are 0 -> Unknown; otherwise -> Valid. value keeps the bit4 Error bit; to test the Error bit use has_error_live() or look at the raw byte.

Live AL code criteria:

VerdictTriggervalue
UnknownThe call failed, or it returned 0xFFFF (the unavailable sentinel)0xFFFF
DegradedThe liveness state / probe read failedRaw code
Staleis_lost() is true, or the probe confirms no responseRaw code (residual)
DegradedProbe evidence is insufficient (unknown)Raw code
Validis_lost() is false and the probe confirms the slave is onlineRaw code
A lost slave is not "no error"

The lower layer returns 0 for a lost / non-responding slave; that 0 is the "no data" placeholder, not "no error". error_code_live_read() uses the liveness state and probe evidence to file it as Stale; the convenience entry points error_code_live() / error_code_raw_live() give Unknown / 0xFFFF. Never read 0 / 0xFFFF as "the device confirmed no fault".

The AL mirror (al_status_mirror()) carries only the low 8 bits of the code, and codes >= 0x0100 are truncated; for the full 16-bit code always use error_code_raw() or the lossless entry point in this section.

ESM timeouts and error acknowledgement​

State transition (ESM) timeouts are stored per slave in milliseconds, with eight fields mapping one-to-one to a transition:

pub struct EsmTimeouts {
pub ip: u32, // Init → PreOp
pub ps: u32, // PreOp → SafeOp
pub so: u32, // SafeOp → OP
pub os: u32, // OP → SafeOp
pub sp: u32, // SafeOp → PreOp
pub pi: u32, // PreOp → Init
pub bi: u32, // Init → Boot (Any → Boot)
pub ib: u32, // Boot → Init
}
MethodReturnsDescription
esm_timeouts()Result<EsmTimeouts>Reads this slave's current timeouts: if a manual override exists it returns the override values, otherwise the ETG.1020 default table
set_esm_timeouts(&EsmTimeouts)Result<()>Writes per-slave override values; all eight fields at 0 = revoke the override, and reads then fall back to the default table
set_error_ack(bool)Result<()>Sets / clears the Error Indication Acknowledge bit of AL Control (0x0120) (ETG.1500 5.3.3)

esm_timeouts() / set_esm_timeouts() return Err(DarraError::Other) when the master or slave index is unavailable or the read fails.

set_error_ack() returns Err(DarraError::Other) when the slave does not really respond or the AL Control write fails. For a slave in OP, it first brings that slave to SafeOp (or an OP already confirmed sound) before setting the bit, and returns Ok(()) only when that convergence succeeded and the Error bit is cleared.

Override values affect only the read side

set_esm_timeouts() stores a per-slave override table and does not change the wait parameters of the master's own state transitions; writing all 0s revokes the override.

Diagnostics mirror​

wc_contributed() / mailbox_healthy() / free_run_demoted() / health_degraded_count() all return the current live value: each call reads the state at that moment directly, sends and receives no frames, does no second-level caching, and needs no manual refresh. al_status_mirror() is not in that category. This value is a cache refreshed by the master only while it is in OP; it is not the live truth at read time. When the master is not currently in OP (or no sample has been taken yet) the getter returns 0 = not sampled / unknown; only a value other than 0 is a trustworthy sample. Once the master leaves OP the sampler stops and the cache keeps its last sample, so this property no longer claims realtime behaviour.

WKC contribution semantics​

wc_contributed() reflects whether this slave is actually responding right now:

  • Contributed — This slave contributes the working counter (WKC) normally, that is, when the aggregate WKC is complete (actual == expected, i.e. the deficit WcDeficit == 0), every slave's per-byte comparison is "full".
  • NotContributed — This slave is not contributing WKC right now (suspected slave loss / hot-plug recovery in progress). This is not a master fault; once the slave recovers, the mirror returns to Contributed on its own.
  • Unknown — No data for this slave yet (PDO cycle not running / index out of range); exposed honestly, never fabricated as "contributed".
Reliability contract

This interface only "reflects bus reality as it is" and takes part in no WKC tampering / accommodation logic. The per-slave contribution bit is the per-slave decomposition of the aggregate WKC deficit (expected - actual): if the aggregate is full the slave contributed; a deficit greater than 0 means some slave is not contributing right now, which calls for an alarm + diagnostics, not a lower expected and not stopping OP.

Example:

for i in 1..=master.slave_count() {
let slave = master.slave(i);
if slave.wc_contributed() == WcContribution::NotContributed {
let al = slave.al_status_mirror();
println!("从站 {} 此刻未贡献 WKC(疑似掉站),AL Code=0x{:04X}", i, al.al_status_code); // Slave {} is not contributing to WKC right now (suspected slave loss), AL Code=0x{:04X}
}
if !slave.mailbox_healthy() {
println!("从站 {} 邮箱半失效, 已持续 {}s", i, slave.health_degraded_count()); // Slave {} mailbox partially failing, for {}s
}
}

recover_mailbox_health()​

pub fn recover_mailbox_health(&self) -> bool

Manually trigger mailbox half-failure recovery for this slave. Normally there is no need to call it — a half-failure repairs itself after about 3 seconds. Returns true = the recovery flow was triggered. This is an explicit maintenance action, not a silent mask.

recover_to_op()​

pub fn recover_to_op(&self) -> Result<Option<EcState>>

Bring this slave back to OP through the INIT→…→OP state machine (legitimate hot-plug recovery) and return the state reached after recovery. The PDO cycle keeps running while a single slave recovers.

Returns:

  • Ok(Some(state)) — State reached after recovery
  • Ok(None) — Did not reach a definite state
  • Err(..) — The call failed

Example:

match slave.recover_to_op()? {
Some(EcState::Operational) => println!("已恢复到 OP"), // Recovered to OP
Some(other) => println!("恢复后停留在 {}", other), // Remains at {} after recovery
None => println!("未能恢复到明确状态"), // Failed to recover to a definite state
}

Identity verification and online status​

MethodReturnsDescription
verify_identity(&SlaveIdentity, check_rev, check_serial)boolIdentity check: vendor_id + product_code are always checked, check_rev additionally checks the revision number, check_serial additionally checks the serial number
is_op_only()boolWhether this slave has the OpOnly flag set (outputs are valid only in OP, ETG.1500 5.3.4)
is_device_emulation()boolWhether this slave has the device emulation flag set (SII General category bit 8)
mailbox_health()MailboxHealthMailbox health tri-state: Healthy / Degraded (in OP but half-failed) / Unknown
path_covers()Option<PathCovers>Whether this slave falls in the expected coverage set of the primary / secondary leg; None = the coverage set is not available
p1_foldback_only()i321 = reachable only through the foldback window; 0 = not a branch slave or not calibrated; -1 = invalid index
topology_info()SlaveTopologyBuilds a master-level topology snapshot (rebuilt on every call), then queries it by slave index
pub fn verify_identity(&self, expected: &SlaveIdentity, check_rev: bool, check_serial: bool) -> bool
pub fn mailbox_health(&self) -> MailboxHealth
pub fn path_covers(&self) -> Option<PathCovers>
pub fn p1_foldback_only(&self) -> i32
pub fn topology_info(&self) -> SlaveTopology

verify_identity() is a plain bool entry (it does not return Result): it compares against the identity tuple that was already read at configuration time and issues no extra bus read; false covers both "a field does not match" and "the slave index is unavailable". When you need to distinguish the actual read values, use identity() and compare yourself.

MailboxHealth reflects only the verdict at this moment: Degraded = in OP but the mailbox is half-failed, Unknown = no mailbox or not in OP (the verdict is meaningless then). The boolean shortcut is mailbox_healthy() in the properties table.

is_op_only() / is_device_emulation() return false when the slave index cannot be resolved; when is_device_emulation() fails to read the SII General word it likewise returns "not set" and logs it — the false there means "not confirmed", not strong evidence that it is definitely absent.

pub struct PathCovers {
pub primary: bool, // Within the primary leg's expected coverage set
pub secondary: bool, // Within the secondary leg's expected coverage set
}

The SlaveTopology returned by topology_info() covers the whole bus, not just the current slave: nodes() / count() / root_slaves() / children(parent) / get(slave_index) / get_by_address("0x03E9"). It is a one-shot snapshot, so fetch it again after the topology changes.

MethodReturnsDescription
read_port_error_counters()Option<([u8; 4], [u8; 4], [u8; 4])>Four-port register snapshot (rx_error, invalid_frame, lost_link); None = read failed and must not be taken as "no errors"
reset_port_error_counters()boolClears this slave's port error counters
port_error_stats()Result<PortErrorStats>Complete values of the register snapshot plus the lifetime accumulation
port_error_accumulated()Result<PortErrorAccumulated>Takes only the three 32-bit lifetime accumulations; a failure returns Err rather than collapsing to all 0s
pub fn read_port_error_counters(&self) -> Option<([u8; 4], [u8; 4], [u8; 4])>
pub fn reset_port_error_counters(&self) -> bool
pub fn port_error_stats(&self) -> Result<PortErrorStats>
pub fn port_error_accumulated(&self) -> Result<PortErrorAccumulated>

The arrays are ordered by port P0..P3. The register snapshots are 8-bit hardware counters (saturating at 255 / wrapping); for long-term trends use the 32-bit acc_* accumulations (struct excerpt, internal baseline fields not listed):

pub struct PortErrorStats {
pub rx_error: [u8; 4], // 0x0300 register snapshot
pub invalid_frame: [u8; 4], // 0x0308 register snapshot
pub lost_link: [u8; 4], // 0x0310 register snapshot
pub fwd_rx_error: [u8; 4], // Forwarded RX error snapshot
pub acc_rx_error: [u32; 4], // Lifetime accumulation (wrap-aware)
pub acc_invalid_frame: [u32; 4],
pub acc_lost_link: [u32; 4],
}

impl PortErrorStats {
pub fn acc_baseline_valid(&self) -> bool; // false = the cumulative baseline is not established yet
}

pub struct PortErrorAccumulated {
pub invalid_frame: u32,
pub rx_error: u32,
pub forwarded_error: u32,
}

port_error_stats() returns Err(DarraError::RegisterFailed) when the snapshot is unavailable; port_error_accumulated() reports the same Err(DarraError::RegisterFailed) and does not return a struct of all 0s.

PortErrorStats cannot currently be imported by name

In the current version PortErrorStats is not exported at the crate root (its module is not public). The return value is still usable: catch the value of port_error_stats() with type inference, then read the fields or call acc_baseline_valid() directly; but you cannot use darra_ethercat::PortErrorStats, nor write it into your own type signatures. Copy the fields you need if you have to keep them long-term.

Protocol support detection​

MethodReturnsDescription
supports_coe()boolWhether CoE is supported
supports_eoe()boolWhether EoE is supported
supports_foe()boolWhether FoE is supported
supports_soe()boolWhether SoE is supported
supports_aoe()boolWhether AoE is supported
voe_is_supported()boolWhether VoE is supported

The criterion is the protocol types declared by this slave's mailbox (MailboxType), not the SII bitmap and not the SyncManager communication type; when the slave index is unavailable they all return false.

if slave.supports_aoe() {
println!("ADS over EtherCAT 可用"); // ADS over EtherCAT available
}
if slave.supports_soe() {
println!("Servo over EtherCAT 可用"); // Servo over EtherCAT available
}
Protocol instances

For the protocol instance entries see the "Sub-objects" table (slave.coe() / slave.eoe() / slave.foe() / slave.soe() / slave.aoe() / slave.voe()); this section only answers "whether this slave declares support for that protocol".

ESC register access (advanced)​

Read and write slave ESC (EtherCAT Slave Controller) registers directly, for fault diagnostics, custom ESC operations and register-level debugging. The protocol layer uses FPRD/FPWR datagrams with automatic primary → secondary → APWR three-level fallback.

Advanced API

No calls are needed during normal SDK use — state transitions / PDO / mailbox flows configure registers automatically. This API is for deep diagnostics and special cases (for example reading error counters, forcing port policy, or debugging an ESI write that does not take effect).

Register definitions are in ETG.1000.4 §6 / ETG.1000.6 §5 (public standards), for example:

RegisterDescription
0x0000Type / Revision / Build (device type)
0x0030AL Control (the master initiates a state request)
0x0130AL Status (current slave state)
0x0134AL Status Code (error code)
0x0300-0x030FPort 0-3 error counters
0x0400-0x043FWatchdog configuration / counters
0x0440-0x0443SM watchdog status / overflow counters: 0x0440 bit0 (0 = overflowed/expired, 1 = healthy or not enabled; 0xFF = read failure/unknown); writing 0 to 0x0442/0x0443 resets them, reads do not clear

read_register(reg_addr, len)​

pub fn read_register(&self, reg_addr: u16, len: u32) -> Result<Vec<u8>>

Read a slave ESC register (FPRD).

Parameters:

  • reg_addr (u16) — Register address (e.g. 0x0130 = AL Status)
  • len (u32) — Number of bytes to read (1 / 2 / 4, etc.)

Returns:

  • Result<Vec<u8>> — Bytes on success; Err on failure (slave offline / timeout)

write_register(reg_addr, data)​

pub fn write_register(&self, reg_addr: u16, data: &[u8]) -> Result<()>

Write a slave ESC register (FPWR).

Parameters:

  • reg_addr (u16) — Register address
  • data (&[u8]) — Data to write

Returns:

  • Result<()> — Ok(()) on success

Example:

let slave = master.slave(1);

// read AL Status (0x0130, 2 bytes)
let al_status = slave.read_register(0x0130, 2)?;
let state = u16::from_le_bytes([al_status[0], al_status[1]]);
println!("AL Status = 0x{:04X} (state={}, err={})",
state, state & 0x0F, (state & 0x10) != 0);

// read AL Status Code (0x0134, error code)
let al_code = slave.read_register(0x0134, 2)?;
let code = u16::from_le_bytes([al_code[0], al_code[1]]);
println!("AL Status Code = 0x{:04X}", code);

// write AL Control = 0x04 (request SafeOp)
slave.write_register(0x0030, &[0x04, 0x00])?;

EEPROM (SII) access​

Read and write the slave SII EEPROM (Slave Information Interface, ETG.1000.6 §6). The EEPROM stores device identity and configuration such as vendor_id / product_code / revision_no / serial_no / SyncManager / FMMU / PDO mapping / Strings. The SDK already reads it automatically during config_init, so applications normally need no direct access.

Dangerous operation

Use EEPROM writes with care — a bad write can corrupt the slave's identity information and in the worst case permanently brick the slave, requiring vendor tools to recover. Use it only for:

  • Burning an alias address (ESC 0x0012)
  • Repairing factory data that was overwritten by mistake
  • Vendor-authorized firmware / parameter flashing

EEPROM writes require the slave to be in Init / PreOp state; writes are refused in OP.

EEPROM size is typically 1 KB - 16 KB (word-addressed, 1 word = 2 bytes). The first 8 words hold basic vendor information, followed by the category list (Strings / General / FMMU / SyncM / TxPdo / RxPdo / DC / End=0xFFFF).

read_eeprom(byte_offset, byte_length)​

pub fn read_eeprom(&self, byte_offset: u16, byte_length: u16) -> Result<Vec<u8>>

Read a byte range of the slave SII EEPROM (looping over words). The SDK handles BUSY polling and word alignment automatically; applications should prefer this high-level API.

Parameters:

  • byte_offset (u16) — Start byte offset (even alignment recommended)
  • byte_length (u16) — Number of bytes to read (even recommended)

Returns:

  • Result<Vec<u8>> — byte_length bytes on success

write_eeprom(byte_offset, data)​

pub fn write_eeprom(&self, byte_offset: u16, data: &[u8]) -> Result<()>

Write a byte range of the slave SII EEPROM (looping over words). Both byte_offset and data.len() must be even.

Parameters:

  • byte_offset (u16) — Start byte offset (must be even)
  • data (&[u8]) — Bytes to write (length must be even)

Returns:

  • Result<()> — Ok(()) when all words are written successfully; invalid parameters (empty data / odd byte_offset / odd length) return Err(DarraError::InvalidParameter), and a write failure returns Err(DarraError::Other)

Example:

let slave = master.slave(1);

// read vendor_id (EEPROM byte offset 0x10, length 4)
let data = slave.read_eeprom(0x10, 4)?;
let vendor_id = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
println!("VendorID = 0x{:08X}", vendor_id);

// read the 16-byte header (includes PDIControl/StationAlias, etc.)
let header = slave.read_eeprom(0, 16)?;
println!("EEPROM 头部: {:02X?}", header); // EEPROM header: {:02X?}

// write the alias address (EEPROM byte offset 0x08)
// the slave must be in Init/PreOp state!
if slave.state() == Some(EcState::Init) {
slave.write_eeprom(0x08, &[0x01, 0x00])?; // alias = 1
}
API choice
  • First choice: read_eeprom / write_eeprom (byte-based, automatic word alignment)
  • Second choice: the packaged properties slave.vendor_id() / product_id() / serial_number(), etc.

Category and string access​

The SII EEPROM category list (Strings / General / FMMU / SyncM / TxPdo / RxPdo / DC / End=0xFFFF) has five additional fine-grained entries:

MethodReturnsDescription
sii_release()Result<()>Releases EEPROM access
sii_read_control_reg()Result<u8>Reads the current value of the SII control / status register
sii_find_category(cat_type)Result<(u32, u32)>Locates a category: returns (字节偏移, 字节长度); returns Err when not found
sii_enumerate_categories(max_count)Result<Vec<u16>>Enumerates category types in chain order; max_count <= 0 returns an empty list
sii_get_string_by_index(string_index, max_bytes)Result<String>Reads the Nth string; max_bytes == 0 returns an empty string
pub fn sii_release(&self) -> Result<()>
pub fn sii_read_control_reg(&self) -> Result<u8>
pub fn sii_find_category(&self, cat_type: u16) -> Result<(u32, u32)>
pub fn sii_enumerate_categories(&self, max_count: i32) -> Result<Vec<u16>>
pub fn sii_get_string_by_index(&self, string_index: u8, max_bytes: u32) -> Result<String>
  • Offsets and lengths are both measured in bytes, the same coordinate system as read_eeprom(byte_offset, byte_length), so they can be used together directly.
  • sii_enumerate_categories() returns only type numbers, without lengths; for lengths, call sii_find_category() for each type.
  • sii_get_string_by_index() truncates the buffer at max_bytes and stops at the first NUL; non-UTF-8 bytes are handled as replacement characters without an error.
  • A read failure (no response from the slave / category does not exist) returns Err(DarraError::Other) and does not return an empty list pretending there is none.
// e.g. enumerate the classification table, then take the string of entry 1
for ty in slave.sii_enumerate_categories(32)? {
if let Ok((off, len)) = slave.sii_find_category(ty) {
println!("分类 {} 偏移 {} 长度 {}", ty, off, len); // Category {} offset {} length {}
}
}
let name = slave.sii_get_string_by_index(1, 64)?;

Three-state category reads (sii_try_*)​

The five entries above fold "the chain really has no such category" and "SII could not read it" into the same Err. Use the three three-state entries below when the two must be told apart:

CategoryPropertyTypeRead/writeDescription
SIIsii_try_find_category(cat_type)Result<Option<(u32, u32)>>read-onlyLocates a category: Ok(Some((偏移, 长度))) found; Ok(None) chain readable and really absent; Err could not be read
SIIsii_try_read_category(cat_type, max_bytes)Result<Option<Vec<u8>>>read-onlyReads category data: Ok(Some(data)) read (length may be 0); Ok(None) really absent; Err locate or read failed
SIIsii_try_general_info()Result<Option<SiiGeneralInfo>>read-onlyGeneral category (type=30): Ok(Some(info)) read; Ok(None) really no General category; Err could not be read / data not fully read
pub fn sii_try_find_category(&self, cat_type: u16) -> Result<Option<(u32, u32)>>
pub fn sii_try_read_category(&self, cat_type: u16, max_bytes: u32) -> Result<Option<Vec<u8>>>
pub fn sii_try_general_info(&self) -> Result<Option<ffi::SiiGeneralInfo>>

The three states (mutually exclusive and distinguishable):

  • Ok(Some(_)) — read succeeded; the output is a real value. Ok(Some(vec![])) from sii_try_read_category is a legitimate empty segment (the category exists but its length is 0, or max_bytes == 0), not "absent".
  • Ok(None) — the chain is readable and really has no such category. This is a normal result, not an error.
  • Err(DarraError::Other) — could not be read: the category-chain enumeration failed, or the chain does contain the category but locating it / reading its length word failed. It must not be treated as "absent".

Failure attribution (same ruling as C# TryFindCategory):

  • SIIFindCategory returns 1 → found (the success path does not enumerate the chain again).
  • After a failed locate, enumerate the chain: enumeration returning < 0 (not even an SII context) → Err.
  • Enumeration succeeded and the chain does contain the category, but locating failed → Err (it is on the chain, so it is not "absent").
  • Enumeration succeeded and the chain does not contain it → Ok(None).

The read entry in addition:

  • sii_try_read_category() performs the locate attribution first; a failed locate is returned as Err, and a real absence as Ok(None).
  • When the category length is 0 or max_bytes == 0, it returns Ok(Some(Vec::new())) and issues no read request.
  • The read cap is min(max_bytes, 分类长度); a failed read reports Err as a whole and no partial data is handed back.

Difference from the old entries: sii_find_category() / sii_read_category() / sii_general_info() are unchanged — "absent" and "read failed" have the same shape (Err) there. Use sii_try_* when they must be distinguished.

// three states: absence is not an error; only a failed read is
match slave.sii_try_find_category(10)? { // 10 = Strings
Some((offset, size)) => println!("Strings 在 {} 处, {} 字节", offset, size), // Strings at {}, {} bytes
None => println!("链上确实没有 Strings 分类"), // There really is no Strings category on the chain
}

// read: Ok(Some(empty)) is a legitimate empty segment; only Ok(None) means "absent"
if let Some(data) = slave.sii_try_read_category(10, 4096)? {
println!("读到 {} 字节", data.len()); // Read {} bytes
}

// General: Ok(None) = there really is no General category
if let Some(info) = slave.sii_try_general_info()? {
println!("General: group_idx={}", info.group_idx);
}

SII identity area and true serial number​

The identity area is a fixed ESC area (ETG.1000.6: word 0x0008..0x000F) and does not go through the category chain, so these entries never produce the "really absent from the chain" Ok(None) — there are only two outcomes: "read" and "cannot read".

MethodReturnsDescription
read_sii_identity()Option<SlaveIdentity>Read the four 32-bit words V/P/R/Serial; if any word does not come back → None (no partial identity delivered)
read_sii_serial_number()Option<u32>Reads only the two Serial words; Some(0) = real value 0, None = cannot read
try_get_serial_number()Option<u32>Returns the snapshot directly when it is not 0; falls back to read_sii_serial_number() only when the snapshot is 0
pub fn read_sii_identity(&self) -> Option<SlaveIdentity>
pub fn read_sii_serial_number(&self) -> Option<u32>
pub fn try_get_serial_number(&self) -> Option<u32>
wordFieldDescription
0x0008 / 0x0009vendor_idV (Vendor ID)
0x000A / 0x000Bproduct_codeP (Product Code)
0x000C / 0x000Drevision_noR (Revision No)
0x000E / 0x000Fserial_noSerial (serial number)

Each item is assembled into 32 bits with the low word first (low | high << 16), matching the EEPROM direct-read convention.

read_sii_identity() returns the crate's authoritative public identity type SlaveIdentity (a crate-root re-export, the same type as identity() — no second identity type is introduced). The SII identity area has no itype source, and the type itself carries no product_id / itype fields — data::structures::SlaveIdentity is the native memory mirror and is a different type with the same name.

if let Some(i) = slave.read_sii_identity() {
println!("V=0x{:08X} P=0x{:08X} R=0x{:08X} Serial={}",
i.vendor_id, i.product_code, i.revision_no, i.serial_no);
}

match slave.read_sii_serial_number() {
Some(sn) => println!("序列号真值 = {}", sn), // May be 0: the real value is 0
None => println!("SII 读不出来(不是 0)"), // SII could not be read out (not the same as 0)
}

A failed read is never folded to 0: if any word does not come back the result is None. An incomplete identity area means no partial identity is delivered, and a failed read is never passed off as 「the device serial number is 0」.

The three meanings of serial number 0​

serial_number() is a native runtime identity snapshot, and 0 can mean any of three things:

CaseMeaningCorrect way to read it
Not readCold configuration only reads the SER word for slaves that miss the ESI (a performance trade-off); slaves that hit the ESI keep 0try_get_serial_number()
Real value 0The serial number declared in the device's SII really is 0try_get_serial_number() → Some(0)
Read failedThe SII cannot be readtry_get_serial_number() → None

try_get_serial_number() order: (a) the native snapshot is not 0 → return it directly without touching the EEPROM; (b) the snapshot is 0 → read SII word 0x000E..0x000F live.

  • Some(0) = a real value was read (the device declares serial number 0)
  • None = cannot be read (some word did not come back), not equal to 「the device serial number is 0」
  • While the snapshot is 0, every call really reads the EEPROM; callers that need it frequently should cache it themselves

Configured Station Alias writes​

Configured Station Alias is stored in the SII EEPROM; writing it is a complete flow of "write word → configuration-area checksum → reload → read back", and it is disabled by default (a per-master switch):

MethodReturnsDescription
configured_alias_write_enabled()Result<bool>Reads this master's alias write switch; Err(DarraError::RegisterFailed) = master index unavailable
set_configured_alias_write_enabled(enabled)Result<()>Toggles the write switch; Err(DarraError::InvalidParameter) = this master cannot switch it
write_configured_alias(alias)(AliasWriteOutcome, u16)Writes the alias and returns (结果, 写入前原值); the previous value can be used for rollback
pub fn configured_alias_write_enabled(&self) -> Result<bool>
pub fn set_configured_alias_write_enabled(&self, enabled: bool) -> Result<()>
pub fn write_configured_alias(&self, alias: u16) -> (AliasWriteOutcome, u16)

AliasWriteOutcome values (Written / Pending count as success, decided in one step with succeeded()):

ValueMeaning
WrittenWritten and verified by reading the runtime register back
PendingThe EEPROM was written and the reload succeeded, but the runtime alias register read-back has not caught up — it takes effect after the slave is powered on again
DisabledThe write switch is not enabled (the default); not a single frame was sent
BadParamInvalid master / slave index
BadStateThe slave is not in a sound Init / PreOp (including having the Error bit set or an unreadable AL status)
NotReadyNo configuration address assigned yet / EEPROM control handover failed / the flow was aborted
ReadbackFailedThe previous value could not be read, so overwriting on top of an unknown value is refused
WriteFailed / VerifyFailed / ChecksumFailed / ReloadFailedFailures in the write, post-write verify, configuration-area checksum, and reload stages
Unrecognized(i32)Unrecognized underlying return code, passed through unchanged
Preconditions for writing

First call set_configured_alias_write_enabled(true) to enable the switch, and the slave must be in a sound Init / PreOp (SafeOp / OP / Boot / the Error bit set are all refused). The returned previous value is 0 when it could not be read; for stages already committed before WriteFailed, judge from the concrete outcome whether the previous value must be written back.

DL Port control​

Read and write the ESC DL Port Control register (0x0101) directly, for port fault-injection testing and manual diagnostics of redundancy/ring topologies.

Advanced API

No calls are needed during normal operation. Most users should diagnose port state by subscribing to the on_slave_port_link_changed event and reading the port error counters. Use it only when you need to actively simulate a port fault (to test redundancy switching) or troubleshoot a specific port problem. Note: write_dl_port / read_dl_port do not appear in the published SDK — do not call them from code you intend to ship.

The ESC has 4 physical ports P0 / P1 / P2 / P3; the DL Port Control register bits are defined as follows:

DLPORT valueBehavior
0x00Auto — all ports managed automatically by the ESC (default)
0x03Disable P0
0x0CDisable P1
0x30Disable P2
0xC0Disable P3

The SDK always uses the primary → secondary → APWR three-level fallback write path, so even after P0 is disabled it can recover through the secondary NIC / broadcast.

write_dl_port(value)​

pub fn write_dl_port(&self, value: u8) -> bool

Write the slave DL Port Control register (0x0101).

Parameters:

  • value (u8) — DLPORT value (see the table above)

Returns:

  • bool — true on success

read_dl_port()​

pub fn read_dl_port(&self) -> Option<u8>

Read the current value of the slave DL Port Control register.

Returns:

  • Option<u8> — Some(dlport) on a successful read; None on a failed read (e.g. the slave is offline)

Example:

// simulate a P1 port fault (test redundancy switching)
let ok = slave.write_dl_port(0x0C);
println!("关闭 P1: {}", if ok { "成功" } else { "失败" }); // Close P1: {} (Success / Failure)

// read back to confirm
if let Some(dlport) = slave.read_dl_port() {
println!("当前 DLPORT = 0x{:02X}", dlport); // Current DLPORT = 0x{:02X}
}

// restore after the fault is cleared
slave.write_dl_port(0x00); // restore Auto
Combined with redundancy diagnostics

After disabling a port, watch master.events().on_slave_port_link_changed and master.diagnostics_info().break_point() to verify that redundancy switching took effect.

FMMU / SyncManager configuration​

Configure a slave's FMMU mapping and SyncManager directly, for custom IO mapping or diagnosing address mapping problems. No calls are needed during normal SDK use — the startup flow configures them automatically from the ESI / PDO mapping.

configure_sync_manager(sm_index, start_addr, length, control, enable)​

pub fn configure_sync_manager(&self, sm_index: u8, start_addr: u16, length: u16, control: u8, enable: bool) -> Result<()>

Configure the start address, length, control word and enable bit of the specified SyncManager. Failure returns Err(DarraError::Other).

configure_fmmu(...)​

pub fn configure_fmmu(&self, fmmu_index: u8, logical_addr: u32, length: u16,
logical_start_bit: u8, logical_end_bit: u8,
physical_addr: u16, physical_start_bit: u8,
fmmu_type: u8, enable: bool) -> Result<()>

Configure the specified FMMU's logical address / length / logical bit boundaries / physical address / physical start bit / type (bit 0 = output, bit 1 = input) / enable. Failure returns Err(DarraError::Other).

enable_output_sync_manager() / disable_output_sync_manager()​

pub fn enable_output_sync_manager(&self) -> Result<()>
pub fn disable_output_sync_manager(&self) -> Result<()>

Enable / disable the SyncManager for the process data output direction in one call. Failure returns Err(DarraError::Other).

Example:

let slave = master.slave(1);

// FMMU0: map 4 bytes starting at logical 0x00010000 to physical 0x0F00 (output direction)
slave.configure_fmmu(0, 0x0001_0000, 4, 0, 7, 0x0F00, 0, 1, true)?;

// enable the output-direction SyncManager in one call
slave.enable_output_sync_manager()?;

Startup configuration​

CategoryMethodTypeRead/writeDescription
Startup configurationstartup()StartupParameterListread-onlyStartup parameter list
pdo_assignment_enabled() / set_pdo_assignment_enabled(bool)boolread/writeWhether to write the PDO Assignment at startup, default true
pdo_configuration_enabled() / set_pdo_configuration_enabled(bool)boolread/writeWhether to write the PDO Configuration at startup, default false
supports_complete_access() / set_supports_complete_access(bool)boolread/writeWhether the slave supports SDO Complete Access

StartupParameterList methods (obtained through slave.startup()):

  • add(param: StartupParameter) — Add a startup parameter
  • add_sdo_write(index, sub_index, data, transition) — Add an SDO write startup parameter
  • remove(idx: usize) — Remove a startup parameter by list index, returns Option<StartupParameter>
  • clear() — Clear all startup parameters
  • count() / params() — Number of parameters / parameter slice
  • sort_by_priority() — Sort by priority
  • sync_to_dll() — Synchronize the list into the runtime library, returns Result<i32>
  • apply(transition: u8, timing: u8) — Apply the startup parameters, returns Result<i32>
  • apply_single(param: &StartupParameter) — Apply a single parameter
slave.startup() returns a new instance every time

slave.startup() returns a newly constructed StartupParameterList on every call. For parameters added with add() to actually be issued, operate on the same bound variable and then call sync_to_dll() / apply(), or add the parameter to the slave directly with slave.add_startup_parameter(...).

StartupParameter struct (note that transition / write_timing are enums, not strings):

pub struct StartupParameter {
pub index: u16, // SDO index
pub sub_index: u8, // SDO subindex
pub data: Vec<u8>, // Data to write
pub transition: StartupTransition, // State transition stage (enum)
pub write_timing: StartupWriteTiming, // Write timing (enum)
pub priority: i32, // Priority (lower value = higher priority)
pub complete_access: bool, // Complete access mode
pub description: String, // Description
}

Example:

use darra_ethercat::{StartupParameter, StartupTransition};

// use the associated constructor (transition is an enum)
let param = StartupParameter::with_transition(
0x1C12, 0, vec![0], StartupTransition::PS);

let mut list = slave.startup();
list.add(param);
list.sync_to_dll()?; // takes effect only after synchronization

StartupTransition enum values (default write timing):

  • IP — Init → PreOp, default AfterTransition
  • PS — PreOp → SafeOp, default BeforeTransition
  • SO — SafeOp → Op, default BeforeTransition
  • OS — Op → SafeOp, default AfterTransition
  • SP — SafeOp → PreOp, default AfterTransition
  • PI — PreOp → Init, default BeforeTransition

Slave-level startup parameter entries​

Besides the slave.startup() list view (see above), Slave has four direct entries:

MethodReturnsDescription
startup_parameter_count()Result<usize>Number of startup parameters currently queued; returns Err when it cannot be read instead of collapsing to 0 entries
apply_startup_parameters(transition, timing)Result<i32>Issues the queued parameters for the given transition / timing, returning the number of entries processed in this pass
needs_startup_reconfig()boolMarker that this slave's configuration has not been applied yet (startup parameters need to be issued again)
clear_startup_reconfig()()Clears that marker
pub fn startup_parameter_count(&self) -> Result<usize>
pub fn apply_startup_parameters(&self, transition: u8, timing: u8) -> Result<i32>
pub fn needs_startup_reconfig(&self) -> bool
pub fn clear_startup_reconfig(&self)

transition / timing use the u8 constants (already exported at the crate root):

ConstantValueTransition / timing
TRANS_IP0Init → PreOp
TRANS_PS1PreOp → SafeOp
TRANS_SO2SafeOp → OP
TRANS_OS3OP → SafeOp
TRANS_SP4SafeOp → PreOp
TRANS_PI5PreOp → Init
TIMING_BEFORE / TIMING_AFTER0 / 1Before / after the transition

Return value semantics (important): the n in Ok(n) is the number of entries processed in this pass; Ok(0) only means "no entry to write in this phase" or "this pass yielded", not that the phase is complete; on failure it returns Err(DarraError::Other) with the underlying return code in the message.

use darra_ethercat::{TRANS_PS, TIMING_BEFORE};

let pending = slave.startup_parameter_count()?;
if pending > 0 {
let done = slave.apply_startup_parameters(TRANS_PS, TIMING_BEFORE)?;
println!("本拍处理 {} / {} 条", done, pending); // Processed {} / {} items this tick
}

needs_startup_reconfig() reflects honestly that "this slave's configuration has not been applied": the bit is normally set together with a failure log and cleared automatically by the recovery path after a successful reconfiguration; call clear_startup_reconfig() manually only when you have confirmed the configuration was completed by other means.

Sub-object access​

The Slave sub-object accessors below cover dc() and the identity shortcut identity(); all other fields are read directly through flat property methods (see the "Properties" table above):

slave.dc()​

pub fn dc(&self) -> crate::slave::dc::SlaveDC

Returns the advanced SlaveDC interface, which provides methods such as configure / configure_mode / disable / has_dc / propagation_delay / sync_window_status.

let dc = slave.dc();
if dc.has_dc() == Some(true) {
// configure(sync0_ns, sync1_ns, shift_ns: Option<i32>)
dc.configure(1_000_000, 0, Some(0))?; // 1ms SYNC0, no SYNC1, 0 shift
println!("传播延迟 {} ns", dc.propagation_delay()); // Propagation delay {} ns
}

DC diagnostics supplement​

SlaveDC also has two entries related to automatic startup / the reference clock, and the DC sampling snapshot has one more availability verdict:

MethodReturnsDescription
SlaveDC::is_reference_clock_self()boolWhether this slave is the current reference clock; always false while no slave is armed (the underlying query has no failure channel, and 0 also means "no reference clock")
SlaveDC::rollback_free_run_for_auto_startup()Result<bool>For automatic-startup failure rollback only: pulls this slave back to FreeRun without recording a user intent
SlaveDCDiagnostics::reset_stats()()Clears this slave's sync window statistics (slave.diagnostics().dc().reset_stats())
DcSlaveSnapshot::arm_outcome_available()boolWhether the arm outcome is available in this SDK: always false
pub fn is_reference_clock_self(&self) -> bool
pub fn rollback_free_run_for_auto_startup(&self) -> Result<bool>

// SlaveDCDiagnostics
pub fn reset_stats(&self)

// DcSlaveSnapshot
pub fn arm_outcome_available(&self) -> bool

rollback_free_run_for_auto_startup() has three outcomes: Ok(true) = the intent was cleared and the 0x0980 withdrawal has been dispatched; Ok(false) = the intent was cleared but the hardware write was deferred (later automatic re-arming is allowed; only the hardware is not confirmed); Err(..) = the master / slave index is unavailable and the intent was not changed. It is not a normal user configuration entry — for FreeRun use disable() / configure_mode().

DcSlaveSnapshot::arm_outcome_available() is always false: the arm outcome of automatic startup is not tracked on the Rust SDK side, so arm_outcome in the snapshot is always None. None means "this snapshot does not provide that verdict", and is not DcArmResult::Unknown.

slave.identity()​

pub fn identity(&self) -> Result<SlaveIdentity>

Returns the vendor/product/revision/serial tuple. It is more convenient than calling vendor_id() / product_id() / rev_id() / serial_number() separately, and errors are unified as Result.

let id = slave.identity()?;
println!("0x{:08X} 0x{:08X} 0x{:08X} 0x{:08X}",
id.vendor_id, id.product_code, id.revision_no, id.serial_no);
Rust-specific syntactic sugar

Rust provides From<&Slave> for SlaveIdentity; one line, let id: SlaveIdentity = (&slave).into();, gets the identity tuple directly without unwrapping field by field.

The Rust SDK uses flat accessors

The Rust implementation uses flat methods: all fields are read directly through slave.input_bits() / mbx_protocol() / physical_type() / link_count() (returns the link count as i32, -1 when unknown) / coe_details(), etc., matching Rust's zero-cost accessor idiom.

Grouped by purpose:

  • Topology: slave.link_count() / parent_station() / entry_port() / active_ports() / physical_type() / child_count() / children()
  • Mailbox: slave.mbx_length() / mbx_protocol() / mbx_read_length() / mbx_write_offset() / mbx_read_offset()
  • SyncManager / FMMU: slave.fmmu0_func() / fmmu1_func() / fmmu2_func() / fmmu3_func() / sync_manager_count()
  • Protocol details: slave.coe_details() / eoe_details() / foe_details() / soe_details() / has_mdp() / supports_frame_repeat()
  • SII EEPROM: read directly through the sii_* family (slave.sii_acquire() / sii_read_category() / sii_get_strings() / sii_general_info(), etc.); parsed EEPROM fields are also available through slave.detailed_info().

To access the full raw structure, use the SlaveDetailedInfo returned by slave.detailed_info().

Rust-specific syntactic sugar

Parsed states are read directly with slave.state() / slave.state_live() (Option<EcState>) and slave.error_code() (EcALState); if you have raw bytes, the sugar module's From<u8> converts them to an enum in one line: let st: EcState = raw.into(); (unknown values land on EcState::None), let lk: LinkState = raw.into();.

Process image handle (SlavePdo)​

slave.pdo() returns the process image handle (SlavePdo, borrowing the master's lifetime). The mapping and read/write entries (inputs() / outputs() / write_outputs(), etc.) are available directly on the handle; this section covers the monitoring and grouped-statistics entries:

MethodReturnsDescription
reset_stats()()Clears this slave's PDO statistics
start_monitoring()()Turns on PDO performance monitoring (a process-wide global switch)
stop_monitoring()()Turns monitoring off and also clears all collected statistics (global, not just this slave)
is_monitoring_enabled()boolCurrent monitoring switch state (global)
get_mutex_protection()boolWhether process image mutual-exclusion protection is on (master-level; the current implementation always reports on, including when the master is unavailable)
group_cycle_divider(group)u8Reads the cycle divider of that group
reset_frame_loss_stats(group)()Clears the frame loss statistics of that group
pub fn reset_stats(&self)
pub fn start_monitoring(&self)
pub fn stop_monitoring(&self)
pub fn is_monitoring_enabled(&self) -> bool
pub fn get_mutex_protection(&self) -> bool
pub fn group_cycle_divider(&self, group: u8) -> u8
pub fn reset_frame_loss_stats(&self, group: u8)
The monitoring switch is global

start_monitoring() / stop_monitoring() act on the whole process, not on a single slave; stop_monitoring() clears all collected statistics. To clear per slave, use reset_stats().

let pdo = slave.pdo();
pdo.start_monitoring();
// ... sample for a while ...
println!("监视中: {}", pdo.is_monitoring_enabled()); // Monitoring: {}
println!("组 1 分频: {}", pdo.group_cycle_divider(1)); // Group 1 cycle divider: {}
pdo.reset_frame_loss_stats(1);

Slave group access (SlaveGroupAccessor)​

Grouping is a master-level view obtained through master.group_accessor(). The public full path of the return type is darra_ethercat::master::core::SlaveGroupAccessor (not re-exported at the crate root); use that full path when you need to write the type name.

MethodReturnsDescription
set_divider(group, div)()Sets the cycle divider of that group; div == 0 is ignored (no write is sent)
pub fn set_divider(&self, group: u8, div: u8)
let groups = master.group_accessor();
groups.set_divider(1, 2); // Group 1 divider = 2
println!("组 1 当前分频: {}", groups.divider(1)); // Group 1 current cycle divider: {}
Only valid values are written

set_divider() returns nothing: div == 0 writes nothing and reports no error; to confirm the result, read it back with divider(group).

Startup auto-configuration capability detection​

pub fn capabilities(&self) -> StartupAutoCapabilities

Note: this capabilities() is a method on crate::slave::startup::StartupAutoConfig (not a method on Slave; call it as StartupAutoConfig::new(master.index(), slave.index()).capabilities()). It returns the set of startup auto-configuration capabilities (four boolean bits: default_pdo_enumeration / esi_auto_startup / mdp_auto_startup / sm_auto_configuration), which differ from the SII EEPROM protocol detail bits — the former are "capabilities determined automatically by the starter", while the SII EEPROM protocol detail bits come from flat methods such as slave.coe_details().

Configuration source declaration (ConfigSource)​

Declaration interfaces on the same StartupAutoConfig: they only record the declaration "the configuration came from ENI or DENI" and do not load files — loading ENI / DENI still goes through the respective configuration loading entry.

pub enum ConfigSource {
Unknown = 0, // Undeclared (instance default; must not be written explicitly)
Eni = 1, // Configuration came from ENI (standard ETG.2100 network configuration XML)
Deni = 2, // Configuration came from DENI (Darra extended network configuration, an ENI superset)
}

impl StartupAutoConfig {
pub fn set_config_source(&mut self, source: ConfigSource) -> Result<()>
pub fn set_config_source_eni(&mut self) // Equivalent to set_config_source(ConfigSource::Eni)
pub fn set_config_source_deni(&mut self) // Equivalent to set_config_source(ConfigSource::Deni)
pub fn config_source(&self) -> &str
pub fn has_executed(&self) -> bool
}
CategoryMethodTypeRead/writeDescription
Configuration sourceset_config_source(ConfigSource)Result<()>write-onlyDeclares the source; ConfigSource::Unknown returns Err(DarraError::InvalidParameter)
set_config_source_eni()()write-onlyForwarder to set_config_source(ConfigSource::Eni), kept for compatibility
set_config_source_deni()()write-onlyForwarder to set_config_source(ConfigSource::Deni), kept for compatibility
config_source()&strread-onlyReads back the declared source: "ENI" / "DENI"; an empty string "" when undeclared (signature unchanged, no enum read-back)
Execution statushas_executed()boolread-onlyWhether auto-configuration has been executed; false after StartupAutoConfig::new()

Write semantics:

  • ConfigSource::Unknown → Err(DarraError::InvalidParameter) — "unknown" is the undeclared default, and writing it explicitly would be fabricating a source
  • On success it also sets has_executed = true — declaring a source means this slave's configuration is in place; the flag lets upper layers tell whether configuration already happened (the SDK has no auto-startup executor today, so whether to skip is the caller's decision)
  • May be called repeatedly: a later declaration overwrites the previous one (ENI ↔ DENI switching is supported)
  • The two forwarders set_config_source_eni() / set_config_source_deni() return () (the Result is ignored internally; they pass Eni / Deni, so they cannot fail)
  • Defaults: after StartupAutoConfig::new(), config_source() is "" and has_executed() is false
  • No bus operation is issued; only the declaration field on this instance changes — it does not load files, read slaves or write slaves
use darra_ethercat::slave::startup::{ConfigSource, StartupAutoConfig};

let mut auto = StartupAutoConfig::new(master.index(), slave.index());
auto.set_config_source(ConfigSource::Deni)?;

println!("{}", auto.config_source()); // "DENI"
println!("{}", auto.has_executed()); // true — declaring a source sets the flag as well
This is SDK-side declaration state, not a native read-back

native does not record the ENI / DENI source per slave — it only records two things per slave: "explicitly planned (explicit_replace)" and "merged ESI defaults (esi_installed)". config_source() returns the declaration value kept on the SDK side, not a read-back from the slave. Do not use has_executed() to judge whether configuration really took effect either — use the return value of the configuration loading entry itself.

Scan result entry helpers (ScannedSlaveInfo)​

The slave entry ScannedSlaveInfo returned by a network scan provides three display helpers (pure formatting / verdicts, no bus access):

MethodReturnsDescription
alias_addr_hex()StringFormats the alias address as 0x%04X (4 uppercase hex digits)
vendor_id_hex()StringFormats the vendor ID as 0x%08X (8 uppercase hex digits)
is_coupler()boolJudges the entry as a coupler when its physical type is 1
impl ScannedSlaveInfo {
pub fn alias_addr_hex(&self) -> String
pub fn vendor_id_hex(&self) -> String
pub fn is_coupler(&self) -> bool
}
use darra_ethercat::scan_slaves;

for s in scan_slaves("以太网 2", None)? { // Ethernet 2
println!("#{} {} {}", s.index, s.vendor_id_hex(), s.alias_addr_hex());
if s.is_coupler() {
println!(" (耦合器)"); // (coupler)
}
}

is_coupler() is decided by the entry's own physical_type (value 1), not inferred from the vendor / model.