使用Node.js连接 OPC UA Server
使用 Node.js 连接 OPC UA Server,最常用的库是 node-opcua。这是一个功能完整的 OPC UA 栈,支持客户端和服务器开发。
✅ 目标
使用 Node.js 编写一个 OPC UA 客户端,连接到 OPC UA Server,读取指定节点的数据。
🛠 步骤 1:初始化项目并安装 node-opcua
# 创建项目目录
mkdir opcua-client-demo
cd opcua-client-demo# 初始化 package.json
npm init -y# 安装 node-opcua(包含客户端功能)
npm install node-opcua
⚠️ 注意:
node-opcua包较大(~100MB),因为它内置了完整的 OPC UA 协议栈。
📜 步骤 2:编写 OPC UA 客户端代码
创建文件 client.js:
// client.js
const opcua = require("node-opcua");// =============== 配置 ===============
const endpointUrl = "opc.tcp://127.0.0.1:4840"; // 替换为你的 OPC UA Server 地址// 创建 OPC UA 客户端
const client = new opcua.OPCUAClient({connectionStrategy: {maxRetry: 3,initialDelay: 1000,maxDelay: 5000},keepSessionAlive: true
});// =============== 主函数 ===============
async function main() {try {console.log("正在连接到 OPC UA Server:", endpointUrl);await client.connect(endpointUrl);console.log("✅ 连接成功!");// 创建会话const session = await client.createSession();console.log("🔐 会话已创建");// 读取服务器状态节点(示例)const serverStatus = await session.read({nodeId: "i=2258", // 标准节点:ServerStatusattributeId: opcua.AttributeIds.Value});console.log("📊 Server Status:", serverStatus.value.value.toString());// 🔁 读取自定义节点(请根据实际节点修改)// 示例:ns=2;s=Temperatureconst nodeId = "ns=2;s=Temperature"; // ← 修改为你要读取的节点const dataValue = await session.read({nodeId: nodeId,attributeId: opcua.AttributeIds.Value});if (dataValue.statusCode.name === "Good") {console.log(`🟢 节点 ${nodeId} 的值:`, dataValue.value.value);} else {console.warn(`🟡 读取失败:`, dataValue.statusCode.name);}// 🔁 可选:订阅数据变化(实时更新)await subscribeToNode(session, nodeId);// 保持连接(用于监听订阅)console.log("💡 程序保持运行,按 Ctrl+C 退出");setTimeout(async () => {await session.close();await client.disconnect();console.log("👋 连接已关闭");}, 60 * 1000); // 60秒后自动关闭} catch (err) {console.error("❌ 错误:", err.message);await client.disconnect().catch(() => {});process.exit(1);}
}// =============== 订阅数据变化 ===============
async function subscribeToNode(session, nodeId) {const subscription = await session.createSubscription2({requestedPublishingInterval: 1000,requestedLifetimeCount: 10,requestedMaxKeepAliveCount: 10,maxNotificationsPerPublish: 10,publishingEnabled: true,priority: 10});const monitoredItem = subscription.monitor({nodeId: nodeId,attributeId: opcua.AttributeIds.Value},{samplingInterval: 1000,filter: null,queueSize: 1},opcua.TimestampsToReturn.Both);monitoredItem.on("changed", (dataValue) => {console.log(`📈 实时数据更新:`, dataValue.value.value);});console.log(`📌 已订阅节点 ${nodeId},每秒更新一次`);
}// =============== 启动程序 ===============
main();
🌐 步骤 3:运行客户端
node client.js
示例输出:
正在连接到 OPC UA Server: opc.tcp://127.0.0.1:4840
✅ 连接成功!
🔐 会话已创建
📊 Server Status: ServerState.Running
🟢 节点 ns=2;s=Temperature 的值: 23.5
📌 已订阅节点 ns=2;s=Temperature,每秒更新一次
📈 实时数据更新: 23.6
📈 实时数据更新: 23.7
...
🧩 常见 OPC UA Server 测试环境
如果你没有现成的 OPC UA Server,可以用以下方式测试:
✅ 1. 使用 node-opcua 自带的简单服务器(测试用)
npx node-opcua-server
默认地址:opc.tcp://localhost:4840/UAServer
✅ 2. 使用 UA Simulation Server(Prosys 或 Unified Automation 提供)
- Prosys OPC UA Simulation Server
- 免费版提供大量测试节点,如:
- ns=3;s=Random.Int32
- ns=3;s=Sinusoid
 
✅ 3. 工业设备或 SCADA 系统
如:西门子 S7-1500、WinCC、Ignition、Kepware 等。
🔐 安全策略说明
如果 Server 启用了安全策略(如 Basic256Sha256),你需要在客户端配置:
const client = new opcua.OPCUAClient({securityMode: opcua.MessageSecurityMode.SignAndEncrypt,securityPolicy: opcua.SecurityPolicy.Basic256Sha256,certificateFile: "path/to/client_certificate.pem",privateKeyFile: "path/to/client_private_key.pem"
});
初学者可先关闭 Server 的安全策略进行测试。
📚 参考文档
- 📚 node-opcua官方文档
- 📚 OPC UA 基础教程
- 📚 GitHub 示例:node-opcua/samples
✅ 总结
| 步骤 | 命令/操作 | 
|---|---|
| 安装库 | npm install node-opcua | 
| 连接 Server | client.connect(endpointUrl) | 
| 创建会话 | client.createSession() | 
| 读取节点 | session.read({nodeId: "ns=2;s=Tag1"}) | 
| 订阅数据 | subscription.monitor() | 
| 关闭连接 | session.close()+client.disconnect() | 
