Skip to content
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

Notify callback rework #1020

Merged
merged 2 commits into from
Sep 22, 2022
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
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ Changed
* Deprecated ``BleakScanner.set_scanning_filter()``.
* Deprecated ``BleakClient.set_disconnected_callback()``.
* Deprecated ``BleakClient.get_services()``.
* Refactored common code in ``BleakClient.start_notify()``.
* (BREAKING) Changed notification callback argument from ``int`` to ``BleakGattCharacteristic``. Fixes #759.

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

import asyncio
import functools
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 +36,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,19 +493,22 @@ 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[
[BleakGATTCharacteristic, bytearray], Union[None, Awaitable[None]]
],
**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``.
Callbacks must accept two inputs. The first will be the characteristic
and the second will be a ``bytearray`` containing the data received.

.. code-block:: python

def callback(sender: int, data: bytearray):
print(f"{sender}: {data}")

client.start_notify(char_uuid, callback)

Args:
Expand All @@ -511,10 +517,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 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!")

if inspect.iscoroutinefunction(callback):

def wrapped_callback(data):
asyncio.ensure_future(callback(characteristic, data))

else:
wrapped_callback = functools.partial(callback, characteristic)

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

async def stop_notify(
self, char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID]
Expand Down
78 changes: 17 additions & 61 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,14 +17,15 @@

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
from .characteristic import BleakGATTCharacteristicBlueZDBus
from .manager import get_global_bluez_manager
from .scanner import BleakScannerBlueZDBus
from .utils import assert_reply, extract_service_handle_from_path
from .utils import assert_reply
from .version import BlueZFeatures

logger = logging.getLogger(__name__)
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, NotifyCallback] = {}

# used to override mtu_size property
self._mtu_size: Optional[int] = None
Expand Down Expand Up @@ -144,9 +146,10 @@ def on_connected_changed(connected: bool) -> None:
disconnecting_event.set()

def on_value_changed(char_path: str, value: bytes) -> None:
if char_path in self._notification_callbacks:
handle = extract_service_handle_from_path(char_path)
self._notification_callbacks[char_path](handle, bytearray(value))
callback = self._notification_callbacks.get(char_path)

if callback:
callback(bytearray(value))

watcher = manager.add_device_watcher(
self._device_path, on_connected_changed, on_value_changed
Expand Down Expand Up @@ -780,65 +783,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[[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
10 changes: 6 additions & 4 deletions bleak/backends/corebluetooth/PeripheralDelegate.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import asyncio
import itertools
import logging
from typing import Callable, Any, Dict, Iterable, NewType, Optional
from typing import Any, Dict, Iterable, NewType, Optional

import async_timeout
import objc
Expand All @@ -23,6 +23,7 @@
)

from ...exc import BleakError
from ..client import NotifyCallback

# logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -60,7 +61,7 @@ def initWithPeripheral_(self, peripheral: CBPeripheral):
self._descriptor_write_futures: Dict[int, asyncio.Future] = {}

self._characteristic_notify_change_futures: Dict[int, asyncio.Future] = {}
self._characteristic_notify_callbacks: Dict[int, Callable[[str, Any], Any]] = {}
self._characteristic_notify_callbacks: Dict[int, NotifyCallback] = {}

self._read_rssi_futures: Dict[NSUUID, asyncio.Future] = {}

Expand Down Expand Up @@ -204,7 +205,7 @@ async def write_descriptor(self, descriptor: CBDescriptor, value: NSData) -> Non

@objc.python_method
async def start_notifications(
self, characteristic: CBCharacteristic, callback: Callable[[str, Any], Any]
self, characteristic: CBCharacteristic, callback: NotifyCallback
) -> None:
c_handle = characteristic.handle()
if c_handle in self._characteristic_notify_callbacks:
Expand Down Expand Up @@ -366,8 +367,9 @@ def did_update_value_for_characteristic(
if not future:
if error is None:
notify_callback = self._characteristic_notify_callbacks.get(c_handle)

if notify_callback:
notify_callback(c_handle, bytearray(value))
notify_callback(bytearray(value))
return

if error is not None:
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
Loading