跳到主要内容

OpcUaNodeId — 强类型 NodeId

概述​

OPC UA 节点 ID 默认用字符串编码 ("ns=2;s=Foo")。OpcUaNodeId 由 struct + enum 组成: OpcUaNodeId { namespace_index: u16, identifier: NodeIdValue }, 显式带 namespace / identifier, id_type() 由 identifier 推出。

对应规范段: Part 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) 当字典 key —— OpcUaNodeId 未 derive Hash / Ord,
// 不能直接做 HashMap / BTreeMap 的 key, 用 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
  • 代码内部用强类型
  • Numeric 优先 (u32 比较快)
  • 用户输入用 try_parse (Option<Self>, 失败返 None) 或 parse (Result<Self, ParseError>), 都不会 panic

跨语言对照​

C#PythonJavaC++RustC
OpcUaNodeIdOpcUaNodeIdOpcUaNodeIdOpcUaNodeIdOpcUaNodeIdDarraUa_NodeId
ParseparseparseParseparseDarraUa_NodeId_Parse
FromNumericfrom_numericfromNumericFromNumericfrom_numericDarraUa_NodeId_FromNumeric

下一步​