Bluetooth LE Devices

Last Updated on : 2023-11-29 07:23:54download

This topic describes the technology to create a peer-to-peer connection between a Bluetooth or Bluetooth Low Energy (LE) device and a mobile phone.

Preparation

  • System requirements: Bluetooth connectivity requires Android 4.3 and later, and the Smart Life App SDK supports Android 4.4 and 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" />
    
  • Precheck of Bluetooth permissions: This percheck is essential. Otherwise, the app cannot use Bluetooth connectivity as expected.
    • Check whether the location feature is enabled for an app before it uses Bluetooth connectivity or starts scanning.
    • Check whether the Bluetooth feature is enabled.

      This precheck is not provided by the Smart Life App SDK. You can manually perform the precheck.

Device scanning

Start scanning

Bluetooth devices to be paired broadcast Bluetooth packets. The SDK parses the packets with the protocol and discovers the target Tuya-enabled Bluetooth LE devices and combo devices.

Bluetooth permissions must be prechecked. Scanning is allowed only after required permissions are granted.

  • Check whether Bluetooth is enabled.
  • Check whether the app is granted location permissions.

API description

void startLeScan(LeScanSetting setting, BleScanResponse response);

Parameters

Parameter Type Description
setting LeScanSetting The setting of the scanning feature.
response BleScanResponse The callback to return the scanning result. It cannot be empty.

Builder class

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

Method name Type Description Required
setTimeout() long The timeout value of a pairing task.
Default value: 40000. Unit: milliseconds.
No
addScanType() ScanType
  • SINGLE: scan for Bluetooth LE devices
  • MESH: scan for Tuya mesh devices
  • SIG_MESH: scan for Bluetooth mesh devices
  • SINGLE_QR: scan a QR code for pairing
Yes
setRepeatFilter() Boolean Specifies whether a repeat filter is enabled. Default value: true. No

Example

LeScanSetting scanSetting = new LeScanSetting.Builder()
        .setTimeout(60000) // The duration of the scanning. Unit: milliseconds.
        .addScanType(ScanType.SINGLE) // ScanType.SINGLE: scans for Bluetooth LE devices.
        // .addScanType(ScanType.SIG_MESH): scans for other types of devices.
        .build();

// Starts scanning.
ThingHomeSdk.getBleOperator().startLeScan(scanSetting, new BleScanResponse() {
    @Override
    public void onResult(ScanDeviceBean bean) {
        // The callback to return the scanning result.
    }
});

Callback description

Properties of ScanDeviceBean

Property Type Description
id String The UUID that is used to uniquely identify the device.
name String The name of the discovered Bluetooth device. The value is empty in most cases.
providerName String The name of a Bluetooth LE device provider. A value of 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
  • If the configType property is config_type_single, a Bluetooth LE device is discovered.
  • If it is config_type_wifi, a combo device is discovered.
productId String The product ID (PID).
uuid String The UUID that is used to uniquely identify the device.
mac String The media access control address (MAC address) of the device. It cannot be used as a unique code.
isbind Boolean Indicates whether the device is bound. If a callback is invoked, the device is inactivated.
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 support pairing over Bluetooth due to unavailable Wi-Fi connections.
  • bit4: indicates whether QR code scanning is required to pair the device.
address String The IP address of the device.
deviceType int The type of device to distinguish different types of device protocols. This parameter can be ignored.

deviceType indicates the type of device to be paired. For more information about combo devices with Wi-Fi enabled, see subsequent instructions for pairing combo devices. For more information about Bluetooth devices, see subsequent instructions for pairing Bluetooth devices.

Value of deviceType configType Device type
200 config_type_single Bluetooth device
300 config_type_single Bluetooth device
301 config_type_wifi Wi-Fi and Bluetooth combo device
304 config_type_wifi Wi-Fi and Bluetooth combo device that supports pairing over Bluetooth if a Wi-Fi connection is unavailable
400 config_type_single Bluetooth device
401 config_type_wifi Wi-Fi and Bluetooth combo device
404 config_type_wifi Wi-Fi and Bluetooth combo device that supports pairing over Bluetooth if a Wi-Fi connection is unavailable

Query a device name

Returns the name and icon of a discovered device.

API description

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

Parameters

