@@ -58,6 +58,7 @@ class TCPModbusClient:
58
58
59
59
PING_LOOP_PERIOD : ClassVar = 1
60
60
CONSECUTIVE_TIMEOUTS_TO_RECONNECT : ClassVar = 5
61
+ COOLDOWN_BEFORE_RECONNECTING_SEC : ClassVar = 0.01
61
62
62
63
def __init__ (
63
64
self ,
@@ -129,6 +130,9 @@ def __init__(
129
130
# This way, we can avoid duplicate transaction IDs via birthday paradox.
130
131
self ._next_transaction_id = random .randint (0 , MAX_TRANSACTION_ID )
131
132
133
+ # Keep track of the last time we closed a connection, to implement a cooldown before reconnecting.
134
+ self ._last_close_time = time .perf_counter ()
135
+
132
136
def __repr__ (self ) -> str :
133
137
last_ping_msg = (
134
138
f"{ self ._last_ping * 1000 :.1f} ms ping"
@@ -156,6 +160,11 @@ async def _get_tcp_connection(
156
160
if self ._reader is not None and self ._writer is not None :
157
161
return self ._reader , self ._writer
158
162
163
+ cooldown_elapsed = time .perf_counter () - self ._last_close_time
164
+ cooldown_remaining = self .COOLDOWN_BEFORE_RECONNECTING_SEC - cooldown_elapsed
165
+ if cooldown_remaining > 0 :
166
+ await asyncio .sleep (cooldown_remaining )
167
+
159
168
self ._lifetime_tcp_connection_num += 1
160
169
161
170
if self .logger is not None :
@@ -351,6 +360,8 @@ def clear_tcp_connection(self) -> None:
351
360
self ._reader = None
352
361
self ._writer = None
353
362
363
+ self ._last_close_time = time .perf_counter ()
364
+
354
365
async def test_connection (
355
366
self , timeout : float | None = DEFAULT_MODBUS_TIMEOUT_SEC
356
367
) -> None :
@@ -521,7 +532,7 @@ async def send_modbus_message(
521
532
"before mbap header, likely catching up stream after timeouts"
522
533
)
523
534
524
- # STEP FOUR : READ THE RESPONSE PDU
535
+ # STEP FIVE : READ THE RESPONSE PDU
525
536
with catchtime () as read_pdu_time :
526
537
response_pdu = await asyncio .wait_for (
527
538
reader .readexactly (request_function .expected_response_pdu_size ),
@@ -551,7 +562,7 @@ async def send_modbus_message(
551
562
except OSError as e :
552
563
if self .logger is not None :
553
564
self .logger .warning (
554
- f"[{ self } ][send_modbus_message] OSError{ type (e ).__name__ } ({ e } ) while sending request { msg_str } , "
565
+ f"[{ self } ][send_modbus_message] OSError( { type (e ).__name__ } ) ({ e } ) while sending request { msg_str } , "
555
566
"clearing connection"
556
567
)
557
568
0 commit comments