# Bluetooth

Bluetooth communications management.

# Manifest Declaration

You need to declare the use of this API in the manifest's features member:

{"name": "system.bluetooth"}

# Module Import

Before using this service in a component, you need to import the module in the script section of the UX document.

import bluetooth from '@system.bluetooth' 

Or

let bluetooth = require("@system.bluetooth")

# Methods

This service has the following methods:

# openAdapter({operateAdapter,success,fail,complete})

Method to initialize the Bluetooth module in the device.

# Arguments

This method requires an object with the following attributes:

  • operateAdapter (boolean). Optional flag to enable (true) or disable the Bluetooth function of the device. The user must grant the permission to use this feature. The value by default is false.
  • success (function). Optional callback function corresponding to the successful execution.
  • fail (function(msg,code)). Optional callback function corresponding to a failed execution. See the possible result codes.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

bluetooth.openAdapter({ 
    operateAdapter: true, 
    success: function () { 
        console.log("success"); 
    }, 
    fail: function () { 
        console.log("fail"); 
    }, 
    complete: function () { 
        console.log("complete"); 
    } 
})

# closeAdapter({operateAdapter,success,fail,complete})

Method to disable the Bluetooth module in the device.

WARNING

This method will disconnect all established connections.

# Arguments

This method requires an object with the following attributes:

  • operateAdapter (boolean). Optional flag to disable (true) the Bluetooth function of the device. The user must grant the permission to use this feature. The value by default is false.
  • success (function). Optional callback function corresponding to the successful execution.
  • fail (function(msg,code)). Optional callback function corresponding to a failed execution. See the possible result codes.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

bluetooth.closeAdapter({ 
    success:function(){ 
        console.log("success"); 
    }, 
    fail: function() { 
        console.log("fail"); 
    }, 
    complete: function (){ 
        console.log("complete"); 
    } 
})

# getAdapterState({success,fail,complete})

Method to get information about the status of the Bluetooth module in the device.

WARNING

This method will disconnect all established connections.

# Arguments

This method requires an object with the following attributes:

  • success (function(res)). Optional callback function corresponding to the successful execution. This function has an argument, an object that have the following members:
    • available (boolean) indicating if the Bluetooth adapter is available.
    • discovering (boolean) indicating if the Bluetooth adapter is searching for devices.
  • fail (function(msg,code)). Optional callback function corresponding to a failed execution. See the possible result codes.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

bluetooth.getAdapterState({ 
    success:function(){ 
        console.log("success"); 
    }, 
    fail: function() { 
        console.log("fail");
    }, 
    complete: function (){ 
        console.log("complete"); 
    } 
})

# startDevicesDiscovery({services,allowDuplicatesKey,interval,success,fail,complete})

Method to scan for nearby Bluetooth devices.

WARNING

This operation is high resource-consuming. After searching for and connecting to the expected device, use stopDevicesDiscovery to stop the search.

# Arguments

This method requires an object with the following attributes:

  • services (array). Optional attribute with a list of UUIDs (string) of the primary services we are looking for.
  • allowDuplicatesKey (boolean). Optional attribute that indicates if the same device can be repeatedly found. The default value is false.
  • interval (number). Optional attribute with the period of time for reporting devices the system found. The default value is 0, indicating that a new device is immediately reported once being found.
  • success (function). Optional callback function corresponding to the successful execution.
  • fail (function(msg,code)). Optional callback function corresponding to a failed execution. See the possible result codes.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

bluetooth.startDevicesDiscovery({ 
    services: ['FEE7'], 
    success: function () { 
        console.log("success") 
    } 
})

# stopDevicesDiscovery({success,fail,complete})

Method to stop scanning for nearby Bluetooth devices.

# Arguments

This method requires an object with the following attributes:

  • success (function). Optional callback function corresponding to the successful execution.
  • fail (function(msg,code)). Optional callback function corresponding to a failed execution. See the possible result codes.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

bluetooth.stopDevicesDiscovery({ 
    success:function(){ 
        console.log("success"); 
    }, 
    fail: function() { 
        console.log("fail"); 
    }, 
    complete: function (){ 
        console.log("complete"); 
    }
})

# getDevices({success,fail,complete})

Gets all the Bluetooth devices found.

This method includes the devices that are currently connected to the device.

# Arguments

