QuickOPC User's Guide and Reference
SubscribeEvents(IEasyAEClient,String,String,Int32,EasyAENotificationEventHandler,Object,AESubscriptionFilter,AEAttributeSetDictionary,Boolean,Boolean) Method
Example 



OpcLabs.EasyOpcClassicCore Assembly > OpcLabs.EasyOpc.AlarmsAndEvents Namespace > IEasyAEClientExtension Class > SubscribeEvents Method : SubscribeEvents(IEasyAEClient,String,String,Int32,EasyAENotificationEventHandler,Object,AESubscriptionFilter,AEAttributeSetDictionary,Boolean,Boolean) Method
The client object that will perform the operation.
Name of the machine. Determines the computer on which the OPC server is located. May be an empty string, in which case the OPC server is assumed to exist on the local computer or at the computer specified for it by DCOM configuration.
Contains ProgID of the OPC server.
The requested notification rate. The notification rate is in milliseconds and tells the server how often to send event notifications. This is a minimum time - do not send event notifications any faster that this UNLESS the buffer size is reached. A value of 0 for notification rate means that the server should send event notifications as soon as it gets them. This parameter is used to improve communications efficiency between client and server. This parameter is a recommendation from the client, and the server is allowed to ignore the parameter.
A callback method to be invoked for each OPC event.
The state object (can be any value supplied by your code); available in event notifications.
An AESubscriptionFilter that determines the filtering criteria to be used for the event subscription.
Determines the attributes to be returned for each category with event notifications. A dictionary where they key is the category ID, and the value is an array of attribute IDs for that event category.
Creates activated or deactivated subscription. See ChangeEventSubscription for more information.
When set, the subscription will automatically perform a Refresh after each successful connection to the server (either the initial connection, or any automatic reconnection after the connection is lost).
Subscribe to particular OPC events. The Notification is generated for each event. Subscribe to OPC events. Specify machine name, server class, notification rate, filter object, returned attributes, callback method, and "active" and "refresh when active" flags.
Syntax
'Declaration
 
<ExtensionAttribute()>
Public Overloads Shared Function SubscribeEvents( _
   ByVal client As IEasyAEClient, _
   ByVal machineName As String, _
   ByVal serverClass As String, _
   ByVal notificationRate As Integer, _
   ByVal callback As EasyAENotificationEventHandler, _
   ByVal state As Object, _
   ByVal filter As AESubscriptionFilter, _
   ByVal returnedAttributesByCategory As AEAttributeSetDictionary, _
   ByVal active As Boolean, _
   ByVal refreshWhenActive As Boolean _
) As Integer
'Usage
 
Dim client As IEasyAEClient
Dim machineName As String
Dim serverClass As String
Dim notificationRate As Integer
Dim callback As EasyAENotificationEventHandler
Dim state As Object
Dim filter As AESubscriptionFilter
Dim returnedAttributesByCategory As AEAttributeSetDictionary
Dim active As Boolean
Dim refreshWhenActive As Boolean
Dim value As Integer
 
value = IEasyAEClientExtension.SubscribeEvents(client, machineName, serverClass, notificationRate, callback, state, filter, returnedAttributesByCategory, active, refreshWhenActive)

Parameters

client
The client object that will perform the operation.
machineName
Name of the machine. Determines the computer on which the OPC server is located. May be an empty string, in which case the OPC server is assumed to exist on the local computer or at the computer specified for it by DCOM configuration.
serverClass
Contains ProgID of the OPC server.
notificationRate
The requested notification rate. The notification rate is in milliseconds and tells the server how often to send event notifications. This is a minimum time - do not send event notifications any faster that this UNLESS the buffer size is reached. A value of 0 for notification rate means that the server should send event notifications as soon as it gets them. This parameter is used to improve communications efficiency between client and server. This parameter is a recommendation from the client, and the server is allowed to ignore the parameter.
callback
A callback method to be invoked for each OPC event.
state
The state object (can be any value supplied by your code); available in event notifications.
filter
An AESubscriptionFilter that determines the filtering criteria to be used for the event subscription.
returnedAttributesByCategory
Determines the attributes to be returned for each category with event notifications. A dictionary where they key is the category ID, and the value is an array of attribute IDs for that event category.
active
Creates activated or deactivated subscription. See ChangeEventSubscription for more information.
refreshWhenActive
When set, the subscription will automatically perform a Refresh after each successful connection to the server (either the initial connection, or any automatic reconnection after the connection is lost).