Parameter Type Description
productId String ScanDeviceBean.getProductId
uuid String ScanDeviceBean.getUuid
mac String ScanDeviceBean.getMac is null for most devices and has values only for certain categories.

Example

ThingHomeSdk.getActivatorInstance().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

Properties of ConfigProductInfoBean

Property Type Description
name String The product name of the device. The value is set in the cloud. In most cases, it is the name used when you create the product.
icon String The icon of the product.

Stop scanning

Stops device scanning. For example, if a pairing page is exited or during a pairing process, scanning can be stopped, so that the overall process will not be slowed down by the scanning task.

API description

void stopLeScan();

Example

ThingHomeSdk.getBleOperator().stopLeScan();

Bluetooth LE device pairing

Start pairing a Bluetooth LE device

If the configType property 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);

Parameters

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

BleActivatorBean stores the parameters and settings of the target device.

Property Type Description Required
homeId long The home ID. Yes
uuid String The device UUID that is returned after scanning. Yes
address String The device IP 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. Yes
isShare Boolean Indicates whether a shared device is used. The value is returned after scanning. Default value: false. No
timeout long The timeout value of a pairing task. This parameter determines whether pairing failed.
Unit: milliseconds. Default value: 60000.
No

Example

BleActivatorBean bleActivatorBean = new BleActivatorBean();

// mScanDeviceBean: returned by ScanDeviceBean in the scanning result callback.
bleActivatorBean.homeId = 123456; // homeId
bleActivatorBean.address = mScanDeviceBean.getAddress(); // The device IP address.
bleActivatorBean.deviceType = mScanDeviceBean.getDeviceType(); // The type of device.
bleActivatorBean.uuid = mScanDeviceBean.getUuid(); // The UUID.
bleActivatorBean.productId = mScanDeviceBean.getProductId(); // The product ID.
bleActivatorBean.isShare = (mScanDeviceBean.getFlag() >> 2) & 0x01 == 1; // The flag that indicates whether a shared device is used.

// Starts pairing.
ThingHomeSdk.getActivator().newBleActivator().startActivator(bleActivatorBean, new IBleActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
        // The device is paired.
    }

    @Override
    public void onFailure(int code, String msg, Object handle) {
        // Failed to pair the device.
    }
});

Stop pairing a Bluetooth LE device

Stops pairing during the pairing process.

API description

void stopActivator(String uuid);

Parameters

Parameter Type Description
uuid String The UUID of the discovered device. It is the same as the value of ScanDeviceBean.uuid.

Example

ThingHomeSdk.getBleManager().stopBleConfig("uuid");

Combo device pairing

Pair a combo device

Activates and pairs a combo device after it is discovered. If the configType property 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);

Parameters

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

Parameters of 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 IP address that is returned after scanning.
mac String The device MAC address that is returned after scanning.
ssid String The service set identifier (SSID) of the target Wi-Fi network.
pwd String The password of the target Wi-Fi network.
token String The pairing token. You can call getActivatorToken to get the token in the same way as that for pairing Wi-Fi devices.
homeId long The current home ID.
timeout long The timeout value of a pairing task. This parameter determines whether pairing failed. Unit: milliseconds.

If not stated, generic devices only support the 2.4 GHz Wi-Fi network. Other certain types of devices support the 5 GHz Wi-Fi network. ScanDeviceBean.flag indicates which type of network is supported.

Example

MultiModeActivatorBean multiModeActivatorBean = new MultiModeActivatorBean(mScanDeviceBean);

// mScanDeviceBean: returned by ScanDeviceBean in the scanning result callback.
multiModeActivatorBean.deviceType = mScanDeviceBean.getDeviceType(); // The type of device.
multiModeActivatorBean.uuid = mScanDeviceBean.getUuid(); // The UUID of the device.
multiModeActivatorBean.address = mScanDeviceBean.getAddress(); // The IP address of the device.
multiModeActivatorBean.mac = mScanDeviceBean.getMac(); // The MAC address of the device.
multiModeActivatorBean.ssid = "WIFI_2.4G"; // The SSID of the target Wi-Fi network.
multiModeActivatorBean.pwd = "WIFI_PASSWORD"; // The password of the target Wi-Fi network.
multiModeActivatorBean.token = "abcd1234"; // The pairing token.
multiModeActivatorBean.homeId = ; // The value of `homeId` for the current home.
multiModeActivatorBean.timeout = 120000; // The timeout value.

