Tuya Mesh

Last Updated on : 2023-03-29 02:40:45download

This topic describes the implementation of communication over Bluetooth based on Tuya’s proprietary mesh networking technology, also known as Tuya mesh. Each Tuya mesh device serves as a child node, and multiple mesh devices form a mesh network, in which the child nodes communicate with each other by advertising. App users can access one of the mesh devices to access and control all devices on the mesh network. This topic provides the development guidance on pairing, control, and management of devices that use Tuya mesh. For more information about Bluetooth mesh concepts, see Bluetooth Mesh.

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 permissions are 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.

  • Initialize a home: Before the development of Tuya mesh capabilities, get familiar with Smart Life App SDK. All Tuya mesh operations are implemented based on the initialized home data. For more information, see Home Management.

Management

Create a Tuya mesh network

A home can belong to multiple mesh networks, but one mesh network is recommended for each home.

API description

void createBlueMesh(String meshName, ITuyaResultCallback<BlueMeshBean> callback);

Parameters

Parameter Type Description
meshName String The name of a mesh network, with up to 16 bytes.
callback ITuyaResultCallback The callback.

Example

TuyaHomeSdk.newHomeInstance("homeId").createBlueMesh("meshName", new ITuyaResultCallback<BlueMeshBean>() {
	@Override
	public void onError(String errorCode, String errorMsg) {
	}

	@Override
	public void onSuccess(BlueMeshBean blueMeshBean) {
	}
});

Delete a mesh network

API description

void removeMesh(IResultCallback callback);

Parameters

Parameter Type Description
callback IResultCallback The callback.

Example

TuyaHomeSdk.newBlueMeshDeviceInstance(meshId).removeMesh(new IResultCallback() {
	@Override
	public void onError(String errorCode, String errorMsg) {
	}

	@Override
	public void onSuccess() {
	}
});

Query a list of mesh networks in a home

API description

List<BlueMeshBean> getMeshList();

Example

ITuyaHome mTuyaHome = TuyaHomeSdk.newHomeInstance("homeId");
if (mTuyaHome.getHomeBean() != null){
	List<BlueMeshBean> meshList = mTuyaHome.getHomeBean().getMeshList();
	BlueMeshBean meshBean= meshList.get(0);
}

Query a list of mesh sub-devices

API description

List<DeviceBean> getMeshSubDevList();

Example

List<DeviceBean> meshSubDevList = TuyaHomeSdk.newBlueMeshDeviceInstance("meshId").getMeshSubDevList();

Query and destroy a mesh instance

We recommend that you destroy the current mesh instance and initialize the mesh instance for the target home when you switch between homes.

API description

// Initializes the mesh network.
TuyaHomeSdk.getTuyaBlueMeshClient().initMesh(String meshId);

// Destroys the current mesh network.
TuyaHomeSdk.getTuyaBlueMeshClient().destroyMesh();

Connect to and disconnect from a mesh sub-device

ITuyaBlueMeshClient provides API methods to start a connection, close a connection, start scanning, and stop scanning.

API description

// Starts a connection.
TuyaHomeSdk.getTuyaBlueMeshClient().startClient(mBlueMeshBean);

// Closes a connection.
TuyaHomeSdk.getTuyaBlueMeshClient().stopClient();

// Starts scanning.
TuyaHomeSdk.getTuyaBlueMeshClient().startSearch()

// Stops scanning.
TuyaHomeSdk.getTuyaBlueMeshClient().stopSearch();

After a connection is started, available devices are scanned for in the background until a device is connected. The background scanning will consume resources. You can start and stop scanning to control the background scanning.

  • Before startClient() is called, the API methods of startSearch() and stopSearch() are invalid.
  • After a mesh network is connected, the API methods of startSearch() and stopSearch() are also invalid.

Pairing

