Skip to main content

PDO inputs and outputs

Access the process image through slave.pdo().​

PDO is a region of the process image that the lower layer exchanges automatically every cycle. Two paths coexist: struct mapping reads and writes the process image as a struct (zero-copy, for continuous control); the element view fetches a single element by byte offset (one current snapshot per call, for one-off reads).

How the PDO cycle relates to the mailbox

Mailbox communication (SDO/CoE/FoE, etc.) rides along in the PDO cycle automatically and uses no extra frames. A mailbox response takes about 2-3 PDO cycles.

Handle and snapshot contract
  • The element view is a lightweight Copy handle that stores no data bytes itself: pdo.in_items().get(i) merely wraps "slave + offset i" into a handle, and taking it does not read the bus.
  • One accessor call = one snapshot: content() / as_int16() / get_bit() copy the complete frame for that direction every time, then parse at the offset.
  • Two calls in the same expression may fall in two different PDO cycles.
  • For several fields from the same instant, take the whole frame once with pdo.try_inputs() and parse from that one copy.
  • in_items() (TxPDO, slave→master) is read-only.
  • Writing its elements reports DarraError::PdoFailed (the exception is the wide-type write write_from_base_data(), which always returns false).
  • Write process data with out_items() (RxPDO).
  • Multi-byte values are always little-endian (EtherCAT wire order); this SDK never byte-swaps.
  • The handle borrows the master: while pdo is alive the master cannot be borrowed again by &mut self calls such as set_state() / stop(); using the handle after drop(master) is a compile error, not a dangling reference.
  • Element accessors are not a zero-copy path (each call copies the complete frame); the zero-copy entries are listed one by one in "Zero-copy entries" below.

Zero-copy entries​

These entries hand the process image directly to the caller (reference / slice) without copying the frame; entries outside this section copy on every call.

  • inputs_mapping<T>() / outputs_mapping<T>() — &T / &mut T; requires align_of::<T>() == 1, otherwise reports PdoFailed
  • input_slice() / output_slice() — the whole segment as &[u8] / &mut [u8]
  • inputs_slice_mapping(offset, size) / outputs_slice_mapping(offset, size) — sub-slice of a range
  • Slave::io() — pub unsafe fn io<'a>(&'a self) -> Result<(&'a mut [u8], &'a [u8])>, takes a bounded view (输出可写, 输入只读) from the slave handle in one call
  • slave.try_get_inputs_ptr() — Option<(*const u8, u32)>, an input image pointer with a liveness guard; None = the image is unavailable or the slave is offline

To get only the image byte count for a direction, use in_items().length() / out_items().length() (the same source, not a second set of statistics). Zero-copy views are pinned to the current IOmap; after the process image is regenerated (re-entering OP) old references / slices become invalid — do not cache them across generations, just take them again.

Alignment gate and direction for struct mapping

inputs_mapping<T>() / outputs_mapping<T>() have an alignment gate: align_of::<T>() != 1 is always rejected with DarraError::PdoFailed, so T must be #[repr(C, packed)]; otherwise field access is unaligned.

The direction is fixed by the entry itself: inputs_* is read-only (the master overwrites the input image every cycle, so writing it is meaningless); to write the process image use outputs_mapping<T>() / output_slice() / outputs_slice_mapping().

For whole-frame transfer use the module-level entries copy_slave_input_pdo() / copy_slave_output_pdo() / write_slave_output_pdo() (under darra_ethercat::slave::pdo): take or submit a whole frame at once, and not zero-copy entries. To copy a range into your own buffer, use read_input_to_buffer() / write_output_from_buffer().

Whole-frame and buffer entries​

These entries no longer collapse a failure into 0: a failed read returns Err(PdoReadError) and a failed write returns Err(PdoWriteError), and the SDK logs one WARN for each. Callers must not treat Err as 「read 0 bytes / wrote 0 bytes」.

// module-level whole-frame entries (darra_ethercat::slave::pdo): one whole frame at a time
pub fn copy_slave_input_pdo(master_index: u16, slave_index: u16) -> Result<Vec<u8>>
pub fn copy_slave_output_pdo(master_index: u16, slave_index: u16) -> Result<Vec<u8>>
pub fn write_slave_output_pdo(master_index: u16, slave_index: u16, data: &[u8]) -> Result<usize>

// module-level buffer entries: failures carry status
pub fn read_input_to_buffer(master_index: u16, slave_index: u16, buf: &mut [u8])
-> std::result::Result<usize, PdoReadError>

pub fn write_output_from_buffer(master_index: u16, slave_index: u16, buf: &[u8])
-> std::result::Result<usize, PdoWriteError>

pub fn batch_write(master_index: u16, slave_index: u16,
offsets: &[usize], values: &[&[u8]])
-> std::result::Result<usize, PdoWriteError>
  • copy_slave_input_pdo() reads the whole TxPDO frame, copy_slave_output_pdo() reads the whole RxPDO frame, and write_slave_output_pdo() submits the whole output frame (the length must byte-for-byte equal the image for that direction). All three return the crate's Result.
  • read_input_to_buffer() reads [0, buf.len()): if the buffer cannot hold the whole frame the status is BufferTooSmall; if the frame is shorter than the buffer it is SizeMismatch.
  • write_output_from_buffer() overwrites [0, buf.len()) of the output image with the whole buffer, committing the frame atomically.
  • batch_write() commits blocks at multiple offsets in one transaction and returns the number of blocks written.

