Skip to content

Commit

Permalink
backends: refactor BleakClient.start_notify
Browse files Browse the repository at this point in the history
* Repeated code for BleakClient.start_notify() is moved from the
  backends to the top-level BleakClient class.
* self._notification_callbacks is removed from BaseBleakClient since
  it is not used in all backends.
* A new (internal) NotifyCallback type alias is added so we don't have
  to repeat the Callable with args multiple times.
* BaseBleakClient.start_notify() arg types are changed.

The battery workaround in the BlueZ backend is removed since the
refactored top-level code will fail before calling the backend code.
Hopefully this should mostly go unnoticed since it will only affect
BlueZ < 5.55 and most users are reporting at least that version on
GitHub.
  • Loading branch information
dlech committed Sep 22, 2022
1 parent bdb37b2 commit 548166f
Show file tree
Hide file tree
Showing 8 changed files with 85 additions and 204 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Changed
* Deprecated ``BleakScanner.set_scanning_filter()``.
* Deprecated ``BleakClient.set_disconnected_callback()``.
* Deprecated ``BleakClient.get_services()``.
* Refactored common code in ``BleakClient.start_notify()``.

Fixed
-----
Expand Down
31 changes: 27 additions & 4 deletions bleak/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
__email__ = "henrik.blidh@gmail.com"

import asyncio
import inspect
import logging
import os
import sys
import uuid
from typing import TYPE_CHECKING, Callable, List, Optional, Type, Union
from typing import TYPE_CHECKING, Awaitable, Callable, List, Optional, Type, Union
from warnings import warn

import async_timeout
Expand All @@ -34,6 +35,7 @@
get_platform_scanner_backend_type,
)
from .backends.service import BleakGATTServiceCollection
from .exc import BleakError

if TYPE_CHECKING:
from .backends.bluezdbus.scanner import BlueZScannerArgs
Expand Down Expand Up @@ -490,7 +492,7 @@ async def write_gatt_char(
async def start_notify(
self,
char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],
callback: Callable[[int, bytearray], None],
callback: Callable[[int, bytearray], Union[None, Awaitable[None]]],
**kwargs,
) -> None:
"""
Expand All @@ -503,6 +505,7 @@ async def start_notify(
def callback(sender: int, data: bytearray):
print(f"{sender}: {data}")
client.start_notify(char_uuid, callback)
Args:
Expand All @@ -511,10 +514,30 @@ def callback(sender: int, data: bytearray):
characteristic, specified by either integer handle,
UUID or directly by the BleakGATTCharacteristic object representing it.
callback:
The function to be called on notification.
The function to be called on notification. Can be regular
function or async function.
"""
await self._backend.start_notify(char_specifier, callback, **kwargs)
if not self.is_connected:
raise BleakError("Not connected")

if inspect.iscoroutinefunction(callback):

def wrapped_callback(s, d):
asyncio.ensure_future(callback(s, d))

else:
wrapped_callback = callback

if not isinstance(char_specifier, BleakGATTCharacteristic):
characteristic = self.services.get_characteristic(char_specifier)
else:
characteristic = char_specifier

if not characteristic:
raise BleakError(f"Characteristic {char_specifier} not found!")

await self._backend.start_notify(characteristic, wrapped_callback, **kwargs)

