pyModbusTCP.client

The Modbus/TCP client. See Modbus/TCP client for an introduction.

from pyModbusTCP.client import ModbusClient

ModbusClient

class pyModbusTCP.client.ModbusClient(host: str = 'localhost', port: int = 502, unit_id: int = 1, timeout: float = 30.0, auto_open: bool = True, auto_close: bool = False, *, connect_retries: int = 0, connect_retry_delay: float = 0.5, tcp_no_delay: bool = True, broadcast_interval: float = 0.15)[source]

Modbus TCP client.

An instance is not thread-safe: share it between threads only with an external lock.

Constructor.

The arguments after auto_close are keyword-only (like ModbusClient('plc', connect_retries=3)).

Parameters:
  • host (str) – hostname or IPv4/IPv6 address of the server

  • port (int) – TCP port number

  • unit_id (int) – unit ID

  • timeout (float) – timeout in seconds for a request (send + receive), not for each socket operation

  • auto_open (bool) – auto TCP connect

  • auto_close (bool) – auto TCP close

  • connect_retries (int) – number of new connect attempts after a failed one (default 0: no retry), for open() and the auto_open connections (a request is never sent twice, only the connection is retried)

  • connect_retry_delay (float) – base delay in seconds before the first connect retry (default 0.5), doubled at each next retry (exponential backoff, capped at 60 s, with a random jitter)

  • tcp_no_delay (bool) – set the TCP_NODELAY option on the connection: disable Nagle’s algorithm (True by default)

  • broadcast_interval (float) – min interval in seconds between two broadcast requests (default 0.15, 0 for no limit): a broadcast sent sooner waits, a client never sends broadcasts faster than a serial line can take

Returns:

Object ModbusClient

Return type:

ModbusClient

property host: str

Get or set the server to connect to.

This can be any string with a valid IPv4 / IPv6 address or hostname. An internationalized domain name must be given in its ASCII form (punycode, like 'xn--caf-dma.fr' for 'café.fr'), see valid_host(). Setting host to a new value will close the current socket.

property port: int

Get or set the current TCP port (default is 502).

Setting port to a new value will close the current socket.

property unit_id: int

Get or set the modbus unit identifier (default is 1).

Any int from 0 to 255 is valid.

property timeout: float

Get or set requests timeout (default is 30 seconds).

The argument may be a floating point number for sub-second precision. This is a limit for the whole request (send + receive), applied from the next request on (the current connection is kept).

property auto_open: bool

Get or set automatic TCP connect mode (True = turn on).

property auto_close: bool

Get or set automatic TCP close after each request mode (True = turn on).

property broadcast_interval: float

Get or set the min interval in seconds between two broadcast requests (default 0.15, 0 for no limit).

property connect_retries: int

Get or set the number of new connect attempts after a failed one (default 0: no retry).

property connect_retry_delay: float

Get or set the base delay in seconds before the first connect retry (default 0.5, doubled at each retry).

property tcp_no_delay: bool

Get or set TCP_NODELAY mode on connection (True = disable Nagle’s algorithm, default).

open() → bool[source]

Connect to modbus server (open TCP connection).

Returns:

connect status (True on success)

Return type:

bool

close() → None

Close current TCP connection.

custom_request(pdu: bytes | bytearray, *, broadcast: bool = False) → bytes | None

Send a custom modbus request.

The reply must have the same function code (or the same with the exception flag): otherwise it is an error.

With broadcast=True, the request is sent to the unit id 0 (a write to every slave of a serial line, through a TCP to RTU gateway) without waiting for a reply: it returns the PDU sent (there is no reply PDU). Only for a function that writes data (0x05, 0x06, 0x0F, 0x10, 0x15, 0x16): ValueError otherwise.

Parameters:

pdu (bytes or bytearray) – a modbus PDU (protocol data unit) of 1 to 253 bytes: function code followed by the request data (the function code is not checked, a code with the exception flag set (0x80 to 0xFF) is sent as is, but its reply can’t be accepted: it’s always a function code mismatch error)

Returns:

modbus frame PDU or None if error

Return type:

bytes or None

property is_open: bool

Get current status of the TCP connection (True = open).

A connection closed or reset by the server (server stopped, idle timeout…) is seen as closed: it is closed on the client side too. A server gone without closing it (power cut, cable pulled) can’t be seen: the connection stays open until a request fails on it.

on_tx_rx(frame: bytes, is_tx: bool) → None

Call for each Tx/Rx (for user purposes).

read_coils(bit_addr: int, bit_nb: int = 1) → list[bool] | None

Modbus function READ_COILS (0x01).

Parameters:
  • bit_addr (int) – bit address (0 to 65535)

  • bit_nb (int) – number of bits to read (1 to 2000)

Returns:

bits list or None if error

Return type:

list of bool or None

read_device_identification(read_code: int = 1, object_id: int = 0) → DeviceIdentificationResponse | None

Modbus function Read Device Identification (0x2B/0x0E).

