Bluetooth Low Energy

Last Updated on : 2024-04-04 16:18:56download

This topic describes the Bluetooth Low Energy (LE) technology that can enable point-to-point communication between a Bluetooth LE device and a mobile phone.

Preparation

  • System requirements: Android 4.3 or later

  • Manifest permissions:

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
    
  • Bluetooth permission precheck: It is performed before Bluetooth scanning and connection. Otherwise, the app cannot use Bluetooth as expected.

    • Before scanning and connection, the app checks if it is allowed to access location services.

    • Check if the phone’s Bluetooth is turned on.

      The Commercial Lighting App SDK does not provide the logic for precheck. You can implement it on your own.

Scan for devices

Start scanning

Bluetooth devices in pairing mode broadcast packets. The SDK can receive and parse these packets to discover nearby Tuya-enabled Bluetooth LE or combo devices.

Precheck is required before Bluetooth scanning. Scanning can be initiated only after required permissions are granted.

  • Check if the phone’s Bluetooth is turned on.
  • Check if the app is allowed to access location services.

API description

void startLeScan(LeScanSetting setting, BleScanResponse response);

Parameter description

Parameter Type Description
setting LeScanSetting The scanning settings.
response BleScanResponse The callback for the scan result. It cannot be empty.

Builder class

LeScanSetting.Builder is used to build the settings for device scanning.

Method Parameter Description Required
setTimeout() long The timeout value, defaulting to 40000, in milliseconds. No
addScanType() ScanType
  • SINGLE: Bluetooth LE device
  • SIG_MESH:Bluetooth mesh device
Required. At least one type is selected.
setRepeatFilter() boolean Specifies whether a repeat filter is enabled. Default value: true. No

Example

LeScanSetting scanSetting = new LeScanSetting.Builder()
        .setTimeout(60000) // Scan timeout (ms)
        .addScanType(ScanType.SINGLE) // To scan for Bluetooth devices, add ScanType.SINGLE.
        // .addScanType(ScanType.SIG_MESH)  You can also add other types of devices.
        .build();

// Start scanning.
ThingOSBLE.operator().startLeScan.startLeScan(scanSetting, new BleScanResponse() {
    @Override
    public void onResult(ScanDeviceBean bean) {
        // The callback for scan results.  TODO
    }
});

Callback description

ScanDeviceBean

Property Type Description
id String The scanning ID, which is typically the UUID to uniquely identify a device.
name String The name of the discovered Bluetooth device. The value is empty in most cases.
providerName String The name of the Bluetooth LE device provider. SingleBleProvider means that your development is only targeted to Bluetooth LE devices and this field can be ignored.
data byte[] The raw data.
configType String
  • config_type_single: Bluetooth LE device
  • config_type_wifi: Bluetooth and Wi-Fi combo device
productId String The product ID.
uuid String The UUID that is used to uniquely identify the device.
mac String The MAC address of the device. It cannot be used as a unique identifier.
isbind boolean Indicates whether the device has been bound. If a callback is invoked, the device has not been paired.
flag int
  • bit0: Indicates whether a combo device supports the 5 GHz Wi-Fi network.
  • bit2: Indicates whether a shared device is used.
  • bit3: Indicates whether to pair over Bluetooth when internet is unavailable.
  • bit4: Indicates whether a device can be paired via QR code scanning.
address String The address of the device.
deviceType int The type of device used to identify the protocol a device uses. This parameter can be ignored.

deviceType indicates the type of device to be paired. See Pair Combo Device and Pair Bluetooth LE Device for details.

deviceType configType Device type
200 config_type_single Bluetooth device
300 config_type_single Bluetooth device
301 config_type_wifi Wi-Fi and Bluetooth LE combo device
304 config_type_wifi Wi-Fi and Bluetooth LE combo device (Bluetooth as fallback pairing mode)
400 config_type_single Bluetooth device
401 config_type_wifi Wi-Fi and Bluetooth LE combo device
404 config_type_wifi Wi-Fi and Bluetooth LE combo device (Bluetooth as fallback pairing mode)

Get device name

Request the name and icon of the discovered device.

API description

void getActivatorDeviceInfo(String productId, String uuid, String mac, IThingDataCallback<ConfigProductInfoBean> callback);

