OPC UA Client

Connect Delphi, C++Builder and .NET applications to PLCs, SCADA systems and gateways that run an OPC UA server: browse the address space, read and write variables, call methods and subscribe to data changes and events over a signed and encrypted opc.tcp connection.

New

TsgcOPCUAClient

One component for the whole client side of OPC UA: secure channel, session, services and subscriptions.

Component class

TsgcOPCUAClient

Protocol

OPC UA binary over opc.tcp (UA TCP, UA Secure Conversation, UA Binary encoding)

Security

Sign and SignAndEncrypt with Basic256Sha256, Aes128_Sha256_RsaOaep and Aes256_Sha256_RsaPss; Anonymous, user name and X.509 identities

Edition

Included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, or as the standalone sgcIndustrial pack

Connect, read and write

Set EndpointUrl, choose the security policy and mode and call Connect. Each service call blocks until the server answers and raises EsgcOPCUAError, with the OPC UA status code, when it fails.

uses
  sgcIndustrial;

procedure TForm1.ConnectAndRead;
begin
  FClient := TsgcOPCUAClient.Create(Self);
  FClient.EndpointUrl := 'opc.tcp://192.168.1.60:4840';
  FClient.SecurityPolicy := opcspNone;
  FClient.SecurityMode := opcsmNone;
  FClient.OnError := OnOPCUAError;
  FClient.Connect;
  // read the Value attribute of a variable
  Memo1.Lines.Add('Temperature: ' + VarToStr(FClient.ReadValue('ns=2;s=Line1.Temperature')));
  // the data type of the node is read first and used for the written value
  FClient.WriteValue('ns=2;s=Line1.Setpoint', 75.5);
end;

procedure TForm1.OnOPCUAError(Sender: TObject; aStatusCode: Cardinal; const aError: string);
begin
  Memo1.Lines.Add('Error: ' + aError);
end;
#include "sgcIndustrial.hpp"

void __fastcall TForm1::ConnectAndRead()
{
  FClient = new TsgcOPCUAClient(this);
  FClient->EndpointUrl = "opc.tcp://192.168.1.60:4840";
  FClient->SecurityPolicy = opcspNone;
  FClient->SecurityMode = opcsmNone;
  FClient->OnError = OnOPCUAError;
  FClient->Connect();
  // read the Value attribute of a variable
  Memo1->Lines->Add("Temperature: " + VarToStr(FClient->ReadValue("ns=2;s=Line1.Temperature")));
  // the data type of the node is read first and used for the written value
  FClient->WriteValue("ns=2;s=Line1.Setpoint", 75.5);
}

void __fastcall TForm1::OnOPCUAError(TObject *Sender, unsigned aStatusCode, const String aError)
{
  Memo1->Lines->Add("Error: " + aError);
}
using System;
using esegece.sgcWebSockets;

class PlantReader
{
    TsgcOPCUAClient FClient = new TsgcOPCUAClient();

    public void ConnectAndRead()
    {
        FClient.EndpointUrl = "opc.tcp://192.168.1.60:4840";
        FClient.SecurityPolicy = TsgcOPCUASecurityPolicy.opcspNone;
        FClient.SecurityMode = TsgcOPCUAMessageSecurityMode.opcsmNone;
        FClient.OnError += OnOPCUAError;
        FClient.Connect();
        // read the Value attribute of a variable
        Console.WriteLine("Temperature: " + FClient.ReadValue("ns=2;s=Line1.Temperature"));
        // the data type of the node is read first and used for the written value
        FClient.WriteValue("ns=2;s=Line1.Setpoint", 75.5);
    }

    void OnOPCUAError(object Sender, uint aStatusCode, string aError)
    {
        Console.WriteLine("Error: " + aError);
    }
}

What's inside

The secure channel, the session and the publish loop are handled by the component, so your code works with node ids and values.

Services

GetEndpoints, Browse and BrowseNext (continuation points are followed for you), TranslateBrowsePath, Read and Write of any attribute, and Call for methods. ReadValue and WriteValue take a node id string and use the data type of the node.

Security policies

Basic256Sha256, Aes128_Sha256_RsaOaep and Aes256_Sha256_RsaPss, plus the deprecated Basic128Rsa15 and Basic256 for older servers, in Sign or SignAndEncrypt mode. The client checks the server signature and nonce and rejects an endpoint list that was changed on the way.

User identity

Anonymous, user name and password (encrypted with the server key when the token policy asks for it) or an X.509 user certificate signed with your private key.

Certificates

The application instance certificate is loaded from DER or PEM files, created on the first connect and saved to those files, or created in memory when no file is set. A server certificate is rejected unless OnValidateServerCertificate accepts it.

Subscriptions

Data change items with sampling interval, queue size, absolute or percent deadband and trigger; event items with select clauses and an optional where clause. Acknowledgements and the republishing of missing notifications are done by the client.

Automatic reconnect

WatchDog reconnects after a network drop, in Delphi, C++Builder and .NET: it reactivates the same session and republishes what was missed, or transfers or recreates the subscriptions in a new session. OnReconnect tells which path was taken.

