Search code examples
androidqtbluetoothbluezqtbluetooth

How to choose local adapter when connecting to service with QBluetoothSocket


In the presence of multiple Bluetooth adapters, is it possible to specify which local adapter to use when creating a QBluetoothSocket or calling QBluetoothSocket::connectToService()? I'm interested in Linux/BlueZ as well as Android (where it is not even clear whether multiple Bluetooth adapters are supported by the Bluetooth stack).


Solution

  • As of Qt 5.6.2, there is no such functionality yet apart from QBluetoothLocalDevice(QBluetoothAddress), QBluetoothDeviceDiscoveryAgent(QBluetoothAddress), QBluetoothServiceDiscoveryAgent(QBluetoothAddress) and QBluetoothServer::listen(QBluetoothAddress). These would only make sense on Linux and not on Android since the Android Bluetooth stack doesn't seem to support multiple dongles, at least yet.

    However, on Linux with BlueZ, the following is possible to choose the local adapter using the BlueZ c API:

    #include <sys/socket.h>
    #include <bluetooth/bluetooth.h>
    #include <bluetooth/rfcomm.h>
    
    ...
    
    QBluetoothSocket* socket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol);
    
    struct sockaddr_rc loc_addr;
    loc_addr.rc_family = AF_BLUETOOTH;
    
    int socketDescriptor = ::socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    if(socketDescriptor < 0){
        qCritical() << strerror(errno);
        return;
    }
    
    const char* localMacAddr = "XX:XX:XX:XX:XX:XX"; //MAC address of the local adapter
    str2ba(localMacAddr, &(loc_addr.rc_bdaddr));
    
    if(bind(socketDescriptor, (struct sockaddr*)&loc_addr, sizeof(loc_addr)) < 0){
        qCritical() << strerror(errno);
        return;
    }
    
    if(!socket->setSocketDescriptor(socketDescriptor, QBluetoothServiceInfo::RfcommProtocol, QBluetoothSocket::UnconnectedState)){
        qCritical() << "Couldn't set socketDescriptor";
        return;
    }
    
    socket->connectToService(...);
    

    The project .pro must contain the following:

    CONFIG += link_pkgconfig
    PKGCONFIG += bluez
    

    The corresponding feature request to possibly integrate this into the Qt APIs: https://bugreports.qt.io/browse/QTBUG-57382