Summary of applet Bluetooth

Posted by Aptana on Fri, 10 May 2019 09:58:03 +0200

 

Question:

Recently I have made a small program involving Bluetooth module, make a summary, make a record of your growth, if you can help you, it would be great;

1. Applet Bluetooth Search Can Search Mobile Devices
2. How to determine if Bluetooth is on or off
3. Search for specified devices
4. The deviceId obtained on the developer tools and Android is the device MAC address, and the device uuid on the iOS.Therefore deviceId cannot be hard coded into code.
How to Connect Bluetooth
5. Device Services How to Select All Services
6. What does the device characteristic do and how to use it?
7. Turn on notify
8. Write data

1. Applet Bluetooth Search Can Search Mobile Devices

No!!!
Applet Bluetooth only supports BLE low power Bluetooth
What is a low power Bluetooth device?Baidu once, you know (^^) Hee-hee

2. How to judge if Bluetooth is on

Use wx.openBluetooth Adapter (OBJECT) to judge if Bluetooth is available
If the user's Bluetooth switch is not turned on or the mobile phone does not support Bluetooth function, calling wx.openBluetooth Adapter will return an error indicating that the mobile phone's Bluetooth function is not available.

wx.openBluetoothAdapter({
  success: function (res) {
    console.log(res)
  },
  fail: function (res) {
      wx.showModal({
           content: 'Please turn on Bluetooth on your mobile phone and try again'
       })
   }
})
  •  

Note: It is recommended that wx.openBluetooth Adapter (OBJECT) and wx.closeBluetooth Adapter (OBJECT) be used in pairs.
Wx.closeBluetooth Adapter: Turn off the Bluetooth module to an uninitialized state.Calling this method will disconnect all established links and release system resources;

3. Search for specified devices

Wx.startBluetooth Devices Discovery (OBJECT) starts searching for nearby Bluetooth peripherals
Wx.getBluetooth Devices (OBJECT) Gets all discovered Bluetooth devices while the applet Bluetooth module is in effect
wx.onBluetoothDeviceFound(CALLBACK) listens for events when a new device is found

Note: Searching for Bluetooth wx.startBluetooth DevicesDiscovery (OBJECT) is a relatively resource-intensive operation. After searching for and connecting to a device, call the wx.stopBluetooth DevicesDiscovery (OBJECT) method to stop the search.

//Start searching for Bluetooth
    wx.startBluetoothDevicesDiscovery({
        success: function (res) {
            console.log('search', res)
        }
    })
//devices detected
      wx.getBluetoothDevices({
         success: function (res) {
            console.log('devices detected', res)
            if (res.devices[0]) { 
                console.log(that.ab2hext(res.devices[0].advertisData))                                      
            }
            //No device found in 5s, turn off search, turn off Bluetooth module
            setTimeout(function(){
                  if (!that.data.deviceId){
                      wx.hideLoading()
                      app.showToast('Search device timeout','none');
                      //Close Search
                      that.stopBluetoothDevicesDiscovery();
                      //Turn off Bluetooth
                      that.closeBluetoothAdapter();
                  }
             },5000)
         }
      })
    //Listen Discovery Device
    wx.onBluetoothDeviceFound(function (devices) {
        console.log('devices detected:', devices.devices)
        for (let i = 0; i < devices.devices.length; i++) {
            //Retrieve the specified device
            if (devices.devices[i].name == 'equipment name') {
                that.setData({
                    deviceId: devices.devices[i].deviceId
                })
                //Close Search
                that.stopBluetoothDevicesDiscovery();
                console.log('Specified device found:', devices.devices[i].deviceId);  
             }
          }
     })
     ab2hext: function(buffer) {
            var hexArr = Array.prototype.map.call(
                new Uint8Array(buffer),
                function (bit) {
                    return ('00' + bit.toString(16)).slice(-2)
                }
            )
            return hexArr.join('');
       }

This code matches the paired device by the device name. If no specified device is found within 5s, the search is turned off and the Bluetooth module is turned off.
The device name is the name found in the Bluetooth device device object

4. The deviceId obtained on the developer tools and Android is the device MAC address, and the device uuid on the iOS.So deviceId can't be hard coded into code, how to connect to Bluetooth