// Starts pairing.
ThingHomeSdk.getActivator().newMultiModeActivator().startActivator(multiModeActivatorBean, new IMultiModeActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
        // The device is paired.
    }

    @Override
    public void onFailure(int code, String msg, Object handle) {
        // Failed to pair the device.
    }
});

Callback description

  • DeviceBean: the type of device data. For more information, see Data model of 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 URL of the device icon.
    errorMsg String The error message.

Optimize pairing for combo devices

  • The SDK maintains the Bluetooth connection with the device during 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

The usage of this API method is similar to the previous API method for pairing a combo device. The difference is that the callback to invoke in this API method applies to combo devices, including Bluetooth plug & play devices.

void startActivator(MultiModeActivatorBean multiModeActivatorBean, IExtMultiModeActivatorListener listener);

Example

ThingHomeSdk.getActivator().newMultiModeActivator().startActivator(multiModeActivatorBean, new IMultiModeActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
        // The device is paired.
    }

    @Override
    public void onFailure(int code, String msg, Object handle) {
        // Failed to pair the device.
    }
    public void onActivatorStatePauseCallback(PauseStateData stateData) {
        // The data that is reported by the device, including the status of the connection to the router. For more information, see the descriptions of parameters.
    }
});

Parameters

PauseStateData

Parameter Description
uuid The UUID of the device.
configStage The current stage during the pairing process.
status The status of the current stage.

Description

configStage Description The description of stage status.
0 Activation of pairing
  • 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 Connection to the network
  • 0: Connected to the router successfully.
  • 1: Incorrect information about connection to the network.
  • 2: Failed to find a router.
  • 3: Incorrect Wi-Fi password.
  • 4: Failed to connect to the router.
  • 5: Failed to get the DHCP-assigned IP address.
3 Activation stage
  • 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 a combo device

Pairing can be stopped during the pairing process. If the device has been activated in the cloud, it might be paired even after the pairing process is stopped.

API description

ThingHomeSdk.getActivator().newMultiModeActivator().stopActivator(uuid);

Parameters

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

Example

ThingHomeSdk.getActivator().newMultiModeActivator().stopActivator("uuidxxxx");

Pair over Bluetooth due to unavailable Wi-Fi

Certain combo devices support pairing over Bluetooth if Wi-Fi connections are unavailable. Certain Wi-Fi and Bluetooth combo devices support pairing over Bluetooth if a Wi-Fi connection is unavailable. App users trigger cloud-based activation and required data is sent to a target device over Bluetooth. Then, the device attempts to connect to the target Wi-Fi network. If the device fails to be activated in the cloud, Bluetooth connections will be created between the device and the app on the mobile phone.

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

Yes
No
Yes
No
Device gets ready for pairing mode
startActivator()
Connected to Wi-Fi and activated in the cloud successfully
Paired successfully (controllable locally and from the cloud)
Activated locally over Bluetooth
Paired successfully (local control only
Failed to pair

API description

void startActivator(MultiModeActivatorBean multiModeActivatorBean, IMultiModeActivatorListener listener);

Parameters of MultiModeActivatorBean

Parameter Type Description
homeId long The ID of the home to which the target device is added.
uuid String The UUID of the target device.
deviceType int The type of device.
address String The IP address of the device.
timeout long The timeout value for pairing. Unit: milliseconds.
phase1Timeout long The timeout value for cloud-based activation. Unit: milliseconds. Default value: 60000.
ssid String The SSID of the target Wi-Fi network to which a paired device is connected.
pwd String The password of the target Wi-Fi network to which a paired device is connected. If no password is set, an empty string is passed.
token String The pairing token generated in the cloud to verify the account identity. You can call getActivatorToken to get the token in the same way as that for pairing Wi-Fi devices.
mac String The MAC address of the device.

If not stated, generic devices only support the 2.4 GHz Wi-Fi network. Other certain types of devices support the 5 GHz Wi-Fi network. ScanDeviceBean.flag indicates which type of network is supported.

Example

// `scanDeviceBean` indicates the device information included in the scanning result returned by the callback.
MultiModeActivatorBean multiModeActivatorBean = new MultiModeActivatorBean(scanDeviceBean);
// The SSID of the target Wi-Fi network to which a paired device is connected.
multiModeActivatorBean.ssid = "SSID_xxx";
// The password of the target Wi-Fi network to which a paired device is connected.
multiModeActivatorBean.pwd = "pwd_xxx";
// The UUID of the device.
multiModeActivatorBean.uuid = scanDeviceBean.getUuid();
// The type of device.
multiModeActivatorBean.deviceType = scanDeviceBean.getDeviceType();
// The MAC address of a device.
multiModeActivatorBean.mac = scanDeviceBean.getMac();
// The IP address of the target device.
multiModeActivatorBean.address = scanDeviceBean.getAddress();
// The value of `homeId` for the target device.
multiModeActivatorBean.homeId = "homeId_xxx";
// The pairing token.
multiModeActivatorBean.token = "token_xxx";
// The timeout value for pairing. Unit: milliseconds.
multiModeActivatorBean.timeout = 120 * 1000L;
// The timeout value for pairing over Wi-Fi only. Unit: milliseconds.
multiModeActivatorBean.phase1Timeout = 60 * 1000L;

// The callback to return the pair result.
IMultiModeActivatorListener listener = new IMultiModeActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
        // The device is paired.
    }
    @Override
    public void onFailure(int code, String error, Object handle) {
        // Failed to pair the device.
    }
};

