bleak.backends.bluezdbus package

Submodules

bleak.backends.bluezdbus.advertisement_monitor module

bleak.backends.bluezdbus.characteristic module

class bleak.backends.bluezdbus.characteristic.BleakGATTCharacteristicBlueZDBus(obj: bleak.backends.bluezdbus.defs.GattCharacteristic1, object_path: str, service_uuid: str, service_handle: int, max_write_without_response_size: int)[source]

Bases: bleak.backends.characteristic.BleakGATTCharacteristic

GATT Characteristic implementation for the BlueZ DBus backend

add_descriptor(descriptor: bleak.backends.descriptor.BleakGATTDescriptor)[source]

Add a BleakGATTDescriptor to the characteristic.

Should not be used by end user, but rather by bleak itself.

property descriptors: List[bleak.backends.descriptor.BleakGATTDescriptor]

List of descriptors for this service

get_descriptor(specifier: Union[int, str, uuid.UUID]) Optional[bleak.backends.descriptor.BleakGATTDescriptor][source]

Get a descriptor by handle (int) or UUID (str or uuid.UUID)

property handle: int

The handle of this characteristic

property path: str

The DBus path. Mostly needed by bleak, not by end user

property properties: List[str]

Properties of this characteristic

Returns the characteristics Flags present in the DBus API.

property service_handle: int

The handle of the Service containing this characteristic

property service_uuid: str

The uuid of the Service containing this characteristic

property uuid: str

The uuid of this characteristic

bleak.backends.bluezdbus.client module

BLE Client for BlueZ on Linux

class bleak.backends.bluezdbus.client.BleakClientBlueZDBus(address_or_ble_device: Union[bleak.backends.device.BLEDevice, str], **kwargs)[source]

Bases: bleak.backends.client.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.

Keyword Arguments
  • timeout (float) – Timeout for required BleakScanner.find_device_by_address call. Defaults to 10.0.

  • disconnected_callback (callable) – Callback that will be scheduled in the event loop when the client is disconnected. The callable must take one argument, which will be this client object.

  • adapter (str) – Bluetooth adapter to use for discovery.

async connect(dangerous_use_bleak_cache: bool = False, **kwargs) bool[source]

Connect to the specified GATT server.

Keyword Arguments

timeout (float) – Timeout for required BleakScanner.find_device_by_address call. Defaults to 10.0.

Returns

Boolean representing connection status.

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() bool[source]

Disconnect from the specified GATT server.

Returns

Boolean representing if device is disconnected.

Raises
  • BleakDBusError – If there was a D-Bus error

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

async get_services(dangerous_use_bleak_cache: bool = False, **kwargs) bleak.backends.service.BleakGATTServiceCollection[source]

Get all services registered for this GATT server.

Parameters

dangerous_use_bleak_cache (bool) – Use cached services if available.

Returns

A bleak.backends.service.BleakGATTServiceCollection with this device’s services tree.

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

async pair(*args, **kwargs) bool[source]

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.

Returns

Boolean regarding success of pairing.

async read_gatt_char(char_specifier: Union[bleak.backends.bluezdbus.characteristic.BleakGATTCharacteristicBlueZDBus, int, str, uuid.UUID], **kwargs) bytearray[source]

Perform read operation on the specified GATT characteristic.

Parameters

char_specifier (BleakGATTCharacteristicBlueZDBus, int, str or UUID) – The characteristic to read from, specified by either integer handle, UUID or directly by the BleakGATTCharacteristicBlueZDBus object representing it.

Returns

(bytearray) The read data.

async read_gatt_descriptor(handle: int, **kwargs) bytearray[source]

Perform read operation on the specified GATT descriptor.

Parameters

handle (int) – The handle of the descriptor to read from.

Returns

(bytearray) The read data.

async start_notify(characteristic: bleak.backends.characteristic.BleakGATTCharacteristic, callback: Callable[[bytearray], None], **kwargs) None[source]

Activate notifications/indications on a characteristic.

async stop_notify(char_specifier: Union[bleak.backends.bluezdbus.characteristic.BleakGATTCharacteristicBlueZDBus, int, str, uuid.UUID]) None[source]

Deactivate notification/indication on a specified characteristic.

Parameters

char_specifier (BleakGATTCharacteristicBlueZDBus, int, str or UUID) – The characteristic to deactivate notification/indication on, specified by either integer handle, UUID or directly by the BleakGATTCharacteristicBlueZDBus object representing it.

async unpair() bool[source]

Unpair with the peripheral.

Returns

Boolean regarding success of unpairing.

async write_gatt_char(char_specifier: Union[bleak.backends.bluezdbus.characteristic.BleakGATTCharacteristicBlueZDBus, int, str, uuid.UUID], data: Union[bytes, bytearray, memoryview], response: bool = False) None[source]

Perform a write operation on the specified GATT characteristic.

