sgcIndustrial: Delphi, C++Builder, .NET용 Modbus, OPC UA, 시리얼 포트

· 컴포넌트
sgcIndustrial: 필드 버스로 SCADA 게이지에 연결된 PLC 랙, Modbus, OPC UA, 시리얼 포트

공장 현장의 소프트웨어 중 상당수는 Delphi, C++Builder, .NET으로 만들어져 있어요. 운영자 패널, 데이터 로거, 테스트 벤치, MES 커넥터, 장비 설정 도구가 그래요. 하지만 이런 애플리케이션이 사용해야 하는 프로토콜인 Modbus, OPC UA, 일반 시리얼 회선은 네이티브 컴포넌트로 제공되는 경우가 드물었어요. 보통은 ActiveX 브리지나 직접 감싼 C 라이브러리, 또는 코드와 PLC 사이에 놓는 별도의 게이트웨이를 썼어요.

sgcIndustrial이 그 공백을 메워요. 비주얼이 아닌 컴포넌트 여섯 개가 애플리케이션을 PLC, SCADA 서버, 전력량계, 드라이브, 시리얼 장치에 연결해요. sgcWebSockets의 나머지 부분과 같은 컴포넌트 방식이고, 전체 소스 코드를 제공하며, Delphi, C++Builder, .NET에서 같은 API를 써요.

1분으로 보는 sgcIndustrial: Delphi, C++Builder, .NET에서 쓰는 Modbus, OPC UA, 시리얼 포트. YouTube에서도 볼 수 있어요.

필드 레벨을 위한 컴포넌트 여섯 개

컴포넌트는 SGC Industrial 팔레트 페이지에 등록돼요. .NET 클래스도 이름이 같아요.

컴포넌트기능
TsgcSerialPortWindows, Linux, macOS에서 RS-232와 RS-485 포트를 열고, 데이터를 쓰고, 이벤트나 블로킹 읽기로 받아요. Modbus RTU 컴포넌트의 전송 계층이기도 해요.
TsgcModbusTCPClient
TsgcModbusRTUClient
TCP/IP나 시리얼 회선으로 코일과 레지스터를 읽고 써요. 32비트 값과 문자열용 타입 헬퍼가 있어요.
TsgcModbusTCPServer
TsgcModbusRTUServer
애플리케이션을 Modbus 장치로 만들어요. 스레드 안전한 TsgcModbusDataModel에서 응답하고, 모든 읽기와 쓰기를 확인하는 이벤트가 있어요.
TsgcOPCUAClientopc.tcp로 OPC UA 서버에 연결하고, 서명과 암호화를 지원하는 보안 정책을 쓰며, 주소 공간을 탐색하고, 읽고, 쓰고, 메서드를 호출하고, 데이터 변경과 이벤트를 구독해요.

Modbus TCP: 몇 줄로 PLC 읽고 쓰기

모든 Modbus 요청은 값을 반환하거나 명확한 예외를 발생시키는 블로킹 호출이라서, PLC를 읽는 일이 로컬 변수를 읽는 것처럼 보여요. 프레이밍, 트랜잭션 id, CRC 검사, 타임아웃, 재시도는 컴포넌트가 처리해요.

uses
  sgcIndustrial;

procedure TForm1.ConnectClient;
begin
  FClient := TsgcModbusTCPClient.Create(Self);
  FClient.Host := '192.168.1.50';
  FClient.Port := 502;
  FClient.UnitId := 1;
  FClient.Timeout := 1000;
  FClient.Retries := 2;
  FClient.Active := True;
end;

procedure TForm1.ReadAndWrite;
var
  vRegisters: TsgcModbusRegisters;
  vCoils: TsgcModbusBits;
