sgcWebSockets · Technical Document

Serial Port

TsgcSerialPort: RS-232 and RS-485 serial port for Delphi, C++Builder and .NET, with event driven or blocking reads on Windows, Linux and macOS.

Overview

TsgcSerialPort opens RS-232 and RS-485 ports and USB serial adapters from Delphi, C++Builder and .NET. It configures the line, writes data and receives it in an event or with blocking reads, on Windows, Linux and macOS. A background reader thread fills a 64 KB receive buffer, and the API is the same in Delphi, C++Builder and C#. The component is also the transport of the Modbus RTU client and server.

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

At a glance

Component class
TsgcSerialPort
Standards / spec
Win32 DCB, POSIX termios, Linux RS-485
Transports
RS-232, RS-485, USB serial adapters
Platforms
Windows, Linux, macOS (not Android or iOS)
Frameworks
VCL, FireMonkey, .NET
Edition
Enterprise

Features

Technical specification

Standards & specsWindows DCB structure (serial line settings) · POSIX termios (Linux and macOS) · Linux RS-485 serial communications
Component classTsgcSerialPort (unit sgcSerial_Port; in Delphi add sgcIndustrial to the uses clause). In .NET the class is TsgcSerialPort in the namespace esegece.sgcWebSockets.
FrameworksVCL, FireMonkey, .NET
PlatformsIn Delphi and C++Builder it works on Windows (Win32 and Win64) with the Win32 communications API, and on Linux64 and macOS with POSIX termios. It is not available on Android and iOS. The .NET version is built on System.IO.Ports.
Receive buffer64 KB (CS_SERIAL_BUFFER_SIZE), filled by a background reader thread
ErrorsEsgcSerialError, with ErrorCode holding the operating system error code

Main properties

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

ActiveOpens or closes the port.
PortName of the port, such as COM3 on Windows or /dev/ttyUSB0 on Linux.
BaudRateLine speed in bits per second.
DataBitsData bits per character, 5 to 8.
ParityspNone, spOdd, spEven, spMark or spSpace.
StopBitsssOne, ssOnePointFive or ssTwo.
FlowControlsfcNone, sfcRtsCts, sfcDtrDsr or sfcXonXoff.
RtsControlsrcDisable, srcEnable, srcHandshake or srcToggle (RS-485 direction control).
ReadTimeoutRead timeout in milliseconds.
WriteTimeoutWrite timeout in milliseconds.
NotifyEventsHow the events are delivered. By default they are queued to the main thread.

Main methods

The principal public methods exposed by the component.

Open()Opens the port with the current line settings.
Close()Closes the port. Works from any thread, also from an event handler, and wakes a blocked Read.
Write()Writes a byte array and returns the number of bytes written. Can be called from any thread.
WriteString()Writes a string.
Read()Blocking read: waits for the first byte and returns when the device has been silent for the given time. Only while OnData is not assigned.
Purge()Discards the bytes waiting in the receive buffer.
SetDTR()Raises or lowers the DTR line.
SetRTS()Raises or lowers the RTS line.
ModemStatus()Returns the state of the CTS, DSR, RI and DCD lines.
BufferCount()Number of bytes waiting in the receive buffer.
ListPorts()Class method that lists the serial ports of the system in natural order.

Events

The published events of the component.

OnOpenThe port has been opened.
OnCloseThe port has been closed.
OnDataA block of bytes has been received.
OnErrorAn error happened while the port is open, for example the device was unplugged or the receive buffer is full.

Good to know

Quick Start

Set the port name and the line settings, assign the events and call Open. The snippet that follows shows the typical Open a port and receive data configuration, the same compiled sample as the component page.

About this scenario. The device is on COM3 at 19200 baud, 8 data bits, even parity and one stop bit. The sample sends an AT command, and OnData receives every block of bytes as it arrives.

Delphi (VCL / FireMonkey)

uses
  sgcIndustrial;

