Repository navigation
Add optional inter-request delay to sync and async serial clients #3081
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
7780602
e7e437c
adba94f
8bcba26
4eed3ff
d0f5fe2
ac9a0d3
e9330a2
2ae8ee7
277d913
d1e50e1
8eccdc4
338dfd9
91e2ba2
ec06b9b
58f7fac
d5b078b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 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 | ||
|
|
@@ -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.0: | ||
| raise ValueError("inter_request_delay must be finite and non-negative") | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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, | ||
|
|
@@ -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 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 | ||
|
|
@@ -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.0: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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, | ||
|
|
@@ -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, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -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 | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
|
|
@@ -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), | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 ?
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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: | ||
|
|
@@ -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) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good point. I will fix this and update the tests.
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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.
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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: | ||
|
|
@@ -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): | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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.""" | ||
|
|
||
There was a problem hiding this comment.
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.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.