Skip to content

Deinit UARTService CharacteristicBuffers on disconnect #193

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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