Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions doc/source/client.rst
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,43 @@ And in case of read retrieve the data depending on type of request

Remark if using :mod:`no_response_expected=True` rr will always be None.


Serial request spacing
----------------------

Some serial devices accept a request and return a valid response, but may not
respond to another request sent immediately afterwards.

Both serial clients accept ``inter_request_delay`` in seconds, and defaults to ``0.0``. For example::

client = ModbusSerialClient("/dev/ttyUSB0", baudrate=115200,
inter_request_delay=0.020)
with client:
temperatures = client.read_input_registers(
temperature_address, count=4, device_id=1
)
diagnostics = client.read_holding_registers(
diagnostics_address, count=2, device_id=1
)

The second request waits until at least 20 ms after the first transaction
finishes.

Broadcast requests (device ID 0) wait for all recorded device delay intervals
and start a delay interval for every device, including previously unused IDs.

The asynchronous equivalent uses the same option::

async with AsyncModbusSerialClient("/dev/ttyUSB0", baudrate=115200,
inter_request_delay=0.020) as client:
temperatures = await client.read_input_registers(
temperature_address, count=4, device_id=1
)
diagnostics = await client.read_holding_registers(
diagnostics_address, count=2, device_id=1
)


Client interface classes
------------------------

Expand Down
11 changes: 11 additions & 0 deletions pymodbus/client/serial.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import contextlib
import math

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems very strange that the math is needed.

@Bingdom Bingdom Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @janiversen thank you for reviewing the code.

For the moment, we need to check if the input is a finite number. We can strip out this check if you consider this level of input validation is out of scope. However, I would suggest the lower-bound check should remain.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there are no need for math. Just do a min/max check which e x ludes all u wanted values like NaN.

