New

Delphi OPC UA Client Component

A native OPC UA client for Delphi and C++Builder. Browse, read and write the variables of PLCs, SCADA servers and industrial gateways, call their methods and receive data changes and alarms through subscriptions, over a signed and encrypted opc.tcp connection that reconnects by itself.

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

One component for the client side of OPC UA

Secure channel, session, services and subscriptions in a non-visual component, written in Pascal and compiled into your application.

A Delphi OPC UA client lets a VCL, FMX, service or console application read the data that machines, PLCs and SCADA systems publish through an OPC UA server, and write setpoints and commands back. sgcWebSockets ships it as TsgcOPCUAClient: set EndpointUrl, choose SecurityPolicy and SecurityMode, call Connect and work with node ids such as ns=2;s=Line1.Speed or i=2253.

Service calls block until the server answers and raise EsgcOPCUAError with the OPC UA status code when they fail. ReadValue returns a Delphi Variant, and WriteValue reads the data type of the node first, so WriteValue('ns=2;s=Line1.Setpoint', 75.5) writes a Float or a Double as the node expects. One uses sgcIndustrial; line brings in the component, its types and its enumerations.

Component class

TsgcOPCUAClient, with TsgcOPCUASubscription and TsgcOPCUAMonitoredItem

Transport

OPC UA binary over opc.tcp, the transport that PLCs and SCADA servers expose

Security

Sign and SignAndEncrypt with Basic256Sha256, Aes128_Sha256_RsaOaep and Aes256_Sha256_RsaPss

Platforms

Delphi 7 to Delphi 13 and C++Builder; Windows 32 and 64 bit and Linux 64 bit

The OPC UA services, one method each

Simple overloads take node id strings; full overloads take the request records of the specification.

Service setServiceMethod
DiscoveryGetEndpointsGetEndpoints
ViewBrowse, BrowseNextBrowse, BrowseNext
ViewTranslateBrowsePathsToNodeIdsTranslateBrowsePath
AttributeReadRead, ReadValue
AttributeWriteWrite, WriteValue
MethodCallCall
SubscriptionCreateSubscription, DeleteSubscriptions, SetPublishingModeCreateSubscription, DeleteSubscription, SetPublishingMode
MonitoredItemCreateMonitoredItems, ModifyMonitoredItems, DeleteMonitoredItemsAddMonitoredItem, AddEventMonitoredItem, ModifyMonitoredItem, RemoveMonitoredItem
SubscriptionPublish, Republish, TransferSubscriptionsDone by the component: OnDataChange, OnEvent, OnKeepAlive, WatchDog

Read a machine in a few lines of Delphi

Create the component, set the endpoint, call a method. Every sample on this page compiles with Delphi 7 and Delphi 13.

uses
  sgcIndustrial;

procedure TForm1.ReadLine1;
begin
  OPCUA := TsgcOPCUAClient.Create(Self);
  OPCUA.EndpointUrl := 'opc.tcp://192.168.1.60:4840';
  OPCUA.Connect;
  try
    Memo1.Lines.Add('Speed: ' + VarToStr(OPCUA.ReadValue('ns=2;s=Line1.Speed')));
    // write with an explicit built-in type
    OPCUA.WriteValue('ns=2;s=Line1.Mode', 2, uabtUInt16);
  except
    on E: EsgcOPCUAError do
      Memo1.Lines.Add('Status ' + IntToHex(Int64(E.StatusCode), 8) + ': ' + E.Message);
  end;
end;
uses
  sgcIndustrial, sgcOPCUA_Types;

procedure TForm1.BrowseAndCall;
var
  vRefs: TsgcOPCUAReferenceDescriptionArray;
  vInputs, vOutputs: TsgcOPCUAVariantArray;
  i: Integer;
begin
  // i=85 is the Objects folder
  vRefs := OPCUA.Browse('i=85');
  for i := 0 to Length(vRefs) - 1 do
    Memo1.Lines.Add(vRefs[i].DisplayName.Text + ' = ' +
      sgcOPCUANodeIdToString(vRefs[i].NodeId.NodeId));
  // resolve a browse path to a node id
  Memo1.Lines.Add(sgcOPCUANodeIdToString(OPCUA.TranslateBrowsePath('i=85', '/2:Line1/2:Speed')));
  // call a method with two Int32 arguments
  SetLength(vInputs, 2);
  vInputs[0] := sgcOPCUAVariantSimple(uabtInt32, 2);
  vInputs[1] := sgcOPCUAVariantSimple(uabtInt32, 3);
  vOutputs := OPCUA.Call('ns=2;s=Methods', 'ns=2;s=Methods.Add', vInputs);
  Memo1.Lines.Add('Result: ' + VarToStr(vOutputs[0].Value));