begin
  try
    // FC 03 and FC 01
    vRegisters := FClient.ReadHoldingRegisters(0, 10);
    vCoils := FClient.ReadCoils(0, 8);
    // FC 05 and FC 06
    FClient.WriteSingleCoil(10, True);
    FClient.WriteSingleRegister(20, 1500);
    // FC 22: clear bit 0 and set bit 3 of register 30
    FClient.MaskWriteRegister(30, $FFF6, $0008);
    // typed values: a 32-bit float stored low word first, as many PLCs do
    FClient.WordOrder := mwoCDAB;
    FClient.WriteFloat32(300, 72.5);
    Memo1.Lines.Add(Format('HR0 = %d, setpoint = %.1f, coil 0 = %s',
      [vRegisters[0], FClient.ReadFloat32(300), BoolToStr(vCoils[0], True)]));
    // a string packed two characters per register
    Memo1.Lines.Add('Model: ' + string(FClient.ReadString(400, 8)));
  except
    on E: EsgcModbusException do
      Memo1.Lines.Add(Format('Device exception %d', [E.ExceptionCode]));
    on E: EsgcModbusTimeout do
      Memo1.Lines.Add('No response');
  end;
end;
#include "sgcIndustrial.hpp"

void __fastcall TForm1::ConnectClient()
{
  FClient = new TsgcModbusTCPClient(this);
  FClient->Host = "192.168.1.50"; // Port is 502 by default
  FClient->UnitId = 1;
  FClient->Timeout = 1000;
  FClient->Retries = 2;
  FClient->Active = true;
}

void __fastcall TForm1::ReadAndWrite()
{
  try
  {
    // FC 03 and FC 01
    TsgcModbusRegisters vRegisters = FClient->ReadHoldingRegisters(0, 10);
    TsgcModbusBits vCoils = FClient->ReadCoils(0, 8);
    // FC 05 and FC 06
    FClient->WriteSingleCoil(10, true);
    FClient->WriteSingleRegister(20, 1500);
    // FC 22: clear bit 0 and set bit 3 of register 30
    FClient->MaskWriteRegister(30, 0xFFF6, 0x0008);
    // typed values: a 32-bit float stored low word first, as many PLCs do
    FClient->WordOrder = mwoCDAB;
    FClient->WriteFloat32(300, 72.5);
    Memo1->Lines->Add("HR0 = " + IntToStr(vRegisters[0]) + ", setpoint = " +
      FloatToStrF(FClient->ReadFloat32(300), ffFixed, 7, 1) + ", coil 0 = " +
      BoolToStr(vCoils[0], true));
    // a string packed two characters per register
    Memo1->Lines->Add("Model: " + String(FClient->ReadString(400, 8)));
  }
  catch (EsgcModbusException &E)
  {
    Memo1->Lines->Add("Device exception " + IntToStr(E.ExceptionCode));
  }
  catch (EsgcModbusTimeout &E)
  {
    Memo1->Lines->Add("No response");
  }
}
using System;
using esegece.sgcWebSockets;

class PlcClient
{
    TsgcModbusTCPClient FClient = new TsgcModbusTCPClient();

    public void ConnectClient()
    {
        FClient.Host = "192.168.1.50";
        FClient.Port = 502;
        FClient.UnitId = 1;
        FClient.Timeout = 1000;
        FClient.Retries = 2;
        FClient.Active = true;
    }

    public void ReadAndWrite()
    {
        try
        {
            // FC 03 and FC 01
            ushort[] vRegisters = FClient.ReadHoldingRegisters(0, 10);
            bool[] vCoils = FClient.ReadCoils(0, 8);
            // FC 05 and FC 06
            FClient.WriteSingleCoil(10, true);
            FClient.WriteSingleRegister(20, 1500);
            // FC 22: clear bit 0 and set bit 3 of register 30
            FClient.MaskWriteRegister(30, 0xFFF6, 0x0008);
            // typed values: a 32-bit float stored low word first, as many PLCs do
            FClient.WordOrder = TsgcModbusWordOrder.mwoCDAB;
            FClient.WriteFloat32(300, 72.5f);
            Console.WriteLine($"HR0 = {vRegisters[0]}, setpoint = {FClient.ReadFloat32(300):F1}, coil 0 = {vCoils[0]}");
            // a string packed two characters per register
            Console.WriteLine("Model: " + FClient.ReadString(400, 8));
        }
        catch (EsgcModbusException E)
        {
            Console.WriteLine("Device exception " + E.ExceptionCode);
        }
        catch (EsgcModbusTimeout)
        {
            Console.WriteLine("No response");
        }
    }
}

데이터 모델을 갖춘 Modbus 서버

