QuickOPC User's Guide and Reference
EasyAEClient Class
Members 



OpcLabs.EasyOpcClassic Assembly > OpcLabs.EasyOpc.AlarmsAndEvents Namespace : EasyAEClient Class

The EasyAEClient object is the main object that allows simple access to OPC Alarms&Events servers.

The core members of this object come from the IEasyAEClient interface.

Object Model
EasyAEClient ClassEasyAEAdaptableParameters ClassEasyAEInstanceParameters ClassEasyAEAdaptableParameters ClassStringObjectDictionary ClassEasyAEClient ClassEasyAESharedParameters Class
Syntax
'Declaration
 
<CLSCompliantAttribute(True)>
<ComDefaultInterfaceAttribute(OpcLabs.EasyOpc.AlarmsAndEvents.ComTypes._EasyAEClient)>
<ComSourceInterfacesAttribute(OpcLabs.EasyOpc.AlarmsAndEvents.ComTypes.DEasyAEClientEvents)>
<ComVisibleAttribute(True)>
<GuidAttribute("3643545B-221F-4960-BF47-8A4DDEC81A67")>
<TypeConverterAttribute(System.ComponentModel.ExpandableObjectConverter)>
<DesignerCategoryAttribute("Component")>
<SerializableAttribute()>
Public NotInheritable Class EasyAEClient 
   Inherits OpcLabs.BaseLib.Widgets.NotifyingWidget
   Implements OpcLabs.BaseLib.Licensing.ILicensingContextHolder, OpcLabs.BaseLib.Widgets.ComTypes._NotifyingWidget, OpcLabs.BaseLib.Widgets.ComTypes._Widget, OpcLabs.BaseLib.Widgets.IWidget, OpcLabs.EasyOpc.AlarmsAndEvents.ComTypes._EasyAEClient, IEasyAEClient, IEasyAEClientEnqueuing, IEasyAEClientSettings, System.ComponentModel.IComponent, System.ICloneable, System.IDisposable, System.IServiceProvider, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable 
'Usage
 
Dim instance As EasyAEClient
[CLSCompliant(true)]
[ComDefaultInterface(OpcLabs.EasyOpc.AlarmsAndEvents.ComTypes._EasyAEClient)]
[ComSourceInterfaces(OpcLabs.EasyOpc.AlarmsAndEvents.ComTypes.DEasyAEClientEvents)]
[ComVisible(true)]
[Guid("3643545B-221F-4960-BF47-8A4DDEC81A67")]
[TypeConverter(System.ComponentModel.ExpandableObjectConverter)]
[DesignerCategory("Component")]
[Serializable()]
public sealed class EasyAEClient : OpcLabs.BaseLib.Widgets.NotifyingWidget, OpcLabs.BaseLib.Licensing.ILicensingContextHolder, OpcLabs.BaseLib.Widgets.ComTypes._NotifyingWidget, OpcLabs.BaseLib.Widgets.ComTypes._Widget, OpcLabs.BaseLib.Widgets.IWidget, OpcLabs.EasyOpc.AlarmsAndEvents.ComTypes._EasyAEClient, IEasyAEClient, IEasyAEClientEnqueuing, IEasyAEClientSettings, System.ComponentModel.IComponent, System.ICloneable, System.IDisposable, System.IServiceProvider, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable  
[CLSCompliant(true)]
[ComDefaultInterface(OpcLabs.EasyOpc.AlarmsAndEvents.ComTypes._EasyAEClient)]
[ComSourceInterfaces(OpcLabs.EasyOpc.AlarmsAndEvents.ComTypes.DEasyAEClientEvents)]
[ComVisible(true)]
[Guid("3643545B-221F-4960-BF47-8A4DDEC81A67")]
[TypeConverter(System.ComponentModel.ExpandableObjectConverter)]
[DesignerCategory("Component")]
[Serializable()]
public ref class EasyAEClient sealed : public OpcLabs.BaseLib.Widgets.NotifyingWidget, OpcLabs.BaseLib.Licensing.ILicensingContextHolder, OpcLabs.BaseLib.Widgets.ComTypes._NotifyingWidget, OpcLabs.BaseLib.Widgets.ComTypes._Widget, OpcLabs.BaseLib.Widgets.IWidget, OpcLabs.EasyOpc.AlarmsAndEvents.ComTypes._EasyAEClient, IEasyAEClient, IEasyAEClientEnqueuing, IEasyAEClientSettings, System.ComponentModel.IComponent, System.ICloneable, System.IDisposable, System.IServiceProvider, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable  
Remarks

 

