使用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", // 标准节点:ServerStatus
            attributeId: opcua.AttributeIds.Value
        });
        console.log("📊 Server Status:", serverStatus.value.value.toString());

        // 🔁 读取自定义节点(请根据实际节点修改)
        // 示例:ns=2;s=Temperature
        const 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()

相关推荐
一心赚狗粮的宇叔6 小时前
VScode常用扩展包&Node.js安装及npm包安装
vscode·npm·node.js·web
花间相见7 小时前
【AI开发】—— Ubuntu系统使用nvm管理Node.js多版本,版本切换一键搞定(实操完整版)
linux·ubuntu·node.js
嘿是我呀7 小时前
【用npm安装node时报错“npm 无法加载文件”】
前端·npm·node.js
西门吹-禅1 天前
prisma
node.js
怪兽毕设1 天前
基于SpringBoot的选课调查系统
java·vue.js·spring boot·后端·node.js·选课调查系统
心.c1 天前
Vue3+Node.js实现文件上传分片上传和断点续传【详细教程】
前端·javascript·vue.js·算法·node.js·哈希算法
roamingcode1 天前
我是如何 Vibe Coding,将 AI CLI 工具从 Node.js 迁移到 Rust 并成功发布的
人工智能·rust·node.js·github·claude·github copilot
Stream_Silver3 天前
【Node.js 安装报错解决方案:解决“A later version of Node.js is already installed”问题】
node.js
Anthony_2313 天前
基于 Vue3 + Node.js 的实时可视化监控系统实现
node.js
说给风听.3 天前
解决 Node.js 版本冲突:Windows 系统 nvm 安装与使用全指南
windows·node.js