Initializing Bluetooth

Before using Bluetooth, you need to initialize The Bluetooth (openBluetoothAdapter) first, then you can call various bluetooth apis. Initial state is divided into two kinds: initial success: when can go to search the bluetooth devices (startBluetoothDevicesDiscovery). Initialization failed: this time need to prompt the user to open the bluetooth, monitor the state of the bluetooth (onBluetoothAdapterStateChange) at the same time, while bluetooth enabled, to search for equipment.

  openBluetoothAdapter() {
    const that = this
    wx.openBluetoothAdapter({
      success: (res) = > {
        console.log('openBluetoothAdapter success', res)
        // Initialization is successful, go to search the device
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) = > {
        if (res.errCode === 10001) {
          // Bluetooth is not enabled
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              that.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  }
Copy the code

Search for Bluetooth devices

Began to search nearby bluetooth devices (startBluetoothDevicesDiscovery), the operation is consuming resources, advice after the connection to the bluetooth device, manually stop the search.

  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    // Start searching for Bluetooth devices. AllowDuplicatesKey will search for the same device repeatedly
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true.success: (res) = > {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  }
Copy the code

Obtaining bluetooth Devices

There are two apis for obtaining bluetooth devices.

  • onBluetoothDeviceFound: Get the newly discovered device, willstartBluetoothDevicesDiscoveryIn theallowDuplicatesKeySet totrue, the method repeatedly reports the same Bluetooth device.
  • getBluetoothDevices: Obtains the list of discovered Bluetooth devices. The number of Bluetooth devices obtained by this method is related to the search time. After the search for Bluetooth devices starts, this method is invoked after a period of time.
  onBluetoothDeviceFound() {
    // Get the newly discovered Bluetooth device
    wx.onBluetoothDeviceFound((res) = > {
      res.devices.forEach(device= > {
        if(! device.name && ! device.localName) {return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === - 1) {
          data[`devices[${foundDevices.length}] `] = device
        } else {
          data[`devices[${idx}] `] = device
        }
        this.setData(data)
      })
    })
  }
Copy the code

Connect bluetooth device

CreateBLEConnection: Connect the Bluetooth device, basically at this point, the Bluetooth device is connected. To avoid multiple connection instances for a device, closeBLEConnection is usually called in pairs. After the connection is successful, you need to call stopBluetoothDevicesDiscovery, stop search the bluetooth.

  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    // Start to connect bluetooth device
    wx.createBLEConnection({
      deviceId,
      success: (res) = > {
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      }
    })
    // Stop searching for Bluetooth after the bluetooth device is connected.
    this.stopBluetoothDevicesDiscovery()
  }
Copy the code

Stop searching for Bluetooth devices

StopBluetoothDevicesDiscovery: after the bluetooth connection is successful, need to stop search the bluetooth devices.

  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  }
Copy the code

Monitor the connection status of bluetooth devices

OnBLEConnectionStateChange: monitored bluetooth connection status, including the loss of a bluetooth device, disconnect, can be processed in this method the abnormal situation happened after connection.

wx.onBLEConnectionStateChange(function (res) {
  // This method can be used to handle exceptions such as unexpected disconnections
  console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)})Copy the code

Obtain bluetooth device services

After connecting to the Bluetooth device, we still want to communicate with the Bluetooth device, or read data from the Bluetooth device, or write data to the Bluetooth device. First, you need to obtain the service information of the Bluetooth device.

  getBLEDeviceServices(deviceId) {
    // Get the service information of the Bluetooth device.
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) = > {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            // Get the eigenvalue of the Bluetooth device
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return}}}})}Copy the code

Get the eigenvalue of the Bluetooth device

GetBLEDeviceCharacteristics: according to the bluetooth service information, can communicate with bluetooth for eigenvalues. Generally, the characteristic values of notify or indicate are true and read or write are true.

Enable notification on bluetooth devices

NotifyBLECharacteristicValueChange: enable notifications of bluetooth devices, this method requires the eigenvalues of the bluetooth device notify or indicate to true. Data changes of bluetooth devices can be monitored only when this function is enabled on the Bluetooth device.

Get bluetooth device data

OnBLECharacteristicValueChange: listening to the bluetooth device data changes, when a bluetooth device data changes, can obtain the data after the corresponding change. You need to enable the notification function of bluetooth device to use.

Write data to bluetooth device

WriteBLECharacteristicValue: write data to the bluetooth device, it is necessary to characteristic values of the write is true.

  // Get the eigenvalue of the Bluetooth device
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) = > {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            // Read bluetooth device data
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            // Write data to bluetooth device
            this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            // Enable the notification function of the Bluetooth device to listen to the changes of bluetooth data
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // Monitor bluetooth device data changes
    wx.onBLECharacteristicValueChange((characteristic) = > {
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (idx === - 1) {
        data[`chs[The ${this.data.chs.length}] `] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}] `] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      this.setData(data)
    })
  }
  // Write data to bluetooth device
  writeBLECharacteristicValue() {
    // Send a 0x00 hexadecimal data to the Bluetooth device
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0.Math.random() * 255 | 0)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: buffer,
    })
  }
Copy the code

Disconnect the Bluetooth device

CloseBLEConnection: Disconnect from the Bluetooth device

  closeBLEConnection() {
    // Disconnect the Bluetooth device
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false.chs: [].canWrite: false})},Copy the code

Disabling the Bluetooth Module

CloseBluetoothAdapter: When bluetooth is finished, close the Bluetooth module and release system resources.

// Disable the Bluetooth module
wx.closeBluetoothAdapter({
  success(res) {
    console.log(res)
  }
})
Copy the code