// Starts pairing.
ThingHomeSdk.getActivator().newMultiModeActivator().startActivator(multiModeActivatorBean, listener);
  • To enable cloud-based activation, make sure the device stays activated over Bluetooth. This way, the information about cloud-based activation can be transmitted to the device over Bluetooth. You can call getCommunicationOnline(CommunicationEnum.BLE) of the DeviceBean instance to check the Bluetooth connection status of the device. The cloud-based activation method can be called only after true is returned.

  • To check whether a device is activated in the cloud, call deviceBean.getMeta().get("wifiEnable") and get the Wi-Fi connection status. A value of true indicates that the cloud-based activation is successful.

Activate locally-connected combo device in cloud

A combo device is locally connected to the app over Bluetooth after it fails to connect to the Wi-Fi network. The following method applies to the attempt to activate this device in the cloud through a Wi-Fi channel. In this call, make sure the target device is connected locally over Bluetooth and has not been activated in the cloud.

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

  • To check whether a device is activated in the cloud, call deviceBean.getMeta().get("wifiEnable") and get the Wi-Fi connection status.

    Yes
    No
    Activate device through Wi-Fi channel
    startWifiEnable()
    Device activated through Wi-Fi channel
    Paired successfully
    (Controllable locally and from the cloud)
    Failed to activate device in the cloud
    (local control only)

API description

void startWifiEnable(MultiModeActivatorBean multiModeActivatorBean, IMultiModeActivatorListener listener);

Parameters

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

Parameters of MultiModeActivatorBean

Parameter Type Description
timeout long The timeout value for the attempt to reconnect the device to the Wi-Fi network and activate it in the cloud. Unit: milliseconds.
ssid String The SSID of the target Wi-Fi network to which a paired device is connected.
pwd String The password of the target Wi-Fi network to which a paired device is connected. If no password is set, an empty string is passed.
devId Long The ID of the device to be connected over Wi-Fi.

Example

MultiModeActivatorBean multiModeActivatorBean = new MultiModeActivatorBean(scanDeviceBean);
multiModeActivatorBean.devId = "devId_xxx"; // The device ID.
multiModeActivatorBean.ssid = "ssid_xxx"; // The SSID of the target Wi-Fi network to which a paired device is connected.
multiModeActivatorBean.pwd = "pwd_xxx"; // The password of the target Wi-Fi network to which a paired device is connected.
multiModeActivatorBean.timeout = 120 * 1000L; // The timeout value for the Wi-Fi reconnection attempt. Unit: milliseconds.

// The callback to return the result of reconnecting to the Wi-Fi network and pairing the device.
IMultiModeActivatorListener listener = new IMultiModeActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
        // Activated the device successfully in the cloud through a Wi-Fi connection.
    }
    @Override
    public void onFailure(int code, String msg, Object handle) {
        // Failed to activate the device in the cloud through a Wi-Fi connection.
    }
};

