简体   繁体   中英

Connect to BLE peripheral on Windows 10

I try to connect to BLE peripheral. First, I watch for advertisements:

watcher = new BluetoothLEAdvertisementWatcher { ScanningMode = BluetoothLEScanningMode.Active };
watcher.Received += WatcherOnReceived;
watcher.Start();

and in the WatcherOnReceived callback I try to create BluetoothLEDevice

public async void WatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs btAdv)
{
    BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(btAdv.BluetoothAddress);
}

However, I always get bleDevice == null in WatcherOnReceived callback. Why and how to fix it? What is the proper way of creating BLE device in UWP application? I then need to connect to that device, discover its GATT services and characteristics, enable notifications on some of them and read/write some of them.

The answer to this question is simple - do not use BLE on Windows 10. The API doesn't work or behaves randomly and is totally undocumented. I like everyone talking about IoT being next industrial revolution and Microsoft not having working BLE API after 6 year BLE exists.

See example 8 and 9 in https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/DeviceEnumerationAndPairing if you want to be able to connect to previously non-paired BLE devices, ie use a DeviceWatcher with a Bluetooth LE selector.

Otherwise you need to first pair it in the system's bluetooth pairing settings before you will be able to retrieve a BluetoothLEDevice from FromBluetoothAddressAsync.

You can check device information in WatcherOnReceived() to ensure that the device is what you want to connect with. Do it like this:

public async void WatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs btAdv)
{
    if (btAdv.Advertisement.LocalName == "SensorTag")
    {
        BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(btAdv.BluetoothAddress);
    }    
}

Use your own BLE device name instead of "SensorTag".

Note: You need pair your BLE device beforehand(either programatically like DeviceEnumerationAndPairing sample or PC's setting app as shown in the following image.). 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM