API

For general use, you can create an asynchronous Modbus client using one of the factory functions provided in the tmodbus module and use the functions of the returned AsyncModbusClient instance to interact with a Modbus server.

If your Modbus device uses non-standard function codes or requires special handling, you can create a custom PDU class by inheriting from ModbusClientPDU and implementing the necessary methods. cfr. Vendor functions for more details.

General

tmodbus.create_async_tcp_client(host: str, port: int = 502, *, unit_id: int, timeout: float = 10.0, connect_timeout: float = 10.0, wait_between_requests: float = 0.0, wait_after_connect: float = 0.0, auto_reconnect: bool | AsyncRetrying = True, on_reconnected: Callable[[], Awaitable[None] | None] | None = None, response_retry_strategy: AsyncRetrying | None = None, retry_on_device_busy: bool = True, retry_on_device_failure: bool = False, **connection_kwargs: Any) AsyncModbusClient

Create an asynchronous TCP Modbus client with automatic reconnect and request retry functionality.

Parameters:
  • host – The IP address or hostname of the Modbus server.

  • port – The port number of the Modbus server (default is 502).

  • unit_id – The unit ID to use for requests.

  • timeout – Timeout in seconds, default 10.0s

  • connect_timeout – Timeout for establishing connection, default 10.0s

  • wait_between_requests – Wait time between requests in seconds (default: 0.0s)

  • wait_after_connect – Wait time after connection establishment in seconds (default: 0.0s)

  • auto_reconnect – Whether to automatically reconnect on connection loss (default: True). Can be a custom AsyncRetrying instance when more control is needed.

  • on_reconnected – Callback to be called after a successful reconnection.

  • response_retry_strategy – Retry strategy for handling failed requests (default: None).

  • retry_on_device_busy – Whether to retry on device busy errors (default: True). Can be a custom AsyncRetrying instance when more control is needed.

  • retry_on_device_failure – Whether to retry on device failure errors (default: False). Can be a custom AsyncRetrying instance when more control is needed.

  • connection_kwargs – Additional connection parameters passed to asyncio.open_connection (e.g., SSL context)

Returns:

An instance of AsyncModbusClient configured for TCP transport.

tmodbus.create_async_rtu_client(port: str, *, unit_id: int, wait_between_requests: float = 0.0, wait_after_connect: float = 0.0, auto_reconnect: bool | AsyncRetrying = True, on_reconnected: Callable[[], Awaitable[None] | None] | None = None, response_retry_strategy: AsyncRetrying | None = None, retry_on_device_busy: bool = True, retry_on_device_failure: bool = False, **serialx_options: Unpack[SerialXOptions]) AsyncModbusClient

Create an asynchronous RTU Modbus client with automatic reconnect and request retry functionality.

Parameters:
  • port – The port number of the Modbus server (default is 502).

  • unit_id – The unit ID to use for requests.

  • timeout – Timeout in seconds, default 10.0s

  • connect_timeout – Timeout for establishing connection, default 10.0s

  • wait_between_requests – Wait time between requests in seconds (default: 0.0s)

  • wait_after_connect – Wait time after connection establishment in seconds (default: 0.0s)

  • auto_reconnect – Whether to automatically reconnect on connection loss (default: True). Can be a custom AsyncRetrying instance when more control is needed.

  • on_reconnected – Callback to be called after a successful reconnection.

  • response_retry_strategy – Retry strategy for handling failed requests (default: None).

  • retry_on_device_busy – Whether to retry on device busy errors (default: True). Can be a custom AsyncRetrying instance when more control is needed.

  • retry_on_device_failure – Whether to retry on device failure errors (default: False). Can be a custom AsyncRetrying instance when more control is needed.

  • serialx_options – Additional connection parameters passed to serialx

Returns:

An instance of AsyncModbusClient configured for TCP transport.

tmodbus.create_async_ascii_client(port: str, *, unit_id: int, wait_between_requests: float = 0.0, wait_after_connect: float = 0.0, auto_reconnect: bool | AsyncRetrying = True, on_reconnected: Callable[[], Awaitable[None] | None] | None = None, response_retry_strategy: AsyncRetrying | None = None, retry_on_device_busy: bool = True, retry_on_device_failure: bool = False, **serialx_options: Unpack[SerialXOptions]) AsyncModbusClient

Create an asynchronous ASCII Modbus client with automatic reconnect and request retry functionality.

Parameters:
  • port – The port number of the Modbus server (default is 502).

  • unit_id – The unit ID to use for requests.

  • timeout – Timeout in seconds, default 10.0s

  • connect_timeout – Timeout for establishing connection, default 10.0s

  • wait_between_requests – Wait time between requests in seconds (default: 0.0s)

  • wait_after_connect – Wait time after connection establishment in seconds (default: 0.0s)

  • auto_reconnect – Whether to automatically reconnect on connection loss (default: True). Can be a custom AsyncRetrying instance when more control is needed.

  • on_reconnected – Callback to be called after a successful reconnection.

  • response_retry_strategy – Retry strategy for handling failed requests (default: None).

  • retry_on_device_busy – Whether to retry on device busy errors (default: True). Can be a custom AsyncRetrying instance when more control is needed.

  • retry_on_device_failure – Whether to retry on device failure errors (default: False). Can be a custom AsyncRetrying instance when more control is needed.

  • serialx_options – Additional connection parameters passed to serialx

Returns:

An instance of AsyncModbusClient configured for TCP transport.

tmodbus.create_async_rtu_over_tcp_client(host: str, port: int = 502, *, unit_id: int, timeout: float = 10.0, connect_timeout: float = 10.0, wait_between_requests: float = 0.0, wait_after_connect: float = 0.0, auto_reconnect: bool | AsyncRetrying = True, on_reconnected: Callable[[], Awaitable[None] | None] | None = None, response_retry_strategy: AsyncRetrying | None = None, retry_on_device_busy: bool = True, retry_on_device_failure: bool = False, **connection_kwargs: Any) AsyncModbusClient

Create an asynchronous RTU over TCP Modbus client with automatic reconnect and request retry functionality.

Parameters:
  • host – The IP address or hostname of the Modbus server.

  • port – The port number of the Modbus server (default is 502).

  • unit_id – The unit ID to use for requests.

  • timeout – Timeout in seconds, default 10.0s

  • connect_timeout – Timeout for establishing connection, default 10.0s

  • wait_between_requests – Wait time between requests in seconds (default: 0.0s)

  • wait_after_connect – Wait time after connection establishment in seconds (default: 0.0s)

  • auto_reconnect – Whether to automatically reconnect on connection loss (default: True). Can be a custom AsyncRetrying instance when more control is needed.

  • on_reconnected – Callback to be called after a successful reconnection.

  • response_retry_strategy – Retry strategy for handling failed requests (default: None).

  • retry_on_device_busy – Whether to retry on device busy errors (default: True). Can be a custom AsyncRetrying instance when more control is needed.

  • retry_on_device_failure – Whether to retry on device failure errors (default: False). Can be a custom AsyncRetrying instance when more control is needed.

  • connection_kwargs – Additional connection parameters passed to asyncio.open_connection (e.g., SSL context)

