Skip to content

Bluetooth-Low Power Central Device

writeBLECharacteristicValue

TIP

The API usage is as follows: wx.writeBLECharacteristicValue(Object object)

TIP

  • There is a possibility of write failure when calling multiple times in parallel.
  • The applet will not limit the size of the written data packet, but the system and Bluetooth devices will limit the data size of a single Bluetooth 4.0 transmission. A write error will occur if the maximum number of bytes is exceeded. It is recommended that no more than 20 bytes be written each time.
  • If the single write data is too long, there will be no callback (including error callback) on iOS.
  • On the Android platform, this interface is called immediately after the call wx.notifyBLECharacteristicValueChange successfully. System error 10008 will occur on some models
  • Functional description: Write binary data to the characteristic value of a Bluetooth low energy device The device's characteristics must support write to successfully call

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    deviceIdstring-YesBluetooth device id
    serviceIdnumber-YesThe UUID of the service corresponding to the Bluetooth characteristic
    characteristicIdboolean-YesThe UUID of the Bluetooth characteristic
    valuestring-YesThe binary value corresponding to the Bluetooth device characteristic
    writeTypestring-NoThe write mode setting of the Bluetooth characteristic value has two modes, iOS prioritizes write and Android prioritizes writeNoResponse. Legal values
    1.write: Forced reply write, error if not supported
    2.writeNoResponse: Forced no reply write, error if not supported
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Error code

    Error codeError messageDescription
    0okNormal
    -1already connectConnected
    10000not initUninitialized Bluetooth adapter
    10001not availableCurrent Bluetooth adapter is unavailable
    10002no deviceNot found the specified device
    10003connection failConnection failed
    10004no serviceNot found the specified service
    10005no characteristicNot found the specified characteristic
    10006no connectionCurrent connection is disconnected
    10007property not supportCurrent characteristic does not support this operation
    10008system errorAll other exceptions reported by the system
    10009system not supportAndroid system specific, system version lower than 4.3 does not support BLE
    10012operate time outConnection timeout
    10013invalid_dataConnection deviceId is empty or format is incorrect
  • Sample code:

js
// Transmit a hexadecimal data of 0x00 to the Bluetooth device.
let buffer = new ArrayBuffer(1)
let dataView = new DataView(buffer)
dataView.setUint8(0, 0)

wx.writeBLECharacteristicValue({
  // The deviceId here must be obtained through the getBluetoothDevices or onBluetoothDeviceFound interfaces.
  deviceId,
  // The ServiceId here must be obtained from the wx.getBLEDeviceServices interface.
  serviceId,
  // The CharacteristicId Here must be obtained from the getBLEDeviceCharacteristics interface.
  characteristicId,
  // The value here is of ArrayBuffer type.
  value: buffer,
  success (res) {
    console.log('writeBLECharacteristicValue success', res.errMsg)
  }
})

readBLECharacteristicValue

TIP

The API usage is as follows: wx.readBLECharacteristicValue(Object object)

TIP

  • Multiple parallel calls may result in read failures
  • The information read by the interface needs to be wx.onBLECharacteristicValueChange Obtained from the callback of method registration
  • Functional description: Read binary data of characteristic value of Bluetooth low energy device , the device's features must support read in order to be successfully called

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    deviceIdstring-YesBluetooth device id
    serviceIdstring-YesThe UUID of the service corresponding to the Bluetooth characteristic
    characteristicIdstring-YesThe UUID of the Bluetooth characteristic
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Error code

    Error codeError messageDescription
    0okNormal
    -1already connectConnected
    10000not initUninitialized Bluetooth adapter
    10001not availableCurrent Bluetooth adapter is unavailable
    10002no deviceNot found the specified device
    10003connection failConnection failed
    10004no serviceNot found the specified service
    10005no characteristicNot found the specified characteristic
    10006no connectionCurrent connection is disconnected
    10007property not supportCurrent characteristic does not support this operation
    10008system errorAll other exceptions reported by the system
    10009system not supportAndroid system specific, system version lower than 4.3 does not support BLE
    10012operate time outConnection timeout
    10013invalid_dataConnection deviceId is empty or format is incorrect
  • Sample code:

js
// Retrieval is only possible in this callback.
wx.onBLECharacteristicValueChange(function(characteristic) {
  console.log('characteristic value comed:', characteristic)
})

wx.readBLECharacteristicValue({
  // The deviceId here must have already established a link with the corresponding device through createBLEConnection.
  deviceId,
  // The ServiceId here must be obtained from the wx.getBLEDeviceServices interface.
  serviceId,
  // The CharacteristicId Here Must be Retrieved from the getBLEDeviceCharacteristics Interface
  characteristicId,
  success (res) {
    console.log('readBLECharacteristicValue:', res.errCode)
  }
})

setBLEMTU

TIP

The API usage is as follows: wx.setBLEMTU(Object object)

  • Functional description: Negotiate to set the maximum transmission unit (MTU) of Bluetooth low energy. wx.createBLEConnection Called after the call is successful. Only valid for Android system 5.1 and above, iOS does not support due to system restrictions

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    deviceIdstring-YesBluetooth device id
    mtunumber-YesMaximum transmission unit. The setting range is (22,512) interval, unit is bytes
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    mtunumberThe final negotiated MTU value is consistent with the input parameter. Android client 8.0.9 and later supports

getBLEMTU

TIP

The API usage is as follows: wx.getBLEMTU(Object object)

TIP

  • The MTU in the applet is ATT_MTU, which includes the length of Op-Code and Attribute Handle. The actual length of data that can be transmitted is ATT_MTU - 3.
  • In iOS, MTU is a fixed value. In Android, MTU will change after successful system negotiation. It is recommended to use wx.onBLEMTUChange Monitoring.
  • Functional description: To obtain the maximum transmission unit of Bluetooth low energy, it needs to be in wx.createBLEConnection Called after the call is successful。

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    deviceIdstring-YesBluetooth device id
    writeTypestringwriteYesWrite mode (iOS-specific parameter), legal values
    1.write: There is a reply to write
    1.writeNoResponse: No reply to write
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    mtunumberMaximum Transmission Unit
  • Error code

    Error codeError messageDescription
    0okNormal
    -1already connectConnected
    10000not initUninitialized Bluetooth adapter
    10001not availableCurrent Bluetooth adapter is unavailable
    10002no deviceNot found the specified device
    10003connection failConnection failed
    10004no serviceNot found the specified service
    10005no characteristicNot found the specified characteristic
    10006no connectionCurrent connection is disconnected
    10007property not supportCurrent characteristic does not support this operation
    10008system errorAll other exceptions reported by the system
    10009system not supportAndroid system specific, system version lower than 4.3 does not support BLE
    10012operate time outConnection timeout
    10013invalid_dataConnection deviceId is empty or format is incorrect
  • Sample code:

js
wx.getBLEMTU({
  deviceId: '',
  writeType: 'write',
  success (res) {
    console.log(res)
  }
})

onBLEMTUChange

TIP

The API usage is as follows: wx.onBLEMTUChange(function listener)

  • Functional description: Listen for the change event of the maximum transmission unit of Bluetooth low energy (only triggered by Android)

  • Parameters and descriptions: function listener,The monitoring function of the Bluetooth low energy maximum transmission unit change event, the parameter Object res is as follows:

    PropertiesTypeDescription
    deviceIdstringMaximum Transmission Unit
    mtunumberMaximum Transmission Unit
  • Sample code:

js
wx.onBLEMTUChange(function (res) {
  console.log('bluetooth mtu is', res.mtu)
})

offBLEMTUChange

TIP

