English
English
简体中文
Contact Us
Register
Log In
layoutIndex

Bluetooth Series

Last Updated on : 2022-02-17 05:53:02download

Tuya Bluetooth has three technology solutions.

  • Bluetooth: Bluetooth single point device, one-to-one connection between Bluetooth device and phone.

  • Tuya mesh: Mesh released by Tuya.

  • Bluetooth mesh: Mesh released by SIG (Bluetooth Special Interest Group).

    In addition to the above three, there are some multi-protocol devices, such as Dual-mode Device with Wi-Fi and Bluetooth capabilities. You can use both Bluetooth and Wi-Fi capabilities.

    Category Product examples
    Bluetooth Body fat scale, bracelet, electric toothbrush, door lock, etc.
    Bluetooth mesh Light bulb, socket, sensor,etc.
    Tuya mesh Light bulb, socket, sensor, etc. This agreement is self-developed by Tuya.
    Dual-mode Device Bluetooth mesh gateways, IPC devices, and new multi-protocol Wi-Fi devices are all possible.

The Bluetooth part has the following functions:

  • Activate Device
    • Scan Bluetooth devices
    • Device activation
  • Device Function
    • Check the device connection status
    • Connect To Bluetooth Device
    • Device Function
    • Unbind Device

Prepare

Mobile System Requirements

SDK has been supported since Android 4.4. API>=19

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" />

Permissions Check

  • Before the APP uses the Bluetooth connection or scanning operation, it needs to check whether the APP positioning permission is allowed.
  • Check if the Bluetooth status is on.

Scan device

Before developing Bluetooth, you need to understand the basic logic of SDK. You must already use SDK to complete the basic operations such as initialization, login, and home creation.

Start scanning

Unactivated Bluetooth devices will send Bluetooth broadcast packets to the surroundings, and the SDK will analyze the broadcast packets according to the protocol to find the surrounding Tuya Bluetooth single-point devices and dual-mode devices.

Important:

Permissions check is required before scanning, only permissions allowable can work.

  1. The Phone Bluetooth is on
  2. APP has positioning permission

Description

void startLeScan(LeScanSetting setting, TyBleScanResponse response);

Parameters

Parameter Type Description
setting LeScanSetting Scan settings
response TyBleScanResponse calback,can not be empty

Builder Class Description

LeScanSetting.Builder is used to build the settings that need to scan the device.

Method Parameter Description Required?
setTimeout() Long Activation timeout, unit ms, 40s default No
addScanType() ScanType SINGLE: Point-to-point Bluetooth.
MESH: Tuya self-developed Bluetooth Mesh.
SIG_MESH: Bluetooth Mesh of SIG
Yes
setRepeatFilter() Boolean Repeat filter No

Example

LeScanSetting scanSetting = new LeScanSetting.Builder()
		.setTimeout(60000) // Activation timeout: ms
		.addScanType(ScanType.SINGLE) // If you need to scan for Bluetooth devices, you only need to add ScanType.SINGLE
		// .addScanType(ScanType.SIG_MESH) Other types of equipment can be added at the same time
		.build();

// Start scanning
TuyaOSBLE.operator().startLeScan(scanSetting, new TyBleScanResponse() {
	@Override
	public void onResult(ScanDeviceBean bean) {
		// Process the results of the scan here
	}
});

Callback Description

ScanDeviceBean description

Attribute Type Description
id String Scan ID usually consists of UUID, which can uniquely distinguish the device
name String Bluetooth name of the device, usually blank
providerName String SingleBleProvider
data byte[] raw data
configType String config_type_single: single Device.
config_type_wifi: Dual-mode device
productId String product id
uuid String product uuid,Device unique code
mac String device mac
isbind Boolean binding status, all devices that can be callback are not activated
flag Integer bit0: Whether to support 5G Wi-Fi;
bit2: Share device or not;
bit3: Whether to support Bluetooth as a guaranteed activation device
address String device address
deviceType Integer device type

The deviceType indicates the type of device to be activated, no special attention is needed. If dual-mode devices with Wi-Fi see dual-mode activation, Bluetooth devices see Bluetooth activation.

deviceType value configType Device type name
200 config_type_single Bluetooth device
300 config_type_single Bluetooth device
301 config_type_wifi Bluetooth device
304 config_type_wifi Wi-Fi + Bluetooth dual-mode device(support Bluetooth as a guaranteed activation device)
400 config_type_single Bluetooth device
401 config_type_wifi Wi-Fi + Bluetooth dual-mode device
404 config_type_wifi Wi-Fi + Bluetooth dual-mode device(support Bluetooth as a guaranteed activation device)

Query device name

After scanning to the target device, you need to query to display the name and icon of the product configuration.