Parameters:
  • read_code (int) – read device id code, 1 to 3 for respectively: basic, regular and extended stream access, 4 for one specific identification object individual access (default is 1)

  • object_id (int) – object id of the first object to obtain (default is 0)

Returns:

a DeviceIdentificationResponse instance with the data or None if the requests fails

Return type:

DeviceIdentificationResponse or None

read_discrete_inputs(bit_addr: int, bit_nb: int = 1) → list[bool] | None

Modbus function READ_DISCRETE_INPUTS (0x02).

Parameters:
  • bit_addr (int) – bit address (0 to 65535)

  • bit_nb (int) – number of bits to read (1 to 2000)

Returns:

bits list or None if error

Return type:

list of bool or None

read_holding_registers(reg_addr: int, reg_nb: int = 1) → list[int] | None

Modbus function READ_HOLDING_REGISTERS (0x03).

Parameters:
  • reg_addr (int) – register address (0 to 65535)

  • reg_nb (int) – number of registers to read (1 to 125)

Returns:

registers list or None if fail

Return type:

list of int or None

read_input_registers(reg_addr: int, reg_nb: int = 1) → list[int] | None

Modbus function READ_INPUT_REGISTERS (0x04).

Parameters:
  • reg_addr (int) – register address (0 to 65535)

  • reg_nb (int) – number of registers to read (1 to 125)

Returns:

registers list or None if fail

Return type:

list of int or None

property version: str

Return the current package version as a str.

write_multiple_coils(bits_addr: int, bits_value: Iterable[int], *, broadcast: bool = False) → bool

Modbus function WRITE_MULTIPLE_COILS (0x0F).

Parameters:
  • bits_addr (int) – bits address (0 to 65535)

  • bits_value (list) – bits values to write (any iterable of bool or int)

  • broadcast (bool) – send to the unit id 0 (every slave of a serial line, through a TCP to RTU gateway), without waiting for a reply: True once the request is sent (default: False)

Returns:

True if write ok

Return type:

bool

write_multiple_registers(regs_addr: int, regs_value: Iterable[int], *, broadcast: bool = False) → bool

Modbus function WRITE_MULTIPLE_REGISTERS (0x10).

Parameters:
  • regs_addr (int) – registers address (0 to 65535)

  • regs_value (list) – registers values to write (any iterable of int)

  • broadcast (bool) – send to the unit id 0 (every slave of a serial line, through a TCP to RTU gateway), without waiting for a reply: True once the request is sent (default: False)

Returns:

True if write ok

Return type:

bool

write_read_multiple_registers(write_addr: int, write_values: Iterable[int], read_addr: int, read_nb: int = 1) → list[int] | None

Modbus function WRITE_READ_MULTIPLE_REGISTERS (0x17).

Parameters:
  • write_addr (int) – write registers address (0 to 65535)

  • write_values (list) – registers values to write (any iterable of int)

  • read_addr (int) – read register address (0 to 65535)

  • read_nb (int) – number of registers to read (1 to 125)

Returns:

registers list or None if fail

Return type:

list of int or None

write_single_coil(bit_addr: int, bit_value: bool, *, broadcast: bool = False) → bool

Modbus function WRITE_SINGLE_COIL (0x05).

Parameters:
  • bit_addr (int) – bit address (0 to 65535)

  • bit_value (bool) – bit value to write

  • broadcast (bool) – send to the unit id 0 (every slave of a serial line, through a TCP to RTU gateway), without waiting for a reply: True once the request is sent (default: False)

Returns:

True if write ok

Return type:

bool

write_single_register(reg_addr: int, reg_value: int, *, broadcast: bool = False) → bool

Modbus function WRITE_SINGLE_REGISTER (0x06).

Parameters:
  • reg_addr (int) – register address (0 to 65535)

  • reg_value (int) – register value to write

  • broadcast (bool) – send to the unit id 0 (every slave of a serial line, through a TCP to RTU gateway), without waiting for a reply: True once the request is sent (default: False)

Returns:

True if write ok

Return type:

bool

property last_error: int

Last error code.

property last_error_as_txt: str

Human-readable text that describe last error.

property last_except: int

Return the last modbus exception code.

property last_except_as_txt: str

Short human-readable text that describe last modbus exception.

property last_except_as_full_txt: str

Verbose human-readable text that describe last modbus exception.

DeviceIdentificationResponse

The result of ModbusClient.read_device_identification().

class pyModbusTCP.client.DeviceIdentificationResponse(conformity_level: int = 0, more_follows: int = 0, next_object_id: int = 0, objects_by_id: dict[int, bytes]=<factory>)[source]

Modbus TCP client function read_device_identification() response struct.

Parameters:
  • conformity_level (int) – this represents supported access and object type

  • more_follows (int) – for stream request can be set to 0xff if other objects are available (0x00 in other cases)

  • next_object_id (int) – the next object id to be asked by following transaction

  • objects_by_id (dict) – a dictionary with requested object (dict keys are object id as int)