From b86dc40fe5b7bdff7a0827297f2c90a1fc6c0e3d Mon Sep 17 00:00:00 2001 From: B Date: Sun, 12 Dec 2021 11:03:31 -0500 Subject: [PATCH] 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. --- adafruit_ble/__init__.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/adafruit_ble/__init__.py b/adafruit_ble/__init__.py index d6eee48..130eaf2 100755 --- a/adafruit_ble/__init__.py +++ b/adafruit_ble/__init__.py @@ -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] @@ -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): @@ -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]