Parameter description

Parameter Type Description
productId String ScanDeviceBean.getProductId
uuid String ScanDeviceBean.getUuid
mac String ScanDeviceBean.getMac is null for most devices. It is specified only for specific categories.

Example

ThingOSActivator.deviceActivator().getActivatorDeviceInfo(
    scanDeviceBean.getProductId(),
    scanDeviceBean.getUuid(),
    scanDeviceBean.getMac(),
    new IThingDataCallback<ConfigProductInfoBean>() {
        @Override
        public void onSuccess(ConfigProductInfoBean result) {

        }

        @Override
        public void onError(String errorCode, String errorMessage) {

        }
});

Callback description

ConfigProductInfoBean

Property Type Description
name String The product name. Its value is set in the cloud. Typically, the name is specified when the product is created.
icon String The icon of the product.

Stop scanning

Stop scanning for devices. For example, scanning can be stopped when users leave the pairing page or begin the pairing process.

API description

void stopLeScan();

Example

ThingOSBLE.operator().stopLeScan();

Pair Bluetooth LE device

Start pairing

If the value of configType is config_type_single, a Bluetooth LE device is discovered. If it is config_type_wifi, a combo device is discovered.

API description

void startActivator(BleActivatorBean bleActivatorBean, IBleActivatorListener listener);

Parameter description

Parameter Type Description
bleActivatorBean BleActivatorBean The collection of parameters for the target device.
listener IBleActivatorListener The callback for the pairing result.

BleActivatorBean stores the parameters and settings of the target device.

Property Type Description Required
homeId long The relation ID of the area to which the device belongs. See Get Area Relation ID. Required
uuid String The device UUID that is returned after scanning. Required
address String The device address that is returned after scanning. No
productId String The product ID that is returned after scanning. No
deviceType Integer The device type that is returned after scanning. Required
isShare boolean Indicates whether this is a shared device. The value is returned after scanning. Default value: false. No
timeout long The pairing timeout, which determines whether the pairing process failed. Unit: milliseconds. Default value: 60000. No

Example

// mScanDeviceBean is from the ScanDeviceBean in the scan callback.
BleActivatorBean bleActivatorBean = new BleActivatorBean(mScanDeviceBean);

bleActivatorBean.homeId = 123456; // homeId
bleActivatorBean.address = mScanDeviceBean.getAddress(); // Device address
bleActivatorBean.deviceType = mScanDeviceBean.getDeviceType(); // Device type
bleActivatorBean.uuid = mScanDeviceBean.getUuid(); // UUID
bleActivatorBean.productId = mScanDeviceBean.getProductId(); // Product ID
bleActivatorBean.isShare = (mScanDeviceBean.getFlag() >> 2) & 0x01 == 1; // Whether this is a shared device

// Start pairing
ThingOSActivator.activator().newBleActivator().startActivator(bleActivatorBean, new IBleActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
        // Pairing succeeded
    }

    @Override
    public void onFailure(int code, String msg, Object handle) {
        // Pairing failed
    }
});

Stop pairing

Stop the pairing process.

API description

void stopActivator(String uuid);

Parameter description

Parameter Type Description
uuid String The UUID of the discovered device, which is the value of ScanDeviceBean.uuid.

Example

ThingOSBLE.manager().stopBleConfig("uuid");

Pair combo device

Start pairing

Pair a Wi-Fi and Bluetooth LE combo device after it is discovered. If the value of configType is config_type_single, a Bluetooth LE device is discovered. If it is config_type_wifi, a combo device is discovered.

API description

void startActivator(MultiModeActivatorBean multiModeActivatorBean, IMultiModeActivatorListener listener);

Parameter description

Parameter Type Description
multiModeActivatorBean MultiModeActivatorBean The collection of parameters for the target combo device.
listener IMultiModeActivatorListener The callback for the result of pairing.

MultiModeActivatorBean