Return Value

The method returns an integer handle that uniquely identifies the event 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
If callback is a null reference, only the Notification events will be generated, but no callback method will be invoked.

 

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

.NET

.NET

.NET

// This example shows how to subscribe to events and display the event message with each notification. It also shows how to 
// unsubscribe afterwards.

using System;
using System.Threading;
using OpcLabs.EasyOpc.AlarmsAndEvents;
using OpcLabs.EasyOpc.AlarmsAndEvents.OperationModel;

namespace DocExamples.AlarmsAndEvents._EasyAEClient
{
    partial class SubscribeEvents
    {
        public static void Main1()
        {
            // Instantiate the client object.
            using (var client = new EasyAEClient())
            {
                var eventHandler = new EasyAENotificationEventHandler(client_Notification);
                client.Notification += eventHandler;

                int handle = client.SubscribeEvents("", "OPCLabs.KitEventServer.2", 1000);

                Console.WriteLine("Processing event notifications for 1 minute...");
                Thread.Sleep(60 * 1000);

                client.UnsubscribeEvents(handle);
            }
        }

        // Notification event handler
        static void client_Notification(object sender, EasyAENotificationEventArgs e)
        {
            if (!e.Succeeded)
            {
                Console.WriteLine("*** Failure: {0}", e.ErrorMessageBrief);
                return;
            }
            if (!(e.EventData is null))
                Console.WriteLine(e.EventData.Message);
        }
    }
}
# This example shows how to subscribe to events and display the event message with each notification. It also shows how to 
# unsubscribe afterwards.

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

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

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

# Notification event handler
Register-ObjectEvent -InputObject $client -EventName Notification -Action { 
    if (-not $EventArgs.Succeeded) {
        Write-Host "*** Failure: $($EventArgs.ErrorMessageBrief)"
        #return
    }
    if ($EventArgs.EventData -ne $null) {
        Write-Host $EventArgs.EventData.Message
    }
}

Write-Host "Subscribing events..."
$handle = [IEasyAEClientExtension]::SubscribeEvents($client, "", "OPCLabs.KitEventServer.2", 1000)

Write-Host "Processing event notifications for 1 minute..."
$stopwatch =  [System.Diagnostics.Stopwatch]::StartNew() 
while ($stopwatch.Elapsed.TotalSeconds -lt 60) {    
    Start-Sleep -Seconds 1
}

Write-Host "Unsubscribing events..."
$client.UnsubscribeEvents($handle)

Write-Host "Finished."
# This example shows how to subscribe to events and display the event message with each notification. It also shows how
# to unsubscribe afterwards.

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

# Import .NET namespaces.
from OpcLabs.EasyOpc import *
from OpcLabs.EasyOpc.AlarmsAndEvents import *


# Notification event handler
def notification(sender, e):
    if not e.Succeeded:
        print('*** Failure: ', e.ErrorMessageBrief, sep='')
        return
    else:
        if e.EventData is not None:
            print(e.EventData.Message)


# Instantiate the client object
client = EasyAEClient()

client.Notification += notification

print('Subscribing events...')
handle = IEasyAEClientExtension.SubscribeEvents(client, '', 'OPCLabs.KitEventServer.2', 1000)

print('Processing event notifications for 1 minute...')
time.sleep(60)

print('Unsubscribing events...')
client.UnsubscribeAllEvents()