In This Topic

General

Subscription is initiated by calling the  SubscribeEvents method. The component will call handlers for Notification event for each event that satisfies the filter criteria of the created subscription. Obviously, you first need to hook up event handler for that event, and in order to prevent event loss, you should do it before subscribing.

Events may be generated quite rapidly. Your application needs to specify the notification rate, which effectively tells the OPC Alarms and Events server that you do not need to receive event notifications any faster than that.

If you want to subscribe to particular set of OPC Events, call the SubscribeEvents method. You can pass in individual arguments for machine name, server class, and notification rate.

// 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 "../../../Assemblies/net47/OpcLabs.EasyOpcClassic.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.

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

Namespace DocExamples.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 and display the event message with each notification. It also shows how to
// unsubscribe afterwards.

type
  TClientEventHandlers = class
    // Notification event handler
    procedure OnNotification(
      ASender: TObject;
      sender: OleVariant;
      const eventArgs: _EasyAENotificationEventArgs);
  end;

procedure TClientEventHandlers.OnNotification(
  ASender: TObject;
  sender: OleVariant;
  const eventArgs: _EasyAENotificationEventArgs);
begin
  if not eventArgs.Succeeded then
    WriteLn(Format('*** Failure: %s', [eventArgs.ErrorMessageBrief]));
  if eventArgs.EventData <> nil then
      WriteLn(eventArgs.EventData.Message);
end;

class procedure SubscribeEvents.Main;
var
  Client: TEasyAEClient;
  ClientEventHandlers: TClientEventHandlers;
  Handle: Integer;
  ServerDescriptor: _ServerDescriptor;
  State: OleVariant;
  SubscriptionParameters: _AESubscriptionParameters;
begin
  ServerDescriptor := CoServerDescriptor.Create;
  ServerDescriptor.ServerClass := 'OPCLabs.KitEventServer.2';

  // Instantiate the client object and hook events
  Client := TEasyAEClient.Create(nil);
  ClientEventHandlers := TClientEventHandlers.Create;
  Client.OnNotification := ClientEventHandlers.OnNotification;

  WriteLn('Subscribing events...');
  SubscriptionParameters := CoAESubscriptionParameters.Create;
  SubscriptionParameters.NotificationRate := 1000;
  Handle := Client.SubscribeEvents(ServerDescriptor, SubscriptionParameters, true, State);

  WriteLn('Processing event notifications for 1 minute...');
  PumpSleep(60*1000);

  WriteLn('Unsubscribing events...');
  Client.UnsubscribeEvents(Handle);

  WriteLn('Finished.');
  FreeAndNil(Client);
  FreeAndNil(ClientEventHandlers);
end;
// This example shows how to subscribe to events and display the event message with each notification. It also shows how to
// unsubscribe afterwards.

class DEasyEAClientEvents {
    function Notification($Sender, $E)
    {
        if (!($E->Succeeded))
        {
            printf("*** Failure: %s\n", $E->ErrorMessageBrief);
            Exit();
        }

        if (!is_null($E->EventData))
        {
            print $E->EventData->Message;
            print "\n";
        }
    }
}

$ServerDescriptor = new COM("OpcLabs.EasyOpc.ServerDescriptor");
$ServerDescriptor->ServerClass = "OPCLabs.KitEventServer.2";

