软件应用2021百度seo
本文介绍如何在NodeJS环境下开发OPC UA Client,通过本文可以对OPC UA的基本概念有所了解,掌握OPC UA的本质。相关软件请登录网信智汇(wangxinzhihui.com)。
开发步骤如下:
1)首先需要安装nodejs,要求版本至少是12。
2)创建项目目录,在cmd下进入项目目录下,执行如下指令:
1)npm init
2)npm i
3)npm install node-opcua --save
3)创建client.js,输入以下代码:
/*引入相关模块*/
const { OPCUAServer, DataType, AttributeIds} = require("node-opcua");async function main() {
//a)创建OPC UA Client并连接到OPC UA Servertry {var option = {};option.securityPolicy = opcua.SecurityPolicy.None;option.securityMode = opcua.MessageSecurityMode.None;option.keepSessionAlive = true;var url = "opc.tcp://SKY-20201126GIK:4380/UADEMO";var client = opcua.OPCUAClient.create(option);await client.connect(url);} catch (err) {console.log(err);return;}if (!client) {console.log("连接失败!");return;}//b)创建会话try {var userIdentity = {};userIdentity.type = opcua.UserTokenType.Anonymous;//采用用户密码//userIdentity.type = opcua.UserTokenType.UserName;//userIdentity.userName = "XXXX";//userIdentity.password = "XXXX";session = await client.createSession(userIdentity);if (!session) {console.log("创建会话失败!");return;}console.log("创建会话成功!");} catch (err) {console.log(err);return;}//c)读取数据var nodeIdS = 'ns=1;s="pressure"'; //待写入的节点Idtry {const dataValue = await session.read({nodeId: nodeIdS,attributeId: AttributeIds.Value,});if (dataValue.statusCode !== opcua.StatusCodes.Good) {console.log("不能读取 ", nodeIdS);} else {console.log("value = ", dataValue.toString());}} catch (err) {console.log(err);return;}//d)写数据try {var nodesToWrite = [{nodeId: nodeIdS,attributeId: opcua.AttributeIds.Value,value: {value: {dataType: opcua.DataType.Double,value: 23.5}}}];session.write(nodesToWrite, function (err, statusCodes) {if (err) {console.log(' 写错误: ' + err);}});} catch (err) {console.log(err);return;}console.log(' 写数据成功!');
}main(); 作者:zhouwl72 https://www.bilibili.com/read/cv26311976/ 出处:bilibili
4)在cmd下进入项目目录,执行:node client。
运行UaExpert,查看var2写入成功。
以上为NodeJS环境下开发OPC UA Client简单教程,通过扩展可开发更多功能。更多通讯资源请登录网信智汇(wangxinzhihui.com)。