Skip to main content

PDO inputs and outputs

Access the process image through slave.pdo.​

A PDO is one segment of the process image, exchanged automatically by the underlying layer every cycle.

Once mapped to a fixed-width struct, reading or writing a member reads or writes the process image itself — zero-copy: no copying, no refreshing; reads always see the current cycle, and writes go out in the next cycle.

When you do not want to define a struct, use the element views input_array / output_array to read and write single points by byte offset.

Process image capacity (two measures)
  • A single process image in this product (inputs + outputs + per-slave mailbox state combined) is capped at 64 KB (65536 bytes)
  • The underlying buffer reserves 64 KB per direction (double buffering; this is the reserved amount, not the usable amount)
  • A single LRW frame carries at most 1486 bytes of process data; a group larger than about 1.5 KB loses the zero-copy fast path and switches to multi-frame forwarding (up to 16 frames rotating per group per cycle) — plan for "a single group ≤ 1.4 KB" when choosing hardware
  • Slave count: the slave table per master is capped at 2048 (1-based station table, at most 2047 slaves)
  • Capacity trade-off point: at an average of ≤ 32 B per slave you hit the slave table limit (2048) first, and only above > 32 B per slave do you hit the 64 KB limit first
Relationship between the PDO cycle and the mailbox

Mailbox communication (SDO/CoE/FoE and so on) rides along with the PDO cycle automatically and does not consume an extra frame. Mailbox responses take about 2-3 PDO cycles.

Struct contract
  • _pack_ = 1 is required, with field order matching the PDO mapping byte for byte; when determinable padding bytes exist (because _pack_ was omitted) the mapping raises RuntimeError instead of silently misaligning.
  • Must not exceed the image byte count for the corresponding direction (slave.pdo.inputs_mapping_info["size"] / outputs_mapping_info["size"]).
    • Oversized, image unavailable and out-of-range offset all raise RuntimeError (the message carries the slave index, direction and byte counts).
    • A smaller struct is valid and covers the image from the given offset.
  • Fields may only be fixed-width types; use fixed-length byte arrays for strings and decode variable-length data from the whole-frame inputs.
  • A mapping stays valid once made; close() / re-entering OP invalidates the old view, so take it again when you re-enter OP.

Usage examples​

Day-to-day usage​

① Map to a struct (zero-copy, keep using it): map once after entering OP, get a struct instance mapped directly onto the process image, then read and write it like a variable.

import ctypes
from darra_ethercat import EtherCATMaster, EcState

class InPdo(ctypes.Structure):
_pack_ = 1 # Required; field order matches the PDO byte for byte
_fields_ = [
("status_word", ctypes.c_uint16),
("actual_position", ctypes.c_int32),
]

class OutPdo(ctypes.Structure):
_pack_ = 1
_fields_ = [
("control_word", ctypes.c_uint16),
("target_position", ctypes.c_int32),
]

master = (EtherCATMaster()
.set_eni(r"C:\EtherCAT\MyProject.deni") # Load DENI in one line
.build())
master.set_state(EcState.OP) # Enter OP

slave = master[1] # Slave (1-based index)

inputs = slave.pdo.inputs_mapping(InPdo) # Read-only view (map once after entering OP)
outputs = slave.pdo.outputs_mapping(OutPdo)

outputs.control_word = 0x000F # Write: sent in the next cycle
outputs.target_position = inputs.actual_position # Read: always the current cycle
print(f"状态字=0x{inputs.status_word:04X} 位置={inputs.actual_position}") # Status word=0x{inputs.status_word:04X} position={inputs.actual_position}

② Element views (no struct definition): take an element by byte offset; each member of the element is a fixed-width scalar read/write port.

# Single point: an out-of-range index raises IndexError
pos = slave.pdo.input_array[2].as_int32 # 4 bytes starting at offset 2
sw = slave.pdo.input_array[0].as_uint16 # 2 bytes starting at offset 0 (StatusWord)

slave.pdo.output_array[0].as_uint16 = 0x000F # Write: sent in the next cycle
slave.pdo.output_array[2].as_int32 = 10000

# Whole frame: one complete input frame snapshot, consistent within the same sample; decode several fields from the same bytes
import struct
frame = slave.pdo.inputs # bytes; returns None when no frame is available
if frame is not None:
sw2, pos2 = struct.unpack_from("<Hi", frame, 0)
print(f"状态字=0x{sw2:04X} 位置={pos2}") # Status word=0x{sw2:04X} position={pos2}

Cycle variation​