client.Notification -= notification

print('Finished.')
' This example shows how to subscribe to events and display the event message with each notification. It also shows how to 
' unsubscribe afterwards.

Imports System.Threading
Imports OpcLabs.EasyOpc.AlarmsAndEvents
Imports OpcLabs.EasyOpc.AlarmsAndEvents.OperationModel

Namespace AlarmsAndEvents._EasyAEClient
    Partial Friend Class SubscribeEvents
        Public Shared Sub Main1()
            Using client = New EasyAEClient()
                Dim eventHandler = New EasyAENotificationEventHandler(AddressOf client_Notification)
                AddHandler client.Notification, eventHandler

                Dim handle As Integer = client.SubscribeEvents("", "OPCLabs.KitEventServer.2", 1000)

                Console.WriteLine("Processing event notifications for 1 minute...")
                Thread.Sleep(60 * 1000)

                client.UnsubscribeEvents(handle)
            End Using
        End Sub

        ' Notification event handler
        Private Shared Sub client_Notification(ByVal sender As Object, ByVal e As EasyAENotificationEventArgs)
            If Not e.Succeeded Then
                Console.WriteLine("*** Failure: {0}", e.ErrorMessageBrief)
                Exit Sub
            End If
            If e.EventData IsNot Nothing Then
                Console.WriteLine(e.EventData.Message)
            End If
        End Sub
    End Class
End Namespace
// This example shows how to filter the events by their category.

using System;
using System.Threading;
using OpcLabs.EasyOpc.AlarmsAndEvents;
using OpcLabs.EasyOpc.AlarmsAndEvents.OperationModel;
using OpcLabs.EasyOpc.DataAccess;

namespace DocExamples.AlarmsAndEvents._EasyAEClient
{
    partial class SubscribeEvents
    {
        // Instantiate the OPC-A&E client object.
        static readonly EasyAEClient AEClient = new EasyAEClient();

        // Instantiate the OPC-DA client object.
        static readonly EasyDAClient DAClient = new EasyDAClient();

        public static void FilterByCategories()
        {
            var eventHandler = new EasyAENotificationEventHandler(AEClient_Notification_FilterByCategories);
            AEClient.Notification += eventHandler;

            Console.WriteLine("Processing event notifications...");
            var subscriptionFilter = new AESubscriptionFilter
            {
                Categories = new long[] { 15531778 }
            };
            // You can also filter using event types, severity, areas, and sources.
            int handle = AEClient.SubscribeEvents("", "OPCLabs.KitEventServer.2", 1000, null, subscriptionFilter);

            // Allow time for initial refresh
            Thread.Sleep(5 * 1000);

            // Set some events to active state.
            DAClient.WriteItemValue("", "OPCLabs.KitServer.2", "SimulateEvents.ConditionState1.Activate", true);
            DAClient.WriteItemValue("", "OPCLabs.KitServer.2", "SimulateEvents.ConditionState2.Activate", true);

            Thread.Sleep(10 * 1000);

            AEClient.UnsubscribeEvents(handle);
            AEClient.Notification -= eventHandler;
        }

        // Notification event handler
        static void AEClient_Notification_FilterByCategories(object sender, EasyAENotificationEventArgs e)
        {
            Console.WriteLine();
            Console.WriteLine(e);
            if (!e.Succeeded)
                return;

            Console.WriteLine("Refresh: {0}", e.Refresh);
            Console.WriteLine("RefreshComplete: {0}", e.RefreshComplete);
            AEEventData eventData = e.EventData;
            if (!(eventData is null))
            {
                Console.WriteLine("Event.CategoryId: {0}", eventData.CategoryId);
                Console.WriteLine("Event.QualifiedSourceName: {0}", eventData.QualifiedSourceName);
                Console.WriteLine("Event.Message: {0}", eventData.Message);
                Console.WriteLine("Event.Active: {0}", eventData.Active);
                Console.WriteLine("Event.Acknowledged: {0}", eventData.Acknowledged);
            }
        }
    }
}
# This example shows how to filter the events by their category.

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