TsgcModbusTCPServer와 TsgcModbusRTUServer는 애플리케이션을 Modbus 장치로 만들어요. 값은 코일, 디스크리트 입력, 홀딩 및 입력 레지스터, 장치 식별 문자열을 담은 스레드 안전한 TsgcModbusDataModel에 있어요. OnReadRequest로 클라이언트가 읽기 직전에 실시간 값을 갱신할 수 있고, OnWriteRequest로 모든 쓰기를 검사해서 Modbus 예외 코드로 거부할 수 있어요. 그래서 시뮬레이터, 게이트웨이, 테스트 장비에 잘 맞아요.

uses
  sgcIndustrial;

procedure TForm1.StartServer;
begin
  FServer := TsgcModbusTCPServer.Create(Self);
  FServer.Port := 502;
  FServer.DataModel.HoldingRegisterCount := 1000;
  FServer.DataModel.SetHoldingRegister(0, 1234);
  FServer.DataModel.SetCoil(5, True);
  // answers FC 43/14, Read Device Identification
  FServer.DataModel.VendorName := 'eSeGeCe';
  FServer.DataModel.ProductCode := 'PLC-1';
  FServer.DataModel.MajorMinorRevision := '1.0';
  FServer.OnReadRequest := OnModbusReadRequest;
  FServer.OnWriteRequest := OnModbusWriteRequest;
  FServer.Active := True;
end;

procedure TForm1.OnModbusReadRequest(Sender: TObject; aUnitId,
  aFunctionCode: Byte; aAddress, aCount: Word; var aExceptionCode: Byte);
begin
  // live value: refresh input register 0 before the client reads it
  if aFunctionCode = CS_MODBUS_FC_READ_INPUT_REGISTERS then
    FServer.DataModel.SetInputRegister(0, FTemperature);
end;

procedure TForm1.OnModbusWriteRequest(Sender: TObject; aUnitId,
  aFunctionCode: Byte; aAddress, aCount: Word; var aBits: TsgcModbusBits;
  var aRegisters: TsgcModbusRegisters; var aExceptionCode: Byte);
var
  i: Integer;
begin
  // connection thread: setpoints accept 0..1000 only
  if (aFunctionCode = CS_MODBUS_FC_WRITE_SINGLE_REGISTER) or
    (aFunctionCode = CS_MODBUS_FC_WRITE_MULTIPLE_REGISTERS) then
    for i := 0 to Length(aRegisters) - 1 do
      if aRegisters[i] > 1000 then
      begin
        aExceptionCode := CS_MODBUS_EX_ILLEGAL_DATA_VALUE;
        Exit;
      end;
end;
#include "sgcIndustrial.hpp"

void __fastcall TForm1::StartServer()
{
  FServer = new TsgcModbusTCPServer(this);
  FServer->Port = 502;
  FServer->DataModel->HoldingRegisterCount = 1000;
  FServer->DataModel->SetHoldingRegister(0, 1234);
  FServer->DataModel->SetCoil(5, true);
  // answers FC 43/14, Read Device Identification
  FServer->DataModel->VendorName = "eSeGeCe";
  FServer->DataModel->ProductCode = "PLC-1";
  FServer->DataModel->MajorMinorRevision = "1.0";
  FServer->OnReadRequest = OnModbusReadRequest;
  FServer->OnWriteRequest = OnModbusWriteRequest;
  FServer->Active = true;
}

void __fastcall TForm1::OnModbusReadRequest(TObject *Sender, Byte aUnitId,
  Byte aFunctionCode, Word aAddress, Word aCount, Byte &aExceptionCode)
{
  // live value: refresh input register 0 before the client reads it
  if (aFunctionCode == CS_MODBUS_FC_READ_INPUT_REGISTERS)
    FServer->DataModel->SetInputRegister(0, FTemperature);
}

void __fastcall TForm1::OnModbusWriteRequest(TObject *Sender, Byte aUnitId,
  Byte aFunctionCode, Word aAddress, Word aCount, TsgcModbusBits &aBits,
  TsgcModbusRegisters &aRegisters, Byte &aExceptionCode)
{
  // connection thread: setpoints accept 0..1000 only
  if ((aFunctionCode == CS_MODBUS_FC_WRITE_SINGLE_REGISTER) ||
      (aFunctionCode == CS_MODBUS_FC_WRITE_MULTIPLE_REGISTERS))
    for (int i = 0; i < aRegisters.Length; i++)
      if (aRegisters[i] > 1000)
      {
        aExceptionCode = CS_MODBUS_EX_ILLEGAL_DATA_VALUE;
        return;
      }
}
using System;
using esegece.sgcWebSockets;