The corresponding whole-frame entries on the process image handle are try_inputs() / try_outputs() / try_write_outputs() (returning the crate's Result; see "inputs() / outputs() / write_outputs(data)" below).

Related structures:

pub struct PdoReadError {
pub status: PdoIoStatus, // last lower-layer status (Busy = bounded retry budget exhausted while still colliding with the RT thread)
pub requested_bytes: usize, // bytes requested by this read (0 = read to the end of the complete frame)
pub message: String, // includes the slave index, requested bytes and the underlying cause
}

pub struct PdoWriteError {
pub status: PdoIoStatus, // last lower-layer status (Busy = retries exhausted)
pub expected_bytes: usize, // bytes expected to be written this time
pub message: String, // includes the slave index, expected bytes, actually written bytes and the underlying cause
}

#[repr(u8)]
pub enum PdoIoStatus {
Failed = 0, // Failure
Ok = 1, // Success
BufferTooSmall = 2, // the caller's buffer cannot hold it
SizeMismatch = 3, // size / offset out of range
Conflict = 4, // commit conflict
Stale = 5, // commit snapshot is stale
Busy = 6, // bounded retry budget exhausted while still colliding with the RT thread
}

Both implement Display / std::error::Error and convert into DarraError::PdoFailed with ? (the From impl exists).

Failure classification:

  • The read/write transaction itself failed → status is the last lower-layer status (Busy = bounded retry budget exhausted)
  • Parameter-type failure (frame shorter than the buffer / range overflow) → on the read side this is SizeMismatch
  • The caller's buffer cannot hold it → BufferTooSmall
  • The write path is an atomic whole-frame commit: on failure not a single byte lands, and no "partial write" is fabricated

batch_write_pooled() keeps its semantics (it returns the number of successful slaves), but logs one WARN whenever any slave fails (failed slave count / first failed slave index / that slave's PdoIoStatus), so a partial failure never slips by silently.

use darra_ethercat::slave::pdo::{read_input_to_buffer, PdoIoStatus, PdoReadError};

let mut buf = [0u8; 8];
match read_input_to_buffer(master.index(), 1, &mut buf) {
Ok(n) => println!("读到 {} 字节", n), // Read {} bytes
Err(PdoReadError { status: PdoIoStatus::Busy, .. }) => {
println!("RT 线程占住帧,重试预算耗尽 —— 不是「没数据」"); // RT thread holds the frame and the retry budget is exhausted — this is not "no data"
}
Err(e) => println!("读失败: {e}"), // Read failed: {e}
}

slave.write_output(data)​

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

Whole-frame output submission on the slave handle: submits the entire RxPDO frame in one call, not a partial patch.

Language boundary: write_output() on this page (and the master-level write_slave_output()) is a real write entry (whole-frame submission; a failure return means nothing was written). The C ABI entries WriteSlaveOutput / WriteSlaveOutputByte are retired empty implementations that always fail; they are not the same thing as this entry. Do not infer this language's behavior from the C ABI names.

Parameters:

  • data (&[u8]) — The complete output frame; the length must byte-for-byte equal the output image for this direction

Returns:

  • Ok(()) — The whole frame was committed
  • Err(DarraError::PdoFailed) — The length does not match the output image, the frame exceeds the 65536-byte limit, or the commit did not succeed (status not Ok / bytes actually written inconsistent with the complete frame length)

Description:

  • The same action as the module-level write_slave_output_pdo(); the handle entry only collapses the written byte count into ().
  • The write path is an atomic whole-frame commit: on failure not a single byte lands, and no "partial write" is fabricated.
  • To change several fields in the same instant, commit once after modifying them: take the whole frame with try_outputs(), modify it, then call write_output(); for a small single-field change use the write_output_u16() family (a partial patch).

Example:

let slave = master.slave(1);
let mut frame = slave.pdo().try_outputs()?; // Current output frame
if frame.len() >= 2 {
frame[0..2].copy_from_slice(&0x000F_u16.to_le_bytes());
}
slave.write_output(&frame)?; // Whole-frame commit; a length mismatch reports Err

Usage examples​

Day-to-day usage​

① Struct mapping (zero-copy, for continuous use): map once after entering OP, get references that point straight at the process image, then read and write them like variables.

use darra_ethercat::{EcState, EtherCATMaster};

#[repr(C, packed)] // packed is mandatory: alignment must be 1
struct InPdo { status_word: u16, actual_position: i32 }

#[repr(C, packed)]
struct OutPdo { control_word: u16, target_position: i32 }

let mut master = EtherCATMaster::builder()
.set_eni(r"C:\EtherCAT\MyProject.deni") // one-line DENI load
.build()?
.master;
master.set_state(EcState::Operational)?; // enter OP
master.start();

let pdo = master.slave(1).pdo(); // the handle borrows the master

// map once: the references point straight at the process image (zero-copy). unsafe wraps only these two calls.
let (inputs, outputs) = unsafe {
(pdo.inputs_mapping::<InPdo>()?, pdo.outputs_mapping::<OutPdo>()?)
};

let pos = inputs.actual_position; // reading a field = reading the current cycle
let sw = inputs.status_word;
outputs.control_word = 0x000F; // writing a field = sent in the next cycle
outputs.target_position = pos + 1000;
println!("status=0x{sw:04X} pos={pos}");

② Element view (one-off reads): no struct; fetch elements purely by byte offset.

let in_items = pdo.in_items();                      // TxPDO: read-only
let sw: u16 = in_items.get(0)?.as_uint16()?; // 2 bytes starting at offset 0
let pos: i32 = in_items.get(2)?.as_int32()?; // 4 bytes starting at offset 2
let ready = in_items.get(6)?.as_bool()?; // true only when the lowest bit is 1

let out_items = pdo.out_items(); // RxPDO: readable and writable
out_items.get(0)?.set_uint16(0x000F)?; // write: sent in the next cycle

Cyclic changes​

One mapping is enough; put the same mapping straight into your own cycle loop:

loop {
outputs.control_word = if inputs.status_word & 0x0004 != 0 { 0x000F } else { 0x0006 };
outputs.target_position = inputs.actual_position;
std::thread::sleep(std::time::Duration::from_millis(1)); // your own pacing
}

The lower layer moves process data every cycle: what you read in the loop is always the current cycle, what you write is sent in the next cycle, no extra calls are needed, and you must not re-map on every iteration. Only stop() or an IOmap generation change invalidates the old references; after re-entering OP, take them once more.

Struct mapping (zero-copy)​

inputs_mapping<T>()​

Map the input process image (TxPDO) to a read-only struct reference that points straight at the IOmap — one of this SDK's zero-copy paths.

pub unsafe fn inputs_mapping<'a, T>(&'a self) -> Result<&'a T>

Returns:

  • Result<&'a T> — A read-only reference pointing straight at the process image (zero-copy, not a snapshot); its borrow is bound to the handle, and the handle borrows the master, so the reference can neither leave the handle's scope nor outlive the master

Description:

  • unsafe contract: T must be #[repr(C, packed)], and the field order must match the slave's TxPDO mapping byte for byte.
  • Alignment other than 1 (a missing packed) reports DarraError::PdoFailed.
  • An unavailable process image (not in OP / not mapped) reports PdoFailed.
  • size_of::<T>() greater than the input image byte count (pdo.in_items().length()) reports PdoFailed.
  • The mapped struct may contain only fixed-width fields (integers, floats, [u8; N]) — String / Vec / references would overlay pointers on process data, which the alignment check cannot catch.
  • A packed field cannot be referenced directly: println!("{}", inputs.actual_position) is a compile error.
  • First copy it into a local with let v = inputs.actual_position;, then use it.
  • This entry does not apply a liveness guard: when the slave is offline it still hands out a reference to the last frame (behavior unchanged). To judge liveness before reading, use slave.try_get_inputs_ptr() or slave.is_lost().

Example:

#[repr(C, packed)]
struct InPdo { status_word: u16, actual_position: i32 }

let pdo = master.slave(1).pdo();
let inputs: &InPdo = unsafe { pdo.inputs_mapping::<InPdo>()? };
let sw = inputs.status_word; // current cycle value

outputs_mapping<T>()​

Map the output process image (RxPDO) to a writable struct reference; changing a field writes the process image.

pub unsafe fn outputs_mapping<'a, T>(&'a self) -> Result<&'a mut T>