end;
procedure TForm1.WatchLine1;
var
  oSubscription: TsgcOPCUASubscription;
begin
  OPCUA.OnDataChange := OnOPCUADataChange;
  oSubscription := OPCUA.CreateSubscription(1000);
  // sampling 100 ms, keep the 10 newest samples between two publishes
  FSpeed := OPCUA.AddMonitoredItem(oSubscription, 'ns=2;s=Line1.Speed', 100, 10);
  // only changes of more than 2 percent of the EURange of the variable
  OPCUA.AddMonitoredItem(oSubscription, 'ns=2;s=Line1.Level', 500, 1, True, uadbtPercent, 2);
end;

procedure TForm1.OnOPCUADataChange(Sender: TObject; aSubscription: TsgcOPCUASubscription;
  aMonitoredItem: TsgcOPCUAMonitoredItem; const aValue: TsgcOPCUADataValue);
begin
  if aMonitoredItem = FSpeed then
    Memo1.Lines.Add('Speed: ' + VarToStr(aValue.Value.Value))
  else
    Memo1.Lines.Add('Level: ' + VarToStr(aValue.Value.Value));
end;
uses
  sgcIndustrial, sgcOPCUA_Encoding;

procedure TForm1.WatchAlarms;
var
  oSubscription: TsgcOPCUASubscription;
begin
  OPCUA.OnEvent := OnOPCUAEvent;
  oSubscription := OPCUA.CreateSubscription(1000);
  // i=2253 is the Server object, which reports the events of the whole server
  OPCUA.AddEventMonitoredItem(oSubscription, 'i=2253', ['Message', 'Severity', 'SourceName']);
end;

procedure TForm1.OnOPCUAEvent(Sender: TObject; aSubscription: TsgcOPCUASubscription;
  aMonitoredItem: TsgcOPCUAMonitoredItem; const aEventFields: TsgcOPCUAVariantArray);
begin
  // the fields arrive in the order of the select clauses
  Memo1.Lines.Add(VarToStr(sgcOPCUAVariantToDelphi(aEventFields[2])) + ' (' +
    VarToStr(sgcOPCUAVariantToDelphi(aEventFields[1])) + '): ' +
    VarToStr(sgcOPCUAVariantToDelphi(aEventFields[0])));
end;
procedure TForm1.StartMonitor;
begin
  OPCUA := TsgcOPCUAClient.Create(Self);
  OPCUA.EndpointUrl := 'opc.tcp://192.168.1.60:4840';
  // try to reconnect every 5 seconds, with no limit of attempts
  OPCUA.WatchDog.Enabled := True;
  OPCUA.WatchDog.Interval := 5;
  OPCUA.WatchDog.Attempts := 0;
  OPCUA.OnStatusChange := OnOPCUAStatusChange;
  OPCUA.OnReconnect := OnOPCUAReconnect;
  OPCUA.Connect;
end;

procedure TForm1.OnOPCUAStatusChange(Sender: TObject; aState: TsgcOPCUAClientState);
begin
  if aState = opccsReconnecting then
    Memo1.Lines.Add('Connection lost, reconnecting');
end;

procedure TForm1.OnOPCUAReconnect(Sender: TObject; aMethod: TsgcOPCUAReconnectMethod);
begin
  case aMethod of
    opcrmSessionReactivated:
      Memo1.Lines.Add('Same session, missing notifications republished');
    opcrmSubscriptionsTransferred:
      Memo1.Lines.Add('New session, subscriptions transferred');
    opcrmSubscriptionsRecreated:
      Memo1.Lines.Add('New session, subscriptions created again');
  else
    Memo1.Lines.Add('New session');
  end;
end;

The helper functions sgcOPCUANodeIdToString and sgcOPCUAVariantSimple live in sgcOPCUA_Types, and sgcOPCUAVariantToDelphi in sgcOPCUA_Encoding; add those units when you use them. Delphi 7 to 2006 also need sgcBase_Helpers for TBytes.

An OPC UA client built for the plant floor

Subscriptions, filters and reconnect handled for you, with events where you want them.

Subscriptions without polling

CreateSubscription sets the publishing interval, AddMonitoredItem the sampling interval and the queue size of each node. The component keeps enough Publish requests in flight, acknowledges every notification and asks the server to republish any message that went missing.

Deadband and triggers

