Skip to content

Commit

Permalink
Merge pull request #193 from dhalbert/deinit-characteristic-buffers
Browse files Browse the repository at this point in the history
Deinit UARTService CharacteristicBuffers on disconnect
  • Loading branch information
dhalbert authored Mar 4, 2024
2 parents 744933f + 9c010cd commit 28349ae
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 1 deletion.
3 changes: 3 additions & 0 deletions adafruit_ble/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,9 @@ def pair(self, *, bond: bool = True) -> None:
def disconnect(self) -> None:
"""Disconnect from peer."""
self._bleio_connection.disconnect()
# Clean up any services that need explicit cleanup.
for service in self._constructed_services.values():
service.deinit()


class BLERadio:
Expand Down
4 changes: 3 additions & 1 deletion adafruit_ble/characteristics/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,9 @@ def __init__(
uuid=uuid, properties=properties, read_perm=read_perm, write_perm=write_perm
)

def bind(self, service: Service) -> Union[_bleio.Characteristic, BoundWriteStream]:
def bind(
self, service: Service
) -> Union[_bleio.CharacteristicBuffer, BoundWriteStream]:
"""Binds the characteristic to the given Service."""
bound_characteristic = super().bind(service)
# If we're given a remote service then we're the client and need to buffer in.
Expand Down
3 changes: 3 additions & 0 deletions adafruit_ble/services/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ def __init__(
else:
getattr(self, class_attr)

def deinit(self):
"""Override this method to do any explicit cleanup necessary on connection close."""

@property
def remote(self) -> bool:
"""True if the service is provided by a peer and accessed remotely."""
Expand Down
8 changes: 8 additions & 0 deletions adafruit_ble/services/nordic.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,14 @@ def __init__(self, service: Optional[_bleio.Service] = None) -> None:
self._tx = self._server_rx
self._rx = self._server_tx

def deinit(self):
"""The characteristic buffers must be deinitialized when no longer needed.
Otherwise they will leak storage.
"""
for obj in (self._tx, self._rx):
if hasattr(obj, "deinit"):
obj.deinit()

def read(self, nbytes: Optional[int] = None) -> Optional[bytes]:
"""
Read characters. If ``nbytes`` is specified then read at most that many bytes.
Expand Down

0 comments on commit 28349ae

Please sign in to comment.