Structure Decoding
Overview
OPC UA 1.04+ Place the field definitions for each custom structure into the node's DataType DataTypeDefinition property (AttributeId=27, Part 5 §6.4.2). The client reads this property → caches it StructureDefinition → and, after retrieving the ExtensionObject bytes, deserializes them into a dict using UA Binary encoding in field order.
UA Binary Decoding capabilities are now complete: all built-in types + nested structures + arrays + unions + optional fields, with triple safeguards for recursion depth, array length, and string length.However, end-to-end decoding isn't working yet., See “Implementation Constraints.”
API
| Members | Category | Reading and Writing | Note |
|---|---|---|---|
| StructDecoder(ua) | Structure | — | Bind to session, ua=None throw ValueError |
| decoder.decode(variant) | Methods | Read | Decode ExtensionObject → Optional[dict] |
| decoder.decode_body(body, data_type_node_id) | Methods | Read | Feed the bytes directly + decode DataType → Optional[dict] |
| decoder.decode_typed(variant, type_) | Methods | Read | Decode and map to strongly typed fields based on field names using reflection |
| decoder.cached_definition_count | Properties | Read | Number of cached struct definitions |
| decoder.clear_cache() | Methods | — | Clear the field table cache (call this when changes are made DataType on the server) |
| variant.decode_structured(decoder) | Extension Methods | Read | Equivalent decoder.decode(variant), hung on OpcUaVariant |
decode / decode_body Returns dict — Field name → value. There is no such DynamicExtensionObject class; nested structs are the same dict, so use write for fields result["X"] and write for iteration result.items().
Related Structures:
class StructureKind(IntEnum):
STRUCTURE = 0 # Regular
STRUCTURE_WITH_SUBTYPED_VALUES = 1 # Subtype
STRUCTURE_WITH_OPTIONAL_FIELDS = 2 # Includes optional fields (prefix EncodingMask)
UNION = 3 # Union (prefix selector)
UNION_WITH_SUBTYPED_VALUES = 4 # Union + Subtype
Code Example
from darra_opcua import DarraOpcUa, StructDecoder, BuiltinType
with DarraOpcUa("opc.tcp://localhost:4840") as ua:
ua.connect()
dec = StructDecoder(ua)
# 1) Decoding — Pass the container OpcUaVariant , not dv.value
# (dv.value returns ExtensionObject None; see variant.md)
class Pose:
X = 0.0
Y = 0.0
with ua.read("ns=2;s=Robot.CurrentPose") as dv:
pose = dec.decode(dv.variant)
typed = dec.decode_typed(dv.variant, Pose) # Reflection Mapped to Its Own Class
# 2) Returns a dictionary: field name → value
if pose is not None and "_status" not in pose:
print(f"x = {pose['X']}")
for name, value in pose.items():
print(f"{name} = {value}")
# 3) Nested structures are also dictionaries
quat = pose.get("Quaternion")
if isinstance(quat, dict):
print(f"qw = {quat['W']}")
# 4) The array field is a list
for a in pose.get("JointAngles") or []:
print(a)
# 5) Proceed directly when you have the raw bytes decode_body
raw = b"\x00\x00\x00\x00..." # ExtensionObject the body
fields = dec.decode_body(raw, "ns=2;i=3001")
# 6) Cache Management
print(dec.cached_definition_count)
dec.clear_cache()
Implementation Constraints
End-to-End DecodingIt doesn't work yet., you'll see two things:
decode_bodyHeng ReturnsNone— The server-side field table is currentlyDataTypeDefinitionunavailable; without the field table, there is no content to decode.UA Binary The decoding functionality itself is complete and will work as soon as the field table is connected.decode(variant)Returns only the portion of the results that contains the field_status— ExtensionObject The TypeId / Body cannot be retrieved at this time, so the only thing we can confirm right now is "whether this is Variant. ExtensionObject"
Other restrictions:
decodeOnly receiveOpcUaVariant; pass it on, and youdv.valuewill receive it (Noneit returns to you anyway ExtensionObjectNone).- The return value is
dict, NoneDynamicExtensionObjectType; Nested structures are alsodict BuiltinType.DataValue/BuiltinType.Variant/BuiltinType.DiagnosticInfoThree built-in types cannot be decoded as struct fields; doing so will result in an exception.NotImplementedError- When the selector of a Union is 0, it returns null
dict(null union); if the selector is out of bounds, it_statusreturns a partial result. - Decoding failure does not throw an exception—returns the decoded portion of the result after
_statuswriting the field - Protection limits: Nesting depth 32, array elements 65536, String/ByteString 16 MiB. Throws "excessive depth" on write
_status; throws "excessive length" on read. Convergence occursValueErrorat the upper level. - The cache is
data_type_node_idstored in; it has an internal lock; if the server changes the definition DataType, you'll have toclear_cache()
Best Practices
- A session shares a field table cache so that it can be reused
StructDecoder. - Server Upgrade / DataType Post-Change Testing
clear_cache() - Use
result["Name"]or to retrieve fieldsresult.get("Name"), and use to iterate through them.result.items() - Check this before the result is announced: See if it's
"_status"there—if it is, that means only part of it has been solved.
Cross-Language Comparison
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| StructDecoder | StructDecoder | StructDecoder | StructDecoder | StructDecoder | DarraUa_StructDecoder |
| Decode(Variant) → Dictionary<string,object> | decode(variant) → Optional[dict] | decode | Decode | decode | DarraUa_StructDecoder_Decode |
| Decode<T>(Variant) | decode_typed(variant, type_) | — | — | — | — |
| DecodeBody(byte[], string) | decode_body(body, data_type_node_id) | — | — | — | — |
| CachedDefinitionCount | cached_definition_count | — | — | — | — |
| ClearCache() | clear_cache() | — | — | — | — |
Both sides returned Dictionary / dict, None of them have this DynamicExtensionObject type—the name in the old documentation is fictional; it doesn't exist in either source code.
Java / C++ / Rust / C: The four columns marked "read-only, unverified" in this entry — indicate that the information has not been verified; it does not mean that it does not exist.