Property Type Description
deviceType Integer The device type that is returned after scanning.
uuid String The device UUID that is returned after scanning.
address String The device address that is returned after scanning.
mac String The device MAC address that is returned after scanning.
ssid String The SSID of the Wi-Fi network.
pwd String The password of the Wi-Fi network.
token String The pairing token. You can request a token in the same way as that for pairing Wi-Fi devices.
homeId long The relation ID of the area to which the device belongs. See Get Area Relation ID.
timeout long The pairing timeout in milliseconds, which determines whether the pairing process failed.

If not specified, most devices only support the 2.4 GHz Wi-Fi network, while certain types of devices also support the 5 GHz Wi-Fi network. ScanDeviceBean.flag indicates the supported band frequency.

Example

// mScanDeviceBean is from the ScanDeviceBean in the scan callback.
MultiModeActivatorBean multiModeActivatorBean = new MultiModeActivatorBean(mScanDeviceBean);

// mScanDeviceBean is from the ScanDeviceBean in the scan callback.
multiModeActivatorBean.deviceType = mScanDeviceBean.getDeviceType(); // Device type
multiModeActivatorBean.uuid = mScanDeviceBean.getUuid(); // Device's UUID
multiModeActivatorBean.address = mScanDeviceBean.getAddress(); // Device address
multiModeActivatorBean.mac = mScanDeviceBean.getMac(); // Device's MAC address
multiModeActivatorBean.ssid = "WIFI_2.4G"; // Wi-Fi SSID
multiModeActivatorBean.pwd = "WIFI_PASSWORD"; // Wi-Fi password
multiModeActivatorBean.token = "abcd1234"; // Obtained token
multiModeActivatorBean.homeId = ; // Relation ID
multiModeActivatorBean.timeout = 120000; // Timeout

// Start pairing
ThingOSActivator.activator().newMultiModeActivator().startActivator(multiModeActivatorBean, new IMultiModeActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
        // Pairing succeeded
    }

    @Override
    public void onFailure(int code, String msg, Object handle) {
        // Pairing failed
    }
});

Callback description

  • DeviceBean: The type of device data. For more information, see DeviceBean.

  • Object handle: The response type of handle is the entity object ConfigErrorBean. The parameters are described in the following table.

    Parameter Type Description
    name String The name of the device.
    errorCode String The error code.
    devId String The device ID.
    iconUrl String The device icon.
    errorMsg String The error message.

Optimize combo device pairing

  • This method allows the app to maintain the Bluetooth connection with the device while pairing. If an error occurs when the device attempts to connect to the router for cloud-based activation, the error will be reported to the app.
  • The TuyaOS version of the firmware built into the target device must be v3.6.1 or later.

API description

This method is similar to pairing a Bluetooth LE device, but the callback applies to combo devices, including those using Bluetooth as the fallback pairing mode.

void startActivator(MultiModeActivatorBean multiModeActivatorBean, IExtMultiModeActivatorListener listener);

Example

ThingOSActivator.activator().newMultiModeActivator().startActivator(multiModeActivatorBean, new IMultiModeActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
        // Pairing succeeded
    }

    @Override
    public void onFailure(int code, String msg, Object handle) {
        // Pairing failed
    }
    public void onActivatorStatePauseCallback(PauseStateData stateData) {
        // The data reported by the device, including connection to the router and other details. See the parameter description.
    }
});

Parameter description

PauseStateData

Parameter Description
uuid The universally unique identifier (UUID).
configStage The current pairing stage.
status The current pairing status.

Description

configStage Description Status
0 Pairing initiation
  • 0: The pairing information is returned successfully.
  • 1: The pairing information is incorrect.
1 Delegate activation
  • 0: The delegate information is returned successfully.
  • 1: The pairing information is incorrect.
2 Network connection
  • 0: Connected to the router successfully.
  • 1: Incorrect network information.
  • 2: The router is not found.
  • 3: Incorrect Wi-Fi password.
  • 4: Failed to connect to the router.
  • 5: Failed to get the DHCP-assigned IP address.
3 Activation
  • 1: Incorrect activation information.
  • 6: Failed to connect the device to the cloud.
  • 7: Failed to get the URL.
  • 8: The request to activate the device failed.
  • 9: Activated successfully.

Stop pairing

Stop the pairing process. If the device is in the activation stage, it may still be paired even if you stop the pairing process.

API description

ThingOSActivator.activator().newMultiModeActivator().stopActivator(uuid);