Returns:

  • Result<&'a mut T> — A writable reference pointing straight at the process image (zero-copy); after assignment the value goes to the slave in the next cycle

Description:

  • Layout and size checks are the same as inputs_mapping<T>().
  • At most one writable reference / writable slice may exist for the same image at the same time:
    • You cannot hold two of outputs_mapping() / output_slice() / outputs_slice_mapping() at once.
    • Taking one twice from the same handle, or one from each of two handles, creates aliasing &mut, which is undefined behavior.
    • Serialize them with scopes.
  • The unsafe contract likewise requires the layout to match the slave's RxPDO byte for byte.

Example:

#[repr(C, packed)]
struct OutPdo { control_word: u16, target_position: i32 }

let outputs: &mut OutPdo = unsafe { pdo.outputs_mapping::<OutPdo>()? };
outputs.target_position = 10000; // sent in the next cycle
outputs.control_word = 0x000F;

input_slice() / output_slice()​

Zero-copy whole segment: take a byte slice pointing straight at the IOmap, without a struct.

pub unsafe fn input_slice<'a>(&'a self) -> &'a [u8]          // whole TxPDO segment, read-only
pub unsafe fn output_slice<'a>(&'a self) -> &'a mut [u8] // whole RxPDO segment, writable

Returns:

  • &'a [u8] / &'a mut [u8] — A whole-segment slice pointing straight at the process image; when the process image is unavailable, the pointer is null or the size is 0, it is an empty slice (no panic)

Description: output_slice() shares the same exclusive contract as outputs_mapping(): at most one writable slice / mapping per image at the same time.

Example:

use darra_ethercat::slave::{read_le_i32, read_le_u16};

let frame: &[u8] = unsafe { pdo.input_slice() }; // no copy; this is the process image itself
let sw = read_le_u16(frame, 0);
let pos = read_le_i32(frame, 2);
println!("status=0x{sw:04X} pos={pos}");

Slave::io() (bounded views in one call)​

Take the full pair of views from the slave handle in one call, outputs writable + inputs read-only:

pub unsafe fn io<'a>(&'a self) -> Result<(&'a mut [u8], &'a [u8])>

Returns:

  • Result<(&'a mut [u8], &'a [u8])> — A bounded (输出可写, 输入只读) view. The slice length is the real image byte count reported by the lower layer, and out-of-range access is caught by the slice bounds, so no bare pointer + bare length is ever handed out. When not mapped / not in OP the corresponding side is an empty slice.

Description:

  • For a snapshot only (a copy that does not pin the IOmap pointer), use SlavePdo's try_inputs() / try_outputs() (see "inputs() / outputs() / write_outputs(data)" below).
  • The exclusive contract is the same as output_slice(): at most one writable view per image at the same time (taking one twice from the same handle, or one from each of two handles, creates aliasing &mut, which is undefined behavior).
  • The view borrows &self, and Slave in turn borrows the master: it cannot be stored as 'static and cannot outlive the master.

