Skip to content

Commit b86dc40

Browse files
committed
Added connection cache cleaning to remove old entries that are no longer valid. This prevents unbounded cache growth from causing memory exhaustion as described in github issue #146.
1 parent 434e367 commit b86dc40

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

adafruit_ble/__init__.py

+8
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,7 @@ def connect(self, peer, *, timeout=4.0):
288288
if not isinstance(peer, _bleio.Address):
289289
peer = peer.address
290290
connection = self._adapter.connect(peer, timeout=timeout)
291+
self._clean_connection_cache()
291292
self._connection_cache[connection] = BLEConnection(connection)
292293
return self._connection_cache[connection]
293294

@@ -299,6 +300,7 @@ def connected(self):
299300
@property
300301
def connections(self):
301302
"""A tuple of active `BLEConnection` objects."""
303+
self._clean_connection_cache()
302304
connections = self._adapter.connections
303305
wrapped_connections = [None] * len(connections)
304306
for i, connection in enumerate(connections):
@@ -337,3 +339,9 @@ def address_bytes(self):
337339
def advertising(self):
338340
"""The advertising state"""
339341
return self._adapter.advertising # pylint: disable=no-member
342+
343+
def _clean_connection_cache(self):
344+
"""Remove cached connections that have disconnected."""
345+
for k, connection in list(self._connection_cache.items()):
346+
if not connection.connected:
347+
del self._connection_cache[k]

0 commit comments

Comments
 (0)