Connectivity Software User's Guide and Reference
DataSourceConditionChanged Event (SparkplugDevice)
Example 



OpcLabs.EasySparkplug Assembly > OpcLabs.EasySparkplug Namespace > SparkplugDevice Class : DataSourceConditionChanged Event
Raised when the connected condition of the data source for the edge node or device has changed.
Syntax
'Declaration
 
Public Event DataSourceConditionChanged As ConnectedConditionChangedEventHandler
'Usage
 
Dim instance As SparkplugDevice
Dim handler As ConnectedConditionChangedEventHandler
 
AddHandler instance.DataSourceConditionChanged, handler
public event ConnectedConditionChangedEventHandler DataSourceConditionChanged
public:
event ConnectedConditionChangedEventHandler^ DataSourceConditionChanged
Event Data

The event handler receives an argument of type ConnectedConditionChangedEventArgs containing data related to this event. The following ConnectedConditionChangedEventArgs properties provide information specific to this event.

PropertyDescription
Indicates the state of the connection.  
Diagnostics information (such as warnings) assembled during the operation. (Inherited from OpcLabs.BaseLib.OperationModel.OperationEventArgs)
Count of diagnostic information elements assembled during the operation. (Inherited from OpcLabs.BaseLib.OperationModel.OperationEventArgs)
Textual summary of diagnostics information, one message per line. (Inherited from OpcLabs.BaseLib.OperationModel.OperationEventArgs)
Gets or sets the error ID of the error. (Inherited from OpcLabs.BaseLib.OperationModel.OperationEventArgs)
Gets or sets a message that describes the current exception. (Inherited from OpcLabs.BaseLib.OperationModel.OperationEventArgs)
The first line of the error message. (Inherited from OpcLabs.BaseLib.OperationModel.OperationEventArgs)
Gets the current exception. Contains null reference when no exception. (Inherited from OpcLabs.BaseLib.OperationModel.OperationEventArgs)
Indicates whether the object is now connected.  
A normalized OpcLabs.BaseLib.OperationModel.OperationEventArgs.Diagnostics collection. (Inherited from OpcLabs.BaseLib.OperationModel.OperationEventArgs)
A normalized OpcLabs.BaseLib.OperationModel.OperationEventArgs.Exception object, or null if there was no error. (Inherited from OpcLabs.BaseLib.OperationModel.OperationEventArgs)
When disconnected, contains time to next reconnection attempt. In milliseconds.  
Gets or sets statistics for the connected condition at the moment the event was generated.  
Status information corresponding to the contents of the event arguments.  
Gets indication whether the operation has succeeded. (Inherited from OpcLabs.BaseLib.OperationModel.OperationEventArgs)
Remarks

This event is raised

  • When the data source starts connecting (or reconnecting).
  • When the data source has successfully connected.
  • When the data source fails to connect properly.
  • When the data source starts disconnecting.
  • When the data source has disconnected.

The OpcLabs.BaseLib.OperationModel.OperationEventArgs.Exception property of the event arguments can be used to determine whether the connection or disconnection operation has been successful.

 

Sparkplug is a trademark of Eclipse Foundation, Inc. "MQTT" is a trademark of the OASIS Open standards consortium. Other related terms are trademarks of their respective owners. Any use of these terms on this site is for descriptive purposes only and does not imply any sponsorship, endorsement or affiliation.

Example
// This example shows how to implement custom data source connection and disconnection handling for a Sparkplug device.
//
// You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
// program, to subscribe to the edge node data. 
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
// Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using OpcLabs.EasySparkplug;
using OpcLabs.EasySparkplug.OperationModel;
using System;
using Timer = System.Timers.Timer;

