Delphi, C++Builder i .NET napędzają dużą część oprogramowania na hali produkcyjnej: panele operatorskie, rejestratory danych, stanowiska testowe, konektory MES i narzędzia do konfiguracji maszyn. Mimo to protokoły, którymi te aplikacje muszą mówić, czyli Modbus, OPC UA i zwykłe łącza szeregowe, rzadko były dostępne jako natywne komponenty. Zwykle odpowiedzią był most ActiveX, ręcznie opakowana biblioteka C albo osobna brama między Twoim kodem a sterownikiem PLC.
sgcIndustrial zamyka tę lukę. Sześć komponentów niewizualnych łączy Twoje aplikacje ze sterownikami PLC, serwerami SCADA, licznikami energii, napędami i urządzeniami szeregowymi, w tym samym stylu komponentów co reszta sgcWebSockets, z pełnym kodem źródłowym, dla Delphi, C++Builder i .NET z tym samym API.
sgcIndustrial w jedną minutę: Modbus, OPC UA i porty szeregowe z Delphi, C++Builder i .NET. Także na YouTube.
Sześć komponentów dla poziomu polowego
Komponenty są zarejestrowane na stronie palety SGC Industrial. Klasy .NET mają te same nazwy.
| Komponent | Co robi |
|---|---|
| TsgcSerialPort | Otwiera porty RS-232 i RS-485 w systemach Windows, Linux i macOS, zapisuje dane i odbiera je w zdarzeniu lub przez odczyty blokujące. Jest też transportem komponentów Modbus RTU. |
| TsgcModbusTCPClient TsgcModbusRTUClient | Odczyt i zapis cewek oraz rejestrów przez TCP/IP lub łącze szeregowe, z typowanymi funkcjami pomocniczymi dla wartości 32-bitowych i łańcuchów. |
| TsgcModbusTCPServer TsgcModbusRTUServer | Zamień swoją aplikację w urządzenie Modbus, które odpowiada z bezpiecznego wątkowo TsgcModbusDataModel, ze zdarzeniami do sprawdzania każdego odczytu i zapisu. |
| TsgcOPCUAClient | Łączy się z serwerami OPC UA przez opc.tcp z podpisanymi i szyfrowanymi politykami bezpieczeństwa, przegląda przestrzeń adresową, odczytuje, zapisuje, wywołuje metody oraz subskrybuje zmiany danych i zdarzenia. |
Modbus TCP: odczyt i zapis sterownika PLC w kilku linijkach
Każde żądanie Modbus jest wywołaniem blokującym, które zwraca wartości albo zgłasza czytelny wyjątek, więc odczyt sterownika PLC wygląda jak odczyt zmiennej lokalnej. Komponenty same obsługują ramkowanie, identyfikatory transakcji, kontrolę CRC, limity czasu i ponowienia.
- Kody funkcji 01 do 08, 15, 16, 22, 23 i 43/14: cewki, wejścia dyskretne, rejestry przechowujące i wejściowe, zapisy pojedyncze i wielokrotne, zapis z maską, odczyt/zapis wielu rejestrów, identyfikacja urządzenia, a na łączach szeregowych także status wyjątku i diagnostyka.
- Wartości typowane: liczby całkowite 32-bitowe, zmiennoprzecinkowe i łańcuchy, w czterech kolejnościach słów, których używają producenci sterowników PLC (
mwoABCD,mwoDCBA,mwoBADC,mwoCDAB). - Czytelne błędy: wyjątek urządzenia zgłasza
EsgcModbusExceptionz jego kodem wyjątku, a urządzenie, które nie odpowiada, zgłaszaEsgcModbusTimeoutpo skonfigurowanych ponowieniach. - TLS, proxy i automatyczne ponowne połączenie dla klienta Modbus TCP.
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");
}
}
}
Serwer Modbus z modelem danych
TsgcModbusTCPServer i TsgcModbusRTUServer zamieniają Twoją aplikację w urządzenie Modbus. Wartości są przechowywane w bezpiecznym wątkowo TsgcModbusDataModel z cewkami, wejściami dyskretnymi, rejestrami przechowującymi i wejściowymi oraz łańcuchami identyfikacji urządzenia. OnReadRequest pozwala odświeżyć wartość bieżącą tuż przed odczytem przez klienta, a OnWriteRequest pozwala sprawdzić każdy zapis i odrzucić go kodem wyjątku Modbus. Dzięki temu serwer dobrze nadaje się do symulatorów, bram i stanowisk testowych.
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 i Modbus RTU
TsgcSerialPort otwiera porty RS-232 i RS-485 w systemach Windows, Linux i macOS. ListPorts zwraca porty komputera, a RtsControl := srcToggle włącza sterownik RS-485 na czas wysyłania, dla magistral półdupleksowych. Ten sam port jest transportem TsgcModbusRTUClient i TsgcModbusRTUServer, które dodają ramkowanie RTU i kontrolę CRC. Identyfikator jednostki 0 wysyła rozgłoszenie, które wykonują wszystkie urządzenia podrzędne, nie odpowiadając.
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: bezpieczne połączenia, odczyt i subskrypcja
TsgcOPCUAClient mówi binarnym protokołem OPC UA przez opc.tcp. Bezpieczeństwo konfiguruje się dwiema właściwościami, a tożsamość użytkownika trzecią:
- Sześć polityk bezpieczeństwa: None, Basic128Rsa15, Basic256, Basic256Sha256, Aes128_Sha256_RsaOaep i Aes256_Sha256_RsaPss.
- Trzy tryby bezpieczeństwa: None, Sign i SignAndEncrypt.
- Trzy sposoby logowania: anonimowe, nazwa użytkownika z hasłem oraz certyfikat użytkownika X.509.
- Certyfikaty: certyfikat instancji aplikacji jest tworzony i zapisywany przy pierwszym uruchomieniu, a
OnValidateServerCertificatedecyduje, którym certyfikatom serwera ufasz.
Przykład łączy się z Basic256Sha256 i SignAndEncrypt, loguje się nazwą użytkownika, odczytuje wartość i subskrybuje ją ze strefą nieczułości, więc serwer zgłasza tylko zmiany większe niż 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);
}
}
Przeglądanie, zapis i wywołanie
Browse wyświetla referencje węzła i samo podąża za punktami kontynuacji, TranslateBrowsePath zamienia ścieżkę taką jak /2:Line1/2:Speed na identyfikator węzła, WriteValue najpierw odczytuje typ danych węzła i zapisuje z jego użyciem, a Call uruchamia metodę na serwerze i zwraca jej argumenty wyjściowe.
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;
Subskrypcje i zdarzenia
Subskrypcje dostarczają zmiany danych do OnDataChange, z interwałem próbkowania, rozmiarem kolejki oraz bezwzględną lub procentową strefą nieczułości dla każdego monitorowanego elementu. Monitorowane elementy zdarzeń dostarczają alarmy i warunki do OnEvent, z polami wybranymi w kolejności, w jakiej je wybierzesz.
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;
Ponowne połączenie WatchDog z przywróceniem subskrypcji
Sieci na hali produkcyjnej zawodzą. Po włączeniu WatchDog klient sam łączy się ponownie po utracie połączenia i przywraca to, co miałeś: reaktywuje tę samą sesję na nowym kanale bezpiecznym i prosi serwer o ponowne opublikowanie brakujących powiadomień, albo otwiera nową sesję i przenosi do niej Twoje subskrypcje, albo tworzy je ponownie z listy klienta. OnReconnect informuje, które z tych zdarzyło się. Automatyczne ponowne połączenie jest dostępne w Delphi i .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;
Przetestowane z innymi implementacjami
Stos protokołów jest tak dobry, jak jego współpraca z innymi, dlatego sgcIndustrial przetestowano z implementacjami, których nie napisaliśmy:
- OPC UA: serwer referencyjny OPC Foundation, Eclipse Milo, node-opcua, open62541 i asyncua, ze wszystkimi politykami i trybami bezpieczeństwa, które oferuje każdy serwer, uwierzytelnianiem anonimowym, nazwą użytkownika i certyfikatem, subskrypcjami, zdarzeniami i ponownym połączeniem.
- Modbus: modpoll, diagslave, libmodbus, modbus_tk i pymodbus, jako klienci i jako serwery, przez TCP i przez łącza szeregowe RTU.
- Delphi i .NET: komponenty Delphi i .NET przetestowano względem siebie, 35 z 35 testów krzyżowych zakończyło się powodzeniem.
Platformy
- Delphi 7 do 13 i C++Builder: Windows Win32 i Win64 oraz Linux64.
- .NET: .NET 8, .NET 9, .NET 10 i .NET Standard 2.0, w pakiecie NuGet
esegece.sgcIndustrial. - Porty szeregowe: Windows, Linux i macOS.
Każdy przykład kodu w tym wpisie został skompilowany z aktualnymi źródłami: przykłady Delphi w Delphi 7 i Delphi 13 (Win32 i Win64), przykłady C++Builder w C++Builder 13, a przykłady C# w .NET 8.
Dostępność i cennik
Od dziś, 27 listopada 2026, sgcIndustrial jest w sprzedaży jako samodzielny pakiet, od €249 dla jednego programisty, a także z licencjami Team i Site. Każda licencja zawiera pełny kod źródłowy i 1 rok aktualizacji, a środowisko uruchomieniowe sgcWebSockets Core jest w zestawie, więc nie musisz kupować niczego więcej. Wersja .NET, sgcIndustrial .NET, jest sprzedawana osobno na stronie cennika.
Jesteś już klientem? Wszystkie sześć komponentów jest też w pakiecie sgcWebSockets Enterprise, dla Delphi i dla .NET, oraz w All-Access.
Poznaj sgcIndustrial Zobacz cennik
Linki
- sgcIndustrial: samodzielny pakiet, zawartość zestawu i platformy
- Cennik sgcIndustrial: licencje Single, Team i Site
- Komponenty przemysłowe: przegląd i przykłady kodu w Delphi, C++Builder i C#
- Dokumentacja referencyjna: Serial Port, Modbus Client, Modbus Server i OPC UA Client, każda także jako PDF
- TsgcOPCUAClient w pomocy online
Pytania lub uwagi? Skontaktuj się z nami. Odpowiedź otrzymasz od osób, które napisały ten kod.