Note

The version check below is for the “type” option to the “Characteristic.WriteValue” method that was added to Bluez in 5.51 Before that commit, Characteristic.WriteValue was only “Write with response”. Characteristic.AcquireWrite was added in Bluez 5.46 which can be used to “Write without response”, but for older versions of Bluez, it is not possible to “Write without response”.

Parameters
  • char_specifier (BleakGATTCharacteristicBlueZDBus, int, str or UUID) – The characteristic to write to, specified by either integer handle, UUID or directly by the BleakGATTCharacteristicBlueZDBus object representing it.

  • data (bytes or bytearray) – The data to send.

  • response (bool) – If write-with-response operation should be done. Defaults to False.

async write_gatt_descriptor(handle: int, data: Union[bytes, bytearray, memoryview]) None[source]

Perform a write operation on the specified GATT descriptor.

Parameters
  • handle (int) – The handle of the descriptor to read from.

  • data (bytes or bytearray) – The data to send.

bleak.backends.bluezdbus.defs module

class bleak.backends.bluezdbus.defs.Adapter1[source]

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[source]

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[source]

Bases: TypedDict

SupportedFeatures: List[str]
SupportedMonitorTypes: List[str]
class bleak.backends.bluezdbus.defs.Battery1[source]

Bases: TypedDict

SupportedFeatures: List[str]
SupportedMonitorTypes: List[str]
class bleak.backends.bluezdbus.defs.Device1[source]

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[source]

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[source]

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[source]

Bases: TypedDict

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

bleak.backends.bluezdbus.descriptor module

class bleak.backends.bluezdbus.descriptor.BleakGATTDescriptorBlueZDBus(obj: bleak.backends.bluezdbus.defs.GattDescriptor1, object_path: str, characteristic_uuid: str, characteristic_handle: int)[source]

Bases: bleak.backends.descriptor.BleakGATTDescriptor

GATT Descriptor implementation for BlueZ DBus backend

property characteristic_handle: int

Handle for the characteristic that this descriptor belongs to

property characteristic_uuid: str

UUID for the characteristic that this descriptor belongs to

property handle: int

Integer handle for this descriptor

property path: str

The DBus path. Mostly needed by bleak, not by end user

property uuid: str

UUID for this descriptor

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, bleak.backends.bluezdbus.defs.Device1], None]

class bleak.backends.bluezdbus.manager.BlueZManager[source]

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, bleak.backends.bluezdbus.defs.Device1], None], device_removed_callback: Callable[[str], None]) Callable[[], Coroutine][source]

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.

add_device_watcher(device_path: str, on_connected_changed: Callable[[bool], None], on_characteristic_value_changed: Callable[[str, bytes], None]) bleak.backends.bluezdbus.manager.DeviceWatcher[source]

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.

async async_init()[source]

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[source]

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

BleakError – if there are no Bluetooth adapters or if none of the adapters are powered

get_device_name(device_path: str) str[source]

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.

async get_services(device_path: str, use_cached: bool) bleak.backends.service.BleakGATTServiceCollection[source]

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.

Returns

A new BleakGATTServiceCollection.

is_connected(device_path: str) bool[source]

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.

async passive_scan(adapter_path: str, filters: List[Union[bleak.backends.bluezdbus.advertisement_monitor.OrPattern, Tuple[int, bleak.assigned_numbers.AdvertisementDataType, bytes]]], advertisement_callback: Callable[[str, bleak.backends.bluezdbus.defs.Device1], None], device_removed_callback: Callable[[str], None]) Callable[[], Coroutine][source]

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.

remove_device_watcher(watcher: bleak.backends.bluezdbus.manager.DeviceWatcher) None[source]

Unregisters a device watcher.

Parameters

by (The device watcher token that was returned) –

:param add_device_watcher().:

class bleak.backends.bluezdbus.manager.CallbackAndState(callback: Callable[[str, bleak.backends.bluezdbus.defs.Device1], None], adapter_path: str)[source]

Bases: NamedTuple

Encapsulates an AdvertisementCallback and some state.

adapter_path: str

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

callback: Callable[[str, bleak.backends.bluezdbus.defs.Device1], None]

The callback.

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]

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.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)[source]

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)[source]

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() bleak.backends.bluezdbus.manager.BlueZManager[source]

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

bleak.backends.bluezdbus.scanner module

class bleak.backends.bluezdbus.scanner.BleakScannerBlueZDBus(detection_callback: Optional[Callable[[bleak.backends.device.BLEDevice, bleak.backends.scanner.AdvertisementData], Optional[Awaitable[None]]]], service_uuids: Optional[List[str]], scanning_mode: Literal['active', 'passive'], *, bluez: bleak.backends.bluezdbus.scanner.BlueZScannerArgs, **kwargs)[source]

Bases: bleak.backends.scanner.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)[source]

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()[source]

