Skip to content

Commit ab9a7f0

Browse files
committed
Fix signals (e.g. ctrl-C) on Windows threads
1 parent d995008 commit ab9a7f0

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

ble_serial/ports/windows_com0com.py

+13-3
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,11 @@ async def run_loop(self):
2525
pool = ThreadPoolExecutor(max_workers=2)
2626
rx = self.loop.run_in_executor(pool, self._run_rx)
2727
tx = self.loop.run_in_executor(pool, self._run_tx)
28-
await asyncio.gather(rx, tx)
28+
main = self._run_main_thread()
29+
await asyncio.gather(main, rx, tx)
2930

3031
def _run_tx(self):
31-
while self.alive and self.serial.is_open:
32+
while self.alive:
3233
try:
3334
data = self.tx_queue.get(block=True, timeout=3)
3435
logging.debug(f'Write: {data}')
@@ -41,7 +42,7 @@ def _run_tx(self):
4142
def _run_rx(self):
4243
# based on ReaderThread(threading.Thread) from:
4344
# https://github.com/pyserial/pyserial/blob/master/serial/threaded/__init__.py
44-
while self.alive and self.serial.is_open:
45+
while self.alive:
4546
data = self.serial.read(1) # request 1 to block
4647
n = min(self.mtu - 1, self.serial.in_waiting) # read the remaning, can be 0
4748
data += self.serial.read(n)
@@ -50,6 +51,15 @@ def _run_rx(self):
5051

5152
logging.debug(f'RX loop ended, alive={self.alive} open={self.serial.is_open}')
5253

54+
async def _run_main_thread(self):
55+
# Dummy work in main thread, it has to run to detect signals (e.g. ctrl-C)
56+
# https://stackoverflow.com/a/29237343
57+
# we can also use it to check if the serial is still open, instead of doing that in every thread
58+
while self.alive:
59+
self.alive = False if not self.serial.is_open else self.alive
60+
await asyncio.sleep(0.5)
61+
62+
5363
def stop_loop(self):
5464
self.alive = False
5565
logging.info('Stopping RX+TX loop')

0 commit comments

Comments
 (0)