OpcUaNodeId — 強型 NodeId
概要
OPC UA ノード ID はデフォルトで文字列としてエンコードされます ("ns=2;s=Foo")。OpcUaNodeId struct と enum で構成され、明示的に名前空間 / 識別子を含み OpcUaNodeId { namespace_index: u16, identifier: NodeIdValue }、 id_type() から導出 identifier されます。
該当する規格の節:第6部 §5.2.2。
API
| メンバー | カテゴリ | 読み書き | 説明 |
|---|---|---|---|
| OpcUaNodeId::null() | ファクトリ | — | 空のセンチネル (ns=0, i=0) |
| OpcUaNodeId::from_numeric(ns, id) | ファクトリ | — | 数値型 (u32) |
| OpcUaNodeId::from_string(ns, id) | ファクトリ | — | 文字列型 |
| OpcUaNodeId::from_guid(ns, [u8; 16]) | ファクトリ | — | GUID 型 (16 バイトの配列、uuid crate なし) |
| OpcUaNodeId::from_opaque(ns, Vec<u8>) | ファクトリ | — | 不透明タイプ |
| OpcUaNodeId::parse(s) | 静的 | — | 解析、戻り値 Result<Self, ParseError> |
| OpcUaNodeId::try_parse(s) | 静的 | — | 解析、失敗時の処理 Option::None |
| nid.to_string() / nid.to_canonical() | 方法 | 読み取り可 | シリアライズ (impl Display) |
| nid.namespace_index / nid.identifier | フィールド | 読み取り可 | 公開フィールド、直接アクセス |
| nid.id_type() / nid.is_null() | 方法 | 読み取り可 | 識別子の型 / 空かどうか |
関連する構造:
pub enum NodeIdType {
Numeric = 0, // コード i=, u32
String = 1, // コード s=, UTF-8
Guid = 2, // コード g=, {xxxx-...}
Opaque = 3, // コード b=, base64
}
コード例
use darra_opcua::{OpcUaNodeId, NodeIdType, NodeIdValue, Session};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut ua = Session::new("opc.tcp://localhost:4840")?;
ua.connect()?;
// 1) 工場
let n1 = OpcUaNodeId::from_numeric(0, 84); // i=84
let n2 = OpcUaNodeId::from_string(2, "Boiler1.Temp");
let n3 = OpcUaNodeId::from_guid(3, [0u8; 16]); // 16バイトの配列
let n4 = OpcUaNodeId::from_opaque(4, vec![1, 2, 3]);
// 2) 解析
let n5 = OpcUaNodeId::parse("ns=2;s=Demo.Tag")?;
println!("ns={}, type={:?}", n5.namespace_index, n5.id_type());
match OpcUaNodeId::try_parse("ns=99;i=foo") {
Some(n) => println!("ok: {}", n),
None => println!("invalid"),
}
// 3) シリアライズ
let s = n2.to_string(); // "ns=2;s=Boiler1.Temp"
// 4) と SDK の相互変換(read は 文字 NodeId 列という単一の引数のみを受け取る)
let dv = ua.read(&n2.to_string())?;
let dv = ua.read_attr(&n2.to_string(), darra_opcua::AttributeId::Value)?;
// 5) 辞書のキーが――Hash または Ord を派生させていない OpcUaNodeId 場合、
// 直接 HashMap / BTreeMap をキーにすることはできません。代わりに 文字 to_canonical() 列を使用してください。
use std::collections::HashMap;
let mut dict: HashMap<String, String> = HashMap::new();
dict.insert(n2.to_canonical(), "锅炉一温度".into());
// 6) Null
println!("{}", OpcUaNodeId::null().is_null()); // true
let _ = (n1, n3, n4, s, dv);
Ok(())
}
ベストプラクティス
- 設定ファイルには文字列を保存し、読み込みにはparseを使用する
- コード内では強型を使用する
- 数値優先(u32の方が高速)
- ユーザー入力には
try_parse(Option<Self>, 失敗時はNone) またはparse(Result<Self, ParseError>) を使用しますが、いずれも panic にはなりません
多言語対照
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| OpcUaNodeId | OpcUaNodeId | OpcUaNodeId | OpcUaNodeId | OpcUaNodeId | DarraUa_NodeId |
| Parse | parse | parse | Parse | parse | DarraUa_NodeId_Parse |
| FromNumeric | from_numeric | fromNumeric | FromNumeric | from_numeric | DarraUa_NodeId_FromNumeric |