Clients

The TCP connection to the server can be established by a synchronous or asynchronous client.

Default Client

class modbusclient.client.Client(host='', port=502, timeout=None, connect=True)[source]

Modbus client

Modbus client to send function calls to a server and receive the respective responses. Can be used in a with block.

Parameters:
  • address (string) – IP Adress of the host. If empty, no connection will be attempted. Defaults to the empty string.
  • port (int) – Port to use. Defaults to 502
  • timeout (float) – Timeout in seconds. If not set, it will be set to the default timeout.
  • connect (bool) – If True, the client immediately connects if an address is specified. Otherwise a call to connect() or __enter__() is required.
host

string – IP Adress of the host

port

int – Port to use. Defaults to 502

timeout

int or None – Timeout in seconds

assert_connected()[source]

Assert client is connected

A helper method which raises an exception, if the client is not connected

Raise:
RuntimeError: if is_connected() returns False.
call(function, **kwargs)[source]

Call a function on the server and return the result

Sends a request via request() followed by an immediate call of get_response()

Parameters:
  • function (int) – Function code
  • **kwargs (dict) – Keyword arguments passed verbatim to request()
Returns:

Data returned by get_response()

Return type:

tuple

connect(**kwargs)[source]

Connect this client to a host

Parameters:
  • address (string) – IP Adress of the host. If provided, it will replace the current Client.address. Defaults to Client.address
  • port (int) – Port to use. If provided, it will replace the current Client.port. Defaults to Client.port.
  • timeout (float) – Timeout in seconds. If provided, it will replace the current Client.timeout. Defaults to Client.timeout
disconnect()[source]

Disconnect this client

If this client is connected, the socket will be shutdown and then closed. If the client is not connected, calling this method has no effect.

get_response()[source]

Get response from the server

Returns:The following values will be returned:
  • The received MBAP header
  • The raw data bytes of the payload without any headers
  • An error code or None, if no error occurred.
Return type:tuple(ApplicationProtocolHeader, bytes, int)
is_connected()[source]

Check if this client is connected to a server

Returns:True if and only if this client is connected to a server
Return type:bool
iter_responses(n)[source]

Iter over a number of responses

n

int – Number of request headers

receive(size)[source]

Receive a given number of bytes from the server

Parameters:size (int) – Number of bytes to receive
Returns:Buffer containing the received bytes.
Return type:bytes
Raises:ConnectionAbortedError – If the connection is terminated unexpectedly
request(function, payload=b'', unit=255, transaction=0, **kwargs)[source]

Send a request to the server

Parameters:
  • function (int) – Function code
  • payload (bytes) – Data sent along with the request. Empty by default. Used only for writing functions.
  • unit (int) – Unit ID of device. Defaults to NO_UNIT
  • transaction (int) – Transaction ID. Defaults to 0.
  • **kwargs (dict) – Keyword arguments passed verbatim to the request of the function
Returns:

Header of the request

Return type:

ApplicationProtocolHeader

Asynchronous Client

class modbusclient.asyncio.Client(host='', port=502, timeout=None, max_transactions=3, loop=None)[source]

Asynchronous Modbus client

An asynchronous Modbus client, which can be used in an``async with`` block.

Parameters:
  • host (string) – IP Adress of the host. If empty, no connection will be attempted. Defaults to the empty string.
  • port (int) – Port to use. Defaults to 502
  • timeout (float) – Timeout in seconds. If not set, it will be set to the default timeout. Currently not used.
  • max_transactions (int) – Max. number of transactions send in parallel to the server. Defaults to 3.
  • loop (EventLoop) – If set to None, event loop will be determined by the method. Defaults to None. Deprecated from python 3.7 onwards.
assert_connected()[source]

Assert client is connected

A helper method which raises an exception, if the client is not connected

Raise:
RuntimeError: if is_connected() returns False.
call(function, **kwargs)[source]

Call a function on the server and await the result

Sends a request via Client.request() and processes responses until the resulting future is complete.

Parameters:
  • function (int) – Function code
  • **kwargs (dict) – Keyword arguments passed verbatim to request().
Returns:

The following values will be returned:

  • The received MBAP header
  • The raw data bytes of the payload without any headers
  • An error code or None, if no error occurred.

Return type:

tuple(ApplicationProtocolHeader, bytes, int)

Raise:

ModbusError: On modbus related errors

asyncio.CancelledError: If future has been cancelled

connect(host=None, port=None)[source]

Connect this client to a host

Parameters:
  • host (string) – IP Adress of the host
  • port (int) – Port to use. Defaults to 502
disconnect()[source]

Disconnect this client

If this client is connected, the socket will be shutdown and then closed. If the client is not connected, calling this method has no effect.

get_response()[source]

Get response from the server

Locks the internal reader lock and reads the next message on the input stream. If the transaction ID is valid and a matching future is found, the result of the future will be set

Returns:The following values are returned:
  • The received MBAP header
  • The raw data bytes of the payload without any headers
  • An error code or None, if no error occurred.
Return type:tuple(ApplicationProtocolHeader, bytes, int)
get_transaction_id()[source]

Get transaction ID

Checks whether any of the available transaction IDs is available and returns the first available ID. If no ID is available, Client.get_response() is invoked, until a free ID is found.

Returns:Available transaction ID in the range [0:self.max_transactions].
Return type:int
is_connected()[source]

Check if this client is connected to a server

Returns:True if and only if this client is connected to a server
Return type:bool
request(function, payload=b'', unit=255, transaction=None, **kwargs)[source]

Send a request to the server

Awaits transaction ID transaction to become available. Then creates a request and sends it to the server. A future for the reply is created and added to self._transactions[transaction].

Note that the future will not be completed unless Client.get_response() is called. For a wrapper which makes sure the result is collected, see Client.call()

Parameters:
  • function (int) – Function code
  • payload (bytes) – Data sent along with the request. Empty by default. Used only for writing functions.
  • unit (int) – Unit ID of device. Defaults to NO_UNIT
  • transaction (int) – Transaction ID. If set to None, a transaction ID will be generated by Client.get_transaction_id(). Defaults to None.
  • kwargs (dict) – Keyword arguments passed verbatim to the request of the function
Returns:

  • Request header
  • Future yielding response header, payload and error code

Return type:

tuple(ApplicationProtocolHeader, asyncio.Future)

Raise:
ValueError: If transaction ID is out of bounds