Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions ble_serial/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,35 @@ async def _run(self):
logging.exception(e)
finally:
logging.warning('Shutdown initiated')

# Stop the run loops first (signals tasks to exit gracefully)
if hasattr(self, 'uart'):
self.uart.remove()
self.uart.stop_loop()
if hasattr(self, 'bt'):
await self.bt.disconnect()
self.bt.stop_loop()

# Cancel and await pending tasks before cleanup
try:
if pending:
for t in pending:
t.cancel()
await asyncio.wait_for(
asyncio.gather(*pending, return_exceptions=True),
timeout=2.0
)
except NameError:
pass # pending not defined if we failed before asyncio.wait
except asyncio.TimeoutError:
logging.warning('Timeout waiting for tasks to cancel')

# Now safe to disconnect BLE and remove uart
if hasattr(self, 'bt'):
try:
await asyncio.wait_for(self.bt.disconnect(), timeout=3.0)
except asyncio.TimeoutError:
logging.warning('Timeout disconnecting BLE')
if hasattr(self, 'uart'):
self.uart.remove()
if hasattr(self, 'log'):
self.log.finish()
logging.info('Shutdown complete.')
Expand Down
10 changes: 10 additions & 0 deletions ble_serial/ports/linux_pty.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ def __init__(self, symlink: str, ev_loop: asyncio.AbstractEventLoop, mtu: int):
self.loop = ev_loop
self.mtu = mtu
self._send_queue = asyncio.Queue()
self._stopping = False

self._controller_fd, endpoint_fd = pty.openpty()
self.endpoint_path = os.ttyname(endpoint_fd)
Expand Down Expand Up @@ -39,6 +40,13 @@ def start(self):

def stop_loop(self):
logging.info('Stopping serial event loop')
self._stopping = True
# Clear any pending items so we exit quickly
while not self._send_queue.empty():
try:
self._send_queue.get_nowait()
except asyncio.QueueEmpty:
break
self._send_queue.put_nowait(None)

def remove(self):
Expand All @@ -58,6 +66,8 @@ def read_sync(self):
return value

def queue_write(self, value: bytes):
if self._stopping:
return # Ignore writes during shutdown
self._send_queue.put_nowait(value)

async def run_loop(self):
Expand Down