Structure Decoding
Overview
OPC UA 1.04+ Place the field definitions for each custom structure into the DataType node’s DataTypeDefinition attribute (AttributeId=27, Part 5 §6.4.2).StructDecoder UA Binary The field-level decoding protocol layer has been implemented (reads scalars/arrays in order Fields[]; unions use selectors; optional fields use EncodingMask; nested structures are processed recursively). Currently, the ability to extract TypeId and Body ExtensionObject is not SDK yet provided; see “Implementation Limitations” for the actual available scope of decode_body() decode() / and.
API
| Members | Category | Reading and Writing | Note |
|---|---|---|---|
| StructDecoder::new(ua) | Structure | — | Bound to Session (Held &Session Borrowed) |
| decoder.decode(variant) | Methods | Read | Decode ExtensionObject → Option<HashMap<String, DecodedValue>> |
| decoder.decode_body(bytes, data_type_id) | Methods | Read | If raw bytes + TypeId are already present, decode directly → Option<HashMap<String, DecodedValue>> |
| decoder.clear_cache() | Methods | — | Clear the field table cache |
| decoder.cached_definition_count() | Methods | Read | Number of cached structures |
| StructDecoder::STATUS_KEY | const | Read | Conventional Diagnosis Field Names "_status" |
| StructDecoder::TYPE_ID_KEY | const | Read | Convention-Based Field Names "_typeId" |
Use the built-in HashMap function to retrieve field values get(&str); use the built-in function to iterate for (name, value) in &map.
Related Structures:
pub enum StructureKind {
Structure = 0, // Regular
StructureWithSubtypedValues = 1, // Subtype
StructureWithOptionalFields = 2, // Includes optional (pre-installed EncodingMask)
Union = 3, // Union (prefix selector)
UnionWithSubtypedValues = 4, // Union + Subtype
}
/// Decoded field values (aligned `Dictionary<string, object>` with C#).
pub enum DecodedValue {
Bool(bool),
I64(i64), // SByte/Int16/Int32/Int64/DateTime Put them all here
U64(u64), // Byte/UInt16/UInt32/UInt64/StatusCode Put them all here
F64(f64), // Float/Double is all here
String(String),
Bytes(Vec<u8>),// Guid/ByteString
Array(Vec<DecodedValue>),
Struct(HashMap<String, DecodedValue>), // Nested Structures
Null,
}
StructDefinition Includes two classification methods: is_union() / has_optional_fields().
Code Example
use darra_opcua::{Session, StructDecoder, DecodedValue, AttributeId};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut s = Session::new("opc.tcp://localhost:4840")?;
s.connect()?;
let dec = StructDecoder::new(&s);
// 1) Read a custom structure (the Value property contains ExtensionObject)
let dv = s.read_attr("ns=2;s=Robot.CurrentPose", AttributeId::Value)?;
let Some(pose) = dec.decode(&dv.variant()) else {
// No ExtensionObject — `decode` returns `None`
return Ok(());
};
// 2) Full-field traversal — decode returns HashMap<String, DecodedValue>
for (name, value) in &pose {
println!("{} = {:?}", name, value);
}
// 3) Retrieve a single field (HashMap uses the built-in `get` function)
if let Some(DecodedValue::F64(x)) = pose.get("X") {
println!("x = {}", x);
}
// 4) Nested Structures
if let Some(DecodedValue::Struct(quat)) = pose.get("Quaternion") {
if let Some(DecodedValue::F64(qw)) = quat.get("W") {
println!("qw = {}", qw);
}
}
// 5) Array Fields
if let Some(DecodedValue::Array(arr)) = pose.get("JointAngles") {
for a in arr {
println!("{:?}", a);
}
}
// 6) Diagnostic field: _status Includes the reason for failure or partial parsing
if let Some(status) = pose.get(StructDecoder::STATUS_KEY) {
println!("decode 状态 = {:?}", status);
}
// 7) TypeId If raw bytes are already present, decode directly at the protocol layer (if the field table is not yet ready, always return None)
let body: Vec<u8> = /* body ExtensionObject obtained from other channels */ vec![0u8; 8];
if let Some(fields) = dec.decode_body(&body, "ns=2;i=3001") {
println!("{:?}", fields);
}
Ok(())
}
Implementation Constraints
decode()Currently, only some results are returned.: The ExtensionObject TypeId / Body extraction capability has not yet been provided; itdecode()always returns a structure containing only one_statuskeyHashMap, so the field destructuring in examples 3), 4), and 5) above will not be matched. The calling method will remain unchanged once this capability is added.decode_body()Current Heng ReturnsNone: It relies on the field table for DataTypeDefinition (AttributeId=27), but decoding for this property has not yet been provided, so loading the field table always returns null.- If you already have the raw bytes, use decoding
decode_body(bytes, type_id); do not calculate the field offsets yourself. - NodeId / ExpandedNodeId / QualifiedName / LocalizedText / Reading UA Binary these ExtensionObject types of fields has not yet been implemented; if encountered, an error will be returned
None.
Best Practices
- Share a decoder; reuse the field table cache (
cached_definition_count()observable) - Use
StructDecoder::STATUS_KEY/ for diagnostic field namesTYPE_ID_KEY; do not hard-code them."_status" - Accessing nested structures using match DecodedValue::Struct
DecodedValue::Structdestructuring - Union and Optional Fields
StructDefinition::is_union()/has_optional_fields()
Cross-Language Comparison
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| StructDecoder | StructDecoder | StructDecoder | StructDecoder | StructDecoder | DarraUa_StructDecoderHandle |
| Decode | decode | decode | Decode | decode | DarraUa_StructDecoder_Decode |