PDO inputs and outputs
Access the process image through slave.PDO
A PDO is one segment of the process image, exchanged automatically by the master every cycle. Once mapped to a 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.
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 PDO cycles.
- Must be
[StructLayout(LayoutKind.Sequential, Pack = 1)], with field order matching the PDO mapping byte for byte; omittingPack = 1adds alignment padding and shifts every field (it still compiles, and you silently read dirty data). - Must not exceed the byte count for the corresponding direction (
slave.InputsByteCount/slave.OutputsByteCount).InputsMapping<T>()/OutputsMapping<T>()throwInvalidOperationExceptionwhen the struct is oversized.- The slice variants throw
ArgumentOutOfRangeExceptionwhen the offset goes out of range. - Overloads with
onChangeddo not check the size when mapping; a mismatch only surfaces on a later read. - A smaller struct is valid and covers the image from the given offset.
- Only fixed-size value types are allowed: reference fields (
string/ arrays / delegates) throwInvalidOperationException(overloads withonChangedskip this check). Decode strings from the whole-frameInputs. - A
boolfield is not bit0 on the zero-copyrefmapping path: C# interprets the struct field itself, applying the language's own rule that a value other than 0 is true. For a non-canonical byte such as0x02/0x80, therefmapping readstruewhile the element viewAsBoolreadsfalse. Useslave.PDO.In[i].AsBoolwhen you need bit0, or the bitwiseGetBit/SetBit. Exception: theValueSnapshotpath normalizes theboolbyte by bit0 before interpreting it, matchingAsBool. - A mapping stays valid once made;
Close/ a generation change invalidates the oldref, so map again when you re-enter OP.- A generation change raises no notification, so an old
refcannot tell that it is stale. When you take aref, storeslave.ProcessImageGenerationalongside it and compare before use: a different value means the generation changed, and the oldrefmust be discarded and remapped. - The value increases monotonically (starts at 1, never returns 0) and is readable from any thread;
Closeand re-applying the DC / ENI configuration increment it by 1. The value does not change during PreOp→SafeOp, so always map again when you re-enter OP.
- A generation change raises no notification, so an old
Usage examples
Day-to-day usage
① Map to a struct (zero-copy, keep using it): map once after entering OP, get a ref pinned to the process image, then read and write it like a variable.
using System.Runtime.InteropServices;
using DarraEtherCAT_Master;
[StructLayout(LayoutKind.Sequential, Pack = 1)] // Pack = 1 is required; field order matches the PDO byte for byte
public struct InPdo { public ushort StatusWord; public int ActualPosition; }
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct OutPdo { public ushort ControlWord; public int TargetPosition; }
using var master = new DarraEtherCAT()
.SetENI(@"C:\EtherCAT\MyProject.deni") // one-line DENI load
.Build()
.Master;
master.SetState(EcState.OP, out _); // enter OP
var slave = master.Slaves[0];
ref readonly InPdo input = ref slave.PDO.InputsMapping<InPdo>(); // map once (after entering OP)
ref OutPdo output = ref slave.PDO.OutputsMapping<OutPdo>();
output.ControlWord = 0x000F; // write: sent in the next cycle
output.TargetPosition = 10000;
Console.WriteLine($"status=0x{input.StatusWord:X4} pos={input.ActualPosition}"); // read: current cycle
② Single read (one-shot): skip the struct and take just one copy of the current value.
// single point: take an element view at a byte offset (an out-of-range index throws IndexOutOfRangeException)
int pos = slave.PDO.In[2].AsInt32; // 4 bytes starting at offset 2
ushort sw = slave.PDO.In[0].AsUInt16; // 2 bytes starting at offset 0 (StatusWord)
// whole segment: a complete input frame snapshot, consistent within a cycle, and it does not follow the bus once copied
byte[] frame = slave.PDO.Inputs;
string name = System.Text.Encoding.ASCII.GetString(frame, 6, 16).TrimEnd('\0'); // string field
Console.WriteLine($"status=0x{frame[0] | (frame[1] << 8):X4} name={name}");
Cyclic changes
One mapping is enough; put the same mapping into your own cyclic loop (or a scheduling point inside it) and use it directly:
The cadence of Thread.Sleep is set by the operating system scheduler, so jitter and phase are outside the bus's control. CSP / synchronized axes must hook master.Events.ProcessDataCyclicSync,
which paces them from the PDO cycle. Do not send motion targets (target position, control-word enable bits) directly from a polling thread either; any beat mismatch with the bus cycle causes jitter.
The pattern below is only suitable for status monitoring and non-realtime IO.
using System.Threading;
while (running)
{
output.ControlWord = (input.StatusWord & 0x0004) != 0 ? (ushort)0x000F : (ushort)0x0006;
output.TargetPosition = input.ActualPosition;
Thread.Sleep(1); // polling cadence on a user thread, not a motion cycle; hook ProcessDataCyclicSync for motion
}
The master moves process data every cycle: reads in your loop always see the current cycle and writes are sent in the next cycle, with no extra calls. Do not map again on every cycle either (Close
/ a generation change is what invalidates an old ref; mapping once more when you re-enter OP is enough).
Struct mapping (zero-copy)
InputsByteCount / OutputsByteCount
Byte counts of the current slave's input / output process image, used to check the struct size before mapping.
public int InputsByteCount { get; }
public int OutputsByteCount { get; }
Return value:
int— input / output process image byte count; 0 when OP has not been entered or nothing is mapped
Description: these two properties are declared on Slave (slave.InputsByteCount), not on slave.PDO. The value is throttled to about 50 ms,
so shortly after a state change it may still show the previous cycle's value.
Example:
using System.Runtime.CompilerServices;
if (Unsafe.SizeOf<InPdo>() > slave.InputsByteCount)
throw new InvalidOperationException("结构体大于输入 PDO"); // (SDK output, = struct larger than input PDO)
Unsafe.SizeOf<T>() measures by the real struct layout (same basis as sizeof). For structs containing bool / char, do not substitute Marshal.SizeOf — it measures by the marshaled layout and may give a different result. It is built in on .NET Core 3.0+, while .NET Framework / netstandard2.0 need the System.Runtime.CompilerServices.Unsafe package.
InputsMapping<T>()
Maps the input process image (TxPDO) to a read-only struct reference pinned to the process image; after one mapping, reading a field reads the current cycle value (zero-copy, not a snapshot).
public ref readonly T InputsMapping<T>() where T : struct
Return value:
ref readonly T— read-only reference pinned to the process image, readable from any thread
Description:
- Call it after entering OP.
- The I area is overwritten by the master every cycle, so writes to it are silently ignored; use
OutputsMapping<T>()to write process data. - Throws
InvalidOperationExceptionwhen the process image is unavailable (OP not entered). - Throws
PdoInputStaleException(derived fromInvalidOperationException) when the slave is offline (slave.IsLost): the image holds the last frame from before the drop, so it must not be delivered as the current value. - Throws
ObjectDisposedExceptionwhen theSlavehas been disposed (afterClose()). - Throws
InvalidOperationExceptionwhen结构体大于输入 PDO(SDK output, = struct larger than input PDO).
Example:
ref readonly InPdo input = ref slave.PDO.InputsMapping<InPdo>();
ushort status = input.StatusWord; // current cycle value
InputsMapping<T>(onChanged)
Maps to a struct instance and attaches a data-change callback. When you only want the ref, call the overload without onChanged; no extra binding API is needed.
public Slave.InputPdoInstance<T> InputsMapping<T>(Action<Slave.PdoStructChangedEventArgs<T>> onChanged) where T : struct
public Slave.InputPdoInstance<T> InputsMapping<T>(Action onChanged) where T : struct
Return value:
InputPdoInstance<T>—.Valueis aref readonly Tpinned to the process image (zero-copy);.ValueSnapshotis a snapshot of the current value (it does not change on its own)
Callback parameters:
public sealed class PdoStructChangedEventArgs<T> : EventArgs where T : struct
{
public ushort SlaveIndex { get; } // slave index
public bool IsInput { get; } // whether this is an input PDO
public T Previous { get; } // value before the change
public T Current { get; } // value after the change
public DateTime Timestamp { get; } // timestamp
}
Description: the SDK continuously compares the complete frame in the background without consuming PDO cycles; the callback runs only when the struct value changes.
Example:
var input = slave.PDO.InputsMapping<InPdo>(e =>
Console.WriteLine($"位置变化: {e.Previous.ActualPosition} -> {e.Current.ActualPosition}")); // Position change: {e.Previous.ActualPosition} -> {e.Current.ActualPosition}
int pos = input.Value.ActualPosition; // zero-copy, current cycle
InPdo snap = input.ValueSnapshot; // snapshot, does not follow the bus
InputsSliceMapping<T>(int offset)
Maps a read-only struct reference at the given byte offset in the input process image, for devices such as MDP units whose modules are laid out as separate segments.
public ref readonly T InputsSliceMapping<T>(int offset) where T : struct
Parameters:
offset(int) — byte offset from the start of this slave's input process image
Return value:
ref readonly T— read-only reference pinned at that offset (zero-copy)
Description: a negative offset, or an offset + Unsafe.SizeOf<T>() past the end, throws ArgumentOutOfRangeException (the size uses the real struct layout; for structs containing bool/char, do not substitute Marshal.SizeOf).
An unavailable process image (OP not entered) throws InvalidOperationException; an available image on an offline slave throws PdoInputStaleException (derived from InvalidOperationException). The staleness guard matches InputsMapping<T>() and holds only at the moment the ref is taken: callers that cache the ref beyond the cycle and keep dereferencing it after a drop must re-check with slave.IsLost.
Related structures:
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, Pack = 1)] // Pack = 1 is required; omitting it adds alignment padding and shifts fields
public struct Module1In // module 1: occupies input image offsets 0-7 (8 bytes in total)
{
public ushort StatusWord; // offset 0
public ushort ErrorCode; // offset 2
public int Value; // offset 4
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Module2In // module 2: input image starts at offset 8
{
public ushort StatusWord; // offset 8
public ushort ErrorCode; // offset 10
public int Value; // offset 12
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Module2Out // module 2: output image starts at offset 8
{
public ushort ControlWord; // offset 8
public int Setpoint; // offset 10
}
The byte width of each struct must match the PDO length of the corresponding module; here module 1 occupies 8 bytes, so module 2 starts at offset 8.
Example:
// MDP device: module 1 starts at offset 0, module 2 at offset 8
ref readonly Module1In mod1 = ref slave.PDO.InputsSliceMapping<Module1In>(0);
ref readonly Module2In mod2 = ref slave.PDO.InputsSliceMapping<Module2In>(8);
InputsSliceMapping<T>(int offset, onChanged)
Maps a struct instance at the given offset in the input process image and attaches a data-change callback.
public Slave.InputPdoInstance<T> InputsSliceMapping<T>(int offset, Action<Slave.PdoStructChangedEventArgs<T>> onChanged) where T : struct
public Slave.InputPdoInstance<T> InputsSliceMapping<T>(int offset, Action onChanged) where T : struct
Parameters:
offset(int) — byte offset from the start of this slave's input process imageonChanged— data-change callback, with the same parameters as above
Example:
var mod2 = slave.PDO.InputsSliceMapping<Module2In>(8, e =>
Console.WriteLine($"模块 2 数据变化: {e.Previous} -> {e.Current}")); // Module 2 data change: {e.Previous} -> {e.Current}
ref readonly Module2In m2 = ref mod2.Value; // zero-copy
OutputsMapping<T>()
Maps the output process image (RxPDO) to a struct reference; changing a field writes to the bus.
public ref T OutputsMapping<T>() where T : struct
Return value:
ref T— writable reference pinned to the process image (zero-copy); field changes are sent to the slave in the next cycle
Description: throws InvalidOperationException when 结构体大于输出 PDO (SDK output, = struct larger than output PDO); an unavailable process image or a disposed Slave behaves as in InputsMapping<T>().
Example:
ref OutPdo output = ref slave.PDO.OutputsMapping<OutPdo>();
output.ControlWord = 0x000F; // sent in the next cycle
OutputsSliceMapping<T>(int offset)
Maps a writable struct reference at the given byte offset in the output process image.
public ref T OutputsSliceMapping<T>(int offset) where T : struct
Parameters:
offset(int) — byte offset from the start of this slave's output process image
Example:
ref Module2Out mod2 = ref slave.PDO.OutputsSliceMapping<Module2Out>(8);
mod2.Setpoint = 1500;
Input process image pointer and freshness
InputsPtr / TryGetInputsPtr are declared on Slave (slave.InputsPtr), not on slave.PDO. All three zero-copy input entry points share one freshness guard: after a slave goes offline, the I area keeps the last frame from before the drop (the "input stays stable" convention), so the address and length are still there but those bytes are no longer the current value.
InputsPtr
public IntPtr InputsPtr { get; }
Start address of the input process image (TxPDO); the same process image that slave.PDO.InputsMapping<T>() exposes.
Return value:
IntPtr— start address of the input process image
Description:
- Read-only direction: the I area is overwritten by the master every cycle, so writes to it are silently ignored; use
OutputsPtrto write process data. - Throws
InvalidOperationException("PDO input image unavailable") when the image is unavailable (not mapped / OP not entered). - Throws
PdoInputStaleExceptionwhen the image is available but the slave is offline (slave.IsLost). - Throws
ObjectDisposedExceptionwhen theSlavehas been disposed (afterClose()). - The guard checks liveness only at the moment the pointer is taken; callers that hold the pointer across cycles must re-check with
slave.IsLost/slave.ProcessImageGeneration.
Example:
IntPtr p = slave.InputsPtr;
Console.WriteLine($"输入映像 {slave.InputsByteCount} 字节, 首地址 0x{p.ToInt64():X}"); // Input image {slave.InputsByteCount} bytes, start address 0x{p.ToInt64():X}
TryGetInputsPtr(out IntPtr pointer, out int byteCount)
public bool TryGetInputsPtr(out IntPtr pointer, out int byteCount)
The non-throwing variant of InputsPtr, for callers such as real-time callbacks that must route a dropped slave through their own failure branch instead of throwing.
Parameters:
pointer(out IntPtr) — start address of the input process image;IntPtr.Zerowhen the method returnsfalsebyteCount(out int) — size of the input process image in bytes;0when the method returnsfalse
Return value:
bool—true= the pointer is usable and the data is not stale;false= the image is unavailable (not mapped / OP not entered) or the slave is offline
Description:
- When it returns
true,pointeris byte-for-byte the same asInputsPtr. falsedoes not distinguish "not mapped" from "offline"; to tell them apart, checkslave.InputsByteCountandslave.IsLost.- Throws
ObjectDisposedExceptionwhen theSlavehas been disposed (afterClose()). - Input direction only:
slave.OutputsPtris the master's own shadow frame, whose validity does not depend on the slave being online.
Example:
if (slave.TryGetInputsPtr(out IntPtr ptr, out int len))
{
// usable this cycle: ptr is valid for len bytes
}
else if (slave.IsLost)
{
// slave offline: the image holds the last frame from before the drop
}
PdoInputStaleException
public sealed class PdoInputStaleException : InvalidOperationException
{
public ushort MasterNumber { get; }
public ushort SlaveNumber { get; }
}
Thrown by InputsPtr / InputsMapping<T>() / InputsSliceMapping<T>(int) when the input image is available but the slave is offline: the image then holds the last frame from before the drop, not the current value.
Properties:
MasterNumber(ushort) — master instance number, the same value asmaster.MasterNumberSlaveNumber(ushort) — slave index, the same value asslave.SlaveNum
Description:
- The only liveness criterion is
slave.IsLost: only a measured offline verdict counts as stale; with no measurement it reports online, so "not sampled" never becomes a false drop alarm on a healthy cycle. - Input direction only: the output area is the master's own shadow frame and stays valid while the slave is offline (the same criterion applies to the input direction only).
- Derives from
InvalidOperationException, so existing code that catches "PDO input image unavailable" withcatch (InvalidOperationException)keeps working unchanged. - To check ahead of time instead of catching: use
slave.IsLostorTryGetInputsPtr. - To take a snapshot and see staleness in the return value: use
slave.CopyInputPdo(...), which reportsPdoIoStatus.Stale.
| Entry point | Image unavailable | Slave offline |
|---|---|---|
slave.InputsPtr | InvalidOperationException | PdoInputStaleException |
slave.PDO.InputsMapping<T>() | InvalidOperationException | PdoInputStaleException |
slave.PDO.InputsSliceMapping<T>(int offset) | InvalidOperationException / ArgumentOutOfRangeException | PdoInputStaleException |
slave.TryGetInputsPtr(...) | returns false | returns false |
slave.GetInputDataSpan() | empty span | empty span |
slave.CopyInputPdo(...) | a PdoIoStatus other than Success | PdoIoStatus.Stale |
Example:
try
{
ref readonly InPdo input = ref slave.PDO.InputsMapping<InPdo>();
Console.WriteLine($"pos={input.ActualPosition}");
}
catch (PdoInputStaleException ex)
{
Console.WriteLine($"主站 {ex.MasterNumber} 从站 {ex.SlaveNumber} 离线, 本拍输入不可用"); // Master {ex.MasterNumber} slave {ex.SlaveNumber} offline, this cycle's inputs are unavailable
}
A generation change and an offline slave are two different things: after a generation change, old refs and old pointers are invalid as a whole (map again when re-entering OP), whereas an offline slave keeps the image but marks it stale. Check both.
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).
In[i] / Out[i]
public PDOArrayInstance In { get; } // TxPDO (slave → master): read-only
public PDOArrayInstance Out { get; } // RxPDO (master → slave): read/write
Indexes process data elements by byte offset: In[i] reads inputs, Out[i] reads and writes outputs, and i is relative to the start of the process image for that direction.
Return value:
PDOArrayInstance— byte-indexed view of the process image;Lengthis the byte count of the process image for this direction, and 0 before OP is entered or before anything is mapped (any index then throwsIndexOutOfRangeException)
Description:
Inis the TxPDO, overwritten by the master every cycle, and read-only: assigning toInor writing one of its element members always throwsInvalidOperationException.Outis the RxPDO; each member assignment runs one versioned transaction (copy → patch → commit, with bounded retry on conflict), and a successful write is sent in the next cycle.- Throws
InvalidOperationExceptionwhen the commit fails. - Each element-view read takes a snapshot of the current frame and then resolves by offset — the same snapshot semantics as
slave.PDO.Inputs, not the zero-copy pinned reference ofInputsMapping<T>(). - An out-of-range index throws
IndexOutOfRangeException. - Out-of-range caused by a wrong byte / wrong type runs through two checks, with different exception types:
- The first check tests against the element view's bounds (the
Lengthcaptured at creation, that is, the direction byte count with about 50 ms of throttling): offset plus width past the end throwsArgumentOutOfRangeException— deliberately distinct from an index error, so a wrong byte is distinguishable from a wrong type. - The second check tests against the frame length actually obtained for this call (the snapshot read, or the frame leased by the write transaction): a mismatch with the element bounds throws
ArgumentException. Only reachable once the element bounds are stale, or after a generation change shrinks the process image.
- The first check tests against the element view's bounds (the
GetBit/SetBitthrow whenbitIndexis outside 0-7, andAsValue/WriteValuethrow when the type is unsupported —ArgumentOutOfRangeExceptionin both cases.SetBitchecks the direction before the index: a call onInthrowsInvalidOperationExceptionwhatever the index; only theOutdirection can throwArgumentOutOfRangeExceptionfor an out-of-rangebitIndex.- Throws
ObjectDisposedExceptionwhen theSlavehas been disposed.
Related structures:
public sealed class PDODataItem // element view returned by slave.PDO.In[i] / Out[i]
{
public byte Content { get; set; } // raw byte (unsigned 8-bit)
public sbyte AsInt8 { get; set; } // signed 8-bit
public byte AsUInt8 { get; set; } // same byte with the same meaning as Content
public short AsInt16 { get; set; } // multi-byte members below are little-endian (EtherCAT wire order)
public ushort AsUInt16 { get; set; }
public int AsInt32 { get; set; }
public uint AsUInt32 { get; set; }
public long AsInt64 { get; set; }
public ulong AsUInt64 { get; set; }
public float AsFloat { get; set; }
public double AsDouble { get; set; }
public bool AsBool { get; set; } // bit0 read semantics; writes the whole byte as 1 / 0 (does not change a single bit)
public bool GetBit(int bitIndex); // bitIndex 0-7, 0 = LSB
public void SetBit(int bitIndex, bool value); // Out only; other bits in the same byte stay unchanged
public object AsValue(EcDataType type); // read a boxed value by mapping type
public void WriteValue(EcDataType type, object value); // write by mapping type
public static implicit operator byte(PDODataItem item); // byte x = slave.PDO.In[0]; ≡ .Content
}
AsBool reads only the lowest bit: both 0x02 and 0x80 read false. To judge truth by the whole byte being 0 or a value other than 0, read Content and compare it yourself.
Conversely, a bool field in the zero-copy ref mapping is true whenever the value is other than 0. For the same non-canonical byte,
the ref mapping field and AsBool disagree; the ValueSnapshot snapshot is already normalized by bit0, so both agree.
GetBit(i) / SetBit(i, value) are the bitwise entry points for the same byte: i runs from 0 to 7, 0 = lowest bit; GetBit reads that bit (In / Out
are both readable), and SetBit changes only that bit, leaving the other bits of the byte untouched.
slave.PDO.Out[i].AsBool = value writes the whole byte as 1 or 0; it does not change only bit0 —
slave.PDO.Out[0].AsBool = true also clears bits 1-7 of the same byte.
When one byte carries both a boolean bit and other flag bits, use SetBit(i, value): it overwrites only the target bit and leaves the rest unchanged.
AsValue / WriteValue support only data types that map one-to-one to a CLR
fixed-width type: Boolean, Integer8/16/32/64, Unsigned8/16/32/64, Real32/Real64.
Bit strings, 24/40/48/56-bit integers, strings and Domain all throw ArgumentOutOfRangeException. Use the public byte path for these wide types and bit strings:
read the whole frame from the slave.PDO.Inputs / Outputs byte snapshots and slice by offset yourself, write several segments with TryWriteOutputBatch + PdoOutputPatch,
and keep using AsValue / WriteValue for fixed-width scalars. 40/48/56-bit integers have no CLR scalar counterpart, so assemble and decode them byte by byte.
Example:
short sw = slave.PDO.In[0].AsInt16; // read: current cycle
slave.PDO.Out[2].AsInt16 = 123; // write: versioned partial commit, sent in the next cycle
slave.PDO.Out[0].SetBit(0, true); // sets only bit0, other bits in the byte untouched
bool flag = slave.PDO.In[3].AsBool; // bit0 semantics
for (int i = 0; i < slave.PDO.Out.Length; i++)
slave.PDO.Out[i].SetBit(0, false); // walk the whole output image
byte same = slave.PDO.In[0]; // implicit conversion: same as .Content
TryWriteOutputBatch(patches)
public bool TryWriteOutputBatch(IReadOnlyList<PdoOutputPatch> patches)
Commits several output byte segments in one versioned transaction: a successful call produces exactly one commit. Use it when several fields must be updated together instead of assigning
Out[i].X = ... one by one (which is one transaction per field).
Parameters:
patches(IReadOnlyList<PdoOutputPatch>) — byte segments to commit; offsets are relative to the start of the output process image
Return value:
bool— whether the commit succeeded;falsemeans the retry budget was exhausted (conflict / busy) and this call wrote nothing
Related structures:
public readonly struct PdoOutputPatch
{
public PdoOutputPatch(int offset, ReadOnlyMemory<byte> data); // a negative offset throws ArgumentOutOfRangeException
public int Offset { get; } // byte offset from the start of this slave's output process image
public ReadOnlyMemory<byte> Data { get; } // bytes to write for this segment
}
Description:
- Before committing, each segment is copied into its own buffer, so retries are unaffected by later changes on the caller side.
- A
nullpatchesthrowsArgumentNullException; an emptyDatasegment, or an out-of-range offset / length, throwsArgumentException. - An empty list returns
true. - The same method also exists on
slave(slave.TryWriteOutputBatch) with identical semantics.
Example:
var patches = new[]
{
new PdoOutputPatch(0, new byte[] { 0x0F, 0x00 }), // ControlWord
new PdoOutputPatch(2, BitConverter.GetBytes(10000)), // TargetPosition
};
bool ok = slave.PDO.TryWriteOutputBatch(patches); // one transaction, one commit
Inputs / Outputs
Byte-level access to the whole process image frame, for fields the struct cannot hold (strings, variable-length data).
public byte[] Inputs { get; } // whole input frame: every access returns a snapshot owned by the caller
public byte[] Outputs { get; set; } // whole output frame: get returns a snapshot; set commits the complete frame
Return value:
byte[]— a snapshot, not zero-copy: consistent within one cycle, and it does not follow the bus once copied out
Description:
- These two properties are declared on
slave.PDO(slave.PDO.Inputs), not onslave. - Every access allocates a new
byte[]; in high-frequency loops useslave.CopyInputPdo(span, out copied, out required)/slave.CopyOutputPdo(...)to copy into your own buffer (no extra allocation, returnsPdoIoStatus: onlySuccesscounts as success, andBufferTooSmallreports the required frame length). - Commit a whole frame with
slave.WriteOutputPdo(span, out _, out _). - The convenience extensions
slave.CopyInputsTo(Span<byte>)/slave.CopyToOutputs(ReadOnlySpan<byte>)return the number of bytes actually copied / written; a return of0means no complete frame was read or written this time (failure / BUSY / size mismatch), not "a normal result of 0 bytes". The specific cause is logged as a Warning (including status / copied / required / slave index). - The
Outputssetter length must matchOutputsByteCount, otherwise it throwsInvalidOperationException. - Both getters throw
ObjectDisposedExceptiononce theSlavehas been disposed (afterClose()). - Throws
InvalidOperationExceptionwhen a complete frame cannot be obtained (it does not return an empty array).
Example:
byte[] frame = slave.PDO.Inputs;
string name = System.Text.Encoding.ASCII.GetString(frame, 6, 16).TrimEnd('\0');
PdoConsistentReader
public sealed class PdoConsistentReader
{
public PdoConsistentReader(ushort masterIndex); // number of the master this slave belongs to
public ulong CycleCount { get; } // number of completed cycles (increments by 1 each cycle)
public T Read<T>(Func<ulong, T> reader, int maxRetries = 8);
public T ReadInput<T>(Slave slave, int offset, int maxRetries = 8) where T : struct;
public int ReadInt32(Slave slave, int offset, int maxRetries = 8);
public short ReadInt16(Slave slave, int offset, int maxRetries = 8);
public byte ReadByte(Slave slave, int offset, int maxRetries = 8);
}
Use it when reading several fields as one logical frame: take the cycle number before and after the read, and the cycle counts as one complete read only when both match; any crossing of a cycle retries the whole thing. For a single field,
In[i] is enough.
Description:
- Consistency is detected by bracketing with the cycle number, and what you read is a snapshot of the current value; nothing is pinned and no raw pointer is returned.
- Compared with taking
slave.PDO.Inputsevery time, it allocates no whole-frame array. - A slave that does not belong to the master bound at construction throws
ArgumentException(anullslavethrowsArgumentNullException). - Throws
InvalidOperationExceptionwhen no consistent snapshot is obtained aftermaxRetriesattempts (8 by default): shorten the reading lambda or read fewer fields at once. - The legacy overloads that take an
IntPtrare obsolete and throwNotSupportedExceptionwhen called — a PDO pointer cannot stay valid across a generation change.
Example:
var reader = new PdoConsistentReader(masterIndex: 1); // number of the master this slave belongs to
InPdo frame = reader.Read(_ => new InPdo
{
StatusWord = slave.PDO.In[0].AsUInt16,
ActualPosition = slave.PDO.In[2].AsInt32,
}); // both fields come from the same cycle, or the whole read is retried
Process image spans and direct buffer access
These calls are the low-level entry points for moving whole frames. They are independent of struct mapping and of the In[i] / Out[i] element views: they work without mapping, and can be used alongside mapping to handle fields the struct cannot hold.
GetInputDataSpan()
public ReadOnlySpan<byte> GetInputDataSpan()
A read-only span over the input process image that points at the process image itself (zero-copy, not a snapshot): reads always see the current cycle. The input direction is overwritten by the master every cycle, so writes through it are silently ignored.
When the process image is unavailable (OP not entered / nothing mapped / could not be obtained) it returns an empty span (Length == 0) instead of throwing; once the Slave has been disposed (after Close()) it throws ObjectDisposedException.
How it differs from slave.PDO.Inputs: the span allocates nothing and follows the current cycle; Inputs returns a snapshot owned by the caller on every access.
Return value:
ReadOnlySpan<byte>— view of the input process image; an empty span when unavailable
Example:
ReadOnlySpan<byte> input = slave.GetInputDataSpan();
if (input.Length < 2)
Console.WriteLine("输入映像不可用或不足 2 字节(未进 OP / 未映射)"); // Input image unavailable or fewer than 2 bytes (not in OP / not mapped)
else
Console.WriteLine($"StatusWord=0x{System.Buffers.Binary.BinaryPrimitives.ReadUInt16LittleEndian(input):X4}");
GetOutputDataSpan()
public Span<byte> GetOutputDataSpan()
A writable span over the output process image that points at the process image itself (zero-copy): changing a byte changes the output sent in the next cycle. It returns an empty span when the process image is unavailable, and throws ObjectDisposedException once the Slave has been disposed.
Changing half a frame byte by byte leaves intermediate states that other readers can see. To make several segments take effect together, use TryWriteOutputBatch; to land a change only if nobody else modified the snapshot, use a versioned transaction (CopyOutputPdoVersioned / CommitOutputPdoVersioned).
Return value:
Span<byte>— view of the output process image; an empty span when unavailable
Example:
Span<byte> output = slave.GetOutputDataSpan();
if (output.Length >= 2)
{
output[0] = 0x0F; // ControlWord low byte
output[1] = 0x00;
}
ReadInputDataToSpan(Span<byte> destination)
public int ReadInputDataToSpan(Span<byte> destination)
Copies the current input frame into the caller's span and returns the number of bytes actually copied. When the destination is longer than the frame, the whole frame is copied; when it is shorter, only the destination length is written and nothing goes out of bounds.
It returns 0 when nothing could be read (OP not entered / no mapping / failure) or the destination is empty — 0 means nothing was read this time, not "the frame length is 0".
Parameters:
destination(Span<byte>) — destination buffer
Return value:
int— number of bytes actually copied; 0 on failure
Example:
Span<byte> buffer = stackalloc byte[64];
int n = slave.ReadInputDataToSpan(buffer);
if (n == 0)
Console.WriteLine("读取失败或无输入映射"); // Read failed or no input mapping
else
Console.WriteLine($"读到 {n} 字节"); // Read {n} bytes
WriteOutputDataFromSpan(ReadOnlySpan<byte> source)
public int WriteOutputDataFromSpan(ReadOnlySpan<byte> source)
Writes the source span into the output process image and returns the number of bytes actually written. When the length equals the output mapping, the whole frame is committed; a short frame performs a partial update against the output mapping (only the supplied segment is overwritten, the other bytes keep their previous values).
It returns 0 when source is empty or the write fails (no exception is thrown). WriteOutputPdo remains the single entry point for writing a whole frame.
Parameters:
source(ReadOnlySpan<byte>) — byte segment to write
Return value:
int— number of bytes actually written; 0 on failure
Example:
Span<byte> outFrame = stackalloc byte[2];
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(outFrame, 0x000F);
int n = slave.WriteOutputDataFromSpan(outFrame);
Console.WriteLine(n == 2 ? "控制字已提交" : "写入失败或被拒"); // Control word submitted / write failed or rejected
ReadInputDataDirect(byte[] buffer, int offset = 0, int count = 0)
public int ReadInputDataDirect(byte[] buffer, int offset = 0, int count = 0)
Copies the input frame into the given range of the caller's array. count = 0 means from offset through the end of the array.
On invalid arguments (buffer is null, offset is out of range) or a failed read it returns 0 and does not throw — the return value is the only way to detect the failure.
Parameters:
buffer(byte[]) — destination arrayoffset(int) — start offset within the destination array,0by defaultcount(int) — number of bytes to read,0= through the end of the array
Return value:
int— number of bytes actually read; 0 on failure
Example:
byte[] frame = new byte[slave.InputsByteCount];
int n = slave.ReadInputDataDirect(frame);
if (n == 0)
Console.WriteLine("未读到输入帧"); // No input frame read
WriteOutputDataDirect(byte[] buffer, int offset = 0, int count = 0)
public int WriteOutputDataDirect(byte[] buffer, int offset = 0, int count = 0)
Writes the given range of the array into the output process image. count = 0 means from offset through the end of the array.
On invalid arguments or a failed write it returns 0 and does not throw.
Parameters:
buffer(byte[]) — source arrayoffset(int) — start offset within the source array,0by defaultcount(int) — number of bytes to write,0= through the end of the array
Return value:
int— number of bytes actually written; 0 on failure
Example:
byte[] frame = new byte[slave.OutputsByteCount];
frame[0] = 0x0F;
int n = slave.WriteOutputDataDirect(frame);
Console.WriteLine(n > 0 ? $"已写入 {n} 字节" : "写入未被接受"); // Wrote {n} bytes / write not accepted
Versioned output transactions
This group covers optimistic concurrent writing: take an output snapshot together with a version token bound to it, change fields on the snapshot, then commit only if nobody changed the output in the meantime. Use it when several writers (UI, scripts, cyclic tasks) write to the same slave at the same time, so they do not overwrite each other. A single regular writer should not take this path; using a mapping or Out[i] directly is cheaper.
CopyOutputPdoVersioned(...)
public PdoIoStatus CopyOutputPdoVersioned(
Span<byte> destination, out int copiedSize, out int requiredSize,
ref ulong transactionTicket, ref ulong nativeDeadlineUs,
out ulong versionToken)
Copies the complete RxPDO and returns a version token bound exactly to that snapshot.
On the first call, transactionTicket and nativeDeadlineUs must both be 0; the SDK issues an opaque ticket and deadline pair. Every later retry after growing the buffer, every restart and every commit must reuse the same pair. The token must be passed to CommitOutputPdoVersioned unchanged.
Parameters:
destination(Span<byte>) — buffer that receives the current output snapshot; leave it empty to obtain just the required lengthcopiedSize(out int) — number of bytes actually copiedrequiredSize(out int) — bytes required for the complete frame; grow the buffer to this size whenBufferTooSmalltransactionTicket(ref ulong) — transaction ticket; pass0on the first callnativeDeadlineUs(ref ulong) — transaction deadline in microseconds; pass0on the first callversionToken(out ulong) — version token bound to this snapshot
Return value:
PdoIoStatus—Successthe snapshot is valid;BufferTooSmallthe buffer is too small (grow it torequiredSizeand retry with the same ticket / deadline pair);Busythe transaction is busy (retry with the ticket / deadline unchanged);Conflict/Stalesomeone else changed the snapshot, copy it again;Failedfailure (the ticket / deadline are reset to0)
Example:
ulong ticket = 0, deadline = 0;
byte[] snapshot = new byte[slave.OutputsByteCount];
PdoIoStatus st = slave.CopyOutputPdoVersioned(
snapshot, out int copied, out int required,
ref ticket, ref deadline, out ulong token);
if (st == PdoIoStatus.Success)
{
snapshot[0] = 0x0F; // Modify fields on the snapshot
st = slave.CommitOutputPdoVersioned(
snapshot.AsSpan(0, copied), token, ticket, deadline,
out ulong committed, out int written, out int need);
}
CommitOutputPdoVersioned(...)
public PdoIoStatus CommitOutputPdoVersioned(
ReadOnlySpan<byte> source, ulong expectedToken,
ulong transactionTicket, ulong nativeDeadlineUs,
out ulong committedToken, out int writtenSize, out int requiredSize)
Commits the modified output frame after validating the token: the change lands only if the output has not been modified by another writer since the snapshot was copied.
Parameters:
source(ReadOnlySpan<byte>) — byte segment to commit (usually the whole frame that was copied out)expectedToken(ulong) — version token returned byCopyOutputPdoVersionedtransactionTicket(ulong) — the same transaction ticket used for the copynativeDeadlineUs(ulong) — the same deadline used for the copycommittedToken(out ulong) — new version token after the commitwrittenSize(out int) — number of bytes actually written (meaningful only onSuccess)requiredSize(out int) — bytes required for the complete frame
Return value:
PdoIoStatus—Successcommitted;Busythe transaction is busy (retry with the same ticket / deadline pair);Conflict/Stalethe snapshot was changed (copy the snapshot again);SizeMismatchthe length does not match the output mapping;Failedfailure
Example:
PdoIoStatus st = slave.CommitOutputPdoVersioned(
snapshot.AsSpan(0, copied), token, ticket, deadline,
out ulong committed, out int written, out int need);
if (st == PdoIoStatus.Conflict || st == PdoIoStatus.Stale)
Console.WriteLine("快照已被其他写入方改动,需重新复制后重试"); // Snapshot was changed by another writer, copy it again before retrying
else if (st == PdoIoStatus.Busy)
Console.WriteLine("事务忙,保持同一对票据重试"); // Transaction busy, retry with the same pair of tickets
PDO IO status normalization
NormalizePdoIoStatus(byte status)
public static PdoIoStatus NormalizePdoIoStatus(byte status)
Normalizes a status byte to PdoIoStatus, for decoding the raw status returned by entry points such as CopyInputPdo / WriteOutputPdo and the versioned transactions.
Mapping rules:
0x00and1→Success(both success encodings are accepted)2..6→BufferTooSmall/SizeMismatch/Conflict/Stale/Busy0xFA..0xFF→ the negative status codes encoded as bytes, mapped value by value back toConflict/Stale/SizeMismatch/BufferTooSmall/Busy/Failed- any other value →
Failed
The public status codes 2..6 match, value for value, the same-named normalization entry point in the other language SDKs. The method is hidden from IntelliSense by default and is meant for direct calls from tests and status decoding.
Parameters:
status(byte) — raw status byte
Return value:
PdoIoStatus— normalized status
Related structures:
public enum PdoIoStatus : byte
{
Failed = 0, // Failure (including an unrecognised status code)
Success = 1, // Success
BufferTooSmall = 2, // Buffer too small, grow it to requiredSize and retry
SizeMismatch = 3, // Length does not match the mapping
Conflict = 4, // Concurrent write conflict, re-take the snapshot and retry
Stale = 5, // The snapshot has expired
Busy = 6 // Transaction busy, retry later
}
Example:
byte rawStatus = 0xFD; // For example the raw return from a whole-frame copy entry point
PdoIoStatus st = DarraEtherCAT.Slave.NormalizePdoIoStatus(rawStatus);
if (st == PdoIoStatus.BufferTooSmall)
Console.WriteLine("缓冲区不足,按所需长度扩容后重试"); // Buffer too small, expand it to the required length and retry