【微信小程序】蓝牙连接 流程

小程序蓝牙低功耗蓝牙主要有以下几个步骤以及会用到的接口

1,打开适配器(openBluetoothAdapter)
2,监听蓝牙适配器状态变化(onBluetoothAdapterStateChange)
3,搜索蓝牙(startBluetoothDevicesDiscovery)
4,寻找到蓝牙新设备(onBluetoothDeviceFound)
5,连接蓝牙(createBLEConnection)
6,停止搜索搜索蓝牙(stopBluetoothDevicesDiscovery)
7,监听蓝牙连接状态(onBLEConnectionStateChange)
8,获取蓝牙设备所有服务(getBLEDeviceServices),9,获取蓝牙设备某个服务中所有特征值(getBLEDeviceCharacteristics)
10,开启notify(notifyBLECharacteristicValueChange)
11,监听低功耗蓝牙设备的特征值变化(onBLECharacteristicValueChange)
12,蓝牙设备特征值中写入二进制数据(writeBLECharacteristicValue),
13,断开蓝牙(closeBLEConnection)
14,关闭蓝牙模块(closeBluetoothAdapter)

1.打开适配器

这是官方关于打开适配器的文档 点击这里
详细步骤:先判断当前微信版本是否支持打开适配器,过程需监听适配器的状态,打开适配器后再去判断手机蓝牙是否打开,手机蓝牙也打开后,去搜索蓝牙设备

代码如下

openBluetoothAdapterBefore: function() {
  var that = this;
  if (!wx.openBluetoothAdapter) {
    wx.showModal({
      title: '提示',
      showCancel: false,
      content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。',
    })
    return;
  }
// 初始化小程序蓝牙模块
  wx.openBluetoothAdapter({
    success: (res) => {
      console.log('openBluetoothAdapter success', res)
      that.startBluetoothDevicesDiscovery() //搜索蓝牙
    },
    fail: (res) => {
      if (res.errCode === 10001) {
        wx.showToast({
          title: '请开启手机蓝牙',
          duration: 5000
        })
        // 监听蓝牙适配器状态变化事件
        wx.onBluetoothAdapterStateChange(function(res) {
          console.log('onBluetoothAdapterStateChange', res)
          if (res.available) {
            that.startBluetoothDevicesDiscovery() //搜索蓝牙
          }
        })
      }
    }
  })
}

2.监听蓝牙适配器状态变化

这是官方的监听蓝牙适配器接口文档 点击这里

详细介绍:在打开适配器后,会出现手机蓝牙未打开的情况,这时就需要去监听适配器的状态变化,以便于手机蓝牙打开后,去搜索蓝牙

wx.onBluetoothAdapterStateChange(function(res) {
   console.log('onBluetoothAdapterStateChange', res)
   if (res.available) {
     that.startBluetoothDevicesDiscovery()
   }
 })

3. 搜索蓝牙

这是官方的搜索蓝牙接口文档 点击这里

/**开始搜寻附近的蓝牙外围设备 */
startBluetoothDevicesDiscovery: function() {
  var that = this;
  wx.startBluetoothDevicesDiscovery({
    // services: ['FEE7'],
    allowDuplicatesKey: false,//不允许重复上报同一设备
    success: (res) => {
      console.log('startBluetoothDevicesDiscovery success', res)
      wx.showLoading({
        title: '搜索蓝牙...',
      })
      that.onBluetoothDeviceFound() //连接蓝牙
    },
  })
}

4.寻找到蓝牙新设备

这是官方的找蓝牙新设备的接口文档 点击这里

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i
    }
  }
  return -1
}
/** 监听寻找到新设备的事件 */
onBluetoothDeviceFound: function() {
  var that = this;
  var devices = data.devices;
  var item = [];
  console.log("监听寻找到新设备:",devices)
  wx.onBluetoothDeviceFound((res) => {

    res.devices.forEach(device => {
      if (!device.name && !device.localName) {
        return
      }
      const foundDevices = devices
      const idx = inArray(foundDevices, 'deviceId', device.deviceId)
      const data = {}

      if (idx === -1) {
      //这里可以写连接此设备的蓝牙设备的条件
        that.connectBle(devices.deviceId)
      } else {
        data[`devices[${idx}]`] = device
        let ballType = device.localName.substring(0, 1);
      }
    })
  })
}