async def stop_notify(
self, char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID]
Expand Down
69 changes: 12 additions & 57 deletions bleak/backends/bluezdbus/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@
BLE Client for BlueZ on Linux
"""
import asyncio
import inspect
import logging
import os
import warnings
from typing import Callable, Optional, Union
from typing import Callable, Dict, Optional, Union, cast
from uuid import UUID

import async_timeout
Expand All @@ -18,7 +17,8 @@

from ... import BleakScanner
from ...exc import BleakDBusError, BleakError
from ..client import BaseBleakClient
from ..characteristic import BleakGATTCharacteristic
from ..client import BaseBleakClient, NotifyCallback
from ..device import BLEDevice
from ..service import BleakGATTServiceCollection
from . import defs
Expand Down Expand Up @@ -70,6 +70,8 @@ def __init__(self, address_or_ble_device: Union[BLEDevice, str], **kwargs):
self._disconnecting_event: Optional[asyncio.Event] = None
# used to ensure device gets disconnected if event loop crashes
self._disconnect_monitor_event: Optional[asyncio.Event] = None
# map of characteristic D-Bus object path to notification callback
self._notification_callbacks: Dict[str, Callable] = {}

# used to override mtu_size property
self._mtu_size: Optional[int] = None
Expand Down Expand Up @@ -780,65 +782,18 @@ async def write_gatt_descriptor(

async def start_notify(
self,
char_specifier: Union[BleakGATTCharacteristicBlueZDBus, int, str, UUID],
callback: Callable[[int, bytearray], None],
characteristic: BleakGATTCharacteristic,
callback: NotifyCallback,
**kwargs,
) -> None:
"""Activate notifications/indications on a characteristic.
Callbacks must accept two inputs. The first will be a integer handle of the characteristic generating the
data and the second will be a ``bytearray`` containing the data sent from the connected server.
.. code-block:: python
def callback(sender: int, data: bytearray):
print(f"{sender}: {data}")
client.start_notify(char_uuid, callback)
Args:
char_specifier (BleakGATTCharacteristicBlueZDBus, int, str or UUID): The characteristic to activate
notifications/indications on a characteristic, specified by either integer handle,
UUID or directly by the BleakGATTCharacteristicBlueZDBus object representing it.
callback (function): The function to be called on notification.
"""
if not self.is_connected:
raise BleakError("Not connected")

if inspect.iscoroutinefunction(callback):

def bleak_callback(s, d):
asyncio.ensure_future(callback(s, d))

else:
bleak_callback = callback

if not isinstance(char_specifier, BleakGATTCharacteristicBlueZDBus):
characteristic = self.services.get_characteristic(char_specifier)
else:
characteristic = char_specifier
Activate notifications/indications on a characteristic.
"""
characteristic = cast(BleakGATTCharacteristicBlueZDBus, characteristic)

if not characteristic:
# Special handling for BlueZ >= 5.48, where Battery Service (0000180f-0000-1000-8000-00805f9b34fb:)
# has been moved to interface org.bluez.Battery1 instead of as a regular service.
# The org.bluez.Battery1 on the other hand does not provide a notification method, so here we cannot
# provide this functionality...
# See https://kernel.googlesource.com/pub/scm/bluetooth/bluez/+/refs/tags/5.48/doc/battery-api.txt
if str(char_specifier) == "00002a19-0000-1000-8000-00805f9b34fb" and (
BlueZFeatures.hides_battery_characteristic
):
raise BleakError(
"Notifications on Battery Level Char ({0}) is not "
"possible in BlueZ >= 5.48. Use regular read instead.".format(
char_specifier
)
)
raise BleakError(
"Characteristic with UUID {0} could not be found!".format(
char_specifier
)
)
self._notification_callbacks[characteristic.path] = callback

self._notification_callbacks[characteristic.path] = bleak_callback
assert self._bus is not None

