ZylSerialPort Delphi & C++Builder Component

Class TZylSerialPort

Description
Hierarchy
Fields
Methods
Properties

Unit

Declaration

type TZylSerialPort = class(TComponent)

Description

Implements serial port communication. General usage: You can use it in asynchronous (AutoReceive = true) and synchronous mode (AutoReceive = false). In asynchronous mode the component will check the serial port periodically for new data (Interval property), it will read automatically all the available data, if exist and will fire the OnReceive event. Here you will be able to get the data from the Buffer parameter. If you set the PacketSize property higher than 0, then maximum PacketSize amount of bytes will be read periodically (it can be fewer, if not enough data is available). If you set PacketTerminator to true, then data will be read automatically until it reach the NewLine property string. This will ensure that you receive the packet in one piece. If it will not receive NewLine in 60 seconds, then it will return the available data without NewLine. In this case PacketSize will be ignored. In synchronous mode OnReceive event will fire every time, when new data is available and you can read the data using the various Read methods programmatically.

Events are raised on a secondary thread.

Hierarchy

Overview

Methods

Public constructor Create(AOwner: TComponent); override;
Public destructor Destroy(); override;
Public function Open(): Boolean;
Public procedure Close();
Public function IsConnected: TCommPort;
Public function StringToCommPort(Port: AnsiString): TCommPort;
Public function IntToCommPort(portNumber: Integer): TCommPort;
Public function CommPortToString(const Port: TCommPort): AnsiString;
Public function BaudRateToInt(const pBaudRate: TBaudRate): Integer;
Public function IntToBaudRate(const Value: Integer): TBaudRate;
Public function SendString(const str: AnsiString): Cardinal;
Public function SendStringLine(const str: AnsiString): Cardinal;
Public procedure SendStringOnNewThread(const str: AnsiString);
Public function SendData(Data: Pointer; dataSize: Cardinal): Cardinal;
Public function SendWord(const number: Word): Cardinal;
Public function SendByte(const number: Byte): Cardinal;
Public function SendChar(const character: AnsiChar): Cardinal;
Public function SendChars(const str: AnsiString): Cardinal;
Public function SendCharsLine(const str: AnsiString): Cardinal;
Public procedure SendCharsOnNewThread(const str: AnsiString);
Public function GetExistingCommPorts: TCommPortSet;
Public procedure GetExistingCommPortNames(Strings: TStrings);
Public function GetCommPortPath(port: TCommPort): Ansistring; overload;
Public function GetCommPortPath(port: AnsiString): Ansistring; overload;
Public function IsExistingCommPort(port: AnsiString): Boolean;
Public function GetCommPortType(port: AnsiString): TSerialCommPortType; overload;
Public function GetCommPortType(port: TCommPort): TSerialCommPortType; overload;
Public function IsCommPortBusy(port: AnsiString): Boolean; overload;
Public function IsCommPortBusy(port: TCommPort): Boolean; overload;
Public function IsCommPortAvailable(port: AnsiString): Boolean; overload;
Public function IsCommPortAvailable(port: TCommPort): Boolean; overload;
Public function SetBreak(const OnOff: Boolean): Boolean;
Public function SetDTR(const OnOff: Boolean): Boolean;
Public function SetRTS(const OnOff: Boolean): Boolean;
Public function SetXonXoff(const OnOff: Boolean): Boolean;
Public function ClearInputBuffer(): Boolean;
Public function ClearOutputBuffer(): Boolean;
Public function GetCTS(): Boolean;
Public function GetDSR(): Boolean;
Public function GetRING(): Boolean;
Public function GetDCD(): Boolean;
Public function GetLastReadBuffer(): AnsiString;
Public function GetEntireBuffer(): AnsiString;
Public function GetAvailableInputBufferSize(): Cardinal;
Public function GetAvailableOutputBufferSize: Cardinal;
Public function ReplaceControlChars(strInput: AnsiString): AnsiString;
Public function InsertControlChars(strInput: AnsiString): AnsiString;
Public function ReadBuffer(): AnsiString;
Public function ReadChar(): AnsiString;
Public function ReadChars(noChars: Integer; timeout: Integer = 60000): AnsiString;
Public function ReadByte(): Byte;
Public function ReadStringUpToEndChars(endChars: AnsiString; timeout: Integer = 60000): AnsiString; overload;
Public function ReadStringUpToEndChars(endChars: AnsiString; timeout: Integer; var partialResult: string; var timedOut: Boolean; var endCharsFound: string): AnsiString; overload;
Public function ReadStringUpToEndChars(endCharsList: TStrings; timeout: Integer = 60000): AnsiString; overload;
Public function ReadStringUpToEndChars(endCharsList: TStrings; timeout: Integer; var partialResult: AnsiString): AnsiString; overload;
Public function ReadStringUpToEndChars(endCharsList: TStrings; timeout: Integer; var partialResult: AnsiString; var timedOut: Boolean; var endCharsFound: AnsiString): AnsiString; overload;
Public function ReadStringLine(timeout: Integer = 60000): AnsiString;
Public function Echo(): AnsiString;
Public function RandomDataGenerator(length: Integer): AnsiString;
Public function DetectDevice(const sentToken, receivedToken: AnsiString; const startBaudRate, endBaudRate: TBaudRate; var pPort: AnsiString; var pBaudRate: TBaudRate): Boolean; overload;
Public function DetectDevice(const sentToken, receivedToken: AnsiString; var pPort: TCommPort; var pBaudRate: TBaudRate): Boolean; overload;
Public function FastDetectDevice(const sentToken, receivedToken: AnsiString; var strPort: AnsiString; var pBaudRate: TBaudRate): Boolean;
Public function TestDevice(sentToken, receivedToken: AnsiString; timeout: Integer = 60000): Boolean;
Public procedure ResetIdleState;
Public procedure SetFault;
Public function GetLastError: TSerialErrorSet;
Public function GetError(errorCode: cardinal): TSerialErrorSet;

Properties