Data changes and events, pushed by the server

Create a subscription, add the items to monitor and handle OnDataChange. The values arrive without polling, at the publishing interval you choose.

procedure TForm1.Subscribe;
var
  oSubscription: TsgcOPCUASubscription;
begin
  FClient.OnDataChange := OnOPCUADataChange;
  // publishing interval 500 ms
  oSubscription := FClient.CreateSubscription(500);
  // sampling 250 ms, queue of 1, report changes larger than 0.5 only
  FClient.AddMonitoredItem(oSubscription, 'ns=2;s=Line1.Temperature', 250, 1, True,
    uadbtAbsolute, 0.5);
  FClient.AddMonitoredItem(oSubscription, 'ns=2;s=Line1.Pressure');
end;

procedure TForm1.OnOPCUADataChange(Sender: TObject; aSubscription: TsgcOPCUASubscription;
  aMonitoredItem: TsgcOPCUAMonitoredItem; const aValue: TsgcOPCUADataValue);
begin
  if (aValue.StatusCode and $80000000) = 0 then
    Memo1.Lines.Add('Item ' + IntToStr(aMonitoredItem.ClientHandle) + ': ' +
      VarToStr(aValue.Value.Value));
end;
void __fastcall TForm1::Subscribe()
{
  FClient->OnDataChange = OnOPCUADataChange;
  // publishing interval 500 ms
  TsgcOPCUASubscription *oSubscription = FClient->CreateSubscription(500);
  // sampling 250 ms, queue of 1, report changes larger than 0.5 only
  FClient->AddMonitoredItem(oSubscription, "ns=2;s=Line1.Temperature", 250, 1, true,
    uadbtAbsolute, 0.5);
  FClient->AddMonitoredItem(oSubscription, "ns=2;s=Line1.Pressure");
}

void __fastcall TForm1::OnOPCUADataChange(TObject *Sender, TsgcOPCUASubscription *aSubscription,
  TsgcOPCUAMonitoredItem *aMonitoredItem, const TsgcOPCUADataValue &aValue)
{
  if ((aValue.StatusCode & 0x80000000) == 0)
    Memo1->Lines->Add("Item " + IntToStr((int)aMonitoredItem->ClientHandle) + ": " +
      VarToStr(aValue.Value.Value));
}
using System;
using esegece.sgcWebSockets;

class PlantMonitor
{
    public void Subscribe(TsgcOPCUAClient aClient)
    {
        aClient.OnDataChange += OnOPCUADataChange;
        // publishing interval 500 ms
        TsgcOPCUASubscription oSubscription = aClient.CreateSubscription(500);
        // sampling 250 ms, queue of 1, report changes larger than 0.5 only
        aClient.AddMonitoredItem(oSubscription, "ns=2;s=Line1.Temperature", 250, 1, true,
            TsgcOPCUADeadbandType.uadbtAbsolute, 0.5);
        aClient.AddMonitoredItem(oSubscription, "ns=2;s=Line1.Pressure");
    }

    void OnOPCUADataChange(object Sender, TsgcOPCUASubscription aSubscription,
        TsgcOPCUAMonitoredItem aMonitoredItem, TsgcOPCUADataValue aValue)
    {
        if ((aValue.StatusCode & 0x80000000) == 0)
            Console.WriteLine("Item " + aMonitoredItem.ClientHandle + ": " + aValue.Value.Value);
    }
}

Signed and encrypted connections

Choose the policy and mode, give the client its application certificate and a user identity, and decide which server certificates you trust.

uses
  sgcIndustrial; // Delphi 7 to 2006: add sgcBase_Helpers (TBytes)

procedure TForm1.ConnectSecure;
begin
  FClient := TsgcOPCUAClient.Create(Self);
  FClient.EndpointUrl := 'opc.tcp://192.168.1.60:4840';
  FClient.SecurityPolicy := opcspBasic256Sha256;
  FClient.SecurityMode := opcsmSignAndEncrypt;
  // application instance certificate: created and saved on the first run
  FClient.Application.ApplicationName := 'Line1 Monitor';
  FClient.Application.CertificateFile := 'C:\pki\own\client.der';
  FClient.Application.PrivateKeyFile := 'C:\pki\own\client.pem';
  // user identity
  FClient.Authentication.AuthenticationType := opcatUserName;
  FClient.Authentication.User := 'operator';
  FClient.Authentication.Password := 'secret';
  // decide which server certificates you trust
  FClient.OnValidateServerCertificate := OnOPCUAValidateServerCertificate;
  FClient.Connect;
end;

procedure TForm1.OnOPCUAValidateServerCertificate(Sender: TObject;
  const aCertificate: TBytes; var aAccept: Boolean);
begin
  // FTrusted holds the DER bytes of the server certificate you trust
  aAccept := (Length(aCertificate) > 0) and (Length(aCertificate) = Length(FTrusted)) and
    CompareMem(@aCertificate[0], @FTrusted[0], Length(aCertificate));
