当前位置: 首页 > news >正文

使用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
连接 Serverclient.connect(endpointUrl)
创建会话client.createSession()
读取节点session.read({nodeId: "ns=2;s=Tag1"})
订阅数据subscription.monitor()
关闭连接session.close() + client.disconnect()

http://www.dtcms.com/a/549133.html

相关文章:

  • h5游戏免费下载:保护堆芯
  • 怎么看网站关键词排名恩施网站制作
  • Jenkins 持续集成与部署
  • 企业查询网站有哪些深圳工业产品设计公司
  • 解析平面卷积/pytorch的nn.Conv2d的计算步骤,in_channels与out_channels如何计算而来
  • 医疗器械经营许可证识别技术通过OCR与AI技术实现资质信息自动提取,显著提升行业效率与合规管理水平
  • Lombok 不生效 —— 从排查到可运行 Demo(含实战解析)
  • 【自然语言处理】预训练02:近似训练
  • 具身智能革命:富唯智能如何用“认知机器人”重塑柔性智造新纪元
  • 孤能子视角:文明演化的适配性考验——从EIS理论看中美技术路径分野
  • itunes礼品卡兑换【完整协议方案】
  • High Rank Adaption系列文章
  • wordpress 网站迁移如何做网站霸屏
  • Rust 中 Raft 协议的云原生深度集成与实践最佳实践
  • html css js网页制作成品——掌心电视剧HTML+CSS网页设计(4页)附源码
  • 基于用户的协同过滤算法实现小说推荐算法
  • 速卖通新客优惠券采购:砍单率高的核心原因
  • 【11408学习记录】考研数学概率论核心突破:一维随机变量函数分布——公式法 分布函数法精讲!​
  • Flutter 网络通信协议:从原理到实战,选对协议让 APP 飞起来
  • 【机器学习入门】9.2:感知机的工作原理 —— 从模型结构到实战分类
  • Flutter---个人信息(3)---实现修改性别
  • 做个网站需要什么制作软件的网站
  • 河北手机响应式网站建设设计企业门户网站管理制度
  • Docker简介与优豆云环境搭建
  • 后端面试实战:手写 Java 线程池核心逻辑,解释核心参数的作用
  • 免费做数学题的网站大连装修公司排名榜
  • Spring Al学习5 :聊天模型 API
  • 分布式锁深度解析:从架构本质到生产实践
  • 浏览器就是画板!PaintBoard让创意灵感不再受设备限制
  • 网站建设要学哪种计算机语言小学生一分钟新闻播报