Public property ExceptionLogger: TExceptionLogger read FExceptionLogger write FExceptionLogger;
Public property IsSending: Boolean read FIsSending default False;
Public property IsReceiving: Boolean read FIsReceiving default False;
Public property IsFaulted: Boolean read FIsFaulted default False;
Public property NeedSynchronization: Boolean read FNeedSynchronization write FNeedSynchronization;
Public property MinCheckDisconnectedInterval: Cardinal read FMinCheckDisconnectedInterval write FMinCheckDisconnectedInterval default 50;
Public property MaxLineLength: Integer read FMaxLineLength write FMaxLineLength default 0;
Public property IsIdle: Boolean read FIdleWasFired;
Public property LastTimeReceived: TDateTime read FLastTimeReceived;
Public property ConnectionTime: TDateTime read FConnectionTime;
Public property Version: double read FVersion;
Public property UnlockKey: AnsiString read FUnlockKey write FUnlockKey;
Published property Port: TCommPort read GetCommPort write SetCommPort default spNone;
Published property BaudRate: TBaudRate read GetBaudRate write SetBaudRate default br004800;
Published property DataWidth: TDataWidth read GetDataWidth write SetDataWidth default dw8Bits;
Published property StopBits: TStopBits read GetStopBits write SetStopBits default sb1Bit;
Published property Parity: TParityBits read GetParity write SetParity default pbNone;
Published property EnableDTROnOpen: Boolean read FEnableDTROnOpen write SetEnableDTROnOpen default True;
Published property EnableRTSOnOpen: Boolean read FEnableRTSOnOpen write SetEnableRTSOnOpen default True;
Published property HwFlowControl: THwFlowControl read FHwFlowControl write SetHwFlowControl default hfNONE;
Published property SwFlowControl: TSwFlowControl read FSwFlowControl write SetSwFlowControl default sfNONE;
Published property XonChar: AnsiChar read FXonChar write SetXonChar default #17;
Published property XoffChar: AnsiChar read FXoffChar write SetXoffChar default #19;
Published property XonLim: Word read FXonLim write SetXonLim default 0;
Published property XoffLim: Word read FXoffLim write SetXoffLim default 1;
Published property ParityCheck: Boolean read FParityCheck write SetParityCheck default False;
Published property ReplaceParityErrors: Boolean read FReplaceParityErrors write SetReplaceParityErrors default False;
Published property DiscardNulls: Boolean read FDiscardNulls write SetDiscardNulls default False;
Published property DsrSensitivity: Boolean read FDsrSensitivity write SetDsrSensitivity default False;
Published property TXContinueOnXoff: Boolean read FTXContinueOnXoff write SetTXContinueOnXoff default False;
Published property ErrorChar: AnsiChar read FErrorChar write SetErrorChar default #0;
Published property EofChar: AnsiChar read FEofChar write SetEofChar default #26;
Published property EvtChar: AnsiChar read FEvtChar write SetEvtChar default #26;
Published property ReadIntervalTimeout: LongWord read FReadIntervalTimeout write FReadIntervalTimeout default MAXDWORD;
Published property ReadTotalTimeoutMultiplier: LongWord read FReadTotalTimeoutMultiplier write FReadTotalTimeoutMultiplier default 0;
Published property ReadTotalTimeoutConstant: LongWord read FReadTotalTimeoutConstant write FReadTotalTimeoutConstant default 0;
Published property WriteTotalTimeoutMultiplier: LongWord read FWriteTotalTimeoutMultiplier write FWriteTotalTimeoutMultiplier default 100;
Published property WriteTotalTimeoutConstant: LongWord read FWriteTotalTimeoutConstant write FWriteTotalTimeoutConstant default 1000;
Published property InputBuffer: Cardinal read FInputBuffer write SetInputBuffer default 4096;
Published property OutputBuffer: Cardinal read FOutputBuffer write SetOutputBuffer default 4096;
Published property Priority: TThreadPriority read FPriority write SetPriority default tpNormal;
Published property Delay: Cardinal read FDelay write FDelay default 100;
Published property Interval: Cardinal read FDelay write FDelay default 100;
Published property IdleInterval: Cardinal read FIdleInterval write FIdleInterval default 0;
Published property IdleTimeoutInterval: Cardinal read FIdleTimeoutInterval write FIdleTimeoutInterval default 0;
Published property CustomPortName: AnsiString read FCustomPortName write SetCustomPortName;
Published property CustomBaudRate: Integer read FCustomBaudRate write SetCustomBaudRate default 0;
Published property LogInput: Boolean read FLogInput write FLogInput default False;
Published property LogDateTime: Boolean read FLogDateTime write FLogDateTime default False;
Published property LogFile: String read FLogFile write FLogFile;
Published property AutoReceive: Boolean read FAutoReceive write SetAutoReceive default true;
Published property AutoReconnect: Boolean read FAutoReconnect write FAutoReconnect default false;
Published property AutoReconnectCheckInterval: Integer read FAutoReconnectCheckInterval write FAutoReconnectCheckInterval default 4000;
Published property KeepEntireBuffer: Boolean read FKeepEntireBuffer write FKeepEntireBuffer default False;
Published property NewLine: AnsiString read FNewLine write FNewLine;
Published property CloseWhenLineStatusIsZero: Boolean read FCloseWhenLineStatusIsZero write FCloseWhenLineStatusIsZero default false;
Published property SkipSetupFailed: Boolean read FSkipSetupFailed write FSkipSetupFailed default false;
Published property PacketSize: LongWord read FPacketSize write FPacketSize;
Published property PacketTerminator: boolean read FPacketTerminator write FPacketTerminator;
Published property OnReceive: TSendReceiveEvent read FOnReceive write FOnReceive;
Published property OnSend: TSendReceiveEvent read FOnSend write FOnSend;
Published property OnLineStatusChange: TLineStatusEvent read FOnLineStatusChange write FOnLineStatusChange;
Published property OnConnect: TConnectEvent read FOnConnect write FOnConnect;
Published property OnDisconnect: TConnectEvent read FOnDisconnect write FOnDisconnect;
Published property OnFault: TConnectEvent read FOnFault write FOnFault;
Published property OnIdle: TNotifyEvent read FOnIdle write FOnIdle;
Published property OnIdleTimeout: TNotifyEvent read FOnIdleTimeout write FOnIdleTimeout;
Published property OnResume: TNotifyEvent read FOnResume write FOnResume;
Published property OnDetect: TDetectEvent read FOnDetect write FOnDetect;
Published property OnReconnect: TReconnectEvent read FOnReconnect write FOnReconnect;
Published property OnError: TErrorEvent read FOnError write FOnError;

