Connectivity Software User's Guide and Reference
State Property (SparkplugMetric)
Example 



OpcLabs.EasySparkplug Assembly > OpcLabs.EasySparkplug Namespace > SparkplugMetric Class : State Property
An arbitrary object associated with the metric.
Syntax
'Declaration
 
<JetBrains.Annotations.CanBeNullAttribute()>
Public Property State As Object
'Usage
 
Dim instance As SparkplugMetric
Dim value As Object
 
instance.State = value
 
value = instance.State
[JetBrains.Annotations.CanBeNull()]
public object State {get; set;}
[JetBrains.Annotations.CanBeNull()]
public:
property Object^ State {
   Object^ get();
   void set (    Object^ value);
}

Property Value

The value of this property can be null (Nothing in Visual Basic).

The default value of this property is null.

Remarks

This method or property does not throw any exceptions, aside from execution exceptions such as System.Threading.ThreadAbortException or System.OutOfMemoryException.

 

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 reading from edge node metrics using a single overriden method.
//
// 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
{
    class OnRead
    {
        /// <summary>
        /// A sparkplug edge node, with specialized read behavior for its metrics.
        /// </summary>
        class EdgeNodeWithOnRead : EasySparkplugEdgeNode
        {
            /// <summary>
            /// Obtains the data for Sparkplug read.
            /// </summary>
            /// <param name="eventArgs">The event arguments.</param>
            protected override void OnRead(SparkplugMetricReadEventArgs eventArgs)
            {
                // Obtain the state associated with the metric that is being read.
                object state = eventArgs.Metric.State;

                // The state is null in metrics that we have not created, such as the "node rebirth" metric.
                if (state is null)
                    return;

                // Use the state as the offset for the random value, so that each metric generates values in a unique range.
                int offset = (int)state * 100;

                // Generate a random value, indicate that the read has been handled, and return the generated value.
                eventArgs.HandleAndReturn(Random.Next(offset, offset + 100));
            }

            static private readonly Random Random = new Random();
        }
        
        static public void Main1()
        {
            // Note that the default port for the "mqtt" scheme is 1883.
            var hostDescriptor = new SparkplugHostDescriptor("mqtt://localhost");

            // Instantiate our derived edge node object and hook events.
            var edgeNode = new EdgeNodeWithOnRead
            {
                EdgeNodeId = "easySparkplugDemo",
                GroupId = "easyGroup",
                SystemDescriptor = hostDescriptor
            };
            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}");
            };

            // Create metrics in the folder. Distinguish them by their state.
            edgeNode.Add(new SparkplugMetric("MyMetric1").ValueType<int>().SetState(1));
            edgeNode.Add(new SparkplugMetric("MyMetric2").ValueType<int>().SetState(2));
            edgeNode.Add(new SparkplugMetric("MyMetric3").ValueType<int>().SetState(3));
            edgeNode.Add(new SparkplugMetric("MyMetric4").ValueType<int>().SetState(4));
            edgeNode.Add(new SparkplugMetric("MyMetric5").ValueType<int>().SetState(5));

            // 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 how to implement reading from edge node metrics using a single overriden method.
'
' 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
    Class OnRead
        ''' <summary>
        ''' A sparkplug edge node, with specialized read behavior for its metrics.
        ''' </summary>
        Class EdgeNodeWithOnRead
            Inherits EasySparkplugEdgeNode

            ''' <summary>
            ''' Obtains the data for Sparkplug read.
            ''' </summary>
            ''' <param name="eventArgs">The event arguments.</param>
            Protected Overrides Sub OnRead(eventArgs As SparkplugMetricReadEventArgs)
                ' Obtain the state associated with the metric that is being read.
                Dim state As Object = eventArgs.Metric.State

                ' Use the state as the offset for the random value, so that each metric generates values in a unique range.
                Dim offset As Integer = CInt(state * 100)

                ' Generate a random value, indicate that the read has been handled, and return the generated value.
                eventArgs.HandleAndReturn(Random.Next(offset, offset + 100))
            End Sub

            Private Shared ReadOnly Random As Random = New Random()
        End Class

        Public Shared Sub Main1()
            ' Note that the default port for the "mqtt" scheme is 1883.
            Dim hostDescriptor = New SparkplugHostDescriptor("mqtt://localhost")

            ' Instantiate our derived edge node object and hook events.
            Dim edgeNode = New EdgeNodeWithOnRead With
            {
                .EdgeNodeId = "easySparkplugDemo",
                .GroupId = "easyGroup",
                .SystemDescriptor = hostDescriptor
            }
            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

            ' Create metrics in the folder. Distinguish them by their state.
            edgeNode.Add(New SparkplugMetric("MyMetric1").ValueType(Of Integer)().SetState(1))
            edgeNode.Add(New SparkplugMetric("MyMetric2").ValueType(Of Integer)().SetState(2))
            edgeNode.Add(New SparkplugMetric("MyMetric3").ValueType(Of Integer)().SetState(3))
            edgeNode.Add(New SparkplugMetric("MyMetric4").ValueType(Of Integer)().SetState(4))
            edgeNode.Add(New SparkplugMetric("MyMetric5").ValueType(Of Integer)().SetState(5))

            ' 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
// This example shows how to react to events in order to initiate and finalize data collection in the push data provision
// model.
//
// 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 System;
using Timer = System.Timers.Timer;

namespace SparkplugDocExamples.EdgeNode._SparkplugMetric
{
    class Starting_Stopped
    {
        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 += (sender, eventArgs) =>
            {
                // Display the new connection state (such as when the connection to the broker succeeds or fails).
                Console.WriteLine($"{nameof(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}");
            };

            // Create a read-only data metric.
            var metric = SparkplugMetric.CreateIn(edgeNode, "ReadThisMetric")
                .ValueType<int>()
                .Writable(false);

            metric.Starting += (sender, args) =>
            {
                // Create a timer for pushing the data to the metric. In a real edge node or device, the activity may also come
                // from other sources.
                var timer = new Timer
                {
                    Interval = 1000,    // 1 second
                    AutoReset = true,
                };

                // Set the read data of the metric to a random value whenever the timer interval elapses.
                // Note that this example shows the basic concept, however there is also an UpdateReadData method that
                // can be used in most cases to achieve slightly more concise code.
                var random = new Random();
                timer.Elapsed += (s, a) =>
                    metric.ReadData = new SparkplugData(random.Next(), DateTime.UtcNow);

                // Associate the timer with the data variable.
                metric.State = timer;

                timer.Start();
            };
            metric.Stopped += (sender, args) =>
            {
                // Obtain the timer associated with the metric.
                var timer = (Timer)((SparkplugMetric)sender).State;

                // Stop the timer.
                timer.Stop();
            };


            // 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 how to react to events in order to initiate and finalize data collection in the push data provision
' model.
'
' 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 Timer = System.Timers.Timer

Namespace Global.SparkplugDocExamples.EdgeNode._SparkplugMetric
    Class Starting_Stopped
        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,
                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

            ' Create a read-only data metric.
            Dim metric = SparkplugMetric.CreateIn(edgeNode, "ReadThisMetric") _
                .ValueType(Of Integer)() _
                .Writable(False)

            AddHandler metric.Starting,
                Sub(sender, args)
                    ' Create a timer for pushing the data to the metric. In a real edge node or device, the activity may also come
                    ' from other sources.
                    Dim timer = New Timer With
                    {
                        .Interval = 1000, ' 1 second
                        .AutoReset = True
                    }

                    ' Set the read data of the metric to a random value whenever the timer interval elapses.
                    ' Note that this example shows the basic concept, however there is also an UpdateReadData method that
                    ' can be used in most cases to achieve slightly more concise code.
                    Dim random = New Random()
                    AddHandler timer.Elapsed,
                        Sub(s, a)
                            metric.ReadData = New SparkplugData(random.Next(), DateTime.UtcNow)
                        End Sub

                    ' Associate the timer with the data variable.
                    metric.State = timer

                    timer.Start()
                End Sub
            AddHandler metric.Stopped,
                Sub(sender, args)
                    ' Obtain the timer associated with the metric.
                    Dim timer = CType(CType(sender, SparkplugMetric).State, Timer)

                    ' Stop the timer.
                    timer.Stop()
                End Sub


            ' 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
// This example shows how to implement reading of different edge node metrics using a single handler.
//
// 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
{
    class Read
    {
        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 += (sender, eventArgs) =>
            {
                // Display the new connection state (such as when the connection to the broker succeeds or fails).
                Console.WriteLine($"{nameof(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}");
            };

            // Create metrics in the folder. Distinguish them by their state.
            edgeNode.Add(new SparkplugMetric("MyMetric1").ValueType<int>().SetState(1));
            edgeNode.Add(new SparkplugMetric("MyMetric2").ValueType<int>().SetState(2));
            edgeNode.Add(new SparkplugMetric("MyMetric3").ValueType<int>().SetState(3));
            edgeNode.Add(new SparkplugMetric("MyMetric4").ValueType<int>().SetState(4));
            edgeNode.Add(new SparkplugMetric("MyMetric5").ValueType<int>().SetState(5));

            // Handle the read event for the edge node.
            edgeNode.Read += EdgeNodeOnRead;

            // 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>
        /// Event handler for the read event on the edge node. 
        /// </summary>
        /// <param name="sender">The edge node object that sends the event.</param>
        /// <param name="eventArgs">Data for the metric read event.</param>
        static private void EdgeNodeOnRead(object sender, SparkplugMetricReadEventArgs eventArgs)
        {
            // Obtain the state associated with the metric that is being read.
            object state = eventArgs.Metric.State;

            // The state is null in metrics that we have not created, such as the "node rebirth" metric.
            if (state is null)
                return;

            // Use the state as the offset for the random value, so that each metric generates values in a unique range.
            int offset = (int)state * 100;

            // Generate a random value, indicate that the read has been handled, and return the generated value.
            eventArgs.HandleAndReturn(Random.Next(offset, offset + 100));
        }

        static private readonly Random Random = new Random();
    }
}
' This example shows how to implement reading of different edge node metrics using a single handler.
'
' 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
    Class Read
        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")
            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

            ' Create metrics in the folder. Distinguish them by their state.
            edgeNode.Add(New SparkplugMetric("MyMetric1").ValueType(Of Integer)().SetState(1))
            edgeNode.Add(New SparkplugMetric("MyMetric2").ValueType(Of Integer)().SetState(2))
            edgeNode.Add(New SparkplugMetric("MyMetric3").ValueType(Of Integer)().SetState(3))
            edgeNode.Add(New SparkplugMetric("MyMetric4").ValueType(Of Integer)().SetState(4))
            edgeNode.Add(New SparkplugMetric("MyMetric5").ValueType(Of Integer)().SetState(5))

            ' Handle the read event for the edge node.
            AddHandler edgeNode.Read, AddressOf EdgeNodeOnRead

            ' 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>
        ''' Event handler for the read event on the edge node.
        ''' </summary>
        ''' <param name="sender">The edge node object that sends the event.</param>
        ''' <param name="eventArgs">Data for the metric read event.</param>
        Private Shared Sub EdgeNodeOnRead(ByVal sender As Object, ByVal eventArgs As SparkplugMetricReadEventArgs)
            ' Obtain the state associated with the metric that is being read.
            Dim state As Object = eventArgs.Metric.State

            ' The state is null in metrics that we have not created, such as the "node rebirth" metric.
            If state Is Nothing Then
                Return
            End If

            ' Use the state as the offset for the random value, so that each metric generates values in a unique range.
            Dim offset As Integer = CInt(state * 100)

            ' Generate a random value, indicate that the read has been handled, and return the generated value.
            eventArgs.HandleAndReturn(Random.Next(offset, offset + 100))
        End Sub

        Private Shared ReadOnly Random As Random = New Random()
    End Class
End Namespace
// This example shows how to handle the write event on the edge node, providing a way to implement writing of different
// metrics using a single handler.
//
// This example shows how to implement reading of multiple edge node metrics using a single handler.
// You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
// program, to subscribe to the edge node data. SparkplugCmd, or other capable Sparkplug application, can be used to write
// data into the metric. 
//
// 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
{
    class Write
    {
        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 += (sender, eventArgs) =>
            {
                // Display the new connection state (such as when the connection to the broker succeeds or fails).
                Console.WriteLine($"{nameof(EasySparkplugEdgeNode.SystemConnectionStateChanged)}: {eventArgs}");
            };

            // Create metrics in the folder. Distinguish them by their state.
            edgeNode.Add(new SparkplugMetric("MyMetric1").ValueType<int>().SetState(1));
            edgeNode.Add(new SparkplugMetric("MyMetric2").ValueType<int>().SetState(2));
            edgeNode.Add(new SparkplugMetric("MyMetric3").ValueType<int>().SetState(3));
            edgeNode.Add(new SparkplugMetric("MyMetric4").ValueType<int>().SetState(4));
            edgeNode.Add(new SparkplugMetric("MyMetric5").ValueType<int>().SetState(5));

            // Handle the write event for the edge node.
            edgeNode.Write += EdgeNodeOnWrite;

            // 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>
        /// Event handler for the write event on the edge node. 
        /// </summary>
        /// <param name="sender">The edge node object that sends the event.</param>
        /// <param name="eventArgs">Data for the metric write event.</param>
        static private void EdgeNodeOnWrite(object sender, SparkplugMetricWriteEventArgs eventArgs)
        {
            // Obtain the state associated with the metric that is being written.
            object state = eventArgs.Metric.State;

            // The state is null in metrics that we have not created, such as the "node rebirth" metric.
            if (state is null)
                return;

            // Display the state on the console together with the new value.
            Console.WriteLine($"Metric {eventArgs.Metric.State}, value written: {eventArgs.Data.Value}");
        }
    }
}
' This example shows how to handle the write event on the edge node, providing a way to implement writing of different
' metrics using a single handler.
'
' This example shows how to implement reading of multiple edge node metrics using a single handler.
' You can use any Sparkplug application, including our SparkplugCmd utility and the SparkplugApplicationConsoleDemo
' program, to subscribe to the edge node data. SparkplugCmd, or other capable Sparkplug application, can be used to write
' data into the metric.
'
' 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
    Class Write
        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,
                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

            ' Create metrics in the folder. Distinguish them by their state.
            edgeNode.Add(New SparkplugMetric("MyMetric1").ValueType(Of Integer)().SetState(1))
            edgeNode.Add(New SparkplugMetric("MyMetric2").ValueType(Of Integer)().SetState(2))
            edgeNode.Add(New SparkplugMetric("MyMetric3").ValueType(Of Integer)().SetState(3))
            edgeNode.Add(New SparkplugMetric("MyMetric4").ValueType(Of Integer)().SetState(4))
            edgeNode.Add(New SparkplugMetric("MyMetric5").ValueType(Of Integer)().SetState(5))

            ' Handle the read event for the edge node.
            AddHandler edgeNode.Write, AddressOf EdgeNodeOnWrite

            ' 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>
        ''' Event handler for the write event on the edge node. 
        ''' </summary>
        ''' <param name="sender">The edge node object that sends the event.</param>
        ''' <param name="eventArgs">Data for the metric write event.</param>
        Private Shared Sub EdgeNodeOnWrite(ByVal sender As Object, ByVal eventArgs As SparkplugMetricWriteEventArgs)
            ' Obtain the state associated with the metric that is being written.
            Dim state As Object = eventArgs.Metric.State

            ' The state is null in metrics that we have not created, such as the "node rebirth" metric.
            If state Is Nothing Then
                Return
            End If

            ' Use the state as the offset for the random value, so that each metric generates values in a unique range.
            Dim offset As Integer = CInt(state * 100)

            ' Display the state on the console together with the new value.
            Console.WriteLine($"Metric {eventArgs.Metric.State}, value written: {eventArgs.Data.Value}")
        End Sub
    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