QuickOPC User's Guide and Reference
SubscribeDataChange(IEasyUAClient,UAEndpointDescriptor,UANodeDescriptor,Int32,UADataChangeFilter) Method
Example 



OpcLabs.EasyOpcUA Assembly > OpcLabs.EasyOpc.UA Namespace > IEasyUAClientExtension Class > SubscribeDataChange Method : SubscribeDataChange(IEasyUAClient,UAEndpointDescriptor,UANodeDescriptor,Int32,UADataChangeFilter) Method
The client object that will perform the operation.
Endpoint descriptor. Identifies the OPC-UA server.
Node descriptor. Identifies the node in OPC server's address space.
The sampling interval (in milliseconds) indicates the fastest rate at which the Server should sample its underlying source for data changes.
The data change filter.
Subscribe to a data change. Specify an endpoint descriptor, node id, sampling interval, and a data change filter (e.g. an absolute deadband value).
Syntax
'Declaration
 
<ExtensionAttribute()>
Public Overloads Shared Function SubscribeDataChange( _
   ByVal client As IEasyUAClient, _
   ByVal endpointDescriptor As UAEndpointDescriptor, _
   ByVal nodeDescriptor As UANodeDescriptor, _
   ByVal samplingInterval As Integer, _
   ByVal dataChangeFilter As UADataChangeFilter _
) As Integer
'Usage
 
Dim client As IEasyUAClient
Dim endpointDescriptor As UAEndpointDescriptor
Dim nodeDescriptor As UANodeDescriptor
Dim samplingInterval As Integer
Dim dataChangeFilter As UADataChangeFilter
Dim value As Integer
 
value = IEasyUAClientExtension.SubscribeDataChange(client, endpointDescriptor, nodeDescriptor, samplingInterval, dataChangeFilter)

Parameters

client
The client object that will perform the operation.
endpointDescriptor
Endpoint descriptor. Identifies the OPC-UA server.
nodeDescriptor
Node descriptor. Identifies the node in OPC server's address space.
samplingInterval
The sampling interval (in milliseconds) indicates the fastest rate at which the Server should sample its underlying source for data changes.
dataChangeFilter
The data change filter.

Return Value

The method returns an integer handle that uniquely identifies the monitored item subscription.
Exceptions
ExceptionDescription

A null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.

This is a usage error, i.e. it will never occur (the exception will not be thrown) in a correctly written program. Your code should not catch this exception.

The value of an argument is outside the allowable range of values as defined by the invoked method.

This is a usage error, i.e. it will never occur (the exception will not be thrown) in a correctly written program. Your code should not catch this exception.

Remarks

You can obtain nodeDescriptor e.g. by calling one of the browsing methods on EasyUAClientCore object.

For filtering with an absolute deadband, you can use an implicit conversion from System.Double to UADataChangeFilter for the dataChangeFilter argument.

 

This method operates (at least in part) asynchronously, with respect to the caller. The actual execution of the operation may be delayed, and the outcome of the operation (if any) is provided to the calling code using an event notification, callback, or other means explained in the text. In a properly written program, this method does not throw any exceptions. You should therefore not put try/catch statements or similar constructs around calls to this method. The only exceptions thrown by this method are for usage errors, i.e. when your code violates the usage contract of the method, such as passing in invalid arguments or calling the method when the state of the object does not allow it. Any operation-related errors (i.e. errors that depend on external conditions that your code cannot reliably check) are indicated by the means the operation returns its outcome (if any), which is described in the text. For more information, see Do not catch any exceptions with asynchronous or multiple-operation methods.
Example

.NET

COM

// This example shows how to subscribe to changes of a monitored item with data change filter.

using System;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.OperationModel;

namespace UADocExamples._EasyUAClient
{
    partial class SubscribeDataChange
    {
        public static void Filter()
        {
            UAEndpointDescriptor endpointDescriptor =
                "opc.tcp://opcua.demo-this.com:51210/UA/SampleServer";
            // or "http://opcua.demo-this.com:51211/UA/SampleServer" (currently not supported)
            // or "https://opcua.demo-this.com:51212/UA/SampleServer/"

            // Instantiate the client object and hook events.
            var client = new EasyUAClient();
            client.DataChangeNotification += client_DataChangeNotification_Filter;

            Console.WriteLine("Subscribing...");
            // Report a notification if either the StatusCode or the value change. 
            // The UADataChangeTrigger has an implicit conversion to UADataChangeFilter and can thus be used in its place.
            client.SubscribeDataChange(endpointDescriptor, "nsu=http://test.org/UA/Data/ ;i=10853", 1000, 
                dataChangeFilter:UADataChangeTrigger.StatusValue);

            Console.WriteLine("Processing data change events for 20 seconds...");
            System.Threading.Thread.Sleep(20 * 1000);

            Console.WriteLine("Unsubscribing...");
            client.UnsubscribeAllMonitoredItems();

            Console.WriteLine("Waiting for 5 seconds...");
            System.Threading.Thread.Sleep(5 * 1000);

            Console.WriteLine("Finished.");
        }

