C# OPC UA客户端代码示例:浏览节点、读取数据、订阅变量

以下是一个简单的C# OPC UA客户端代码示例,演示了如何连接到OPC UA服务器、浏览节点、读取数据以及订阅变量:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Opc.Ua;
using Opc.Ua.Client;

namespace OPCClient
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建一个 OPC UA 客户端实例
            var client = new Opc.Ua.Client.Session();

            // 连接到 OPC UA 服务器
            client.Connect(new Uri('opc.tcp://localhost:4840'));

            // 浏览 OPC UA 服务器上的节点
            var browseRequest = new BrowseRequest
            {
                NodesToBrowse = new[] { new BrowseDescription { NodeId = NodeId.Parse(ObjectIds.ObjectsFolder), BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), IncludeSubtypes = true, NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method } },
                RequestedMaxReferencesPerNode = 0,
                View = new ViewDescription { ViewId = NodeId.DefaultView, Timestamp = DateTime.MinValue }
            };
            var browseResponse = client.Browse(browseRequest);

            // 打印节点的名称和类型
            foreach (var result in browseResponse.Results)
            {
                foreach (var reference in result.References)
                {
                    Console.WriteLine('{0} ({1})', reference.DisplayName, reference.NodeClass);
                }
            }

            // 读取节点的值
            var readRequest = new ReadRequest
            {
                NodesToRead = new[] { new ReadValueId { NodeId = NodeId.Parse('ns=2;s=MyVariable'), AttributeId = Attributes.Value } },
                MaxAge = 0,
                TimestampsToReturn = TimestampsToReturn.Both
            };
            var readResponse = client.Read(readRequest);
            var value = readResponse.Results[0].GetValueOrDefault<string>();
            Console.WriteLine('MyVariable: {0}', value);

            // 订阅节点的值变化
            var subscription = new Subscription(client.DefaultSubscription) { PublishingInterval = 1000 };
            var monitoredItem = new MonitoredItem(subscription.DefaultItem) { StartNodeId = NodeId.Parse('ns=2;s=MyVariable'), AttributeId = Attributes.Value };
            monitoredItem.Notification += OnNotification;
            subscription.AddItem(monitoredItem);
            client.AddSubscription(subscription);
            subscription.Create();

            // 等待用户按下 Enter 键
            Console.ReadLine();

            // 取消订阅并关闭客户端
            subscription.Delete();
            client.RemoveSubscription(subscription);
            client.Disconnect();
        }

        static void OnNotification(MonitoredItem item, MonitoredItemNotificationEventArgs e)
        {
            Console.WriteLine('{0}: {1}', item.StartNodeId, e.NotificationValue);
        }
    }
}

代码说明:

  1. 连接到OPC UA服务器: 代码使用opc.tcp://localhost:4840地址连接到本地服务器。
  2. 浏览节点: 使用BrowseRequest浏览服务器上的节点,并打印节点的显示名称和节点类型。
  3. 读取数据: 使用ReadRequest读取名为'MyVariable'的变量的值。
  4. 订阅变量: 使用SubscriptionMonitoredItem订阅'MyVariable'变量的值变化,并在值变化时打印新值。
  5. 取消订阅和断开连接: 代码最后取消订阅并断开与服务器的连接。

这段代码提供了一个简单的C# OPC UA客户端示例,您可以根据自己的需求修改和扩展这段代码。

C# OPC UA客户端代码示例:浏览节点、读取数据、订阅变量

原文地址: https://www.cveoy.top/t/topic/jzq3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录