// Starts the attempt to activate the device in the cloud through a Wi-Fi connection.
ThingHomeSdk.getActivator().newMultiModeActivator().startWifiEnable(multiModeActivatorBean, listener);

Pair combo device only over Bluetooth

Connects a combo device to the app through a Bluetooth connection for local activation if the device fails to connect to the Wi-Fi network.

Example

// scanDeviceBean indicates the device information included in the scanning result returned by the callback.
MultiModeActivatorBean multiModeActivatorBean = new MultiModeActivatorBean(scanDeviceBean);
// The UUID of the device.
multiModeActivatorBean.uuid = scanDeviceBean.getUuid();
// The type of device.
multiModeActivatorBean.deviceType = scanDeviceBean.getDeviceType();
// The MAC address of a device.
multiModeActivatorBean.mac = scanDeviceBean.getMac();
// The IP address of the target device.
multiModeActivatorBean.address = scanDeviceBean.getAddress();
// The value of homeId for the target device.
multiModeActivatorBean.homeId = "homeId_xxx";
// The pairing token.
multiModeActivatorBean.token = "token_xxx";
// The timeout value for pairing. Unit: milliseconds.
multiModeActivatorBean.timeout = 120 * 1000L;
// The timeout value for pairing over Wi-Fi only. Unit: milliseconds.
multiModeActivatorBean.phase1Timeout = 60 * 1000L;

// The callback to return the pairing result.
IMultiModeActivatorListener listener = new IMultiModeActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
        // The device is paired.
    }
    @Override
    public void onFailure(int code, String msg, Object handle) {
        // Failed to pair the device.
    }
};

// Activates the device directly through a local Bluetooth connection.
ThingHomeSdk.getActivator().newMultiModeActivator().startBleActivator(multiModeActivatorBean, listener);

Restart pairing

  • Asks users to provide the correct Wi-Fi name and password, and restarts pairing if the entered password is incorrect. During the pairing process, the SDK automatically connects to the device within a certain period. After the device is connected, the SDK gets and reports 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

/**
 * Restarts pairing.
 * return -1: Failed to pair, unable to restart pairing. 0: Restart of pairing is supported and triggered.
**/
int resumeActivator(@NonNull ResumeActivatorBean multiModeActivatorBean);

Parameters

ResumeActivatorBean

Parameter Description
uuid The UUID of the device for which pairing is restarted.
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. Valid values:
  • ResumeActivatorBean.RESUME_TYPE_WIFI: Pair a combo device through a Wi-Fi connection.
  • ResumeActivatorBean.RESUME_TYPE_BLE: Pair a combo device only through a Bluetooth connection.

Example

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

Optimized pairing of combo devices

In this optimized pairing solution, the TuyaOS version of the firmware built into the target device must be v3.6.1 or later.

Scan for Wi-Fi networks

API description

Connects to a Bluetooth device by Bluetooth advertising packets and UUID, and scans for the Wi-Fi networks that are supported by the device.

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

Parameters

MultiModeQueryBuilder

Parameter Description
homeId The home ID.
timeout The operation timeout value. Unit: milliseconds. This parameter is optional and can be set to 0.
scanDeviceBean The advertising packet ScanDeviceBean included in the scanning result callback.

Example

MultiModeQueryBuilder queryBuilder = new MultiModeQueryBuilder.Builder()
                .setHomeId(homeId)
                .setTimeout(timeout * 1000)
                .setScanDeviceBean(scandeviceBean)// scandeviceBean: The advertising packet found by scanning. With this packet, the Bluetooth device is matched and connected through a local Bluetooth connection by UUID.
                .build();
ThingHomeSdk.getActivator().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) {
            // A list of Wi-Fi networks is obtained.
        }
        @Override
        public void onError(String errorCode, String errorMessage) {
            // Failed to get a list of Wi-Fi networks.
        }
    });

Start pairing after Wi-Fi networks scanning

API description

Starts 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);

Parameters

MultiModeActivatorBuilder

Parameter Description
uuid The UUID of the device for which pairing is restarted.
ssid The name of the target Wi-Fi network.
pwd The password of the target Wi-Fi network.
timeout The timeout value for pairing. Unit: milliseconds.

Example

MultiModeActivatorBuilder builder = new MultiModeActivatorBuilder.Builder()
                .setUuid(uuid)
                .setSsid(ssid)
                .setPwd(pwd)
                .setTimeout(120 * 1000)
                .setToken(token)
                .build();
