I am looking for an API call that could be used to retrieve all the Bluetooth devices near me. These samples Web Bluetooth talk about getting different characteristics from a single Bluetooth device, however I couldn't find any example which retrieves all the Bluetooth devices(like available bluetooth devices list on windows native Bluetooth app). Is it even supported?
3 回答
我个人没有对 Web Bluetooth API 进行过很多试验,但我认为您正在寻找Device Discovery和Request Bluetooth Devices:
此版本的 Web 蓝牙 API 规范允许以 Central 角色运行的网站通过 BLE 连接连接到远程 GATT 服务器。它支持实现蓝牙 4.0 或更高版本的设备之间的通信。
当网站使用 navigator.bluetooth.requestDevice 请求访问附近的设备时,谷歌浏览器会提示用户使用设备选择器,他们可以在其中选择一个设备或简单地取消请求。
navigator.bluetooth.requestDevice 函数采用定义过滤器的强制对象。这些过滤器用于仅返回与某些广告的蓝牙 GATT 服务和/或设备名称匹配的设备。
此外,这里是GATT 服务列表。
(好吧,这个问题让我陷入了困境......)
几年后,我们开始看到生命迹象api.Bluetooth.getDevices
。我最终得到了一个在 Chrome 中工作的实验性演示。
您可能需要启用 Chrome 的“网络蓝牙实验”。(Firefox 有一个等价物,但我没有尝试过。)
转到
chrome://flags/
然后搜索bluetooth
并启用 API。点击演示页面上的按钮: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);
});
}
祝你好运!