发现后Windows UWP连接到BLE设备

斯文·迈克尔·斯图伯

我正在BluetoothLEAdvertisementWatcher寻找附近的BLE设备,并且运行良好。找到它们之后,我想通过GATT连接和读取/写入数据。但是在获取BluetoothLEAdvertisementhttps://msdn.microsoft.com/de-de/library/windows/apps/windows.devices.bluetooth.genericattributeprofile之后,我不知道如何使用API

public class Adapter
{
    private readonly BluetoothLEAdvertisementWatcher _bleWatcher = new BluetoothLEAdvertisementWatcher();

    public Adapter()
    {
        _bleWatcher.Received += BleWatcherOnReceived;
    }

    private void BleWatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
    {       
        // how to connect?
        // I know, it's the wrong place to to this, but this is just an example
    }

    public void StartScanningForDevices(Guid[] serviceUuids)
    {
        _blewatcher.advertisementfilter.advertisement.serviceuuids.clear();
        foreach (var uuid in serviceuuids)
        {
            _blewatcher.advertisementfilter.advertisement.serviceuuids.add(uuid);
        }
        _blewatcher.start();
    }
}

我发现正在使用DeviceInformation.FindAllAsync而不是的样本,BluetoothLEAdvertisementWatcher但这些样本无法正常工作/找不到任何设备。

更新

经过一段时间的挖掘,我发现了以下方法。但不幸的是,配对失败。该设备只是带有BLE屏蔽的Arduino。我绝对可以连接Android和iOS。因此,以某种方式使用UWP必须有可能。:/

private void BleWatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{       
    var dev = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
    // dev.DeviceInformation.Pairing.CanPair is true
    // dpr.Status is Failed
    DevicePairingResult dpr = await dev.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.None);
    var service = await GattDeviceService.FromIdAsync(dev.DeviceInformation.Id);
}

更新#2

我现在可以发现并配对(不稳定,但暂时还可以),但是

var service = await GattDeviceService.FromIdAsync(args.Id);

引发以下异常

System.IO.FileNotFoundException:系统找不到指定的文件。(来自HRESULT的异常:0x80070002)

我不知道为什么。

杰拉德·威尔金森

更新04/17-创建者更新

Microsoft刚刚更新了其蓝牙API。现在,我们有未配对的BLE设备通信!

目前,他们的文档很少,但这是简化得多的新结构:

BleWatcher = new BluetoothLEAdvertisementWatcher 
{ 
    ScanningMode = BluetoothLEScanningMode.Active
};
BleWatcher.Start();

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);
};

现在好多了。正如我所说的,目前几乎没有文档,我有一个奇怪的问题,即ValueChanged回调在30秒左右后停止调用,尽管这似乎是一个单独的范围界定问题。

更新2-有些古怪

在与新的创建者进行更多的更新之后,构建BLE应用程序时还需要考虑一些其他事项。

  • 您不再需要在UI线程上运行Bluetooth东西。没有配对,似乎没有BLE的任何权限窗口,因此不再需要在UI线程上运行。
  • 您可能会发现一段时间后,应用程序停止从设备接收更新。这是一个范围确定的问题,在该问题中不应丢弃对象。在上面的代码中,如果您正在收听,ValueChangedcharac可能会遇到此问题。这是因为GattCharacteristic应先将其处置,然后将特征设置为全局特征,而不要依赖于其被复制到其中。
  • 断开连接似乎有点破损。退出应用程序不会终止连接。因此,请确保使用App.xml.cs OnSuspended回调来终止连接。否则,您会陷入一种奇怪的状态,即Windows似乎维护(并继续阅读!)BLE连接。

好吧,它有它的怪癖,但它有效!

老答案

遵循杰森(Jason)关于需要配对以使其服务被发现的设备的正确答案,下面是一些示例代码来解决此问题:

    private void SetupBluetooth()
    {
        Watcher = new BluetoothLEAdvertisementWatcher { ScanningMode = BluetoothLEScanningMode.Active };
        Watcher.Received += DeviceFound;

        DeviceWatcher = DeviceInformation.CreateWatcher();
        DeviceWatcher.Added += DeviceAdded;
        DeviceWatcher.Updated += DeviceUpdated;

        StartScanning();
    }

    private void StartScanning()
    {
        Watcher.Start();
        DeviceWatcher.Start();
    }

    private void StopScanning()
    {
        Watcher.Stop();
        DeviceWatcher.Stop();
    }

    private async void DeviceFound(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs btAdv)
    {
        if (_devices.Contains(btAdv.Advertisement.LocalName))
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Low, async () =>
            {
                Debug.WriteLine($"---------------------- {btAdv.Advertisement.LocalName} ----------------------");
                Debug.WriteLine($"Advertisement Data: {btAdv.Advertisement.ServiceUuids.Count}");
                var device = await BluetoothLEDevice.FromBluetoothAddressAsync(btAdv.BluetoothAddress);
                var result = await device.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.None);
                Debug.WriteLine($"Pairing Result: {result.Status}");
                Debug.WriteLine($"Connected Data: {device.GattServices.Count}");
            });
        }
    }

    private async void DeviceAdded(DeviceWatcher watcher, DeviceInformation device)
    {
        if (_devices.Contains(device.Name))
        {
            try
            {
                var service = await GattDeviceService.FromIdAsync(device.Id);
                Debug.WriteLine("Opened Service!!");
            }
            catch
            {
                Debug.WriteLine("Failed to open service.");
            }
        }
    }

    private void DeviceUpdated(DeviceWatcher watcher, DeviceInformationUpdate update)
    {
        Debug.WriteLine($"Device updated: {update.Id}");
    }

