Skip to content

Commit

Permalink
BleakScanner: Add async iterator scanning capability
Browse files Browse the repository at this point in the history
Add `observe()` async iterator method to the `BleakScanner` which yields
results of the ongoing scan.
  • Loading branch information
bojanpotocnik committed Jul 21, 2023
1 parent 05793e1 commit 2cb1bb0
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 9 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ Changed
* Scanner backends modified to allow multiple advertisement callbacks. Merged #1367.
* Changed default handling of the ``response`` argument in ``BleakClient.write_gatt_char``.
Fixes #909.
* Added ``observe()`` async iterator method to ``BleakScanner``.
* Added ``scan_iterator.py`` example.

Fixed
-----
Expand Down
38 changes: 30 additions & 8 deletions bleak/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import uuid
from typing import (
TYPE_CHECKING,
AsyncGenerator,
Awaitable,
Callable,
Dict,
Expand Down Expand Up @@ -214,6 +215,31 @@ def set_scanning_filter(self, **kwargs):
)
self._backend.set_scanning_filter(**kwargs)

async def observe(
self,
) -> AsyncGenerator[Tuple[BLEDevice, AdvertisementData], None]:
"""
Yields devices and their advertising data as they are discovered.
.. note::
Ensure that scanning is started before calling this method.
Returns:
An async iterator that yields tuples (:class:`BLEDevice`, :class:`AdvertisementData`).
.. versionadded:: 0.20.1
"""
devices = asyncio.Queue()

unregister_callback = self._backend.register_detection_callback(
lambda bd, ad: devices.put_nowait((bd, ad))
)
try:
while True:
yield await devices.get()
finally:
unregister_callback()

@overload
@classmethod
async def discover(
Expand Down Expand Up @@ -370,16 +396,12 @@ async def find_device_by_filter(
the timeout.
"""
found_device_queue: asyncio.Queue[BLEDevice] = asyncio.Queue()

def apply_filter(d: BLEDevice, ad: AdvertisementData):
if filterfunc(d, ad):
found_device_queue.put_nowait(d)

async with cls(detection_callback=apply_filter, **kwargs):
async with cls(**kwargs) as scanner:
try:
async with async_timeout(timeout):
return await found_device_queue.get()
async for bd, ad in scanner.observe():
if filterfunc(bd, ad):
return bd
except asyncio.TimeoutError:
return None

Expand Down
8 changes: 7 additions & 1 deletion docs/api/scanner.rst
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,19 @@ following methods:
Getting discovered devices and advertisement data
-------------------------------------------------

If you aren't using the "easy" class methods, there are two ways to get the
If you aren't using the "easy" class methods, there are three ways to get the
discovered devices and advertisement data.

For event-driven programming, you can provide a ``detection_callback`` callback
to the :class:`BleakScanner` constructor. This will be called back each time
and advertisement is received.

Alternatively, you can utilize the asynchronous iterator to iterate over
advertisements as they are received. The method below returns an async iterator
that yields the same tuples as otherwise provided to ``detection_callback``.

.. automethod:: bleak.BleakScanner.observe

Otherwise, you can use one of the properties below after scanning has stopped.

.. autoproperty:: bleak.BleakScanner.discovered_devices
Expand Down
35 changes: 35 additions & 0 deletions examples/scan_iterator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""
Scan/Discovery Async Iterator
--------------
Example showing how to scan for BLE devices using async iterator instead of callback function
Created on 2023-07-07 by bojanpotocnik <info@bojanpotocnik.com>
"""
import asyncio

from bleak import BleakScanner


async def main():
async with BleakScanner() as scanner:
n = 5
print(f"Scanning for {n} devices...")
async for bd, ad in scanner.observe():
print(f"{n}. {bd!r} with {ad!r}")
n -= 1
if n == 0:
break

n = 6
print(f"\nScanning for a device with name longer than {n} characters...")
async for bd, ad in scanner.observe():
found = len(bd.name or "") > n or len(ad.local_name or "") > n
print(f"Found{' it' if found else ''} {bd!r} with {ad!r}")
if found:
break


if __name__ == "__main__":
asyncio.run(main())

0 comments on commit 2cb1bb0

Please sign in to comment.