# Me and the Devil BlueZ: Implementing a BLE Central in Linux - Part 1

In my last article, I covered the basic Bluetooth Low Energy concepts required to implement a BLE peripheral in an MCU board. We used a Raspberry Pi Pico board and MicroPython for our implementation. We ended up with a prototype firmware that used the on-board LED, read from the on-board temperature sensor, and implemented a BLE peripheral with two services and several characteristics – one that depended on measured data and could push notifications to its client.

In this article, we will be focusing on the other side of the BLE communication: the BLE central, rather than the BLE peripheral. Our collecting station is going to gather the data from the sensors and it is a Raspberry Pi 3A+ with a Linux distribution, namely, Raspberry Pi OS wormbook which is a Debian derivative commonly used in this platform.
, replacing the previously available OpenBT.

Initially, all the tools were command-line based and the libraries used raw sockets to access the Host Controller Interface offered by hardware. But since the early beginning of its adoption, there was interest to integrate it into the different desktop alternatives, mainly Gnome and KDE. Sharing the Bluetooth interface across the different desktop applications required a different approach: a daemon that took care of all the Bluetooth tasks that take place outside of the Linux Kernel, and an interface that would allow sharing access to that daemon. D-Bus had been designed as a common initiative for interoperability among free-software desktop environments, managed by FreeDesktop, and had already been adopted by the major Linux desktops, so it became the preferred option for that interface.

### D-Bus

D-Bus, short for desktop bus, is an interprocess communication mechanism that uses a message bus. The bus is responsible for taking the messages sent by any process connected to it and delivering them to other processes in the same bus.
 and `hcitool` were the blessed tools to work with Bluetooth, but they used raw sockets and were deprecated around 2017. Nowadays, the recommended tools are `bluetoothctl` and `btmgmt`, although I believe that the old tools have been changed under their skin and are available without using raw sockets.

Enabling the Bluetooth radio was usually done with `sudo hciconfig hci0 up`. Nowadays, we can use `bluetoothctl` instead:

```sh
bluetoothctl
bluetooth]# show
Controller XX:XX:XX:XX:XX:XX (public)
        Name: ...
        Alias: ...
        Powered: no
        ...
[bluetooth]# power on
Changing power on succeeded
[CHG] Controller XX:XX:XX:XX:XX:XX Powered: yes
[bluetooth]# show
Controller XX:XX:XX:XX:XX:XX (public)
        Name: ...
        Alias: ...
        Powered: yes
        ...
```

With the radio on, we can start scanning for BLE devices:

```sh
bluetoothctl
[bluetooth]# menu scan
[bluetooth]# transport le
[bluetooth]# back
[bluetooth]# scan on
[bluetooth]# devices
```

This shows several devices and my RP2 here:

> Device XX:XX:XX:XX:XX:XX RP2-SENSOR

Now that we know the MAC address/name pairs, we can use the former piece of data to connect to it:

```sh
  [bluetooth]# connect XX:XX:XX:XX:XX:XX
  Attempting to connect to XX:XX:XX:XX:XX:XX
  Connection successful
  [NEW] Primary Service (Handle 0x2224)
        /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0004
        00001801-0000-1000-8000-00805f9b34fb
        Generic Attribute Profile
[NEW] Characteristic (Handle 0x7558)
        /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0004/char0005
        00002a05-0000-1000-8000-00805f9b34fb
        Service Changed
[NEW] Primary Service (Handle 0x78c4)
        /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0007
        0000180a-0000-1000-8000-00805f9b34fb
        Device Information
[NEW] Characteristic (Handle 0x7558)
        /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0007/char0008
        00002a29-0000-1000-8000-00805f9b34fb
        Manufacturer Name String
[NEW] Characteristic (Handle 0x7558)
        /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0007/char000a
        00002a24-0000-1000-8000-00805f9b34fb
        Model Number String
[NEW] Characteristic (Handle 0x7558)
        /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0007/char000c
        00002a25-0000-1000-8000-00805f9b34fb
        Serial Number String
[NEW] Characteristic (Handle 0x7558)
        /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0007/char000e
        00002a26-0000-1000-8000-00805f9b34fb
        Firmware Revision String
[NEW] Characteristic (Handle 0x7558)
        /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0007/char0010
        00002a27-0000-1000-8000-00805f9b34fb
        Hardware Revision String
[NEW] Primary Service (Handle 0xb324)
        /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0012
        0000181a-0000-1000-8000-00805f9b34fb
        Environmental Sensing
[NEW] Characteristic (Handle 0x7558)
        /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0012/char0013
        00002a1c-0000-1000-8000-00805f9b34fb
        Temperature Measurement
[NEW] Descriptor (Handle 0x75a0)
        /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0012/char0013/desc0015
        00002902-0000-1000-8000-00805f9b34fb
        Client Characteristic Configuration
[NEW] Descriptor (Handle 0x75a0)
        /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0012/char0013/desc0016
        0000290d-0000-1000-8000-00805f9b34fb
        Environmental Sensing Trigger Setting
[RP2-SENSOR]# scan off
```

