Bleak
Bleak (Bluetooth Low Energy platform Agnostic Klient)1 is a Bluetooth Low Energy (BLE) library for Python. It is a cross-platform library that supports Windows, Linux, and macOS. It is built on top of the asyncio
Python library.
It can be found on GitHub here.
Installation
Install Bleak with pip:
It’s recommended to install Bleak in a virtual environment (create one with python -m venv .venv
, and then activate it).
Basic Usage
Bleak uses asyncio, so you need to run it in an asyncio event loop.
To scan for devices, you can use the following code:
When I ran this at home, I got the following output:
Here is a simple example that connects to BLE device and reads the model number, based of it’s MAC address:
A context manager is used (the with
above), which removes the need to manually disconnect from the device (it will automatically disconnect when the context manager exits).
As part of the connection process, Bleak will scan for BLE devices until it finds one that matches the MAC address.
Bleak will raise a BleakDeviceNotFoundError
exception if it cannot find the device.
To get debug information from Bleak, you can import logging
and set the logging level to DEBUG
:
Backends
On Windows, Bleak uses the winrt
(Windows Runtime) backend. On Linux, it communicates with BlueZ via DBus. On macOS, it interfaces with the CoreBluetooth API2.
Footnotes
-
GitHub. Bleak repository. Retrieved 2024-09-15, from https://github.com/hbldh/bleak. ↩ ↩2
-
Bleak. _Backend implementations [docs]. Retrieved 2024-09-15, from https://bleak.readthedocs.io/en/latest/backends/index.html. ↩