* web H5 网页 浏览器 蓝牙 Bluetooth

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)

  1. 需要HTTPS
  2. 需要用户给予蓝牙权限,需要用户点击确认
button.addEventListener('pointerup', function(event) {
   
  // Call navigator.bluetooth.requestDevice
});
  1. 系统要求,具体的看这里 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
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

caesarding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值