Description

Methods

Public constructor Create(AOwner: TComponent); override;

Constructor of the component.

Public destructor Destroy(); override;

Destructor of the component.

Public function Open(): Boolean;

Opens the serial port.

Returns

true if succeeded.

Public procedure Close();

Closes the serial port.

Public function IsConnected: TCommPort;

Returns true if the serial port is connected (open).

Returns

Connected (open) = true; not connected = false;

Public function StringToCommPort(Port: AnsiString): TCommPort;

Converts string to TCommPort.

Parameters
port
String representation of the port.
Returns

The equivalent TCommPort value.

Public function IntToCommPort(portNumber: Integer): TCommPort;

Converts integer to TCommPort.

Parameters
portNumber
Number of the port.
Returns

The equivalent TCommPort value.

Public function CommPortToString(const Port: TCommPort): AnsiString;

Converts TCommPort to string.

Parameters
port
TCommPort value.
Returns

String representation of the port.

Public function BaudRateToInt(const pBaudRate: TBaudRate): Integer;

Converts TBaudRate to integer.

Parameters
pBaudRate
TBaudRate value.
Returns

Integer value of baud rate.

Public function IntToBaudRate(const Value: Integer): TBaudRate;

Converts integer to TBaudRate.

Parameters
Value
Baud rate value.
Returns

The equivalent TBaudRate value.

Public function SendString(const str: AnsiString): Cardinal;

Sends an ANSI string to the serial port (NULL terminated if $H+ (default)).

Parameters
str
String to be sent.
Returns

The count of sent bytes.

Public function SendStringLine(const str: AnsiString): Cardinal;

Sends an ANSI string to the serial port and add new line at the end of the string. NewLine can be set by the NewLine property.

Parameters
str
String to be sent.
Returns

The count of sent bytes, including NewLine.

Public procedure SendStringOnNewThread(const str: AnsiString);

Sends an ANSI string to the serial port on a separate thread.

Parameters
str
String to be sent.
Public function SendData(Data: Pointer; dataSize: Cardinal): Cardinal;

Sends a buffer to the serial port.

Parameters
Data
Buffer to be sent.
dataSize
Buffer size.
Returns

The count of sent bytes.

Public function SendWord(const number: Word): Cardinal;

Sends a word number to the serial port.

Parameters
number
Word to be sent.
Returns

The count of sent bytes.

Public function SendByte(const number: Byte): Cardinal;

Sends a byte to the serial port.

sends a byte number

Parameters
number
Byte to be sent.
Returns

The count of sent bytes.

Public function SendChar(const character: AnsiChar): Cardinal;

Sends a char to the serial port.

sends a character

Parameters
character
Char to be sent.
Returns

The count of sent bytes.

Public function SendChars(const str: AnsiString): Cardinal;

Sends an ANSI string to the serial port, including null characters.

Parameters
str
String to be sent.
Returns

The count of sent bytes.

Public function SendCharsLine(const str: AnsiString): Cardinal;

Sends an ANSI string to the serial port, including null characters and add new line at the end of the string. NewLine can be set by the NewLine property.

Parameters
str
String to be sent.
Returns

The count of sent bytes, including NewLine.

Public procedure SendCharsOnNewThread(const str: AnsiString);

Sends an ANSI string to the serial port, including null characters on a separate thread.

Parameters
str
String to be sent.
Returns

The count of sent bytes.

Public function GetExistingCommPorts: TCommPortSet;

Returns the existing serial ports of the system.

Returns

Existing serial ports of the system in an array of SerialCommPort objects.

Public procedure GetExistingCommPortNames(Strings: TStrings);

Returns the existing serial port names of the system.

Returns

Existing serial ports of the system in an array of strings.

Public function GetCommPortPath(port: TCommPort): Ansistring; overload;

Returns the OS level name of the port. E.g.: \Device\PCISerial1 If the port does not exists, returns empty string.

Parameters
port
The serial port.
Returns

OS level name of the port.

Public function GetCommPortPath(port: AnsiString): Ansistring; overload;

Returns the OS level name of the port. E.g.: \Device\PCISerial1 If the port does not exists, returns empty string.

Parameters
port
The serial port.
Returns

OS name of the port.

Public function IsExistingCommPort(port: AnsiString): Boolean;

Checks if a serial port exists.

Parameters
port
The serial port, which is checked, if exists.
Returns

true, if the port exists.

Public function GetCommPortType(port: AnsiString): TSerialCommPortType; overload;

Returns the type of the serial port.

Parameters
port
Serial port.
Returns

Type of the serial port.

Public function GetCommPortType(port: TCommPort): TSerialCommPortType; overload;

Returns the type of the serial port.

Parameters
port
Serial port.
Returns

Type of the serial port.

Public function IsCommPortBusy(port: AnsiString): Boolean; overload;

Checks if a serial port is already opened by another or the same process (busy). If the port does not exists, SerialPortException is thrown.

Parameters
port
Port name.
Returns

true, if busy.

Public function IsCommPortBusy(port: TCommPort): Boolean; overload;

Checks if a serial port is already opened by another or the same process (busy). If the port does not exists, SerialPortException is thrown.

Parameters
port
Port name.
Returns

true, if busy.

Public function IsCommPortAvailable(port: AnsiString): Boolean; overload;

Checks if the serial port is available (It exists and is not busy, opened by another or the same process).

Parameters
port
Port name.
Returns

true, if available.

Public function IsCommPortAvailable(port: TCommPort): Boolean; overload;