This method requires an object with the following attributes:

  • success (function(res)). Optional callback function corresponding to the successful execution. The argument of the callback function is an object with the member:
    • devices (array). List of the UUID of the devices and their information, represented as an object with the following members:
      • name (string). Name of a Bluetooth device. Some devices may have no names.
      • deviceId (string). Unique ID of a Bluetooth device.
      • RSSI (number). Signal strength of the current Bluetooth device.
      • advertisData (ArrayBuffer). The ManufacturerData segment in the broadcast data of the current Bluetooth device.
      • advertisServiceUUIDs (array). The ServiceUUIDs segment in the broadcast data of the current Bluetooth device.
      • localName (string). The LocalName segment in the broadcast data of the current Bluetooth device.
      • serviceData (string). ServiceData segment in the broadcast data of the current Bluetooth device. The structure returned is as follows: {"service uuid string": ArrayBuffer}.
  • fail (function(msg,code)). Optional callback function corresponding to a failed execution. See the possible result codes.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

bluetooth.getDevices({ 
    success:function(res){ 
        console.log(res) 
        if (res.devices[0]) { 
            console.log(res.devices[0].advertisData) 
        } 
    }, 
    fail: function() { 
        console.log("fail"); 
    }, 
    complete: function (){ 
        console.log("complete"); 
    } 
})

# getConnectedDevices({success,fail,complete,services})

Gets the connected devices based on their UUID.

This method includes the devices that are currently connected to the device.

# Arguments

This method requires an object with the following attributes:

  • success (function(res)). Optional callback function corresponding to the successful execution. The argument of the callback function is an object with the member:
    • devices (array). List of the UUID of the devices and their information, represented as an object with the following members:
      • name (string). Name of a Bluetooth device.
      • deviceId (string). Unique ID of a Bluetooth device.
  • fail (function(msg,code)). Optional callback function corresponding to a failed execution. See the possible result codes.
  • complete (function). Optional callback function corresponding to the end of the execution.
  • services (array). Mandatory array of strings with the list of the UUIDs of the Bluetooth devices.

Example:

bluetooth.getConnectedDevices({ 
    success:function(res){ 
        console.log(res) 
        if (res.devices[0]) { 
            console.log(res.devices[0]. name) 
        } 
    }, 
    fail: function() { 
        console.log("fail"); 
    }, 
    complete: function (){ 
        console.log("complete"); 
    },
    services: ['FEE7']  
})

# createBLEConnection({deviceId,timeout,success,fail,complete})

Method to connect to a BLE device.

Connects to a previously connected device with the deviceId obtained when the device was discovered last time. No additional device discovery process is required.

# Arguments

This method requires an object with the following attributes:

  • deviceId (string). Mandatory attribute with the unique ID of a Bluetooth device.
  • timeout (number). Optional attribute with the timeout interval, in milliseconds (empty, no timeout).
  • success (function). Optional callback function corresponding to the successful execution.
  • fail (function(msg,code)). Optional callback function corresponding to a failed execution. See the possible result codes.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

bluetooth.createBLEConnection({ 
    deviceId:deviceId, 
    success:function(){ 
        console.log("success"); 
    }, 
    fail: function() { 
        console.log("fail"); 
    }, 
    complete: function (){ 
        console.log("complete"); 
    } 
})

# closeBLEConnection({deviceId,timeout,success,fail,complete})

Method to disconnect from a BLE device.

# Arguments

This method requires an object with the following attributes:

  • deviceId (string). Mandatory attribute with the unique ID of a Bluetooth device.
  • success (function). Optional callback function corresponding to the successful execution.
  • fail (function(msg,code)). Optional callback function corresponding to a failed execution. See the possible result codes.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

bluetooth.closeBLEConnection({ 
    deviceId:deviceId, 
    success:function(){ 
        console.log("success"); 
    }, 
    fail: function() { 
        console.log("fail"); 
    }, 
    complete: function (){ 
        console.log("complete"); 
    } 
})

# getBLEDeviceServices({deviceId,success,fail,complete})

Method to get all the services provided by a BLE device.

# Arguments

This method requires an object with the following attributes:

  • deviceId (string). Mandatory attribute with the unique ID of a Bluetooth device.
  • success (function). Optional callback function corresponding to the successful execution. The argument of the callback function is an object with the member:
    • services (array). List of the services provided by the device. Every service is represented by an object with the following members:
      • uuid (string). UUIDs mapping the services provided by the Bluetooth device.
      • isPrimary (boolean). Flag that indicates whether this service is the primary one.
  • fail (function(msg,code)). Optional callback function corresponding to a failed execution. See the possible result codes.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

bluetooth.getBLEDeviceServices({ 
    deviceId:deviceId, 
    success:function(res){ 
        console.log('device services:', res.services) 
    }, 
    fail: function() { 
        console.log("fail"); 
    }, 
    complete: function (){ 
        console.log("complete"); 
    } 
})

