2022/1/18 更新说明
为了避免重复造轮子,请参考这篇文章。其中内容详细且全面,目前也已经有了中文版
1. 通过 JavaScript 与蓝牙设备通信
目标
最近正在开发一个项目,项目的需求如下:
在H5(基于vue框架)页面上,通过js调用webbluetooth接口,读取某个蓝牙设备传输的数据,并返回显示。
介绍
背景
随着PWA的兴起,越来越多的web服务被支持。但其中一个领域几乎是原生应用的专属领域:与设备通信。长期以来,开发者们一直在致力于解决这个问题。
The web is excellent for talking to servers, but not for talking to devices
……
于是乎WebBluetooth应运而生,这是一个已经在Chrome和三星互联网上实现的新规范。
WebBluetooth is a new specification that has been implemented in Chrome and Samsung Internet that allows us to communicate directly to Bluetooth Low Energy devices from the browser.
Bluetooth Low Energy (BLE)
Generic Attribute Profile (GATT)
蓝牙BLE: GATT Profile 简介(GATT 与 GAP)
GAP 使你的设备被其他设备可见,并决定了你的设备是否可以或者怎样与合同设备进行交互。
GATT协议 - 通用属性配置
WebBluetooth API
通过使用WebBluetooth API,我们只需要几行JavaScript就可以和蓝牙设备进行沟通。
The Web Bluetooth API aims to do exactly that with a promise-based API, which allows you to interact with many BLE(Bluetooth Low Energy) enabled devices.
使用条件(prerequisites)
- 需要HTTPS
- 需要用户给予蓝牙权限,需要用户点击确认
button.addEventListener('pointerup', function(event) {
// Call navigator.bluetooth.requestDevice
});
- 系统要求,具体的看这里 MDN’s Browser compatibility
A subset of the Web Bluetooth API is available in Chrome OS, Chrome for Android 6.0, Mac (Chrome 56) and Windows 10 (Chrome 70)
navigator.bluetooth.requestDevice()
接受一个定义筛选器的强制对象。这些过滤器用于仅返回匹配某些已发布的蓝牙GATT服务和/或设备名称的设备。
使用:过滤器
- Services filter
navigator.bluetooth.requestDevice({
filters: [{
services: ['battery_service'] }] })
.then(device => {
/* … */ })
.catch(error => {
console.error(error); });
如果蓝牙设备不在这个服务列表里面,我们需要提供完整的Bluetooth UUID 或者16-/32-bit 的排列
navigator.bluetooth.requestDevice({
filters: [{
services: [0x1234, 0x12345678, '99999999-0000-1000-8000-00805f9b34fb']
}]
})
.then(device => {
/* … */ })
.catch(error => {
console.error(error); });
- Name filter
navigator.bluetooth