跳到主要内容

结构体解码

概述​

OPC UA 1.04+ 把每个自定义结构体的字段定义放到 DataType 节点的 DataTypeDefinition 属性 (AttributeId=27, Part 5 §6.4.2)。StructDecoder 已实现 UA Binary 字段级解码协议层 (按 Fields[] 顺序读标量 / 数组, Union 走 selector, 可选字段走 EncodingMask, 嵌套结构递归)。当前 SDK 尚未提供 ExtensionObject 的 TypeId / Body 提取能力, decode() / decode_body() 的实际可用范围见「实现限制」。

API​

成员类别读写说明
StructDecoder::new(ua)构造—绑定到会话 (持 &Session 借用)
decoder.decode(variant)方法读解码 ExtensionObject → Option<HashMap<String, DecodedValue>>
decoder.decode_body(bytes, data_type_id)方法读已有原始字节 + TypeId 时直接解码 → Option<HashMap<String, DecodedValue>>
decoder.clear_cache()方法—清空字段表缓存
decoder.cached_definition_count()方法读已缓存的结构体数量
StructDecoder::STATUS_KEYconst读约定诊断字段名 "_status"
StructDecoder::TYPE_ID_KEYconst读约定类型字段名 "_typeId"

字段取值直接用 HashMap 自带的 get(&str);遍历用 for (name, value) in &map。

相关结构:

pub enum StructureKind {
Structure = 0, // 普通
StructureWithSubtypedValues = 1, // 含子类型
StructureWithOptionalFields = 2, // 含可选 (前置 EncodingMask)
Union = 3, // Union (前置 selector)
UnionWithSubtypedValues = 4, // Union + 子类型
}

/// 解码出的字段值 (与 C# `Dictionary<string, object>` 对齐).
pub enum DecodedValue {
Bool(bool),
I64(i64), // SByte/Int16/Int32/Int64/DateTime 一律落这里
U64(u64), // Byte/UInt16/UInt32/UInt64/StatusCode 一律落这里
F64(f64), // Float/Double 都落这里
String(String),
Bytes(Vec<u8>),// Guid/ByteString
Array(Vec<DecodedValue>),
Struct(HashMap<String, DecodedValue>), // 嵌套结构体
Null,
}

StructDefinition 带两个分类方法: is_union() / has_optional_fields()。

代码示例​

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) 读自定义结构 (Value 属性里是 ExtensionObject)
let dv = s.read_attr("ns=2;s=Robot.CurrentPose", AttributeId::Value)?;
let Some(pose) = dec.decode(&dv.variant()) else {
// 不是 ExtensionObject —— decode 返回 None
return Ok(());
};

// 2) 全字段遍历 —— decode 返回的就是 HashMap<String, DecodedValue>
for (name, value) in &pose {
println!("{} = {:?}", name, value);
}

// 3) 取单个字段 (HashMap 自带 get)
if let Some(DecodedValue::F64(x)) = pose.get("X") {
println!("x = {}", x);
}

// 4) 嵌套结构体
if let Some(DecodedValue::Struct(quat)) = pose.get("Quaternion") {
if let Some(DecodedValue::F64(qw)) = quat.get("W") {
println!("qw = {}", qw);
}
}

// 5) 数组字段
if let Some(DecodedValue::Array(arr)) = pose.get("JointAngles") {
for a in arr {
println!("{:?}", a);
}
}

// 6) 诊断字段: 失败 / 部分解析时 _status 携带原因
if let Some(status) = pose.get(StructDecoder::STATUS_KEY) {
println!("decode 状态 = {:?}", status);
}

// 7) 已有原始字节 + TypeId 时直接走协议层解码 (当前字段表未就绪, 恒返回 None)
let body: Vec<u8> = /* 从其它通道拿到的 ExtensionObject body */ vec![0u8; 8];
if let Some(fields) = dec.decode_body(&body, "ns=2;i=3001") {
println!("{:?}", fields);
}

Ok(())
}

实现限制​

  • decode() 当前只返回部分结果: 尚未提供 ExtensionObject 的 TypeId / Body 提取能力, decode() 恒返回只含 _status 一个键的 HashMap, 上面示例里 3) / 4) / 5) 的字段解构不会命中。能力补齐后调用方式不变。
  • decode_body() 当前恒返回 None: 它依赖 DataTypeDefinition (AttributeId=27) 的字段表, 而该属性的解码尚未提供, 字段表加载恒返回空。
  • 已有原始字节时用 decode_body(bytes, type_id) 解码, 不要自己拼字段偏移。
  • NodeId / ExpandedNodeId / QualifiedName / LocalizedText / ExtensionObject 这几类字段的 UA Binary 读取尚未接入, 遇到会返回 None。

最佳实践​

  • 共享一个 decoder, 字段表缓存复用 (cached_definition_count() 可观察)
  • 诊断字段名用 StructDecoder::STATUS_KEY / TYPE_ID_KEY, 不要硬写 "_status"
  • 嵌套结构用 DecodedValue::Struct match 解构访问
  • Union 与可选字段看 StructDefinition::is_union() / has_optional_fields()

跨语言对照​

C#PythonJavaC++RustC
StructDecoderStructDecoderStructDecoderStructDecoderStructDecoderDarraUa_StructDecoderHandle
DecodedecodedecodeDecodedecodeDarraUa_StructDecoder_Decode

下一步​