$Client = new COM("OpcLabs.EasyOpc.AlarmsAndEvents.EasyAEClient");
$Events = new DEasyEAClientEvents();
com_event_sink($Client, $Events, "DEasyEAClientEvents");

print "Subscribing events...\n";
$SubscriptionParameters = new COM("OpcLabs.EasyOpc.AlarmsAndEvents.AESubscriptionParameters");
$SubscriptionParameters->NotificationRate = 1000;
$handle = $Client->SubscribeEvents($ServerDescriptor, $SubscriptionParameters, TRUE, NULL);

print "Processing event notifications for 1 minute...\n";
$startTime = time(); do { com_message_pump(1000); } while (time() < $startTime + 60);

print "Unsubscribing events...\n";
$Client->UnsubscribeEvents($handle);

print "Finished.\n";
Rem This example shows how to subscribe to events and display the event message with each notification. It also shows how to
Rem unsubscribe afterwards.

Option Explicit

Dim ServerDescriptor: Set ServerDescriptor = CreateObject("OpcLabs.EasyOpc.ServerDescriptor")
ServerDescriptor.ServerClass = "OPCLabs.KitEventServer.2"

Dim Client: Set Client = CreateObject("OpcLabs.EasyOpc.AlarmsAndEvents.EasyAEClient")
WScript.ConnectObject Client, "Client_"

WScript.Echo "Subscribing events..."
Dim SubscriptionParameters: Set SubscriptionParameters = CreateObject("OpcLabs.EasyOpc.AlarmsAndEvents.AESubscriptionParameters")
SubscriptionParameters.NotificationRate = 1000
Dim handle: handle = Client.SubscribeEvents(ServerDescriptor, SubscriptionParameters, True, Nothing)

WScript.Echo "Processing event notifications for 1 minute..."
WScript.Sleep 60*1000

WScript.Echo "Unsubscribing events..."
Client.UnsubscribeEvents handle

WScript.Echo "Finished."



Rem Notification event handler
Sub Client_Notification(Sender, e)
    If Not e.Succeeded Then
        WScript.Echo "*** Failure: " & e.ErrorMessageBrief
        Exit Sub
    End If

    If Not e.EventData Is Nothing Then WScript.Echo e.EventData.Message
End Sub

 

Optionally, you can specify a subscription filter; it is a separate object of AESubscriptionFilterType type. Other optional parameters are attributes that should be returned in event notifications (separate set of attributes for each event category is needed), and the “active” and “refresh when active” flags. You can also pass in a State argument of any type. When any event notification is generated, the State argument is then passed to the Notification event handler in the EasyAENotificationEventArgs.Arguments.State object.

You can alternatively pass in a ServerDescriptor in place of machine name and server class arguments. You can also replace the individual notification rate, subscription filter, and returned attributes arguments by passing in an AESubscriptionParameters object.

The State argument is typically used to provide some sort of correlation between objects in your application, and the event notifications. For example, if you are programming an HMI application and you want the event handler to update the control that displays the event messages, you may want to set the State argument to the control object itself. When the event notification arrives, you simply update the control indicated by the State property of EasyAENotificationEventArgs, without having to look it up.

The “refresh when active” flag enables a functionality that is useful if you want to keep a “copy” of condition states (that primarily exist in the OPC server) in your application. When this flag is set, the component will automatically perform a subscription Refresh (see further below) after the connection is first time established, and also each time it is reestablished (after a connection loss). This way, the component assures that your code will get notifications that allow you to “reconstruct” the state of event conditions at any given moment.

Note: It is NOT an error to subscribe to the same set of events twice (or more times), even with precisely the same parameters. You will receive separate subscription handles, and with regard to your application, this situation will look no different from subscribing to different set of events.

More examples

The example below logs OPC Alarms and Events notifications into an XML file.

The main program:

// Logs OPC Alarms and Events notifications into an XML file.

