Skip to content

Commit 547d0a8

Browse files
committed
Simplify calculation of inter-frame delay
Also rename the variable to make it more descriptive
1 parent ba4b299 commit 547d0a8

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

umodbus/serial.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -112,12 +112,16 @@ def __init__(self,
112112
else:
113113
self._ctrlPin = None
114114

115+
# timing of 1 character in microseconds (us)
115116
self._t1char = (1000000 * (data_bits + stop_bits + 2)) // baudrate
117+
118+
# inter-frame delay in microseconds (us)
119+
# - <= 19200 bps: 3.5x timing of 1 character
120+
# - > 19200 bps: 1750 us
116121
if baudrate <= 19200:
117-
# 4010us (approx. 4ms) @ 9600 baud
118-
self._t35chars = (3500000 * (data_bits + stop_bits + 2)) // baudrate
122+
self._inter_frame_delay = (self._t1char * 3500) // 1000
119123
else:
120-
self._t35chars = 1750 # 1750us (approx. 1.75ms)
124+
self._inter_frame_delay = 1750
121125

122126
def _calculate_crc16(self, data: bytearray) -> bytes:
123127
"""
@@ -180,7 +184,7 @@ def _uart_read(self) -> bytearray:
180184
break
181185

182186
# wait for the maximum time between two frames
183-
time.sleep_us(self._t35chars)
187+
time.sleep_us(self._inter_frame_delay)
184188

185189
return response
186190

@@ -196,10 +200,9 @@ def _uart_read_frame(self, timeout: Optional[int] = None) -> bytearray:
196200
"""
197201
received_bytes = bytearray()
198202

199-
# set timeout to at least twice the time between two frames in case the
200-
# timeout was set to zero or None
203+
# set default timeout to at twice the inter-frame delay
201204
if timeout == 0 or timeout is None:
202-
timeout = 2 * self._t35chars # in milliseconds
205+
timeout = 2 * self._inter_frame_delay # in microseconds
203206

204207
start_us = time.ticks_us()
205208

@@ -212,13 +215,13 @@ def _uart_read_frame(self, timeout: Optional[int] = None) -> bytearray:
212215

213216
# do not stop reading and appending the result to the buffer
214217
# until the time between two frames elapsed
215-
while time.ticks_diff(time.ticks_us(), last_byte_ts) <= self._t35chars:
218+
while time.ticks_diff(time.ticks_us(), last_byte_ts) <= self._inter_frame_delay:
216219
# WiPy only
217220
# r = self._uart.readall()
218221
r = self._uart.read()
219222

220223
# if something has been read after the first iteration of
221-
# this inner while loop (during self._t35chars time)
224+
# this inner while loop (within self._inter_frame_delay)
222225
if r is not None:
223226
# append the new read stuff to the buffer
224227
received_bytes.extend(r)

0 commit comments

Comments
 (0)