结构体解码 (StructDecoder)
概述
OPC UA 1.04+ 把每个自定义结构体的字段定义放到 DataType 节点的 DataTypeDefinition 属性 (AttributeId=27, Part 5 §6.4.2)。设计上的流程是: 客户端 Read 该属性 → 拿 StructureDefinition (Fields[]) → 缓存; 拿到 ExtensionObject 二进制后, 按字段顺序用 UA Binary 编码 (Part 6 §5.2) 反序列化为 字段名 → 值 字典。
当前状态 (必读): Decode(Variant) 现在只返回诊断字典、不返回字段值, DecodeBody 恒返回 null。细节见文末「实现限制」, 请先读完再决定是否接入。
解码规则覆盖以下形态 (当前拿不到 ExtensionObject 字节流与字段定义, 走不到解码这一步):
- 全部基本类型 (Boolean / Int / Float / Double / String / DateTime / Guid / ByteString / NodeId / ExpandedNodeId / StatusCode / QualifiedName / LocalizedText / XmlElement)
- 嵌套结构体 (字段 DataType 指向另一个自定义结构, 自动递归)
- 枚举 (按 Int32 解码)
- 数组 (ValueRank ≥ 1)
- Union (1-based selector)
- Optional 字段 (UInt32 EncodingMask)
- 递归深度上限 32 层 + 环引用检测 (超限抛
InvalidDataException, 不会栈溢出崩进程)
API
| 成员 | 类别 | 读写 | 说明 |
|---|---|---|---|
| new StructDecoder(ua) | 构造 | — | 绑定到会话 (ua == null 抛 ArgumentNullException) |
| decoder.Decode(Variant v) | 方法 | 读 | 解码 ExtensionObject, 返回 Dictionary<string, object> |
| decoder.Decode<T>(Variant v) | 方法 | 读 | 解码到强类型 T (字段按名映射) |
| decoder.DecodeBody(byte[] body, string dataTypeNodeId) | 方法 | 读 | 直接给字节流 + DataType 解码 |
| decoder.ClearCache() | 方法 | — | 清字段表缓存 (服务端 DataType 改了时调) |
| decoder.CachedDefinitionCount | 属性 | 读 | 已缓存的结构体数量 |
| StructDecoder.StatusKey | 常量 | — | "_status", 诊断字段名 |
| StructDecoder.TypeIdKey | 常量 | — | "_typeId", 诊断字段名 |
真签名:
public sealed class StructDecoder
{
public const string StatusKey = "_status";
public const string TypeIdKey = "_typeId";
public StructDecoder(DarraOpcUa ua);
public void ClearCache();
public int CachedDefinitionCount { get; }
public Dictionary<string, object> Decode(Variant v);
public T Decode<T>(Variant v) where T : new();
public Dictionary<string, object> DecodeBody(byte[] body, string dataTypeNodeId);
}
返回值约定:
| 调用 | 非 ExtensionObject / 入参为 null | 是 ExtensionObject |
|---|---|---|
Decode(Variant) | null | 只含 _status 的字典 (当前拿不到字节流) |
Decode<T>(Variant) | default (T 为类时即 null) | 一个 new T() 空实例 — 字段全是默认值 |
DecodeBody(...) | null | null (字段定义解析尚未接通) |
Decode<T> 的空实例当成功Decode<T> 在 T 是 class 时, null 只代表"不是 ExtensionObject"; 拿到一个非 null 但字段全默认的 T, 说明进了 ExtensionObject 分支但没解出字段。判成功要看 Decode(Variant) 返回的字典里有没有 _status, 不要看 Decode<T> 是否为 null。
相关结构:
public sealed class StructDefinition
{
public string Name { get; set; } // 结构体名 (DataType 节点 BrowseName)
public string DataTypeId { get; set; } // DataType NodeId (字符串形式)
public string BaseDataType { get; set; } // 父类型 NodeId
public StructureKind Kind { get; set; } // 结构体类别, 默认 Structure
public List<StructField> Fields { get; set; } // 字段表 (顺序 = 二进制编码顺序)
public string DefaultEncodingId { get; set; } // Binary Encoding 节点 NodeId
public bool IsUnion { get; } // 是否 Union 编码 (前置 selector)
public bool HasOptionalFields { get; } // 是否带 Optional 字段 (前置 EncodingMask)
}
public sealed class StructField
{
public string Name { get; set; } // 字段名
public string Description { get; set; } // 字段描述 (LocalizedText 的 Text 部分)
public string DataType { get; set; } // 字段类型 NodeId
public int ValueRank { get; set; } // -1 标量 / 0 单维或更高 / 1+ 数组, 默认 -1
public uint[] ArrayDimensions { get; set; } // 每维上限
public uint MaxStringLength { get; set; } // String/ByteString/XmlElement 最大长度 (0 = 不限)
public bool IsOptional { get; set; } // Optional 字段标记
}
public enum StructureKind
{
Structure = 0, // 普通, 顺序固定
StructureWithSubtypedValues = 1, // 含子类型字段 (编码同 Structure)
StructureWithOptionalFields = 2, // 含可选字段, 前置 UInt32 EncodingMask
Union = 3, // Union, 前置 UInt32 selector (1-based, 0=null)
UnionWithSubtypedValues = 4 // Union 含子类型 (编码同 Union)
}
代码示例
using System;
using System.Collections.Generic;
using DarraOpcUa_Client;
using var ua = new DarraOpcUa("opc.tcp://localhost:4840");
ua.Connect();
var dec = new StructDecoder(ua);
// 1) 读包含自定义结构体的节点 (例如 Robot.CurrentPose : PoseType)
using var dv = ua.Read("ns=2;s=Robot.CurrentPose");
// 当前 Decode 只回诊断字典 — 用 _status 判断是否真解出字段
var fields = dec.Decode(dv.Value);
if (fields == null)
{
Console.WriteLine("不是 ExtensionObject");
}
else if (fields.TryGetValue(StructDecoder.StatusKey, out var diag))
{
Console.WriteLine($"暂不可用: {diag}");
}
else
{
foreach (var (name, value) in fields)
Console.WriteLine($"{name} = {value}");
}
// 2) 强类型 — 注意: 当前会拿到一个字段全为默认值的空实例, 不能当成功
var pose = dec.Decode<PoseType>(dv.Value);
if (pose != null) Console.WriteLine($"x = {pose.X}");
// 3) 已经手上有原始字节时走 DecodeBody
// (当前恒返回 null)
byte[] rawBody = LoadExtensionObjectBody(); // 调用方自己取到的 EO body
var dict = dec.DecodeBody(rawBody, "ns=2;i=3001");
// 4) 缓存管理
Console.WriteLine($"已缓存结构体定义 = {dec.CachedDefinitionCount}");
dec.ClearCache();
PoseType 是调用方自己写的 POCO, 字段名要和服务端字段名一致 (按名映射, 不匹配就跳过):
public class PoseType
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
}
实现限制
当前版本还拿不到字段值, 按调用路径说明:
Decode(Variant)不返回字段 — 拿不到ExtensionObject的 TypeId / Body, 恒返回只含_status的字典 (StructDecoder.StatusKey)。DecodeBody(byte[], string)恒返回null— 读DataTypeDefinition拿不到StructDefinition, 没有字段表就解不出字段。Decode<T>的空实例陷阱 — 见上文 API 表下方的 warning。
可用的部分:
- 递归深度上限 32 层, 超限抛
InvalidDataException - 环引用检测 (A→B→A) — 同一 DataType 递归出现会直接抛
InvalidDataException ClearCache()/CachedDefinitionCount缓存管理接口
BuiltinType.DiagnosticInfo 不支持解码。
最佳实践
- 共享一个 decoder 实例 — 字段表缓存随实例保存, 每个会话保持一个
- 先判
_status再用字段 — 见代码示例第 1 步, 不要假设Decode已经返回字段 Decode<T>的 POCO 字段名对齐服务端字段名 — 按名映射, 不一致的字段会被静默跳过- 服务端 DataType 定义变了要
ClearCache()— 缓存不会自动失效
跨语言对照
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| StructDecoder | StructDecoder | StructDecoder | StructDecoder | StructDecoder | DarraUa_StructDecoder |
| Decode | decode | decode | Decode | decode | DarraUa_StructDecoder_Decode |
Decode<T> / DecodeBody / ClearCache / CachedDefinitionCount 在 C# 侧分别对应 Python 的 decode_typed / decode_body / clear_cache / cached_definition_count。