OpcUa作为客户端测试代码
1、打开服务端,使用开源代码GitHub - OPCFoundation/UA-.NETStandard: OPC Unified Architecture .NET Standard中Quickstarts.ReferenceServer启动服务端
2、运行打印结果如下
测试标准OPC UA
Session_KeepAlive
2023/9/27 21:09:39Connected, loading complex type system.
ReadNode查询到这个Node的属性
data value : 55
3、测试启动
MyOpcUaServer myOpcUaServer = new MyOpcUaServer();
4、连接服务端测试类,引用NuGet:OPCFoundation.NetStandard.Opc.Ua
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Configuration;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Client.ComplexTypes;
using Org.BouncyCastle.Asn1.X509;
namespace 标准OPC_UA
{
internal class MyOpcUaClient
{
public string OpcUaName = "My Opc ua";
private ApplicationConfiguration m_configuration;
private Session m_session;
private SessionReconnectHandler m_reconnectHandler;
private CertificateValidationEventHandler m_CertificateValidation;
//private Dictionary m_endpoints;
public MyOpcUaClient(string uri = "opc.tcp://lplsszsz4435n:62541/Quickstarts/ReferenceServer", bool useSecurity = false, int sessionTimeout = 1000) {
InitConfiguration();
// 连接测试
Connect(uri, useSecurity, sessionTimeout);
//Read();
ConfiguredEndpointCollection configuredEndpoints = new ConfiguredEndpointCollection();
List list = configuredEndpoints.GetEndpoints("opc.tcp://lplsszsz4435n:62541/Quickstarts/ReferenceServer");
if (m_session != null)
{
// 读取属性和值
Node node = m_session.ReadNode("ns=7;s=Alarms.AnalogSource");
if (node != null)
{
Console.WriteLine("ReadNode查询到这个Node的属性");
}
WriteValueCollection nodesToWrite = new WriteValueCollection();
WriteValue writeValue = new WriteValue();
writeValue.NodeId = "ns=7;s=Alarms.AnalogSource"; // 看下属性是否是可写
writeValue.AttributeId = 13u; // 不定义无法正常设置
writeValue.Value = new DataValue(new Variant(55)); // 设置值
nodesToWrite.Add(writeValue);
StatusCodeCollection statusCodes = new StatusCodeCollection();
DiagnosticInfoCollection diagnosticInfos = new DiagnosticInfoCollection();
ResponseHeader rep = m_session.Write(null, nodesToWrite, out statusCodes, out diagnosticInfos);
DataValue value = m_session.ReadValue("ns=7;s=Alarms.AnalogSource");
if(value != null)
{
Console.WriteLine("data value : " + value.ToString());
}
}
//TranslateBrowsePathsToNodeIds();
}
void InitConfiguration()
{
var certificateValidator = new CertificateValidator();
certificateValidator.CertificateValidation += (sender, eventArgs) =>
{
if (ServiceResult.IsGood(eventArgs.Error))
eventArgs.Accept = true;
else if (eventArgs.Error.StatusCode.Code == StatusCodes.BadCertificateUntrusted)
eventArgs.Accept = true;
else
throw new Exception(string.Format("Failed to validate certificate with error code {0}: {1}", eventArgs.Error.Code, eventArgs.Error.AdditionalInfo));
};
SecurityConfiguration securityConfigurationcv = new SecurityConfiguration
{
AutoAcceptUntrustedCertificates = true,
RejectSHA1SignedCertificates = false,
MinimumCertificateKeySize = 1024,
};
certificateValidator.Update(securityConfigurationcv);
// Build the application configuration
var configuration = new ApplicationConfiguration
{
ApplicationName = OpcUaName,
ApplicationType = ApplicationType.Client,
CertificateValidator = certificateValidator,
ApplicationUri = "urn:MyClient", //Kepp this syntax
ProductUri = "OpcUaClient",
ServerConfiguration = new ServerConfiguration
{
MaxSubscriptionCount = 100000,
MaxMessageQueueSize = 1000000,
MaxNotificationQueueSize = 1000000,
MaxPublishRequestCount = 10000000,
},
SecurityConfiguration = new SecurityConfiguration
{
AutoAcceptUntrustedCertificates = true,
RejectSHA1SignedCertificates = false,
MinimumCertificateKeySize = 1024,
SuppressNonceValidationErrors = true,
ApplicationCertificate = new CertificateIdentifier
{
StoreType = CertificateStoreType.X509Store,
StorePath = "CurrentUser\\My",
SubjectName = OpcUaName,
},
TrustedIssuerCertificates = new CertificateTrustList
{
StoreType = CertificateStoreType.X509Store,
StorePath = "CurrentUser\\Root",
},
TrustedPeerCertificates = new CertificateTrustList
{
StoreType = CertificateStoreType.X509Store,
StorePath = "CurrentUser\\Root",
}
},
TransportQuotas = new TransportQuotas
{
OperationTimeout = 6000000,
MaxStringLength = int.MaxValue,
MaxByteStringLength = int.MaxValue,
MaxArrayLength = 65535,
MaxMessageSize = 419430400,
MaxBufferSize = 65535,
ChannelLifetime = -1,
SecurityTokenLifetime = -1
},
ClientConfiguration = new ClientConfiguration
{
DefaultSessionTimeout = -1,
MinSubscriptionLifetime = -1,
},
DisableHiResClock = true
};
configuration.Validate(ApplicationType.Client);
m_configuration = configuration;
}
async void Connect(string uri = "opc.tcp://lplsszsz4435n:62541/Quickstarts/ReferenceServer", bool useSecurity = false, int sessionTimeout = 1000)
{
if (m_session != null)
{
m_session.KeepAlive -= Session_KeepAlive;
m_session.Close(10000);
m_session = null;
}
// select the best endpoint.
var endpointDescription = CoreClientUtils.SelectEndpoint(m_configuration, uri, useSecurity, sessionTimeout);
var endpointConfiguration = EndpointConfiguration.Create(m_configuration);
var endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);
m_session = await Session.Create(
m_configuration,
//connection,
endpoint,
false,
//true, //DisableDomainCheck
"Quickstart Reference Client", //(String.IsNullOrEmpty(SessionName)) ? m_configuration.ApplicationName : SessionName,
(uint)sessionTimeout,
null, //UserIdentity,
null); //PreferredLocales
// set up keep alive callback.
m_session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive);
// set up reconnect handler.
m_reconnectHandler = new SessionReconnectHandler(true, 10 * 1000);
try
{
Console.WriteLine(DateTime.Now + "Connected, loading complex type system.");
var typeSystemLoader = new ComplexTypeSystem(m_session);
await typeSystemLoader.Load();
}
catch (Exception e)
{
Console.WriteLine(DateTime.Now + "Connected, failed to load complex type system.");
Utils.LogError(e, "Failed to load complex type system.");
}
}
bool Read()
{
DataValueCollection dataValues = new DataValueCollection();
DiagnosticInfoCollection diagnosticInfos = new DiagnosticInfoCollection();
ResponseHeader resp = m_session.Read(null, 0, TimestampsToReturn.Both, null, out dataValues, out diagnosticInfos);
return true;
}
void TranslateBrowsePathsToNodeIds()
//RequestHeader requestHeader,
//BrowsePathCollection browsePaths)
//out BrowsePathResultCollection results,
//out DiagnosticInfoCollection diagnosticInfos)
{
//m_session.TranslateBrowsePathsToNodeIds(null, "opc.tcp://lplsszsz4435n:62541/Quickstarts/ReferenceServer");
BrowsePathResultCollection results;
DiagnosticInfoCollection diagnosticInfos;
var startNodeId = new NodeId(Objects.ObjectsFolder);
var browsePaths1 = new BrowsePathCollection
{
new BrowsePath
{
RelativePath = RelativePath.Parse("Objects", m_session.TypeTree, m_session.NamespaceUris, m_session.NamespaceUris),
StartingNode = startNodeId
}
};
ResponseHeader resp = m_session.TranslateBrowsePathsToNodeIds(null, browsePaths1, out results, out diagnosticInfos);
}
private void ChangeSession(Session session, bool refresh)
{
//m_session = session;
//if (AttributesControl != null)
//{
// AttributesControl.ChangeSession(session);
//}
//BrowseTV.Nodes.Clear();
//if (m_session != null)
//{
// INode node = m_session.NodeCache.Find(m_rootId);
// if (node != null)
// {
// TreeNode root = new TreeNode(node.ToString());
// root.ImageIndex = ClientUtils.GetImageIndex(m_session, node.NodeClass, node.TypeDefinitionId, false);
// root.SelectedImageIndex = ClientUtils.GetImageIndex(m_session, node.NodeClass, node.TypeDefinitionId, true);
// ReferenceDescription reference = new ReferenceDescription();
// reference.NodeId = node.NodeId;
// reference.NodeClass = node.NodeClass;
// reference.BrowseName = node.BrowseName;
// reference.DisplayName = node.DisplayName;
// reference.TypeDefinition = node.TypeDefinitionId;
// root.Tag = reference;
// root.Nodes.Add(new TreeNode());
// BrowseTV.Nodes.Add(root);
// root.Expand();
// BrowseTV.SelectedNode = root;
// }
//}
}
private void Session_KeepAlive(ISession session, KeepAliveEventArgs e)
{
Console.WriteLine("Session_KeepAlive");
}
}
}