Wechat development BLE small program preparatory work:

  1. Wechat applet Bluetooth development document
  2. Wechat development tools as for this software is written by Nw.js why does not support Linux I do not know
  3. Required Bluetooth devices (this article will be explained for BLE devices only)
  4. If you’re a fast app developer, imagine the Fast app API and if I’m right, most oF the apis have the same fast app Bluetooth document
// Quick application example 'FEE7' is the same as wechat. This serviceuUID is the Bluetooth smart light of wechat hardware platform
bluetooth.startDevicesDiscovery({
 services: ['FEE7'].success: function() {
   console.log('success')}})Copy the code

Wechat Bluetooth API

Wechat has four operations for bluetooth adapters.
// Initialize (open) the Bluetooth adapter
wx.openBluetoothAdapter 
// Disable the Bluetooth module
wx.closeBluetoothAdapter
// Get the status of the native Bluetooth adapter
wx.getBluetoothAdapterState 
// Listen for bluetooth adapter status change events
wx.onBluetoothAdapterStateChange 
Copy the code

Note: Turning on the Bluetooth device adapter is not equal to turning on the Bluetooth switch of the mobile phone. This operation is based on turning on the Bluetooth switch of wechat at the level of wechat. If the system’s Bluetooth is not turned on, Wx.

Scan and obtain surrounding devices four times
// Start searching for nearby Bluetooth peripherals
wx.startBluetoothDevicesDiscovery 
// Stop searching for nearby Bluetooth peripherals
wx.stopBluetoothDevicesDiscovery 
// Get all discovered Bluetooth devices
wx.getBluetoothDevices 
// Listen for the event that a new device was found
wx.onBluetoothDeviceFound 
Copy the code
  1. Wx. StartBluetoothDevicesDiscovery and wx. OnBluetoothDeviceFound is matched using, bluetooth communication API basically for subscription type, and the traditional HTTP communication are quite different. Search Bluetooth can be distinguished by the ServiceuUID, any service in the array will be searched.
  2. Due to service requirements, it is necessary to format Bluetooth broadcast messages and name filtering. Wx. getBluetoothDevices this API obtains original search data, so it is not recommended to use it and maintain a formatted list by itself.
  3. In low version of the IOS side WeChat will duplicate the bluetooth device, but wx. StartBluetoothDevicesDiscovery has stated in the report not repeat allowDuplicatesKey: false.
Bluetooth connection operation 2

// Connect a low-power Bluetooth device
wx.createBLEConnection 
// Disconnect from the low-power Bluetooth device
wx.closeBLEConnection 
Copy the code
  1. It is not recommended to use the wx. CloseBluetoothAdapter to directly close the Bluetooth module. It is simple, rough and quick, but each time you operate the Bluetooth device, you need to call to open the adapter first.
Read and write 8 BLE eigenvalue operations

// Get connected devices based on the UUID
wx.getConnectedBluetoothDevices 
// Get all bluetooth device services.
wx.getBLEDeviceServices 
// Get all characteristic values of bluetooth devices
wx.getBLEDeviceCharacteristics  
// Reads the binary data value of the eigenvalue of the low-power Bluetooth device
wx.readBLECharacteristicValue  
// Writes binary data to the low-power Bluetooth device eigenvalues
wx.writeBLECharacteristicValue 
// Enable the notify function when the eigenvalues of bluetooth low-power devices change
wx.notifyBLECharacteristicValueChange  
// Listen for changes in eigenvalues of low-power Bluetooth devices
wx.onBLECharacteristicValueChange
// Listen for changes in connection status of low-power Bluetooth connections
wx.onBLEConnectionStateChange 

Copy the code

Bluetooth Serviceuids are generally used to distinguish between devices. Basically, each ID corresponds to a BLE Bluetooth product. Each serviceuUID corresponds to a different characteristic, These characteristic usually contains the read/write/write/indicate one or more of the attributes (specific see the bluetooth protocol) within the small program through service and characteristic combination to listen or sending a message, A listener can be successfully invoked only when the features of the device support notify or indicate, and binary data can be written only when the features of the device support read.

Bluetooth Development process