end;
void __fastcall TForm1::ConnectSecure()
{
  FClient = new TsgcOPCUAClient(this);
  FClient->EndpointUrl = "opc.tcp://192.168.1.60:4840";
  FClient->SecurityPolicy = opcspBasic256Sha256;
  FClient->SecurityMode = opcsmSignAndEncrypt;
  // application instance certificate: created and saved on the first run
  FClient->Application->ApplicationName = "Line1 Monitor";
  FClient->Application->CertificateFile = "C:\\pki\\own\\client.der";
  FClient->Application->PrivateKeyFile = "C:\\pki\\own\\client.pem";
  // user identity
  FClient->Authentication->AuthenticationType = opcatUserName;
  FClient->Authentication->User = "operator";
  FClient->Authentication->Password = "secret";
  // decide which server certificates you trust
  FClient->OnValidateServerCertificate = OnOPCUAValidateServerCertificate;
  FClient->Connect();
}

void __fastcall TForm1::OnOPCUAValidateServerCertificate(TObject *Sender,
  const TBytes aCertificate, bool &aAccept)
{
  // FTrusted holds the DER bytes of the server certificate you trust
  aAccept = (aCertificate.Length > 0) && (aCertificate.Length == FTrusted.Length) &&
    CompareMem((void*)&aCertificate[0], &FTrusted[0], aCertificate.Length);
}
using System.IO;
using System.Linq;
using esegece.sgcWebSockets;

class SecureClient
{
    TsgcOPCUAClient FClient = new TsgcOPCUAClient();
    // DER bytes of the server certificate you trust
    byte[] FTrusted = File.ReadAllBytes(@"C:\pki\trusted\server.der");

    public void ConnectSecure()
    {
        FClient.EndpointUrl = "opc.tcp://192.168.1.60:4840";
        FClient.SecurityPolicy = TsgcOPCUASecurityPolicy.opcspBasic256Sha256;
        FClient.SecurityMode = TsgcOPCUAMessageSecurityMode.opcsmSignAndEncrypt;
        // application instance certificate: created and saved on the first run
        FClient.Application.ApplicationName = "Line1 Monitor";
        FClient.Application.CertificateFile = @"C:\pki\own\client.der";
        FClient.Application.PrivateKeyFile = @"C:\pki\own\client.pem";
        // user identity
        FClient.Authentication.AuthenticationType = TsgcOPCUAAuthenticationType.opcatUserName;
        FClient.Authentication.User = "operator";
        FClient.Authentication.Password = "secret";
        // decide which server certificates you trust
        FClient.OnValidateServerCertificate += OnOPCUAValidateServerCertificate;
        FClient.Connect();
    }

    void OnOPCUAValidateServerCertificate(object Sender, byte[] aCertificate, ref bool aAccept)
    {
        aAccept = aCertificate != null && aCertificate.SequenceEqual(FTrusted);
    }
}

Specifications & references

Authoritative sources for the protocol this component implements.

OPC UA client questions

Any OPC UA server with an opc.tcp endpoint: PLCs and controllers with a built-in server, SCADA and MES systems and protocol gateways. The client is tested against a reference server built on asyncua, an independent open-source OPC UA stack, on all eleven of its endpoints.

Browse from the Objects folder (i=85) with Browse, or resolve a path such as /2:Line1/2:Speed with TranslateBrowsePath. Node ids are written as text: ns=2;s=Line1.Speed for a string id, i=2258 for a numeric id in namespace 0.

The default is opcspNone, which most servers only allow for testing. Set SecurityPolicy and SecurityMode to sign or encrypt. Server certificates are rejected unless OnValidateServerCertificate accepts them, and Basic128Rsa15 and Basic256 are deprecated and kept for older servers only.

Yes, set WatchDog.Enabled: the client reactivates the session and republishes the missed notifications, or opens a new session and transfers or recreates the subscriptions. It works the same in Delphi, C++Builder and .NET, and OnReconnect tells which path was taken.

The component is an OPC UA client over opc.tcp with the binary encoding. It does not include an OPC UA server, the HTTPS, JSON and WebSocket transports, HistoryRead, PubSub, Reverse Connect and the Global Discovery Server.

It is included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, as part of the sgcIndustrial pack. In Delphi, add sgcIndustrial to the uses clause.

Documentation & Demos

Deep-link to the component reference, open the demo project and read the technical document.

Online Help: TsgcOPCUAClient Full property, method and event reference for the OPC UA client.
Online Help: OPC UA Subscriptions Monitored items, deadbands, event filters, keep-alive and reconnect behaviour.
Demo Project: Industrial\05.OPCUA_Client An OPC UA client for Delphi, C++Builder and .NET. It ships inside the sgcWebSockets package.
Technical Document (PDF) Features, quick start, code samples and primary-source references for this component only.
User Manual (PDF) Comprehensive manual covering every component in the library.
Best value: All-AccessEvery eSeGeCe product, Premium Support included, from €1,059/year.
See All-Access pricing

Included in sgcWebSockets Enterprise

Included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, or as the standalone sgcIndustrial pack.