ThingHomeSdk.getActivator().newMultiModeActivator().startOptimizationActivator(builder, new IMultiModeActivatorListener() {
        @Override
        public void onSuccess(DeviceBean deviceBean) {
            // The device is paired.
        }
        @Override
        public void onFailure(int code, String msg, Object handle) {
            // Failed to pair the device. For more information, see the descriptions of error codes 207206 and 207223 at the end of this topic.
        }
    });

Restart pairing

Asks users to provide the correct Wi-Fi name and password, and restarts pairing if the entered password is incorrect. During the pairing process, the SDK automatically connects to the device within a certain period. After the device is connected, the SDK gets and reports the device status. This feature is supported by the latest firmware version only.

API description

/**
 * Restarts pairing.
 * return -1: Failed to pair, unable to restart pairing. 0: Restart of pairing is supported and triggered.
**/
int resumeActivator(@NonNull ResumeActivatorBean multiModeActivatorBean);

Parameters

ResumeActivatorBean

Parameter Description
uuid The UUID of the device for which pairing is restarted.
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. Valid values:
  • Set the value to ResumeActivatorBean.RESUME_TYPE_WIFI for the optimized pairing process for a combo device. Pairing through a Bluetooth connection is not supported in this process.

Example

ResumeActivatorBean bean = new ResumeActivatorBean.Builder()
                    .setResumeType(ResumeActivatorBean.RESUME_TYPE_WIFI)// The optimized pairing process, only available to combo devices including plug & play devices. Set the value to RESUME_TYPE_WIFI.
                    .setUuid(param.uuid)
                    .setSsid(param.ssid)
                    .setPassword(param.pwd)
                    .build();
ThingHomeSdk.getActivator().newMultiModeActivator().resumeActivator(bean);

Stop pairing

Example

ThingHomeSdk.getActivator().newMultiModeActivator().stopActivator(uuid);

Device operations

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

Determine whether device is online

  • Method 1: Get the device status by using the same method as that for a Wi-Fi device. If the Bluetooth device is added to a gateway, the device can stay online in the cloud.

    ThingHomeSdk.getDataInstance().getDeviceBean(devId).getIsOnline();
    
  • Method 2: Check whether a device is locally connected over Bluetooth. In most cases of a Bluetooth device, you can care about only the local connection status. If the Bluetooth device is added to a Bluetooth gateway, the device status in the cloud must be checked.

    ThingHomeSdk.getBleManager().isBleLocalOnline(devId);
    

Connect to an offline device

This method is called in the main thread.

API description

void connectBleDevice(List<BleConnectBuilder> builderList);

Parameters

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

Description of BleConnectBuilder

Method name Type Description
setDirectConnect() Boolean
  • true: uses a cached connection to accelerate the process.
  • false: does not use a cached connection.
setDevId() String The ID of the target device.
setScanTimeout() Integer The timeout value for scanning. Unit: milliseconds.
setLevel() BleConnectBuilder.Level
  • NORMAL: If connection resources have reached the upper limit, the current connection is ignored.
  • FORCE: If connection resources have reached the upper limit, other resources are released to enable the current connection.
Default value: NORMAL

Example

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

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

bleConnectBuilder1.setDevId(devId1); // The value of `devId` for Device 1.
bleConnectBuilder2.setDevId(devId2); // The value of `devId` for Device 2.

builderList.add(bleConnectBuilder1); // Adds Device 1.
builderList.add(bleConnectBuilder2); // Adds Device 2.

ThingHomeSdk.getBleManager().connectBleDevice(builderList); // Starts the connection task.

Disconnect a device

This method is called in the main thread.

API description

void disconnectBleDevice(List<BleConnectBuilder> builderList);

Parameters

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

Description of BleConnectBuilder

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

Example

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

builderList.add(new BleConnectBuilder().setDevId(devId1)); // The value of `devId` for Device 1.
builderList.add(new BleConnectBuilder().setDevId(devId2)); // The value of `devId` for Device 2.

ThingHomeSdk.getBleManager().disconnectBleDevice(builderList); // Starts the disconnection task.

Operate devices