One mapping is enough; put the same mapping into your own cycle loop (or a scheduling point inside the loop) and use it directly:

import time

while running:
outputs.control_word = 0x000F if inputs.status_word & 0x0004 else 0x0006
outputs.target_position = inputs.actual_position
time.sleep(0.001) # Your own pacing, for example 1 ms

The underlying layer moves process data every cycle: reads in the loop always see the current cycle, writes go out in the next cycle, no extra call is needed, and you must not remap every sample (the old view only becomes invalid after close() / re-entering OP; just take it once again when you re-enter OP).

Struct mapping (zero-copy)​

inputs_mapping() / outputs_mapping()​

def inputs_mapping(self, struct_type, offset=0)      # TxPDO (slave → master): read-only
def outputs_mapping(self, struct_type, offset=0) # RxPDO (master → slave): readable and writable

Map a fixed-width struct onto the live process image; after mapping once, reading a field reads the current cycle value (zero-copy, not a snapshot).

Parameters:

  • struct_type (fixed-width struct type) — _pack_ = 1 is required, with field order matching the PDO mapping for that direction byte for byte
  • offset (int) — byte offset relative to the start of the process image for that direction (optional), default 0

Returns:

  • Input direction — a struct instance mapped directly onto the live input process image; read-only, assigning to a field raises RuntimeError
  • Output direction — a struct instance mapped directly onto the live output process image; changing a field changes the PDO and it is sent in the next cycle

Description:

  • Call this after entering OP.
  • The following cases all raise RuntimeError:
    • Mapping failure (master not started / not in OP / no mapping for that direction)
    • The image is empty
    • offset is negative
    • offset + struct_type 的字节尺寸 byte size exceeds the image byte count
    • The struct has determinable padding bytes

Example:

inputs  = slave.pdo.inputs_mapping(InPdo)           # Map only once (after entering OP)
outputs = slave.pdo.outputs_mapping(OutPdo)

outputs.control_word = 0x000F # Write: sent in the next cycle
pos = inputs.actual_position # Read: current cycle value

inputs_slice_mapping() / outputs_slice_mapping()​

Map directly at a given byte offset, for devices such as MDP that are segmented per module.

def inputs_slice_mapping(self, struct_type, offset)   # Input slice: read-only
def outputs_slice_mapping(self, struct_type, offset) # Output slice: writable

Parameters:

  • struct_type (fixed-width struct type) — _pack_ = 1 is required, with field order matching the PDO mapping byte for byte
  • offset (int) — byte offset relative to the start of the process image for that direction; required (no default 0, to avoid accidentally writing a slice call as a whole-segment call)

Returns:

  • Same type as inputs_mapping / outputs_mapping — a struct instance mapped directly at offset in the live process image (not a snapshot); read-only for the input direction

Description:

  • Same implementation and same out-of-range rules as inputs_mapping(struct_type, offset).
  • A negative offset, or offset + struct_type 的字节尺寸 byte size exceeding the image byte count, raises RuntimeError.

Example:

# MDP device: module 1 starts at offset 0 and module 2 starts at offset 8 (each module defines its own ctypes struct)
mod1 = slave.pdo.inputs_slice_mapping(Module1In, 0)
mod2 = slave.pdo.inputs_slice_mapping(Module2In, 8)

out2 = slave.pdo.outputs_slice_mapping(Module2Out, 8)
out2.setpoint = 1500

bind_pdo_struct()​

def bind_pdo_struct(self, struct_type, is_input=True, offset=0)

Selects inputs_mapping / outputs_mapping from a direction flag, giving call sites that need both directions a single entry point.

Parameters:

  • struct_type (fixed-width struct type) — _pack_ = 1 is required
  • is_input (bool) — True selects the input direction (read-only), False selects the output direction (writable), default True
  • offset (int) — byte offset relative to the start of the process image for that direction, default 0

Returns:

  • Struct instance — mapped directly onto the live process image (not a snapshot); read-only for the input direction

Example:

input_ref = slave.pdo.bind_pdo_struct(InPdo, is_input=True)
print(input_ref.actual_position) # Every read gives the latest value

inputs_mapping_info / outputs_mapping_info​

@property
def inputs_mapping_info(self) -> dict # slave.pdo
@property
def outputs_mapping_info(self) -> dict

The live pointer and byte count of the process image for this direction, used to check the struct size before mapping.

Returns:

  • dict — {"pointer": int, "size": int, "slave_index": int}; size is the process image byte count for this direction, 0 when not in OP / not mapped

Example:

import ctypes