Checks if the serial port is available (It exists and is not busy, opened by another or the same process).

Parameters
port
Port name.
Returns

true, if available.

Public function SetBreak(const OnOff: Boolean): Boolean;

Sets break line. When value is true, suspends character transmission and places the transmission line in a break state. When value is false, restores character transmission and places the transmission line in a nonbreak state.

Parameters
OnOff
true = high; false = low
Returns

true if succeeded.

Public function SetDTR(const OnOff: Boolean): Boolean;

Sets DTR (data-terminal-ready) line.

Parameters
OnOff
true = high; false = low
Returns

True, if succeeded.

Public function SetRTS(const OnOff: Boolean): Boolean;

Sets RTS (request-to-send) line.

Parameters
OnOff
true = high; false = low
Returns

True, if succeeded.

Public function SetXonXoff(const OnOff: Boolean): Boolean;

Sets XOnXoff state. When value is true, causes transmission to act as if an XON character has been received. When value is false, Causes transmission to act as if an XOFF character has been received.

Parameters
OnOff
true = high; false = low
Returns

True, if succeeded.

Public function ClearInputBuffer(): Boolean;

Clears input buffer.

Returns

true, if succeeded.

Public function ClearOutputBuffer(): Boolean;

Clears output buffer.

Returns

true, if succeeded.

Public function GetCTS(): Boolean;

Returns the state of CTS (clear-to-send) line.

Returns

Returns the state of CTS line.

Public function GetDSR(): Boolean;

Returns the state of DSR (data-set-ready) line.

Returns

Returns the state of DSR line.

Public function GetRING(): Boolean;

Returns the state of RING line.

Returns

Returns the state of RING line.

Public function GetDCD(): Boolean;

Returns the state of DCD line. Data Carrier Detect, or alternately Carrier Detect abbreviated as CD or RLSD (receive-line-signal-detect).

Returns

Returns the state of DCD line.

Public function GetLastReadBuffer(): AnsiString;

Returns the last received buffer. It is used when AutoReceive = false.

Returns

Returns the last received buffer.

Public function GetEntireBuffer(): AnsiString;

Returns the entire buffer, starting from the last open of the port (only if KeepEntireBuffer property is set to true).

Returns

Returns the entire buffer, starting from the last open of the port.

Public function GetAvailableInputBufferSize(): Cardinal;

Returns the number of bytes of data not yet read in the receive buffer (bytes to read). It is used when AutoReceive = false.

Returns

Returns the number of bytes of data in the receive buffer.

Public function GetAvailableOutputBufferSize: Cardinal;

Returns the number of bytes of data not yet written in the send buffer (bytes to write). This value will be zero for a non-overlapped write.

Returns

Returns the number of bytes of data in the send buffer.

Public function ReplaceControlChars(strInput: AnsiString): AnsiString;

Replaces control characters 0-31 with readable text.

Parameters
strInput
Raw text.
Returns

Readable text. Example: #0 = "[NUL]" #1 = "[SOH]" #2 = "[STX]" #3 = "[ETX]" #4 = "[EOT]" #5 = "[ENQ]" #6 = "[ACK]" #7 = "[BEL]" #8 = "[BS]" #9 = "[TAB]" #10 = "[LF]" #11 = "[VT]" #12 = "[FF]" #13 = "[CR]" #14 = "[SO]" #15 = "[SI]" #16 = "[DLE]" #17 = "[DC1]" #18 = "[DC2]" #19 = "[DC3]" #20 = "[DC4]" #21 = "[NAK]" #22 = "[SYN]" #23 = "[ETB]" #24 = "[CAN]" #25 = "[EM]" #26 = "[SUB]" #27 = "[ESC]" #28 = "[FS]" #29 = "[GS]" #30 = "[RS]" #31 = "[US]"

Public function InsertControlChars(strInput: AnsiString): AnsiString;

Replaces readable text with control characters 0-31.

Parameters
strInput
Readable text.
Returns

Text with control characters. Example: #0 = "[NUL]" #1 = "[SOH]" #2 = "[STX]" #3 = "[ETX]" #4 = "[EOT]" #5 = "[ENQ]" #6 = "[ACK]" #7 = "[BEL]" #8 = "[BS]" #9 = "[TAB]" #10 = "[LF]" #11 = "[VT]" #12 = "[FF]" #13 = "[CR]" #14 = "[SO]" #15 = "[SI]" #16 = "[DLE]" #17 = "[DC1]" #18 = "[DC2]" #19 = "[DC3]" #20 = "[DC4]" #21 = "[NAK]" #22 = "[SYN]" #23 = "[ETB]" #24 = "[CAN]" #25 = "[EM]" #26 = "[SUB]" #27 = "[ESC]" #28 = "[FS]" #29 = "[GS]" #30 = "[RS]" #31 = "[US]"

Public function ReadBuffer(): AnsiString;

Synchronously reads the received data from the serial port to a byte array. It works only if AutoReceive property is false.

Returns

Returns the current buffer of the serial port in a byte array and discards it.

Public function ReadChar(): AnsiString;

Synchronously reads one character from the serial port. It works only if AutoReceive property is false, otherwise returns empty string.

Returns

Returns one character in a string from the available buffer and discards that char. Returns empty string, if there is no data in the buffer or AutoReceive is true.

Public function ReadChars(noChars: Integer; timeout: Integer = 60000): AnsiString;

Reads noChars chars from the serial port into string and discards them. It works only if AutoReceive property is false.

Parameters
noChars
The number of chars to read.
timeout
If the timeout (milliseconds) interval elapses and cannot read enough bytes (numberOfChars), the method will return what it read till then, less bytes. Default value: 60000.
Returns

Returns noChars bytes from the serial port into string.

Public function ReadByte(): Byte;

Synchronously reads one byte from the serial port, if data available. It works only if AutoReceive property is false, otherwise returns 0.

Returns

Returns one byte from the available buffer and discards that byte. Returns 0, if there is no data in the buffer or AutoReceive is true.

