温馨提示×

OPC UA C#客户端如何实现

c#
小樊
192
2024-08-08 22:22:45
栏目: 编程语言

在C#中实现OPC UA客户端,可以使用OPC Foundation提供的开源库UA-.NETStandard。下面是一个简单的示例代码,演示如何创建一个OPC UA客户端并连接到服务器。

首先,你需要在项目中安装UA-.NETStandard库。可以通过NuGet包管理器搜索并安装"Opc.Ua"包。

接下来,创建一个OPC UA客户端类,并实现连接到服务器的方法:

using Opc.Ua;
using Opc.Ua.Client;

public class OpcUaClient
{
    private Session session;

    public async Task Connect(string endpointUrl)
    {
        var endpoint = new ConfiguredEndpoint(null, new EndpointDescription
        {
            EndpointUrl = endpointUrl
        });

        var endpointConfiguration = EndpointConfiguration.Create();
        var endpointConfiguration.SecurityConfiguration = new SecurityConfiguration
        {
            ApplicationCertificate = new CertificateIdentifier(),
            TrustedPeerCertificates = new CertificateTrustList(),
            RejectSHA1SignedCertificates = false
        };

        session = await Session.Create(
            configuration: endpointConfiguration,
            endpoint: endpoint,
            updateBeforeConnect: false,
            checkDomain: false,
            sessionName: "OPC UA Client",
            sessionTimeout: 60000,
            identity: null,
            preferredLocales: null
        );

        session.KeepAliveInterval = 10000;
        session.KeepAlive += Session_KeepAlive;
    }

    private void Session_KeepAlive(Session session, KeepAliveEventArgs e)
    {
        Console.WriteLine("KeepAlive received: " + e.CurrentState.ToString());
    }

    public void Disconnect()
    {
        session?.Close();
        session?.Dispose();
    }
}

在上面的示例代码中,Connect方法用于连接到指定的OPC UA服务器,Disconnect方法用于断开连接。在Connect方法中,首先创建一个ConfiguredEndpoint对象,指定服务器的地址;然后创建一个Session对象,连接到服务器,并设置一些参数,如会话名称和保持活动间隔。

接着,可以使用上面的OPC UA客户端类来实现对服务器的读写操作。例如,读取服务器上的变量值:

public async Task ReadValue(string nodeId)
{
    var nodeToRead = new ReadValueId
    {
        NodeId = nodeId,
        AttributeId = Attributes.Value
    };

    var nodesToRead = new List<ReadValueId> { nodeToRead };

    var response = await session.ReadValues(null, nodesToRead);

    foreach (var result in response)
    {
        Console.WriteLine($"Node {result.Value.Source.ToString()} value: {result.Value.Value}");
    }
}

以上是一个简单的示例,演示了如何使用OPC UA-.NETStandard库在C#中实现OPC UA客户端。在实际应用中,你可能需要根据服务器的具体配置和要求进行更多的定制。

0