BleakScanner class

class bleak.BleakScanner(detection_callback: Optional[AdvertisementDataCallback] = None, service_uuids: Optional[List[str]] = None, scanning_mode: Literal['active', 'passive'] = 'active', *, bluez: BlueZScannerArgs = {}, cb: CBScannerArgs = {}, backend: Optional[Type[BaseBleakScanner]] = None, **kwargs)[source]

Interface for Bleak Bluetooth LE Scanners.

The scanner will listen for BLE advertisements, optionally filtering on advertised services or other conditions, and collect a list of BLEDevice objects. These can subsequently be used to connect to the corresponding BLE server.

A BleakScanner can be used as an asynchronous context manager in which case it automatically starts and stops scanning.

Parameters
  • detection_callback – Optional function that will be called each time a device is discovered or advertising data has changed.

  • service_uuids – Optional list of service UUIDs to filter on. Only advertisements containing this advertising data will be received. Required on macOS >= 12.0, < 12.3 (unless you create an app with py2app).

  • scanning_mode – Set to "passive" to avoid the "active" scanning mode. Passive scanning is not supported on macOS! Will raise BleakError if set to "passive" on macOS.

  • bluez – Dictionary of arguments specific to the BlueZ backend.

  • cb – Dictionary of arguments specific to the CoreBluetooth backend.

  • backend – Used to override the automatically selected backend (i.e. for a custom backend).

  • **kwargs – Additional args for backwards compatibility.

Tip

The first received advertisement in detection_callback may or may not include scan response data if the remote device supports it. Be sure to take this into account when handing the callback. For example, the scan response often contains the local name of the device so if you are matching a device based on other data but want to display the local name to the user, be sure to wait for adv_data.local_name is not None.

Changed in version 0.15.0: detection_callback, service_uuids and scanning_mode are no longer keyword-only. Added bluez parameter.

Changed in version 0.18.0: No longer is alias for backend type and no longer inherits from BaseBleakScanner. Added backend parameter.

Easy methods

These methods and handy for simple programs but are not recommended for more advanced use cases like long running programs, GUIs or connecting to multiple devices.

async classmethod BleakScanner.discover(timeout: float = 5.0, *, return_adv: Literal[False] = False, **kwargs) List[BLEDevice][source]
async classmethod BleakScanner.discover(timeout: float = 5.0, *, return_adv: Literal[True], **kwargs) Dict[str, Tuple[BLEDevice, AdvertisementData]]

Scan continuously for timeout seconds and return discovered devices.

Parameters
  • timeout – Time, in seconds, to scan for.

  • return_adv – If True, the return value will include advertising data.

  • **kwargs – Additional arguments will be passed to the BleakScanner constructor.

Returns

The value of discovered_devices_and_advertisement_data if return_adv is True, otherwise the value of discovered_devices.

Changed in version 0.19.0: Added return_adv parameter.

async classmethod BleakScanner.find_device_by_name(name: str, timeout: float = 10.0, **kwargs: Unpack[ExtraArgs]) Optional[BLEDevice][source]

Obtain a BLEDevice for a BLE server specified by the local name in the advertising data.

Parameters
  • name – The name sought.

  • timeout – Optional timeout to wait for detection of specified peripheral before giving up. Defaults to 10.0 seconds.

  • **kwargs – additional args passed to the BleakScanner constructor.

Returns

The BLEDevice sought or None if not detected.

New in version 0.20.0.

async classmethod BleakScanner.find_device_by_address(device_identifier: str, timeout: float = 10.0, **kwargs: Unpack[ExtraArgs]) Optional[BLEDevice][source]

Obtain a BLEDevice for a BLE server specified by Bluetooth address or (macOS) UUID address.

Parameters
  • device_identifier – The Bluetooth/UUID address of the Bluetooth peripheral sought.

  • timeout – Optional timeout to wait for detection of specified peripheral before giving up. Defaults to 10.0 seconds.

  • **kwargs – additional args passed to the BleakScanner constructor.

Returns

The BLEDevice sought or None if not detected.

async classmethod BleakScanner.find_device_by_filter(filterfunc: AdvertisementDataFilter, timeout: float = 10.0, **kwargs: Unpack[ExtraArgs]) Optional[BLEDevice][source]