        static void client_DataChangeNotification_Filter(object sender, EasyUADataChangeNotificationEventArgs e)
        {
            // Display value.
            if (e.Succeeded)
                Console.WriteLine($"Value: {e.AttributeData.Value}");
            else
                Console.WriteLine($"*** Failure: {e.ErrorMessageBrief}");
        }
    }
}
# This example shows how to subscribe to changes of a monitored item with data change filter.

#requires -Version 5.1
using namespace OpcLabs.EasyOpc.UA

# The path below assumes that the current directory is [ProductDir]/Examples-NET/PowerShell/Windows .
Add-Type -Path "../../../Components/Opclabs.QuickOpc/net472/OpcLabs.EasyOpcUA.dll"
Add-Type -Path "../../../Components/Opclabs.QuickOpc/net472/OpcLabs.EasyOpcUAComponents.dll"

[UAEndpointDescriptor]$endpointDescriptor =
    "opc.tcp://opcua.demo-this.com:51210/UA/SampleServer"
# or "http://opcua.demo-this.com:51211/UA/SampleServer" (currently not supported)
# or "https://opcua.demo-this.com:51212/UA/SampleServer/"

# Instantiate the client object.
$client = New-Object EasyUAClient

# Data change notification handler
Register-ObjectEvent -InputObject $client -EventName DataChangeNotification -Action { 
    # Display value.
    if ($EventArgs.Succeeded) {
        Write-Host "Value: $($EventArgs.AttributeData.Value)"
    }
    else {
        Write-Host "*** Failure: $($EventArgs.ErrorMessageBrief)"
    }
}

Write-Host "Subscribing..."
# Report a notification if either the StatusCode or the value change. 
# The UADataChangeTrigger has an implicit conversion to UADataChangeFilter and can thus be used in its place.
[IEasyUAClientExtension]::SubscribeDataChange($client, $endpointDescriptor, "nsu=http://test.org/UA/Data/ ;i=10853", 1000,
    [UADataChangeTrigger]::StatusValue)

Write-Host "Processing data change events for 20 seconds..."
$stopwatch =  [System.Diagnostics.Stopwatch]::StartNew() 
while ($stopwatch.Elapsed.TotalSeconds -lt 20) {    
    Start-Sleep -Seconds 1
}

Write-Host "Unsubscribing..."
$client.UnsubscribeAllMonitoredItems()

Write-Host "Waiting for 5 seconds..."
Start-Sleep -Seconds 5

Write-Host "Finished."
# This example shows how to subscribe to changes of a monitored item with data change filter.

# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc
import time

# Import .NET namespaces.
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.OperationModel import *


def dataChangeNotification(sender, e):
    # Display value.
    if e.Succeeded:
        print('Value: ', e.AttributeData.Value, sep='')
    else:
        print('*** Failure: ', e.ErrorMessageBrief, sep='')


endpointDescriptor = UAEndpointDescriptor('opc.tcp://opcua.demo-this.com:51210/UA/SampleServer')
# or 'http://opcua.demo-this.com:51211/UA/SampleServer' (currently not supported)
# or 'https://opcua.demo-this.com:51212/UA/SampleServer/'

# Instantiate the client object and hook events.
client = EasyUAClient()
client.DataChangeNotification += dataChangeNotification

print('Subscribing...')
# Report a notification if either the StatusCode or the value change.
# The UADataChangeTrigger has an implicit conversion to UADataChangeFilter.
IEasyUAClientExtension.SubscribeDataChange(client,
    endpointDescriptor,
    UANodeDescriptor('nsu=http://test.org/UA/Data/ ;i=10853'),
    1000,
    UADataChangeFilter(UADataChangeTrigger.StatusValue))

print('Processing data change events for 20 seconds...')
time.sleep(20)