Search for Bluetooth devices
   // part 1.
   // Disable the Bluetooth module to prevent the bluetooth cache from being turned off and on again, just in case
      wx.closeBluetoothAdapter({
        // The interface calls the finished callback function
        successfunction ({
          // Initialize the Bluetooth module
          wx.openBluetoothAdapter({
            successfunction ({
              // Getting the native Bluetooth adapter status is rarely used
              // wx.getBluetoothAdapterState({
              // success: function (res) {
              // console.log(res)
              / /},
              // })
              // Start searching for nearby Bluetooth peripherals
              wx.startBluetoothDevicesDiscovery({
                // It is not allowed to report devices repeatedly (ios of early version may fail, which is manifested as different RSSI signal strength of the same device)
                allowDuplicatesKeyfalse.// Report frequency of bluetooth search. The device is reported every 120 milliseconds
                interval120.// For business requirements, our equipment contains these two services. If either one is included here, it can be searched
                services: ['0000FFC0'.'0000FFF0'].successfunction ({
                 //do somthing... The general formula is used to initialize some properties}})},// Call a popup on failure to tell the user that Bluetooth is not turned on
            failfunction ({
              wx.showModal({
                title'tip'.content'Please check whether bluetooth is on'.showCancelfalse.successfunction ({
                  // do something},})},})// Part 2. This part is the focus of the subscription operation after the device is found
  
 // Find the new Bluetooth device
    // Accept an OBJ containing the device found within 120 milliseconds
    wx.onBluetoothDeviceFound(function (obj{
      // This list is an unfiltered list
      const list = []
      // Visible after filtering
      const viewList=[]
     // The device in the object is the real body
      const {
        devices
      } = obj
      for (let device of devices) {
      Obtain the MAC address from the broadcast value. The device type is used for ios devices. This operation requires the device firmware to write a MAC address
      const bleType = getType(device)
        // Resolve the broadcast packet according to the protocol
        if (device.advertisData) {
          // Parse different protocols for different devices
          device.advertisData = formatterAdvertis(device.advertisData, bleType)
        } 
        device.bleType = bleType
       
       list.push(device)
       // Whether the filter device is visible
        if (deviceCanView(device)) {
         viewList.push(device)
        }
      }
      // Because 120 ms setData call once on some low-end models is too slow here to do an interval, because the early data volume is small, but also convenient home loading display, so the second and fifth time also refresh, otherwise every 1200 ms brush a new time.
      if (that.data.cnt % 10= =0| | [2.5].includes(that.data.cnt)) {
        that.setData({
          viewList: [...that.data.viewList,...viewList]
        })
      }
      / / count
      that.data.cnt++
      // Direct assignment does not change the page data and assigns unfiltered data
      that.data.devicesList = [...that.data.devicesList, ...list]
    })
    
    
// part 3.

// Listen for Bluetooth disconnection to reset some properties
wx.onBLEConnectionStateChange(function (res{
        // Operation after disconnection
        if(! res.connected) {// dosomthing
          Dialog.close()
          wx.showToast({
            title'Bluetooth is disconnected'.icon'success'.duration500,})}})Copy the code
Connect bluetooth device
 // Part 1. Connect the device and listen to notify
 // Sets the maximum transmission unit (MTU)
 // The data is too long before the flow control, so it needs to be set. It only works for Android devices, and ios devices will automatically negotiate
  wx.setBLEMTU({
    // This id is the UUID of the Apple device the MAC address of the Android device
    deviceId: device.deviceId,
    mtu160.success(res) = > {
      console.log("setBLEMTU success")},fail(res) = > {
      console.log("setBLEMTU fail", res)
    }
  });
  wx.getBLEDeviceServices({
   // This id is the UUID of the Apple device the MAC address of the Android device
    deviceId: device.deviceId,
    successfunction (serviceRes{
      // Each device has one or more services, so we get a list of services to filter as needed
      const services = serviceRes.services.filter(item= > item.uuid.startsWith('0000FFF0'))0]
      wx.getBLEDeviceCharacteristics({
        deviceId: device.deviceId,
        serviceId: services.uuid,
        successfunction (characterRes{
           // The eigenvalues are the same. Each service contains a different eigenvalue and gets a list
          // Write eigenvalue This eigenvalue is used to write binary data to the device
          const characteristics = characterRes.characteristics.filter(item= > item.uuid.startsWith('0000FFF1'))0]
          // notify Eigenvalue This eigenvalue is used to listen on notify
          const notifyCharacteristics = characterRes.characteristics.filter(item= > item.uuid.startsWith('0000FFF4'))0]
         // Start broadcast
          wx.notifyBLECharacteristicValueChange({
            statetrue.deviceId: device.deviceId,
            serviceId: services.uuid,
            characteristicId: notifyCharacteristics.uuid,
            successfunction (_{
              // dosomething...
            },
            failfunction (e{
              console.log('Failed to enable notify', e)
            },
          })
        },
      })
    },
  })


// Part 2. Writing binary data to the device
 wx.writeBLECharacteristicValue({
     // This id is the UUID of the Apple device the MAC address of the Android device
    deviceId: device.deviceId,
    // The required eigenvalues
    serviceId: services.uuid,
    // The characteristic value of the device used for notify
    characteristicId: characteristics.uuid,
    // ArrayBuffers are generally packaged binary protocol packages
    value: buffer,
    successfunction (res{
      if (toast) {
        wx.showToast({
          title'Sent successfully'.icon'success'.duration500,}}}),failfunction (res{
      wx.showToast({
        title'Send failed'.icon'error'.duration500,}}),complete: callBack
  })


Copy the code

Bluetooth search, connect, write, and listen operations are all listed above, and some, such as read operations, are not listed because they are not involved in actual development.

Supplement some basic knowledge 1. Wechat BLE Bluetooth communication 2. Low power Bluetooth protocol interpretation 3