Skip to main content

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​

MembersCategoryReading and WritingNote
StructDecoder(ua)Structure—Bind to session, ua=None throw ValueError
decoder.decode(variant)MethodsReadDecode ExtensionObject → Optional[dict]
decoder.decode_body(body, data_type_node_id)MethodsReadFeed the bytes directly + decode DataType → Optional[dict]
decoder.decode_typed(variant, type_)MethodsReadDecode and map to strongly typed fields based on field names using reflection
decoder.cached_definition_countPropertiesReadNumber 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 MethodsReadEquivalent 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:

  1. decode_body Heng Returns None — The server-side field table is currently DataTypeDefinition unavailable; 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.
  2. 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:

  • decode Only receive OpcUaVariant; pass it on, and you dv.value will receive it ( None it returns to you anyway ExtensionObject None).
  • The return value is dict, NoneDynamicExtensionObject Type; Nested structures are also dict
  • BuiltinType.DataValue / BuiltinType.Variant / BuiltinType.DiagnosticInfo Three 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 _status returns a partial result.
  • Decoding failure does not throw an exception—returns the decoded portion of the result after _status writing 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 occurs ValueError at the upper level.
  • The cache is data_type_node_id stored in; it has an internal lock; if the server changes the definition DataType, you'll have to clear_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 fields result.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#PythonJavaC++RustC
StructDecoderStructDecoderStructDecoderStructDecoderStructDecoderDarraUa_StructDecoder
Decode(Variant) → Dictionary<string,object>decode(variant) → Optional[dict]decodeDecodedecodeDarraUa_StructDecoder_Decode
Decode<T>(Variant)decode_typed(variant, type_)————
DecodeBody(byte[], string)decode_body(body, data_type_node_id)————
CachedDefinitionCountcached_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.

Next Step​