# getBLEDeviceCharacteristics({deviceId,serviceId,success,fail,complete})

Method to get the characteristic values of a service provided by a BLE device.

# Arguments

This method requires an object with the following attributes:

  • deviceId (string). Mandatory attribute with the unique ID of a Bluetooth device.
  • serviceId (string). Mandatory attribute with the service UUID that can be obtained using the - getBLEDeviceServices method.
  • success (function). Optional callback function corresponding to the successful execution. The argument of the callback function is an object with the member:
    • characteristics (array). List of the characteristic values of a service provided by the device. Every service is represented by an object with the following members:
      • uuid (string). UUID of a Bluetooth device characteristic value.
      • properties (object). Operations supported by a characteristic value, represented by the following attributes:
        • read (boolean). Flag that indicates if the characteristic value supports the read operation.
        • write (boolean). Flag that indicates if the characteristic value supports the write operation.
        • notify (boolean). Flag that indicates if the characteristic value supports the notify operation.
        • indicate (boolean). Flag that indicates if the characteristic value supports the indicate operation.
  • fail (function(msg,code)). Optional callback function corresponding to a failed execution. See the possible result codes.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

bluetooth.getBLEDeviceCharacteristics({ 
    deviceId:deviceId, 
    serviceId:serviceId, 
    success:function(res){ 
        console.log('device getBLEDeviceCharacteristics:', 
        res.characteristics)}, 
    fail: function() { 
        console.log("fail"); 
    }, 
    complete: function (){ 
        console.log("complete"); 
    } 
})

# readBLECharacteristicValue({deviceId,serviceId,characteristicId,success,fail,complete})

Method to get the characteristic values from a BLE device in binary.

WARNING

This method is only available when the Bluetooth device characteristic values support read operations.

# Arguments

This method requires an object with the following attributes:

  • deviceId (string). Mandatory attribute with the unique ID of a Bluetooth device.
  • serviceId (string). Mandatory attribute with the UUID of the service corresponding to the Bluetooth characteristic values.
  • characteristicId (string). Mandatory attribute with the UUID of a Bluetooth characteristic value.
  • success (function). Optional callback function corresponding to the successful execution.
  • fail (function(msg,code)). Optional callback function corresponding to a failed execution. See the possible result codes.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

bluetooth.readBLECharacteristicValue({
    // The Bluetooth device specified by deviceId here must have been connected through createBLEConnection. 
    deviceId:deviceId, 
    // The value of serviceId needs to be obtained through the getBLEDeviceServices API. 
    serviceId:serviceId, 
    // The value of characteristicId needs to be obtained through the getBLEDeviceCharacteristics API. 
    characteristicId, 
    success:function() { 
        console.log("success") 
    })
})

# writeBLECharacteristicValue({deviceId,serviceId,characteristicId,value,success,fail,complete})

Method to write binary data to the characteristic values of a BLE device.

WARNING

This method is only available when the Bluetooth device characteristic values support write operations.

# Arguments

This method requires an object with the following attributes:

  • deviceId (string). Mandatory attribute with the unique ID of a Bluetooth device.
  • serviceId (string). Mandatory attribute with the UUID of the service corresponding to the Bluetooth characteristic values.
  • characteristicId (string). Mandatory attribute with the UUID of a Bluetooth characteristic value.
  • value (ArrayBuffer). Mandatory attribute with the binary value to write.
  • success (function). Optional callback function corresponding to the successful execution.
  • fail (function(msg,code)). Optional callback function corresponding to a failed execution. See the possible result codes.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

bluetooth.writeBLECharacteristicValue({ 
    // The value of deviceId must be obtained through the getBluetoothDevices or onBluetoothDeviceFound. 
    // API. 
    deviceId:deviceId, 
    // The value of serviceId needs to be obtained through the getBLEDeviceServices API. 
    serviceId:serviceId, 
    // The value of characteristicId needs to be obtained through the getBLEDeviceCharacteristics API. 
    characteristicId:characteristicId, 
    // The value is of the ArrayBuffer type. 
    value: buffer, 
    success:function(){ 
        console.log("success"); 
    }, 
    fail: function() { 
        console.log("fail"); 
    }, 
    complete: function (){ 
        console.log("complete"); 
    } 
})

# notifyBLECharacteristicValueChange({deviceId,serviceId,characteristicId,state,success,fail,complete})

Method to notify any characteristic value changes to a BLE device and subscribes to BLE characteristic values.

WARNING