print('Unsubscribing...')
client.UnsubscribeAllMonitoredItems()

print('Waiting for 5 seconds...')
time.sleep(5)

print('Finished.')
' This example shows how to subscribe to changes of a monitored item with data change filter.

Imports OpcLabs.EasyOpc.UA
Imports OpcLabs.EasyOpc.UA.OperationModel

Namespace _EasyUAClient
    Partial Friend Class SubscribeDataChange
        Public Shared Sub Filter()

            ' Define which server we will work with.
            Dim endpointDescriptor As UAEndpointDescriptor =
                    "opc.tcp://opcua.demo-this.com:51210/UA/SampleServer"
            ' or "http://opcua.demo-this.com:51211/UA/SampleServer" (currently not supported)
            ' or "https://opcua.demo-this.com:51212/UA/SampleServer/"

            ' Instantiate the client object and hook events
            Dim client = New EasyUAClient()
            AddHandler client.DataChangeNotification, AddressOf client_DataChangeNotification_Filter

            Console.WriteLine("Subscribing...")
            ' Report a notification if either the StatusCode Or the value change. 
            ' The UADataChangeTrigger has an implicit conversion to UADataChangeFilter And can thus be used in its place.
            client.SubscribeDataChange(endpointDescriptor, "nsu=http://test.org/UA/Data/ ;i=10853", 1000, UADataChangeTrigger.StatusValue)

            Console.WriteLine("Processing data change events for 20 seconds...")
            Threading.Thread.Sleep(20 * 1000)

            Console.WriteLine("Unsubscribing...")
            client.UnsubscribeAllMonitoredItems()

            Console.WriteLine("Waiting for 5 seconds...")
            Threading.Thread.Sleep(5 * 1000)
        End Sub

        Private Shared Sub client_DataChangeNotification_Filter(ByVal sender As Object, ByVal e As EasyUADataChangeNotificationEventArgs)
            ' Display value
            If e.Succeeded Then
                Console.WriteLine("Value: {0}", e.AttributeData.Value)
            Else
                Console.WriteLine("*** Failure: {0}", e.ErrorMessageBrief)
            End If
        End Sub
    End Class
End Namespace
// This example shows how to subscribe to changes of a monitored item
// with data change filter.

type
  TClientEventHandlers120 = class
    procedure Client_DataChangeNotification(
      ASender: TObject;
      sender: OleVariant;
      const eventArgs: _EasyUADataChangeNotificationEventArgs);
  end;

procedure TClientEventHandlers120.Client_DataChangeNotification(
  ASender: TObject;
  sender: OleVariant;
  const eventArgs: _EasyUADataChangeNotificationEventArgs);
begin
  // Display the data
  if eventArgs.Succeeded then
  begin
      WriteLn(eventArgs.AttributeData.ToString);
  end
  else
      WriteLn(' *** Failure: ', eventArgs.ErrorMessageBrief);
end;

class procedure SubscribeDataChange.Filter;
const
  UADataChangeFilter_StatusValue = 1;
var
  Arguments: OleVariant;
  Client: TEasyUAClient;
  ClientEventHandlers: TClientEventHandlers120;
  DataChangeFilter: _UADataChangeFilter;
  EndpointDescriptor: string;
  MonitoringItemArguments1: _EasyUAMonitoredItemArguments;
  MonitoringParameters:  _UAMonitoringParameters;