寻找已经添加的蓝牙设备

  /** 监听寻找到已添加的蓝牙设备*/
  onBleDeviceFound: function() {
    var that = this;
    wx.getBluetoothDevices({
      success: function(res) {
        console.log("寻找设备成功:", res)
        let devices = res.devices
        for (let i = 0; i < devices.length; i++) {
        //这里可以写连接此设备的蓝牙设备的条件
        that.connectBle(devices[i].deviceId)
      },
      fail: function(res) {
        console.log("搜索蓝牙设备失败", res)
      }
    });
  },


注意:若使用该接口找不到之前已经连接过的蓝牙设备,可以用这个【getBluetoothDevices】接口,找到已经添加过的蓝牙设备去连接

5.连接蓝牙

这是官方连接蓝牙接口 点击这里

/**连接低功耗蓝牙设备 */
  connectBle: function(deviceId) {
    var that = this;
    const name = that.data.deviceName
    wx.showLoading({
      title: '连接中'
    })
    wx.createBLEConnection({
      deviceId,
      timeout: 5000, //设置超时时间
      success: function(res) {
       wx.showLoading({
        title: '连接成功',
         icon: 'success',
       })
        console.log("连接蓝牙成功", res)
        that.setData({
          name,
          deviceId,
          btnName: "已连接",
        })
        that.onBleConnectState(); //监听蓝牙连接状态
        that.getBLEDeviceServices(deviceId); //获取蓝牙设备所有 service(服务)
      },
      fail: function(res) {
        console.log("连接失败", res);
        if (res.errCode === 10003) { //连接失败,有可能是蓝牙强度比较低
          that.onBleDeviceFound() //获取已经添加的蓝牙设备
        } else if (res.errCode === 10012) { //连接过程,低功耗蓝牙设备已关闭
          wx.showLoading({
            title: '请打开蓝牙设备'
          })
          that.onBleDeviceFound() //获取已经添加的蓝牙设备
        } 
      },

      complete() {
        setTimeout(function() { //延迟两秒执行,
          wx.hideLoading()
        }, 2000)
      }
    })
  },

6.停止搜索搜索蓝牙

这里是官方停止搜索蓝牙的文档 点击这里
代码:

  /**停止搜寻附近的蓝牙外围设备 */
  stopBluetoothDevicesDiscovery: function() {
    wx.stopBluetoothDevicesDiscovery({
      success:(res)=>{
        console.log("停止搜索蓝牙成功:",res)
      },
      fail:(res)=>{
        console.log("停止搜索蓝牙失败:",res)
      }
    })
  },

7.监听蓝牙连接状态

官方的监听蓝牙连接状态接口文档 点击这里

代码:

  onBleConnectState: function() {
    let that = this;
    wx.onBLEConnectionStateChange(function(res) {
      console.log("蓝牙连接状态:", res.connected);
      if (!res.connected) {
        that.onBleDeviceFound; //自动连接
      }
    })
  },

8. 获取蓝牙设备所有服务

官方获取蓝牙设备所有服务接口文档 点击这里
代码:

  /**获取蓝牙设备所有 service(服务) */
  getBLEDeviceServices: function(deviceId) {
    var that = this;
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        console.log("获取蓝牙设备所有服务成功", res)
        for (let i = 0; i < res.services.length; i++) {
          let uuid_slice = res.services[i].uuid.slice(4, 8);
          if (uuid_slice != "180A" && uuid_slice != "1800" && uuid_slice != "1801" && uuid_slice != "1802") {
            if (res.services[i].isPrimary) {
              console.log("serviceId:" + res.services[i].uuid)
              that.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
              return
            }
          }
        }
      },
      fail:(res)=>{
        console.log("获取蓝牙设备所有服务失败:",res)
      }
    })
  },

9. 获取蓝牙设备某个服务中所有特征值

官方获取特征值的接口文档 点击这里
详细介绍:分别获取对蓝牙进行读、写、notify的特征值,便于接下来对蓝牙进行读、写操作

代码:

 /**蓝牙设备characteristic(特征值)信息 */
  getBLEDeviceCharacteristics: function(deviceId, serviceId) {
    var that = this;
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          const item = res.characteristics[i]
            //读
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          //写
          if (item.properties.write) {
            if (item.uuid === '6E400002-B5A3-F393-E0A9-E50E24DCCA9E') {
              that.setData({
                deviceId: deviceId,
                serviceId: serviceId,
                writeCharacteristicId: item.uuid,
              });
            }
          }
            //notify
          if (item.properties.notify || item.properties.indicate) {
            that.setData({
              deviceId: deviceId,
              serviceId: serviceId,
              characteristicId: item.uuid
            })
            that.openNotify()
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
  },

10. 开启notify

官方开启notify的接口文档 点击这里
代码:


  /** 开启notify */
  openNotify: function() {
    var that = this;
    wx.notifyBLECharacteristicValueChange({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.characteristicId,
      state: true,
      success: function(res) {
        that.onBLECharacteristicValueChange(); //监听返回值变化
        // 写入数据 (同步数据)
        that.writeData(0xa0, timestamp);
      },
      fail: function(res) {
        console.log("开启notify失败", res);
      }
    })
  },

11. 监听低功耗蓝牙设备的特征值变化

官方的监听蓝牙设备特征值的接口文档 点击这里
代码:

  /** 监听返回值变化 */
  onBLECharacteristicValueChange: function() {
    var that = this;
    wx.onBLECharacteristicValueChange(function(res) {
      //对数据进行操作
    })
  },

12. 蓝牙设备特征值中写入二进制数据

官方写入数据的接口文档 点击这里
详细介绍:
代码:

/** 写入二进制数据*/
  writeData: function(cmd, values) {
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(16)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, cmd) //命令
    dataView.setUint32(1, values) //向蓝牙发送命令参数

    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.writeCharacteristicId,
      value: buffer,
      success: function(res) {
        console.log('写入蓝牙特征值成功:', res.errMsg);
      },
      fail: function(res) {
        console.log('写入蓝牙特征值失败:', res.errMsg);
      },
    })
  },

13. 断开蓝牙

官方打开蓝牙接口文档 点击这里
详细介绍:断开蓝牙一般用在主动断开蓝牙
代码:

  /**断开与低功耗蓝牙设备的连接 */
  closeBLEConnection: function() {
    wx.closeBLEConnection({
      success: function(res) {
        console.log("断开蓝牙成功", res)
      },
      fail: function(res) {
        console.log("断开蓝牙失败", res)
      }
    })
  },

14. 关闭蓝牙模块

官方关闭蓝牙模块的接口文档 点击这里
详细介绍:一般退出当前连接蓝牙页面时,就可关闭蓝牙模块
代码:

  /**关闭蓝牙模块,使其进入未初始化状态 */
  closeBluetoothAdapter: function() {
    wx.closeBluetoothAdapter({
      success: (res) => {
        console.log("关闭适配器成功:", res)
      },
      fail: (res) => {
        console.log("关闭适配器失败:", res)
      }
    })
  },

以上即 微信小程序蓝牙连接过程。。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容