[英]QtBluetooth Win10, how to check if bluetooth adapter is available and ON?
我在 Win10 下使用QtBluetooth
。 工作正常。
但是,由於我的應用程序部署在筆記本電腦(可能有也可能沒有 BT 適配器)和台式機(可能沒有適配器)上,我想以編程方式檢查適配器是否可用(存在並啟用)。
考慮到文檔,我測試了 4 個函數:
bool isBluetoothAvailable1()
{
return !QBluetoothLocalDevice::allDevices().empty();
}
bool isBluetoothAvailable2()
{
QBluetoothLocalDevice localDevice;
return localDevice.isValid();
}
bool isBluetoothAvailable3()
{
std::shared_ptr<QLowEnergyController> created( QLowEnergyController::createPeripheral() );
if ( created )
{
if ( !created->localAddress().isNull() )
return true;
}
return false;
}
bool isBluetoothAvailable4()
{
std::shared_ptr<QLowEnergyController> created( QLowEnergyController::createCentral( QBluetoothDeviceInfo() ) );
if ( created )
{
if ( !created->localAddress().isNull() )
return true;
}
return false;
}
但是當我在 Win10 筆記本電腦上運行我的代碼時,它們都返回 false! 即使我可以使用QBluetooth
API 搜索連接遠程設備。
了解 BLE 適配器是否可用的正確方法是什么?
正確的解決辦法是使用isBluetoothAvailable1()
因為調用allDevices()
列出所有已連接的藍牙適配器。 但是,這不適用於 Windows。
我不完全理解他們的推理,但 Qt 中有 2 個 Windows 實現此功能。
默認情況下,它使用始終返回空列表的列表( qbluetoothlocaldevice_win.cpp
)。
QList<QBluetoothHostInfo> QBluetoothLocalDevice::allDevices()
{
QList<QBluetoothHostInfo> localDevices;
return localDevices;
}
最簡單的解決方案是使用其他 Windows 實現中的代碼( qbluetoothlocaldevice_winrt.cpp
)
#include <Windows.h>
#include <BluetoothAPIs.h>
QList<QBluetoothHostInfo> allDevices()
{
BLUETOOTH_FIND_RADIO_PARAMS params;
::ZeroMemory(¶ms, sizeof(params));
params.dwSize = sizeof(params);
QList<QBluetoothHostInfo> foundAdapters;
HANDLE hRadio = nullptr;
if (const HBLUETOOTH_RADIO_FIND hSearch = ::BluetoothFindFirstRadio(¶ms, &hRadio)) {
for (;;) {
BLUETOOTH_RADIO_INFO radio;
::ZeroMemory(&radio, sizeof(radio));
radio.dwSize = sizeof(radio);
const DWORD retval = ::BluetoothGetRadioInfo(hRadio, &radio);
::CloseHandle(hRadio);
if (retval != ERROR_SUCCESS)
break;
QBluetoothHostInfo adapterInfo;
adapterInfo.setAddress(QBluetoothAddress(radio.address.ullLong));
adapterInfo.setName(QString::fromWCharArray(radio.szName));
foundAdapters << adapterInfo;
if (!::BluetoothFindNextRadio(hSearch, &hRadio))
break;
}
::BluetoothFindRadioClose(hSearch);
}
return foundAdapters;
}
您還需要鏈接必要的庫Bthprops
和ws2_32
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.