LoginSignup
1
1

More than 5 years have passed since last update.

BluetoothLEAdvertisementWatcher.Received のコールバックが返って来ない

Posted at

最初に結論

Package.appxmanifest を編集してBluetoothの機能を使う設定にしてください。

BluetoothLEAdvertisementWatcher

https://docs.microsoft.com/en-us/uwp/api/windows.devices.bluetooth.advertisement.bluetoothleadvertisementwatcher
このクラスのReceivedのイベントにコールバックを登録すると、周辺でアドバタイズ中のBLEデバイスの情報を随時取得できます。

実装例

var BleWatcher = new BluetoothLEAdvertisementWatcher 
{ 
    ScanningMode = BluetoothLEScanningMode.Active
};

BleWatcher.Received += async (w, btAdv) => {
    var device = await BluetoothLEDevice.FromBluetoothAddressAsync(btAdv.BluetoothAddress);
    Debug.WriteLine($"BLEWATCHER Found: {device.name}");

    // SERVICES!!
    var gatt = await device.GetGattServicesAsync();
    Debug.WriteLine($"{device.Name} Services: {gatt.Services.Count}, {gatt.Status}, {gatt.ProtocolError}");

    // CHARACTERISTICS!!
    var characs = await gatt.Services.Single(s => s.Uuid == SAMPLESERVICEUUID).GetCharacteristicsAsync();
    var charac = characs.Single(c => c.Uuid == SAMPLECHARACUUID);
    await charac.WriteValueAsync(SOMEDATA);
};

BleWatcher.Start();

だがしかし

ログに何も出てきません。色々調べながら回りまわって公式ドキュメントに目を通していると、
https://docs.microsoft.com/ja-jp/windows/uwp/devices-sensors/ble-beacon
無題3.png
🤮

再チャレンジ

Visual Studio上のソリューションエクスプローラから
無題2.png
Package.appxmanifestをダブルクリックして編集します。

無題.png
[機能]からBluetoothにチェックを入れます。

さすればログに目的のBLEデバイスのスキャン結果が表示されるようになりました。

AndroidのAndroid.manifestやiOSのinfo.plistにもBLEのパーミッションを記載する設定ファイルがありますが、こちらは開発(デバッグ)中は未設定でも動作したはずですが、WindowsのUWPアプリの仕様は違うようです。

何も出ないのでBLEデバイス側に問題があるのかとか色々ハマりました。
何かしらエラーを吐いてくれれば気づけたでしょうが、公式のドキュメントはちゃんと見た方がよいという話です。(個々人のブログだと当たり前すぎることは書いてないので)

参考

Why is BluetoothLEDevice.GattServices Empty
Windows 10 における Bluetooth サポートについて

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1