# bleak.backends.bluezdbus package

## Submodules

## bleak.backends.bluezdbus.advertisement_monitor module

### Advertisement Monitor

This module contains types associated with the BlueZ D-Bus advertisement monitor api <https://github.com/bluez/bluez/blob/master/doc/org.bluez.AdvertisementMonitor.rst>.

class bleak.backends.bluezdbus.advertisement_monitor.AdvertisementMonitor(*args: Any, **kwargs: Any)

  Bases: `ServiceInterface`

  Implementation of the org.bluez.AdvertisementMonitor1 D-Bus interface.

  The BlueZ advertisement monitor API design seems to be just for device presence (is it in range or out of range), but this isn’t really what we want in Bleak, we want to monitor changes in advertisement data, just like in active scanning.

  So the only thing we are using here is the “or_patterns” since it is currently required, but really we don’t need that either. Hopefully an “all” “Type” could be added to BlueZ in the future.

  Activate()
  DeviceFound(device: o)
  DeviceLost(device: o)
  Patterns()
  RSSIHighThreshold() → n
  RSSIHighTimeout() → q
  RSSILowThreshold() → n
  RSSILowTimeout() → q
  RSSISamplingPeriod() → q
  Release()
  Type() → s

## bleak.backends.bluezdbus.client module

BLE Client for BlueZ on Linux

class bleak.backends.bluezdbus.client.BleakClientBlueZDBus(address_or_ble_device: BLEDevice | str, services: set[str] | None = None, **kwargs: Any)

  Bases: `BaseBleakClient`

  A native Linux Bleak Client

  Implemented by using the BlueZ DBUS API.

  Parameters:

    - address_or_ble_device (BLEDevice or str) – The Bluetooth address of the BLE peripheral to connect to or the BLEDevice object representing it.

    - services – Optional list of service UUIDs that will be used.

  async connect(pair: bool, dangerous_use_bleak_cache: bool = False, **kwargs: Any) → None

    Connect to the specified GATT server.

    Keyword Arguments:

      timeout (float) – Timeout for required `BleakScanner.find_device_by_address` call.

    Raises:

      - BleakError – If the device is already connected or if the device could not be found.

      - BleakDBusError – If there was a D-Bus error

      - asyncio.TimeoutError – If the connection timed out

  async disconnect() → None

    Disconnect from the specified GATT server.

    Raises:

      - BleakDBusError – If there was a D-Bus error

      - asyncio.TimeoutError if the device was not disconnected within 10 seconds –

  property is_connected: bool

    Check connection status between this client and the server.

    Returns:

      Boolean representing connection status.

  property mtu_size: int

    Get ATT MTU size for active connection

  property name: str

    See `bleak.BleakClient.name()`.

  async pair(*args: Any, **kwargs: Any) → None

    Pair with the peripheral.

    You can use ConnectDevice method if you already know the MAC address of the device. Else you need to StartDiscovery, Trust, Pair and Connect in sequence.

  async read_gatt_char(characteristic: BleakGATTCharacteristic, **kwargs: Any) → bytearray

    Perform read operation on the specified GATT characteristic.

    Parameters:

      characteristic (BleakGATTCharacteristic) – The characteristic to read from.

    Returns:

      (bytearray) The read data.

  async read_gatt_descriptor(descriptor: BleakGATTDescriptor, **kwargs: Any) → bytearray

    Perform read operation on the specified GATT descriptor.

    Parameters:

      descriptor – The descriptor to read from.

    Returns:

      The read data.

  async start_notify(characteristic: BleakGATTCharacteristic, callback: Callable[[bytearray], None], **kwargs: Any) → None

    Activate notifications/indications on a characteristic.

  async stop_notify(characteristic: BleakGATTCharacteristic) → None

    Deactivate notification/indication on a specified characteristic.

    Parameters:

      characteristic (BleakGATTCharacteristic) – The characteristic to deactivate notification/indication on.

  async unpair() → None

    Unpair with the peripheral.

  async write_gatt_char(characteristic: BleakGATTCharacteristic, data: SizedBuffer, response: bool) → None

    Perform a write operation on the specified GATT characteristic.

    Parameters:

      - characteristic – The characteristic to write to.

      - data – The data to send.

      - response – If write-with-response operation should be done.

  async write_gatt_descriptor(descriptor: BleakGATTDescriptor, data: SizedBuffer) → None

    Perform a write operation on the specified GATT descriptor.

    Parameters:

      - handle – The handle of the descriptor to read from.

      - data – The data to send (any bytes-like object).