Mesh devices to be paired are classified into:

  • A common Tuya mesh device that runs without a gateway, also known as a mesh sub-device

  • A mesh gateway

    Common mesh sub-devices include smart lights, smart sockets, and low-power products. All mesh devices without mesh gateway capabilities can be regarded as common Tuya mesh devices.

Reset devices

The default name of a device in the reset state is out_of_mesh and the default password is 123456. The following list describes common device resetting methods.

Product category Reset method State pending pairing
Lighting Turn on and off the light consecutively three times in a row The indicator is flickering quickly.
Socket Tap and hold the switch for three seconds The indicator is flickering quickly.
Gateway product Tap and hold the switch for three seconds The red and blue indicators are flickering quickly.
Low-power device Tap and hold the switch for three seconds Press the switch once again to see that the indicator is steady on. The pairing process must be completed when the indicator is on.
Alarm Tap and hold the switch for three seconds The indicator is flickering quickly.

Scan for sub-devices pending pairing

You must check Bluetooth and location permissions and then start scanning for mesh devices pending pairing.

API description

// Starts scanning.
void startSearch();
// Stops scanning.
void stopSearch();

Example

ITuyaBlueMeshSearchListener iTuyaBlueMeshSearchListener = new ITuyaBlueMeshSearchListener() {
	@Override
	public void onSearched(SearchDeviceBean deviceBean) {
	}

	@Override
	public void onSearchFinish() {
	}
};

SearchBuilder searchBuilder = new SearchBuilder()
				// The name of the device to be scanned for. Default value: `out_of_mesh` to represent the name of the device in the pairing state.
				.setMeshName("out_of_mesh")
				.setTimeOut(100) // The duration of the scanning. Unit: seconds.
				.setTuyaBlueMeshSearchListener(iTuyaBlueMeshSearchListener).build();

ITuyaBlueMeshSearch mMeshSearch = TuyaHomeSdk.getTuyaBlueMeshConfig().newTuyaBlueMeshSearch(searchBuilder);

// Starts scanning.
mMeshSearch.startSearch();

// Stops scanning.
mMeshSearch.stopSearch();

Pair mesh sub-devices

API description

// Starts pairing.
void startActivator();

// Stops pairing.
void stopActivator();

Parameters

Parameter String Description
mSearchDeviceBeans List The set of devices pending pairing.
timeout Int The timeout value of a pairing task. Default value: 100. Unit: seconds.
ssid String The name of the home Wi-Fi network to which a paired device is connected.
password String The password of the home Wi-Fi network to which a paired device is connected.
mMeshBean MeshBean MeshBean
homeId Long The home to which the mesh network of the paired device belongs.
version String
  • Pair common mesh devices: 1.0
  • Pair gateway devices: 2.2

Example

// Pairs a common mesh device.
TuyaBlueMeshActivatorBuilder tuyaBlueMeshActivatorBuilder = new TuyaBlueMeshActivatorBuilder()
				.setSearchDeviceBeans(foundDevices)
				.setVersion("1.0")
				.setBlueMeshBean(mMeshBean)
				.setTimeOut(timeOut)
				.setTuyaBlueMeshActivatorListener(new ITuyaBlueMeshActivatorListener() {
	@Override
	public void onSuccess(DeviceBean deviceBean) {
	}

	@Override
	public void onError(String errorCode, String errorMsg) {
	}

	@Override
	public void onFinish() {
	}});

ITuyaBlueMeshActivator iTuyaBlueMeshActivator = TuyaHomeSdk.getTuyaBlueMeshConfig().newActivator(tuyaBlueMeshActivatorBuilder);
// Starts pairing.
iTuyaBlueMeshActivator.startActivator();

// Stops pairing.
iTuyaBlueMeshActivator.stopActivator();

Pair a mesh gateway

API description

// Starts pairing.
void startActivator();
// Stops pairing.
void stopActivator();

Parameters

