Smart Scenes

Last Updated on : 2024-07-18 15:26:50download

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

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.

Class name Description
ThingSmartScene Add, edit, run, or delete a scene. The scene ID is required for initialization. It is the sceneId field of ThingSmartSceneModel and can be obtained from the returned list of smart scenes.
ThingSmartSceneManager Request data on conditions, tasks, devices, and cities for scenes along with the scene list.
ThingSmartScenePreConditionFactory The utility class that provides methods to quickly create conditions for automations.
ThingSmartSceneConditionFactory The utility class that provides methods to quickly create conditions for smart scenes.
ThingSmartSceneActionFactory The utility class that provides methods to quickly create actions for smart scenes.
ThingSmartSceneConditionExprBuilder The utility class that provides methods to quickly create conditional expressions for smart scenes.

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

Scene conditions

The ThingSmartSceneConditionModel class is used to create scene conditions, supporting the following condition types.

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

ThingSmartSceneConditionModel object

Field Type Description
defaultIconUrl String The default icon of the condition.
conditionId String The condition ID.
entityName String The condition name.
entityId String The device ID. This field works for device conditions.
entityType Int The condition type. Example:
  • Tap-to-run: 99
  • Device: 1
  • Weather condition: 3
  • Schedule: 6
  • PIR: 7
  • Geofence: 10
  • When home members come home: 11
  • Security: 12
  • Duration calculation: 13
  • Sunset and sunrise: 16
  • Energy: 28
  • Struct: 30
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
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.
expr Array The expression of the DP condition. Example: [["$temp","<",-40]]
iconUrl String The icon of the condition.
exprDisplay String The name of the subtitle. Example: "Temperature: less than -40°F".
productId String The product ID. This field works for device conditions.
productPic String The product image. This field works for device conditions.
devDelMark Bool 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 Dictionary The extension properties of the condition.

extraInfo properties:

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 Dictionary<String,String> The DP that acts as a condition and its value that ranges from 0% to 100%.
percent1 Dictionary<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 Dictionary<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 ThingSmartSceneActionModel class is used to manage scene tasks. Automation scenes can also be enabled or disabled.

You can create the objects of scene conditions and scene tasks to add a smart scene. For more information, see Examples.

ThingSmartSceneActionModel object

Field Type Description
actionId String The action ID.
entityId String The device ID.
entityName String The name of the device.
actionDisplay String The displayed details of an action.
actionDisplayNew Dictionary The displayed details of an action.
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.
executorProperty Dictionary The execution details of an action.
extraProperty Dictionary The additional information about an action.

Scene management

Query the lightweight list of scenes

API description

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 API method is a lightweight version of Querying the list of scenes.

- (void)getSimpleSceneListWithHomeId:(long long)homeId
        success:(void(^)(NSArray<ThingSmartSceneModel *> *list))success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
homeId The home ID.
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)fetchSimpleSceneListDataWithHomeId:(long long)homeId {
    [[ThingSmartSceneManager sharedInstance] getSimpleSceneListWithHomeId:homeId success:^(NSArray<ThingSmartSceneModel *> *list) {
        NSLog(@"get simple scene list success = %@", list);
    } failure:^(NSError *error) {
        NSLog(@"get simple scene list error = %@", error);
    }];
}

Swift:

func getSimpleSceneList(homeId: Int64) {
   ThingSmartSceneManager.sharedInstance()?.getSimpleSceneList(withHomeId: homeId, success: { (sceneModelList) in
        if let sceneList = sceneModelList {
            print("get simple scene list success: \(sceneList)")
        }
   }, failure: { (error) in
        if let e = error {
            print("get simple scene list error: \(e)")
        }
   })
}

Query the list of scenes

API description

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 method is no longer updated. It is recommended to query the lightweight list of scenes instead.

- (void)getSceneListWithHomeId:(long long)homeId
        success:(void(^)(NSArray<ThingSmartSceneModel *> *list))success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
homeId The home ID.
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

// Query the list of scenes in a home 
- (void)getSmartSceneList {
    [[ThingSmartSceneManager sharedInstance] getSceneListWithHomeId:homeId success:^(NSArray<ThingSmartSceneModel *> *list) {
        NSLog(@"get scene list success %@:", list);
    } failure:^(NSError *error) {
        NSLog(@"get scene list failure: %@", error);
    }];
}

Swift:

// Query the list of scenes in a home
func getSmartSceneList() {
    ThingSmartSceneManager.sharedInstance()?.getSceneList(withHomeId: homeId, success: { (list) in
        print("get scene list success: \(list)")
    }, failure: { (error) in
        if let e = error {
            print("get scene list failure: \(e)")
        }
    })
}