using System;
using System.Diagnostics;
using System.Xml;
using System.Xml.Serialization;
using OpcLabs.EasyOpc.AlarmsAndEvents;
using OpcLabs.EasyOpc.AlarmsAndEvents.OperationModel;

namespace XmlEventLogger
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Starting up...");
            var xmlSerializer = new XmlSerializer(typeof(EasyAENotificationEventArgs));
            var xmlWriter = XmlWriter.Create("OpcEvents.xml", new XmlWriterSettings
            {
                Indent = true,
                CloseOutput = true
            });
            // The root element can have any name you need, but the name below also allows reading the log back as .NET array
            xmlWriter.WriteStartElement("ArrayOfEasyAENotificationEventArgs");

            Console.WriteLine("Logging events for 30 seconds...");
            int handle = EasyAEClient.SharedInstance.SubscribeEvents("", "OPCLabs.KitEventServer.2", 100,
               (_, eventArgs) =>
                   {
                       Debug.Assert(!(eventArgs is null));
                       Console.Write(".");
                       xmlSerializer.Serialize(xmlWriter, eventArgs);
                   });
            System.Threading.Thread.Sleep(30 * 1000);

            Console.WriteLine();
            Console.WriteLine("Shutting down...");
            EasyAEClient.SharedInstance.UnsubscribeEvents(handle);
            xmlWriter.WriteEndElement();    // not really necessary - XmlWriter would write the end tag for us anyway
            xmlWriter.Close();

            Console.WriteLine("Finished.");
        }
    }
}
' Logs OPC Alarms and Events notifications into an XML file.

Imports System.Xml
Imports System.Xml.Serialization
Imports OpcLabs.EasyOpc.AlarmsAndEvents
Imports OpcLabs.EasyOpc.AlarmsAndEvents.OperationModel


Friend Class Program
    Shared WithEvents _client As New EasyAEClient
    Shared ReadOnly XmlSerializer As New XmlSerializer(GetType(EasyAENotificationEventArgs))
    Shared _xmlWriter As XmlWriter

    Shared Sub Main()
        Console.WriteLine("Starting up...")
        _xmlWriter = XmlWriter.Create("OpcEvents.xml", New XmlWriterSettings With {.Indent = True, .CloseOutput = True})
        ' The root element can have any name you need, but the name below also allows reading the log back as .NET array
        _xmlWriter.WriteStartElement("ArrayOfEasyAENotificationEventArgs")

        Console.WriteLine("Logging events for 30 seconds...")
        Dim handle As Integer = _client.SubscribeEvents("", "OPCLabs.KitEventServer.2", 100)
        Threading.Thread.Sleep(30 * 1000)

        Console.WriteLine()
        Console.WriteLine("Shutting down...")
        _client.UnsubscribeEvents(handle)
        _xmlWriter.WriteEndElement() ' not really necessary - XmlWriter would write the end tag for us anyway
        _xmlWriter.Close()

        Console.WriteLine("Finished.")
    End Sub

    Private Shared Sub Notification(ByVal sender As Object, ByVal eventArgs As Object) Handles _client.Notification
        Debug.Assert(eventArgs IsNot Nothing)
        Console.Write(".")
        XmlSerializer.Serialize(_xmlWriter, eventArgs)
    End Sub
End Class

 

 

 

Inheritance Hierarchy

System.Object
   System.MarshalByRefObject
      System.ComponentModel.Component
         OpcLabs.BaseLib.Widgets.Widget
            OpcLabs.BaseLib.Widgets.NotifyingWidget
               OpcLabs.EasyOpc.AlarmsAndEvents.EasyAEClient

Requirements

Target Platforms: .NET Framework: Windows 10, Windows Server 2012, Windows Server 2016; .NET Core, .NET 5: Linux, macOS, Microsoft Windows

See Also

Reference

EasyAEClient Members
OpcLabs.EasyOpc.AlarmsAndEvents Namespace