BleakClient class
- class bleak.BleakClient(address_or_ble_device: BLEDevice | str, disconnected_callback: Callable[[BleakClient], None] | None = None, services: Iterable[str] | None = None, *, timeout: float = 10.0, pair: bool = False, winrt: WinRTClientArgs = {}, backend: type[BaseBleakClient] | None = None, **kwargs: Any)[source]
The 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
BLEDevice
received from aBleakScanner
or 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
discover
call whenaddress_or_ble_device
is not aBLEDevice
. Defaults to 10.0.pair – Attempt to pair with the the device before connecting, if it is not already paired. This has no effect on macOS since pairing is initiated automatically when accessing a characteristic that requires authentication. In rare cases, on other platforms, it might be necessary to pair the device first in order to be able to even enumerate the services during the connection process.
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
BleakClient
with 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_device
argument.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
BLEDevice
causes 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:
disconnected_callback
is no longer keyword-only. Addedwinrt
parameter.Changed in version 0.18: No longer is alias for backend type and no longer inherits from
BaseBleakClient
. Addedbackend
parameter.Changed in version unreleased: Added
pair
parameter.
Connecting and disconnecting
Before doing anything else with a BleakClient
object, it must be connected.
bleak.BleakClient
is a an async context manager, so the recommended
way of connecting is to use it as such:
import asyncio
from bleak import BleakClient
async def main():
async with BleakClient("XX:XX:XX:XX:XX:XX") as client:
# Read a characteristic, etc.
...
# Device will disconnect when block exits.
...
# Using asyncio.run() is important to ensure that device disconnects on
# KeyboardInterrupt or other unhandled exception.
asyncio.run(main())
It is also possible to connect and disconnect without a context manager, however this can leave the device still connected when the program exits:
- async BleakClient.connect(**kwargs: Any) None [source]
Connect to the specified GATT server.
- Parameters:
**kwargs – For backwards compatibility - should not be used.
Changed in version unreleased: No longer returns
True
. Instead, the return type isNone
.
- async BleakClient.disconnect() None [source]
Disconnect from the specified GATT server.
Changed in version unreleased: No longer returns
True
. Instead, the return type isNone
.
The current connection status can be retrieved with:
- property BleakClient.is_connected: bool
Check connection status between this client and the GATT server.
- Returns:
Boolean representing connection status.
A callback can be provided to the BleakClient
constructor via the
disconnect_callback
argument to be notified of disconnection events.
Device information
- property BleakClient.address: str
Gets the Bluetooth address of this device (UUID on macOS).
- property BleakClient.mtu_size: int
Gets the negotiated MTU size in bytes for the active connection.
Consider using
bleak.backends.characteristic.BleakGATTCharacteristic.max_write_without_response_size
instead.Warning
The BlueZ backend will always return 23 (the minimum MTU size). See the
mtu_size.py
example for a way to hack around this.
GATT Client Operations
All Bluetooth Low Energy devices use a common Generic Attribute Profile (GATT) for interacting with the device after it is connected. Some GATT operations like discovering the services/characteristic/descriptors and negotiating the MTU are handled automatically by Bleak and/or the OS Bluetooth stack.
The primary operations for the Bleak client are reading, writing and subscribing to characteristics.
Services
The available services on a device are automatically enumerated when connecting to a device. Services describe the devices capabilities.
- property BleakClient.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.
GATT characteristics
Most I/O with a device is done via the characteristics.
- async BleakClient.read_gatt_char(char_specifier: BleakGATTCharacteristic | int | str | UUID, **kwargs: Any) 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.
- Raises:
BleakGattCharacteristicNotFoundError – if a characteristic with the handle or UUID specified by
char_specifier
could not be found.backend-specific exceptions – if the read operation failed.
- async BleakClient.write_gatt_char(char_specifier: BleakGATTCharacteristic | int | str | UUID, data: Buffer, response: bool | None = 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.
- Parameters:
char_specifier – The characteristic to write to, specified by either integer handle, UUID or directly by the
BleakGATTCharacteristic
object 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. Omitting the argument is deprecated and may raise a warning. If this arg is omitted, the default behavior is to check the characteristic properties to see if the “write” property is present. If it is, a write-with-response operation will be used. Note: some devices may incorrectly report or omit the property, which is why an explicit argument is encouraged.
- Raises:
BleakGattCharacteristicNotFoundError – if a characteristic with the handle or UUID specified by
char_specifier
could not be found.backend-specific exceptions – if the write operation failed.
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"\x00\x01\x02\x03", response=True)
- async BleakClient.start_notify(char_specifier: BleakGATTCharacteristic | int | str | UUID, callback: Callable[[BleakGATTCharacteristic, bytearray], None | Awaitable[None]], *, cb: CBStartNotifyArgs = {}, **kwargs: Any) 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
bytearray
containing 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.
cb – CoreBluetooth specific arguments.
- Raises:
BleakGattCharacteristicNotFoundError – if a characteristic with the handle or UUID specified by
char_specifier
could not be found.backend-specific exceptions – if the start notification operation failed.
Changed in version 0.18: The first argument of the callback is now a
BleakGATTCharacteristic
instead of anint
.Changed in version unreleased: Added the
cb
parameter.
- async BleakClient.stop_notify(char_specifier: 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.
- Raises:
BleakGattCharacteristicNotFoundError – if a characteristic with the handle or UUID specified by
char_specifier
could not be found.backend-specific exceptions – if the stop notification operation failed.
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.
GATT descriptors
Descriptors can provide additional information about a characteristic.
- async BleakClient.read_gatt_descriptor(desc_specifier: BleakGATTDescriptor | int, **kwargs: Any) bytearray [source]
Perform read operation on the specified GATT descriptor.
- Parameters:
desc_specifier – The descriptor to read from, specified by either integer handle or directly by the BleakGATTDescriptor object representing it.
- Raises:
BleakError – if the descriptor could not be found.
backend-specific exceptions – if the read operation failed.
- Returns:
The read data.
- async BleakClient.write_gatt_descriptor(desc_specifier: BleakGATTDescriptor | int, data: Buffer) None [source]
Perform a write operation on the specified GATT descriptor.
- Parameters:
desc_specifier – The descriptor to write to, specified by either integer handle directly by the BleakGATTDescriptor object representing it.
data – The data to send.
- Raises:
BleakError – if the descriptor could not be found.
backend-specific exceptions – if the read operation failed.
Pairing/bonding
On some devices, some characteristics may require authentication in order to read or write the characteristic. In this case pairing/bonding the device is required.
Tip
If you need to pair the device before connecting, pass pair=True
to the BleakClient
constructor. Then pairing will happen during
the connection process and you do not need to call the pair
method explicitly.
- async BleakClient.pair(*args: Any, **kwargs: Any) None [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.
Changed in version unreleased: No longer returns
True
. Instead, the return type isNone
.
- async BleakClient.unpair() None [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.
Changed in version unreleased: No longer returns
True
. Instead, the return type isNone
.