# BleakScanner class

class bleak.BleakScanner(detection_callback: Callable[[BLEDevice, AdvertisementData], Coroutine[Any, Any, None] | None] | None = None, service_uuids: list[str] | None = None, scanning_mode: Literal['active', 'passive'] = 'active', *, bluez: BlueZScannerArgs = {}, cb: CBScannerArgs = {}, backend: type[BaseBleakScanner] | None = None, **kwargs: Any)

  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: `detection_callback`, `service_uuids` and `scanning_mode` are no longer keyword-only. Added `bluez` parameter.

  Changed in version 0.18: 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: Unpack[ExtraArgs]) → list[BLEDevice]
async classmethod BleakScanner.discover(timeout: float = 5.0, *, return_adv: Literal[True], **kwargs: Unpack[ExtraArgs]) → 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: Added `return_adv` parameter.

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

  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.

  Added in version 0.20.

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

  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]) → BLEDevice | None

  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.

  adapter: str | None

    Name of adapter to use (BlueZ specific), e.g. hci0.

  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

  Start scanning for devices.

  Raises:

    BleakBluetoothNotAvailableError – if Bluetooth is not currently available

  Changed in version 2.0: Now raises `BleakBluetoothNotAvailableError` instead of `BleakError` when Bluetooth is not currently available.

async BleakScanner.stop() → None

  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]

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

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

  Added in version 0.19.

## Extra information

property BleakScanner.backend_id: BleakBackend | str

  Gets the identifier of the backend in use.

  The value is one of the `BleakBackend` enum values in case of built-in backends, or a string identifying a custom backend.

  Added in version 2.0.