Skip to main content

PDO inputs and outputs

Access the process image through the mapping view and element view of slave.PDO(), and the whole-frame read/write of slave.slavePdo().​

A PDO is a segment of data inside the process image, sent and received automatically every cycle at runtime. Once mapped into a structure, the view maps directly onto the process image — zero-copy: the mapping itself does not copy data and does not create a separate buffer for the whole frame; what you write is sent in the next cycle; but the structure's fields are Java-side caches, so you must read() before reading and write() after modifying, otherwise you read stale values and your writes do not take effect.

Process image capacity (two readings)
  • The per-pass process image for this product (input + output + per-station mailbox state combined) has an upper limit of 64 KB (65536 bytes)
  • The lower-layer buffer reserves 64 KB per direction (double buffering; this is the reservation, not the usable amount)
  • The single-frame LRW process data limit is 1486 bytes; a single group above about 1.5 KB loses the zero-copy fast path and switches to multi-frame forwarding (up to 16 frames rotating per component per cycle) — plan for 「single group ≤ 1.4 KB」 during selection
  • Slave count: the per-master slave table limit is 2048 (1-based station table, up to 2047 slaves)
  • Capacity exclusivity point: with an average of ≤ 32 B per station the slave table limit (2048) is hit first; only with > 32 B is the 64 KB limit hit first

Method overview​

CategoryMethodTypeRead/writeDescription
Struct mappinginputsMapping(Class<T>)Tread-onlyMap to TxPDO; after read() the fields are the current cycle
inputsSliceMapping(Class<T>, offset)Tread-onlyMap starting at byte offset in the input image
outputsMapping(Class<T>)Tread/writeMap to RxPDO; changes take effect after write()
outputsSliceMapping(Class<T>, offset)Tread/writeMap starting at byte offset in the output image
bindPdoStruct(Class<T>, isInput)Tread/writeUse isInput to select the direction, provided only on slavePdo(); returns null on failure
Element viewin() / out()PDOArrayInstanceread/writeIndex this direction's process image by byte; in is read-only and writing to it throws UnsupportedOperationException
get(index) / set(index, value)PDODataItem / voidread/writeGet the element view at byte index / write a single byte; out of range throws IndexOutOfBoundsException
length()intread-onlyByte count of this direction's process image; 0 when not in OP
Fixed-width read/writecontent() / content(byte)byteread/writeSingle-byte raw value (same byte as asInt8 / asUInt8)
asInt8 / asUInt8 / asInt16 / asUInt16 / asInt32 / asUInt32 / asInt64 / asUInt64Per fixed widthread/writeFixed-width integer read/write, always little-endian for multi-byte; the same-named overload with an argument writes
asFloat / asDoublefloat / doubleread/write32 / 64-bit floating point (little-endian)
asBool() / asBool(boolean)booleanread/writebit0 semantics; writes the whole byte (true→0x01)
asValue(EcDataType) / writeValue(EcDataType, Object)Object / voidread/writeHandles the 11 fixed-width types; other types throw IllegalArgumentException
asBaseData(int dataType) / writeFromBaseData(BaseData)BaseData / booleanread/writeTake a byte copy / write the whole segment back, returns false on failure
Bit operationsgetBit(bitIndex)booleanread-onlyBit n of the byte the element points at (0 = LSB)
setBit(bitIndex, value)voidwrite-onlyBit-field read-modify-write, changes only that bit; for out only
Whole frameslavePdo().inputs() / outputs()byte[]read-onlyWhole input / output frame snapshot, consistent within one sample
slavePdo().outputs(byte[])booleanwrite-onlyExact whole-frame replacement, length must equal the output mapping
copyInputPdo / copyOutputPdoPdoIoStatusread-onlyCopy into the caller's buffer, returns copied and required lengths
writeOutputPdoPdoIoStatuswrite-onlyWhole-frame write, bounded retry on Busy
Partial writewriteFromTyped(byte[], byteOffset)booleanwrite-onlyPatch a chunk of bytes at an offset (versioned read-modify-write transaction)
readInputDataDirect / writeOutputDataDirectintread/writeRead the input frame / write the output frame, returns the actual byte count
BatchbatchRead(int[], int[])ByteBuffer[]read-onlyRead multiple offsets in one call, failed entries are null
batchWrite(int[], byte[][])intwrite-onlyWrite multiple offsets in one transaction, returns the number of applied entries
batchReadPooled / batchWritePooledMap / intread/writeBatch read / write across multiple slaves
StringslavePdo().readString(offset, maxLength)Stringread-onlyFixed-length string (NUL-terminated); returns null when the frame is unavailable or the offset is out of range
slavePdo().writeString(offset, value, maxLength)booleanwrite-onlyWrite and pad with NUL to maxLength; over-long UTF-8 throws IllegalArgumentException
Group dividergetGroupCycleDivider(group) / setGroupCycleDivider(group, divider)byte / booleanread/writeGroup PDO cycle divider, see Divider frequency calculation
MonitoringstartMonitoring() / stopMonitoring()voidwrite-onlyPDO monitoring switch (the sampling interval is not configurable)
IOmap locklockIOmap() / unlockIOmap()boolean / voidread/writeNon-blocking try-lock; only the holder may unlock
Status statisticsisValid() / expectedSize()boolean / intread-onlyWhether mapped / total input+output byte count
avgCycleTimeNs() / errorCount()long / intread-onlyThis slave's average PDO cycle (ns) / error count
Relationship between the PDO cycle and the mailbox

