小程序中,iOS设备获取蓝牙设备的Mac地址

遇到的问题

在使用蓝牙的过程中,我们需要获取蓝牙设备的Mac地址。在Android设备上,onBluetoothDeviceFound方法中,deviceId 是蓝牙设备的Mac地址。而在 iOS设备上,deviceId则是蓝牙设备的uuid。我们想要在iOS设备上获取Mac地址,就需要自己想办法。

解决的方法

通过查阅一些相关资料,发现有些蓝牙设备有180A这个服务id,该服务id中的2A23特征值可以获取蓝牙设备的Mac地址。具体操作参考下面的代码:

  function array2String(buffer) {
    let hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return `${hexArr[7]}:${hexArr[6]}:${hexArr[5]}:${hexArr[2]}:${hexArr[1]}:${hexArr[0]}`
  }
// 连接蓝牙
wx.createBLEConnection({
  deviceId,
  success: res => {
    // 获取服务id
    wx.getBLEDeviceServices({
      deviceId,
      success: res => {
        let serviceId = ''
        for (let i = 0, len = res.services.length; i < len; i++) {
          // 使用包含 180A 的服务id
          if (~res.services[i].uuid.indexOf('180A')) {
            serviceId = res.services[i].uuid
            // 获取对应的特征值
            wx.getBLEDeviceCharacteristics({
              deviceId,
              serviceId,
              success: res => {
                let characteristicId = ''
                for (let i = 0, len = res.characteristics.length; i < len; i++) {
                  // 使用含有 2A23 对应的特征值
                  if (~res.characteristics[i].uuid.indexOf('2A23')) {
                    characteristicId = res.characteristics[i].uuid
                  }
                }
                wx.readBLECharacteristicValue({
                  deviceId,
                  serviceId,
                  characteristicId,
                  success: res => {
                    console.log('mac read ----------', res)
                  }
                })
                wx.notifyBLECharacteristicValueChange({
                  deviceId,
                  serviceId,
                  characteristicId,
                  state: true,
                })
                wx.onBLECharacteristicValueChange(function (characteristic) {
                  // 当特征值是查询 Mac 地址时
                  if (~characteristic.characteristicId.indexOf('2A23')) {
                    let macInfo = (array2String(characteristic.value)).toUpperCase()
                    console.log('mac info -----------', macInfo)
                  }
                })
              }
            })
          }
        }
      }
    })
  }
})

后续

当获取到蓝牙设备Mac地址后,我们一般还是要继续使用蓝牙的。这个时候需要重新获取蓝牙设备的服务id,以及新的特征值。

wx.getBLEDeviceCharacteristics({
  deviceId,
  // 新的服务id, 通过 getBLEDeviceServices 获取
  serviceId: newServiceId,
  success: res => {
    wx.notifyBLECharacteristicValueChange({
      state: true,
      deviceId,
      serviceId: newServiceId,
      // 新的特征值
      characteristicId: newCharacteristicId
    })
    // 监听低功耗蓝牙连接的错误事件
    wx.onBLEConnectionStateChange(res => { })
  }
})
posted @ 2019-05-18 15:28  yangrenmu  阅读(6337)  评论(1编辑  收藏  举报