# Import .NET namespaces.
from OpcLabs.EasyOpc import *
from OpcLabs.EasyOpc.AlarmsAndEvents import *
from OpcLabs.EasyOpc.DataAccess import *
from OpcLabs.EasyOpc.OperationModel import *


# Notification event handler
def notification(sender, e):
    print()
    print(e)
    if not e.Succeeded:
        return
    print('Refresh: ', e.Refresh, sep='')
    print('RefreshComplete: ', e.RefreshComplete, sep='')
    eventData = e.EventData
    if eventData is not None:
        print('Event.CategoryId: ', eventData.CategoryId, sep='')
        print('Event.QualifiedSourceName: ', eventData.QualifiedSourceName, sep='')
        print('Event.Message: ', eventData.Message, sep='')
        print('Event.Active: ', eventData.Active, sep='')
        print('Event.Acknowledged: ', eventData.Acknowledged, sep='')


# Instantiate the OPC-A&E client object.
aeClient = EasyAEClient()

# Instantiate the OPC-DA client object.
daClient = EasyDAClient()

#
aeClient.Notification += notification

print('Processing event notifications...')
subscriptionFilter = AESubscriptionFilter()
subscriptionFilter.Categories = [15531778]
# You can also filter using event types, severity, areas, and sources.
handle = IEasyAEClientExtension.SubscribeEvents(aeClient, '', 'OPCLabs.KitEventServer.2', 1000, None, subscriptionFilter)

# Allow time for initial refresh.
time.sleep(5)

# Set some events to active state.
try:
    IEasyDAClientExtension.WriteItemValue(daClient, '', 'OPCLabs.KitServer.2',
                                          'SimulateEvents.ConditionState1.Activate', True)
    IEasyDAClientExtension.WriteItemValue(daClient, '', 'OPCLabs.KitServer.2',
                                          'SimulateEvents.ConditionState2.Activate', True)
except OpcException as opcException:
    print('*** Failure: ' + opcException.GetBaseException().Message)
    exit()

time.sleep(10)

aeClient.UnsubscribeEvents(handle)
aeClient.Notification -= notification

print('Finished.')
' This example shows how to filter the events by their category.

Imports System.Threading
Imports OpcLabs.EasyOpc.AlarmsAndEvents
Imports OpcLabs.EasyOpc.AlarmsAndEvents.OperationModel
Imports OpcLabs.EasyOpc.DataAccess

Namespace AlarmsAndEvents._EasyAEClient

    Partial Friend Class SubscribeEvents
        _
        Private Shared ReadOnly AEClient As New EasyAEClient()
        _
        Private Shared ReadOnly DAClient As New EasyDAClient()

        Public Shared Sub FilterByCategories()
            Dim eventHandler = New EasyAENotificationEventHandler(AddressOf AEClient_Notification_FilterByCategories)
            AddHandler AEClient.Notification, eventHandler

            Console.WriteLine("Processing event notifications...")
            Dim subscriptionFilter As New AESubscriptionFilter() With _
                {.Categories = New Long() {15531778}}
            ' You can also filter using event types, severity, areas, and sources.
            Dim handle As Integer = AEClient.SubscribeEvents("", "OPCLabs.KitEventServer.2", Nothing, subscriptionFilter)

            ' Allow time for initial refresh
            Thread.Sleep(5 * 1000)

            ' Set some events to active state.
            DAClient.WriteItemValue("", "OPCLabs.KitServer.2", "SimulateEvents.ConditionState1.Activate", True)
            DAClient.WriteItemValue("", "OPCLabs.KitServer.2", "SimulateEvents.ConditionState2.Activate", True)

            Thread.Sleep(10 * 1000)

            AEClient.UnsubscribeEvents(handle)
            RemoveHandler AEClient.Notification, eventHandler
        End Sub

        ' Notification event handler
        Private Shared Sub AEClient_Notification_FilterByCategories(ByVal sender As Object, ByVal e As EasyAENotificationEventArgs)
            Console.WriteLine()
            Console.WriteLine(e)
            If Not e.Succeeded Then
                Exit Sub
            End If

            Console.WriteLine("Refresh: {0}", e.Refresh)
            Console.WriteLine("RefreshComplete: {0}", e.RefreshComplete)
            Dim eventData As AEEventData = e.EventData
            If e.EventData IsNot Nothing Then
                Console.WriteLine("Event.CategoryId: {0}", eventData.CategoryId)
                Console.WriteLine("Event.QualifiedSourceName: {0}", eventData.QualifiedSourceName)
                Console.WriteLine("Event.Message: {0}", eventData.Message)
                Console.WriteLine("Event.Active: {0}", eventData.Active)
                Console.WriteLine("Event.Acknowledged: {0}", eventData.Acknowledged)
            End If
        End Sub
    End Class
