【问题标题】:UWP Bluetooth: issues with DeviceWatcher and findAllAsync()UWP 蓝牙:DeviceWatcher 和 findAllAsync() 的问题
【发布时间】:2017-05-20 08:12:06
【问题描述】:

我想获得使用 UWP 的蓝牙设备。我真的很想使用Devicewatcher,因为我应该继续寻找新设备。

我在DeviceWatcher 的Added 事件中得到的结果是DeviceInformation,并且我的应用程序中没有我需要的所有属性,因此我应该调用一些东西来获取BluetoothDevice 对象。问题是当我使用从DeviceWatcher 得到的Device.ID 调用以下方法时,会出现不同的错误:

  • BluetoothDevice.fromBluetoothAddressAsync() 的设备 ID 永远不会调用 done 方法。
  • BluetoothDevice.fromIdAsync() 引发 Element not Found 错误。

正如我在另一篇文章中所读到的,我还尝试从DeviceInformation.findAllAsync() 获取设备,它们都调用了上述两种方法,但结果相同。 (winjs-and-bluetooth-connection-error)

任何人都可以提出问题所在或其他方法吗?我的代码如下。

创建观察者的代码:

ondeviceadd = function (args) {
    //my code here
};
deviceWatch = Windows.Devices.Enumeration.DeviceInformation.createWatcher(selector, null);
deviceWatch.addEventListener("added", ondeviceadd);
deviceWatch.addEventListener("removed", ondeviceRemove);
deviceWatch.addEventListener("updated", ondeviceUpdate);
deviceWatch.addEventListener("stopped", onStopped);
deviceWatch.addEventListener("enumerationcompleted", ondeviceComplete);
deviceWatch.start();

从 findAllAsync 获取设备的代码:

var selector = Windows.Devices.Bluetooth.BluetoothDevice.getDeviceSelector();
Windows.Devices.Enumeration.DeviceInformation.findAllAsync(selector, null).done(function (data) {
    for (var i = 0; i < data.length; i++) {
        //My code here
    }
});

获取蓝牙设备的代码:

Windows.Devices.Bluetooth.BluetoothDevice.fromBluetoothAddressAsync(devid).done(
function(devinfo) {
    res = devinfo;
})
Windows.Devices.Bluetooth.BluetoothDevice.fromIdAsync(data.id).done(function(result){
    //my code here
});
Windows.Devices.Bluetooth.Rfcomm.RfcommDeviceService.fromIdAsync(devId).done(function (result) {    
    //my code here
})

【问题讨论】:

  • "我在另一篇文章中读到,"...那篇文章是什么?请编辑问题以将该文本链接到帖子...
  • 添加了另一个帖子的链接。

标签: javascript bluetooth uwp winjs


【解决方案1】:

BluetoothDevice.FromIdAsync | fromIdAsync method 是获取具有给定设备 ID 的 BluetoothDevice 对象的正确方法。在DeviceWatcher.Added | added event 中,我们可以得到DeviceInformation 对象,其中包含DeviceInformation.Id | id property 但没有蓝牙地址信息。所以这里不能使用BluetoothDevice.FromBluetoothAddressAsync | fromBluetoothAddressAsync method。

但是在使用BluetoothDevice.fromIdAsync 方法时,我们需要注意这个方法需要蓝牙能力。请参阅 要求 → 功能 以及 Device capabilities。所以要使用这个方法,我们需要在Package.appxmanifest中添加Bluetooth能力,比如:

然后当我们第一次调用这个方法时,系统会请求用户授予访问蓝牙设备的权限。如果用户选择Yes,此方法将返回一个BluetoothDevice 对象代表设备。但是如果用户选择No那么这个方法会返回null。

【讨论】:

  • 我今天会试一试。但我真的很想使用 DeviceWatcher,因为我需要在进程启动后持续观察蓝牙设备是否打开或被发现。我想如果我能找到某种方法从 devicewatcher 获取设备,然后创建 bluetoothdevice.fromIDAsync 那么它可能是一个完美的解决方案。
  • @PriyankC 您可以将DeviceWatcher 与BluetoothDevice.fromIdAsync 方法一起使用。我已经测试过了,效果很好。
  • 嗨@PriyankC,有什么更新吗?我的回答解决了你的问题吗?是acceptable answer吗?
猜你喜欢
  • 1970-01-01
  • 2017-10-26
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
  • 2016-08-10
  • 2015-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多