结构体解码
概述
OPC UA 1.04+ 把每个自定义结构体的字段定义放到 DataType 节点的 DataTypeDefinition 属性 (AttributeId=27, Part 5 §6.4.2)。客户端 Read 该属性 → 缓存 StructureDefinition → 拿到 ExtensionObject 字节后按字段顺序用 UA Binary 编码反序列化为 dict。
UA Binary 解码能力已经完整: 全部内置类型 + 嵌套结构 + 数组 + Union + Optional 字段, 并带递归深度 / 数组长度 / 字符串长度三重防护。但端到端解码当前还跑不通, 见「实现限制」。
API
| 成员 | 类别 | 读写 | 说明 |
|---|---|---|---|
| StructDecoder(ua) | 构造 | — | 绑定到会话, ua=None 抛 ValueError |
| decoder.decode(variant) | 方法 | 读 | 解码 ExtensionObject → Optional[dict] |
| decoder.decode_body(body, data_type_node_id) | 方法 | 读 | 直接给字节 + DataType 解码 → Optional[dict] |
| decoder.decode_typed(variant, type_) | 方法 | 读 | 解码并按字段名反射映射到强类型 |
| decoder.cached_definition_count | 属性 | 读 | 已缓存的结构体定义数 |
| decoder.clear_cache() | 方法 | — | 清字段表缓存 (服务端 DataType 改了时调) |
| variant.decode_structured(decoder) | 扩展方法 | 读 | 等价 decoder.decode(variant), 挂在 OpcUaVariant 上 |
decode / decode_body 返回的是 dict — 字段名 → 值。没有 DynamicExtensionObject 这个类; 嵌套结构体也是 dict, 所以取字段写 result["X"], 遍历写 result.items()。
相关结构:
class StructureKind(IntEnum):
STRUCTURE = 0 # 普通
STRUCTURE_WITH_SUBTYPED_VALUES = 1 # 含子类型
STRUCTURE_WITH_OPTIONAL_FIELDS = 2 # 含可选字段 (前置 EncodingMask)
UNION = 3 # Union (前置 selector)
UNION_WITH_SUBTYPED_VALUES = 4 # Union + 子类型
代码示例
from darra_opcua import DarraOpcUa, StructDecoder, BuiltinType
with DarraOpcUa("opc.tcp://localhost:4840") as ua:
ua.connect()
dec = StructDecoder(ua)
# 1) 解码 — 传 OpcUaVariant 容器, 不是 dv.value
# (dv.value 对 ExtensionObject 返回 None, 见 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) # 反射映射到自己的类
# 2) 返回 dict: 字段名 → 值
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) 嵌套结构体同样是 dict
quat = pose.get("Quaternion")
if isinstance(quat, dict):
print(f"qw = {quat['W']}")
# 4) 数组字段是 list
for a in pose.get("JointAngles") or []:
print(a)
# 5) 手上有原始字节时直接走 decode_body
raw = b"\x00\x00\x00\x00..." # ExtensionObject 的 body
fields = dec.decode_body(raw, "ns=2;i=3001")
# 6) 缓存管理
print(dec.cached_definition_count)
dec.clear_cache()
实现限制
端到端解码当前还跑不通, 你会看到两件事:
decode_body恒返回None— 服务端的DataTypeDefinition字段表当前取不到, 没有字段表就没有可解的内容。UA Binary 本身的解码能力是完整的, 字段表一接上就能用。decode(variant)只返回带_status字段的部分结果 — ExtensionObject 的 TypeId / Body 当前取不到, 所以现在能确定的只有"这个 Variant 是不是 ExtensionObject"。
其它限制:
decode只收OpcUaVariant; 传dv.value会得到None(它对 ExtensionObject 本来就返回None)- 返回值是
dict, 没有DynamicExtensionObject类型; 嵌套结构体也是dict BuiltinType.DataValue/BuiltinType.Variant/BuiltinType.DiagnosticInfo三种内置类型不能当结构体字段解码, 会抛NotImplementedError- Union 的 selector 为 0 时返回空
dict(null union); selector 越界写_status并返回部分结果 - 解码失败不抛穿 — 写
_status字段后返回已解出的部分结果 - 防护上限: 嵌套深度 32、数组元素 65536、String/ByteString 16 MiB。超深度写
_status; 超长度抛ValueError由上层收敛 - 缓存按
data_type_node_id存, 内部有锁; 服务端改了 DataType 定义要自己clear_cache()
最佳实践
- 一个会话共享一个
StructDecoder, 字段表缓存才能复用 - 服务端升级 / DataType 变更后调
clear_cache() - 取字段用
result["Name"]或result.get("Name"), 遍历用result.items() - 判结果前先看
"_status"在不在 — 在就说明只解出了一部分
跨语言对照
| 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() | — | — | — | — |
两侧返回的都是 Dictionary / dict, 都没有 DynamicExtensionObject 这个类型 — 旧文档里的这个名字是虚构的, 两边源码里都不存在。
Java / C++ / Rust / C 四列本次只读未核, — 表示未核实, 不表示不存在。