ble_beginner
ble_beginner

Reputation: 1

Bluetooth Low Energy on Linux: Implement a GATT-Client

I´m new in Bluetooth Low Energy and I´m trying to build my own C-Program on Linux which connects and interacts with an Bluetooth Low Energy Device. For that I'm using the Linux Bluetooth Protocol Stack Bluez.

After reading this blog (https://www.jaredwolff.com/blog/get-started-with-bluetooth-low-energy/) it´s possible for me to connect and communicate with my Device over Command-Line. But now I stuck in doing this with my Code. I looked at the Gatttool Sourcefiles but it´s hard for me to understand..

I tried to connect to the device with gatt_conncect(const char *src, const char *dst, const char *dst_type, const char *sec_level, int psm, int mtu, BtIOConnect connect_cb, GError **gerr), but I think something is wrong with the Arguments which I pass to the function.

char dst[] = "XX:XX:XX:XX:XX:XX"; //device address
char dst_type = BDADDR_LE_RANDOM;
char sec_level = BT_IO_SEC_LOW;
GError *gerr;
BtIOConnect connect_cb; //Compiler says it´s uninitialized, but I don´t in what way I have how to initialize it 
GIOhannel *chan;

chan = gatt_connect(NULL, dst, &dst_type, &sec_level, 0, 0, connect_cb, &gerr); 

The function crashes. I think something is wrong with connect_cb functionpointer. But after looking in the Gattool Sourcecode I don´t how to fix it.

Upvotes: 0

Views: 2374

Answers (1)

Prabhakar Lad
Prabhakar Lad

Reputation: 1438

Definition for gatt_connect is :

GIOChannel *gatt_connect(const char *src, const char *dst,
            const char *dst_type, const char *sec_level,
            int psm, int mtu, BtIOConnect connect_cb,
            GError **gerr);

connect_cb is callback function (typedef void (*BtIOConnect)(GIOChannel *io, GError *err, gpointer user_data);) which will be called when connected. since you have garbage callback probably that’s the reason its crashing!

following is my callback function which I am using:

static void connect_cb(GIOChannel *io, GError *err, gpointer user_data)
{
    VVBOX_BLE_DEV_t *pdev = (VVBOX_BLE_DEV_t *)user_data;
    uint16_t mtu;
    uint16_t cid;

    if (err) {
        if (reply_to_listner) {
            mq_send_probe_ble_rsp(listener_id, 0, 5, "");
            reply_to_listner = 0;
        }
        printf("%s failed %s",__FUNCTION__, err->message);
        return;
    }

    bt_io_get(io, &err, BT_IO_OPT_IMTU, &mtu,
                BT_IO_OPT_CID, &cid, BT_IO_OPT_INVALID);

    if (err) {
        printf("%s Can't detect MTU, using default: %s", __FUNCTION__, err->message);
        g_error_free(err);
        mtu = ATT_DEFAULT_LE_MTU;
    }

    if (cid == ATT_CID)
        mtu = ATT_DEFAULT_LE_MTU;

    pdev->attrib = g_attrib_new(pdev->iochannel, mtu, false);
    printf("Connection successful\n");

    gatt_discover_primary(pdev->attrib, NULL, primary_all_cb, user_data);
    return;
}

Upvotes: 0

Related Questions