Returns:

An instance of AsyncModbusClient configured for RTU over TCP transport.

Client layer

The AsyncModbusClient class provides methods to interact with a Modbus server. It supports reading and writing coils, discrete inputs, holding registers, and input registers. It inherits from two mixins: HoldingRegisterReadMixin and HoldingRegisterWriteMixin, which provide additional methods for reading and writing structured data from/to holding registers.

tModbus Clients.

class tmodbus.client.AsyncModbusClient(transport: AsyncBaseTransport, *, unit_id: int, word_order: Literal['big', 'little'] = 'big', byte_order: Literal['big', 'little'] = 'big')

Bases: HoldingRegisterReadMixin, HoldingRegisterWriteMixin

Asynchronous Modbus Client.

Provides an user-friendly asynchronous Modbus interface to a single Modbus device. All methods use Python native data types (int, float, str, list, etc.),

If you want to query another device on the same connection, use the for_unit_id method.

This class is agnostic to the transport layer: just pass the desired transport instance.

Example

>>> import asyncio
>>> from tmodbus import AsyncModbusClient, AsyncTcpTransport
>>> async def main():
...     transport = AsyncTcpTransport('localhost', 502)
...     client = AsyncModbusClient(transport, unit_id=1)
...     async with client:
...         print("Contents of register 0:", await client.read_holding_registers(0, 1))
...
>>> asyncio.run(main())

Initialize Async Modbus Client.

The combination of word_order and byte_order determines the final byte ordering:

Byte Order Combinations (for a 32-bit value 0x0A0B0C0D):
  • word_order=”big”, byte_order=”big”: ABCD → 0x0A 0x0B 0x0C 0x0D (standard Modbus)

  • word_order=”big”, byte_order=”little”: BADC → 0x0B 0x0A 0x0D 0x0C (byte-swapped)

  • word_order=”little”, byte_order=”big”: CDAB → 0x0C 0x0D 0x0A 0x0B (word-swapped)

  • word_order=”little”, byte_order=”little”: DCBA → 0x0D 0x0C 0x0B 0x0A (full little-endian)

Parameters:
  • transport – Async transport layer instance (AsyncTcpTransport, etc.)

  • unit_id – Unit ID of the Modbus device

  • word_order – Word order for multi-register values (‘big’ or ‘little’). - ‘big’: Most significant register first (standard Modbus) - ‘little’: Least significant register first

  • byte_order – Byte order within each register (‘big’ or ‘little’). - ‘big’: Most significant byte first within each register (standard Modbus) - ‘little’: Least significant byte first within each register

async connect() None

Connect to the server.

property connected: bool

Report if the client is connected to the server.

async disconnect() None

Close the server connection.

async execute(pdu: BaseClientPDU[RT]) RT

Execute PDU Request.

Parameters:

pdu – Modbus PDU instance

Returns:

Response PDU bytes

Raises:

InvalidResponseError – If response is invalid or does not match request

for_unit_id(unit_id: int) AsyncModbusClient

Create a new client instance for a different unit ID, but using the same connection.

Parameters:

unit_id – The unit ID for the new client instance.

Returns:

A new instance of AsyncModbusClient configured for the specified unit ID.

async mask_write_register(address: int, and_mask: int, or_mask: int) tuple[int, int]

Mask Write Register (Function Code 0x16).

Parameters:
  • address – Register address

  • and_mask – AND mask (16-bit)

  • or_mask – OR mask (16-bit)

Returns:

A tuple with the AND and OR masks that were written.

Example

>>> await client.mask_write_register(0, 0xFF00, 0x00FF)
async read_coils(start_address: int, quantity: int) list[bool]

Read Coil Status (Function Code 0x01).

Parameters:
  • start_address – Starting address

  • quantity – Quantity to read (1-2000)

Returns:

List of coil status, True for ON, False for OFF

Raises:

InvalidResponseError – If response is invalid or does not match request

Example

>>> coils = await client.read_coils(1, 0, 8)
[True, False, True, False, False, False, True, False]
async read_device_identification(device_code: Literal[1, 2, 3, 4], object_id: int) dict[int, bytes]

Read Device Identification (Function Code 0x2B/0x0E).

Parameters:
  • device_code – Device code (0x01 for Basic, 0x02 for Regular, 0x03 for Extended, 0x04 for Specific)

  • object_id – Object ID to start reading from (0x00 to 0xFF)

Returns:

A dictionary mapping object IDs to their corresponding string values.

Example

>>> device_info = await client.read_device_identification(1, 0)
{0: 'VendorName', 1: 'ProductCode', ...}
async read_discrete_inputs(start_address: int, quantity: int) list[bool]

Read Discrete Inputs (Function Code 0x02).

Parameters:
  • start_address – Starting address

  • quantity – Quantity to read (1-2000)

Returns:

List of coil status, True for ON, False for OFF

Example

>>> coils = await client.read_coils(1, 0, 8)
[True, False, True, False, False, False, True, False]
async read_exception_status() int

Read Exception Status (Function Code 0x07).

Returns:

The exception status as an integer (0-255).

Example

>>> status = await client.read_exception_status()
>>> print("Exception Status:", status)
async read_fifo_queue(address: int) list[int]

Read FIFO Queue (Function Code 0x18).

Parameters:

address – Address of the FIFO queue to read

Returns:

List of register values in the FIFO queue, each value is a 16-bit unsigned integer (0-65535)

Example

>>> fifo_values = await client.read_fifo_queue(0)  # Read FIFO queue at address 0
[100, 200, 300, 400]
async read_holding_registers(start_address: int, quantity: int) list[int]

Read Holding Registers (Function Code 0x03).

Parameters:
  • start_address – Starting address

  • quantity – Quantity to read (1-125)

Returns:

List of register values, each value is a 16-bit unsigned integer (0-65535)

Example

>>> registers = await client.read_holding_registers(0, 4)  # Read holding registers 0, 1, 2, 3
[1234, 5678, 9012, 3456]
async read_input_registers(start_address: int, quantity: int) list[int]

Read Input Registers (Function Code 0x04).

Parameters:
  • start_address – Starting address

  • quantity – Quantity to read (1-125)

Returns:

List of register values, each value is a 16-bit unsigned integer (0-65535)

Example

>>> registers = await client.read_input_registers(0, 4) # Read input registers 0, 1, 2, 3
[1234, 5678, 9012, 3456]
async read_server_id() ServerIdResponse

Read Server ID (Function Code 0x11).

Returns:

An instance of ServerIdResponse containing the server ID and run indicator status.

Example

>>> response = await client.read_server_id()
>>> print("Server ID:", response.server_id)
>>> print("Run Indicator Status:", response.run_indicator_status)
async read_write_multiple_registers(read_start_address: int, read_quantity: int, write_start_address: int, write_values: list[int]) list[int]

Read/Write Multiple Registers (Function Code 0x17).

Parameters:
  • read_start_address – Starting address to read from

  • read_quantity – Quantity of registers to read (1-125)

  • write_start_address – Starting address to write to

  • write_values – List of register values to write, each value 0-65535