Mailbox reads (SDO/CoE/FoE, etc.) are piggybacked on PDO frames and do not consume extra cycle time. Mailbox response latency is about 2-3 PDO cycles.

Outbound mailbox traffic (such as SDO writes) is scheduled adaptively by the system according to the PDO cycle; no user intervention is needed.

Usage examples​

Everyday use​

① Map to a class (zero-copy, continuous use): map once after entering OP, get a Structure view that maps directly onto the process image, and then read and write it as variables.

import com.sun.jna.Structure;
import com.sun.jna.Structure.FieldOrder;

@FieldOrder({"statusWord", "actualPosition"}) // Field order matches the PDO byte for byte
public static class InPdo extends Structure {
public short statusWord;
public int actualPosition;
public InPdo() { super(ALIGN_NONE); } // ALIGN_NONE = Pack 1, required
}

@FieldOrder({"controlWord", "targetPosition"})
public static class OutPdo extends Structure {
public short controlWord;
public int targetPosition;
public OutPdo() { super(ALIGN_NONE); }
}
import com.darra.ethercat.master.EtherCATMaster;
import com.darra.ethercat.data.EcState;
import com.darra.ethercat.slave.Slave;

EtherCATMaster.BuildResult r = EtherCATMaster.create()
.setENI("C:/EtherCAT/MyProject.deni") // DENI one-line load
.build();
if (!r.success) throw new Exception(r.message);
EtherCATMaster master = r.master;
if (!master.setState(EcState.OP)) { // Enter OP, must check the return value
System.out.println("进入 OP 失败, 状态 " + master.state()); // Failed to enter OP, state {master.state()}
return;
}

Slave slave = new Slave(master.MasterIndex, (short) 1, master); // The DENI path does not populate the list; construct from master index + station number

InPdo inputs = slave.PDO().inputsMapping(InPdo.class); // Map once (after entering OP)
OutPdo outputs = slave.PDO().outputsMapping(OutPdo.class);

inputs.read(); // Refresh fields = current cycle input
short statusWord = inputs.statusWord;
outputs.controlWord = 0x000F; // Modify fields
outputs.targetPosition = inputs.actualPosition;
outputs.write(); // Write back to the IOmap: sent in the next cycle

② One-off read (single shot): skip the structure and take one current value.

// Single point: take the element view at an offset, then read on the element
int sw = slave.PDO().in().get(0).asUInt16(); // u16 at offset 0 (StatusWord)
int pos = slave.PDO().in().get(2).asInt32(); // i32 at offset 2 (ActualPosition)

// Whole segment: one complete input frame snapshot, consistent within one sample, and it will not change with the bus after copying
byte[] frame = slave.slavePdo().inputs();
String name = new String(frame, 6, 16, java.nio.charset.StandardCharsets.US_ASCII)
.replace("\0", "").trim(); // String field: 16 bytes starting at offset 6
System.out.printf("status=0x%04X pos=%d name=%s%n", sw, pos, name);

Cyclic changes​

Mapping once is enough; put the same mapping into your own cycle loop and use it directly:

while (running) {
inputs.read(); // Input for this cycle
outputs.controlWord = (inputs.statusWord & 0x0004) != 0 ? (short) 0x000F : (short) 0x0006;
outputs.targetPosition = inputs.actualPosition;
outputs.write(); // Write back to the IOmap: sent this cycle
Thread.sleep(1); // Your own cadence, e.g. 1 ms
}

At runtime the process data is moved every cycle: what you read in the loop is always the current cycle and what you write is sent in the next cycle, with no extra call needed, and you should not re-map every sample (close() / re-entering OP is what invalidates the old view; taking it once more when re-entering OP is enough).

Struct mapping​

public <T extends Structure> T inputsMapping(Class<T> type)                // slave.PDO(), input (TxPDO)
public <T extends Structure> T outputsMapping(Class<T> type) // slave.PDO(), output (RxPDO)
public <T extends Structure> T inputsSliceMapping(Class<T> type, int offset) // starting at an offset in the input image
public <T extends Structure> T outputsSliceMapping(Class<T> type, int offset) // starting at an offset in the output image
public <T extends Structure> T bindPdoStruct(Class<T> type, boolean isInput) // only on slavePdo(), returns null on failure

After entering OP, overlay the packed Structure onto the process image: the view maps directly onto the real-time process image (zero-copy, not a snapshot).

PDO.inputsMapping / outputsMapping and the same-named methods on SlavePdo share one implementation; bindPdoStruct(type, isInput) is provided only on SlavePdo (a compatibility entry).

@FieldOrder({"statusWord", "actualPosition", "actualVelocity"})
public static class ServoInput extends Structure {
public short statusWord;
public int actualPosition;
public int actualVelocity;
public ServoInput() { super(ALIGN_NONE); } // Pack 1
}

@FieldOrder({"controlWord", "targetPosition", "targetVelocity"})
public static class ServoOutput extends Structure {
public short controlWord;
public int targetPosition;
public int targetVelocity;
public ServoOutput() { super(ALIGN_NONE); }
}

ServoInput inputs = slave.PDO().inputsMapping(ServoInput.class); // Map only once
ServoOutput outputs = slave.PDO().outputsMapping(ServoOutput.class);

