How to choose local adapter when connecting to service with QBluetoothSocket

 ̄綄美尐妖づ 提交于 2019-12-12 04:29:29

问题


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).


回答1:


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



来源:https://stackoverflow.com/questions/40762145/how-to-choose-local-adapter-when-connecting-to-service-with-qbluetoothsocket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!