API Reference

This page contains the complete API reference for libserial, automatically generated from the source code.

Classes

class Serial

A C++ wrapper class for serial port communication.

The Serial class provides a high-level interface for serial port operations on Linux systems. It encapsulates low-level POSIX system calls and provides exception-based error handling for serial communication.

Author

Nestor Pereira Neto

Version

0.0.0

Public Functions

Serial() = default

Default constructor.

Creates a Serial object without opening any port. Use open() method to establish connection. Initializes with default baud rate of 9600.

explicit Serial(const std::string &port)

Constructor with automatic port opening.

Creates a Serial object and immediately opens the specified port.

Parameters:

port – The device path (e.g., “/dev/ttyUSB0”, “/dev/ttyS0”)

Throws:

SerialException – if the port cannot be opened

~Serial() noexcept

Destructor.

Automatically closes the serial port if it’s open, ensuring proper resource cleanup.

void open(const std::string &port)

Opens a serial port for communication.

Parameters:

port – The device path to open (e.g., “/dev/ttyUSB0”)

Throws:
  • SerialException – if the port doesn’t exist or cannot be accessed

  • PermissionDeniedException – if insufficient permissions

void close()

Closes the currently open serial port.

Throws:

SerialException – if an error occurs during closing

void write(std::string_view data)

Writes data to the serial port.

Sends the provided string data to the serial port. The string is sent as-is without any additional formatting or terminators.

Parameters:

data – String view containing the data to write

Throws:

libserial::IOException – if the write operation fails

ssize_t writeRaw(const uint8_t *data, size_t size)

Writes raw byte data to the serial port.

Sends the provided byte data to the serial port without any modification.

Parameters:
  • data – Pointer to the byte data to write

  • size – Number of bytes to write from the buffer pointed to by data

Throws:

libserial::IOException – if the write operation fails

Returns:

Number of bytes actually written

ssize_t writeRaw(const std::vector<uint8_t> &data)

Writes raw byte data to the serial port.

Overloaded version that accepts a vector of bytes. This is a convenience method that simply calls the pointer-based writeRaw after checking for an empty vector.

Parameters:

data – Vector containing the byte data to write

Throws:

libserial::IOException – if the write operation fails

Returns:

Number of bytes actually written

size_t read(std::string &buffer)

Reads data from serial port into a pointer buffer.

Reads up to max_length bytes from the serial port and stores them in the provided string buffer. This version provides better memory management and avoids unnecessary string copies. Just works in canonical mode.

Note

The buffer will be resized to contain exactly the read data

Parameters:

buffer – String where data will be stored

Throws:

libserial::IOException – if the read operation fails

Returns:

Number of bytes actually read

size_t readBytes(std::string &buffer, size_t num_bytes)

Reads a number of bytes from the serial port.

Reads up to num_bytes from the serial port and stores them in the provided string buffer. Just works in non-canonical mode.

Note

The buffer will be resized to contain exactly the read data

Parameters:
  • buffer – String where data will be stored

  • num_bytes – Number of bytes to read

Throws:
  • libserial::IOException – if the read operation fails

  • std::invalid_argument – if buffer is null

  • std::invalid_argument – if num_bytes is zero

Returns:

Number of bytes actually read

size_t readUntil(std::string &buffer, char terminator)

Reads data until a specific terminator character is found.

Continues reading byte by byte until the specified terminator character is encountered. The terminator is included in the result. Works in both canonical and non-canonical modes.

Warning

This method reads one byte at a time and may be slower for large amounts of data

Parameters:
  • buffer – String where data will be stored

  • terminator – The character to stop reading at

Throws:
  • libserial::IOException – if the read operation fails

  • std::invalid_argument – if buffer is null

Returns:

String containing all read data including the terminator

ssize_t readRaw(uint8_t *buffer, size_t size)

Reads raw byte data from the serial port.

Reads up to size bytes of raw data from the serial port into the provided buffer. This method is intended for non-canonical mode.

Parameters:
  • buffer – Byte array where data will be stored

  • size – Maximum number of bytes to read

Throws:

libserial::IOException – if the buffer pointer is null, the size is invalid, or the read operation fails

Returns:

Number of bytes actually read

