Modbus TCP and RTU Client
Read and write the coils and registers of PLCs, energy meters and drives from Delphi, C++Builder and .NET, over TCP/IP or over an RS-232 or RS-485 serial line.
New
Read and write the coils and registers of PLCs, energy meters and drives from Delphi, C++Builder and .NET, over TCP/IP or over an RS-232 or RS-485 serial line.
New
Two clients with the same methods: one connects to a Modbus TCP device or gateway, the other is a Modbus RTU master on a serial line.
TsgcModbusTCPClientTsgcModbusRTUClient
Modbus Application Protocol V1.1b3, Modbus TCP and Modbus RTU
TCP: every platform of sgcWebSockets. RTU: Windows, Linux and macOS
Included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, or as the standalone sgcIndustrial pack
Set Host and UnitId, set Active to True and call the methods. Each request blocks until the matching response arrives, and raises an exception when the device reports an error or does not answer.
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.OnConnect := OnModbusConnect;
FClient.OnError := OnModbusError;
FClient.Active := True;
end;
procedure TForm1.OnModbusConnect(Sender: TObject);
begin
Memo1.Lines.Add('Connected');
end;
procedure TForm1.ReadValues;
var
vRegisters: TsgcModbusRegisters;
vTemperature: Single;
begin
try
vRegisters := FClient.ReadHoldingRegisters(0, 10);
FClient.WriteSingleCoil(10, True);
// 32-bit float stored low word first by many PLCs
FClient.WordOrder := mwoCDAB;
vTemperature := FClient.ReadFloat32(300);
Memo1.Lines.Add(Format('HR0 = %d, temperature = %.1f',
[vRegisters[0], vTemperature]));
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;
procedure TForm1.OnModbusError(Sender: TObject; const aError: string);
begin
Memo1.Lines.Add('Error: ' + aError);
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->OnConnect = OnModbusConnect;
FClient->OnError = OnModbusError;
FClient->Active = true;
}
void __fastcall TForm1::OnModbusConnect(TObject *Sender)
{
Memo1->Lines->Add("Connected");
}
void __fastcall TForm1::ReadValues()
{
try
{
TsgcModbusRegisters vRegisters = FClient->ReadHoldingRegisters(0, 10);
FClient->WriteSingleCoil(10, true);
// 32-bit float stored low word first by many PLCs
FClient->WordOrder = mwoCDAB;
float vTemperature = FClient->ReadFloat32(300);
Memo1->Lines->Add("HR0 = " + IntToStr(vRegisters[0]) + ", temperature = " +
FloatToStrF(vTemperature, ffFixed, 7, 1));
}
catch (EsgcModbusException &E)
{
Memo1->Lines->Add("Device exception " + IntToStr(E.ExceptionCode));
}
catch (EsgcModbusTimeout &E)
{
Memo1->Lines->Add("No response");
}
}
void __fastcall TForm1::OnModbusError(TObject *Sender, const String aError)
{
Memo1->Lines->Add("Error: " + aError);
}
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.OnConnect += OnModbusConnect;
FClient.OnError += OnModbusError;
FClient.Active = true;
}
void OnModbusConnect(object Sender, EventArgs e)
{
Console.WriteLine("Connected");
}
public void ReadValues()
{
try
{
ushort[] vRegisters = FClient.ReadHoldingRegisters(0, 10);
FClient.WriteSingleCoil(10, true);
// 32-bit float stored low word first by many PLCs
FClient.WordOrder = TsgcModbusWordOrder.mwoCDAB;
float vTemperature = FClient.ReadFloat32(300);
Console.WriteLine($"HR0 = {vRegisters[0]}, temperature = {vTemperature:F1}");
}
catch (EsgcModbusException E)
{
Console.WriteLine("Device exception " + E.ExceptionCode);
}
catch (EsgcModbusTimeout)
{
Console.WriteLine("No response");
}
}
void OnModbusError(object Sender, string aError)
{
Console.WriteLine("Error: " + aError);
}
}
The framing, timing and error handling of Modbus are done by the component, so your code only deals with addresses and values.
01 to 06, 15, 16, 22 (mask write), 23 (read/write multiple registers) and 43/14 (device identification, with paging). The RTU client adds 07 (read exception status) and 08 (diagnostics).
ReadInt32, ReadUInt32, ReadFloat32, ReadString and their write twins, plus reads from input registers. WordOrder selects ABCD, DCBA, BADC or CDAB to match the device.
Call the methods from any thread: the requests are serialized and every response is matched by its transaction id. Timeout applies to each attempt and Retries adds more attempts.
A Modbus exception reply raises EsgcModbusException with the exception and function codes, no answer raises EsgcModbusTimeout, and every other problem raises EsgcModbusError. Quantities out of the specification are rejected before anything is sent.
The TCP client supports TLS, Proxy and WatchDog for automatic reconnection. A request that is waiting when the connection drops raises at once, without waiting for the timeout.
Every method has an overload with a leading unit id, so one TCP connection reaches all the devices behind a Modbus TCP to RTU gateway without changing UnitId.
Open a TsgcSerialPort, link it with SerialPort and set the slave address in UnitId. The client builds the RTU frame with its CRC16 and waits for the slave.
procedure TForm1.ReadSlave;
var
vRegisters: TsgcModbusRegisters;
begin
FPort := TsgcSerialPort.Create(Self);
FPort.Port := 'COM4';
FPort.BaudRate := 19200;
FPort.Parity := spEven;
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;
void __fastcall TForm1::ReadSlave()
{
FPort = new TsgcSerialPort(this);
FPort->Port = "COM4";
FPort->BaudRate = 19200;
FPort->Parity = spEven;
FPort->Open();
FRTU = new TsgcModbusRTUClient(this);
FRTU->SerialPort = FPort;
FRTU->UnitId = 17;
FRTU->Timeout = 500;
FRTU->Retries = 2;
TsgcModbusRegisters vRegisters = FRTU->ReadHoldingRegisters(107, 3);
Memo1->Lines->Add("Register 107 = " + IntToStr(vRegisters[0]));
// unit id 0 = broadcast: every slave executes the write, none answers
FRTU->WriteSingleRegister(0, 1, 100);
}
using System;
using esegece.sgcWebSockets;
class RtuMaster
{
TsgcSerialPort FPort = new TsgcSerialPort();
TsgcModbusRTUClient FRTU = new TsgcModbusRTUClient();
public void ReadSlave()
{
FPort.Port = "COM4";
FPort.BaudRate = 19200;
FPort.Parity = TsgcSerialParity.spEven;
FPort.Open();
FRTU.SerialPort = FPort;
FRTU.UnitId = 17;
FRTU.Timeout = 500;
FRTU.Retries = 2;
ushort[] vRegisters = FRTU.ReadHoldingRegisters(107, 3);
Console.WriteLine("Register 107 = " + vRegisters[0]);
// unit id 0 = broadcast: every slave executes the write, none answers
FRTU.WriteSingleRegister(0, 1, 100);
}
}
TurnaroundDelay pause
Authoritative sources for the protocol this component implements.
The methods take the protocol address, which starts at 0. The register that many manuals document as 40001 is holding register 0, so call ReadHoldingRegisters(0, 1).
Call ReadFloat32 with the address of the first of its two registers. If the value looks wrong, the device stores the bytes in another order: set WordOrder to the order the device uses. Many PLCs store the low word first, which is mwoCDAB.
Each attempt waits Timeout milliseconds. After Retries + 1 attempts without a valid answer the request raises EsgcModbusTimeout, with the function code, the unit id and the number of attempts in the message.
No. Open the TsgcSerialPort yourself and leave its OnData event empty, because the client reads the replies with Read. A request raises EsgcModbusError when the port is not assigned, not open or has OnData assigned.
It is included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, as part of the sgcIndustrial pack. In Delphi, add sgcIndustrial to the uses clause.
Deep-link to the component reference, open the demo project and read the technical document.
| Online Help: TsgcModbusTCPClient Full property, method and event reference for the Modbus TCP client. | Open | |
| Online Help: TsgcModbusRTUClient Full property, method and event reference for the Modbus RTU client. | Open | |
| Demo Project: Industrial\02.Modbus_TCP_Client A Modbus TCP client for Delphi, C++Builder and .NET. It ships inside the sgcWebSockets package. | Open | |
| Technical Document (PDF) Features, quick start, code samples and primary-source references for this component only. | Open | |
| User Manual (PDF) Comprehensive manual covering every component in the library. | Open |