Returns:

A list of register values read from the device.

Example

>>> await client.read_write_multiple_registers(0, 1, 0, [1234])
async write_multiple_coils(start_address: int, values: list[bool]) int

Write Multiple Coils (Function Code 0x0F).

Parameters:
  • start_address – Starting address

  • values – List of coil values, True for ON, False for OFF

Returns:

The number of coils that have been written to.

Example

>>> await client.write_multiple_coils(0, [True, False, True, False])
async write_multiple_registers(start_address: int, values: list[int]) int

Write Multiple Registers (Function Code 0x10).

Parameters:
  • start_address – Starting address

  • values – List of register values, each value 0-65535

Returns:

The number of registers that have been written to.

Example

>>> await client.write_multiple_registers(0, [1234, 5678, 9012])
async write_single_coil(address: int, value: bool) int

Write Single Coil (Function Code 0x05).

Parameters:
  • address – Coil address

  • value – Coil value (True for ON, False for OFF)

Returns:

The value that was written

Example

>>> await client.write_single_coil(0, True)  # Write ON to coil 0
async write_single_register(address: int, value: int) int

Write Single Register (Function Code 0x06).

Parameters:
  • address – Register address

  • value – Register value (0-65535)

Returns:

the value that was written

Example

>>> await client.write_single_register(0, 1234)  # Write 1234 to register 0
class tmodbus.pdu.holding_registers_struct.HoldingRegisterReadMixin(word_order: Literal['big', 'little'] = 'big', byte_order: Literal['big', 'little'] = 'big')

Mixin for holding register read operations.

Initialize the mixin.

The combination of word_order and byte_order determines the final byte ordering:

Byte Order Combinations (for a 32-bit value 0x0A0B0C0D):
  • word_order=”big”, byte_order=”big”: ABCD → 0x0A 0x0B 0x0C 0x0D (standard Modbus)

  • word_order=”big”, byte_order=”little”: BADC → 0x0B 0x0A 0x0D 0x0C (byte-swapped)

  • word_order=”little”, byte_order=”big”: CDAB → 0x0C 0x0D 0x0A 0x0B (word-swapped)

  • word_order=”little”, byte_order=”little”: DCBA → 0x0D 0x0C 0x0B 0x0A (full little-endian)

Parameters:
  • word_order – Word order for multi-register values (‘big’ or ‘little’). - ‘big’: Most significant register first (standard Modbus) - ‘little’: Least significant register first

  • byte_order – Byte order within each register (‘big’ or ‘little’). - ‘big’: Most significant byte first within each register (standard Modbus) - ‘little’: Least significant byte first within each register

async read_float(start_address: int, *, input_register: bool = False) float

Read holding registers and decode them as a float.

A float is 4 bytes wide (2 registers).

Parameters:
  • start_address – Starting address of the registers to read.

  • input_register – Whether to read holding registers (False) or input registers (True).

Returns:

Decoded float value.

async read_int16(start_address: int, *, input_register: bool = False) int

Read holding registers and decode them as a signed 16-bit integer.

A signed 16-bit integer is 2 bytes wide (1 register).

Parameters:
  • start_address – Starting address of the registers to read.

  • input_register – Whether to read holding registers (False) or input registers (True).

Returns:

Decoded signed 16-bit integer.

async read_int32(start_address: int, *, input_register: bool = False) int

Read holding registers and decode them as a signed 32-bit integer.

A signed 32-bit integer is 4 bytes wide (2 registers).

Parameters:
  • start_address – Starting address of the registers to read.

  • input_register – Whether to read holding registers (False) or input registers (True).

Returns:

Decoded signed 32-bit integer.

async read_int64(start_address: int, *, input_register: bool = False) int

Read holding registers and decode them as a signed 64-bit integer.

A signed 64-bit integer is 8 bytes wide (4 registers).

Parameters:
  • start_address – Starting address of the registers to read.

  • input_register – Whether to read holding registers (False) or input registers (True).

Returns:

Decoded signed 64-bit integer.

async read_simple_struct_format(start_address: int, *, format_struct: Struct | str, input_register: bool = False) Any

Read holding registers and decode them as a single value using the provided struct format.

Parameters:
  • struct_format – Struct format to decode the response

  • start_address – Starting address of the registers to read

  • format_struct – Struct format to decode the response

  • input_register – Whether to read holding registers (False) or input registers (True)

Returns:

Decoded response data as a single value

async read_string(start_address: int, *, number_of_registers: int, input_register: bool = False, encoding: str = 'ascii') str

Read holding registers and decode them as a string.

Parameters:
  • start_address – Starting address of the registers to read.

  • length – Length of the string to decode.

  • number_of_registers – Number of registers to read.

  • input_register – Whether to read holding registers (False) or input registers (True).

  • encoding – Encoding format for the string (default is “ascii”).

Returns:

Decoded string value.

async read_struct_format(start_address: int, *, format_struct: Struct | str, input_register: bool = False) tuple[Any, ...]

Read holding registers and decode them using the provided struct format.

Parameters:
  • start_address – Starting address of the registers to read

  • format_struct – Struct format to decode the response

  • input_register – Whether to read holding registers (False) or input registers (True)

Returns:

Decoded response data using the provided struct format

async read_uint16(start_address: int, *, input_register: bool = False) int

Read holding registers and decode them as an unsigned 16-bit integer.

An unsigned 16-bit integer is 2 bytes wide (1 register).

Parameters:
  • start_address – Starting address of the registers to read.

  • input_register – Whether to read holding registers (False) or input registers (True).

Returns:

Decoded unsigned 16-bit integer.

async read_uint32(start_address: int, *, input_register: bool = False) int

Read holding registers and decode them as an unsigned 32-bit integer.

An unsigned 32-bit integer is 4 bytes wide (2 registers).

Parameters:
  • start_address – Starting address of the registers to read.

  • input_register – Whether to read holding registers (False) or input registers (True).

Returns:

Decoded unsigned 32-bit integer.

async read_uint64(start_address: int, *, input_register: bool = False) int

Read holding registers and decode them as an unsigned 64-bit integer.

An unsigned 64-bit integer is 8 bytes wide (4 registers).

Parameters:
  • start_address – Starting address of the registers to read.

  • input_register – Whether to read holding registers (False) or input registers (True).

Returns:

Decoded unsigned 64-bit integer.

class tmodbus.pdu.holding_registers_struct.HoldingRegisterWriteMixin(word_order: Literal['big', 'little'] = 'big', byte_order: Literal['big', 'little'] = 'big')

Mixin for holding register write operations.

Initialize the mixin.

The combination of word_order and byte_order determines the final byte ordering:

Byte Order Combinations (for a 32-bit value 0x0A0B0C0D):
  • word_order=”big”, byte_order=”big”: ABCD → 0x0A 0x0B 0x0C 0x0D (standard Modbus)

  • word_order=”big”, byte_order=”little”: BADC → 0x0B 0x0A 0x0D 0x0C (byte-swapped)

  • word_order=”little”, byte_order=”big”: CDAB → 0x0C 0x0D 0x0A 0x0B (word-swapped)

  • word_order=”little”, byte_order=”little”: DCBA → 0x0D 0x0C 0x0B 0x0A (full little-endian)