Public function ReadStringUpToEndChars(endChars: AnsiString; timeout: Integer = 60000): AnsiString; overload;

Reads the serial port up to the first occurrence of endChars sequence. It works only if AutoReceive property is false.

Parameters
endChars
Terminator characters.
timeout
If the timeout (milliseconds) interval elapses and no endChars are found, the method will return with empty string (anti-blocking protection). Default value: 60000.
Returns

Returns the contents of the input buffer up to the first occurrence of a endChars sequence, but endChars are not included in the result.

Public function ReadStringUpToEndChars(endChars: AnsiString; timeout: Integer; var partialResult: string; var timedOut: Boolean; var endCharsFound: string): AnsiString; overload;

Reads the serial port up to the first occurrence of endChars sequence. It works only if AutoReceive property is false.

Parameters
endChars
Terminator characters.
timeout
If the timeout (milliseconds) interval elapses and no endChars are found, the method will return with empty string (anti-blocking protection). Default value: 60000.
partialResult
partialResult is empty string, if endChars sequence was found, otherwise contains the discarded data.
timedout
Indicates if the read process was timed out.
endCharsFound
The terminator characters sequence, which was reached.
Returns

Returns the contents of the input buffer up to the first occurrence of a endChars sequence, but endChars are not included in the result.

Public function ReadStringUpToEndChars(endCharsList: TStrings; timeout: Integer = 60000): AnsiString; overload;

Reads the serial port up to the first occurrence of one of the endChars sequences of the endCharsList collection. It works only if AutoReceive property is false.

Parameters
endCharsList
Collection of terminator characters sequence.
timeout
If the timeout (milliseconds) interval elapses and no endChars are found, the method will return with empty string (anti-blocking protection). Default value: 60000.
Returns

Returns the contents of the input buffer up to the first occurrence of a endChars sequence, but endChars are not included in the result.

Public function ReadStringUpToEndChars(endCharsList: TStrings; timeout: Integer; var partialResult: AnsiString): AnsiString; overload;

Reads the serial port up to the first occurrence of one of the endChars sequences of the endCharsList collection. It works only if AutoReceive property is false.

Parameters
endCharsList
Collection of terminator characters sequence.
partialResult
partialResult is empty string, if endChars sequence was found, otherwise contains the discarded data.
timeout
If the timeout (milliseconds) interval elapses and no endChars are found, the method will return with empty string (anti-blocking protection). Default value: 60000.
Returns

Returns the contents of the input buffer up to the first occurrence of a endChars sequence, but endChars are not included in the result.

Public function ReadStringUpToEndChars(endCharsList: TStrings; timeout: Integer; var partialResult: AnsiString; var timedOut: Boolean; var endCharsFound: AnsiString): AnsiString; overload;

Reads the serial port up to the first occurrence of one of the endChars sequences of the endCharsList collection. It works only if AutoReceive property is false.

Parameters
endCharsList
Collection of terminator characters sequence.
partialResult
partialResult is empty string, if endChars sequence was found, otherwise contains the discarded data.
timeout
If the timeout (milliseconds) interval elapses and no endChars are found, the method will return with empty string (anti-blocking protection).
timedout
Indicates if the read process was timed out.
endCharsFound
The terminator characters sequence, which was reached.
Returns

Returns the contents of the input buffer up to the first occurrence of a endChars sequence, but endChars are not included in the result.

Public function ReadStringLine(timeout: Integer = 60000): AnsiString;

Reads the serial port up to the first occurrence of NewLine sequence. NewLine can be set by the NewLine property. It works only if AutoReceive property is false.

Parameters
timeout
If the timeout (milliseconds) interval elapses and no NewLine is found, the method will return with empty string (anti-blocking protection). Default value: 60000.
Returns

Returns the contents of the input buffer up to the first occurrence of a NewLine, but NewLine is not included in the result.

Public function Echo(): AnsiString;

Sends the last received buffer back.

Returns

Returns the last received buffer, which was sent back to the port.

Public function RandomDataGenerator(length: Integer): AnsiString;

Generates random data in string format (chars between 0 - 255).

Parameters
length
The size of random data.
Returns

Random data.

Public function DetectDevice(const sentToken, receivedToken: AnsiString; const startBaudRate, endBaudRate: TBaudRate; var pPort: AnsiString; var pBaudRate: TBaudRate): Boolean; overload;

Detects the serial port where the device is connected to and returns as output parameters the communication port and baud rate. In the detection process senToken will be sent and receivedToken is expected to receive. Only baud rate values between startBaudRate and endBaudRate are checked.

Parameters
sentToken
The token, which is sent in the detection process, to check the port.
receivedToken
The token, expected to receive in the detection process, to check the port.
startBaudRate
The lowest baud rate limit used at the detection process.
endBaudRate
The highest baud rate limit used at the detection process.
pPort
The serial port where the device is connected to.
pBaudRate
Baud rate of the communication.
Returns

Returns true, if a device was detected, otherwise false.

Public function DetectDevice(const sentToken, receivedToken: AnsiString; var pPort: TCommPort; var pBaudRate: TBaudRate): Boolean; overload;

Detects the serial port where the device is connected to and returns as output parameters the communication port and baud rate. In the detection process senToken will be sent and receivedToken is expected to receive.

Parameters
sentToken
The token, which is sent in the detection process, to check the port.
receivedToken
The token, expected to receive in the detection process, to check the port.
pPort
The serial port where the device is connected to.
pBaudRate
Baud rate of the communication.
Returns

Returns true, if a device was detected, otherwise false.

Public function FastDetectDevice(const sentToken, receivedToken: AnsiString; var strPort: AnsiString; var pBaudRate: TBaudRate): Boolean;

Detects the serial port where the device is connected to and returns as output parameters the communication port and baud rate. In the detection process senToken will be sent and receivedToken is expected to receive. Only baud rates between 4800 and 921600 will be checked.

Parameters
sentToken
The token, which is sent in the detection process, to check the port.
receivedToken
The token, expected to receive in the detection process, to check the port.
strPort
The serial port where the device is connected to.
pBaudRate
Baud rate of the communication.
Returns