## bleak.backends.bluezdbus.defs module

class bleak.backends.bluezdbus.defs.Adapter1

  Bases: `TypedDict`

  Address: str
  Alias: str
  Class: int
  Discoverable: bool
  DiscoverableTimeout: int
  Discovering: int
  ExperimentalFeatures: list[str]
  Modalias: str
  Name: str
  Pairable: bool
  PairableTimeout: int
  Powered: bool
  Roles: list[str]
  UUIDs: list[str]

class bleak.backends.bluezdbus.defs.AdvertisementMonitor1

  Bases: `TypedDict`

  Patterns: list[tuple[int, int, bytes]]
  RSSIHighThreshold: int
  RSSIHighTimeout: int
  RSSILowThreshold: int
  RSSILowTimeout: int
  RSSISamplingPeriod: int
  Type: str

class bleak.backends.bluezdbus.defs.AdvertisementMonitorManager1

  Bases: `TypedDict`

  SupportedFeatures: list[str]
  SupportedMonitorTypes: list[str]

class bleak.backends.bluezdbus.defs.Battery1

  Bases: `TypedDict`

  SupportedFeatures: list[str]
  SupportedMonitorTypes: list[str]

class bleak.backends.bluezdbus.defs.Device1

  Bases: `TypedDict`

  Adapter: str
  Address: str
  AddressType: str
  AdvertisingData: dict[int, bytes]
  AdvertisingFlags: bytes
  Alias: str
  Appearance: int
  Blocked: bool
  Bonded: bool
  Class: int
  Connected: bool
  Icon: str
  LegacyPairing: bool
  ManufacturerData: dict[int, bytes]
  Modalias: str
  Name: str
  Paired: bool
  RSSI: int
  ServiceData: dict[str, bytes]
  ServicesResolved: bool
  Trusted: bool
  TxPower: int
  UUIDs: list[str]
  WakeAllowed: bool

class bleak.backends.bluezdbus.defs.GattCharacteristic1

  Bases: `TypedDict`

  Flags: list[Literal['broadcast', 'read', 'write-without-response', 'write', 'notify', 'indicate', 'authenticated-signed-writes', 'extended-properties', 'reliable-write', 'writable-auxiliaries', 'encrypt-read', 'encrypt-write', 'encrypt-authenticated-read', 'encrypt-authenticated-write', 'authorize']]
  MTU: int
  NotifyAcquired: bool
  Notifying: bool
  Service: str
  UUID: str
  Value: bytes
  WriteAcquired: bool

class bleak.backends.bluezdbus.defs.GattDescriptor1

  Bases: `TypedDict`

  Characteristic: str
  Flags: list[Literal['read', 'write', 'encrypt-read', 'encrypt-write', 'encrypt-authenticated-read', 'encrypt-authenticated-write', 'authorize']]
  UUID: str
  Value: bytes

class bleak.backends.bluezdbus.defs.GattService1

  Bases: `TypedDict`

  Device: str
  Includes: list[str]
  Primary: bool
  UUID: str

## bleak.backends.bluezdbus.manager module

### BlueZ D-Bus manager module

This module contains code for the global BlueZ D-Bus object manager that is used internally by Bleak.

bleak.backends.bluezdbus.manager.AdvertisementCallback

  A callback that is called when advertisement data is received.

  Parameters:

    - arg0 – The D-Bus object path of the device.

    - arg1 – The D-Bus properties of the device object.

  alias of `Callable`[[`str`, `Device1`], `None`]