Query scene details

API description

- (void)fetchSceneDetailWithDetailParams:(TSceneDetailParams *)detailParams
                                 success:(ThingSceneGetModelCompletion)success
                                 failure:(ThingFailureError)failure;

Parameters

Parameter Description
detailParams The parameter object for scene details.
success The success callback, returning the ThingSmartSceneModel object.
failure The failure callback, returning an error message.

TSceneDetailParams object

Parameter Description
sceneId The scene ID.
gid The home ID.
supportHome Support for room information
  • If set to YES, the room associated with the scene will be returned.
  • If set to NO, the room associated with the scene will not be returned.
ruleGenre The scene type.
  • 1: Tap-to-run
  • 2: Automation

Fields of ThingSmartSceneModel

Field Type Description
sceneId String The scene ID.
name String The scene name.
enabled Bool Indicates whether an automation scene is enabled.
stickyOnTop Bool Indicates whether the scene is displayed on the homepage.
conditions Array The list of conditions. A collection of ThingSmartSceneConditionModel objects.
statusConditions Array The list of status conditions. A collection of ThingSmartSceneConditionModel objects.
actions Array The list of actions. A collection of ThingSmartSceneActionModel objects.
preConditions Array The active periods for scenes. A collection of ThingSmartScenePreConditionModel objects.
coverIcon String The icon of the tap-to-run scene.
displayColor String The background color of the scene.
matchType ThingSmartConditionMatchType The condition matching type.
  • ThingSmartConditionMatchAny: Meet any of the conditions.
  • ThingSmartConditionMatchAll: Meet all conditions.
subMatchType ThingSmartConditionSubMatchType The status condition matching type.
  • ThingSmartConditionSubMatchAny: Meet any of the conditions.
  • ThingSmartConditionSubMatchAll: Meet all conditions.
boundForPanel Bool Indicates whether to bind the scene with the panel. If this field or boundForWiFiPanel is set to true, the scene will be bound with the panel.
boundForWiFiPanel Bool Indicates whether to bind the scene with the panel. If this field or boundForPanel is set to true, the scene will be bound with the panel.
newLocalScene Bool (Deprecated) Indicates whether the tap-to-run scene is managed by the same gateway.
gwId String The ID of the central gateway that manages the scene.
panelType ThingSmartScenePanelType The device type supported by the panel.
  • ThingSmartScenePanelTypeNonAllDevevice: Zigbee sub-devices only.
  • ThingSmartScenePanelTypeAllDevices: All devices.
localLinkage Bool Indicates whether the automation is managed by the same gateway.
linkageType ThingLocalLinkageType The scene type:
  • ThingLinkageTypeUnknow: Cloud
  • ThingLinkageTypeLocal: Local (single gateway)
  • ThingLinkageTypeLan: LAN
arrowIconUrl String The arrow icon of the scene.
outOfWork ThingSmartSceneWorkingStatus The state of a scene.
  • ThingSmartSceneWorkingStatusFine: Normal
  • ThingSmartSceneWorkingStatusInvalid: Invalid
  • ThingSmartSceneWorkingStatusException: Anomaly
ruleGenre ThingSmartSceneRuleGenre The scene type:
  • ThingSmartSceneRuleGenreManual: Tap-to-run
  • ThingSmartSceneRuleGenreAuto: Automation

Example

Objective-C:

TSceneDetailParams *detailParams = [TSceneDetailParams new];
detailParams.sceneId = @"sceneID";
detailParams.gid = 123456;
detailParams.supportHome = NO;
detailParams.ruleGenre = ThingSmartSceneRuleGenreManual;

[[ThingSmartSceneManager sharedInstance] fetchSceneDetailWithDetailParams:detailParams success:^(ThingSmartSceneModel * _Nonnull scene) {

} failure:^(NSError *error) {

}];

Swift:

let detailParams = TSceneDetailParams.init();
detailParams.sceneId = "sceneID";
detailParams.gid = 123456;
detailParams.supportHome = false;
detailParams.ruleGenre = .manual;

ThingSmartSceneManager.sharedInstance().fetchSceneDetail(with: detailParams) { sceneModel in

} failure: { error in

}

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.
- (void)getConditionListWithFahrenheit:(BOOL)fahrenheit
        success:(void(^)(NSArray<ThingSmartSceneDPModel *> *list))success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
fahrenheit
  • YES: °F is used as the unit.
  • NO: °C is used as the unit.
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)getConditionList {
    [[ThingSmartSceneManager sharedInstance] getConditionListWithFahrenheit:YES success:^(NSArray<ThingSmartSceneDPModel *> *list) {
        NSLog(@"get condition list success:%@", list);
    } failure:^(NSError *error) {
        NSLog(@"get condition list failure: %@", error);
    }];
}