Parameters:
  • word_order – Word order for multi-register values (‘big’ or ‘little’). - ‘big’: Most significant register first (standard Modbus) - ‘little’: Least significant register first

  • byte_order – Byte order within each register (‘big’ or ‘little’). - ‘big’: Most significant byte first within each register (standard Modbus) - ‘little’: Least significant byte first within each register

async write_double(address: int, value: float) Any

Write a double to holding registers.

A double is 4 holding registers wide.

Parameters:
  • address – Address of the register to write.

  • value – Float value to write.

Returns:

None

async write_float(address: int, value: float) Any

Write a float to holding registers.

A float is 2 holding registers wide.

Parameters:
  • address – Address of the register to write.

  • value – Float value to write.

Returns:

None

async write_int16(address: int, value: int) Any

Write a signed 16-bit integer to holding registers.

A signed 16-bit integer is 1 holding register wide.

Parameters:
  • address – Address of the register to write.

  • value – Signed 16-bit integer value to write.

Returns:

None

async write_int32(address: int, value: int) Any

Write a signed 32-bit integer to holding registers.

A signed 32-bit integer is 2 holding registers wide.

Parameters:
  • address – Address of the register to write.

  • value – Signed 32-bit integer value to write.

Returns:

None

async write_int64(address: int, value: int) Any

Write a signed 64-bit integer to holding registers.

A signed 64-bit integer is 4 holding registers wide.

Parameters:
  • address – Address of the register to write.

  • value – Signed 64-bit integer value to write.

Returns:

None

async write_simple_struct_format(address: int, value: Any, *, format_struct: Struct | str) Any

Write a single value to holding registers using the provided struct format.

Parameters:
  • address – Address of the register to write.

  • value – Value to encode and write.

  • format_struct – Struct format to encode the value.

Returns:

None

async write_string(start_address: int, value: str, *, number_of_registers: int, encoding: str = 'ascii') Any

Write a string to holding registers.

Parameters:
  • start_address – Starting address of the registers to write.

  • value – String value to write.

  • number_of_registers – Number of registers to write.

  • encoding – Encoding format for the string (default is “ascii”).

Returns:

None

async write_struct_format(start_address: int, values: tuple[Any, ...], *, format_struct: Struct | str) int

Write holding registers using the provided struct format.

Parameters:
  • start_address – Starting address of the registers to write

  • values – Values to encode and write

  • format_struct – Struct format to encode the values

Returns:

The number of registers that have been written.

async write_uint16(address: int, value: int) Any

Write an unsigned 16-bit integer to holding registers.

An unsigned 16-bit integer is 1 holding register wide.

Parameters:
  • address – Address of the register to write.

  • value – Unsigned 16-bit integer value to write.

Returns:

None

async write_uint32(address: int, value: int) Any

Write an unsigned 32-bit integer to holding registers.

An unsigned 32-bit integer is 2 holding registers wide.

Parameters:
  • address – Address of the register to write.

  • value – Unsigned 32-bit integer value to write.

Returns:

None

async write_uint64(address: int, value: int) Any

Write an unsigned 64-bit integer to holding registers.

An unsigned 64-bit integer is 4 holding registers wide.

Parameters:
  • address – Address of the register to write.

  • value – Unsigned 64-bit integer value to write.

Returns:

None

Transport layer

Transport layer.

class tmodbus.transport.AsyncAsciiTransport(port: str, *, timeout: float | None = None, **serialx_options: Unpack[SerialXOptions])

Async Modbus ASCII Transport Layer Implementation.

Handles async Modbus Serial communication using the ASCII framing, LRC checking, and timeouts.

Initialize async Serial transport layer for ASCII.

Parameters:
  • port – Target serial port (e.g., ‘/dev/ttyUSB0’)

  • timeout – Optional timeout for connection and response operations (in seconds)

  • serialx_options – Additional SerialX options like baudrate, parity, stopbits, etc.

async close() None

Close Serial connection.

is_open() bool

Check Serial connection status.

async open() None

Establish Serial connection.

async send_and_receive(unit_id: int, pdu: BaseClientPDU[RT]) RT

Async send PDU and receive response.

Parameters:
  • unit_id – Unit identifier (slave address)

  • pdu – PDU object to send

class tmodbus.transport.AsyncBaseTransport

Transport Layer Base Class.

All transport layer implementations (RTU, TCP, etc.) must inherit from this class and implement all abstract methods. This design completely encapsulates complexities such as CRC verification and MBAP header processing within the transport layer, providing a unified and concise interface for clients.

abstractmethod async close() None

Close Transport Connection.

Closes connection with Modbus device and releases related resources.

abstractmethod is_open() bool

Check Connection Status.

Returns:

True if connection is established and available, False otherwise

abstractmethod async open() None

Open Transport Connection.

Establishes connection with Modbus device. For serial port, opens the port; for TCP, establishes socket connection.

Raises:

ConnectionError – When connection cannot be established

abstractmethod async send_and_receive(unit_id: int, pdu: BaseClientPDU[RT]) RT

Send PDU and Receive Response.

This is the core method of the transport layer. It receives pure PDU (Protocol Data Unit), is responsible for adding necessary transport layer information (such as RTU address and CRC, or TCP MBAP header), sends requests, receives responses, verifies response integrity, and then returns the PDU part of the response.

Parameters:
  • unit_id – Slave address/unit identifier

  • pdu – Protocol Data Unit, contains function code and data, excludes address and checksum

Returns:

PDU part of response with transport layer information removed

Raises:
class tmodbus.transport.AsyncRtuOverTcpTransport(host: str, port: int = 502, *, timeout: float = 10.0, connect_timeout: float = 10.0, **connection_kwargs: Any)

Async Modbus RTU over TCP Transport Layer Implementation.

Handles async Modbus RTU over TCP communication, combining: - TCP connection management (like AsyncTcpTransport) - RTU framing with CRC-16 validation (like AsyncRtuTransport)

This transport is used for serial-to-Ethernet converters that forward RTU frames over TCP without converting them to Modbus TCP format.

Initialize async RTU over TCP transport layer.

Parameters:
  • host – Target host IP address or domain name

  • port – Target port, default 502 (Modbus TCP standard port)

  • timeout – Timeout in seconds for read/write operations, default 10.0s

  • connect_timeout – Timeout for establishing connection, default 10.0s

  • connection_kwargs – Additional connection parameters passed to asyncio.open_connection

Raises:

ValueError – When parameters are invalid

async close() None

Close RTU/TCP connection.

is_open() bool

Check RTU/TCP connection status.

async open() None

Establish TCP connection.

async send_and_receive(unit_id: int, pdu: BaseClientPDU[RT]) RT

Async send PDU and receive response.

Parameters:
  • unit_id – Unit identifier (slave address)

  • pdu – PDU object to send

