在OPC UA中,訂閱與發布模式是一種常用的通信模式,用于在客戶端和服務器之間實現實時數據傳輸。下面是一個簡單的示例,演示如何在C#中使用OPC UA庫實現訂閱與發布模式:
首先,需要引用OPC UA庫。可以通過NuGet包管理器安裝"Opc.Ua"庫。
創建一個OPC UA客戶端,并連接到OPC UA服務器:
using Opc.Ua;
using Opc.Ua.Client;
Uri serverUri = new Uri("opc.tcp://localhost:4840");
var endpoint = new ConfiguredEndpoint(null, new EndpointDescription(serverUri));
var session = Session.Create(null, endpoint, false, "OPC UA Client", 60000, new UserIdentity(new AnonymousIdentityToken()), null).Result;
session.ReturnDiagnostics = DiagnosticsMasks.All;
var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 1000 };
subscription.Create();
subscription.AddItems(new MonitoredItem(new ReadValueId { NodeId = "ns=2;i=1", AttributeId = Attributes.Value }, MonitoringMode.Reporting, new MonitoringParameters { ClientHandle = 1, QueueSize = 1, DiscardOldest = true }));
subscription.AddItems(new MonitoredItem(new ReadValueId { NodeId = "ns=2;i=2", AttributeId = Attributes.Value }, MonitoringMode.Reporting, new MonitoringParameters { ClientHandle = 2, QueueSize = 1, DiscardOldest = true }));
subscription.Notification += (sender, args) =>
{
foreach (var notification in args.MonitoredItems)
{
Console.WriteLine($"Node: {notification.StartNodeId} Value: {notification.Value}");
}
};
subscription.ApplyChanges();
subscription.SetPublishingMode(true);
session.KeepAlive += (sender, args) => session.KeepAlive();
通過以上步驟,我們實現了一個簡單的OPC UA訂閱與發布模式的示例。在實際應用中,可以根據需求添加更多訂閱項和處理邏輯。