原函數是opcUaClient.MonitorValue("ns=4;s=MAIN.d", new Action<double, Action>(MonitorTestValueFloat));服務器
因爲訂閱函的的回調函的類型是session
public void MonitorValue<T>(string tag, Action<T, Action> callback);
因此返回的函數參數中只有數值,因此在實際應用中是不夠的,另外多個訂閱就要加多個回調函數處理。爲此須要更改成
private void MonitorTestValueFloat(object clientHandle, DataValue value)
操做步驟以下:
先繼承OpcUaHelper.OpcUaClient 後添加訂閱方法 具體代碼以下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Opc.Ua;
using Opc.Ua.Client;
namespace 組態
{
/// <summary>
/// 值變化委託函數
/// </summary>
/// <param name="clientHandle">客戶處理事件</param>
/// <param name="value">變化的值</param>
public delegate void valueChanged(object clientHandle, DataValue value);
class MyOpcUa:OpcUaHelper.OpcUaClient
{
/// <summary>
/// OPCUA服務器訂閱
/// </summary>
private Subscription m_Subscription;
/// <summary>
/// 添加處理函數
/// </summary>
public void addNotificationHandle(int publishingInterval)
{
try
{
Opc.Ua.Client.Subscription innerSubscription = new Opc.Ua.Client.Subscription(this.Session.DefaultSubscription);app
innerSubscription.DisplayName = "My Subscription Name";
innerSubscription.PublishingEnabled = true;
innerSubscription.PublishingInterval = publishingInterval; // in milliseconds.
innerSubscription.KeepAliveCount = 10; // 10*UaRefreshRate = 5s if UaRefreshRate = 500
innerSubscription.LifetimeCount = 100; // UaRefreshRate*100 = 50s if UaRefreshRate = 500;
innerSubscription.MaxNotificationsPerPublish = 100;tcp
//將訂閱與會話關聯起來
this.Session.AddSubscription(innerSubscription);函數
// Call the server and create the subscription.
//調用服務器並建立訂閱。
innerSubscription.Create();ui
// At this point the subscription is sending publish requests at the keep alive rate.
// Use the Notification event the session to receive updates when a publish completes.
//此時,訂閱將以保持活躍的速率發送發佈請求。
//使用通知事件會話在發佈完成時接收更新。
this.Session.Notification += new NotificationEventHandler(Session_Notification);this
m_Subscription = innerSubscription;
//m_Subscription.Session = m_Session;
//newSubscription.innerSubscription = innerSubscription;
}
catch (Exception e)
{
throw e;
}
this.Session.Notification += Session_Notification;
}
/// <summary>
/// 添加訂閱函數
/// </summary>
/// <param name="variableNodeId">節點ID</param>
/// <param name="clientHandle">客戶端對象</param>
/// <param name="callback">回調函數</param>
/// <param name="samplingRate">採樣時間.</param>
/// <param name="serverHandle">服務處理</param>
public void AddDataMonitoredItem(NodeId variableNodeId, object clientHandle, valueChanged callback, uint samplingRate, out object serverHandle)
{
serverHandle = null;spa
try
{
if (m_Subscription==null)
{
m_Subscription = new Subscription();
//m_Subscription.Session = m_Session;
}
MonitoredItem monitoredItem = (m_Subscription.DefaultItem);
ClientMonitoredItemData clientData = new ClientMonitoredItemData();
clientData.callback = callback;
clientData.clientHandle = clientHandle;code
// Monitored item settings:
monitoredItem.StartNodeId = variableNodeId;
monitoredItem.AttributeId = Attributes.Value;
monitoredItem.MonitoringMode = MonitoringMode.Reporting;
monitoredItem.SamplingInterval = (int)samplingRate; // Affects the read cycle between UA Server and data source
monitoredItem.QueueSize = 1;
monitoredItem.DiscardOldest = false;
monitoredItem.Handle = clientData;server
// Add item to subscription.
m_Subscription.AddItem(monitoredItem);
// Call the server and apply any changes to the state of the subscription or monitored items.
m_Subscription.ApplyChanges();
// Check result of add.
if (monitoredItem.Status.Error != null && StatusCode.IsBad(monitoredItem.Status.Error.StatusCode))
{
throw ServiceResultException.Create(
monitoredItem.Status.Error.StatusCode.Code,
"Creation of data monitored item failed");
}
serverHandle = monitoredItem;
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// 當服務器發佈數據時,響應從到達時,就會執行函數。
/// </summary>
/// <param name="session">The target of the event.</param>
/// <param name="e">The <see cref="Opc.Ua.Client.NotifacationEventArgs"/>Instance containing the event data.</param>
private void Session_Notification(Session session, NotificationEventArgs e)
{
NotificationMessage message = e.NotificationMessage;
// Check for keep alive.
if (message.NotificationData.Count == 0)
{
return;
}
// Get the data changes (oldest to newest).
foreach (MonitoredItemNotification datachange in message.GetDataChanges(false))
{
// Lookup the monitored item.
MonitoredItem monitoredItem = e.Subscription.FindItemByClientHandle(datachange.ClientHandle);
if (monitoredItem == null)
{
continue;
}
ClientMonitoredItemData clientData = monitoredItem.Handle as ClientMonitoredItemData;
clientData.callback(clientData.clientHandle, datachange.Value);
}
}
}
/// <summary>
/// 客戶端監控項數據
/// </summary>
public class ClientMonitoredItemData
{
/// <summary>
/// 客戶端處理對象
/// </summary>
public object clientHandle = null;
/// <summary>
/// 變化值
/// </summary>
public valueChanged callback = null;
}
}
調用方法
MyOpcUa opcUaClient = new MyOpcUa();
opcUaClient.ConnectServer("opc.tcp://localhost:4840");
opcUaClient.addNotificationHandle(1000);
object sobj = null;
//opcUaClient.MonitorValue("ns=4;s=MAIN.d", new Action<double, Action>(MonitorTestValueFloat));
opcUaClient.AddDataMonitoredItem("ns=4;s=MAIN.d", null, MonitorTestValueFloat, 1000, out sobj);
//回調處理函數
//clientHandle:用戶對象,
//value:數據值
private void MonitorTestValueFloat(object clientHandle, DataValue value) { object objv = value.Value; }