Skip to main content

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​

CategoryProtocolMethodRead/writeDescription
DataSDOslave.sdo_read_value::<T>() / sdo_write_value()read/writeTyped SDO read/write
DataOD treeOdList::load(master_idx, slave_idx)read-onlyObject dictionary traversal
MailboxCoEslave.coe() / CoEInstance::new(master_idx, slave_idx)read/writeCANopen over EtherCAT instance
DriveCiA 402CiA402Instance::new(master_idx, slave_idx, pdo_map)read/writeConstructs a servo drive instance independently
MailboxSoEslave.soe()read/writeServo over EtherCAT
MailboxFoEslave.foe()read/writeFile over EtherCAT
MailboxEoEslave.eoe()read/writeEthernet over EtherCAT
MailboxAoEslave.aoe()read/writeADS over EtherCAT
MailboxVoEslave.voe()read/writeVendor over EtherCAT
SafetyFSoESafetyManager / SafeMdpread/writeFunctional safety protocol (constructed independently)
SafetyMDPmdp_discover()read-onlyModular device discovery (module-level functions)
SyncDCslave.dc()read/writeDC 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 u8 plus 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() on SlavePdo (see PDO inputs and outputs).
  • Safety contract (three unsafe rules):
    1. 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 &mut and is undefined behavior.
    2. The view borrows &self, and Slave in turn borrows the master — it cannot be stored as 'static.
    3. The view must not outlive the master.

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_records decides how many records this call fetches at most (pass a smaller value if needed).
  • max_records == 0 reports a parameter error (InvalidParameter, not an "empty history").
  • A read failure returns Err and is never folded into an empty history; an empty Vec only 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
Which one to use
  • 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 call slave_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();