Smart Scenes

Last Updated on : 2023-05-22 06:38:26

Smart scenes include the following types: tap-to-run and automation.

  • Tap-to-run: Users can add actions to a smart scene. Later, they can tap the tap-to-run scene to run it when needed.
  • Automation: Users can set specific conditions to run a smart scene. When the conditions are met, the automation scene is automatically triggered.

Feature overview

Tuya supports users’ smart life requirements. For example, set weather conditions or device status as triggers for a specific smart scene. When any triggers occur, one or more linked devices will run predefined tasks.

Scene management Description
TuyaHomeSdk.getSceneServiceInstance() Manage conditions, tasks, devices, scenes, and logs, and implement smart scenes.

Before you make API requests for smart scenes, you must learn about scene conditions and scene tasks.

Scene conditions

The SceneCondition class is used to manage scene conditions. Tuya supports the following conditions:

  • Weather conditions: temperature, humidity, weather, PM2.5, air quality, sunrise, and sunset. Users can select the current city when they set weather conditions.
  • Device conditions: Users can predefine a device condition in a specific smart scene. When this condition is met, the task in the specified smart scene will be triggered. The same device cannot be used as a condition and a task at the same time. Otherwise, operation conflicts might occur.
  • Scheduled tasks: A task can be scheduled to run at a specific time.

The following table lists the attributes of SceneCondition.

Field Type Description
defaultIconUrl String The default icon of a condition.
id String The condition ID.
entitySubIds String The identifiers of the conditions other than devices. Example:
  • temp: temperature
  • humidity: humidity
  • condition: weather
  • pm25: PM2.5
  • aqi: air quality
  • sunsetrise: sunrise and sunset
  • windSpeed: wind speed