这里要注意的关键事项是:

  • DeviceWatcher需要同时设置添加和更新属性。
  • 您需要捕获异常FileNotFound,该异常在尝试查询未配对或尚未准备就绪的服务时发生。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

仅在Asus标签中无法发现并连接到ble设备

来自分类Dev

连接到BLE设备后如何获取电池电量?

来自分类Dev

拔出电池后重新连接到BLE设备

来自分类Dev

在Windows 10上连接到BLE外围设备

来自分类Dev

关闭蓝牙然后再次打开后,Android 6.0将不再连接到BLE设备

来自分类Dev

一旦Windows 10 UWP中的连接断开,如何以编程方式连接到配对的蓝牙设备

来自分类常见问题

何时发现BLE设备?

来自分类Dev

何时发现BLE设备?

来自分类Dev

Windows 10无法连接到Intranet设备

来自分类Dev

设备断开连接后如何取消BLE任务?

来自分类Dev

Android BLE按名称连接到设备

来自分类Dev

Android BLE按名称连接到设备

来自分类常见问题

每个发现的设备后如何获取列表?

来自分类Dev

更新到Windows 10后连接到VMWare Player中的USB设备时出错

来自分类Dev

通知图像仅在设备连接到系统后可见

来自分类Dev

无法通过HttpClient或其他方式连接到UWP中的127.0.0.1(localhost)设备门户(仅适用于Windows 10 Mobile RS1)

来自分类Dev

连接到非Windows设备上的Windows Homegroup

来自分类Dev

取消BLE外围设备连接后无法重新连接iOS

来自分类Dev

Windows VirtualBox无法将USB设备连接到Linux Guest

来自分类Dev

iOS在didSelectRowAtIndexPath连接到BLE设备EXC_BREAKPOINT

来自分类Dev

iOS如何在后台重新连接到BLE设备?

来自分类Dev

iOS-将BLE设备连接到应用和iOS

来自分类Dev

连接到ble设备时是否可以启动服务/活动?

来自分类Dev

将BLE设备连接到Android发送数据(nUART)

来自分类Dev

发现后,iOS外围设备服务仍然为空

来自分类Dev

设备扫描后Android列出BLE设备

来自分类Dev

Android Bluetooth LE:连接后未发现服务

来自分类Dev

如何使用Meteor和Cordova BLE插件连接到BLE设备

来自分类Dev

如何使用Meteor和Cordova BLE插件连接到BLE设备

Related 相关文章

  1. 1

    仅在Asus标签中无法发现并连接到ble设备

  2. 2

    连接到BLE设备后如何获取电池电量?

  3. 3

    拔出电池后重新连接到BLE设备

  4. 4

    在Windows 10上连接到BLE外围设备

  5. 5

    关闭蓝牙然后再次打开后,Android 6.0将不再连接到BLE设备

  6. 6

    一旦Windows 10 UWP中的连接断开,如何以编程方式连接到配对的蓝牙设备

  7. 7

    何时发现BLE设备?

  8. 8

    何时发现BLE设备?

  9. 9

    Windows 10无法连接到Intranet设备

  10. 10

    设备断开连接后如何取消BLE任务?

  11. 11

    Android BLE按名称连接到设备

  12. 12

    Android BLE按名称连接到设备

  13. 13

    每个发现的设备后如何获取列表?

  14. 14

    更新到Windows 10后连接到VMWare Player中的USB设备时出错

  15. 15

    通知图像仅在设备连接到系统后可见

  16. 16

    无法通过HttpClient或其他方式连接到UWP中的127.0.0.1(localhost)设备门户(仅适用于Windows 10 Mobile RS1)

  17. 17

    连接到非Windows设备上的Windows Homegroup

  18. 18

    取消BLE外围设备连接后无法重新连接iOS

  19. 19

    Windows VirtualBox无法将USB设备连接到Linux Guest

  20. 20

    iOS在didSelectRowAtIndexPath连接到BLE设备EXC_BREAKPOINT

  21. 21

    iOS如何在后台重新连接到BLE设备?

  22. 22

    iOS-将BLE设备连接到应用和iOS

  23. 23

    连接到ble设备时是否可以启动服务/活动?

  24. 24

    将BLE设备连接到Android发送数据(nUART)

  25. 25

    发现后,iOS外围设备服务仍然为空

  26. 26

    设备扫描后Android列出BLE设备

  27. 27

    Android Bluetooth LE:连接后未发现服务

  28. 28

    如何使用Meteor和Cordova BLE插件连接到BLE设备

  29. 29

    如何使用Meteor和Cordova BLE插件连接到BLE设备

热门标签

归档