Bleak
Connects to Bluetooth Low Energy devices as an asynchronous GATT client.
- Downloads / mo
- 2.4M
- Stars
- 2.6K
- Last release
- 3.1.0
- License
- MIT
Strengths
- Cleans up managed connections. An async context manager connects and disconnects the client.
- Reads and subscribes to characteristics. Read values, write values, or receive GATT notifications.
Limitations
- Classic RFCOMM needs another library. Bleak handles BLE GATT rather than classic RFCOMM sockets.
- Address-based connections trigger discovery. Pass a discovered BLEDevice when connecting to multiple devices.
Quickstart
import asyncio from bleak import BleakScanner async def main(): print(await BleakScanner.discover()) asyncio.run(main())
Bleak examples
async def _async_see_update_ble_battery( mac: str, now: datetime, service_info: bluetooth.BluetoothServiceInfoBleak, ) -> None: """Lookup Bluetooth LE devices and update status.""" battery = None # We need one we can connect to since the tracker will # accept devices from non-connectable sources if service_info.connectable: device = service_info.device elif connectable_device := bluetooth.async_ble_device_from_address( hass, service_info.device.address, True ): device = connectable_device else: # The device can be seen by a passive tracker but we # don't have a route to make a connection return try: async with BleakClient(device) as client: bat_char = await client.read_gatt_char(BATTERY_CHARACTERISTIC_UUID) battery = ord(bat_char) except TimeoutError: _LOGGER.debug( "Timeout when trying to get battery status for %s", service_info.name ) # Bleak currently has a few places where checking dbus attributes # can raise when there is another error. We need to trap AttributeError # until bleak releases v0.15+ which resolves these. except (AttributeError, BleakError) as err: _LOGGER.debug("Could not read battery status: %s", err) # If the device does not offer battery information, # there is no point in asking again later on. # Remove the device from the battery-tracked # devices, so that their battery is not wasted # trying to get an unavailable information. del devs_track_battery[mac] if battery: await async_see_device(mac, service_info.name, battery=battery)