begin
  EndpointDescriptor := 
    //'http://opcua.demo-this.com:51211/UA/SampleServer';
    //'https://opcua.demo-this.com:51212/UA/SampleServer/';
    'opc.tcp://opcua.demo-this.com:51210/UA/SampleServer';

  // Instantiate the client object and hook events
  Client := TEasyUAClient.Create(nil);
  ClientEventHandlers := TClientEventHandlers120.Create;
  Client.OnDataChangeNotification := ClientEventHandlers.Client_DataChangeNotification;

  // Prepare the arguments.
  // Report a notification if either the StatusCode or the value change.
  DataChangeFilter := CoUADataChangeFilter.Create;
  DataChangeFilter.Trigger := UADataChangeFilter_StatusValue;
  MonitoringParameters := CoUAMonitoringParameters.Create;
  MonitoringParameters.DataChangeFilter := DataChangeFilter;
  MonitoringParameters.SamplingInterval := 100;
  MonitoringItemArguments1 := CoEasyUAMonitoredItemArguments.Create;
  MonitoringItemArguments1.EndpointDescriptor.UrlString := EndpointDescriptor;
  MonitoringItemArguments1.NodeDescriptor.NodeId.ExpandedText := 'nsu=http://test.org/UA/Data/ ;i=10853';
  MonitoringItemArguments1.MonitoringParameters := MonitoringParameters;

  Arguments := VarArrayCreate([0, 0], varVariant);
  Arguments[0] := MonitoringItemArguments1;

  WriteLn('Subscribing...');
  Client.SubscribeMultipleMonitoredItems(arguments);

  WriteLn('Processing monitored item changed events for 20 seconds...');
  PumpSleep(20*1000);

  WriteLn('Unsubscribing...');
  Client.UnsubscribeAllMonitoredItems;

  WriteLn('Waiting for 5 seconds...');
  PumpSleep(5*1000);

  WriteLn('Finished.');
  VarClear(Arguments);
  FreeAndNil(Client);
  FreeAndNil(ClientEventHandlers);
end;
// This example shows how to subscribe to changes of a monitored item
// with data change filter.

class ClientEvents {
    function DataChangeNotification($Sender, $E)
    {
        // Display the data
        if ($E->Succeeded)
            printf("%s\n", $E->AttributeData);
        else
            printf(" *** Failure: %s\n", $E->ErrorMessageBrief);
    }
}

const UADataChangeFilter_StatusValue = 1;

$EndpointDescriptor = new COM("OpcLabs.EasyOpc.UA.UAEndpointDescriptor");
$EndpointDescriptor->UrlString = 
    //"http://opcua.demo-this.com:51211/UA/SampleServer";
    //"https://opcua.demo-this.com:51212/UA/SampleServer/";
    "opc.tcp://opcua.demo-this.com:51210/UA/SampleServer";


// Instantiate the client object and hook events
$Client = new COM("OpcLabs.EasyOpc.UA.EasyUAClient");
$ClientEvents = new ClientEvents();
com_event_sink($Client, $ClientEvents, "DEasyUAClientEvents");

// Prepare the arguments.
// Report a notification if either the StatusCode or the value change.
$DataChangeFilter = new COM("OpcLabs.EasyOpc.UA.UADataChangeFilter");
$DataChangeFilter->Trigger = UADataChangeFilter_StatusValue;
$MonitoringParameters = new COM("OpcLabs.EasyOpc.UA.UAMonitoringParameters");
$MonitoringParameters->DataChangeFilter = $DataChangeFilter;
$MonitoringParameters->SamplingInterval = 100;
$MonitoredItemArguments1 = new COM("OpcLabs.EasyOpc.UA.OperationModel.EasyUAMonitoredItemArguments");
$MonitoredItemArguments1->EndpointDescriptor->UrlString = $EndpointDescriptor;
$MonitoredItemArguments1->NodeDescriptor->NodeId->ExpandedText = "nsu=http://test.org/UA/Data/ ;i=10853";
$MonitoredItemArguments1->MonitoringParameters = $MonitoringParameters;
$arguments[0] = $MonitoredItemArguments1;

printf("Subscribing...\n");
$Client->SubscribeMultipleMonitoredItems($arguments);

printf("Processing monitored item changed events for 20 seconds...\n");
$startTime = time(); do { com_message_pump(1000); } while (time() < $startTime + 20);

printf("Unsubscribing...\n");
$Client->UnsubscribeAllMonitoredItems;

printf("Waiting for 5 seconds...\n");
$startTime = time(); do { com_message_pump(1000); } while (time() < $startTime + 5);
Rem This example shows how to subscribe to changes of a monitored item with data change filter.

Option Explicit

Const UADataChangeTrigger_StatusValue = 1

Dim endpointDescriptor: endpointDescriptor = _
    "opc.tcp://opcua.demo-this.com:51210/UA/SampleServer"
    '"http://opcua.demo-this.com:51211/UA/SampleServer"  
    '"https://opcua.demo-this.com:51212/UA/SampleServer/"

' Instantiate the client object and hook events
Dim Client: Set Client = CreateObject("OpcLabs.EasyOpc.UA.EasyUAClient")
WScript.ConnectObject Client, "Client_"