Parameter String Description
mSearchDeviceBeans List The set of devices pending pairing.
timeout Int The timeout value of a pairing task. Default value: 100. Unit: seconds.
ssid String The name of the home Wi-Fi network to which a paired device is connected.
password String The password of the home Wi-Fi network to which a paired device is connected.
mMeshBean MeshBean MeshBean
homeId Long The home to which the mesh network of the paired device belongs.
version String
  • Pair common mesh devices: 1.0
  • Pair gateway devices: 2.2

Example

// Pairs the gateway.
TuyaBlueMeshActivatorBuilder tuyaBlueMeshActivatorBuilder = new TuyaBlueMeshActivatorBuilder()
				.setWifiSsid(mSsid)
				.setWifiPassword(mPassword)
				.setSearchDeviceBeans(foundDevices)
				.setVersion("2.2 ")
				.setBlueMeshBean(mMeshBean)
				.setHomeId("homeId")
				.setTuyaBlueMeshActivatorListener(new ITuyaBlueMeshActivatorListener() {
				@Override
				public void onSuccess(DeviceBean devBean) {
					// The callback that is used when a single device is paired.
					L.d(TAG, "startConfig success");
				}

				@Override
				public void onError(String errorCode, String errorMsg) {
					// The callback that is used when a single device failed to be paired.
					// The error code. See the subsequent list of pairing error codes.
				L.d(TAG, "errorCode: " + errorCode + " errorMsg: " + errorMsg);
				}

				@Override
				public void onFinish() {
					// The callback that is used when all devices are paired.
				}
				});
ITuyaBlueMeshActivator iTuyaBlueMeshActivator = TuyaHomeSdk.getTuyaBlueMeshConfig().newWifiActivator(tuyaBlueMeshActivatorBuilder);

// Starts pairing.
iTuyaBlueMeshActivator.startActivator();

// Stops pairing.
//iTuyaBlueMeshActivator.stopActivator();

Pairing error codes

Error code Description
13007 Failed to log in to a device.
13004 Failed to reset a device address.
13005 The upper limit for the number of device addresses is reached.
13007 The SSID is empty.
13011 The pairing task timed out.

Devices

Check a mesh device type

API description

DeviceBean deviceBean=TuyaHomeSdk.getDataInstance().getDeviceBean(mDevId);
// Checks whether a Bluetooth mesh device is a gateway or a sub-device.
if(deviceBean.isBlueMesh()){
	L.d(TAG, "This device is blue mesh device");
}

// Checks whether a Bluetooth mesh gateway is used.
if(deviceBean.isBlueMeshWifi()){
	L.d(TAG, "This device is blue mesh wifi device");
}

Rename a mesh sub-device

API description

void renameMeshSubDev(String devId, String name, IResultCallback callback);

Parameters

Parameter Type Description
devId String The device ID.
name String The new name of the device.
callback IResultCallback The callback.

Example

mTuyaBlueMesh.renameMeshSubDev(devBean.getDevId(),"Device name", new IResultCallback() {
			@Override
			public void onError(String code, String errorMsg) {
			}

			@Override
			public void onSuccess() {
			}
		});

Check connections to a mesh network and a gateway

Example

DeviceBean deviceBean=TuyaHomeSdk.getDataInstance().getDeviceBean(mDevId);
DeviceBean gwBean=TuyaHomeSdk.getDataInstance().getDeviceBean(deviceBean.getParentId());

// The online status, including the status of connections to the local mesh network and gateway.
boolean online=deviceBean.getIsOnline()
// The device online status of connections to the local Bluetooth mesh network.
boolean localOnline=deviceBean.getIsLocalOnline()
// The device online status of connections to the gateway. The gateway is online only when the gateway and its sub-devices are both online.
boolean wifiOnline=deviceBean.isCloudOnline() && gwBean.getIsOnline()

Remove a mesh sub-device

API description

void removeMeshSubDev(String devId, IResultCallback callback);

Parameters

