实际应用
之前做的一个项目需求就是,windows系统的pc连接双模的蓝牙设备,根据已经连接的edr蓝牙去跟对应的ble蓝牙进行通信。
我的基本思路是,双模蓝牙设备的edr和ble的mac地址要一致或者要有对应关系,使用windows的api枚举出已经连接的edr设备并获取到mac地址,再根据mac地址去发现对应ble设备的实例地址。
方案
目前我了解到的,在windows上开发ble蓝牙有两种方案:
- 使用windows的api,有集成的开源库,这里提供连接:https://github.com/DerekGn/WinBle
- 使用uwp平台的api,有官方提供的demo,这里提供连接:https://learn.microsoft.com/zh-cn/windows/uwp/devices-sensors/gatt-client
我是选择的uwp平台的api,因为毕竟是官方的。
下面就按照上面提到的思路来一步步实现。
实现步骤
一、获取已经连接的Edr蓝牙设备的Mac地址
直接使用windows提供的api就可以实现了,贴代码。
#include <devguid.h>
#include <setupapi.h>
#include <comdef.h>
#pragma comment(lib, "Bthprops.lib")
#pragma comment(lib, "Setupapi.lib")
std::vector<BLUETOOTH_DEVICE_INFO> getConnectDevice()
{
BLUETOOTH_DEVICE_SEARCH_PARAMS searchParams = { sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS) };
BLUETOOTH_DEVICE_INFO deviceInfo = { sizeof(BLUETOOTH_DEVICE_INFO) };
searchParams.fReturnAuthenticated = FALSE;
searchParams.fReturnRemembered = FALSE;
searchParams.fReturnConnected = TRUE;
searchParams.fIssueInquiry = FALSE;
searchParams.cTimeoutMultiplier = 2;
HANDLE hDeviceFind = BluetoothFindFirstDevice(&searchParams, &deviceInfo);
std::vector<BLUETOOTH_DEVICE_INFO> connectedDevices;
if (hDeviceFind == NULL) {
//std::cerr << "No connected Bluetooth devices found." << std::endl;
return connectedDevices;
}
do {
connectedDevices.push_back(deviceInfo);
//std::wcout << L"Device Name: " << deviceInfo.szName << std::endl;
//std::wcout << L"Device Address: " << deviceInfo.Address.ullLong << std::endl;
//std::wcout << L"Device Class: 0x" << std::hex << deviceInfo.ulClassofDevice << std::dec << std::endl;
//std::wcout << L"-------------------------------------" << std::endl;
} while (BluetoothFindNextDevice(hDeviceFind, &deviceInfo));
BluetoothFindDeviceClose(hDeviceFind);
return connectedDevices;
}
可以通过配置 BLUETOOTH_DEVICE_SEARCH_PARAMS
这个结构体实现枚举不同状态的设备。两个结构体更详细的说明可以在微软官网找到。
二、根据Mac地址发现Ble蓝牙的实例路径
最主要的就是设置Ble Watcher的过滤器和Watcher的回调函数。
// 提供部分核心代码
#include <vector&g