Skip to content

Commit c619813

Browse files
authored
Fix send_periodic duration (#1713)
* Add test case * Fix bug * Improve unittest * MR feedback
1 parent 3f6e951 commit c619813

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

can/broadcastmanager.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,9 @@ def _run(self) -> None:
297297
win32event.WaitForSingleObject(self.event.handle, 0)
298298

299299
while not self.stopped:
300+
if self.end_time is not None and time.perf_counter() >= self.end_time:
301+
break
302+
300303
# Prevent calling bus.send from multiple threads
301304
with self.send_lock:
302305
try:
@@ -318,8 +321,7 @@ def _run(self) -> None:
318321

319322
if not USE_WINDOWS_EVENTS:
320323
msg_due_time_ns += self.period_ns
321-
if self.end_time is not None and time.perf_counter() >= self.end_time:
322-
break
324+
323325
msg_index = (msg_index + 1) % len(self.messages)
324326

325327
if USE_WINDOWS_EVENTS:

test/back2back_test.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,23 @@ def test_sub_second_timestamp_resolution(self):
273273
self.bus2.recv(0)
274274
self.bus2.recv(0)
275275

276+
def test_send_periodic_duration(self):
277+
"""
278+
Verify that send_periodic only transmits for the specified duration.
279+
280+
Regression test for #1713.
281+
"""
282+
for params in [(0.01, 0.003), (0.1, 0.011), (1, 0.4)]:
283+
duration, period = params
284+
messages = []
285+
286+
self.bus2.send_periodic(can.Message(), period, duration)
287+
while (msg := self.bus1.recv(period * 1.25)) is not None:
288+
messages.append(msg)
289+
290+
delta_t = round(messages[-1].timestamp - messages[0].timestamp, 2)
291+
assert delta_t <= duration
292+
276293

277294
@unittest.skipUnless(TEST_INTERFACE_SOCKETCAN, "skip testing of socketcan")
278295
class BasicTestSocketCan(Back2BackTestCase):

0 commit comments

Comments
 (0)