void flushInputBuffer()

Flushes the input buffer.

Discards any data that has been received but not yet read. Useful for clearing stale data before starting fresh communication.

Throws:

libserial::IOException – if flush operation fails

void setBaudRate(unsigned int baud_rate)

Sets the baud rate for serial communication.

Configures the speed of serial communication. Both input and output speeds are set to the same value.

Note

The port must be opened before calling this method

Parameters:

baud_rate – The desired baud rate (e.g., 9600, 115200)

Throws:

libserial::SerialException – if baud rate cannot be set

int getAvailableData() const

Gets the number of bytes available for reading.

Returns the number of bytes currently available in the input buffer without actually reading them. Useful for non-blocking operations.

Throws:

SerialException – if operation fails

Returns:

Number of bytes available for reading

void setReadTimeout(std::chrono::milliseconds timeout)

Sets the read timeout in milliseconds.

Configures the maximum time to wait for read operations before timing out. A value of 0 means no timeout and -1 means infinite timeout.

Note

The system timeout is set in deciseconds (100ms units), so the value will be rounded down to the nearest multiple of 100ms. For example, 1549ms will be set as 1500ms.

Parameters:

timeout – Timeout in milliseconds

void setWriteTimeout(std::chrono::milliseconds timeout)

Sets the write timeout in milliseconds.

Configures the maximum time to wait for write operations before timing out. A value of 0 means no timeout and -1 means infinite timeout.

Parameters:

timeout – Timeout in milliseconds

Throws:

SerialException – if setting cannot be applied

void setDataLength(DataLength nbits)

Sets the number of data bits per byte.

Configures the number of data bits used in each byte of serial communication.

Parameters:

nbits – The desired number of data bits (5, 6, 7, or 8)

Throws:

SerialException – if number of bits cannot be set

void setParity(Parity parity)

Sets the parity configuration.

Configures the parity checking mechanism for serial communication.

Parameters:

parity – The desired parity setting (ENABLE or DISABLE)

Throws:

SerialException – if parity cannot be set

void setStopBits(StopBits stop_bits)

Sets the stop bits configuration.

Configures the number of stop bits used in serial communication.

Parameters:

stop_bits – The desired stop bits setting (ONE, ONE_AND_HALF, or TWO)

Throws:

SerialException – if stop bits cannot be set

void setFlowControl([[maybe_unused]] FlowControl flow_control)

Sets the flow control configuration.

Configures the flow control mechanism for serial communication.

Parameters:

flow_control – The desired flow control setting (HARDWARE or SOFTWARE)

Throws:

SerialException – if flow control cannot be set

void setCanonicalMode(CanonicalMode mode)

Sets canonical mode for input processing.

Configures whether the input is processed in canonical (line-based) mode or non-canonical (raw) mode.

Parameters:

canonical_mode – The desired canonical mode setting (ENABLE or DISABLE)

Throws:

SerialException – if canonical mode cannot be set

void setTerminator(Terminator term)

Sets the terminator character for readUntil operations.

Configures the character that signals the end of a readUntil operation.

Parameters:

term – The desired terminator character

Throws:

SerialException – if terminator cannot be set

void setTimeOut(uint16_t time)

Sets the read timeout in deciseconds.

Parameters:

time – Timeout in deciseconds

Throws:

SerialException – if setting cannot be applied

void setMinNumberCharRead(uint16_t)

Sets the minimum number of characters to read.

Parameters:

num – Minimum number of characters to read

Throws:

SerialException – if setting cannot be applied

void setBaudRate(BaudRate baud_rate)

Set the baud rate using BaudRate enum.

This overloaded version accepts a BaudRate enum value, providing type safety and preventing invalid baud rate values.

Note

The port must be opened before calling this method

Parameters:

baud_rate – The baud rate from BaudRate enum

Throws:

SerialException – if baud rate cannot be set

void setMaxSafeReadSize(size_t size)

Sets the maximum safe read size.

Configures the maximum number of bytes that can be read in a single read operation to prevent excessive memory usage.

Parameters:

size – The desired maximum safe read size in bytes

size_t getMaxSafeReadSize() const

Gets the maximum safe read size.

Retrieves the maximum number of bytes that can be read in a single read operation to prevent excessive memory usage.

