你不知道的前端蓝牙应用实践 -- 心率带

438次阅读  |  发布于1年以前

一、背景

最近开启了减肥计划,购入了一条心率带,期望在使用划船机过程中监测心率情况。购入后的情况如下:

于是萌生了在自己的节拍器小程序内监听心率数据的想法,即Taro小程序中的蓝牙应用实践。

二、简单了解蓝牙

中心设备/外围设备

客户端(中心设备):在本次实践中为笔者的手机。

服务端(外围设备):在本次实践中为心率带、耳机等设备。

BLE(Bluetooth Low Energy)

蓝牙低能耗技术,实现设备间的连接与通信。顾名思义,能耗与成本都更低,与之相对应的则称为经典蓝牙。基于笔者的开发目的,本文简单了解设备连接前(GAP)和连接后(GATT)所涉及的两个协议。

(了解更多:蓝牙低能耗——百度百科[1]、一文读懂蓝牙技术从 1.0 到 5.0 的前世今生[2])

GAP(Generic Access Profile)

主要用来控制设备连接和广播。通常是由外围设备主动、间隔性地广播设备信息,等待中心设备发现并建立连接。需要注意的是,这种连接方式是独占的,在建立连接后,外围设备将停止广播。

另一方面,还存在仅向外广播而不建立连接的iBeacon设备。

GATT(Generic Attribute Profile)

定义了两个设备间的数据传输方式。GATT中有两个关键概念:service(服务)与characteristic(特征)。

Service就是一个独立的逻辑项,它包含一个或多个Characteristic。

Characteristic是GATT中最小的逻辑数据单元,其属性包含properties,标识该特性是否能够被read、write、notify、indicate。notify与indicate的区别在于,indicate需要有回复才能发送下一个数据包。

每个服务和特性都具有唯一的UUID标识,其中部分是由Bluetooth SIG官方定义的, Assigned Numbers | Bluetooth® Technology Website[3],如设备名、心率数据等常用属性都是官方定义来统一规范。此外UUID也可以由硬件工程师来自定义实现。

(了解更多:BLE相关协议(GAP&GATT)[4])

三、API简介

Taro中的蓝牙API

Taro.openBluetoothAdapter(option) | Taro 文档[5]

初始化蓝牙模块

Taro.openBluetoothAdapter({
      success: function (res) {
        console.log("蓝牙环境已启动:", res);
        setInitStatus(true);
      },
      fail: function (err) {
        if (err.errMsg.includes("fail already opened")) {
          console.log("蓝牙环境原先已启动:", err);
          setInitStatus(true);
        } else {
          console.log("蓝牙环境启动失败:", err);
          setInitStatus(false);
        }
      },
    });

Taro.getBluetoothDevices(option) | Taro 文档[6]

获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。

 discoverInterval = setInterval(() => {
        Taro.getBluetoothDevices({
          success: async function (res) {
            const canConnectDevices = res.devices.filter(
              (item) =>
                // 信号强度大于-80
                item.RSSI > -80 &&
                // 含有设备名
                !["未知设备", "MBeacon"].includes(item.name)
            );
            console.log("获取蓝牙设备列表成功:", canConnectDevices);

            setDeviceList(() => canConnectDevices);
          },
        });
      }, 2000);

也可以使用 Taro.onBluetoothDeviceFound(callback) | Taro 文档[7]来发现设备。

Taro.createBLEConnection(option) | Taro 文档[8]

连接低功耗蓝牙设备。

若小程序在之前已有搜索过某个蓝牙设备,并成功建立连接,可直接传入之前搜索获取的 deviceId 直接尝试连接该设备,无需进行搜索操作。

 Taro.createBLEConnection({
        deviceId,
        success: function (res) {
          console.log("设备连接成功", res);
          setConnectDeviceId(deviceId);

          Taro.onBLEConnectionStateChange(function (res) {
            // 该方法回调中可以用于处理连接意外断开等异常情况
            console.log(
              `设备 ${res.deviceId}连接状态发生变化: ${res.connected}`
            );
            if (!res.connected) {
              setConnectDeviceId("");
            }
          });
        },
      });