End Namespace
// This example shows how to subscribe to events and display the event message with each notification. It also shows how to 
// unsubscribe afterwards.

using System;
using System.Threading;
using OpcLabs.EasyOpc.AlarmsAndEvents;
using OpcLabs.EasyOpc.AlarmsAndEvents.OperationModel;

namespace DocExamples.AlarmsAndEvents._EasyAEClient
{
    partial class SubscribeEvents
    {
        public static void Main1()
        {
            // Instantiate the client object.
            using (var client = new EasyAEClient())
            {
                var eventHandler = new EasyAENotificationEventHandler(client_Notification);
                client.Notification += eventHandler;

                int handle = client.SubscribeEvents("", "OPCLabs.KitEventServer.2", 1000);

                Console.WriteLine("Processing event notifications for 1 minute...");
                Thread.Sleep(60 * 1000);

                client.UnsubscribeEvents(handle);
            }
        }

        // Notification event handler
        static void client_Notification(object sender, EasyAENotificationEventArgs e)
        {
            if (!e.Succeeded)
            {
                Console.WriteLine("*** Failure: {0}", e.ErrorMessageBrief);
                return;
            }
            if (!(e.EventData is null))
                Console.WriteLine(e.EventData.Message);
        }
    }
}
# This example shows how to subscribe to events and display the event message with each notification. It also shows how to 
# unsubscribe afterwards.

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

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

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

# Notification event handler
Register-ObjectEvent -InputObject $client -EventName Notification -Action { 
    if (-not $EventArgs.Succeeded) {
        Write-Host "*** Failure: $($EventArgs.ErrorMessageBrief)"
        #return
    }
    if ($EventArgs.EventData -ne $null) {
        Write-Host $EventArgs.EventData.Message
    }
}

Write-Host "Subscribing events..."
$handle = [IEasyAEClientExtension]::SubscribeEvents($client, "", "OPCLabs.KitEventServer.2", 1000)

Write-Host "Processing event notifications for 1 minute..."
$stopwatch =  [System.Diagnostics.Stopwatch]::StartNew() 
while ($stopwatch.Elapsed.TotalSeconds -lt 60) {    
    Start-Sleep -Seconds 1
}

Write-Host "Unsubscribing events..."
$client.UnsubscribeEvents($handle)

Write-Host "Finished."
# This example shows how to subscribe to events and display the event message with each notification. It also shows how
# to unsubscribe afterwards.

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

# Import .NET namespaces.
from OpcLabs.EasyOpc import *
from OpcLabs.EasyOpc.AlarmsAndEvents import *


# Notification event handler
def notification(sender, e):
    if not e.Succeeded:
        print('*** Failure: ', e.ErrorMessageBrief, sep='')
        return
    else:
        if e.EventData is not None:
            print(e.EventData.Message)


# Instantiate the client object
client = EasyAEClient()

client.Notification += notification

