Process Data
By device.ProcessData reading and writing process data.
Process data refers to the bytes exchanged between the device and the controller in each cycle. When mapped to a structure, reading and writing the fields is equivalent to reading and writing the current process data: no copying or flushing is required; what is read is always the data from the current cycle, and what is written is transmitted in the next cycle.
Direction: Write Q (device → controller), read I (controller → device). Zone I is read-only; writing to it returns NotSupported(an element written to Zone I is discarded In[i] InvalidOperationException).
Once you type "Q," the controller will read the value you entered. The changes take effect immediately and are automatically sent in the next cycle; there's no need to call any commit functions.
Cycle switching occurs automatically; there is no need to write your own cycle loop. Any thread can use it simultaneously.
GSDML the "I" and "Q" terms. The 20-byte input (device → controller) in that section SDK is Q; GSDML The 32-byte output (controller → device) SDK is I.
The two terms are reversed in the configuration file and SDK ; don't take them literally.SDK Always refer to them based on the direction of the data flow: Write "Q", read "I".
- Must
[StructLayout(LayoutKind.Sequential, Pack = 1)]. Offset byDeclarations are listed in tight-indentation orderCalculated independently; this is notMarshalthe layout (Marshalwhereboolis 4 bytesBOOL, and the mapping is calculated as 1 byte).- Not a single attribute is labeled: "Discard
ArgumentException." The message says, "Must be labeled.[StructLayout(LayoutKind.Sequential, Pack=1)]" - Write only Do not write
SequentialPack:PackSet to 0, throw an exceptionArgumentException; the message states "Must bePack=1(without alignment padding)."
- Not a single attribute is labeled: "Discard
- Supported fields: digital (
sbyte/byte/short/ushort/int/uint/long/ulong/float/double),bool(1 byte), enumeration (based on the width of the underlying type), fixed-lengthbyte[](must be marked[MarshalAs(UnmanagedType.ByValArray, SizeConst = N)]), nested structs (recursive; same as aboveSequential Pack = 1). stringField throwsNotSupportedException(switch to fixed-lengthbyte[]);charfield throwsNotSupportedException(switch toushort). Structures containing reference fields (string/class/array/delegate/interface) throwInvalidOperationException("结构体含引用字段,不能映射到过程映像").- The structure size must be 1 - 65536 bytes; otherwise an
ArgumentExceptionis thrown, with a message in the form of "Invalid structure size (must be between 1 - 65536 bytes): full type name". - A multi-byte field is network big-endian (PROFINET wire order). Reading it directly as host
short/intreverses the bytes; for host-order values useRead<T>/Write<T>(big-endian encode/decode). - I and Q are two separate structures; do not combine them into one.
Only the entire structure mapping —— ProcessData.InputsMapping<T>() / ProcessData.OutputsMapping<T>() —— returns a reference that always points to the current value; when modified, it is written to the Q-area, and when read, it refers to the current cycle.
In[i] / Out[i] That family, Inputs / Outputs, ReadArea / WriteArea, Read<T> / all Write<T> obtainedA Snapshot of That Moment. ..and once it's removed, it won't change along with the bus.
Don't treat "elements retrieved by offset" as live views—only the offset is [i] fixed; the values are still snapshots from that moment.
Read/WriteReport errors accurately, it will not be silently downgraded.
Use Cases
Everyday Use
① mapping to a structure (for ongoing use): Start mapping it once to obtain a pointer to the I/Q data ref, and then read and write the variable.
using System.Runtime.InteropServices;
using Darra.PnS;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct FromPlc // I: Controller → Device
{
public byte Present; // Offset 0
public short Recipe; // Offset 1: multi-byte values are network big-endian
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct ToPlc // Q: Equipment → Controller
{
public byte Ready; // Offset 0
public byte Busy; // Offset 1
}
using (var device = new DarraPnS())
{
PnSErrorCode rc = device.Start();
if (rc != PnSErrorCode.Success)
return;
ref readonly FromPlc inp = ref device.ProcessData.InputsMapping<FromPlc>(); // Map once
ref ToPlc outp = ref device.ProcessData.OutputsMapping<ToPlc>();
byte present = inp.Present; // Read: Current Cycle
outp.Ready = 1; // Note: To be sent in the next cycle; no submission call.
device.Stop();
}
② Single-read (one-time retrieval): Do not use a structure; just retrieve a single copy of the current value.
byte[] i = device.ProcessData.Inputs; // I. Entire passage: Read in one go; self-consistent within a single beat
short recipe = device.ProcessData.In[2].AsInt16; // Read a value by byte offset
int counter = device.ProcessData.In[4].AsInt32;
A string field in process data is simply a fixed-length byte sequence: the mapping does not accept reference fields; instead, it reads the entire field at once using a snapshot.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct FromPlcText
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] PartNo;
}
var text = new FromPlcText();
PnSErrorCode rc = device.ProcessData.Read(ref text); // I shielding Snapshot Read (Big-Endian Decoding)
string partNo = System.Text.Encoding.ASCII.GetString(text.PartNo).TrimEnd('\0');
③ Retrieve a value by address TIA: The address notation is the same as in the PLC. First, use PnSAddress.Parse to convert it to a byte offset, then use the element port to read or write.
PnSAddress done = PnSAddress.Parse("I0.0"); // position
PnSAddress recipe = PnSAddress.Parse("IW2"); // word
PnSAddress counter = PnSAddress.Parse("ID4"); // double word
bool d = device.ProcessData.In[done.ByteOffset].Bits[done.BitNumber];
short r = device.ProcessData.In[recipe.ByteOffset].AsInt16;
int c = device.ProcessData.In[counter.ByteOffset].AsInt32;
device.ProcessData.Out[0].SetBit(0, true); // Write Q0.0
device.ProcessData.Out[2].AsInt16 = 123; // Write QW2
Cyclical Changes
You only need to retrieve the mapping once. Place the same mapping into your own loop (or a call to a scheduler within the loop) and use it directly:
ref readonly FromPlc inp = ref device.ProcessData.InputsMapping<FromPlc>();
ref ToPlc outp = ref device.ProcessData.OutputsMapping<ToPlc>();
while (running) // Your own recurring tasks—set your own schedule
{
outp.Ready = (byte)(inp.Present + 1); // Read the current beat → Calculate → Write down the beat and play it
Thread.Sleep(10);
}
What is read within the loop is always from the current cycle, and what is written is sent in the next cycle—no additional calls are required.SDK There are no user-defined cycle callbacks; you determine the scheduling (loops, timers, events) yourself.
It is still recommended to retrieve the mapping once outside the loop.
Structure Mapping
Mapping has no offset parameter: the starting byte[] point is always the 0th byte of the data. To mapping a section in the middle, place a section of placeholder data at the beginning of the structure; or use In[i] / to retrieve data by ReadArea offset.
InputsMapping<T>()
mapping Zone I (controller → device) to a read-only structure. mapping it once; after that, reading a field is equivalent to reading the current cycle.
public unsafe ref readonly T InputsMapping<T>() where T : struct
Return value:
ref readonly T— A read-only reference to data in Zone I; any thread can read it
Note:
- **Available only after
Start(). ** IfStarthas not been called, orStophas, anInvalidOperationExceptionis thrown whose message is "Process data input image unavailable: reason". The reason comes fromLastServiceError, for example "Service not started or has STOP: process image unavailable, please start it first (Start())"; with no reason only the base string is shown, without a trailing colon. - Channel Not Mapped:
LastServiceErrorThis indicates that "the process data channel is not mapped, and the process image is unavailable (please call Start() first to establish the process data channel)." The exception thrown is the same as above. - Structures containing reference fields:
InvalidOperationException("结构体含引用字段,不能映射到过程映像"). - Structure exceeds the available data range:
InvalidOperationException("结构体大于输入过程映像"). - Invalid structure layout:
ArgumentException(unmarkedSequential/Pack != 1/ size out of bounds / field type not supported). - Zone I Read-Only: Writing to I is not supported, so it returns
ref readonly T, which is explicitly write-protected by type. To write process data, useOutputsMapping<T>(). - The mapping window is based on this call., Do not hard-code offsets or lengths yourself. If a structure exceeds the available range, the mapping will return an fault immediately.
- It is recommended to retrieve the mapping data once outside the loop. However, if the structure is larger thanIO the actual length of the I sent by the controller, the bytes read from the trailing fields will not be updated—they are returned as-is SDK , without falsification.
- Life Cycle:
refValidity cycle time = mapping lifetime.Stop()Only stop refreshing; do not remove the mapping (read the old value).Dispose()After removing the mapping, it becomes invalid immediatelyref; subsequent reads will access undefined memory, and no exception will be thrown to indicate this. - Readable by any thread.
Example:
ref readonly FromPlc inp = ref device.ProcessData.InputsMapping<FromPlc>();
byte present = inp.Present; // Current cycle value
InputsMapping<T>(onChanged)
mapping it to a struct instance and attach a callback for data changes. It takes snapshots on a polling 1 ms basis, capturing the values at that exact moment; the primary usage is still the parameterless overload mentioned above.
public InputProcessDataInstance<T> InputsMapping<T>(Action onChanged) where T : struct
public InputProcessDataInstance<T> InputsMapping<T>(Action<ProcessDataStructChangedEventArgs<T>> onChanged) where T : struct
Return value:
InputProcessDataInstance<T>— Polling encapsulation;.ValueSnapshotthis is the latest snapshot (it does not update automatically based on changes to the bus),.PollingErrorwhich is the cause of the background failure.
Callback parameters:
public sealed class ProcessDataStructChangedEventArgs<T> : EventArgs where T : struct
{
public T Previous { get; } // Snapshot before the change
public T Current { get; } // Snapshot after the change
}
Overloaded methods with parameters return Previous / ; Current overloaded methods without parameters simply signal that "something has changed." The two overloaded methods behave identically in all other respects.
Note:
- A snapshot is read once during construction. If it hasn't
Startbeen constructed yet, it's discardedInvalidOperationException("读取输入过程数据初始快照失败: rc=InvalidHandle"). Therefore, the callback cannot be triggeredStartbefore that. - Background polling: each time a snapshot is 1 ms read, Only the content has changedJust a callback (deep comparison field by field, not byte-by-byte).
- The callback runs on that background thread. —— Reading in a callback does not
ValueSnapshotcause self-locking. - Throwing an exception in a callback = the polling stops permanently. The exception is swallowed
PollingError; only one line is writtenTrace.TraceError, and the callback is never invoked again; it isn't untilValueSnapshotthe next read that the cause is thrown:InvalidOperationException("输入过程数据后台轮询已停止", 内层异常). - If a snapshot read fails (for example, if it
Stopis interrupted), this is also logged inInvalidOperationException("读取输入过程数据快照失败: rc=...")PollingErrorand polling is STOP. PollingErrorWhen there is no failure, it isnull.- If you want to stop
Dispose(): idempotent; wait for at most 1000 ms threads to finish, and if there's a timeout,TimeoutExceptionlog toPollingError. - Q SideNoneOverrides the corresponding callback.
- This is not a bus cycle notification; it is a snapshot.
Example:
InputProcessDataInstance<FromPlc> watch = device.ProcessData.InputsMapping<FromPlc>(
(ProcessDataStructChangedEventArgs<FromPlc> e) =>
Console.WriteLine($"{e.Previous.Recipe} -> {e.Current.Recipe}"));
FromPlc now = watch.ValueSnapshot; // The latest snapshot
watch.Dispose(); // Stop Polling
OutputsMapping<T>()
mapping the Q zone (Device → Controller) to a writable structure. Once mapped, modifying a field updates the Q data.
public unsafe ref T OutputsMapping<T>() where T : struct
Return value:
ref T— A writable reference to data in Zone Q; changes to the field will take effect in the next cycle
Note:
- These exceptions have a one-to-one correspondence
InputsMapping<T>(); simply replace "input" with "output":InvalidOperationExceptionthe messages are "Process data output image unavailable: reason" and "Structure exceeds output process image"; exceptions are also thrown for fields containing references and invalid layouts. - There were no commit calls. Just edit the field, and it will be sent automatically in the next cycle.
- Available windowsis exactly equal to
ProcessData.Outputs.Length. - A writable mapping isSingle owner: Only one writable mapping is allowed at a time. Reads can be performed concurrently; the caller is responsible for serializing writes.
Dispose()After unmounting the mapping, it becomes invalidref;Stop()only stop refreshing—do not unmount the mapping.- Former Name
OutputsMapping<T>(ref T)Deleted. It's a snapshot commit; while it shares the same name as this mapping, it has a different meaning. It's now calledSubmitStruct<T>(ref T), and no redirects[Obsolete]were left. Don't use the old name in new code.
Example:
ref ToPlc outp = ref device.ProcessData.OutputsMapping<ToPlc>();
outp.Ready = 1; // To be sent in the next cycle
outp.Busy = 0;
Read<T>(ref T)
[Snapshot] Zone I → Structure, big-endian decoding. To keep this reference, use InputsMapping<T>().
public PnSErrorCode Read<T>(ref T data) where T : struct
Return value:
PnSErrorCode— Success is ;Successsee below for failure
Note:
- Not
Start→InvalidHandle. - Structure larger than Zone I →
LengthMismatch. The boundary here isThe entire paragraphProcessData.Inputs.Length, which is more lenient than the mapping window. - Channel not ready (mapped / read exception) →
NativeError, the reason is described inLastServiceError. - Invalid structure layout →
ArgumentException(Snapshots and mappings use the same layout validation). - Includes reference fields /
string/char→NotSupportedExceptionorArgumentException, and applies the same set of criteria as the mapping. boolFields by bit0 Encoding/Decoding: During decoding, only the least significant bit is set to true (0x02/0x80decodedfalse); during encoding, only1/ is written0. It uses theAsBoolsame pin as the element pin.- What you get is a snapshot of that moment; it won't change as the bus changes.
device.ReadStruct<T>(ref x)Synonymous with it.
Example:
FromPlc rx = new FromPlc();
PnSErrorCode rc = device.ProcessData.Read(ref rx);
Write<T>(ref T)
[Snapshot] Structure → Q zone, big-endian encoding. To keep this reference, use OutputsMapping<T>().
public PnSErrorCode Write<T>(ref T data) where T : struct
Return value:
PnSErrorCode—SuccessIndicates that the entire message was sent immediately
Note:
- Not
Start→InvalidHandle. - Structure larger than the Q region →
LengthMismatch. The boundary isProcessData.Outputs.Length. - Channel not ready / Commit failed →
NativeError, with the reason specified inLastServiceError. When a commit fails, those bytes are not lost; they will be included in the next write, and at the same time,IoStatus.OutputValidis set tofalse(not marked as delivered). - Invalid structure layout →
ArgumentException; the actual length of a fixed-lengthbyte[]field does not match the specifiedSizeConst→ArgumentException, with a message like "byte[] field X must be N bytes long." - Zone I has no corresponding write entry: writing to I is not supported.
device.WriteStruct<T>(ref x)Synonymous with it.
Example:
ToPlc tx = new ToPlc { Ready = 1, Busy = 0 };
PnSErrorCode rc = device.ProcessData.Write(ref tx);
SubmitStruct<T>(ref T)
Write<T> an alias for [...], forwarded verbatim to [...] Write.
public PnSErrorCode SubmitStruct<T>(ref T data) where T : struct
Return value:
PnSErrorCode— Same asWrite<T>
Note:
- The failure patterns are exactly
Write<T>the same as (failed to startInvalidHandle/ out of boundsLengthMismatch/ commit failedNativeError/ invalid layoutArgumentException). - It replaces the old name
OutputsMapping<T>(ref T). In new code eitherSubmitStruct<T>orWrite<T>works — the two are synonymous.
Example:
device.ProcessData.SubmitStruct(ref tx);
GetFieldAddress<T>(fieldName)
Convert the structure field names to PLC-style addresses to save on data bytes.
public string GetFieldAddress<T>(string fieldName) where T : struct
public string GetFieldAddress<T>(string fieldName, PnSAddressArea area) where T : struct
Return value:
string— Address string; if omitted, the substitution valueareais Zone I (Readsame direction as )
The format is determined by the field type:
bool→I<偏移>.0(The 0th bit of this byte; this is the same bit as the one readIn[偏移].Bits[0])- 2 bytes (
short/ushort/ 2-byte enumeration) →IW<偏移> - 4 bytes (
int/uint/float/ 4-byte enumeration) →ID<偏移> - 1 byte / 8 bytes / fixed-length array / nested structure →
I<偏移>(starting byte address; address strings do not use 8-byte width notation) - Directions are determined
areaby:PnSAddressArea.InputExitI,PnSAddressArea.OutputExitQ
Note:
- Field NameCase-sensitive(Based on the ratio
Ordinal). Could not findArgumentException("结构体 类型名 中不存在字段: 名字"). - Field name is empty / completely blank:
ArgumentException("字段名不能为空"). areaNoInput/Output:ArgumentException("仅支持 Input (I 区) / Output (Q 区) 地址").- Invalid structure layout:
ArgumentException(same criteria as for mappings). - The generated addressMay be misaligned(An offset is simply a declared offset), and since address resolution does not require alignment, the two are consistent with each other.
Example:
string addr = device.ProcessData.GetFieldAddress<FromPlc>("Recipe"); // "IW1"
string qAddr = device.ProcessData.GetFieldAddress<ToPlc>("Ready", PnSAddressArea.Output); // "Q0" (Ready is 1 byte, without the . bit number)
PnSAddress a = PnSAddress.Parse(addr);
short recipe = device.ProcessData.In[a.ByteOffset].AsInt16;
Direct Access (Works Even Without Mapping)
The following set of calls maps to the structureMutually independent: You can use it directly without mapping, and it is often used in conjunction with mapping as well.
In / Out
public ProcessDataArrayInstance In { get; } // Zone I (Controller → Device): Read-only
public ProcessDataArrayInstance Out { get; } // Zone Q (Devices → Controllers): Read/Write
Return value:
ProcessDataArrayInstance— Byte-offset accessor; A new one is created each time a property is accessed., and it is in the "offset not yet selected" ST
Note:
InThis is Zone I; the controller overwrites it every cycle → read-only. Any attempt toInassign a value to it or write to its element members will result in an exceptionInvalidOperationException.OutIn the Q zone, each member assignment is submitted on the spot, and if successful, it is sent in the next cycle.- I just got it and haven't written anything yet, but I'm already
[i]using its features:InvalidOperationException("请先通过 ProcessData.In[index] 或 ProcessData.Out[index] 选择字节偏移").
Example:
byte first = device.ProcessData.In[0].Content;
In[i] / Out[i]
public ProcessDataArrayInstance this[int index] { get; }
Select from the process dataAbsolute Byte Offset. i This is a byte address, not an element index—which is different from other arrays.
Parameters:
index(int) — The byte offset in this direction, relative to the start of data in this direction
Return value:
ProcessDataArrayInstance— Offset-based accessor; does not move data itself, but reads it only when retrieving a value
Note:
indexValues less than 0 or greater than 65535 are discardedArgumentOutOfRangeException.- The index is valid, but that read operation fails (none
Start/ offset exceeds the current zone length / channel not up): When retrieving a valueThrowInvalidOperationException—the message includes an offset and an fault code. - The element port has no
Lengthproperty. Take the length fromProcessData.Inputs.Length/ProcessData.Outputs.Length. - Access the 8-byte field using
AsInt64/AsUInt64with an offset; or use the structure mapping directly. Out[i]Writing field by field isOne submission at a time; To modify multiple fields at once, useOutputsMapping<T>()— You do not need to submit the call to modify fields.
Related Structures:
public sealed class ProcessDataArrayInstance // The type of ProcessData.In[i] / Out[i]
{
// Subscripts and Raw Bytes
public ProcessDataArrayInstance this[int index] { get; } // Absolute byte offset; < 0 or > 65535 results in an exception ArgumentOutOfRangeException
public byte Content { get; set; } // Raw bytes; In is read-only, Out is writable
// Fixed-width scalars (all multi-byte values are in network big-endianPROFINET order)
public sbyte AsInt8 { get; set; } // Signed 8-bit, 1 byte
public byte AsUInt8 { get; set; } // Unsigned 8-bit, 1 byte; same byte as Content
public short AsInt16 { get; set; } // Signed 16-bit, 2-byte
public ushort AsUInt16 { get; set; } // Unsigned 16-bit, 2 bytes
public int AsInt32 { get; set; } // Signed 32-bit, 4 bytes
public uint AsUInt32 { get; set; } // Unsigned 32-bit, 4 bytes
public long AsInt64 { get; set; } // Signed 64-bit, 8 bytes
public ulong AsUInt64 { get; set; } // Unsigned 64-bit, 8 bytes
public float AsFloat { get; set; } // IEEE754 Single resolution, 4 bytes
public double AsDouble { get; set; } // IEEE754 Double resolution, 8 bytes
public bool AsBool { get; set; } // bit0 Semantics: Write the entire byte as 1 or 0; do not just modify it. bit0
// position
public ProcessDataBitView Bits { get; } // Bit view Bits[i]: 0–7, where 0 is the least significant bit; both In and Out are readable
public void SetBit(int bitIndex, bool value); // Change only this bit; leave the rest of the Byte unchanged; Out only
// In and Out by Data Type
public object AsValue(PnSDataType type); // Read PnSDataType boxed values
public void WriteValue(PnSDataType type, object value); // Press to write PnSDataType ; Out only
}
Failure patterns for each opening:
- Read FailedUniform fault reporting
InvalidOperationException. Messages for single-byte ports (Content/AsInt8/AsUInt8/AsBool) take the form 「Failed to read process data byte from Zone I: index=0, rc=LengthMismatch」;messages for multi-byte ports (AsInt16and above) take the form 「Failed to read process data from Zone I: index=2, length=2, rc=LengthMismatch.」 When the direction is Q, the letter in the message is Q. - Write Failure (Q Side): For single-byte ports: 「Failed to write process data byte to Q-area: index=0, rc=...」; for multi-byte ports: 「Failed to write process data to Q-area: index=2, length=2, rc=...」.
- Write to Side I:
In[i]OnAnyAlways omit the "Content/AsXxxSetBit" symbolInvalidOperationException("ProcessData.In 对应 I 区 (控制器→设备),只允许读取")—not a single one. - Each retrieval is one portionNew Copy: The values read— /
byteshort/ ...—are the values at that exact moment and do not change with the bus.
AsBool Yes bit0 Semantics: Byte 0x02 / When reading 0x80 such non-standard values false, 0x00 / 0x01 is the correct way false / true. You must determine true or false based on whether the entire byte is 0 or not 0; compare the values yourself Content .
device.ProcessData.Out[i].AsBool = value , setting the byte as a whole to 1 or 0, NoChanging only bit 0
device.ProcessData.Out[0].AsBool = true will clear bits 1–7 of the same byte as well.
When a byte contains both a Boolean bit and other flag bits, use SetBit(i, value): This overwrites only the target bit; the remaining bits remain unchanged.
Example:
byte b = device.ProcessData.In[0].Content; // Read: Current Bid
short iw = device.ProcessData.In[2].AsInt16; // Big-Endian Decoding
int id = device.ProcessData.In[4].AsInt32;
bool f = device.ProcessData.In[0].AsBool; // bit0 Semantics
device.ProcessData.Out[0].Content = 0x11; // Note: To be sent in the next cycle
device.ProcessData.Out[2].AsInt16 = 123;
Bit View Bits[i] / SetBit(bitIndex, value)
Use a specific bit within a single byte. Read the bit to access the property Bits; see Usage In[0].Bits[0].
public ProcessDataBitView Bits { get; } // Bit-level view entry point; both In and Out are readable
public bool this[int bitIndex] { get; } // In the view: 0–7, where 0 is the least significant bit
public void SetBit(int bitIndex, bool value); // Out Only
Parameters:
bitIndex(int) — Bit number 0–7, where 0 = the least significant bit (LSB)value(bool) — Set to 1 for true, clear to 0 for false
Return value:
bool— Is this bit a 1?
Note:
bitIndexNot in 0–7: TossArgumentOutOfRangeException; the message is 「The index must be between 0 and 7.」This check is at the very beginning, and the same applies toIncalls—they also report a wrong bit number first.- The position number is valid, but the direction is
In:SetBitThrow an exception when writing to itInvalidOperationException("ProcessData.In 对应 I 区 (控制器→设备),只允许读取"). SetBitRead-Modify-Write the same byte: First, read the current byte; then, modify the target bit; finally, write the entire byte back, leaving the remaining bits unchanged. Still.- When no bytes are read, those
Contenttwo read failure exceptions are thrown.
Example:
bool run = device.ProcessData.In[3].Bits[0]; // Read the 3rd byte of I bit0
device.ProcessData.Out[0].SetBit(0, true); // Set only the 0th byte of Q bit0
AsValue(type) / WriteValue(type, value)
Iterate through data types; this approach is suitable for scenarios where the type is determined at runtime (table-driven, variable association tables).
public object AsValue(PnSDataType type); // In: Read Zone I; Out: Read Q Shadow
public void WriteValue(PnSDataType type, object value); // Out Only
Parameters:
type(PnSDataType) — Procedure data typevalue(object) — The value to be written must be convertible to the corresponding type CLR
Return value:
object— Packing values:bool/sbyte/short/int/long/byte/ushort/uint/ulong/float/double
Supported values (width and byte order are the same as for the fixed-width port above):
Bool→bool(bit0 semantics)Integer8/Integer16/Integer32/Integer64→sbyte/short/int/longUnsigned8/Unsigned16/Unsigned32/Unsigned64→byte/ushort/uint/ulongReal32/Real64→float/doubleByte/Word/DWord/LWordare aliases forUnsigned8/16/32/64respectively, all of the same width
Note:
typeNot supported:ArgumentOutOfRangeExceptionThe message is formatted as "Unsupported process data type: xxx."WriteValueisvaluenull:ArgumentNullException.valueCan't get past it:ConvertThrow it yourself (InvalidCastException/FormatException/OverflowException).- On
In, callingWriteValue: when it lands on the write port it throwsInvalidOperationException("ProcessData.In 对应 I 区 (控制器→设备),只允许读取"). - When no bytes are read, those
Contenttwo read failure exceptions are thrown.
Example:
object v = device.ProcessData.In[4].AsValue(PnSDataType.Integer32);
device.ProcessData.Out[4].WriteValue(PnSDataType.DWord, 10000);
Related Structures:
public enum PnSDataType
{
Bool, // Boolean, 1 byte;bit0 Semantic (0 = false, 1 = true)
Integer8, // Signed 8-bit integer, 1 byte
Integer16, // Signed 16-bit integer, 2 bytes, big-endian
Integer32, // Signed 32-bit integer, 4 bytes, big-endian
Integer64, // Signed 64-bit integer, 8 bytes, big-endian
Unsigned8, // Unsigned 8-bit integer, 1 byte
Unsigned16, // Unsigned 16-bit integer, 2 bytes, big-endian
Unsigned32, // Unsigned 32-bit integer, 4 bytes, big-endian
Unsigned64, // Unsigned 64-bit integer, 8 bytes, big-endian
Real32, // IEEE754 Single-resolution floating-point, 4 bytes, big-endian
Real64, // IEEE754 Double-resolution floating-point, 8 bytes, big-endian
Byte, // Unsigned8 Alias, 1 byte
Word, // Unsigned16 Alias, 2 bytes, big-endian
DWord, // Unsigned32 Alias, 4 bytes, big-endian
LWord, // Unsigned64 Alias, 8 bytes, big-endian
}
The variable table data_type uses a different set of 4-value terms PnSAddressDataType(Bit / Byte / byte / DWord), which is not the same as this enumeration.
Full Frame and Full Region
Use these interfaces to mapping fields that cannot be stored (strings, variable-length data, and batch snapshots). All copies — Each call returns a snapshot of the data at that moment: the data returned by a single call is consistent within that call, but consistency across multiple calls is not guaranteed. To ensure consistency, read all the data in a single call.
Inputs / Outputs
public byte[] Inputs { get; } // I. Entire Paragraph: A new snapshot is provided with each visit
public byte[] Outputs { get; set; } // Q Entire segment: get returns a snapshot; set commits the entire segment
Return value:
byte[]— A snapshot of that moment; once copied, it won't change along with the bus.
Note:
- These two property declarations are
device.ProcessDataon , Not heredeviceUp. - Each access to
Inputsallocates a freshbyte[]. When the data cannot be read (noStart, or the channel is not up) it returns an empty array and does not throw — checkLengthto tell whether anything was read, do not rely on exceptions. - The get of
Outputsworks the same way: it returns an empty array when the data cannot be read. - The set of
Outputsis a short write: it only overwrites the first N bytes and does not require the length to equal the whole area. AssigningnullthrowsArgumentNullException; a failed commit throwsInvalidOperationException("写输出过程数据失败 rc=" + 错误码). InputsThe data starts at index 0; do not add an offset yourself;Inputs.Lengthfollow Section IThe entire paragraphThe length is calculated by padding with 0 at the end, so the valid data is shorterLengththan .Outputs.LengthThis is the length of the available data in the Q region.- Avoid using these two properties in high-frequency loops: they allocate a new large array on every access. Either use the mapping described above, or switch to
In[i]/Out[i]on-demand retrieval.
Example:
byte[] frame = device.ProcessData.Inputs;
string name = System.Text.Encoding.ASCII.GetString(frame, 0, 16).TrimEnd('\0');
ReadArea(area, out data) / WriteArea(area, data)
Read or write entire segments at once by region, instead of repeatedly reading and writing address by address.
public PnSErrorCode ReadArea(PnSAddressArea area, out byte[] data);
public PnSErrorCode WriteArea(PnSAddressArea area, byte[] data);
Parameters:
area(PnSAddressArea) —Input= Zone I (read-only) /Output= Zone Q (write-only).Memory/Db/UnknownIn all casesInvalidArgument: Zone M and DB are not supported.
Return value:
PnSErrorCode—SuccessThat is success;datait is a snapshot of that moment in time
ReadArea Failure Patterns:
- The region is not
Input/Output→InvalidArgument. - Not
Start→InvalidHandle. - Channel not ready, or read failed →
NativeError, reason recorded inLastServiceError. - The returned length
dataisProcessData.Inputs.Length(Zone I) /ProcessData.Outputs.Length(Zone Q), Entire Zone, Full Volume. There is no such thing as "crossing the line."
WriteArea Failure Patterns:
- Write Zone I →
NotSupported(Do not discard). Before the check is initiated, this line is the same evenStartif it is not presentNotSupported. - The zone is not
Output(e.g., /MemoryDb) →InvalidArgument. - Not
Start→InvalidHandle. dataFornullor an empty array →InvalidArgument.data.LengthDoes notProcessData.Outputs.Lengthmatch →LengthMismatch. The lengths must be exactly equal., no more and no less.- Submission failed →
NativeError.
Note:
ReadAreaReads the current value without blocking.WriteAreaAfter writingEffective immediately:SuccessThe entire district has already been delivered.- A single call reads and writes the whole region, saving round trips compared with calling
Read*/Write*one by one.
Example:
device.ReadArea(PnSAddressArea.Input, out byte[] i); // I Entire Paragraph
byte[] q = new byte[device.ProcessData.Outputs.Length];
Array.Copy(i, q, q.Length);
device.WriteArea(PnSAddressArea.Output, q); // Q: The entire segment must be of equal length.
Related Structures:
public enum PnSAddressArea
{
Unknown = 0, // Unknown
Input = 1, // Zone I: Read-only (Controller → Device)
Output = 2, // Section Q: Write only (device → controller)
Memory = 3, // Zone M: For reporting unsupported items only
Db = 4, // DB District: For reporting unsupported cases only
}
Read(out fromPlc) / Write(toPlc)
Convenient packaging for entire sections; the meaning is the same as above.
public PnSErrorCode Read(out byte[] fromPlc); // = ReadArea(Input), Read Section I
public PnSErrorCode Write(byte[] toPlc); // Write "Q District"; abbreviations are allowed.
Parameters:
toPlc(byte[]) — The bytes in the Q region to be sent, Abbreviations allowed(Covers only the first N bytes)
Return value:
PnSErrorCode— fault code same asReadArea/WriteArea
Note:
ReadExactlyReadArea(PnSAddressArea.Input, out fromPlc)—the failure patterns are exactly the same.WriteThere is only one differenceWriteArea(Output, ...)from :Writeallows a length shorter than the entire shielding (shorthand),WriteAreawhile requires the length to be exactly the same.toPlcFornullor an empty array →InvalidArgument.- Length exceeds the current Q zone →
LengthMismatch. - Not
Start→ ;InvalidHandleSubmission failed →NativeError.
Example:
device.Write(new byte[] { 0x01, 0x00 }); // Short Answer Q: Overwrite only the first 2 bytes
device[offset] (indexer)
Syntactic sugar for reading and writing a single byte based on an absolute byte offset.
public byte this[int offset] { get; set; }
Parameters:
offset(int) — Absolute byte offset
Return value:
byte— The byte to be offset
Note:
- It's not a view. "get" reads the entire Zone I → retrieves the
offsetth byte; each retrieval copies the entire zone. Avoid using this for high-frequency operations. - get: throws
ArgumentOutOfRangeExceptionifoffsetis less than 0; throwsInvalidOperationExceptionif the read fails oroffsetexceeds the current area length, with a message in the form of "Failed to read process data: offset=N rc=error code server cause". - set:
offsetIf the value is less than 0 or greater than 65535, an exception is thrown;ArgumentOutOfRangeExceptionif the write failsInvalidOperationException, an exception is thrown. The message is formatted as follows: "Failed to write process data offset=N rc=fault code server cause." - "get" reads Zone I, "set" writes to Zone Q; one property, two directions, Semantic shifts are independent of one another(Reads from a different district.)
Example:
byte b = device[0]; // Read Zone I, Offset 0
device[0] = 0x11; // Write to Q, offset 0
Address-Based Positioning (Region + Byte + Bit)
When you do not want to compute the offset yourself and want to find bytes by the address shown in TIA, use PnSAddress.Parse to resolve the address into an offset, then go through the element port: region letter + byte offset + bit.
PnSAddress done = PnSAddress.Parse("I0.0"); // position
PnSAddress recipe = PnSAddress.Parse("IW2"); // word
PnSAddress counter = PnSAddress.Parse("ID4"); // double word
bool d = device.ProcessData.In[done.ByteOffset].Bits[done.BitNumber];
short r = device.ProcessData.In[recipe.ByteOffset].AsInt16;
int c = device.ProcessData.In[counter.ByteOffset].AsInt32;
device.ProcessData.Out[0].SetBit(0, true); // Write Q0.0
device.ProcessData.Out[2].AsInt16 = 123; // Write QW2
device.ProcessData.Out[4].AsInt32 = 10000; // Write QD4
| How to Write an Address | What is it? |
|---|---|
| I0.0 / Q0.0 | Bit address: Bit 0 of byte 0 (bit numbers must be between 0 and 7) |
| IB0 / QB0 | Byte (1 byte) |
| IW2 / QW2 | Word (2 bytes) |
| ID4 / QD4 | Double word (4 bytes) |
Sharing Agreement:
- Alignment to 2/4 is not required.
IW3/ID2All are valid; the offset refers to a byte offset — which is consistent with the generatedGetFieldAddressunaligned addresses. - The M zone and DB zone are not supported.
- The parsed offset is fed directly into the element port
In/Out. Data is readBits[位号]andSetBit(位号, value)written bit by bit. - Describing a failed pattern in the Q zone: "element thrown out
InvalidOperationException." ReadBool/WriteBool/ReadInt16/WriteInt16/ReadInt32/WriteInt32This family's address string scalar portDeleted(Duplicate of Element View). The old code has been changed to usePnSAddress.Parse+In[i]/Out[i].
Entire District WriteArea Encountering Side IDo not discard, return PnSErrorCode.NotSupported — Remember to evaluate the return value.
Element Port(In[i].Content = ... as well as various types of assignments In[i] on ) are discarded InvalidOperationException.
PnSAddress.Parse(address)
Address string parser: first parse notations such as I0.0 / IW2 into offsets, then feed them to the element port; alternatively, parse and then validate yourself.
public static PnSAddress Parse(string address)
Return value:
PnSAddress— Analysis results; members includeArea/ByteOffset/BitNumber/DataType/DataLengthBytes/SpanBytes/IsBit/Original/DbNumber
public sealed class PnSAddress
{
public PnSAddressArea Area { get; } // Input (Zone I) / Output (Zone Q)
public int ByteOffset { get; } // Byte Offset
public int BitNumber { get; } // Bit numbers 0–7; valid only when set DataType to "Bit"
public PnSAddressDataType DataType { get; } // Bit / Byte / Word / DWord
public int DataLengthBytes { get; } // Bit = 0, Byte = 1, byte = 2, Double byte = 4
public int SpanBytes { get; } // Access span: 1 byte for bit operations; all other values remain the same. DataLengthBytes
public bool IsBit { get; }
public int DbNumber { get; } // Reserved field; not supported DB; always equals 0
public string Original { get; } // Original address string
public void ValidateRange(int imageLength); // Off-Bound Check
}
Note: This openingThrows an exception(This differs Read* from the approach used for returning Write* fault codes.) The message is as follows:
- Address is empty / All fields are blank:
ArgumentException("地址不能为空") DBIntroduction:ArgumentException("不支持 DB")MIntroduction:ArgumentException("不支持 M 区")- The region code is not
I/Q/M:ArgumentException("不支持的地址区域: 原地址") - Unformed character (e.g.,
I0./I.a):ArgumentException("地址格式非法 (位地址应为 I0.0 形式): 原地址") - There is no number after the region:
ArgumentException("地址缺少偏移量: 原地址") - Offset or index is not a pure number / is negative:
ArgumentException("字节偏移非法: 原地址")orArgumentException("位号非法: 原地址") - Digits outside the range 0–7 (e.g.,
I0.8):ArgumentException("位号必须在 0-7 之间: 原地址") - Addresses without a type character (
I0/Q7) are treated asByteHandle this in accordance with standard practice HSL ; the byte address must be written.位号.
ValidateRange(imageLength) Additionally ArgumentOutOfRangeException, an fault message appears, such as: 「Address IW7 requires 2 bytes, which exceeds the process image length of 4.」
Example:
PnSAddress a = PnSAddress.Parse("IW3");
int off = a.ByteOffset; // 3. Parses even when not aligned
a.ValidateRange(device.ProcessData.Inputs.Length);
Subscripts and Index Spaces
Byte Index
Process data is used forByte OffsetWhen the subscript isProcessData.In[i] / Out[i], i it refers to a byte address, not an element index. Offsets are not required to be aligned to 2 or 4, In[3] and / and refer IW3 to the same location.
The structure being mapped is aligned starting from the 0th byte of the data, so “accessing elements by offset” and “structure fields” are two different measures: if the structure layouts match, their offsets will be consistent (which is also why addresses GetFieldAddress can be generated).
Record Index Space
The records on the diagnosis side areAnother address axis. ..and has nothing to do with the byte offset of the process data. It is divided into two segments and uses two different entry points:
- User Area
0x0000-0x7FFF——device.Records(GET /api/records). All user records written by the controller are included in this section. - I&M
0xAFF0-0xAFF4——device.ImData(GET /api/im). Equipment identification records are maintained by the equipment itself, Not entered into the user area log.
So you will not find it by rummaging through Records for 0xAFF0: the user-area record table only covers 0x0000-0x7FFF, and I&M goes through ImData. Do not treat the two endpoints as one table.
How do I get the number of bytes?
The length is determined by the value negotiated by the PLC (IO controller) and is automatically matched after link, Don't be too rigid 20 / 32. There are no InputsByteCount / OutputsByteCount such openings.
| What you want | Where to get it |
|---|---|
| I Adjust the length of this paragraph | device.ProcessData.Inputs.Length |
| Q: Length of the entire section | device.ProcessData.Outputs.Length |
| Configuration Lengths in Both Directions | device.InputLength / OutputLength (int) |
InputsThe data starts at index 0;Inputs.Lengthit still followsEntire DistrictWhen calculating the length, pad the end with 0.Outputs.LengthThis is the length of the available data in Q.- The window size for structure mapping can be smaller
Inputs.Lengththan : Calculate the structure size based on the mapping results; don't stick strictly toInputs.Length. - The length returned by
ReadArea(Input)equalsInputs.Length; the length required byWriteArea(Output, data)equalsOutputs.Length.
So “the mapping can accommodate it” and “it’sInputs.Length big enough” are not the same thing. If you’re unsure, let the mapping report an fault on its own: it will throw an exception if the limit is exceeded InvalidOperationException("结构体大于输入过程映像").