if ctypes.sizeof(InPdo) > slave.pdo.inputs_mapping_info["size"]:
raise RuntimeError("结构体大于输入 PDO") # (SDK output, = struct larger than input PDO)

try_get_inputs_ptr() / is_input_frame_stale​

The liveness guard for the input direction: tells you whether this input image can be used as the current value right now. It does not throw.

def try_get_inputs_ptr(self) -> Optional[Tuple[int, int]]

@property
def is_input_frame_stale(self) -> bool

Returns:

  • tuple[int, int] — (输入过程映像指针, 字节数); the same live image inputs_mapping() points at
  • None — the image is unavailable (not mapped / not in OP / this slave has no input mapping), or the slave is offline
  • is_input_frame_stale → bool — whether the input frame can no longer be used as the current value; True only when LOST was actually measured

Notes:

  • While a slave is offline the I area keeps the last frame from before the drop (the "input stability" rule); that is not the current value. This entry point returns None at that moment so the caller can take its own failure branch instead of consuming a stale value.
  • The only criterion is the lost-slave determination, the same source as the snapshot path: it returns None only when LOST was actually measured. With no measurement evidence it reports the image as usable ("not confirmed offline"), so "not measured" never hurts a normal cycle.
  • It applies to the input direction only: the output area is the master's own shadow frame, so a slave going offline does not invalidate it and the output direction is not intercepted.
  • If the liveness read fails, is_input_frame_stale returns False ("unknown is not lost"), matching the fail-safe semantics of slave.is_lost; use slave.is_lost (tri-state, None on read failure) for the online check itself.
  • This entry point only checks liveness at the moment the pointer is taken. Callers that hold the pointer and read it across cycles must re-check with slave.is_lost themselves.
inputs_mapping() does not guard against a lost slave

inputs_mapping() / inputs_slice_mapping() / bind_pdo_struct(is_input=True) only validate image availability and byte size; they do not check whether the slave is offline. Once mapped, you read whatever is in the I area (the last frame before the drop while offline). The whole-frame snapshot slave.pdo.inputs returns None when the input frame is stale (the same shape as "no frame available", so None alone cannot tell you which happened). To confirm that a frame is the current value before consuming it, call try_get_inputs_ptr() first, or check slave.is_lost.

Example:

import ctypes

ptr = slave.pdo.try_get_inputs_ptr()
if ptr is None:
# Image unavailable, or the slave is offline (the I area holds the last frame before the drop)
print("本周期输入不可用,按掉线处理") # Inputs unavailable this cycle, treated as connection loss
else:
frame = ctypes.string_at(ptr[0], ptr[1]) # read this frame without writing to the image
status_word = frame[0] | (frame[1] << 8)
print(f"状态字=0x{status_word:04X}, 本帧 {ptr[1]} 字节") # Status word=0x{status_word:04X}, {ptr[1]} bytes in this frame

Direct access (works without mapping)​

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

input_array / output_array​

@property
def input_array(self) -> PDOArrayInstance # TxPDO (slave → master): read-only
@property
def output_array(self) -> PDOArrayInstance # RxPDO (master → slave): readable and writable

Index process data elements by byte offset: input_array[i] reads inputs, output_array[i] reads and writes outputs, and i is relative to the start of the process image for this direction.

Returns:

  • PDOArrayInstance — a process image view indexed by byte; length is the process image byte count for this direction, 0 when not in OP / not mapped (in that case any index raises IndexError)

Description:

  • input_array is TxPDO, overwritten by the master every cycle and read-only: writing one of its element members or input_array[i] = v always raises RuntimeError.
  • output_array is RxPDO; every member assignment goes through a versioned transaction (Copy → modify frame → commit, with bounded retries on conflict), and a successful write is sent in the next cycle.
  • A failed commit raises RuntimeError.
  • Element views are cached and reused by offset; every read takes a snapshot of the current frame and then parses it by offset — the same snapshot semantics as slave.pdo.inputs, not the zero-copy direct mapping reference of inputs_mapping().
  • An out-of-range index raises IndexError; an offset or width outside the process image for this direction raises ValueError (deliberately kept separate from an out-of-range index, so you can tell a wrong byte from a wrong type).
  • A non-integer index, or a non-integer assignment to an integer member (content and as_int8 … as_uint64; bool counts as 0 / 1), raises TypeError.
  • as_float / as_double also accept int / float / bool.
  • When a snapshot cannot be obtained (not in OP / no mapping for that direction) it raises RuntimeError.

