[英]Connect to BLE peripheral on Windows 10
我尝试连接到BLE外围设备。 首先,我看广告:
watcher = new BluetoothLEAdvertisementWatcher { ScanningMode = BluetoothLEScanningMode.Active };
watcher.Received += WatcherOnReceived;
watcher.Start();
在WatcherOnReceived回调中,我尝试创建BluetoothLEDevice
public async void WatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs btAdv)
{
BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(btAdv.BluetoothAddress);
}
但是,我总是在WatcherOnReceived回调中得到bleDevice == null。 为什么以及如何解决? 在UWP应用程序中创建BLE设备的正确方法是什么? 然后,我需要连接到该设备,发现其GATT服务和特性,在其中一些上启用通知,并读/写其中一些。
这个问题的答案很简单-不要在Windows 10上使用BLE。该API无法正常工作或行为随机,并且完全没有文档说明。 我喜欢每个人都在谈论物联网是下一次工业革命,并且微软在存在6年的BLE后仍无法使用BLE API。
如果您希望能够连接到以前未配对的BLE设备,请参见https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/DeviceEnumerationAndPairing中的示例8和9,即使用DeviceWatcher与蓝牙LE选择器。
否则,您需要先在系统的蓝牙配对设置中将其配对,然后才能从FromBluetoothAddressAsync检索BluetoothLEDevice。
您可以在WatcherOnReceived()
检查设备信息,以确保该设备是您要连接的设备。 像这样做:
public async void WatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs btAdv)
{
if (btAdv.Advertisement.LocalName == "SensorTag")
{
BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(btAdv.BluetoothAddress);
}
}
使用您自己的BLE设备名称代替“ SensorTag”。
注意:您需要预先配对BLE设备(以编程方式,例如DeviceEnumerationAndPairing示例或PC的设置应用程序,如下图所示)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.