Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ BLE read/write example with Bluez

I am starting to build up a simple BLE network with a microcontroller and a raspberry pi (tardis BLE dongle). As a starting point, I am looking for a simple C or C++ example to read/write a BLE device, similar to what I am able to do over the command line. The examples I have found so far are quite complicated. As a BLE beginner I need some very simple examples to build from before moving forward with a more complicated design. I am okay with hard-coding the BLE device name as I have in the gatttool example below.

Here is how I currently use the command line options from Bluez.

From the command line I am able to use:

$ sudo hcitool lescan
LE Scan ...
BB:A0:50:02:18:07 MyDevice

Next I am able to connect to the device on the command line with gatttool:

$ sudo gatttol -b BB:A0:50:02:18:07 -I
[BB:A0:50:02:18:07][LE]> connect
Attempting to connect to BB:A0:50:02:18:07
Connection successful

Finally I am able to read and write using the appropriate handles

[BB:A0:50:02:18:07][LE]> char-write-req 000f 0100
Characteristic value was written successfully
[BB:A0:50:02:18:07][LE]> char-write-cmd 0011 4C467A

Some sites I have used for initial research and to get started:
http://people.csail.mit.edu/albert/bluez-intro/c404.html
https://github.com/carsonmcdonald/bluez-experiments/blob/master/experiments/scantest.c

like image 587
Cole Wilson Avatar asked May 22 '15 00:05

Cole Wilson


1 Answers

Bluez (Linux official Bluetooth stack) has moved to DBUS for its API. While in the past, it was 'accepted' to 'fork' bluez code to access BLE support on Linux, now the approach is to use DBUS. Bluez DBUS API is documented here: https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc

Either you directly speak to DBUS for your bluetooth C/C++ application or you use a GATT library as a helper. The second one is probably the best approach for beginner (and also for non-beginner who would prefer to keep their program Bluez agnostic for instance to support other OSes or Bluez pre-DBUS API or to have their sources more readable).

One of these GATT libraries that support modern D-BUS API is gattlib (note: I am the author of this library). Here is a simple example based on this library for reading/writing a BLE device: https://github.com/labapart/gattlib/blob/master/examples/read_write/read_write.c

like image 74
OlivierM Avatar answered Sep 28 '22 07:09

OlivierM