class tmodbus.transport.AsyncRtuTransport(port: str, *, timeout: float | None = None, **serialx_options: Unpack[SerialXOptions])

Async Modbus Serial Transport Layer Implementation.

Handles async Modbus Serial communication based on asyncio, including: - Async Serial port connection management - RTU frame construction and parsing - CRC validation - Async error handling and timeout management

Initialize async Serial transport layer.

Parameters:
  • port – Target serial port (e.g., ‘/dev/ttyUSB0’)

  • timeout – Timeout in seconds, default 10.0 seconds

  • serialx_options – Additional SerialX options like baudrate, parity, stopbits, etc.

Raises:
async close() None

Close Serial connection.

is_open() bool

Check Serial connection status.

async open() None

Establish Serial connection.

async send_and_receive(unit_id: int, pdu: BaseClientPDU[RT]) RT

Async send PDU and receive response.

Parameters:
  • unit_id – Unit identifier (slave address)

  • pdu – PDU object to send

class tmodbus.transport.AsyncSmartTransport(base_transport: AsyncBaseTransport, *, wait_between_requests: float = 0.0, wait_after_connect: float = 0.0, auto_reconnect: bool | AsyncRetrying = True, on_reconnected: Callable[[], Awaitable[None] | None] | None = None, response_retry_strategy: AsyncRetrying | None = None, retry_on_device_busy: bool = True, retry_on_device_failure: bool = False)

Smart Transport Layer.

This transport layer is built on top of RTU or TCP transport layers, adding features such as wait time between requests, wait time after connection, and automatic reconnection on connection loss.

Initialize Smart Transport Layer.

Parameters:
  • base_transport – Underlying transport layer instance (AsyncRtuTransport, AsyncTcpTransport, etc.)

  • wait_between_requests – Wait time between requests in seconds (default: 0.0s)

  • wait_after_connect – Wait time after connection establishment in seconds (default: 0.0s)

  • auto_reconnect – Whether to automatically reconnect on connection loss (default: True). Can be a custom AsyncRetrying instance when more control is needed.

  • on_reconnected – Callback to be called after a successful reconnection.

  • response_retry_strategy – Retry strategy for handling failed requests (default: None).

  • retry_on_device_busy – Whether to retry on device busy errors (default: True). Can be a custom AsyncRetrying instance when more control is needed.

  • retry_on_device_failure – Whether to retry on device failure errors (default: False). Can be a custom AsyncRetrying instance when more control is needed.

async close() None

Close Transport Connection.

Closes connection with Modbus device and releases related resources.

is_open() bool

Check Connection Status.

Returns:

True if connection was established and should still be available. False otherwise.

async open() None

Open Transport Connection.

Establishes connection with Modbus device and waits for the specified time to allow the device to be ready.

Raises:

ConnectionError – When connection cannot be established

async send_and_receive(unit_id: int, pdu: BaseClientPDU[RT]) RT

Send PDU and Receive Response.

class tmodbus.transport.AsyncTcpTransport(host: str, port: int = 502, *, timeout: float = 10.0, connect_timeout: float = 10.0, **connection_kwargs: Any)

Async Modbus TCP Transport Layer Implementation.

Handles async Modbus TCP communication based on asyncio, including: - Async TCP socket connection management - MBAP header construction and parsing - Transaction identifier management - Async error handling and timeout management

Initialize async TCP transport layer.

Parameters:
  • host – Target host IP address or domain name

  • port – Target port, default 502 (Modbus TCP standard port)

  • timeout – Timeout in seconds, default 10.0s

  • connect_timeout – Timeout for establishing connection, default 10.0s

  • connection_kwargs – Additional connection parameters passed to asyncio.create_connection (e.g., SSL context)

Raises:
async close() None

Close TCP connection.

is_open() bool

Check if TCP connection is open.

async open() None

Async establish TCP connection.

async send_and_receive(unit_id: int, pdu: BaseClientPDU[RT]) RT

Async send PDU and receive response.

Parameters:
  • unit_id – Unit identifier (slave address)

  • pdu – PDU object to send

PDU layer

Modbus Protocol Data Unit (PDU).

class tmodbus.pdu.BaseClientPDU

Base class that defines the functions needed to handle Modbus PDUs on the client-side.

abstractmethod decode_response(response: bytes) RT

Decode the response PDU.

Parameters:

response – Response PDU bytes

Returns:

Decoded response data, type depends on the specific PDU implementation

abstractmethod encode_request() bytes

Convert PDU to bytes.

This method should be implemented by subclasses to convert the PDU into a byte representation suitable for transmission.

classmethod get_expected_response_data_length(data: bytes) int | None

Get the expected number of bytes for the data part of the response PDU.

This method should be implemented by subclasses to return the expected length of the response based on the specific PDU type.

Returns:

Expected length of the response PDU in bytes, or None if it cannot be determined yet.

class tmodbus.pdu.BasePDU

Base class that defines the functions needed to handle Modbus PDUs on both the client-side and server-side.

abstractmethod classmethod decode_request(request: bytes) Self

Create an instance of this PDU from a request byte sequence.

abstractmethod encode_response(value: RT) bytes

Convert the response value to bytes.

Parameters:

value – The value to encode in the response

Returns:

Bytes representation of the response PDU

classmethod get_expected_request_data_length(data: bytes) int

Get the expected number of bytes for the data part of the request PDU.

This method should be implemented by subclasses to return the expected length of the request based on the specific PDU type.

Returns:

Expected length of the request PDU in bytes

class tmodbus.pdu.BaseSubFunctionClientPDU

Extends the BaseClientPDU to include sub-function code.

Only the get_expected_response_data_length method is changed in this class.

classmethod get_expected_response_data_length(data: bytes) int | None

Get the expected number of bytes for the data part of the response PDU.

This method should be implemented by subclasses to return the expected length of the response based on the specific PDU type.

Returns:

Expected length of the response PDU in bytes, or None if it cannot be determined yet.

class tmodbus.pdu.BaseSubFunctionPDU

Extends the BaseServerPDU to include sub-function code.

Only the get_expected_response_data_length method is changed in this class.

classmethod get_expected_request_data_length(data: bytes) int

Get the expected number of bytes for the data part of the request PDU.

This method should be implemented by subclasses to return the expected length of the request based on the specific PDU type.

Returns:

Expected length of the request PDU in bytes

classmethod get_expected_response_data_length(data: bytes) int | None

Get the expected number of bytes for the data part of the response PDU.

This method should be implemented by subclasses to return the expected length of the response based on the specific PDU type.

Returns:

Expected length of the response PDU in bytes

class tmodbus.pdu.FileRecord(file_number: int, record_number: int, data: bytes)

Data structure for Write File Record response.

class tmodbus.pdu.FileRecordRequest(file_number: int, record_number: int, record_length: int)

Data structure for a single file record request.

class tmodbus.pdu.MaskWriteRegisterPDU(address: int, and_mask: int, or_mask: int)

Mask Write Register PDU.

Initialize Mask Write Register PDU.

Parameters:
  • address – Address of the register to write

  • and_mask – AND mask to apply

  • or_mask – OR mask to apply

