本人第一次接触OPCUA,如有不对的地方望指正,获取的是公司的OPCUA服务器的数据
方式一:
测试环境:
window11
vs2022
OPCFoundation.NetStandard.Opc.Ua
.net framework 4.8 (2025-06-23 经过测试,.net8也可以使用这套.net framework的代码并成功读取到数据,版本也是选择1.5.376.213)
测试环境如下:
1 新建.net framework 4.8的控制台项目,项目名称为OPCDemo3
2 在nuget中安装OPCFoundation.NetStandard.Opc.Ua,版本选择1.5.376.213,如下图:
3 编写代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Configuration;
namespace OPCDemo3
{internal class Program{static void Main(string[] args){string endpointUrl = "opc.tcp://ip地址:4840";//节点Id,根据实际情况填写string nodeId = "ns=4;s=|var|CODESYS Control Win V3 x64.Application.Para.PLC_Inf.wHeatBeat";// 创建应用配置var config = new ApplicationConfiguration(){ApplicationName = "OPCDemo2",ApplicationType = ApplicationType.Client,SecurityConfiguration = new SecurityConfiguration{ApplicationCertificate = new CertificateIdentifier(),AutoAcceptUntrustedCertificates = true},TransportConfigurations = new TransportConfigurationCollection(),TransportQuotas = new TransportQuotas { OperationTimeout = 15000 },ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 }};config.Validate(ApplicationType.Client);// 创建OPC UA会话var selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointUrl, false);var endpointConfiguration = EndpointConfiguration.Create(config);var endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration);var session = Session.Create(config, endpoint, false, "OPCDemo2", 60000, null, null).Result;Console.WriteLine("打开成功");// 读取节点DataValue value = session.ReadValue(nodeId);if (StatusCode.IsGood(value.StatusCode)){ushort wHeatBeat = Convert.ToUInt16(value.Value);Console.WriteLine($"wHeatBeat:{wHeatBeat}");}else{Console.WriteLine("读取失败");}Console.ReadLine();}}
}
4 程序运行结果如下:
方式二:
测试环境:
window11
vs2022
SuperPLC.OPCUA
.net 8
测试步骤如下:
1 新建.net 8控制台项目,名称为OPCDemo2
2 在Nuget中安装OpcUaHelper,版本选择2.2.1,同时安装SuperPLC.OPCUA,版本选择:1.1.0
但在安装SuperPLC.OPCUA时,很奇怪,Nuget程序包管理界面搜不出来,如下图:
只能通过nuget控制台安装,命令如下:
NuGet\Install-Package SuperPLC.OPCUA -Version 1.1.0
3 编辑代码如下:
// See https://aka.ms/new-console-template for more informationusing SuperPLC.OPCUA;
//节点Id,根据实际情况填写
string _prefixPLCApp = $@"ns=4;s=|var|CODESYS Control Win V3 x64.Application.";Plc plc = new Plc("ip地址");
bool ret = plc.Open();
if (!ret)
{Console.WriteLine("打开失败");return;
}
plc.TryRead($"{_prefixPLCApp}Para.PLC_Inf.wHeatBeat", out ushort wHeatBeat);Console.WriteLine($"wHeatBeat:{wHeatBeat}");Console.WriteLine("打开成功");
Console.ReadLine();
4 运行结果如下: