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。

一分钟了解 sgcIndustrial:在 Delphi、C++Builder 和 .NET 中使用 Modbus、OPC UA 和串口。也可在 YouTube 观看。

面向现场层的六个组件

这些组件注册在 SGC Industrial 组件面板页上。.NET 类使用相同的名称。

组件功能
TsgcSerialPort在 Windows、Linux 和 macOS 上打开 RS-232 和 RS-485 端口,写入数据,并通过事件或阻塞读取接收数据。它同时也是 Modbus RTU 组件的传输层。
TsgcModbusTCPClient
TsgcModbusRTUClient
通过 TCP/IP 或串行线路读写线圈和寄存器,并为 32 位数值和字符串提供类型化的辅助方法。
TsgcModbusTCPServer
TsgcModbusRTUServer
把您的应用程序变成 Modbus 设备,由线程安全的 TsgcModbusDataModel 应答,并提供事件来检查每一次读写。
TsgcOPCUAClient通过 opc.tcp 连接 OPC UA 服务器,支持签名和加密的安全策略,可浏览地址空间、读取、写入、调用方法,并订阅数据变化和事件。

Modbus TCP:几行代码读写 PLC

每个 Modbus 请求都是一次阻塞调用,要么返回数值,要么抛出明确的异常,因此读取 PLC 就像读取本地变量一样。组件会为您处理帧格式、事务标识、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 校验。单元标识 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 二进制协议。安全性由两个属性配置,用户身份由第三个属性配置:

该示例使用 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 这样的路径解析为节点标识;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 作为独立软件包发售,单个开发者起价 €249,同时也提供 Team 和 Site 许可证。每个许可证都包含完整源代码和 1 年更新,并包含 sgcWebSockets Core 运行时,因此无需再购买其他任何东西。现在购买的许可证从发布当天起即可使用。.NET 版本 sgcIndustrial .NET 在价格页面单独销售。

已经是客户了吗?这六个组件也包含在 sgcWebSockets Enterprise(Delphi 和 .NET)和 All-Access 中。

了解 sgcIndustrial 查看价格

链接

有问题或反馈?联系我们。您将收到编写这些代码的人的回复。