import sys
import time
from collections.abc import Callable
Expand Down Expand Up @@ -40,6 +41,7 @@ class AsyncModbusSerialClient(ModbusBaseClient):
:param reconnect_delay_max: Maximum delay when reconnecting, in seconds (use decimals for milliseconds).
:param timeout: Timeout for connecting and receiving data, in seconds (use decimals for milliseconds).
:param retries: Max number of retries per request.
:param inter_request_delay: Minimum seconds between completing a transaction attempt and sending the next request to the same device ID, including retries. Broadcasts apply to all devices. Default 0.0 (disabled).
:param trace_packet: Called with bytestream received/to be sent
:param trace_pdu: Called with PDU received/to be sent
:param trace_connect: Called when connected/disconnected
Expand Down Expand Up @@ -81,6 +83,7 @@ def __init__(
reconnect_delay_max: float = 300,
timeout: float = 3,
retries: int = 3,
inter_request_delay: float = 0.0,
trace_packet: Callable[[bool, bytes], bytes] | None = None,
trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None,
trace_connect: Callable[[bool], None] | None = None,
Expand All @@ -93,6 +96,8 @@ def __init__(
)
if framer not in [FramerType.ASCII, FramerType.RTU]:
raise TypeError("Only FramerType RTU/ASCII allowed.")
if not math.isfinite(inter_request_delay) or inter_request_delay < 0.0:
raise ValueError("inter_request_delay must be finite and non-negative")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No it must be a float (which includes int) according to the typing

@janiversen janiversen Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a max check and isfinite is no longer needed.

self.comm_params = CommParams(
comm_type=CommType.SERIAL,
host=port,
Expand All @@ -101,6 +106,7 @@ def __init__(
parity=parity,
stopbits=stopbits,
handle_local_echo=handle_local_echo,
inter_request_delay=inter_request_delay,
comm_name=name,
reconnect_delay=reconnect_delay,
reconnect_delay_max=reconnect_delay_max,
Expand Down Expand Up @@ -137,6 +143,7 @@ class ModbusSerialClient(ModbusBaseSyncClient):
:param reconnect_delay_max: Not used in the sync client
:param timeout: Timeout for connecting and receiving data, in seconds.
:param retries: Max number of retries per request.
:param inter_request_delay: Minimum seconds between completing a transaction attempt and sending the next request to the same device ID, including retries. Broadcasts apply to all devices. Default 0.0 (disabled).
:param trace_packet: Called with bytestream received/to be sent
:param trace_pdu: Called with PDU received/to be sent
:param trace_connect: Called when connected/disconnected
Expand Down Expand Up @@ -173,6 +180,7 @@ def __init__(
reconnect_delay_max: float = 300,
timeout: float = 3,
retries: int = 3,
inter_request_delay: float = 0.0,
trace_packet: Callable[[bool, bytes], bytes] | None = None,
trace_pdu: Callable[[bool, ModbusPDU], ModbusPDU] | None = None,
trace_connect: Callable[[bool], None] | None = None,
Expand All @@ -185,6 +193,8 @@ def __init__(
)
if framer not in [FramerType.ASCII, FramerType.RTU]:
raise TypeError("Only RTU/ASCII allowed.")
if not math.isfinite(inter_request_delay) or inter_request_delay < 0.0:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here.

raise ValueError("inter_request_delay must be finite and non-negative")
self.comm_params = CommParams(
comm_type=CommType.SERIAL,
host=port,
Expand All @@ -193,6 +203,7 @@ def __init__(
parity=parity,
stopbits=stopbits,
handle_local_echo=handle_local_echo,
inter_request_delay=inter_request_delay,
comm_name=name,
reconnect_delay=reconnect_delay,
reconnect_delay_max=reconnect_delay_max,
Expand Down
182 changes: 112 additions & 70 deletions pymodbus/transaction/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
from __future__ import annotations

import asyncio
from collections.abc import Callable
import math
from collections.abc import AsyncGenerator, Callable
from contextlib import asynccontextmanager
from threading import RLock
from time import monotonic
from time import monotonic, perf_counter, sleep

from ..exceptions import ConnectionException, ModbusIOException
from ..framer import FramerBase
Expand Down Expand Up @@ -50,6 +52,7 @@ def __init__(
self.max_buffer_size = framer.MAX_SIZE
self.framer = framer
self.retries = retries
self._last_transaction_end: dict[int, float] = {}
self.next_tid: int = 0

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seriel do not have transaction ids, so the name is strange... is the int the dev_id ?

self.request_dev_id: int = 0
self.request_transaction_id: int = 0
Expand Down Expand Up @@ -137,6 +140,36 @@ def _io_exception_from_request(
dev_id=request.dev_id,
)

def _inter_request_delay(self, dev_id: int) -> float:
"""Return this device's remaining delay interval, including broadcasts."""
if not self.comm_params.inter_request_delay or not self._last_transaction_end:
return 0.0
if dev_id == 0: # pylint: disable=use-implicit-booleaness-not-comparison-to-zero
# Broadcasts address all slaves, so use the latest transaction completion.
last_end = max(self._last_transaction_end.values())
else:
last_end = max(
self._last_transaction_end.get(dev_id, -math.inf),
self._last_transaction_end.get(0, -math.inf),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since dev_id == 0 is handled in the "if", it should not be added to the dict, this just causes confusion.

)
remaining = self.comm_params.inter_request_delay - (perf_counter() - last_end)
return remaining if remaining > 0.0 else 0.0

@asynccontextmanager
async def _request_lock(self, dev_id: int) -> AsyncGenerator[None]:
"""Serialize attempts, releasing the wire during device delay intervals."""
while True:
async with self._lock:
if not (delay := self._inter_request_delay(dev_id)):
yield
return
await asyncio.sleep(delay)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in what situation can this loop ? once the sleep is done the proces can continue ?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the purpose of the lock, all parts inside the lock is read only so it does not seem needed.


def _set_transaction_end(self, dev_id: int) -> None:
"""Record completion for the addressed device when spacing is enabled."""
if self.comm_params.inter_request_delay:
self._last_transaction_end[dev_id] = perf_counter()

def _no_response(self, request: ModbusPDU) -> ModbusIOException:
"""Count a request that got no response, and build the exception to raise."""
if self.count_until_disconnect < 0:
Expand Down Expand Up @@ -165,28 +198,33 @@ def sync_execute(self, no_response_expected: bool, request: ModbusPDU) -> Modbus
request.transaction_id = self.getNextTID()
count_retries = 0
while count_retries <= self.retries:
self.pdu_send(request)
if no_response_expected:
return None # type: ignore[return-value]
if delay := self._inter_request_delay(request.dev_id):
sleep(delay)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On a serial line you often have multiple devices, but this causes a delay for all calls....it should only be a delay if calling the same device.

This slows all devices, which seems wrong.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. I will fix this and update the tests.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still slows down all devices connected to one client ?

the lock is set in line 197, before your. changes.

try:
response = self.sync_get_response(
request.dev_id, request.transaction_id
)
self.count_until_disconnect = self.max_until_disconnect
if response.dev_id != request.dev_id:
raise self._io_exception_from_request(
f"ERROR: request uses device id={request.dev_id} but received {response.dev_id}.",
request,
)
if response.transaction_id != request.transaction_id:
raise self._io_exception_from_request(
f"ERROR: request uses transaction id={request.transaction_id} but received {response.transaction_id}.",
request,
self.pdu_send(request)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this moved inside the try/expect that is wrong.

This is a fundamental change that have nothing to do with inter-request delay, so it should be done in a separate PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's put into a try/finally. It doesn't catch exceptions, so all of that still propagates normally.

It's like that so it records the spacing timestamp for failures too.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a change that have nothing to do with the wait !

Having it in this PR just makes bisecting so much harder, please move it to a separate PR.

if no_response_expected:
return None # type: ignore[return-value]
try:
response = self.sync_get_response(
request.dev_id, request.transaction_id
)
response.retries = count_retries
return response
except asyncio.exceptions.TimeoutError:
count_retries += 1
self.count_until_disconnect = self.max_until_disconnect
if response.dev_id != request.dev_id:
raise self._io_exception_from_request(
f"ERROR: request uses device id={request.dev_id} but received {response.dev_id}.",
request,
)
if response.transaction_id != request.transaction_id:
raise self._io_exception_from_request(
f"ERROR: request uses transaction id={request.transaction_id} but received {response.transaction_id}.",
request,
)
response.retries = count_retries
return response
except asyncio.exceptions.TimeoutError:
count_retries += 1
finally:
self._set_transaction_end(request.dev_id)
raise self._no_response(request)

async def _connect_if_needed(self) -> None:
Expand All @@ -207,57 +245,61 @@ async def execute(
and the wait after a cancel. any changes in either method MUST be mirrored !!!
"""
await self._connect_if_needed()
async with self._lock:
cancel_key = (request.dev_id, request.function_code)
if cancelled := self.cancelled_requests.pop(cancel_key, None):
late_response, until = cancelled
await asyncio.wait([late_response], timeout=until - monotonic())
request.transaction_id = self.getNextTID()
count_retries = 0
while count_retries <= self.retries:
self.recv_buffer = b""
self.response_future = asyncio.Future()
self.pdu_send(request)
if no_response_expected:
return None # type: ignore[return-value]
request.transaction_id = self.getNextTID()
count_retries = 0
while count_retries <= self.retries:
async with self._request_lock(request.dev_id):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This waits for any dev id, showing the system.

cancel_key = (request.dev_id, request.function_code)
if cancelled := self.cancelled_requests.pop(cancel_key, None):
late_response, until = cancelled
await asyncio.wait([late_response], timeout=until - monotonic())
try:
response: ModbusPDU = await asyncio.wait_for(
self.response_future, timeout=self.comm_params.timeout_connect
)
self.count_until_disconnect = self.max_until_disconnect
if (request.dev_id and response.dev_id != request.dev_id) or (
response.function_code & 0x7F
) != request.function_code:
Log.error(
f"ERROR: request ask for id/fc={request.dev_id}/{request.function_code} but got {response.dev_id}/{response.function_code}, Skipping."
)
continue
if (
response.transaction_id
and response.transaction_id != request.transaction_id
):
raise self._io_exception_from_request(
f"ERROR: request uses transaction id={request.transaction_id} but received {response.transaction_id}.",
request,
)
response.retries = count_retries
return response
except asyncio.exceptions.TimeoutError:
count_retries += 1
except asyncio.exceptions.CancelledError:
# RTU/ASCII responses carry no transaction id, so the next
# request to this device with this function code first
# waits for the response to this one. A response from
# another device or with another function code is skipped,
# so other requests are not delayed.
if not request.transaction_id:
self.response_future = asyncio.Future()
self.cancelled_requests[cancel_key] = (
self.recv_buffer = b""
self.response_future = asyncio.Future()
self.pdu_send(request)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is pdu_send now within the try/expect, that is wrong

This is a fundamental change that have nothing to do with inter-request delay, so it should be done in a separate PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And my response is also similar.

if no_response_expected:
return None # type: ignore[return-value]
try:
response: ModbusPDU = await asyncio.wait_for(
self.response_future,
monotonic() + self.comm_params.timeout_connect,
timeout=self.comm_params.timeout_connect,
)
raise
raise self._no_response(request)
self.count_until_disconnect = self.max_until_disconnect
if (request.dev_id and response.dev_id != request.dev_id) or (
response.function_code & 0x7F
) != request.function_code:
Log.error(
f"ERROR: request ask for id/fc={request.dev_id}/{request.function_code} but got {response.dev_id}/{response.function_code}, Skipping."
)
continue
if (
response.transaction_id
and response.transaction_id != request.transaction_id
):
raise self._io_exception_from_request(
f"ERROR: request uses transaction id={request.transaction_id} but received {response.transaction_id}.",
request,
)
response.retries = count_retries
return response
except asyncio.exceptions.TimeoutError:
count_retries += 1
except asyncio.exceptions.CancelledError:
# RTU/ASCII responses carry no transaction id, so the next
# request to this device with this function code first
# waits for the response to this one. A response from
# another device or with another function code is skipped,
# so other requests are not delayed.
if not request.transaction_id:
self.response_future = asyncio.Future()
self.cancelled_requests[cancel_key] = (
self.response_future,
monotonic() + self.comm_params.timeout_connect,
)
raise
finally:
self._set_transaction_end(request.dev_id)
raise self._no_response(request)

def pdu_send(self, pdu: ModbusPDU, addr: tuple | None = None) -> None:
"""Build byte stream and send."""
Expand Down
1 change: 1 addition & 0 deletions pymodbus/transport/transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ class CommParams:
parity: str = ""
stopbits: int = -1
handle_local_echo: bool = False
inter_request_delay: float = 0.0

def copy(self: CommParams) -> CommParams:
"""Create a copy."""
Expand Down
Loading
Loading