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

Introduction

When implementing a Sparkplug edge node with Rapid Toolkit for Sparkplug, your code needs to perform the following basic steps:

  1. Create an instance of the edge node object - the EasySparkplugEdgeNode Class. In some cases, this step can already set some properties and define some contents of the edge node.
  2. Set properties of the edge node (such as MQTT broker address).
  3. Define the contents of the edge node (the metrics and their behavior, optionally organized in devices). For more information, see Rapid Toolkit for Sparkplug Producer Data Model.
  4. Control the edge node operations - start it, let it run, and eventually stop it. This is described further below.

Steps 1 to 3 prepare the edge node instance for subsequent operations. The properties and the contents of the edge node object must be defined before the edge node is started in Step 4.

The example shows a very simple Sparkplug edge node implementation with a single metric, and all the steps described above. 

.NET

// This example shows how to create a Sparkplug edge node with a single metric, start and stop it.
//
// 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 OpcLabs.EasySparkplug;
using OpcLabs.EasySparkplug.OperationModel;

namespace SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
{
    partial class Start_Stop
    {
        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 and hook events.
            var edgeNode = new EasySparkplugEdgeNode(hostDescriptor, "easyGroup", "easySparkplugDemo");
            edgeNode.SystemConnectionStateChanged += edgeNode_Main1_SystemConnectionStateChanged;

            // Define a metric providing random integers.
            var random = new Random();
            edgeNode.Metrics.Add(new SparkplugMetric("MyMetric").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.");
        }


        static void edgeNode_Main1_SystemConnectionStateChanged(
            object sender, 
            SparkplugConnectionStateChangedEventArgs eventArgs)
        {
            // Display the new connection state (such as when the connection to the broker succeeds or fails).
            Console.WriteLine($"{nameof(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}");
        }
    }
}
' This example shows how to create a Sparkplug edge node with a single metric, start and stop it.
'
' 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

Namespace Global.SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
    Partial Class Start_Stop
        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 and hook events.
            Dim edgeNode = New EasySparkplugEdgeNode(hostDescriptor, "easyGroup", "easySparkplugDemo")
            AddHandler edgeNode.SystemConnectionStateChanged, AddressOf edgeNode_Main1_SystemConnectionStateChanged

            ' Define a metric providing random integers.
            Dim random = New Random()
            edgeNode.Metrics.Add(New SparkplugMetric("MyMetric").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

        Private Shared Sub edgeNode_Main1_SystemConnectionStateChanged _
            (ByVal sender As Object, ByVal eventArgs As SparkplugConnectionStateChangedEventArgs)
            ' Display the new connection state (such as when the connection to the broker succeeds or fails).
            Console.WriteLine($"{NameOf(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}")
        End Sub
    End Class
End Namespace

 

Preparing the Edge Node Instance

Before the edge node can be started, it has to be created and configured. You need at least:

For more information and code examples to this part, see Rapid Toolkit for Sparkplug Producer Data Model.

Controlling Edge Node Operations

Simply creating the edge node object, setting its properties and defining contents does not make the edge node "live". The edge node must be started first, using the Start Method. After the node is started, it connects to the Sparkplug system (MQTT broker), publishes data and receives commands. It also automatically reconnects in case the connection to the broker is lost. Your code will eventually also stop the edge node, e.g. when the program is instructed to terminate.

For more information about starting and stopping the edge node, see Sparkplug Edge Node Object Operations And Notifications.

Using Primary Host Application

Sparkplug has a concept of Primary Host Application that can (optionally) be configured for an edge node, and it controls when the edge node (and its devices) can publish data.

The choice between these two approaches is up to you or the users of your application, and depends on the project requirements.

In Rapid Toolkit for Sparkplug, the primary host application ID is set using the PrimaryHostId Property on the EasySparkplugEdgeNode Class. When this property contains an empty string (the default), no primary host application is configured for this edge node. When this property contains a non-empty string, the string is the host ID of the application that will be the primary host for this edge node.

The PrimaryHostId Property can be set using an assignment statement in the code after the edge node object has been created. For shorter code, there are also constructors overloads on the EasySparkplugEdgeNode Class that take the primary host ID as their argument.

In the following example, the edge node is configured to use "easyApplication" as its primary host.

.NET

// This example shows the edge node publishing can be controlled by its primary host application
//
// You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
// program, to subscribe to the edge node data. 
// CAUTION: For this example, the application must be configured as a primary host application with the host ID
// "easyApplication".
//
// 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 OpcLabs.EasySparkplug;

namespace SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
{
     class PrimaryHostId
    {
        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 with the host ID of its primary host application.
            // The primary host application must be configured with this host ID.
            // Note that it is also possible to use a constructor overload with a primary host ID parameter.
            edgeNode.PrimaryHostId = "easyApplication";

            // 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 ApplicationOnlineChanged event to handle changes in the online state of the primary host
            // application.
            edgeNode.ApplicationOnlineChanged += (sender, eventArgs) =>
            {
                // The edge node will publish data only when the primary host application is online.
                Console.WriteLine($"{nameof(EasySparkplugEdgeNode.ApplicationOnlineChanged)}: {edgeNode.ApplicationOnline}");
            };
            
            // 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");

            // 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.");
        }
    }
}
' This example shows the edge node publishing can be controlled by its primary host application
'
' You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
' program, to subscribe to the edge node data.
' CAUTION: For this example, the application must be configured as a primary host application with the host ID
' "easyApplication".
'
' 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

Namespace Global.SparkplugDocExamples.EdgeNode._EasySparkplugEdgeNode
    Class PrimaryHostId
        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 with the host ID of its primary host application.
            ' The primary host application must be configured with this host ID.
            ' Note that it is also possible to use a constructor overload with a primary host ID parameter.
            edgeNode.PrimaryHostId = "easyApplication"

            ' 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 ApplicationOnlineChanged event to handle changes in the online state of the primary host
            ' application.
            AddHandler edgeNode.ApplicationOnlineChanged,
                Sub(sender, eventArgs)
                    ' The edge node will publish data only when the primary host application is online.
                    Console.WriteLine($"{NameOf(EasySparkplugEdgeNode.ApplicationOnlineChanged)}: {edgeNode.ApplicationOnline}")
                End Sub

            ' Define a metric on the edge node providing random integers.
            Dim random = New Random()
            edgeNode.Metrics.Add(New SparkplugMetric("MyMetric1").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
    End Class
End Namespace

 

The edge node that is configured with primary host application will appear "dead" (will not publish any data) until it can positively determine that the primary host is online.

 

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.