' Prepare the arguments.
' Report a notification if either the StatusCode or the value change. 
Dim DataChangeFilter: Set DataChangeFilter = CreateObject("OpcLabs.EasyOpc.UA.UADataChangeFilter")
DataChangeFilter.Trigger = UADataChangeTrigger_StatusValue
'
Dim MonitoringParameters: Set MonitoringParameters = CreateObject("OpcLabs.EasyOpc.UA.UAMonitoringParameters")
Set MonitoringParameters.DataChangeFilter = DataChangeFilter
MonitoringParameters.SamplingInterval = 1000
'
Dim MonitoredItemArguments1: Set MonitoredItemArguments1 = CreateObject("OpcLabs.EasyOpc.UA.OperationModel.EasyUAMonitoredItemArguments")
MonitoredItemArguments1.EndpointDescriptor.UrlString = endpointDescriptor
MonitoredItemArguments1.NodeDescriptor.NodeId.ExpandedText = "nsu=http://test.org/UA/Data/ ;i=10853"
MonitoredItemArguments1.MonitoringParameters = MonitoringParameters
'
Dim arguments(0)
Set arguments(0) = MonitoredItemArguments1

WScript.Echo "Subscribing..."
Client.SubscribeMultipleMonitoredItems arguments

WScript.Echo "Processing monitored item changed events for 20 seconds..."
WScript.Sleep 20*1000

WScript.Echo "Unsubscribing..."
Client.UnsubscribeAllMonitoredItems

WScript.Echo "Waiting for 5 seconds..."
WScript.Sleep 5 * 1000



Sub Client_DataChangeNotification(Sender, e)
    ' Display value
    Dim display: If e.Exception Is Nothing Then display = e.AttributeData Else display = "*** Failure: " & e.ErrorMessageBrief
    WScript.Echo display
End Sub
Rem This example shows how to subscribe to changes of a monitored item with data change filter.

' The client object, with events
'Public WithEvents Client3 As EasyUAClient

Public Sub SubscribeDataChange_Filter_Command_Click()
    OutputText = ""

    Dim endpointDescriptor As String
    'endpointDescriptor = "http://opcua.demo-this.com:51211/UA/SampleServer"
    'endpointDescriptor = "https://opcua.demo-this.com:51212/UA/SampleServer/"
    endpointDescriptor = "opc.tcp://opcua.demo-this.com:51210/UA/SampleServer"

    ' Instantiate the client object and hook events
    Set Client3 = New EasyUAClient
    
    ' Prepare the arguments.
    ' Report a notification if either the StatusCode or the value change.
    Dim DataChangeFilter As New UADataChangeFilter
    DataChangeFilter.Trigger = UADataChangeTrigger_StatusValue
    
    Dim MonitoringParameters As New UAMonitoringParameters
    Set MonitoringParameters.DataChangeFilter = DataChangeFilter
    MonitoringParameters.SamplingInterval = 1000
    
    Dim MonitoredItemArguments1 As New EasyUAMonitoredItemArguments
    MonitoredItemArguments1.endpointDescriptor.UrlString = endpointDescriptor
    MonitoredItemArguments1.nodeDescriptor.NodeId.expandedText = "nsu=http://test.org/UA/Data/ ;i=10853"
    Set MonitoredItemArguments1.MonitoringParameters = MonitoringParameters

    Dim arguments(0) As Variant
    Set arguments(0) = MonitoredItemArguments1

    OutputText = OutputText & "Subscribing..." & vbCrLf
    Call Client3.SubscribeMultipleMonitoredItems(arguments)

    OutputText = OutputText & "Processing monitored item changed events for 20 seconds..." & vbCrLf
    Pause 20000

    OutputText = OutputText & "Unsubscribing..." & vbCrLf
    Client3.UnsubscribeAllMonitoredItems

    OutputText = OutputText & "Waiting for 5 seconds..." & vbCrLf
    Pause 5000

    Set Client3 = Nothing
End Sub

Public Sub Client3_DataChangeNotification(ByVal sender As Variant, ByVal eventArgs As EasyUADataChangeNotificationEventArgs)
    ' Display the data
    If eventArgs.Exception Is Nothing Then
        OutputText = OutputText & eventArgs.AttributeData & vbCrLf
    Else
        OutputText = OutputText & eventArgs.ErrorMessageBrief & vbCrLf
    End If
End Sub
Requirements

Target Platforms: .NET Framework: Windows 10 (selected versions), Windows 11 (selected versions), Windows Server 2016, Windows Server 2022; .NET: Linux, macOS, Microsoft Windows

See Also