Swift:

func getConditionList() {
    ThingSmartSceneManager.sharedInstance()?.getConditionList(withFahrenheit: true, success: { (list) in
        print("get condition list success: \(list)")
    }, failure: { (error) in
        if let e = error {
            print("get condition list failure: \(e)")
        }
    })
}

Query the list of device tasks

API description

Get the list of devices that run specific tasks when you add the tasks.

- (void)getActionDeviceListWithHomeId:(long long)homeId
        success:(void(^)(NSArray<ThingSmartDeviceModel *> *list))success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
homeId The home ID.
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)getActionDeviceList {
    [[ThingSmartSceneManager sharedInstance] getActionDeviceListWithHomeId:homeId success:^(NSArray<ThingSmartDeviceModel *> *list) {
        NSLog(@"get action device list success:%@", list);
    } failure:^(NSError *error) {
        NSLog(@"get action device list failure: %@", error);
    }];
}

Swift:

func getActionDeviceList() {
    ThingSmartSceneManager.sharedInstance()?.getActionDeviceList(withHomeId: homeId, success: { (list) in
        print("get action device list success: \(list)")
    }, failure: { (error) in
        if let e = error {
            print("get action device list failure: \(e)")
        }
    })
}

Query the list of device conditions

API description

Get the list of devices that can be specified as conditions, in addition to temperature, humidity, weather, and more. You can select a device from the response and specify it as a condition to run as a specific task.

- (void)getConditionDeviceListWithHomeId:(long long)homeId
        success:(void(^)(NSArray<ThingSmartDeviceModel *> *list))success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
homeId The home ID.
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)getConditionDeviceList {
    [[ThingSmartSceneManager sharedInstance] getConditionDeviceListWithHomeId:homeId success:^(NSArray<ThingSmartDeviceModel *> *list) {
        NSLog(@"get condition device list success:%@", list);
    } failure:^(NSError *error) {
        NSLog(@"get condition device list failure: %@", error);
    }];
}

Swift:

func getConditionDeviceList() {
    ThingSmartSceneManager.sharedInstance()?.getConditionDeviceList(withHomeId: homeId, success: { (list) in
        print("get condition device list success: \(list)")
    }, failure: { (error) in
        if let e = error {
            print("get condition device list failure: \(e)")
        }
    })
}

Query the list of DPs for device tasks

API description

Get the list of data points (DPs) that are supported by the specified deviceId. You can select a DP from the response and specify it as the task that the device runs in a smart scene.

- (void)getNewActionDeviceDPListWithDevId:(NSString *)devId
        success:(void(^)(NSArray<ThingSmartSceneCoreFeatureModel *> *list))success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
devId The device ID.
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)getActionDeviceDPList {
    [[ThingSmartSceneManager sharedInstance] getNewActionDeviceDPListWithDevId:@"your_device_id" success:^(NSArray<ThingSmartSceneCoreFeatureModel *> *list) {
        NSLog(@"get action device DP list success:%@", list);
    } failure:^(NSError *error) {
        NSLog(@"get action device DP list failure: %@", error);
    }];
}

Swift:

func getActionDeviceDPList() {
    ThingSmartSceneManager.sharedInstance()?.getNewActionDeviceDPListWithDevId(withDevId: "your_device_id", success: { (list) in
        print("get action device DP list success: \(list)")
    }, failure: { (error) in
        if let e = error {
            print("get action device DP list failure: \(e)")
        }
    })
}

Query the list of DPs for device conditions

API description

To set a scene condition, after a device is selected, request the list of DPs supported by the specified deviceId. Then, the desired DP can be selected as the condition to trigger a scene.


- (void)getCondicationDeviceDPListWithDevId:(NSString *)devId
        success:(void(^)(NSArray<ThingSmartSceneDPModel *> *list))success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
devId The device ID.
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)getCondicationDeviceDPList {
    [[ThingSmartSceneManager sharedInstance] getCondicationDeviceDPList:@"your_device_id" success:^(NSArray<ThingSmartSceneDPModel *> *list) {
        NSLog(@"get condition device DP list success:%@", list);
    } failure:^(NSError *error) {
        NSLog(@"get condition device DP list failure: %@", error);
    }];
}

Swift:

func getCondicationDeviceDPList() {
    ThingSmartSceneManager.sharedInstance()?.getCondicationDeviceDPList(withDevId: "your_device_id", success: { (list) in
        print("get condition device DP list success: \(list)")
    }, failure: { (error) in
        if let e = error {
            print("get condition device DP list failure: \(e)")
        }
    })
}

