Cliente OPC UA

Conecte aplicações Delphi, C++Builder e .NET a CLPs, sistemas SCADA e gateways que executam um servidor OPC UA: navegue pelo espaço de endereçamento, leia e grave variáveis, chame métodos e assine mudanças de dados e eventos por uma conexão opc.tcp assinada e criptografada.

Novo

TsgcOPCUAClient

Um componente para todo o lado cliente do OPC UA: canal seguro, sessão, serviços e assinaturas.

Classe de componente

TsgcOPCUAClient

Protocolo

OPC UA binary sobre opc.tcp (UA TCP, UA Secure Conversation, codificação UA Binary)

Segurança

Sign e SignAndEncrypt com Basic256Sha256, Aes128_Sha256_RsaOaep e Aes256_Sha256_RsaPss; identidades Anonymous, nome de usuário e X.509

Edição

Incluído no sgcWebSockets Enterprise (Delphi e .NET) e All-Access, ou no pacote independente sgcIndustrial

Conectar, ler e gravar

Defina EndpointUrl, escolha a política e o modo de segurança e chame Connect. Cada chamada de serviço bloqueia até o servidor responder e levanta EsgcOPCUAError, com o código de status OPC UA, quando falha.

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);
    }
}

O que tem por dentro

O canal seguro, a sessão e o ciclo de publicação ficam por conta do componente, então seu código trabalha com ids de nó e valores.

Serviços

GetEndpoints, Browse e BrowseNext (os pontos de continuação são seguidos para você), TranslateBrowsePath, Read e Write de qualquer atributo, e Call para métodos. ReadValue e WriteValue recebem uma string de id de nó e usam o tipo de dados do nó.

Políticas de segurança

Basic256Sha256, Aes128_Sha256_RsaOaep e Aes256_Sha256_RsaPss, além das obsoletas Basic128Rsa15 e Basic256 para servidores mais antigos, no modo Sign ou SignAndEncrypt. O cliente verifica a assinatura e o nonce do servidor e rejeita uma lista de endpoints alterada no caminho.

Identidade do usuário

Anonymous, nome de usuário e senha (criptografados com a chave do servidor quando a política do token exige) ou um certificado de usuário X.509 assinado com sua chave privada.

Certificados

O certificado da instância da aplicação é carregado de arquivos DER ou PEM, criado na primeira conexão e salvo nesses arquivos, ou criado em memória quando nenhum arquivo é definido. Um certificado de servidor é rejeitado a menos que OnValidateServerCertificate o aceite.

Assinaturas

Itens de mudança de dados com intervalo de amostragem, tamanho da fila, deadband absoluto ou percentual e gatilho; itens de evento com cláusulas select e uma cláusula where opcional. Os reconhecimentos e a republicação das notificações perdidas ficam por conta do cliente.

Reconexão automática

WatchDog reconecta após uma queda de rede, no Delphi, C++Builder e .NET: ele reativa a mesma sessão e republica o que foi perdido, ou transfere ou recria as assinaturas em uma nova sessão. OnReconnect informa qual caminho foi seguido.

Mudanças de dados e eventos, enviados pelo servidor

Crie uma assinatura, adicione os itens a monitorar e trate OnDataChange. Os valores chegam sem polling, no intervalo de publicação que você escolher.

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);
    }
}

Conexões assinadas e criptografadas

Escolha a política e o modo, forneça ao cliente o certificado da aplicação e uma identidade de usuário, e decida em quais certificados de servidor confiar.

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);
    }
}

Especificações e referências

Fontes autoritativas do protocolo que este componente implementa.

Perguntas sobre o cliente OPC UA

Qualquer servidor OPC UA com um endpoint opc.tcp: CLPs e controladores com servidor embutido, sistemas SCADA e MES e gateways de protocolo. O cliente é testado contra um servidor de referência baseado em asyncua, uma pilha OPC UA open source independente, em todos os seus onze endpoints.

Navegue a partir da pasta Objects (i=85) com Browse, ou resolva um caminho como /2:Line1/2:Speed com TranslateBrowsePath. Os ids de nó são escritos como texto: ns=2;s=Line1.Speed para um id string, i=2258 para um id numérico no namespace 0.

O padrão é opcspNone, que a maioria dos servidores só permite para testes. Defina SecurityPolicy e SecurityMode para assinar ou criptografar. Certificados de servidor são rejeitados a menos que OnValidateServerCertificate os aceite, e Basic128Rsa15 e Basic256 estão obsoletos e são mantidos apenas para servidores mais antigos.

Sim, defina WatchDog.Enabled: o cliente reativa a sessão e republica as notificações perdidas, ou abre uma nova sessão e transfere ou recria as assinaturas. Funciona da mesma forma no Delphi, C++Builder e .NET, e OnReconnect informa qual caminho foi seguido.

O componente é um cliente OPC UA via opc.tcp com codificação binária. Ele não inclui um servidor OPC UA, os transportes HTTPS, JSON e WebSocket, HistoryRead, PubSub, Reverse Connect e o Global Discovery Server.

Ele está incluído no sgcWebSockets Enterprise (Delphi e .NET) e All-Access, como parte do pacote sgcIndustrial. No Delphi, adicione sgcIndustrial à cláusula uses.

Documentação e demos

Acesse diretamente a referência do componente, abra o projeto de demonstração e leia o documento técnico.

Online Help: TsgcOPCUAClient Referência completa de propriedades, métodos e eventos do cliente OPC UA.
Online Help: OPC UA Subscriptions Itens monitorados, deadbands, filtros de eventos, keep-alive e comportamento de reconexão.
Projeto de demonstração: Industrial\05.OPCUA_Client Um cliente OPC UA para Delphi, C++Builder e .NET. Ele acompanha o pacote sgcWebSockets.
Documento técnico (PDF) Recursos, início rápido, exemplos de código e referências de fontes primárias somente para este componente.
Manual do usuário (PDF) Manual abrangente cobrindo todos os componentes da biblioteca.
Melhor custo-benefício: All-AccessTodos os produtos da eSeGeCe, com Suporte Premium incluído, a partir de €1,059/ano.
Ver preços do All-Access

Incluído no sgcWebSockets Enterprise

Incluído no sgcWebSockets Enterprise (Delphi e .NET) e All-Access, ou no pacote independente sgcIndustrial.