OPC UA 클라이언트

Delphi, C++Builder, .NET 애플리케이션을 OPC UA 서버를 실행하는 PLC, SCADA 시스템, 게이트웨이에 연결하세요. 서명 및 암호화된 opc.tcp 연결로 주소 공간을 탐색하고, 변수를 읽고 쓰고, 메서드를 호출하고, 데이터 변경과 이벤트를 구독할 수 있어요.

신규

TsgcOPCUAClient

OPC UA 클라이언트 측 전체를 하나의 컴포넌트로: 보안 채널, 세션, 서비스, 구독.

컴포넌트 클래스

TsgcOPCUAClient

프로토콜

opc.tcp 기반 OPC UA 바이너리 (UA TCP, UA Secure Conversation, UA Binary 인코딩)

보안

Basic256Sha256, Aes128_Sha256_RsaOaep, Aes256_Sha256_RsaPss 기반 Sign 및 SignAndEncrypt, Anonymous, 사용자 이름, X.509 ID

에디션

sgcWebSockets Enterprise(Delphi 및 .NET)와 All-Access, 또는 독립형 sgcIndustrial 팩에 포함

연결하고, 읽고, 쓰기

EndpointUrl을 설정하고, 보안 정책과 모드를 선택한 다음 Connect를 호출해요. 각 서비스 호출은 서버가 응답할 때까지 블로킹되며, 실패하면 OPC UA 상태 코드와 함께 EsgcOPCUAError를 발생시켜요.

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

내부 구성

보안 채널, 세션, 게시 루프는 컴포넌트가 처리하므로, 코드는 노드 ID와 값만 다루면 돼요.

서비스

GetEndpoints, Browse와 BrowseNext(연속 지점은 자동으로 따라가요), TranslateBrowsePath, 모든 속성에 대한 Read와 Write, 메서드용 Call. ReadValue와 WriteValue는 노드 ID 문자열을 받고 노드의 데이터 타입을 사용해요.

보안 정책

Basic256Sha256, Aes128_Sha256_RsaOaep, Aes256_Sha256_RsaPss, 그리고 구형 서버용으로 더 이상 권장되지 않는 Basic128Rsa15와 Basic256을 Sign 또는 SignAndEncrypt 모드로 사용할 수 있어요. 클라이언트는 서버 서명과 nonce를 검사하고, 도중에 변경된 엔드포인트 목록을 거부해요.

사용자 ID

Anonymous, 사용자 이름과 비밀번호(토큰 정책이 요구하면 서버 키로 암호화), 또는 개인 키로 서명한 X.509 사용자 인증서.

인증서

애플리케이션 인스턴스 인증서는 DER 또는 PEM 파일에서 불러오며, 처음 연결할 때 생성되어 해당 파일에 저장돼요. 파일을 지정하지 않으면 메모리에서 생성돼요. 서버 인증서는 OnValidateServerCertificate가 승인하지 않으면 거부돼요.

구독

샘플링 간격, 큐 크기, 절대 또는 퍼센트 데드밴드, 트리거를 지원하는 데이터 변경 항목, select 절과 선택적 where 절을 지원하는 이벤트 항목. 확인 응답과 누락된 알림의 재게시는 클라이언트가 처리해요.

자동 재연결

WatchDog는 Delphi, C++Builder, .NET에서 네트워크가 끊긴 뒤 재연결해요. 같은 세션을 다시 활성화하고 놓친 내용을 다시 게시하거나, 새 세션으로 구독을 이전하거나 다시 만들어요. OnReconnect가 어떤 경로를 택했는지 알려 줘요.

서버가 푸시하는 데이터 변경과 이벤트

구독을 만들고, 모니터링할 항목을 추가하고, OnDataChange를 처리해요. 값은 폴링 없이 선택한 게시 간격으로 도착해요.

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

서명 및 암호화된 연결

정책과 모드를 선택하고, 클라이언트에 애플리케이션 인증서와 사용자 ID를 지정하고, 신뢰할 서버 인증서를 결정하세요.

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

사양 및 참고문헌

이 컴포넌트가 구현하는 프로토콜의 공식 출처예요.

OPC UA 클라이언트 관련 질문

opc.tcp 엔드포인트를 가진 모든 OPC UA 서버: 내장 서버가 있는 PLC와 컨트롤러, SCADA 및 MES 시스템, 프로토콜 게이트웨이. 클라이언트는 독립적인 오픈 소스 OPC UA 스택인 asyncua 기반 참조 서버의 11개 엔드포인트 전체에 대해 테스트됐어요.

Browse로 Objects 폴더(i=85)에서 탐색하거나, /2:Line1/2:Speed 같은 경로를 TranslateBrowsePath로 해석하세요. 노드 ID는 텍스트로 써요. 문자열 ID는 ns=2;s=Line1.Speed, 네임스페이스 0의 숫자 ID는 i=2258이에요.

기본값은 opcspNone이며, 대부분의 서버는 테스트용으로만 허용해요. 서명하거나 암호화하려면 SecurityPolicy와 SecurityMode를 설정하세요. 서버 인증서는 OnValidateServerCertificate가 승인하지 않으면 거부되며, Basic128Rsa15와 Basic256은 더 이상 권장되지 않고 구형 서버를 위해서만 유지돼요.

네, WatchDog.Enabled를 설정하세요. 클라이언트가 세션을 다시 활성화하고 놓친 알림을 다시 게시하거나, 새 세션을 열어 구독을 이전하거나 다시 만들어요. Delphi, C++Builder, .NET에서 동일하게 동작하며, OnReconnect가 어떤 경로를 택했는지 알려 줘요.

이 컴포넌트는 바이너리 인코딩을 사용하는 opc.tcp 기반 OPC UA 클라이언트예요. OPC UA 서버, HTTPS, JSON, WebSocket 전송, HistoryRead, PubSub, Reverse Connect, Global Discovery Server는 포함되지 않아요.

sgcIndustrial 팩의 일부로 sgcWebSockets Enterprise(Delphi 및 .NET)와 All-Access에 포함돼요. Delphi에서는 uses 절에 sgcIndustrial을 추가하세요.

문서 및 데모

컴포넌트 레퍼런스로 바로 이동하고, 데모 프로젝트를 열고, 기술 문서를 읽어 보세요.

Online Help: TsgcOPCUAClient OPC UA 클라이언트의 전체 속성, 메서드, 이벤트 레퍼런스예요.
Online Help: OPC UA Subscriptions 모니터링 항목, 데드밴드, 이벤트 필터, keep-alive, 재연결 동작.
데모 프로젝트: Industrial\05.OPCUA_Client Delphi, C++Builder, .NET용 OPC UA 클라이언트. sgcWebSockets 패키지에 포함되어 있어요.
기술 문서 (PDF) 이 컴포넌트만을 위한 기능, 빠른 시작, 코드 샘플, 1차 자료 레퍼런스.
사용자 매뉴얼 (PDF) 라이브러리의 모든 컴포넌트를 다루는 종합 매뉴얼이에요.
최고의 가성비: All-Access모든 eSeGeCe 제품과 프리미엄 지원이 포함되어 연 €1,059부터 이용할 수 있어요.
All-Access 가격 보기

sgcWebSockets Enterprise에 포함

sgcWebSockets Enterprise(Delphi 및 .NET)와 All-Access, 또는 독립형 sgcIndustrial 팩에 포함.