Modbus TCP and RTU Server

Turn a Delphi, C++Builder or .NET application into a Modbus device. Answer SCADA systems, HMIs and Modbus clients over TCP/IP or a serial line, from a thread-safe data model.

New

TsgcModbusTCPServer and TsgcModbusRTUServer

Two servers that answer from the same TsgcModbusDataModel: one listens on TCP port 502, the other is a Modbus RTU slave on a serial line.

Component classes

TsgcModbusTCPServer
TsgcModbusRTUServer
TsgcModbusDataModel

Protocol

Modbus Application Protocol V1.1b3, Modbus TCP and Modbus RTU

Platforms

TCP: every platform of sgcWebSockets. RTU: Windows, Linux and macOS

Edition

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

Start a Modbus TCP server

Fill the data model, assign the events and set Active to True. OnReadRequest refreshes a live value before it is read, and OnWriteRequest rejects setpoints out of range.

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

What's inside

A Modbus device in a component: the server parses the requests, checks them and answers from the data model.

Function codes

01 to 08 (08 with sub-function 0), 15, 16, 22 (mask write, applied atomically), 23 (read/write multiple registers) and 43/14 (device identification, paged with More Follows).

Data model

Coils, discrete inputs, holding registers and input registers, 10000 of each by default and up to 65536. Every Get and Set method is thread-safe, and a request beyond a table gets exception 02.

Read and write events

OnReadRequest fires before the data is read, to load live values. OnWriteRequest fires before the data is written, to change the values or reject the request with a Modbus exception code.

Connections

Each TCP connection is served on its own, and several requests in one packet are answered in order. A malformed header fires OnError and closes that connection. OnClientConnect and OnClientDisconnect report the peers.

Unit ids

By default the TCP server answers every unit id. Set UnitId to answer one id only: the requests for other ids get no response and the connection stays open, as a gateway does with a missing device.

Device identification

VendorName, ProductCode and MajorMinorRevision are the basic objects, and VendorUrl, ProductName and ModelName the regular ones, answered to function 43/14.

An RTU slave on RS-232 and RS-485

Link a TsgcSerialPort and set the slave address in UnitId (1 to 247). The server opens the port when it starts and answers from its data model.

procedure TForm1.StartRTUServer;
begin
  FPort := TsgcSerialPort.Create(Self);
  FPort.Port := 'COM5';
  FPort.BaudRate := 19200;
  FPort.Parity := spEven;

  FRTUServer := TsgcModbusRTUServer.Create(Self);
  FRTUServer.SerialPort := FPort;
  FRTUServer.UnitId := 17;
  FRTUServer.DataModel.SetInputRegister(0, 215);
  // the server opens the port when it is closed
  FRTUServer.Active := True;
end;
void __fastcall TForm1::StartRTUServer()
{
  FPort = new TsgcSerialPort(this);
  FPort->Port = "COM5";
  FPort->BaudRate = 19200;
  FPort->Parity = spEven;

  FRTUServer = new TsgcModbusRTUServer(this);
  FRTUServer->SerialPort = FPort;
  FRTUServer->UnitId = 17;
  FRTUServer->DataModel->SetInputRegister(0, 215);
  // the server opens the port when it is closed
  FRTUServer->Active = true;
}
using System;
using esegece.sgcWebSockets;

class RtuSlave
{
    TsgcSerialPort FPort = new TsgcSerialPort();
    TsgcModbusRTUServer FRTUServer = new TsgcModbusRTUServer();

    public void StartRTUServer()
    {
        FPort.Port = "COM5";
        FPort.BaudRate = 19200;
        FPort.Parity = TsgcSerialParity.spEven;

        FRTUServer.SerialPort = FPort;
        FRTUServer.UnitId = 17;
        FRTUServer.DataModel.SetInputRegister(0, 215);
        // the server opens the port when it is closed
        FRTUServer.Active = true;
    }
}

Specifications & references

Authoritative sources for the protocol this component implements.

Modbus server questions

In the thread that serves the TCP connection, or in the frame thread of the RTU server. They are never synchronized with the main thread, because the server needs the answer of the handler to build the response. Do not access the user interface directly from them, and do not set Active to False from an event handler of the TCP server.

Write the values into the data model whenever they change, or load them in OnReadRequest, which fires before every read with the function code, the address and the count. The data model methods can be called from the event, and from any other thread.

Set aExceptionCode in OnWriteRequest, for example to CS_MODBUS_EX_ILLEGAL_DATA_VALUE (03). The client receives that Modbus exception and the tables are left untouched. The event can also change the values before they are written.

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.

Documentation & Demos

Deep-link to the component reference, open the demo project and read the technical document.

Online Help: TsgcModbusTCPServer Full property, method and event reference for the Modbus TCP server.
Online Help: TsgcModbusRTUServer Full property, method and event reference for the Modbus RTU server.
Online Help: TsgcModbusDataModel The tables, the device identification objects and the events of the data model.
Demo Project: Industrial\03.Modbus_TCP_Server A Modbus TCP server for Delphi, C++Builder and .NET. It ships inside the sgcWebSockets package.
Technical Document (PDF) Features, quick start, code samples and primary-source references for this component only.
User Manual (PDF) Comprehensive manual covering every component in the library.
Best value: All-AccessEvery eSeGeCe product, Premium Support included, from €1,059/year.
See All-Access pricing

Included in sgcWebSockets Enterprise

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