Smart Scenes

Last Updated on : 2024-07-18 10:42:37download

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

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

Features

The SDK 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
ThingHomeSdk.getSceneServiceInstance() Manage conditions, tasks, devices, scenes, and logs, and implement smart scenes.

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

Scene conditions

The SceneCondition class is used to manage scene conditions. The SDK 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.
  • Schedule: An action can be scheduled to run at a specific time.

The following table lists the properties of SceneCondition.

Field Type Description
defaultIconUrl String The default icon of the condition.
id String The condition ID.
entitySubIds String The identifiers of the conditions other than devices. Example:
  • Temperature: temp
  • Humidity: humidity
  • Weather condition: condition
  • PM2.5: pm25
  • Air quality index: aqi
  • Sunrise and sunset: sunsetrise
  • Wind speed: windSpeed
entityType Int The condition type. Example:
  • Tap-to-run: 99
  • Device: 1
  • When home members come home: 11
  • When location changes: 10
  • Schedule: 6
  • expr List<Object> The expression of the DP condition. Example: [["$temp","<",-40]]
    iconUrl String The icon of the condition.
    entityName String The condition name.
    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 the 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 of the device displayed when it is removed. This field works for device conditions.
    extraInfo ConditionExtraInfo The extension properties of the condition.

    Fields of ConditionExtraInfo:

    Field Type Description
    tempUnit String The current temperature unit.
    cityName String The city name.
    delayTime String The preset value of the custom duration condition for infrared devices.
    percent Map<String,String> The DP that acts as a condition and its value that ranges from 0% to 100%.
    percent1 Map<String,String> The DP that acts as a condition and its value that ranges from 1% to 100%.
    members String The members of the smart lock that is specified as a condition.
    timeWindow long The set value of the custom duration condition for infrared devices.
    calType String The type of the custom duration condition for infrared devices.
    maxSeconds long The maximum value of the custom duration condition for infrared devices.
    center Map<String,Double> The central coordinates of the geofence.
    radius int The radius of the geofence.
    geotitle String The name of the 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: Trigger a scene.
    • ruleEnable: Enable a scene.
    • ruleDisable: Disable a scene.
    • appPushTrigger: Push a notification.
    • mobileVoiceSend: Make a phone call.
    • smsSend: Send an SMS message.
    • deviceGroupDpIssue: Control a device group.
    • irIssue: Control an IR device.
    • dpIssue: Control a common device.
    • delay: Delay an action.
    • irIssueVii: Control an IR device with real IR codes.
    • toggle: Run an on/off action.
    • dpStep: Run a step 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 about an action.

    Scene condition management

    Query the list of cities

    API description

    Get the 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

          ThingHomeSdk.getSceneServiceInstance().conditionService().getLocalCityAll(
                "cn", // 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 city name.
    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

    Get city information by longitude and latitude to display the current weather conditions.

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

    Parameters

    Parameter Description
    lon The longitude.
    lat The latitude.
    callback The callback.

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

    Example

            ThingHomeSdk.getSceneServiceInstance().conditionService().getLocalByCoordinate(
                longitude.toString(), //  Longitude
                latitude.toString(), //  Latitude
                object : IResultCallback<LocationCity?>() {
                    override fun onSuccess(result: LocationCity?) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Query city information by city ID

    API description

    Get 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 the list of cities.

    Example

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

    Query the list of conditions

    API description

    Get the list of conditions, for example, temperature, humidity, weather, PM2.5, sunrise, and sunset. 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 unit of wind speed.
    callback The callback.

    Example

            ThingHomeSdk.getSceneServiceInstance().conditionService().getConditionAll(
                homeId, // 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 DP ID or condition type (such as 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 device ID, geofence ID, or condition type (such as temp, humidity, condition, pm25, aqi, windSpeed, and sunsetrise).
    entityType int The condition type.
    entityName String The condition name.
    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 city name.
    delayTime String The preset value of the custom duration condition for infrared devices.
    percent Map<String,String> The DP that acts as a condition and its value that ranges from 0% to 100%.
    percent1 Map<String,String> The DP that acts as a condition and its value that ranges from 1% to 100%.
    members String The members of the smart lock that is specified as a condition.
    timeWindow long The set value of the custom duration condition for infrared devices.
    calType String The type of the custom duration condition for infrared devices.
    maxSeconds long The maximum value of the custom duration condition for infrared devices.
    center Map<String,Double> The central coordinates of the geofence.
    radius int The radius of the geofence.
    geotitle String The name of the 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).

    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 more.
    type String Type
    scale int The number of decimal places.

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

    • Value
    • Enum
    • Boolean
    • Types for scheduled tasks, corresponding to the value, enum, and Boolean types in conditions.

    Different API methods are provided for each Property type.

    Scene device management

    Query the list of DPs for device conditions

    API description

    To set a scene condition, after a device is selected, the list of DPs for the selected deviceId must be obtained. 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 the list of conditions.

    Example

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

    Query the list of device conditions

    API description

    Get the list of devices that support device conditions.

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

    Parameters

    Parameter Description
    relationId The home ID.
    callback The callback.

    Example

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

    Query the list of condition device IDs

    API description

    Get the list of device IDs that support device conditions.

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

    Parameters

    Parameter Description
    relationId The home ID.
    callback The callback.

    Example

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

    Query the list of DPs for action device

    API description

    To set a scene action, after a device is selected, the list of DPs for the selected deviceId must be obtained. 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 the device DP.
    productId String The product ID (PID) of the device.
    functionName String The name of the device DP.
    dataPoints List The list of the device DPs.

    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 the light DP.
    dpProperty String The type of the 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

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

    Query the list of DPs for action device group

    API description

    To set a scene action, after a device is selected, the list of DPs for the selected deviceId must be obtained. 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 the list of DPs for action device.

    Example

            ThingHomeSdk.getSceneServiceInstance().deviceService().getActionGroupDeviceDpAll(
                groupDeviceId, // Device or group ID
                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 the list of action devices

    API description

    Get the list of devices that can act as a scene action. Users 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

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

    Query the list of action device IDs

    API description

    Get the list of device IDs that can act as a scene action.

    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 The list of group device IDs.
    exts Map<String, Map<String, String>> The additional information.

    Example

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

    Scene management

    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 getSimpleSceneAll 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()
    
            ThingHomeSdk.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 the lightweight list of scenes

    API description

    Get the 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

            ThingHomeSdk.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 scene name.
    conditions List The list of scene conditions.
    displayColor String The background color of the scene.
    actions List The list of actions.
    enabled boolean Indicates whether an automation scene is enabled.
    stickyOnTop boolean Indicates whether the scene is displayed on the homepage.
    newLocalScene boolean Indicates whether the tap-to-run scene is managed by the same gateway. This field has been deprecated.
    gwId String The ID of the central gateway that manages the scene.
    localLinkage boolean Indicates whether the automation is managed by the same gateway.
    linkageType int The scene type:
    • 0: Cloud
    • 1: Local (single gateway)
    • 2: LAN
    arrowIconUrl String The arrow icon of the scene.
    preConditions List The active period of the scene.
    outOfWork int The state of a scene. Valid values:
    • 0: Success
    • 1: Unavailable
    • 2: Anomaly
    ruleGenre int The scene type:
    • 1: Tap-to-run
    • 2: Automation

    Fields of PreCondition

    Field Type Description
    id String The condition ID.
    condType String The condition type, fixed as timeCheck.
    expr PreConditionExpr The details of the active period.

    Fields of PreConditionExpr

    Field Type Description
    loops String The recurrence frequency, for example, 1111111 for daily, 1000001 for weekends, and 0111110 for Monday to Friday.
    start String The custom start time. Example: 00:00.
    end String The custom end time. Example: 23:59.
    timeInterval String The active period.
    • custom: Custom
    • daytime: Daytime
    • night: Night
    • allDay: All day
    cityId String The city ID.
    timeZoneId String The time zone ID.
    cityName String The city name.

    Query scene details by IDs (including execution method)

    API description

    fun getSceneDetailV1(relationId: Long, sceneId: String, ruleGenre: Int? = null, homeModel: Boolean = false, callback: IResultCallback<NormalScene?>?)
    
    

    Parameters

    Parameter Description
    relationId The home ID.
    sceneId The scene ID.
    ruleGenre (Optional) The rule type. The default is null if not specified.
    homeModel (Optional) Whether the smart mode is used. The default is false if not specified.
    callback The callback.

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

    Example

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

    Query scene details by IDs

    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 the lightweight list of smart scenes.

    Example

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

    Add a 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 active period is optional and can be included in the preconditions. If it is not defined, the scene is active 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 scene data.
    callback The callback.

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

    Example

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

    Modify a scene

    API description

    Modify a scene. The updated scene data is returned on success.

    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 updated scene data.
    callback The callback.

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

    Example

            sceneBean.setName("New name") // Change scene name
    
            sceneBean.setConditions(Collections.singletonList(condition)) // Change scene condition
    
            sceneBean.setActions(tasks) // Change scene action
    
            val sceneId: String = sceneBean.getId() // Get the scene ID to initialize
    
            ThingHomeSdk.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

            ThingHomeSdk.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()
    
            ThingHomeSdk.getSceneServiceInstance().baseService().enableAutomation(
                sceneId,
                object : IResultCallback() {
                    override fun onSuccess() {
                        Log.d(TAG, "enable Scene Success")
                    }
    
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    
            ThingHomeSdk.getSceneServiceInstance().baseService().disableAutomation(
                sceneId,
                object : IResultCallback() {
                    override fun onSuccess() {
                        Log.d(TAG, "disable Scene Success")
                    }
    
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Schedule an automation scene

    API description

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

    Parameters

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

    Example

            val sceneId: String = sceneBean.getId()
    
            ThingHomeSdk.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 scene

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

    API description

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

    Parameters

    Parameter Description
    sceneData The scene data.
    callback The callback.

    Example

            val sceneId: String = sceneBean.getId()
            ThingHomeSdk.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

    Monitor 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 {
        /**
         * Disable automation
         */
        fun onDisableScene(sceneId: String)
    
        /**
         * Enable automation
         */
        fun onEnableScene(sceneId: String)
    
        /**
         * Remove a scene
         */
        fun onDeleteScene(sceneId: String)
    
        /**
         * Create a scene
         */
        fun onAddScene(sceneId: String)
    
        /**
         * Update a scene
         */
        fun onUpdateScene(sceneId: String)
    }
    

    Example

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

    Remove a listener for scene information changes when no longer needed.

    fun unRegisterDeviceMqttListener()
    

    Example

    ThingHomeSdk.getSceneServiceInstance().executeService().unRegisterDeviceMqttListener()
    

    Scene logs

    Check for new scene execution logs

    API description

    Check for new scene execution logs on the scene list or other main pages.

    fun hasNewlyGeneratedSceneLog(
            relationId: Long,
            callback: IResultCallback<Boolean>?
        )
    

    Parameters

    Parameter Description
    relationId The home ID.
    callback The callback.

    Example

            ThingHomeSdk.getSceneServiceInstance().logService().hasNewlyGeneratedSceneLog(
                homeId,
                object : IResultCallback<Boolean>() {
                    override fun onSuccess(result: Boolean) {
    
                    }
                    override fun onError(errorCode: String?, errorMessage: String?) {
    
                    }
                })
    

    Query scene execution logs (including local execution)

    API description

    Get the list of logs on the log page.

    fun getSceneLogInfoAll(
            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 entry.
    endTime The end time of the log entry.
    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 scene name.
    uid String The user ID.
    execResult int 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 the scene is executed.
    sceneType int The scene type.
    execMessage String The information about the execution.

    Example

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

    Query scene execution logs

    API description

    Get the 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 entry.
    endTime The end time of the log entry.
    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 ExecuteLogList and ExecuteLogItem properties, see Query scene execution logs (including local execution).

    Example

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

    Get 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 entry.
    endTime The end time of the log entry.
    returnType The log type.
    • 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 action.
    actionEntityName String The name of the device that runs the action.
    executeTime String The time when the scene is executed.
    errorCode String The error code.
    execStatus int The execution status.
    errorMsg String The error message.
    actionEntityUrl String The icon of the device that runs the action.
    actionExecutor String The DP of the device that runs the action.
    detail List The log details.

    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.
    code String The error code.
    msg String The error message.
    icon String The icon.

    Example

            ThingHomeSdk.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 the list of device logs

    API description

    The app panel uses this method to retrieve the list of device logs.

    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 entry.
    endTime The end time of the log entry.
    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 scene execution logs.

    Example

            ThingHomeSdk.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?) {
    
                    }
                })
    

    Examples

    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
    Schedule
    • entityId: Set to the string timer.
    • entitySubIds: Set to the string timer.
    • entityType: Set to 6.
    • expr: Contain a map at the inner layer. Example: {timeZoneId = "Asia/Shanghai",loops = "0000000",time = "08:00",date = "20180308"}.
    Weather changes
    • entityId: The city ID.
    • entitySubIds: Enumeration of weather types, such as humidity.
    • entityType: Set to 3.
    • expr: Contain a list at the inner layer. Example: ["$humidity", "==", "comfort"]
    Device
    • entityId: The device ID.
    • entitySubIds: The DP ID.
    • entityType: Set to 1.
    • expr: Contain a list at the inner layer. Example: ["$dp1", "==", true]

    Assemble scene condition object 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 expr for weather conditions:

      • Temperature: [["$temp","<",15]]
      • Humidity: [["$humidity","==","comfort"]]
      • Weather: [["$condition","==","snowy"]]
      • PM2.5: [["$pm25","==","fine"]]
      • Air quality: [["$aqi","==","fine"]]
      • Sunrise and sunset: [["$sunsetrise","==","sunrise"]]
    • Examples of expr for schedule conditions:

      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 the day of the week, Sunday through Saturday. 1 indicates the schedule is on, while 0 indicates the schedule is off. expr is an array, so the map for schedule conditions must also be enclosed in an array.

    • Examples of expr for device conditions:

      A device condition is specified with an array to represent a specific condition value. The concatenated expr for the selected condition can be [[“$dp1”,“==”,true]], indicating the light is turned on. In this expression, dp1 is DP+DP ID.

    Set a scene action

    The scene action class is SceneAction. It includes three important properties: entityId, actionExecutor, and executorProperty. These three properties describe the object, type, and specific content of an action.

    Action type Description
    Device
    • entityId: The devId of the device.
    • actionExecutor: The dpIssue.
    • executorProperty: 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 the method of getting the list of DPs for device tasks to get the DP ID and its valid values.
    Group
    • entityId: The groupId of the group.
    • actionExecutor: The deviceGroupDpIssue.
    • Other properties are the same as those of device actions.
    Trigger
    • entityId: The sceneId of the scene.
    • actionExecutor: The ruleTrigger.
    • executorProperty: Not required.
    Enable automation
    • entityId: The sceneId of the automation.
    • actionExecutor: The ruleEnable.
    • executorProperty: Not required.
    Disable automation
    • entityId: The sceneId of the automation.
    • actionExecutor: The ruleDisable.
    • executorProperty: Not required.
    Delay action
    • entityId: Set to delay.
    • actionExecutor: Set to 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 scene: The condition device performs actions at the set time.
    */
    
    var deviceId: String // Device ID
    var dpId: Int // DP ID
    
    val normalScene = NormalScene().apply {
        conditions = listOf(SceneCondition().apply {
            entityId = "timer"
            entitySubIds = "timer"
            entityType = 6
            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)
        })
    }