'DeclarationEvent ConnectDataSource As SparkplugProducerProcessedEventHandler
'UsageDim instance As ISparkplugProducerEvents Dim handler As SparkplugProducerProcessedEventHandler AddHandler instance.ConnectDataSource, handler
event SparkplugProducerProcessedEventHandler ConnectDataSource
event SparkplugProducerProcessedEventHandler^ ConnectDataSource
The event handler receives an argument of type SparkplugProducerProcessedEventArgs containing data related to this event. The following SparkplugProducerProcessedEventArgs properties provide information specific to this event.
| Property | Description |
|---|---|
| Device | The device associated with this event, if any. |
| EdgeNode | The edge node associated with this event. |
| Handled | (Inherited from System.ComponentModel.HandledEventArgs) |
| MetricName | The name of the metric associated with this event. Empty if the event is not associated with a metric. |
Handle this event in order to implement code that connects the data source for your edge node or device.
If the event is handled (its System.ComponentModel.HandledEventArgs.Handled property is set to true), your code is expected to attempt to connect to the data source (for example, a database or a PLC) and call either the ISparkplugProducer.DataSourceConnectionSuccess method (for success) or the DataSourceConnectionFailure method (for failure). This can be done synchronously (while handling the event) or asynchronously (e.g. by using a task or a thread).
If the event is not handled (its System.ComponentModel.HandledEventArgs.Handled property remains at false), the data source is considered immediately successfully connected (as if your code had called the ISparkplugProducer.DataSourceConnectionSuccess method). Therefore, if you do not need an extra code to connect to your data source, you can rely on this default behavior and not handle the event at all.
Handling of this event MUST NOT block the calling thread for any significant amount of time. If the data source connection processing can block, handle the event asynchronously.
Instead of adding an event handler to this event, you can use the ISparkplugProducerExtension.ConnectDataSourceAction method and specify the action that connects the data source.
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.
// 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