Returns true, if a device was detected, otherwise false.

Public function TestDevice(sentToken, receivedToken: AnsiString; timeout: Integer = 60000): Boolean;

Tests if the connection is alive sending sentToken and expecting to receive receivedToken.

Parameters
sentToken
The token, which is sent in the test process, to check the port.
receivedToken
The token, expected to receive in the test process.
timeout
If the timeout (milliseconds) interval elapses and no receivedToken is received, the method will return with false result. Default value: 60000.
Returns

True, if the receivedToken was received (test succeeded), otherwise false.

Public procedure ResetIdleState;

Resets the idle state of the port.

Public procedure SetFault;

Emulates faulted state, raises the OnFault event and close the port. If AutoReconnect is true, it will try to reconnect.

Public function GetLastError: TSerialErrorSet;

Returns the last error occured.

Returns

Last error occured.

Public function GetError(errorCode: cardinal): TSerialErrorSet;

Converts errorCode to TSerialErrorSet.

Parameters
errorCode
Error code.
Returns

TSerialErrorSet value.

Properties

Public property ExceptionLogger: TExceptionLogger read FExceptionLogger write FExceptionLogger;

Exception logger object.

Public property IsSending: Boolean read FIsSending default False;

This property is true when the component is sending data to the port, otherwise is false. Use this property to check if the component is inside a sending process.

Public property IsReceiving: Boolean read FIsReceiving default False;

This property is false when the component is receiving data from the port, otherwise is false. Use this property to check if the component is inside a receiving process.

Public property IsFaulted: Boolean read FIsFaulted default False;

Indicates that the last connection was faulted. Example: When you unplug an USB device which communicates on a virtual serial port.

Public property NeedSynchronization: Boolean read FNeedSynchronization write FNeedSynchronization;

Set this property to true for thread safety. The default value is false. Note: if you set it to true, you may experiment thread interblocking and lower speed.

Do not set it to true in Delphi 6, because of Delphi bug.

Public property MinCheckDisconnectedInterval: Cardinal read FMinCheckDisconnectedInterval write FMinCheckDisconnectedInterval default 50;

must be false for Delphi 6 - IDE bug <summary> The minimum time interval in milliseconds, for which the port availability is checked. For time critical usage it's recommended to set it to a higher value. The default value is 50. </summary>

Public property MaxLineLength: Integer read FMaxLineLength write FMaxLineLength default 0;

The maximum length of a line, when ReadStringLine or ReadStringUpToEndChars methods are used in synchronous mode (AutoReceive = false). If maximum length is reached, the methods return with empty string. If this value is 0, there is no maximum length. The default value is 0.

Public property IsIdle: Boolean read FIdleWasFired;

True if Idle occurred, until Resumed. It works only for AutoReceive = true.

Public property LastTimeReceived: TDateTime read FLastTimeReceived;

Last date-time when data received from the serial port.

Public property ConnectionTime: TDateTime read FConnectionTime;

Indicates when the last connection was established.

Public property Version: double read FVersion;

Version number of the component.

Public property UnlockKey: AnsiString read FUnlockKey write FUnlockKey;

Unlock key of the component.

Set the unlock key after the component is created. E.g.: componentName.UnlockKey = 'your unlock key';

Published property Port: TCommPort read GetCommPort write SetCommPort default spNone;

Physical name of the serial port.

Published property BaudRate: TBaudRate read GetBaudRate write SetBaudRate default br004800;

Baud rate at which the communications device operates.

Published property DataWidth: TDataWidth read GetDataWidth write SetDataWidth default dw8Bits;

Number of bits in the bytes transmitted and received.

Published property StopBits: TStopBits read GetStopBits write SetStopBits default sb1Bit;

Number of stop bits to be used.

Published property Parity: TParityBits read GetParity write SetParity default pbNone;

Parity scheme to be used.

Published property EnableDTROnOpen: Boolean read FEnableDTROnOpen write SetEnableDTROnOpen default True;

Enable DTR when the port is opening. The default value is true.

Published property EnableRTSOnOpen: Boolean read FEnableRTSOnOpen write SetEnableRTSOnOpen default True;

Enable RTS when the port is opening. The default value is true.

Published property HwFlowControl: THwFlowControl read FHwFlowControl write SetHwFlowControl default hfNONE;

Hardware flow control of the serial port.

Published property SwFlowControl: TSwFlowControl read FSwFlowControl write SetSwFlowControl default sfNONE;

Software flow control of the serial port.

Published property XonChar: AnsiChar read FXonChar write SetXonChar default #17;

Value of the XON character for both transmission and reception (ANSI: 0 - 255). The default value is #17.

Published property XoffChar: AnsiChar read FXoffChar write SetXoffChar default #19;

Value of the XOFF character for both transmission and reception (ANSI: 0 - 255). The default value is #19.

Published property XonLim: Word read FXonLim write SetXonLim default 0;

Minimum number of bytes allowed in the input buffer before the XON character is sent. The default value is 0, which means InputBuffer div 4.

Published property XoffLim: Word read FXoffLim write SetXoffLim default 1;

Maximum number of bytes allowed in the input buffer before the XOFF character is sent. The maximum number of bytes allowed is calculated by subtracting this value from the size, in bytes, of the input buffer. The default value is 1.

Published property ParityCheck: Boolean read FParityCheck write SetParityCheck default False;

If this property is true, parity checking is performed and parity errors are reported. This should not be confused with the Parity member, which controls the type of parity used in communications. The default value is false.

Published property ReplaceParityErrors: Boolean read FReplaceParityErrors write SetReplaceParityErrors default False;

Specifies whether bytes received with parity errors are replaced with the character specified by the ErrorChar member. If this member is true and the ParityCheck member is true, replacement occurs. The default value is false.

Published property DiscardNulls: Boolean read FDiscardNulls write SetDiscardNulls default False;

Specifies whether null bytes are discarded. If this member is true, null bytes are discarded when received. The default value is false.

Published property DsrSensitivity: Boolean read FDsrSensitivity write SetDsrSensitivity default False;

