Skip to content

Bluetooth-General

stopBluetoothDevicesDiscovery

TIP

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

  • Functional description: Stop searching for nearby Bluetooth peripheral devices. If the required Bluetooth device has been found and no further search is needed, it is recommended to call this interface to stop the Bluetooth search.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    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.stopBluetoothDevicesDiscovery({
  success (res) {
    console.log(res)
  }
})

startBluetoothDevicesDiscovery

TIP

Considering that the Bluetooth function can be positioned indirectly, Android 6.0 and above versions cannot search for devices without positioning permission or when the positioning switch is not turned on. In this case, before Android 8.0.16, the interface call is successful but the device cannot be scanned; Android 8.0.16 and above versions will return an error.

TIP

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

  • Functional description: Start searching for nearby Bluetooth peripheral devices. This operation consumes system resources. Please call it in time after searching for the required device wx.stopBluetoothDevicesDiscovery StopSearch

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    servicesArray.<string>-NoThe UUID list of the main service of the Bluetooth device to be searched (supports 16/32/128-bit UUID). Some Bluetooth devices broadcast the UUID of their main service. If this parameter is set, only Bluetooth devices with main services corresponding to the UUID in the broadcast packet will be searched. It is recommended to use this parameter to filter out other Bluetooth devices that do not need to be processed in the surrounding area
    allowDuplicatesKeybooleanfalseNoWhether to allow repeated reporting of the same device. If repeated reporting is allowed, thenwx.onBluetoothDeviceFound The method will report the same device multiple times, but the RSSI value will be different.
    intervalnumber0NoThe interval for reporting devices, in ms. 0 means that new devices are reported immediately when they are found, and other values
    powerLevelstringmediumNoScan mode, the higher the value, the faster the scan, and the more power it consumes. Only supported by Android host client 7.0.12 and above, the legal value is:
    1.low: Low
    2.medium: Medium
    3.high: High
    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
// Taking the Bluetooth smart light of the host client's hardware platform as an example, the UUID of the main service is FEE7. By passing in this parameter, only devices with a main service UUID of FEE7 will be searched for.
wx.startBluetoothDevicesDiscovery({
  services: ['FEE7'],
  success (res) {
    console.log(res)
  }
})

openBluetoothAdapter

TIP

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

TIP

  • Other Bluetooth-related APIs must be used after wx.openBluetoothAdapter calling. Otherwise, the API will return an error (errCode=10000).
  • If the user's Bluetooth switch is not turned on or the mobile phone does not support the Bluetooth function, calling wx.openBluetoothAdapter will return an error (errCode=10001), indicating that the mobile phone Bluetooth function is not available.
  • Functional description: Initialize the Bluetooth module. When turning on the host/slave (peripheral device) mode on iOS, you need to call it once respectively and specify the corresponding mode.

  • Parameters and descriptions: Object object。

    PropertiesTypeLegal values Default valueRequiredDescription
    modestring1.central: Host mode
    2.peripheral: Slave (peripheral device) mode
    centralNoBluetooth mode, can be used as master/slave device, only required for iOS
    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
  • The state parameter returned by the object.fail callback function (only for iOS)

    status codeDescription
    0Unknown
    1Resetting
    2Not supported
    3Unauthorized
    4Not enabled
  • Sample code:

js
wx.openBluetoothAdapter({
  success (res) {
    console.log(res)
  }
})

getConnectedBluetoothDevices

TIP

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

  • Functional description: Get connected Bluetooth devices based on the master service UUID.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    servicesArray-YesUUID list of Bluetooth device master services (supports 16/32/128 bit UUID)
    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
    devicesArray.<Object>List of searched devices
    Structure propertiesTypeDescription
    namestringBluetooth device name, some devices may not have
    deviceIdstringID used to distinguish devices
  • 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.getConnectedBluetoothDevices({
  services: ['FEE7'],
  success (res) {
    console.log(res)
  }
})

getBluetoothDevices

TIP

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

TIP

The device list obtained by this interface is all the Bluetooth devices searched during the Bluetooth module is effective. If the Bluetooth module is not called in time after the use process ends wx.closeBluetoothAdapter Release resources. Calling this interface will return the Bluetooth devices searched in the previous Bluetooth usage process. The device may no longer be with the user and cannot be connected.

  • Functional description: Get all Bluetooth devices searched during the Bluetooth module is effective. Including devices that are already connected to the machine.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    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
    devicesArray.<Object>List of connected devices corresponding to UUID
    Structure propertiesTypeDescription
    namestringBluetooth device name, some devices may not have
    deviceIdstringBluetooth device id
    RSSInumberSignal strength of the current Bluetooth device, unit: dBm
    advertisDataArrayBufferManufacturerData data segment in the broadcast data segment of the current Bluetooth device
    advertisServiceUUIDsArray.<string>ServiceUUIDs data segment in the broadcast data segment of the current Bluetooth device
    localNamestringLocalName data segment in the broadcast data segment of the current Bluetooth device
    serviceDataObjectServiceData data segment in the broadcast data segment of the current Bluetooth device
    connectablebooleanWhether the current Bluetooth device is connectable (Android 8.0 and below do not support returning this value)
  • Sample code:

js
// ArrayBuffer to 16 progress string example
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function(bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
wx.getBluetoothDevices({
  success: function (res) {
    console.log(res)
    if (res.devices[0]) {
      console.log(ab2hex(res.devices[0].advertisData))
    }
  }
})

getBluetoothAdapterState

TIP

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

  • Functional description: Get the status of the local Bluetooth adapter.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    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
    discoveringbooleanWhether searching for devices
    availablebooleanWhether the Bluetooth adapter is available
  • 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.getBluetoothAdapterState({
  success (res) {
    console.log(res)
  }
})

closeBluetoothAdapter

TIP

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

  • Functional description: Turn off the Bluetooth module. Calling this method will disconnect all established connections and release system resources. It is recommended to call it in pairs with wx.openBluetoothAdapterafter using the Bluetooth process.

  • Parameters and descriptions: Object object。

    PropertiesTypeDefault valueRequiredDescription
    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.closeBluetoothAdapter({
  success (res) {
    console.log(res)
  }
})

onBluetoothDeviceFound

TIP

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

TIP

  • If a device is called back in wx.onBluetoothDeviceFound, the device will be added towx.getBluetoothDevices The array obtained by the interface.
  • When a Bluetooth device is searched, the name field returned by the system is generally the device name in the LocalName field in the broadcast packet. If a connection is established with a Bluetooth device, the name field returned by the system will be changed to the GattName obtained from the Bluetooth device. If you need to dynamically change the device name and display it, it is recommended to use the localName field.
  • Some models under Android require location permissions to search for devices. Please pay attention to whether the location permission is enabled.
  • Functional description: Listen for events of searching for new devices.

  • Parameters and descriptions: function listener,The listener function for events of searching for new devices, the parameter object res is as follows:

    PropertiesTypeDescription
    devicesArray.<Object>List of newly searched devices
  • devicesStructure properties

    Structure propertiesTypeDescription
    namestringBluetooth device name, some devices may not have
    deviceIdstringBluetooth device id
    RSSInumberSignal strength of the current Bluetooth device, unit: dBm
    advertisDataArrayBufferManufacturerData data segment in the broadcast data segment of the current Bluetooth device
    advertisServiceUUIDsArray.<string>ServiceUUIDs data segment in the broadcast data segment of the current Bluetooth device
    localNamestringLocalName data segment in the broadcast data segment of the current Bluetooth device
    serviceDataObjectServiceData data segment in the broadcast data segment of the current Bluetooth device
    connectablebooleanWhether the current Bluetooth device is connectable (Android 8.0 and below do not support returning this value)
  • Sample code:

js
// ArrayBuffer to 16 progress string example
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function(bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
wx.onBluetoothDeviceFound(function(res) {
  var devices = res.devices;
  console.log('new device list has founded')
  console.dir(devices)
  console.log(ab2hex(devices[0].advertisData))
})

offBluetoothDeviceFound

TIP

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

  • Functional description: Remove all listener functions for events of searching for new devices.

  • Sample code:

js
wx.offBluetoothDeviceFound()

onBluetoothAdapterStateChange

TIP

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

  • Functional description: Monitor Bluetooth adapter status change events.

  • Parameters and descriptions: Object res Parameter, function listener, the listener function for Bluetooth adapter status change events.

    PropertiesTypeDescription
    availablebooleanWhether the Bluetooth adapter is available
    discoveringbooleanWhether the Bluetooth adapter is in the search state
  • Sample code:

js
wx.onBluetoothAdapterStateChange(function (res) {
  console.log('adapterState changed, now is', res)
})

offBluetoothDeviceFound

TIP

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

  • Functional description: Remove all listener functions for Bluetooth adapter status change events.

  • Sample code:

js
wx.offBluetoothAdapterStateChange()

makeBluetoothPair

TIP

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

  • Functional description: Bluetooth pairing interface, only supported by Android. Under normal circumstances (when a pin code or password needs to be specified), the system will take over the pairing process and directly call wx.createBLEConnection. This interface should only be used when the developer does not want the user to manually enter the pin code and the real machine verification confirmation can take effect normally.
  • Parameters and descriptions: Object object。
    PropertiesTypeDefault valueRequiredDescription
    deviceIdstring-YesBluetooth device id
    pinstring-Yespin code, Base64 format
    timeoutnumber20000NoTimeout, unit: ms
    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)

isBluetoothDevicePaired

TIP

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

  • Functional description: Query whether the Bluetooth device is paired, only supported by Android.
  • 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)