bleak package
Subpackages
- bleak.backends package
- Subpackages
- bleak.backends.bluezdbus package
- Submodules
- bleak.backends.bluezdbus.advertisement_monitor module
- bleak.backends.bluezdbus.characteristic module
- bleak.backends.bluezdbus.client module
- bleak.backends.bluezdbus.defs module
- bleak.backends.bluezdbus.descriptor module
- bleak.backends.bluezdbus.manager module
- bleak.backends.bluezdbus.scanner module
- bleak.backends.bluezdbus.service module
- bleak.backends.bluezdbus.signals module
- bleak.backends.bluezdbus.utils module
- bleak.backends.bluezdbus.version module
- Module contents
- bleak.backends.corebluetooth package
- Submodules
- bleak.backends.corebluetooth.CentralManagerDelegate module
- bleak.backends.corebluetooth.PeripheralDelegate module
- bleak.backends.corebluetooth.characteristic module
- bleak.backends.corebluetooth.client module
- bleak.backends.corebluetooth.descriptor module
- bleak.backends.corebluetooth.scanner module
- bleak.backends.corebluetooth.service module
- bleak.backends.corebluetooth.utils module
- Module contents
- bleak.backends.p4android package
- Submodules
- bleak.backends.p4android.characteristic module
- bleak.backends.p4android.client module
- bleak.backends.p4android.defs module
- bleak.backends.p4android.descriptor module
- bleak.backends.p4android.scanner module
- bleak.backends.p4android.service module
- bleak.backends.p4android.utils module
- Module contents
- bleak.backends.winrt package
- bleak.backends.bluezdbus package
- Submodules
- bleak.backends.characteristic module
BleakGATTCharacteristicBleakGATTCharacteristic.add_descriptor()BleakGATTCharacteristic.descriptionBleakGATTCharacteristic.descriptorsBleakGATTCharacteristic.get_descriptor()BleakGATTCharacteristic.handleBleakGATTCharacteristic.max_write_without_response_sizeBleakGATTCharacteristic.propertiesBleakGATTCharacteristic.service_handleBleakGATTCharacteristic.service_uuidBleakGATTCharacteristic.uuid
GattCharacteristicsFlagsGattCharacteristicsFlags.authenticated_signed_writesGattCharacteristicsFlags.broadcastGattCharacteristicsFlags.extended_propertiesGattCharacteristicsFlags.indicateGattCharacteristicsFlags.notifyGattCharacteristicsFlags.readGattCharacteristicsFlags.reliable_writeGattCharacteristicsFlags.writable_auxiliariesGattCharacteristicsFlags.writeGattCharacteristicsFlags.write_without_response
- bleak.backends.client module
BaseBleakClientBaseBleakClient.connect()BaseBleakClient.disconnect()BaseBleakClient.get_services()BaseBleakClient.is_connectedBaseBleakClient.mtu_sizeBaseBleakClient.pair()BaseBleakClient.read_gatt_char()BaseBleakClient.read_gatt_descriptor()BaseBleakClient.set_disconnected_callback()BaseBleakClient.start_notify()BaseBleakClient.stop_notify()BaseBleakClient.unpair()BaseBleakClient.write_gatt_char()BaseBleakClient.write_gatt_descriptor()
get_platform_client_backend_type()
- bleak.backends.descriptor module
- bleak.backends.device module
- bleak.backends.scanner module
- bleak.backends.service module
BleakGATTServiceBleakGATTServiceCollectionBleakGATTServiceCollection.add_characteristic()BleakGATTServiceCollection.add_descriptor()BleakGATTServiceCollection.add_service()BleakGATTServiceCollection.characteristicsBleakGATTServiceCollection.descriptorsBleakGATTServiceCollection.get_characteristic()BleakGATTServiceCollection.get_descriptor()BleakGATTServiceCollection.get_service()BleakGATTServiceCollection.services
- Module contents
- Subpackages
Submodules
bleak.assigned_numbers module
Bluetooth Assigned Numbers
This module contains useful assigned numbers from the Bluetooth spec.
See <https://www.bluetooth.com/specifications/assigned-numbers/>.
- class bleak.assigned_numbers.AdvertisementDataType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
IntEnumGeneric Access Profile advertisement data types.
Source <https://btprodspecificationrefs.blob.core.windows.net/assigned-numbers/Assigned%20Number%20Types/Generic%20Access%20Profile.pdf>.
New in version 0.15.0.
- CLASS_OF_DEVICE = 13
- COMPLETE_LIST_SERVICE_UUID128 = 7
- COMPLETE_LIST_SERVICE_UUID16 = 3
- COMPLETE_LIST_SERVICE_UUID32 = 5
- COMPLETE_LOCAL_NAME = 9
- FLAGS = 1
- INCOMPLETE_LIST_SERVICE_UUID128 = 6
- INCOMPLETE_LIST_SERVICE_UUID16 = 2
- INCOMPLETE_LIST_SERVICE_UUID32 = 4
- MANUFACTURER_SPECIFIC_DATA = 255
- SERVICE_DATA_UUID128 = 33
- SERVICE_DATA_UUID16 = 22
- SERVICE_DATA_UUID32 = 32
- SHORTENED_LOCAL_NAME = 8
- TX_POWER_LEVEL = 10
bleak.exc module
- exception bleak.exc.BleakDBusError(dbus_error: str, error_body: list)[source]
Bases:
BleakErrorSpecialized exception type for D-Bus errors.
- property dbus_error: str
Gets the D-Bus error name, e.g.
org.freedesktop.DBus.Error.UnknownObject.
- property dbus_error_details: Optional[str]
Gets the optional D-Bus error details, e.g. ‘Invalid UUID’.
- exception bleak.exc.BleakDeviceNotFoundError(identifier: str, *args: object)[source]
Bases:
BleakErrorException which is raised if a device can not be found by
connect,pairandunpair. This is the case if the OS Bluetooth stack has never seen this device or it was removed and forgotten.- identifier: str
bleak.uuids module
- bleak.uuids.normalize_uuid_16(uuid: int) str[source]
Normaizes a 16-bit integer UUID to the format used by Bleak.
- Returns:
128-bit UUID as string with the format
"0000xxxx-1000-8000-00805f9b34fb".
Example:
uuid = normalize_uuid_16(0x1234) # uuid == "00001234-1000-8000-00805f9b34fb"
New in version 0.21.
- bleak.uuids.normalize_uuid_32(uuid: int) str[source]
Normaizes a 32-bit integer UUID to the format used by Bleak.
- Returns:
128-bit UUID as string with the format
"xxxxxxxx-1000-8000-00805f9b34fb".
Example:
uuid = normalize_uuid_32(0x12345678) # uuid == "12345678-1000-8000-00805f9b34fb"
New in version 0.21.
- bleak.uuids.normalize_uuid_str(uuid: str) str[source]
Normaizes a UUID to the format used by Bleak.
Converted to lower case.
16-bit and 32-bit UUIDs are expanded to 128-bit.
Example:
# 16-bit uuid1 = normalize_uuid_str("1234") # uuid1 == "00001234-1000-8000-00805f9b34fb" # 32-bit uuid2 = normalize_uuid_str("12345678") # uuid2 == "12345678-1000-8000-00805f9b34fb" # 128-bit uuid3 = normalize_uuid_str("12345678-1234-1234-1234567890ABC") # uuid3 == "12345678-1234-1234-1234567890abc"
New in version 0.20.
Changed in version 0.21: Added support for 32-bit UUIDs.
Module contents
Top-level package for bleak.
- class bleak.BleakClient(address_or_ble_device: Union[BLEDevice, str], disconnected_callback: Optional[Callable[[BleakClient], None]] = None, services: Optional[Iterable[str]] = None, *, timeout: float = 10.0, winrt: WinRTClientArgs = {}, backend: Optional[Type[BaseBleakClient]] = None, **kwargs)[source]
Bases:
objectThe Client interface for connecting to a specific BLE GATT server and communicating with it.
A BleakClient can be used as an asynchronous context manager in which case it automatically connects and disconnects.
How many BLE connections can be active simultaneously, and whether connections can be active while scanning depends on the Bluetooth adapter hardware.
- Parameters:
address_or_ble_device – A
BLEDevicereceived from aBleakScanneror a Bluetooth address (device UUID on macOS).disconnected_callback – 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.
services – Optional list of services to filter. If provided, only these services will be resolved. This may or may not reduce the time needed to enumerate the services depending on if the OS supports such filtering in the Bluetooth stack or not (should affect Windows and Mac). These can be 16-bit or 128-bit UUIDs.
timeout – Timeout in seconds passed to the implicit
discovercall whenaddress_or_ble_deviceis not aBLEDevice. Defaults to 10.0.winrt – Dictionary of WinRT/Windows platform-specific options.
backend – Used to override the automatically selected backend (i.e. for a custom backend).
**kwargs – Additional keyword arguments for backwards compatibility.
Warning
Although example code frequently initializes
BleakClientwith a Bluetooth address for simplicity, it is not recommended to do so for more complex use cases. There are several known issues with providing a Bluetooth address as theaddress_or_ble_deviceargument.macOS does not provide access to the Bluetooth address for privacy/ security reasons. Instead it creates a UUID for each Bluetooth device which is used in place of the address on this platform.
Providing an address or UUID instead of a
BLEDevicecauses theconnect()method to implicitly callBleakScanner.discover(). This is known to cause problems when trying to connect to multiple devices at the same time.
Changed in version 0.15.0:
disconnected_callbackis no longer keyword-only. Addedwinrtparameter.Changed in version 0.18.0: No longer is alias for backend type and no longer inherits from
BaseBleakClient. Addedbackendparameter.- property address: str
Gets the Bluetooth address of this device (UUID on macOS).
- async connect(**kwargs) bool[source]
Connect to the specified GATT server.
- Parameters:
**kwargs – For backwards compatibility - should not be used.
- Returns:
Always returns
Truefor backwards compatibility.
- async disconnect() bool[source]
Disconnect from the specified GATT server.
- Returns:
Always returns
Truefor backwards compatibility.
- async get_services(**kwargs) BleakGATTServiceCollection[source]
Get all services registered for this GATT server.
Deprecated since version 0.17.0: This method will be removed in a future version of Bleak. Use the
servicesproperty instead.- Returns:
A
bleak.backends.service.BleakGATTServiceCollectionwith this device’s services tree.
- property is_connected: bool
Check connection status between this client and the GATT server.
- Returns:
Boolean representing connection status.
- property mtu_size: int
Gets the negotiated MTU size in bytes for the active connection.
Consider using
bleak.backends.characteristic.BleakGATTCharacteristic.max_write_without_response_sizeinstead.Warning
The BlueZ backend will always return 23 (the minimum MTU size). See the
mtu_size.pyexample for a way to hack around this.
- async pair(*args, **kwargs) bool[source]
Pair with the specified GATT server.
This method is not available on macOS. Instead of manually initiating paring, the user will be prompted to pair the device the first time that a characteristic that requires authentication is read or written. This method may have backend-specific additional keyword arguments.
- Returns:
Always returns
Truefor backwards compatibility.
- async read_gatt_char(char_specifier: Union[BleakGATTCharacteristic, int, str, UUID], **kwargs) bytearray[source]
Perform read operation on the specified GATT characteristic.
- Parameters:
char_specifier – The characteristic to read from, specified by either integer handle, UUID or directly by the BleakGATTCharacteristic object representing it.
- Returns:
The read data.
- async read_gatt_descriptor(handle: int, **kwargs) bytearray[source]
Perform read operation on the specified GATT descriptor.
- Parameters:
handle – The handle of the descriptor to read from.
- Returns:
The read data.
- property services: BleakGATTServiceCollection
Gets the collection of GATT services available on the device.
The returned value is only valid as long as the device is connected.
- Raises:
BleakError – if service discovery has not been performed yet during this connection.
- set_disconnected_callback(callback: Optional[Callable[[BleakClient], None]], **kwargs) None[source]
Set the disconnect callback.
Deprecated since version 0.17.0: This method will be removed in a future version of Bleak. Pass the callback to the
BleakClientconstructor instead.- Parameters:
callback – callback to be called on disconnection.
- async start_notify(char_specifier: Union[BleakGATTCharacteristic, int, str, UUID], callback: Callable[[BleakGATTCharacteristic, bytearray], Union[None, Awaitable[None]]], **kwargs) None[source]
Activate notifications/indications on a characteristic.
Callbacks must accept two inputs. The first will be the characteristic and the second will be a
bytearraycontaining the data received.def callback(sender: BleakGATTCharacteristic, data: bytearray): print(f"{sender}: {data}") client.start_notify(char_uuid, callback)
- Parameters:
char_specifier – The characteristic to activate notifications/indications on a characteristic, specified by either integer handle, UUID or directly by the BleakGATTCharacteristic object representing it.
callback – The function to be called on notification. Can be regular function or async function.
Changed in version 0.18.0: The first argument of the callback is now a
BleakGATTCharacteristicinstead of anint.
- async stop_notify(char_specifier: Union[BleakGATTCharacteristic, int, str, UUID]) None[source]
Deactivate notification/indication on a specified characteristic.
- Parameters:
char_specifier – The characteristic to deactivate notification/indication on, specified by either integer handle, UUID or directly by the BleakGATTCharacteristic object representing it.
Tip
Notifications are stopped automatically on disconnect, so this method does not need to be called unless notifications need to be stopped some time before the device disconnects.
- async unpair() bool[source]
Unpair from the specified GATT server.
Unpairing will also disconnect the device.
This method is only available on Windows and Linux and will raise an exception on other platforms.
- Returns:
Always returns
Truefor backwards compatibility.
- async write_gatt_char(char_specifier: Union[BleakGATTCharacteristic, int, str, UUID], data: typing_extensions.Buffer, response: bool = None) None[source]
Perform a write operation on the specified GATT characteristic.
There are two possible kinds of writes. Write with response (sometimes called a Request) will write the data then wait for a response from the remote device. Write without response (sometimes called Command) will queue data to be written and return immediately.
Each characteristic may support one kind or the other or both or neither. Consult the device’s documentation or inspect the properties of the characteristic to find out which kind of writes are supported.
Tip
Explicit is better than implicit. Best practice is to always include an explicit
response=Trueorresponse=Falsewhen calling this method.- Parameters:
char_specifier – The characteristic to write to, specified by either integer handle, UUID or directly by the
BleakGATTCharacteristicobject representing it. If a device has more than one characteristic with the same UUID, then attempting to use the UUID wil fail and a characteristic object must be used instead.data – The data to send. When a write-with-response operation is used, the length of the data is limited to 512 bytes. When a write-without-response operation is used, the length of the data is limited to
max_write_without_response_size. Any type that supports the buffer protocol can be passed.response – If
True, a write-with-response operation will be used. IfFalse, a write-without-response operation will be used. If omitted orNone, the “best” operation will be used based on the reported properties of the characteristic.
Changed in version 0.21: The default behavior when
response=is omitted was changed.Example:
MY_CHAR_UUID = "1234" ... await client.write_gatt_char(MY_CHAR_UUID, b"", response=True)
- 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]
Bases:
objectInterface 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
BLEDeviceobjects. These can subsequently be used to connect to the corresponding BLE server.A
BleakScannercan 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 raiseBleakErrorif 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_callbackmay 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 foradv_data.local_name is not None.Changed in version 0.15.0:
detection_callback,service_uuidsandscanning_modeare no longer keyword-only. Addedbluezparameter.Changed in version 0.18.0: No longer is alias for backend type and no longer inherits from
BaseBleakScanner. Addedbackendparameter.- class ExtraArgs[source]
Bases:
TypedDictKeyword args from
BleakScannerthat 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 raiseBleakErrorif 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).
- async 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.
- async classmethod discover(timeout: float = 5.0, *, return_adv: Literal[False] = False, **kwargs) List[BLEDevice][source]
- async classmethod discover(timeout: float = 5.0, *, return_adv: Literal[True], **kwargs) Dict[str, Tuple[BLEDevice, AdvertisementData]]
Scan continuously for
timeoutseconds 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
BleakScannerconstructor.
- Returns:
The value of
discovered_devices_and_advertisement_dataifreturn_advisTrue, otherwise the value ofdiscovered_devices.
Changed in version 0.19.0: Added
return_advparameter.
- property 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_datainstead.
- property 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.
- async classmethod find_device_by_address(device_identifier: str, timeout: float = 10.0, **kwargs: Unpack[ExtraArgs]) Optional[BLEDevice][source]
Obtain a
BLEDevicefor 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
BleakScannerconstructor.
- Returns:
The
BLEDevicesought orNoneif not detected.
- async classmethod find_device_by_filter(filterfunc: AdvertisementDataFilter, timeout: float = 10.0, **kwargs: Unpack[ExtraArgs]) Optional[BLEDevice][source]
Obtain a
BLEDevicefor 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
Trueonly 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
BleakScannerconstructor.
- Returns:
The
BLEDevicesought orNoneif not detected before the timeout.
- async classmethod find_device_by_name(name: str, timeout: float = 10.0, **kwargs: Unpack[ExtraArgs]) Optional[BLEDevice][source]
Obtain a
BLEDevicefor 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
BleakScannerconstructor.
- Returns:
The
BLEDevicesought orNoneif not detected.
New in version 0.20.0.
- async 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_devicesproperty instead.- Returns:
A list of the devices that the scanner has discovered during the scanning.
- 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
BleakScannerconstructor instead.- Parameters:
callback – A function, coroutine or
None.
- set_scanning_filter(**kwargs)[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
BleakScannerconstructor instead.- Parameters:
**kwargs – The filter details.
- bleak.discover(*args, **kwargs)[source]
Deprecated since version 0.17.0: This method will be removed in a future version of Bleak. Use
BleakScanner.discover()instead.