Now we can use the General Attribute Profile (GATT) to send commands to the device, including listing the attributes, reading a characteristic, and receiving notifications.

```sh
[RP2-SENSOR]# menu gatt
[RP2-SENSOR]# list-attributes
...
Characteristic (Handle 0x0001)
    /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0012/char0013
    00002a1c-0000-1000-8000-00805f9b34fb
    Temperature Measurement
...
[RP2-SENSOR]# select-attribute /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0012/char0013
[MPY BTSTACK:/service0012/char0013]# read
Attempting to read /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0012/char0013
[CHG] Attribute /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0012/char0013 Value:
  00 0c 10 00 fe                                   .....
  00 0c 10 00 fe                                   .....
[MPY BTSTACK:/service0012/char0013]# notify on
[CHG] Attribute /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0012/char0013 Notifying: yes
Notify started
[CHG] Attribute /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0012/char0013 Value:
  00 3b 10 00 fe                                   .;...
[CHG] Attribute /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0012/char0013 Value:
  00 6a 10 00 fe                                   .j...
[MPY BTSTACK:/service0012/char0013]# notify off
```

And we leave it in its original state:

```sh
[MPY BTSTACK:/service0012/char0013]# back
[MPY BTSTACK:/service0012/char0013]# disconnect
Attempting to disconnect from 28:CD:C1:0F:4B:AE
[CHG] Device 28:CD:C1:0F:4B:AE ServicesResolved: no
Successful disconnected
[CHG] Device 28:CD:C1:0F:4B:AE Connected: no
[bluetooth]# power off
Changing power off succeeded
[CHG] Controller B8:27:EB:4D:70:A6 Powered: no
[CHG] Controller B8:27:EB:4D:70:A6 Discovering: no
[bluetooth]# exit
```

### Query the services in the system bus

`dbus-send` comes with D-Bus.

We are going to send a message to the system bus. The message is addressed to "org.freedesktop.DBus" which is the service implemented by D-Bus itself. We use the single D-Bus instance, "/org/freedesktop/DBus". And we use the "Introspect" method of the "org.freedesktop.DBus.Introspectable". Hence, it is a method call. Finally, it is important to highlight that we must request that the reply gets printed, with "–print-reply" if we want to be able to watch it.

```sh
dbus-send --system --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.Introspectable.Introspect | less
```

This method call has a long reply, but let me highlight some interesting parts. Right after the header, we get the description of the interface "org.freedesktop.DBus":

```xml

  
    
      
    
    
    ...
    
    
    ...
```

These are the methods, properties and signals related to handling connections to the bus and information about it. Methods may have parameters (args with direction "in") and results (args with direction "out") and both define the type of the expected data. Signals also declare the arguments, but they are broadcasted and no response is expected, so there is no need to use "direction."

Then we have an interface to expose the D-Bus properties:

```xml

...
```

And a description of the "org.freedesktop.DBus.Introspectable" interface that we have already used to obtain all the interfaces. Inception? Maybe.

```xml

  
    
  

```

Finally, we find three other interfaces:

```xml
  
     ...
  
  
    ...
  
  
    ...
  

```

Let's use the method of the first interface that tells us what is connected to the bus. In my case, I get:

```sh
dbus-send --system --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.ListNames
method return time=1698320750.822056 sender=org.freedesktop.DBus -> destination=:1.50 serial=3 reply_serial=2
   array [
      string "org.freedesktop.DBus"
      string ":1.7"
      string "org.freedesktop.login1"
      string "org.freedesktop.timesync1"
      string ":1.50"
      string "org.freedesktop.systemd1"
      string "org.freedesktop.Avahi"
      string "org.freedesktop.PolicyKit1"
      string ":1.43"
      string "org.bluez"
      string "org.freedesktop.ModemManager1"
      string ":1.0"
      string ":1.1"
      string ":1.2"
      string ":1.3"
      string ":1.4"
      string "fi.w1.wpa_supplicant1"
      string ":1.5"
      string ":1.6"
   ]
```

The "org.bluez" is the service that we want to use. We can use introspect with it:

```xml
dbus-send --system --print-reply=literal --dest=org.bluez /org/bluez org.freedesktop.DBus.Introspectable.Introspect |
xmllint --format - | less
```

> xmllint can be installed with `sudo apt-get install libxml2-utils`.

After the header, I get the following interfaces:

```xml

  
    
      
    
  
  
    
      
      
    
    
      
    
    
      
    
  
  
    
      
      
      
    
    
      
    
  
  
    
      
      
    
    
      
    
  
  

```

Have you noticed the node that represents the child object for the HCI0? We could also have learned about it using `busctl tree org.bluez`. And we can query that child object too. We will now obtain the information about HCI0 using introspection but send the message to BlueZ and refer to the HCI0 instance.