print('Subscribing events...')
handle = IEasyAEClientExtension.SubscribeEvents(client, '', 'OPCLabs.KitEventServer.2', 1000)

print('Processing event notifications for 1 minute...')
time.sleep(60)

print('Unsubscribing events...')
client.UnsubscribeAllEvents()

client.Notification -= notification

print('Finished.')
' This example shows how to subscribe to events and display the event message with each notification. It also shows how to 
' unsubscribe afterwards.

Imports System.Threading
Imports OpcLabs.EasyOpc.AlarmsAndEvents
Imports OpcLabs.EasyOpc.AlarmsAndEvents.OperationModel

Namespace AlarmsAndEvents._EasyAEClient
    Partial Friend Class SubscribeEvents
        Public Shared Sub Main1()
            Using client = New EasyAEClient()
                Dim eventHandler = New EasyAENotificationEventHandler(AddressOf client_Notification)
                AddHandler client.Notification, eventHandler

                Dim handle As Integer = client.SubscribeEvents("", "OPCLabs.KitEventServer.2", 1000)

                Console.WriteLine("Processing event notifications for 1 minute...")
                Thread.Sleep(60 * 1000)

                client.UnsubscribeEvents(handle)
            End Using
        End Sub

        ' Notification event handler
        Private Shared Sub client_Notification(ByVal sender As Object, ByVal e As EasyAENotificationEventArgs)
            If Not e.Succeeded Then
                Console.WriteLine("*** Failure: {0}", e.ErrorMessageBrief)
                Exit Sub
            End If
            If e.EventData IsNot Nothing Then
                Console.WriteLine(e.EventData.Message)
            End If
        End Sub
    End Class
End Namespace
// This example shows how to subscribe to events with specified event attributes, and obtain the attribute values in event 
// notifications.

using System;
using System.Collections.Generic;
using System.Threading;
using OpcLabs.EasyOpc.AlarmsAndEvents;
using OpcLabs.EasyOpc.AlarmsAndEvents.OperationModel;
using OpcLabs.EasyOpc.DataAccess;
using OpcLabs.EasyOpc.OperationModel;

namespace DocExamples.AlarmsAndEvents._EasyAENotificationEventArgs
{
    class AttributeValues
    {
        public static void Main1()
        {
            // Instantiate the OPC-A&E client object.
            var aeClient = new EasyAEClient();

            // Instantiate the OPC-DA client object.
            var daClient = new EasyDAClient();

            var eventHandler = new EasyAENotificationEventHandler(aeClient_Notification);
            aeClient.Notification += eventHandler;

            // Inactivate the event condition (we will later activate it and receive the notification)
            daClient.WriteItemValue("", "OPCLabs.KitServer.2", "SimulateEvents.ConditionState1.Inactivate", true);

            var subscriptionFilter = new AESubscriptionFilter
            {
                Sources = new AENodeDescriptor[] { "Simulation.ConditionState1" }
            };

            // Prepare a dictionary holding requested event attributes for each event category
            // The event category IDs and event attribute IDs are hard-coded here, but can be obtained from the OPC 
            // server by querying as well.
            var returnedAttributesByCategory = new AEAttributeSetDictionary
            {
                [0x00ECFF02] = new long[] {0x00EB0003, 0x00EB0008}
            };

            Console.WriteLine("Subscribing to events...");
            int handle = aeClient.SubscribeEvents("", "OPCLabs.KitEventServer.2", 1000, null, subscriptionFilter,
                returnedAttributesByCategory);

            // Give the refresh operation time to complete
            Thread.Sleep(5 * 1000);

            // Trigger an event carrying specified attributes (activate the condition)
            try
            {
                daClient.WriteItemValue("", "OPCLabs.KitServer.2",
                    "SimulateEvents.ConditionState1.AttributeValues.15400963", 123456);
                daClient.WriteItemValue("", "OPCLabs.KitServer.2",
                    "SimulateEvents.ConditionState1.AttributeValues.15400968", "Some string value");
                daClient.WriteItemValue("", "OPCLabs.KitServer.2", "SimulateEvents.ConditionState1.Activate", true);
            }
            catch (OpcException opcException)
            {
                Console.WriteLine("*** Failure: {0}", opcException.GetBaseException().Message);
                return;
            }

            Console.WriteLine("Processing event notifications for 10 seconds...");
            Thread.Sleep(10 * 1000);

            aeClient.UnsubscribeEvents(handle);
        }