Sort scenes

API description

Sort the existing scenes.

- (void)sortSceneWithHomeId:(long long)homeId
        sceneIdList:(NSArray<NSString *> *)sceneIdList
        success:(TYSuccessHandler)success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
homeId The home ID.
sceneIdList The array of scene IDs after sorting.
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void) sortScene {
    [[ThingSmartSceneManager sharedInstance] sortSceneWithHomeId:homeId sceneIdList:(NSArray<NSString *> *) success:^{
        NSLog(@"sort scene success");
    } failure:^(NSError *error) {
        NSLog(@"sort scene failure:%@", error);
    }];
}

Swift:

func sortScene() {
    ThingSmartSceneManager.sharedInstance()?.sortScene(withHomeId: homeId, sceneIdList: ["sceneId list"], success: {
        print("sort scene success")
    }, failure: { (error) in
        if let e = error {
            print("sort scene failure: \(e)")
        }
    })
}

Query the list of scene background images

API description

Get the list of URLs for scene background images.

- (void)getSmartSceneBackgroundCoverWithsuccess:(TYSuccessList)success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)getDefaultSceneCover {
    [[ThingSmartSceneManager sharedInstance] getSmartSceneBackgroundCoverWithsuccess:^(NSArray *list) {

    } failure:^(NSError *error) {

    }];
}

Swift:

func getDefaultSceneCover() {
    ThingSmartSceneManager.sharedInstance()?.getSmartSceneBackgroundCover(withsuccess: {(list) in

    }, failure: { (error) in

    })
}

Query city information

Query the list of cities

API description

Get the list of cities by country code when users set weather conditions for a smart scene. countryCode is set to a value from isoCountryCode. For example, cn specifies China.

For users registered in cities outside of mainland China, we recommend that you query city information by latitude and longitude because the returned list may be incomplete.

- (void)getCityListWithCountryCode:(NSString *)countryCode
        success:(void(^)(NSArray<ThingSmartCityModel *> *list))success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
countryCode The country code. It is set to a value from isoCountryCode. For example, cn specifies China.
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)getCityList {
    [[ThingSmartSceneManager sharedInstance] getCityListWithCountryCode:@"your_country_code" success:^(NSArray<ThingSmartCityModel *> *list) {
        NSLog(@"get city list success:%@", list);
    } failure:^(NSError *error) {
           NSLog(@"get city list failure: %@", error);
    }];
}

Swift:

func getCityList() {
    ThingSmartSceneManager.sharedInstance()?.getCityList(withCountryCode: "your_country_code", success: { (list) in
        print("get city list success: \(list)")
    }, failure: { (error) in
        if let e = error {
            print("get city list failure: \(e)")
        }
    })
}

Query city information by longitude and latitude

API description

- (void)getCityInfoWithLatitude:(NSString *)latitude
            longitude:(NSString *)longitude
            success:(void(^)(ThingSmartCityModel *model))success
            failure:(TYFailureError)failure;

Parameters

Parameter Description
latitude The latitude.
longitude The longitude.
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)getCityInfo {
    [[ThingSmartSceneManager sharedInstance] getCityInfoWithLatitude:@"your_location_latitude" longitude:@"your_location_longitude" success:^(ThingSmartCityModel *city) {
        NSLog(@"get city info success:%@", city);
    } failure:^(NSError *error) {
        NSLog(@"get city info failure:%@", error);
    }];
}

Swift:

func getCityInfo() {
    ThingSmartSceneManager.sharedInstance()?.getCityInfo(withLatitude: "your_location_latitude", longitude: "your_location_longitude", success: { (city) in
        print("get city info success: \(city)")
    }, failure: { (error) in
        if let e = error {
            print("get city info failure: \(e)")
        }
    })
}

Query city information by city ID

API description

Get city information by city ID that can be obtained from the returned list of cities.

- (void)getCityInfoWithCityId:(NSString *)cityId
        success:(void(^)(ThingSmartCityModel *model))success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
cityId The city ID.
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void) getCityInfo {
    [[ThingSmartSceneManager sharedInstance] getCityInfoWithCityId:@"your_city_id" success:^(ThingSmartCityModel *city) {
        NSLog(@"get city info success:%@", city);
    } failure:^(NSError *error) {
        NSLog(@"get city info failure:%@", error);
    }];
}

Swift:

func getCityInfo() {
    ThingSmartSceneManager.sharedInstance()?.getCityInfo(withCityId: "your_city_id", success: { (city) in
        print("get city info success: \(city)")
    }, failure: { (error) in
        if let e = error {
            print("get city info failure: \(e)")
        }
    })
}