Taro.getBLEDeviceServices(option) | Taro 文档[9]

获取蓝牙设备所有服务(service)。

Taro.getBLEDeviceServices({
  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  deviceId,
  success: function (res) {
    console.log('device services:', res.services)
  }
})

Taro.getBLEDeviceCharacteristics(option) | Taro 文档[10]

获取蓝牙设备某个服务中所有特征值(characteristic)。

Taro.getBLEDeviceCharacteristics({
  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  deviceId,
  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
  serviceId,
  success: function (res) {
    console.log('device getBLEDeviceCharacteristics:', res.characteristics)
  }
})

Taro.readBLECharacteristicValue(option) | Taro 文档[11]

读取低功耗蓝牙设备的特征值的二进制数据值。注意:必须设备的特征值支持 read 才可以成功调用。

Taro.notifyBLECharacteristicValueChange(option) | Taro 文档[12]

启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。注意:必须设备的特征值支持 notify 或者 indicate 才可以成功调用。

另外,必须先启用 notifyBLECharacteristicValueChange 才能监听到设备 characteristicValueChange 事件

Taro.onBLECharacteristicValueChange(callback) | Taro 文档[13]

监听低功耗蓝牙设备的特征值变化事件。必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。

WEB蓝牙API

此处贴一些资料,感兴趣可自行阅读

Web Bluetooth API - Web APIs | MDN[14]

通过 JavaScript 与蓝牙设备通信[15]

四、设备名称(Device Name)详解

首先getBLEDeviceServices获取到服务列表:

查询资料

可知0x1800是我们需要的服务。getBLEDeviceCharacteristics获取其特征列表:

查询资料

可知0x2A00是我们需要的特征。此时可以看到read属性为true,我们通过onBLECharacteristicValueChange和readBLECharacteristicValue读一下数据看看。

  Taro.onBLECharacteristicValueChange(function (characteristic) {
      const buffer = characteristic.value
      const unit8Array = new Uint8Array(buffer);
      console.log("unit8Array: ", unit8Array);

      // 转字符串
      const encodedString = String.fromCodePoint.apply(null, unit8Array);
      console.log('设备名:', encodedString)
  });

  Taro.readBLECharacteristicValue({
    deviceId,
    serviceId: DeviceNameService,
    characteristicId: DeviceNameCharacteristics,
  });

得到输出,某米耳机:

大家应该已经发现,给到的特征值其实是ArrayBuffer格式。

(了解更多:谈谈JS二进制:File、Blob、FileReader、ArrayBuffer、Base64 - 掘金[16])

此时需要我们将其转化为字符串。除了上面的方法外,还可以先转16进制,再转字符串:

// 转16进制
 const hexString = Array.prototype.map
    .call(unit8Array, function (bit) {
      return ("00" + bit.toString(16)).slice(-2);
    })
    .join("");
 console.log("hexString: ", hexString);

 // 16进制转字符串
 const hex2String = (hexString:string) => {
     if (hexString.length % 2) return "";
     var tmp = "";
     for (let i = 0; i < hexString.length; i += 2) {
        tmp += "%" + hexString.charAt(i) + hexString.charAt(i + 1);
     }
     return decodeURI(tmp);
 }

五、心率测量(Heart Rate Measurement)详解

同样,首先我们拿到了所需的服务和特征如下。

export const HEART_RATE_SERVICE_UUID =
    "0000180D-0000-1000-8000-00805F9B34FB";
export const HEART_RATE_CHARACTERISTIC_UUID =
     "00002A37-0000-1000-8000-00805F9B34FB";

在设备连接后,通过onBLECharacteristicValueChange和notifyBLECharacteristicValueChange订阅特征值变化。

export const blueToothGetHeartRate = (
  deviceId: string,
  onHeartRateChange: (newHeartRate: number) => void
) => {
  Taro.onBLECharacteristicValueChange(function (characteristic) {
    const heartRateValue = getHeartRateValue(characteristic.value);
    onHeartRateChange(heartRateValue);
  });
  Taro.notifyBLECharacteristicValueChange({
    state: true, // 启用 notify 功能
    deviceId,
    serviceId: HEART_RATE_SERVICE_UUID,
    characteristicId: HEART_RATE_CHARACTERISTIC_UUID,
  });
};

