Process Data
By svc.process_data reading and writing process data: inputs_mapping / outputs_mapping mapping the entire I/Q to a structure ctypes , In[i] / Out[i] and read from and write to this read_bool("I0.0") structure as a single port.
Process data refers to the bytes automatically exchanged between the controller and the device every cycle: write Q (device → controller) and read I (controller → device).The most convenient approach is to mapping this sequence of bytes to a struct ctypes all at once; thereafter, reading or writing fields is equivalent to reading or writing the current process data—no copying or flushing is required, and what is read is always the data from the current cycle, while what is written is transmitted in the next cycle.
Zone I is read-only; all write operations to Zone I are rejected: writing to an address (write_bool / write_int16 / write_int32 / write_area) throws PnSServiceError(NOT_AVAILABLE), and assigning a value to an element (In[i] = v) throws RuntimeError. Writing is only allowed in Zone Q; assigning a value to a field takes effect immediately, No commit calls.
In addition to the mapping, there are three single-value entry points, all copies: fetch by offset (pd.In[i] / pd.Out[i]), fetch by address ("I0.0" / "IW2" / "QD4"), and fetch the whole segment (svc.read()). The advantage is that you don't need to build a structure first; the cost is that every fetch copies out that small segment of bytes and interprets it as big-endian.
Cycle switching occurs automatically;SDK there are no user-defined cycle callbacks, and you are responsible for determining the scheduling (loop, timer, or thread).
Once you write the Q value, the controller will read the value you entered. Q is the device output, and the direction is from the device to the controller. Changes take effect immediately and are automatically sent in the next cycle; there is no need to call any commit functions.
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.
The device is a fixed single module (Slot 1 / subslot 1); this is this SDK's process data input point. There is no place that accepts slot or subslot parameters.
- Must
_pack_ = 1: Process data is an in-line byte stream; it must not contain alignment padding. Any value other than 1 is immediately discardedTypeError; misalignment will not be silently tolerated. - Use the length specified in the report SDK ; do not specify a fixed offset.: Data Length = Effective Length =
min(映像真长, 可用数据长度)(HMI screen length =GET /api/io/inputLengthoutputLength, field names are opposite to the I/Q direction—do not rely on the names; if unknown, fall back to the maximum available value), do not extrapolate beyond the zone capacity. - The criterion is based solely on the number of "available" bytes SDK reported.(If the mapping fails,
ValueErrorit will display "Required / Available"), so don't hard-code the offset yourself. - Multi-byte values are network big-endian: fields use
ctypes.BigEndianStructure. A plainctypes.Structuredecodes in native little-endian, so the values come out reversed, and it raises no error. - The life cycle is real, but a stable starting point is not.: The mapping remains valid for the duration of the channel;
stop()the mapping persists afterward (you can still read the old values, but they are no longer updated);close()after that, the struct becomes invalid—do not use it anymore. Don't treat the starting point of a mapping as a cached constant., and remap it once after the channel has been rebuilt. - Q-zone mapping has a single owner: reads are concurrent, Note: The caller must perform serialization on their own..
- I is read-only: Do not assign values to the I field; use Q to write data.
In[i] / Out[i]) is a copy, not a viewpd.In[0].content / pd.Out[2].as_int16 Each time a value is retrieved, that small segment of bytes is copiedExtractFollowing the big-endian explanation, the same principle applies to writing. [i] Only the offset is specified; the value remains a snapshot of that exact moment—it is not a "live view retrieved via an index," nor does it reuse cached objects.Therefore, retrieving several values in succession In[i] does not capture the same instant—to ensure you’re getting the same instant, retrieve all values at once (svc.read() / pd.inputs / retrieve an entire segment in one read_area go). To obtain a structure that continuously tracks the current value, use inputs_mapping / outputs_mapping.
Use Cases
Everyday Use
① mapping to a class (for ongoing use): start() After mapping it once, the structure instance obtained continuously tracks the current process data; subsequently, when the variable is used—assigning a value is a write operation, and retrieving a value is a read operation—there is no need to update it again write().
import ctypes
from darra_pns import PnSService
svc = PnSService() # Adjustable at any time
svc.start() # Start the Service + Establish a Process Data Channel
class FromPlc(ctypes.BigEndianStructure): # I: Controller → Device (read-only)
_pack_ = 1
_fields_ = [("present", ctypes.c_uint8),
("recipe", ctypes.c_int16), # big-endian
("part_no", ctypes.c_char * 16)] # Fixed-length byte field; read up NUL to the first one
class ToPlc(ctypes.BigEndianStructure): # Q: Devices → Controllers (writable)
_pack_ = 1
_fields_ = [("ready", ctypes.c_uint8),
("busy", ctypes.c_uint8)]
inp = svc.process_data.inputs_mapping(FromPlc) # Map once
outp = svc.process_data.outputs_mapping(ToPlc)
outp.ready = 1 # Note: To be sent in the next cycle
present = inp.present # Read: Always the current cycle
part_no = inp.part_no.decode()
② Retrieving elements using subscripts (without creating a structure): In[i] / Retrieves an element Out[i] based on a byte offset; each member of the element is a fixed-width read/write port. Each time a value is retrieved, a new copy is made from the current HMI screen.
present = svc.process_data.In[0].content # I 1 byte with an offset of 0
recipe = svc.process_data.In[1].as_int16 # I: Offset 1, 2 bytes starting from there, big-endian
flag = svc.process_data.In[4].get_bit(2) # I, offset by 4 from that byte's bit2
svc.process_data.Out[0].content = 0x11 # Q: Write 1 byte at offset 0
svc.process_data.Out[2].as_int16 = 123 # Q: Offset 2, starting at 2 bytes, big-endian
svc.process_data.Out[4].set_bit(0, True) # Change only that bit; leave the remaining bits in the same byte unchanged.
③ Pick up by address (enter the address exactly as it appears in the engineering software): Region letter + byte offset + bit; you don't need to calculate the bytes yourself.
done = svc.read_bool("I0.0") # position
recipe = svc.read_int16("IW2") # word (2 bytes, big-endian)
counter = svc.read_int32("ID4") # double word (4 bytes, big-endian)
svc.write_bool("Q0.0", True)
svc.write_int16("QW2", 123)
svc.write_int32("QD4", 10000)
Cyclical Changes
You only need to retrieve the mapping once. Place the same mapping into your own loop (or a callback within the loop) and use it directly:
import time
inp = svc.process_data.inputs_mapping(FromPlc)
outp = svc.process_data.outputs_mapping(ToPlc)
while running: # At your own pace, for example 10 ms
outp.ready = 1 if inp.present else 0 # Read the current beat → Calculate → Write down the beat and play it
outp.busy = inp.recipe
time.sleep(0.01)
What is read within a cycle is always from the current cycle, and what is written is sent in the next cycle—no additional calls are required. Mappings remain valid across cycles; there’s no need to remap with every beat—butDon'tThink of the mapping as a promise that the "offset will never change": After channel reconstruction (reopening start() after close() a interrupt), the mapping must be re-established.
Process DataNo change callback: SDK Does not provide user-defined periodic callbacks; svc.events only runtime-style events can be subscribed to.IO Quality: On the first read, IOPS only the baseline is recorded, and no callback is triggered; inputIopsHex if outputIopsHex both conditions are missing, no data is fabricated and no callback is triggered; a callback is triggered only when the count of non-GOOD bytes changes. A callback is not triggered on every read. You determine the scheduling (loop / timer / thread) yourself.
allThrows as is, it will not be silently downgraded.
Structure Mapping
Both entry points are located svc.process_data at ; the returned struct instance continuously tracks the current process data—assignment is a write, and retrieval is a read, so no additional padding is required write(). Mapping starts from the 0th byte of the data: to overwrite the middle section, place a placeholder array (("_skip", ctypes.c_uint8 * k)) at the beginning of the structure to push it up; if you only want to retrieve a segment of bytes based on an offset, use directly svc.read_area(). The field offsets are calculated by _pack_ = 1 itself (there is a item.offset available at the element port).
inputs_mapping()
mapping Zone I (controller → device) to a struct ctypes instance and return it—reading the fields retrieves the process data for the current cycle.
def inputs_mapping(self, struct_type)
Parameters:
struct_type(ctypes.StructureSubclass)—Must beClassItself (also throws when passing an instanceTypeError); must_pack_ = 1
Return value:
- Structure Instance — Continuously tracks the current input variable (VAR_INPUT); it is not a snapshot. It includes a property
_live_ownerthat ensures the mapping remains valid even when only the structure is held.
Note:
-
Call this function
start()afterward. In the following situations, an fault will always be reported, and no intermediate result will be returned:Situation Exception News Highlights struct_typeNot a subclassctypes.Structure(including instances passed as arguments)TypeErrorTip: Use read_structto take a snapshot_pack_No. 1TypeError结构体必须 _pack_ = 1 (无对齐填充)The structure size is 0 or greater than 65536 ValueError结构体大小非法: NThe structure is larger than the currently available window. ValueError结构体大于输入过程映像: 需要 N, 可用 MThe data pointer is null RuntimeError过程数据输入映像不可用: 数据指针为空 (0x0)Session not established (none start())PnSServiceErrorCode NOT_INITIALIZED,本机服务会话未建立Channel not ready / No HMI screen in this direction PnSServiceErrorcode NOT_AVAILABLE,过程数据未就绪, 无法映射 IOor过程数据输入映像不可用 -
Use the length returned by the interface; do not hard-code an offset.: Data length = effective length =
min(映像真长, 可用数据长度)(if the actual length of the HMI screen is unknown, return the maximum available length). It is recommended to mapping the data once for long-term use; remap it once after channel reconstruction. For absolute alignment, use the entire segment and calculate the offset yourselfsvc.read(). -
Structures must start at byte 0 of the data (the same starting point as
pd.In[0]/svc.read()[0]). To map to a middle section, add a placeholder at the head of the structure:("_skip", ctypes.c_uint8 * k). -
For multi-byte fields, use
ctypes.BigEndianStructure(PROFINET big-endian).ctypes.c_char * NTruncate NUL when the first is encountered; Writing a shorter string will not clear the old bytes at the end of the field., if you want to make it clear, you have to write the entire paragraph as a supplementb"..."NUL. -
I is read-only: Do not assign values to the I field; use Q to write data.
-
Read access is allowed;
close()after that, this structure is no longer valid—do not use it anymore.
Example:
import ctypes
class FromPlc(ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = [("present", ctypes.c_uint8),
("recipe", ctypes.c_int16),
("part_no", ctypes.c_char * 16)]
inp = svc.process_data.inputs_mapping(FromPlc) # mapping Once, Use Forever
print(inp.present, inp.recipe, inp.part_no.decode())
outputs_mapping()
mapping the Q zone (Device → Controller) to a struct ctypes instance and return it—assigning values to the fields writes Q, which is transmitted in the next cycle.
def outputs_mapping(self, struct_type)
Parameters:
struct_type(ctypes.StructureSubclass)—Same as aboveinputs_mapping; must be a class and_pack_ = 1
Return value:
- Structure Example — Continuously tracks the current output variable (VAR_OUTPUT); readable and writable; also includes
_live_owner
Note:
- Failure patterns correspond
inputs_mappingone-to-one with the success patterns, differing only in direction: the literals in the message are replaced with "output" (结构体大于输出过程映像: 需要 N, 可用 M/过程数据输出映像不可用: 数据指针为空 (0x…)). - The writable length is determined by the interface's return value: data length = effective length =
min(映像真长, 可用数据长度); if the actual length of the HMI screen is unknown, the maximum available length is returned. - Writing a field takes effect immediately: no need to call
svc.write()again, andsvc.output_committedis not changed either (that is the marker for the whole segment). - Use only one method to write to the same Q: Do not mix mapping writes with writes from the /
svc.write()configuration tool. - Write is single-owner: reads are concurrent; the caller must serialize writes.
Example:
import ctypes
class ToPlc(ctypes.BigEndianStructure):
_pack_ = 1
_fields_ = [("ready", ctypes.c_uint8),
("busy", ctypes.c_uint8)]
outp = svc.process_data.outputs_mapping(ToPlc) # mapping Once, Use Forever
outp.ready = 1 # Changing a field modifies the process image; it will be issued in the next cycle.
print(outp.busy) # Read the current output image
Direct Access (Works Even Without Mapping)
Mapping the following type to a structureMutually independent: You can use them directly without creating a mapping, but they are often used in conjunction with mappings (they are used to resolve fields that don't fit within a struct). This entire family consists ofCopy.
svc.process_data.In / inn / Out
Three properties retrieve two arrays from the same object ProcessData — In / inn is a read-only array I, Out and is a writable array Q. It does not move data itself; it only provides indices.
@property
def In(self) -> ProcessDataArray # I (Controller → Device): Read-only
@property
def inn(self) -> ProcessDataArray # Aliases for `in`; the same array instance
@property
def Out(self) -> ProcessDataArray # Q (Device → Controller): Writable
Return value:
ProcessDataArray— An array object containing process data; elements are accessed by index (see next item);Initinnis the same instance as (pd.inn is pd.Inis true)
Note:
InIt is a valid identifier, so it serves as the primary name;innit is an alias used for the "all-lowercase style," and its semantics are exactly the sameInas .- Operations on arrays will
lengthSuppress the exception and return 0, Don't treat 0 as a criterion for "there is truly no data." - I and Q are two separate objects;
Inyou cannot write to them,Outand the value read from them is the local shadow value that was most recently written.
Example:
pd = svc.process_data
print(pd.In.length, pd.Out.length) # Number of data bytes in both directions; returns 0 if unavailable
print(pd.inn is pd.In) # True: The same array
Related Structures:
class ProcessDataArray: # svc.process_data.In / inn / Out
length # int, read-only property: The number of data bytes in this direction; silently returns 0 if the value cannot be retrieved.
def __len__() # ≡ length
def __getitem__(offset) # → ; ProcessDataItem offset must be an int and not less than 0
def __setitem__(offset, value) # Out only: Equivalent to Out[offset].content = value
class ProcessDataItem: # svc.process_data.In[i] / Out[i]
offset # int, read-only property: The byte offset of this item
content # int, read/write property: 1-byte value (0..255); 0xFF truncated on the write side
Content # Aliases for "content" (C# name mapping)
as_int8 / as_uint8 # int, read/write property: 1 byte, signed / unsigned (uint8 same value as `content`)
as_int16 / as_uint16 # int, read/write attributes: 2 bytes, big-endian
as_int32 / as_uint32 # int, read/write attributes: 4 bytes, big-endian
as_int64 / as_uint64 # int, read/write attributes: 8 bytes, big-endian
as_float # float, read/write property: 4 bytes, big-endian IEEE754
as_double # float, read/write property: 8 bytes, big-endian IEEE754
as_bool # bool, read/write property:bit0 Semantics; Write True = 0x01, False = 0x00(integer byte)
def get_bit(bit) # → bool: The bit (0–7, where 0 is the least significant bit) of the byte at the offset specified by this entry.
def set_bit(bit, value) # Out Only: Modifies only the target bit; leaves the remaining bits in the same byte unchanged
def __int__() / __index__() # int(item) ≡ item.content; hex(item) can also be used directly
def __eq__(other) # item is greater than or equal to content; item is never equal to True or False
pd.In[i] / pd.Out[i]
Retrieve an element by byte offset — read In[i] into I (where the offset starts at the 0th byte of the data), Out[i] and read/write to Q. Each retrieval is a snapshot.
def __getitem__(self, offset) -> ProcessDataItem
def __setitem__(self, offset, value) # Out only: Equivalent to Out[offset].content = value
Parameters:
offset(int) — Byte offset, starting from the 0th byte of the data; does not need to be 2- or 4-byte aligned, nor does it need to fall on a field boundaryvalue(int) — For internalOut[i] = vuse only; written as 1 byte (contentrounding,0xFFtruncation)
Return value:
ProcessDataItem— Element View;[i]it only tracks offsets, Do not read or write bytes
Note:
- Returns every
[i]timeNew Object, no caching, no reuse; the offset can be any non-negative integer. Out-of-bounds values are not reported at the time of retrieval, but are reported according to the criteria below when the actual read or write occurs. offsetNotint→TypeError.offsetLess than 0 →ValueError(偏移不能为负: N).In[i] = v(I side assignment) →RuntimeError(ProcessData.In 只读 I (控制器→设备); 写请用 ProcessData.Out[i].content).Out[i] = vwrites the whole byte into the Q image (it does not modify bits); when the channel is not ready it throwsPnSServiceError(NOT_AVAILABLE).- Offset Out of BoundsException types are classified by directionThis is intentional: reading a single byte from "I" goes through the service indexer, and out-of-bounds access is
PnSServiceError(INVALID_PARAM,地址越界: 偏移 N 超出过程映像区 M 字节); reading a single byte from "Q" and out-of-bounds access for multi-byte reads in both directions areValueError(读过程数据越界: offset=N 超出 Q 区 M 字节/读过程数据失败 offset=N len=L 区长=M); write out-of-bounds access isPnSServiceError(INVALID_PARAM). - Multibyte writing isEither write it all or don't write it at all: First, check the "offset + width" against the valid length (
min(映像真长, 可用数据长度)). If it goes out of bounds, throw an exceptionPnSServiceError(INVALID_PARAM) before any bytes are written—none of the bytes at the end of the valid length will be modified. When a multi-byte value straddles the end of the valid length, the result isThe entire passage, without omission, not "half-written."
Example:
pd = svc.process_data
present = pd.In[0].content # I 1 byte with an offset of 0
recipe = pd.In[1].as_int16 # I Offset 1, starting with 2 bytes (big-endian)
pd.Out[0].content = 0x11 # Q: Write 1 byte at offset 0
pd.Out[2] = 0x22 # Equivalent to pd.Out[2].content = 0x22
for i in range(pd.Out.length): # Iterate through the entire output image
pd.Out[i].content = 0
item.offset
The byte offset recorded by this element view. Read-only, for accounting purposes only.
@property
def offset(self) -> int
Return value:
int— The byte offset of this element (counting from byte 0 of the data)
Note:
- Retrieving a value does not access the process image and will not fail—even if the offset is out of bounds,
offsetit will still return the number to you. - When using it for your own address arithmetic, don't forget that the process image isbig-endian.
Example:
item = svc.process_data.In[3]
print(item.offset) # 3
item.content / item.Content
1-byte original value (0..255). In[i].content Read I, Out[i].content read/write Q —— Copy.
@property
def content(self) -> int
@content.setter
def content(self, value)
Content = content # Synonyms
Parameters:
value(int, write-only) — Writes only the lower 8 bits (truncated to ,0xFFno exception thrown for out-of-range values)
Return value:
int— The value of that byte (0–255)
Note:
- Write-only
Out:In[i].content = vThrows an exceptionRuntimeError(I-side read-only) before any byte is written. - Writing a value is not
int→TypeError. - Reading Beyond the Boundaries: I side throw
PnSServiceError(INVALID_PARAM,地址越界: 偏移 N 超出过程映像区 M 字节); Q side throwValueError(读过程数据越界: offset=N 超出 Q 区 M 字节). - Write "out of bounds" →
PnSServiceError(INVALID_PARAM,地址越界: 偏移 N 超出过程映像区 M 字节). - Channel not ready: Type of read exceptionClassified by direction as well —— On the I side, a throw occurs
PnSServiceError(when the session has not been establishedNOT_INITIALIZED, or when the session exists but the channel is not readyNOT_AVAILABLE); on the Q side, the shadow is read—the shadow is empty when the session has not been established, and the previous entry is thrownValueError(notPnSServiceError). Write and throwPnSServiceError(NOT_AVAILABLE,过程数据未就绪, 无法提交 IO). Content"与" and "content是" are the same property (externally, they are aliases with the same name used for the target language).- One retrieval = one new current byte. When retrieving two members consecutively from the same element, a bus cycle may have elapsed between the two operations.
Example:
svc.process_data.Out[0].content = 0x11 # Write Q
print(svc.process_data.Out[0].Content) # Alias, reads back 0x11 (the Q side can read back the local shadow)
print(svc.process_data.In[0].content) # Read I: This is the byte sent by the controller; it is not the value just written.
item.as_int8 / as_uint8
Reads or writes the 1-byte element at the specified offset as a signed or unsigned value. as_uint8 content Equivalent to reading or writing the same value to the same byte. Copy.
@property
def as_int8(self) -> int
@as_int8.setter
def as_int8(self, value: int)
@property
def as_uint8(self) -> int
@as_uint8.setter
def as_uint8(self, value: int)
Parameters:
value(int, write-only) — Truncate to 1 byte (0xFF)
Return value:
int— The range is −128 to 127 for signed values; 0 to 255 for unsigned values.
Note:
- Signed reading: If a byte is greater than 127, subtract 256 (
0xFF→ −1). - The two write-side entry points follow the same rule: first
& 0xFF, then write the byte.-1and255write the same byte. - The failure pattern matches
contentexactly: I profile;RuntimeErrorout-of-bounds read on I isPnSServiceError, out-of-bounds read on Q is ;ValueErrorout-of-bounds write is ;PnSServiceErrorvalueintis notTypeError. - No alignment is required, nor is it tied to the element's width—the byte is simply retrieved from the specified offset.
Example:
svc.process_data.Out[3].as_int8 = -1 # Write 0xFF
print(svc.process_data.Out[3].as_uint8) # 255: The same byte—try looking at it as unsigned
print(svc.process_data.Out[3].as_int8) # -1
item.as_int16 / as_uint16
2 bytes, big-endian(PROFINET online sequence). In[i] Read I, Out[i] read/write Q. Copy.
@property
def as_int16(self) -> int
@as_int16.setter
def as_int16(self, value: int)
@property
def as_uint16(self) -> int
@as_uint16.setter
def as_uint16(self, value: int)
Parameters:
value(int, write-only) — Truncated to 16 bits and packed as unsigned
Return value:
int— Signed range: −32768..32767 (0xFFFE→ −2); unsigned range: 0..65535
Note:
- Write-to-Side, No-Discard Overflow: First, take the modulo based on the byte width (
& 0xFFFF), then output the bytes; for out-of-range values, use two's complement to determine the lower byte.as_int16 = -2Thisas_int16 = 0xFFFEoutputs the same pair of bytes as . - Writing a value is not
int→TypeError. - Out-of-range reading (offset + 2 exceeds the available data length for this direction) →
ValueError(读过程数据失败 offset=N len=2 区长=M), the I and Q directions have the same bandwidth. - I out-of-bounds access →
RuntimeError; Q out-of-bounds access →PnSServiceError(INVALID_PARAM); channel not ready →PnSServiceError(NOT_AVAILABLE). - Big-endian is a strict convention:
as_int16it is not affected by the host machine's byte order and does not allow reordering at the call site.
Example:
svc.process_data.Out[2].as_int16 = 123
svc.process_data.Out[4].as_int16 = -2 # Fall FF FE
print(svc.process_data.Out[2].as_int16) # 123
print(svc.process_data.Out[4].as_uint16) # 65534
item.as_int32 / as_uint32
4 bytes, big-endian. In[i] Read I, Out[i] read and write Q. Copy.
@property
def as_int32(self) -> int
@as_int32.setter
def as_int32(self, value: int)
@property
def as_uint32(self) -> int
@as_uint32.setter
def as_uint32(self, value: int)
Parameters:
value(int, write-only) — Truncate to 32 bits (& 0xFFFFFFFF)
Return value:
int— Signed range: −2147483648..2147483647; unsigned range: 0..4294967295
Note:
- The truncation threshold is the same
as_int16as : For out-of-range values, silently take the least significant bit according to two's complement and do not generate an fault. - Out-of-Bounds Read →
ValueError(读过程数据失败 offset=N len=4 区长=M). - Other failure conditions include
as_int16(I: profileRuntimeError, write out of boundsPnSServiceError, non-integerTypeError, channel not readyPnSServiceError). - 4-byte alignment is not required:
In[1].as_int32Reading 4 bytes starting at offset 1 is valid.
Example:
svc.process_data.Out[4].as_int32 = 10000
print(svc.process_data.In[1].as_int32) # Read I: 4 bytes starting at offset 1; valid, big-endian
print(svc.process_data.Out[4].as_int32) # Read Q: 10000 just written in
item.as_int64 / as_uint64
8 bytes, big-endian. In[i] Read I, Out[i] read and write Q. Copy.
@property
def as_int64(self) -> int
@as_int64.setter
def as_int64(self, value: int)
@property
def as_uint64(self) -> int
@as_uint64.setter
def as_uint64(self, value: int)
Parameters:
value(int, write-only) — Truncate to 64 bits (& 0xFFFFFFFFFFFFFFFF)
Return value:
int— For signed numbers, this is the two's complement representation; for unsigned numbers, it is 0..18446744073709551615
Note:
- 64-bit values are ordinary
intin Python and do not overflow into floating point. - Out-of-Bounds Read →
ValueError(读过程数据失败 offset=N len=8 区长=M). - The other failure patterns are the same as
as_int16. - An 8-byte value requires an 8-byte window: In most sample configurations, I is 32 bytes and Q is 20 bytes, which fits in both directions, but don’t place it at the very end of the offset.
Example:
svc.process_data.Out[8].as_uint64 = 0x1122334455667788
print(hex(svc.process_data.Out[8].as_uint64)) # 0x1122334455667788
print(svc.process_data.In[8].as_uint64) # Read I: The one sent by the controller; it has nothing to do with the above.
item.as_float / as_double
4 bytes / 8 bytes, Big-Endian IEEE 754, Binary values are input and output as-is, without any digital conversion. Copy.
@property
def as_float(self) -> float
@as_float.setter
def as_float(self, value)
@property
def as_double(self) -> float
@as_double.setter
def as_double(self, value)
Parameters:
value(int or float, write-only) — Accepts integers, which are treated as digital conversions (1writing to this fieldas_floatis equivalent to1.0); does not accept objects of thisstrtype
Return value:
float— the value decoded from big-endian IEEE 754
Note:
- Bit-by-bit copy: Writing
NaN/infwill not be blocked, and the value read back will be the exact same bit-by-bit copy — SDK no value range checks are performed, and no nearest-even rounding is applied. - Out-of-bounds read →
ValueError(读过程数据失败 offset=N len=4 区长=M;as_doubleyeslen=8). - The other failure patterns are the same
as_int16. as_floatis 4 bytes andas_doubleis 8 bytes — do not guess from the names that "because double is 8 bytes, float must be 8 bytes too".
Example:
svc.process_data.Out[4].as_float = 1.5
print(svc.process_data.Out[4].as_float) # 1.5
svc.process_data.Out[8].as_double = -0.125
print(svc.process_data.Out[8].as_double) # -0.125
item.as_bool
Whole-byte Boolean, bit0 Semantics — It is true only if the least significant bit is 1. In[i] Read I; Out[i] read and write Q. Copy.
@property
def as_bool(self) -> bool
@as_bool.setter
def as_bool(self, value)
Parameters:
value(Boolean value, write only) — True write0x01, False write0x00
Return value:
bool— Is the least significant bit of the byte 1?
Note:
- Reading: bytes
0x02and0x80are both judgedFalse,0x01is judgedTrue. To judge true/false by whole-byte 0 / not 0, readcontentand compare it yourself — there is no second "any non-zero is true" opening. - Write isWhole ByteWrite: Writing
Truewill set the byte to0x01, and clear bits 1–7 of that byte; to read or write on a per-bit basis, useget_bit()/set_bit(). - The failure pattern
contentmatches (I profileRuntimeError; out-of-bounds read I isPnSServiceError, out-of-bounds read Q is ;ValueErrorwrite out-of-boundsPnSServiceError).
Example:
svc.process_data.Out[1].as_bool = True
print(svc.process_data.Out[1].as_bool) # True: Consider only the least significant bit
print(svc.process_data.Out[1].content) # 1: The entire byte was written as 0x01, bit1–bit7 and was cleared out along with it
item.get_bit() / item.set_bit()
Read/write bit bit of that one byte at the offset of this element. get_bit works in both directions; set_bit only for Out. Copy.
def get_bit(self, bit) -> bool
def set_bit(self, bit, value) -> None
Parameters:
bit(int) — Bit number 0–7;0this is the least significant bit (LSB)value(Boolean value, onlyset_bit)— New value for the target bit
Return value:
bool— Is this bit currently set to 1(get_bit)?None—set_bitNo return value
Note:
- Bitwise OperationsByte-addressed, independent of element width: Regardless of whether you intend to interpret this element as 1, 2, 4, or 8 bytes wide,
bitit always points to the element's offset atThat one byte, and will not extend into adjacent bytes. - Index not in the range 0–7 →
ValueError(位号必须在 0-7 之间: N). set_bitTo I side →RuntimeError(I side read-only).get_bitCross-boundary readings: I sidePnSServiceError, Q sideValueError(contentsame caliber as );set_bitcross-boundary →PnSServiceError.- Channel not ready →
PnSServiceError(NOT_AVAILABLE).
Example:
svc.process_data.Out[0].set_bit(0, True) # The byte at offset 0 bit0
svc.process_data.Out[0].set_bit(7, False) # Within the same byte bit7
ready = svc.process_data.In[4].get_bit(2) # Offset by 4 bytes from that byte bit2
Comparison of int(item) and item
Element views can be used directly as integers — both int(item) and hex(item) take that byte from it. Copy.
def __int__(self) -> int
def __index__(self) -> int
def __eq__(self, other) -> bool
Return value:
int— Equivalentitem.contentto
Note:
item == 5comparescontent;itemandTrue/Falseare never equal (booleans are deliberately not compared as integers, so thatitem == Truedoes not quietly hold for bits other than bit0).- When comparing two element views, the comparison is based on "offset + direction," not the byte value of that particular cell.
- The exception thrown when a value is out of bounds is the same
contentas .
Example:
item = svc.process_data.In[0]
print(int(item), hex(item), item == 0x12) # content / Hexadecimal / Comparison with Integers
Read/Write by Address (Region + Byte + Bit)
Use this group when 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.
| How to Write an Address | What is it? | Read/Write Port of SDK This |
|---|---|---|
I0.0 / Q0.0 | Bit address: Bit 0 of byte 0; the bit number must be between 0 and 7. | read_bool / write_bool |
IB0 / QB0 | Byte (the type indicator may be omitted after the region: I0 synonymous IB0 with ) | Use svc[offset] Read I, svc[offset] = v Write Q |
IW2 / QW2 | Word: 2 bytes, big-endian | read_int16 / write_int16 |
ID4 / QD4 | Double word: 4 bytes, big-endian | read_int32 / write_int32 |
- Do not enforce 2/4 alignment:
IW3/ID2Both are valid; "offset" refers to a byte offset. - Does not support the M zone / DB zone →
PnSServiceError(INVALID_PARAM,不支持 M 地址: M0/不支持 DB 地址: DB1), do not guess or mapping. - Case-insensitive (
i0.0/ is equivalentq5.7); leading and trailing spaces are stripped. - The data read back from Zone Q isLocal shadow values(The one you entered recently), Zone I reads the current value sent by the controller.
- Always throw an exception for failures
PnSServiceError; see the specific code below for each member — don’t just look at the fault code;INVALID_PARAMthere are several different types of invalid inputs hidden underneath.
PnSService.parse_address()
Only parses the address string, splitting I0.0 / IB0 / IW2 / ID4 / Q… into a structured region + offset + bit + width. It does not touch the process image or move any data.
@staticmethod
def parse_address(address: str) -> PnSServiceAddress
Parameters:
address(str) — Address string, such as"I0.0"/"IB0"/"IW2"/"QD4"
Return value:
PnSServiceAddress— The deconstructed address structure; upon successslot/subslotare always 1
Note:
-
Use this if you want to validate the address yourself or convert the address to a byte offset. Just because the analysis is successful doesn't mean it will definitely work. — Out-of-bounds errors are reported only when actual read/write operations occur.
-
All parsing failures
PnSServiceError(codeINVALID_PARAM), trigger conditions and copy:Input Copy Empty string / All spaces 地址不能为空M0/MB0不支持 M 地址: M0DB1/DBA不支持 DB 地址: DB1The first letter is not I / Q / M / D (e.g., X0)不支持的地址区域: X0The address is missing an offset or a position number ( I.0/I0.)地址格式非法 (位地址应为 I0.0 形式): I0.Position number greater than 7 ( I0.8)位号必须在 0-7 之间: I0.8Missing Offset ( I/IW)地址缺少偏移量: IThe offset is not an unsigned decimal number ( IA0/IB-1)字节偏移非法: IA0Offset greater than 65535 ( IW65536)字节偏移超出范围: IW65536 -
lengthWidth: bit address = 1 (spans 1 byte),B/ untyped character = 1,W= 2,D= 4;bita value of −1 indicates non-bit addressing. -
addressNotstr→TypeError.
Example:
a = svc.parse_address("IW3") # Does not enforce 2-byte alignment
print(a.area, a.byte_offset, a.length, a.bit) # 1 3 2 -1
Related Structures:
class PnSServiceAddress: # parse_address() Return value (dataclass)
area # int:PnSServiceArea Possible values (see the [entry svc.read_area() ] for the enumeration definition)
slot # int: Constant 1 (fixed in Zone I/Q;DB the ID belongs to Zone DB , which is not SDK supported here)
subslot # int: Heng 1
byte_offset # int: Byte offset, relative to the start of this region
bit # int: bit number 0–7; -1 = non-bit addressing
length # int: Data width (bits = 1-byte span, B / untyped character = 1, W = 2, D = 4)
read_bool() / write_bool()
Reading and Writing a Bit — read_bool("I0.0") Read I, write_bool("Q0.0", True) Write Q. Writing isRead, Modify, and Write by the Byte, move only the target position. Copy(Retrieves one current byte per call.)
def read_bool(self, address: str) -> bool
def write_bool(self, address: str, value: bool) -> PnSErr
Parameters:
address(str) — Must include a position number, such as"I0.0"/"Q5.7"value(Boolean, write-only) — New value for the target bit
Return value:
bool— whether this bit is currently 1 (read_bool; Q reads the local shadow value most recently written).PnSErr— Success CodePnSErr.OK, And it returns "OK" only if that byte has already been loaded into the process image.(write_bool)
Note:
- Addresses without unit numbers (e.g.,
"IB0") →PnSServiceError(INVALID_PARAM,位地址必须带位号: IB0). - The address itself is invalid →
PnSServiceError(INVALID_PARAM; see theparse_address()table for the wording). - Out of bounds →
PnSServiceError(INVALID_PARAM,地址越界: 偏移 N + 长度 M 超出过程映像区 K 字节). - Write to side I →
PnSServiceError(NOT_AVAILABLE,I 区 (控制器 -> 设备) 只读, 不支持写); do not silently discard. - Session not established →
PnSServiceError(NOT_INITIALIZED,本机服务会话未建立); Channel not ready →PnSServiceError(NOT_AVAILABLE,过程数据未就绪, 无法读写 IOor过程数据未就绪, 无法提交 IO). - A bit write involves reading a single byte, modifying a specific bit, and then writing the entire byte back—so the other bits in that same byte aren’t cleared in the process.
- Only bit numbers 0–7 are supported; there is no such thing as "bit numbers 8 and above spanning multiple bytes."
Example:
if svc.read_bool("I0.0"):
svc.write_bool("Q0.0", True)
else:
svc.write_bool("Q0.0", False)
read_int16() / write_int16()
Read or write a word (2 bytes, big-endian). Copy.
def read_int16(self, address: str) -> int
def write_int16(self, address: str, value: int) -> PnSErr
Parameters:
address(str) — Must beWwidth and non-bit-addressed; for example,"IW2"/"QW2"(IW3such unaligned addresses are valid)value(int, write-only) — Truncated to 16 bits and stored in big-endian byte order (out-of-range values are silently set to the lowest bit; no exception is thrown)
Return value:
int— SignedValue (interpreted as two's complement when the most significant bit is 1:0xFFFE→ −2). To make it unsigned, you must& 0xFFFFPnSErr— Success codePnSErr.OK; returned only if those 2 bytes have been loaded into the process image (write_int16)
Note:
- The address width is incorrect (
"IB0", or an address"I0.0"like this) →PnSServiceError(INVALID_PARAM,字地址必须为 2 字节且非位寻址: IB0). - Out of bounds →
PnSServiceError(INVALID_PARAM,地址越界: 偏移 N + 长度 M 超出过程映像区 K 字节). - Write I side →
PnSServiceError(NOT_AVAILABLE,I 区 (控制器 -> 设备) 只读, 不支持写). - The same applies to other failures (session not established
NOT_INITIALIZED, channel not readyNOT_AVAILABLE)read_bool(). - The value returned is the host integer decoded big-endian; you don't need to do it yourself
struct.unpack.
Example:
recipe = svc.read_int16("IW2") # Signed, big-endian
svc.write_int16("QW2", -2) # Fall FF FE
print(svc.read_int16("QW2")) # -2 (Read back the local shadow)
read_int32() / write_int32()
Read or write a double word (4 bytes, big-endian). Copy.
def read_int32(self, address: str) -> int
def write_int32(self, address: str, value: int) -> PnSErr
Parameters:
address(str) — Must beDwidth and non-bit-addressed; for example,"ID4"/"QD4"(ID2such unaligned addresses are valid)value(int, write-only) — Truncated to 32 bits, then packed in big-endian byte order
Return value:
int— SignedValue (0xFFFFFFFE→ −2). To be unsigned, you must& 0xFFFFFFFFPnSErr— Success codePnSErr.OK; returned only when the 4 bytes have been loaded into the process image (write_int32)
Note:
- The address width is incorrect →
PnSServiceError(INVALID_PARAM,双字地址必须为 4 字节且非位寻址: IB0). - Out of bounds →
PnSServiceError(INVALID_PARAM,地址越界: 偏移 N + 长度 M 超出过程映像区 K 字节). - Write I side →
PnSServiceError(NOT_AVAILABLE,I 区 (控制器 -> 设备) 只读, 不支持写). - The rest of the failures are the same
read_int16(). - Unsigned versions are not available: There is no such option
read_uint32; to obtain an unsigned version, you must perform a bitwise AND operation yourself.
Example:
counter = svc.read_int32("ID4")
svc.write_int32("QD4", 10000)
print(svc.read_int32("QD4")) # 10000 (the value read back is the local shadow)
print(svc.read_int32("ID4") & 0xFFFFFFFF) # Unbiased View
Entire Zone Entry (Entire Segment / Short Form / Snapshot Structure)
This section covers the "no mapping" approach: whole-byte segments, segments with region offsets, and snapshot structures. They're all copies.
svc.read()
Read the controller → the device's entire process data (Zone I), retrieving one set per call. Copy(A new sample is drawn each time; the same batch is consistent within itself.)
def read(self) -> bytes
Return value:
bytes— Current contents of Zone I data; length = valid length =min(映像真长, 可用数据长度)(actual HMI screen length unknown, fallback to available upper limit)
Note:
- One call = one snapshot: If you need to use multiple fields together, retrieve all the bytes in a single call—don’t split it into multiple calls.
- If the channel doesn't form, sell immediately.
- Session not established (not
start()) →PnSServiceError(NOT_INITIALIZED,本机服务会话未建立). - Channel not ready →
PnSServiceError(NOT_AVAILABLE,过程数据未就绪, 无法读写 IO).
Example:
frame = svc.read() # A Snapshot of I
present, recipe = frame[0], int.from_bytes(frame[1:3], "big")
print(len(frame), present, recipe)
pd.inputs / pd.Inputs
A snapshot of Zone I, originating svc.read() from , is mounted svc.process_data on . Copy.
@property
def inputs(self) -> bytes
@property
def Inputs(self) -> bytes # Alias, same value
Return value:
bytes— Current data for Zone I; a new set is retrieved with each visit
Note:
- It matches byte-for-byte
svc.read(), except for the starting position (svc.process_data.inputs). - Failure patterns are the same as
svc.read():NOT_INITIALIZED/NOT_AVAILABLE. InputsThese are synonyms of the same name in the reference language. Note the direction: **inputsIn Python, this corresponds to Zone I (controller → device)**Don't get thrown off by those two reversed property names on the server side.
Example:
print(svc.process_data.inputs == svc.read()) # True
svc.write()
Write device → controller full-process data (Q area); short writes are allowed. Copy(Pass the input bytes into the procedure's HMI screen.)
def write(self, data: bytes) -> None
Parameters:
data(bytes) — Bytes to be written; overwrite starting at offset 0, The short version covers only the first N bytes., leave the rest as is
Return value:
- No return value — A successful return indicates that these bytes have been written to the procedure HMI screen; a failure always results in an exception being thrown
PnSServiceError, in which case none of the bytes are written. To obtain a return code, use thewrite_bool/write_int16/write_areafamily of commands (which return on successPnSErr.OK).
Note:
- Extra-longThrows as is, no silent truncation (a delivery is not considered successful if the truncated portion is not delivered).
- Empty data →
PnSServiceError(INVALID_PARAM,写数据不能为空). - Out of bounds / Too long →
PnSServiceError(INVALID_PARAM,地址越界: 偏移 N + 长度 M 超出过程映像区 K 字节). - Session not established →
PnSServiceError(NOT_INITIALIZED); Channel not ready →PnSServiceError(NOT_AVAILABLE,过程数据未就绪, 无法读写 IOor过程数据未就绪, 无法提交 IO, in which case no bytes have been committed). - Once written, it
svc.output_committedis true (unless a new failed sector occurs at the moment of reading). - There is no concept of a "submit call" here—each submission is
write()done on the spot.
Example:
svc.write(b"\x11\x22\x33\x44") # Write 4 bytes starting at offset 0
print(svc.output_committed) # True: Process image has been saved
pd.outputs / pd.Outputs
Shadow readback of the current content in Q; assigns a value to a property equal to the entire segment / short form. Copy.
@property
def outputs(self) -> bytes
@outputs.setter
def outputs(self, value)
@property
def Outputs(self) -> bytes # Aliases, same value; assignments are also forwarded
Parameters:
value(bytes / bytearray / memoryview, write-only) — bytes to be written; the short form overwrites only the first N bytes
Return value:
bytes— Current content in Q; an empty byte string if no content is available
Note:
- This reads the "version you wrote" (read back exactly what was written). If there is no dialogue, return
b"", Do not discard. - Note: Assignment is not part of the bytes family →
TypeError(outputs 必须为 bytes); null →ValueError(写入不能为空); greater than 65536 →ValueError(写入超过过程映像上限: N). - Throw
PnSServiceError(NOT_AVAILABLE/NOT_INITIALIZED) when the rung to create the process image fails. - To write multiple items at onceNon-adjacentFor the range: either merge it into a single segment and write it again, or call it once for each segment—each call constitutes a separate commit.
Example:
svc.process_data.outputs = b"\x01\x00" # Short description: Overwrite the first 2 bytes starting at offset 0
print(svc.process_data.outputs[:2]) # b'\x01\x00'
pd.copy_inputs_to() / pd.copy_to_outputs()
Copy the snapshot from Zone I into the caller's buffer / Write the caller's buffer to Zone Q, and return the actual number of bytes. Copy(In both directions).
def copy_inputs_to(self, buf) -> int
def copy_to_outputs(self, src) -> int
Parameters:
buf(bytearray / memoryview, onlycopy_inputs_to)— target buffer; pressthe shorter sideCopysrc(bytes / bytearray / memoryview, onlycopy_to_outputs)— source bytes; shorthand allowed
Return value:
int— Actual number of bytes copied/written (copy_inputs_toYesmin(I 长度, len(buf));copy_to_outputsYeslen(src))
Note:
- If the buffer is too small, no fault will be reported; it will simply copy less data—the return value serves as the criterion.
bufAcceptbytearray/memoryview(bytesDo not accept);srcAcceptbytes/bytearray/memoryview. Type mismatch →TypeError.copy_to_outputs: Over 65536 →ValueError(写入超过过程映像上限: N); an empty bytes value will throwPnSServiceError(INVALID_PARAM,写数据不能为空) when it reaches the process image stage.- Submission failed (channel not ready / session not established) →
PnSServiceError. - These two ports correspond to fixed directions:
copy_inputs_toread I,copy_to_outputswrite Q; there is no version where the directions are reversed.
Example:
buf = bytearray(4)
n = svc.process_data.copy_inputs_to(buf) # Read from I into my own buffer
n = svc.process_data.copy_to_outputs(b"\x01\x02") # Type "Q" and return 2
svc.read_area() / svc.write_area()
Reads or writes a contiguous shielding of bytes based on a regional offset; one call is made for each read and one for each write. Copy.
def read_area(self, area, offset, length) -> bytes
def write_area(self, area, offset, data) -> PnSErr
Parameters:
area(int) — Region:PnSServiceArea.INPUT(1) or.OUTPUT(2)offset(int) — Byte offset, relative to the start of the regionlength(int) — Number of bytes to read (onlyread_area)data(bytes) — Data to be written (not empty, onlywrite_area)
Return value:
bytes— The segment extracted based on offset / length (read_area)PnSErr— Success codePnSErr.OK; returned only when the bytes in this segment have already been loaded into the process image (write_area)
Note:
read_area: Region not I / Q →PnSServiceError(INVALID_PARAM,区域非法: 3);offset/lengthis negative →INVALID_PARAM(offset / length 不能为负); Out of bounds →INVALID_PARAM(区域越界: 偏移 N + 长度 M 超出过程映像区 K 字节); Session not established →NOT_INITIALIZED.write_area: Write to Zone I →PnSServiceError(NOT_AVAILABLE,I 区 (控制器 -> 设备) 只读, 不支持写); Invalid zone →INVALID_PARAM(区域非法: 3); Empty data →INVALID_PARAM(写数据不能为空);offsetNegative value →INVALID_PARAM(offset 不能为负); Out of bounds →INVALID_PARAM(区域越界: 偏移 N + 长度 M 超出过程映像区 K 字节).- Write only once per callA continuous segmentbytes; non-contiguous segments represent multiple calls (each of which is a separate commit).
dataIt must bebytes(Passbytearray/ Domemoryviewnot accept either).
Example:
from darra_pns import PnSServiceArea
part = svc.read_area(PnSServiceArea.INPUT, 4, 2) # Read 2 bytes starting at offset 4 in Section I
rc = svc.write_area(PnSServiceArea.OUTPUT, 4, b"\x11") # Write 1 byte starting at offset 4 from Q, and commit immediately
Related Structures:
class PnSServiceArea(IntEnum): # Range enumeration (IntEnumwhere the values can be used as `int`s)
UNKNOWN = 0 # Unknown
INPUT = 1 # Zone I: Read-only (Controller → Device)
OUTPUT = 2 # Section Q: Write only (device → controller)
MEMORY = 3 # Zone M: Used only for "not supported" reports (resolution failed, no mapping)
DB = 4 # DB Zone: Used only for "not supported" reports (resolution failed, no mapping)
svc.get_io()
A single call retrieves both the Q shadow and the I snapshot simultaneously. Copy (Returns two byte strings.)
def get_io(self) -> Tuple[bytes, bytes]
Return value:
(Q 影子, I 快照)— The order is Q first, followed by I.(read_output()First,read_input()Then)
Note:
- Use it when you want "both directions in one beat"; it costs one fewer decision than adjusting
svc.input/svc.outputseparately. - Session not established →
PnSServiceError(NOT_INITIALIZED); Channel not ready →PnSServiceError(NOT_AVAILABLE,过程数据未就绪, 无法读写 IO). - For everyday reading and writing, please use
svc.read()/svc.write()/ ;svc.process_datathis method is primarily intended for callers that need to access "two directions at once."
Example:
q_shadow, i_snapshot = svc.get_io() # Note the order: Q comes first
print(len(q_shadow), len(i_snapshot))
svc[offset] / svc[offset] = value
Read one byte from I and write one byte to Q, using a byte offset. Copy.
def __getitem__(self, offset) -> int
def __setitem__(self, offset, value) -> None
Parameters:
offset(int) — Byte offset, starting from the 0th byte of the datavalue(int, write-only) — Writes only the lower 8 bits
Return value:
int— This byte (0..255,svc[offset])None— An assignment has no return value, soUnable to determine the result code; To determine the return value, usewrite_int16a type like this
Note:
offsetNotint→TypeError.offsetNegative →PnSServiceError(INVALID_PARAM,偏移不能为负: N).- Read out of bounds →
PnSServiceError(INVALID_PARAM,地址越界: 偏移 N 超出过程映像区 M 字节); Write out of bounds →PnSServiceError(INVALID_PARAM,地址越界: 偏移 N 超出过程映像区 M 字节). - Writing a value is not
int→PnSServiceError(INVALID_PARAM,字节值必须为 int). - Before writing, check the channel first: not ready →
PnSServiceError(NOT_AVAILABLE,过程数据未就绪, 无法提交 IO); session not established →NOT_INITIALIZED. - The indexer and
In[i]/Out[i]read and write the same set of bytes; in everyday use just useIn[i]/Out[i].
Example:
b = svc[0] # Read I, offset 0
svc[0] = 0x11 # Write Q with offset 0 (submit immediately)
read_struct() / write_struct()
No mapping is built and no ctypes structure is used — a struct format string reads / writes a whole segment at once; fmt is always interpreted as big-endian. Copy (snapshot).
def read_struct(self, fmt=None) # Alias: svc.process_data.read_struct
def write_struct(self, fmt, *values) # Alias: svc.process_data.write_struct
# svc.read_struct(fmt) / svc.write_struct(fmt, *values) is a forwarding call from the same implementation
Parameters:
fmt— three forms:None/""(returns the whole segment as bytes),int(returns the first n bytes),str(structformat string, big-endian unpacking)values(Write only) — Use the value specified in the packagefmt; you can also pass only onebyteswhen the entire data segment
Return value:
bytesortuple—fmtempty for the entire segment;bytesfor a solvedstrtuple (read_struct)None—write_structNo return value; success indicates that the transaction has been committed
Note:
- Endianness is forced to big-endian: any
@/=/</>/!in the format string is stripped and replaced with>, so"<Hi"and"Hi"give the same result. Don't expect writing<to switch to native little-endian. fmtIf the string is empty → return the entire string;bytesif a negative number is passed →ValueError(读长度不能为负).fmtis not a valid format string →struct.error(e.g.bad char in struct format); wrong number of arguments →struct.error(e.g.pack expected 2 items for packing (got 1)).- a value outside that format's value range →
struct.error(e.g.'H' format requires 0 <= number <= 65535); this path does not truncate by bit width, unlike theOut[i].as_int16family (that family silently takes the low bits when out of range). - Invalid structure size (not less than 0, or greater than 65536) →
ValueError(结构体大小非法: N). - Zone I is insufficient →
ValueError(I 区不足: 需要 N 字节, 实际 M); Writing beyond the upper limit →ValueError(结构体超过过程映像上限: N); Writing a null value →ValueError(写入不能为空). - Session not established →
PnSServiceError(NOT_INITIALIZED); Channel not ready →PnSServiceError(NOT_AVAILABLE). - This road isSnapshot: Read and resolve once; the value won't change as the bus updates. To continuously track the current value, use
inputs_mapping/outputs_mapping.
Example:
present, recipe = svc.read_struct("BH") # Decode the first 3 bytes of the big-endian data
head = svc.read_struct(8) # First 8 bytes
svc.write_struct("BH", 1, 2) # Pack big-endian and write to Q (values must be within the format's value range)
svc.write_struct(b"\x11\x22") # Write the entire data segment to Q
svc.input / svc.output / output_committed
Three service-level attributes — input is the readback of the Q shadow, output is the snapshot of the I zone, output_committed is the criterion for whether "the Q of this session has already been loaded into the process image". The first two are copies.
@property
def input(self) -> bytes # Q Shadow Readback (Device → Controller)
@property
def output(self) -> bytes # Zone I Snapshot (Controller → Devices)
@property
def output_committed(self) -> bool
Return value:
bytes—input: The read response from Q that you sent;output: The I snapshot sent by the controller. When there is no session, it always returnsb"", Do not discardbool—output_committed: This session has successfully written Q into the process image, AndThere are currently no unsaved local writes.
Note:
- These three are service-level attributes and are not included
process_datain : usesvc.read()/ for read/write Isvc.process_data.inputs, and usesvc.write()/ for read/write Qsvc.process_data.outputs. output_committedNot unconditionally true: Q has never been written, or the submission failed—both areFalse.stop()Do not reset this flag (the session and HMI screen content remain);close()reset.
Example:
svc.write(b"\x01\x02")
print(svc.output_committed) # True
print(svc.input[:2]) # b'\x01\x02': Q Shadow Re-read
svc.input it's Q, svc.output it's IThe names of those two properties on the server side are the same as those in that process_data setThe opposite —— svc.input The "Q" (device → controller) is what you send out, svc.output and the "I" (controller → device) is what you receive from the controller.
For everyday reading, writing, and navigation svc.read() / svc.write() / svc.process_data.In / Out this set is all you need; if you need to use svc.input / svc.output take a quick look here first. Another example following the same principle is get_io(): it returns in the order of (Q 影子, I 快照) .
Record Index Space (Non-Periodic Data)
Non-periodic data trendsRecord Index, The index numbers are divided into segments. This document SDK only makes two of those segments available; the two routes do not overlap:
| Index Section | What is it? | Where SDK Am I Going? |
|---|---|---|
0x0000 – 0x7FFF | User/Manufacturer Section: Application parameter records written by the controller and stored on the device side | svc.get_records() / svc.records |
0x8000 Start | Standard Index Section (Expected Actual Identifiers, Diagnoses, Substitute Values, etc.) | This does SDK not provide a general-purpose record read port. |
0xAFF0 – 0xAFF4 | I&M Identification: I&M0(0xAFF0) and I&M1–4(0xAFF1–0xAFF4) | svc.get_im_data() / svc.im_data |
svc.get_records() / svc.records
TakeUser AreaA snapshot of the record (index 0x0000–0x7FFF). The device saves the record written by the controller andSDK reads it back to you. Read-Only Observation.
def get_records(self) -> PnSServiceRecords
@property
def records(self) -> PnSServiceRecords # Same Implementation
Return value:
PnSServiceRecords— dataclass:records(PnSServiceUserRecordarray, each entry containsslot/subslot/index/length/data_hex),count,timestamp. If there are no records, it is an empty array +count = 0, Not a failure
Note:
- Use the service management interface (not the process data channel), and there is no requirement to do so first
start(). - Service Unavailable →
PnSServiceError(NO_DEVICE, as stated in the original string无法连接服务 127.0.0.1:18840 (…)). - Service-side fault / Response cannot be parsed →
NOT_AVAILABLE(as in the original string, such as服务返回 HTTP N: …,服务响应不是合法 JSON: …). - Missing fields are treated as 0 or empty;
recordsthey are not fabricated. If the field is not a array, it is treated as an empty array. - I&M isn't in this port: Only the section in the user area is included here;
0xAFF0the identifier that marks it will never be visible. - There is no entry point for "writing SDK records to the controller"—records are written by the controller, stored on the device side,SDK and read.
- Writing a record does not alter the cycle HMI screen, nor does reading a record—it has absolutely nothing to do with process data.
Example:
recs = svc.get_records()
print(recs.count, recs.timestamp)
for r in recs.records:
print(f"index=0x{r.index:04X} slot={r.slot} subslot={r.subslot} len={r.length} data={r.data_hex}")
svc.get_im_data() / svc.im_data
Take an observation snapshot of the device with the identifier I&M — Index 0xAFF0—0xAFF4.
def get_im_data(self) -> PnSServiceImData
@property
def im_data(self) -> PnSServiceImData # Same Implementation
Return value:
PnSServiceImData— dataclass:vendor_id/device_id,order_id/serial_number/hardware_revision/software_revision,station_name/product_name,im_supported/im14_supported,im_note,im1_tag_function/im1_tag_location/im2_date/im3_descriptor/im4_signature_hex,project_order_number/project_hardware_release/project_software_release
Note:
- Use the service management interface (not the process data channel); likewise, no prior action is required
start(). - Failure patterns are the same
get_records()as: service unreachableNO_DEVICE, service-side fault, or unparseable responseNOT_AVAILABLE. im14_supportedThe " " symbol indicatesFalsethat I&M1–4 was not brought back this time (the field is an empty string); it does not mean "unable to do so." For items such as order numbers, serial numbers, and software/hardware versions that are not integrated into the native stack,im_notethis will be clearly stated as such.- I want to view I&M records myself by index number → NoneThis port; I&M data is output only through this port, and the user log port never sees the segment
0xAFF0.
Example:
im = svc.im_data
print(f"vendor=0x{im.vendor_id:04X} device=0x{im.device_id:04X} station={im.station_name}")
print(im.im_supported, im.im14_supported)
print(im.im_note)
How do I get the number of bytes?
Use the actual length from the server (GET /api/io inputLength / outputLength, field names are reversed in the I/Q direction—do not use the names to determine the length); valid length = min(映像长, 可用数据长度); mapping length unknown (0) returns the maximum available value; Do not extrapolate based on district capacity. Determined by the value negotiated by the PLC (IO controller); automatically matches after link, Don't be too rigid 20 / 32.
| What you want | Where to get it |
|---|---|
| I Data Length (Effective Length) | len(svc.read()) / len(svc.process_data.inputs) / svc.process_data.In.length |
| Q Data Length (Effective Length) | len(svc.process_data.outputs) / svc.process_data.Out.length |
| The images in both directions are really long. | svc.diag_snapshot.input_area_length / .output_area_length |
The data lengths for mapping and read/write operations are bothEffective Length = min(映像真长, 可用数据长度): If the HMI screen is too long, use the input_area_length / above output_area_length; if unknown, return the available upper limit. If the mapping fails, ValueError will display "Need N / Available M."
In.length / Return 0 silently Out.length on failureIf the channel hasn't been established start(), return length 0, Do not throw exceptions. So 0 could mean either "actually 0 bytes" or "unreadable"—for information on how to determine which is the case, see svc.connected / svc.diag_snapshot.ok.