Description

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

Parameters

Parameter Type Description
productId String ScanDeviceBean.getProductId
uuid String ScanDeviceBean.getUuid
mac String ScanDeviceBean.getMac

Example

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

		}

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

		}
});

Example

ConfigProductInfoBean description

Attributes Type Description
name String The product’s name
icon String The product’s icon

Stop scanning

Stop scanning devices, such as exiting the activation page.

Description

void stopLeScan();

Example

TuyaOSBLE.operator().stopLeScan();

Bluetooth device activation

Start activation

Scanned devices configType = config_type_single represents a single Bluetooth device. config_type_wifi is a dual-mode device.

Description

void startActivator(BleActivatorBean bleActivatorBean, IBleActivatorListener listener);

Parameters

Parameter Type Description
bleActivatorBean BleActivatorBean The parameter collection of the device to be connected
listener IBleActivatorListener Activation result callback

BleActivatorBean Description

Attributes Type Description Required?
homeId Long Current home’s Id Yes
uuid String ScanDeviceBean.uuid. Can be obtained by scanning Yes
address Boolean ScanDeviceBean.address. Can be obtained by scanning No
productId String ScanDeviceBean.productId. Can be obtained by scanning No
deviceType Integer Device type. Can be obtained by scanning Yes
isShare Boolean Whether the device is shared. Can be obtained by scanning No
timeout Long Total activation timeout.
Unit: milliseconds, default 60000
No

Example

BleActivatorBean bleActivatorBean = new BleActivatorBean();

// mScanDeviceBean is from the scan callback: ScanDeviceBean
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

// listener
IBleActivatorListener listener = new IBleActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
    
    }

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

// start activator
TuyaOSActivator.activator().newBleActivator().startActivator(bleActivatorBean, listener);

Cancel activation

Stop it during activation.

Description

void stopActivator(String uuid);

Parameters

Parameters Type Description
uuid String ScanDeviceBean.uuid

Example

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

Dual-mode device activation

Start dual-mode device activation

Scanned devices configType = config_type_single represents a single Bluetooth device. config_type_wifi is a Dual

Description

void startActivator(MultiModeActivatorBean multiModeActivatorBean, IMultiModeActivatorListener listener);

Parameters

Parameters Type Description
multiModeActivatorBean MultiModeActivatorBean Multi-mode device parameter bean that needs to be activated
listener IMultiModeActivatorListener Activation result callback

MultiModeActivatorBean Description

Attributes Type Description
deviceType Integer Device type. Can be obtained by scanning
uuid String ScanDeviceBean.uuid. Can be obtained by scanning
address String ScanDeviceBean.address. Can be obtained by scanning
mac String Device mac. Can be obtained by scanning
ssid String Wi-Fi ssid
pwd String Wi-Fi password
token String The way to obtain the token is the same as the Wi-Fi device Get Token
homeId Long Current home’s Id
timeout Long Total activation timeout. Unit: milliseconds

Note: If not specified, the device only supports a 2.4G Wi-Fi network, and some devices support 5G. It can be determined based on ScanDeviceBean.flag.

Example

MultiModeActivatorBean multiModeActivatorBean = new MultiModeActivatorBean();

// mScanDeviceBean is from the scan callback: ScanDeviceBean
multiModeActivatorBean.deviceType = mScanDeviceBean.getDeviceType(); // device type
multiModeActivatorBean.uuid = mScanDeviceBean.getUuid(); // device uuid
multiModeActivatorBean.address = mScanDeviceBean.getAddress(); // device address
multiModeActivatorBean.mac = mScanDeviceBean.getMac(); // device mac
multiModeActivatorBean.ssid = "WIFI_2.4G"; // Wi-Fi SSID
multiModeActivatorBean.pwd = "WIFI_PASSWORD"; // Wi-Fi password
multiModeActivatorBean.token = "abcd1234"; // token
multiModeActivatorBean.homeId = 123456; // homeId
multiModeActivatorBean.timeout = 120000;