namespace SparkplugDocExamples.EdgeNode._SparkplugDevice
{
     class ConnectDataSource
    {
        static public void Main1()
        {
            // Note that the default port for the "mqtt" scheme is 1883.
            var hostDescriptor = new SparkplugHostDescriptor("mqtt://localhost");

            // Instantiate the edge node object.
            var edgeNode = new EasySparkplugEdgeNode(hostDescriptor, "easyGroup", "easySparkplugDemo");

            // Hook the SystemConnectionStateChanged event to handle system connection state changes.
            edgeNode.SystemConnectionStateChanged += (sender, eventArgs) =>
            {
                // Display the new connection state (such as when the connection to the broker succeeds or fails).
                Console.WriteLine($"{nameof(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}");
            };

            // Define a metric on the edge node providing random integers.
            var random = new Random();
            edgeNode.Metrics.Add(new SparkplugMetric("MyMetric1").ReadValueFunction(() => random.Next()));

            // Create a device.
            SparkplugDevice device = SparkplugDevice.CreateIn(edgeNode, "Device");

            // Hook the DataSourceConditionChanged event to handle data source connection state changes.
            device.DataSourceConditionChanged += (sender, eventArgs) =>
            {
                // Display the new data source condition.
                Console.WriteLine($"{nameof(SparkplugDevice.DataSourceConditionChanged)}: {eventArgs}");
            };

            // Hook the events to connect and disconnect the device data source.
            device.ConnectDataSource += DeviceOnConnectDataSource;
            device.DisconnectDataSource += DeviceOnDisconnectDataSource;

            // Define a metric on the device providing random integers.
            device.Metrics.Add(new SparkplugMetric("MyMetric2").ReadValueFunction(() => random.Next()));

            // Start the edge node.
            Console.WriteLine("The edge node is starting...");
            edgeNode.Start();

            Console.WriteLine("The edge node is started.");
            Console.WriteLine();

            // Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...");
            Console.ReadLine();

            // Stop the edge node.
            Console.WriteLine("The edge node is stopping...");
            edgeNode.Stop();

            Console.WriteLine("The edge node is stopped.");
        }

        /// <summary>
        /// Handles the <see cref="SparkplugDevice.ConnectDataSource"/> event.
        /// </summary>
        static private void DeviceOnConnectDataSource(object sender, SparkplugProducerProcessedEventArgs eventArgs)
        {
            // The event sender is the device.
            var device = (SparkplugDevice)sender;
            Console.WriteLine(nameof(device.ConnectDataSource));

            // Simulate a connection to the data source that takes 5 seconds to either succeed or fail.
            // In a real application, you would connect to the actual data source here.
            var timer = new Timer(5 * 1000) { AutoReset = false };
            timer.Elapsed += (s, e) =>
            {
                if (Random.Next(0, 3) == 0)
                {
                    // Simulate a successful connection to the data source. Reconnect after 10 seconds.
                    device.DataSourceConnectionSuccess();
                }
                else
                {
                    // Simulate a failure to connect to the data source.
                    device.DataSourceConnectionFailure(
                        "Simulated connection failure.", 
                        10*1000);
                }
            };
            timer.Start();

            // Indicate that the event is handled. This is necessary to do, otherwise the default behavior would kick in,
            // and the data source would be considered immediately successfully connected.
            eventArgs.Handled = true; 
        }

        /// <summary>
        /// Handles the <see cref="SparkplugDevice.DisconnectDataSource"/> event.
        /// </summary>
        static private void DeviceOnDisconnectDataSource(object sender, SparkplugProducerProcessedEventArgs eventArgs)
        {
            // The event sender is the device.
            var device = (SparkplugDevice)sender;
            Console.WriteLine(nameof(device.DisconnectDataSource));
            
            // Simulate a disconnection from the data source that takes 5 seconds.
            // In a real application, you would disconnect from the actual data source here.
            var timer = new Timer(5 * 1000) { AutoReset = false };
            timer.Elapsed += (s, e) => device.DataSourceDisconnectionSuccess();
            timer.Start();

            // Indicate that the event is handled. This is necessary to do, otherwise the default behavior would kick in,
            // and the data source would be considered immediately successfully disconnected.
            eventArgs.Handled = true;
        }


        static private readonly Random Random = new Random();
    }
}
' This example shows how to implement custom data source connection and disconnection handling for a Sparkplug device.
'
' You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
' program, to subscribe to the edge node data.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-ConnectivityStudio/Latest/examples.html .
' Sparkplug examples in C# on GitHub: https://github.com/OPCLabs/Examples-ConnectivityStudio-CSharp .
' Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
' a commercial license in order to use Online Forums, and we reply to every post.

Imports OpcLabs.EasySparkplug
Imports OpcLabs.EasySparkplug.OperationModel
Imports Timer = System.Timers.Timer