class PlcServer
{
    TsgcModbusTCPServer FServer = new TsgcModbusTCPServer();
    ushort FTemperature = 215;

    public void StartServer()
    {
        FServer.Port = 502;
        FServer.DataModel.HoldingRegisterCount = 1000;
        FServer.DataModel.SetHoldingRegister(0, 1234);
        FServer.DataModel.SetCoil(5, true);
        // answers FC 43/14, Read Device Identification
        FServer.DataModel.VendorName = "eSeGeCe";
        FServer.DataModel.ProductCode = "PLC-1";
        FServer.DataModel.MajorMinorRevision = "1.0";
        FServer.OnReadRequest += OnModbusReadRequest;
        FServer.OnWriteRequest += OnModbusWriteRequest;
        FServer.Active = true;
    }

    void OnModbusReadRequest(object Sender, byte aUnitId, byte aFunctionCode,
        ushort aAddress, ushort aCount, ref byte aExceptionCode)
    {
        // live value: refresh input register 0 before the client reads it
        if (aFunctionCode == sgcModbus_Classes.CS_MODBUS_FC_READ_INPUT_REGISTERS)
            FServer.DataModel.SetInputRegister(0, FTemperature);
    }

    void OnModbusWriteRequest(object Sender, byte aUnitId, byte aFunctionCode,
        ushort aAddress, ushort aCount, ref bool[] aBits, ref ushort[] aRegisters,
        ref byte aExceptionCode)
    {
        // connection thread: setpoints accept 0..1000 only
        if (aFunctionCode == sgcModbus_Classes.CS_MODBUS_FC_WRITE_SINGLE_REGISTER ||
            aFunctionCode == sgcModbus_Classes.CS_MODBUS_FC_WRITE_MULTIPLE_REGISTERS)
            foreach (ushort vValue in aRegisters)
                if (vValue > 1000)
                {
                    aExceptionCode = sgcModbus_Classes.CS_MODBUS_EX_ILLEGAL_DATA_VALUE;
                    return;
                }
    }
}

RS-485와 Modbus RTU

TsgcSerialPort는 Windows, Linux, macOS에서 RS-232와 RS-485 포트를 열어요. ListPorts는 컴퓨터의 포트 목록을 반환하고, RtsControl := srcToggle은 반이중 버스를 위해 전송하는 동안 RS-485 드라이버를 켜요. 같은 포트가 TsgcModbusRTUClient와 TsgcModbusRTUServer의 전송 계층이고, 이 둘이 RTU 프레이밍과 CRC 검사를 더해요. 유닛 id 0은 브로드캐스트를 보내고, 모든 슬레이브가 응답 없이 실행해요.

uses
  sgcIndustrial;

procedure TForm1.ReadSlave;
var
  vRegisters: TsgcModbusRegisters;
begin
  // COM1, COM3, ... on Windows; /dev/ttyUSB0, /dev/ttyACM0, ... on Linux
  TsgcSerialPort.ListPorts(ComboBox1.Items);

  FPort := TsgcSerialPort.Create(Self);
  FPort.Port := 'COM4';
  FPort.BaudRate := 19200;
  FPort.Parity := spEven;
  FPort.RtsControl := srcToggle; // RS-485 half duplex: RTS on while sending
  FPort.Open;

  FRTU := TsgcModbusRTUClient.Create(Self);
  FRTU.SerialPort := FPort;
  FRTU.UnitId := 17;
  FRTU.Timeout := 500;
  FRTU.Retries := 2;
  vRegisters := FRTU.ReadHoldingRegisters(107, 3);
  Memo1.Lines.Add(Format('Register 107 = %d', [vRegisters[0]]));

  // unit id 0 = broadcast: every slave executes the write, none answers
  FRTU.WriteSingleRegister(0, 1, 100);
end;