inputs.read(); // read() if you want the latest values
int pos = inputs.actualPosition;
outputs.controlWord = 0x000F;
outputs.targetPosition = pos + 1000;
outputs.write(); // after modifying you must write(), otherwise it does not take effect
  • The structure must extends Structure + constructor super(ALIGN_NONE) (= Pack 1) + @FieldOrder listing the fields explicitly.
  • size() must not exceed the byte count for that direction (slave.ibytes() / slave.obytes()), otherwise it throws IllegalStateException.
  • Fields are Java-side caches: you must inputs.read() before reading and outputs.write() after modifying, otherwise you read stale values and writes do not take effect.
  • The alignment contract is not validated at runtime (only an out-of-range size() throws).
  • Misaligned fields only silently read dirty data.
  • The input mapping hangs on a read-only pointer; calling write() / Pointer.setXxx on an input view throws UnsupportedOperationException.
  • The view does not need re-mapping every sample; after close() / re-entering OP the old view is invalid and must be taken again.
  • Slice mapping: inputsSliceMapping / outputsSliceMapping map starting at byte offset (modular device scenarios), also zero-copy; the input side is likewise read-only.
  • Exception layering for mapping failures: null type or out-of-range offset throws IllegalArgumentException; an unavailable image (not in OP / not mapped) throws IllegalStateException; when the structure does not fit, offset == 0 throws IllegalStateException (the structure is larger than the input / output PDO) and offset > 0 throws IllegalArgumentException.
  • bindPdoStruct(type, isInput) is a compatibility entry (only on slavePdo()): equivalent to choosing between the two methods above with isInput, but it returns null on failure instead of throwing; new code should prefer inputsMapping / outputsMapping (failures throw immediately, so problems are not swallowed).

Element view​

slave.PDO().in() / slave.PDO().out() is the path for taking a single PDO item by byte offset: get(index) yields the element view PDODataItem at the index-th byte, and the fixed-width accessors on the element read and write by type. It reads the same process image as struct mapping — a third path to the same data, except that you do not declare the whole layout up front, only fetch the few fields you use by offset.

get(index) returns a view handle, not a copy: it points at that one byte (or run of bytes) in the process image and stores no data itself. Repeating get at the same offset returns the same element object.

Every access is an independent process image access: a read takes a whole-frame snapshot each time (consistent within one sample), and a write is a versioned read-modify-write transaction.

public PDOArrayInstance in()                   // slave.PDO(), input (TxPDO), read-only
public PDOArrayInstance out() // slave.PDO(), output (RxPDO), writable

public PDODataItem get(int index) // PDOArrayInstance, index = byte offset
public void set(int index, byte value) // PDOArrayInstance, equivalent to get(index).content(value)
public int length() // PDOArrayInstance, byte count of this direction's process image

public PDODataItem(Pointer basePtr, int offset, boolean isInput) // Raw pointer escape hatch, width limit falls back to the protocol limit
public PDODataItem(Pointer basePtr, int offset, boolean isInput, int maxIomapSize) // Same as above, width limit passed explicitly

Reading​

Both in and out are readable. Multi-byte members are always little-endian (the EtherCAT wire order).

public byte    content()                     // Single-byte raw value, fully synonymous with asInt8() / asUInt8()
public byte asInt8() // Signed 8-bit
public byte asUInt8() // Unsigned 8-bit; Java's byte is signed, so & 0xFF yourself to get the unsigned value
public short asInt16()
public int asUInt16() // Returns int to represent unsigned
public int asInt32()
public long asUInt32() // Returns long to represent unsigned
public long asInt64()
public long asUInt64() // Raw 64 bits returned as long; use the Long Unsigned series for an unsigned interpretation
public float asFloat()
public double asDouble()
public boolean asBool() // bit0 semantics, see below
public boolean getBit(int bitIndex) // bitIndex 0-7, 0 = LSB
public Object asValue(EcDataType type) // Boxed value according to the PDO mapping type
public BaseData asBaseData(int dataType) // Byte copy of that type's length (little-endian), not a live view

One read = one independent snapshot: two accesses in the same expression are not guaranteed to be from the same sample; a single multi-byte access is never torn internally.

asBaseData likewise returns a byte copy cut from one whole-frame snapshot of that direction (not a live view).

byte    raw  = slave.PDO().in().get(0).content();     // Raw byte at offset 0
short sw = slave.PDO().in().get(0).asInt16(); // i16 at offsets 0..1 (little-endian)
int pos = slave.PDO().in().get(2).asInt32(); // i32 at offsets 2..5
float vel = slave.PDO().in().get(6).asFloat(); // f32 at offsets 6..9
boolean rdy = slave.PDO().in().get(0).getBit(2); // bit2 at offset 0
boolean en = slave.PDO().in().get(10).asBool(); // bit0 at offset 10

Writing​

Only out (RxPDO, master→slave) is writable.

public void content(byte value)                    // Single byte
public void asInt8(byte value)
public void asUInt8(byte value)
public void asInt16(short value)
public void asUInt16(int value)
public void asInt32(int value)
public void asUInt32(long value)
public void asInt64(long value)
public void asUInt64(long value)
public void asFloat(float value)
public void asDouble(double value)
public void asBool(boolean value) // Writes the whole byte
public void setBit(int bitIndex, boolean value) // Change only that bit; the other bits in the same byte stay untouched
public void writeValue(EcDataType type, Object value)
public boolean writeFromBaseData(BaseData data) // Write the whole segment of bytes back, true on success, false on failure
slave.PDO().out().get(6).content((byte) 0x11);        // Whole byte at offset 6
slave.PDO().out().get(0).asInt16((short) 0x000F); // i16 at offsets 0..1 (little-endian)
slave.PDO().out().get(2).asInt32(pos + 1000); // i32 at offsets 2..5
slave.PDO().out().get(0).setBit(3, true); // Only set bit3 at offset 0