Specifies whether the communications driver is sensitive to the state of the DSR signal. If this member is true, the driver ignores any bytes received, unless the DSR modem input line is high. The default value is false.

Published property TXContinueOnXoff: Boolean read FTXContinueOnXoff write SetTXContinueOnXoff default False;

Specifies whether transmission stops when the input buffer is full and the driver has transmitted the Xoff character. If this member is true, transmission continues after the Xoff character has been sent. If this member is false, transmission does not continue until the input buffer is within XonLim bytes of being empty and the driver has transmitted the Xon character. The default value is false.

Published property ErrorChar: AnsiChar read FErrorChar write SetErrorChar default #0;

Value of the character used to replace bytes received with a parity error (ANSI: 0 - 255). The default value is #0.

Published property EofChar: AnsiChar read FEofChar write SetEofChar default #26;

Value of the character used to signal the end of data (ANSI: 0 - 255). The default value is #26.

Published property EvtChar: AnsiChar read FEvtChar write SetEvtChar default #26;

Value of the character used to signal an event (ANSI: 0 - 255). The default value is #26.

Published property ReadIntervalTimeout: LongWord read FReadIntervalTimeout write FReadIntervalTimeout default MAXDWORD;

Maximum time allowed to elapse between the arrival of two characters on the communications line, in milliseconds. During a ReadFile operation, the time period begins when the first character is received. If the interval between the arrival of any two characters exceeds this amount, the ReadFile operation is completed and any buffered data is returned. A value of zero indicates that interval time-outs are not used. A value of MAXDWORD, combined with zero values for both the ReadTotalTimeoutConstant and ReadTotalTimeoutMultiplier members, specifies that the read operation is to return immediately with the characters that have already been received, even if no characters have been received. The default value is MAXDWORD.

Published property ReadTotalTimeoutMultiplier: LongWord read FReadTotalTimeoutMultiplier write FReadTotalTimeoutMultiplier default 0;

Multiplier used to calculate the total time-out period for read operations, in milliseconds. For each read operation, this value is multiplied by the requested number of bytes to be read. The default value is 0.

Published property ReadTotalTimeoutConstant: LongWord read FReadTotalTimeoutConstant write FReadTotalTimeoutConstant default 0;

Constant used to calculate the total time-out period for read operations, in milliseconds. For each read operation, this value is added to the product of the ReadTotalTimeoutMultiplier member and the requested number of bytes. A value of zero for both the ReadTotalTimeoutMultiplier and ReadTotalTimeoutConstant members indicates that total time-outs are not used for read operations. The default value is 0.

Published property WriteTotalTimeoutMultiplier: LongWord read FWriteTotalTimeoutMultiplier write FWriteTotalTimeoutMultiplier default 100;

Multiplier used to calculate the total time-out period for write operations, in milliseconds. For each write operation, this value is multiplied by the number of bytes to be written. WriteTotalTimeout = WriteTotalTimeoutMultiplier * noOfBytesWritten + WriteTotalTimeoutConstant (milliseconds). The default value is 100.

Published property WriteTotalTimeoutConstant: LongWord read FWriteTotalTimeoutConstant write FWriteTotalTimeoutConstant default 1000;

Constant used to calculate the total time-out period for write operations, in milliseconds. For each write operation, this value is added to the product of the WriteTotalTimeoutMultiplier member and the number of bytes to be written. A value of zero for both the WriteTotalTimeoutMultiplier and WriteTotalTimeoutConstant members indicates that total time-outs are not used for write operations. WriteTotalTimeout = WriteTotalTimeoutMultiplier * noOfBytesWritten + WriteTotalTimeoutConstant (milliseconds). The default value is 1000.

Published property InputBuffer: Cardinal read FInputBuffer write SetInputBuffer default 4096;

Recommended size of the device's internal input buffer, in bytes. The device driver receives the recommended buffer sizes, but is free to use any input and output (I/O) buffering scheme, as long as it provides reasonable performance and data is not lost due to overrun (except under extreme circumstances). The default value is 4096.

Published property OutputBuffer: Cardinal read FOutputBuffer write SetOutputBuffer default 4096;

Recommended size of the device's internal output buffer, in bytes. The device driver receives the recommended buffer sizes, but is free to use any input and output (I/O) buffering scheme, as long as it provides reasonable performance and data is not lost due to overrun (except under extreme circumstances). The default value is 4096.

Published property Priority: TThreadPriority read FPriority write SetPriority default tpNormal;

Priority of the receiver thread. The default value is tpNormal.

Published property Delay: Cardinal read FDelay write FDelay default 100;

Time interval between two receivings in milliseconds (frequency). It must be a positive value. The default value is 100. Same as interval.

Obsolete. Use Interval instead.

Published property Interval: Cardinal read FDelay write FDelay default 100;

Time interval between two receivings in milliseconds (frequency). It must be a positive value. The default value is 100.

Published property IdleInterval: Cardinal read FIdleInterval write FIdleInterval default 0;

Idle time interval in milliseconds. If the elapsed time from the last receive is higher than IdleInterval, OnIdle event occurs. If IdleInterval is 0, OnIdle event never occurs. It works only for AutoReceive = true. The default value is 0.

Published property IdleTimeoutInterval: Cardinal read FIdleTimeoutInterval write FIdleTimeoutInterval default 0;

You can set a time-out value to automatically close the connection and fire the OnIdleTimeout event, if there is no data received in several milliseconds. A value of zero indicates that time-out is not used. The default value is 0.

Published property CustomPortName: AnsiString read FCustomPortName write SetCustomPortName;

Custom port name can be used when Port is set to Custom. You can use any name, different from COMMxx.

Published property CustomBaudRate: Integer read FCustomBaudRate write SetCustomBaudRate default 0;

Custom baud rate value, used when BaudRate is set to Custom. Unit of measurement: bps (bits per second). The default value is 0.

Published property LogInput: Boolean read FLogInput write FLogInput default False;

Enables or disables received data logging. If you enable it, all the incoming data will be logged to the LogFile. The default value is false.