Parameter description

Parameter Type Description
devUuid String The UUID of the discovered device.

Example

ThingOSActivator.activator().newMultiModeActivator().stopActivator("uuidxxxx");

Pair combo device locally over Bluetooth

Some Wi-Fi and Bluetooth LE combo devices can pair over Bluetooth when the Wi-Fi connection is not available. The app sends the pairing information to the device over Bluetooth. The device will attempt to connect to the Wi-Fi network. However, if the device fails to connect to the internet for activation, the app will pair with the device over Bluetooth locally.

You can call the method getDeviceType() in ScanDeviceBean to check whether a discovered device supports pairing over Bluetooth. The return value 404 or 304 indicates that it is supported. Otherwise, it is not.

Yes
No
Yes
No
Device enters pairing mode.
startActivator()
Device is activated in the cloud over Wi-Fi.
Pairing succeeded.
Device can be
controlled locally and
through the cloud.
Device is activated locally over Bluetooth.
Pairing succeeded.
Device can be
controlled locally.
Pairing failed.

API description

void startActivator(MultiModeActivatorBean multiModeActivatorBean, IMultiModeActivatorListener listener);

MultiModeActivatorBean

Parameter Type Description
homeId long The relation ID of the area to which the device belongs. See Get Area Relation ID.
uuid String The UUID of the target device.
deviceType int Device type
address String The address of the device.
timeout long The pairing timeout in milliseconds, which determines whether the pairing process failed.
phase1Timeout long The timeout for cloud-based activation, defaulting to 60000, in milliseconds.
ssid String The SSID of the target Wi-Fi network.
pwd String The password of the target Wi-Fi network. If not specified, pass an empty string.
token String The pairing token generated in the cloud to verify the account identity. See Get Token for details.
mac String The MAC address of the device.

If not specified, most devices only support the 2.4 GHz Wi-Fi network, while certain types of devices also support the 5 GHz Wi-Fi network. ScanDeviceBean.flag indicates the supported band frequency.

Example

// scanDeviceBean is the callback for the information about the discovered Bluetooth device.
MultiModeActivatorBean multiModeActivatorBean = new MultiModeActivatorBean(scanDeviceBean);
// Set Wi-Fi SSID
multiModeActivatorBean.ssid = "SSID_xxx";
// Set Wi-Fi password
multiModeActivatorBean.pwd = "pwd_xxx";
// Set device's UUID
multiModeActivatorBean.uuid = scanDeviceBean.getUuid();
// Set device type
multiModeActivatorBean.deviceType = scanDeviceBean.getDeviceType();
// Set device's MAC address
multiModeActivatorBean.mac = scanDeviceBean.getMac();
// Set device address
multiModeActivatorBean.address = scanDeviceBean.getAddress();
// Set HomeID
multiModeActivatorBean.homeId = "homeId_xxx";
// Set the obtained token
multiModeActivatorBean.token = "token_xxx";
// Set pairing timeout (ms)
multiModeActivatorBean.timeout = 120 * 1000L;
// Set Wi-Fi connection timeout (ms)
multiModeActivatorBean.phase1Timeout = 60 * 1000L;

// The callback for pairing results.
IMultiModeActivatorListener listener = new IMultiModeActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
        // Pairing succeeded
    }
    @Override
    public void onFailure(int code, String error, Object handle) {
        // Pairing failed
    }
};

// Start pairing
ThingOSActivator.activator().newMultiModeActivator().startActivator(multiModeActivatorBean, listener);

  • To activate a device with the cloud, make sure it is connected over Bluetooth for data transmission. You can call getCommunicationOnline(CommunicationEnum.BLE) in DeviceBean to check the Bluetooth connection status of the device. The cloud-based activation method can be called only after true is returned.
  • You can call deviceBean.getMeta().get("wifiEnable") to check if the device is connected to the Wi-Fi network. A value of true indicates that the device is ready to be activated with the cloud.

Activate locally-connected combo device in cloud