Search we can get the deviceId of the device and connect to Bluetooth via deviceId
The deviceId obtained on Android is the MAC address of the device, and the deviceId obtained on iOS is the uuid of the device, so the deviceId cannot be hardcoded into code.
Then maybe an intelligent partner said, set two variables, one for the device MAC and one for the device uuid.
Judge the model before connecting the device, ios device deviceId take: device uuid, android device deviceId: MAC address!!!(
I thought the same thing, because we did this little program that scanned to connect the specified device (just like sharing a bicycle), so we wanted to put mac and uuid in the QR code and get the corresponding value according to the model when connecting.
But!!!But!!!But!!!(
In the implementation process, it is found that the device deviceId searched by different ios mobile phones is different.
So it's still a good idea to get deviceId to connect through device name (broadcast name).
 
 
Just because I'm inexperienced, I always want to take shortcuts.
The correct process is
Initialize Bluetooth wx.openBluetooth Adapter (OBJECT)
↓ 
Start searching for Bluetooth wx.startBluetooth Devices Discovery (OBJECT)
↓ 
All discovered Bluetooth devices wx.getBluetooth Devices (OBJECT)
↓ 
Listen for events wx.onBluetoothDeviceFound(CALLBACK) that find a new device
↓ 
Connect low power Bluetooth device wx.createBLEConnection(OBJECT)
↓ 
Get all services (services) for Bluetooth devices wx.getBLED eviceServices (OBJECT)
↓ 
Get all characteristic (eigenvalues) wx.getBLED eviceCharacteristics (OBJECT) in a service of a Bluetooth device
↓ 
Enable notify function wx.notifyBLECharacteristicValueChange(OBJECT) when feature value changes for low power Bluetooth devices
↓ 
Write wx.writeBLECharacteristicValue(OBJECT)

Connect the device by getting its deviceId after searching for it

wx.createBLEConnection({
    deviceId: that.data.deviceId,//Bluetooth device id obtained by searching device
    success: function (res) {
        console.log('Connect Bluetooth:', res.errMsg);
    },
    fail: function (res) {
        app.showToast('connection timed out,Please try again or change your vehicle', 'none');
        that.closeBluetoothAdapter();
    }
})

5. How to choose serviceId

Once the connection is successful, you can get the list of services for the device. Here's the service ID for FEE7

wx.getBLEDeviceServices({
  deviceId: that.data.deviceId,//Bluetooth device id obtained by searching device
  success: function (res) {        
    let service_id = "";
    for(let i = 0;i<res.services.length;i++){
      if(services[i].uuid.toUpperCase().indexOf("FEE7") != -1){
        service_id = services[i].uuid;
        break;
      }
    }
     console.log('fee7-service_id:', that.data.service_id);
  },
  fail(res){
    console.log(res);
  }
})

6.characteristic (eigenvalue) what to do and how to use it

What do service eigenvalues do: Each service contains a set of eigenvalues describing some properties of the service, getting whether it is readable, writable, notify notifications can be turned on, and so on, which are needed to transfer data when you communicate with Bluetooth.(
How to use service eigenvalues:

//Getting eigenvalues
wx.getBLEDeviceCharacteristics({
    deviceId: that.data.deviceId,//Bluetooth device id obtained by searching device
    serviceId: that.data.service_id,//Service ID
    success: function (res) {
        console.log('device characteristic value:', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
            let charc = res.characteristics[i];
            if (charc.properties.indicate) {
                that.setData({indicate_id: charc.uuid});
                console.log('indicate_id:', that.data.indicate_id);
            }
            if (charc.properties.write) {
                that.setData({write_id: charc.uuid});
                console.log('write write_id:', that.data.write_id);
            }
            if (charc.properties.read) {
                that.setData({read_id: charc.uuid});
                console.log('read read_id:', that.data.read_id);
            }
        }
   }
});

Filter out the service characteristics you need.
When corresponding eigenvalues are obtained, they can be used when performing related operations.
For example:
Turn notify on: Eigenvalues of the device must support notify or indicate to be invoked successfully.
The branch does not support notify or indicate, which is the value we filtered above

 if (charc.properties.indicate) {
     that.setData({indicate_id: charc.uuid});
     console.log('indicate_id:', that.data.indicate_id);
 }

7. Turn on notify

When notify is turned on, it can monitor the changes in the eigenvalues of low-power Bluetooth devices.The notify interface must be enabled before notification s from device pushes can be received

//Open notify
wx.notifyBLECharacteristicValueChange({
    state: true, // Enable notify functionality
    deviceId: that.data.deviceId,//Bluetooth device id
    serviceId: that.data.service_id,//Service id
    characteristicId: that.data.indicate_id,//Service eigenvalue indicate
    success: function (res) {
        console.log('open notify', res.errMsg)
        //Listen for eigenvalue changes of low power Bluetooth devices
        wx.onBLECharacteristicValueChange(function (res) {
            console.log('Eigenvalue change', that.arrayBufferToHexString(res.value));
        })
        //Write data

    }
});

8. How to write data

How do I write data, by getting the write eigenvalue write_id
Note: The device's eigenvalue must support write before it can be invoked successfully

 let buffer = that.hexStringToArrayBuffer(ArrayBuffer);
 //Write data
 wx.writeBLECharacteristicValue({
     deviceId: that.data.deviceId,//Device deviceId
     serviceId: that.data.service_id,//Device service_id
     characteristicId: that.data.write_id,//Device write eigenvalue
     value: buffer,//Write data
     success: function (res) {
         console.log('send data:', res.errMsg)
     }
 });
 hexStringToArrayBuffer:function (str) {
        if(!str) {
            return new ArrayBuffer(0);
        }
        var buffer = new ArrayBuffer(str.length);
        let dataView = new DataView(buffer)
        let ind = 0;
        for (var i = 0, len = str.length; i < len; i += 2) {
            let code = parseInt(str.substr(i, 2), 16)
            dataView.setUint8(ind, code)
            ind++
        }
        return buffer;
 }

Summary: There are a few special points to note, take out the small book quickly.
1. Search cannot start immediately after the Bluetooth status changes in IOS, otherwise the device will not be searched, you must wait for more than 2 seconds.
2. Messages cannot be sent immediately after notify is turned on. Bluetooth devices have a preparation process that requires a delay of more than one second in setTimeout before sending, otherwise sending fails

setTimeout(function () {
   wx.writeBLECharacteristicValue({
     deviceId: that.data.deviceId,
     serviceId: that.data.service_id,
     characteristicId: that.data.write_id,
     value: buffer,
     success: function (res) {
         console.log('send data:', res.errMsg)
     }
 });
}, 1100);

3. Release the resource stopBluetoothDevicesDiscovery after searching for the device
4. Always turn off Bluetooth.wx.openBluetooth Adapter (OBJECT) and wx.closeBluetooth Adapter (OBJECT) pairing when Bluetooth is not required

Topics: Mobile Mac iOS Android