Scene operations

ThingSmartScene allows users to add, modify, run, or delete a single scene. The scene ID is required for initialization. It is the sceneId field of ThingSmartSceneModel and can be obtained from the returned list of smart scenes.

Add a scene

API description

To add a smart 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 can be included in the preconditions. The smart 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.

+ (void)addNewSceneWithName:(NSString *)name
                    homeId:(long long)homeId
                background:(NSString *)background
            showFirstPage:(BOOL)showFirstPage
        preConditionList:(NSArray<ThingSmartScenePreConditionModel*> *)preConditionList
            conditionList:(NSArray<ThingSmartSceneConditionModel*> *)conditionList
                actionList:(NSArray<ThingSmartSceneActionModel*> *)actionList
                matchType:(ThingSmartConditionMatchType)matchType
                    success:(void (^)(ThingSmartSceneModel *sceneModel))success
                    failure:(TYFailureError)failure;

Parameters

Parameter Description
name The name of the scene.
homeId The home ID.
background The URL of the background image. Query the list of scene background images to get the available background image.
showFirstPage Specifies whether the scene is displayed on the homepage.
preConditionList The active period. It is specified as an array of preconditions.
conditionList The array of conditions.
actionList The array of actions.
matchType The matching logic for conditions can be either and or or.
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)addSmartScene {

    [ThingSmartScene addNewSceneWithName:@"your_scene_name" homeId:homeId background:@"background_url" showFirstPage:YES conditionList:(NSArray<ThingSmartSceneConditionModel *> *) actionList:(NSArray<ThingSmartSceneActionModel *> *) matchType:ThingSmartConditionMatchAny success:^(ThingSmartSceneModel *sceneModel) {
        NSLog(@"add scene success %@:", sceneModel);
    } failure:^(NSError *error) {
        NSLog(@"add scene failure: %@", error);
    }];
}

Swift:

func addSmartScene() {
    ThingSmartScene.addNewScene(withName: "your_scene_name", homeId: homeId, background: "background_url", showFirstPage: true, conditionList: [ThingSmartSceneConditionModel]!, actionList: [ThingSmartSceneActionModel]!, matchType: ThingSmartConditionMatchAny, success: { (sceneModel) in
        print("add scene success :\(sceneModel)")
    }) { (error) in
        if let e = error {
            print("add scene failure: \(e)")
        }
    }
}

Modify a scene

API description

To modify a smart scene, users can set the scene name and URL of the background image. Users can also define the list of conditions, tasks, and preconditions. The active period can be included in the preconditions. The smart scene can also be configured to run when any or all conditions are met.

- (void)modifySceneWithName:(NSString *)name
                background:(NSString *)background
            showFirstPage:(BOOL)showFirstPage
        preConditionList:(NSArray<ThingSmartScenePreConditionModel*> *)preConditionList
            conditionList:(NSArray<ThingSmartSceneConditionModel*> *)conditionList
                actionList:(NSArray<ThingSmartSceneActionModel*> *)actionList
                matchType:(ThingSmartConditionMatchType)matchType
                    success:(TYSuccessHandler)success
                    failure:(TYFailureError)failure;

Parameters

Parameter Description
name The name of the scene.
background The URL of the background image. Query the list of scene background images to get the available background image.
showFirstPage Specifies whether the scene is displayed on the homepage.
preConditionList The active period. It is specified as an array of preconditions.
conditionList The array of conditions.
actionList The array of actions.
matchType The matching logic for conditions can be either and or or.
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)modifySmartScene {
//    self.smartScene = [ThingSmartScene sceneWithSceneId:@"your_scene_id"];
    [self.smartScene modifySceneWithName:name background:@"background_url" showFirstPage:YES condition:(NSArray<ThingSmartSceneConditionModel *> *) actionList:(NSArray<ThingSmartSceneActionModel *> *) matchType:ThingSmartConditionMatchAny success:^{
        NSLog(@"modify scene success");
    } failure:^(NSError *error) {
        NSLog(@"modify scene failure: %@", error);
    }];
}

Swift:

func modifySmartScene() {
    smartScene?.modifyScene(withName: "name", background: "background_url", showFirstPage: true, conditionList: [ThingSmartSceneConditionModel]!, actionList: [ThingSmartSceneActionModel]!, matchType: ThingSmartConditionMatchAny, success: {
        print("modify scene success")
    }, failure: { (error) in
        if let e = error {
            print("modify scene failure: \(e)")
        }
    })
}

Delete a scene

API description

- (void)deleteSceneWithHomeId:(long long)homeId
                      success:(TYSuccessBOOL)success
                      failure:(TYFailureError)failure;