class bleak.backends.bluezdbus.manager.BlueZManager

  Bases: `object`

  BlueZ D-Bus object manager.

  Use `bleak.backends.bluezdbus.get_global_bluez_manager()` to get the global instance.

  async active_scan(adapter_path: str, filters: dict[str, dbus_fast.Variant], advertisement_callback: Callable[[str, Device1], None], device_removed_callback: Callable[[str], None]) → Callable[[], Coroutine[Any, Any, None]]

    Configures the advertisement data filters and starts scanning.

    Parameters:

      - adapter_path – The D-Bus object path of the adapter to use for scanning.

      - filters – A dictionary of filters to pass to `SetDiscoveryFilter`.

      - advertisement_callback – A callable that will be called when new advertisement data is received.

      - device_removed_callback – A callable that will be called when a device is removed from BlueZ.

    Returns:

      An async function that is used to stop scanning and remove the filters.

    Raises:

      BleakError – if the adapter is not present in BlueZ

  add_device_watcher(device_path: str, on_connected_changed: Callable[[bool], None], on_characteristic_value_changed: Callable[[str, bytes], None]) → DeviceWatcher

    Registers a device watcher to receive callbacks when device state changes or events are received.

    Parameters:

      - device_path – The D-Bus object path of the device.

      - on_connected_changed – A callback that is called when the device’s “Connected” state changes.

      - on_characteristic_value_changed – A callback that is called whenever a characteristic receives a notification/indication.

    Returns:

      A device watcher object that acts a token to unregister the watcher.

    Raises:

      BleakError – if the device is not present in BlueZ

  async async_init() → None

    Connects to the D-Bus message bus and begins monitoring signals.

    It is safe to call this method multiple times. If the bus is already connected, no action is performed.

  get_default_adapter() → str

    Gets the D-Bus object path of of the first powered Bluetooth adapter.

    Returns:

      Name of the first found powered adapter on the system, i.e. “/org/bluez/hciX”.

    Raises:

      BleakBluetoothNotAvailableError – if there are no Bluetooth Low Energy adapters or if none of the adapters are powered

    Changed in version 2.0: Now raises `BleakBluetoothNotAvailableError` instead of `BleakError`.

  get_device_address(device_path: str) → str

    Gets the value of the “Address” property for a device.

    Parameters:

      device_path – The D-Bus object path of the device.

    Returns:

      The current property value.

    Raises:

      BleakError – if the device is not present in BlueZ

  get_device_name(device_path: str) → str

    Gets the value of the “Name” property for a device.

    Parameters:

      device_path – The D-Bus object path of the device.

    Returns:

      The current property value.

    Raises:

      BleakError – if the device is not present in BlueZ

  async get_services(device_path: str, use_cached: bool, requested_services: set[str] | None) → BleakGATTServiceCollection

    Builds a new `BleakGATTServiceCollection` from the current state.

    Parameters:

      - device_path – The D-Bus object path of the Bluetooth device.

      - use_cached – When `True` if there is a cached `BleakGATTServiceCollection`, the method will not wait for `"ServicesResolved"` to become true and instead return the cached service collection immediately.

      - requested_services – When given, only return services with UUID that is in the list of requested services.

    Returns:

      A new `BleakGATTServiceCollection`.

    Raises:

      BleakError – if the device is not present in BlueZ

  is_connected(device_path: str) → bool

    Gets the value of the “Connected” property for a device.

    Parameters:

      device_path – The D-Bus object path of the device.

    Returns:

      The current property value or `False` if the device does not exist in BlueZ.

  is_paired(device_path: str) → bool

    Gets the value of the “Paired” property for a device.

    Parameters:

      device_path – The D-Bus object path of the device.

    Returns:

      The current property value or `False` if the device does not exist in BlueZ.

  async passive_scan(adapter_path: str, filters: list[OrPattern | tuple[int, AdvertisementDataType, bytes]], advertisement_callback: Callable[[str, Device1], None], device_removed_callback: Callable[[str], None]) → Callable[[], Coroutine[Any, Any, None]]

    Configures the advertisement data filters and starts scanning.

    Parameters:

      - adapter_path – The D-Bus object path of the adapter to use for scanning.

      - filters – A list of “or patterns” to pass to `org.bluez.AdvertisementMonitor1`.

      - advertisement_callback – A callable that will be called when new advertisement data is received.

      - device_removed_callback – A callable that will be called when a device is removed from BlueZ.

    Returns:

      An async function that is used to stop scanning and remove the filters.

    Raises:

      BleakError – if the adapter is not present in BlueZ

  remove_device_watcher(watcher: DeviceWatcher) → None

    Unregisters a device watcher.

    Parameters:

      by (The device watcher token that was returned)

    :param `add_device_watcher()`.:

