Search code examples
bluetoothembedded-linuxbluetooth-lowenergybluezgatt

How to get Disconnect Event from GATT Server on Bluez/Linux


Environment: Bluez 5.14, Linux 3.1, USB Plugable BLE radio, TI BLE keyfob (CC2541 dev kit) Linux Device <---hci----> USB BLE Radio

We enabled key press events on TI keyfob using gatttool and started to listen for events

gatttool -b [hardware ID] --char-write-req -a [handle] -n [value] --listen 
(gatttool -b 90:59:AF:09:E1:5D --char-write-req -a 0x0048 -n 0100 --listen)

Pressing buttons on the keyfob and see these events

Notification handle = 0x0047 value: 02 
Notification handle = 0x0047 value: 00 
Notification handle = 0x0047 value: 02

Hence we can receive the key press events from the Keyfob through the Bluez stack

Objective:

We need to catch the GATT Disconnect Event i.e. When we remove the battery from the keyfob sooner or later the GATT connection is broken. We would like to receive a disconnect event from Bluez stack. Bluez has this capability since Android supports GATT disconnect event which is built over Bluez.

Question:

How do we receive the GATT Disconnect event using Bluez command line hcitool/gatttool or Bluez API.


Solution

  • Watch for G_IO_HUP and shutdown gracefully.

    chan = gatt_connect(opt_src, opt_dst, opt_dst_type, opt_sec_level,
                    opt_psm, opt_mtu, connect_cb, &gerr);
    if (chan == NULL) {
        log_printf(LOG_LEVEL_ERROR,"%s: chan is NULL\n",__func__);
        log_printf(LOG_LEVEL_ERROR,"%s\n", gerr->message);
        g_error_free(gerr);
        g_main_loop_quit(event_loop);
    } else {
        log_printf(LOG_LEVEL_INFO,"Connected to %s\n",opt_dst);
        g_io_add_watch(chan, G_IO_HUP, channel_watcher, NULL);
    }