Windows平台如何扫描未配对BLE设备并获取hDevice句柄?
Windows平台未配对BLE设备扫描与hDevice句柄获取
一、扫描BLE设备(Win32环境)
方法1:使用WinRT BluetoothLEAdvertisementWatcher(Win32项目可调用)
初始化扫描器并捕获设备广播:
#include <winrt/Windows.Devices.Bluetooth.Advertisement.h> using namespace winrt::Windows::Devices::Bluetooth::Advertisement; // 初始化扫描器 BluetoothLEAdvertisementWatcher watcher; // 可选:设置过滤规则,比如指定目标服务UUID auto filter = watcher.AdvertisementFilter(); filter.Advertisement().ServiceUuids().Append(winrt::guid{L"目标服务UUID"}); watcher.AdvertisementFilter(filter); // 注册扫描回调,获取设备地址等信息 watcher.Received([&](auto const&, BluetoothLEAdvertisementReceivedEventArgs const& args) { uint64_t deviceAddr = args.BluetoothAddress(); winrt::hstring deviceName = args.Advertisement().LocalName(); // 后续可通过设备地址或名称关联设备实例 }); // 启动扫描 watcher.Start();
方法2:使用Win32 SetupAPI枚举BLE设备
通过设备类GUID枚举所有当前在线的BLE设备:
#include <SetupAPI.h> #include <BluetoothAPIs.h> #pragma comment(lib, "SetupAPI.lib") #pragma comment(lib, "Bthprops.lib") // BLE设备类GUID GUID bleDeviceClass = {0xe0cbf06c, 0xcd8b, 0x4647, {0xbb, 0x8a, 0x26, 0x3b, 0x43, 0xf0, 0xf9, 0x74}}; HDEVINFO hDevInfo = SetupDiGetClassDevs(&bleDeviceClass, nullptr, nullptr, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if (hDevInfo == INVALID_HANDLE_VALUE) { // 处理初始化错误 return; } SP_DEVICE_INTERFACE_DATA deviceInterfaceData = {0}; deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); for (DWORD i = 0; SetupDiEnumDeviceInterfaces(hDevInfo, nullptr, &bleDeviceClass, i, &deviceInterfaceData); i++) { // 获取设备实例路径所需缓冲区大小 DWORD requiredSize = 0; SetupDiGetDeviceInterfaceDetail(hDevInfo, &deviceInterfaceData, nullptr, 0, &requiredSize, nullptr); // 分配缓冲区并获取设备实例路径 std::unique_ptr<SP_DEVICE_INTERFACE_DETAIL_DATA> pDetailData(reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA*>(new char[requiredSize])); pDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &deviceInterfaceData, pDetailData.get(), requiredSize, nullptr, nullptr)) { // pDetailData->DevicePath 即为设备的唯一实例路径 } } SetupDiDestroyDeviceInfoList(hDevInfo);
二、获取未配对设备的hDevice句柄
通过上述方法拿到设备实例路径后,直接用CreateFile打开设备,无需提前配对:
HANDLE hDevice = CreateFile( pDetailData->DevicePath, // 设备实例路径 GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, nullptr ); if (hDevice != INVALID_HANDLE_VALUE) { // 成功获取hDevice,可直接传入BluetoothGATTGetServices使用 // 使用完成后记得关闭句柄 CloseHandle(hDevice); }
注意事项
- 项目需链接必要库:
SetupAPI.lib、Bthprops.lib、BluetoothAPIs.lib - 桌面应用可能需要管理员权限或蓝牙设备访问权限才能正常扫描和打开设备
- 若使用WinRT API,需确保项目支持C++/WinRT或通过COM方式调用
内容的提问来源于stack exchange,提问作者user4521550
相关产品推荐
相关产品推荐

