[英]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.