Parameters

Parameter Description
homeId The home ID.
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)deleteSmartScene {
//    self.smartScene = [ThingSmartScene sceneWithSceneId:@"your_scene_id"];
    long long homeId = your home id;
    [self.smartScene deleteSceneWithHomeId:homeId success:^{
        NSLog(@"delete scene success");
    } failure:^(NSError *error) {
        NSLog(@"delete scene failure: %@", error);
    }];
}

Swift:

func deleteSmartScene() {
    var homeId = your home id
    smartScene?.delete(homeId:homeId, success: {
        print("delete scene success")
    }, failure: { (error) in
        if let e = error {
            print("delete scene failure: \(e)")
        }
    })
}

Run a scene

API description

This API method is only used to send commands to the cloud for running smart scenes. To check whether the target device has finished the required tasks, you can follow the instructions in Listen for a delegate and get the DP status changes of the device.

- (void)executeSceneWithSuccess:(TYSuccessHandler)success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)executeSmartScene {
//    self.smartScene = [ThingSmartScene sceneWithSceneId:@"your_scene_id"];
    [self.smartScene executeSceneWithSuccess:^{
           NSLog(@"execute scene success");
    } failure:^(NSError *error) {
        NSLog(@"execute scene failure: %@", error);
    }];
}

Swift:

func executeSmartScene() {
    smartScene?.execute(success: {
        print("execute scene success")
    }, failure: { (error) in
        if let e = error {
            print("execute scene failure: \(e)")
        }
    })
}

Enable an automation scene

Only automation scenes can be enabled or disabled.

API description

- (void)enableSceneWithSuccess:(TYSuccessHandler)success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)enableSmartScene {
//    self.smartScene = [ThingSmartScene sceneWithSceneId:@"your_scene_id"];
    [self.smartScene enableSceneWithSuccess:^{
           NSLog(@"enable scene success");
    } failure:^(NSError *error) {
        NSLog(@"enable scene failure: %@", error);
    }];
}

Swift:

func enableSmartScene() {
    smartScene?.enable(success: {
        print("enable scene success")
    }, failure: { (error) in
        if let e = error {
            print("enable scene failure: \(e)")
        }
    })
}

Disable an automation scene

API description

Disable an automation scene to prevent it from running automatically.

- (void)disableSceneWithSuccess:(TYSuccessHandler)success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
success The success callback.
failure The failure callback, returning an error message.

Example

Objective-C:

- (void)disableSmartScene {
//    self.smartScene = [ThingSmartScene sceneWithSceneId:@"your_scene_id"];
    [self.smartScene disableSceneWithSuccess:^{
           NSLog(@"disable scene success");
    } failure:^(NSError *error) {
        NSLog(@"disable scene failure: %@", error);
    }];
}

Swift:

func disableSmartScene() {
    smartScene?.disableScene(success: {
        print("disable scene success")
    }, failure: { (error) in
        if let e = error {
            print("disable scene failure: \(e)")
        }
    })
}

Listen for changes in scene information

API description

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

- (void)sceneManager:(ThingSmartSceneManager *)manager state:(NSString *)state sceneId:(NSString *)sceneId;

Parameters

Parameter Description
ThingSmartSceneManager The scene data management class that can be used to return the list of smart scenes.
state The type of scene status change. Example:
  • update: Update
  • disable: Disable automation
sceneId The scene ID.

Example

Objective-C:

- (void)sceneManager:(ThingSmartSceneManager *)manager state:(NSString *)state sceneId:(NSString *)sceneId {
    if ([state isEqualToString:@"update"]) {
        NSLog(@"update scene list");
    }
}

Swift:

func sceneManager(_ manager: ThingSmartSceneManager!, state: String!, sceneId: String!) {
    if state == "update" {
        print("reload scene list")
    }
}

Scene logs

Check for new scene execution logs

API description

Check for new scene logs in the current home.

- (void)hasNewLogsWithHomeId:(long long)homeId success:(nullable ThingSuccessBOOL)success failure:(nullable ThingFailureError)failure;

Parameters

Parameter Description
homeId The home ID.
success The success callback, returning YES if new logs are generated, and NO otherwise.
failure The failure callback.

Query the list of scene logs

API description

Get all scene logs, including notifications for successful or failed executions and push messages.

- (void)getSmartSceneLogWithHomeId:(long long)homeId
                         startTime:(long long)startTime
                           endTime:(long long)endTime
                              size:(NSInteger)size
                            lastId:(NSString *)lastId
                    lastRecordTime:(long long)lastRecordTime
                           success:(ThingSceneLogCompletion)success
                           failure:(ThingFailureError)failure;