Freshness:

  • One member access = one new snapshot.
  • If item.as_int16 and item.as_bool are read separately, a bus cycle may pass between the two reads, so two fields of the same element may come from different samples.
  • For several fields to be consistent within one sample, first take a whole frame with frame = slave.pdo.inputs, then parse that single bytes object by offset.
  • For a zero-copy whole-segment view, use inputs_mapping(struct_type).

Byte order: multi-byte values are always little-endian (EtherCAT wire order); this layer performs no byte swapping.

zero-copy:

  • Element accessors are not a zero-copy path — every read first copies a complete process image frame (length bytes) and then parses it by offset.
  • Only the following entry points are zero-copy (all map directly onto the live process image, not a snapshot):
    • inputs_mapping
    • outputs_mapping
    • inputs_slice_mapping
    • outputs_slice_mapping
    • bind_pdo_struct

Related structures:

class PDOArrayInstance:        # slave.pdo.input_array / output_array
length # int, read-only: process image byte count for this direction; not in OP / not mapped = 0
def __getitem__(index) # → PDODataItem; index ∉ [0, length) raises IndexError
def __setitem__(index, value) # output_array[i] = v ≡ output_array[i].content = v
def __len__() # ≡ length

class PDODataItem: # View of a single PDO item: slave.pdo.input_array[i] / output_array[i]
content # int, read/write: raw byte (unsigned 8-bit)
as_int8 # int, read/write: signed 8-bit
as_uint8 # Same meaning and same byte as content
as_int16 # Multi-byte values are always little-endian (EtherCAT wire order)
as_uint16
as_int32
as_uint32
as_int64
as_uint64
as_float # IEEE754 single precision
as_double # IEEE754 double precision
as_bool # bool, read/write: bit0 semantics; True only when the lowest bit is 1
def get_bit_in_byte(bit_index) # → bool; bit_index 0-7, 0 = LSB
def set_bit_in_byte(bit_index, value) # Output direction only; changes only the target bit, leaving the other bits of the same byte untouched
def as_value(data_type) # Read by EcDataType: only the 11 fixed-width types are supported
def write_value(data_type, value) # Write by EcDataType
def as_base_data(data_type) # → BaseData: the outlet for bit strings / variable-length types
def write_from_base_data(data) # → bool; returns False on failure (no exception)
def __int__() # int(item) ≡ .content

as_bool only looks at the lowest bit: bytes 0x02 and 0x80 both read False.

Writing as_bool writes the whole byte: True writes 0x01 and False writes 0x00 (it does not change a single bit), so bit1–bit7 of that byte are cleared as well; for bit-level reads and writes use get_bit_in_byte() / set_bit_in_byte().

To judge truth by a whole byte being 0 / non-0, read content and compare it yourself — there is no second path where non-0 means true.

as_value / write_value only support the 11 data types that map one-to-one to fixed-width types:

  • BOOLEAN
  • INTEGER8 / INTEGER16 / INTEGER32 / INTEGER64
  • UNSIGNED8 / UNSIGNED16 / UNSIGNED32 / UNSIGNED64
  • REAL32 / REAL64

Bit strings (BIT1…BIT8), 24 / 40 / 48 / 56-bit integers, strings and DOMAIN all raise ValueError.

Example:

item = slave.pdo.input_array[2]                  # Element view at offset 2
pos = item.as_int32 # Read: current frame snapshot
sw = slave.pdo.input_array[0].as_uint16 # 2 bytes starting at offset 0 (StatusWord)

slave.pdo.output_array[2].as_int32 = 10000 # Write: versioned partial commit, sent in the next cycle
slave.pdo.output_array[0].set_bit_in_byte(0, True) # Sets only bit0; the other bits of the same byte stay untouched
slave.pdo.output_array[0] = 0x11 # ≡ output_array[0].content = 0x11
flag = slave.pdo.input_array[3].as_bool # bit0 semantics
byte0 = int(slave.pdo.input_array[0]) # ≡ .content

for i in range(slave.pdo.output_array.length): # Iterate the whole output image
slave.pdo.output_array[i].set_bit_in_byte(0, False)

get_bit_in_byte() / set_bit_in_byte()​

Read / write bit bit_index of the byte the element is in.

def get_bit_in_byte(self, bit_index) -> bool
def set_bit_in_byte(self, bit_index, value) -> None

Parameters:

  • bit_index (int) — bit number 0-7, where 0 is the least significant bit (LSB); anything outside 0-7 raises ValueError
  • value (bool) — new value of the target bit (set_bit_in_byte only)

Returns:

  • bool — whether that bit is currently 1 (get_bit_in_byte)
  • None — set_bit_in_byte returns nothing