Namespace Global.SparkplugDocExamples.EdgeNode._SparkplugDevice
    Class ConnectDataSource
        Public Shared Sub Main1()
            ' Note that the default port for the "mqtt" scheme is 1883.
            Dim hostDescriptor = New SparkplugHostDescriptor("mqtt://localhost")

            ' Instantiate the edge node object.
            Dim edgeNode = New EasySparkplugEdgeNode(hostDescriptor, "easyGroup", "easySparkplugDemo")

            ' Hook the SystemConnectionStateChanged event to handle system connection state changes.
            AddHandler edgeNode.SystemConnectionStateChanged,
                Sub(sender, eventArgs)
                    ' Display the new connection state (such as when the connection to the broker succeeds or fails).
                    Console.WriteLine($"{NameOf(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}")
                End Sub

            ' Define a metric providing random integers.
            Dim random = New Random()
            edgeNode.Metrics.Add(New SparkplugMetric("MyMetric").ReadValueFunction(Function() random.Next()))

            ' Create a device.
            Dim device As SparkplugDevice = SparkplugDevice.CreateIn(edgeNode, "Device")

            ' Hook the DataSourceConditionChanged event to handle data source connection state changes.
            AddHandler device.DataSourceConditionChanged,
                Sub(sender, eventArgs)
                    ' Display the new data source condition.
                    Console.WriteLine($"{NameOf(SparkplugDevice.DataSourceConditionChanged)}: {eventArgs}")
                End Sub

            ' Hook the events to connect and disconnect the device data source.
            AddHandler device.ConnectDataSource, AddressOf DeviceOnConnectDataSource
            AddHandler device.DisconnectDataSource, AddressOf DeviceOnDisconnectDataSource

            ' Define a metric on the device providing random integers.
            device.Metrics.Add(New SparkplugMetric("MyMetric2").ReadValueFunction(Function() random.Next()))

            ' Start the edge node.
            Console.WriteLine("The edge node is starting...")
            edgeNode.Start()

            Console.WriteLine("The edge node is started.")
            Console.WriteLine()

            ' Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...")
            Console.ReadLine()

            ' Stop the edge node.
            Console.WriteLine("The edge node is stopping...")
            edgeNode.Stop()

            Console.WriteLine("The edge node is stopped.")
        End Sub

        ''' <summary>
        ''' Handles the <see cref="SparkplugDevice.ConnectDataSource"/> event.
        ''' </summary>
        Private Shared Sub DeviceOnConnectDataSource(ByVal sender As Object, ByVal eventArgs As SparkplugProducerProcessedEventArgs)
            ' The event sender is the device.
            Dim device = CType(sender, SparkplugDevice)
            Console.WriteLine(NameOf(device.ConnectDataSource))

            ' Simulate a connection to the data source that takes 5 seconds to either succeed or fail.
            ' In a real application, you would connect to the actual data source here.
            Dim timer = New Timer(5 * 1000) With {.AutoReset = False}
            AddHandler timer.Elapsed,
                Sub(s, e)
                    If Random.Next(0, 3) = 0 Then
                        ' Simulate a successful connection to the data source. Reconnect after 10 seconds.
                        device.DataSourceConnectionSuccess()
                    Else
                        ' Simulate a failure to connect to the data source.
                        device.DataSourceConnectionFailure(
                            "Simulated connection failure.",
                            10 * 1000)
                    End If
                End Sub
            timer.Start()

            ' Indicate that the event is handled. This is necessary to do, otherwise the default behavior would kick in,
            ' and the data source would be considered immediately successfully connected.
            eventArgs.Handled = True
        End Sub

        ''' <summary>
        ''' Handles the <see cref="SparkplugDevice.DisconnectDataSource"/> event.
        ''' </summary>
        Private Shared Sub DeviceOnDisconnectDataSource(ByVal sender As Object, ByVal eventArgs As SparkplugProducerProcessedEventArgs)
            ' The event sender is the device.
            Dim device = CType(sender, SparkplugDevice)
            Console.WriteLine(NameOf(device.DisconnectDataSource))

            ' Simulate a disconnection from the data source that takes 5 seconds.
            ' In a real application, you would disconnect from the actual data source here.
            Dim timer = New Timer(5 * 1000) With {.AutoReset = False}
            AddHandler timer.Elapsed, Sub(s, e) device.DataSourceDisconnectionSuccess()
            timer.Start()

            ' Indicate that the event is handled. This is necessary to do, otherwise the default behavior would kick in,
            ' and the data source would be considered immediately successfully disconnected.
            eventArgs.Handled = True
        End Sub

        Private Shared ReadOnly Random As Random = New Random()
    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