Parameter Type Description
devId String The device ID.
pcc String The category and type of the device.
callback IResultCallback The callback.

Example

mTuyaBlueMesh.removeMeshSubDev(devBean.getDevId(), new IResultCallback(){
@Override
public void onError(String code, String errorMsg) {
	Toast.makeText(mContext, "Failed to remove a sub-device"+ errorMsg,   Toast.LENGTH_LONG).show();
}

@Override
public void onSuccess() {
	Toast.makeText(mContext, "Sub-device removed successfully", Toast.LENGTH_LONG).show();
}
});

Query mesh sub-device status

The data point (DP) information returned from the cloud might not be the real-time data of the specified device. You can run the following command to query the current DP value of the device. The result is returned by the method onDpUpdate of IMeshDevListener.

API description

void querySubDevStatusByLocal(String pcc, String nodeId, IResultCallback callback);

Parameters

Parameter Type Description
pcc String The category and type of the device.
nodeId String The value of nodeId for the device.
callback IResultCallback The callback.

Example

mTuyaBlueMeshDevice.querySubDevStatusByLocal(devBean.getCategory(), devBean.getNodeId(), new IResultCallback() {
			@Override
			public void onError(String code, String errorMsg) {
			}

			@Override
			public void onSuccess() {
			}
		});

Groups

The ITuyaGroup class provides operations to manage mesh groups.

Check a mesh group

You can check whether MeshId is used by a group to determine whether it is a mesh group or a common Wi-Fi group.

API description

GroupBean groupBean=TuyaHomeSdk.getDataInstance().getGroupBean("groupId");
if(!TextUtils.isEmpty(groupBean.getMeshId())){
	L.d(TAG, "This group is a Bluetooth mesh group");
}

Create a mesh group

Each mesh network supports up to 28,672 groups. In the response to group creation, the group ID ranges from 8000 to EFFF in hexadecimal and can be locally maintained.

API description

void addGroup(String name, String pcc, String localId,IAddGroupCallback callback);

Parameters

Parameter Description
name The name of the group.
pcc The categories and types of devices in the group. Different types of devices can be created in a group. FF01 specifies the lighting category.
localId The value of localId for the group. Valid values: 8000 to EFFF in hexadecimal.
callback The callback.

Example

mITuyaBlueMesh.addGroup("Group name","Category and type", "8001", new IAddGroupCallback() {
@Override
public void onError(String errorCode, String errorMsg) {
}

@Override
public void onSuccess(long groupId) {
}
});

Add sub-devices to a mesh group

API description

void addDevice(String devId,IResultCallback callback);

Parameters

Parameter Type Description
devId String The device ID.
callback IResultCallback The callback.

Example

ITuyaGroup mGroup = TuyaHomeSdk.newBlueMeshGroupInstance(groupId);
mGroup.addDevice("devId", new IResultCallback() {
@Override
public void onError(String code, String errorMsg) {
}

@Override
public void onSuccess() {
}
});

Remove sub-devices from a group

API description

void removeDevice(String devId,IResultCallback callback);

Parameters

Parameter Type Description
devId String The device ID.
callback IResultCallback The callback.

Example

ITuyaGroup mGroup = TuyaHomeSdk.newBlueMeshGroupInstance(groupId);
mGroup.removeDevice("devId", new IResultCallback() {
@Override
public void onError(String code, String errorMsg) {
}

@Override
public void onSuccess() {
}
});

Delete a mesh group

API description

void dismissGroup(IResultCallback callback);

Parameters

Parameter Type Description
callback IResultCallback The callback.

API description

ITuyaGroup mGroup = TuyaHomeSdk.newBlueMeshGroupInstance(groupId);
mGroup.dismissGroup(new IResultCallback() {
@Override
public void onError(String code, String errorMsg) {
}

@Override
public void onSuccess() {
}
});

Rename a mesh group

API description

void renameGroup(String groupName,IResultCallback callback);

Parameters