Description:

  • Bit operations are byte-addressed and independent of the element width: whether the element is interpreted as a 1 / 2 / 4 / 8-byte type, bit_index always refers to that one byte at the element offset and never extends into adjacent bytes.
  • get_bit_in_byte can read in both the input and output direction.
  • set_bit_in_byte is for the output direction only (the input direction raises RuntimeError); it goes through a versioned transaction, changes only the target bit, and leaves the other bits of the same byte unchanged.
  • An offset beyond the current frame raises ValueError, and a failed transaction commit raises RuntimeError.

Example:

slave.pdo.output_array[0].set_bit_in_byte(0, True)       # bit0 of the byte at offset 0
slave.pdo.output_array[0].set_bit_in_byte(7, False) # bit7 of the same byte
ready = slave.pdo.input_array[4].get_bit_in_byte(2) # bit2 of the byte at offset 4 — independent of the element width

as_value() / write_value()​

def as_value(self, data_type)                        # → int | float | bool
def write_value(self, data_type, value) # Output direction only

Read and write using the data type of that PDO mapping entry in the ESI / ENI, so you do not have to remember the width yourself.

Parameters:

  • data_type (EcDataType) — the mapping type at that position
  • value — the value to write (write_value only); it is converted to the target type and does not have to be of the same kind as data_type

Returns:

  • int / float / bool — the value read; BOOLEAN returns bool (bit0 semantics)

Description:

  • Only the exactly 11 fixed-width types are accepted; everything else raises ValueError — no width guessing and no silent 1-byte read (BIT8 deliberately does not fall back to as_uint8: a bit string and an unsigned 8-bit value have different semantics).
  • write_value converts the value to the target type: floating-point to integer rounds to nearest even, and NaN / infinity / values outside the target type range raise OverflowError.
  • value=None or an unsupported source type raises TypeError.

Example:

from darra_ethercat import EcDataType

pos = slave.pdo.input_array[2].as_value(EcDataType.INTEGER32)
flag = slave.pdo.input_array[3].as_value(EcDataType.BOOLEAN) # bit0 semantics

slave.pdo.output_array[2].write_value(EcDataType.INTEGER32, 10000)

as_base_data() / write_from_base_data()​

Wide-type outlet: as_value / write_value cover only the 11 fixed-width types; use this pair for bit strings and variable-length fields.

def as_base_data(self, data_type) -> BaseData
def write_from_base_data(self, data) -> bool

Parameters:

  • data_type (EcDataType) — the mapping type at that position; the byte width comes from the data type table (rounded up to a whole byte), and variable-length / unknown types are treated as 1 byte
  • data (BaseData) — the whole raw byte segment to write back

Returns:

  • BaseData — a wrapper around the raw bytes copied from the current position using the data_type width
  • bool — whether the write succeeded; returns False on failure (no exception), and the input direction always returns False

Description:

  • as_base_data raises ValueError when the offset / width goes beyond the current frame.
  • write_from_base_data goes through the output PDO versioned commit and is sent in the next cycle.
  • Out-of-range, an object that is not BaseData, and empty data all return False without raising an exception.

Example:

from darra_ethercat import EcDataType
from darra_ethercat.utils import BaseData

wide = slave.pdo.input_array[0].as_base_data(EcDataType.BIT3) # Bit string: not covered by the fixed-width scalars
ok = slave.pdo.output_array[0].write_from_base_data(wide) # Returns False on failure (no exception)

blob = BaseData(b"\x01\x02", dtype=EcDataType.UNSIGNED16) # You can also construct the whole segment yourself and write it back
slave.pdo.output_array[0].write_from_base_data(blob)

inputs / outputs / write_outputs()​

Access the whole process image frame by byte, for fields the struct cannot hold (strings, variable-length data).

@property
def inputs(self) -> Optional[bytes] # Whole input frame: each access returns a private snapshot
@property
def outputs(self) -> Optional[bytes] # Whole output frame snapshot
def write_outputs(self, data) -> bool # Whole-frame replacement
@property
def last_write_status(self) -> Optional[int] # PdoIoStatus of the most recent write_outputs

Returns:

  • bytes — a snapshot, not zero-copy: consistent within one sample and it does not change with the bus after being copied; returns None when no frame is available, and b"" when that direction has length 0
  • bool — whether the write succeeded (write_outputs)
  • Optional[int] — last_write_status: the PdoIoStatus integer value of the most recent write_outputs; None when it has never been written