Raises:

ValueError – If address or masks are invalid

classmethod decode_request(request: bytes) Self

Decode Mask Write Register Request PDU.

Parameters:

request – The request bytes.

Returns:

MaskWriteRegisterPDU instance created from the request.

Raises:

InvalidRequestError – If request format is invalid

decode_response(response: bytes) tuple[int, int]

Decode the response PDU.

Parameters:

response – Response PDU bytes

Returns:

Tuple of AND and OR masks applied

Raises:

InvalidResponseError – If response format is invalid

encode_request() bytes

Convert PDU to bytes.

Returns:

Bytes representation of the Mask Write Register PDU

encode_response(value: tuple[int, int]) bytes

Encode the response PDU.

Parameters:

value – Tuple of (and_mask, or_mask) that were applied.

Returns:

Bytes representation of the Mask Write Register response PDU.

class tmodbus.pdu.ReadCoilsPDU(start_address: int, quantity: int)

Read Coils PDU.

Initialize Read Coils PDU.

Parameters:
  • start_address – Starting address of the coils to read

  • quantity – Number of coils to read

Raises:

ValueError – If start_address or quantity is invalid

classmethod decode_request(request: bytes) Self

Decode Read Coils Request PDU.

Parameters:

request – the request bytes.

Returns:

The decoded Read Coils Request PDU.

Return type:

ReadCoilsPDU

decode_response(response: bytes) list[bool]

Decode the response PDU.

Parameters:

response – Response PDU bytes

Returns:

List of boolean values representing the coil states

Raises:

ValueError – If response format is invalid

encode_request() bytes

Convert PDU to bytes.

Returns:

Bytes representation of the Read Coils PDU

encode_response(value: list[bool]) bytes

Convert PDU to bytes.

Parameters:

value – List of boolean values representing the coil states

Returns:

Bytes representation of the Read Coils Response PDU

class tmodbus.pdu.ReadDeviceIdentificationPDU(read_device_id_code: Literal[1, 2, 3, 4], object_id: int)

Modbus Request to read a device identifier.

decode_response(response: bytes) ReadDeviceIdentificationResponse

Decode Device Identifier PDU response.

encode_request() bytes

Encode ReadDeviceIdentifierPDU.

classmethod get_expected_response_data_length(data: bytes) int | None

Get the expected number of bytes for the data part of the response PDU.

Returns:

Expected length of the response PDU in bytes, or None if it cannot be determined yet.

class tmodbus.pdu.ReadDeviceIdentificationResponse(device_id_code: Literal[1, 2, 3, 4], conformity_level: ConformityLevel, more: bool, next_object_id: int, number_of_objects: int, objects: dict[int, bytes])

Contents of the ReadDeviceInfo response.

class tmodbus.pdu.ReadDiscreteInputsPDU(start_address: int, quantity: int)

Read Discrete Inputs PDU.

Initialize Read Coils PDU.

Parameters:
  • start_address – Starting address of the coils to read

  • quantity – Number of coils to read

Raises:

ValueError – If start_address or quantity is invalid

class tmodbus.pdu.ReadExceptionStatusPDU

Read Exception Status PDU (Function Code 0x07).

classmethod decode_request(data: bytes) ReadExceptionStatusPDU

Decode Read Exception Status request PDU.

Parameters:

data – Request PDU data as bytes

Returns:

Decoded ReadExceptionStatus instance

Raises:

ValueError – If data length is incorrect

decode_response(data: bytes) int

Decode Read Exception Status response PDU.

Parameters:

data – Response PDU data as bytes

Returns:

Decoded exception status (0-255)

Raises:

ValueError – If data length is incorrect

encode_request() bytes

Encode Read Exception Status request PDU.

Returns:

Encoded request PDU as bytes

encode_response(status: int) bytes

Encode Read Exception Status response PDU.

Parameters:

status – Exception status (0-255)

Returns:

Encoded response PDU as bytes

Raises:

ValueError – If status is out of range

class tmodbus.pdu.ReadFifoQueuePDU(address: int, function_code: int = FunctionCode.READ_FIFO_QUEUE)

Read FIFO Queue PDU (Function Code 0x18).

classmethod decode_request(data: bytes) Self

Decode Read FIFO Queue request PDU.

Parameters:

data – Request PDU data as bytes

Returns:

Decoded ReadFifoQueuePDU instance

Raises:

ValueError – If data length is incorrect

decode_response(data: bytes) list[int]

Decode Read FIFO Queue response PDU.

Parameters:

data – Response PDU data as bytes

Returns:

List of values from the FIFO queue

Raises:

ValueError – If data length is incorrect or count doesn’t match values

encode_request() bytes

Encode Read FIFO Queue request PDU.

Returns:

Encoded request PDU as bytes

encode_response(values: list[int]) bytes

Encode Read FIFO Queue response PDU.

Parameters:

values – List of values from the FIFO queue

Returns:

Encoded response PDU as bytes

Raises:

ValueError – If count or values are out of range

class tmodbus.pdu.ReadFileRecordPDU(requests: list[FileRecordRequest])

PDU for Read File Record (function code 0x14).

Initialize ReadFileRecordPDU.

Parameters:

requests – List of FileRecordRequest instances to request.

Raises:

InvalidRequestError – If any record is invalid.

classmethod decode_request(request: bytes) Self

Decode the request PDU.

Parameters:

request – Bytes to decode.

Returns:

List of FileRecordRequest instances as requested.

Raises:

InvalidRequestError – If the request is invalid.

decode_response(response: bytes) list[bytes]

Decode the response PDU.

Parameters:

response – Bytes to decode.

Returns:

every entry corresponds to a requested record.

Return type:

List of bytes

Raises:

InvalidResponseError – If the response is invalid.

encode_request() bytes

Encode the PDU into bytes.

Returns:

Encoded bytes of the PDU.

encode_response(file_records: list[bytes]) bytes

Encode the response PDU.

Returns:

Encoded bytes of the PDU.

class tmodbus.pdu.ReadHoldingRegistersPDU(start_address: int, quantity: int)

Read Holding Register PDU.

Initialize Read Holding Registers PDU.

Parameters:
  • start_address – Starting address of the registers to read

  • quantity – Number of registers to read

Raises:

ValueError – If start_address or quantity is invalid

classmethod decode_request(request: bytes) Self

Decode Read Holding Registers Request PDU.

Parameters:

request – The request bytes.

Returns:

ReadHoldingRegistersPDU instance created from the request.

decode_response(response: bytes) list[int]

Decode the response PDU.

Parameters:

response – Response PDU bytes

Returns:

List of integers representing the register values

Raises:

ValueError – If response format is invalid

encode_request() bytes

Convert PDU to bytes.

Returns:

Bytes representation of the Read Holding Registers PDU

encode_response(value: list[int]) bytes

Encode the response PDU with register values.

Parameters:

value – List of register values (unsigned 16-bit).

Returns:

Bytes representation of the Read Holding Registers response PDU.

class tmodbus.pdu.ReadInputRegistersPDU(start_address: int, quantity: int)

Read Input Registers PDU.