此时我们已经能够获取到心率带发送的心率数据如下。

但是此时如果按照上文解析设备名称的方式,将其转化为字符串,将得到一串乱码。

所以需要根据协议文档(https://www.bluetooth.com/specifications/specs/heart-rate-service-1-0/)来解读这几个数据。

1 . 标志字段:

2 . 心率数值:

3 . RR-intreval 心率间隔:

六、总结与疑惑

至此整个蓝牙心率设备数据获取的实现就完成了,可以在使用节拍器的同时监控自身的心率数据了。

整体来说整个开发过程还是比较简单的,毕竟API文档描述的非常清晰,主要时间耗费在解读心率数据这个过程,后来知道应该从协议文档出发解读就好说了。

由于是在业余时间实现的上述能力,开发过程中存在不少疑惑没来得及研究。这里先抛两个问题出来,希望了解相关知识的同学能够不吝赐教。

1 . 在arraybuffer转16进制过程中("00" + bit.toString(16)).slice(-2);,为什么要先"00" +,然后再.slice(-2)?直接bit.toString(16)是否可行?

2 . 针对某米耳机,笔者暂时没有在服务和特征中找到电量信息相关的数据,那么手机设备又是如何获取到耳机电量的呢?

a . 猜测电池服务和特性分别是0x180F Battery service0x2A19 Battery Level,但上图耳机返回的service列表中没找到该服务。

b .

本文作者正在等待你的帮助。

参考资料

[1]蓝牙低能耗——百度百科: https://baike.baidu.com/item/%E8%93%9D%E7%89%99%E4%BD%8E%E8%83%BD%E8%80%97

[2]一文读懂蓝牙技术从 1.0 到 5.0 的前世今生: https://zhuanlan.zhihu.com/p/37717509

[3]Assigned Numbers | Bluetooth® Technology Website: https://www.bluetooth.com/specifications/assigned-numbers/

[4]BLE相关协议(GAP&GATT): https://www.jianshu.com/p/62eb2f5407c9

[5]Taro.openBluetoothAdapter(option) | Taro 文档: https://docs.taro.zone/docs/apis/device/bluetooth/openBluetoothAdapter

[6]Taro.getBluetoothDevices(option) | Taro 文档: https://docs.taro.zone/docs/apis/device/bluetooth/getBluetoothDevices

[7]Taro.onBluetoothDeviceFound(callback) | Taro 文档: https://docs.taro.zone/docs/apis/device/bluetooth/onBluetoothDeviceFound

[8]Taro.createBLEConnection(option) | Taro 文档: https://docs.taro.zone/docs/apis/device/bluetooth-ble/createBLEConnection

[9]Taro.getBLEDeviceServices(option) | Taro 文档: https://docs.taro.zone/docs/apis/device/bluetooth-ble/getBLEDeviceServices

[10]Taro.getBLEDeviceCharacteristics(option) | Taro 文档: https://docs.taro.zone/docs/apis/device/bluetooth-ble/getBLEDeviceCharacteristics

[11]Taro.readBLECharacteristicValue(option) | Taro 文档: https://docs.taro.zone/docs/apis/device/bluetooth-ble/readBLECharacteristicValue

[12]Taro.notifyBLECharacteristicValueChange(option) | Taro 文档: https://docs.taro.zone/docs/apis/device/bluetooth-ble/notifyBLECharacteristicValueChange

[13]Taro.onBLECharacteristicValueChange(callback) | Taro 文档: https://docs.taro.zone/docs/apis/device/bluetooth-ble/onBLECharacteristicValueChange

[14]Web Bluetooth API - Web APIs | MDN: https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API

[15]通过 JavaScript 与蓝牙设备通信: https://web.dev/i18n/zh/bluetooth/

[16]谈谈JS二进制:File、Blob、FileReader、ArrayBuffer、Base64 - 掘金: https://juejin.cn/post/7148254347401363463#heading-9

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8