Description:

  • These members are declared on slave.pdo (slave.pdo.inputs / slave.pdo.last_write_status), not on slave.
  • write_outputs is the single-writer authoritative whole-frame replacement: when the length does not match the process image byte count for that direction it refuses and returns False, without truncating.
  • It is a whole-frame write; do not use it for partial / bulk read-modify-write (those updates belong to element view members, which go through versioned transactions).
  • For the failure reason check last_write_status (a PdoIoStatus integer value): BUSY = the iomap is held by the RT cycle thread (the method already retries with a bound; still returning BUSY means it still could not acquire it, which is not a silent dropped write and may be resent); SIZE_MISMATCH = the length does not match the current PDO mapping; FAILED = invalid arguments / call exception; other values follow the corresponding PdoIoStatus semantics.

last_write_status returns Optional[int]: None when write_outputs() has never been called, otherwise the integer value of PdoIoStatus (an IntEnum, from darra_ethercat.utils.dll import PdoIoStatus):

class PdoIoStatus(IntEnum):
FAILED = 0
OK = 1
BUFFER_TOO_SMALL = 2
SIZE_MISMATCH = 3
CONFLICT = 4
STALE = 5
BUSY = 6

The success member is named OK in this language, Success in C# / Java and Ok in Rust — all have the numeric value 1, and the name follows each language SDK's own naming.

Example:

frame = slave.pdo.inputs
if frame is not None:
name = frame[6:22].split(b"\x00", 1)[0].decode("ascii", "replace")
print(f"status=0x{frame[0] | (frame[1] << 8):04X} name={name}")

out = bytearray(slave.pdo.outputs or b"")
if out:
out[0:2] = (0x000F).to_bytes(2, "little")
slave.pdo.write_outputs(bytes(out)) # Whole-frame replacement

batch_read() / batch_write()​

Read several ranges in one call / commit several ranges in one call.

def batch_read(self, requests) -> list               # Extract several ranges from one snapshot
def batch_write(self, requests) -> int # Write several ranges in one transaction

Parameters:

  • requests (list) — a list of (offset, data) tuples for batch_read; a list of (offset, size) tuples for batch_write
  • offset (int) — byte offset relative to the start of the process image for that direction

Returns:

  • list — batch_read returns a list of bytes, with None for failed items
  • int — batch_write returns the number of successfully written items (the whole batch is one transaction: returns the total when all succeed, and 0 when any item fails)

Description:

  • batch_read takes one complete input frame snapshot and extracts several ranges from the same sample.
  • batch_write is one transaction, one commit: any out-of-range item fails the whole batch, with no partial commit and no silent truncation.
  • Single-field reads and writes go through the element views (input_array / output_array): read slave.pdo.input_array[0].as_uint16, write slave.pdo.output_array[0].as_int32 = 10000; out of range raises an exception instead of returning a default value.
  • For fields the struct cannot hold, such as strings, decode the whole frame inputs / outputs yourself.

Example:

values = slave.pdo.batch_read([(0, 2), (2, 4)])      # One snapshot, several fields
ok = slave.pdo.batch_write([(0, (0x000F).to_bytes(2, "little")),
(2, (10000).to_bytes(4, "little"))])

Slave.pdo_read()​

def pdo_read(self, pdo_index: int, buffer_size: int = 256) -> Optional[bytes]

Reads a copy of this slave's complete input process data frame (TxPDO). Declared on the slave object (slave.pdo_read(...)), not on slave.pdo.

Parameters:

  • pdo_index (int) — a placeholder kept for the historical call convention; it takes no part in slicing and only appears in failure logs; always pass 0
  • buffer_size (int) — the maximum number of bytes copied in one call, default 256; a negative value makes buffer allocation raise ValueError directly

Returns:

  • bytes — the input data read, at most buffer_size bytes long, with all fields of the same bytes object consistent within one sample
  • None — invalid arguments, the slave is offline / the read fails underneath, or 0 bytes were read this time; an empty bytes is never used to stand in for "no data"

Description:

  • This is a snapshot copy, not a zero-copy live view; for continuous direct reads use inputs_mapping().
  • Difference from slave.pdo.inputs: this method can cap the maximum length of a single read, so you do not have to fetch the whole frame first and then slice it.
  • When the runtime lacks this read entry point it raises NotImplementedError and does not disguise itself as None.

Example:

data = slave.pdo_read(0, 256)
if data is not None:
status_word = int.from_bytes(data[0:2], "little")
print(f"状态字=0x{status_word:04X}, 本帧 {len(data)} 字节") # Status word=0x{status_word:04X}, {len(data)} bytes in this frame

Slave.pdo_write()​

