using Opc.Ua.Client;
|
using Opc.Ua;
|
using System;
|
using Opc.Ua.Configuration;
|
|
|
namespace HH.WCS.Mobox3.DSZSH.device
|
{
|
internal class OpcUaHelper
|
{
|
private static Opc.Ua.Client.Session session;
|
|
static OpcUaHelper()
|
{
|
CreateUpcSession();
|
}
|
|
/// <summary>
|
/// 连接OPC服务
|
/// </summary>
|
internal static async void CreateUpcSession()
|
{
|
try
|
{
|
// 创建一个应用配置对象,用于设置应用名称、唯一标识、类型、证书和安全策略
|
var config = new ApplicationConfiguration()
|
{
|
ApplicationName = "MyClient",
|
ApplicationUri = Utils.Format(@"urn:{0}:MyClient", System.Net.Dns.GetHostName()),
|
ApplicationType = ApplicationType.Client,
|
SecurityConfiguration = new SecurityConfiguration
|
{
|
ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = "MyClientSubjectName" },
|
TrustedIssuerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Certificate Authorities" },
|
TrustedPeerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Applications" },
|
RejectedCertificateStore = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\RejectedCertificates" },
|
AutoAcceptUntrustedCertificates = true,
|
RejectSHA1SignedCertificates = false,
|
MinimumCertificateKeySize = 1024,
|
NonceLength = 32,
|
},
|
TransportConfigurations = new TransportConfigurationCollection(),
|
TransportQuotas = new TransportQuotas { OperationTimeout = 15000 },
|
ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 },
|
TraceConfiguration = new TraceConfiguration()
|
};
|
|
// 验证应用配置对象
|
await config.Validate(ApplicationType.Client);
|
|
// 设置证书验证事件,用于自动接受不受信任的证书
|
if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates)
|
{
|
config.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); };
|
}
|
|
// 创建一个应用实例对象,用于检查证书
|
var application = new ApplicationInstance(config);
|
|
// 检查应用实例对象的证书
|
bool check = await application.CheckApplicationInstanceCertificate(false, 2048);
|
// 创建一个会话对象,用于连接到 OPC UA 服务器
|
EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint("opc.tcp://172.16.57.41:4840", true);
|
EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(config);
|
ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);
|
session = await Session.Create(config, endpoint, false, false, "DataCollector", 60000, new UserIdentity(), null);
|
if (session != null && session.Connected)
|
{
|
Console.WriteLine("The session is connected to the OPC UA server.");
|
LogHelper.Info($"创建OPC连接成功", "OPC");
|
}
|
else
|
{
|
Console.WriteLine("The session is not connected to the OPC UA server.");
|
LogHelper.Info($"创建OPC连接失败", "OPC");
|
}
|
}
|
catch (Exception e)
|
{
|
LogHelper.Info($"连接OPC服务异常" + e.Message, "OPC");
|
}
|
}
|
|
/// <summary>
|
/// 读取OPC节点数据
|
/// </summary>
|
/// <param name="nodeId"></param>
|
internal static object ReadOpcValue(string nodeId)
|
{
|
try
|
{
|
if (session != null && session.Connected)
|
{
|
// 读取数据节点
|
DataValue item = session.ReadValue(nodeId: nodeId);
|
LogHelper.Info($"OPC读取:nodeid:{nodeId},value:{item.Value}", "OPC");
|
return item.Value;
|
}
|
else
|
{
|
Console.WriteLine("The session is not connected to the OPC UA server.");
|
LogHelper.Info($"OPC连接失败", "OPC");
|
CreateUpcSession();
|
}
|
|
}
|
catch (Exception e)
|
{
|
|
LogHelper.Info($"读取OPC数据异常" + e.Message, "OPC");
|
}
|
return null;
|
}
|
|
/// <summary>
|
/// 写OPC节点数据
|
/// </summary>
|
/// <param name="nodeId"></param>
|
/// <param name="val"></param>
|
internal static void WriteOpcValue(string nodeId,bool val)
|
{
|
try
|
{
|
if (session != null && session.Connected)
|
{
|
// 写入数据到节点
|
WriteValue writeValue = new WriteValue
|
{
|
NodeId = new NodeId(nodeId),
|
AttributeId = Attributes.Value,
|
Value = new DataValue(val)
|
};
|
|
StatusCodeCollection results;
|
DiagnosticInfoCollection diagnosticInfos;
|
session.Write(null, new WriteValueCollection { writeValue }, out results, out diagnosticInfos);
|
Console.WriteLine($"Write Status for {nodeId}: {results[0]}");
|
LogHelper.Info($"OPC写入:nodeid:{nodeId},value:{val}", "OPC");
|
}
|
else
|
{
|
Console.WriteLine("The session is not connected to the OPC UA server.");
|
LogHelper.Info($"OPC连接失败", "OPC");
|
CreateUpcSession();
|
}
|
|
}
|
catch (Exception e)
|
{
|
LogHelper.Info($"写入OPC数据异常" + e.Message, "OPC");
|
}
|
}
|
|
/// <summary>
|
/// 写OPC节点数据
|
/// </summary>
|
/// <param name="nodeId"></param>
|
/// <param name="val"></param>
|
internal static void WriteOpcValue(string nodeId, int val)
|
{
|
try
|
{
|
if (session != null && session.Connected)
|
{
|
// 写入数据到节点
|
WriteValue writeValue = new WriteValue
|
{
|
NodeId = new NodeId(nodeId),
|
AttributeId = Attributes.Value,
|
Value = new DataValue(val)
|
};
|
|
StatusCodeCollection results;
|
DiagnosticInfoCollection diagnosticInfos;
|
session.Write(null, new WriteValueCollection { writeValue }, out results, out diagnosticInfos);
|
Console.WriteLine($"Write Status for {nodeId}: {results[0]}");
|
LogHelper.Info($"OPC写入:nodeid:{nodeId},value:{val}", "OPC");
|
}
|
else
|
{
|
Console.WriteLine("The session is not connected to the OPC UA server.");
|
LogHelper.Info($"OPC连接失败", "OPC");
|
CreateUpcSession();
|
}
|
|
}
|
catch (Exception e)
|
{
|
LogHelper.Info($"写入OPC数据异常" + e.Message, "OPC");
|
}
|
}
|
}
|
}
|