Writes do not land in the process image directly. Each setter call = one versioned read-modify-write transaction: copy the complete output frame → patch bytes on the copy → atomically replace the whole frame.

There is no separate write() step for the caller as in the struct path — the commit happens inside the setter. But it is not "send as soon as you modify": the value you write is replaced atomically with the whole frame at the moment of commit, so there is no race with the master's frame transmission.

Trade-off: whole-frame hot paths still use outputsMapping (zero-copy). The element view is only suitable for single-point or few-field changes and is not suitable inside a 1 ms cycle (see the reason below).

Semantics and boundaries​

  • Byte order: multi-byte members are always little-endian (the EtherCAT wire order); bytes are assembled/split explicitly as little-endian and do not depend on the JVM or platform default byte order.
  • asBool() has bit0 semantics: only when the lowest bit is 1 is it true — 0x01 → true, 0x02 → false, 0x80 → false. It is not "non-zero means true"; to judge truth by the whole byte, read content() and compare yourself (this class deliberately does not provide a second boolean convention).
  • asBool(boolean) writes the whole byte: true → 0x01, false → 0x00; non-canonical bytes are not preserved (writing false clears the whole byte).
  • setBit is a bit-field read-modify-write: only the bitIndex bit changes; the other bits in the same byte keep their original values.
  • bitIndex takes 0-7 (0 = LSB); out of range throws IllegalArgumentException.
  • Writing to in throws UnsupportedOperationException: the I area is overwritten by the master from the slaves every cycle, so writing it is silently ineffective, hence the type-level rejection. The write members on the element and set all throw; writeValue is the exception — it converts the value first, and throws IllegalArgumentException first when the value itself is invalid. Always use out to write process data.
  • A failed element write transaction throws IllegalStateException: not in OP, retries exhausted on conflict or busy, and exhaustion of the 5 ms budget all end here. It never silently drops the write; the caller decides whether to retry or give up (set throws as well).
  • Exception layering (three kinds deliberately reported separately, to locate a wrong byte, a wrong type, or a not-ready state):
    • index outside [0, length()) → IndexOutOfBoundsException;
    • offset + width beyond this direction's process image → IllegalArgumentException;
    • process image unavailable (not in OP / not mapped / null pointer) → IllegalStateException.
  • length() is the byte count of this direction's process image; it is 0 when not in OP or when the slave has no PDO for that direction, in which case any index is out of range.
  • View lifetime: in() / out() re-resolve the process image pointer on every call and rebuild the instance when the pointer or length changes.
  • Old instances remain usable, but their bounds are not updated: reads take a snapshot per call, so an old instance carries no "stale pointer" read risk. However, the length bounds are those captured when in() / out() was called — you must fetch them again across close() / re-entering OP.
  • asValue / writeValue support only the 11 fixed-width types: BOOLEAN / INTEGER8·16·32·64 / UNSIGNED8·16·32·64 / REAL32 / REAL64; the rest (Bit1..Bit8, Integer24·40·48·56, strings, Domain) have no Java scalar counterpart and always throw IllegalArgumentException. writeValue throws on out-of-range instead of silently truncating.
  • Raw pointer escape hatch: new PDODataItem(...) accepts a caller-supplied buffer base address. The element reads and writes that memory directly by offset, bypassing both snapshots and versioned commits. The width limit comes from the passed maxIomapSize (falls back to the protocol limit when omitted). Use it only when that memory is owned by the caller and not shared with the master's frame transmission; normal usage always goes through in() / out() (length and direction are filled in by the lower layer).
Do not put the element view on a 1 ms cycle hot path

