Device Control

Last Updated on : 2024-06-12 10:22:40download

In simple application scenarios, a mobile app is used to control only one smart device. However, with the technical advancement in the IoT field, more and more IoT devices are serving smart scenes. A mobile app can be used to control a host of smart devices.

In specific scenarios, certain devices are controlled by multiple users. For example, furniture-like smart power strips can be switched on or off by all home members. In this case, the following requirements must be met: a mobile app can be used to control multiple devices. Multiple users can be authorized to mutually control multiple devices. Therefore, group management and smart scenes are designed to achieve these purposes.

This topic describes how to achieve device control.

Data points

  • The dps property for the class DeviceBean defines the current device status. The status is known as one or more data points (DPs).

  • In each array of dps, key matches dpId of a DP, and dpValue matches the value of the DP.

    You can check the definitions of DPs for a product on the Tuya IoT Development Platform. The following figure shows a list of DPs.

    Device Control

    For more information, see Product Functions.

Command format

Send a control command in the following format:

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

Sample DPs

The following sample code shows the DPs 101, 102, 103, 104, and 105 of a light product that is created on the Tuya IoT Development Platform:

// The data point of Boolean type with the `dpId` value of `101`. Feature: switches on the light.
dps = {"101": true};

// The data point of String type with the `dpId` value of `102`. Feature: sets the red, green, and blue (RGB) value to `ff5500`.
dps = {"102": "ff5500"};

// The data point of Enumeration type with the `dpId` value of `103`. Feature: sets the lighting level to `2`.
dps = {"103": "2"};

// The data point of Value type with the `dpId` value of `104`. Feature: sets the temperature to `20`.
dps = {"104": 20};

// The data point of Raw type with the `dpId` value of `105`. Feature: passes through the infrared data `1122`.
dps = {"105": "1122"};

// Sends multiple DPs in a command.
dps = {"101": true, "102": "ff5500"};

mDevice.publishDps(dps, new IResultCallback() {
        @Override
        public void onError(String code, String error) {
        // The error code 11001 is returned due to the following causes:
        // 1: Data has been sent in an incorrect format. For example, the data of String type has been sent in the format of Boolean data.
        // 2: Read-only DPs cannot be sent. For more information, see SchemaBean getMode. `ro` indicates the read-only type.
        // 3: Data of Raw type has been sent in a format rather than a hexadecimal string.
        }
        @Override
        public void onSuccess() {
        }
    });

Data types must be correct when a control command is sent. Example:

  • A DP of Value type can be sent in the format of {"104": 25} rather than {"104": "25"}.
  • A byte array of Raw type is a hexadecimal string with an even number of digits. In this case, the array can be sent in the format of {"105": "0110"} rather than {"105": "110"}.

Control devices

To enable device control, you must first initialize the device control class. Then, send a control command to a device to change the device status and control the device.

Device control can be implemented in the following three modes:

  • Control over a local area network (LAN): Devices are controlled over a LAN in this mode.
  • Cloud-based control: Devices are controlled through the MQTT and HTTPS channels in this mode. You can call isMqttConnected to query the running status of the MQTT channel.
  • Auto selection of channels: Devices are controlled through the automatically selected channel, which can be LAN, MQTT, or HTTPS.

If the LAN is connected, control over the LAN is recommended. Otherwise, control in the cloud is recommended.

API description

  • Control over the LAN

    IThingDevice.publishDps(dps, ThingDevicePublishModeEnum.ThingDevicePublishModeLocal, callback);
    
  • Device control from the cloud

    IThingDevice.publishDps(dps, ThingDevicePublishModeEnum.ThingDevicePublishModeInternet, callback);
    
  • Automatic control

    IThingDevice.publishDps(dps, ThingDevicePublishModeEnum.ThingDevicePublishModeAuto, callback);
    

    Or

    IThingDevice.publishDps(dps, callback);
    

    We recommend that you call IThingDevice.publishDps(dps, callback) to control devices.

  • Control through a specified channel

    IThingDevice.publishDps(dps, orders, callback);
    

Parameters

Parameter Description
dps The DPs of the device in the format of JSON strings. For more information, see Data points.
callback The callback that indicates whether the control request is successful.
ThingDevicePublishModeEnum The device control method.
orders The sequence of channels through which device control is achieved. Take the enumeration class CommunicationEnum for example. [3 , 1] represents that devices are controlled over Bluetooth in priority. If Bluetooth is unavailable, cloud-based control is implemented.

Example for Java

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();
    }
});
  • Device control is not finished after a command is sent. The device has been controlled as expected only after IDevListener onDpUpdate returns the response.
  • The command string is converted to a JSON string in the format of Map<String,Object>. In this string, String matches dpId, and Object matches dpValue.
  • Each command string can include multiple DPs in each request.

Cache DP data for low power devices

Cache the dps intended for the device in the cloud. When the device wakes up, it will proactively request the cache or receive the push from the cloud.

This method applies to low power devices only and can be invoked even when the device is offline.

API description

void sendCacheDps(String devId, String dps, long validity, int dpCacheType, IThingDataCallback<Boolean> listener);

Parameters

Parameter Description
devId The device ID.
dps The DP.
validity The validity time for the cache, in seconds, ranging from 1 to 172800.
dpCacheType The type of the DP cache.
  • 0: The device proactively pulls the cache.
  • 1: The device receives the push from the cloud.
onSuccess The success callback.
onError The failure callback.

Example

java:

    // validity = 10: indicating the DP data is cached in the cloud for 10s.
    // dpCacheType = 0: indicating the device proactively pulls the cache.
    // After the method is invoked, the dps will be cached in the cloud for 10s, and the device will wake up in 10s to pull the cache.

ThingHomeSdk.getRequestInstance().sendCacheDps("devId", "{\"102\":\"1\",\"125\":\"1\"}", 10, 0, new IThingDataCallback<Boolean>() {
                    @Override
                    public void onSuccess(Boolean result) {
                        Log.i("sendCacheDps", "onSuccess: " + result);
                    }        

                    @Override
                    public void onError(String errorCode, String errorMessage) {
                        Log.i("sendCacheDps", "onError: " + errorMessage);
                    }
                });
            }

Query MQTT status

Devices can be controlled over a LAN, MQTT, or HTTPS. The MQTT channel is most frequently used. You can make the following API request to determine whether the MQTT channel is running as expected.

API description

boolean isMqttConnected = ThingHomeSdk.getServerInstance().isServerConnect();