Parameters

Parameter Description
homeId 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.
success The success callback, returning the ThingSmartSceneLogModel object.
failure The failure callback, returning an error message.

Return parameters

ThingSmartSceneLogModel object

Parameter Description
datas An array of ThingSmartSceneLogData objects.
totalCount The total number of arrays.

ThingSmartSceneLogData object

Field Type Description
eventId String The log ID.
ownerId String The ID of the home to which the group belongs.
ruleId String The scene ID.
ruleName String The scene name.
runMode string The scene execution mode.
  • local: Local execution.
  • cloud: Cloud execution.
sceneType int The scene type.
  • 1: Tap-to-run
  • 2: Automation
uid String The user ID.
execTime long The time when the scene is executed.
detailTime String The information about the execution.
execResult int The execution result.
  • 0: Failure
  • 1: Success
  • 2: Partial success
  • 3: Being executed
execResultMsg String The information about the execution result.
failureCode int The error code.
failureCause String The error message.

Query device-related scene logs

API description

Get the list of scene logs related to devices.

- (void)getSmartSceneLogOfDeviceWithDevId:(NSString *)devId
                                   homeId:(long long)homeId
                                startTime:(long long)startTime
                                  endTime:(long long)endTime
                                     size:(NSInteger)size
                                   lastId:(NSString *)lastId
                           lastRecordTime:(long long)lastRecordTime
                                  success:(ThingSceneLogCompletion)success
                                  failure:(ThingFailureError)failure;

Parameters

Parameter Description
devId The device ID.
homeId 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.
success The success callback, returning the ThingSmartSceneLogModel object.
failure The failure callback, returning an error message.

Query log details

API description

- (void)getSmartSceneLogDetailWithHomeId:(long long)homeId
                                 eventId:(NSString *)eventId
                               startTime:(long long)startTime
                                 endTime:(long long)endTime
                              returnType:(long long)returnType
                                 success:(ThingSceneLogDetailListCompletion)success
                                 failure:(ThingFailureError)failure;

Parameters

Parameter Description
homeId The home ID.
eventId The log ID.
startTime The start time of the log entry.
endTime The end time of the log entry.
returnType
  • 1: Retrieve all logs.
  • 0: Retrieve error logs only.
success The success callback, returning an array of ThingSmartSceneLogDetailModel objects.
failure The failure callback, returning an error message.

Return parameters

ThingSmartSceneLogDetailModel object

Parameter Description
actionEntityId The ID of the entity that performs the specified action, such as the device ID.
actionEntityName The name of the entity that performs the specified action.
actionEntityUrl The icon of the entity that performs the specified action.
actionExecutor The description of the actuator.
actionId The action ID.
errorCode The error code.
errorMsg The error message.
execStatus The execution status.
executeTime The time when the scene is executed.

Examples

  • For the SDK versions earlier than 3.14.0, set the conditions and actions based on the following examples.

  • For the SDK version 3.14.0 and later, ThingSmartSceneDataFactory is recommended to set scene conditions and actions. The utility class set ThingSmartSceneDataFactory is added to the SDK version 3.14.0 and later. It can accelerate the settings of scene conditions, actions, and active periods for a smart scene.

Create a scene condition object

The scene condition object is ThingSmartSceneConditionModel.

  • Weather conditions: temperature, humidity, PM2.5, air quality, sunrise, and sunset. In this example, temperature is used to set a weather condition object.
  • Scene conditions can include scheduled tasks and device conditions.

You can call getConditionList to get the list of the ThingSmartSceneDPModel objects for all weather conditions. Weather conditions can vary depending on entityName and entityId of each ThingSmartSceneDPModel object. From the returned city information, you can get an object of ThingSmartCityModel and use the value of cityId as the location information.

Your settings such as the temperature and city information are saved to an object of ThingSmartSceneDPModel or your specified object. You can initialize a condition object of ThingSmartSceneDPModel with an object of ThingSmartSceneConditionModel. In the following example, ThingSmartSceneConditionModel is used to add a class method:

// Initialization method
- (instancetype)initWithSmartSceneDPModel:(ThingSmartSceneDPModel *)dpModel {

    if (self = [super init]) {
        self.entityType = dpModel.entityType;
        self.iconUrl = dpModel.iconUrl;
        if (dpModel.entityType == 3) {
            // The weather condition.
            self.entityId = dpModel.cityId;
            self.entityName = dpModel.cityName;
            self.entitySubIds = dpModel.entitySubId;
            self.cityName = dpModel.cityName;
            self.cityLatitude = dpModel.cityLatitude;
            self.cityLongitude = dpModel.cityLongitude;
        } else if (dpModel.entityType == 7) {
            // The schedule condition.
            NSString *value = dpModel.valueRangeJson[dpModel.selectedRow][0];
            self.extraInfo = @{@"delayTime" : value};
        } else {
            // The device condition.
            self.entityId = dpModel.devId;
            ThingSmartDevice *device = [ThingSmartDevice deviceWithDeviceId:dpModel.devId];
            self.entityName = device.deviceModel.name;
            self.entitySubIds = [NSString stringWithFormat:@"%ld", (long)dpModel.dpId];
        }
        // The assembly of the expr array is described below.
        self.expr = dpModel.expr;
    }
    return self;
}

Assemble scene condition object expr

The expr property of ThingSmartSceneConditionModel describes an expression of scene conditions. For example, the condition of temperature lower than 15°C can be described with expr.

expr is an array and its outermost layer must be an array. Each object in the array represents a condition. For example, @[@"$temp",@"<",@15] indicates the condition where the temperature is lower than 15°C.

Each weather condition matches an object of ThingSmartSceneConditionModel. Therefore, expr only contains one condition array.

  • Examples of expr for weather conditions:

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

    A schedule condition is specified with a dictionary, for 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 dictionary 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",@"==",@YES]], indicating the light is turned on. dp1 is the name of the DP provided by ThingSmartSceneDPModel.

Set a scene action

The scene action class is ThingSmartSceneActionModel and the actionExecutor property represents the type of scene action. The following types of scene actions are supported:

  • dpIssue: Device
  • deviceGroupDpIssue: Group
  • ruleTrigger: Trigger a scene
  • ruleEnable: Enable automation
  • ruleDisable: Disable automation
  • delay: Delay action

After an object of ThingSmartSceneActionModel is created, set its properties, especially 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 is a dictionary. For example, {"1":YES} specifies an action of setting DP 1 to YES, applying to Boolean DPs, such as the light on/off 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 dictionary. 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.

ThingSmartSceneDataFactory utility class set

ThingSmartSceneDataFactory includes the following creation utility classes:

Class name Description
ThingSmartScenePreConditionFactory Create the preconditions of automation scenes, such as the active period.
ThingSmartSceneConditionFactory Create the conditions of automation scenes, such as the weather conditions and device conditions.
ThingSmartSceneActionFactory Create an action for a smart scene, such as a device action.

The following two auxiliary classes are supported.

Class name Description
ThingSmartSceneExprModel Store the expr for scene conditions.
ThingSmartSceneConditionExprBuilder The utility class that generates conditional expressions for automation scenes.

The settings of active periods, conditions, and actions and the supported types follow the comments in the SDK header files. To meet multilingual requirements, conditions and actions do not include exprDisplay and actionDisplayNew that show the details of conditions and actions. You must combine the condition expression expr with the action parameter executorProperty to generate a conditional expression.

Sample

A device condition of switch type is created in the following example. Perform these steps:

  1. Use ThingSmartSceneConditionExprBuilder to create a ThingSmartSceneExprModel object and generate the required conditional expr.
  2. Call the API method of ThingSmartSceneConditionFactory, specify the object of ThingSmartSceneExprModel generated in Step 1, and then set other required parameters to generate the condition object.

API description

// Create exprModel
+ (ThingSmartSceneExprModel *)createBoolExprWithType:(NSString *)type
        isTrue:(BOOL)isTrue
        exprType:(ExprType)exprType;

Parameters

Parameter Description
type The weather type or device DP ID.
isTrue A Boolean value.
exprType An enum value of the created weather type or device type.

API description

// Create a device condition.
+ (ThingSmartSceneConditionModel *)createDeviceConditionWithDevice:(ThingSmartDeviceModel *)device
        dpModel:(ThingSmartSceneDPModel *)dpModel
        exprModel:(ThingSmartSceneExprModel *)exprModel;

Parameters

Parameter Description
device The device model.
dpModel The value of dpModel to create a device condition. For example, dpModel can be set to enable or disable a device DP.
exprModel The model object created by ThingSmartSceneConditionExprBuilder.

Example

ThingSmartSceneExprModel *exprModel = [ThingSmartSceneConditionExprBuilder createBoolExprWithType:dpModel.entitySubId
        isTrue:YES
        exprType:exprType];
ThingSmartSceneConditionModel *conditionModel = [ThingSmartSceneConditionFactory createDeviceConditionWithDevice:deviceModel
        dpModel:self.model
        exprModel:exprModel];

ThingSmartScenePreConditionFactory and ThingSmartSceneActionFactory provide the API methods to generate preconditions and actions.