bleak.backends.bluezdbus.manager.CharacteristicValueChangedCallback

  A callback that is called when a characteristics’s “Value” property changes.

  Parameters:

    - arg0 – The D-Bus object path of the characteristic.

    - arg1 – The current value of the “Value” property.

  alias of `Callable`[[`str`, `bytes`], `None`]

class bleak.backends.bluezdbus.manager.DeviceConditionCallback(callback: Callable[[Any | None], None], property_name: str)

  Bases: `NamedTuple`

  Encapsulates a `DevicePropertiesChangedCallback` and the property name being watched.

  callback: Callable[[Any | None], None]

    The callback.

  property_name: str

    The name of the property to watch.

bleak.backends.bluezdbus.manager.DeviceConnectedChangedCallback

  A callback that is called when a device’s “Connected” property changes.

  Parameters:

    arg0 – The current value of the “Connected” property.

  alias of `Callable`[[`bool`], `None`]

bleak.backends.bluezdbus.manager.DevicePropertiesChangedCallback

  A callback that is called when the properties of a device change in BlueZ.

  Parameters:

    arg0 – The new property value.

  alias of `Callable`[[`Any` | `None`], `None`]

bleak.backends.bluezdbus.manager.DeviceRemovedCallback

  A callback that is called when a device is removed from BlueZ.

  Parameters:

    arg0 – The D-Bus object path of the device.

  alias of `Callable`[[`str`], `None`]

class bleak.backends.bluezdbus.manager.DeviceRemovedCallbackAndState(callback: Callable[[str], None], adapter_path: str)

  Bases: `NamedTuple`

  Encapsulates an `DeviceRemovedCallback` and some state.

  adapter_path: str

    The D-Bus object path of the adapter associated with the callback.

  callback: Callable[[str], None]

    The callback.

class bleak.backends.bluezdbus.manager.DeviceWatcher(device_path, on_connected_changed, on_characteristic_value_changed)

  Bases: `NamedTuple`

  device_path: str

    The D-Bus object path of the device.

  on_characteristic_value_changed: Callable[[str, bytes], None]

    A callback that is called when a characteristics’s “Value” property changes.

  on_connected_changed: Callable[[bool], None]

    A callback that is called when a device’s “Connected” property changes.

async bleak.backends.bluezdbus.manager.get_global_bluez_manager() → BlueZManager

  Gets an existing initialized global BlueZ manager instance associated with the current event loop, or initializes a new instance.

bleak.backends.bluezdbus.manager.get_max_write_without_response_size(char_props: GattCharacteristic1) → int

## bleak.backends.bluezdbus.scanner module