// start
TuyaOSActivator.activator().newMultiModeActivator().startActivator(multiModeActivatorBean, new IMultiModeActivatorListener() {
	@Override
	public void onSuccess(DeviceBean deviceBean) {
		// Activated successfully
	}

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

Callback Description

For the detailed DeviceBean description, see DeviceBean Data Model.

Cancel multi-mode device activation

Stop it during activation.

Description

void stopActivator(String uuid);

Parameters

Parameters Type Description
devUuid String ScanDeviceBean.uuid

Example

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

Dual-mode device activation (Bluetooth as a guaranteed)

Some dual-mode devices have Bluetooth as a guaranteed activation capability. The user uses the APP to transmit the Wi-Fi information that the device needs to connect to the device to be activated through the Bluetooth of the mobile phone. The device will try to connect to Wi-Fi. When Wi-Fi cannot connect to the Internet, the local connection mode will be activated, and the mobile phone Bluetooth will be used to directly communicate with the device.

To determine whether the scanned device has Bluetooth protection activation capability, you can use the getDeviceType() method of ScanDeviceBean. The return value is 404 or 304, which means the device has Bluetooth protection activation capability, and other results indicate There is no such ability.

Bluetooth Series

Description

void startActivator(MultiModeActivatorBean multiModeActivatorBean, IMultiModeActivatorListener listener);

Parameters

MultiModeActivatorBean

Parameters Type Description
homeId long Add the device to the homeId with the specified ID
uuid String Need to activate the device uuid
deviceType int Device Type
address String Device address
timeout long The total duration of device activation timeout, unit: ms
phase1Timeout long Connect to the cloud activation timeout period, default: 60000, unit: ms
ssid String Wi-Fi SSID to be connected
pwd String Wi-Fi password that needs to be connected, if there is no password, pass an empty string
token String Account authentication information obtained from the cloud
mac String Device mac

If not specified, general equipment only supports 2.4G frequency band WIFI distribution network, and some equipment supports 5G. It can be judged according to ScanDeviceBean.flag.
token: The method of obtaining token is the same as that of Wi-Fi device network configuration, see Wi-Fi part network configuration to obtain Token

Example

// scanDeviceBean is a callback for device information scanned by Bluetooth Low Energy (Bluetooth LE)
MultiModeActivatorBean multiModeActivatorBean = new MultiModeActivatorBean();
// Set Wi-Fi SSID
multiModeActivatorBean.ssid = "SSID_xxx";
// Set Wi-Fi password
multiModeActivatorBean.pwd = "pwd_xxx";
// Set device UUID
multiModeActivatorBean.uuid = scanDeviceBean.getUuid();
// Set device type
multiModeActivatorBean.deviceType = scanDeviceBean.getDeviceType();
// Set device 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 the total timeout of the distribution network, unit: ms
multiModeActivatorBean.timeout = 120 * 1000L;
// Set the timeout for Wi-Fi connection only, unit: ms
multiModeActivatorBean.phase1Timeout = 60 * 1000L;

// Activation result callback
IMultiModeActivatorListener listener = new IMultiModeActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
        // Activated successfully
    }
    @Override
    public void onFailure(int code, String error, Object handle) {
        // Activation fails
    }
};

// Start activation
IMultiModeActivator mMultiModeActivator = TuyaOSActivator.activator().newMultiModeActivator();
mMultiModeActivator.startActivator(multiModeActivatorBean, listener);

To determine whether a device with a successful network configuration is activated through Bluetooth guarantee, you can use the getCommunicationOnline(CommunicationEnum.BLE) method of the callback DeviceBean to specify whether to query whether BluetLE is activated or not. The result is true, which means that the Bluetooth guarantee capability is used The distribution network is in a local connection state.

To determine whether the cloud link is activated, you can use deviceBean.getMeta().get("wifiEnable") to get whether the device is connected to Wi-Fi: the result is true, which means the cloud link is activated.

Wi-Fi activation

If the Wi-Fi activation of the above Bluetooth activated device fails, it will enter the Bluetooth local connection for operation. At this time, if you want to retry to connect the device to Wi-Fi for cloud activation, you can call the following interface.

When calling, you need to ensure that the device is in the local Bluetooth connection state and the cloud link is not activated: use the getCommunicationOnline(CommunicationEnum.BLE) method of DeviceBean to query whether the local Bluetooth link is activated. Use deviceBean.getMeta().get("wifiEnable") to get whether the device activates the cloud link.

Bluetooth Series

Description

void startWifiEnable(MultiModeActivatorBean multiModeActivatorBean, IMultiModeActivatorListener listener);

When calling, make sure that the device and APP are connected and Wi-Fi is not turned on:

Use connectBleDevice() to connect offline local devices.

Use deviceBean.getMeta().get("wifiEnable") to get whether the device is connected to Wi-Fi and whether it is false.

Parameters

Parameters Type Description
multiModeActivatorBean MultiModeActivatorBean Parameter collection of devices that need to reconnect to Wi-Fi
listener IMultiModeActivatorListener Callback of Wi-Fi reconnection results

Example

MultiModeActivatorBean multiModeActivatorBean = new MultiModeActivatorBean();
multiModeActivatorBean.devId = "devId_xxx"; // devId
multiModeActivatorBean.ssid = "ssid_xxx"; // Wi-Fi ssid to connect
multiModeActivatorBean.pwd = "pwd_xxx"; // Wi-Fi password required to connect
multiModeActivatorBean.timeout = 120 * 1000L; // Timeout duration, unit: ms

