微信小程序-蓝牙 - zhishiyv

微信小程序-蓝牙

这篇主要讲在微信小程序项目开发过程中关于蓝牙的应用

1 openBluetoothAdapter 初始化蓝牙模块

 wx.openBluetoothAdapter({
        success: res => {
            // 初始化蓝牙适配器成功后续操作
        },
        fail: err => {
            if (err.state && err.state == 3) {
                wx.showModal({
                    content: \'请在iPhone的“设置-隐私-蓝牙”选项中,允许微信访问你的蓝牙\',
                    confirmText: \'好\',
                    showCancel: false
                })
            } else {
                wx.showModal({
                    content: \'请开启你的蓝牙使用权限\',
                    confirmText: \'好\',
                    showCancel: false
                })
            }
        }
    });

(注:ios手机在fail回调函数中若返回state参数,state=3; IOS手机未授权微信使用蓝牙,到手机设置功能里授权微信的蓝牙使用权限, 其他state参数含义,请浏览官方文档。)

2. 开始搜寻附近的蓝牙外围设备。此操作比较耗费系统资源,请在搜索并连接到设备后调用 wx.stopBluetoothDevicesDiscovery 方法停止搜索。

wx.startBluetoothDevicesDiscovery({
        success: function(res) {
              // success 返回结果处理
        }
});

3 wx.onBluetoothDeviceFound(function callback) 监听寻找到新设备的事件

  wx.onBluetoothDeviceFound(function(res) {
       for (let i = 0; i < res.devices.length; i++) {
              //  对监听过程中获取到的蓝牙设备进行操作
       }
  }

(注:

有种说法是: wx.onBluetoothDeviceFound这个方法只能找到新的蓝牙设备,之前连接过的在部分安卓机型上,

不算做新的蓝牙设备,因此重新连接搜索不到

解决办法:

关闭蓝牙连接,也要关闭蓝牙设备,否则安卓下再次进入会搜索不到设备,除非关闭小程序进程再进才可以,

IOS不受影响

笔者未证实这个说法

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

   wx.getBluetoothDevices({
        success: function(res) {
            console.log(\'getBluetoothDevices\', res)
            //8s内未搜索到设备,关闭搜索,关闭蓝牙模块
            setTimeout(function() {
                if (!matchingFlag) {
                    wx.stopBluetoothDevicesDiscovery();
                    wx.closeBluetoothAdapter();
                    callback({
                        code: -1
                    })
                }
            }, 8000)
        }
    })

5 连接 蓝牙设备

连接低功耗蓝牙设备。直接传入搜索获取的 deviceId 直接尝试连接该设备。
...
wx.stopBluetoothDevicesDiscovery()
...
wx.createBLEConnection({ deviceId: xxx.deviceId, success: function(res) { console.log(\'连接成功:\', res); connectedDeviceId = xxx.deviceId callback({ code: 0 }) }, fail: function(err) { console.log("调用失败", err); if (xxx.connecttimes >= 2) { flag= true callback({ code: -1 }) }
else { let timeout = setTimeout(function() { xxx.connecttimes = xxx.connecttimes + 1; // 重新连接 clearTimeout(timeout); }, 1000); } }, complete: function() { if (!!connectedDeviceId) { console.log(\'已连接设备ID:\' + connectedDeviceId); } } });
(注 蓝牙设备连接成功后,我们有一个必须要做的操作就是停止蓝牙搜索设备)

6 wx.getBLEDeviceServices 获取已连接蓝牙的所有服务

wx.getBLEDeviceServices({
  deviceId,
  success (res) {
       // console.log(\'device services:\', res.services)
  }
})

7 获取蓝牙设备服务中的特征值

wx.getBLEDeviceCharacteristics({
     // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取 
      deviceId: connectedDeviceId,
     // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取 
      serviceId: serviceId,

      success: function(res) {
           console.log(res);
           // 获取mesh读写服务特征值
            for (var i = 0; i < res.characteristics.length; i++) {
                 if (res.characteristics[i].uuid.indexOf(\'xxx\') != -1) {
                         //注意characteristic(特征值)信息,properties对象
                         notifyServicweId = serviceId
// 设备特征值的UUID notifyCharacteristicsId = res.characteristics[i].uuid
readServicweId = serviceId readCharacteristicsId = res.characteristics[i].uuid } if (res.characteristics[i].uuid.indexOf(\'xxx\') != -1) { writeServicweId = serviceId writeCharacteristicsId = res.characteristics[i].uuid } } }, fail: function() { console.log("获取连接设备的所有特征值 失败返回信息:", res); flag= false callback2({ code: -1 }) }, complete: function() { console.log("complete!"); } });

8 启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。

注意:必须设备的特征值支持 notify 或者 indicate 才可以成功调用。
另外,必须先启用 notifyBLECharacteristicValueChange 才能监听到设备 characteristicValueChange 事件
wx.notifyBLECharacteristicValueChange({
    state: true, // 启用 notify 功能
     // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  
deviceId, // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId, // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId,
success (res) { console.log(\'notifyBLECharacteristicValueChange success\', res.errMsg) } })

9 监听低功耗蓝牙设备的特征值变化事件 接收蓝牙返回消息

  function ab2hex(buffer) {
     let hexArr = Array.prototype.map.call(
           new Uint8Array(buffer),
           function(bit) {
                return (\'00\' + bit.toString(16)).slice(-2)
           }
     )
     return hexArr.join(\'\');
  }
  
  wx.onBLECharacteristicValueChange(function(res) {
         console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
         console.log(ab2hex(res.value))
  })

10 向低功耗蓝牙设备特征值中写入二进制数据。(注意:必须设备的特征值支持 write 才可以成功调用)

 // 向蓝牙设备发送一个0x00的16进制数据
 let buffer = new ArrayBuffer(1)
 let dataView = new DataView(buffer)
 dataView.setUint8(0, 0)

 wx.writeBLECharacteristicValue({
     // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
     deviceId,
     // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
     serviceId,
     // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
     characteristicId,
     // 这里的value是ArrayBuffer类型
     value: buffer,
     success (res) {
        console.log(\'writeBLECharacteristicValue success\', res.errMsg)
     }
  })

11 断开与低功耗蓝牙设备的连接

  wx.closeBLEConnection({
    deviceId,
    success (res) {
       console.log(res)
    }
  })

12 监听低功耗蓝牙连接状态的改变事件。包括开发者主动连接或断开连接,设备丢失,连接异常断开等等

  wx.onBLEConnectionStateChange(function(res) {
     // 该方法回调中可以用于处理连接意外断开等异常情况
     console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
  })