From 778060286d17919e6db8a8458cbc512921a987d4 Mon Sep 17 00:00:00 2001 From: James Morrow Date: Tue, 3 Nov 2026 16:22:18 +1100 Subject: [PATCH 01/11] Fix missed buffered serial replies after a delayed wakeup --- pymodbus/client/serial.py | 3 +++ test/client/test_client_sync.py | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/pymodbus/client/serial.py b/pymodbus/client/serial.py index 173d85410..3038b2078 100644 --- a/pymodbus/client/serial.py +++ b/pymodbus/client/serial.py @@ -299,6 +299,9 @@ def _wait_for_data(self) -> int: more_data = True size = available time.sleep(self._recv_interval) + else: + # Data may have arrived while sleeping past the timeout. + size = self._in_waiting() return size def recv(self, size: int | None) -> bytes: diff --git a/test/client/test_client_sync.py b/test/client/test_client_sync.py index a89e58c26..f04fd9f80 100755 --- a/test/client/test_client_sync.py +++ b/test/client/test_client_sync.py @@ -469,6 +469,31 @@ def test_serial_client_recv(self, mockSocket): assert client.recv(None) == b"" assert client.recv(0) == b"" + @pytest.mark.parametrize( + ("initial_size", "reply"), [(0, b""), (0, b"123456789"), (4, b"123456789")] + ) + @mock.patch("pymodbus.client.serial.time") + def test_serial_client_recv_after_delayed_wakeup( + self, mock_time, initial_size, reply + ): + """Read the current buffer when a sleep outlasts the receive timeout.""" + client = ModbusSerialClient("/dev/null", timeout=0.2) + mock_socket = mock.MagicMock() + client.socket = mock_socket + mock_socket.in_waiting = initial_size + mock_socket.read.side_effect = lambda size: reply[:size] + mock_time.time.return_value = 0 + + def delayed_wakeup(_interval): + mock_socket.in_waiting = len(reply) + mock_time.time.return_value = 0.3 + + mock_time.sleep.side_effect = delayed_wakeup + + assert client.recv(None) == reply + mock_socket.read.assert_called_once_with(len(reply)) + mock_time.sleep.assert_called_once() + def test_serial_client_recv_drops_socket_on_os_error(self): """Test that a read against a torn-down port drops it rather than escaping.""" client = ModbusSerialClient("/dev/null") From e7e437cd29795dc496b7187e60ae1d20e978aacc Mon Sep 17 00:00:00 2001 From: James Morrow Date: Wed, 4 Nov 2026 15:36:59 +1100 Subject: [PATCH 02/11] Added inter-request delay to sync and async serial clients --- doc/source/client.rst | 24 ++ pymodbus/client/serial.py | 11 + pymodbus/transaction/transaction.py | 130 ++++++---- pymodbus/transport/transport.py | 1 + test/transaction/test_inter_request_delay.py | 259 +++++++++++++++++++ 5 files changed, 377 insertions(+), 48 deletions(-) create mode 100644 test/transaction/test_inter_request_delay.py diff --git a/doc/source/client.rst b/doc/source/client.rst index e9b4a7e65..364f61db2 100644 --- a/doc/source/client.rst +++ b/doc/source/client.rst @@ -237,6 +237,30 @@ 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: + client.write_coil(0, True, device_id=1) + client.read_coils(0, count=1, device_id=1) + +The second request waits until at least 20 ms after the first transaction +finishes. The asynchronous equivalent uses the same option:: + + async with AsyncModbusSerialClient("/dev/ttyUSB0", baudrate=115200, + inter_request_delay=0.020) as client: + await client.write_coil(0, True, device_id=1) + await client.read_coils(0, count=1, device_id=1) + + Client interface classes ------------------------ diff --git a/pymodbus/client/serial.py b/pymodbus/client/serial.py index 3038b2078..675a44081 100644 --- a/pymodbus/client/serial.py +++ b/pymodbus/client/serial.py @@ -3,6 +3,7 @@ from __future__ import annotations import contextlib +import math import sys import time from collections.abc import Callable @@ -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, including retries. 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 @@ -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, @@ -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: + raise ValueError("inter_request_delay must be finite and non-negative") self.comm_params = CommParams( comm_type=CommType.SERIAL, host=port, @@ -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, @@ -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, including retries. 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 @@ -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, @@ -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: + raise ValueError("inter_request_delay must be finite and non-negative") self.comm_params = CommParams( comm_type=CommType.SERIAL, host=port, @@ -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, diff --git a/pymodbus/transaction/transaction.py b/pymodbus/transaction/transaction.py index de7b5aba5..30782e024 100644 --- a/pymodbus/transaction/transaction.py +++ b/pymodbus/transaction/transaction.py @@ -5,7 +5,7 @@ import asyncio from collections.abc import Callable from threading import RLock -from time import monotonic +from time import monotonic, sleep from ..exceptions import ConnectionException, ModbusIOException from ..framer import FramerAscii, FramerBase, FramerRTU @@ -50,6 +50,7 @@ def __init__( self.max_buffer_size = framer.MAX_SIZE self.framer = framer self.retries = retries + self._last_transaction_end: float | None = None self.next_tid: int = 0 self.request_dev_id: int = 0 self.request_transaction_id: int = 0 @@ -133,6 +134,29 @@ def _io_exception_from_request( dev_id=request.dev_id, ) + def _inter_request_delay(self) -> float: + """Return remaining idle time while holding the transaction lock.""" + if ( + not self.comm_params.inter_request_delay + or self._last_transaction_end is None + ): + return 0.0 + return max( + 0.0, + self.comm_params.inter_request_delay + - (monotonic() - self._last_transaction_end), + ) + + async def _wait_before_request(self) -> None: + """Wait for the remaining idle interval without blocking the event loop.""" + if delay := self._inter_request_delay(): + await asyncio.sleep(delay) + + def _set_transaction_end(self) -> None: + """Record completion only when request spacing is enabled.""" + if self.comm_params.inter_request_delay: + self._last_transaction_end = monotonic() + def sync_execute(self, no_response_expected: bool, request: ModbusPDU) -> ModbusPDU: """Execute requests asynchronously. @@ -147,28 +171,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(): + sleep(delay) 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) + 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() if self.count_until_disconnect < 0: if self.comm_params.comm_type != CommType.SERIAL: self.connection_lost(asyncio.TimeoutError("Server not responding")) @@ -199,35 +228,40 @@ async def execute( 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] + await self._wait_before_request() 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, + self.recv_buffer = b"" + self.response_future = asyncio.Future() + self.pdu_send(request) + if no_response_expected: + return None # type: ignore[return-value] + try: + response: ModbusPDU = await asyncio.wait_for( + self.response_future, + timeout=self.comm_params.timeout_connect, ) - response.retries = count_retries - return response - except asyncio.exceptions.TimeoutError: - count_retries += 1 + 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 + finally: + self._set_transaction_end() if self.count_until_disconnect < 0: if self.comm_params.comm_type != CommType.SERIAL: self.connection_lost(asyncio.TimeoutError("Server not responding")) diff --git a/pymodbus/transport/transport.py b/pymodbus/transport/transport.py index 2f38f1498..19b3b9555 100644 --- a/pymodbus/transport/transport.py +++ b/pymodbus/transport/transport.py @@ -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.""" diff --git a/test/transaction/test_inter_request_delay.py b/test/transaction/test_inter_request_delay.py new file mode 100644 index 000000000..3233912c4 --- /dev/null +++ b/test/transaction/test_inter_request_delay.py @@ -0,0 +1,259 @@ +"""Test optional serial transaction spacing without wall-clock delays.""" + +import asyncio +import math +from concurrent.futures import ThreadPoolExecutor +from threading import Event +from unittest import mock + +import pytest + +import pymodbus.transaction.transaction as transaction_module +from pymodbus.client import AsyncModbusSerialClient, ModbusSerialClient +from pymodbus.exceptions import ModbusIOException +from pymodbus.framer import FramerRTU +from pymodbus.pdu import DecodePDU +from pymodbus.pdu.bit_message import ReadCoilsRequest, ReadCoilsResponse +from pymodbus.transaction import TransactionManager +from pymodbus.transport import CommParams, CommType + + +@pytest.fixture(name="clock") +def fake_clock(monkeypatch): + """Provide monotonic time and advancing sync/async sleeps.""" + now, waits = [100.0], [] + + def sleep(delay): + waits.append(delay) + now[0] += delay + + async def async_sleep(delay): + sleep(delay) + + monkeypatch.setattr(transaction_module, "monotonic", lambda: now[0]) + monkeypatch.setattr(transaction_module, "sleep", sleep) + monkeypatch.setattr(transaction_module.asyncio, "sleep", async_sleep) + return now, waits + + +def manager(sync, delay, retries=0): + """Construct a transaction manager without opening a port.""" + params = CommParams( + comm_type=CommType.SERIAL, inter_request_delay=delay, timeout_connect=1 + ) + client = mock.Mock() if sync else None + result = TransactionManager( + params, + FramerRTU(DecodePDU(False)), + retries, + False, + None, + None, + None, + sync_client=client, + ) + result.transport = mock.Mock() + return result + + +async def execute(transact, sync, no_response=False): + """Run the same request through either implementation.""" + request = ReadCoilsRequest(address=0, count=1, dev_id=1) + if sync: + return transact.sync_execute(no_response, request) + return await transact.execute(no_response, request) + + +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("delay", [0.0, 0.02]) +async def test_completion_spacing_and_idle_time(clock, monkeypatch, sync, delay): + """Count from response completion, skip the first wait and credit idle time.""" + now, waits = clock + transact = manager(sync, delay) + starts = [] + + def send(request): + starts.append(now[0]) + response = ReadCoilsResponse(dev_id=1, transaction_id=request.transaction_id) + + def receive(*_args): + now[0] += 0.03 + if not sync: + transact.response_future.set_result(response) + return response + + if sync: + monkeypatch.setattr(transact, "sync_get_response", receive) + else: + asyncio.get_running_loop().call_soon(receive) + + monkeypatch.setattr(transact, "pdu_send", send) + for _ in range(2): + await execute(transact, sync) + assert starts == pytest.approx([100.0, 100.03 + delay]) + now[0] += 1 + await execute(transact, sync) + assert len(waits) == (1 if delay else 0) + + +@pytest.mark.parametrize("sync", [False, True]) +async def test_timeouts_retries_and_next_call(clock, monkeypatch, sync): + """Timeouts pace retries and subsequent calls, preserving the original error.""" + now, waits = clock + transact = manager(sync, 0.02, retries=1) + send = mock.Mock() + monkeypatch.setattr(transact, "pdu_send", send) + + def timeout(*_args, **_kwargs): + now[0] += 0.2 + raise TimeoutError + + async def async_timeout(*args, **kwargs): + return timeout(*args, **kwargs) + + monkeypatch.setattr(transact, "sync_get_response", timeout) + monkeypatch.setattr(transaction_module.asyncio, "wait_for", async_timeout) + for _ in range(2): + with pytest.raises(ModbusIOException): + await execute(transact, sync) + assert send.call_count == 4 + assert waits == pytest.approx([0.02] * 3) + + +@pytest.mark.parametrize("sync", [False, True]) +async def test_no_response_and_independent_clients(clock, monkeypatch, sync): + """No-response sends are paced without sharing deadlines between clients.""" + _, waits = clock + first, second = manager(sync, 0.02), manager(sync, 0.02) + monkeypatch.setattr(first, "pdu_send", mock.Mock()) + monkeypatch.setattr(second, "pdu_send", mock.Mock()) + await execute(first, sync, True) + await execute(second, sync, True) + assert waits == [] + await execute(first, sync, True) + assert waits == pytest.approx([0.02]) + + +@pytest.mark.parametrize("sync", [False, True]) +async def test_send_error_still_paces_next_attempt(clock, monkeypatch, sync): + """An exceptional send must not bypass pacing.""" + _, waits = clock + transact = manager(sync, 0.02) + monkeypatch.setattr( + transact, "pdu_send", mock.Mock(side_effect=[OSError("send failed"), None]) + ) + with pytest.raises(OSError, match="send failed"): + await execute(transact, sync, True) + await execute(transact, sync, True) + assert waits == pytest.approx([0.02]) + + +@pytest.mark.parametrize("client_class", [ModbusSerialClient, AsyncModbusSerialClient]) +@pytest.mark.parametrize("delay", [-1, math.nan, math.inf]) +async def test_invalid_serial_delay(client_class, delay): + """Reject delay values that cannot define a finite nonnegative interval.""" + with pytest.raises(ValueError, match="inter_request_delay"): + client_class("test", inter_request_delay=delay) + + +@pytest.mark.parametrize("client_class", [ModbusSerialClient, AsyncModbusSerialClient]) +async def test_serial_option_forwarding(client_class): + """Both public clients default to zero and forward explicit delays.""" + for kwargs, expected in (({}, 0.0), ({"inter_request_delay": 0.02}, 0.02)): + client = client_class("test", **kwargs) + transact = ( + client.transaction if isinstance(client, ModbusSerialClient) else client.ctx + ) + assert transact.comm_params.inter_request_delay == expected + client.close() + + +async def test_async_concurrent_callers(clock, monkeypatch): + """Queued callers cannot send during another caller's idle interval.""" + now, waits = clock + transact = manager(False, 0.02) + starts = [] + sleeping, release = asyncio.Event(), asyncio.Event() + + async def sleep(delay): + sleeping.set() + await release.wait() + waits.append(delay) + now[0] += delay + + monkeypatch.setattr(transaction_module.asyncio, "sleep", sleep) + monkeypatch.setattr(transact, "pdu_send", lambda _request: starts.append(now[0])) + await execute(transact, False, True) + second = asyncio.create_task(execute(transact, False, True)) + await asyncio.wait_for(sleeping.wait(), 1) + third = asyncio.create_task(execute(transact, False, True)) + queued = asyncio.Event() + asyncio.get_running_loop().call_soon(queued.set) + await queued.wait() + assert starts == [100.0] + release.set() + await asyncio.wait_for(asyncio.gather(second, third), 1) + assert starts == pytest.approx([100.0, 100.02, 100.04]) + assert waits == pytest.approx([0.02, 0.02]) + + +async def test_sync_concurrent_callers(clock, monkeypatch): + """Threads sharing a client retain spacing while queued on its lock.""" + now, waits = clock + transact = manager(True, 0.02) + starts = [] + sleeping, release = Event(), Event() + + def sleep(delay): + sleeping.set() + assert release.wait(2) + waits.append(delay) + now[0] += delay + + monkeypatch.setattr(transaction_module, "sleep", sleep) + monkeypatch.setattr(transact, "pdu_send", lambda _request: starts.append(now[0])) + await execute(transact, True, True) + with ThreadPoolExecutor(max_workers=2) as executor: + second = executor.submit(transact.sync_execute, True, ReadCoilsRequest()) + try: + assert sleeping.wait(2) + third = executor.submit(transact.sync_execute, True, ReadCoilsRequest()) + assert starts == [100.0] + finally: + release.set() + second.result(timeout=2) + third.result(timeout=2) + assert starts == pytest.approx([100.0, 100.02, 100.04]) + assert waits == pytest.approx([0.02, 0.02]) + + +async def test_cancel_during_idle_interval(clock, monkeypatch): + """Cancellation sends nothing and preserves the remaining idle interval.""" + now, waits = clock + transact = manager(False, 0.02) + send = mock.Mock() + monkeypatch.setattr(transact, "pdu_send", send) + await execute(transact, False, True) + sleeping = asyncio.Event() + + async def sleep(_delay): + sleeping.set() + await asyncio.Future() + + monkeypatch.setattr(transaction_module.asyncio, "sleep", sleep) + pending = asyncio.create_task(execute(transact, False, True)) + await asyncio.wait_for(sleeping.wait(), 1) + now[0] += 0.01 + pending.cancel() + with pytest.raises(asyncio.CancelledError): + await pending + assert send.call_count == 1 + + async def finish_sleep(delay): + waits.append(delay) + now[0] += delay + + monkeypatch.setattr(transaction_module.asyncio, "sleep", finish_sleep) + await execute(transact, False, True) + assert send.call_count == 2 + assert waits == pytest.approx([0.01]) From 8bcba26649bf6eaf1b2e7b0fb690268bc5b08b79 Mon Sep 17 00:00:00 2001 From: James Morrow Date: Wed, 4 Nov 2026 15:47:30 +1100 Subject: [PATCH 03/11] Updated transaction test to include inter request delay --- test/transaction/test_transaction.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/transaction/test_transaction.py b/test/transaction/test_transaction.py index 5dffb56db..5204f1b5d 100755 --- a/test/transaction/test_transaction.py +++ b/test/transaction/test_transaction.py @@ -353,7 +353,10 @@ async def _cancel_send(self, transact, transport, delay_cond, pdu): @pytest.mark.parametrize( "cases", ["timeout", "resend", "resend_response", "new_id", "new_fc"] ) - async def test_transaction_execute_cancel(self, use_clc, cases): + @pytest.mark.parametrize("inter_request_delay", [0.0, 0.02]) + async def test_transaction_execute_cancel( + self, use_clc, cases, inter_request_delay + ): """Test next request does not get the response of a cancelled request.""" req_org = ReadHoldingRegistersRequest(dev_id=1, count=4) resp_org = ReadHoldingRegistersResponse(dev_id=1, registers=[1, 2, 3, 4]) @@ -374,6 +377,7 @@ async def test_transaction_execute_cancel(self, use_clc, cases): ) transact.retries = 0 transact.comm_params.timeout_connect = 0.5 + transact.comm_params.inter_request_delay = inter_request_delay transport = mock.Mock() transact.connection_made(transport) resp = asyncio.create_task(transact.execute(False, req_org)) From 4eed3ff0f5f3cbfb8d91050f98ebf7927e24cd11 Mon Sep 17 00:00:00 2001 From: James Morrow Date: Wed, 4 Nov 2026 15:57:16 +1100 Subject: [PATCH 04/11] Fixed python3.10 failed tests --- test/transaction/test_inter_request_delay.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/transaction/test_inter_request_delay.py b/test/transaction/test_inter_request_delay.py index 3233912c4..a7160640f 100644 --- a/test/transaction/test_inter_request_delay.py +++ b/test/transaction/test_inter_request_delay.py @@ -106,7 +106,7 @@ async def test_timeouts_retries_and_next_call(clock, monkeypatch, sync): def timeout(*_args, **_kwargs): now[0] += 0.2 - raise TimeoutError + raise asyncio.TimeoutError async def async_timeout(*args, **kwargs): return timeout(*args, **kwargs) From d0f5fe2d8bed13c7f7411ac9b8d1c181e676613a Mon Sep 17 00:00:00 2001 From: James Morrow Date: Thu, 5 Nov 2026 10:55:55 +1100 Subject: [PATCH 05/11] Changed to float comparison --- pymodbus/client/serial.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pymodbus/client/serial.py b/pymodbus/client/serial.py index 675a44081..41e532475 100644 --- a/pymodbus/client/serial.py +++ b/pymodbus/client/serial.py @@ -96,7 +96,7 @@ 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: + if not math.isfinite(inter_request_delay) or inter_request_delay < 0.0: raise ValueError("inter_request_delay must be finite and non-negative") self.comm_params = CommParams( comm_type=CommType.SERIAL, @@ -193,7 +193,7 @@ 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: + if not math.isfinite(inter_request_delay) or inter_request_delay < 0.0: raise ValueError("inter_request_delay must be finite and non-negative") self.comm_params = CommParams( comm_type=CommType.SERIAL, From ac9a0d3245c0d58c368e4ddc7d3e490ff61a20b0 Mon Sep 17 00:00:00 2001 From: James Morrow Date: Thu, 5 Nov 2026 11:38:11 +1100 Subject: [PATCH 06/11] Updated test cases based on feedback --- test/transaction/test_inter_request_delay.py | 461 +++++++++---------- 1 file changed, 226 insertions(+), 235 deletions(-) diff --git a/test/transaction/test_inter_request_delay.py b/test/transaction/test_inter_request_delay.py index a7160640f..a64b5f497 100644 --- a/test/transaction/test_inter_request_delay.py +++ b/test/transaction/test_inter_request_delay.py @@ -1,12 +1,13 @@ -"""Test optional serial transaction spacing without wall-clock delays.""" +"""Test optional serial transaction spacing.""" import asyncio import math -from concurrent.futures import ThreadPoolExecutor -from threading import Event +from itertools import pairwise +from time import monotonic, sleep from unittest import mock import pytest +import pytest_asyncio import pymodbus.transaction.transaction as transaction_module from pymodbus.client import AsyncModbusSerialClient, ModbusSerialClient @@ -15,245 +16,235 @@ from pymodbus.pdu import DecodePDU from pymodbus.pdu.bit_message import ReadCoilsRequest, ReadCoilsResponse from pymodbus.transaction import TransactionManager -from pymodbus.transport import CommParams, CommType +from pymodbus.transport import CommType -@pytest.fixture(name="clock") -def fake_clock(monkeypatch): - """Provide monotonic time and advancing sync/async sleeps.""" - now, waits = [100.0], [] +@pytest.mark.usefixtures("use_clc") +@pytest.mark.parametrize("use_port", [5098]) +@pytest.mark.parametrize("use_comm_type", [CommType.SERIAL]) +class TestInterRequestDelay: + """Exercise real transactions with mocked serial I/O.""" - def sleep(delay): - waits.append(delay) - now[0] += delay - - async def async_sleep(delay): - sleep(delay) - - monkeypatch.setattr(transaction_module, "monotonic", lambda: now[0]) - monkeypatch.setattr(transaction_module, "sleep", sleep) - monkeypatch.setattr(transaction_module.asyncio, "sleep", async_sleep) - return now, waits - - -def manager(sync, delay, retries=0): - """Construct a transaction manager without opening a port.""" - params = CommParams( - comm_type=CommType.SERIAL, inter_request_delay=delay, timeout_connect=1 - ) - client = mock.Mock() if sync else None - result = TransactionManager( - params, - FramerRTU(DecodePDU(False)), - retries, - False, - None, - None, - None, - sync_client=client, + @pytest_asyncio.fixture( + name="transact", params=[False, True], ids=["async", "sync"] ) - result.transport = mock.Mock() - return result - - -async def execute(transact, sync, no_response=False): - """Run the same request through either implementation.""" - request = ReadCoilsRequest(address=0, count=1, dev_id=1) - if sync: - return transact.sync_execute(no_response, request) - return await transact.execute(no_response, request) - - -@pytest.mark.parametrize("sync", [False, True]) -@pytest.mark.parametrize("delay", [0.0, 0.02]) -async def test_completion_spacing_and_idle_time(clock, monkeypatch, sync, delay): - """Count from response completion, skip the first wait and credit idle time.""" - now, waits = clock - transact = manager(sync, delay) - starts = [] - - def send(request): - starts.append(now[0]) - response = ReadCoilsResponse(dev_id=1, transaction_id=request.transaction_id) - - def receive(*_args): - now[0] += 0.03 - if not sync: - transact.response_future.set_result(response) - return response - - if sync: - monkeypatch.setattr(transact, "sync_get_response", receive) - else: - asyncio.get_running_loop().call_soon(receive) - - monkeypatch.setattr(transact, "pdu_send", send) - for _ in range(2): - await execute(transact, sync) - assert starts == pytest.approx([100.0, 100.03 + delay]) - now[0] += 1 - await execute(transact, sync) - assert len(waits) == (1 if delay else 0) - - -@pytest.mark.parametrize("sync", [False, True]) -async def test_timeouts_retries_and_next_call(clock, monkeypatch, sync): - """Timeouts pace retries and subsequent calls, preserving the original error.""" - now, waits = clock - transact = manager(sync, 0.02, retries=1) - send = mock.Mock() - monkeypatch.setattr(transact, "pdu_send", send) - - def timeout(*_args, **_kwargs): - now[0] += 0.2 - raise asyncio.TimeoutError - - async def async_timeout(*args, **kwargs): - return timeout(*args, **kwargs) - - monkeypatch.setattr(transact, "sync_get_response", timeout) - monkeypatch.setattr(transaction_module.asyncio, "wait_for", async_timeout) - for _ in range(2): - with pytest.raises(ModbusIOException): - await execute(transact, sync) - assert send.call_count == 4 - assert waits == pytest.approx([0.02] * 3) - - -@pytest.mark.parametrize("sync", [False, True]) -async def test_no_response_and_independent_clients(clock, monkeypatch, sync): - """No-response sends are paced without sharing deadlines between clients.""" - _, waits = clock - first, second = manager(sync, 0.02), manager(sync, 0.02) - monkeypatch.setattr(first, "pdu_send", mock.Mock()) - monkeypatch.setattr(second, "pdu_send", mock.Mock()) - await execute(first, sync, True) - await execute(second, sync, True) - assert waits == [] - await execute(first, sync, True) - assert waits == pytest.approx([0.02]) - + async def transaction(self, request, use_clc): + """Use the existing communication fixture for both transaction paths.""" + use_clc.inter_request_delay = 0.02 + use_clc.timeout_connect = 0.05 + client = mock.Mock() if request.param else None + manager = TransactionManager( + use_clc, + FramerRTU(DecodePDU(False)), + 0, + False, + None, + None, + None, + sync_client=client, + ) + manager.connection_made(mock.Mock()) + yield manager + manager.close() + + @pytest.fixture(name="wire") + def serial_output(self, transact): + """Observe bytes sent without replacing transaction methods.""" + return ( + transact.sync_client.send if transact.is_sync else transact.transport.write + ) -@pytest.mark.parametrize("sync", [False, True]) -async def test_send_error_still_paces_next_attempt(clock, monkeypatch, sync): - """An exceptional send must not bypass pacing.""" - _, waits = clock - transact = manager(sync, 0.02) - monkeypatch.setattr( - transact, "pdu_send", mock.Mock(side_effect=[OSError("send failed"), None]) + async def execute(self, transact, no_response=False): + """Send one request through the selected transaction implementation.""" + request = ReadCoilsRequest(address=0, count=1, dev_id=1) + if transact.is_sync: + return transact.sync_execute(no_response, request) + return await transact.execute(no_response, request) + + @pytest.mark.parametrize( + ("delay", "last_end", "now", "expected"), + [ + (0.0, 100.0, 100.0, 0.0), + (0.02, None, 100.0, 0.0), + (0.02, 100.0, 100.0, 0.02), + (0.02, 100.0, 100.01, 0.01), + (0.02, 100.0, 100.02, 0.0), + (0.02, 100.0, 101.0, 0.0), + ], ) - with pytest.raises(OSError, match="send failed"): - await execute(transact, sync, True) - await execute(transact, sync, True) - assert waits == pytest.approx([0.02]) - - -@pytest.mark.parametrize("client_class", [ModbusSerialClient, AsyncModbusSerialClient]) -@pytest.mark.parametrize("delay", [-1, math.nan, math.inf]) -async def test_invalid_serial_delay(client_class, delay): - """Reject delay values that cannot define a finite nonnegative interval.""" - with pytest.raises(ValueError, match="inter_request_delay"): - client_class("test", inter_request_delay=delay) - + async def test_remaining_interval(self, transact, delay, last_end, now, expected): + """First requests, disabled spacing and elapsed idle time need no wait.""" + transact.comm_params.inter_request_delay = delay + transact._last_transaction_end = last_end + # Replace only the imported reference owned by the transaction module. + with mock.patch.object(transaction_module, "monotonic", return_value=now): + assert transact._inter_request_delay() == pytest.approx(expected) + + @pytest.mark.parametrize("delay", [0.0, 0.02]) + async def test_completion_spacing(self, transact, wire, delay): + """Measure the interval from response completion, not request start.""" + transact.comm_params.inter_request_delay = delay + starts, completions = [], [] + response = transact.framer.buildFrame(ReadCoilsResponse(dev_id=1, bits=[True])) + + def receive(): + completions.append(monotonic()) + transact.data_received(response) + + def send(*_args, **_kwargs): + starts.append(monotonic()) + if not transact.is_sync: + asyncio.get_running_loop().call_later(0.03, receive) + + def read(_size): + sleep(0.03) + completions.append(monotonic()) + return response -@pytest.mark.parametrize("client_class", [ModbusSerialClient, AsyncModbusSerialClient]) -async def test_serial_option_forwarding(client_class): - """Both public clients default to zero and forward explicit delays.""" - for kwargs, expected in (({}, 0.0), ({"inter_request_delay": 0.02}, 0.02)): - client = client_class("test", **kwargs) - transact = ( - client.transaction if isinstance(client, ModbusSerialClient) else client.ctx + wire.side_effect = send + if transact.is_sync: + transact.sync_client.recv.side_effect = read + for _ in range(2): + result = await self.execute(transact) + assert result.bits[0] + assert len(starts) == len(completions) == 2 + assert starts[1] - completions[0] >= delay - 0.001 + assert (transact._last_transaction_end is None) == (delay == 0.0) + + async def test_timeouts_retries_and_next_call(self, transact, wire): + """Real receive timeouts pace retries and the next transaction.""" + transact.retries = 1 + gaps = [] + + def send(*_args, **_kwargs): + if transact._last_transaction_end is not None: + gaps.append(monotonic() - transact._last_transaction_end) + + wire.side_effect = send + if transact.is_sync: + transact.sync_client.recv.return_value = b"" + for _ in range(2): + with pytest.raises(ModbusIOException): + await self.execute(transact) + assert wire.call_count == 4 + minimum = transact.comm_params.inter_request_delay + assert len(gaps) == 3 + assert all(gap >= minimum - 0.001 for gap in gaps) + + async def test_no_response_and_independent_clients(self, transact, wire, use_clc): + """No-response transactions record completion only on their own client.""" + client = mock.Mock() if transact.is_sync else None + second = TransactionManager( + use_clc, + FramerRTU(DecodePDU(False)), + 0, + False, + None, + None, + None, + sync_client=client, ) - assert transact.comm_params.inter_request_delay == expected - client.close() - - -async def test_async_concurrent_callers(clock, monkeypatch): - """Queued callers cannot send during another caller's idle interval.""" - now, waits = clock - transact = manager(False, 0.02) - starts = [] - sleeping, release = asyncio.Event(), asyncio.Event() - - async def sleep(delay): - sleeping.set() - await release.wait() - waits.append(delay) - now[0] += delay - - monkeypatch.setattr(transaction_module.asyncio, "sleep", sleep) - monkeypatch.setattr(transact, "pdu_send", lambda _request: starts.append(now[0])) - await execute(transact, False, True) - second = asyncio.create_task(execute(transact, False, True)) - await asyncio.wait_for(sleeping.wait(), 1) - third = asyncio.create_task(execute(transact, False, True)) - queued = asyncio.Event() - asyncio.get_running_loop().call_soon(queued.set) - await queued.wait() - assert starts == [100.0] - release.set() - await asyncio.wait_for(asyncio.gather(second, third), 1) - assert starts == pytest.approx([100.0, 100.02, 100.04]) - assert waits == pytest.approx([0.02, 0.02]) - - -async def test_sync_concurrent_callers(clock, monkeypatch): - """Threads sharing a client retain spacing while queued on its lock.""" - now, waits = clock - transact = manager(True, 0.02) - starts = [] - sleeping, release = Event(), Event() - - def sleep(delay): - sleeping.set() - assert release.wait(2) - waits.append(delay) - now[0] += delay - - monkeypatch.setattr(transaction_module, "sleep", sleep) - monkeypatch.setattr(transact, "pdu_send", lambda _request: starts.append(now[0])) - await execute(transact, True, True) - with ThreadPoolExecutor(max_workers=2) as executor: - second = executor.submit(transact.sync_execute, True, ReadCoilsRequest()) + second.connection_made(mock.Mock()) + starts = [] + wire.side_effect = lambda *_args, **_kwargs: starts.append(monotonic()) try: - assert sleeping.wait(2) - third = executor.submit(transact.sync_execute, True, ReadCoilsRequest()) - assert starts == [100.0] + await self.execute(transact, True) + assert transact._last_transaction_end is not None + previous_completion = second._last_transaction_end + assert previous_completion is None + assert second._inter_request_delay() == 0.0 + await self.execute(second, True) + assert second._last_transaction_end is not None + await self.execute(transact, True) + assert starts[1] - starts[0] >= 0.019 finally: - release.set() - second.result(timeout=2) - third.result(timeout=2) - assert starts == pytest.approx([100.0, 100.02, 100.04]) - assert waits == pytest.approx([0.02, 0.02]) - - -async def test_cancel_during_idle_interval(clock, monkeypatch): - """Cancellation sends nothing and preserves the remaining idle interval.""" - now, waits = clock - transact = manager(False, 0.02) - send = mock.Mock() - monkeypatch.setattr(transact, "pdu_send", send) - await execute(transact, False, True) - sleeping = asyncio.Event() - - async def sleep(_delay): - sleeping.set() - await asyncio.Future() - - monkeypatch.setattr(transaction_module.asyncio, "sleep", sleep) - pending = asyncio.create_task(execute(transact, False, True)) - await asyncio.wait_for(sleeping.wait(), 1) - now[0] += 0.01 - pending.cancel() - with pytest.raises(asyncio.CancelledError): - await pending - assert send.call_count == 1 - - async def finish_sleep(delay): - waits.append(delay) - now[0] += delay - - monkeypatch.setattr(transaction_module.asyncio, "sleep", finish_sleep) - await execute(transact, False, True) - assert send.call_count == 2 - assert waits == pytest.approx([0.01]) + second.close() + + @pytest.mark.parametrize("error", [OSError, asyncio.TimeoutError]) + async def test_send_error_propagates_and_paces_next_attempt( + self, transact, wire, error + ): + """Send errors propagate without entering the receive retry handler.""" + transact.retries = 1 + wire.side_effect = error("send failed") + with pytest.raises(error, match="send failed"): + await self.execute(transact, True) + assert wire.call_count == 1 + completed = transact._last_transaction_end + assert completed is not None + starts = [] + wire.side_effect = lambda *_args, **_kwargs: starts.append(monotonic()) + await self.execute(transact, True) + assert starts[0] - completed >= 0.019 + + @pytest.mark.parametrize( + "client_class", [ModbusSerialClient, AsyncModbusSerialClient] + ) + @pytest.mark.parametrize("delay", [-1.0, math.nan, math.inf]) + async def test_invalid_serial_delay(self, client_class, delay): + """Reject delay values that cannot define a finite nonnegative interval.""" + with pytest.raises(ValueError, match="inter_request_delay"): + client_class("test", inter_request_delay=delay) + + @pytest.mark.parametrize( + "client_class", [ModbusSerialClient, AsyncModbusSerialClient] + ) + async def test_serial_option_forwarding(self, client_class): + """Both public clients default to zero and forward explicit delays.""" + for kwargs, expected in (({}, 0.0), ({"inter_request_delay": 0.02}, 0.02)): + client = client_class("test", **kwargs) + try: + transact = ( + client.transaction + if isinstance(client, ModbusSerialClient) + else client.ctx + ) + assert transact.comm_params.inter_request_delay == expected + finally: + client.close() + + @pytest.mark.parametrize("transact", [False], indirect=True) + async def test_async_same_device_callers(self, transact, wire): + """Queued requests to the same slave preserve the recovery interval.""" + starts = [] + wire.side_effect = lambda *_args, **_kwargs: starts.append(monotonic()) + await self.execute(transact, True) + await asyncio.wait_for( + asyncio.gather(self.execute(transact, True), self.execute(transact, True)), + timeout=2, + ) + assert len(starts) == 3 + assert all(later - earlier >= 0.019 for earlier, later in pairwise(starts)) + + @pytest.mark.parametrize("transact", [False], indirect=True) + async def test_cancel_during_idle_interval(self, transact, wire): + """Cancellation sends nothing and does not reset the last completion.""" + transact.comm_params.inter_request_delay = 0.1 + await self.execute(transact, True) + completed = transact._last_transaction_end + waiting = asyncio.Event() + original_wait = transact._wait_before_request + + async def observe_wait(): + waiting.set() + await original_wait() + + with mock.patch.object( + transact, "_wait_before_request", side_effect=observe_wait + ): + pending = asyncio.create_task(self.execute(transact, True)) + try: + await asyncio.wait_for(waiting.wait(), timeout=2) + pending.cancel() + with pytest.raises(asyncio.CancelledError): + await pending + finally: + pending.cancel() + await asyncio.gather(pending, return_exceptions=True) + assert wire.call_count == 1 + assert transact._last_transaction_end == completed + starts = [] + wire.side_effect = lambda *_args, **_kwargs: starts.append(monotonic()) + await self.execute(transact, True) + assert wire.call_count == 2 + assert starts[0] - completed >= 0.099 From e9330a23424f427f8c5b805dbcd455a8bf00b48f Mon Sep 17 00:00:00 2001 From: James Morrow Date: Thu, 5 Nov 2026 12:44:23 +1100 Subject: [PATCH 07/11] Updated examples --- doc/source/client.rst | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/doc/source/client.rst b/doc/source/client.rst index 364f61db2..671663b32 100644 --- a/doc/source/client.rst +++ b/doc/source/client.rst @@ -249,16 +249,24 @@ Both serial clients accept ``inter_request_delay`` in seconds, and defaults to ` client = ModbusSerialClient("/dev/ttyUSB0", baudrate=115200, inter_request_delay=0.020) with client: - client.write_coil(0, True, device_id=1) - client.read_coils(0, count=1, device_id=1) + 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. The asynchronous equivalent uses the same option:: async with AsyncModbusSerialClient("/dev/ttyUSB0", baudrate=115200, inter_request_delay=0.020) as client: - await client.write_coil(0, True, device_id=1) - await client.read_coils(0, count=1, device_id=1) + 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 From 2ae8ee736303e2312f84665362a073c3cf73ea63 Mon Sep 17 00:00:00 2001 From: James Morrow Date: Thu, 5 Nov 2026 13:08:55 +1100 Subject: [PATCH 08/11] Track inter-request delay by slave ID --- doc/source/client.rst | 7 ++- pymodbus/client/serial.py | 4 +- pymodbus/transaction/transaction.py | 44 +++++++------- test/transaction/test_inter_request_delay.py | 60 ++++++++++++++------ 4 files changed, 74 insertions(+), 41 deletions(-) diff --git a/doc/source/client.rst b/doc/source/client.rst index 671663b32..8dfd1e4ec 100644 --- a/doc/source/client.rst +++ b/doc/source/client.rst @@ -257,7 +257,12 @@ Both serial clients accept ``inter_request_delay`` in seconds, and defaults to ` ) The second request waits until at least 20 ms after the first transaction -finishes. The asynchronous equivalent uses the same option:: +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: diff --git a/pymodbus/client/serial.py b/pymodbus/client/serial.py index 41e532475..db7912041 100644 --- a/pymodbus/client/serial.py +++ b/pymodbus/client/serial.py @@ -41,7 +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, including retries. Default 0.0 (disabled). + :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 @@ -143,7 +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, including retries. Default 0.0 (disabled). + :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 diff --git a/pymodbus/transaction/transaction.py b/pymodbus/transaction/transaction.py index 583ed390b..4f0e4d5d5 100644 --- a/pymodbus/transaction/transaction.py +++ b/pymodbus/transaction/transaction.py @@ -50,7 +50,7 @@ def __init__( self.max_buffer_size = framer.MAX_SIZE self.framer = framer self.retries = retries - self._last_transaction_end: float | None = None + self._last_transaction_end: dict[int, float] = {} self.next_tid: int = 0 self.request_dev_id: int = 0 self.request_transaction_id: int = 0 @@ -138,28 +138,30 @@ def _io_exception_from_request( dev_id=request.dev_id, ) - def _inter_request_delay(self) -> float: - """Return remaining idle time while holding the transaction lock.""" - if ( - not self.comm_params.inter_request_delay - or self._last_transaction_end is None - ): + 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 - return max( - 0.0, - self.comm_params.inter_request_delay - - (monotonic() - self._last_transaction_end), - ) + if dev_id == 0: + # 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, float("-inf")), + self._last_transaction_end.get(0, float("-inf")), + ) + remaining = self.comm_params.inter_request_delay - (monotonic() - last_end) + return remaining if remaining > 0.0 else 0.0 - async def _wait_before_request(self) -> None: + async def _wait_before_request(self, dev_id: int) -> None: """Wait for the remaining idle interval without blocking the event loop.""" - if delay := self._inter_request_delay(): + if delay := self._inter_request_delay(dev_id): await asyncio.sleep(delay) - def _set_transaction_end(self) -> None: - """Record completion only when request spacing is enabled.""" + 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 = monotonic() + self._last_transaction_end[dev_id] = monotonic() def sync_execute(self, no_response_expected: bool, request: ModbusPDU) -> ModbusPDU: """Execute requests asynchronously. @@ -175,7 +177,7 @@ def sync_execute(self, no_response_expected: bool, request: ModbusPDU) -> Modbus request.transaction_id = self.getNextTID() count_retries = 0 while count_retries <= self.retries: - if delay := self._inter_request_delay(): + if delay := self._inter_request_delay(request.dev_id): sleep(delay) try: self.pdu_send(request) @@ -201,7 +203,7 @@ def sync_execute(self, no_response_expected: bool, request: ModbusPDU) -> Modbus except asyncio.exceptions.TimeoutError: count_retries += 1 finally: - self._set_transaction_end() + self._set_transaction_end(request.dev_id) if self.count_until_disconnect < 0: if self.comm_params.comm_type != CommType.SERIAL: self.connection_lost(asyncio.TimeoutError("Server not responding")) @@ -236,7 +238,7 @@ async def execute( # noqa: C901 request.transaction_id = self.getNextTID() count_retries = 0 while count_retries <= self.retries: - await self._wait_before_request() + await self._wait_before_request(request.dev_id) try: self.recv_buffer = b"" self.response_future = asyncio.Future() @@ -282,7 +284,7 @@ async def execute( # noqa: C901 ) raise finally: - self._set_transaction_end() + self._set_transaction_end(request.dev_id) if self.count_until_disconnect < 0: if self.comm_params.comm_type != CommType.SERIAL: self.connection_lost(asyncio.TimeoutError("Server not responding")) diff --git a/test/transaction/test_inter_request_delay.py b/test/transaction/test_inter_request_delay.py index a64b5f497..43cbfa5e6 100644 --- a/test/transaction/test_inter_request_delay.py +++ b/test/transaction/test_inter_request_delay.py @@ -54,9 +54,9 @@ def serial_output(self, transact): transact.sync_client.send if transact.is_sync else transact.transport.write ) - async def execute(self, transact, no_response=False): + async def execute(self, transact, no_response=False, dev_id=1): """Send one request through the selected transaction implementation.""" - request = ReadCoilsRequest(address=0, count=1, dev_id=1) + request = ReadCoilsRequest(address=0, count=1, dev_id=dev_id) if transact.is_sync: return transact.sync_execute(no_response, request) return await transact.execute(no_response, request) @@ -75,10 +75,10 @@ async def execute(self, transact, no_response=False): async def test_remaining_interval(self, transact, delay, last_end, now, expected): """First requests, disabled spacing and elapsed idle time need no wait.""" transact.comm_params.inter_request_delay = delay - transact._last_transaction_end = last_end + transact._last_transaction_end = {} if last_end is None else {1: last_end} # Replace only the imported reference owned by the transaction module. with mock.patch.object(transaction_module, "monotonic", return_value=now): - assert transact._inter_request_delay() == pytest.approx(expected) + assert transact._inter_request_delay(1) == pytest.approx(expected) @pytest.mark.parametrize("delay", [0.0, 0.02]) async def test_completion_spacing(self, transact, wire, delay): @@ -109,7 +109,7 @@ def read(_size): assert result.bits[0] assert len(starts) == len(completions) == 2 assert starts[1] - completions[0] >= delay - 0.001 - assert (transact._last_transaction_end is None) == (delay == 0.0) + assert (not transact._last_transaction_end) == (delay == 0.0) async def test_timeouts_retries_and_next_call(self, transact, wire): """Real receive timeouts pace retries and the next transaction.""" @@ -117,8 +117,8 @@ async def test_timeouts_retries_and_next_call(self, transact, wire): gaps = [] def send(*_args, **_kwargs): - if transact._last_transaction_end is not None: - gaps.append(monotonic() - transact._last_transaction_end) + if 1 in transact._last_transaction_end: + gaps.append(monotonic() - transact._last_transaction_end[1]) wire.side_effect = send if transact.is_sync: @@ -149,12 +149,12 @@ async def test_no_response_and_independent_clients(self, transact, wire, use_clc wire.side_effect = lambda *_args, **_kwargs: starts.append(monotonic()) try: await self.execute(transact, True) - assert transact._last_transaction_end is not None - previous_completion = second._last_transaction_end + assert 1 in transact._last_transaction_end + previous_completion = second._last_transaction_end.get(1) assert previous_completion is None - assert second._inter_request_delay() == 0.0 + assert second._inter_request_delay(1) == 0.0 await self.execute(second, True) - assert second._last_transaction_end is not None + assert 1 in second._last_transaction_end await self.execute(transact, True) assert starts[1] - starts[0] >= 0.019 finally: @@ -170,7 +170,7 @@ async def test_send_error_propagates_and_paces_next_attempt( with pytest.raises(error, match="send failed"): await self.execute(transact, True) assert wire.call_count == 1 - completed = transact._last_transaction_end + completed = transact._last_transaction_end.get(1) assert completed is not None starts = [] wire.side_effect = lambda *_args, **_kwargs: starts.append(monotonic()) @@ -205,7 +205,7 @@ async def test_serial_option_forwarding(self, client_class): @pytest.mark.parametrize("transact", [False], indirect=True) async def test_async_same_device_callers(self, transact, wire): - """Queued requests to the same slave preserve the recovery interval.""" + """Queued requests to the same slave preserve the delay interval.""" starts = [] wire.side_effect = lambda *_args, **_kwargs: starts.append(monotonic()) await self.execute(transact, True) @@ -221,13 +221,13 @@ async def test_cancel_during_idle_interval(self, transact, wire): """Cancellation sends nothing and does not reset the last completion.""" transact.comm_params.inter_request_delay = 0.1 await self.execute(transact, True) - completed = transact._last_transaction_end + completed = transact._last_transaction_end.get(1) waiting = asyncio.Event() original_wait = transact._wait_before_request - async def observe_wait(): + async def observe_wait(dev_id): waiting.set() - await original_wait() + await original_wait(dev_id) with mock.patch.object( transact, "_wait_before_request", side_effect=observe_wait @@ -242,9 +242,35 @@ async def observe_wait(): pending.cancel() await asyncio.gather(pending, return_exceptions=True) assert wire.call_count == 1 - assert transact._last_transaction_end == completed + assert transact._last_transaction_end.get(1) == completed starts = [] wire.side_effect = lambda *_args, **_kwargs: starts.append(monotonic()) await self.execute(transact, True) assert wire.call_count == 2 assert starts[0] - completed >= 0.099 + + async def test_device_intervals_and_broadcasts(self, transact): + """Other devices retain independent deadlines; broadcasts affect all.""" + with mock.patch.object(transaction_module, "monotonic", return_value=100.0): + transact._set_transaction_end(1) + assert transact._inter_request_delay(1) == pytest.approx(0.02) + assert transact._inter_request_delay(2) == 0.0 + assert transact._inter_request_delay(0) == pytest.approx(0.02) + with mock.patch.object(transaction_module, "monotonic", return_value=100.01): + transact._set_transaction_end(2) + assert transact._inter_request_delay(1) == pytest.approx(0.01) + assert transact._inter_request_delay(2) == pytest.approx(0.02) + transact._set_transaction_end(0) + assert transact._inter_request_delay(1) == pytest.approx(0.02) + assert transact._inter_request_delay(3) == pytest.approx(0.02) + + async def test_interleaved_devices(self, transact, wire): + """Requests to B do not reset A's delay interval.""" + starts = [] + wire.side_effect = lambda *_args, **_kwargs: starts.append(monotonic()) + await self.execute(transact, True, 1) + completed = transact._last_transaction_end[1] + await self.execute(transact, True, 2) + assert transact._last_transaction_end[1] == completed + await self.execute(transact, True, 1) + assert starts[2] - completed >= 0.019 From 277d913fceec1cbbc9b30fecd3902860940f4e55 Mon Sep 17 00:00:00 2001 From: James Morrow Date: Thu, 5 Nov 2026 13:24:26 +1100 Subject: [PATCH 09/11] Release async transaction lock during inter-request delays --- pymodbus/transaction/transaction.py | 54 +++++---- test/transaction/test_inter_request_delay.py | 117 ++++++++++++++++++- 2 files changed, 143 insertions(+), 28 deletions(-) diff --git a/pymodbus/transaction/transaction.py b/pymodbus/transaction/transaction.py index 4f0e4d5d5..33b19157c 100644 --- a/pymodbus/transaction/transaction.py +++ b/pymodbus/transaction/transaction.py @@ -3,7 +3,8 @@ from __future__ import annotations import asyncio -from collections.abc import Callable +from collections.abc import AsyncGenerator, Callable +from contextlib import asynccontextmanager from threading import RLock from time import monotonic, sleep @@ -153,9 +154,15 @@ def _inter_request_delay(self, dev_id: int) -> float: remaining = self.comm_params.inter_request_delay - (monotonic() - last_end) return remaining if remaining > 0.0 else 0.0 - async def _wait_before_request(self, dev_id: int) -> None: - """Wait for the remaining idle interval without blocking the event loop.""" - if delay := self._inter_request_delay(dev_id): + @asynccontextmanager + async def _request_lock(self, dev_id: int) -> AsyncGenerator[None, None]: + """Serialize attempts, releasing the wire during device delay intervals.""" + while True: + async with self._lock: + delay = self._inter_request_delay(dev_id) + if not delay: + yield + return await asyncio.sleep(delay) def _set_transaction_end(self, dev_id: int) -> None: @@ -230,15 +237,14 @@ async def execute( # noqa: C901 raise ConnectionException( "Client cannot connect (automatic retry continuing) !!" ) - 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: - await self._wait_before_request(request.dev_id) + request.transaction_id = self.getNextTID() + count_retries = 0 + while count_retries <= self.retries: + async with self._request_lock(request.dev_id): + 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: self.recv_buffer = b"" self.response_future = asyncio.Future() @@ -285,17 +291,17 @@ async def execute( # noqa: C901 raise finally: self._set_transaction_end(request.dev_id) - if self.count_until_disconnect < 0: - if self.comm_params.comm_type != CommType.SERIAL: - self.connection_lost(asyncio.TimeoutError("Server not responding")) - raise self._io_exception_from_request( - "ERROR: No response received of the last requests (default: retries+3), CLOSING CONNECTION.", - request, - ) - self.count_until_disconnect -= 1 - txt = f"No response received after {self.retries} retries, continue with next request" - Log.error(txt) - raise self._io_exception_from_request(txt, request) + if self.count_until_disconnect < 0: + if self.comm_params.comm_type != CommType.SERIAL: + self.connection_lost(asyncio.TimeoutError("Server not responding")) + raise self._io_exception_from_request( + "ERROR: No response received of the last requests (default: retries+3), CLOSING CONNECTION.", + request, + ) + self.count_until_disconnect -= 1 + txt = f"No response received after {self.retries} retries, continue with next request" + Log.error(txt) + raise self._io_exception_from_request(txt, request) def pdu_send(self, pdu: ModbusPDU, addr: tuple | None = None) -> None: """Build byte stream and send.""" diff --git a/test/transaction/test_inter_request_delay.py b/test/transaction/test_inter_request_delay.py index 43cbfa5e6..f47caa793 100644 --- a/test/transaction/test_inter_request_delay.py +++ b/test/transaction/test_inter_request_delay.py @@ -223,14 +223,14 @@ async def test_cancel_during_idle_interval(self, transact, wire): await self.execute(transact, True) completed = transact._last_transaction_end.get(1) waiting = asyncio.Event() - original_wait = transact._wait_before_request + original_delay = transact._inter_request_delay - async def observe_wait(dev_id): + def observe_delay(dev_id): waiting.set() - await original_wait(dev_id) + return original_delay(dev_id) with mock.patch.object( - transact, "_wait_before_request", side_effect=observe_wait + transact, "_inter_request_delay", side_effect=observe_delay ): pending = asyncio.create_task(self.execute(transact, True)) try: @@ -274,3 +274,112 @@ async def test_interleaved_devices(self, transact, wire): assert transact._last_transaction_end[1] == completed await self.execute(transact, True, 1) assert starts[2] - completed >= 0.019 + + @pytest.mark.parametrize("transact", [False], indirect=True) + async def test_ready_device_overtakes_waiting_device(self, transact, wire): + """Waiting for a delay interval must not reserve the wire against device B.""" + transact.comm_params.inter_request_delay = 0.2 + sent = [] + wire.side_effect = lambda data: sent.append(data[0]) + await self.execute(transact, True, 1) + waiting = asyncio.Event() + original_delay = transact._inter_request_delay + + def observe_delay(dev_id): + waiting.set() + return original_delay(dev_id) + + with mock.patch.object( + transact, "_inter_request_delay", side_effect=observe_delay + ): + pending = asyncio.create_task(self.execute(transact, True, 1)) + try: + await asyncio.wait_for(waiting.wait(), 2) + await self.execute(transact, True, 2) + assert sent == [1, 2] + await asyncio.wait_for(pending, 2) + assert sent == [1, 2, 1] + finally: + pending.cancel() + await asyncio.gather(pending, return_exceptions=True) + + @pytest.mark.parametrize("transact", [False], indirect=True) + async def test_other_device_waits_for_active_response(self, transact, wire): + """Delay intervals can overlap other work, but wire transactions cannot.""" + sent = [] + started = asyncio.Event() + + def send(data): + sent.append(data[0]) + started.set() + + wire.side_effect = send + transact.comm_params.timeout_connect = 2 + first = asyncio.create_task(self.execute(transact, False, 1)) + second = asyncio.create_task(self.execute(transact, True, 2)) + try: + await asyncio.wait_for(started.wait(), 1) + await asyncio.sleep(0) + assert sent == [1] + response = transact.framer.buildFrame( + ReadCoilsResponse(dev_id=1, bits=[True]) + ) + transact.data_received(response) + await asyncio.wait_for(asyncio.gather(first, second), 2) + assert sent == [1, 2] + finally: + first.cancel() + second.cancel() + await asyncio.gather(first, second, return_exceptions=True) + + @pytest.mark.parametrize("transact", [False], indirect=True) + async def test_cancel_while_waiting_for_wire_lock(self, transact, wire): + """A cancelled waiter must not release another caller's wire lock.""" + await transact._lock.acquire() + pending = asyncio.create_task(self.execute(transact, True)) + try: + await asyncio.sleep(0) + pending.cancel() + with pytest.raises(asyncio.CancelledError): + await pending + assert transact._lock.locked() + wire.assert_not_called() + assert transact._last_transaction_end == {} + finally: + pending.cancel() + await asyncio.gather(pending, return_exceptions=True) + transact._lock.release() + await asyncio.wait_for(self.execute(transact, True), 1) + wire.assert_called_once() + assert not transact._lock.locked() + + @pytest.mark.parametrize("transact", [False], indirect=True) + async def test_other_device_runs_during_retry_delay(self, transact, wire): + """A timed-out slave's retry interval must not reserve the wire.""" + transact.retries = 1 + transact.comm_params.inter_request_delay = 0.2 + sent = [] + wire.side_effect = lambda data: sent.append(data[0]) + retry_waiting = asyncio.Event() + original_delay = transact._inter_request_delay + + def observe_delay(dev_id): + if dev_id == 1 and sent: + retry_waiting.set() + return original_delay(dev_id) + + with mock.patch.object( + transact, "_inter_request_delay", side_effect=observe_delay + ): + pending = asyncio.create_task(self.execute(transact, False, 1)) + try: + await asyncio.wait_for(retry_waiting.wait(), 2) + await self.execute(transact, True, 2) + assert sent == [1, 2] + with pytest.raises(ModbusIOException): + await asyncio.wait_for(pending, 2) + assert sent == [1, 2, 1] + assert not transact._lock.locked() + finally: + pending.cancel() + await asyncio.gather(pending, return_exceptions=True) From 8eccdc49cdbd3a4fd187b4582e5e90ef8ce66ecb Mon Sep 17 00:00:00 2001 From: James Morrow Date: Thu, 5 Nov 2026 13:50:52 +1100 Subject: [PATCH 10/11] Pylint fixes --- pymodbus/transaction/transaction.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pymodbus/transaction/transaction.py b/pymodbus/transaction/transaction.py index 7798a281d..353fc1077 100644 --- a/pymodbus/transaction/transaction.py +++ b/pymodbus/transaction/transaction.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import math from collections.abc import AsyncGenerator, Callable from contextlib import asynccontextmanager from threading import RLock @@ -143,24 +144,23 @@ 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: + 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, float("-inf")), - self._last_transaction_end.get(0, float("-inf")), + self._last_transaction_end.get(dev_id, -math.inf), + self._last_transaction_end.get(0, -math.inf), ) remaining = self.comm_params.inter_request_delay - (monotonic() - last_end) return remaining if remaining > 0.0 else 0.0 @asynccontextmanager - async def _request_lock(self, dev_id: int) -> AsyncGenerator[None, None]: + 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: - delay = self._inter_request_delay(dev_id) - if not delay: + if not (delay := self._inter_request_delay(dev_id)): yield return await asyncio.sleep(delay) From 338dfd992cd40c3d0ceb0231dc52395c767eed8f Mon Sep 17 00:00:00 2001 From: James Morrow Date: Thu, 5 Nov 2026 14:32:22 +1100 Subject: [PATCH 11/11] Fixed issue due to imprecise monotonic clock with <3.13 on windows --- pymodbus/transaction/transaction.py | 6 ++--- test/transaction/test_inter_request_delay.py | 28 +++++++++++--------- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/pymodbus/transaction/transaction.py b/pymodbus/transaction/transaction.py index 353fc1077..9df356de3 100644 --- a/pymodbus/transaction/transaction.py +++ b/pymodbus/transaction/transaction.py @@ -7,7 +7,7 @@ from collections.abc import AsyncGenerator, Callable from contextlib import asynccontextmanager from threading import RLock -from time import monotonic, sleep +from time import monotonic, perf_counter, sleep from ..exceptions import ConnectionException, ModbusIOException from ..framer import FramerAscii, FramerBase, FramerRTU @@ -152,7 +152,7 @@ def _inter_request_delay(self, dev_id: int) -> float: self._last_transaction_end.get(dev_id, -math.inf), self._last_transaction_end.get(0, -math.inf), ) - remaining = self.comm_params.inter_request_delay - (monotonic() - last_end) + remaining = self.comm_params.inter_request_delay - (perf_counter() - last_end) return remaining if remaining > 0.0 else 0.0 @asynccontextmanager @@ -168,7 +168,7 @@ async def _request_lock(self, dev_id: int) -> AsyncGenerator[None]: 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] = monotonic() + 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.""" diff --git a/test/transaction/test_inter_request_delay.py b/test/transaction/test_inter_request_delay.py index f47caa793..8d1d2bff9 100644 --- a/test/transaction/test_inter_request_delay.py +++ b/test/transaction/test_inter_request_delay.py @@ -3,7 +3,7 @@ import asyncio import math from itertools import pairwise -from time import monotonic, sleep +from time import perf_counter, sleep from unittest import mock import pytest @@ -77,28 +77,30 @@ async def test_remaining_interval(self, transact, delay, last_end, now, expected transact.comm_params.inter_request_delay = delay transact._last_transaction_end = {} if last_end is None else {1: last_end} # Replace only the imported reference owned by the transaction module. - with mock.patch.object(transaction_module, "monotonic", return_value=now): + with mock.patch.object(transaction_module, "perf_counter", return_value=now): assert transact._inter_request_delay(1) == pytest.approx(expected) @pytest.mark.parametrize("delay", [0.0, 0.02]) async def test_completion_spacing(self, transact, wire, delay): """Measure the interval from response completion, not request start.""" transact.comm_params.inter_request_delay = delay + # Leave scheduling margin for the response scheduled after 30 ms. + transact.comm_params.timeout_connect = 0.5 starts, completions = [], [] response = transact.framer.buildFrame(ReadCoilsResponse(dev_id=1, bits=[True])) def receive(): - completions.append(monotonic()) + completions.append(perf_counter()) transact.data_received(response) def send(*_args, **_kwargs): - starts.append(monotonic()) + starts.append(perf_counter()) if not transact.is_sync: asyncio.get_running_loop().call_later(0.03, receive) def read(_size): sleep(0.03) - completions.append(monotonic()) + completions.append(perf_counter()) return response wire.side_effect = send @@ -118,7 +120,7 @@ async def test_timeouts_retries_and_next_call(self, transact, wire): def send(*_args, **_kwargs): if 1 in transact._last_transaction_end: - gaps.append(monotonic() - transact._last_transaction_end[1]) + gaps.append(perf_counter() - transact._last_transaction_end[1]) wire.side_effect = send if transact.is_sync: @@ -146,7 +148,7 @@ async def test_no_response_and_independent_clients(self, transact, wire, use_clc ) second.connection_made(mock.Mock()) starts = [] - wire.side_effect = lambda *_args, **_kwargs: starts.append(monotonic()) + wire.side_effect = lambda *_args, **_kwargs: starts.append(perf_counter()) try: await self.execute(transact, True) assert 1 in transact._last_transaction_end @@ -173,7 +175,7 @@ async def test_send_error_propagates_and_paces_next_attempt( completed = transact._last_transaction_end.get(1) assert completed is not None starts = [] - wire.side_effect = lambda *_args, **_kwargs: starts.append(monotonic()) + wire.side_effect = lambda *_args, **_kwargs: starts.append(perf_counter()) await self.execute(transact, True) assert starts[0] - completed >= 0.019 @@ -207,7 +209,7 @@ async def test_serial_option_forwarding(self, client_class): async def test_async_same_device_callers(self, transact, wire): """Queued requests to the same slave preserve the delay interval.""" starts = [] - wire.side_effect = lambda *_args, **_kwargs: starts.append(monotonic()) + wire.side_effect = lambda *_args, **_kwargs: starts.append(perf_counter()) await self.execute(transact, True) await asyncio.wait_for( asyncio.gather(self.execute(transact, True), self.execute(transact, True)), @@ -244,19 +246,19 @@ def observe_delay(dev_id): assert wire.call_count == 1 assert transact._last_transaction_end.get(1) == completed starts = [] - wire.side_effect = lambda *_args, **_kwargs: starts.append(monotonic()) + wire.side_effect = lambda *_args, **_kwargs: starts.append(perf_counter()) await self.execute(transact, True) assert wire.call_count == 2 assert starts[0] - completed >= 0.099 async def test_device_intervals_and_broadcasts(self, transact): """Other devices retain independent deadlines; broadcasts affect all.""" - with mock.patch.object(transaction_module, "monotonic", return_value=100.0): + with mock.patch.object(transaction_module, "perf_counter", return_value=100.0): transact._set_transaction_end(1) assert transact._inter_request_delay(1) == pytest.approx(0.02) assert transact._inter_request_delay(2) == 0.0 assert transact._inter_request_delay(0) == pytest.approx(0.02) - with mock.patch.object(transaction_module, "monotonic", return_value=100.01): + with mock.patch.object(transaction_module, "perf_counter", return_value=100.01): transact._set_transaction_end(2) assert transact._inter_request_delay(1) == pytest.approx(0.01) assert transact._inter_request_delay(2) == pytest.approx(0.02) @@ -267,7 +269,7 @@ async def test_device_intervals_and_broadcasts(self, transact): async def test_interleaved_devices(self, transact, wire): """Requests to B do not reset A's delay interval.""" starts = [] - wire.side_effect = lambda *_args, **_kwargs: starts.append(monotonic()) + wire.side_effect = lambda *_args, **_kwargs: starts.append(perf_counter()) await self.execute(transact, True, 1) completed = transact._last_transaction_end[1] await self.execute(transact, True, 2)