        // Notification event handler
        static void aeClient_Notification(object sender, EasyAENotificationEventArgs e)
        {
            if (!e.Succeeded)
            {
                Console.WriteLine("*** Failure: {0}", e.ErrorMessageBrief);
                return;
            }
            if (!e.Refresh && (!(e.EventData is null)))
            {
                // Display all received event attribute IDs and their corresponding values
                Console.WriteLine("Event attribute count: {0}", e.EventData.AttributeValues.Count);
                foreach (KeyValuePair<long, object> pair in e.EventData.AttributeValues)
                    Console.WriteLine("    {0}: {1}", pair.Key, pair.Value);
            }
        }
    }
}
# This example shows how to subscribe to events with specified event attributes, and obtain the attribute values in
# event notifications.

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

# Import .NET namespaces.
from OpcLabs.EasyOpc import *
from OpcLabs.EasyOpc.AlarmsAndEvents import *
from OpcLabs.EasyOpc.DataAccess import *
from OpcLabs.EasyOpc.OperationModel import *


# Notification event handler
def notification(sender, e):
    if not e.Succeeded:
        print('*** Failure: ', e.ErrorMessageBrief, sep='')
        return
    if (not e.Refresh) and (e.EventData is not None):
        # Display all received event attribute IDs and their corresponding values.
        print('Event attribute count: ', e.EventData.AttributeValues.Count, sep='')
        for pair in e.EventData.AttributeValues:
            print('    ', pair.Key, ': ', pair.Value, sep='')


# Instantiate the OPC-A&E client object.
aeClient = EasyAEClient()

# Instantiate the OPC-DA client object.
daClient = EasyDAClient()

#
aeClient.Notification += notification

# Inactivate the event condition (we will later activate it and receive the notification).
try:
    IEasyDAClientExtension.WriteItemValue(daClient, '', 'OPCLabs.KitServer.2',
                                          'SimulateEvents.ConditionState1.Inactivate', True)
except OpcException as opcException:
    print('*** Failure: ' + opcException.GetBaseException().Message)
    exit()

subscriptionFilter = AESubscriptionFilter()
subscriptionFilter.Sources = [AENodeDescriptor('Simulation.ConditionState1')]

# Prepare a dictionary holding requested event attributes for each event category.
# The event category IDs and event attribute IDs are hard-coded here, but can be obtained from the OPC
# server by querying as well.
returnedAttributesByCategory = AEAttributeSetDictionary()
returnedAttributesByCategory.Add(0x00ECFF02, [0x00EB0003, 0x00EB0008])

print('Subscribing to events...')
handle = IEasyAEClientExtension.SubscribeEvents(aeClient, '', 'OPCLabs.KitEventServer.2', 1000, None,
                                                subscriptionFilter, returnedAttributesByCategory)

# Give the refresh operation time to complete.
time.sleep(5)

# Trigger an event carrying specified attributes (activate the condition).
try:
    IEasyDAClientExtension.WriteItemValue(daClient, '', 'OPCLabs.KitServer.2',
                                          'SimulateEvents.ConditionState1.AttributeValues.15400963', 123456)
    IEasyDAClientExtension.WriteItemValue(daClient, '', 'OPCLabs.KitServer.2',
                                          'SimulateEvents.ConditionState1.AttributeValues.15400968', 'Some string value')
    IEasyDAClientExtension.WriteItemValue(daClient, '', 'OPCLabs.KitServer.2',
                                          'SimulateEvents.ConditionState1.Activate', True)
