Process Data
Process data consists of two segments, I and Q, which are automatically transmitted and received every cycle—you don't need to send them manually.
Structure MappingInterpret the entire data segment as a structure #[repr(C, packed)] ; reading and writing fields means reading and writing the current process data itself. What is read is always from the current cycle, and what is written is transmitted in the next cycle—use this to read and write the same set of fields in each cycle.
Typed Read/Write by Offset / By ItemEach time it's called, it returns a small segment to you; use it to read and write specific values here and there.
Write Q (device → controller), read I (controller → device). The I region is read-only, and the controller overwrites the entire region every cycle. The cycle proceeds automatically;SDK there are no user-defined cycle callbacks—you determine the scheduling yourself.
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 two names are two perspectives: GSDML names things from the Controller side, while the SDK names things from the device side; they refer to the same direction.
The equipment isFixed Single Module: Slot 1, Sub-slot 1.SDK There are no input parameters for the slot or sub-slot—nor is there a second module to select.
inputs_mapping::<T>()/outputs_mapping::<T>()With byte-levelinputs_slice()/outputs_slice()read and write operations, the data being accessed is the current process data itself; no copying or flushing is required.- The other entry points return a small segment to you with each call.
in_*/ A segment is copied with eachout_*call;in_item()/ Each read or write operation onout_item()the handle constitutes a round trip;read()/read_area()/read_struct()The return value is a snapshot. TMust be#[repr(C, packed)](aligned to 1). RuntimeCheck firstalign_of::<T>() == 1, and if it doesn't meet the standards, it's immediatelyServiceError::InvalidParam.- All multi-byte valuesbig-endian(PROFINET network sequence). This SDK does not perform any byte reversal.
- bool Unification bit0 Meaning:
0x01Yes;true``0x02/ All0x80of themfalse. - Zone I is read-only. Writing to Zone I isReally
Err, the variant isServiceError::OutputReadOnly— not a panic, nor a silent discard. - Mappings and handles are both borrowed
PnSService. When they are presentclose()&mut self, they cannot be borrowed—this is a guarantee provided by the borrowing checker, not a runtime check.
Use Cases
Everyday Use
① Structure mapping (ongoing use): Once the structure is defined and mapped once, it can be used as a variable. unsafe It only appears during the mapping process.
use darra_pns::{PnSService, ServiceResult};
#[repr(C, packed)]
struct FromPlc { present: u8, recipe: i16 } // I: Controller → Device
#[repr(C, packed)]
struct ToPlc { ready: u8, busy: u8 } // Q: Devices → Controllers (I and Q are two separate structures)
fn main() -> ServiceResult<()> {
let device = PnSService::new(); // The structure is not connected to the bus and does not occupy a real-time connection.
device.start()?; // start: Process data channel just created
let pd = device.process_data();
let inp = unsafe { pd.inputs_mapping::<FromPlc>()? }; // &FromPlc: Map once, read-only
let outp = unsafe { pd.outputs_mapping::<ToPlc>()? }; // &mut ToPlc: writable
outp.ready = 1; // Write it down and send it out in the next cycle; no need to submit a call.
let present = inp.present; // The value read is always from the current cycle (the `packed` field is first copied to a local variable).
println!("{present}");
device.stop()
}
② Retrieve a value based on the offset (one-time): You don't want to define a struct, or you just want a block of bytes or a single value.
let pd = device.process_data();
let b: u8 = pd.in_u8(0)?; // 1 byte at offset 0 in Zone I
let recipe = pd.in_i16(2)?; // Zone I, Offset 2, Big-Endian Int16
pd.out_u16(4, 123)?; // Big-endian with a Q-zone offset of 4 UInt16
③ Retrieve an element by key (index-based access, one-time): Provide an index, get a handle, then select the width and interpret it.
let pd = device.process_data();
let ready = pd.in_item(6).as_bool()?; // 6th byte in Zone I,bit0 evaluated as true
let pos = pd.in_item(2).as_i32()?; // 4 bytes starting from the 2nd byte in Zone I, big-endian
pd.out_item(0).set_u16(0x000F)?; // 2 bytes starting at byte 0 in Q zone
pd.out_item(0).set_bit(0, true)?; // Set only this bit bit0; leave the remaining bits of the byte unchanged.
String fields are fixed-length bytes (padded with 0 at the end). Read the bytes in this segment all at once, then convert them &str.
let raw = device.read()?; // A snapshot of Zone I
let head = &raw[..raw.len().min(16)]; // Even if the zone is shorter than 16 bytes, it won't cause a panic.
let part_no = std::str::from_utf8(head).unwrap_or("").trim_end_matches('\0');
Cyclical Changes
Place the same map directly into your own loop (the map is retrieved only once outside the loop, and the values are automatically updated each iteration).
while running { // Your own recurring tasks—set your own schedule
let recipe = i16::from_be(inp.recipe); // Online Big-Endian Byte → Host Value; if not converted, it is an out-of-alignment value
outp.ready = (recipe as u8) + 1; // Read the current beat → Calculate → Write down the beat and play it
std::thread::sleep(std::time::Duration::from_millis(10));
}
You don't need to remap within the loop, nor should you.SDK There are no user-defined periodic callbacks—you determine the scheduling (loop, timer, or thread) yourself; events() these are runtime-based events.
Structure Mapping
To directly interpret the entire I/Q data segment according to the layout of T , T it must be #[repr(C, packed)]. Reading and writing fields means reading and writing the current process data itself; no copying or flushing is required.
Mapping starts from the 0th byte of the data in that direction; the available length is determined by what the interface returns on the spot—do not hard-code the offset yourself. To map fields in the middle of the data, place a placeholder array (_skip: [u8; k]) at the beginning of the structure to pad it out; or use read_area / byte_at / in_item to access data by offset instead.
You can also wrap it yourself: ProcessData::new(&device) , which is equivalent to device.process_data(), meaning the slave node is not started and no requests are sent.
inputs_mapping<T>()
Map Zone I (controller → device) to T, and returnRead-onlyQuote: "Map once, and the fields update automatically when the controller is updated—it's not a snapshot."
pub unsafe fn inputs_mapping<T>(&self) -> ServiceResult<&'a T>
Return value:
ServiceResult<&'a T>— A read-only reference to data in Zone I.'aItProcessDatasharesPnSServicethe same lifecycle as the service object, so the reference does not outlive the service object.
Note:
unsafeContract:TThe field order must match the production environment byte-for-byte.align_of::<T>() != 1(Missingpacked) →ServiceError::InvalidParam("结构体对齐不是 1:请用 #[repr(C, packed)]"). This provision was the first to be ruled on, even if the session hasn't been established or isn't active, this error is stillstart()reported.- The passage isn't finished yet →
ServiceError::SharedMemory("过程数据输入映像不可用"). size_of::<T>() == 0Or exceeds the available length in Zone I →ServiceError::InvalidParam("结构体大于输入过程映像").- Door sizes are determined based on the available length on site; do not assume that “it worked last time” is a guarantee.
- If you write it, it won't compile: the signature is
&T, not&mut T. Writing it will returnServiceError::OutputReadOnly, but this is blocked at the type level and caught at compile time. - The
packedfield cannot be used directly:println!("{}", inp.recipe)a compilation error will occur. Firstlet v = inp.recipe;copy it to a local variable, then use it. - Structures can only contain fixed-width fields (integers, floating-point numbers, etc.
[u8; N]).String/Vec/ References overlay pointers on top of procedure data, and alignment checks cannot prevent this type of error.
Example:
#[repr(C, packed)]
struct FromPlc { present: u8, recipe: i16, counter: u32 }
let pd = device.process_data();
let inp: &FromPlc = unsafe { pd.inputs_mapping::<FromPlc>()? };
let recipe = inp.recipe; // For ByteDance online applications, the host must i16 perform the conversion itself (see “Big-Endian Packaging/Unpacking”).
let present = inp.present;
outputs_mapping<T>()
Map Q (Device → Controller) to T, and return a writable reference. Modifying this field modifies Q, and the change takes effect in the next cycle.
pub unsafe fn outputs_mapping<T>(&self) -> ServiceResult<&'a mut T>
Return value:
ServiceResult<&'a mut T>— A writable reference to data in region Q
Note:
- Alignment, Dimensions,
unsafeand Contract are the sameinputs_mapping; only the error messages have been changed to Output side:ServiceError::InvalidParam("结构体大于输出过程映像")andServiceError::SharedMemory("过程数据输出映像不可用"). - An alias
&mutis undefined behavior.: At any given time, there can be only one writable reference (or one writable slice) to the same segment of Q data. Taking the same handle twice, or taking one with each of two handles, are both considered aliases. Use scope to serialize them. - Writing to a field does not require any "submit" call; it is automatically triggered in the next cycle.
- If a field doesn't fit in a structure, you can use the offset operator (
out_*/out_item) to adjust it; this modifies the same segment of Q data.
Example:
#[repr(C, packed)]
struct ToPlc { ready: u8, busy: u8 }
let pd = device.process_data();
let outp: &mut ToPlc = unsafe { pd.outputs_mapping::<ToPlc>()? };
outp.ready = 1; // To be sent in the next cycle
outp.busy = 0;
inputs_slice() / outputs_slice()
Retrieve the entire byte slice directly, without going through a structure.
pub unsafe fn inputs_slice(&self) -> ServiceResult<&'a [u8]> // I Entire data set, read-only
pub unsafe fn outputs_slice(&self) -> ServiceResult<&'a mut [u8]> // Q: The entire data set; can be written
Return value:
&'a [u8]/&'a mut [u8]— A slice of data pointing in that direction. Length = Effective Length = min(Data Length, Available Length)(Data length =GET /api/ioofinputLength/outputLength, field names are in the opposite direction of I/Q; do not rely on the names; use the available length when unknown)
Note:
- Same as
inputs_mapping/outputs_mappingreading and writing the same data, except that the data is represented as raw bytes. - This does not apply to alignment gates (there are none
T), but for dimension gates, when the available length is ≤ 0, replace it with →ServiceError::SharedMemory("过程数据输入映像不可用")/("过程数据输出映像不可用"). outputs_slice()outputs_mapping()Shares the same exclusive rule: Only one writable view can exist for the same Q data at any given time.unsafeYou really need to be careful: the pointer is only valid beforeDroptheunmap/ , andThe service will concurrently modify these bytes(This is especially true on the left side.)
Example:
let pd = device.process_data();
let frame: &[u8] = unsafe { pd.inputs_slice()? }; // Do not copy
let x_words = unsafe { pd.outputs_slice()? }; // Changing the bytes writes Q
if frame.len() >= 2 {
x_words[0] = frame[0].wrapping_add(1);
}
Mapping Length and Stability
The available length is determined by the value returned by the interface; do not hard-code any offsets or lengths. Valid length = min(数据长度, 可用长度)(Data length = GET /api/io of inputLength / outputLength, field names are in the opposite direction of I/Q; do not rely on the names; when unknown, use the available length; do not extrapolate beyond the block capacity).
That part about the life cycle is true.(End of borrowing / unmap / Expires after the channel is closed). Address stability is not — Do not make any assumptions about “constant addresses,” and do not cache pointers in locations that span multiple cycles.
"Retrieve the mapping once outside the loop" is still the recommended approach., but it saves one parse. The trade-off is that if the actual data length differs from what you expected, the reference you have will point to the wrong location—thisIt won't report it. Err. ..even size-of-the-door won't stop it (when the structure is small, it still "fits," but the value read will be misaligned).
Direct Access (Works Even Without Mapping)
The following set is independent of the structure mapping: it can be used on its own without mapping, and is often used in conjunction with mapping (it is used to resolve fields that do not fit within the structure).
Each time you call these entry points, they return a small segment to you.. in_* / Copy a small segment with each out_* call; for each item handle, a round trip is made for each read or write operation.
in_item(offset) / out_item(offset)
Take oneItem-based handle: Provide a byte index to obtain a handle, then use typed methods to read from and write to it.
pub fn in_item(&self, offset: usize) -> ProcessDataItem<'a> // Zone I: Read-only
pub fn out_item(&self, offset: usize) -> ProcessDataItem<'a> // Zone Q: Read/Write
Parameters:
offset(usize) — Byte offset relative to the start of this direction zone
Return value:
ProcessDataItem<'a>— Lightweight handle (Clone + Copy). It holds only three elements: "service + offset + direction," and does not store any data bytes.
Note:
- Does not return
Result: Creating a handle is a purely local operation—it does not read the bus, send requests, or require anythingstart(). It is each read or write call on the handle that actually establishes the session. - HandleNot a snapshot: Every read or write takes effect immediately. Between
content()two operations at the same offset, the value may have changed. - HandleDoes not hold a pointer: It does not assume responsibility for those
*_slicetwo lifecycle/pointer validity obligations, nor is itunsafe. To achieve "changes at the source, automatic field updates," use a struct mapping. - Offset out-of-bounds conditions are not reported when creating a handle; they are
OutOfRangereported during read/write operations (the upper limits vary depending on the width; see the next item). - Handle Checkout
PnSService: Youclose()cannot check out a handle while it is already checked out.
Related Structures:
pub struct ProcessDataItem<'a> { /* Service + Offset + Direction; no data bytes stored */ }
impl<'a> ProcessDataItem<'a> {
pub fn offset(&self) -> usize; // Byte offset for this item (relative to the start of the zone)
pub fn is_writable(&self) -> bool; // true = Section Q item (writable); false = Section I item (read-only)
}
impl<'a> ProcessDataItem<'a> {
// ── Read: Direction Determined by Handle (in_item Read Zone I,out_item Read Current Value of Zone Q) ──
pub fn content(&self) -> ServiceResult<u8>; // 1-byte original value, unsigned
pub fn as_i8(&self) -> ServiceResult<i8>; // 1 byte, signed
pub fn as_u8(&self) -> ServiceResult<u8>; // 1 byte, unsigned (same as content)
pub fn as_i16(&self) -> ServiceResult<i16>; // 2 bytes, signed, big-endian
pub fn as_u16(&self) -> ServiceResult<u16>; // 2 bytes, unsigned, big-endian
pub fn as_i32(&self) -> ServiceResult<i32>; // 4 bytes, signed, big-endian
pub fn as_u32(&self) -> ServiceResult<u32>; // 4 bytes, unsigned, big-endian
pub fn as_i64(&self) -> ServiceResult<i64>; // 8 bytes, signed, big-endian
pub fn as_u64(&self) -> ServiceResult<u64>; // 8 bytes, unsigned, big-endian
pub fn as_f32(&self) -> ServiceResult<f32>; // 4 bytesIEEE754, big-endian
pub fn as_f64(&self) -> ServiceResult<f64>; // 8 bytesIEEE754, big-endian
pub fn as_bool(&self) -> ServiceResult<bool>; // 1 bytebit0 , semantics
pub fn bit(&self, bit: u8) -> ServiceResult<bool>; // The bit at position bit in this byte (0 = LSB), if the bit number is greater than 7, a report is issued InvalidParam
}
impl<'a> ProcessDataItem<'a> {
// ── Note: Only out_item the handles for can be adjusted;in_item all handles for are ── OutputReadOnly
pub fn set_content(&self, value: u8) -> ServiceResult<()>;
pub fn set_i8(&self, value: i8) -> ServiceResult<()>; // 1 byte
pub fn set_u8(&self, value: u8) -> ServiceResult<()>; // 1 byte
pub fn set_i16(&self, value: i16) -> ServiceResult<()>; // 2 bytes, big-endian
pub fn set_u16(&self, value: u16) -> ServiceResult<()>; // 2 bytes, big-endian
pub fn set_i32(&self, value: i32) -> ServiceResult<()>; // 4 bytes, big-endian
pub fn set_u32(&self, value: u32) -> ServiceResult<()>; // 4 bytes, big-endian
pub fn set_i64(&self, value: i64) -> ServiceResult<()>; // 8 bytes, big-endian
pub fn set_u64(&self, value: u64) -> ServiceResult<()>; // 8 bytes, big-endian
pub fn set_f32(&self, value: f32) -> ServiceResult<()>; // 4 bytesIEEE754, big-endian
pub fn set_f64(&self, value: f64) -> ServiceResult<()>; // 8 bytesIEEE754, big-endian
pub fn set_bool(&self, value: bool) -> ServiceResult<()>;// 1 byte; write 1 for true / write 0 for false
pub fn set_bit(&self, bit: u8, value: bool) -> ServiceResult<()>; // Read-Modify-Write the bit at position bit of this byte (0 = LSB)
}
Example:
let pd = device.process_data();
let flag = pd.in_item(6).as_bool()?; // The 6th byte in Zone I,bit0
let raw = pd.in_item(6).content()?; // The original value of the same byte
let item = pd.out_item(2);
item.set_i16(123)?; // Q Zone, offset 2, starting at 2 bytes
item.set_bit(0, true)?; // Re-post bit0
content() / as_() / set_() (item-typed read/write operations)
Read or write using the specified width based on the handle's offset and direction. Read from Zone I or read the value currently to be sent from Zone Q; writing applies only to Zone Q entries.
pub fn content(&self) -> ServiceResult<u8>
pub fn as_i16(&self) -> ServiceResult<i16> // The rest as_* have the same form; see “Related Structures” above.
pub fn set_i16(&self, value: i16) -> ServiceResult<()>
Return value:
ServiceResult<u8>/ServiceResult<i16>/ … — Interpretation of the result for this width (big-endian)ServiceResult<()>—Ok⟺ Submission is effective immediately (submitted on the spot, with no delay)
Note:
- Byte Order: All multibyte valuesbig-endian(PROFINET network order).
as_f32/as_f64It is IEEE 754, also big-endian. - The maximum width varies depending on the direction (boundary = effective length =
min(数据长度, 可用长度); when the data length is unknown, use the available length):- For Zone I items, the reading width can be any length, as long as
offset + 宽度 ≤ 有效长. - The same applies to reads in Q-zone; writes are also limited to the valid length. If exceeded →
ServiceError::OutOfRange(offset, 宽度, 上限).
- For Zone I items, the reading width can be any length, as long as
- Calling any
set_*→ on a read-only itemServiceError::OutputReadOnly. This door is located before the session begins.: Evenstart()if not, just report it anyway. - No session established → ;
ServiceError::NotConnectedSession is active, not active →start()ServiceError::NotStarted. as_bool()Recognize only bit0:0x01Yestrue,0x02/0x80bothfalse. This SDK does not have a second entry for 「non-0 is true」 — you must judge based on whether the byte is 0 or not 0; compare it yourselfcontent().set_bool()It writes a whole byte0x01/0x00, not a bit.- Each
as_*/set_*represents a separate read/write session. The service may have updated its value between the two calls. — To synchronize, use onceread()/read_area()take a snapshot.
Example:
let pd = device.process_data();
let ready = pd.in_item(0).as_bool()?; // 0x02 / 0x80 All Read false
let as_byte = pd.in_item(0).content()?; // If you want to check for authenticity by reading entire bytes, read this.
pd.out_item(4).set_f32(1.5)?; // big-endian IEEE754
pd.out_item(0).set_bool(true)?; // Write the entire byte 1, not a single bit.
bit(bit) / set_bit(bit, value) (bit-addressable)
PresspositionRead or write the byte at the handle offset.
pub fn bit(&self, bit: u8) -> ServiceResult<bool>
pub fn set_bit(&self, bit: u8, value: bool) -> ServiceResult<()>
Parameters:
bit(u8) — Bit numbers 0–7, Bit0 = LSB; Position No. > 7ServiceError::InvalidParam(report this before accessing the gate in any session)value(bool) — Set / Clear
Return value:
ServiceResult<bool>— The current value of this bitServiceResult<()>— Set successfully (submitted immediately)
Note:
- A bit accessor isBy byteYes, not by width:
bitit only addresses the location at the handle offset. That one byte. ..regardless of what width you plan to use for this item. - The position number is
u8(0–7); runtime validation:bit > 7→ServiceError::InvalidParam. Position-based access takes precedence over any session access, it won't—and won'tstart()—proceed to the session. set_bit()Bit-level read-modify-write: Only the target bit is overwritten; the remaining bits in the same byte retain their original values.set_bit()The order of the two gates is: first theOutputReadOnly(read-only) gate, then the bit-number gate.set_bit()Internally, the same byte must be read back first (which requires one additional read operation compared to other write ports). That door in the "Read-Only" section is still at the very front.: So the items in Zone I are still reportedOutputReadOnly, while the items in Zone Q are reportedstart()only when there is noNotStarted.
Example:
let pd = device.process_data();
pd.out_item(0).set_bit(0, true)?; // Set only this bit bit0; leave the remaining bits of the byte unchanged.
pd.out_item(0).set_bit(7, false)?; // Only Clear bit7
let lsb = pd.in_item(3).bit(0)?; // Bit0 = LSB
in_i8() … in_f64() / in_bool() / in_bit() (read I by offset)
If you don't want to create a handle, read a value directly using an offset in a single step. Read from Zone I (controller → device), with the offset relative to the data start point.
pub fn in_i8(&self, offset: usize) -> ServiceResult<i8>
pub fn in_u8(&self, offset: usize) -> ServiceResult<u8>
pub fn in_i16(&self, offset: usize) -> ServiceResult<i16>
pub fn in_u16(&self, offset: usize) -> ServiceResult<u16>
pub fn in_i32(&self, offset: usize) -> ServiceResult<i32>
pub fn in_u32(&self, offset: usize) -> ServiceResult<u32>
pub fn in_i64(&self, offset: usize) -> ServiceResult<i64>
pub fn in_u64(&self, offset: usize) -> ServiceResult<u64>
pub fn in_f32(&self, offset: usize) -> ServiceResult<f32>
pub fn in_f64(&self, offset: usize) -> ServiceResult<f64>
pub fn in_bool(&self, offset: usize) -> ServiceResult<bool>
pub fn in_bit(&self, offset: usize, bit: u8) -> ServiceResult<bool>
Parameters:
offset(usize) — Byte offset in Zone I. Do not enforce 2/4 alignment, an offset is a byte offsetbit(u8) —in_bitbit numbers 0–7, Bit0 = LSB; > 7 indicates an errorInvalidParam
Return value:
- Values corresponding to the width (
i8/u8/i16/u16/i32/u32/i64/u64/f32/f64/bool)
Note:
- These are all copies, not views. Read a small segment each time you call the service, then interpret it in big-endian order. Rust doesn’t have live objects like
In[i]that—don’t mistake “offset parameters” for “getting a live view.” - multibytebig-endian;
in_f32/in_f64means read u32 / u64 in big-endian order, then callfrom_bits - The width is the number of bytes you want (
in_i16read 2 bytes,in_f64read 8 bytes); out-of-bounds access is handled according to the upper limit specified above. - Failure Patterns:
- No session established →
ServiceError::NotConnected - None
start()→ServiceError::NotStarted offset + 宽度Exceeds valid length →ServiceError::OutOfRange(offset, 宽度, 有效长), displayed as地址越界: 偏移 N + 长度 M 超出过程映像区 K 字节- Channel Unavailable →
ServiceError::SharedMemory("过程数据未就绪, 无法读 IO")
- No session established →
in_bitThe position number isu8(0–7); runtime validation:bit > 7→ServiceError::InvalidParam.in_boolas_bool()Same caliber as the one on the handle (bit0) /0x020x80Checkfalse. You need to check for true or false on a per-byte basis; compare them yourselfin_u8.
Example:
let pd = device.process_data();
let b = pd.in_u8(0)?; // 1 byte at offset 0 in Zone I
let iw = pd.in_i16(3)?; // Big-endian with an offset of 3 Int16 — 2-byte alignment is not required
let f = pd.in_f32(8)?; // Big-endian with an offset of 8 float32
let bit0 = pd.in_bit(0, 0)?; // Bit 0 of 0 bytes in Zone I
out_i8() … out_f64() / out_bool() / out_bit() (write Q by offset)
Write to Q area (Device → Controller). Ok ⟺ The byte has been written and takes effect immediately.
pub fn out_i8(&self, offset: usize, value: i8) -> ServiceResult<()>
pub fn out_u8(&self, offset: usize, value: u8) -> ServiceResult<()>
pub fn out_i16(&self, offset: usize, value: i16) -> ServiceResult<()>
pub fn out_u16(&self, offset: usize, value: u16) -> ServiceResult<()>
pub fn out_i32(&self, offset: usize, value: i32) -> ServiceResult<()>
pub fn out_u32(&self, offset: usize, value: u32) -> ServiceResult<()>
pub fn out_i64(&self, offset: usize, value: i64) -> ServiceResult<()>
pub fn out_u64(&self, offset: usize, value: u64) -> ServiceResult<()>
pub fn out_f32(&self, offset: usize, value: f32) -> ServiceResult<()>
pub fn out_f64(&self, offset: usize, value: f64) -> ServiceResult<()>
pub fn out_bool(&self, offset: usize, value: bool) -> ServiceResult<()>
pub fn out_bit(&self, offset: usize, bit: u8, value: bool) -> ServiceResult<()>
Parameters:
offset(usize) — Byte offset in the Q section (relative to the start of data in the Q section), Do not enforce 2/4 alignmentvalue— Value to be writtenbit(u8) —out_bitPosition numbers 0–7; > 7 reportsInvalidParam
Return value:
ServiceResult<()>—Ok⟺ Write operation is effective immediately (submitted on the spot, with no delay, and no "success response without submission")
Note:
- multibytebig-endianEncoding (
to_be_bytes), not little-endian. - The upper limit is based on the valid long card (
offset + 宽度 ≤ min(数据长度, 可用长度)or the available length if the data length is unknown). If exceeded →ServiceError::OutOfRange(offset, 宽度, 有效长). - Failure Patterns:
- No session established →
ServiceError::NotConnected - None
start()→ServiceError::NotStarted - Out of Bounds →
ServiceError::OutOfRange(…) - Channel Unavailable →
ServiceError::SharedMemory("过程数据未就绪, 无法写 IO")
- No session established →
out_bitYesRead, Edit, and Write in the Same Byte: First, read the byte back, modify the target bit, and then write the entire byte back. So, compared to other write operations, it involves one extra read, but it doesn't triggerstart()an error immediatelyNotStarted.out_bitThe position number isu8(0–7); runtime validation:bit > 7→ServiceError::InvalidParam.out_boolWrite a fixed number of standard bytes:truewrite1,falsewrite0. Not bits, nor 「an entire byte non-0.」- Each call constitutes a separate commit. Multiple non-contiguous changes result in multiple commits.
Example:
let pd = device.process_data();
pd.out_u8(0, 0x11)?; // 1 byte in Q zone with an offset of 0
pd.out_i16(3, 123)?; // Big-endian with an offset of 3 Int16
pd.out_bit(0, 0, true)?; // Set only the 0-byte Q zone to bit0
pd.out_bool(5, true)?; // Write a full byte of 1
read_struct<T>() / write_struct<T>(&T)
Snapshot path: First few bytes of Zone I → structure; structure → Zone Q, offset 0. One call encodes and decodes one copy.
PnSService There is a convenient method with the same name above, which is equivalent to device.process_data().read_struct() / .write_struct(). Snapshot pathNot required #[repr(C, packed)] — It follows its own declared pack/unpack process and does not perform any transmutation.
pub fn read_struct<T: ProcessDataPacked>(&self) -> ServiceResult<T>
pub fn write_struct<T: ProcessDataPacked>(&self, value: &T) -> ServiceResult<()>
Return value:
ServiceResult<T>— The extracted structure (a snapshot; the copied values do not change along with the service)ServiceResult<()>—Ok⟺ The encoded bytes have been written to Q
Note:
TTo achieveProcessDataPacked:pub trait ProcessDataPacked: Sized {
fn packed_size() -> usize;
fn unpack_from(buf: &[u8]) -> ServiceResult<Self>;
fn pack_into(&self, buf: &mut [u8]) -> ServiceResult<()>;
fn pack_to_vec(&self) -> ServiceResult<Vec<u8>>;
}- Write your own
unpack_from/pack_intoand you decide the byte order too. It is recommended to match the SDK convention and use big-endian; use theunpack_i16_be/pack_i16_befamily from the next section directly instead of writing a second byte order implementation. - Failure Patterns:
T::packed_size() == 0→ServiceError::InvalidParam("结构体紧排大小不能为 0")pack_into/ Insufficient bufferunpack_from→ServiceError::OutOfRange(0, 需要, 实得)read_struct: Notstart()→NotStarted;packed_size()Greater than the effective length →OutOfRangewrite_struct: Nonestart()→NotStarted; Length after encoding exceeds valid length →OutOfRange
read_struct"And" and "write_structAll"Effective Length =min(数据长度, 可用长度)Card (use available length when data length is unknown).- If you want to "change the source and let the fields update automatically," use
inputs_mapping/outputs_mapping— the snapshot path does not support this.
Example:
use darra_pns::{ServiceResult, ProcessDataPacked};
use darra_pns::service::process_data::{pack_i16_be, unpack_i16_be};
struct FromPlc { present: u8, recipe: i16 } // No need for `packed` or `repr(C)`
impl ProcessDataPacked for FromPlc {
fn packed_size() -> usize { 3 }
fn unpack_from(buf: &[u8]) -> ServiceResult<Self> {
Ok(Self { present: buf[0], recipe: unpack_i16_be(&buf[1..3])? })
}
fn pack_into(&self, buf: &mut [u8]) -> ServiceResult<()> {
buf[0] = self.present;
buf[1..3].copy_from_slice(&pack_i16_be(self.recipe));
Ok(())
}
}
let snap: FromPlc = device.read_struct()?; // A Snapshot
device.write_struct(&snap)?; // Write the entire segment to Q (starting at offset 0)
inputs() / write_outputs() / copy_inputs_to() / copy_to_outputs()
All the convenient access points for both directions are on ProcessData. Together with device.read() / device.write(), they are two names for the same thing.
pub fn inputs(&self) -> ServiceResult<Vec<u8>> // = device.read()
pub fn write_outputs(&self, data: &[u8]) -> ServiceResult<()> // = device.write(data)
pub fn copy_inputs_to(&self, dest: &mut [u8]) -> ServiceResult<usize>
pub fn copy_to_outputs(&self, src: &[u8]) -> ServiceResult<usize>
Parameters:
dest(&mut [u8]) — Caller's buffer for receiving the I-snapshotsrc(&[u8]) — Data to be written to Zone Qdata(&[u8]) — Ibid.
Return value:
Vec<u8>— One copy from Zone ISnapshot(Synchronized with the same beat; copying it doesn't change the timing.)usize— Actual number of bytes copied/writtenServiceResult<()>—Ok⟺ Byte written
Note:
copy_inputs_toTake the shorter of the two lengths and copy it, soAllowed to be shorter thandestZone I(Returns the actual number of bytes copied); it will not cause a buffer overflow.copy_to_outputsWhen you writesrc.len()to , the value returned is ;src.len()if the data length exceeds the valid length, an error will be reportedOutOfRange.write_outputs/copy_to_outputsAll come fromOffset 0 Rewrite the entire paragraph / Keep it brief; do not make partial edits.- The failure pattern is the same
write()asread()/ (see the next two sections).
Example:
let pd = device.process_data();
let mut buf = [0u8; 8];
let n = pd.copy_inputs_to(&mut buf)?; // Take only the first 8 bytes and return 8
println!("取了 {n} 字节");
pd.copy_to_outputs(&buf)?; // Short Write Q: Write these 8 bytes starting at offset 0
read() / write(data)
PnSService The entire segment of bidirectional entries is equivalent write_outputs() to ProcessData::inputs() / .
pub fn read(&self) -> ServiceResult<Vec<u8>> // I Entire Segment (Controller → Device)
pub fn write(&self, data: &[u8]) -> ServiceResult<()> // Write Q (device → controller), short write starting at offset 0
Parameters:
data(&[u8]) — Bytes to be written to Q, must not be empty
Return value:
Vec<u8>— A snapshot of Zone I. Length = Effective Length = min(Data Length, Available Length)(When the data length is unknown, use the available length rather than extrapolating based on the partition capacity); data starts at byte 0ServiceResult<()>—Ok⟺ Byte written
Note:
read()There is no check for "whether or not.start()"stop()After that, it returns to Snapshot I as usual (the content is from the moment it paused). It only requires that the process data channel be present.read()There is only one failure pattern: Channel unavailable →ServiceError::SharedMemory("过程数据未就绪, 无法读 IO"). After a session fails to establish, or when there is no responsestart(),close()this is the error that is reported.write()If you go withwrite_area(ServiceArea::Output, 0, data)that approach, see the next section for examples of failure.- The return value of
read()a single call is consistent within the same batch.: Multiple fields in the same snapshot must be captured at the same time. This is the method for ensuring consistency across multiple fields. - The same beat is not guaranteed across multiple calls.: Each
in_*/in_itemrepresents a new session read.
Example:
let raw: Vec<u8> = device.read()?; // A Snapshot of I
if raw.len() >= 2 {
let first_word = u16::from_be_bytes([raw[0], raw[1]]); // big-endian
println!("{first_word}");
}
device.write(&[0x01, 0x00])?; // Write 2 bytes starting at offset 0
read_area(area, offset, length) / write_area(area, offset, data)
Batch reads and writes by region + offset, accessing a contiguous block of bytes in a single call.
pub fn read_area(&self, area: ServiceArea, offset: usize, length: usize) -> ServiceResult<Vec<u8>>
pub fn write_area(&self, area: ServiceArea, offset: usize, data: &[u8]) -> ServiceResult<()>
Parameters:
area(ServiceArea) —ServiceArea::Input(Zone I, controller → device) orServiceArea::Output(Zone Q, device → controller).Unknown/Memory/DbAll requests are deniedoffset(usize) — Byte offset relative to the start of the regionlength(usize) — Number of bytes readdata(&[u8]) — The byte to be written, Not Empty
Return value:
Vec<u8>— A snapshot of that intervalServiceResult<()>—Ok⟺ Submission is effective immediately (submitted on the spot, with no delay)
Note:
- The upper limit is based on the valid long card (= the available length
min(数据长度, 可用长度)when the data length is unknown): the same caliber on both the I and Q sides. - Read (no short version): Either give enough, or
OutOfRange. - Write in a single callA continuous segmentRange. Non-adjacent changes are automatically merged into a single write; if they are called multiple times, they result in multiple commits.
read_areaFailure patterns, in order of determination:- Session not established →
ServiceError::NotConnected - None
start()→ServiceError::NotStarted areaNot Input / Output →ServiceError::InvalidAddress("区域非法: 区域名")- Channel Unavailable →
ServiceError::SharedMemory("过程数据未就绪, 无法读 IO") offset + lengthOverflow →ServiceError::InvalidAddress("区域越界: offset + length 溢出")- Out of bounds →
ServiceError::OutOfRange(偏移, 长度, 有效长), displayed as地址越界: 偏移 N + 长度 M 超出过程映像区 K 字节
- Session not established →
write_areaFailure patterns, in order of determination:- Session not established →
ServiceError::NotConnected area == Input→ServiceError::OutputReadOnly(This door predatesNotStarted)areaNot Output →ServiceError::InvalidAddress("区域非法: 区域名")- None
start()→ServiceError::NotStarted - Empty data →
ServiceError::InvalidAddress("写数据不能为空") - Channel Unavailable →
ServiceError::SharedMemory("过程数据未就绪, 无法写 IO") offset + data.len()Overflow →ServiceError::InvalidAddress("区域越界: offset + length 溢出")- Out of Bounds →
ServiceError::OutOfRange(偏移, 长度, 有效长)
- Session not established →
OutOfRangeThe offset field in isu16; if it exceeds 65535, it willTruncationDisplay it again at 65535.
Example:
use darra_pns::ServiceArea;
let part = device.read_area(ServiceArea::Input, 4, 2)?; // Zone I, offset 4, starting at 2 bytes
device.write_area(ServiceArea::Output, 0, &[0x01, 0x00])?; // Q zone, starting at offset 0, 2 bytes
// Writing to Zone I is a real error—it isn't silently ignored.
let err = device.write_area(ServiceArea::Input, 0, &[0x00]);
assert!(matches!(err, Err(darra_pns::ServiceError::OutputReadOnly)));
Related Structures:
pub enum ServiceArea {
Unknown, // Unknown
Input, // Zone I Read-Only (Controller → Device)
Output, // In Section Q, write only (Device → Controller)
Memory, // The "M" zone is used only to indicate that something is not supported.
Db, // DB " " is used only for reporting; it is not supported.
}
byte_at(offset) / set_byte_at(offset, value)
Single-byte read/write operations with absolute offsets.
pub fn byte_at(&self, offset: usize) -> ServiceResult<u8> // Read 1 byte from Zone I
pub fn set_byte_at(&self, offset: usize, value: u8) -> ServiceResult<()> // Write 1 byte to Q
Parameters:
offset(usize) — Byte offset relative to the start of the regionvalue(u8) — Bytes to be written
Return value:
ServiceResult<u8>— The value of this byteServiceResult<()>—Ok⟺ Submitted
Note:
- It is simply a single layer
write_area(Output, offset, &[value])of packaging consisting of andread_area(Input, offset, 1); the failure pattern is exactly the same as in the previous section. byte_atIt's mainly used to retrieve things that aren't included in the snapshot you receivedread(): It displays readings directly based on zone offset., and it is not the same as the snapshot.- Where strings or structures can't reach, use this pair to move data byte by byte.
Example:
let b = device.byte_at(4)?; // Zone I Offset 4
device.set_byte_at(4, b ^ 0x01)?; // Q Zone Offset 4
Read/Write by Address (Region + Byte + Bit)
Use these ports if you don't want to calculate the offset yourself and want to write to the addresses as they appear in the engineering software: Region Letter + Byte Offset + Bit. The address object is ServiceAddress.
let done: bool = device.read_bool("I0.0")?; // position
let recipe: i16 = device.read_int16("IW2")?; // word
let counter: i32 = device.read_int32("ID4")?; // double word
device.write_bool("Q0.0", true)?;
device.write_int16("QW2", 123)?;
device.write_int32("QD4", 10000)?;
| How to Write an Address | What is it? | Is there a corresponding entry point? |
|---|---|---|
I0.0 / Q0.0 | Bit address: Bit 0 of byte 0 (bit numbers must be between 0 and 7) | There are: read_bool / write_bool |
IW2 / QW2 | Word (2 bytes) | There are: read_int16 / write_int16 |
ID4 / QD4 | Double word (4 bytes) | There are: read_int32 / write_int32 |
IB0 / QB0 | Byte (1 byte) | It can be parsed, but there's no entry point to handle it. |
- Do not enforce 2/4 alignment:
IW3/ID2Both are valid; "offset" refers to a byte offset. - Does not support the M zone / DB zone:
M…and are rejected duringDB…the parsing phase. - When you read from a Q address (
QW2etc.), you get back the value you wrote; whatever you write is what you read back. - Write to Side I →
ServiceError::OutputReadOnly, do not silence.
parse_address(text)
Parse the address string into ServiceAddress. All address entry points use this to parse addresses, and you can also use it on its own for validation.
pub fn parse_address(text: &str) -> ServiceResult<ServiceAddress> // Associative functions:PnSService::parse_address (…)
Parameters:
text(&str) — Address string; leading and trailing spaces aretrimstripped
Return value:
ServiceResult<ServiceAddress>— Analysis Results
Related Structures:
pub struct ServiceAddress {
pub area: ServiceArea, // Input (Zone I) / Output (Zone Q)
pub slot: u16, // I/Q Zone Fixed 1 (SDK No slot parameters)
pub subslot: u16, // Pinned 1
pub byte_offset: u16, // Byte offset, maximum 65535
pub bit: i32, // Bit numbers 0–7; -1 = non-bit addressing
pub length: usize, // Data width: bits = 1,IB/QB = 1,IW/QW = 2,ID/QD = 4
}
Note:
- Failure patterns (
ServiceError::InvalidAddressall messages include the original URL):- Empty string →
"地址不能为空" DBStart (case-insensitive) →"不支持 DB 地址: {地址}"MStart →"不支持 M 地址: {地址}"- Other initials →
"不支持的地址区域: {地址}" - There is one,
.but the dot is at the very beginning / end →"地址格式非法 (位地址应为 I0.0 形式): {地址}" - Position No. > 7 →
"位号必须在 0-7 之间: {地址}" - No offset value →
"地址缺少偏移量: {地址}" - Offset / Position number is not a pure number →
"字节偏移非法: {地址}"/"位号非法: {地址}" - Number > 65535 →
"字节偏移超出范围: {地址}"/"位号超出范围: {地址}"
- Empty string →
- Regional CharactersCase-insensitive(
i0.0That works, too); type characterB/W/DRecognize only uppercase letters,iw2it will be treated as "untyped character + offsetw2" and result in an fault字节偏移非法. - If there is no type character, pressByteExplanation: (
I0The value oflengthis 1.) - Purely analytical, without touching the bus: It can be called even if the session hasn't been established.
Example:
use darra_pns::{PnSService, ServiceAddress};
let a: ServiceAddress = PnSService::parse_address("IW3")?; // word address; 2-byte alignment is not required
assert_eq!(a.byte_offset, 3);
assert_eq!(a.length, 2);
assert_eq!(a.bit, -1);
Analysis of areas outside the I/Q region (M/DB) returns Err — This SDK only supports the I/Q region.
read_bool(address)
Read onepositionAddress (I0.0 / Q0.0).
pub fn read_bool(&self, address: &str) -> ServiceResult<bool>
Parameters:
address(&str) — An address that must include a position number, such asI0.0
Return value:
ServiceResult<bool>— The current value of this bit
Note:
- Addresses must include a unit number.
read_bool("IB0")→ServiceError::InvalidAddress("位地址必须带位号: IB0"). - Reads the entire byte and retrieves the value at that
1 << bitposition: an invalid bit number is rejected during the parsing phase (位号必须在 0-7 之间: {地址}). - Failure Patterns:
- Invalid address →
ServiceError::InvalidAddress(…)(See [link] for various messagesparse_address) - No session established →
ServiceError::NotConnected - None
start()→ServiceError::NotStarted - Out of Bounds →
ServiceError::OutOfRange(字节偏移, 1, 有效长) - Channel Unavailable →
ServiceError::SharedMemory("过程数据未就绪, 无法读 IO")
- Invalid address →
QThe address returns the value you entered;Ithe address reads from the input area.
Example:
let run: bool = device.read_bool("I0.0")?;
let ready: bool = device.read_bool("Q0.0")?;
read_int16(address)
Read one word address (IW2 / QW2), big-endian.
pub fn read_int16(&self, address: &str) -> ServiceResult<i16>
Parameters:
address(&str) — word address; must resolve to 2 bytes and must not be bit-addressed
Return value:
ServiceResult<i16>— Big-endian Int16
Note:
- The address must be 2 bytes wide and must not include a bit number.
read_int16("IB0")/read_int16("I0.0")→ServiceError::InvalidAddress("字地址必须为 2 字节且非位寻址: {地址}"). - Offset is not required to be 2-byte aligned:
IW3Valid. - Failure Patterns:
InvalidAddress(Analysis / Width, see above), ...NotConnected, ...NotStarted``OutOfRange(字节偏移, 2, 有效长), ...SharedMemory("过程数据未就绪, 无法读 IO"), ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., - Big-endian decoding, same
in_i16as .
Example:
let recipe: i16 = device.read_int16("IW2")?;
let set_pt: i16 = device.read_int16("IW3")?; // No forced alignment; valid
read_int32(address)
Read one double word address (ID4 / QD4), big-endian.
pub fn read_int32(&self, address: &str) -> ServiceResult<i32>
Parameters:
address(&str) — A double word address; must be resolved to 4 bytes and must not be bit-addressed
Return value:
ServiceResult<i32>— Int32 (big-endian)
Note:
- The address must be 4 bytes wide and must not include a bit number.
read_int32("IW2")→ServiceError::InvalidAddress("双字地址必须为 4 字节且非位寻址: IW2"). - Offset is not required to be 4-byte-aligned:
ID2Valid. - The failure pattern is the same
read_int16, but the width is changed to 4.
Example:
let counter: i32 = device.read_int32("ID4")?;
write_bool(address, value)
Write apositionAddress (Q0.0).
pub fn write_bool(&self, address: &str, value: bool) -> ServiceResult<()>
Parameters:
address(&str) — An address must include a position numbervalue(bool) — Set / Clear
Return value:
ServiceResult<()>—Ok⟺ Submitted
Note:
- Bitwise operations must read and write in full bytes, so they areRead—Revise—Rewrite: First, read the byte, modify the target bit, and then write the entire byte back. The other bits in the same byte are not affected.
- Precisely because it has to read it first, First Reported
start()at the Wei HourNotStarted, rather than “Zone I Read-Only.” - Write
Iaddress (e.g.,I0.0) →ServiceError::OutputReadOnly. Reading that rung is valid; the issue occurs during the write rung. - Failure Patterns:
InvalidAddress("位地址必须带位号: {地址}"),NotConnected,NotStarted,OutputReadOnly,OutOfRange(字节偏移, 1, 有效长),SharedMemory("过程数据未就绪, 无法写 IO").
Example:
device.write_bool("Q0.0", true)?;
let err = device.write_bool("I0.0", true); // Already called start(): Used the read-first approach, but got stuck on the write rung → Read-only in Zone I
assert!(matches!(err, Err(darra_pns::ServiceError::OutputReadOnly)));
write_int16(address, value)
Write a word address (QW2), big-endian.
pub fn write_int16(&self, address: &str, value: i16) -> ServiceResult<()>
Parameters:
address(&str) — word addressvalue(i16) — Value to be written
Return value:
ServiceResult<()>—Ok⟺ Submitted
Note:
- The address must be 2 bytes wide and must not include a bit number; otherwise,
ServiceError::InvalidAddress("字地址必须为 2 字节且非位寻址: {地址}"). write_boolUnlike , itNo need to read it first: SoIW2when writing toOutputReadOnly, it immediately reports an fault without checking the STstart()of .- Failure Patterns:
InvalidAddress,NotConnected,OutputReadOnly,NotStarted,OutOfRange(字节偏移, 2, 有效长),SharedMemory("过程数据未就绪, 无法写 IO"). - Big-endian encoding, same
out_i16as .
Example:
device.write_int16("QW2", 123)?;
device.write_int16("QW3", 456)?; // No forced alignment
write_int32(address, value)
Write a double word address (QD4), big-endian.
pub fn write_int32(&self, address: &str, value: i32) -> ServiceResult<()>
Parameters:
address(&str) — double word addressvalue(i32) — The value to be written
Return value:
ServiceResult<()>—Ok⟺ Submitted
Note:
- The address must be 4 bytes wide and unindexed; otherwise,
ServiceError::InvalidAddress("双字地址必须为 4 字节且非位寻址: {地址}"). - If you don't read it first, the failure pattern is the same
write_int16, but the width changes to 4.
Example:
device.write_int32("QD4", 10000)?;
Big-Endian Encapsulation / Decapsulation (for Snapshot Parsing)
When parsing multiple fields from a snapshot (read() the result read_area() of /) based on offsets, use this set of common functions; do not write a second byte-order implementation.
Path: darra_pns::service::process_data (Not in the crate root).
pub fn pack_u8(value: u8) -> [u8; 1]
pub fn pack_i16_be(value: i16) -> ServiceResult<[u8; 2]> // big-endian
pub fn pack_u16_be(value: u16) -> ServiceResult<[u8; 2]> // big-endian
pub fn pack_i32_be(value: i32) -> ServiceResult<[u8; 4]> // big-endian
pub fn pack_u32_be(value: u32) -> ServiceResult<[u8; 4]> // big-endian
pub fn pack_i64_be(value: i64) -> ServiceResult<[u8; 8]> // big-endian
pub fn pack_u64_be(value: u64) -> ServiceResult<[u8; 8]> // big-endian
pub fn pack_f32_be(value: f32) -> ServiceResult<[u8; 4]> // IEEE754, big-endian (network byte order)
pub fn pack_f64_be(value: f64) -> ServiceResult<[u8; 8]> // IEEE754, big-endian (network byte order)
pub fn unpack_u8(buf: &[u8]) -> ServiceResult<u8>
pub fn unpack_i8(buf: &[u8]) -> ServiceResult<i8>
pub fn unpack_i16_be(buf: &[u8]) -> ServiceResult<i16>
pub fn unpack_u16_be(buf: &[u8]) -> ServiceResult<u16>
pub fn unpack_i32_be(buf: &[u8]) -> ServiceResult<i32>
pub fn unpack_u32_be(buf: &[u8]) -> ServiceResult<u32>
pub fn unpack_i64_be(buf: &[u8]) -> ServiceResult<i64>
pub fn unpack_u64_be(buf: &[u8]) -> ServiceResult<u64>
pub fn unpack_f32_be(buf: &[u8]) -> ServiceResult<f32>
pub fn unpack_f64_be(buf: &[u8]) -> ServiceResult<f64>
pub fn bool_bit0(value: u8) -> ServiceResult<bool> // (value & 1) != 0
Return value:
[u8; 1]/ServiceResult<[u8; N]>— Encoded bytes (pack_u8returns immediately if there is no failure path; otherwise, returns the result of the packing functionResult)ServiceResult<i16>/ … — The calculated valueServiceResult<bool>— bit0 evaluation result
Note:
- UnpackStarting from the 0th byte of the buffer, Insufficient bufferReport errors accurately, Do not silently pad 0: 2 / 4 / 8-byte buffers that are insufficient → ;
ServiceError::OutOfRange(0, 需要, 实得)``unpack_u8If an empty buffer is encountered →OutOfRange(0, 1, 0). - The only ones without a suffix
_bearepack_u8/unpack_u8/unpack_i8— 1 byte with no byte order. bool_bit0(0x00)=false,bool_bit0(0x01)=true,bool_bit0(0x02)=false,bool_bit0(0x80)=false. ReturnServiceResult<bool>. This implementation does not SDK provide the second implementation of 「a non-0 byte is true.」- None
pack_bool/ ;unpack_boolUse to write "boolset_bool," or write it yourself0 / 1.
Example:
use darra_pns::service::process_data::{bool_bit0, unpack_i16_be, unpack_i32_be};
let raw = device.read()?; // A snapshot (one call, one shot)
let recipe = unpack_i16_be(&raw[2..4])?; // Big-endian with offset 2 Int16
let counter = unpack_i32_be(&raw[4..8])?; // Big-endian with an offset of 4 Int32
let ready = bool_bit0(raw[6])?; // 0x02 / 0x80 All are false
println!("{recipe} {counter} {ready}");
Record Index Space (Another Approach to Indexed Addressing)
Process data isCycleYes, a "Record" isNon-periodic. Both use "subscripts" for indexing, but they are two different index spaces—don't confuse them:
| Index Space | Scope | Who's Reading? | Which entry point should I use? |
|---|---|---|---|
| Process Data I/Q | Byte offset, 0 … 区长度 | You (all entries in the first half of this section) | process_data() That family |
| User Area Records | 0x0000 – 0x7FFF | Controller (IODRead / IODWrite) | device.records() (GET /api/records) |
| I&M Records | 0xAFF0 – 0xAFF4 | Controller | Not in the log entry — See device.im_data()(GET /api/im) |
0xAFF0 – Handled 0xAFF4 by the protocol stack itself, Record channel without entering the user area, so you'll never records() see them. To read I&M, use im_data().
records()
Read the user area record table (Index 0x0000 – 0x7FFF).
pub fn records(&self) -> ServiceResult<UserRecords> // PnSService The entry point on
Return value:
ServiceResult<UserRecords>— Record Sheet
Related Structures:
pub struct UserRecords {
pub records: Vec<UserRecord>, // Table with missing fields is empty
pub count: i32, // Server-side count; if a field is missing, the substitution value is 0; do not pad based on the array length
pub timestamp: String, // Snapshot Moment (ISO-8601, original string)
}
pub struct UserRecord {
pub slot: u16, // Slot; if a field is missing, the substitution value is 0
pub subslot: u16, // subslot; if a field is missing, the substitution value is 0
pub index: u16, // Record Index (User Area 0x0000-0x7FFF)
pub length: u16, // Number of data bytes; if this field is missing, the substitution value is 0.
pub data_hex: String, // Hexadecimal data; if a field is missing, leave it blank.
}
Note:
- No record does not mean failure:
Ok+ spacerecords. data_hexYesHexadecimal string, not a byte array — figure it out yourself.- Failure Patterns:
- Session not established →
ServiceError::NotConnected - Service Unavailable →
ServiceError::ConnectFailed(host, port, 原因) - The service returned a non-200 ST code →
ServiceError::HttpStatus(状态码, 原因) - Response is invalid JSON / Missing field →
ServiceError::BadResponse(原因)
- Session not established →
- No entry for the log: SDK There is no method in the side to call
IODWrite. Writes to user-space records are initiated by the controller,SDK which reads only from this table. - Missing field in a single recordReturn the substitution value as-is(0 / empty string), non-fictional, etc.
Example:
for r in device.records()?.records {
println!(
"槽 {}/{} Index 0x{:04X} {} 字节 {}",
r.slot, r.subslot, r.index, r.length, r.data_hex
);
}
// I&M is not in this index space.
let im = device.im_data()?;
println!("I&M 已启用: {} / 订货号 {}", im.im_supported, im.order_id);
Validity Periods of Mappings and Handles
| What was done? | Existing &T / &mut T / slice / handles | Remap |
|---|---|---|
stop() | It's still there. It's just that the value being read is static. | AlsoGet New Mapping (stop Without Unloading Channels) |
close() | Suspended(Channel has been unmapped) | Retrieve mapping report; SharedMemory need to restart start() |
drop(device) | Drop The passage will be opened; same as above. | — |
- Scalar and shielding accessors operate on a different scale:
stop()Every read or write onin_item(…)read_area/write_area/byte_at/in_*/out_*/ returnsNotStarted. - But
read()NoneAfter this check:stop()It still returns the I snapshot. close(&mut self)To borrow exclusively, while the mapping/handle'aremains borrowed—PnSServiceso it's safe in Rust. Can't write it"Hold the mapping and click 'Close'."This guarantee comes from the borrowing checker, not from runtime checks.let pd = device.process_data();
let inp = unsafe { pd.inputs_mapping::<FromPlc>()? };
device.close(); // configuration fault: `device` has been borrowed as immutable- A handle (
ProcessDataItem) is not a raw pointer, so it does not bear the responsibility for managing the pointer's lifetime; however, it relies on the service and similarly blocksclose(). - MappedAddress StabilityThere are no promises.
How do I get the number of bytes?
The length is taken as GET /api/io inputLength / outputLength(the field name is in the opposite direction of I/Q; do not use the name as a reference), effective length = min(数据长度, 可用长度), and when the data length is unknown (0), use the available length, 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) | device.read()?.len() |
| Input Area Length | device.diag_snapshot()?.input_area_length(u32 Field) |
| Output Area Length | device.diag_snapshot()?.output_area_length(u32 Field) |
| I Effective Length | device.read()?.len() (= min(数据长度, 可用长度)) |
- Effective length =
min(数据长度, 可用长度), when the data length is unknown (0), use the available length; Do not extrapolate based on district capacity. - Use the valid long card uniformly; do not calculate based on the district head or capacity.
So the "mapping holder" cannot hold a district chief or a memory card. Fortunately, the size checker automatically rejects items that are too large: if they exceed the limit, they are returned ServiceError::InvalidParam("结构体大于输入过程映像") / ("结构体大于输出过程映像"), andThis check comes after the channel check. —— The first start() thing I saw was SharedMemory.
The public evaluation version and installation package are available only for Windows 10/11 x64 (there is no public Linux evaluation version). Non-Windows targets should report to / ServiceError::SharedMemory("PnS 过程数据通道仅支持 Windows") ServiceError::CoreUnavailable(...).