Returns:

The maximum safe read size in bytes

int getBaudRate() const

Gets the current baud rate.

Throws:

SerialException – if unable to retrieve baud rate

Returns:

The current baud rate

DataLength getDataLength() const

Gets the current data length setting.

Retrieves the number of data bits configured for serial communication.

Returns:

The current data length (number of data bits)

std::chrono::milliseconds getReadTimeout() const

Gets the current read timeout setting.

Returns:

The current read timeout in milliseconds

uint16_t getMinNumberCharRead() const

Gets the current minimum number of characters to read setting.

Returns:

The current minimum number of characters to read

class Ports

A class to manage and list available serial ports on the system.

The Ports class provides functionality to scan for available serial ports, retrieve their details, and find specific ports by unique identifiers. It leverages the udev system on Linux to discover connected serial devices.

Author

Nestor Pereira Neto

Public Functions

Ports() = default

Constructor of the Ports class.

~Ports() = default

Destroyer of the Ports class.

uint16_t scanPorts()

Scans the system for available serial ports.

Throws:

SerialException – if no ports are found

Returns:

uint16_t The number of serial ports found

void getDevices(std::vector<Device> &devices) const

Retrieves the list of detected serial devices.

Parameters:

devices – A reference to a vector that will be populated with Device entries for each detected device

Throws:

SerialException – if device list cannot be retrieved

std::optional<std::string> findPortPath(uint16_t id) const

Finds the port path for a device with the specified ID.

Parameters:

id – The unique identifier of the device to search for

Throws:

SerialException – if search operation fails

Returns:

std::optional<std::string> The port path if found, or std::nullopt if not found

std::optional<std::string> findBusPath(uint16_t id) const

Finds the bus path for a device with the specified ID.

Parameters:

id – The unique identifier of the device to search for

Throws:

SerialException – if search operation fails

Returns:

std::optional<std::string> The bus path if found, or std::nullopt if not found

std::optional<std::string> findName(uint16_t id) const

Finds the name for a device with the specified ID.

Parameters:

id – The unique identifier of the device to search for

Throws:

SerialException – if search operation fails

Returns:

std::optional<std::string> The name if found, or std::nullopt if not found

class Device

A class representing a serial device.

The Device class encapsulates the properties of a serial device, including its name, port path, bus path, and unique identifier.

Author

Nestor Pereira Neto

Public Functions

Device() = default

Default constructor of the Device class.

~Device() = default

Default destructor of the Device class.

Device(const std::string &name, const std::string &port_path, const std::string &bus_path, uint16_t id)

Parameterized constructor of the Device class.

With this constructor, you can create a Device instance by providing its name, port path, bus path, and unique identifier.

Parameters:
  • name – The name of the device

  • port_path – The port path of the device

  • bus_path – The bus path of the device

  • id – The unique identifier of the device

std::string getName() const

Retrieves the name of the device.

Returns:

std::string The name of the device

std::string getPortPath() const

Retrieves the port path of the device.

Returns:

std::string The port path of the device

std::string getBusPath() const

Retrieves the bus path of the device.

Returns:

std::string The bus path of the device

uint16_t getId() const

Retrieves the unique identifier of the device.

Returns:

uint16_t The unique identifier of the device

void setName(const std::string &name)

Sets the name of the device.

Parameters:

name – The name to set

void setPortPath(const std::string &port_path)

Sets the port path of the device.

Parameters:

port_path – The port path to set

void setBusPath(const std::string &bus_path)

Sets the bus path of the device.

Parameters:

bus_path – The bus path to set

void setId(uint16_t id)

Sets the unique identifier of the device.

Parameters:

id – The unique identifier to set

Exceptions

class SerialException : public std::exception

Exception class for serial port errors.

The SerialException class is used to represent errors that occur during serial port operations. It inherits from std::exception and provides a descriptive error message.

Author

Nestor Pereira Neto

Subclassed by libserial::IOException, libserial::PermissionDeniedException, libserial::PortNotFoundException, libserial::TimeoutException

Enumerations

enum class libserial::Parity

Enumeration for serial port parity configuration.