An absolute deadband (uadbtAbsolute) or a percent of the EURange (uadbtPercent) keeps noise out of your handlers. The trigger chooses whether a status change, a value change or a new timestamp is reported.

Events and alarms

AddEventMonitoredItem takes the event fields to return, such as Message, Severity and SourceName, and an optional where clause. Subscribe to a single source or to the Server object for every event of the server.

WatchDog reconnect

After a network drop, WatchDog first reactivates the same session and republishes the notifications that were missed. If the session is gone it opens a new one and transfers the subscriptions, or creates them again. OnReconnect reports which path was taken.

Same objects after a reconnect

Subscriptions and monitored items are owned by the client and survive a WatchDog reconnect. Server ids can change, the ClientHandle of an item never does, so your handlers keep working.

Events where you want them

OnDataChange, OnEvent, OnKeepAlive, OnConnect, OnDisconnect and OnError are delivered through NotifyEvents: queued to the main thread by default, synchronized, or raised in the client threads for services and console applications.

Signed and encrypted, with safe defaults

Set SecurityPolicy to opcspBasic256Sha256, opcspAes128_Sha256_RsaOaep or opcspAes256_Sha256_RsaPss and SecurityMode to opcsmSign or opcsmSignAndEncrypt. opcspBasic128Rsa15 and opcspBasic256 are deprecated by the OPC Foundation and are there for older servers. The client picks the matching endpoint from GetEndpoints and, when none matches, the error lists what the server offers.

Application certificate

Application.CertificateFile and PrivateKeyFile load the instance certificate. When the files do not exist yet, the client creates the certificate and saves it there, so the server administrator trusts it once. With no files set it is created in memory.

Server certificate

A server certificate is rejected unless OnValidateServerCertificate accepts it, so a fresh client never trusts an unknown server by accident. AutoAcceptServerCertificate exists for test benches.

User identity

Authentication.AuthenticationType selects Anonymous, user name and password, or an X.509 user certificate. The password is encrypted with the server key whenever the token policy of the server asks for it.

Tested against an independent OPC UA stack

The client is tested on the wire against a reference server built on asyncua, an independent open-source OPC UA implementation: all eleven endpoints of the server (every policy and mode), the three identity types, browsing 1,000 references with continuation points, reading 18 built-in types with arrays and a matrix, writing scalars and arrays, method calls, data change and event subscriptions with deadbands and where clauses, a two-minute publish run without a lost or duplicated message, and each reconnect path of the WatchDog.

Delphi OPC UA questions

Create a TsgcOPCUAClient, set EndpointUrl to the opc.tcp address of the server, call Connect and then ReadValue('ns=2;s=Line1.Speed'). It returns a Variant. Read reads several nodes and attributes in one call.

Call CreateSubscription with the publishing interval, add the nodes with AddMonitoredItem and assign OnDataChange. The event receives the subscription, the monitored item and the new TsgcOPCUADataValue with its status code and timestamps.

Basic256Sha256, Aes128_Sha256_RsaOaep and Aes256_Sha256_RsaPss in Sign or SignAndEncrypt mode, plus the deprecated Basic128Rsa15 and Basic256 for older servers, and None for test benches.

With WatchDog.Enabled the client retries every WatchDog.Interval seconds. It reactivates the same session when the server still has it, otherwise it opens a new session and transfers or recreates the subscriptions. OnReconnect reports which path was taken, and your subscription objects stay valid.

Yes. Set NotifyEvents := neNoSync when there is no message loop: the events then run in the client threads. Do not call Connect or other blocking services from those events; let WatchDog reconnect.

Delphi 7 to Delphi 13 and C++Builder, on Windows (32 and 64 bit) and Linux 64 bit.

The OPC UA client is included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, or as the standalone sgcIndustrial pack. It does not include an OPC UA server, the HTTPS, JSON and WebSocket transports, HistoryRead, PubSub, Reverse Connect and the Global Discovery Server.

More industrial components in sgcWebSockets

Industrial components

Serial port, Modbus and OPC UA in one section, with the full component reference.

OPC UA client reference

Properties, methods and events of TsgcOPCUAClient, with C++Builder and C# samples.

Delphi Modbus TCP and RTU

Modbus clients and servers for the devices that do not speak OPC UA.

Delphi MQTT client

Forward OPC UA data changes to MQTT topics: the usual gateway from the plant to the cloud.

Also for C# and .NET

The same OPC UA client, with the same class names, for .NET 8, 9, 10 and .NET Standard 2.0.

Best value: All-AccessEvery eSeGeCe product, Premium Support included, from €1,059/year.
See All-Access pricing

Read your first OPC UA node from Delphi

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