// Wi-Fi reactivation result callback
IMultiModeActivatorListener listener = new IMultiModeActivatorListener() {
    @Override
    public void onSuccess(DeviceBean deviceBean) {
        // Activate Wi-Fi and connect to the cloud successfully
    }
    @Override
    public void onFailure(int code, String msg, Object handle) {
        // Failed to connect to the cloud
    }
};

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

Bluetooth device function

Summary

  1. Device status query
  2. Device connection
  3. Device sends instructions
  4. Modify the device
  5. Unbind the device

Device status query

  • The general query is the same as the Wi-Fi device (this status is a comprehensive status, if the Bluetooth device is added under the gateway, the Bluetooth device can be online in the cloud)
    TuyaOSDevice.getDataInstance().getDeviceBean(devId).getIsOnline();
    
  • Query if the device is locally connected
    TuyaOSBLE.manager().isBleLocalOnline(devId);
    

    Note: Usually only the local state needs to be considered. Only Bluetooth devices that join the gateway need to consider whether the cloud is online.

Connect device

If the device is offline, you can call the connection method to connect the device.

Note: The API needs to be called in the main thread

Description

void connectBleDevice(List<BleConnectBuilder> builderList);

Parameters

Parameters Type Description
builderList List See the description of BleConnectBuilder below

Bleconnectitbuilder is used to build settings that need to connect devices.

Method Type Description
setDirectConnect() Boolean true: Use cached connection, default;
false: Do not use cached connections
setDevId() String The devId of the device that needs to be connected
setScanTimeout() Integer Timeout, unit ms, 30s default
setLevel() BleConnectBuilder.Level NORMAL: default style If the connection resources are full, the connection will be ignored;
FORCE: If the connection resources are full, other resources will be released 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

TuyaOSBLE.manager().connectBleDevice(builderList); // Start connecting

Disconnect device

Can actively disconnect connected devices.

Note: The API needs to be called in the main thread.

Description

void disconnectBleDevice(List<BleConnectBuilder> builderList);

Parameters

Parameters Type Description
builderList List BleConnectBuilder list

Bleconnectitbuilder is used to build settings that need to disconnect devices.

Method Type Description
setDevId() String The devId of the device that needs to be disconnected

Example

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

builderList.add(new BleConnectBuilder().setDevId(devId1)); // Device 1
builderList.add(new BleConnectBuilder().setDevId(devId2)); // Device 2

TuyaOSBLE.manager().disconnectBleDevice(builderList); // Disconnect

Bluetooth device function

Can monitor device status. This section is similar to Wi-Fi devices, please refer to it for more information Wi-Fi Function

Unlike Wi-Fi devices, it does not have a LAN delivery function. Only some delivery functions are supported.

Description

void publishDps(String dps, IResultCallback callback);

Parameters

Parameter Type Description
dps String data points
callback IResultCallback callback

Example

Assuming that the device function point of the light is 101, the control code of the light is as follows:

mDevice.publishDps("{\"101\": true}", new IResultCallback() {
	@Override
	public void onError(String code, String error) {
	}

	@Override
	public void onSuccess() {
	}
});
  • Rename device

    Consistent with Wi-Fi device: Rename Device

  • Remove device

    Consistent with Wi-Fi device: Remove Device

    **Note:

    • The unbinding of Bluetooth devices is consistent with the Wi-Fi device.
      TuyaOSDevice.newDeviceInstance("devId").removeDevice() or resetFactory()
    • But in addition to Bluetooth cloud removal. If the device is locally connected at this time, the device will be automatically removed. If the device is offline at this time, only the cloud will be removed.
  • Recycling device resources

    Consistent with Wi-Fi device: Recycling Device Resources

Error code

Code Description
1 Format of the packet received by the device is incorrect
2 The device cannot find the router
3 Wi-Fi password error
4 Device cannot connect to router
5 Device DHCP failed
6 The device fails to connect to the cloud
100 User cancels activation
101 Bluetooth connection error
102 Bluetooth service error found
103 Failed to open Bluetooth communication channel
104 Bluetooth failed to get device information
105 Bluetooth pairing failed
106 Activation timeout
107 Wi-Fi information transmission failed
108 Token is invalid
109 Failed to get Bluetooth encryption key
110 Device does not exist
111 Device cloud registration failed
112 Device cloud activation failed
113 Cloud device has been bound
114 Active disconnect
115 Failed to get device information in the cloud
116 The device is being networked by other methods at this time
117 OTA upgrade failed
118 OTA upgrade timeout
119 Wi-Fi parameter verification failed