Example:

let (outputs, inputs) = unsafe { slave.io()? };   // bounded; out-of-range access is caught by the slice bounds

slave.try_get_inputs_ptr() and is_lost()​

An input process image pointer entry with a liveness guard — for callers that take a raw pointer and read it themselves; before handing over the pointer it confirms this frame may be used as the current value.

pub fn try_get_inputs_ptr(&self) -> Option<(*const u8, u32)>
pub fn is_lost(&self) -> bool

Returns:

  • Some((指针, 字节数)) — the input image is available and the slave has not been judged offline
  • None — the image is unavailable (not mapped / not in OP: the lower layer's GetIO is not 0|1, the input pointer is null, or the input byte count is 0), or the slave is offline

Description:

  • The only source of the predicate is is_lost() (the lower-layer SlaveLiveness three-state): only an observed LOST counts as stale; with no observed evidence it truthfully returns false (not confirmed offline), so "could not measure" is never mistaken for offline on a healthy cycle.
  • While a slave is offline the input image keeps the last frame before it dropped. A stale frame must not be used as the current value: on None, take your own failure branch instead of reading the old bytes.
  • The snapshot path uses the same predicate: copy_slave_input_pdo() / try_inputs() return Err(PdoReadError) when the slave is offline, with status = PdoIoStatus::Stale.
  • Zero-copy mapping entries such as inputs_mapping<T>() / input_slice() do not apply this liveness guard; their behavior is unchanged. To judge liveness before reading, use this entry or check is_lost().
  • The output direction is not blocked: the output area is the master's own shadow frame, and a slave being offline does not affect its validity (the same lower-layer predicate applies to the input direction only).
  • The pointer is valid only on the current IOmap; after the process image is regenerated (re-entering OP) it must be taken again.

Example:

let slave = master.slave(1);
match slave.try_get_inputs_ptr() {
Some((ptr, len)) => {
// SAFETY: len comes from the lower layer; reads are limited to [0, len)
let frame = unsafe { std::slice::from_raw_parts(ptr, len as usize) };
println!("输入帧 {} 字节,首字节 0x{:02X}", frame.len(), frame[0]); // Input frame {} bytes, first byte 0x{:02X}
}
None => eprintln!(
"输入映像不可用或从站已离线(is_lost={})—— 不读陈旧帧", // Input image unavailable or the slave is offline (is_lost={}) — not reading a stale frame
slave.is_lost()
),
}

inputs_slice_mapping(offset, size) / outputs_slice_mapping(offset, size)​

Take a zero-copy sub-slice for a byte range, for splitting multi-module devices into segments.

pub unsafe fn inputs_slice_mapping<'a>(&'a self, offset: usize, size: usize) -> &'a [u8]
pub unsafe fn outputs_slice_mapping<'a>(&'a self, offset: usize, size: usize) -> &'a mut [u8]

Parameters:

  • offset (usize) — Byte offset relative to the start of this slave's process image in this direction
  • size (usize) — Number of bytes in the sub-slice

Returns:

  • &'a [u8] / &'a mut [u8] — The slice for that range. If the offset + size addition overflows, or offset + size exceeds the process image length, it returns an empty slice: no panic, and no clamping to the boundary (an out-of-range request is never truncated to "as much as fits")

Description: The writable sub-slice shares the same exclusive contract as output_slice().

Example:

// MDP device: module 1 starts at offset 0, module 2 at offset 8
let m1: &[u8] = unsafe { pdo.inputs_slice_mapping(0, 8) };
let m2: &mut [u8] = unsafe { pdo.outputs_slice_mapping(8, 8) };

Direct access (works without mapping)​

These calls are independent of struct mapping: they work without mapping, and are often used alongside it (to unpack fields the struct cannot hold).

in_items() / out_items()​

Get the byte-indexed container for the process image in this direction.

pub fn in_items(&self)  -> PdoArrayInstance<'m>   // TxPDO (slave→master): read-only
pub fn out_items(&self) -> PdoArrayInstance<'m> // RxPDO (master→slave): readable and writable

Returns:

  • PdoArrayInstance<'m> — A byte-indexed view of the process image; length() is the byte count of the process image in this direction, and is 0 when not in OP / not mapped (any index is out of range then)

Description: Both the container and the element view are lightweight Copy handles that store no data bytes. Obtaining the container does not return a Result: when the length cannot be obtained it is 0. 'm has the same origin as the handle, so the container cannot leave the master's scope.

Related structures:

pub struct PdoArrayInstance<'m> { /* slave + direction + length; stores no data bytes */ }

impl<'m> PdoArrayInstance<'m> {
pub fn length(&self) -> usize; // byte count of the process image in this direction
pub fn is_input(&self) -> bool; // true = TxPDO (read-only)
pub fn get(&self, index: usize) -> Result<PdoDataItem<'m>>; // get the element view at byte index
pub fn set(&self, index: usize, value: u8) -> Result<()>; // commit byte index (Out only)
}

Example:

let in_items = pdo.in_items();
println!("输入映像 {} 字节", in_items.length()); // Input image {} bytes

let item = in_items.get(2)?; // taking a view does not read the bus
let pos = item.as_int32()?; // only here is a snapshot taken and parsed at the offset

get(index)​

Get the element view at byte index — it holds only the four elements "slave + offset + direction + bounds" and stores no data bytes itself.

pub fn get(&self, index: usize) -> Result<PdoDataItem<'m>>

Parameters:

  • index (usize) — Byte offset relative to the start of the process image in this direction

