1. 程式人生 > 實用技巧 >微信小程式藍芽

微信小程式藍芽

初始化藍芽模組

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
    },