Obtain a BLEDevice for a BLE server that matches a given filter function.

This can be used to find a BLE server by other identifying information than its address, for example its name.

Parameters
  • filterfunc – A function that is called for every BLEDevice found. It should return True only for the wanted device.

  • timeout – Optional timeout to wait for detection of specified peripheral before giving up. Defaults to 10.0 seconds.

  • **kwargs – Additional arguments to be passed to the BleakScanner constructor.

Returns

The BLEDevice sought or None if not detected before the timeout.

class bleak.BleakScanner.ExtraArgs

Keyword args from BleakScanner that can be passed to other convenience methods.

backend: Type[BaseBleakScanner]

Used to override the automatically selected backend (i.e. for a custom backend).

bluez: BlueZScannerArgs

Dictionary of arguments specific to the BlueZ backend.

cb: CBScannerArgs

Dictionary of arguments specific to the CoreBluetooth backend.

scanning_mode: Literal['active', 'passive']

Set to "passive" to avoid the "active" scanning mode. Passive scanning is not supported on macOS! Will raise BleakError if set to "passive" on macOS.

service_uuids: List[str]

Optional list of service UUIDs to filter on. Only advertisements containing this advertising data will be received. Required on macOS >= 12.0, < 12.3 (unless you create an app with py2app).

Starting and stopping

BleakScanner is an context manager so the recommended way to start and stop scanning is to use it in an async with statement:

import asyncio
from bleak import BleakScanner

async def main():
    stop_event = asyncio.Event()

    # TODO: add something that calls stop_event.set()

    def callback(device, advertising_data):
        # TODO: do something with incoming data
        pass

    async with BleakScanner(callback) as scanner:
        ...
        # Important! Wait for an event to trigger stop, otherwise scanner
        # will stop immediately.
        await stop_event.wait()

    # scanner stops when block exits
    ...

asyncio.run(main())

It can also be started and stopped without using the context manager using the following methods:

async BleakScanner.start() None[source]

Start scanning for devices

async BleakScanner.stop() None[source]

Stop scanning for devices

Getting discovered devices and advertisement data

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 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.

async BleakScanner.advertisement_data() AsyncGenerator[Tuple[BLEDevice, AdvertisementData], None][source]

Yields devices and associated advertising data packets as they are discovered.

Note

Ensure that scanning is started before calling this method.

Returns

An async iterator that yields tuples (BLEDevice, AdvertisementData).

New in version 0.21.

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

property BleakScanner.discovered_devices: List[BLEDevice]

Gets list of the devices that the scanner has discovered during the scanning.

If you also need advertisement data, use discovered_devices_and_advertisement_data instead.

property BleakScanner.discovered_devices_and_advertisement_data: Dict[str, Tuple[BLEDevice, AdvertisementData]]

Gets a map of device address to tuples of devices and the most recently received advertisement data for that device.

The address keys are useful to compare the discovered devices to a set of known devices. If you don’t need to do that, consider using discovered_devices_and_advertisement_data.values() to just get the values instead.

New in version 0.19.0.

Deprecated

BleakScanner.register_detection_callback(callback: Optional[Callable[[BLEDevice, AdvertisementData], Optional[Coroutine[Any, Any, None]]]]) None[source]

Register a callback that is called when a device is discovered or has a property changed.

Deprecated since version 0.17.0: This method will be removed in a future version of Bleak. Pass the callback directly to the BleakScanner constructor instead.

Parameters

callback – A function, coroutine or None.

BleakScanner.set_scanning_filter(**kwargs) None[source]

Set scanning filter for the BleakScanner.

Deprecated since version 0.17.0: This method will be removed in a future version of Bleak. Pass arguments directly to the BleakScanner constructor instead.

Parameters

**kwargs – The filter details.

async BleakScanner.get_discovered_devices() List[BLEDevice][source]

Gets the devices registered by the BleakScanner.

Deprecated since version 0.11.0: This method will be removed in a future version of Bleak. Use the discovered_devices property instead.

Returns

A list of the devices that the scanner has discovered during the scanning.