Introduction to Bluetooth

Connecting to, and Reading Data from Bluetooth Devices using Python and Bleak

Updated: 03 September 2023

Overview

Bluetooth Low Energy (BLE) devices make use of a few different concepts for reading and writing data. At a high level, bluetooth data is organized as follows:

GATT Data hierarchy

Each characteristic contains the following attributes:

  • Properties - specify the operations allowed on a characteristic, e.g. read, write
  • UUID - A unique ID for this characteristic, this can be a 16-bit, approved UUID from this list or a custom 128 bit as specified by the device manufacturer
  • Value - The actual value contained in a characteristic. How this value is interpreted is based on the UUID and is either a standard value or a custom manufacturer-specific value

Reading Bluetooth Data

I’m going to be using Bleak with Python to read Bluetooth data and characteristics. Although it’s also possible to use the nrf Connect app or another bluetooth debugging tool to do much of the same kind of stuff I’m doing here

Install Bleak

In order to connect to bluetooth devices I’m using a library called Bleak. To install Bleak you can use the following command:

Terminal window
1
pip3 install bleak

Scan for Devices

To scan for devices we can use the BleakScanner.discover method:

discover.py

1
import asyncio
2
from bleak import BleakScanner
3
4
async def main():
5
async with BleakScanner() as scanner:
6
devices = await scanner.discover()
7
for d in devices:
8
print(d)
9
10
if __name__ == "__main__":
11
asyncio.run(main())

This will print all devices that were found during the discover call in the form of:

1
Device Address: Device Name

An example can be seen below:

1
24:71:89:CC:09:05: Device Name

List Services and Characteristics

To list the services of a device we can make use of the BleakClient class. To do this we need a client address as we saw above:

get_device_info.py

1
import asyncio
2
import sys
3
from bleak import BleakClient
4
5
async def main(address):
6
async with BleakClient(address) as client:
7
if (not client.is_connected):
8
raise "client not connected"
9
10
services = await client.get_services()
11
12
for service in services:
13
print('service', service.handle, service.uuid, service.description)
14
15
16
if __name__ == "__main__":
17
address = sys.argv[1]
18
print('address:', address)
19
asyncio.run(main(address))

We can expand on the above to list the characteristics and descriptors of each service as well:

get_device_info.py

1
import asyncio
2
import sys
3
from bleak import BleakClient
4
5
async def main(address):
6
async with BleakClient(address) as client:
7
if (not client.is_connected):
8
raise "client not connected"
9
10
services = await client.get_services()
11
12
for service in services:
13
print('\nservice', service.handle, service.uuid, service.description)
14
15
characteristics = service.characteristics
16
17
for char in characteristics:
18
print(' characteristic', char.handle, char.uuid, char.description, char.properties)
19
20
descriptors = char.descriptors
21
22
for desc in descriptors:
23
print(' descriptor', desc)
24
25
if __name__ == "__main__":
26
address = sys.argv[1]
27
print('address:', address)
28
asyncio.run(main(address))

Below you can see the results of reading from a sample server that I’ve configured which has a few characteristics with different permissions