A combo device that fails to connect to the Wi-Fi network can be controlled locally over Bluetooth. To attempt to connect the combo device to the Wi-Fi network again for activation, use the following method. Before the call, ensure that the target device is connected locally over Bluetooth and has not been activated in the cloud.

  • You can call getCommunicationOnline(CommunicationEnum.BLE) in DeviceBean to check the Bluetooth connection status.

  • To check whether the device has been connected to the cloud, call deviceBean.getMeta().get("wifiEnable").

API description

void startWifiEnable(MultiModeActivatorBean multiModeActivatorBean, IMultiModeActivatorListener listener);

Parameter description

Parameter Type Description
multiModeActivatorBean MultiModeActivatorBean The collection of parameters for the target device.
listener IMultiModeActivatorListener The callback for reconnecting to the Wi-Fi network.

MultiModeActivatorBean

Parameter Type Description
timeout long The timeout, in milliseconds, for reconnecting to the Wi-Fi network to activate in the cloud.
ssid String The SSID of the target Wi-Fi network.
pwd String The password of the target Wi-Fi network. If not specified, pass an empty string.
devId Long The ID of the device to be connected over Wi-Fi.

Example

MultiModeActivatorBean multiModeActivatorBean = new MultiModeActivatorBean(scanDeviceBean);
multiModeActivatorBean.devId = "devId_xxx"; // Device's devId
multiModeActivatorBean.ssid = "ssid_xxx"; // Target Wi-Fi SSID
multiModeActivatorBean.pwd = "pwd_xxx"; // Target Wi-Fi password
multiModeActivatorBean.timeout = 120 * 1000L; // Timeout (ms)

// The callback for the result of connecting to the cloud.
IMultiModeActivatorListener listener = new IMultiModeActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
        // Success.
    }
    @Override
    public void onFailure(int code, String msg, Object handle) {
        // Failure.
    }
};

// Reconnect to Wi-Fi and activate in the cloud.
ThingOSActivator.activator().newMultiModeActivator().startWifiEnable(multiModeActivatorBean, listener);

Activate combo device directly over Bluetooth

Pair a combo device over Bluetooth for local control if the device fails to connect to the Wi-Fi network.

Example

// scanDeviceBean is the callback for the information about the discovered Bluetooth device.
MultiModeActivatorBean multiModeActivatorBean = new MultiModeActivatorBean(scanDeviceBean);
// Set device's UUID
multiModeActivatorBean.uuid = scanDeviceBean.getUuid();
// Set device type
multiModeActivatorBean.deviceType = scanDeviceBean.getDeviceType();
// Set device's MAC address
multiModeActivatorBean.mac = scanDeviceBean.getMac();
// Set device address
multiModeActivatorBean.address = scanDeviceBean.getAddress();
// Set HomeID
multiModeActivatorBean.homeId = "homeId_xxx";
// Set the obtained token
multiModeActivatorBean.token = "token_xxx";
// Set pairing timeout (ms)
multiModeActivatorBean.timeout = 120 * 1000L;
// Set Wi-Fi connection timeout (ms)
multiModeActivatorBean.phase1Timeout = 60 * 1000L;

// The callback for pairing results.
IMultiModeActivatorListener listener = new IMultiModeActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
        //Pairing succeeded
    }
    @Override
    public void onFailure(int code, String msg, Object handle) {
        // Pairing failed
    }
};

// Activate the device locally over Bluetooth.
ThingOSActivator.activator().newMultiModeActivator().startBleActivator(multiModeActivatorBean, listener);

Restart pairing

  • Ask users to input the correct Wi-Fi name and password, and restart pairing if the password is incorrect. During the pairing process, the SDK automatically connects to the device within the specified period. Upon successful connection, it will get and report the device status. This feature is supported by the latest firmware version only.
  • The TuyaOS version of the firmware built into the target device must be v3.6.1 or later.

API description

/**
 * Restart pairing
 * return -1: Failure. Restart pairing is not supported. 0: Restart pairing is supported and the pairing process is triggered.
**/
int resumeActivator(@NonNull ResumeActivatorBean multiModeActivatorBean);

Parameter description

ResumeActivatorBean

Parameter Description
uuid The UUID of the target device.
ssid The name of the target Wi-Fi network.
pwd The password of the target Wi-Fi network.
resumeType The type of pairing to be restarted.
  • ResumeActivatorBean.RESUME_TYPE_WIFI: Pair a combo device over Wi-Fi.
  • ResumeActivatorBean.RESUME_TYPE_BLE: Pair a combo device over Bluetooth.