entityType Int The type of condition. Example:
  • 99: tap-to-run scene
  • 1: device
  • 11: return home
  • 10: location change
  • 6: scheduled task
  • expr List<Object> The expression of a condition DP. Example: [["$temp","<",-40]].
    iconUrl String The icon of a condition.
    entityName String The name of a condition.
    condType Integer The rules of matching conditions. Example:
    • 1: match against expressions
    • 2: simple match
    Note: This field is intended for raw type of data. The value of condType is 2 for this type of data.
    exprDisplay String The name of a subtitle. Example: "Temperature: less than -40°F".
    entityId String The device ID. This field works for device conditions.
    productId String The product ID. This field works for device conditions.
    productPic String The product image. This field works for device conditions.
    devDelMark Boolean Indicates whether a device is removed. This field works for device conditions.
    deleteDevIcon String The icon that indicates a removed device. This field works for device conditions.
    extraInfo ConditionExtraInfo The extension properties of a condition.

    Fields of ConditionExtraInfo

    Field Type Description
    tempUnit String The current temperature unit.
    cityName String The name of a city
    delayTime String The value of the delay condition that is predefined for an infrared device.
    percent Map<String,String> The DP of percent type, including the DP value that ranges from 0% to 100%.
    percent1 Map<String,String> The DP of percent type, including the DP value that ranges from 1% to 100%.
    members String The members of a smart lock that is specified as a condition.
    timeWindow long The value of the delay condition that is customized for an infrared device.
    calType String The tag of the delay condition that is customized for an infrared device.
    maxSeconds long The maximum value of the delay condition that is customized for an infrared device.
    center Map<String,Double> The central coordinates of a geofence.
    radius int The radius of a geofence.
    geotitle String The name of a geofence.
    windSpeedUnit String The unit of wind speed.
    originTempUnit String The original unit of temperature.
    dpScale int The conversion factor between Celsius (°C) and Fahrenheit (°F).

    Scene tasks

    In a scene task, one or more devices are triggered to run specific tasks when specified weather or device conditions are met in the scene. The SceneAction class is used to manage scene tasks. Automation scenes can also be enabled or disabled.

    Fields of SceneAction

    Field Type Description
    id String The action ID.
    actionExecutor String The type of the action. Enum values:
    • ruleTrigger: triggered scene
    • ruleEnable: automation scene enabled
    • ruleDisable: automation scene disabled
    • appPushTrigger: push notifications
    • mobileVoiceSend: phone call services
    • smsSend: SMS services
    • deviceGroupDpIssue: control a device group
    • irIssue: control an IR device
    • dpIssue: control a common device
    • delay: delayed action
    • irIssueVii: run an IR device (real IR control code used)
    • toggle: control a toggle switch
    • dpStep: run a stepped action
    entityId String The device ID.
    entityName String The name of the device.
    actionDisplayNew Map<String, List<String>> The displayed details of an action.
    executorProperty Map<String, Object> The execution details of an action.
    extraProperty Map<String, Object> The additional information of an action.

    Scene conditions

    Query a list of cities

    API description

    Returns a list of cities to create a weather condition.

    Currently, only cities in mainland China can be returned.

    fun getLocalCityAll(countryCode: String, callback: IResultCallback<List<LocationCity>?>?)
    

    Parameters

    Parameter Description
    countryCode The country or region code. Example: cn means China.
    callback The callback.

    Example

          TuyaHomeSdk.getSceneServiceInstance().conditionService().getLocalCityAll(
                "cn",  // Means mainland China.
                object : IResultCallback<List<LocationCity?>?>() {
                    override fun onSuccess(result: List<LocationCity?>?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Fields of LocationCity

    Field Type Description
    area String The name of the area.
    province String The name of the province.
    city String The name of the city.
    cityId long The city ID.
    pinyin String The Hanyu Pinyin of the city name in Chinese.

    Query city information by longitude and latitude

    API description

    Returns city information by longitude and latitude to display the current weather condition.

    fun getLocalByCoordinate(lon: String, lat: String, callback: IResultCallback<LocationCity?>?)
    

    Parameters

    Parameter Description
    lon The longitude of the city.
    lat The latitude of the city.
    callback The callback.

    The properties of LocationCity are described in Query a list of cities.

    Example

            TuyaHomeSdk.getSceneServiceInstance().conditionService().getLocalByCoordinate(
                longitude.toString(),  // The longitude of the city.
                latitude.toString(),  // The latitude of the city.
                object : IResultCallback<LocationCity?>() {
                    override fun onSuccess(result: LocationCity?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Query city information by city ID

    API description

    Returns existing weather conditions. You can call getLocalCityAll to get the city ID.

    fun getLocalByCityId(cityId: Long, callback: IResultCallback<LocationCity?>?)
    

    Parameters

    Parameter Description
    cityId The city ID.
    callback The callback.

    The properties of LocationCity are described in Query a list of cities.

    Example

            TuyaHomeSdk.getSceneServiceInstance().conditionService().getLocalByCityId(
                cityId,  // The city ID.
                object : IResultCallback<LocationCity?>() {
                    override fun onSuccess(result: LocationCity?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Query a list of conditions

    API description

    Returns a list of conditions. For example, temperature, humidity, weather, PM2.5, sunrise, and sunset can be returned as the conditions. Note that devices can also be used as conditions. Temperature can be displayed in °C or °F. You can specify the required unit for temperature.

    fun getConditionAll(
            relationId: Long,
            showFahrenheit: Boolean,
            windSpeedUnit: String? = "",
            callback: IResultCallback<ConditionItemList?>?
        )
    

    Parameters

    Parameter Description
    relationId The home ID.
    showFahrenheit
    • true: °F is used as the unit.
    • false: °C is used as the unit.
    windSpeedUnit The wind speed unit.
    callback The callback.

    Example

            TuyaHomeSdk.getSceneServiceInstance().conditionService().getConditionAll(
                homeId,  // The home ID.
                true, "", object : IResultCallback<ConditionItemList?>() {
                    override fun onSuccess(result: ConditionItemList?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Fields of ConditionItemList

    Field Type Description
    envConds List The list of weather conditions.
    devConds List The list of scene condition types.

    Fields of ConditionItemDetail

    Field Type Description
    entitySubId String The tag of a data point (DP) ID or condition type. Example: temp, humidity, condition, pm25, aqi, windSpeed, and sunsetrise.
    operators String The array of logical expressions in the JSON format. The operators include <, =, and >.
    id long The condition ID.
    entityId String The tag of a device ID, geofence ID, or condition type. Example: temp, humidity, condition, pm25, aqi, windSpeed, and sunsetrise.
    entityType int The type of condition.
    entityName String The name of the condition.
    valueRangeJson List<List> The DP ID and DP value.
    mcGroups List The object of the multi-control group.
    condCalExtraInfo ConditionExtraInfo The extension properties of the condition.
    property ConditionOuterProperty The properties of the condition.

    Fields of ConditionExtraInfo

    Field Type Description
    tempUnit String The current temperature unit.
    cityName String The name of the city.
    delayTime String The value of the delay condition that is predefined for an infrared device.
    percent Map<String,String> The DP of percent type, including the DP value that ranges from 0% to 100%.
    percent1 Map<String,String> The DP of percent type, including the DP value that ranges from 1% to 100%.
    members String The members of a smart lock that is specified as a condition.
    timeWindow long The value of the delay condition that is customized for an infrared device.
    calType String The tag of the delay condition that is customized for an infrared device.
    maxSeconds long The maximum value of the delay condition that is customized for an infrared device.
    center Map<String,Double> The central coordinates of a geofence.
    radius int The radius of a geofence.
    geotitle String The name of a geofence.
    windSpeedUnit String The wind speed unit.
    originTempUnit String The original unit of temperature.
    dpScale int The conversion factor from Celsius to Fahrenheit.

    Fields of ConditionOuterProperty

    Field Type Description
    id String The DP ID.
    property ConditionInnerProperty The details of the property.

    Fields of ConditionInnerProperty

    Field Type Description
    unit String The unit.
    min int The minimum value.
    max int The maximum value.
    step int The step. If the maximum value is 100 and the step is 10, the valid values can be min, min+10, min+20 …, and 100.
    type String The type of condition.
    scale int The decimal conversion factor.

    Property is a common data structure to control devices and implement other features. The following Property types are supported:

    • Numeric
    • Enum
    • Boolean
    • The type of scheduled task (numeric, enum, or Boolean as specified in conditions)

    Different API methods are provided for each Property type.

    Scene devices

    Query a list of DPs for device conditions

    API description

    To set a scene condition, after a device is selected, the list of data points (DPs) must be obtained by the value of deviceId for the specified device. Then, the preferred DP can be selected as the condition that triggers the scene in which the device implements the task of the DP.

    fun getConditionDeviceDpAll(deviceId: String, callback: IResultCallback<List<ConditionItemDetail>?>?)
    

    Parameters

    Parameter Description
    deviceId The device ID.
    callback The callback.

    For more information about the properties of ConditionItemDetail, see Query a list of conditions.

    Example

            TuyaHomeSdk.getSceneServiceInstance().deviceService().getConditionDeviceDpAll(
                "devId", // The device ID.
                object : IResultCallback<List<ConditionItemDetail>?>() {
                    override fun onError(errorCode: String?, errorMessage: String?) {
                    }
    
                    override fun onSuccess(result: List<ConditionItemDetail>?) {
                    }
                })
    

    Query a list of devices specified as conditions

    API description

    Return a list of devices that support specific conditions.

    fun getConditionDeviceAll(
            relationId: Long,
            callback: IResultCallback<List<DeviceBean?>?>?
        )
    

    Parameters

    Parameter Description
    relationId The home ID.
    callback The callback.

    Example

            TuyaHomeSdk.getSceneServiceInstance().deviceService().getConditionDeviceAll(
                homeId,  // The home ID.
                object : IResultCallback<List<DeviceBean?>?>() {
                    override fun onSuccess(deviceBeans: List<DeviceBean?>?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Query a list of DPs for device conditions

    API description

    Return a list of device IDs that support specific conditions.

    fun getConditionDeviceIdAll(
            relationId: Long,
            callback: IResultCallback<List<String>?>?
        )
    

    Parameters

    Parameter Description
    relationId The home ID.
    callback The callback.

    Example

      TuyaHomeSdk.getSceneServiceInstance().deviceService().getConditionDeviceIdAll(
                homeId,  // The home ID.
                object : IResultCallback<List<String?>?>() {
                    override fun onSuccess(deviceIds: List<String?>?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Query a list of DPs for action device

    API description

    To select a scene task, after a device is selected, the list of data points (DPs) must be obtained by the value of deviceId for the specified device. Then, the preferred DP can be selected as the task to be run in the scene.

    fun getActionDeviceDpAll(deviceId: String, callback: IResultCallback<List<ActionDeviceDataPointList>?>?)
    

    Parameters

    Parameter Description
    deviceId The device ID.
    callback The callback.

    Fields of ActionDeviceDataPointList

    Field Type Description
    id long The ID of the device DP.
    functionType Int The type of device DP.
    productId String The product ID of the device.
    functionName String The name of the device DP.
    dataPoints List The list of DPs for the device.

    Fields of ActionDeviceDataPointDetail

    Field Type Description
    dpName String The name of the device DP.
    dpId int The ID of the device DP.
    editable Boolean Indicates whether a DP can be modified.
    valueType String The type of light for the DP.
    dpProperty String The type of DP value.
    valueRangeJson String The content of the DP value.
    defaultValue Object The default value of the DP.
    stepHighDpProperty StepDpProperty The incremental step.
    stepLowDpProperty StepDpProperty The decreased step.

    Example

            TuyaHomeSdk.getSceneServiceInstance().deviceService().getActionDeviceDpAll(
                "devId", // The device ID.
                object : IResultCallback<List<ActionDeviceDataPointList>?>() {
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
    
                    override fun onSuccess(result: List<ActionDeviceDataPointList>?) {
                    }
    
                })
    

    Query a list of DPs for action device group

    API description

    To select a scene task, after a device is selected, the list of data points (DPs) must be obtained by the value of deviceId for the specified device. Then, the preferred DP can be selected as the task to be run in the scene.

    fun getActionGroupDeviceDpAll(groupDeviceId: String, callback: IResultCallback<List<ActionDeviceDataPointList>?>?)
    

    Parameters

    Parameter Description
    groupDeviceId The ID of the device group.
    callback The callback.

    For more information about the properties of ActionDeviceDataPointList, see Query a list of DPs for action device.

    Example

            TuyaHomeSdk.getSceneServiceInstance().deviceService().getActionGroupDeviceDpAll(
                groupDeviceId, // The ID of the device group.
                object : IResultCallback<List<ActionDeviceDataPointList>?>() {
                    override fun onError(errorCode: String?, errorMessage: String?) {
                        TODO("Not yet implemented")
                    }
    
                    override fun onSuccess(result: List<ActionDeviceDataPointList>?) {
                        TODO("Not yet implemented")
                    }
                })
    

    Query a list of action devices

    API description

    Returns a list of devices that support a specific action in a scene. You can select common devices, group devices, and IR devices from the list to create the actions to be performed.

    fun getActionDeviceAll(relationId: Long, callback: IResultCallback<ActionDeviceGroup?>?)
    

    Parameters

    Parameter Description
    relationId The home ID.
    callback The callback.

    Fields of ActionDeviceGroup

    Field Type Description
    devices List<DeviceBean> The list of common devices.
    groups List<GroupBean> The list of group devices.
    exts Map<String, Map<String, String>> The additional information.

    Example

            TuyaHomeSdk.getSceneServiceInstance().deviceService().getActionDeviceAll(homeId, object : IResultCallback<ActionDeviceGroup>() {
                override fun onError(errorCode: String?, errorMessage: String?) {
                }
    
                override fun onSuccess(result: ActionDeviceGroup) {
                }
            })
    

    Query a list of action device IDs

    API description

    Return a list of devices that support specific actions in a scene.

    fun getActionDeviceIdAll(relationId: Long, callback: IResultCallback<ActionDeviceGroupId?>?)
    

    Parameters

    Parameter Description
    relationId The home ID.
    callback The callback.

    Fields of ActionDeviceGroupId

    Field Type Description
    deviceIds List<String> The list of common device IDs.
    groupIds List<Long> The list of group device IDs.
    exts Map<String, Map<String, String>> The additional information.

    Example

         TuyaHomeSdk.getSceneServiceInstance().deviceService().getActionDeviceIdAll(homeId, object : IResultCallback<ActionDeviceGroupId>() {
                override fun onError(errorCode: String?, errorMessage: String?) {
    
                }
    
                override fun onSuccess(result: ActionDeviceGroupId) {
                }
    
            });
    

    Smart scenes

    Tuya Smart Life App SDK allows users to create, modify, run, and delete a single smart scene. These operations except creation require a scene ID for initialization. You can call getSceneList to get the scene ID.

    Delete a scene

    API description

    fun deleteSceneWithHomeId(relationId: Long, sceneId: String, callback: IResultCallback<Boolean>?)
    

    Parameters

    Parameter Description
    relationId The home ID.
    sceneId The scene ID.
    callback The callback.

    Example

            val sceneId: String = sceneBean.getId()
    
            TuyaHomeSdk.getSceneServiceInstance().baseService().deleteSceneWithHomeId(
                relationId,
                sceneId,
                object : IResultCallback<Boolean?>() {
                    override fun onSuccess(result: Boolean?) {
                        Log.d(TAG, "Delete Scene Success")
                    }
    
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Query a lightweight list of smart scenes

    API description

    Returns a list of smart scenes. Tap-to-run and automation scenes are queried in the same request. The conditions field can be set or not to differentiate both types of smart scenes. This field can be set to a single condition for a tap-to-run scene.

    fun getSimpleSceneAll(relationId: Long, callback: IResultCallback<List<NormalScene>?>?)
    

    Parameters

    Parameter Description
    relationId The home ID.
    callback The callback.

    Example

            TuyaHomeSdk.getSceneServiceInstance().baseService().getSimpleSceneAll(
                homeId,
                object : IResultCallback<List<NormalScene?>?>() {
                    override fun onSuccess(result: List<NormalScene?>?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Fields of NormalScene

    Field Type Description
    id String The scene ID.
    coverIcon String The icon of the tap-to-run scene.
    name String The name of the scene.
    conditions List The list of scene conditions.
    displayColor String The background color of a scene.
    actions List The list of actions.
    enabled Boolean Indicates whether an automation scene is enabled.
    stickyOnTop Boolean Indicates whether a scene is displayed on the homepage.
    newLocalScene Boolean Indicates whether tap-to-run scenes are supported by the same gateway.
    localLinkage Boolean Indicates whether automation scenes are supported by the same gateway.
    arrowIconUrl String The arrow icon of a scene.
    preConditions List Set the effective period of a scene.
    fullData Boolean Indicates whether full data is displayed for a scene.
    outOfWork int The state of a scene. Valid values:
    • 0: normal
    • 1: expired
    • 2: exceptional

    Fields of PreCondition

    Field Type Description
    id String The condition ID.
    condType String The type of condition. It is a fixed value of timeCheck.
    expr PreConditionExpr The details of the effective period.

    Fields of PreConditionExpr

    Field Type Description
    loops String Indicates the way a smart scene recurs. For example, 1111111 means that it recurs every day, 1000001 means that it recurs at weekends, and 0111110 means that it recurs from Monday to Friday.
    start String The start time of the custom recurring effective period. Example: 00:00.
    end String The end time of the custom recurring effective period. Example: 23:59.
    timeInterval String The effective period. Example:
    • custom: custom time
    • daytime: daytime
    • night: night
    • allDay: all day
    cityId String The city ID.
    timeZoneId String The time zone ID.
    cityName String The name of the city.

    Query scene details by home ID and scene ID

    API description

    fun getSceneDetail(relationId: Long, sceneId: String, callback: IResultCallback<NormalScene?>?)
    

    Parameters

    Parameter Description
    relationId The home ID.
    sceneId The scene ID.
    callback The callback.

    For more information about the properties of NormalScene, see Query a lightweight list of smart scenes.

    Example

            TuyaHomeSdk.getSceneServiceInstance().baseService().getSceneDetail(
                homeId,
                sceneId,
                object : IResultCallback<NormalScene?>() {
                    override fun onSuccess(result: NormalScene?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Add a smart scene

    API description

    To add a scene, users must set the home ID, scene name, and URL of the background image, and specify whether to show the scene on the homepage. Users must also define the list of conditions, tasks, and preconditions. At least one task must be specified. The effective period is optional and can be included in the preconditions. If it is not defined, the scene takes effect all day long. The scene can also be configured to run when any or all conditions are met. Users can also only set the name, task, and background image, and skip conditions. Then, users need to tap the smart scene to run it.

    fun saveScene(relationId: Long, sceneData: NormalScene, callback: IResultCallback<NormalScene?>?)
    

    Parameters

    Parameter Description
    relationId The home ID.
    sceneData The smart scene data.
    callback The callback.

    For more information about the properties of NormalScene, see Query a lightweight list of smart scenes.

    Example

            TuyaHomeSdk.getSceneServiceInstance().baseService().saveScene(
                homeId,
                sceneData,
                object : IResultCallback<NormalScene?>() {
                    override fun onSuccess(result: NormalScene?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Modify a smart scene

    API description

    Modifies a smart scene. The new scene is returned after a successful call.

    This API method only applies when a scene is modified. Do not specify the NormalScene object to create a new scene.

    fun modifyScene(sceneId: String, sceneData: NormalScene, callback: IResultCallback<NormalScene?>?)
    

    Parameters

    Parameter Description
    sceneId The scene ID.
    sceneData The modified scene object.
    callback The callback.

    For more information about the properties of NormalScene, see Query a lightweight list of smart scenes.

    Example

            sceneBean.setName("New name") // Renames a smart scene.
    
            sceneBean.setConditions(Collections.singletonList(condition)) // Modifies the scene conditions.
    
            sceneBean.setActions(tasks) // Modifies the scene actions.
    
            val sceneId: String = sceneBean.getId() // Returns the scene ID for initialization.
    
            TuyaHomeSdk.getSceneServiceInstance().baseService().modifyScene(
                sceneId,
                sceneBean,
                object : IResultCallback<NormalScene?>() {
                    override fun onSuccess(result: NormalScene?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Sort tap-to-run or automation scenes

    API description

    fun sortSceneList(relationId: Long, sceneIds: List<String>, callback: IResultCallback<Boolean>?)
    

    Parameters

    Parameter Description
    relationId The home ID.
    sceneIds The list of scene IDs.
    callback The callback.

    Example

            TuyaHomeSdk.getSceneServiceInstance().baseService().sortSceneList(
                homeId,
                sceneIds,
                object : IResultCallback<Boolean?>() {
                    override fun onSuccess(result: Boolean?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Enable or disable an automation scene

    API description

    fun enableAutomation(sceneId: String, callback: IResultCallback<Boolean>?)
    
    fun disableAutomation(sceneId: String, callback: IResultCallback<Boolean>?)
    

    Parameters

    Parameter Description
    sceneId The scene ID.
    callback The callback.

    Example

            val sceneId: String = sceneBean.getId()
    
            TuyaHomeSdk.getSceneServiceInstance().baseService().enableAutomation(
                sceneId,
                object : IResultCallback() {
                    override fun onSuccess() {
                        Log.d(TAG, "enable Scene Success")
                    }
    
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    
            TuyaHomeSdk.getSceneServiceInstance().baseService().disableAutomation(
                sceneId,
                object : IResultCallback() {
                    override fun onSuccess() {
                        Log.d(TAG, "disable Scene Success")
                    }
    
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Enable an automation scene at specified time

    API description

    fun enableAutomationWithTime(sceneId: String, time: Int, callback: IResultCallback<Boolean>?)
    

    Parameters

    Parameter Description
    sceneId The scene ID.
    time The time when the smart scene is enabled.
    callback The callback.

    Example

            val sceneId: String = sceneBean.getId()
    
            TuyaHomeSdk.getSceneServiceInstance().baseService().enableAutomationWithTime(
                sceneId,
                time,
                object : IResultCallback() {
                    override fun onSuccess() {
                        Log.d(TAG, "enable Scene Success")
                    }
    
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Run a smart scene

    This API method is only used to send commands to run a scene. To check whether the device successfully runs the scene, use TuyaHomeSdk.newDeviceInstance(devId).registerDevListener() to listen for changes of device DPs.

    API description

    fun executeScene(sceneData: NormalScene, callback: IResultCallback? = null)
    

    Parameters

    Parameter Description
    sceneData The smart scene data.
    callback The callback.

    Example

            val sceneId: String = sceneBean.getId()
            TuyaHomeSdk.getSceneServiceInstance().executeService().executeScene(
                sceneData,
                object : IResultCallback() {
                    override fun onSuccess() {
                        Log.d(TAG, "Excute Scene Success")
                    }
    
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Register a listener for changes in scene information

    API description

    Listens for changes in scene information. For example, a scene is created, modified, deleted, enabled, or disabled.

    fun registerDeviceMqttListener(callback: SceneChangeCallback)
    

    Parameters

    Parameter Description
    callback The listener for changes in scene status.

    SceneChangeCallback

    interface SceneChangeCallback {
        /**
         * Disables an automation scene.
         */
        fun onDisableScene(sceneId: String)
    
        /**
         * Enables an automation scene.
         */
        fun onEnableScene(sceneId: String)
    
        /**
         * Deletes a scene.
         */
        fun onDeleteScene(sceneId: String)
    
        /**
         * Creates a scene.
         */
        fun onAddScene(sceneId: String)
    
        /**
         * Updates a scene.
         */
        fun onUpdateScene(sceneId: String)
    }
    

    Example

            TuyaHomeSdk.getSceneServiceInstance().executeService().registerDeviceMqttListener(object : SceneChangeCallback {
                override fun onDisableScene(sceneId: String) {
    
                }
                override fun onEnableScene(sceneId: String) {
    
                }
                override fun onDeleteScene(sceneId: String) {
    
                }
                override fun onAddScene(sceneId: String) {
    
                }
                override fun onUpdateScene(sceneId: String) {
    
                }
            })
    

    Unregister a listener for changes in scene information

    API description

    Unregisters a listener for changes in scene information when the change status is not required.

    fun unRegisterDeviceMqttListener()
    

    Example

    TuyaHomeSdk.getSceneServiceInstance().executeService().unRegisterDeviceMqttListener()
    

    Scene logs

    Query a list of scene running logs

    API description

    Returns a list of logs on the log page.

    fun getExecuteLogAll(
            relationId: Long,
            startTime: Long,
            endTime: Long,
            size: Int,
            lastId: String?,
            lastRecordTime: Long?,
            callback: IResultCallback<ExecuteLogList?>?
        )
    

    Parameters

    Parameter Description
    relationId The home ID.
    startTime The start time of the log entries.
    endTime The end time of the log entries.
    size The number of entries returned per page.
    lastId The value of eventId for the last log entry returned. It is used to load more data on pages.
    lastRecordTime The value of execTime for the last log entry returned. It is used to load more data on pages.
    callback The callback.

    Fields of ExecuteLogList

    Field Type Description
    totalCount int The total number of log entries.
    datas List The list of log details.

    Fields of ExecuteLogItem

    Field Type Description
    eventId String The log ID.
    ruleId String The scene ID.
    ruleName String The name of the scene.
    uid String The user ID.
    execResult int The code that indicates the execution result.
    execResultMsg String The information about the execution result.
    failureCode int The error code.
    failureCause String The error message.
    execTime long The time when a smart scene is executed.
    sceneType int The type of smart scene.
    execMessage String The information about the execution.

    Example

            TuyaHomeSdk.getSceneServiceInstance().logService().getExecuteLogAll(
                homeId,
                startTime,
                endTime,
                size,
                lastId,
                lastRecordTime,
                object : IResultCallback<ExecuteLogList?>() {
                    override fun onSuccess(result: ExecuteLogList?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Query log details

    API description

    Returns the details about a single log entry by log ID.

    fun getExecuteLogDetail(
            relationId: Long,
            eventId: String?,
            startTime: Long,
            endTime: Long,
            returnType: Long,
            callback: IResultCallback<List<ExecuteLogDetail>?>?
        )
    

    Parameters

    Parameter Description
    relationId The home ID.
    eventId The log ID.
    startTime The start time of the log entries.
    endTime The end time of the log entries.
    returnType The type of log. Valid values:
    • 0: all logs
    • 1: failure logs
    callback The callback.

    Fields of ExecuteLogDetail

    Field Type Description
    actionId String The ID of the scene action.
    actionEntityId String The ID of the device that runs the target action.
    actionEntityName String The name of the device that runs the target action.
    executeTime String The time when a smart scene is executed.
    errorCode String The error code.
    execStatus int The execution status of the smart scene.
    errorMsg String The error message.
    actionEntityUrl String The icon of the device that runs the target action.
    actionExecutor String The DP of the device that runs the target action.
    detail List The details of the log.

    Fields of LogDetail

    Field Type Description
    detailId String The ID of the log details.
    detailName String The name of the log details.
    status int The execution status of the smart scene.
    code String The error code.
    msg String The error message.
    icon String The icon of the log details.

    Example

            TuyaHomeSdk.getSceneServiceInstance().logService().getExecuteLogDetail(
                homeId,
                eventId,
                startTime,
                endTime,
                type,
                object : IResultCallback<List<ExecuteLogDetail?>?>() {
                    override fun onSuccess(result: List<ExecuteLogDetail?>?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Query a list of device logs

    API description

    Returns a list of device logs to a target panel.

    fun getDeviceLogAll(
            relationId: Long,
            deviceId: String,
            startTime: Long,
            endTime: Long,
            size: Int,
            lastId: String?,
            lastRecordTime: Long?,
            callback: IResultCallback<ExecuteLogList?>?
        )
    

    Parameters

    Parameter Description
    relationId The home ID.
    deviceId The device ID.
    startTime The start time of the log entries.
    endTime The end time of the log entries.
    size The number of entries returned per page.
    lastId The value of eventId for the last log entry returned. It is used to load more data on pages.
    lastRecordTime The value of execTime for the last log entry returned. It is used to load more data on pages.
    callback The callback.

    For more information about the properties of ExecuteLogList, see Query a list of scene running logs.

    Example

            TuyaHomeSdk.getSceneServiceInstance().logService().getDeviceLogAll(
                homeId,
                devId,
                startTime,
                endTime,
                size,
                lastId,
                lastRecordTime,
                object : IResultCallback<ExecuteLogList?>() {
                    override fun onSuccess(result: ExecuteLogList?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Example

    Create a scene condition object

    The SceneCondition class is used to manage scene conditions. It includes four important properties: entityId, entitySubIds, entityType, and expr.

    Scene condition type Description
    Scheduled task
    • The entityId property is set to the string timer.
    • The entitySubIds property is set to the string timer.
    • The entityType property is set to 6.
    • The expr property contains a map at the inner layer. Example: {timeZoneId = "Asia/Shanghai",loops = "0000000",time = "08:00",date = "20180308"}.
    Weather changes
    • The entityId property is set to a city ID.
    • The entitySubIds property is an enumeration of weather types, such as humidity.
    • The entityType property is set to 3.
    • The expr property contains a list at the inner layer. Example: ["$humidity", "==", "comfort"].
    Device
    • The entityId property is set to a device ID.
    • The entitySubIds property is set to a DP ID.
    • The entityType property is set to 1.
    • The expr property contains a list at the inner layer. Example: ["$dp1", "==", true].

    Combine scene condition objects using expr

    The expr property of SceneCondition describes a condition expression. For example, expr can be used to describe the condition that the temperature is lower than 15°C.

    The outermost layer of expr must be an array. Each object of the array represents a condition. For example, the array ["$temp","<",15] shows the condition in which the temperature is lower than 15°C.

    • Examples of weather conditions specified by expr:

      • Temperature: [[“$temp”,“<”,15]]
      • Humidity: [[“$humidity”,“==”,“comfort”]]
      • Weather: [[“$condition”,“==”,“snowy”]]
      • PM2.5: [[“$pm25”,“==”,“fine”]]
      • Air quality: [[“$aqi”,“==”,“fine”]]
      • Sunrise and sunset: [[“$sunsetrise”,“==”,“sunrise”]]
    • Examples of scheduled tasks specified by expr:

      A scheduled task condition is specified by a map. Example: {timeZoneId = "Asia/Shanghai",loops = "0000000",time = "08:00",date = "20180308"}. Each bit of loops represents a day from Sunday to Saturday, in which 1 means valid and 0 means invalid. expr is an array, so the scheduled task map must be enclosed with an array.

    • Examples of device conditions specified by expr:

      A device condition is specified with an array to represent a specific condition value. The combined conditions of expr can be expressed as [[“$dp1”,“==”,true]]. This expression shows the condition in which the light is switched on. In this expression, dp1 is DP+DP ID.

    Set scene actions

    The scene action class is SceneAction. It includes three important properties: entityId describes the object, actionExecutor describes the action type, and executorProperty describes the action details.

    Scene action type Description
    Device
    • The entityId property is set to the value of devId.
    • actionExecutor is set to the value of dpIssue.
    • executorProperty is a map. For example, {"1":true} specifies DP 1, and the action is set to true. This applies to DPs of Boolean type, such as the light switch status. You can call getActionDeviceDpAll to get the ID and possible values of a specific DP.
    Device group
    • The entityId property is set to the value of groupId.
    • actionExecutor is set to the value of deviceGroupDpIssue.
    • Other properties are the same as those of device actions.
    Trigger a scene
    • The entityId property is set to the value of sceneId for a smart scene.
    • actionExecutor is set to the value of ruleTrigger.
    • executorProperty is not required.
    Automation scene enabled
    • The entityId property is set to the value of sceneId for an automation scene.
    • actionExecutor is set to the value of ruleEnable.
    • executorProperty is not required.
    Automation scene disabled
    • The entityId property is set to the value of sceneId for an automation scene.
    • actionExecutor is set to the value of ruleDisable.
    • executorProperty is not required.
    Delayed action
    • The entityId property is set to the value of delay.
    • actionExecutor is set to the value of delay.
    • executorProperty specifies a delay expressed with a map. For example, {"minutes":"1","seconds":"30"} specifies a delay of 1 minute and 30 seconds. Currently, the delay can be up to five hours or 300 minutes.

    Example

    /**
     * Create a scheduled task in a smart scene: Condition devices run actions at a specified point of time.
     */
    
    var deviceId: String // The device ID.
    var dpId: Int  // The DP ID.
    
    val normalScene = NormalScene().apply {
        conditions = listOf(SceneCondition().apply {
            entityId = "timer"
            entitySubIds = "timer"
            entityType = 3
            expr = listOf(
                mutableMapOf(
                    "timeZoneId" to TimeZone.getDefault().id,
                    "loops" to "0000000",
                    "time" to "08:00",
                    "date" to "20180308"
                )
            )
        })
        actions = listOf(SceneAction().apply {
            entityId = deviceId
            actionExecutor = "dpIssue"
            executorProperty = mapOf("\$dp${dpId}" to true)
        })
    }