微信小程序蓝牙

初始化蓝牙模块

openBluetoothAdapter() {
      wx.openBluetoothAdapter({
        success: (res) => {
          wx.showToast({
            title: '初始化成功',
          })
        },
        fail: (res) => {
          wx.showToast({
            title: '初始化失败',
            icon: 'none'
          })
        }
      })
    },

开始搜索蓝牙模块

startBluetoothDevicesDiscovery() {
      if (this._discoveryStarted) {
        return
      }
      this._discoveryStarted = true
      wx.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: true,
        success: (res) => {
          this.onBluetoothDeviceFound()
        },
        fail: (res) => {
          wx.showToast({
            title: '扫描失败',
            icon: 'none'
          })
        }
      })
    },

搜索蓝牙设备

onBluetoothDeviceFound() {
      wx.onBluetoothDeviceFound((res) => {
        res.devices.forEach(device => {
          if (!device.name && !device.localName) {
            return
          }
          let foundDevices = this.data.devices
          let idx = inArray(foundDevices, 'deviceId', device.deviceId)
          let data = {}
          if (idx === -1) {
            data[`devices[${foundDevices.length}]`] = device
          } else {
            data[`devices[${idx}]`] = device
          }
          this.setData(data)
        })
      })
    },

连接蓝牙设备

createBLEConnection(e) {
      let ds = e.currentTarget.dataset
      app.globalData.deviceId = ds.deviceId;
      app.globalData.deviceName = ds.name;
      let deviceId = ds.deviceId;
      let name = app.globalData.deviceName;
      //创建低功耗蓝牙连接
      wx.showLoading({
        title: '正在连接···',
        icon: 'loading',
      })
      wx.createBLEConnection({
        deviceId,
        success: (res) => {
          wx.showToast({
            title: '连接设备成功',
          })
          this.setData({
            connected: true,
            show: true,
            name: name,
            deviceId: deviceId,
          })
          app.globalData.show = "true"
          app.globalData.connected = "true"
          //获取所有服务
          wx.getBLEDeviceServices({
            deviceId,
            success: (res) => {
              this.setData({
                res2: res
              })
            }
          })
          wx.navigateBack({
            delta: 1
          })
        },
        fail() {
          wx.showToast({
            title: '连接设备失败',
            icon: 'none'
          })
        }
      })
    },

停止搜寻附近的蓝牙外围设备

closeBLEConnection: function (e) {
      wx.closeBLEConnection({
        deviceId: this.data.deviceId
      })
      this.setData({
        connected: false,
        chs: [],
        canWrite: false,
        show: false,
      })
      app.globalData.connected = false
      app.globalData.show = false
    },

关闭蓝牙模块

closeBluetoothAdapter() {
      wx.closeBluetoothAdapter()
      this._discoveryStarted = false
    },
原文地址:https://www.cnblogs.com/xz233/p/13964877.html