```sh
dbus-send --system --print-reply=literal --dest=org.bluez /org/bluez/hci0 org.freedesktop.DBus.Introspectable.Introspect | xmllint --format - | less
```

```xml

  
    
      
    
  
  
    
    
      
    
    
    
      
    
    
      
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  
  
    
      
      
      
    
    
      
      
      
    
    
      
      
    
    
      
      
      
    
  
  
    
      
      
    
    
      
    
  
  
    
      
      
    
    
      
    
    
    
    
    
  
  
    
      
      
    
    
      
    
    
      
      
    
    
      
    
    
      
      
    
    
      
    
  
  
    
      
      
    
    
      
    
  

```

Let's check the status of the Bluetooth radio using D-Bus messages to query the corresponding property:

```sh
dbus-send --system --type=method_call --print-reply --dest=org.bluez /org/bluez/hci0 org.freedesktop.DBus.Properties.Get string:org.bluez.Adapter1 string:Powered
```

We can then switch the radio on, setting the same property:

```sh
dbus-send --system --type=method_call --print-reply --dest=org.bluez /org/bluez/hci0 org.freedesktop.DBus.Properties.Set string:org.bluez.Adapter1 string:Powered variant:boolean:true
```

And check the status of the radio again to verify the change:

```sh
dbus-send --system --type=method_call --print-reply --dest=org.bluez /org/bluez/hci0 org.freedesktop.DBus.Properties.Get string:org.bluez.Adapter1 string:Powered
```

The next step is to start scanning, and it seems that we should use this command:

```sh
dbus-send --system --type=method_call --print-reply --dest=org.bluez /org/bluez/hci0 org.bluez.Adapter1.StartDiscovery
```

But this doesn't work because `dbus-send` exits almost immediately and BlueZ keeps track of the D-Bus clients that request the discovery.

### Capture the messages produced by `bluetoothctl`

Instead, we are going to use the command line utility `bluetoothctl` and monitor the messages that go through the system bus.

We start `dbus-monitor` for the system bus and redirect the output to a file. We launch `bluetoothctl` and inspect the log. This connects to the D-Bus with a "Hello" method. It invokes AddMatch to show interest in BlueZ. It does `GetManagedObjects` to find the objects that are managed by BlueZ.

We then select Low Energy (`menu scan`, `transport le`, `back`). This doesn't produce messages because it just configures the tool.

We start scanning (`scan on`), connect to the device (`connect XX:XX:XX:XX:XX:XX`), and stop scanning (`scan off`). In the log, the second message is a method call to start scanning (`StartDiscovery`), preceded by a call (to `SetDiscoveryFilter`) with LE as a parameter. Then, we find signals –one per device that is discoverable– with all the metadata of the device, including its MAC address, its name (if available), and the transmission power that is normally used to estimate how close a device is, among other properties. The app shows its interest in the devices it has found with an `AddMatch` method call, and we can see signals with properties updates.

Then, a call to the method `Connect` of the `org.bluez.Device1` interface is invoked with the path pointing to the desired device. Finally, when we stop scanning, we can find an immediate call to `StopDiscovery`, and the app declares that it is no longer interested in updates of the previously discovered devices with calls to the `RemoveMatch` method. A little later, an announcement signal tells us that the "connected" property of that device has changed, and then there's a signal letting us know that `InterfacesAdded` implemented `org.bluez.GattService1`, `org.bluez.GattCharacteristic1` for each of the services and characteristics. We get a signal with a "ServicesResolved" property stating that the present services are Generic Access Service, Generic Attribute Service, Device Information Service, and Environmental Sensing Service (0x1800, 0x1801, 0x180A, and 0x181A). In the process, the app uses `AddMatch` to show interest in the different services and characteristics.

We select the attribute for the temperature characteristic (`select-attribute /org/bluez/hci0/dev_28_CD_C1_0F_4B_AE/service0012/char0013`), which doesn't produce any D-Bus messages. Then, we `read` the characteristic that generates a method call to `ReadValue` of the `org.bluez.GattCharacteristic1` interface with the path that we have previously selected. Right after, we receive a method return message with the five bytes of that characteristic.

As for notifications, when we enable them (`notify on`), a method call to `StartNotify` is issued with the same parameters as the `ReadValue` one. The notification comes as a `PropertiesChanged` signal that contains the new value and then we send the `StopNotify` command. Both changes to the notification state produce signals that share the new state.

## Recap and future content

In this article, I have explained all the steps required to interact with the BLE peripheral from the command line. Then, I did some reverse engineering to understand how those steps translated into D-Bus messages. Find the [resources for this article and links to others.

In the next article, I will try to use the information that we have gathered about the D-Bus messages to interact with the Bluetooth stack using C++.

If you have questions or feedback, join me in the MongoDB Developer Community!

  [1]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/bltb57cbfa9d1521fb5/657704f0529e1390f6b953bc/Debian.jpg
  [2]: https://images.contentstack.io/v3/assets/blt39790b633ee0d5a7/blt177196690c5045e5/65770264529e137250b953a8/Bus.jpg