From b233bb92fbb872764dfcd1f9e7c9ed7135641fa1 Mon Sep 17 00:00:00 2001 From: trivialkettle <126059809+trivialkettle@users.noreply.github.com> Date: Thu, 7 Nov 2024 16:12:13 +0100 Subject: [PATCH] Avoid busy looping in rx thread Currently the rx thread is busy looping until it gets something to read. This change makes the read blocking (waits for at least on byte). During disconnect the read command is canceled and the rx thread stops. --- pyusbtin/usbtin.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/pyusbtin/usbtin.py b/pyusbtin/usbtin.py index 679353b..be0b167 100644 --- a/pyusbtin/usbtin.py +++ b/pyusbtin/usbtin.py @@ -261,6 +261,7 @@ def stop_rx_thread(self): # tell the thread to exit self.rx_thread_state = USBtin.RX_THREAD_TERMINATE + self.serial_port.cancel_read() while self.rx_thread_state != USBtin.RX_THREAD_STOPPED: # wait for thread to end, sleep 1ms sleep(0.001) @@ -272,11 +273,9 @@ def rx_thread(self): """ process data as long as requested """ while self.rx_thread_state == USBtin.RX_THREAD_RUNNING: - # fetch bytes if available - rxcount = self.serial_port.inWaiting() - if rxcount > 0: - # fetch all data from serial buffer - buf = self.serial_port.read(rxcount) + # fetch at least one byte of data from serial buffer + buf = self.serial_port.read(max(1, self.serial_port.in_waiting)) + if buf: if PY_VERSION == 2: buf = [ord(b) for b in buf]