Connectivity Software User's Guide and Reference
Rapid Toolkit for Sparkplug Producer Error Model
Rapid Toolkit for Sparkplug > Concepts > Developing Sparkplug Edge Nodes > Rapid Toolkit for Sparkplug Producer Error Model
In This Topic

Operation Errors in Synchronous Operations

Most operation methods used in Rapid Toolkit for Sparkplug producer development operate synchronously (the notable exception to this are the Start and Stop methods). Such methods report errors by throwing an exception, and the possible exceptions are listed in the .NET Assemblies Reference.

Operation Errors in Asynchronous Operations

The most important asynchronous operations used in Rapid Toolkit for Sparkplug producer development are invoked by the Start Method and Stop Method on the EasySparkplugEdgeNode Class. Aside from asynchronous execution errors and usage errors, methods that invoke asynchronous operations do not throw any exceptions. Instead, the operation outcome is indicated through events that you can handle. In case of the Start and Stop methods, the SystemConnectionStateChanged Event has this purpose (for more information, see Rapid Toolkit for Sparkplug Operation Monitoring Services).

Publishing Errors

publishing error occurs when the Sparkplug producer (edge node or device) encounters an error while publishing data.

Publishing error can occur:

Publishing errors are reported through the PublishingError Event on the corresponding Sparkplug edge node (EasySparkplugEdgeNode Class) or device (SparkplugDevice Class). This event represents an error related to publishing of a single message. By default, publishing error is simply reported through this event, but has no other consequences. You can handle this event to implement functionality such as custom error handling or logging for publishing failures.

In some configurations and situations, it is expected to receive publishing errors. For example, if the producer is set to connect to its data source and publish data when the component starts, and the edge node is configured to use primary host application and the application is offline, publishing will fail because the edge node will also be offline.

The example below shows how to process an event when a publishing error occurs.

.NET

// This example shows how to get notified when the Sparkplug edge encounters a failure during message publishing.
//
// 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 System;
using System.Threading;
using OpcLabs.EasySparkplug;
using Timer = System.Timers.Timer;

namespace SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
{
     class PublishingError
    {
        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");

            // Configure the edge node so that we will publish data fully manually.
            edgeNode.PublishingInterval = Timeout.Infinite;
            edgeNode.ReportByException = true;
            
            // 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}");
            };

            // Hook the PublishingError event to handle errors that occur during publishing.
            edgeNode.PublishingError += (sender, eventArgs) =>
            {
                // Display the error that occurred.
                Console.WriteLine($"{nameof(EasySparkplugEdgeNode.PublishingError)}: {eventArgs}");
            };

            // Define a metric providing random integers.
            var random = new Random();
            SparkplugMetric myMetric = SparkplugMetric.CreateIn(edgeNode, "MyMetric").ValueType<int>();

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

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

            // Create a timer for publishing the data, and start it.
            var timer = new Timer
            {
                Interval = 2*1000,  // 2 seconds
                AutoReset = true,
            };
            timer.Elapsed += (sender, eventArgs) =>
                edgeNode.PublishDataPayload(new SparkplugPayload(myMetric.Name, new SparkplugMetricData(random.Next())));
            timer.Start();

            // You can simulate a publishing error e.g. by stopping the MQTT broker or disconnecting the network cable.
            // Note that without the manual publishing, triggering the error would not be easy, as the edge node
            // automatically pauses its own publishing attempts when it detects a connection failure.
            
            // Let the user decide when to stop.
            Console.WriteLine("Press Enter to stop the edge node...");
            Console.ReadLine();
            
            // Stop the timer.
            timer.Stop();

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

            Console.WriteLine("The edge node is stopped.");
        }
    }
}
' This example shows how to get notified when the Sparkplug edge encounters a failure during message publishing.
'
' 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 System.Threading
Imports OpcLabs.EasySparkplug
Imports Timer = System.Timers.Timer

Namespace Global.SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
    Class PublishingError
        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")

            ' Configure the edge node so that we will publish data fully manually.
            edgeNode.PublishingInterval = Timeout.Infinite
            edgeNode.ReportByException = True

            ' 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

            ' Hook the PublishingError event to handle errors that occur during publishing.
            ' application.
            AddHandler edgeNode.PublishingError,
                Sub(sender, eventArgs)
                    ' Display the error that occurred.
                    Console.WriteLine($"{NameOf(EasySparkplugEdgeNode.PublishingError)}: {eventArgs}")
                End Sub

            ' Define a metric providing random integers.
            Dim random = New Random()
            Dim myMetric As SparkplugMetric = SparkplugMetric.CreateIn(edgeNode, "MyMetric").ValueType(Of Integer)()

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

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

            ' Create a timer for publishing the data, and start it.
            Dim timer = New Timer With
            {
                .Interval = 2 * 1000, ' 2 seconds
                .AutoReset = True
            }
            AddHandler timer.Elapsed,
                Sub(sender, EventArgs)
                    edgeNode.PublishDataPayload(New SparkplugPayload(myMetric.Name, New SparkplugMetricData(random.Next())))
                End Sub
            timer.Start()

            ' You can simulate a publishing error e.g. by stopping the MQTT broker or disconnecting the network cable.
            ' Note that without the manual publishing, triggering the error would not be easy, as the edge node
            ' automatically pauses its own publishing attempts when it detects a connection failure.

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

            ' Stop the timer.
            timer.Stop()

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

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

 

Write Errors

A write error occurs when the Sparkplug producer (edge node or device) has received data for the metric (through a Sparkplug command), but the metric data cannot be updated, e.g. because of the data type mismatch.

Possible causes of the write error include:

Write errors are reported through the WriteError Event on the corresponding Sparkplug edge node (EasySparkplugEdgeNode Class) or device (SparkplugDevice Class). The event arguments include the name of the metric that has encountered the write error, in the MetricName Property.

Exceptions in Event Handlers

Event handlers that you add to events on various Rapid Toolkit for Sparkplug objects are not supposed to throw any exceptions (except for asynchronous execution errors and usage errors). If an exception is thrown anyway, the Rapid Toolkit for Sparkplug handles it by creating an event log entry with information about the exception. For more information, see Component Event Logging.

 

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.

See Also