This method is only available when the Bluetooth device characteristic values support notify or indicate operations.

You must use this method to enable listening to characteristicValueChange events of the device.

# Arguments

This method requires an object with the following attributes:

  • deviceId (string). Mandatory attribute with the unique ID of a Bluetooth device.
  • serviceId (string). Mandatory attribute with the UUID of the service corresponding to the Bluetooth characteristic values.
  • characteristicId (string). Mandatory attribute with the UUID of a Bluetooth characteristic value.
  • state (boolean). Mandatory flag to enable the notify function.
  • success (function). Optional callback function corresponding to the successful execution.
  • fail (function(msg,code)). Optional callback function corresponding to a failed execution. See the possible result codes.
  • complete (function). Optional callback function corresponding to the end of the execution.

Example:

bluetooth.notifyBLECharacteristicValueChange({ 
    state: true, // Enable the notify function. 
    // The Bluetooth device specified by this deviceId must have been connected through createBLEConnection. 
    deviceId:deviceid, 
    // The value of serviceId needs to be obtained through the getBLEDeviceServices API. 
    serviceId:serviceId, 
    // The value of characteristicId needs to be obtained through the getBLEDeviceCharacteristics API. 
    characteristicId:characteristicId, 
    success:function(){ 
        console.log("success") 
    }, 
    fail: function() { 
        console.log("fail"); 
    }, 
    complete: function (){ 
        console.log("complete"); 
    } 
})

# Events

This service provides the following listeners:

# onadapterstatechange(function({available,discovering}))

Listener for Bluetooth adapter change events.

# Arguments

This method requires an object with the following attributes:

  • available (boolean). Flag that indicates if the Bluetooth adapter is available.
  • discovering (boolean). Flag that indicates if the Bluetooth adapter is searching for devices.

Example:

bluetooth.onadapterstatechange = function (event) { 
    console.log('adapterState changed, now is', event.available) 
}

# ondevicefound(function({devices}))

Listener triggered when new devices are discovered.

# Arguments

This method requires an object with the following attribute:

  • devices (array). List of devices found. Each device is represented by an object with the following members:
    • name (string). Name of a Bluetooth device. Some devices may have no names.
    • deviceId (string). Unique ID of a Bluetooth device.
    • RSSI (number). Signal strength of the current Bluetooth device.
    • advertisData (ArrayBuffer). The ManufacturerData segment in the broadcast data of the current Bluetooth device.
    • advertisServiceUUIDs (array). The ServiceUUIDs segment in the broadcast data of the current Bluetooth device.
    • localName (string). The LocalName segment in the broadcast data of the current Bluetooth device.
    • serviceData (string). ServiceData segment in the broadcast data of the current Bluetooth device. The structure returned is as follows: {"service uuid string": ArrayBuffer}.

Example:

bluetooth.ondevicefound = function (event) { 
    console.log('new device list has founded') 
}

# onblecharacteristicvaluechange(function({deviceId,serviceId,characteristicId,value}))

Listener triggered when there are changes in the characteristic values of a BLE device.

TIP

To receive notifications sent by the connected Bluetooth device, enable the notifyBLECharacteristicValueChange method in advance.

# Arguments

This method requires an object with the following attributes:

  • deviceId (string). The unique ID of a Bluetooth device.
  • serviceId (string). The UUID of the service corresponding to the Bluetooth characteristic values.
  • characteristicId (string). UUID of a Bluetooth characteristic value.
  • value (ArrayBuffer). The latest characteristic value.

Example:

bluetooth.onblecharacteristicvaluechange = function (event) { 
    console.log(event.value) 
}

# onbleconnectionstatechange(function({deviceId,connected}))

Listener triggered when there are changes in the connection status with a BLE device.

# Arguments

This method requires an object with the following attributes:

  • deviceId (string). The unique ID of a Bluetooth device.
  • connected (boolean). Flag indicating if the BLE device is connected.

Example:

bluetooth.onbleconnectionstatechange = function(res){ 
  console.log('device'+ res.deviceId+'state has changed,connected:'+res.connected) 
}

# Result Codes

Result code Message Description
0 ok Normal state.
10000 not init` No connection initiated.
10001 not available` The Bluetooth adapter is unavailable.
10002 no device` The specified device is not found.
10003 connection fail` Connection failed.
10004 no service` The specified service is not found.
10005 no characteristic` The specified characteristics value is not found.
10006 no connection` The Bluetooth device is disconnected.
10007 property not support` The current characteristic value does not support the operation.
10008 system error` Other exceptions reported by the system.
10009 system not support` The system does not support BLE.