命名空间 (C)
OPC UA 节点 NodeId 由 NamespaceIndex + Identifier 组成, 但 NamespaceIndex 不稳定 — Server 重启可能改变. 生产代码必须用 NamespaceUri 反查 Index, 不能硬编码 ns=2.
前置阅读
- 标准 ns=0 节点常量请参考 WellKnownNodes.
- 节点 Browse / 路径解析请参考 Nodes.
API 速查
| 函数 | 说明 |
|---|---|
DarraUa_Session_LoadNamespaceArray(h) | 主动重读服务端 i=2255 |
DarraUa_Session_GetNamespaceCount(h) | 命名空间数 (含 ns=0) |
DarraUa_Session_GetNamespaceUri(h, idx) | URI 查询 (返回内部指针, 不要 free) |
DarraUa_Session_FindNamespaceIndex(h, uri) | 反查 URI → Index, 找不到返回 -1 |
Connect 成功后 SDK 自动 LoadNamespaceArray 一次, 后续无需手动调.
API 详解
DARRA_OPCUA_API DarraUa_Status DARRA_OPCUA_CALL
DarraUa_Session_LoadNamespaceArray(DarraUa_SessionHandle h);
DARRA_OPCUA_API uint32_t DARRA_OPCUA_CALL
DarraUa_Session_GetNamespaceCount(DarraUa_SessionHandle h);
DARRA_OPCUA_API const char* DARRA_OPCUA_CALL
DarraUa_Session_GetNamespaceUri(DarraUa_SessionHandle h, uint32_t index);
DARRA_OPCUA_API int32_t DARRA_OPCUA_CALL
DarraUa_Session_FindNamespaceIndex(DarraUa_SessionHandle h, const char* uri);
GetNamespaceUri 返回 Stack 内部 const char*, 生命周期跟随 Session, 无需 (也不能) 释放. 如要保存请自行 strdup.
反查 Index 拼 NodeId
int32_t idx = DarraUa_Session_FindNamespaceIndex(h, "urn:my-company:plc1");
if (idx < 0) {
fprintf(stderr, "Server does not have my namespace\n");
return -1;
}
char node_id[64];
snprintf(node_id, sizeof(node_id), "ns=%d;s=Temperature", (int)idx);
DarraUa_Status st = 0;
DarraUa_DataValue* dv = DarraUa_Session_ReadNode(
h, node_id, DARRA_UA_ATTR_VALUE, &st);
/* ... */
DarraUa_DataValue_Delete(dv);
列出全部命名空间 (调试)
uint32_t n = DarraUa_Session_GetNamespaceCount(h);
for (uint32_t i = 0; i < n; ++i) {
const char* uri = DarraUa_Session_GetNamespaceUri(h, i);
printf(" [%u] %s\n", (unsigned)i, uri ? uri : "");
}
输出示例:
[0] http://opcfoundation.org/UA/
[1] urn:server-host
[2] urn:my-company:plc1
[3] http://my-company.com/UA/
动态命名空间变更
某些 Server 启动后才注册命名空间 (插件式), Connect 拿到的 NamespaceArray 不全. 此时调 LoadNamespaceArray 重读:
DarraUa_Session_LoadNamespaceArray(h);
int32_t idx = DarraUa_Session_FindNamespaceIndex(h,
"urn:plugin:loaded-after-startup");
标准命名空间 (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.