Process Data
Process data consists of a sequence of bytes automatically transmitted between the controller IO and the device every cycle: Write Q (device → controller) and Read I (controller → device).When mapped to a structure, reading and writing its members directly reads and writes the current process data; no copying or flushing is required: the value read is the current cycle’s value, and the value written is transmitted in the next cycle. The I area is read-only; the controller overwrites the entire segment every cycle, and writing to it is not supported (InputsMapping<T>() it returns an fault const T&, and writing is disabled at configuration time).The bus cycle is handled by the service side;SDK you are not required to write a cycle loop.
The 20-byte Input in GSDML (device → controller) is the SDK's Q; the 32-byte Output in GSDML (controller → device) is the SDK's I.
This product is Fixed Single Module: Channel 1 / Subchannel 1, sample configuration: Q 20 bytes, I 32 bytes. The length is determined by the value negotiated by the PLC (IO controller); it is automatically matched after link, so do not hard-code it — on the C++ side No function takes slot or subslot parameters.
After writing a "Q," the controller reads the value you entered. "Q" is a device output, and the direction is from the device to the controller. Changes take effect immediately and are automatically sent in the next cycle. Not necessaryAdjust any submission functions again.
- It is mandatory
#pragma pack(push, 1)to ensure consistency before and after mapping#pragma pack(pop). Since the mapping involves an in-memory byte stream, structs with alignment padding will be shifted as a whole; if you omit thepackkeyword, the compiler will flag it during configuration (alignof(T) == 1this is a strict requirement). TMust trivially copyable And standard layout: It must not contain virtual functions, referenced members, or non-trivial copies; otherwise, the mapping result will be incorrect. This is also a configuration-time checkstatic_assert.- The field order matches that of the online version byte-for-byte. Multi-byte fields are big-endian in PROFINET networks: If you read the
int16_t/floatfield directly as a host-ordered value, the bytes will be reversed — to obtain a host-ordered value, use the element port or the address-based interface (which perform big-endian encoding and decoding), or assemble the bytes yourself. - I / Q RatioTwo setsStructures should not be combined into a single one.
sizeof(T)The length must not exceed the available data length for that direction; otherwisePnSException, an exception is thrown. A shorter length is valid. - Mapping is available only after it has succeeded
Start();Stop()refreshing is paused, but the view still exists (and reads the old value);Close()/ The reference becomes invalid after the destructor unmaps it. - A mapping is a real-time byte-level view, Not a synchronization primitive: Do not use it for inter-thread synchronization, and do not perform conditional polling on it. When waiting for a value to be set, use the snapshot (
Read()/ReadStruct<T>()) to re-read the value instead.
Use Cases
Everyday Use
① mapping to a structure (for ongoing use): Define the layout, mapping it once, obtain a reference, and then treat it as a variable for reading and writing.
#include "pns.hpp"
#include <iostream>
using namespace darra::pns;
#pragma pack(push, 1) // Required: Online byte stream; no alignment padding allowed.
struct FromPlc { uint8_t Present; }; // I: Controller → Device
struct ToPlc { uint8_t Ready; }; // Q: Devices → Controllers (I and Q are two separate structures)
#pragma pack(pop)
PnSService device; // Non-bus-connected configuration
if (!device.Start()) { // Start is required for enablement IO; returns false on failure, without throwing an exception
std::cerr << device.LastServiceError() << "\n";
return 1;
}
const FromPlc& inp = device.ProcessData().InputsMapping<FromPlc>(); // mapping once, reuse
ToPlc& outp = device.ProcessData().OutputsMapping<ToPlc>();
outp.Ready = 1; // Note: To be sent in the next cycle; no commit calls are required.
uint8_t present = inp.Present; // Read: Always returns the value for the current cycle
② Single-read (retrieve one value or a shielding of bytes at a time): I don't want to define a struct just for a single read, or I only need those few bytes.
std::vector<uint8_t> raw = device.ProcessData().Inputs(); // Section I: Read the entire passage in one go; ensure it makes sense within a single beat
int16_t recipe = device.ProcessData().In()[2].AsInt16(); // Read a Value with Byte-Offset Typing (Big-Endian)
bool done = device.ReadBool("I0.0"); // Read one bit by address
Inputs() and device.Read() take the same snapshot of zone I; the element at In()[i] isCopy Slice(Not a view); the section on “Direct Access” below will explain this distinction in detail. String fields are fixed-length byte arrays, not std::string: To obtain a copy that won’t change on its own, read the entire field at once and trim it to the first '\0'.
#pragma pack(push, 1)
struct FromPlcText { char PartNo[16]; }; // Fixed length + pad the tail with 0
#pragma pack(pop)
FromPlcText t = device.ProcessData().Read<FromPlcText>(); // Snapshot Read (Forward) ReadStruct<T>())
std::string partNo(t.PartNo, strnlen(t.PartNo, sizeof t.PartNo));
③ Read and write by address (write according to the addresses specified in the engineering software): If you don't want to calculate the byte offset yourself, use the address-based interface, which is written as "region letter + byte offset + bit."
device.WriteBool("Q0.0", true); // Bit: Only that one byte is modified bit0; the remaining bits in the same byte remain unchanged.
device.WriteInt16("QW2", 123); // Word: 2 bytes, big-endian
device.WriteInt32("QD4", 10000); // Double word: 4 bytes, big-endian
int16_t recipe = device.ReadInt16("IW2"); // On the I side, read by address as well
int32_t counter = device.ReadInt32("ID4");
Cyclical Changes
Place the same mapping directly into your own recurring task (retrieve the mapping once outside the loop):
const FromPlc& inp = device.ProcessData().InputsMapping<FromPlc>();
ToPlc& outp = device.ProcessData().OutputsMapping<ToPlc>();
while (running) { // Your own recurring tasks—set your own schedule
outp.Ready = (uint8_t)(inp.Present + 1); // Read the current beat → Calculate → Write down the beat and play it
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
Perform the mapping once outside the loop, and once inside the loopDon'tRemapping occurs on every frame.SDK There are no user-defined cycle callbacks; you are responsible for scheduling (loops, timers, events).
sizeof(T) and must not exceed the available data length in this direction, otherwise an exception is thrown; PnSException a smaller value is valid. The available data length is determined by the value returned by the interface, Do not hard-code offsets or lengths yourself.: If the actual length is known, use it as the limit; if the actual length is unknown (0), revert to the capacity limit, Do not extrapolate based on district capacity(Extraction will treat non-data segments as data.) To get GET /api/io the true length, use outputLength(the field name is opposite to the I/Q direction—don’t rely on the name).
Retrieve the mapping once outside the loop, and once inside the loopDon'tRemap on every call. The approach is to retrieve the value once after a successful Start() operation and use it until ; Close()``Close() / It must be retrieved again after the destructor is called.
Structure Mapping
Mapping returns a reference, not a snapshot: once mapped, it always reads the same data; Read() / ReadStruct<T>() is a snapshot.
Structures are aligned starting at the 0th byte of available data in this direction. To mapping the middle section, place a placeholder array (uint8_t _skip[k];) at the beginning of the structure to fill the space; otherwise, use the ReadArea(area, offset, length) offset to retrieve bytes as needed.
InputsMapping<T>()
mapping Zone I (controller → device) to a read-only struct reference. mapping it once, and thereafter, reading a field retrieves the value for the current cycle.
template <typename T>
const T& InputsMapping();
Return value:
const T&— Read-only references to Zone I. Zone I is read-only; writing is explicitly prohibited by type.
Note:
TMust be both#pragma pack(push, 1)trivially copyable and have a standard layout—these are two configuration-time checksstatic_assert, and the fault message will directly specify which one is missing.- All failures are thrown as exceptions
PnSException(All instances ofPnSException“throw” on this page are single-argument constructs-1;code()only write commit failures and server startup/shutdown failures are thrown as coded exceptions):- Not /
ConnectNotStart:"会话未建立 (请先 Start 或 Connect)"or"未 Start, 无法读写 IO". - When mapping is unavailable:
"过程数据输入映像不可用". sizeof(T) == 0, orsizeof(T)exceeds the length of available data for this direction:"结构体大于输入过程映像".
- Not /
- The available data length is determined by the interface; do not hard-code offsets or lengths.
- References remain valid for the duration of the mapping.
Stop()Only the device is disabled; the view remains, and the reference remains valid;Close()/ the reference becomes invalid after the mapping is destroyed. It is safest to reacquireStart()the view once. - This is a real-time byte view, not a synchronization primitive: do not use it for inter-thread synchronization, and do not perform conditional polling on it. To "wait for a value to be set," use a snapshot re-read.
- Read operations can be performed concurrently; for write operations (
OutputsMapping), only one writer is allowed per HMI screen at any given time. Please serialize write operations manually if using multiple threads.
Example:
#pragma pack(push, 1)
struct FromPlc {
uint8_t Present; // Offset 0
int16_t Recipe; // Offset 1: Big-endian — If read directly as a host `short`, the bytes will be reversed
uint8_t Flag; // Offset 3
};
#pragma pack(pop)
const FromPlc& inp = device.ProcessData().InputsMapping<FromPlc>();
uint8_t present = inp.Present; // Current cycle value
int16_t recipe = device.ProcessData().In()[1].AsInt16(); // The host sequence values must be output through the element port.
OutputsMapping<T>()
mapping the Q zone (Device → Controller) to a struct reference; modifying this field is equivalent to writing to Q.
template <typename T>
T& OutputsMapping();
Return value:
T&— Writable reference in Zone Q; changes to this field will take effect in the next cycle.
Note:
- Asymmetry relative to the I-side isDeliberate: This side returns
T&(writable), the I side returnsInputsMapping<T>()const T&(read-only). TThe two configuration-time steps are exactly the samestatic_assertas those on the I side.- Failure message
PnSException: "Not connected / Not"—the twoStartmessages are the same as above; "Mapping unavailable" is ;"过程数据输出映像不可用""Size exceeded" is"结构体大于输出过程映像". - To modify a field, type "Q"; the placement is the same
SetOutputs()as for "/Write()": Not necessaryAdjust the submission function one more time, and it will be sent automatically in the next cycle. - The lifecycle is the same as that of thread safety;
InputsMapping<T>()only one writer is allowed to write to the same HMI screen at a time. - Check the dimensions before writing:
Outputs().size()Return the number of bytes currently available in this direction;sizeof(T)the value must not exceed the available data length in this direction, but a smaller value is valid.
Example:
#pragma pack(push, 1)
struct ToPlc {
uint8_t Ready; // Offset 0
uint8_t Busy; // Offset 1
};
#pragma pack(pop)
ToPlc& outp = device.ProcessData().OutputsMapping<ToPlc>();
outp.Ready = 1; // Will be sent in the next cycle; no need to submit a request.
outp.Busy = 0;
Direct Access (Works Even Without Mapping)
Read and write individual elements by byte offset. This family isCopy, not View: In()[i] / Out()[i] This only [i] specifies a byte offset; each time a value is retrieved, it represents the value at that exact moment, not a "live view" obtained via indexing. To maintain a long-term reference to the same data, use a structure mapping (InputsMapping<T>() / OutputsMapping<T>()).
uint8_t b = device.ProcessData().In()[0].Content(); // Read 1 byte starting at offset 0
int16_t iw = device.ProcessData().In()[2].AsInt16(); // Read 2 bytes starting at offset 2 (big-endian)
float f = device.ProcessData().In()[8].AsFloat(); // Read I, offset 8, starting with 4 bytes (big-endian IEEE754)
bool bit = device.ProcessData().In()[0].GetBit(0); // Read the byte at offset 0 bit0
device.ProcessData().Out()[0].Content(0x11); // Write the 1-byte value at Q offset 0
device.ProcessData().Out()[2].AsInt16(123); // Write 2 bytes starting at offset 2 from Q (big-endian)
device.ProcessData().Out()[0].SetBit(0, true); // Write the byte at offset 0 in Q bit0
In() / Out()
Retrieve an array of elements from this direction. In() Corresponds to I (read-only) andOut() Q (writable).
PnSProcessDataArray& In();
PnSProcessDataArray& Out();
Return value:
PnSProcessDataArray&— A reference to an array of elements; its creation does not check the session or allocate memory.
Note:
- Both return references to array objects; the actual byte retrieval occurs during subsequent
operator[]read/write calls. - Writing to the retrieved
In()element will cause an exception to be thrownPnSException("ProcessData.In 只读 I (控制器→设备); 写请用 ProcessData.Out"). - The element port does not have a "get_length" member. How many bytes should be retrieved from the snapshot port in this direction:
device.ProcessData().Inputs().size()/Outputs().size(). - Don't bind the reference to
Out()In()/ to a temporaryPnSProcessDataobject.ProcessData()YesReturn by ValueYes,auto& in = device.ProcessData().In();the temporary variable in that ST disappearsPnSProcessDataat the end of the entire ST andinis immediately left hanging. To use a reference, you must first ST it:
PnSProcessData pd = device.ProcessData(); // Save the variable—it'll last until you no longer need it.
auto& in = pd.In();
auto& out = pd.Out();
Structure mappings are not affected by this rule — InputsMapping<T>() / The returned OutputsMapping<T>() reference is not bound to PnSProcessData the object.
Related Structures:
class PnSProcessDataArray { // In() / Out() returns exactly that
public:
PnSProcessDataArray(PnSService& svc, bool writable);
// Retrieve an element by byte offset (the offset is relative to the start of the data in this direction, not the element's index)
PnSProcessDataItem operator[](int offset) const; // offset < 0: throw PnSException
};
Example:
uint8_t lo = device.ProcessData().In()[0].Content(); // Just string them together; don't bind the references first.
device.ProcessData().Out()[0].Content(lo + 1); // Type "Q" and submit it right away.
PnSProcessData pd = device.ProcessData(); // If you want to quote it, save it first.
auto& in = pd.In(); // I: Read-only
auto& out = pd.Out(); // Q: Writable
out[1].Content(in[1].Content() + 1);
PnSProcessDataItem (element)
A single process data element. It's a copy of the slice, not a view.: [i] Only the byte offset is specified; each read operation returns the value at that exact moment, and each write operation takes effect immediately.
class PnSProcessDataItem {
public:
PnSProcessDataItem(PnSService& svc, size_t offset, bool writable);
// ... See below for members
};
Note:
- Each member comes from this direction. Current OffsetFirst, read and write one segment at a time based on the width of that type, without performing any implicit alignment. The offset isByteOffset; does not enforce 2/4 alignment.
- Read Direction:
In()The element labeled "I" is read first;Out()the element labeled "Q" is read next (the read order matches the write order). - Writing direction: This holds true only for elements that are
Out()output, andEvery time I write something, I submit it right away., Normal return ⟺ Bytes written. - No "Early Interception" for Out-of-Bounds Conditions: If the read/write width exceeds the area in the current direction, an out-of-bounds fault is thrown
PnSException("区域越界: 偏移 N + 长度 M 超出过程映像区 K 字节"). - One evaluation = one new region snapshot. Therefore, two evaluations of the same expression may occur in two different bus cycles, and synchronization across calls is not guaranteed.
Related Structures:
class PnSProcessDataItem {
public:
PnSProcessDataItem(PnSService& svc, size_t offset, bool writable); // Generally, you don't have to make it yourself.
// Byte: 1 byte, unsigned, raw byte
uint8_t Content() const; void Content(uint8_t value);
// Fixed-width scalars: Use the parameter-less overload to read values, and the single-parameter overload with the same name to write values; all multi-byte values are in big-endian (PROFINET network order).
int8_t AsInt8() const; // 1 byte, signed void AsInt8(int8_t value);
uint8_t AsUInt8() const; // 1 byte, unsigned void AsUInt8(uint8_t value); // Synonymous with Content and same byte size
int16_t AsInt16() const; // 2 bytes, signed, big-endian void AsInt16(int16_t value);
uint16_t AsUInt16() const; // 2 bytes, unsigned, big-endian void AsUInt16(uint16_t value);
int32_t AsInt32() const; // 4 bytes, signed, big-endian void AsInt32(int32_t value);
uint32_t AsUInt32() const; // 4 bytes, unsigned, big-endian void AsUInt32(uint32_t value);
int64_t AsInt64() const; // 8 bytes, signed, big-endian, void AsInt64(int64_t value);
uint64_t AsUInt64() const; // 8 bytes, unsigned, big-endian void AsUInt64(uint64_t value);
float AsFloat() const; // 4 bytes IEEE754 big-endian void AsFloat(float value);
double AsDouble() const; // 8 bytes IEEE754 big-endian void AsDouble(double value);
// Boolean: Whole Byte, bit0 Semantics
bool AsBool() const; void AsBool(bool value); // Write: Full byte 0 / 1
// Position: Affects only the byte at the current offset; indices 0–7, where 0 = LSB
bool GetBit(int bitIndex) const;
void SetBit(int bitIndex, bool value); // The remaining bits in the same byte remain unchanged.
};
Example:
// Read (Side I)
uint8_t b = device.ProcessData().In()[0].Content();
int16_t iw = device.ProcessData().In()[2].AsInt16();
uint32_t dw = device.ProcessData().In()[4].AsUInt32();
double f8 = device.ProcessData().In()[8].AsDouble();
// Write (Q side)
device.ProcessData().Out()[0].Content(0x11);
device.ProcessData().Out()[2].AsInt16(-123);
device.ProcessData().Out()[4].AsUInt32(10000);
AsBool()
Read the true or false value by reading whole bytes, bit0 Semantics: Only if the least significant bit is 1 is it true.
bool AsBool() const;
void AsBool(bool value);
Return value:
bool— The value of the least significant bit of the byte at the current offset (0→false,1→true).
Note:
- Non-standard bytes
0x02and0x80are both read asfalse— not 「non-0 means true」. - This function provides only SDK this single full-byte Boolean value. To determine whether the value is true or false based on whether the full byte is 0 or not 0, please read the value and compare it yourself
Content(). - Write "Steering Wheel"The entire byteWrite as
0x01or0x00, not by modifying individual bits. To read or write bit by bit, useGetBit()/SetBit(). - Write
In()side elements:PnSException.
Example:
bool flag = device.ProcessData().In()[3].AsBool(); // It is true only if the least significant bit is 1.
uint8_t raw = device.ProcessData().In()[3].Content(); // To determine true or false based on whether the entire byte is 0 or not 0, read the raw byte.
device.ProcessData().Out()[3].AsBool(true); // Write: Entire byte = 0x01
GetBit() / SetBit()
The location where the read-write element is locatedOne byteOne of them.
bool GetBit(int bitIndex) const;
void SetBit(int bitIndex, bool value);
Return value:
bool— The value of this bit.
Note:
- Bit index value
0–7,0is the least significant bit (LSB). An out-of-bounds access results in a throwPnSException("位索引必须在 0-7 之间"). - Bit indexing uses only the byte at the element's offset and is independent of the element's width: taking
0–7at the offset used for reading/writing withAsInt16/AsInt32still only accesses the starting byte and never extends to subsequent bytes. SetBitis read-modify-write: read that one byte, flip only the target bit, and write the entire byte back — leaving the remaining bits of the byte unchanged.SetBitThis holds true only for theOut()side; for the side, "read-only" is flagged firstIn()PnSException(since the read-only check is performed before the bit index check,In()[0].SetBit(9, true)reports "read-only" rather than a bit index out-of-bounds fault). When writing, the remaining bits in the same byte remain unchanged.- When the ball goes out of bounds, the "out-of-bounds" announcement is played (see the
PnSProcessDataIteminstructions).
Example:
bool b0 = device.ProcessData().In()[3].GetBit(0); // Offset by 3 bytes from that byte bit0
device.ProcessData().Out()[3].SetBit(0, true); // Set only this bit bit0; leave the remaining bits of the byte unchanged
device.ProcessData().Out()[3].SetBit(0, false); // Only Clear bit0
Same Shot and Snapshot
There are three types of reading interfaces; you must understand the differences before using them interchangeably:
| How to Read | Nature | "The Value at That Moment" |
|---|---|---|
InputsMapping<T>() / Citations obtained OutputsMapping<T>() | Live View, always connected to the same dataset | Without the "read once" operation, the member will simply receive the value as it stands at that moment. |
Elements In()[i] / Out()[i] | Snapshot: Each time a value is retrieved, a new complete region in this direction is selected, and then the value is calculated based on the offset. | One retrieval = one new snapshot |
Read() / ReadArea() / ReadStruct<T>() / Inputs() / Outputs() / GetIo() | Snapshot | One call = one new snapshot |
SoTwo evaluations of the same expression may occur in two different bus cycles.:
// Two calls = two separate snapshots; no guarantee that they will be taken at the same time.
int32_t delta = device.ProcessData().In()[6].AsInt32()
- device.ProcessData().In()[2].AsInt32();
The same applies to writing directions: Write once = Submit once, no batching. Out()[0].Content(v) and Out()[2].AsInt16(v) are two independent commit points, each written immediately; if a commit fails, the data to be written is retained (no loss), and the next write attempt will retry the operation along with the retained portion.
If multiple fields must match, select any one of the following:
① Use a mapped reference to create a copy by value(The simplest and most economical):
const FromPlc& live = device.ProcessData().InputsMapping<FromPlc>();
FromPlc snapshot = live; // Single copy: Once the copy is complete, it no longer changes with the bus.
int16_t recipe = snapshot.Recipe; // From snapshot.Present the same copy
② Read the entire segment in one go, then parse it yourself using offsets.:
std::vector<uint8_t> frame = device.Read(); // A complete snapshot of Zone I; consistent within the same shot
if (frame.size() >= 6) {
uint8_t a = frame[0];
int32_t b = (int32_t)((frame[2] << 24) | (frame[3] << 16) | // Big Endian, put it together yourself
(frame[4] << 8) | frame[5]);
}
③ Structure Snapshot: ReadStruct<T>() Copy one structure at a time; the fields come from the same copy.
FromPlc s = device.ProcessData().Read<FromPlc>(); // Equivalent ReadStruct<FromPlc>()
InputsMapping<T>()—— Zone I is mapped toconst T&, and the value read is the current cycle value.OutputsMapping<T>()—— The "Q" zone is mapped toT&; changing this field is equivalent to writing "Q."
Element Port, Read() / ReadArea() / ReadStruct<T>() / GetIo() All of themCopy. All paths except OutputsMapping<T>() are snapshot commits (Write() / SetOutputs() / WriteArea()).
entry point to the Entire District (Snapshot)
If you don't want to process items one by one, simply read and write the entire segment. These are all copies, not views. —— To achieve “automatic field conversion at the source,” you still need to use structure mapping.
Read()
Take a full snapshot of Zone I (Controller → Devices).
std::vector<uint8_t> Read();
Return value:
std::vector<uint8_t>— Copy the entire segment from Zone I. Length = effective length (if the true length is known, use that as the boundary; if the true length is unknown (0), return the capacity limit). The true length is takenGET /api/iofromoutputLength(the field names are in the opposite direction of I/Q; do not use the names to determine the values).The data returned by a single call belongs to the same sample and is internally consistent across fields.
Note:
- Failure message
PnSException: See the twoStartmessages for "Not connected" / "Not"InputsMapping<T>(); when mapping is unavailable, the message is"过程数据未就绪, 无法读写 IO". - Retrieves the current value on each call; does not cache based on the beat.
- The return length is the effective length (not extrapolated based on zone capacity) and corresponds to the same diameter
*nas the mapping. - Across Multiple CallsNot guaranteed to be the same lot: Make sure multiple fields match; read them all at once and then split them yourself.
Example:
std::vector<uint8_t> all = device.Read(); // I Entire Paragraph
if (all.size() >= 4) {
int16_t recipe = (int16_t)((all[2] << 8) | all[3]); // Interpret it yourself using the big-endian approach
}
Write(data)
Write Q (device → controller); abbreviations are allowed.
void Write(const std::vector<uint8_t>& toPlc);
Return value:
- None. Normal return ⟺ Bytes written (immediate commit, no delay based on the timer cycle).
Note:
- Overwrite the first
data.size()bytes starting at offset 0, StillThe remaining bytes. - Stop-Loss Order
PnSException:dataEmpty:"写数据不能为空".- Not connected / Not
Start:"会话未建立 (请先 Start 或 Connect)"/"未 Start, 无法读写 IO". - When mapping is unavailable:
"过程数据未就绪, 无法读写 IO". data.size()Exceeds District Chief Q:"区域越界: 偏移 0 + 长度 M 超出过程映像区 K 字节".- Submission failed:
code() == PnSErrorCode::NativeError,what()is"IO 提交失败: <真因>"or"过程数据未就绪, 无法提交 IO". Data to be written retained, I'll try again the next time I write; I won't report a false success, nor will I lose any data.
Write()andSetOutputs()are two different ways of writing the same path (the latter is onProcessData()).- You can see the failure even without catching exceptions:
device.LastServiceError()/ staticLastError()/LastErrorCode().
Example:
device.Write(std::vector<uint8_t>{0x01, 0x00}); // 2 bytes starting at offset 0
ReadStruct<T>() / WriteStruct<T>(data)
In/out of structure snapshots, Not a mapping: The return value does not change automatically when the bus is refreshed.
template <typename T>
T ReadStruct();
template <typename T>
void WriteStruct(const T& data);
Return value:
T— A copy of the struct returned by value.
Note:
TIt must be trivially copyable (at configuration timestatic_assert). Not necessarypack(1): This is a value copy; it does not use mapping.- The copied string isOnline Byte, as is, No byte order conversion: The
int16_t/floatfield in the structure is still in big-endian byte order; you'll need to convert it yourself to use it. ReadStruct<T>()Failure: Outside the assertion,sizeof(T)greater than I, long throwPnSException("结构体大小 N 超出 I 区 M 字节")(this copy itself is positioning information with a size mismatch).WriteStruct<T>(data)Failure:sizeof(T) == 0Will be treated as a blank submission and discarded;"写数据不能为空"all other failures are identicalWrite()to (incomplete submission, submission on the spot, or submission failure with aNativeErrorcode and the data to be written retained).- To display a live view that continuously updates in real-time, use
InputsMapping<T>()/OutputsMapping<T>().
Example:
FromPlcText t = device.ProcessData().Read<FromPlcText>(); // Equivalent ReadStruct<FromPlcText>()
ToPlc out{}; out.Ready = 1;
device.ProcessData().Write(out); // Equivalent WriteStruct(out)
GetIo()
Retrieve data copies from both directions in a single operation.
std::pair<std::vector<uint8_t>, std::vector<uint8_t>> GetIo();
Return value:
std::pair—firstYes Q-side data(on theOutputs()same piece);secondYes I. Side Data(On the same shieldingInputs()). The lengths on both sides are valid lengths (if the true length is known, it serves as the boundary; if the true length is unknown (0), the upper capacity limit is used instead). They're all copies.
Note:
- Failure message
PnSException: "Not connected / Not available"—the twoStartmessages are the same as above; when mapping is unavailable, the message is"过程数据未就绪, 无法读写 IO". ReadAreaUnlike , it does not participate in the "write-after-read consistency" shadow semantics—it returns the current value.first/ It's easy to mix up the order ofsecond: Q First, Then I. If you can't remember it, just useInputs()/Outputs()— it's more straightforward.- Two LengthsIndependent of one another(Q true length =
GET /api/ioinputLength, I true length =outputLength; the field names are opposite to the I/Q directions—don’t go by the names), soDon't directlysecond.size()compare the sizes offirst.size()and .
Example:
auto io = device.GetIo();
size_t qLen = io.first.size(); // Q: Equipment → Controller
size_t iLen = io.second.size(); // I: Controller → Device
if (!io.second.empty()) {
uint8_t firstByteOfI = io.second[0];
}
ReadArea() / WriteArea()
Read the entire segment or write a partial overwrite based on region and byte offset.
std::vector<uint8_t> ReadArea(PnSServiceArea area, size_t offset, size_t length);
std::vector<uint8_t> ReadArea(PnSServiceArea area);
void WriteArea(PnSServiceArea area, size_t offset, const std::vector<uint8_t>& data);
void WriteArea(PnSServiceArea area, const std::vector<uint8_t>& data);
Return value:
ReadArea(...)—std::vector<uint8_t>: A segment of the full-zone snapshot capturedlengthatoffset/ .WriteArea(...)— None. Normal return ⟺ The entire shielding of bytes has been written (committed immediately).
Note:
areaRecognizes onlyPnSServiceArea::Input(I, read-only) andPnSServiceArea::Output(Q, write-only). PassMemory/DborUnknowndiscardPnSException("区域非法").- Read failure types:
"区域非法";offset + lengthOut of range:"区域越界: 偏移 N + 长度 M 超出过程映像区 K 字节"; Not attached / NotStart/ Mapping unavailable—see above. - There are more examples of incorrect forms; the order is as follows: Check the parameters first, then modify the data.: Zone I exception;
"I 区 (控制器 -> 设备) 只读, 不支持写"illegal zone exception;"区域非法"``datanull exception"写数据不能为空"; out-of-bounds exception (out-of-bounds zone); submission failure exceptionPnSException(code = PnSErrorCode::NativeError); data to be written is retained for retry. WriteArea(area, data)It is an abbreviation forWriteArea(area, 0, data)"yes" and is overwritten starting at offset 0.- One call = one commit: You can make multiple changes to non-adjacent segments, but that counts as multiple commits, not a single batch. To commit multiple non-adjacent changes in a single operation, please combine the consecutive segments yourself
datain or switch toOutputsMapping<T>()to edit the fields directly. - You don't need to worry about it even when you're only taking a few bytes; the region itself is only a few dozen bytes.
Related Structures:
enum class PnSServiceArea {
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 items only
};
Example:
std::vector<uint8_t> part = device.ReadArea(PnSServiceArea::Input, 4, 2); // Zone I, offset 4, starting at 2 bytes
std::vector<uint8_t> allQ = device.ReadArea(PnSServiceArea::Output); // Q: Entire District
device.WriteArea(PnSServiceArea::Output, 4, std::vector<uint8_t>{0x01, 0x02}); // Cover Q[4..5]
Inputs() / Outputs() / SetOutputs() / Read<T>() / Write<T>()
ProcessData() "Convenient forwarding" here is synonymous with the "entering the entire zone" option mentioned above.
std::vector<uint8_t> Inputs(); // → Read()
std::vector<uint8_t> Outputs(); // → ReadArea(Output)
void SetOutputs(const std::vector<uint8_t>& data); // → Write(data)
template <typename T> T Read(); // → ReadStruct<T>()
template <typename T> void Write(const T& data); // → WriteStruct<T>()
Return value:
Inputs()/Outputs()— Copy the entire paragraph.Read<T>()— Copying structures.SetOutputs()/Write<T>()— None.
Note:
- Reading and Writing Have Different Names:
Outputs()YesRead Q: Shadow; to write "Q," useSetOutputs(data). The old post with the same name has been deletedOutputs(data), Do not include "deprecated" in the forward. — Don't just copy the old examples. Inputs()/Outputs()Length and diameter: Both sides are effective lengths (if the true length is known, it is used as the boundary; if the true length is unknown (0), the calculation reverts to the capacity limit).- The failure patterns are identical to those of the entry points to which they are forwarded; no separate set is created.
Example:
std::vector<uint8_t> i = device.ProcessData().Inputs();
std::vector<uint8_t> q = device.ProcessData().Outputs();
device.ProcessData().SetOutputs(std::vector<uint8_t>{0x01, 0x00});
ToPlc out{}; out.Ready = 1;
device.ProcessData().Write(out); // Snapshot port for "Q" in the structure
Read/Write by Address (Region + Byte + Bit)
Use this set if you don't want to calculate the offset yourself and want to write the address exactly as it appears in the engineering software: Region Letter + Byte Offset + Bit. The address is resolved by ParseAddress, and word / double word offsets are just byte offsets; 2/4 alignment is not enforced.
| 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 | Bytes: 1 byte |
IW2 / QW2 | Word: 2 bytes, big-endian |
ID4 / QD4 | Double word: 4 bytes, big-endian |
I0 / Q4 | Type-less character = byte field (length 1) |
Not allowed: Zone M / Zone DB(Service mode not supported; the request is discarded upon parsing.)
ParseAddress()
Static resolution of HSL expression address strings. Does not require a link or to be started — This is purely string processing and can be used to validate the address entered by the user before startup.
static PnSServiceAddress ParseAddress(const std::string& text);
Return value:
PnSServiceAddress— Analysis results: region, byte offset, bit number, data width.bit“ ” indicates-1non-bit addressing;slot“/ ”subslotis a fixed value in the interface (fixed to a single module for this product), and neither read nor write paths use them.
Note: array all failure cases one by one (all are single-argument constructs PnSException, code() where is -1):
| Input | Draft Copy |
|---|---|
| Empty string / All spaces | "地址不能为空" |
DB1.DBD4, (case-insensitive db at the beginning) | "不支持 DB 地址: DB1.DBD4" |
M0.0(M District) | "不支持 M 地址: M0.0" |
Other initials, such as X0.0 | "不支持的地址区域: X0.0" |
I0. / I.0 / Q1. | "地址格式非法 (位地址应为 I0.0 形式): I0." |
The position number is not in the range 0–7, such as I0.8 | "位号必须在 0-7 之间: I0.8" |
Offsets or index numbers contain non-digital characters, such as Q-1 / I0.0.0 | "字节偏移非法: Q-1" / "位号非法: I0.0.0" |
Offset or index exceeds 0xFFFF | "字节偏移超出范围: IW70000" / "位号超出范围: I0.65536" |
Only contains regional and type characters, with no numbers, such as I / IW | "地址缺少偏移量: IW" |
- Regional CharactersCase-insensitive(
i0.0=I0.0,q4=Q4); Type: CharacterB/W/DRecognize only uppercase letters,Iw2it will be discarded because it is treated as having non-digital characters in the offset"字节偏移非法: Iw2". - Word / double word offsets are not checked for alignment:
IW3/ID2are both valid; the offset refers to the byte offset. - The
lengthof a bit address is always counted as 1 byte—bit operations must read and write in whole bytes to avoid overwriting other bits in the same byte.
Example:
PnSServiceAddress a = PnSService::ParseAddress("IW2");
// a.area == PnSServiceArea::Input, a.byte_offset == 2, a.bit == -1, a.length == 2
Areas outside the I/Q band (M/DB) are resolved and discarded PnSException(see table above for details) — This unit supports SDK only the I/Q band.
ReadBool() / WriteBool()
Read or write a single bit using a bit-addressed operation.
bool ReadBool(const std::string& address);
void WriteBool(const std::string& address, bool value);
Return value:
bool— The value of that bit in the byte at that address (0→false,1→true).
Note:
- The address must beWith a seat number(
I0.0/Q3.7). Throw an exception for addressesIB0of this type that do not have a position numberPnSException("位地址必须带位号: IB0"). - What is actually being judged here is that bit (
(byte & (1 << bit)) != 0), which is different from theAsBool()whole-byte bit0 measurement at port : the former measures the bit you select, while the latter always measures byte bit0. To determine true or false based on whether the whole byte is 0 or not 0, read the value and compare it yourselfContent(). WriteBoolYesRead and Rewrite: Read the entire byte, flip only the target bit, and write the entire byte back — leaving the other bits in the byte unchanged.WriteBoolWrite "I" in Zone (I0.0)PnSException("I 区 (控制器 -> 设备) 只读, 不支持写").- Throw an out-of-bounds exception
"地址越界: 偏移 N + 长度 M 超出过程映像区 K 字节"; see the documentation for "Not connected / NotStart/ Mapping unavailable"InputsMapping<T>(); throw a "Write commit failed" exceptionPnSException(code = PnSErrorCode::NativeError), and retain the data to be written for a retry. - Read operations can be performed concurrently; you are responsible for serializing write operations.
Example:
bool done = device.ReadBool("I0.0"); // Read the 0th byte of I bit0
device.WriteBool("Q0.0", true); // Set only the 0th byte of Q to bit0
device.WriteBool("Q0.1", false); // Clear only the 0th byte of Q bit1; leave the rest unchanged bit0 .
ReadInt16() / WriteInt16()
Read and write by word address (2 bytes), big-endian encoding and decoding.
int16_t ReadInt16(const std::string& address);
void WriteInt16(const std::string& address, int16_t value);
Return value:
int16_t— The first 2 bytes of this address arebig-endian(PROFINET network sequence) The signed value derived from this.
Note:
- The address must be 2 bytes wide andNon-bit addressing: Only accepts
IW2/QW2this type; does not accept othersIW2.0. RejectsI0(width 1),ID2(width 4),I0.0and (bit-addressed)PnSException("字地址必须为 2 字节且非位寻址: <地址>"). - Does not enforce 2-byte alignment:
IW3Legal. - The byte order isbig-endian: Send the high-order byte first.
WriteInt16("QW2", 123)Completed00 7B. WriteInt16Write "Sell" in Zone I"I 区 (控制器 -> 设备) 只读, 不支持写".- If you need unsigned 16-bit or floating-point values, there is no corresponding entry in this group—use the element port
In()[i].AsUInt16()/AsFloat(), orReadArearetrieve the raw bytes yourself.
Example:
int16_t recipe = device.ReadInt16("IW2"); // I Offset 2, starting at 2 bytes (big-endian)
device.WriteInt16("QW2", 123); // Q: Offset 2, starting at 2 bytes (big-endian)
device.WriteInt16("QW3", -1); // Offset 3 is also valid: misalignment does not result in an fault
ReadInt32() / WriteInt32()
Read and write using double word addresses (4 bytes), with big-endian encoding and decoding.
int32_t ReadInt32(const std::string& address);
void WriteInt32(const std::string& address, int32_t value);
Return value:
int32_t— The first 4 bytes starting at this address arebig-endianThe signed values obtained.
Note:
- Addresses must be 4 bytes wide and non-bit-addressable: e.g
QD4., /ID4. ExcludeIW2(width 2) andI0.0(bit-addressable)PnSException("双字地址必须为 4 字节且非位寻址: <地址>"). - Do not enforce 4-byte alignment:
ID2Legal. - Byte order:
WriteInt32("QD4", 10000)big-endian: Completed00 00 27 10. - The other failure scenarios (Zone I read-only / out of bounds / not started / submission failure) are
ReadInt16()exactly the same. - For unsigned 32-bit or floating-point values, use the element port
In()[i].AsUInt32()/AsFloat()/AsDouble().
Example:
int32_t counter = device.ReadInt32("ID4");
device.WriteInt32("QD4", 10000);
PnSSharedImage Direct Read/Write
PnSSharedImage Directly read and write IO data, There are no session parameters in the class. —— The entire set of entry points mentioned above (ProcessData() / Read() / address-based read/write) requires establishing a service session first andStart() can only be used after the session is successfully established; this group does not require establishing a session, as determined by is_mapped() and connected().
i_payload() / q_payload() Provide a byte address that can be read from and written to directly. This family does not recognize structures and does not include size checks; for out-of-bounds access, it calculates the valid length on its own (image_len if known, it is considered in bounds; if unknown, it falls back to the upper capacity limit).
pns.hpp has already #include been ; pns_shm.hpp the latter can also be included separately and used in any pns.hpp order with , all within the darra::pns namespace. The failure of this familyThrow PnSShmException(Not the one above PnSException), the two sets of copy are not interchangeable.
#include "pns.hpp" // Already included pns_shm.hpp; you can also #include "pns_shm.hpp" separately
using namespace darra::pns;
PnSSharedImage shm;
shm.map(); // Open + mapping + Verify Header (Throw on failure PnSShmException)
uint32_t i_len = 2, q_len = 2; // Very long (I-side = GET /api/io outputLength, Q-side = inputLength; field name is opposite to the/Q I-direction), unknown transmission 0
shm.write_to_plc(0, {0x11, 0x22}, q_len); // Write Q (device → controller); write boundary = true length, fall back to the capacity limit when unknown
std::vector<uint8_t> fromPlc = shm.read_from_plc(i_len); // Read I; length = actual length, unknown return capacity limit
bool run = shm.connected(); // Cycle data is normal
// Automatic unmap on destruct
map() / unmap() / is_mapped()
Open IO Data Mapping and verify the Size and in the header Version.
void map(); // Idempotent: Returns the mapped value directly
void unmap() noexcept; // Idempotent, non-throwing
bool is_mapped() const;
Return value:
is_mapped()—bool: The view is at →true.
Note:
map()Idempotent: If the mapping already exists, return immediately. Otherwise, return a failure. Throws as isPnSShmException, included in the code;NTSTATUSthe failure path closes any open handles or views, Do not leave the ST in a semi-mapped ST.map()Check the mapping size against the header'sSize/Version; if they don't match, discard it, and reclaim both the view and the handle.- The fault message for "Driver not loaded / Non-administrator / Service not RUN"
map()includes these three clues. - It compiles on non-Windows platforms, but
map()throws an exception"PnSSharedImage 仅支持 Windows". unmap()Unmaps and closes the handle; idempotent and does not throw an exception; the destructor is equivalent tounmap(). Once the mapping is removed,i_payload()/ the specifiedq_payload()address becomes invalid immediately.
Example:
PnSSharedImage shm;
shm.map(); // The failure has been discarded; the return indicates that the mapping has been completed.
bool mapped = shm.is_mapped(); // true
shm.unmap(); // Idempotent, non-discarding—it’s fine to call it again.
read_from_plc() / read_to_plc_shadow()
std::vector<uint8_t> read_from_plc(uint32_t image_len = 0) const;
std::vector<uint8_t> read_to_plc_shadow(uint32_t image_len = 0) const;
Read the input area (I, controller → device) and the shadow of the output area (Q, the most recent entry you wrote there). Both are copies.. image_len = True Length (read_from_plc according GET /api/io to I, True Length = outputLength; read_to_plc_shadow according to Q, True Length = ; inputLength field names are opposite to the I/Q directions—do not assume they correspond to their names), 0 = Unknown, returns the maximum capacity.
Return value:
std::vector<uint8_t>— Data bytes for I/Q.
Note:
- Return length = effective length (if the true length is known, it is used as the limit; if the true length is unknown (0), the upper capacity limit is returned), Do not extrapolate based on district capacity; Equivalent
*ntoq_payload()i_payload()/ . read_to_plc_shadow()Symmetricwrite_to_plc(): Writes and reads the same data. Returns when the output buffer is not yet ready (output buffer length ≤ 3 bytes). Empty vector.- Reads in this family are snapshots; if this occurs concurrently with periodic updates, you might end up reading a mix of new and old data; to ensure consistency at any given moment, you must read all the data at once.
- Exception
PnSShmException: Unmapped; out-of-bounds access in the process data area.
Example:
std::vector<uint8_t> i = shm.read_from_plc(image_i_len);
std::printf("I %zu 字节\n", i.size());
std::vector<uint8_t> shadow = shm.read_to_plc_shadow(image_q_len); // Review the Q you just entered
write_to_plc()
Write offset to Q region starting at data offset (device → controller). Short writes are allowed.
void write_to_plc(uint32_t offset, const uint8_t* data, size_t length,
uint32_t image_len = 0);
void write_to_plc(uint32_t offset, const std::vector<uint8_t>& data,
uint32_t image_len = 0); // Convenient Reloading
Return value:
- None.
Note:
- The landing point is the offset
offsetwithin the available data range; the write boundary = the valid length (the true length is the boundary when known; when the true length is unknown (0), fall back to the capacity limit — do not extrapolate from the zone capacity). The true length is taken frominputLengthofGET /api/io(the field names are opposite to the I / Q direction; do not take them by name). - Abbreviations allowed: When writing data that exceeds the allowed length, truncate it without reporting a fault; verify the actual amount written using
read_to_plc_shadow(). For ports that require an "out-of-bounds fault" to be reported, use theWriteArea()/ element port family. length == 0Allowed: Do not copy data; submit only once.- After writing, it is automatically sent in the next cycle; there is no need to call the commit method again.
- Throw
PnSShmException:dataA null pointerlength > 0;offsetgoing beyond the available data range;offset + lengthunable to write even a single byte.
Example:
shm.write_to_plc(0, std::vector<uint8_t>{0x01, 0x00}, image_q_len); // Q: 2 bytes starting at data offset 0
uint8_t q[2] = {0x02, 0x00};
shm.write_to_plc(0, q, sizeof(q), image_q_len); // Pointer Overloading: The Same Path
std::vector<uint8_t> back = shm.read_to_plc_shadow(image_q_len); // Verify Actual Settlement
i_payload() / q_payload()
Addresses where data bytes can be read and written—not copied.
volatile uint8_t* i_payload(size_t* n = nullptr, uint32_t image_len = 0) const;
volatile uint8_t* q_payload(size_t* n = nullptr, uint32_t image_len = 0) const;
Return value:
volatile uint8_t*— Read/write addresses of data bytes (not a copy).nIf not empty, the number of data bytes written back equals the valid length (if the true length is known, it is used as the limit; if the true length is unknown (0), the upper capacity limit is used); values are not extrapolated beyond the zone’s capacity.
Note:
- After a single mapping, the bus refresh field changes on its own—this type does not generate any copies.
i_payload()Same asread_from_plc()in terms of size, but not a fixed address: Use*nas the reference for available length; do not hard-code offsets or lengths.q_payload()The landing point is the samewrite_to_plc()as . Changing the bytes is writing Q; it will be sent automatically in the next cycle.- The address is atValid for the duration of the mapping view's lifecycle:
unmap()/ Becomes invalid after destruction. - A structure mapped according to this view must be
pack(1)(padding makes the whole thing misaligned); all multi-byte values are network big-endian — this is the same rule as the structure contract at the top of the page. - Thrown
PnSShmException: Not mapped; input/output buffer out of bounds; insufficient data length in input buffer ("过程数据输入映像不可用"); output buffer length ≤ 3 bytes ("过程数据输出映像不可用").
Example:
size_t n = 0;
volatile uint8_t* qp = shm.q_payload(&n, image_q_len); // Data address, not a copy; n = effective length
uint8_t* raw = const_cast<uint8_t*>(qp);
raw[0] = 0x01; // Changing a byte is the same as writing a "Q"
size_t m = 0;
volatile uint8_t* ip = shm.i_payload(&m, image_i_len); // I: Same road on the same side; m = effective length
read_header() / connected()
Header read_header() const;
bool connected() const;
uint32_t driver_state() const;
uint64_t last_error() const;
Return value:
read_header()—Header: A one-time snapshot of the header.connected()—bool: IO Is the controller's periodic data normal?driver_state()—uint32_t: Original value in the RUN ST.last_error()—uint64_t: The original value that triggered the most recent fault.
Note:
connected()To determine whether the periodic data is normal, No Fake Green:1= Normal cycle data,0= Disconnected / safe state. During the cycle, this is checked first, and then a decision is made whether to use the data or enter safe state. Even when0it is set to , it willread_from_plc()still return bytes—however, there is no guarantee as to which beat those bytes belong to.driver_state()Returns one of the following valuesDARRT_PNS_STATE: STOP / Bound / Configured / RUN / Safe / Faulted.- On the headLength/offset-type fields are clipped to the upper limit after being read, it will not return out-of-bounds values.
- These are allSnapshot. ..When this occurs concurrently with periodic updates, you may end up reading a mix of new and old data. To determine whether “the copy you have is the latest one,” check the values of
Heartbeatand at the beginningCpmCycleCounter(both of which increment periodically). - If not mapped, throw an exception uniformly
"过程数据未就绪 (请先 map())".
Example:
if (!shm.connected()) {
// cable break / Safe State: Wait between shots on your own; this end does not handle scheduling.
}
PnSSharedImage::Header h = shm.read_header();
std::printf("State=%u LastError=0x%llX 心跳=%llu\n",
h.State, (unsigned long long)h.LastError, (unsigned long long)h.Heartbeat);
Record Index Space (User Area / I&M)
Acyclic records also have two sets of index spaces and two sets of endpoints; don't treat them as a single table when searching.
| Index Space | Scope | The entry point to SDK This Place |
|---|---|---|
| User Area Records | 0x0000–0x7FFF | GetRecords()(Diagnostics().Records() Same data) |
| I&M Equipment Identification | 0xAFF0–0xAFF4 | GetIm() / ImData() |
GetRecords()
Retrieve the user area record table. Read-Only Observation, There was originally no SDK entry for this record.
PnSUserRecords GetRecords();
Return value:
PnSUserRecords— Record table. If there are no records, it is an empty table, Not a failure.
Note:
- The coverage isUser Area
0x0000–0x7FFF. In this contextNone I&M records. - Missing fields will always be set to their default values (0 or an empty string); no values are fabricated.
countThis is a server-side count and is not affected by the length of the local array. - Failure exception
PnSException: Unhandled exception;"会话未建立 (请先 Start 或 Connect)"server response not 200 / unreachable exceptionPnSException(single-argument constructor,code()=-1). Not necessaryStart()—— OnceConnectyou've created it, you'll be able to read it. - Each record strip
slot/subslot/index/length/data_hex—— Information from the other end is inIn the record entry, butThe calling side does not accept slot parameters.(This product is a fixed single-module unit.)
Related Structures:
struct PnSUserRecord {
uint16_t slot = 0; // Bay
uint16_t subslot = 0; // subslot
uint16_t index = 0; // Record Index (User Area 0x0000-0x7FFF)
uint16_t length = 0; // Number of data bytes
std::string data_hex; // Hexadecimal data string (empty strings for missing fields)
};
struct PnSUserRecords {
std::vector<PnSUserRecord> records; // Record array (empty = no records; not an fault)
int count = 0; // Server Count (Missing fields are set to 0)
};
Example:
PnSUserRecords recs = device.GetRecords();
for (const PnSUserRecord& r : recs.records) {
std::printf("slot %u/%u index 0x%04X len %u %s\n",
r.slot, r.subslot, r.index, r.length, r.data_hex.c_str());
}
GetRecords() readings are not included in this table. User Area(0x0000–0x7FFF); I&M is in a different index space (0xAFF0–0xAFF4) and uses a different endpoint. To look up the I&M index in the record table, useCannot be found —— I&M Please use the one below GetIm().
GetIm() / ImData()
Retrieve observation data for equipment identification (I&M). The two names refer to the same implementation.
PnSServiceImInfo GetIm();
PnSServiceImInfo ImData(); // Same as GetIm()
Return value:
PnSServiceImInfo— I&M0 effective value + I&M1–I&M3 readback value + project identifier field.
Note:
- This is from SDK the bookThe Only OneEntry for service I&M (
0xAFF0–0xAFF4); the record tableGetRecords()cannot access this index space. - I&M1–I&M3 Enabled by the native stack and read back verbatim: When the server-side site is RUN
im14_supported == true, the field containsIO the value written by the controller (IO if the controller has not written a value, it uses the stack’s substitution value placeholder value); if I&M4 is not enabled (GSDML not declared),im4_signature_hexthe field is empty. The criteria for both of these scenarios are accurately documented in [...im_note]. order_id/serial_number/hardware_revision/software_revisionis a mirror of the native stack's fixed default values;project_*is an identifier field XML in the project (not yet integrated with I&M0). These values are also recorded accurately in ,im_noteso do not report them as actual measured values.- If a field is missing or parsing fails, the substitution value (empty string / 0) is used, and no fault is reported.
- Failure exception
PnSException: Unhandled exception;"会话未建立 (请先 Start 或 Connect)"server response not 200 / unreachable exceptionPnSException(single-argument constructor,code()=-1). Not necessaryStart()—— OnceConnectyou've created it, you'll be able to read it.
Related Structures:
struct PnSServiceImInfo {
uint16_t vendor_id = 0; // Vendor ID (I&M0, read from runtime configuration)
uint16_t device_id = 0; // Device ID (I&M0, read from runtime configuration)
std::string order_id; // Order Number (Mirror of Native Stack substitution value)
std::string serial_number; // Serial Number (Mirror of the native stack's fixed substitution value)
std::string hardware_revision;
std::string software_revision;
std::string station_name; // Site Name (DCP for discovery purposes; taken from the runtime configuration)
std::string product_name; // Product Name (LLDP/SNMP Used in the runtime configuration)
std::string im_supported; // Enabled I&M record sets (strung together exactly as specified by the native stack shielding, e.g., "I&M0,I&M1,I&M2,I&M3")
bool im14_supported = false; // M1I&-4 Did the read operation succeed? (IO Device is RUN = true; not RUN and cannot be read = false; field is an empty string)
std::string im_note; // Scope Notes (Accurately indicate data sources / which ones are not enabled / not integrated)
std::string im1_tag_function; // I&M1 Function Labels (IO If not programmed in the controller = factory substitution value)
std::string im1_tag_location; // I&M1 Installation Location (IO If not specified in the controller = factory substitution value)
std::string im2_date; // I&M2 Date (IO Not programmed in the controller = factory substitution value)
std::string im3_descriptor; // I&M3 Description (IO Not programmed in the controller = factory substitution value)
std::string im4_signature_hex; // I&M4 Signature (Not enabled; left blank)
std::string project_order_number; // Engineering XML <OrderNumber> (Not connected to I&M0)
std::string project_hardware_release; // Engineering XML <HardwareRelease> (Not connected to I&M0)
std::string project_software_release; // Engineering XML <SoftwareRelease> (Not connected to I&M0)
};
Example:
PnSServiceImInfo im = device.GetIm(); // or device.ImData()
std::printf("vendor=0x%04X device=0x%04X station=%s\n",
im.vendor_id, im.device_id, im.station_name.c_str());
if (!im.im14_supported)
std::printf("I&M1-4 不可读: %s\n", im.im_note.c_str());
How do I get the number of bytes?
The length is taken as the true length of the server's I / Q; the effective length = the true length (when known it is the boundary; the Q write boundary is the same), and when the true length is unknown (0), fall back to the capacity limit, do not extrapolate from the zone capacity. The length fields are taken from GET /api/io: inputLength = the true length of the Q area (device → controller), outputLength = the true length of the I area (controller → device), the field names are opposite to the I / Q direction; do not take them by name. The length is determined by the value negotiated with the PLC (IO controller) and is matched automatically after connection, do not hard-code 20 / 32. On the C++ side there is no separate "get the length" function; the length is simply the .size() of the bytes returned.
| What you want | Where to get it |
|---|---|
| I Data Length | device.Read().size() / device.ProcessData().Inputs().size() / GetIo().second.size() |
| Q Data Length | device.ProcessData().Outputs().size() / ReadArea(PnSServiceArea::Output).size() / GetIo().first.size() |
| Mapping Available Length | i_payload(&n, image_len) / q_payload(&n, image_len) Output parameter n = Valid length (if the true length is known, it is used as the boundary; if unknown, the upper capacity limit is returned) |
| The true length of both directions | is the .size() of the two lines above. The input_area_length / output_area_length of GetDiag() are the zone lengths, not the true length or the write boundary |
Two common pitfalls:
- The effective length is determined by the grip.: Length = True length (if known, this is the boundary); if the true length is unknown, return the capacity limit. Capacity limitIt's not that the data is really long — Don’t confuse the district’s capacity or the “district chief” with the data chief.
sizeof(T)The upper limit is based on the valid long-term card: UseRead().size()/ the mapped parameter*nas the upper limit. If exceeded, an exception will be thrown"结构体大于输入过程映像".
Life Cycle and Failure
The valid windows for mappings and references are tied to the device lifecycle; failure scenarios are as follows:
| entry point | Signature | Failure Patterns |
|---|---|---|
Start() | bool Start() | Do not discard. Returns on failure false; the reason is in device.LastServiceError()(instance) and static LastError() / LastErrorCode(). Returns idempotently Stop when has Start and has not true. The process data channel is only available whenThis machine's host(empty / 127.0.0.1 / localhost / ::1) is established; PnSService(host, port) when the backup link attempts to connect to another host without a local process data channel, it will fail at "过程数据未就绪, 无法启用 IO". |
Stop() | void Stop() | Do not discard. best-effort: The results are not reported; in case of failure, write LastServiceError() / static LastError()(+ LastErrorCode()), and the startup ST reverts to "not started." Destructor / Close() / All destructors ScopedStart use this. |
StopChecked() | void StopChecked() | Can throw. Follow the Stop() same deactivation process as above, but replaceThis call to selfThe results are reported accurately (without relying on "sticky" string for inference; even when the string is identical in both cases, the results are reported correctly): Failure PnSException(code() = the failure code for this attempt), and the startup STKeep RUN(As is: Disabling not confirmed); calling it again will trigger a true retry. The destructor path is disabled. |
Close() | void Close() | Do not discard. If it is still RUN, proceed first; Stop() clear all Q and I entries from the service; then unmap and release the real-time link. After that, all mapping references become invalid. |
| Destructor | ~PnSService() | Equivalent to Close(). |
- Mappings must be retrieved after the operation succeeds
Start();Stop()refreshing is paused—the view still exists, but the values read are outdated;Close()they become invalid afterward. IsRunning()Check whether "Start" has succeeded and "Stop" has not yet occurred;IO check whether the controller is actually in cyclic switching modeConnected()(or static modeServiceConnected())—the two are not the same thing.- The criteria for ST query failures vary:
Status()/ Throw an exception as-isStatusEx()when the service is unreachable;PnSException``WaitReason()Never Give Up — Use the static version when not connectedServiceWaitReason(); if connected but the request fails, fall back to the previous fault message.Connected()Do not throw an exception when not connected (use the static versionServiceConnected()); if connected but the service is unreachable,StatusEx()throw an exception accordingly.
Complete Example
#include "pns.hpp"
#include "pns_sugar.hpp"
#include <cstdio>
#include <iostream>
#include <vector>
using namespace darra::pns;
#pragma pack(push, 1)
struct FromPlc { // I: Controller → Device (Read-Only)
uint8_t Present; // Offset 0
int16_t Recipe; // Offset 1: Big-endian
};
struct ToPlc { // Q: Devices → Controllers (writable)
uint8_t Ready; // Offset 0
uint8_t Busy; // Offset 1
};
#pragma pack(pop)
int main() {
PnSService device; // Non-bus-connected configuration
ScopedStart guard(device); // Enter scope: Start; Exit scope: Stop
if (!guard.ok()) { // Do not throw an exception: Check if it has been called using ok()
std::cerr << device.LastServiceError() << "\n";
return 1;
}
// ① Structure mapping: A one-time mapping; after that, reading and writing members is equivalent to reading and writing the current process data.
const FromPlc& inp = device.ProcessData().InputsMapping<FromPlc>();
ToPlc& outp = device.ProcessData().OutputsMapping<ToPlc>();
outp.Ready = 1; // Note: To be sent in the next cycle
// ② Element Port (Copy Slice, One-Time Value Retrieval)
int16_t recipe = device.ProcessData().In()[1].AsInt16(); // Big-Endian → Host Order
uint8_t present = inp.Present; // Current cycle value
// ③ Read and write by address (area + byte + bit)
bool done = device.ReadBool("I0.0"); // Read I, byte 0 bit0
device.WriteInt16("QW2", recipe); // Write 2 bytes starting at offset 2 from Q
// Snapshot of the entire segment (copy): You must read the entire segment at once to ensure it’s all captured in a single shot.
std::vector<uint8_t> allI = device.Read();
std::vector<uint8_t> allQ = device.ProcessData().Outputs(); // To read Q, use Outputs()
std::printf("present=%u recipe=%d done=%d I=%zu Q=%zu\n",
(unsigned)present, (int)recipe, (int)done, allI.size(), allQ.size());
// Negotiation length in both directions (not hard-coded to 20/32; automatically matched after link)
std::printf("配置长度 I=%zu Q=%zu\n", allI.size(), allQ.size());
return 0; // guard destructor: Stop (no exception thrown)
}