Inherits from ReadHoldingRegistersPDU, as the structure is the same. Only the function code differs.

Initialize Read Holding Registers PDU.

Parameters:
  • start_address – Starting address of the registers to read

  • quantity – Number of registers to read

Raises:

ValueError – If start_address or quantity is invalid

class tmodbus.pdu.ReadWriteMultipleRegistersPDU(read_start_address: int, read_quantity: int, write_start_address: int, write_values: list[int])

Read/Write Multiple Registers PDU (0x17).

This function code performs a combination of one read operation and one write operation in a single MODBUS transaction. The write operation is performed before the read.

classmethod decode_request(request: bytes) Self

Decode Read/Write Multiple Registers Request PDU.

Parameters:

request – The request bytes.

Returns:

ReadWriteMultipleRegistersPDU instance created from the request.

decode_response(response: bytes) list[int]

Decode the response PDU.

Parameters:

response – Response PDU bytes

Returns:

List of integers representing the register values read

Raises:

InvalidResponseError – If response format is invalid

encode_request() bytes

Convert PDU to bytes.

Returns:

Bytes representation of the Read/Write Multiple Registers PDU

encode_response(value: list[int]) bytes

Encode the response PDU with register values.

Parameters:

value – List of register values.

Returns:

Bytes representation of the Read/Write Multiple Registers response PDU.

class tmodbus.pdu.ReportServerIdPDU

PDU for Report Server ID (function code 0x11).

Initialize ReportServerIdPDU.

classmethod decode_request(data: bytes) Self

Decode bytes into a PDU instance.

Parameters:

data – Bytes to decode.

Returns:

Instance of ReportServerIdPDU.

Raises:

InvalidRequestError – If the data is invalid.

decode_response(response: bytes) ServerIdResponse

Decode the response PDU.

Parameters:

response – Bytes to decode.

Returns:

Instance of ServerIdResponse.

Raises:

InvalidResponseError – If the response is invalid.

encode_request() bytes

Encode the PDU into bytes.

Returns:

Encoded bytes of the PDU.

encode_response(value: ServerIdResponse) bytes

Encode the response PDU.

Parameters:

value – Instance of ServerIdResponse to encode.

Returns:

Encoded bytes of the response PDU.

class tmodbus.pdu.ServerIdResponse(server_id: bytes, run_indicator_status: bool, additional_data: bytes)

Response data structure for Report Server ID.

class tmodbus.pdu.WriteFileRecordPDU(file_records: list[FileRecord])

PDU for Write File Record (function code 0x15).

classmethod decode_request(request: bytes) Self

Decode the request PDU.

Parameters:

request – Bytes to decode.

Returns:

List of FileRecord instances as requested.

Raises:

InvalidRequestError – If the request is invalid.

decode_response(response: bytes) list[FileRecord]

Decode the response PDU.

Parameters:

response – Bytes to decode.

Returns:

List of FileRecord instances as echoed by the server.

Raises:

InvalidResponseError – If the response is invalid.

encode_request() bytes

Encode the request PDU.

Returns:

Encoded bytes of the PDU.

encode_response(value: list[FileRecord]) bytes

Encode the response PDU.

Parameters:

value – List of FileRecord instances to encode.

Returns:

Encoded bytes of the PDU.

class tmodbus.pdu.WriteMultipleCoilsPDU(start_address: int, values: list[bool])

Write Multiple Coils PDU.

Initialize Write Multiple Coils PDU.

Parameters:
  • start_address – Starting address of the coils to write

  • values – List of boolean values representing the coil states

Raises:

ValueError – If start_address or values are invalid

classmethod decode_request(request: bytes) Self

Decode Write Multiple Coils Request PDU.

Parameters:

request – the request bytes.

Returns:

The decoded Write Multiple Coils Request PDU.

Return type:

WriteMultipleCoilsPDU

decode_response(response: bytes) int

Decode the response PDU.

Parameters:

response – Response PDU bytes

Raises:

InvalidResponseError – If response format is invalid

encode_request() bytes

Convert PDU to bytes.

Returns:

Bytes representation of the Write Multiple Coils PDU

encode_response(value: int) bytes

Encode the response PDU.

Parameters:

value – The number of coils written to.

Returns:

Bytes representation of the Write Multiple Coils response PDU.

class tmodbus.pdu.WriteMultipleRegistersPDU(start_address: int, values: list[int])

Write Multiple Registers PDU.

Initialize Write Multiple Registers PDU.

Parameters:
  • start_address – Address of the first register to write

  • values – List of values to write to the registers

Raises:

ValueError – If address or values are invalid

classmethod decode_request(request: bytes) Self

Decode Write Multiple Registers Request PDU.

Parameters:

request – The request bytes.

Returns:

WriteMultipleRegistersPDU instance created from the request.

decode_response(response: bytes) int

Verify the response PDU.

Parameters:

response – Response PDU bytes

Returns:

None

Raises:

InvalidResponseError – If response format is invalid

encode_request() bytes

Convert PDU to bytes.

Returns:

Bytes representation of the Write Multiple Registers PDU

encode_response(value: int) bytes

Encode the response PDU.

Returns:

Bytes representation of the Write Multiple Registers response PDU.

class tmodbus.pdu.WriteSingleCoilPDU(address: int, value: bool)

Write Single Coil PDU.

Initialize Write Single Coil PDU.

Parameters:
  • address – Address of the coil to write

  • value – Value to write (True for ON, False for OFF)

Raises:

ValueError – If address is invalid

classmethod decode_request(request: bytes) Self

Decode Write Single Coil Request PDU.

Parameters:

request – the request bytes.

Returns:

The decoded Write Single Coil Request PDU.

Return type:

WriteSingleCoilPDU

decode_response(response: bytes) bool

Decode the response PDU.

Parameters:

response – Response PDU bytes

Raises:

InvalidResponseError – If response format is invalid

encode_request() bytes

Convert PDU to bytes.

Returns:

Bytes representation of the Write Single Coil PDU

encode_response(value: bool) bytes

Encode the response PDU.

Returns:

Bytes representation of the Write Single Coil response PDU.

Notes

For Write Single Coil, the response echoes the request.

class tmodbus.pdu.WriteSingleRegisterPDU(address: int, value: int)

Write Single Register PDU.

Initialize Write Single Register PDU.

Parameters:
  • address – Address of the register to write

  • value – Value to write to the register

Raises:

ValueError – If address or value is invalid

classmethod decode_request(request: bytes) Self

Decode Write Single Register Request PDU.

Parameters:

request – The request bytes.

Returns:

WriteSingleRegisterPDU instance created from the request.

decode_response(response: bytes) int

Decode the response PDU.

Parameters:

response – Response PDU bytes

Returns:

None

Raises:

InvalidResponseError – If response format is invalid

encode_request() bytes

Convert PDU to bytes.

Returns:

Bytes representation of the Write Single Register PDU

encode_response(value: int) bytes

Encode the response PDU.

Returns:

Bytes representation of the Write Single Register response PDU (echo).

tmodbus.pdu.register_pdu_class(pdu_class: type[BaseClientPDU[Any]]) None

