问题描述
我有一个 BLE 应用程序。
当我开始设备扫描时,DeviceWatcher.Added
事件将立即调用并显示当前已关闭的先前连接的设备。但在 DeviceWatcher.Removed
事件中它会被清除。
我怎样才能防止这种情况。在我的应用程序中,我试图在 DeviceWatcher.Added
事件中列出设备时立即连接设备。我不想等到 DeviceWatcher.EnumerationCompleted
事件。
由于此实现,连接 API BluetoothLEDevice bluetoothLEDevice = BluetoothLEDevice::FromIdAsync(GetId()).get();
返回成功。在服务扫描 API GattDeviceServicesResult result = m_BluetoothLEDevice.GetGattServicesAsync(BluetoothCacheMode::Uncached).get();
中,我获得了 GattCommunicationStatus::Unreachable
状态。
我在最初扫描时需要此状态。或者有什么其他方法可以检查设备是否无法访问?
解决方法
此处编写的示例是用 C# 编写的,您可以在 docs.microsoft.com
中找到 C++ 替换- 您可以像这样获得所有配对的 BLE 设备。
var pairedBleDevices = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)); # Return all the paired Bluetooth LE devices
现在,如果您想删除特定设备的配对,您可以遍历 pairedBleDevices 并通过匹配特定属性(例如设备名称或地址)找到您的删除设备。
foreach (var device in pairedBleDevices )
{
if (!device::Name.Contains("myDevice")) continue;
await device.Pairing.UnpairAsync();
break;
}
-
现在,正如 Mike 建议的那样,您拥有所有先前配对的具有属性的 LE 设备,您可以使用 BluetoothLEAdvertisementWatcher 来发现 BLE 设备并通过匹配蓝牙地址(来自配对设备)来过滤广告。如果发现新设备,请配对设备或执行 GATT 操作并开始通信。
-
您收到 GattCommunicationStatus::Unreachable 这可能是您尝试与之通信的设备处于睡眠模式。所以最好的方法是首先使用 BluetoothLEAdvertisementWatcher 捕获广告,然后启动配对或 GATT 操作。