Every scalar read = one whole-frame snapshot (length = the byte count of this direction's process image), and a write adds a versioned transaction on top — it is only suitable for single-point or few-field changes.

When a transaction conflicts the SDK retries automatically; it throws only when the retries still fail, and never silently drops the write.

For whole-frame / batch / cyclic hot paths use struct mapping (inputsMapping / outputsMapping) or copyInputPdo to take the whole frame once and parse it locally.

Read and write a single value by offset​

When you know the offset and need only a few fields, use the element view: take the element by offset, then read and write by type on the element.

int sw  = slave.PDO().in().get(0).asUInt16();        // Read the u16 at offset 0
int pos = slave.PDO().in().get(2).asInt32(); // Read the i32 at offset 2
slave.PDO().out().get(0).asInt16((short) 0x000F); // Write the i16 at offsets 0..1, sent in the next cycle
slave.PDO().out().get(0).setBit(3, true); // Only set bit3 at offset 0

Always pick AsUInt* for unsigned values: asUInt16() returns int, asUInt32() returns long, and a wire value of 0xFFFF reads as 65535 instead of turning negative. asInt16() / asInt32() are signed; use them only when the value really falls in a narrow range.

Whole-frame, batch and cyclic hot paths do not use the element view; they use the following:

byte[]  in  = slave.slavePdo().inputs();                                  // Whole input frame snapshot
boolean ok = slave.slavePdo().outputs(new byte[]{0x0F, 0x00}); // Whole output frame commit (length must equal the output mapping)
int n = slave.PDO().writeOutputDataDirect(new byte[]{0x0F, 0x00}); // Write the output frame, returns the number of bytes written
int m = slave.PDO().readInputDataDirect(buf); // Read the input frame, returns the number of bytes read
boolean ok2 = slave.PDO().writeFromTyped(new byte[]{0x0F, 0x00}, 0); // Patch a chunk of bytes at an offset

ByteBuffer[] bufs = slave.PDO().batchRead(new int[]{0, 2}, new int[]{2, 4}); // Read multiple offsets in one call

copyInputPdo / copyOutputPdo / writeOutputPdo are the complete form of the same job: besides the data itself they also return the actual length and the required length. Cyclic hot paths still use struct mapping (inputsMapping / outputsMapping, zero-copy).

Busy retry in writeOutputPdo​

public PDO.PdoIoStatus writeOutputPdo(byte[] source, int[] writtenSize, int[] requiredSize)

When the output area is occupied by real-time data exchange and the lock cannot be acquired, it returns PdoIoStatus.Busy. This method does a bounded retry on Busy; when the retries are exhausted and it is still Busy it returns Busy and writes a WARNING log, clearly stating that this write was not committed and the caller needs to retry — it never disguises a conflict as a length error (SizeMismatch) or as success (Success).

PdoIoStatus values: Failed / Success / BufferTooSmall / SizeMismatch / Conflict / Stale / Busy.

batchWritePooled(...) writes a WARNING entry for each slave whose data is null, whose write failed (including Busy / SizeMismatch / slave loss) or that threw (with the slave index and status), instead of silently skipping.

Whole-frame read/write​

inputs() / outputs() / outputs(byte[] data)​

public byte[]  inputs()              // slavePdo()
public byte[] outputs() // slavePdo()
public boolean outputs(byte[] data) // slavePdo()
  • inputs() — whole input frame snapshot: consistent within one sample, and it no longer changes with the bus once copied out; returns an empty array when the mapping length is 0.
  • outputs() — snapshot of the output image currently sent (for read-back), also a copy.
  • outputs(byte[] data) — exact whole-frame replacement: data.length must equal the current output mapping length; a mismatch is rejected outright with no truncation; returns true on success and false on failure (failures are visible; writes are never silently dropped).

Parameters: data (byte[]) — complete output frame.

copyInputPdo / copyOutputPdo​

public PDO.PdoIoStatus copyInputPdo(byte[] destination, int[] copiedSize, int[] requiredSize)
public PDO.PdoIoStatus copyOutputPdo(byte[] destination, int[] copiedSize, int[] requiredSize)

Copy the whole frame into a caller-preallocated buffer and return both "how much was actually copied / how much is needed in total". copyOutputPdo copies the output image already sent (read-back); to send, use writeOutputPdo / outputs(byte[]).

Parameters:

  • destination (byte[]) — destination buffer; null or length 0 = size query only (returns BufferTooSmall, with requiredSize giving the required byte count)
  • copiedSize (int[]) — out parameter, length at least 1; on success [0] = copied byte count, otherwise 0
  • requiredSize (int[]) — out parameter, length at least 1; [0] = byte count required by the current mapping

Returns: PdoIoStatus (values in Failures and handling); only Success counts as success.

Throws: either out-parameter array is null or shorter than 1 → IllegalArgumentException.

writeFromTyped(byte[] data, int byteOffset)​

public boolean writeFromTyped(byte[] data, int byteOffset)

A partial write that patches a chunk of bytes into the output area at an offset: copy the current complete output frame → patch data at byteOffset → atomically replace the whole frame, with no race against the master's frame transmission; collisions are retried automatically (bounded retry + shared time budget).

Parameters:

  • data (byte[]) — bytes to write
  • byteOffset (int) — output area byte offset (relative to the start of this slave's output area)

Returns: boolean — true when the commit succeeded; false on failure (data is null or empty / offset out of range / not in OP / conflict or busy exhausted / budget exhausted), and writes are never silently dropped.

The element view's scalar writes, set(index, value), writeString and batchWrite all go through this same commit path — single-point writes and partial writes are one implementation, with no second write channel; they only map failures to IllegalStateException / false according to their own contracts (see Failures and handling).

readInputDataDirect / writeOutputDataDirect​

public int readInputDataDirect(byte[] buffer)
public int readInputDataDirect(byte[] buffer, int offset, int count)
public int writeOutputDataDirect(byte[] buffer)
public int writeOutputDataDirect(byte[] buffer, int offset, int count)

Read and write the whole frame through a buffer, returning the actual byte count (0 on failure).

  • readInputDataDirect — copy the whole input frame into buffer; when the destination buffer is shorter than the mapping it copies as much as fits instead of returning 0.
  • writeOutputDataDirect — exact whole-frame replacement when the length equals the output mapping; a short frame (shorter than the output mapping) automatically degrades to a versioned partial write at offset 0.
  • count = 0 means the remaining buffer length; returns 0 when buffer is null, offset is out of range, or the writable length is 0.

batchRead / batchWrite​

public ByteBuffer[] batchRead(int[] offsets, int[] sizes)
public int batchWrite(int[] offsets, byte[][] values)
  • batchRead — take one whole input frame, then cut multiple segments by offsets / sizes (each segment is a little-endian ByteBuffer); out-of-range entries are null. Mismatched array lengths throw IllegalArgumentException.
  • batchWrite — multiple patches within the same frame are committed together in one versioned transaction (not one whole-frame write per item); returns the number of applied entries, and 0 when the transaction fails (nothing lands). Out-of-range / empty entries (null or length 0) are skipped and not counted in the return value; mismatched offsets and values lengths throw IllegalArgumentException.

batchReadPooled / batchWritePooled​

public Map<Short, byte[]> batchReadPooled(short[] slaveIndices, int[] expectedSizes)
public int batchWritePooled(short[] slaveIndices, byte[][] dataList)

Batch read/write across multiple slaves (one call covers a group of slaves):

  • batchReadPooled — returns input snapshots keyed by slave index; slaves that failed to read are absent from the result (and a WARNING is logged), so callers must check for absence by key and not assume a value is always present.
  • batchWritePooled — commits per slave (equal length uses whole-frame replacement, a short frame uses a versioned partial write) and returns the number of slaves written successfully; failed slaves are not counted silently and each logs a WARNING.
  • When the two array lengths differ it returns an empty result / 0.

getInputByteBuffer / getOutputByteBuffer​

public ByteBuffer getInputByteBuffer()      // slavePdo()
public ByteBuffer getOutputByteBuffer() // slavePdo()

A little-endian ByteBuffer view of the whole-frame snapshot (returns an empty buffer on failure). Writing to these two buffers does not go back to the bus; to send, use outputs(byte[]), writeFromTyped or the element view.

Zero-copy input pointer and offline guard​

slavePdo() exposes zero-copy pointers to the input process image (TxPDO) and separates "image unavailable" from "slave offline — the image still holds the last frame before the drop". A stale frame must not be consumed as the current value. The guard applies to the input direction only.

CategoryPropertyTypeRead/writeDescription
Input pointerslavePdo().tryGetInputsPtr()Pointerread-onlyPointer; returns null when the image is unavailable or stale
slavePdo().getInputsPtr()Pointerread-onlyPointer; throws IllegalStateException when unavailable, PdoInputStaleException when stale
Offline predicateslavePdo().isInputFrameStale()booleanread-onlyTrue only when liveness is actually measured as lost (unsampled returns false)

tryGetInputsPtr()​

public com.sun.jna.Pointer tryGetInputsPtr()   // slavePdo()

The non-throwing variant, for real-time callbacks and other callers that must take their own failure branch instead of throwing.

  • Returns null: the image is unavailable (not mapped / not in OP), or the slave is offline (isInputFrameStale() is true).
  • Returns non-null: the same address as getInputsPtr(), readable byte by byte (the input area is read-only).
  • Existing entry points are unchanged: inputs() / inputsMapping(...) keep their own contracts.

getInputsPtr()​

public com.sun.jna.Pointer getInputsPtr()      // slavePdo()
  • Image unavailable → IllegalStateException ("PDO input image unavailable").
  • Image available but the slave is offline → PdoInputStaleException (extends IllegalStateException). The message states that the input image holds the last frame before the drop and must not be treated as the current value; use slave.isLost() to test liveness.
  • The exception carries getMasterNumber() / getSlaveNumber() for logging.
  • The guard checks liveness only at the moment the pointer is taken; callers that hold the pointer across cycles must re-check with isInputFrameStale() / slave.isLost(). After a master restart / remap the pointer must be taken again.

isInputFrameStale()​

public boolean isInputFrameStale()             // slavePdo()

The sole source of truth is the slave-liveness tri-state: true only when liveness is actually measured LOST; with no measured evidence (failed verdict read / unsampled) it honestly returns false, so "not measured" is never mistaken for offline on a healthy cycle. It is the same predicate as the Stale result of copyInputPdo, not a second threshold.

The output direction is not guarded: the output area is the master's own shadow frame, so a slave going offline does not invalidate it (the STALE predicate applies to the INPUT direction only).

How to consume the input image safely
com.sun.jna.Pointer p = slave.slavePdo().tryGetInputsPtr();
if (p == null) {
// Image unavailable, or the slave is offline: no usable input this sample
} else {
int raw = p.getInt(0); // the input area is read-only
}

When the snapshot path needs to keep "stale" as a state, use copyInputPdo(...), whose result is Stale; the zero-copy entry points have no status out-parameter, so they fail closed with an exception / null.

String read/write​

readString(int offset, int maxLength)​

public String readString(int offset, int maxLength)      // slavePdo()

Read a fixed-length string starting at offset in the input area (UTF-8, terminated at NUL).

Parameters:

  • offset (int) — start byte offset
  • maxLength (int) — maximum number of bytes to read (including the NUL terminator)

Returns: String — returns null (not an empty string) when the snapshot is unavailable, offset is negative or the offset is out of range; callers must check for null.

Throws: maxLength <= 0 throws IllegalArgumentException.

writeString(int offset, String value, int maxLength)​

public boolean writeString(int offset, String value, int maxLength)      // slavePdo()

Write value as UTF-8 as a whole segment at offset in the output area and pad with NUL up to maxLength (guaranteeing that old trailing remnants are overwritten), then commit through a versioned transaction.

Parameters:

  • offset (int) — start byte offset (relative to the start of this slave's output area)
  • value (String) — string value
  • maxLength (int) — fixed length, including the NUL terminator

Returns: boolean — true only when the write was really committed.

Failure semantics (three forms kept separate, not the same thing):

  • The UTF-8 byte count exceeds maxLength - 1 → throws IllegalArgumentException, not a single byte written (no truncation, no false return);
  • value is null, offset is negative, or maxLength <= 0 → returns false;
  • Parameters valid but the transaction failed (not in OP / conflict or busy exhausted / budget exhausted) → returns false; this write was not committed.

There is no "truncating write" path for over-long content: either increase maxLength / shorten the string, or switch to the overlay approach (outputsMapping struct mapping, where you define the field layout yourself and write straight into the output area with zero-copy).

Group mapping and dividers​

Slaves are divided into groups (0-7; 0 = unassigned, automatically placed in group 1 before mapping, valid PDO groups are 1-7), each with its own PDO cycle divider, so different groups can exchange data at different rates. Group membership is written with slave.group(byte) (must be before SAFE_OP; out of range throws IllegalArgumentException, an unwritable state throws IllegalStateException); the full semantics of the divider are in Divider frequency calculation. slavePdo() also has a pair of entries for the same capability:

public byte    getGroupCycleDivider(byte group)              // slavePdo()
public boolean setGroupCycleDivider(byte group, byte divider)

Parameters: group (byte) — group number; divider (byte) — divider value (default 1 per group).

Returns: getGroupCycleDivider returns the current divider value of the group; setGroupCycleDivider returns true on success.

Monitoring and IOmap lock​

startMonitoring / stopMonitoring​

public void startMonitoring()
public void startMonitoring(int updateIntervalMs) // always throws UnsupportedOperationException
public void stopMonitoring()
  • startMonitoring() — enable PDO monitoring (repeated calls have no side effect); stopMonitoring() — disable.
  • startMonitoring(int updateIntervalMs) — always throws UnsupportedOperationException: the monitoring sampling interval is not configurable (only an enabling switch exists); the old implementation silently ignored this parameter, and it now reports the error honestly. Use the no-argument overload for monitoring.

lockIOmap / unlockIOmap / setMutexProtection​

public boolean lockIOmap()                       // slavePdo()
public void unlockIOmap() // slavePdo()
public void setMutexProtection(boolean enable)
  • lockIOmap() — non-blocking try-lock: true = lock acquired, and must be paired with unlockIOmap() at the end of the critical section; false = not acquired (held by another thread / master not ready / shutting down), and you must not enter the critical section or call unlockIOmap().
  • setMutexProtection(boolean) — turn the mutex protection on or off.

PDO status and statistics​

public boolean isValid()
public int expectedSize()
public long avgCycleTimeNs()
public int errorCount()
public Pointer getPerformanceStats()
public void resetPerformanceStats()
MethodReturnsDescription
isValid()booleanWhether mapped to the process image (input or output byte count > 0)
expectedSize()intTotal input + output byte count (0 when not mapped)
avgCycleTimeNs()longThis slave's average PDO cycle (ns), 0 when unavailable
errorCount()intThis slave's PDO error count, 0 when unavailable
getPerformanceStats()PointerRaw performance statistics block, null when unavailable
resetPerformanceStats()voidReset the performance statistics

Mapping information and direct read/write​

Mapping information answers "where this direction's process image is and how large it is"; direct read/write takes and commits at the whole-frame level. The struct view and the element view are described above; this section is a fourth way to use the same process image: it does not ask about the layout, only about the base address and the length.

CategoryMethodType/returnRead/writeDescription
Mapping informationinputsMappingInfo()java.util.Map<String, Object>callInput direction triple: pointer / size / slaveIndex
outputsMappingInfo()java.util.Map<String, Object>callOutput direction triple: pointer / size / slaveIndex
Direct readpdoReadDirect(short, int)byte[]callRead the input snapshot directly at the requested length, returns null on failure
Direct write (retired)pdoWriteDirect(short, byte[])booleancallDeprecated: always returns false, writes no output

inputsMappingInfo()​

public java.util.Map<String, Object> inputsMappingInfo()

Returns the mapping information for the input direction (on slavePdo()):

  • pointer — real-time base address of the input process image
  • size — input byte count (same reading as slave.ibytes())
  • slaveIndex — this slave's index

Returns:

  • java.util.Map<String, Object> — the three keys are always present. For a struct view use inputsMapping(...); this method only answers "where the mapping is and how large it is" and copies no data

outputsMappingInfo()​

public java.util.Map<String, Object> outputsMappingInfo()

Returns the mapping information for the output direction (on slavePdo()); the keys are the same as inputsMappingInfo(): pointer is the real-time base address of the output process image, size is the output byte count (same reading as slave.obytes()), and slaveIndex is this slave's index.

Returns:

  • java.util.Map<String, Object> — the three keys are always present

Example:

java.util.Map<String, Object> in = slave.slavePdo().inputsMappingInfo();
java.util.Map<String, Object> out = slave.slavePdo().outputsMappingInfo();
System.out.printf("输入 %d 字节, 输出 %d 字节%n", in.get("size"), out.get("size")); // Input %d bytes, output %d bytes%n

pdoReadDirect(short pdoIndex, int dataSize)​

public byte[] pdoReadDirect(short pdoIndex, int dataSize)

High-performance direct read: copies this slave's current input snapshot and trims the returned length to the number of bytes actually read.

Parameters:

  • pdoIndex (short) — historical parameter kept for compatibility; the read range is determined by dataSize
  • dataSize (int) — expected byte count to read, valid range 1 .. 4096

Returns:

  • byte[] — the bytes actually read (length = the actual length, which may be smaller than dataSize); returns null when dataSize is out of range or the read fails
null is not length 0

null only means "nothing was read". To tell "the read failed" apart from 「the real length is 0」, use copyInputPdo (it returns the copied length and the required length).

Example:

byte[] in = slave.slavePdo().pdoReadDirect((short) 0, 32);
if (in == null) {
System.out.println("读取失败"); // Read failed
} else {
System.out.printf("读到 %d 字节%n", in.length); // Read %d bytes%n
}

pdoWriteDirect(short pdoIndex, byte[] data)​

@Deprecated
public boolean pdoWriteDirect(short pdoIndex, byte[] data)

Deprecated: the direct-write entry always rejects, so this method always returns false and not one byte is written into the output area. It is kept only for compatibility with old call sites; it likewise returns false when data is null or an empty array.

Parameters:

  • pdoIndex (short) — historical parameter
  • data (byte[]) — bytes to write

Returns:

  • boolean — always false

Replacement paths: use slavePdo().outputs(byte[]) for exact whole-frame replacement, writeFromTyped(byte[], int) for patching a chunk of bytes at an offset, and outputsMapping(...) for struct hot paths.

Example:

// Old approach: always fails, do not use it any more
boolean legacy = slave.slavePdo().pdoWriteDirect((short) 0, new byte[]{0x0F, 0x00});

// Switch to an exact whole-frame replacement
boolean ok = slave.slavePdo().outputs(new byte[]{0x0F, 0x00});

Full example​

import com.darra.ethercat.master.EtherCATMaster;
import com.darra.ethercat.data.EcState;
import com.darra.ethercat.slave.Slave;
import com.sun.jna.Structure;
import com.sun.jna.Structure.FieldOrder;

@FieldOrder({"statusWord", "actualPosition"})
public static class InPdo extends Structure {
public short statusWord;
public int actualPosition;
public InPdo() { super(ALIGN_NONE); }
}

@FieldOrder({"controlWord", "targetPosition"})
public static class OutPdo extends Structure {
public short controlWord;
public int targetPosition;
public OutPdo() { super(ALIGN_NONE); }
}

EtherCATMaster.BuildResult r = EtherCATMaster.create()
.setENI("C:/EtherCAT/MyProject.deni") // DENI one-line load
.build();
if (!r.success) throw new Exception(r.message);

try (EtherCATMaster master = r.master) {
if (!master.setState(EcState.OP)) { // Enter OP, must check the return value
System.out.println("进入 OP 失败, 状态 " + master.state()); // Failed to enter OP, state {master.state()}
return;
}

Slave slave = new Slave(master.MasterIndex, (short) 1, master); // The DENI path does not populate the list; construct from master index + station number

// Map once: the view maps directly onto the process image (zero-copy)
InPdo inputs = slave.PDO().inputsMapping(InPdo.class);
OutPdo outputs = slave.PDO().outputsMapping(OutPdo.class);

inputs.read(); // Read: current cycle
outputs.controlWord = 0x000F; // Write: sent in the next cycle
outputs.targetPosition = inputs.actualPosition + 1000;
outputs.write();
System.out.printf("status=0x%04X pos=%d%n", inputs.statusWord & 0xFFFF, inputs.actualPosition);

// Single read: whole-frame snapshot (consistent within one sample) + single-point element view
byte[] frame = slave.slavePdo().inputs();
System.out.printf("快照 %d 字节, 单点读 pos=%d%n", // Snapshot %d bytes, single-point read pos=%d%n
frame.length, slave.PDO().in().get(2).asInt32());

System.in.read();
}

Failures and handling​

The PdoIoStatus values returned by copyInputPdo / copyOutputPdo / writeOutputPdo: Failed / Success / BufferTooSmall / SizeMismatch / Conflict / Stale / Busy, and only Success counts as success.

SymptomCauseHandling
writeOutputPdo returns BusyCollision with real-time data exchange; still uncommitted after the bounded retryThis write was not committed; handle it as Busy and retry; it is never disguised as a length error or as success
Returns SizeMismatchFrame length differs from the current output mappingTake the correct length from requiredSize and resend; to write a short frame use writeFromTyped
Returns BufferTooSmallDestination buffer too small (or this was only a size query)Grow to requiredSize and copy again
Returns Conflict / StaleThe output area was updated during the commitFetch the frame again and rewrite
Element write throws IllegalStateExceptionNot in OP / conflict or busy exhausted / budget exhaustedThe caller decides whether to retry or give up; the write is never silently dropped
Element write throws UnsupportedOperationExceptionWrote to the input view (in)Always use out for process data writes
Throws IndexOutOfBoundsExceptionindex is not in [0, length())Check the byte offset; when length() is 0 any index is out of range
Throws IllegalArgumentExceptionOffset + width beyond this direction's image / type outside the supported rangeCheck the width and EcDataType (only the 11 fixed-width types are supported)
readString returns nullSnapshot unavailable / offset out of rangeCheck for null, then retry or verify the offset
writeString throws IllegalArgumentExceptionUTF-8 exceeds maxLength - 1Increase maxLength or shorten the string, or switch to the outputsMapping overlay approach; it will not truncate and write half a string

The element view's read/write contract (byte order, bit0 boolean semantics, bit-field read-modify-write, view lifetime) is described above in Element view.