class bleak.backends.bluezdbus.scanner.BleakScannerBlueZDBus(detection_callback: Callable[[BLEDevice, AdvertisementData], Coroutine[Any, Any, None] | None] | None, service_uuids: list[str] | None, scanning_mode: Literal['active', 'passive'], *, bluez: BlueZScannerArgs, **kwargs: Any)

  Bases: `BaseBleakScanner`

  The native Linux Bleak BLE Scanner.

  For possible values for filters, see the parameters to the `SetDiscoveryFilter` method in the BlueZ docs

  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. Specifying this also enables scanning while the screen is off on Android.

    - scanning_mode – Set to `"passive"` to avoid the `"active"` scanning mode.

    - **bluez – Dictionary of arguments specific to the BlueZ backend.

    - **adapter (str) – Bluetooth adapter to use for discovery.

  set_scanning_filter(**kwargs: Any) → None

    Sets OS level scanning filters for the BleakScanner.

    For possible values for filters, see the parameters to the `SetDiscoveryFilter` method in the BlueZ docs

    See variant types here: <https://python-dbus-next.readthedocs.io/en/latest/type-system/>

    Keyword Arguments:

      filters (dict) – A dict of filters to be applied on discovery.

  async start() → None

    Start scanning for devices

  async stop() → None

    Stop scanning for devices

## bleak.backends.bluezdbus.signals module

exception bleak.backends.bluezdbus.signals.InvalidMessageTypeError(type: str)

  Bases: `TypeError`

class bleak.backends.bluezdbus.signals.MatchRules(type: str = 'signal', sender: str | None = None, interface: str | None = None, member: str | None = None, path: str | None = None, path_namespace: str | None = None, destination: str | None = None, arg0namespace: str | None = None, **kwargs: Any)

  Bases: `object`

  D-Bus signal match rules.

  See also

  https://dbus.freedesktop.org/doc/dbus-specification.html#message-bus-routing-match-rules

  static parse(rules: str) → MatchRules

async bleak.backends.bluezdbus.signals.add_match(bus: dbus_fast.aio.message_bus.MessageBus, rules: MatchRules) → dbus_fast.message.Message

  Calls org.freedesktop.DBus.AddMatch using `rules`.

bleak.backends.bluezdbus.signals.assert_bus_name_valid(type: str) → None

  Raise an error if this is not a valid message type.

  See also

  https://dbus.freedesktop.org/doc/dbus-specification.html#message-bus-routing-match-rules

  Parameters:

    type – The message type to validate.

  Raises:

    - `InvalidMessageTypeError` - If this is not a valid message type.

bleak.backends.bluezdbus.signals.is_message_type_valid(type: str) → bool

  Whether this is a valid message type.

  See also

  https://dbus.freedesktop.org/doc/dbus-specification.html#message-bus-routing-match-rules

  Parameters:

    type – The message type to validate.

  Returns:

    Whether the name is a valid message type.

  Return type:

    bool

async bleak.backends.bluezdbus.signals.remove_match(bus: dbus_fast.aio.message_bus.MessageBus, rules: MatchRules) → dbus_fast.message.Message

  Calls org.freedesktop.DBus.RemoveMatch using `rules`.

## bleak.backends.bluezdbus.utils module

bleak.backends.bluezdbus.utils.assert_reply(reply: dbus_fast.message.Message) → None

  Checks that a D-Bus message is a valid reply.

  Raises:

    - BleakDBusError – if the message type is `MessageType.ERROR`

    - AssertionError – if the message type is not `MessageType.METHOD_RETURN`

bleak.backends.bluezdbus.utils.device_path_from_characteristic_path(characteristic_path: str) → str

  Scrape the device path from a D-Bus characteristic path.

  Parameters:

    characteristic_path – The D-Bus object path of the characteristic.

  Returns:

    A D-Bus object path of the device.

bleak.backends.bluezdbus.utils.extract_service_handle_from_path(path: str) → int

bleak.backends.bluezdbus.utils.get_dbus_authenticator() → dbus_fast.auth.AuthExternal | None

## bleak.backends.bluezdbus.version module

class bleak.backends.bluezdbus.version.BlueZFeatures

  Bases: `object`

  Check which features are supported by the BlueZ backend.

  async classmethod check_bluez_version() → None

    Check the bluez version.

  checked_bluez_version = False
  supported_version = True

## Module contents

BlueZ backend.