Slave API
Obtain a slave handle through master.slave(n) (1-based index), or all slaves through master.slaves().
Quick start
Index access
let slave = master.slave(1); // the 1st slave (1-based)
let count = master.slave_count(); // total number of slaves (u16)
let all = master.slaves(); // all slaves Vec<Slave>
Identity access
let name: String = slave.name(); // device name
let drive_name: String = slave.drive_name(); // drive name (SDO 0x1008)
let vendor_id: u32 = slave.vendor_id(); // vendor ID
let product_id: u32 = slave.product_id(); // product ID
let revision: u32 = slave.rev_id(); // revision
let serial: u32 = slave.serial_number(); // serial number
Address access
let addr: u16 = slave.config_addr(); // physical configuration address
let alias: u16 = slave.alias_address(); // alias address
// find by address
let target = master.slaves().iter()
.find(|s| s.config_addr() == 0x1001);
Group access
// query the group the slave belongs to
let group: u8 = slave.group();
// query the number of slaves in the group
let group_count = master.group_slave_count(1);
States and error codes
let state = slave.state(); // Option<EcState>: base state, without the Error bit
let raw = slave.state_raw(); // u8: native raw byte, 0x18 = OP+Error
let err = slave.has_error(); // bool: raw & 0x10 != 0
let status = slave.status(); // EcSlaveStatus: OP / OpFault / SafeOpFault ...
let code = slave.error_code(); // EcALState: the table gives named variants for the raw codes
let code_raw = slave.error_code_raw(); // u16: raw AL Status Code, codes outside the table are kept as-is
state() returns only the low 4-bit base state: 0x14 (SafeOp+Error) and 0x18 (OP+Error) are
both reported as a clean SafeOp / OP. To judge whether a slave is reporting an error, use
has_error() or status():
if slave.state() == Some(EcState::Operational) && !slave.has_error() {
// Truly clean OP
}
match slave.status() {
EcSlaveStatus::OpFault => println!("OP + Error, AL=0x{:04X}", slave.error_code_raw()),
s => println!("{}", s),
}
The AL Status Code has two entry points: error_code() is the enum view and only lists codes
in the ETG.1020 table; out-of-table codes land in Unknown(0xFFFF) (the same value as 「no
code」, which the enum itself cannot tell apart); error_code_raw() gives the 16-bit raw value
directly (out-of-table codes kept unchanged) — use it for numeric comparison and logging.
state_raw_live() / has_error_live() / error_code_live() are the live read variant of
the same semantics (they bypass the cache). The full property table and the difference between
cache and live are covered in Slave API.
Protocol access
| Category | Protocol | Method | Read/write | Description |
|---|---|---|---|---|
| Data | SDO | slave.sdo_read_value::<T>() / sdo_write_value() | read/write | Typed SDO read/write |
| Data | OD tree | OdList::load(master_idx, slave_idx) | read-only | Object dictionary traversal |
| Mailbox | CoE | slave.coe() / CoEInstance::new(master_idx, slave_idx) | read/write | CANopen over EtherCAT instance |
| Drive | CiA 402 | CiA402Instance::new(master_idx, slave_idx, pdo_map) | read/write | Constructs a servo drive instance independently |
| Mailbox | SoE | slave.soe() | read/write | Servo over EtherCAT |
| Mailbox | FoE | slave.foe() | read/write | File over EtherCAT |
| Mailbox | EoE | slave.eoe() | read/write | Ethernet over EtherCAT |
| Mailbox | AoE | slave.aoe() | read/write | ADS over EtherCAT |
| Mailbox | VoE | slave.voe() | read/write | Vendor over EtherCAT |
| Safety | FSoE | SafetyManager / SafeMdp | read/write | Functional safety protocol (constructed independently) |
| Safety | MDP | mdp_discover() | read-only | Modular device discovery (module-level functions) |
| Sync | DC | slave.dc() | read/write | DC synchronization configuration |
PDO data read/write
After entering OP, map a #[repr(C, packed)] struct onto the process image and modify fields directly from multiple threads:
#[repr(C, packed)]
struct InPdo {
status_word: u16,
actual_position: i32,
}
#[repr(C, packed)]
struct OutPdo {
control_word: u16,
target_position: i32,
}
let pdo = master.slave(1).pdo(); // handle borrowed from the master; `SlavePdo`::new is a deprecated and hidden legacy entry point
unsafe {
let inputs = pdo.inputs_mapping::<InPdo>()?;
let outputs = pdo.outputs_mapping::<OutPdo>()?;
outputs.control_word = 0x000F;
let pos = inputs.actual_position; // copy packed fields into a local variable first
println!("当前位置: {pos}"); // Current position: {pos}
}
Slave::io() (bounded output + input views)
The slave handle also has a pair of zero-copy whole-image entry points, Slave::io(): one call returns bounded views
of both directions of the slave (a writable output slice + a read-only input slice). The return value is a slice, not a raw pointer:
pub unsafe fn io<'a>(&'a self) -> Result<(&'a mut [u8], &'a [u8])>
// returns (writable output slice, read-only input slice)
Contract:
- The slice length equals the real image byte count reported by
GetIO; out-of-bounds access is stopped by the slice boundary — no raw*mut u8plus raw length is handed to the caller anymore. - When unmapped / not in OP, the corresponding side is an empty slice.
- For a snapshot only (a copy that does not pin the IOmap pointer), use
try_inputs()/try_outputs()onSlavePdo(see PDO inputs and outputs). - Safety contract (three
unsaferules):- Only one writable view of the same image may exist at any moment — taking it twice from the same handle, or once from each of two handles, creates aliasing
&mutand is undefined behavior. - The view borrows
&self, andSlavein turn borrows the master — it cannot be stored as'static. - The view must not outlive the master.
- Only one writable view of the same image may exist at any moment — taking it twice from the same handle, or once from each of two handles, creates aliasing
Example:
let slave = master.slave(1);
let (outputs, inputs) = unsafe { slave.io()? };
if inputs.len() >= 2 {
println!("status=0x{:04X}", u16::from_le_bytes([inputs[0], inputs[1]]));
}
if outputs.len() >= 2 {
outputs[0] = 0x0F;
outputs[1] = 0x00;
}
To get the byte offsets of this slave within the whole IOmap, use slave.input_offset() / slave.output_offset() (u32).
SDO read/write example:
// typed read
let status: u16 = slave.sdo_read_value(0x6041, 0x00)?;
let position: i32 = slave.sdo_read_value(0x6064, 0x00)?;
// typed write
slave.sdo_write_value(0x6040, 0x00, &0x0006u16)?;
// raw byte read/write (third parameter: complete_access)
let data = slave.sdo_read(0x1000, 0x00, false)?;
slave.sdo_write(0x6040, 0x00, false, &[0x06, 0x00])?;
EMCY emergency messages
A slave sends an EMCY (Emergency) message when it detects an exception; the history is returned in chronological order (oldest → newest).
Slave-level entries: Slave::emcy_history / Slave::clear_emcy
pub fn emcy_history(&self, max_records: usize) -> Result<Vec<EmcyRecord>>
pub fn clear_emcy(&self)
Semantics (the same authority as the module-level emcy_get_history):
- The EMCY history holds at most 256 records;
max_recordsdecides how many records this call fetches at most (pass a smaller value if needed). max_records == 0reports a parameter error (InvalidParameter, not an "empty history").- A read failure returns
Errand is never folded into an empty history; an emptyVeconly means the slave confirmed there are no EMCY records.
Module-level three-parameter function: emcy_get_history(master_index, slave_index, max_records)
The module-level entry of the same authority, with three parameters: master index, slave index, and the maximum number of records to pull this time. It is likewise limited by the same 256-record history capacity; passing 0 for max_records reports InvalidParameter (parameter error), a failure returns Err, and a failure is never folded into an empty history.
use darra_ethercat::slave::{emcy_get_count, emcy_get_history, emcy_clear_history};
// the example lives in a function that returns Result, so errors propagate via ? (otherwise handle Ok/Err explicitly with match)
let count = emcy_get_count(master.index(), 1)?;
// the 3rd parameter of emcy_get_history is the maximum number of records to pull this time; it returns Result<Vec<EmcyRecord>>
let history = emcy_get_history(master.index(), 1, 64)?;
for msg in &history {
let code = msg.error_code; // EmcyRecord is packed, so copy it into a local variable first
println!("错误码: 0x{:04X}", code); // Error code: 0x{:04X}
}
emcy_clear_history(master.index(), 1);
// slave-level entry (same authority)
let history = slave.emcy_history(64)?;
for msg in &history {
let code = msg.error_code; // likewise copy into a local variable first
println!("错误码: 0x{:04X}", code); // Error code: 0x{:04X}
}
slave.clear_emcy(); // clear the EMCY history of this slave
Topology queries
The master layer provides two topology interfaces; choose by use case:
Flat node list (topology() / topology_build()) — for simple queries that only need the node list / child nodes /
root nodes.
let topo = master.topology(); // Vec<TopologyNode>, cached after the first build
let topo2 = master.topology_build(); // force a rebuild (call after rescanning)
let children = master.topology_get_children(1); // direct child nodes Vec<u16>
let roots = master.topology_get_roots(); // root nodes Vec<u16>
Advanced SlaveTopology object (slave_topology()) — returns a wrapped SlaveTopology instance
that builds the parent/children bidirectional index after a single internal scan and supports structured traversal
such as depth calculation / path lookup / address queries. It suits tooling code that needs multiple queries on the topology tree (for example, an IDE topology view or a configuration exporter).
pub fn slave_topology(&self) -> SlaveTopology
let topo = master.slave_topology();
topo.nodes(); // &[TopologyNode] — all nodes
topo.count(); // usize — node count
topo.root_slaves(); // &[u16] — root slave list
topo.children(parent_idx); // &[u16] — child slave indices
topo.child_count(parent_idx);// usize — child count
topo.get(slave_index); // Option<&TopologyNode>
topo.get_by_address("0x1001"); // Option<&TopologyNode>, supports hex / dec
topo.parent_of(slave_index); // Option<u16>
topo.depth(slave_index); // u32 — distance to the root node
- Quick root / child queries →
topology_get_children/topology_get_roots - Building a topology visualization / multiple structured queries →
slave_topology(), built once and reused - After a rescan →
topology_build()or callslave_topology()again
Startup parameters (add_startup_parameter / clear_startup_parameters):
// add a startup parameter
slave.add_startup_parameter(
0x1C12, 0x00, // index, subindex
&[0x00], // data
TRANS_IP, // at the Init → PreOp transition
TIMING_BEFORE, // execute before the transition
false, // not Complete Access
);
// clear all startup parameters
slave.clear_startup_parameters();