Listens for device status by using the device operation class. Similar API methods for Wi-Fi devices are called. For more information, see Device Management. The following operations are supported:

  • Query device information

  • Initialize device control

  • Register a device listener

  • Unregister a device listener

  • Data points of devices

  • Rename a devices

  • Remove a device

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

    • The target Bluetooth device will be removed from the cloud and locally connected device list. If the device is offline, it is only removed from the cloud and is still bound with the app.
    • To bind a device again after the unbinding operation, the device must be manually set to the state to be paired.
    • During device scanning, if the SDK discovers the device in the bound state but disconnected from the cloud, the device will be automatically reset.
  • Recycle device resources

Firmware update

Firmware information must be checked before the over-the-air (OTA) update.

Check firmware information

API description

void requestUpgradeInfo(String devId, IRequestUpgradeInfoCallback callback);

Parameters

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

Example

ThingHomeSdk.getMeshInstance().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. Valid values:
  • 0: no update available
  • 1: update available
  • 2: updating
version String The target firmware version.
currentVersion String The current firmware version.
timeout Integer The timeout value. Unit: seconds.
upgradeType Integer
  • 0: app notification of update
  • 2: forced app update
  • 3: check for update
type Integer The type of module. Valid values:
  • 0: Wi-Fi module
  • 1: Bluetooth module
  • 2: GPRS module
  • 3: Zigbee module
  • 9: MCU
typeDesc String The description of the update module.
lastUpgradeTime long The duration of the latest update. Unit: milliseconds.
url String The URL to download the new firmware. This parameter has a value when type is 1 or 9.
fileSize long The size of the new firmware.
md5 String The MD5 (Message-Digest algorithm 5) hash value of the firmware.

Perform OTA update

Starts the OTA update after the available firmware update is downloaded.

API description

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

Parameters

Parameter Type Description
uuid String The UUID of the target device. You can call deviceBean.getUuid() to get the value.
type int The type of update. Valid values:
  • 0: Bluetooth firmware update, BLEUpgradeBean.type = 1.
  • 1: MCU update, BLEUpgradeBean.type = 9.
  • version String The version number of the new firmware.
    binPackagePath String The path of the downloaded firmware.
    listener OnBleUpgradeListener The callback to return the update progress.
    ThingHomeSdk.getBleManager().startBleOta(uuid, type, version, binPackagePath, new OnBleUpgradeListener() {
        @Override
        public void onUpgrade(int percent) {
            // The progress of the firmware update in percentage.
        }
    
        @Override
        public void onSuccess() {
            // The firmware is updated.
        }
    
        @Override
        public void onFail(String errorCode, String errorMsg) {
            // Failed to update the firmware.
        }
    });
    

    Error codes

    Error code Description
    1 The format of the packet received by the device is wrong.
    2 The device failed to find a router.
    3 The password of the target Wi-Fi network is wrong.
    4 The device failed to connect to a router.
    5 Failed to get a Dynamic Host Configuration Protocol (DHCP)-assigned IP address.
    6 Failed to connect the device to the cloud.
    100 The pairing process is canceled by the user.
    101 An error has occurred while connecting to the device over Bluetooth.
    102 An error has occurred while scanning for Bluetooth devices.
    103 Failed to enable a Bluetooth channel.
    104 Failed to query Bluetooth device information.
    105 Failed to pair devices over Bluetooth.
    106 The pairing task timed out.
    107 Failed to send Wi-Fi information.
    108 The token has expired.
    109 Failed to query the key with which Bluetooth connections are encrypted.
    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 query device information in 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 the feature of getting available Wi-Fi networks.
    207222 Failed to get Wi-Fi networks available to the device.
    207226 An empty list of Wi-Fi networks available to the device is returned.
    207227 A timeout error has occurred while sending a command for getting Wi-Fi networks available to the device.
    207209 Incorrect pairing information.
    207210 Failed to find a router.
    207211 Incorrect password of the router.
    207212 Failed to connect to the router.
    207213 Failed to get the DHCP-assigned IP address.
    207214 An error has occurred while activating the device in the cloud.
    207215 Failed to connect the device to the cloud.
    207216 The request to activate the device in the cloud failed.
    207218 The cloud-based request failed.
    207219 Failed to connect to iot-dns in the cloud.
    207220 Device pairing timed out.
    207221 Failed to connect to the device over Bluetooth.