微信小程序使用蓝牙连接设备流程

微信小程序使用蓝牙连接设备流程

小程序使用蓝牙连接设备介绍
使用到的api

流程:

  1. 初始化蓝牙模块 wx.openBluetoothAdapter
 wx.openBluetoothAdapter({
    
      success: function (res) {
   
        wx.showToast({
   
          title: '初始化成功',
          icon: 'success',
          duration: 800
        })
        //搜索设备
        self.findMachine(); 
      },
      fail: function (res) {
    //手机上的蓝牙没有打开
        wx.showToast({
   
          title: '请开启蓝牙',
          icon: 'error',
          duration: 1500
        })
      }
    })
  1. 搜索周边蓝牙设备 wx.startBluetoothDevicesDiscovery
findMachine() {
   
    var that = this
    //此操作比较耗费系统资源,请在搜索到需要的设备后及时调用 wx.stopBluetoothDevicesDiscovery 停止搜索。
    wx.startBluetoothDevicesDiscovery({
   
      allowDuplicatesKey: false,
      interval: 0,
      success: function (res) {
   
        console.log(res)
        wx.showLoading({
   
          title: '正在搜索设备',
        })
        //查找设备
        that.getMachine()
      }
    })
  },
  1. 找到要连接的设备(根据名称查找) wx.getBluetoothDevices
  getMachine() {
   
    var that = this
    wx.getBluetoothDevices({
   
      success: function (res) {
   
        console.log(res)
        wx.hideLoading();
        var list = res.devices;
        if (list.length != 0) {
   
          var name = "设备名称"

你可能感兴趣的:(微信小程序,小程序)