Web Bluetooth API 获取附近所有可用设备的列表

Web Bluetooth API get list of all available device nearby

我正在寻找可用于检索我附近所有蓝牙设备的 API 呼叫。这些示例 Web Bluetooth 讨论了从单个蓝牙设备获取不同的特性,但是我找不到任何检索所有蓝牙设备的示例(例如 windows 本机蓝牙应用程序上的可用蓝牙设备列表)。甚至支持吗?

我个人对网络蓝牙 API 的试验不多,但我认为您正在寻找 Device Discovery and Request Bluetooth Devices:

This version of the Web Bluetooth API specification allows websites, running in the Central role, to connect to remote GATT Servers over a BLE connection. It supports communication among devices that implement Bluetooth 4.0 or later.

When a website requests access to nearby devices using navigator.bluetooth.requestDevice, Google Chrome will prompt user with a device chooser where they can pick one device or simply cancel the request.

The navigator.bluetooth.requestDevice function takes a mandatory Object that defines filters. These filters are used to return only devices that match some advertised Bluetooth GATT services and/or the device name.

此外,这是 GATT 的列表 服务.

A Web Bluetooth Scanning specification draft exists, but implementation isn't started 截至 2018 年的任何地方。

(好吧,这个问题让我掉进了兔子洞...)

几年后,我们开始看到 api.Bluetooth.getDevices 的生命迹象。我最终在 Chrome.

中得到了一个实验性演示

您可能需要启用 Chrome 的“网络蓝牙实验”。 (Firefox 有一个等价物,但我没试过。)

  1. 转到 chrome://flags/ 然后搜索 bluetooth 并启用 API.

  2. 单击演示页面上的按钮:Web Bluetooth / Get Devices Sample


来自同一页面的演示代码

function onGetBluetoothDevicesButtonClick() {
  log('Getting existing permitted Bluetooth devices...');
  navigator.bluetooth.getDevices()
  .then(devices => {
    log('> Got ' + devices.length + ' Bluetooth devices.');
    for (const device of devices) {
      log('  > ' + device.name + ' (' + device.id + ')');
    }
  })
  .catch(error => {
    log('Argh! ' + error);
  });
}

function onRequestBluetoothDeviceButtonClick() {
  log('Requesting any Bluetooth device...');
  navigator.bluetooth.requestDevice({
 // filters: [...] <- Prefer filters to save energy & show relevant devices.
    acceptAllDevices: true
  })
  .then(device => {
    log('> Requested ' + device.name + ' (' + device.id + ')');
  })
  .catch(error => {
    log('Argh! ' + error);
  });
}

祝你好运!