Published property LogDateTime: Boolean read FLogDateTime write FLogDateTime default False;

When this property is true, a date-time stamp will be added before the logged received data. The default value is false.

Published property LogFile: String read FLogFile write FLogFile;

Name and full path of the received data log file.

Published property AutoReceive: Boolean read FAutoReceive write SetAutoReceive default true;

Set this property to true, if you want to receive the incoming data automatically in the OnReceive event. Otherwise you have to use ReadBuffer method to get the received data. The default value is true.

Published property AutoReconnect: Boolean read FAutoReconnect write FAutoReconnect default false;

Set this property to true, if you want to automatically reconnect to the serial port after a OnFault event, when the port is available again. Set AutoReconnect to true, before the port is faulted, otherwise it will have no effect. The default value is false.

Published property AutoReconnectCheckInterval: Integer read FAutoReconnectCheckInterval write FAutoReconnectCheckInterval default 4000;

The time interval in milliseconds the serial port is trying to periodically reconnect, after a OnFault event occur, if AutoReconnect is set to true. It must be a positive value. The default value is 4000.

Published property KeepEntireBuffer: Boolean read FKeepEntireBuffer write FKeepEntireBuffer default False;

When KeepEntireBuffer property is set to true, you will be able to get the entire buffer, starting from the last open of the port with the GetEntireBuffer method. You have to set it before calling the Open method.

Published property NewLine: AnsiString read FNewLine write FNewLine;

Gets or sets the value used to interpret the end of line in the ReadLine or SendAsciiStringLine methods. Default value is #13#10.

Published property CloseWhenLineStatusIsZero: Boolean read FCloseWhenLineStatusIsZero write FCloseWhenLineStatusIsZero default false;

When this property is true and LineStatus becomes 0 (supposing that it was non 0 after the port has been opened), the port will be closed automatically. Set it to true, for improved fault detection. If you have problems with the port closing itself automatically immediately after open, set this property to false. The default value is true.

Published property SkipSetupFailed: Boolean read FSkipSetupFailed write FSkipSetupFailed default false;

When this property is true, if setting serial parameters like DCB in the Open method fails, will ignore this. Otherwise method Open will return false and the port will not be opened. The default value is false.

Published property PacketSize: LongWord read FPacketSize write FPacketSize;

The size of the packets in bytes you want to receive automatically in the OnReceive event. Use this property, if you want to receive packets of equal size in the OnReceive event. If the value is 0, this property will be ignored. It works only for AutoReceive = true. Default value is 0.

Published property PacketTerminator: boolean read FPacketTerminator write FPacketTerminator;

If true, NewLine property value will be used as a packet terminator in the OnReceive event. OnReceive event will fire only, when it finds the packet terminator in the packet. This will ensure that you receive the packet in one piece. It will ignore the PacketSize property. It will return all the data, including the terminator. If it will not receive NewLine in 60 seconds, then it will return the available data without NewLine in the OnReceive event. It works only for AutoReceive = true. The default value is false.

Published property OnReceive: TSendReceiveEvent read FOnReceive write FOnReceive;

Occurs when data was received. You will get the received data in Buffer, when AutoReceive is true. When AutoReceive is false, Buffer property is empty and you have to read the data with one of the Read methods.

Published property OnSend: TSendReceiveEvent read FOnSend write FOnSend;

Occurs when data was sent.

Published property OnLineStatusChange: TLineStatusEvent read FOnLineStatusChange write FOnLineStatusChange;

Occurs when the line status of the serial port is changed.

Published property OnConnect: TConnectEvent read FOnConnect write FOnConnect;

Occurs after the serial port is connected.

Published property OnDisconnect: TConnectEvent read FOnDisconnect write FOnDisconnect;

Occurs when the serial port is disconnected.

Published property OnFault: TConnectEvent read FOnFault write FOnFault;

Occurs when the serial port communication is faulted. After an OnFault event, the port will be closed automatically. Example: When you unplug an USB device which communicates on a virtual serial port. Do not try to reconnect from the OnFault or OnDisconnect event. Set AutoReconnect property to true, to automatically reconnect after an OnFault event, or use the property IsFaulted, which is automatically set to true after an OnFault event and use a timer which checks periodically this property and reconnect from the OnTimer event when IsFaulted is true. In order to work, set CloseWhenLineStatusIsZero property to true and Interval to a higher value than MinCheckDisconnectedInterval. If it does not work, try to set EnableDtrOnOpen or EnableRtsOnOpen to true, before opening the port.

Published property OnIdle: TNotifyEvent read FOnIdle write FOnIdle;

If the elapsed time from the last receive is higher than IdleInterval (milliseconds), OnIdle event occurs. If IdleTinerval is 0, this event will never occur. It works only for AutoReceive = true.

Published property OnIdleTimeout: TNotifyEvent read FOnIdleTimeout write FOnIdleTimeout;

Occurs when there is no data received in several milliseconds, the interval is specified in the IdleTimeoutInterval property.

Published property OnResume: TNotifyEvent read FOnResume write FOnResume;

Occurs when the receiver is idle and data is received. It works only for AutoReceive = true.

Published property OnDetect: TDetectEvent read FOnDetect write FOnDetect;

Occurs when the serial port detection process is in progress. and there are new values of port or baud rate to be checked.

Published property OnReconnect: TReconnectEvent read FOnReconnect write FOnReconnect;

Occurs when the serial port connection was lost (faulted) and it tries to reconnect. AutoReconnect must be true.

Published property OnError: TErrorEvent read FOnError write FOnError;

Fires when an error occurs. The error will be cleared automatically.

You can sometimes get errors at the beginning of the communication. The problem is probably that you are opening the port while the remote device is in the middle of transmitting. This can cause your serial port to miss-detect the start bit of the data byte, causing corrupted data (framing errors) until there is a gap in the communication and the UART can resynchronize with the next start bit in the data stream.

Copyright © 2003 - 2025 by Zyl Soft. All rights reserved.
Generated by PasDoc 0.16.0.