Namespaces — s.namespaces()
OPC UA 节点 NodeId 由 NamespaceIndex + Identifier 组成, 但 NamespaceIndex 不稳定 —
Server 重启可能改变. 生产代码必须用 NamespaceUri 反查 Index, 不能硬编码 ns=2.
前置阅读
- 标准 ns=0 节点常量请参考 WellKnownNodes.
- 节点 Browse / 路径解析请参考 Nodes.
NamespaceCollection 公共成员
s.namespaces() 返回 NamespaceCollection, Connect 时已自动从服务端 NamespaceArray
(i=2255) 加载.
| 类别 | 属性 | 类型 | 访问 | 说明 |
|---|---|---|---|---|
| 查询 | count() | u32 | R | 命名空间数量 |
get(index) | Option<String> | R | 按索引取 URI, 越界返回 None | |
index_of(uri) | i32 | R | 反查 URI → Index, 找不到返回 -1 | |
iter() | NamespaceIter | R | 遍历所有 URI, 实现 Iterator<Item=String> | |
| 刷新 | reload() | StatusCode | RW | 主动重读服务端 NamespaceArray (Server 动态变更时) |
常见用法
反查 Index 拼 NodeId
s.connect()?;
let ns = s.namespaces();
let idx = ns.index_of("urn:my-company:plc1");
if idx < 0 {
return Err("Server does not have my namespace".into());
}
let node_id = format!("ns={};s=Temperature", idx);
let dv = s.read(&node_id)?;
列出全部命名空间 (调试)
let ns = s.namespaces();
for (i, uri) in ns.iter().enumerate() {
println!(" [{}] {}", i, uri);
}
输出示例:
[0] http://opcfoundation.org/UA/
[1] urn:server-host
[2] urn:my-company:plc1
[3] http://my-company.com/UA/
动态命名空间变更
某些 Server 启动后才注册命名空间 (插件式), Connect 拿到的 NamespaceArray 不全.
此时调 reload() 重读:
let ns = s.namespaces();
ns.reload();
let idx = ns.index_of("urn:plugin:loaded-after-startup");
通过 NodeCollection 自动构造 NodeId
NodeCollection::make_numeric(uri, identifier) 和 make_string(uri, identifier)
内部已封装 namespace 反查:
// 数字 NodeId: "ns=2;i=1234"
let node = s.nodes().make_numeric("urn:my-company:plc1", 1234)?;
// 字符串 NodeId: "ns=2;s=Temperature"
let node = s.nodes().make_string("urn:my-company:plc1", "Temperature")?;
namespace 不存在时返回
Err(OpcUaError { status: DARRA_INVALID_ARGUMENT, message: "Namespace URI 'xxx' not found" }).
标准命名空间 (ns=0)
OPC Foundation 规定 Index 0 永远是 http://opcfoundation.org/UA/,
所有标准节点都在 ns=0:
| 节点 | NodeId | 说明 |
|---|---|---|
| Root | i=84 | 根 |
| Objects | i=85 | 业务数据根 |
| Types | i=86 | 类型定义根 |
| Server | i=2253 | Server 自身对象 |
| ServerStatus | i=2256 | Server 状态结构 |
| ServerStatus.CurrentTime | i=2258 | 服务端当前时间 |
| NamespaceArray | i=2255 | 命名空间数组 |
| ServerArray | i=2254 | 服务端数组 |
详见 WellKnownNodes.
use darra_opcua::well_known_nodes;
let dv = s.read(well_known_nodes::SERVER_NAMESPACE_ARRAY)?;
// dv.variant() 是 String[] 数组, 内容与 s.namespaces().iter() 相同