Returns:

  • Result<PdoDataItem<'m>> — Element view (lightweight Copy handle, zero heap allocation)

Description:

  • An index outside [0, length()) reports DarraError::InvalidParameter.
  • Taking a view does not read the bus; reads happen when an accessor is called (one snapshot each), and writes happen when set_* is called (one versioned commit each, sent in the next cycle).
  • Inside an accessor, offset + width beyond the process image in this direction likewise reports InvalidParameter; writing an element in the in_items() direction reports PdoFailed.

Related structures:

impl<'m> PdoDataItem<'m> {
pub fn offset(&self) -> usize; // byte offset of this element in the process image for this direction
pub fn is_input(&self) -> bool; // true = TxPDO (read-only)

pub fn content(&self) -> Result<u8>; // 1 raw byte (unsigned 8-bit)
pub fn set_content(&self, value: u8) -> Result<()>;
pub fn as_int8(&self) -> Result<i8>; // signed 8-bit
pub fn set_int8(&self, value: i8) -> Result<()>;
pub fn as_uint8(&self) -> Result<u8>; // same byte and same width as content()
pub fn set_uint8(&self, value: u8) -> Result<()>; // synonymous with set_content()
pub fn as_int16(&self) -> Result<i16>; // all multi-byte values below are little-endian
pub fn set_int16(&self, value: i16) -> Result<()>;
pub fn as_uint16(&self) -> Result<u16>;
pub fn set_uint16(&self, value: u16) -> Result<()>;
pub fn as_int32(&self) -> Result<i32>;
pub fn set_int32(&self, value: i32) -> Result<()>;
pub fn as_uint32(&self) -> Result<u32>;
pub fn set_uint32(&self, value: u32) -> Result<()>;
pub fn as_int64(&self) -> Result<i64>;
pub fn set_int64(&self, value: i64) -> Result<()>;
pub fn as_uint64(&self) -> Result<u64>;
pub fn set_uint64(&self, value: u64) -> Result<()>;
pub fn as_float(&self) -> Result<f32>; // IEEE754 single precision (little-endian wire order)
pub fn set_float(&self, value: f32) -> Result<()>;
pub fn as_double(&self) -> Result<f64>; // IEEE754 double precision (little-endian wire order)
pub fn set_double(&self, value: f64) -> Result<()>;
pub fn as_bool(&self) -> Result<bool>; // bit0 semantics: true only when the lowest bit is 1
pub fn set_bool(&self, value: bool) -> Result<()>; // true → 0x01, false → 0x00 (whole byte)

pub fn get_bit(&self, bit_index: u8) -> Result<bool>; // 0-7, 0 = LSB
pub fn set_bit(&self, bit_index: u8, value: bool) -> Result<()>; // Out only
}

as_bool() honors only the lowest bit: byte 0x01 is true; 0x02 and 0x80 both read false.

This SDK has no second "non-zero means true" entry. To judge truth by whole-byte 0 / not 0, read content() and compare yourself.

set_bool() writes a whole byte, 0x01 / 0x00, not a bit.

Multi-byte values are always little-endian (EtherCAT wire order): as_int16() / as_uint16() / … / as_double() all reinterpret little-endian directly; this SDK never byte-swaps.

Direction: only elements from out_items() are writable; in_items() is overwritten by the master every cycle, and writing it reports DarraError::PdoFailed.

Example:

let in_items = pdo.in_items();
let sw = in_items.get(0)?.as_uint16()?; // read: current cycle
let raw = in_items.get(0)?.content()?; // raw value of the same byte
let flag = in_items.get(3)?.as_bool()?; // bit0 semantics: both 0x02 / 0x80 are false

let out_items = pdo.out_items();
out_items.get(2)?.set_int16(123)?; // write: versioned commit, sent in the next cycle
out_items.set(0, 0x11)?; // equivalent to out_items.get(0)?.set_content(0x11)?

get_bit(bit_index) / set_bit(bit_index, value)​

Read and write the byte at the element offset at bit level.

pub fn get_bit(&self, bit_index: u8) -> Result<bool>
pub fn set_bit(&self, bit_index: u8, value: bool) -> Result<()>

Parameters:

  • bit_index (u8) — Bit index 0-7, 0 = LSB
  • value (bool) — Set / clear the bit

Returns:

  • bool — Current value of that bit
  • () — Set succeeded (versioned commit, sent in the next cycle)

Description:

  • Bit accessors are per byte, not per width: bit_index addresses only that one byte at the element offset, regardless of the width you use to read the element.
    • get(2)?.get_bit(0)? always tests the lowest bit of byte 2, even if you intend to read 4 bytes from the same offset with as_int32().
  • u8 already excludes negative values; 8..=255 reports DarraError::InvalidParameter.
  • set_bit() is a bitfield read-modify-write: only the target bit is overwritten; the other bits of the same byte keep their values.
  • Calling set_bit() on an element in the in_items() direction reports PdoFailed (get_bit() is readable in both directions).

Example:

let out_items = pdo.out_items();
out_items.get(0)?.set_bit(0, true)?; // set bit0 only; the other bits of the byte stay unchanged
out_items.get(0)?.set_bit(7, false)?; // clear bit7 only

let lsb = pdo.in_items().get(3)?.get_bit(0)?; // 0 = LSB

as_value(data_type) / write_value(data_type, value)​

Read and write the value at the current position by EtherCAT data type (little-endian).

pub fn as_value(&self, data_type: EcDataType) -> Result<EcValue>
pub fn write_value(&self, data_type: EcDataType, value: &EcValue) -> Result<()>