OPC UA: 보안 연결, 읽기, 구독

TsgcOPCUAClient는 opc.tcp 위에서 OPC UA 바이너리 프로토콜을 사용해요. 보안은 속성 두 개로, 사용자 ID는 세 번째 속성으로 설정해요.

샘플은 Basic256Sha256과 SignAndEncrypt로 연결하고, 사용자 이름으로 로그인하고, 값을 읽은 다음 데드밴드를 지정해 구독해요. 그래서 서버는 0.5보다 큰 변화만 알려 줘요.

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

procedure TForm1.ConnectSecure;
var
  oSubscription: TsgcOPCUASubscription;
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: opcatAnonymous, opcatUserName or opcatCertificate
  FClient.Authentication.AuthenticationType := opcatUserName;
  FClient.Authentication.User := 'operator';
  FClient.Authentication.Password := 'secret';
  // decide which server certificates you trust
  FClient.OnValidateServerCertificate := OnOPCUAValidateServerCertificate;
  FClient.OnDataChange := OnOPCUADataChange;
  FClient.Connect;
  // read the Value attribute of a variable
  Memo1.Lines.Add('Temperature: ' + VarToStr(FClient.ReadValue('ns=2;s=Line1.Temperature')));
  // publishing interval 500 ms, sampling 250 ms, report changes larger than 0.5
  oSubscription := FClient.CreateSubscription(500);
  FClient.AddMonitoredItem(oSubscription, 'ns=2;s=Line1.Temperature', 250, 1, True,
    uadbtAbsolute, 0.5);
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;

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;
#include "sgcIndustrial.hpp"

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: opcatAnonymous, opcatUserName or opcatCertificate
  FClient->Authentication->AuthenticationType = opcatUserName;
  FClient->Authentication->User = "operator";
  FClient->Authentication->Password = "secret";
  // decide which server certificates you trust
  FClient->OnValidateServerCertificate = OnOPCUAValidateServerCertificate;
  FClient->OnDataChange = OnOPCUADataChange;
  FClient->Connect();
  // read the Value attribute of a variable
  Memo1->Lines->Add("Temperature: " + VarToStr(FClient->ReadValue("ns=2;s=Line1.Temperature")));
  // publishing interval 500 ms, sampling 250 ms, report changes larger than 0.5
  TsgcOPCUASubscription *oSubscription = FClient->CreateSubscription(500);
  FClient->AddMonitoredItem(oSubscription, "ns=2;s=Line1.Temperature", 250, 1, true,
    uadbtAbsolute, 0.5);
}

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

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 System.IO;
using System.Linq;
using esegece.sgcWebSockets;

class LineMonitor
{
    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: opcatAnonymous, opcatUserName or opcatCertificate
        FClient.Authentication.AuthenticationType = TsgcOPCUAAuthenticationType.opcatUserName;
        FClient.Authentication.User = "operator";
        FClient.Authentication.Password = "secret";
        // decide which server certificates you trust
        FClient.OnValidateServerCertificate += OnOPCUAValidateServerCertificate;
        FClient.OnDataChange += OnOPCUADataChange;
        FClient.Connect();
        // read the Value attribute of a variable
        Console.WriteLine("Temperature: " + FClient.ReadValue("ns=2;s=Line1.Temperature"));
        // publishing interval 500 ms, sampling 250 ms, report changes larger than 0.5
        TsgcOPCUASubscription oSubscription = FClient.CreateSubscription(500);
        FClient.AddMonitoredItem(oSubscription, "ns=2;s=Line1.Temperature", 250, 1, true,
            TsgcOPCUADeadbandType.uadbtAbsolute, 0.5);
    }

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

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

탐색, 쓰기, 호출

Browse는 노드의 참조를 나열하고 연속 지점을 대신 따라가요. TranslateBrowsePath는 /2:Line1/2:Speed 같은 경로를 노드 id로 변환하고, WriteValue는 먼저 노드의 데이터 형식을 읽어서 그 형식으로 쓰며, Call은 서버의 메서드를 실행하고 출력 인수를 반환해요.

uses
  sgcIndustrial, sgcOPCUA_Types;

