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

Quick Start with Commercial Lighting App SDK for Android

Last Updated on : 2022-02-17 05:43:44download

Tuya Commercial Lighting App SDK is a mobile development tool specifically for IoT applications in the lighting industry. With the Commercial Lighting App SDK, you can quickly implement app functionality suitable for commercial lighting and scene linkage. This SDK is compatible with multiple protocols and can meet existing and new commercial lighting demands. Green buildings and healthy buildings can be implemented with smart features, such as device management, energy management, and human-centric lighting.

This tutorial walks you through a few steps to get started with the SDK and develop a preferred IoT app within two hours. You will learn how to implement the following features:

  • Register a merchant account on the Tuya Commercial Lighting Console and manage this account on the app.
  • Create and manage a project and an area for the merchant account.
  • Connect to and control devices in the area.

You can go to GitHub and download the sample code for the different features mentioned in this tutorial. Then, you can integrate the required sample code into your SDK development on the Tuya IoT Platform.

App SDK Development GitHub Sample

Preparation

Before you start, the following requirements must be met:

  1. An account of the Tuya IoT Platform is registered, an app is built on the platform, and the values of AppKey and AppSecret of the SDK are obtained. For more information, see Preparation.

    Before you start, you must request a commercial lighting account that can be either of the following types:

    • Type 1: Trial account
      • Follow the instructions in Preparation to open the Get SDK tab, and click subscribe to the trial version at the top of the page to get a 30-day trial account.
      • During the trial, you can log in to the app developed by the SDK. After the app expires, login to the app is disabled. In this case, you cannot subscribe to the trial version again. You must subscribe to the official version to continue using the app.
    • Type 2: Standard account
      • You can subscribe to the value-added service 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, you must provide Tuya’s account manager with the domain name and domain certificate that are required for the configuration.
  2. Tuya Commercial Lighting App SDK for Android is integrated into your project with Android Studio. For more information, see Fast Integration with Commercial Lighting App SDK for Android.

    To enable local debugging, you must configure the signature by using the Android closure in the app module.

    signingConfigs {
    	debug {
    		storeFile file('../xxx.jks')
    		storePassword 'xxx'
    		keyAlias 'xxx'
    		keyPassword 'xxx'
    	}
    }
    

User management

Users are classified into brand owner accounts, enterprise main accounts, and enterprise sub-accounts. A typical service mode is the single SaaS merchant mode, where only one merchant account is created for a brand owner account. You can follow the instructions in the Preparation step to register a Tuya developer account and log in to the Tuya Commercial Lighting Console.

Step 1: Register an enterprise main account

Currently, Tuya Commercial Lighting App SDK does not support registration on the app. You must go to the Tuya Commercial Lighting Console to purchase a merchant account plan and enable an enterprise main account.

Step 2: Log in to the account with the password

You can call the API method loginWithPassword to implement login to the enterprise main account.

public void loginWithPwd(View view) {
    String username = etUsername.getText().toString();
    String merchantCode = etMerchant.getText().toString();
    String password = etPwd.getText().toString();
    TuyaUserLoginWithPwdReqBean reqBean = new TuyaUserLoginWithPwdReqBean();
    reqBean.setPassword(password);
    reqBean.setUsername(username);
    reqBean.setCountryCode("86");
    reqBean.setMerchantCode(merchantCode);

    TuyaOSUser.getUserInstance().loginWithPassword(reqBean, new ITuyaUserLoginCallback<User>() {
        @Override
        public void onPreLogin(List<TuyaMerchantBean> merchantBeanList) {
                    }

        @Override
        public void onSuccess(User data) {

        }

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

        }
    });
}

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.

In addition to the account and password, you can also implement login with a verification code, or submit a ticket to enable third-party login.

Step 3: Manage the account

The account information, such as the password and nickname, can be modified.

public void modifyPwd(View view) {
  String oldPwd = etPwd.getText().toString();
  String newPwd = etNewPwd.getText().toString();
  TuyaUserModifyPwdReqBean reqBean = new
  TuyaUserModifyPwdReqBean();
  reqBean.setOldPassword(oldPwd);
  reqBean.setNewPassword(newPwd);

  TuyaOSUser.getUserInstance().modifyPassword(reqBean, new IResultCallback() {
    @Override
    public void onError(String code, String error) {
      toast(error);
      L.e(TAG, error);
    }

    @Override
    public void onSuccess() {
      toast("modify success");
    }
  });
}