def pdo_write(self, pdo_index: int, data: bytes) -> bool

The whole-frame RxPDO write entry point kept for the old signature; it writes from offset 0 of the complete RxPDO.

Parameters:

  • pdo_index (int) — only 0 is accepted; the historical implementation never interpreted this parameter, and a value other than 0 cannot be reliably mapped to a byte offset, so it always fails
  • data (bytes) — the complete RxPDO frame; it must not be empty and its length must equal the output process image byte count

Returns:

  • bool — True = written; False = pdo_index is not 0, the data is empty, the length does not match the RxPDO, the argument type is invalid, or the write failed
A pdo_index other than 0 is not a partial write

Passing a value other than 0 does not degrade into "write only at some offset"; it returns False directly. To rewrite by offset use slave.pdo.output_array[...] or write_output_data_direct().

Short data is not accepted either

This entry point takes the whole-frame write path; when data is shorter than the complete RxPDO it does not "update only the leading bytes" but returns False. For partial updates use the output element views or write_output_data_direct().

Example:

frame = slave.pdo.outputs
if frame is not None:
ok = slave.pdo_write(0, bytes(frame)) # must be the full frame length
print("写入成功" if ok else "写入被拒绝") # Write succeeded / write rejected

Slave.write_output()​

def write_output(self, data: bytes) -> bool

Writes outputs as a complete RxPDO frame; this is the slave-level entry point for slave.pdo.write_outputs(data).

Language boundary: write_output() on this page 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 (bytes) — the complete RxPDO frame; its length must equal the output process image byte count

Returns:

  • bool — True = the whole frame was written; False = the length does not match (refused, not truncated) or the write failed

Description:

  • Like pdo_write() it requires the whole-frame length; the only difference is that pdo_write() keeps the pdo_index parameter from the old signature (only 0 is accepted).
  • Do not use this method for partial rewrites; use the output element views or write_output_data_direct().
  • For the failure reason check slave.pdo.last_write_status (a PdoIoStatus integer value).

Example:

frame = slave.pdo.outputs
if frame is not None:
out = bytearray(frame)
out[0:2] = (0x000F).to_bytes(2, "little")
slave.write_output(bytes(out))

SlavePdo.read_input_data_direct()​

def read_input_data_direct(self, buffer: bytearray, offset: int = 0,
length: int = 0) -> int

Copies the input frame into a writable buffer supplied by the caller, which suits reusing an allocated buffer and avoids creating a new bytes object on every call.

Parameters:

  • buffer (bytearray) — the target buffer; it must be writable
  • offset (int) — the write offset inside the target buffer, default 0
  • length (int) — the number of bytes to read, 0 = read to the end of the frame, default 0

Returns:

  • int — the number of bytes actually written
  • 0 — failure / no data (the frame cannot be obtained, arguments are invalid, or the target buffer has no space left)

Description:

  • Internally it first copies a complete input frame snapshot and then writes it into buffer; all fields within the same snapshot are consistent within one sample.
  • offset is an offset in the target buffer, not in the process image; the requested length is also clipped by the frame length and the remaining space in the target buffer, so it never writes out of bounds.
  • When the runtime lacks the input copy entry point it raises NotImplementedError; every other failure path returns 0.

Example:

buf = bytearray(64)
n = slave.pdo.read_input_data_direct(buf, 0, 32)
if n:
print(f"读到 {n} 字节: {buf[:n].hex()}") # Read {n} bytes: {buf[:n].hex()}

SlavePdo.write_output_data_direct()​

def write_output_data_direct(self, data: bytes, offset: int = 0,
length: int = 0) -> int

Merges a segment of output data into the complete RxPDO and writes it back precisely.

Parameters:

  • data (bytes) — the source data
  • offset (int) — the start offset within the source data, which also serves as the target offset in the output process image, default 0
  • length (int) — the number of bytes to write, 0 = from offset to the end of the source data, default 0

Returns:

  • int — the number of bytes actually written
  • 0 — failure (invalid arguments, the requested length exceeds the length available in the source data, or reading / writing back the frame fails); there is no partial-success count

Description:

  • With offset != 0 it goes through a versioned partial commit: read back the complete RxPDO → change the target range → write it back precisely.
  • With offset == 0 it writes as a whole frame: the length written this time must exactly equal the output process image byte count, otherwise it returns 0. To change a region starting at byte 0 partially, first take slave.pdo.outputs, assemble the whole frame and then use write_outputs().
  • A failed write returns 0; it never returns the byte count of a half-written frame.

Example:

