BleakClient class

class bleak.BleakClient(address_or_ble_device: Union[BLEDevice, str], disconnected_callback: Optional[Callable[[BleakClient], None]] = None, *, timeout: float = 10.0, winrt: WinRTClientArgs = {}, backend: Optional[Type[BaseBleakClient]] = None, **kwargs)[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 a BleakScanner 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.

  • timeout – Timeout in seconds passed to the implicit discover call when address_or_ble_device is not a BLEDevice. 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 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 the address_or_ble_device argument.

  1. 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.

  2. Providing an address or UUID instead of a BLEDevice causes the connect() method to implicitly call BleakScanner.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_callback is no longer keyword-only. Added winrt parameter.

Changed in version 0.18.0: No longer is alias for backend type and no longer inherits from BaseBleakClient. Added backend 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) bool[source]

Connect to the specified GATT server.

Parameters

**kwargs – For backwards compatibility - should not be used.

Returns

Always returns True for backwards compatibility.

async BleakClient.disconnect() bool[source]

Disconnect from the specified GATT server.

Returns

Always returns True for backwards compatibility.

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: 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 BleakClient.write_gatt_char(char_specifier: Union[BleakGATTCharacteristic, int, str, UUID], data: Union[bytes, bytearray, memoryview], response: bool = False) None[source]

Perform a write operation on the specified GATT characteristic.

Parameters
  • char_specifier – The characteristic to write to, specified by either integer handle, UUID or directly by the BleakGATTCharacteristic object representing it.

  • data – The data to send.

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

async BleakClient.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 bytearray containing the data received.

def callback(sender: int, 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 BleakGATTCharacteristic instead of an int.

async BleakClient.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.

GATT descriptors

Descriptors can provide additional information about a characteristic.

async BleakClient.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.

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

Perform a write operation on the specified GATT descriptor.

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

  • data – The data to send.

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.

async BleakClient.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 True for backwards compatibility.

async BleakClient.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 True for backwards compatibility.

Deprecated

BleakClient.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 BleakClient constructor instead.

Parameters

callback – callback to be called on disconnection.

async BleakClient.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 services property instead.

Returns

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