Account management supports additional features. For example, reset the password, exit the account, change the avatar, and synchronize and update user information. For more information, see Manager Information.

Project management

A project is an independent unit that is managed by a user. The maximum number of projects that can be created for a user depends on the plan purchased by the user.

A newly created user is not assigned projects. Projects must be created after login to enable follow-up operations. 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.

TuyaCommercialLightingProject.getLightingProjectManager()
.createProject(projectType, projectName, leaderName, leaderMobile, detailAddress, regionId, new ITuyaHomeResultCallback() {
    @Override
    public void onSuccess(HomeBean homeBean) {

    }

    @Override
    public void onError(String s, String s1) {

    }
});
  • For indoor projects, the parameter regionId can be set based on the locationId field that is returned by the API method getRegionList.
  • For outdoor projects, the parameter regionLocationId can be set to empty.

Step 2: Query projects for a user

You can call the API method getProjectList to query all projects for a user.

TuyaCommercialLightingProject.getLightingProjectManager().getProjectList(new ITuyaGetHomeListCallback() {
    @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);
    }
});

Project information can be modified or deleted. For more information, see Modify a project.

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 about the terms, see Concepts.

  • 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

You can call different API methods to create indoor and outdoor areas for the current project. Only indoor areas can be created for indoor projects, and only outdoor areas can be created for outdoor projects. For more information, see Create an area.

All examples and methods in this topic are used to process indoor projects.

TuyaCommercialLightingArea.getLightingAreaManager().createArea(projectId, currentAreaId, name, roomLevel, new ITuyaResultCallback<SimpleAreaBean>() {
            @Override
            public void onSuccess(SimpleAreaBean result) {
                //success callback
            }

            @Override
            public void onError(String errorCode, String errorMessage) {
            		//error callback
            }
        });

Parent areas or sub-areas can be created for areas in indoor or outdoor projects. Sub-areas cannot be created for a bottom-level area.

Parameters

  • projectId: the current project ID.

  • currentAreaId: the current area ID.

    • If no areas are created or a level-1 area is required, this parameter can be 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 based on an existing area, set the value to the existing area ID. You can call an API method to get the existing area ID.
  • roomLevel: the area level. 1 indicates the top level.

    • When currentAreaId is 0, the target area is an independent area, no matter what the value of roomLevel is.
    • If an existing area ID is specified, a sub-area or parent ara is created based on the existing area ID.

Step 2: Query a list of areas

After one or more areas are created, a list of areas or area details including the devices in the area can be queried.

Query area information

TuyaCommercialLightingArea.newAreaInstance(projectId, areaId).getAreaInfo(new ITuyaResultCallback<SimpleAreaBean>() {
            @Override
            public void onSuccess(SimpleAreaBean result) {
                //success callback
            }

            @Override
            public void onError(String errorCode, String errorMessage) {
            	//error callback
            }
        });

Query device information in an area

TuyaCommercialLightingArea.newAreaInstance(mProjectId, mAreaId).queryDeviceListInArea("", 20,
                "1", new ITuyaResultCallback<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. After area information is obtained, areas and the devices in the areas can be managed. For example, modify an area, transfer devices, and control a device group in an area.

Device pairing

Devices must be paired before they can be controlled. After users pair a device with the app, the device is connected and registered to the cloud and can communicate with the cloud. The Commercial Lighting App SDK empowers smart devices to be paired in multiple pairing modes. For example, they can be paired over Wi-Fi and Bluetooth. For more information, see Device Pairing (Android) and Bluetooth Series.

Pairing modes

In this section, the Wi-Fi pairing modes are used as an example to describe how to integrate the SDK and register a device to the cloud.

Wi-Fi pairing modes include: Wi-Fi Easy Connect (EZ), Access Point (AP), and QR code.

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 the pairing token

Before the AP pairing process, the SDK 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 get a token, the current value of projectId must be provided. Therefore, during this process, the account must be in the logged-in state and at least one project is created for the account. You can call the API method getProjectList to return HomeBean and get the required value of projectId.

In the following example, homeId represents projectId.

TuyaOSActivator.deviceActivator().getActivatorToken(homeId,
		new ITuyaActivatorGetToken() {

			@Override
			public void onSuccess(String token) {

			}

			@Override
			public void onFailure(String s, String s1) {

			}
		});

Start pairing

Before the pairing process is started, the device must keep a state pending pairing. To set the device to this state, you can guide users to follow the device user manual.

To call the pairing API method, you must set builder, including the SSID of the router (the Wi-Fi name), password, and the token obtained from the cloud.

ActivatorBuilder builder = new ActivatorBuilder()
		.setSsid(ssid)
		.setContext(context)
		.setPassword(password)
		.setActivatorModel(ActivatorModelEnum.TY_EZ)
		.setTimeOut(timeout)
		.setToken(token)
		.setListener(new ITuyaSmartActivatorListener() {

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

				}
			}
		));