Start scanning for devices

async stop()[source]

Stop scanning for devices

class bleak.backends.bluezdbus.scanner.BlueZDiscoveryFilters[source]

Bases: TypedDict

Dictionary of arguments for the org.bluez.Adapter1.SetDiscoveryFilter D-Bus method.

https://github.com/bluez/bluez/blob/master/doc/adapter-api.txt

Discoverable: bool

Make adapter discoverable while discovering, if the adapter is already discoverable setting this filter won’t do anything.

DuplicateData: bool

Disables duplicate detection of advertisement data.

This does not affect the Filter Duplicates parameter of the LE Set Scan Enable HCI command to the Bluetooth adapter!

Although the default value for BlueZ is True, Bleak sets this to False by default.

Pathloss: int

Pathloss threshold value.

Pattern: str

Discover devices where the pattern matches either the prefix of the address or device name which is convenient way to limited the number of device objects created during a discovery.

RSSI: int

RSSI threshold value.

Transport: str

Transport parameter determines the type of scan.

This should not be used since it is required to be set to "le".

UUIDs: List[str]

Filter by service UUIDs, empty means match _any_ UUID.

Normally, the service_uuids argument of bleak.BleakScanner is used instead.

class bleak.backends.bluezdbus.scanner.BlueZScannerArgs[source]

Bases: TypedDict

BleakScanner args that are specific to the BlueZ backend.

filters: bleak.backends.bluezdbus.scanner.BlueZDiscoveryFilters

Filters to pass to the adapter SetDiscoveryFilter D-Bus method.

Only used for active scanning.

or_patterns: List[Union[bleak.backends.bluezdbus.advertisement_monitor.OrPattern, Tuple[int, bleak.assigned_numbers.AdvertisementDataType, bytes]]]

Or patterns to pass to the AdvertisementMonitor1 D-Bus interface.

Only used for passive scanning.

bleak.backends.bluezdbus.service module

class bleak.backends.bluezdbus.service.BleakGATTServiceBlueZDBus(obj, path)[source]

Bases: bleak.backends.service.BleakGATTService

GATT Service implementation for the BlueZ DBus backend

add_characteristic(characteristic: bleak.backends.bluezdbus.characteristic.BleakGATTCharacteristicBlueZDBus)[source]

Add a BleakGATTCharacteristicBlueZDBus to the service.

Should not be used by end user, but rather by bleak itself.

property characteristics: List[bleak.backends.bluezdbus.characteristic.BleakGATTCharacteristicBlueZDBus]

List of characteristics for this service

property handle: int

The integer handle of this service

property path

The DBus path. Mostly needed by bleak, not by end user

property uuid: str

The UUID to this service

bleak.backends.bluezdbus.signals module

exception bleak.backends.bluezdbus.signals.InvalidMessageTypeError(type)[source]

Bases: TypeError

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

Bases: object

D-Bus signal match rules.

static parse(rules: str)[source]
bleak.backends.bluezdbus.signals.add_match(bus: dbus_fast.aio.message_bus.MessageBus, rules: bleak.backends.bluezdbus.signals.MatchRules) Coroutine[Any, Any, dbus_fast.message.Message][source]

Calls org.freedesktop.DBus.AddMatch using rules.

bleak.backends.bluezdbus.signals.assert_bus_name_valid(type: str)[source]

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

Parameters

type – The message type to validate.

Raises
bleak.backends.bluezdbus.signals.is_message_type_valid(type: str) bool[source]

Whether this is a valid message type.

Parameters

type – The message type to validate.

Returns

Whether the name is a valid message type.

Return type

bool

bleak.backends.bluezdbus.signals.remove_match(bus: dbus_fast.aio.message_bus.MessageBus, rules: bleak.backends.bluezdbus.signals.MatchRules) Coroutine[Any, Any, dbus_fast.message.Message][source]

Calls org.freedesktop.DBus.RemoveMatch using rules.

bleak.backends.bluezdbus.utils module

bleak.backends.bluezdbus.utils.assert_reply(reply: dbus_fast.message.Message)[source]

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.bdaddr_from_device_path(device_path: str) str[source]

Scrape the Bluetooth address from a D-Bus device path.

Parameters

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

Returns

A Bluetooth address as a string.

bleak.backends.bluezdbus.utils.extract_service_handle_from_path(path)[source]
bleak.backends.bluezdbus.utils.validate_address(address)[source]

bleak.backends.bluezdbus.version module

class bleak.backends.bluezdbus.version.BlueZFeatures[source]

Bases: object

Check which features are supported by the BlueZ backend.

can_write_without_response = True
async classmethod check_bluez_version() None[source]

Check the bluez version.

checked_bluez_version = False
hides_battery_characteristic = True
hides_device_name_characteristic = True
supported_version = True
write_without_response_workaround_needed = False

Module contents

BlueZ backend.