Componente porta seriale

Apri porte RS-232 e RS-485 da Delphi, C++Builder e .NET. Configura la linea, scrivi i dati e ricevili in un evento o con letture bloccanti, su Windows, Linux e macOS.

Novità

TsgcSerialPort

Una porta seriale con un thread di lettura in background, un buffer di ricezione da 64 KB e la stessa API in Delphi, C++Builder e C#. È anche il trasporto del client e del server Modbus RTU.

Classe del componente

TsgcSerialPort

Interfacce

Adattatori seriali RS-232, RS-485 e USB

Piattaforme

Windows, Linux e macOS (non Android né iOS)

Edizione

Incluso in sgcWebSockets Enterprise (Delphi e .NET) e All-Access, oppure nel pacchetto standalone sgcIndustrial

Apri una porta e ricevi dati

Imposta il nome della porta e i parametri della linea, assegna gli eventi e chiama Open. OnData riceve ogni blocco di byte appena arriva.

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

Cosa c'è all'interno

Una porta seriale completa per strumenti, modem, lettori di codici a barre, bilance e bus di campo.

Impostazioni della linea

BaudRate, DataBits (da 5 a 8), Parity (nessuna, dispari, pari, mark, space), StopBits (1, 1.5, 2) e FlowControl (RTS/CTS o XON/XOFF). Le combinazioni non valide sollevano EsgcSerialError all'apertura della porta.

Eventi o letture bloccanti

Con OnData assegnato, ogni blocco di byte va all'evento. Senza, i byte attendono in un buffer da 64 KB e Read restituisce una risposta completa: attende il primo byte e termina dopo un silenzio a tua scelta.

Controllo della direzione RS-485

Imposta RtsControl su srcToggle per gli adattatori che commutano la direzione con RTS. Su Windows il driver alza RTS durante la trasmissione, e su Linux viene abilitata la modalità RS-485 del kernel. In .NET la commutazione è temporizzata dal componente.

Porte e linee del modem

TsgcSerialPort.ListPorts elenca le porte in ordine naturale (COM2 prima di COM10). SetDTR, SetRTS e ModemStatus pilotano e leggono le linee del modem.

Thread-safe

Write può essere chiamato da qualsiasi thread. Close funziona da qualsiasi thread, anche da un gestore di eventi, e sblocca un Read in attesa. In Delphi e C++Builder gli eventi sono accodati per impostazione predefinita al thread principale, e NotifyEvents lo modifica.

Errori chiari

Ogni errore solleva EsgcSerialError, il cui ErrorCode contiene il codice di errore del sistema operativo quando questo lo ha segnalato. Un dispositivo scollegato mentre la porta è aperta, o un buffer di ricezione pieno, fa scattare OnError.

Invia un comando, leggi la risposta

Lascia vuoto OnData, scrivi il comando e chiama Read: attende fino a 1000 ms il primo byte e restituisce quando il dispositivo è rimasto in silenzio per 50 ms.

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

Specifiche e riferimenti

Le interfacce del sistema operativo su cui si basa questo componente.

Domande sulla porta seriale

In Delphi e C++Builder funziona su Windows (Win32 e Win64) con l'API di comunicazione Win32, e su Linux64 e macOS con POSIX termios. Non è disponibile su Android e iOS. La versione .NET si basa su System.IO.Ports.

Usa OnData per i dispositivi che inviano dati da soli, come un lettore di codici a barre o una bilancia. Usa Read per i protocolli richiesta e risposta: invia il comando, poi leggi finché il dispositivo smette di inviare. I due sono mutuamente esclusivi: Read solleva EsgcSerialError mentre OnData è assegnato, e un solo thread alla volta può chiamare Read.

Un adattatore che commuta la direzione automaticamente non richiede alcuna impostazione. Un adattatore che commuta la direzione con la linea RTS richiede RtsControl impostato su srcToggle. Su Linux il componente abilita allora la modalità RS-485 del driver e solleva EsgcSerialError quando il driver non la supporta. macOS non supporta srcToggle.

È incluso in sgcWebSockets Enterprise (Delphi e .NET) e All-Access, come parte del pacchetto sgcIndustrial. In Delphi, aggiungi sgcIndustrial alla clausola uses.

Documentazione e demo

Link diretti al riferimento del componente, apri il progetto demo e leggi il documento tecnico.

Online Help: TsgcSerialPort Riferimento completo di proprietà, metodi ed eventi di questo componente.
Progetto demo: Industrial\01.Serial_Port Un terminale seriale per Delphi, C++Builder e .NET. È incluso nel pacchetto sgcWebSockets.
Documento tecnico (PDF) Funzionalità, guida rapida, esempi di codice e riferimenti a fonti primarie solo per questo componente.
Manuale utente (PDF) Manuale completo che copre ogni componente della libreria.
La scelta più conveniente: All-AccessTutti i prodotti eSeGeCe, con Supporto Premium incluso, a partire da €1,059/anno.
Vedi i prezzi All-Access

Incluso in sgcWebSockets Enterprise

Incluso in sgcWebSockets Enterprise (Delphi e .NET) e All-Access, oppure nel pacchetto standalone sgcIndustrial.