Example

ResumeActivatorBean bean = new ResumeActivatorBean.Builder()
                    .setResumeType(ResumeActivatorBean.RESUME_TYPE_WIFI)
                    .setUuid(param.uuid)
                    .setSsid(param.ssid)
                    .setPassword(param.pwd)
                    .build();
ThingOSActivator.activator().newMultiModeActivator().resumeActivator(bean);

Optimize combo device pairing

The optimized pairing solution requires the target device to be built with TuyaOS firmware v3.6.1 or later.

Scan for Wi-Fi networks

API description

Connect to a device over Bluetooth using the captured advertising packet and UUID, and then scan for supported Wi-Fi networks.

void queryDeviceConfigState(MultiModeQueryBuilder queryBuilder, IThingResultCallback<List<WiFiInfo>> callback);

Parameter description

MultiModeQueryBuilder

Parameter Description
homeId The relation ID of the area to which the device belongs. See Get Area Relation ID.
timeout (Optional) The operation timeout, in milliseconds. It can be set to 0.
scanDeviceBean The captured advertising packet.

Example

MultiModeQueryBuilder queryBuilder = new MultiModeQueryBuilder.Builder()
                .setHomeId(homeId)
                .setTimeout(timeout * 1000)
                .setScanDeviceBean(scandeviceBean)// The advertising packet captured by scandeviceBean. The SDK will match the Bluetooth device by UUID to connect it over Bluetooth.
                .build();
ThingOSActivator.activator().newMultiModeActivator().queryDeviceConfigState(queryBuilder, new IThingResultCallback<List<com.thingclips.smart.android.ble.api.WiFiInfo>>() {
        @Override
        public void onSuccess(List<com.thingclips.smart.android.ble.api.WiFiInfo>result) {
            // Wi-Fi network list is obtained.
        }
        @Override
        public void onError(String errorCode, String errorMessage) {
            // Failed to obtain Wi-Fi network list.
        }
    });

Start pairing

API description

Start pairing after the device is connected to a discovered Wi-Fi network. This API method is designed to minimize resource usage and avoid repeated connections.

void startOptimizationActivator(@NonNull MultiModeActivatorBuilder activatorBuilder, IMultiModeActivatorListener listener);

Parameter description

MultiModeActivatorBuilder

Parameter Description
uuid The UUID of the target device.
ssid The name of the target Wi-Fi network.
pwd The password of the target Wi-Fi network.
timeout The pairing timeout, in milliseconds.

Example

MultiModeActivatorBuilder builder = new MultiModeActivatorBuilder.Builder()
                .setUuid(uuid)
                .setSsid(ssid)
                .setPwd(pwd)
                .setTimeout(120 * 1000)
                .setToken(token)
                .build();
ThingOSActivator.activator().newMultiModeActivator().startOptimizationActivator(builder, new IMultiModeActivatorListener() {
        @Override
        public void onSuccess(DeviceBean deviceBean) {
            //Pairing succeeded
        }
        @Override
        public void onFailure(int code, String msg, Object handle) {
            //Pairing failed, see error codes 207206 to 207223
        }
    });

Restart pairing

Ask users to input the correct Wi-Fi name and password, and restart pairing if the password is incorrect. During the pairing process, the SDK automatically connects to the device within the specified period. Upon successful connection, it will get and report the device status. This feature is supported by the latest firmware version only.

API description

/**
 * Restart pairing
 * return -1: Failure. Restart pairing is not supported. 0: Restart pairing is supported and the pairing process is triggered.
**/
int resumeActivator(@NonNull ResumeActivatorBean multiModeActivatorBean);

Parameter description

ResumeActivatorBean

Parameter Description
uuid The UUID of the target device.
ssid The name of the target Wi-Fi network.
pwd The password of the target Wi-Fi network.
resumeType The type of pairing to be restarted. Set the value to ResumeActivatorBean.RESUME_TYPE_WIFI for the optimized combo device pairing. This does not apply to combo device pairing over Bluetooth.

Example

