Skip to content

kbrashears5/net-standard-opc-ua-helper

Repository files navigation

Net Standard OPC UA Helper

Collection of helper functions for interacting with OPC UA servers

Build Status Tests Code Coverage

nuget nuget

Usage

OPC UA Client Helper

Base Usage

var helper = new OpcUaClientHelper();

helper.InitializeOpcUaClientConnection(clientName: "MyOpcUaClient",
    configPath: @"C:\temp\client.xml",
    opcUaUrl: "opc.tcp://localhost:4840",
    sessionName: "MySessionName",
    sessionTimeout: 60000);

var monitoredItems = new List<MonitoredItems>()
{
    helper.CreateOpcUaMonitoredItem(opcUaNodeId: "node.attributeName",
        notification: this.NotificationEventHandler),
};

helper.CreateOpcUaSubscription(monitoredItems: monitoredItems,
    publishingInterval: 1000);

Event Handler

public void NotificationEventHandler(MonitoredItem monitoredItem,
    EventArgs eventArgs)
{
    Console.WriteLine(monitoredItem.StartNodeId.Identifier.ToString());

    foreach (var value in monitoredItem.DequeueValues())
    {
        Console.WriteLine(value.Value);
        Console.WriteLine(value.SourceTimestamp.ToString());
    }
}

Keep Alive

You can run your own keep alive code by providing a keep alive to the InitializeOpcUaClientConnection function

var helper = new OpcUaClientHelper();

await helper.InitializeOpcUaClientConnection(clientName: "MyOpcUaClient",
    configPath: @"C:\temp\client.xml",
    opcUaUrl: "opc.tcp://localhost:4840",
    sessionName: "MySessionName",
    sessionTimeout: 60000,
    keepAlive: this.SessionKeepAlive_Event);

Where the keep alive event looks like:

private void SessionKeepAlive_Event(Session sender,
    KeepAliveEventArgs eventArgs)
{
    if (eventArgs.Status != null && ServiceResult.IsNotGood(status: eventArgs.Status))
    {
        // keep alive code
    }
}  

NewSession Event

When unable to reconnect to the OPC UA server, the helper will try to create a new session until it succeeds

When this happens however, you'll lose the subscriptions that were previously there.

Subscribe to the NewSession event to recreate these subscriptions once the new session has been

OpcUa.Client.Config.xml

A sample client config XML file is located in the root of the repo

OPC UA Server Helper

Base Usage

var server = new StandardServer();

var helper = new OpcUaServerHelper(server: server,
    port: 4840);

await helper.InitializeOpcUaServer(configPath: @"C:\temp\server.xml");

OpcUa.Server.Config.xml

A sample client config XML file is located in the root of the repo