Skip to content

Commit

Permalink
Merge pull request adafruit#22 from dhalbert/cleanup-on-exit
Browse files Browse the repository at this point in the history
disconnect connections on ctrl-c
  • Loading branch information
dhalbert authored Oct 19, 2020
2 parents 2b3d84c + 114c8dc commit ed19372
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion _bleio/adapter_.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
from typing import Iterable, Optional, Union

import asyncio
import atexit
import platform
import threading
import time
Expand Down Expand Up @@ -84,6 +85,18 @@ def __init__(self):
# device scanning.
self._cached_devices = {}

# Clean up connections, etc. when exiting (even by KeyboardInterrupt)
atexit.register(self._cleanup)

def _cleanup(self):
"""Clean up connections, so that the underlying OS software does not
leave them open.
"""
# Use a copy of the list because each connection will be deleted
# on disconnect().
for connection in self._connections.copy():
connection.disconnect()

@property
def _use_hcitool(self):
if self._hcitool_is_usable is None:
Expand Down Expand Up @@ -367,7 +380,6 @@ async def _connect_async(self, address: Address, *, timeout: float) -> None:
client = BleakClient(device if device else address._bleak_address)
# connect() takes a timeout, but it's a timeout to do a
# discover() scan, not an actual connect timeout.
# TODO: avoid the second discovery.
try:
await client.connect(timeout=timeout)
# This does not seem to connect reliably.
Expand Down

0 comments on commit ed19372

Please sign in to comment.