ResumeActivatorBean bean = new ResumeActivatorBean.Builder()
                    .setResumeType(ResumeActivatorBean.RESUME_TYPE_WIFI)// Optimized pairing process, only applying to combo devices (including Plug&Play), fixed to RESUME_TYPE_WIFI.
                    .setUuid(param.uuid)
                    .setSsid(param.ssid)
                    .setPassword(param.pwd)
                    .build();
ThingOSActivator.activator().newMultiModeActivator().resumeActivator(bean);

Stop pairing

Example

ThingOSActivator.activator().newMultiModeActivator().stopActivator(uuid);

Operate device

This section describes how to operate a paired Bluetooth LE device. For example, check the device status, connect to the device, or unbind it.

Check online status

  • Method 1: Check if the device is online in the cloud. If the Bluetooth device has been added to a gateway, it can stay online in the cloud.

    ThingOSDevice.getDeviceBean(devId).getIsOnline();
    
  • Method 2: Check if the device is locally online over Bluetooth. Generally, you only need to take care of the local connection status for a Bluetooth device. If the Bluetooth device is added to a Bluetooth gateway, the device status in the cloud must be checked.

    ThingOSBLE.manager().isBleLocalOnline(devId);
    

Connect to offline device

API description

void connectBleDevice(List<BleConnectBuilder> builderList);

Parameter description

Parameter Type Description
builderList List BleConnectBuilder is used to build the settings for device connections.

Description of BleConnectBuilder

Method Parameter Description
setDirectConnect() boolean
  • true: Use the cache to connect to a device.
  • false: Not use the cache to connect to a device.
setDevId() String The ID of the target device.
setScanTimeout() Integer The scanning timeout, in milliseconds.
setLevel() BleConnectBuilder.Level
  • NORMAL (default): If the connection limit is reached, ignore the connection request.
  • FORCE: If the connection limit is reached, free resources to connect to the current device.

Example

List<BleConnectBuilder> builderList = new ArrayList<>();

BleConnectBuilder bleConnectBuilder1 = new BleConnectBuilder();
BleConnectBuilder bleConnectBuilder2 = new BleConnectBuilder();

bleConnectBuilder1.setDevId(devId1); // devId of device 1
bleConnectBuilder2.setDevId(devId2); // devId of device 2

builderList.add(bleConnectBuilder1); // Add device 1
builderList.add(bleConnectBuilder2); // Add device 2

ThingOSBLE.manager().connectBleDevice(builderList); // Start connection.

Disconnect device

API description

void disconnectBleDevice(List<BleConnectBuilder> builderList);

Parameter description

Parameter Type Description
builderList List BleConnectBuilder is used to build the settings for device disconnections.

Description of BleConnectBuilder

Method Parameter Description
setDevId() String The ID of the target device.

Example

List<BleConnectBuilder> builderList = new ArrayList<>();

builderList.add(new BleConnectBuilder().setDevId(devId1)); // devId of device 1
builderList.add(new BleConnectBuilder().setDevId(devId2)); // devId of device 2

ThingOSBLE.manager().disconnectBleDevice(builderList); // Disconnection.

Manage device

Listen for device status by using the device operation class. The operations are similar to those for Wi-Fi devices. For more information, see Device Management. The following commands are supported:

  • Get device information

  • Initialize device control

  • Register device listener

  • Remove device listener

  • Data points of devices

  • Rename a device

  • Remove a device

    Similar to a Wi-Fi device, to unbind a Bluetooth device, call ThingOSDevice.newDeviceInstance("devId").removeDevice() or resetFactory(). However, note the following differences:

    • If the device is connected locally when removed, it will be deleted from both the cloud and locally. If the device is offline when removed, it will only be deleted from the cloud and remain bound locally.
    • To pair the device, users must manually reset it to trigger pairing mode.
    • During scanning, if the SDK detects a device in a bound state locally but unbound in the cloud, it will reset the device automatically.
  • Recycle device resources

Update firmware

Firmware information must be checked before an OTA update.

Check firmware information

API description

void requestUpgradeInfo(String devId, IRequestUpgradeInfoCallback callback);

Parameter description

Parameter Type Description
devId String The ID of the target device.
callback IRequestUpgradeInfoCallback The callback.

