Quick Start

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:

  • Register a merchant account on the Smart Commercial Lighting platform and manage this account on the app.
  • Create and manage a project and an area for the merchant account.
  • Pair and control a device in the area.

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

Preparation

Before starting, ensure you have the following prepared.

  1. 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.

    • Type 1: Trial account
      • When you are on the Get SDK page during Preparation, find the banner at the top of the page and click Subscribe to the Trial Version to get a 30-day free trial.
      • During the trial, you can log in to the SDK-based app using the trial account. Once the trial ends, access to the app with this account will be unavailable. You need to subscribe to the official version.
    • Type 2: Standard account
      • Subscribe to the Commercial Lighting PaaS.
      • The validity of the standard version depends on your purchased service plan, and the official app SDK needs to be coupled with Commercial Lighting SaaS or open APIs. To integrate Commercial Lighting PaaS, provide Tuya’s account manager with the domain name and domain certificate that are required for the configuration.
  2. 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'
    	}
    }
    

Account management

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.

Step 1: Create an account

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.

Step 2: Log in with a password

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.

Project 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.

Step 1: Create an indoor project

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) {

    }
});
  • For indoor projects, the regionId can be set based on the locationId returned by the method getRegionList.
  • For outdoor projects, the parameter regionLocationId can be set to empty.
  • networkType indicates the mesh network mode, 0 for single mesh network, and 1 for multi-mesh network.
    • For indoor projects, set the networkType to either single mesh network or multi-mesh network.
    • For outdoor projects, set the networkType to single mesh network.
    • For parking lot projects, set the networkType to multi-mesh network.

Step 2: Get the project list

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.

Area management

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.

  • An area can be configured with one or more sub-areas. Sub-areas cannot be created for a bottom-level area.
  • In each area, one or more devices and groups can be created.

Step 1: Create an indoor area

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.

    • If you have not created an area or intend to create a first-level area, you can set this parameter to any value. To avoid conflict, we recommend that you set the value to 0 or a negative number.
    • To create a parent area or sub-area in an existing area, set the value to the area ID obtained from the list of sub-areas.
  • roomLevel: The area level, with 1 being the top level.

    • When currentAreaId is 0, the target area is an independent area, regardless of roomLevel.
    • If currentAreaId is specified, a sub-area or parent area is created based on the specified value.

Step 2: Get the area list

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.

Device pairing

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.

Pairing modes

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.

Get a pairing token

Before the pairing process, the app must get a pairing token from the cloud in the networked state.

  • The token is valid for 10 minutes and expires immediately after the device is paired. A new token must be generated if the device needs to be paired again.
  • To request a token, you need to upload the relation ID of the area to which the device belongs. Therefore, make sure that the account has been logged in and has at least one project and area created.

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) {

			}
		});

Start pairing

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) {

				}
			}
		));

Stop pairing

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

Device control

In this section, the objects IThingDevice and DeviceBean are used.

Object Description Reference
DeviceBean
  • Similar to IThingHomeManager and HomeBean, DeviceBean stores the basic information about a device, such as the ID, name, and icon.
  • The dps in the DeviceBean class defines the status of a device. The status is also known as data point (DP). Each DP stores a feature of a device. For example, on/off (Boolean type) for a switch and brightness (value type) for a light bulb. The device is controlled by querying and setting the DP value.
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

Get the device list

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

View device information

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

Control device

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){

    };
}

Remove device

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() {
	}
});

Next steps

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.