Parameters:

  • data_type (EcDataType) — The mapping type at this position; supported fixed-width scalar types: Boolean, Integer8/16/32/64, Unsigned8/16/32/64, Real32, Real64
  • value (EcValue) — Value to write

Returns:

  • EcValue — Value read out (Bool / I8 / U8 / I16 / U16 / I32 / U32 / I64 / U64 / F32 / F64)
  • () — Write succeeded

Description:

  • Types outside the fixed-width scalars above (bit strings Bit1..Bit8, Integer24/40/48/56, Unsigned24/40/48/56, TimeOfDay / TimeDifference, strings, Domain) report DarraError::InvalidParameter.
    • No guessing the width and no silent 1-byte read.
  • For these types use as_base_data(): the width is the lower-layer data type table bit width rounded up (Integer24 3 bytes, Integer40 / Unsigned40 5 bytes, Integer48 / Unsigned48 / TimeOfDay / TimeDifference 6 bytes, Integer56 / Unsigned56 7 bytes, bit strings 1 byte).
  • On write the value is converted as a scalar (floats round to nearest, ties to even; a boolean target accepts EcValue::Bool or any integer / float, 0 = false, not 0 = true, then applies bit0 whole-byte semantics).
  • EcValue::String / EcValue::Bytes are explicit non-scalar variants and always report an error — this SDK provides no implicit path for "writing a string into PDO as a number".
  • Only elements from out_items() are writable.

Example:

use darra_ethercat::{EcDataType, EcValue};

let out_items = pdo.out_items();
out_items.get(4)?.write_value(EcDataType::Real32, &EcValue::F32(3.5))?;

let v: EcValue = pdo.in_items().get(4)?.as_value(EcDataType::Real32)?;
if let EcValue::F32(temp) = v {
println!("温度 {temp}"); // Temperature {temp}
}

// no fixed-width scalar counterpart for bit strings: report an error instead of guessing 1 byte
if let Err(e) = pdo.in_items().get(0)?.as_value(EcDataType::Bit3) {
eprintln!("不支持的数据类型: {e}"); // Unsupported data type: {e}
}

as_base_data(data_type) / write_from_base_data(data)​

Wide-type exit: as_value() / write_value() cover only fixed-width scalar types; use this pair for bit strings and variable-length fields.

pub fn as_base_data(&self, data_type: EcDataType) -> Result<BaseData>
pub fn write_from_base_data(&self, data: &BaseData) -> bool

Parameters:

  • data_type (EcDataType) — The mapping type at this position; byte width = the lower-layer data type table bit width rounded up (Integer40 / Unsigned40 5 bytes, Integer48 / Unsigned48 / TimeOfDay / TimeDifference 6 bytes, Integer56 / Unsigned56 7 bytes); variable-length types (strings / Domain) and types not defined in the lower-layer data type table are taken as 1 byte
  • data (BaseData) — Whole raw byte block to write back

Returns:

  • BaseData — Raw bytes copied from the current position at the data_type width, wrapped
  • bool — Whether the write succeeded; failure returns false (no throw), and the in_items() direction always returns false

Description:

  • The byte width taken and the BaseData container width come from the same place: they are necessarily equal for fixed-width types, and the container accepts any length for variable-length types. So failures such as "the bytes taken do not fit the container" cannot happen.
  • Value shape: TimeOfDay / TimeDifference and Integer40/48/56 yield EcValue::I64, Unsigned40/48/56 yield EcValue::U64, bit strings yield EcValue::Bool (bit0 semantics); variable-length types yield EcValue::String / EcValue::Bytes.
  • TimeOfDay / TimeDifference is 6 bytes / 48 bit: the low 32 bits are milliseconds since midnight, the high 16 bits are days since 1984-01-01 (little-endian), read as an unsigned 48-bit value; read() on the container yields EcValue::I64 carrying exactly this packed value.
  • as_base_data() reports DarraError::InvalidParameter when offset + width exceeds the process image in this direction, and DarraError::PdoFailed when the snapshot is unavailable.
  • write_from_base_data() uses the output direction's versioned commit and is sent in the next cycle.
  • Any failure returns false, sparing the caller an exception branch.

Example:

use darra_ethercat::EcDataType;

let wide = pdo.in_items().get(0)?.as_base_data(EcDataType::Integer24)?; // 24-bit integer: not covered by the fixed-width scalars
if !pdo.out_items().get(0)?.write_from_base_data(&wide) {
eprintln!("宽类型写回被拒绝"); // failure returns false, no throw
}

inputs() / outputs() / write_outputs(data)​

Access the whole process image frame by byte.

pub fn inputs(&self)  -> Vec<u8>                    // whole input frame: a failure collapses to an empty Vec
pub fn try_inputs(&self) -> Result<Vec<u8>> // whole input frame: a failure returns Err
pub fn outputs(&self) -> Vec<u8> // whole output frame: a failure collapses to an empty Vec
pub fn try_outputs(&self) -> Result<Vec<u8>>
pub fn write_outputs(&self, data: &[u8]) -> bool // submit the complete output frame
pub fn try_write_outputs(&self, data: &[u8]) -> Result<()>

Parameters:

  • data (&[u8]) — Complete output frame; the length must byte-for-byte equal the output image for this direction

Returns:

  • Vec<u8> — A snapshot, not zero-copy: consistent within one instant, and the copy does not change with the bus
  • bool / () — Whether the write succeeded

Description:

  • One call = one complete frame: several fields from the same snapshot are necessarily from the same instant; this is how multi-field consistency is achieved (parse with the read_le_u16() family).
  • write_outputs() does no partial patching: it fails if the frame length does not match the output image or if the versioned commit fails.

