sgcWebSockets · Technical Document

Modbus Server

TsgcModbusTCPServer and TsgcModbusRTUServer: Modbus TCP and Modbus RTU server for Delphi, C++Builder and .NET, answering from a thread-safe data model.

Overview

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. The two servers answer from the same TsgcModbusDataModel: TsgcModbusTCPServer listens on TCP port 502, and TsgcModbusRTUServer is a Modbus RTU slave on a serial line. The server parses the requests, checks them and answers from the data model.

Availability. Included in sgcWebSockets Enterprise (Delphi and .NET) and All-Access.

At a glance

Component classes
TsgcModbusTCPServer, TsgcModbusRTUServer, TsgcModbusDataModel
Standards / spec
Modbus Application Protocol V1.1b3
Transports
TCP, RS-232, RS-485
Platforms
TCP: every sgcWebSockets platform. RTU: Windows, Linux, macOS
Frameworks
VCL, FireMonkey, .NET
Edition
Enterprise

Features

Technical specification

Standards & specsModbus Application Protocol Specification V1.1b3 · Modbus Messaging on TCP/IP Implementation Guide V1.0b · Modbus over Serial Line Specification V1.02
Component classesTsgcModbusTCPServer and TsgcModbusRTUServer (unit sgcModbus_Server), TsgcModbusDataModel (unit sgcModbus_DataModel); in Delphi add sgcIndustrial to the uses clause. In .NET the classes have the same names in the namespace esegece.sgcWebSockets.
Function codes01 to 08 (08 with sub-function 0), 15, 16, 22, 23 and 43/14
Data tablesCoils, discrete inputs, holding registers and input registers, 10000 of each by default and up to 65536
Default TCP port502
RTU slave address1 to 247; broadcast writes (address 0) are executed and never answered
FrameworksVCL, FireMonkey, .NET
PlatformsTCP: every platform of sgcWebSockets. RTU: Windows, Linux and macOS

Main properties

The principal published properties used to configure and drive the component. Consult the online help for the full list.

ActiveStarts or stops the server. The RTU server opens the serial port when it starts.
DataModelThe TsgcModbusDataModel the server answers from.
PortTCP server: listening port, 502 by default.
BindingsTCP server: the addresses and ports to listen on.
UnitIdTCP server: answer one unit id only (0 answers every id). RTU server: the slave address, 1 to 247.
SerialPortRTU server: the TsgcSerialPort used as transport.
DataModel.CoilCountSize of the coil table. DiscreteInputCount, HoldingRegisterCount and InputRegisterCount size the other three tables.
DataModel.VendorNameBasic identification object, with ProductCode and MajorMinorRevision.
DataModel.VendorUrlRegular identification object, with ProductName and ModelName.

Main methods

The principal public methods exposed by the component.

GetCoil() / SetCoil()Reads or writes one coil of the data model. GetCoils and SetCoils work on a range.
GetDiscreteInput() / SetDiscreteInput()Reads or writes one discrete input. GetDiscreteInputs and SetDiscreteInputs work on a range.
GetHoldingRegister() / SetHoldingRegister()Reads or writes one holding register. GetHoldingRegisters and SetHoldingRegisters work on a range.
GetInputRegister() / SetInputRegister()Reads or writes one input register. GetInputRegisters and SetInputRegisters work on a range.
ProcessRequest()Answers a Modbus request PDU from the data model.
Assign()Copies the tables and the identification objects of another data model.

Events

The published events of the component.

OnReadRequestFires before the data is read, with the unit id, the function code, the address and the count. Load live values here.
OnWriteRequestFires before the data is written. Change the values, or set aExceptionCode to reject the request.
OnErrorAn error happened, for example a malformed header on a TCP connection.
OnClientConnectTCP server: a client has connected.
OnClientDisconnectTCP server: a client has disconnected.

Good to know

Quick Start

Fill the data model, assign the events and set Active to True. The snippet that follows shows the typical Start a Modbus TCP server configuration, the same compiled sample as the component page.

About this scenario. OnReadRequest refreshes a live value before it is read, and OnWriteRequest rejects setpoints out of range.

Delphi (VCL / FireMonkey)

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;

C++ Builder

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

.NET (C#)

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

Common scenarios

The following scenarios use the same compiled samples as the component page. Each shows the configuration and method calls needed to drive the component through a specific real-world flow.

1 · Modbus 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.

Delphi (VCL / FireMonkey)
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;
C++ Builder
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;
}
.NET (C#)
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;
    }
}

Sources used to build this document

Every external claim links back to a primary source. The online-help references decode the canonical deep-link the company maintains for this component.

Document scope. This document covers the publicly-documented surface of the Modbus TCP and RTU server components shipped with sgcWebSockets. For full property, method and event reference consult the online help linked above.