要在C#中實現(xiàn)OPC UA訂閱功能,您需要使用OPC UA客戶端庫。以下是一個簡單的示例,展示了如何使用OPC UA客戶端庫實現(xiàn)訂閱功能:
首先,安裝OPC UA客戶端庫。您可以使用NuGet包管理器安裝OPCFoundation.NetStandard.Opc.Ua.Client
庫。在Visual Studio中,右鍵單擊項目,然后選擇“管理NuGet程序包”。在“瀏覽”選項卡中搜索并安裝OPCFoundation.NetStandard.Opc.Ua.Client
庫。
創(chuàng)建一個新的C#控制臺應用程序項目。
在Program.cs
文件中,添加以下命名空間引用:
using Opc.Ua;
using Opc.Ua.Client;
using System;
using System.Threading.Tasks;
Main
方法中,添加以下代碼以連接到OPC UA服務器并創(chuàng)建一個會話:// 設置OPC UA服務器的URL
string serverUrl = "opc.tcp://localhost:4840";
// 創(chuàng)建一個應用程序配置
ApplicationConfiguration config = new ApplicationConfiguration();
config.ApplicationName = "OPC UA Client";
config.ApplicationType = ApplicationType.Client;
config.SecurityConfiguration = new SecurityConfiguration { ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = Utils.Format(@"CN={0}, DC={1}", config.ApplicationName, Environment.UserDomainName) }, 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" } };
config.TransportConfigurations = new TransportConfigurationCollection();
config.TransportQuotas = new TransportQuotas { OperationTimeout = 15000 };
// 創(chuàng)建一個會話
Session session = null;
try
{
session = Session.Create(config, new ConfiguredEndpoint(null, new EndpointDescription(serverUrl)), false, "", 60000, null, null).Result;
}
catch (Exception ex)
{
Console.WriteLine("連接失敗: " + ex.Message);
return;
}
Main
方法中,添加以下代碼以創(chuàng)建一個訂閱并添加一個監(jiān)視項:// 創(chuàng)建一個訂閱
Subscription subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 1000 };
// 添加一個監(jiān)視項
NodeId nodeId = new NodeId("ns=2;s=MyVariable"); // 更改為您的變量節(jié)點ID
MonitoredItem monitoredItem = new MonitoredItem(subscription.DefaultItem) { StartNodeId = nodeId, AttributeId = Attributes.Value };
monitoredItem.Notification += OnNotification;
subscription.AddItem(monitoredItem);
// 應用訂閱更改
subscription.ApplyChanges();
OnNotification
的事件處理程序,該處理程序將在收到通知時調(diào)用:private static void OnNotification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
{
foreach (var notification in e.NotificationValue.NotificationData)
{
if (notification is DataChangeNotification dataChangeNotification)
{
foreach (var monitoredItemNotification in dataChangeNotification.MonitoredItems)
{
Console.WriteLine($"變量值已更改: {monitoredItemNotification.ItemToMonitor.NodeId} - {monitoredItemNotification.Value.WrappedValue}");
}
}
}
}
Main
方法中,添加以下代碼以保持應用程序運行,直到用戶按下Enter鍵:Console.WriteLine("按Enter鍵退出...");
Console.ReadLine();
// 關閉會話
if (session != null)
{
session.Close();
session.Dispose();
}
現(xiàn)在,您已經(jīng)創(chuàng)建了一個簡單的C# OPC UA客戶端,它可以連接到OPC UA服務器并訂閱變量的更改。當變量值發(fā)生更改時,OnNotification
事件處理程序將被調(diào)用,并在控制臺上顯示新值。