1
service 1 00001801-0000-1000-8000-00805f9b34fb Generic Attribute Profile
2
characteristic 2 00002a05-0000-1000-8000-00805f9b34fb Service Changed ['indicate']
3
4
service 40 0000180d-0000-1000-8000-00805f9b34fb Heart Rate
5
characteristic 41 00002a37-0000-1000-8000-00805f9b34fb Heart Rate Measurement ['notify']
6
descriptor 00002902-0000-1000-8000-00805f9b34fb (Handle: 43): Client Characteristic Configuration
7
characteristic 44 00002a38-0000-1000-8000-00805f9b34fb Body Sensor Location ['read']
8
characteristic 46 00002a39-0000-1000-8000-00805f9b34fb Heart Rate Control Point ['write']
9
10
service 48 0000aaa0-0000-1000-8000-aabbccddeeff Unknown
11
characteristic 49 0000aaa1-0000-1000-8000-aabbccddeeff Unknown ['read', 'notify']
12
descriptor 00002902-0000-1000-8000-00805f9b34fb (Handle: 51): Client Characteristic Configuration
13
descriptor 0000aab0-0000-1000-8000-aabbccddeeff (Handle: 52): None
14
descriptor 00002901-0000-1000-8000-00805f9b34fb (Handle: 53): Characteristic User Description
15
descriptor 00002904-0000-1000-8000-00805f9b34fb (Handle: 54): Characteristic Presentation Format
16
characteristic 55 0000aaa2-0000-1000-8000-aabbccddeeff Unknown ['write-without-response', 'write', 'indicate']
17
descriptor 00002902-0000-1000-8000-00805f9b34fb (Handle: 57): Client Characteristic Configuration
18
19
service 58 0000181c-0000-1000-8000-00805f9b34fb User Data
20
characteristic 59 00002a8a-0000-1000-8000-00805f9b34fb First Name ['read', 'write']
21
characteristic 61 00002a90-0000-1000-8000-00805f9b34fb Last Name ['read', 'write']
22
characteristic 63 00002a8c-0000-1000-8000-00805f9b34fb Gender ['read', 'write']

Using the above, I can read some characteristics using their UUID like so:

1
import asyncio
2
import sys
3
from bleak import BleakClient
4
5
FIRST_NAME_ID = '00002a8a-0000-1000-8000-00805f9b34fb'
6
7
async def main(address):
8
async with BleakClient(address) as client:
9
if (not client.is_connected):
10
raise "client not connected"
11
12
services = await client.get_services()
13
14
name_bytes = await client.read_gatt_char(FIRST_NAME_ID)
15
name = bytearray.decode(name_bytes)
16
print('name', name)
17
18
if __name__ == "__main__":
19
address = sys.argv[1]
20
print('address:', address)
21
asyncio.run(main(address))

Depending on the data structure and type the requirements for decoding the data may be different.

Using the above idea, Bleak also gives us a way to listen to data that’s being sent from a client by way of the BleakClient.start_notify method which takes a characteristic to listen to and a callback which will receive a handle for the characteristic as well as the value

1
import asyncio
2
import sys
3
from bleak import BleakClient
4
5
HEART_RATE_ID = '00002a37-0000-1000-8000-00805f9b34fb'
6
7
def heart_rate_callback(handle, data):
8
print(handle, data)
9
10
async def main(address):
11
async with BleakClient(address) as client:
12
if (not client.is_connected):
13
raise "client not connected"
14
15
services = await client.get_services()
16
17
18
client.start_notify(heart_rate_char, heart_rate_callback)
19
await asyncio.sleep(60)
20
await client.stop_notify(heart_rate_char)

References

Overview

A good overview of how Bluetooth and how GATT (The Generic Attribute Profile) for a bluetooth device structures data can be found in Getting Started with Bluetooth Low Energy by Kevin Townsend, Carles Cufí, Akiba, Robert Davidson. A good overview of what we’ll be using can be found on Chapter 1 - Introduction and Chapter 4 - GATT (Services and Characteristics)

Library

A library I’ve found to be fairly simple for using to play around with Bluetooth is Bleak which is a multi-platform library for Python

I’ve had some issues using Bleak with Windows so I would recommend a Linux-based OS instead

Debugging Tool

A useful and easy to use tool for snooping around for bluetooth activity and exploring bluetooth data is the nrf Connect Android App

Reverse Engineering

An approach for reverse engineering the data structure for a simple bluetooth device can be found on BLE Reverse engineering — Mi Band 5

List of Bluetooth IDs

A database of bluetooth numbers can be found in the Bluetooth numbers database as well as the previously mentioned {Bluetooth specifications document}(https://btprodspecificationrefs.blob.core.windows.net/assigned-values/16-bit%20UUID%20Numbers%20Document.pdf)

Next Ideas

It may be worth looking into creating a Bluetooth Server. The library installed on Raspberry Pi is Bluez and it looks it supports creating a Bluetooth Server. The documentation for Bluez can be found here. Additionally, there’s also the Bluetooth for Linux developers which goes through creating a device that acts as a Bluetooth LE peripheral which could be useful in simulating a BLE device