Parity is an error-checking mechanism where an extra bit is added to each byte of data to detect transmission errors. The parity bit makes the total number of 1 bits in the byte either even (even parity) or odd (odd parity).

Note

This enum currently provides basic enable/disable functionality. Future versions may include specific parity types (EVEN, ODD, MARK, SPACE).

Values:

enumerator ENABLE

Enable parity checking.

enumerator DISABLE

Disable parity checking.

enum class libserial::StopBits

Enumeration for serial port stop bits configuration.

Stop bits are used to signal the end of a data frame in asynchronous serial communication. Common configurations include 1 stop bit (standard) or 2 stop bits (for slower or noisy communication).

Values:

enumerator ONE

One stop bit.

enumerator TWO

Two stop bits.

enum class libserial::FlowControl

Enumeration for serial port flow control configuration.

Flow control is used to prevent data loss when the receiver cannot keep up with the sender’s transmission rate. It provides mechanisms to pause and resume data transmission.

Values:

enumerator HARDWARE

Hardware flow control (RTS/CTS signals)

enumerator SOFTWARE

Software flow control (XON/XOFF characters)

enum class libserial::CanonicalMode

Enumeration for terminal canonical mode configuration.

Canonical mode (also known as “cooked mode”) controls how input is processed by the terminal driver. In canonical mode, input is line-buffered and processed for special characters (backspace, delete, etc.). In non-canonical mode (raw mode), input is available immediately without line buffering.

Values:

enumerator DISABLE

Disable canonical mode (raw mode, immediate input)

enumerator ENABLE

Enable canonical mode (line-buffered, processed input)

enum class libserial::Terminator

Enumeration for data transmission terminator characters.

Terminator characters are used to mark the end of data frames or messages in serial communication protocols. These characters help the receiver identify message boundaries in continuous data streams.

Values:

enumerator CR

Carriage Return (ASCII 13, ‘\r’)

enumerator LF

Line Feed (ASCII 10, ‘

’)

enum class libserial::BaudRate

Enumeration for serial port baud rate (bits per second) configuration.

Baud rate defines the speed of data transmission in bits per second (bps). This enum class provides type-safe access to standard baud rates commonly used in serial communication. Higher baud rates allow faster data transfer but may be more susceptible to transmission errors over long distances or in noisy environments.

Note

The underlying integer values represent the actual baud rate in bps. These values can be used with system calls that require integer baud rate parameters through static_cast<int>().

Values:

enumerator BAUD_RATE_50

50 bps - Very slow, legacy systems

enumerator BAUD_RATE_75

75 bps - Very slow, legacy systems

enumerator BAUD_RATE_110

110 bps - Slow, legacy systems

enumerator BAUD_RATE_134

134 bps - Slow, legacy systems

enumerator BAUD_RATE_150

150 bps - Slow, legacy systems

enumerator BAUD_RATE_200

200 bps - Slow, legacy systems

enumerator BAUD_RATE_300

300 bps - Slow, early modems

enumerator BAUD_RATE_600

600 bps - Slow, early modems

enumerator BAUD_RATE_1200

1200 bps - Slow, early modems

enumerator BAUD_RATE_1800

1800 bps - Uncommon rate

enumerator BAUD_RATE_2400

2400 bps - Low speed applications

enumerator BAUD_RATE_4800

4800 bps - Low speed applications

enumerator BAUD_RATE_9600

9600 bps - Common default rate

enumerator BAUD_RATE_19200

19200 bps - Medium speed applications

enumerator BAUD_RATE_38400

38400 bps - Medium speed applications

enumerator BAUD_RATE_57600

57600 bps - High speed applications

enumerator BAUD_RATE_115200

115200 bps - Very common high speed rate

enumerator BAUD_RATE_230400

230400 bps - Very high speed applications

enum class libserial::DataLength

Enumeration for serial port data bits configuration.

Data bits define the number of bits used to represent each byte of data in serial communication. Common configurations include 5, 6, 7, or 8 data bits per byte. The choice of data bits affects the range of values that can be transmitted and may need to match between communicating devices.

Values:

enumerator FIVE

5 data bits per byte

enumerator SIX

6 data bits per byte

enumerator SEVEN

7 data bits per byte

enumerator EIGHT

8 data bits per byte