Example:

use darra_ethercat::slave::{read_le_i32, read_le_u16};

let frame = pdo.try_inputs()?; // one complete input frame snapshot
let sw = read_le_u16(&frame, 0); // necessarily the same instant as the line below
let pos = read_le_i32(&frame, 2);
println!("status=0x{sw:04X} pos={pos}");

let mut out = pdo.try_outputs()?; // read-modify-write of the whole frame
if out.len() >= 2 {
out[0..2].copy_from_slice(&0x000F_u16.to_le_bytes());
}
if !pdo.write_outputs(&out) {
eprintln!("整帧提交失败"); // Full-frame commit failed
}

read_le_u16() / read_le_u32() / read_le_i16() / read_le_i32()​

Parse a fixed-width little-endian value from a frame snapshot by byte offset.

pub fn read_le_u16(data: &[u8], offset: usize) -> u16
pub fn read_le_u32(data: &[u8], offset: usize) -> u32
pub fn read_le_i16(data: &[u8], offset: usize) -> i16
pub fn read_le_i32(data: &[u8], offset: usize) -> i32

Parameters:

  • data (&[u8]) — A frame snapshot (e.g. the result of pdo.try_inputs()?)
  • offset (usize) — Byte offset within the frame

Returns:

  • u16 / u32 / i16 / i32 — Little-endian parse result; collapses to 0 when the offset is out of range or the value is not representable

Description:

  • Declared under darra_ethercat::slave (not at the crate root).
  • Used with one try_inputs() / try_outputs(), several fields parsed from the same snapshot are necessarily from the same instant.
  • The element view (a new snapshot per call) cannot give you this.

Example:

use darra_ethercat::slave::{read_le_i32, read_le_u16};

let frame = pdo.try_inputs()?; // one snapshot
let sw = read_le_u16(&frame, 0); // StatusWord from the same instant
let pos = read_le_i32(&frame, 2); // ActualPosition from the same instant
println!("status=0x{sw:04X} pos={pos}");

read_input_() / write_output_() (fixed-width shortcuts)​

Fixed-width shortcuts on the slave handle slave = master.slave(i) that read inputs / write outputs directly by byte offset — no structs and no element views.

// slave = master.slave(i): reads use the lower-layer direct-read channel, writes return Result
pub fn read_input_u8(&self, offset: u32) -> u8
pub fn read_input_i8(&self, offset: u32) -> i8
pub fn read_input_i16(&self, offset: u32) -> i16
pub fn read_input_u16(&self, offset: u32) -> u16
pub fn read_input_i32(&self, offset: u32) -> i32
pub fn read_input_u32(&self, offset: u32) -> u32
pub fn read_input_f32(&self, offset: u32) -> f32
pub fn write_output_u8(&self, offset: u32, value: u8) -> Result<()>
pub fn write_output_i8(&self, offset: u32, value: i8) -> Result<()>
pub fn write_output_i16(&self, offset: u32, value: i16) -> Result<()>
pub fn write_output_u16(&self, offset: u32, value: u16) -> Result<()>
pub fn write_output_i32(&self, offset: u32, value: i32) -> Result<()>
pub fn write_output_u32(&self, offset: u32, value: u32) -> Result<()>
pub fn write_output_f32(&self, offset: u32, value: f32) -> Result<()>

Parameters:

  • offset (u32) — Byte offset within the process image for this direction
  • value (u8 / i8 / i16 / u16 / i32 / u32 / f32) — Fixed-width value to write

Returns:

  • u8 / i8 / i16 / u16 / i32 / u32 / f32 — Little-endian parse result; collapses to 0 when the frame is unavailable or the offset is out of range
  • Result<()> — Ok(()) on a successful write, Err on failure

Description:

  • Reads use the lower-layer direct-read channel (no whole-frame copy): the cheapest option for single-field polling.
  • A failed read collapses to 0 and the caller cannot see why — to distinguish 「a real 0」 from "out of range", use the element view (which reports Err) or the read_le_u16() family instead.
  • Writes are partial patches: one call touches only the target field; for several fields in one transaction use the element view, or try_inputs() → modify → write_outputs() on the whole frame.

Example:

let slave = master.slave(1);

let sw = slave.read_input_u16(0); // collapses to 0 when out of range
slave.write_output_u16(0, 0x000F)?; // reports Err on failure
let temp = slave.read_input_f32(10); // single-field polling: lower-layer direct read, no whole-frame copy

read_string() / write_string() (process image handle)​

The string entries live on the process image handle pdo = master.slave(i).pdo():

pub fn read_string(&self, offset: u32, max_len: u32) -> String
pub fn write_string(&self, offset: u32, value: &str, max_len: u32) -> Result<()>

Parameters:

  • offset (u32) — Byte offset within the process image for this direction
  • max_len (u32) — The maximum bytes read_string() reads; the total write length for write_string() (including the trailing NUL; writable bytes = max_len - 1)

Returns:

  • String — A string truncated at \0 (decoded as UTF-8, or byte by byte as Latin-1 when not UTF-8); returns an empty string when it cannot be read
  • Result<()> — Ok(()) on a successful write. Failures are reported faithfully as Err, with no truncation and no collapse to false:
    • UTF-8 byte count > max_len - 1 → Err(DarraError::InvalidParameter), with the actual length and the maxLength-1 limit in the message
    • max_len == 0 → Err(DarraError::InvalidParameter) (message: 「maxLength must be > 0 (including the NUL terminator)」)
    • Process image transaction not committed → Err(DarraError::PdoFailed) (message: "failed to write the output PDO string (process image transaction not committed)")

