Skip to content

Commit 2ce8b21

Browse files
committed
Flush recv_buffer on cancellation
If asyncio.wait_for is cancelled by the caller we need to clean up the recv_buffer as well. We also need to guard self.response_future.set_result with a done() check to prevent asyncio.exceptions.InvalidStateError: invalid state errors.
1 parent 528d70d commit 2ce8b21

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

pymodbus/transaction/transaction.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,9 @@ async def execute(self, no_response_expected: bool, request: ModbusPDU) -> Modbu
153153
return response
154154
except asyncio.exceptions.TimeoutError:
155155
count_retries += 1
156+
except asyncio.exceptions.CancelledError:
157+
self.recv_buffer = b""
158+
raise
156159
if self.count_until_disconnect < 0:
157160
self.connection_lost(asyncio.TimeoutError("Server not responding"))
158161
raise ModbusIOException(
@@ -194,7 +197,8 @@ def callback_data(self, data: bytes, addr: tuple | None = None) -> int:
194197
raise ModbusIOException(
195198
f"ERROR: request ask for id={self.request_dev_id} but got id={pdu.dev_id}, CLOSING CONNECTION."
196199
)
197-
self.response_future.set_result(self.last_pdu)
200+
if not self.response_future.done():
201+
self.response_future.set_result(self.last_pdu)
198202
return used_len
199203

200204
def getNextTID(self) -> int:

0 commit comments

Comments
 (0)