跳到主要内容

Namespaces — ua.namespaces

OPC UA 节点 NodeId 由 NamespaceIndex + Identifier 组成, 但 NamespaceIndex 不稳定 — Server 重启可能改变. 生产代码必须用 NamespaceUri 反查 Index, 不能硬编码 ns=2.

前置阅读
  • 标准 ns=0 节点常量请参考 WellKnownNodes.
  • 节点 Browse / 路径解析请参考 Nodes.

NamespaceCollection 公共成员

OpcUaSession.namespacesNamespaceCollection, 在 connect() 时自动从服务端 NamespaceArray (i=2255) 加载.

类别属性类型访问说明
协议级len(ns)intR命名空间数量 (用 Python 内置 len())
ns[i]Optional[str]R下标访问, 返回该 Index 对应的 URI

方法

方法返回说明
index_of(uri)int (-1 找不到)反查 URI → Index
reload()StatusCode主动重读服务端 NamespaceArray (Server 动态变更时)

迭代支持: for uri in ua.namespaces: ...


常见用法

反查 Index 拼 NodeId

ua.connect()
idx = ua.namespaces.index_of("urn:my-company:plc1")
if idx < 0:
raise RuntimeError("Server does not have my namespace")

node_id = f"ns={idx};s=Temperature"
with ua.read(node_id) as dv:
print(dv.value)

列出全部命名空间 (调试)

for i, uri in enumerate(ua.namespaces):
print(f" [{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() 重读:

ua.namespaces.reload()
idx = ua.namespaces.index_of("urn:plugin:loaded-after-startup")

标准命名空间 (ns=0)

OPC Foundation 规定 Index 0 永远是 http://opcfoundation.org/UA/, 所有标准节点都在 ns=0:

节点NodeId说明
Rooti=84
Objectsi=85业务数据根
Typesi=86类型定义根
Serveri=2253Server 自身对象
ServerStatusi=2256Server 状态结构
ServerStatus.CurrentTimei=2258服务端当前时间
NamespaceArrayi=2255命名空间数组
ServerArrayi=2254服务端数组

或用常量 (推荐):

from darra_opcua import well_known_nodes as wkn

with ua.read(wkn.SERVER_SERVER_STATUS_CURRENT_TIME) as dv:
print(dv.value)

详见 WellKnownNodes.

下一步