labapart / gattlib

Library to access GATT information from BLE (Bluetooth Low Energy) devices
http://labapart.com/
436 stars 157 forks source link

BLE-scan failes to connect? #208

Open Thanh-Binh opened 3 years ago

Thanh-Binh commented 3 years ago

I have just test ble_scan, it can discovers my devices, but can not connect to it and provides errors. Could you please explain me why? Thanks

Discovered 98:D3:71:F5:F8:91 - 'H-C-2010-06-01' ------------START 98:D3:71:F5:F8:91 --------------- Device '98:D3:71:F5:F8:91' cannot be found Fail to connect to the bluetooth device. ------------DONE 98:D3:71:F5:F8:91 ---------------

makosolo commented 3 years ago

static int l2cap_connect(int sock, const bdaddr_t *dst, uint8_t dst_type, uint16_t psm, uint16_t cid, uint16_t timeout) { int err; struct sockaddr_l2 addr;

if (timeout > 0) {
    struct timeval timeval;
    timeval.tv_sec = timeout;
    timeval.tv_usec = 0;

    if (setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeval, sizeof(timeval)) < 0) {
        fprintf(stderr, "l2cap_connect: Failed to setsockopt for receive timeout.\n");
        return -1;
    }

    if (setsockopt (sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeval, sizeof(timeval)) < 0) {
        fprintf(stderr, "l2cap_connect: Failed to setsockopt for sending timeout.\n");
        return -1;
    }
}

memset(&addr, 0, sizeof(addr));
addr.l2_family = AF_BLUETOOTH;
bacpy(&addr.l2_bdaddr, dst);
if (cid)
    addr.l2_cid = htobs(cid);
else
    addr.l2_psm = htobs(psm);

addr.l2_bdaddr_type = dst_type;

err = connect(sock, (struct sockaddr *) &addr, sizeof(addr));
if (err < 0 && !(errno == EAGAIN || errno == EINPROGRESS))
    return -errno;

return 0;

}

You should check the result of the above 'setsockopt‘'.Most of the errors I encounter are caused by timeouts,Modifying the value of 'CONNECTION_TIMEOUT' helps to improve, but I think this should be right interface input.

Thanh-Binh commented 3 years ago

Yes I found its definition in a c-file, and it it fixed Can user set their timeout individually? Thanks

makosolo commented 3 years ago

No, there are two concepts here: one is the timeout at the end of the scan, and the other is the timeout when the scan has no equipment or fails. Here you need to modify the source code appropriately.