reply = await self._bus.call(
Message(
Expand Down
28 changes: 10 additions & 18 deletions bleak/backends/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
from .characteristic import BleakGATTCharacteristic
from .device import BLEDevice

NotifyCallback = Callable[[int, bytearray], None]


class BaseBleakClient(abc.ABC):
"""The Client Interface for Bleak Backend implementations to implement.
Expand All @@ -43,7 +45,6 @@ def __init__(self, address_or_ble_device: Union[BLEDevice, str], **kwargs):
self.services = BleakGATTServiceCollection()

self._services_resolved = False
self._notification_callbacks = {}

self._timeout = kwargs.get("timeout", 10.0)
self._disconnected_callback = kwargs.get("disconnected_callback")
Expand Down Expand Up @@ -218,27 +219,18 @@ async def write_gatt_descriptor(
@abc.abstractmethod
async def start_notify(
self,
char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],
callback: Callable[[int, bytearray], None],
characteristic: BleakGATTCharacteristic,
callback: NotifyCallback,
**kwargs,
) -> None:
"""Activate notifications/indications on a characteristic.
Callbacks must accept two inputs. The first will be a integer handle of the characteristic generating the
data and the second will be a ``bytearray``.
.. code-block:: python
def callback(sender: int, data: bytearray):
print(f"{sender}: {data}")
client.start_notify(char_uuid, callback)
"""
Activate notifications/indications on a characteristic.
Args:
char_specifier (BleakGATTCharacteristic, int, str or UUID): The characteristic to activate
notifications/indications on a characteristic, specified by either integer handle,
UUID or directly by the BleakGATTCharacteristic object representing it.
callback (function): The function to be called on notification.
Implementers should call the OS function to enable notifications or
indications on the characteristic.
To keep things the same cross-platform, notifications should be preferred
over indications if possible when a characteristic supports both.
"""
raise NotImplementedError()

Expand Down
45 changes: 8 additions & 37 deletions bleak/backends/corebluetooth/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@
Created on 2019-06-26 by kevincar <kevincarrolldavis@gmail.com>
"""
import asyncio
import inspect
import logging
import uuid
from typing import Callable, Optional, Union
from typing import Optional, Union

from CoreBluetooth import (
CBCharacteristicWriteWithoutResponse,
Expand All @@ -20,7 +19,7 @@
from ... import BleakScanner
from ...exc import BleakError
from ..characteristic import BleakGATTCharacteristic
from ..client import BaseBleakClient
from ..client import BaseBleakClient, NotifyCallback
from ..device import BLEDevice
from ..service import BleakGATTServiceCollection
from .CentralManagerDelegate import CentralManagerDelegate
Expand Down Expand Up @@ -348,44 +347,16 @@ async def write_gatt_descriptor(

async def start_notify(
self,
char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],
callback: Callable[[int, bytearray], None],
characteristic: BleakGATTCharacteristic,
callback: NotifyCallback,
**kwargs,
) -> None:
"""Activate notifications/indications on a characteristic.
Callbacks must accept two inputs. The first will be a integer handle of the characteristic generating the
data and the second will be a ``bytearray`` containing the data sent from the connected server.
.. code-block:: python
def callback(sender: int, data: bytearray):
print(f"{sender}: {data}")
client.start_notify(char_uuid, callback)
Args:
char_specifier (BleakGATTCharacteristic, int, str or UUID): The characteristic to activate
notifications/indications on a characteristic, specified by either integer handle,
UUID or directly by the BleakGATTCharacteristic object representing it.
callback (function): The function to be called on notification.
"""
if inspect.iscoroutinefunction(callback):

def bleak_callback(s, d):
asyncio.ensure_future(callback(s, d))

else:
bleak_callback = callback

if not isinstance(char_specifier, BleakGATTCharacteristic):
characteristic = self.services.get_characteristic(char_specifier)
else:
characteristic = char_specifier
if not characteristic:
raise BleakError("Characteristic {0} not found!".format(char_specifier))
Activate notifications/indications on a characteristic.
"""
assert self._delegate is not None

await self._delegate.start_notifications(characteristic.obj, bleak_callback)
await self._delegate.start_notifications(characteristic.obj, callback)

async def stop_notify(
self, char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID]
Expand Down
39 changes: 9 additions & 30 deletions bleak/backends/p4android/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
import logging
import uuid
import warnings
from typing import Callable, Optional, Union
from typing import Optional, Union

from android.broadcast import BroadcastReceiver
from jnius import java_method

from ...exc import BleakError
from ..client import BaseBleakClient
from ..characteristic import BleakGATTCharacteristic
from ..client import BaseBleakClient, NotifyCallback
from ..device import BLEDevice
from ..service import BleakGATTServiceCollection
from . import defs, utils
Expand Down Expand Up @@ -457,39 +458,17 @@ async def write_gatt_descriptor(

async def start_notify(
self,
char_specifier: Union[BleakGATTCharacteristicP4Android, int, str, uuid.UUID],
callback: Callable[[int, bytearray], None],
characteristic: BleakGATTCharacteristic,
callback: NotifyCallback,
**kwargs,
) -> None:
"""Activate notifications/indications on a characteristic.
Callbacks must accept two inputs. The first will be an integer handle of the characteristic generating the
data and the second will be a ``bytearray`` containing the data sent from the connected server.
.. code-block:: python
def callback(sender: int, data: bytearray):
print(f"{sender}: {data}")
client.start_notify(char_uuid, callback)
Args:
char_specifier (BleakGATTCharacteristicP4Android, int, str or UUID): The characteristic to activate
notifications/indications on a characteristic, specified by either integer handle,
UUID or directly by the BleakGATTCharacteristicP4Android object representing it.
callback (function): The function to be called on notification.
"""
if not isinstance(char_specifier, BleakGATTCharacteristicP4Android):
characteristic = self.services.get_characteristic(char_specifier)
else:
characteristic = char_specifier

if not characteristic:
raise BleakError(
f"Characteristic with UUID {char_specifier} could not be found!"
)

Activate notifications/indications on a characteristic.
"""
self._subscriptions[characteristic.handle] = callback

assert self.__gatt is not None

if not self.__gatt.setCharacteristicNotification(characteristic.obj, True):
raise BleakError(
f"Failed to enable notification for characteristic {characteristic.uuid}"
Expand Down
Loading

0 comments on commit 548166f

Please sign in to comment.