New

Delphi Modbus TCP and RTU: Client and Server Components

Native Modbus TCP and Modbus RTU components for Delphi and C++Builder. Poll PLCs, drives, energy meters and gateways, or publish your own data as a Modbus server, with typed Float32, Int32 and string helpers in any word order.

Included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, or as the standalone sgcIndustrial pack.

Two clients, two servers, one Modbus API

Modbus TCP and Modbus RTU masters and slaves as non-visual components, written in Pascal and compiled into your application.

A Delphi Modbus library lets a VCL, FMX, service or console application talk to the devices found on every factory floor: PLCs, frequency drives, energy meters, temperature controllers and protocol gateways. sgcWebSockets ships it as four components: TsgcModbusTCPClient and TsgcModbusRTUClient poll devices, while TsgcModbusTCPServer and TsgcModbusRTUServer expose your own data to SCADA systems, HMIs and any other Modbus master.

Both clients descend from TsgcModbusClient_Base, so the code that reads a register over Ethernet reads it over RS-485 too: you swap the component, not the calls. Each call blocks until the answer arrives or Timeout expires, returns the values as Delphi arrays and raises a typed exception when the device reports an error. One uses sgcIndustrial; line brings in every class.

Component classes

TsgcModbusTCPClient, TsgcModbusRTUClient, TsgcModbusTCPServer, TsgcModbusRTUServer, TsgcModbusDataModel

Transports

Modbus TCP on port 502 with optional TLS and proxy; Modbus RTU over RS-232 and RS-485 through TsgcSerialPort

Function codes

01 to 08, 15, 16, 22, 23 and 43/14 (read device identification)

Platforms

Delphi 7 to Delphi 13 and C++Builder; Windows, Linux and macOS

Every common Modbus function, one method each

The client checks quantities against the specification before anything is sent; the servers answer every code in this table.

FCFunctionClient method
01Read CoilsReadCoils
02Read Discrete InputsReadDiscreteInputs
03Read Holding RegistersReadHoldingRegisters, ReadInt32, ReadUInt32, ReadFloat32, ReadString
04Read Input RegistersReadInputRegisters, ReadInputInt32, ReadInputUInt32, ReadInputFloat32
05Write Single CoilWriteSingleCoil
06Write Single RegisterWriteSingleRegister
07Read Exception Status (serial line)ReadExceptionStatus on the RTU client
08Diagnostics (serial line)Diagnostics on the RTU client
15Write Multiple CoilsWriteMultipleCoils
16Write Multiple RegistersWriteMultipleRegisters, WriteInt32, WriteUInt32, WriteFloat32, WriteString
22Mask Write RegisterMaskWriteRegister
23Read/Write Multiple RegistersReadWriteMultipleRegisters
43/14Read Device IdentificationReadDeviceIdentification (basic, regular, extended and single object)

Read a PLC in a few lines of Delphi

Create the component, set the address, call a method. Every sample on this page compiles with Delphi 7 and Delphi 13.

uses
  sgcIndustrial;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Modbus := TsgcModbusTCPClient.Create(Self);
  Modbus.Host := '192.168.1.50';
  Modbus.Port := 502;
  Modbus.UnitId := 1;
  Modbus.Timeout := 2000;          // ms per attempt
  Modbus.Retries := 2;             // extra attempts after a timeout
  Modbus.WatchDog.Enabled := True; // reconnect after a network drop
  Modbus.OnConnect := ModbusConnect;
  Modbus.OnError := ModbusError;
  Modbus.Active := True;
end;

procedure TForm1.ModbusConnect(Sender: TObject);
begin
  Memo1.Lines.Add('connected');
end;

procedure TForm1.ModbusError(Sender: TObject; const aError: string);
begin
  Memo1.Lines.Add('error: ' + aError);
end;

procedure TForm1.btnReadClick(Sender: TObject);
var
  vRegisters: TsgcModbusRegisters;
  vCoils: TsgcModbusBits;
  i: Integer;
begin
  vRegisters := Modbus.ReadHoldingRegisters(0, 10); // FC 03
  for i := 0 to Length(vRegisters) - 1 do
    Memo1.Lines.Add(Format('HR%d = %d', [i, vRegisters[i]]));

  vCoils := Modbus.ReadCoils(0, 8);                 // FC 01
  if vCoils[0] then
    Memo1.Lines.Add('coil 0 is on');

  Modbus.WriteSingleRegister(100, 1234);            // FC 06
  Modbus.WriteSingleCoil(5, True);                  // FC 05
end;
procedure TForm1.btnTypedClick(Sender: TObject);
var
  vTemperature: Single;
  vCounter: Integer;
  vName: TsgcModbusAnsiString;