ITuyaActivator mTuyaActivator = TuyaOSActivator.deviceActivator().newMultiActivator(builder);
// Start pairing.
mTuyaActivator.start();

The timeout parameter is set to 100 by default. Unit: 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 ITuyaSmartActivatorListener() {

				@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 allow users to cancel or complete pairing during the process, you must call the API method that supports pairing.

// Stops pairing.
mTuyaActivator.stop();
// Exits the page and destroys certain caches and listeners.
mTuyaActivator.onDestroy();

Device control

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

Object Description Reference
DeviceBean
  • Similar to ITuyaHomeManager and HomeBean, DeviceBean stores the basic information about a device, such as the ID, name, and icon.
  • The dps attribute of the DeviceBean class defines the status of a device. The status is known as one or more data points (DPs). Each DP stores the features of a device. A DP can define a switch of Boolean type or the brightness of Value type. To enable device control, the DPs can be queried and modified.
DPs
ITuyaDevice Stores all data of device features, such as device control and firmware management. You must use the correct value of deviceId to initialize ITuyaDevice. Device Management (Android)

Query a list of devices

After a device is paired, users can query a list of devices that are created for a specific area.

You must first call the API method that enables the query. Otherwise, the query will fail even after the device is paired.

        TuyaCommercialLightingArea.newAreaInstance(mProjectId, mAreaId).queryDeviceListInArea("", 20,
                "1", new ITuyaResultCallback<LightingDeviceListBean>() {
                    @Override
                    public void onSuccess(LightingDeviceListBean result) {
                        //success callback0
                    }

                    @Override
                    public void onError(String errorCode, String errorMessage) {
                    		//error callback
                    }
                });

View device information

All DP data is stored in dps. Each DP is encapsulated as a key-value pair.

TuyaOSDevice.newDeviceInstance(devId).getDp(dpId, new IResultCallback() {
    @Override
    public void onError(String code, String error) {

    }

    @Override
    public void onSuccess() {

    }
});

In the query of DP data, the response is asynchronously called back by IDevListener.onDpUpdate().

Control a device

To enable device control, you must initialize the device control class. DPs can be sent to a device to change the device status or features and control the device.

The parameter dps can define one or more DPs. Thus, multiple states of a device can be changed in the same call.

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 successfully.", Toast.LENGTH_SHORT).show();
	}
});

To listen for changes in device status, such as getting online, removal notifications, and DP data changes, register IDevListener. For more information, see Listen for devices.

mDevice.registerDevListener(new IDevListener() {
	/**
	* Updates the DP.
	* `devId`: the device ID.
	* `dpStr`: The updated DP. It is a JSON string in the following format: {"101": true}.
	*/
	@Override
	public void onDpUpdate(String devId, String dpStr){

    };

	/**
	* The callback of 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`: indicates 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` indicates 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 of device updates.
	* `devId`: the device ID.
	*/
	@Override
	public void onDevInfoUpdate(String devId){

    };
}

Remove a device

You can call the API method removeDevice to remove a device from a specific project.

mDevice.removeDevice(new IResultCallback() {
	@Override
	public void onError(String errorCode, String errorMsg) {
	}

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

Next step

In most commercial lighting scenarios, devices are managed in groups. A group is an aggregation of one or more devices that follow certain rules. This way, devices can be easily controlled by group.

For more information, see Group Management. You can also download the GitHub sample as mentioned at the beginning of this tutorial to get your development up and running.