procedure TForm1.BrowseWriteAndCall;
var
  vRefs: TsgcOPCUAReferenceDescriptionArray;
  vInputs, vOutputs: TsgcOPCUAVariantArray;
  i: Integer;
begin
  // i=85 is the Objects folder
  vRefs := FClient.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(FClient.TranslateBrowsePath('i=85', '/2:Line1/2:Speed')));
  // the data type of the node is read first and used for the written value
  FClient.WriteValue('ns=2;s=Line1.Setpoint', 75.5);
  // call a method with two Int32 arguments
  SetLength(vInputs, 2);
  vInputs[0] := sgcOPCUAVariantSimple(uabtInt32, 2);
  vInputs[1] := sgcOPCUAVariantSimple(uabtInt32, 3);
  vOutputs := FClient.Call('ns=2;s=Methods', 'ns=2;s=Methods.Add', vInputs);
  Memo1.Lines.Add('Result: ' + VarToStr(vOutputs[0].Value));
end;

구독과 이벤트

구독은 데이터 변경을 OnDataChange로 전달하고, 모니터링 항목마다 샘플링 간격, 큐 크기, 절대값 또는 백분율 데드밴드를 지정할 수 있어요. 이벤트 모니터링 항목은 알람과 조건을 OnEvent로 전달하고, 선택한 필드를 선택한 순서대로 받아요.

uses
  sgcIndustrial, sgcOPCUA_Encoding;

procedure TForm1.WatchAlarms;
var
  oSubscription: TsgcOPCUASubscription;
begin
  FClient.OnEvent := OnOPCUAEvent;
  oSubscription := FClient.CreateSubscription(1000);
  // i=2253 is the Server object, which reports the events of the whole server
  FClient.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;

구독을 복원하는 WatchDog 재연결

공장 현장의 네트워크는 끊어져요. WatchDog를 켜면 클라이언트는 연결이 끊긴 뒤 스스로 다시 연결하고 가지고 있던 것을 복원해요. 새 보안 채널에서 같은 세션을 다시 활성화하고 서버에 누락된 알림을 다시 게시하도록 요청하거나, 새 세션을 열어 구독을 옮기거나, 클라이언트 목록에서 구독을 다시 만들어요. 이 중 어느 경우였는지는 OnReconnect가 알려 줘요. 자동 재연결은 Delphi와 .NET에서 쓸 수 있어요.

procedure TForm1.StartMonitor;
begin
  FClient := TsgcOPCUAClient.Create(Self);
  FClient.EndpointUrl := 'opc.tcp://192.168.1.60:4840';
  // try to reconnect every 5 seconds, with no limit of attempts
  FClient.WatchDog.Enabled := True;
  FClient.WatchDog.Interval := 5;
  FClient.WatchDog.Attempts := 0;
  FClient.OnStatusChange := OnOPCUAStatusChange;
  FClient.OnReconnect := OnOPCUAReconnect;
  FClient.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;

다른 구현과의 호환성 테스트

프로토콜 스택은 상호 운용성만큼만 좋은 법이라서, sgcIndustrial은 우리가 만들지 않은 구현과 대조해 테스트했어요.

플랫폼

이 글의 모든 코드 샘플은 현재 소스에 대해 컴파일했어요. Delphi 샘플은 Delphi 7과 Delphi 13(Win32, Win64)으로, C++Builder 샘플은 C++Builder 13으로, C# 샘플은 .NET 8로 컴파일했어요.

출시 시기와 가격

오늘 2026년 11월 27일부터 sgcIndustrial은 독립형 팩으로 판매하며, 개발자 1인용은 €249부터 시작하고 Team과 Site 라이선스도 있어요. 모든 라이선스에는 전체 소스 코드와 1년간의 업데이트가 포함되고 sgcWebSockets Core 런타임도 들어 있어서 따로 살 것이 없어요. .NET 에디션인 sgcIndustrial .NET은 가격 페이지에서 따로 판매해요.

이미 고객이신가요? 여섯 개 컴포넌트는 Delphi용과 .NET용 sgcWebSockets Enterprise와 All-Access에도 모두 포함돼요.

sgcIndustrial 알아보기 가격 보기

링크

질문이나 의견이 있으신가요? 문의해 주세요. 코드를 직접 작성한 사람들이 답변해 드려요.