構造体のデコード
概要
OPC UA 1.04+ 各カスタム構造体のフィールド定義を、ノード DataType の属性 DataTypeDefinition (AttributeId=27、第5部 §6.4.2)に配置する。StructDecoder フィールドレベルのデコード UA Binary プロトコル層はすでに実装済み (スカラー/配列は の順序で Fields[] 読み込み、Union は selector 経由、オプションフィールドは EncodingMask 経由、ネストされた構造体は再帰処理)。現時点では、 の ExtensionObject TypeId/Body 抽出機能は提供されて SDK おらず、 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_KEY | const | 読み取り可 | 診断フィールド名の規定 "_status" |
| StructDecoder::TYPE_ID_KEY | const | 読み取り可 | 約定タイプフィールド名 "_typeId" |
フィールドの値を取得するには、標準 HashMap 機能の を使用し get(&str)、反復処理には を使用します for (name, value) in &map。
関連する構造:
pub enum StructureKind {
Structure = 0, // 普通
StructureWithSubtypedValues = 1, // 子を含むタイプ
StructureWithOptionalFields = 2, // オプションを含む(前置 EncodingMask)
Union = 3, // Union(前置セレクタ)
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()現時点では結果の一部のみが返されます: 現時点では TypeId / Body の ExtensionObject 抽出機能は提供されておらず、常に 一つの_statusキーのみを含む値がdecode()返されますHashMap。そのため、上記の例の 3) / 4) / 5) におけるフィールドの展開は一致しません。機能が追加された後も、呼び出し方法は変わりません。decode_body()は現在常にNoneを返します: DataTypeDefinition (AttributeId=27) のフィールドテーブルに依存していますが、このプロパティのデコードはまだ提供されておらず、フィールドテーブルの読み込みは常に空を返します。- 元のバイトデータがある場合はデコード
decode_body(bytes, type_id)を使用し、自分でフィールドオフセットを計算しないでください。 - NodeId / ExpandedNodeId / QualifiedName / LocalizedText / ExtensionObject これらの種類のフィールドの UA Binary 読み取り機能はまだ実装されておらず、該当する場合は が返されます
None。
ベストプラクティス
- デコーダを共有し、フィールドテーブルのキャッシュを再利用する(
cached_definition_count()オブザーバブル) - 診断フィールド名には
StructDecoder::STATUS_KEY/ を使用しTYPE_ID_KEY、直接記述しないでください"_status" - ネストされた構造に対する
DecodedValue::StructDecodedValue::Struct match によるデコンストラクションによるアクセス - Union とオプションフィールドについて
StructDefinition::is_union()/has_optional_fields()
多言語対照
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| StructDecoder | StructDecoder | StructDecoder | StructDecoder | StructDecoder | DarraUa_StructDecoderHandle |
| Decode | decode | decode | Decode | decode | DarraUa_StructDecoder_Decode |