Example

private IBlueMeshManager getBleMeshManager() {
        IThingBlueMeshPlugin iThingBlueMeshPlugin = PluginManager.service(IThingBlueMeshPlugin.class);
        if (iThingBlueMeshPlugin == null) return null;
        return iThingBlueMeshPlugin.getMeshInstance();
    }

getBleMeshManager().requestUpgradeInfo(mDevID, new IRequestUpgradeInfoCallback() { @Override public void onSuccess(ArrayList<BLEUpgradeBean> bleUpgradeBeans) { } @Override public void onError(String errorCode, String errorMsg) { } });

BLEUpgradeBean returns the firmware update information as described in the following table.

Field Type Description
upgradeStatus Integer The update status.
  • 0: No update available
  • 1: An update available
  • 2: Updating
version String The latest version.
currentVersion String The current version.
timeout Integer The specified timeout, in seconds.
upgradeType Integer
  • 0: Update notification
  • 2: Forced update
  • 3: Check for update
type Integer The source of the firmware.
  • 0: Wi-Fi module
  • 1: Bluetooth module
  • 2: GPRS module
  • 3: Zigbee module
  • 9: MCU module
typeDesc String The description of the update.
lastUpgradeTime long The last update time, in milliseconds.
url String The URL to download the update. This parameter has a value when type is 1 or 9.
fileSize long The size of the update.
md5 String The MD5 hash value of the update.

Perform OTA updates

Start the OTA update after the firmware update is downloaded.

API description

void startBleOta(String uuid, int type, String version, String binPackagePath, OnBleUpgradeListener listener);

Parameter description

Parameter Type Description
uuid String The UUID of the target device. You can call deviceBean.getUuid() to get the value.
type int
  • 0: Bluetooth firmware update, with BLEUpgradeBean.type being 1.
  • 1: MCU update, BLEUpgradeBean.type being 9.
version String The version of the new firmware.
binPackagePath String The path of the downloaded firmware.
listener OnBleUpgradeListener The callback for the update progress.
ThingOSBLE.manager().startBleOta(uuid, type, version, binPackagePath, new OnBleUpgradeListener() {
    @Override
    public void onUpgrade(int percent) {
        // The update progress in percentage.
    }

    @Override
    public void onSuccess() {
        // Update succeeded.
    }

    @Override
    public void onFail(String errorCode, String errorMsg) {
        // Update failed.
    }
});

Error code

Error code Description
1 Incorrect format of the received packet.
2 Router is not found.
3 Incorrect Wi-Fi password.
4 The device failed to connect to the router.
5 Failed to get the DHCP-assigned IP address.
6 Failed to connect the device to the cloud.
100 The user canceled the pairing process.
101 Bluetooth connection error.
102 Bluetooth discovery error.
103 Failed to turn on the Bluetooth channel.
104 Failed to get Bluetooth device information.
105 Failed to pair the device over Bluetooth.
106 Pairing timeout.
107 Failed to send Wi-Fi information.
108 The token has expired.
109 Failed to get the Bluetooth encryption key.
110 The specified device does not exist.
111 Failed to register the device in the cloud.
112 Failed to activate the device in the cloud.
113 The specified device has been bound in the cloud.
114 The current connection is manually closed.
115 Failed to request device information from the cloud.
116 The specified device is being paired in another mode.
117 The OTA update failed.
118 The OTA update timed out.
119 Failed to verify the parameters for Wi-Fi pairing.
207206 The device status is unknown.
207207 The device does not support getting available Wi-Fi networks.
207222 Failed to get available Wi-Fi networks.
207226 The list of Wi-Fi networks is empty.
207227 The command to get Wi-Fi networks timed out.
207209 Wrong pairing information.
207210 Router is not found.
207211 Incorrect Wi-Fi password.
207212 Failed to connect to the router.
207213 Failed to get the DHCP-assigned IP address.
207214 Cloud activation error.
207215 Failed to connect the device to the cloud.
207216 The request to activate the device in the cloud failed.
207218 The cloud request failed.
207219 IoT DNS connection failed.
207220 Device pairing timed out.
207221 Failed to connect to the device over Bluetooth.