Last Updated on : 2024-06-24 08:43:53download
The Commercial Lighting App SDK is a mobile development tool designed to create IoT applications for the lighting industry. It helps you efficiently implement app features for managing projects, areas, and devices in commercial lighting applications. This SDK works with both legacy and new commercial lighting fixtures, supporting multiple protocols. Smart features such as device management, energy management, and human-centric lighting can contribute to creating green and healthy buildings.
This tutorial walks you through a few steps to develop a smart app with the SDK in two hours. You will learn how to implement the following features:
You can go to GitHub and download the sample code. This tutorial is broken down into sections based on features, making it easy for you to quickly locate the code.
App SDK Development GitHub Sample
Before starting, ensure you have the following prepared.
Create a Tuya Developer Platform account and an app, with the AppKey
and AppSecret
ready. For more information, see Preparation.
You need to request a commercial lighting account with one of the following two types.
Integrate the Commercial Lighting App SDK for Android into your project with Android Studio. For more information, see Fast Integration.
To enable local debugging, you need to configure the signature by using the Android closure in the app
module.
signingConfigs {
debug {
storeFile file('../xxx.jks')
storePassword 'xxx'
keyAlias 'xxx'
keyPassword 'xxx'
}
}
Accounts are classified into brand owner accounts, enterprise main accounts, and enterprise sub-accounts. A brand owner account can create only one merchant account. You can log in to the Smart Commercial Lighting platform using the account created in the Preparation step.
Currently, the Commercial Lighting App SDK does not support app account registration. Go to the Smart Commercial Lighting platform to purchase a merchant account plan and enable an enterprise main account.
You can call the login method to log in to the enterprise main account.
public void login(String userName, String password) {
ThingUserLoginWithPwdReqBean loginWithPwdReqBean = new ThingUserLoginWithPwdReqBean();
loginWithPwdReqBean.setUsername(userName);
loginWithPwdReqBean.setPassword(password);
loginWithPwdReqBean.setCountryCode(mCountryCode);
ThingOSUser.getUserInstance().loginWithPassword(loginWithPwdReqBean, new IThingUserLoginCallback<User>() {
@Override
public void onPreLogin(List<ThingMerchantBean> list) {
//Do nothing because of unique merchant code
}
@Override
public void onSuccess(User user) {
//login succeeded
}
@Override
public void onError(String s, String s1) {
//login failed
}
});
}
Each account can be assigned to only one merchant. Therefore, during the login, the account automatically matches the merchant. You do not need to pass in the parameter merchantCode
.
You can also implement login with a verification code, or submit a ticket to enable third-party login.
Account management also enables users to reset their password, log out, change their avatar, and update user information. For more information, see Account Management.
A project is an independent unit that is managed in a specific account. The number of projects that can be created depends on the subscribed plan.
A new account has no default project. You need to create one. Projects are classified into indoor and outdoor projects. For more information, see Project Overview.
All examples and methods in this topic are used to process indoor projects.
After login, a project must be created.
ThingCommercialLightingProject.getLightingProjectManager().createProject(projectType,
projectName, leaderName, leaderMobile, detailAddress, regionId, networkType, new IThingHomeResultCallback() {
@Override
public void onSuccess(HomeBean homeBean) {
}
@Override
public void onError(String s, String s1) {
}
});
regionId
can be set based on the locationId
returned by the method getRegionList.regionLocationId
can be set to empty.networkType
indicates the mesh network mode, 0
for single mesh network, and 1
for multi-mesh network.
networkType
to either single mesh network or multi-mesh network.networkType
to single mesh network.networkType
to multi-mesh network.You can call getProjectList to get the list of projects in an account.
ThingCommercialLightingProject.getLightingProjectManager().getProjectList(new IThingGetHomeListCallback() {
@Override
public void onSuccess(List<HomeBean> list) {
Log.i(TAG, "queryProjectList onSuccess: " + JSON.toJSONString(list));
if (null == iProjectIndexView.getContext()) {
return;
}
if (CollectionUtils.isEmpty(list)) {
iProjectIndexView.showProjectEmptyView();
} else {
iProjectIndexView.setProjectList(list);
}
}
@Override
public void onError(String s, String s1) {
Log.e(TAG, "queryProjectList onError: errorCode=" + s);
}
});
For other actions, see Update Project Information.
An area is also known as a space. It is an independent unit that is managed in a specific project. For more information, see Terms.
Two different methods are used to create an indoor area and an outdoor area. For more information, see Create an area.
All examples and methods in this topic are used to process indoor projects.
ThingCommercialLightingArea.getLightingAreaManager().createArea(projectId, currentAreaId, name, roomLevel, new IThingResultCallback<SimpleAreaBean>() {
@Override
public void onSuccess(SimpleAreaBean result) {
//success callback
}
@Override
public void onError(String errorCode, String errorMessage) {
//error callback
}
});
Parameter description
projectId
: The ID of the current project.
currentAreaId
: The ID of the current area.
0
or a negative number.roomLevel
: The area level, with 1
being the top level.
currentAreaId
is 0
, the target area is an independent area, regardless of roomLevel
.currentAreaId
is specified, a sub-area or parent area is created based on the specified value.Get the list of created areas, area details, and devices in each area.
Get area details
ThingCommercialLightingArea.newAreaInstance(projectId, areaId).getAreaInfo(new IThingResultCallback<SimpleAreaBean>() {
@Override
public void onSuccess(SimpleAreaBean result) {
//success callback
}
@Override
public void onError(String errorCode, String errorMessage) {
//error callback
}
});
Get the list of devices in an area
ThingCommercialLightingArea.newAreaInstance(mProjectId, mAreaId).queryDeviceListInArea("", 20,
"1", new IThingResultCallback<LightingDeviceListBean>() {
@Override
public void onSuccess(LightingDeviceListBean result) {
//success callback0
}
@Override
public void onError(String errorCode, String errorMessage) {
//error callback
}
});
For more information, see Get Area Information. With area information, you can manage the area and the device in an area. For example, modify an area, transfer devices, and bulk control devices in an area.
Devices must be paired before they can be controlled. Pairing is intended to connect and register a smart device to the cloud and allow it to communicate with the cloud. The Commercial Lighting App SDK empowers smart devices to be paired in multiple modes. For example, they can be paired over Wi-Fi and Bluetooth. For more information, see Device Pairing and Bluetooth Technology Stack.
In this section, the Wi-Fi pairing modes are used as an example to describe how to connect a device to the cloud using the SDK.
Wi-Fi pairing modes include: Wi-Fi Easy Connect (EZ) and Access Point (AP).
Compared with the Wi-Fi EZ mode, the AP mode results in a higher success rate, optimal reliability, and fewer compatibility requirements for mobile phones and routers. We recommend that you use the AP mode instead of the Wi-Fi EZ mode.
Before the pairing process, the app must get a pairing token from the cloud in the networked state.
The homeId
in the following example code represents the relation ID of the target area.
ThingOSActivator.deviceActivator().getActivatorToken(homeId,
new IThingActivatorGetToken() {
@Override
public void onSuccess(String token) {
}
@Override
public void onFailure(String s, String s1) {
}
});
Before the pairing process, the device must be in pairing mode. Information on how to put a device in pairing mode can be found in its user guide.
Call the pairing method, with the builder
included. builder
includes the Wi-Fi credentials (Wi-Fi SSID and password) and the token.
ActivatorBuilder builder = new ActivatorBuilder()
.setSsid(ssid)
.setContext(context)
.setPassword(password)
.setActivatorModel(ActivatorModelEnum.TY_EZ)
.setTimeOut(timeout)
.setToken(token)
.setListener(new IThingSmartActivatorListener() {
@Override
public void onError(String errorCode, String errorMsg) {
}
@Override
public void onActiveSuccess(DeviceBean devResp) {
// Multiple callbacks are required to pair multiple devices in the same call.
}
@Override
public void onStep(String step, Object data) {
}
}
));
IThingActivator mTuyaActivator = ThingOSActivator.deviceActivator().newMultiActivator(builder);
// Start pairing.
mTuyaActivator.start();
The timeout
defaults to 100
, in seconds. You can specify any preferred value. However, a small value is not recommended. A proper value can ensure optimal pairing performance.
In AP pairing mode, you must set activatorModel
to ActivatorModelEnum.TY_AP
and listen for the callback of the pairing result.
ActivatorBuilder builder = new ActivatorBuilder()
.setContext(context)
.setSsid(ssid)
.setPassword(password)
.setActivatorModel(ActivatorModelEnum.TY_AP)
.setTimeOut(timeout)
.setToken(token)
.setListener(new IThingSmartActivatorListener() {
@Override
public void onError(String errorCode, String errorMsg) {
}
@Override
public void onActiveSuccess(DeviceBean devResp) {
}
@Override
public void onStep(String step, Object data) {
}
}
));
After the pairing process is started, the app continuously broadcasts the pairing data until a device is paired or the process times out. To cancel or complete pairing during the process, you must stop pairing.
// Stops pairing.
mTuyaActivator.stop();
// Exits the page and destroys certain caches and listeners.
mTuyaActivator.onDestroy();
In this section, the objects IThingDevice
and DeviceBean
are used.
Object | Description | Reference |
---|---|---|
DeviceBean |
|
Data Points |
IThingDevice | Stores all data of device features, such as device control and firmware management. You must use the correct value of deviceId to initialize IThingDevice . |
Device Management |
After a device is paired, it will appear in the list of devices in the corresponding area.
You must first get the project details. Otherwise, the request for the device list will fail even if the device is paired successfully.
ThingCommercialLightingArea.newAreaInstance(mProjectId, mAreaId).queryDeviceListInArea("", 20,
"1", new IThingResultCallback<LightingDeviceListBean>() {
@Override
public void onSuccess(LightingDeviceListBean result) {
//success callback0
}
@Override
public void onError(String errorCode, String errorMessage) {
//error callback
}
});
dps
stores the information about all DPs, with each DP represented as a key-value pair
.
ThingOSDevice.newDeviceInstance(devId).getDp(dpId, new IResultCallback() {
@Override
public void onError(String code, String error) {
}
@Override
public void onSuccess() {
}
});
The response to a DP query is asynchronously called back by IDevListener.onDpUpdate()
.
To control a device, use the method Initialize Device Control. The method sends the DP data to a device to change its status or features for control.
The dps
can include one or more DPs, enabling control of multiple DPs at a time.
The following sample code shows how to switch on a light by using DP 101.
mDevice.publishDps("{\"101\": true}", new IResultCallback() {
@Override
public void onError(String code, String error) {
Toast.makeText(mContext, "Failed to switch on the light", Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess() {
Toast.makeText(mContext, "The light is switched on", Toast.LENGTH_SHORT).show();
}
});
To monitor changes in device status, such as connection, removal, and DP data changes, register IDevListener
to listen for these events.
mDevice.registerDevListener(new IDevListener() {
/**
* Updates the DP.
* devId The device ID.
* dpStr The updated DP. It is a JSON string in the format: {"101": true}.
*/
@Override
public void onDpUpdate(String devId, String dpStr){
};
/**
* The callback for device removal.
* devId The device ID.
*/
@Override
public void onRemoved(String devId){
};
/**
* The callback that is executed when the device gets online or offline. If the sub-device is powered off or disconnected from the network, the server executes the callback three minutes after the event occurs.
* devId The device ID.
* online Indicate whether the device is online. A value of `true` indicates that the device is online.
*/
@Override
public void onStatusChanged(String devId, boolean online){
};
/**
* The callback that is executed when the network status changes.
* devId The device ID.
* status Indicate whether the network is available. A value of `true` indicates that the network is available.
*/
@Override
public void onNetworkStatusChanged(String devId, boolean status){
};
/**
* The callback for device updates.
* devId The device ID.
*/
@Override
public void onDevInfoUpdate(String devId){
};
}
Use removeDevice to remove a device from a project.
mDevice.removeDevice(new IResultCallback() {
@Override
public void onError(String errorCode, String errorMsg) {
}
@Override
public void onSuccess() {
}
});
In most commercial lighting scenarios, devices are managed in groups. A group is a collection of devices that match specific rules. This enables multiple devices to be controlled in one go.
For more information, see Group Management. You can download the GitHub sample as mentioned at the beginning of this tutorial to get your development up and running.
Is this page helpful?
YesFeedbackIs this page helpful?
YesFeedback