begin
  Modbus.WordOrder := mwoCDAB;              // low word first
  vTemperature := Modbus.ReadFloat32(200);  // 2 holding registers
  vCounter := Modbus.ReadInt32(202);
  vName := Modbus.ReadString(300, 8);       // 8 registers, 16 characters
  Memo1.Lines.Add(Format('%s: %.1f C, %d cycles',
    [string(vName), vTemperature, vCounter]));

  Modbus.WriteFloat32(210, 21.5);
  Modbus.WriteUInt32(212, 3000000000);

  // explicit unit id, for a gateway with several devices behind it
  Memo1.Lines.Add(FloatToStr(Modbus.ReadInputFloat32(7, 0))); // unit 7, FC 04

  try
    Modbus.ReadHoldingRegisters(9000, 4);
  except
    on E: EsgcModbusException do // the device answered with an exception
      Memo1.Lines.Add(Format('exception %d, function %d',
        [E.ExceptionCode, E.FunctionCode]));
    on E: EsgcModbusTimeout do   // no answer after Retries + 1 attempts
      Memo1.Lines.Add(E.Message);
  end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
  Serial := TsgcSerialPort.Create(Self);
  Serial.Port := 'COM3';          // '/dev/ttyUSB0' on Linux
  Serial.BaudRate := 19200;
  Serial.Parity := spEven;        // 8E1, the Modbus RTU default
  Serial.RtsControl := srcToggle; // RS-485: RTS switches the transmitter
  Serial.Active := True;

  RTU := TsgcModbusRTUClient.Create(Self);
  RTU.SerialPort := Serial;
  RTU.UnitId := 17;               // slave address
  RTU.Timeout := 500;
  RTU.Retries := 1;
end;

procedure TForm1.btnPollClick(Sender: TObject);
var
  vValues: TsgcModbusRegisters;
begin
  vValues := RTU.ReadInputRegisters(0, 4);                      // FC 04
  Memo1.Lines.Add(Format('IR0 = %d', [vValues[0]]));
  Memo1.Lines.Add(Format('status = %d', [RTU.ReadExceptionStatus])); // FC 07
  RTU.WriteSingleRegister(0, 10, 500); // unit 0: broadcast to every slave, no reply
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
  Server := TsgcModbusTCPServer.Create(Self);
  Server.Port := 502;
  Server.UnitId := 0;                          // answer every unit id
  Server.DataModel.HoldingRegisterCount := 1000;
  Server.DataModel.SetHoldingRegister(0, 42);
  Server.DataModel.SetCoil(0, True);
  Server.DataModel.VendorName := 'My Company'; // FC 43/14 identification
  Server.DataModel.ProductCode := 'GW-100';
  Server.OnReadRequest := ServerReadRequest;
  Server.OnWriteRequest := ServerWriteRequest;
  Server.Active := True;
end;

// runs in the connection thread, before the table is read
procedure TForm1.ServerReadRequest(Sender: TObject; aUnitId, aFunctionCode: Byte;
  aAddress, aCount: Word; var aExceptionCode: Byte);
begin
  if aFunctionCode = CS_MODBUS_FC_READ_INPUT_REGISTERS then
    Server.DataModel.SetInputRegister(0, Random(1000)); // fresh value
end;

// registers 0..9 are read only
procedure TForm1.ServerWriteRequest(Sender: TObject; aUnitId, aFunctionCode: Byte;
  aAddress, aCount: Word; var aBits: TsgcModbusBits;
  var aRegisters: TsgcModbusRegisters; var aExceptionCode: Byte);
begin
  if (Length(aRegisters) > 0) and (aAddress < 10) then
    aExceptionCode := CS_MODBUS_EX_ILLEGAL_DATA_ADDRESS;
end;

A Modbus master you can call from any thread

Blocking calls, typed values and clear errors, on TCP and on the serial line.

Typed 32 bit values and strings

ReadFloat32, ReadInt32, ReadUInt32 and their write and input register twins combine two registers into one value. WordOrder covers the four layouts devices use: mwoABCD (big endian, the Modbus default), mwoCDAB, mwoBADC and mwoDCBA. ReadString and WriteString pack two characters per register.

Thread-safe blocking calls

One request runs at a time per client, guarded by a lock that covers all its retries, so several threads can share one connection. On TCP the answer is matched by the receive thread, so a call from the main thread cannot deadlock.

Timeouts and retries

Timeout is the wait per attempt and Retries the extra attempts. A TCP retry uses a new transaction id, and late or duplicate answers are dropped instead of being mistaken for the next reply.

Typed exceptions

EsgcModbusException carries the device's ExceptionCode and FunctionCode, EsgcModbusTimeout reports a missing answer, and EsgcModbusError covers everything else, from a closed connection to an RTU frame with a bad CRC.

Unit id per call

Every method also has an overload with a leading unit id, so one connection to a gateway reaches all the devices behind it. UnitId is the default for the calls without it.

TLS, proxy and reconnect on TCP

TLS and TLSOptions wrap the Modbus TCP stream in TLS, Proxy reaches a device through an HTTP or SOCKS proxy, and WatchDog reconnects after a network drop. All three come from the sgcWebSockets TCP client the component is built on.

RTU framing done right

The RTU client waits for the 3.5 character silence before it sends, reads the reply by its expected length (USB adapters deliver bytes in bursts), checks the CRC of every frame and ignores frames from other slave addresses.

RS-485 and broadcast

Set RtsControl := srcToggle on the serial port and RTS switches the RS-485 transmitter on every write, through the driver on Windows and the kernel RS-485 mode on Linux. Unit id 0 sends a broadcast write to every slave and waits TurnaroundDelay instead of an answer.