The API usage is as follows: wx.offBLEMTUChange(function listener)

  • Functional description: Remove the listener function of the change event of the maximum transmission unit of Bluetooth low energy

  • Parameters and descriptions: function listener,onBLEMTUChange The listening function passed in. If this parameter is not passed, all listening functions will be removed.

  • Sample code:

js
const listener = function (res) { console.log(res) }

wx.onBLEMTUChange(listener)
wx.offBLEMTUChange(listener) // Pass the same function object used for listening.

onBLEConnectionStateChange

TIP

The API usage is as follows: wx.onBLEConnectionStateChange(function listener)

  • Functional description: Listen for Bluetooth low energy connection status change events, including developer-initiated connection or disconnection, device loss, abnormal connection disconnection, etc.

  • Parameters and descriptions: function listener,The listener function for Bluetooth low energy connection status change events, the parameter Object res is as follows:

    PropertiesTypeDescription
    deviceIdstringBluetooth device id
    connectedbooleanIs it in the connected state?
  • Sample code:

js
wx.onBLEConnectionStateChange(function(res) {
  // This method callback can be used to handle exceptional situations such as unexpected disconnections.
  console.log(device ${res.deviceId} state has changed, connected: ${res.connected})
})

offBLEConnectionStateChange

TIP

The API usage is as follows: wx.offBLEConnectionStateChange(function listener)

  • Functional description: Remove the listener function of the change event of the connection state of Bluetooth low energy

  • Parameters and descriptions: function listener,onBLEConnectionStateChange The listening function passed in. If this parameter is not passed, all listening functions will be removed

  • Sample code:

js
const listener = function (res) { console.log(res) }

wx.onBLEConnectionStateChange(listener)
wx.offBLEConnectionStateChange(listener) // pass the same listener function to unregister the listener

onBLECharacteristicValueChange

TIP

The API usage is as follows: wx.onBLECharacteristicValueChange(function listener)

  • Functional description: Monitor the characteristic value change event of the Bluetooth low energy device. You must call wx.notifyBLECharacteristicValueChange The interface can receive the notification pushed by the device

  • Parameters and descriptions: function listener,The monitoring function of the characteristic value change event of the Bluetooth low energy device, the parameter Object res is as follows:

    PropertiesTypeDescription
    deviceIdstringBluetooth device id
    serviceIdstringThe UUID of the service corresponding to the Bluetooth characteristic
    characteristicIdstringThe UUID of the Bluetooth characteristic
    valueArrayBufferThe latest value of the characteristic
  • Sample code:

js
// ArrayBuffer to 16
function ab2hex(buffer) {
  let hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function(bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
wx.onBLECharacteristicValueChange(function(res) {
  console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
  console.log(ab2hex(res.value))
})

offBLECharacteristicValueChange

TIP

The API usage is as follows: wx.offBLECharacteristicValueChange()

  • Functional description: Remove all listeners for characteristic value change events of Bluetooth low energy devices

  • Sample code:

js
wx.offBLECharacteristicValueChange()

notifyBLECharacteristicValueChange

TIP

The API usage is as follows: wx.notifyBLECharacteristicValueChange(Object object)

TIP

  • After the subscription operation is successful, the device needs to actively update the value of the feature to trigger wx.onBLECharacteristicValueChange Other events on the App can be completed using
  • On the Android platform, call this interface immediately after it is successfully called wx.writeBLECharacteristicValue interface, a 10008 system error may occur on some models.
  • The device's characteristic must support notify or indicate before it can be successfully called. In addition, wx.notifyBLECharacteristicValueChange must be enabled before the device characteristicValueChange event can be monitored.
  • Functional description: Enable the notify function when the characteristic value of the Bluetooth low-power device changes, and subscribe to the characteristic.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    deviceIdstring-YesBluetooth device id
    serviceIdstring-YesThe UUID of the service corresponding to the Bluetooth characteristic
    characteristicIdstring-YesThe UUID of the Bluetooth characteristic
    stateboolean-YesWhether to enable notify
    typestringindicationNoSet the characteristic subscription type, valid values
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Error code

    Error codeError messageDescription
    0okNormal
    -1already connectConnected
    10000not initUninitialized Bluetooth adapter
    10001not availableCurrent Bluetooth adapter is unavailable
    10002no deviceNot found the specified device
    10003connection failConnection failed
    10004no serviceNot found the specified service
    10005no characteristicNot found the specified characteristic
    10006no connectionCurrent connection is disconnected
    10007property not supportCurrent characteristic does not support this operation
    10008system errorAll other exceptions reported by the system
    10009system not supportAndroid system specific, system version lower than 4.3 does not support BLE
    10012operate time outConnection timeout
    10013invalid_dataConnection deviceId is empty or format is incorrect
  • Sample code:

js
// Transmit a hexadecimal data of 0x00 to the Bluetooth device.
let buffer = new ArrayBuffer(1)
let dataView = new DataView(buffer)
dataView.setUint8(0, 0)


wx.writeBLECharacteristicValue({
  // The deviceId here must be obtained through the getBluetoothDevices or onBluetoothDeviceFound interfaces.
  deviceId,
  // The ServiceId here must be obtained from the wx.getBLEDeviceServices interface.
  serviceId,
  // The CharacteristicId Here Must be Retrieved from the getBLEDeviceCharacteristics Interface
  characteristicId,
  // The Value Here is of ArrayBuffer Type
  value: buffer,
  success (res) {
    console.log('writeBLECharacteristicValue success', res.errMsg)
  }
})

getBLEDeviceServices

TIP

The API usage is as follows: wx.getBLEDeviceServices(Object object)

  • Functional description: Get all services (service) of the Bluetooth low-power device.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    deviceIdstring-YesBluetooth device id. Need to have been connected throughwx.createBLEConnection Established
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    servicesArray.<Object>Device service list
  • Service structure attributes

    PropertiesTypeDescription
    uuidstringUUID of the Bluetooth device service
    isPrimarybooleanIs this service the main service
  • Sample code:

js
wx.getBLEDeviceServices({
  //  deviceId  wx.createBLEConnection 
  deviceId,
  success (res) {
    console.log('device services:', res.services)
  }
})

getBLEDeviceRSSI

TIP

The API usage is as follows: wx.getBLEDeviceRSSI(Object object)

  • Functional description: Get the signal strength (Received Signal Strength Indication, RSSI) of the Bluetooth low-power device.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    deviceIdstring-YesBluetooth device id
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    RSSINumberSignal strength, unit: dBm

getBLEDeviceCharacteristics

TIP

The API usage is as follows: wx.getBLEDeviceCharacteristics(Object object)

  • Functional description: Get all characteristics (characteristic) in a service of the Bluetooth low-power device.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    deviceIdstring-YesBluetooth device id. Need to have been connected throughwx.createBLEConnection Established
    serviceIdstring-YesBluetooth service UUID. Need to call firstwx.createBLEConnection
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • object.success callback function parameters: Object res。

    PropertiesTypeDescription
    characteristicsArray.<Object>Device feature list
    • characteristics structure attribute
      Structure propertiesTypeDescription
      uuidstringUUID of Bluetooth device feature
      propertiesObjectOperation types supported by this feature
      • properties structure attribute
        PropertiesTypeDescription
        readbooleanDoes this feature support read operation
        writebooleanDoes this feature support write operation
        notifybooleanDoes this feature support notify operation
        indicatebooleanDoes this feature support indicate operation
        writeNoResponsebooleanDoes this feature support writeNoResponse operation
        writeDefaultbooleanDoes this feature support writeDefault operation
  • Error code

    Error codeError messageDescription
    0okNormal
    -1already connectConnected
    10000not initUninitialized Bluetooth adapter
    10001not availableCurrent Bluetooth adapter is unavailable
    10002no deviceNot found the specified device
    10003connection failConnection failed
    10004no serviceNot found the specified service
    10005no characteristicNot found the specified characteristic
    10006no connectionCurrent connection is disconnected
    10007property not supportCurrent characteristic does not support this operation
    10008system errorAll other exceptions reported by the system
    10009system not supportAndroid system specific, system version lower than 4.3 does not support BLE
    10012operate time outConnection timeout
    10013invalid_dataConnection deviceId is empty or format is incorrect
  • Sample code:

js
wx.getBLEDeviceCharacteristics({
  // The deviceId here needs to have already established a link with the corresponding device through wx.createBLEConnection
  deviceId,
  // The ServiceId here must be obtained from the wx.getBLEDeviceServices interface.
  serviceId,
  success (res) {
    console.log('device getBLEDeviceCharacteristics:', res.characteristics)
  }
})

createBLEConnection

TIP

The API usage is as follows: wx.createBLEConnection(Object object)

TIP

  • Please make sure to call wx.createBLEConnection and wx.closeBLEConnection interfaces in pairs as much as possible. If Android repeatedly calls wx.createBLEConnection to create a connection, it may cause the system to hold multiple instances of the same device, resulting in the inability to truly disconnect the device when calling closeBLEConnection.
  • The Bluetooth connection may be disconnected at any time. It is recommended to listen to the wx.onBLEConnectionStateChange callback event and perform reconnection operations on demand when the Bluetooth device is disconnected.
  • If the interface for data read and write operations is called for an unconnected device or a disconnected device, a 10006 error will be returned. It is recommended to reconnect.
  • Functional description: Connect to a Bluetooth low energy device. If the applet has previously searched for a Bluetooth device and successfully established a connection, you can directly pass in the deviceId obtained from the previous search to directly try to connect to the device without searching again.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    deviceIdstring-YesBluetooth device id
    timeoutnumber-NoTimeout, in ms. If it is not filled, it will not time out.
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Error code

    Error codeError messageDescription
    0okNormal
    -1already connectConnected
    10000not initUninitialized Bluetooth adapter
    10001not availableCurrent Bluetooth adapter is unavailable
    10002no deviceNot found the specified device
    10003connection failConnection failed
    10004no serviceNot found the specified service
    10005no characteristicNot found the specified characteristic
    10006no connectionCurrent connection is disconnected
    10007property not supportCurrent characteristic does not support this operation
    10008system errorAll other exceptions reported by the system
    10009system not supportAndroid system specific, system version lower than 4.3 does not support BLE
    10012operate time outConnection timeout
    10013invalid_dataConnection deviceId is empty or format is incorrect
  • Sample code:

js
wx.createBLEConnection({
  deviceId,
  success (res) {
    console.log(res)
  }
})

closeBLEConnection

TIP

The API usage is as follows: wx.closeBLEConnection(Object object)

  • Functional description: Disconnect from Bluetooth low energy devices

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    deviceIdstring-YesBluetooth device id
    successFunction-NoCallback function for successful interface call
    failFunction-NoCallback function for failed interface call
    completeFunction-NoCallback function for interface call completion (executed regardless of success or failure)
  • Error code

    Error codeError messageDescription
    0okNormal
    -1already connectConnected
    10000not initUninitialized Bluetooth adapter
    10001not availableCurrent Bluetooth adapter is unavailable
    10002no deviceNot found the specified device
    10003connection failConnection failed
    10004no serviceNot found the specified service
    10005no characteristicNot found the specified characteristic
    10006no connectionCurrent connection is disconnected
    10007property not supportCurrent characteristic does not support this operation
    10008system errorAll other exceptions reported by the system
    10009system not supportAndroid system specific, system version lower than 4.3 does not support BLE
    10012operate time outConnection timeout
    10013invalid_dataConnection deviceId is empty or format is incorrect
  • Sample code:

js
wx.closeBLEConnection({
  deviceId,
  success (res) {
    console.log(res)
  }
})