# Write the 2 bytes starting at source offset 2 to output process image offset 2
n = slave.pdo.write_output_data_direct(b"\x01\x02\x0f\x00", 2, 2)
if n == 0:
print("写入被拒绝或失败") # Write rejected or failed

SlavePdo.get_input_memoryview()​

def get_input_memoryview(self) -> memoryview

Returns a read-only snapshot memoryview of the input process data.

Returns:

  • memoryview — a read-only view of the whole input frame; when the read fails / nothing is mapped yet it returns an empty memoryview (length 0)
  • When the runtime lacks the input copy entry point it raises NotImplementedError and does not collapse into an empty view

Description:

  • Internally it first copies a complete snapshot; this is not a live pointer, and the snapshot does not change with later bus cycles.
  • It has the same snapshot semantics as slave.pdo.inputs; the difference is that this method hands back a memoryview, so slicing copies no further bytes and the result can go straight to struct.unpack_from.
  • The view is read-only and assignment raises TypeError; to write outputs use write_outputs() or the output element views.

Example:

mv = slave.pdo.get_input_memoryview()
if len(mv) >= 2:
status_word = int.from_bytes(mv[0:2], "little")
print(f"状态字=0x{status_word:04X}") # Status word=0x{status_word:04X}

SlavePdo.get_output_memoryview()​

def get_output_memoryview(self) -> memoryview

Returns a read-only snapshot memoryview of the output process data.

Returns:

  • memoryview — a read-only view of the whole output frame; when the read fails / nothing is mapped yet it returns an empty memoryview (length 0)
  • When the runtime lacks the output copy entry point it raises NotImplementedError and does not collapse into an empty view

Description:

  • It has the same snapshot semantics as slave.pdo.outputs; it is likewise a read-only snapshot, so changing it does not write back to the bus.
  • To write outputs use write_outputs(), the output element views or write_output_data_direct().

Example:

mv = slave.pdo.get_output_memoryview()
if len(mv) >= 2:
print(f"当前控制字=0x{int.from_bytes(mv[0:2], 'little'):04X}") # Current control word=0x{int.from_bytes(mv[0:2], 'little'):04X}

Complete example​

import ctypes
import time
from darra_ethercat import EcDataType, EtherCATMaster, EcState

class InPdo(ctypes.Structure):
_pack_ = 1
_fields_ = [("status_word", ctypes.c_uint16),
("actual_position", ctypes.c_int32)]

class OutPdo(ctypes.Structure):
_pack_ = 1
_fields_ = [("control_word", ctypes.c_uint16),
("target_position", ctypes.c_int32)]

master = (EtherCATMaster()
.set_eni(r"C:\EtherCAT\MyProject.deni") # Load DENI in one line
.build())
master.set_state(EcState.OP) # Enter OP

slave = master[1] # Slave (1-based index)

# ① zero-copy: map once and the struct maps directly onto the live process image
inputs = slave.pdo.inputs_mapping(InPdo) # Read-only view
outputs = slave.pdo.outputs_mapping(OutPdo)

# ② Element views: no struct definition, single-point reads and writes by byte offset
print(slave.pdo.input_array[0].as_uint16) # 2 bytes starting at offset 0, little-endian
slave.pdo.output_array[2].write_value(EcDataType.INTEGER32, 10000)
slave.pdo.output_array[0].set_bit_in_byte(0, True) # Change only bit0 of the byte at offset 0

# ③ Whole-frame snapshot: consistent within one sample, for fields the struct cannot hold
frame = slave.pdo.inputs
if frame is not None:
print(f"快照 {len(frame)} 字节, status=0x{frame[0] | (frame[1] << 8):04X}") # Snapshot {len(frame)} bytes, status=0x{frame[0] | (frame[1] << 8):04X}

# Cycle loop: reads always see the current cycle, writes go out in the next cycle
for _ in range(1000):
outputs.control_word = 0x000F if inputs.status_word & 0x0004 else 0x0006
outputs.target_position = inputs.actual_position
time.sleep(0.001) # Your own pacing, for example 1 ms

print(f"状态字=0x{inputs.status_word:04X} 位置={inputs.actual_position}") # Status word=0x{inputs.status_word:04X} position={inputs.actual_position}
master.close()
Type width must match the mapping

The byte width at offset must match the mapping entry: reading an I32 on a mapping entry that is only 2 bytes reads into an adjacent field. as_value(EcDataType...) / write_value() support only the 11 fixed-width types; bit strings and variable-length fields go through as_base_data() / write_from_base_data(). All reads and writes land on the same process image; do not build a second cache.