使用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()

相关推荐
学习3人组4 小时前
Node.js模块化开发课堂案例
node.js
艾克马斯奎普特4 小时前
从平平无奇的 npm create 开始,一张图带你完整揭秘 npm 包命令执行机制
前端·npm·node.js
木木子999910 小时前
Next.js, Node.js, JavaScript, TypeScript 的关系
javascript·typescript·node.js
柑橘乌云_10 小时前
学习记录-package.json的scripts添加参数的方式有那些
前端·学习·node.js·json
T___T1 天前
AIGC 实战:用 pnpm 提速 + Node.js 调用 OpenAI 🤖
面试·node.js
qq. 28040339841 天前
nestjs引篇
后端·node.js·nestjs
茄汁面1 天前
Angular(TypeScript ) 中基于 ExcelJS 实现导入模板下载功能(带样式与数据验证)
前端·javascript·node.js
浏览器API调用工程师_Taylor1 天前
日报自动化实战:告别手动复制粘贴
前端·javascript·node.js