except OpcException as opcException:
    print('*** Failure: ' + opcException.GetBaseException().Message)
    exit()

print('Processing event notifications for 10 seconds...')
time.sleep(10)

aeClient.UnsubscribeEvents(handle)
aeClient.Notification -= notification

print('Finished.')
' This example shows how to subscribe to events with specified event attributes, and obtain the attribute values in event 
' notifications.

Imports System.Threading
Imports OpcLabs.EasyOpc.AlarmsAndEvents
Imports OpcLabs.EasyOpc.AlarmsAndEvents.OperationModel
Imports OpcLabs.EasyOpc.DataAccess
Imports OpcLabs.EasyOpc.OperationModel

Namespace AlarmsAndEvents._EasyAENotificationEventArgs
    Friend Class AttributeValues
        Public Shared Sub Main1()
            Dim aeClient = New EasyAEClient()
            Dim daClient = New EasyDAClient()

            Dim eventHandler = New EasyAENotificationEventHandler(AddressOf aeClient_Notification)
            AddHandler aeClient.Notification, eventHandler

            ' Inactivate the event condition (we will later activate it and receive the notification)
            daClient.WriteItemValue("", "OPCLabs.KitServer.2", "SimulateEvents.ConditionState1.Inactivate", True)

            Dim subscriptionFilter As New AESubscriptionFilter
            subscriptionFilter.Sources = New AENodeDescriptor() {"Simulation.ConditionState1"}

            ' Prepare a dictionary holding requested event attributes for each event category
            ' The event category IDs and event attribute IDs are hard-coded here, but can be obtained from the OPC 
            ' server by querying as well.
            Dim returnedAttributesByCategory = New AEAttributeSetDictionary()
            returnedAttributesByCategory(&HECFF02) = New Long() {&HEB0003, &HEB0008}

            Console.WriteLine("Subscribing to events...")
            Dim handle As Integer = aeClient.SubscribeEvents("", "OPCLabs.KitEventServer.2", 1000, Nothing, subscriptionFilter, returnedAttributesByCategory)

            ' Give the refresh operation time to complete
            Thread.Sleep(5 * 1000)

            ' Trigger an event carrying specified attributes (activate the condition)
            Try
                daClient.WriteItemValue("", "OPCLabs.KitServer.2", "SimulateEvents.ConditionState1.AttributeValues.15400963", 123456)
                daClient.WriteItemValue("", "OPCLabs.KitServer.2", "SimulateEvents.ConditionState1.AttributeValues.15400968", "Some string value")
                daClient.WriteItemValue("", "OPCLabs.KitServer.2", "SimulateEvents.ConditionState1.Activate", True)
            Catch opcException As OpcException
                Console.WriteLine("*** Failure: {0}", opcException.GetBaseException().Message)
                Exit Sub
            End Try

            Console.WriteLine("Processing event notifications for 10 seconds...")
            Thread.Sleep(10 * 1000)

            aeClient.UnsubscribeEvents(handle)
        End Sub

        ' Notification event handler
        Private Shared Sub aeClient_Notification(ByVal sender As Object, ByVal e As EasyAENotificationEventArgs)
            If Not e.Succeeded Then
                Console.WriteLine("*** Failure: {0}", e.ErrorMessageBrief)
                Exit Sub
            End If

            If (Not e.Refresh) AndAlso (e.EventData IsNot Nothing) Then
                ' Display all received event attribute IDs and their corresponding values
                Console.WriteLine("Event attribute count: {0}", e.EventData.AttributeValues.Count)
                For Each pair As KeyValuePair(Of Long, Object) In e.EventData.AttributeValues
                    Console.WriteLine("    {0}: {1}", pair.Key, pair.Value)
                Next pair
            End If
        End Sub
    End Class
End Namespace
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