首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >发现后Windows UWP连接到BLE设备

发现后Windows UWP连接到BLE设备
EN

Stack Overflow用户
提问于 2016-02-15 23:21:49
回答 4查看 33.2K关注 0票数 21

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

代码语言:javascript
复制
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。我绝对可以连接到安卓和iOS。所以用UWP一定是有可能的。:/

代码语言:javascript
复制
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

我现在能够发现和配对(不稳定,但目前还可以),但是

代码语言:javascript
复制
var service = await GattDeviceService.FromIdAsync(args.Id);

引发以下异常

System.IO.FileNotFoundException:系统找不到指定的文件。(HRESULT例外: 0x80070002)

我不知道为什么。

EN

Stack Overflow用户

回答已采纳

发布于 2016-03-19 19:26:49

更新04/17 -创建者更新

微软刚刚更新了他们的蓝牙API。我们现在有未配对的BLE设备通信!

目前,他们的文档很少,但下面是一个非常简化的新结构:

代码语言:javascript
复制
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线程上运行蓝牙内容。没有配对的BLE似乎没有任何权限窗口,因此不再需要在UI线程上运行。
  • 您可能会发现,您的应用程序在一段时间后停止从设备接收更新。这是一个不应该处理对象的范围问题。在上面的代码中,如果您在charac上收听charac,您可能会碰到这个问题。这是因为GattCharacteristic在应该被释放之前就被释放了,将特性设置为全局特性,而不是依赖于它被复制。
  • 断线好像有点断了。退出应用程序不会终止连接。因此,请确保使用App.xml.cs OnSuspended回调来终止连接。否则,您会陷入一种奇怪的状态,Windows似乎在那里维护(并继续阅读!)BLE连接。

嗯,它有它的怪癖,但它有效!

旧答案

以下是Jason关于设备需要配对才能发现其服务的正确答案,下面是一些解决此问题的示例代码:

代码语言:javascript
复制
    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,该异常在试图询问未配对或尚未准备好的服务时发生。
票数 21
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35420940

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档