procedure TForm1.OpenPort;
begin
  FPort := TsgcSerialPort.Create(Self);
  FPort.Port := 'COM3';
  FPort.BaudRate := 19200;
  FPort.DataBits := 8;
  FPort.Parity := spEven;
  FPort.StopBits := ssOne;
  FPort.OnData := OnSerialData;
  FPort.OnError := OnSerialError;
  FPort.Open;
  FPort.WriteString('AT' + #13);
end;

procedure TForm1.OnSerialData(Sender: TObject; const aData: TBytes);
begin
  // queued to the main thread by default (NotifyEvents = neAsynchronous)
  Memo1.Lines.Add(IntToStr(Length(aData)) + ' bytes received');
end;

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

C++ Builder

#include "sgcIndustrial.hpp"

void __fastcall TForm1::OpenPort()
{
  FPort = new TsgcSerialPort(this);
  FPort->Port = "COM3";
  FPort->BaudRate = 19200;
  FPort->DataBits = 8;
  FPort->Parity = spEven;
  FPort->StopBits = ssOne;
  FPort->OnData = OnSerialData;
  FPort->OnError = OnSerialError;
  FPort->Open();
  FPort->WriteString("AT\r");
}

void __fastcall TForm1::OnSerialData(TObject *Sender, const TBytes aData)
{
  // queued to the main thread by default (NotifyEvents = neAsynchronous)
  Memo1->Lines->Add(IntToStr(aData.Length) + " bytes received");
}

void __fastcall TForm1::OnSerialError(TObject *Sender, const String aError)
{
  Memo1->Lines->Add("Error: " + aError);
}

.NET (C#)

using System;
using esegece.sgcWebSockets;

class SerialTerminal
{
    TsgcSerialPort FPort = new TsgcSerialPort();

    public void OpenPort()
    {
        FPort.Port = "COM3";
        FPort.BaudRate = 19200;
        FPort.DataBits = 8;
        FPort.Parity = TsgcSerialParity.spEven;
        FPort.StopBits = TsgcSerialStopBits.ssOne;
        FPort.OnData += OnSerialData;
        FPort.OnError += OnSerialError;
        FPort.Open();
        FPort.WriteString("AT\r");
    }

    void OnSerialData(object Sender, byte[] aData)
    {
        Console.WriteLine(aData.Length + " bytes received");
    }

    void OnSerialError(object Sender, string aError)
    {
        Console.WriteLine("Error: " + aError);
    }
}

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 · Request and reply

Leave OnData empty, write the command and call Read: it waits up to 1000 ms for the first byte and returns when the device has been silent for 50 ms.

Delphi (VCL / FireMonkey)
procedure TForm1.QueryDevice;
var
  vData: TBytes;
  vCount: Integer;
begin
  // OnData is not assigned: the bytes wait in the receive buffer for Read
  FPort.Purge;
  FPort.WriteString('*IDN?' + #10);
  // wait up to 1000 ms for the first byte, the reply ends after 50 ms of silence
  vCount := FPort.Read(vData, 256, 1000, 50);
  if vCount = 0 then
    Memo1.Lines.Add('No reply')
  else
    Memo1.Lines.Add(IntToStr(vCount) + ' bytes read');
end;
C++ Builder
void __fastcall TForm1::QueryDevice()
{
  // OnData is not assigned: the bytes wait in the receive buffer for Read
  FPort->Purge();
  FPort->WriteString("*IDN?\n");
  // wait up to 1000 ms for the first byte, the reply ends after 50 ms of silence
  TBytes vData;
  int vCount = FPort->Read(vData, 256, 1000, 50);
  if (vCount == 0)
    Memo1->Lines->Add("No reply");
  else
    Memo1->Lines->Add(IntToStr(vCount) + " bytes read");
}
.NET (C#)
using System;
using esegece.sgcWebSockets;

class SerialQuery
{
    TsgcSerialPort FPort = new TsgcSerialPort();

    public void QueryDevice()
    {
        // OnData is not assigned: the bytes wait in the receive buffer for Read
        FPort.Port = "COM3";
        FPort.Open();
        FPort.Purge();
        FPort.WriteString("*IDN?\n");
        // wait up to 1000 ms for the first byte, the reply ends after 50 ms of silence
        byte[] vData = FPort.Read(256, 1000, 50);
        if (vData.Length == 0)
            Console.WriteLine("No reply");
        else
            Console.WriteLine(vData.Length + " bytes read");
    }
}

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 serial port component shipped with sgcWebSockets. For full property, method and event reference consult the online help linked above.