Events where you want them

OnConnect, OnDisconnect and OnError are delivered through NotifyEvents: queued to the main thread by default, synchronized, or raised directly in the receive thread.

Modbus TCP and RTU servers with a live data model

Turn a Delphi application into a Modbus slave: a gateway that exposes values from a database or a REST API, a device simulator for testing HMI screens, or the Modbus face of your own controller. Each server owns a TsgcModbusDataModel with the four Modbus tables (coils, discrete inputs, holding registers and input registers, 10,000 entries each by default and up to 65,536), the device identification strings answered on FC 43/14 and the exception status answered on FC 07.

The data model is thread safe: one lock guards all the tables, so your code can update values while clients read them. Two hooks put your code in the request path. OnReadRequest runs before a table is read, so it can refresh the values just in time or refuse the request with an exception code. OnWriteRequest receives the values before they are stored, so it can validate them, change them or reject the write and leave the tables untouched.

TsgcModbusTCPServer

Many concurrent connections, each with its own thread. Requests that arrive together in one packet are answered in order, a request split over several packets is reassembled, and a malformed header closes that connection and fires OnError. UnitId = 0 answers any unit id; another value answers only that one. Bindings choose the interfaces and ports, and OnClientConnect and OnClientDisconnect report the peers.

TsgcModbusRTUServer

Listens on a TsgcSerialPort as slave UnitId (1 to 247). It frames requests by their expected length and the 3.5 character silence, ignores frames with a bad CRC or another address, and executes broadcast writes from unit id 0 without answering, as the serial line specification requires.

Hooks in the connection thread

The server events run in the connection thread (TCP) or the frame thread (RTU) and return their result synchronously. Keep them short, and call the data model methods freely: the hooks run with no lock held.

Tested against an independent Modbus stack

The Modbus client and server are tested on the wire against pymodbus, an independent open-source implementation, over Modbus TCP: function codes 01 to 06, 15, 16, 22, 23 and 43/14, exception replies, Float32 values and device identification. The typed helpers are checked against known byte vectors in all four word orders. The Delphi components are also tested against the sgcWebSockets .NET Modbus components in both directions, client against server, with 35 out of 35 checks passing each way.

The serial port is tested on a real COM port on Windows and on pseudo terminals on Linux, including closing the port while a read is waiting. The Modbus RTU client and server are tested against simulated slaves and masters: split frames, CRC errors, other slave addresses and broadcasts. The same code compiles for macOS.

Delphi Modbus questions

Create a TsgcModbusTCPClient, set Host, Port (502 by default) and UnitId, set Active := True and call ReadHoldingRegisters(Address, Count). It returns a TsgcModbusRegisters array with one Word per register. Addresses are zero based, as they travel on the wire.

Call ReadFloat32, ReadInt32 or ReadUInt32 with the address of the first of the two registers, or the ReadInput... variants for input registers. If the value looks wrong, the device uses another word order: set WordOrder to mwoCDAB, mwoBADC or mwoDCBA instead of the default mwoABCD.

Yes. Open a TsgcSerialPort on the adapter and assign it to the SerialPort property of TsgcModbusRTUClient or TsgcModbusRTUServer. Adapters with automatic direction control need nothing else. For adapters that switch the transmitter with RTS, set RtsControl := srcToggle: Windows uses the driver's RTS toggle mode and Linux the kernel RS-485 mode.

Yes. The client runs one transaction at a time and holds a lock for the whole request, retries included, so calls from several threads queue up and each one gets its own answer. Calls from the main thread do not deadlock: on TCP the reply is received by a separate thread.

Drop a TsgcModbusTCPServer (or TsgcModbusRTUServer with a serial port), fill its DataModel with SetHoldingRegister, SetCoil and the other setters, and set Active := True. Use OnReadRequest and OnWriteRequest to compute values on demand or to reject writes with a Modbus exception code.

Delphi 7 to Delphi 13 and C++Builder, on Windows (32 and 64 bit), Linux 64 bit and macOS. The serial port, and with it Modbus RTU, is not available on Android and iOS.

The Modbus and serial port components are included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, or as the standalone sgcIndustrial pack.

More industrial components in sgcWebSockets

Industrial components

Serial port, Modbus and the OPC UA client in one section, with the full component reference.

Modbus client reference

Properties, methods and events of TsgcModbusTCPClient and TsgcModbusRTUClient.

Modbus server reference

TsgcModbusTCPServer, TsgcModbusRTUServer and the TsgcModbusDataModel hooks.

Delphi serial port

TsgcSerialPort for Windows, Linux and macOS: the transport of Modbus RTU, and a serial component of its own.

Delphi MQTT client

Publish Modbus values to an MQTT broker: the usual way to bring factory data to the cloud.

Also for C# and .NET

The same Modbus clients and servers, with the same class names, for .NET 8, 9, 10 and .NET Standard 2.0.

Best value: All-AccessEvery eSeGeCe product, Premium Support included, from €1,059/year.
See All-Access pricing

Talk to your first PLC from Delphi

Included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access, or as the standalone sgcIndustrial pack.