A valid write pads max_len with NULs, overwriting stale tail bytes (a longer old string leaves no residue).

Example:

let pdo = master.slave(1).pdo();
let name = pdo.read_string(6, 16); // truncated at \0, at most 16 bytes
pdo.write_string(6, "axis-1", 16)?; // 16 includes the NUL: at most 15 bytes written, more reports Err

PDO assignment verification and recovery​

slave.recover_pdo_assignments()​

pub fn recover_pdo_assignments(&self) -> Result<i32>

Performs one real read-back verification of this slave's PDO assignment and mapping: it covers every phase of the configuration (Init / PreOp / SafeOp) and every write timing (Before / After), reading back the entry count and entry contents of 0x1C12 / 0x1C13 item by item; where they differ, it resubmits through the same write path as the first configuration and rechecks.

Returns:

  • Ok(1) — Verification passed in all phases (items that needed re-writing were resubmitted and rechecked)
  • Ok(0) — Verification did not pass, or the master / slave index is unavailable (the latter changes no assignment)
  • Err(DarraError::PdoFailed) — Failed (the message carries the return code)

Description:

  • When everything matches, nothing is done: the assignment and mapping are not rewritten just to be safe.
  • Only this slave's configuration is handled; other slaves are not iterated. For a batch recovery, call it slave by slave.
  • Ok(0) is not success: the caller must explicitly require the return value == 1 to treat it as passed.

Example:

let slave = master.slave(1);
match slave.recover_pdo_assignments()? {
1 => println!("PDO 分配核对通过"), // PDO assignment check passed
0 => eprintln!("核对未通过(或主站 / 站号不可用)—— 不是成功"), // Verification did not pass (or master / station number unavailable) — this is not success
other => println!("已处理,返回码 {other}"), // Processed, return code {other}
}

Input change monitoring (PdoMonitor)​

If you only want to "sense input changes" at the application layer without introducing a new event mechanism, the SDK provides PdoMonitor for manual polling (darra_ethercat::slave::PdoMonitor). It reads only input (TxPDO) bytes, keeps the previous snapshot per watch point, and leaves the polling pace to the caller.

pub fn new(master_index: u16) -> Self
pub fn watch(&mut self, slave_index: u16, name: impl Into<String>, byte_offset: u32, byte_count: u32)
pub fn unwatch(&mut self, slave_index: u16, name: &str)
pub fn unwatch_slave(&mut self, slave_index: u16)
pub fn check(&mut self) -> Vec<PdoChange> // compare against the snapshot, return the changed items
pub fn check_slave(&mut self, slave_index: u16) -> Vec<PdoChange>
pub fn reset_snapshots(&mut self) // re-establish the baseline
pub fn watch_count(&self) -> usize / watch_count_for_slave(slave_index) / watch_list()

PdoChange fields: watch_name / slave_index / old_data / new_data, plus format_hex(). A sample whose read fails is skipped (it produces no fabricated change) and does not update the snapshot.

use darra_ethercat::slave::PdoMonitor;

let mut monitor = PdoMonitor::new(master.index());
monitor.watch(1, "status", 0, 2);
loop {
for change in monitor.check() {
println!("{}", change.format_hex());
}
std::thread::sleep(std::time::Duration::from_millis(10));
}

Full example​

use darra_ethercat::slave::{read_le_i32, read_le_u16};
use darra_ethercat::{EcState, EtherCATMaster};

#[repr(C, packed)]
struct InPdo { status_word: u16, actual_position: i32 }

#[repr(C, packed)]
struct OutPdo { control_word: u16, target_position: i32 }

fn main() -> darra_ethercat::Result<()> {
let mut master = EtherCATMaster::builder()
.set_eni(r"C:\EtherCAT\MyProject.deni") // one-line DENI load
.build()?
.master;
master.set_state(EcState::Operational)?; // enter OP
master.start();

let pdo = master.slave(1).pdo(); // the handle borrows the master

// zero-copy: map once and the references point straight at the process image (unsafe wraps only these two calls)
let (inputs, outputs) = unsafe {
(pdo.inputs_mapping::<InPdo>()?, pdo.outputs_mapping::<OutPdo>()?)
};

// element view: each accessor call takes its own snapshot, so two calls may span two PDO cycles
let in_items = pdo.in_items();
let sw_point = in_items.get(0)?.as_uint16()?;
let pos_point = in_items.get(2)?.as_int32()?;

// parse several fields from one snapshot: the three values below are necessarily from the same instant
let frame = pdo.try_inputs()?;
let sw = read_le_u16(&frame, 0);
let pos = read_le_i32(&frame, 2);
println!("单点 {sw_point}/{pos_point},整帧 {sw}/{pos}"); // Single point {sw_point}/{pos_point}, full frame {sw}/{pos}

// cycle loop: mapped references and the element view can be used together
for _ in 0..10 {
let cw = if inputs.status_word & 0x0004 != 0 { 0x000F_u16 } else { 0x0006_u16 };
outputs.control_word = cw; // write a field: sent in the next cycle
outputs.target_position = pos;
pdo.out_items().get(0)?.set_bit(0, true)?; // bit-level patch: the other bits of the byte stay unchanged

let mapped_sw = inputs.status_word; // copy packed fields to locals before formatting
let mapped_pos = inputs.actual_position;
println!("status=0x{mapped_sw:04X} pos={mapped_pos}");
std::thread::sleep(std::time::Duration::from_millis(1));
}

Ok(()) // master drop: stops automatically
}