Register a PDU class for a specific function code.

Parameters:

pdu_class – PDU class to register

Exceptions

When the server responds with an error, tModbus will raise the corresponding subclass of ModbusResponseError:

If an unknown exception code is returned, a generic ModbusResponseError will be raised.

When the server responds with an invalid response, tModbus will raise the corresponding subclass of ModbusInvalidResponseError:

Exceptions.

exception tmodbus.exceptions.ASCIIFrameError(*args: Any, response_bytes: bytes, **kwargs: Any)

Bases: InvalidResponseError

ASCII frame error exception.

Raised when there is a framing error in the received ASCII frame.

Initialize RTUFrameError.

exception tmodbus.exceptions.AbnormalDeviceDescriptionError(error_code: int, function_code: int)

Bases: ModbusResponseError

The device description definition call returned a response.

Initialize ModbusResponseError.

Parameters:
  • error_code – Error code from the Modbus exception response

  • function_code – Function code of the request that caused the exception

exception tmodbus.exceptions.AcknowledgeError(error_code: int, function_code: int)

Bases: ModbusResponseError

Acknowledge error.

The server has accepted the requests and it processing it, but a long duration of time will be required to do so.

Initialize ModbusResponseError.

Parameters:
  • error_code – Error code from the Modbus exception response

  • function_code – Function code of the request that caused the exception

exception tmodbus.exceptions.CRCError(*args: Any, response_bytes: bytes, **kwargs: Any)

Bases: InvalidResponseError

CRC validation error exception.

Raised when CRC validation of received data frame fails.

Initialize RTUFrameError.

exception tmodbus.exceptions.FunctionCodeError(*args: Any, response_bytes: bytes, **kwargs: Any)

Bases: InvalidResponseError

Function code error exception.

Raised when the function code in the response does not match the request.

Initialize RTUFrameError.

exception tmodbus.exceptions.GatewayPathUnavailableError(error_code: int, function_code: int)

Bases: ModbusResponseError

The gateway is probably misconfigured or overloaded.

Initialize ModbusResponseError.

Parameters:
  • error_code – Error code from the Modbus exception response

  • function_code – Function code of the request that caused the exception

exception tmodbus.exceptions.GatewayTargetDeviceFailedToRespondError(error_code: int, function_code: int)

Bases: ModbusResponseError

Didn’t get a response from target device.

Initialize ModbusResponseError.

Parameters:
  • error_code – Error code from the Modbus exception response

  • function_code – Function code of the request that caused the exception

exception tmodbus.exceptions.HeaderMismatchError(*args: Any, response_bytes: bytes, **kwargs: Any)

Bases: InvalidResponseError

Header mismatch error exception.

Raised when the header of the received response does not match the request.

Initialize RTUFrameError.

exception tmodbus.exceptions.IllegalDataAddressError(error_code: int, function_code: int)

Bases: ModbusResponseError

The data address received in the request is not an allowable address for the server.

Initialize ModbusResponseError.

Parameters:
  • error_code – Error code from the Modbus exception response

  • function_code – Function code of the request that caused the exception

exception tmodbus.exceptions.IllegalDataValueError(error_code: int, function_code: int)

Bases: ModbusResponseError

The value contained in the request data field is not an allowable value for the server.

Initialize ModbusResponseError.

Parameters:
  • error_code – Error code from the Modbus exception response

  • function_code – Function code of the request that caused the exception

exception tmodbus.exceptions.IllegalFunctionError(error_code: int, function_code: int)

Bases: ModbusResponseError

The function code received in the request is not an allowable action for the server.

Initialize ModbusResponseError.

Parameters:
  • error_code – Error code from the Modbus exception response

  • function_code – Function code of the request that caused the exception

exception tmodbus.exceptions.InvalidRequestError(*args: Any, request_bytes: bytes | None = None, **kwargs: Any)

Bases: TModbusError

Invalid request error exception.

Raised when a request is malformed or invalid.

Initialize InvalidRequestError.

exception tmodbus.exceptions.InvalidResponseError(*args: Any, response_bytes: bytes, **kwargs: Any)

Bases: TModbusError

Invalid response error exception.

Raised when received response format is incorrect or unexpected.

Initialize RTUFrameError.

exception tmodbus.exceptions.LRCError(*args: Any, response_bytes: bytes, **kwargs: Any)

Bases: InvalidResponseError

LRC validation error exception.

Raised when LRC validation of received data frame fails.

Initialize RTUFrameError.

exception tmodbus.exceptions.MemoryParityError(error_code: int, function_code: int)

Bases: ModbusResponseError

The server attempted to read record file, but detected a parity error in memory.

Initialize ModbusResponseError.

Parameters:
  • error_code – Error code from the Modbus exception response

  • function_code – Function code of the request that caused the exception

exception tmodbus.exceptions.ModbusConnectionError(*args: Any, bytes_read: bytes | None = None, **kwargs: Any)

Bases: TModbusError

Connection error exception.

Raised when unable to establish or maintain connection with Modbus device.

Initialize RTUFrameError.

response_bytes: bytes

The bytes that were read before the connection error occurred. Can be empty.

exception tmodbus.exceptions.ModbusResponseError(error_code: int, function_code: int)

Bases: TModbusError

Base class for all Modbus exception response.

Initialize ModbusResponseError.

Parameters:
  • error_code – Error code from the Modbus exception response

  • function_code – Function code of the request that caused the exception

exception tmodbus.exceptions.RTUFrameError(*args: Any, response_bytes: bytes, **kwargs: Any)

Bases: InvalidResponseError

RTU frame error exception.

Raised when there is a framing error in the received RTU frame.

Initialize RTUFrameError.

exception tmodbus.exceptions.RequestRetryFailedError

Bases: TModbusError

Failed to get an appropriate response after exhausting all retries.

Raised when all retry attempts for a request have been exhausted without success.

exception tmodbus.exceptions.ServerDeviceBusyError(error_code: int, function_code: int)

Bases: ModbusResponseError

The server is engaged in a long-duration program command.

Initialize ModbusResponseError.

Parameters:
  • error_code – Error code from the Modbus exception response

  • function_code – Function code of the request that caused the exception

exception tmodbus.exceptions.ServerDeviceFailureError(error_code: int, function_code: int)

Bases: ModbusResponseError

An unrecoverable error occurred.

Initialize ModbusResponseError.

Parameters:
  • error_code – Error code from the Modbus exception response

  • function_code – Function code of the request that caused the exception

exception tmodbus.exceptions.TModbusError

Bases: Exception

Base exception class for ModbusLink library.

exception tmodbus.exceptions.UnknownModbusResponseError(error_code: int, function_code: int)

Bases: ModbusResponseError

Unknown Modbus exception response.

Initialize UnknownModbusResponseError.

Parameters:
  • error_code – Error code from the Modbus exception response

  • function_code – Function code of the request that caused the exception

tmodbus.exceptions.register_custom_exception(err_cls: type[ModbusResponseError]) None

Register a custom Modbus exception class.

Parameters:

err_cls – Custom exception class to register