Skip to content

Commit

Permalink
Merge pull request #147 from 300bps/main
Browse files Browse the repository at this point in the history
Prevent unbounded BLERadio._connection_cache growth from causing memory exhaustion (issue #146)
  • Loading branch information
tannewt authored Dec 13, 2021
2 parents 434e367 + b86dc40 commit a695cde
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions adafruit_ble/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,7 @@ def connect(self, peer, *, timeout=4.0):
if not isinstance(peer, _bleio.Address):
peer = peer.address
connection = self._adapter.connect(peer, timeout=timeout)
self._clean_connection_cache()
self._connection_cache[connection] = BLEConnection(connection)
return self._connection_cache[connection]

Expand All @@ -299,6 +300,7 @@ def connected(self):
@property
def connections(self):
"""A tuple of active `BLEConnection` objects."""
self._clean_connection_cache()
connections = self._adapter.connections
wrapped_connections = [None] * len(connections)
for i, connection in enumerate(connections):
Expand Down Expand Up @@ -337,3 +339,9 @@ def address_bytes(self):
def advertising(self):
"""The advertising state"""
return self._adapter.advertising # pylint: disable=no-member

def _clean_connection_cache(self):
"""Remove cached connections that have disconnected."""
for k, connection in list(self._connection_cache.items()):
if not connection.connected:
del self._connection_cache[k]

0 comments on commit a695cde

Please sign in to comment.