Connectivity Software User's Guide and Reference
DataSourceConnectionFailure(ISparkplugProducer,String,Int32) Method
Example 



OpcLabs.EasySparkplug Assembly > OpcLabs.EasySparkplug Namespace > ISparkplugProducerExtension Class > DataSourceConnectionFailure Method : DataSourceConnectionFailure(ISparkplugProducer,String,Int32) Method
The Sparkplug producer that will perform the operation.

The value of this parameter cannot be null (Nothing in Visual Basic).

The message that describes the cause of the failure.

The value of this parameter cannot be null (Nothing in Visual Basic).

The interval, in milliseconds, in which reconnection wil lbe attempted.
Indicates that the data source connection for the edge node or device has failed, specifying an error message and reconnection interval.
Syntax
'Declaration
 
<ExtensionAttribute()>
Public Overloads Shared Sub DataSourceConnectionFailure( _
   ByVal producer As ISparkplugProducer, _
   ByVal message As String, _
   ByVal reconnectIntervalMilliseconds As Integer _
) 
'Usage
 
Dim producer As ISparkplugProducer
Dim message As String
Dim reconnectIntervalMilliseconds As Integer
 
ISparkplugProducerExtension.DataSourceConnectionFailure(producer, message, reconnectIntervalMilliseconds)
[Extension()]
public static void DataSourceConnectionFailure( 
   ISparkplugProducer producer,
   string message,
   int reconnectIntervalMilliseconds
)
[Extension()]
public:
static void DataSourceConnectionFailure( 
   ISparkplugProducer^ producer,
   String^ message,
   int reconnectIntervalMilliseconds
) 

Parameters

producer
The Sparkplug producer that will perform the operation.

The value of this parameter cannot be null (Nothing in Visual Basic).

message
The message that describes the cause of the failure.

The value of this parameter cannot be null (Nothing in Visual Basic).

reconnectIntervalMilliseconds
The interval, in milliseconds, in which reconnection wil lbe attempted.
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.

Remarks

This is an extension method (info: C#, VB.NET). In languages that have support for extensions methods (such as C# and VB.NET), you can use the extension method as if it were a regular method on the object that is its first parameter. In other languages (such as with Python.NET), you will call the extension as a static method, and pass it the object on which it acts as its first parameter.

 

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