Linux backend
The Linux backend of Bleak communicates with BlueZ over DBus. Communication uses the dbus-fast package for async access to DBus messaging.
Special handling for write_gatt_char
The type
option to the Characteristic.WriteValue
method 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 (5.43, 5.44, 5.45), it is not possible to “Write without response”.
Resolving services with get_services
By default, calling get_services
will wait for services to be resolved
before returning the BleakGATTServiceCollection
. If a previous connection
to the device was made, passing the dangerous_use_bleak_cache
argument will
return the cached services without waiting for them to be resolved again. This
is useful when you know services have not changed, and you want to use the
services immediately, but don’t want to wait for them to be resolved again.
Parallel Access
Each Bleak object should be created and used from a single asyncio event
loop. Simple asyncio programs will only have a single event loop. It’s also
possible to use Bleak with multiple event loops, even at the same time, but
individual Bleak objects should not be shared between event loops. Otherwise,
RuntimeErrors similar to [...] got Future <Future pending> attached to a
different loop
will be thrown.
D-Bus Authentication
Connecting to the host DBus from within a user namespace will fail. This is because the remapped UID will not match the UID that the hosts sees. To work around this, you can hardcode a UID with the BLEAK_DBUS_AUTH_UID environment variable.
API
Scanner
- class bleak.backends.bluezdbus.scanner.BleakScannerBlueZDBus(detection_callback: Optional[Callable[[BLEDevice, AdvertisementData], Optional[Coroutine[Any, Any, None]]]], service_uuids: Optional[List[str]], scanning_mode: Literal['active', 'passive'], *, bluez: BlueZScannerArgs, **kwargs)[source]
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.
- seen_devices: Dict[str, Tuple[BLEDevice, AdvertisementData]]
Map of device identifier to BLEDevice and most recent advertisement data.
This map must be cleared when scanning starts.
- set_scanning_filter(**kwargs) None [source]
Sets OS level scanning filters for the BleakScanner.
For possible values for filters, see the parameters to the
SetDiscoveryFilter
method in the BlueZ docsSee 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.
- class bleak.backends.bluezdbus.scanner.BlueZDiscoveryFilters[source]
Dictionary of arguments for the
org.bluez.Adapter1.SetDiscoveryFilter
D-Bus method.- 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 theLE Set Scan Enable
HCI command to the Bluetooth adapter!Although the default value for BlueZ is
True
, Bleak sets this toFalse
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 ofbleak.BleakScanner
is used instead.
- class bleak.backends.bluezdbus.scanner.BlueZScannerArgs[source]
BleakScanner
args that are specific to the BlueZ backend.- filters: BlueZDiscoveryFilters
Filters to pass to the adapter SetDiscoveryFilter D-Bus method.
Only used for active scanning.
- or_patterns: List[Union[OrPattern, Tuple[int, AdvertisementDataType, bytes]]]
Or patterns to pass to the AdvertisementMonitor1 D-Bus interface.
Only used for passive scanning.
Client
BLE Client for BlueZ on Linux
- class bleak.backends.bluezdbus.client.BleakClientBlueZDBus(address_or_ble_device: Union[BLEDevice, str], services: Optional[Set[str]] = None, **kwargs)[source]
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.
- 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) 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[BleakGATTCharacteristicBlueZDBus, int, str, 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: BleakGATTCharacteristic, callback: Callable[[bytearray], None], **kwargs) None [source]
Activate notifications/indications on a characteristic.
- async stop_notify(char_specifier: Union[BleakGATTCharacteristicBlueZDBus, int, str, 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(characteristic: BleakGATTCharacteristic, data: typing_extensions.Buffer, response: bool) None [source]
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.