Martin Dusek
Martin Dusek

Reputation: 1292

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.

Upvotes: 1

Views: 15291

Answers (3)

Rita Han
Rita Han

Reputation: 9700

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.).enter image description here

Upvotes: 0

Martin Dusek
Martin Dusek

Reputation: 1292

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.

Upvotes: 6

Emil
Emil

Reputation: 18442

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, i.e. 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.

Upvotes: 2

Related Questions