您可能想阅读https://developers.google.com/web/updates/2015/07/interact-with-ble-devices-on-the-web,其中显示了您必须通过的所有强制性选项:
例如,请求蓝牙设备广告蓝牙 GATT 电池服务很简单:
navigator.bluetooth.requestDevice({ filters: [{ services: ['battery_service'] }] })
.then(device => { /* ... */ })
.catch(error => { console.log(error); });
如果您的蓝牙 GATT 服务不在标准化蓝牙 GATT 服务列表中,您可以提供完整的蓝牙 UUID 或简短的 16 位或 32 位格式。
navigator.bluetooth.requestDevice({
filters: [{
services: [0x1234, 0x12345678, '99999999-0000-1000-8000-00805f9b34fb']
}]
})
.then(device => { /* ... */ })
.catch(error => { console.log(error); });
您还可以根据使用name
过滤器键公布的设备名称请求蓝牙设备,甚至可以使用
namePrefix
过滤器键根据该名称的前缀请求蓝牙设备。请注意,在这种情况下,您还需要定义optionalServices
能够访问某些服务的密钥。如果不这样做,稍后在尝试访问它们时会出现错误。
navigator.bluetooth.requestDevice({
filters: [{
name: 'Francois robot'
}],
optionalServices: ['battery_service']
})
.then(device => { /* ... */ })
.catch(error => { console.log(error); });