Parameter Type Description
groupName String The new name of the group.
callback IResultCallback The callback.

Example

ITuyaGroup mGroup = TuyaHomeSdk.newBlueMeshGroupInstance(groupId);
mGroup.renameGroup("Group name",new IResultCallback() {
@Override
public void onError(String code, String errorMsg) {
}

@Override
public void onSuccess() {
}
});

Control

Smart devices are managed with DPs. Tuya mesh devices are also controlled by device DPs. The ITuyaBlueMeshDevice class provides operations to manage mesh groups.

Command format

Send a control command in the following format:

{
	"(dpId)":"(dpValue)"
}

For more information about DPs, see Data points.

Send DPs to control a device

API description

void publishDps(String nodeId, String pcc, String dps, IResultCallback callback);

Parameters

Parameter Description
nodeId The local ID of a sub-device.
pcc The product category and type of the sub-device.
dps The control command.
callback The callback.

Example

String dps = {"1":false};
ITuyaBlueMeshDevice mTuyaBlueMeshDevice=TuyaHomeSdk.newBlueMeshDeviceInstance("meshId");
mTuyaBlueMeshDevice.publishDps(devBean.getNodeId(), devBean.getCategory(), dps, new IResultCallback() {
@Override
public void onError(String s, String s1) {
}

@Override
public void onSuccess() {
}
});

Send DPs to control a group

API description

void multicastDps(String localId, String pcc, String dps, IResultCallback callback)

Parameters

Parameter Description
localId The local ID of a group.
pcc The product category and type of the sub-device.
dps The control command.
callback The callback.

Example

String dps = {"1":false};
ITuyaBlueMeshDevice mTuyaBlueMeshDevice= TuyaHomeSdk.newBlueMeshDeviceInstance("meshId");
mTuyaBlueMeshDevice.multicastDps(groupBean.getLocalId(), devBean.getCategory(), dps, new IResultCallback() {
@Override
public void onError(String errorCode, String errorMsg) {
}

@Override
public void onSuccess() {
}
});

Listen for mesh device status

Device information on a mesh network, such as DP data, status changes, device name, and device removal, is synchronized to IMeshDevListener in real time.

Example

mTuyaBlueMeshDevice.registerMeshDevListener(new IMeshDevListener() {

/**
	* Data is updated.
	* @param nodeId    The value of `nodeId` for the device.
	* @param dps       DP data.
	* @param isFromLocal   The data source. Valid values: `true` to indicate the local Bluetooth mesh network, and `false` to indicate the cloud.
	*/
@Override
public void onDpUpdate(String nodeId, String dps,boolean isFromLocal) {
// Returns `DeviceBean` by using `node`.
DeviceBean deviceBean = mTuyaBlueMeshDevice.getMeshSubDevBeanByNodeId(nodeId);
}

/**
	* Reports the device status.
	* @param online    The list of online devices.
	* @param offline   The list of offline devices.
	* @param gwId      The source of the status. If `gwId` is not empty, the cloud returns the status. `gwId` indicates the ID of the gateway that reports the data. If `gwId` is empty, the local Bluetooth mesh network returns the status.
	*/
@Override
public void onStatusChanged(List<String> online, List<String> offline,String gwId) {
}

/**
	* The changed network status.
	* @param devId
	* @param status
	*/
@Override
public void onNetworkStatusChanged(String devId, boolean status) {

}

/**
	* Reports the Raw type of data.
	* @param bytes
	*/
@Override
public void onRawDataUpdate(byte[] bytes) {

}

/**
	* The changes of device information, such as the device name.
	* @param bytes
	*/
@Override
public void onDevInfoUpdate(String devId) {
}
/**
	* The device is removed.
	* @param devId
	*/
@Override
public void onRemoved(String devId) {
}
});

Update

Tuya mesh shares the same logic of device firmware updates as Bluetooth mesh. For more information, see Firmware updates for Bluetooth mesh.