Smart Scenes

Last Updated on : 2022-03-03 06:47:15

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

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

Background information

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

Class name Description
TuyaSmartScene Adds, edits, runs, or deletes a single scene. The scene ID is required for initialization. It is the sceneId field of TuyaSmartSceneModel and can be obtained from the returned list of smart scenes.
TuyaSmartSceneManager Provides data of conditions, tasks, devices, and cities for smart scenes, and returns a list of smart scenes.
TuyaSmartScenePreConditionFactory The utility class that provides methods to quickly create conditions for automation scenes.
TuyaSmartSceneConditionFactory The utility class that provides methods to quickly create conditions for smart scenes.
TuyaSmartSceneActionFactory The utility class that provides methods to quickly create actions for smart scenes.
TuyaSmartSceneConditionExprBuilder The utility class that provides methods to quickly create conditional expressions for smart scenes.

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

Scene conditions

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

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

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 smart scene. The TuyaSmartSceneActionModel 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 Example.

Smart scene management

Get a list of scenes

API description

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

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

Parameters

Parameter Description
homeId The site ID.
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

// Returns a list of smart scenes created for a site.
- (void)getSmartSceneList {
    [[TuyaSmartSceneManager sharedInstance] getSceneListWithHomeId:homeId success:^(NSArray<TuyaSmartSceneModel *> *list) {
        NSLog(@"get scene list success %@:", list);
    } failure:^(NSError *error) {
        NSLog(@"get scene list failure: %@", error);
    }];
}

Swift:

// Returns a list of smart scenes created for a site.
func getSmartSceneList() {
    TuyaSmartSceneManager.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)")
        }
    })
}

Get a lightweight list of smart scenes

API description

Returns a lightweight 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 API method is a lightweight version of getSceneListWithHomeId.

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

Parameters

Parameter Description
homeId The site ID.
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

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

Swift:

func getSimpleSceneList(homeId: Int64) {
   TuyaSmartSceneManager.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)")
        }
   })
}

Get a list of conditions

API description

Returns a list of conditions. For example, temperature, humidity, weather, PM2.5, sunrise, and sunset can be returned as the conditions.

  • Devices can also be used as conditions.
  • Temperature can be displayed in Celsius (°C) or Fahrenheit (°F). You must specify the required unit for temperature.
- (void)getConditionListWithFahrenheit:(BOOL)fahrenheit
        success:(void(^)(NSArray<TuyaSmartSceneDPModel *> *list))success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
fahrenheit Specifies whether to display temperature in °F. Valid values:
  • YES: yes.
  • NO: Temperature is displayed in °C.
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

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

Swift:

func getConditionList() {
    TuyaSmartSceneManager.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)")
        }
    })
}

Get a list of devices to run tasks

API description

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

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

Parameters

Parameter Description
homeId The site ID.
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

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

Swift:

func getActionDeviceList() {
    TuyaSmartSceneManager.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)")
        }
    })
}

Get a list of devices for conditions

API description

Returns a 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<TuyaSmartDeviceModel *> *list))success
        failure:(TYFailureError)failure;

Parameters

Parameter Description
homeId The site ID.
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

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

Swift:

func getConditionDeviceList() {
    TuyaSmartSceneManager.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)")
        }
    })
}

Get a list of DPs for device tasks

API description

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

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

Parameters

Parameter Description
devId The device ID.
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

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

Swift:

func getActionDeviceDPList() {
    TuyaSmartSceneManager.sharedInstance()?.getActionDeviceDPList(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)")
        }
    })
}

Get a list of DPs for device conditions

API description

Returns a list of DPs that are supported by the device specified by deviceId. You can select a DP from the response and specify it as the condition that triggers a smart scene.


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

Parameters

Parameter Description
devId The device ID.
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

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

Swift:

func getCondicationDeviceDPList() {
    TuyaSmartSceneManager.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)")
        }
    })
}

Get a list of cities

API description

Returns a list of cities by country code when users set weather conditions for a smart scene. (Note: The list of cities in certain countries outside China might be incomplete. We recommend that the app users outside China get the list of cities by latitude and longitude.) countryCode is set to a value from isoCountryCode. For example, cn specifies China.

- (void)getCityListWithCountryCode:(NSString *)countryCode
        success:(void(^)(NSArray<TuyaSmartCityModel *> *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. An error message is returned.

Example

ObjC:

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

Swift:

func getCityList() {
    TuyaSmartSceneManager.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)")
        }
    })
}

Get city information by longitude and latitude

API description

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

Parameters

Parameter Description
latitude The latitude of the device.
longitude The longitude of the device.
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

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

Swift:

func getCityInfo() {
    TuyaSmartSceneManager.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)")
        }
    })
}

Get city information by city ID

API description

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

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

Parameters

Parameter Description
cityId The city ID.
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

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

Swift:

func getCityInfo() {
    TuyaSmartSceneManager.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)")
        }
    })
}

Sort smart scenes

API description

Sorts the existing smart scenes.

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

Parameters

Parameter Description
homeId The site ID.
sceneIdList The list of sorted smart scenes.
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

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

Swift:

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

Get a list of scene background images

API description

Returns a 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. An error message is returned.

Example

ObjC:

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

    } failure:^(NSError *error) {

    }];
}

Swift:

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

    }, failure: { (error) in

    })
}

Scene operations

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

Add a smart scene

API description

To add a smart scene, users must set the site ID, scene name, and URL of the background image, and specify whether to show the scene on the homepage. Users must also define the list of conditions, tasks, and preconditions. At least one task must be specified. The effective period 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<TuyaSmartScenePreConditionModel*> *)preConditionList
            conditionList:(NSArray<TuyaSmartSceneConditionModel*> *)conditionList
                actionList:(NSArray<TuyaSmartSceneActionModel*> *)actionList
                matchType:(TuyaSmartConditionMatchType)matchType
                    success:(void (^)(TuyaSmartSceneModel *sceneModel))success
                    failure:(TYFailureError)failure;

Parameters

Parameter Description
name The name of the smart scene.
homeId The site ID.
background The URL of the background image. Call getDefaultSceneCover to get the background image.
showFirstPage Specifies whether the scene is displayed on the homepage.
preConditionList The effective period. It is specified as an array of preconditions.
conditionList The array of conditions.
actionList The array of actions.
matchType The matching type for the conditions. For example, any or all conditions can be matched.
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

- (void)addSmartScene {

    [TuyaSmartScene addNewSceneWithName:@"your_scene_name" homeId:homeId background:@"background_url" showFirstPage:YES conditionList:(NSArray<TuyaSmartSceneConditionModel *> *) actionList:(NSArray<TuyaSmartSceneActionModel *> *) matchType:TuyaSmartConditionMatchAny success:^(TuyaSmartSceneModel *sceneModel) {
        NSLog(@"add scene success %@:", sceneModel);
    } failure:^(NSError *error) {
        NSLog(@"add scene failure: %@", error);
    }];
}

Swift:

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

Edit 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 effective 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<TuyaSmartScenePreConditionModel*> *)preConditionList
            conditionList:(NSArray<TuyaSmartSceneConditionModel*> *)conditionList
                actionList:(NSArray<TuyaSmartSceneActionModel*> *)actionList
                matchType:(TuyaSmartConditionMatchType)matchType
                    success:(TYSuccessHandler)success
                    failure:(TYFailureError)failure;

Parameters

Parameter Description
name The name of the smart scene.
background The URL of the background image. Call getDefaultSceneCover to get the background image.
showFirstPage Specifies whether the scene is displayed on the homepage.
preConditionList The effective period. It is specified as an array of preconditions.
conditionList The array of conditions.
actionList The array of actions.
matchType The matching type for the conditions. For example, any or all conditions can be matched.
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

- (void)modifySmartScene {
//    self.smartScene = [TuyaSmartScene sceneWithSceneId:@"your_scene_id"];
    [self.smartScene modifySceneWithName:name background:@"background_url" showFirstPage:YES condition:(NSArray<TuyaSmartSceneConditionModel *> *) actionList:(NSArray<TuyaSmartSceneActionModel *> *) matchType:TuyaSmartConditionMatchAny 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: [TuyaSmartSceneConditionModel]!, actionList: [TuyaSmartSceneActionModel]!, matchType: TuyaSmartConditionMatchAny, success: {
        print("modify scene success")
    }, failure: { (error) in
        if let e = error {
            print("modify scene failure: \(e)")
        }
    })
}

Delete a smart scene

API description

Deletes a smart scene.

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

Parameters

Parameter Description
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

- (void)deleteSmartScene {
//    self.smartScene = [TuyaSmartScene sceneWithSceneId:@"your_scene_id"];
    [self.smartScene deleteSceneWithSuccess:^{
        NSLog(@"delete scene success");
    } failure:^(NSError *error) {
        NSLog(@"delete scene failure: %@", error);
    }];
}

Swift:

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

Run a smart scene

API description

Runs a smart scene.

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. An error message is returned.

Example

ObjC:

- (void)executeSmartScene {
//    self.smartScene = [TuyaSmartScene 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

Enables an automation scene.

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

Parameters

Parameter Description
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

- (void)enableSmartScene {
//    self.smartScene = [TuyaSmartScene 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

Only automation scenes can be enabled or disabled.

API description

Disables an automation scene that will no longer automatically run.

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

Parameters

Parameter Description
success The success callback.
failure The failure callback. An error message is returned.

Example

ObjC:

- (void)disableSmartScene {
//    self.smartScene = [TuyaSmartScene 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

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

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

Parameters

Parameter Description
TuyaSmartSceneManager The scene data management class that can be used to return the list of smart scenes.
state The string that indicates status changes. Example: update and disable.
sceneId The scene ID.

Example

ObjC:

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

Swift:

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

Create smart scenes

The utility class set TuyaSmartSceneDataFactory is added to the SDK version 3.14.0 and later. It can accelerate the settings of scene conditions, actions, and effective period for a smart scene.

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, TuyaSmartSceneDataFactory is recommended to set scene conditions and actions.

Create a scene condition object

The scene condition object is TuyaSmartSceneConditionModel.

  • 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 a list of the TuyaSmartSceneDPModel objects for all weather conditions. Weather conditions can vary depending on entityName and entityId of each TuyaSmartSceneDPModel object. From the returned city information, you can get an object of TuyaSmartCityModel 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 TuyaSmartSceneDPModel or your specified object. You can initialize a condition object of TuyaSmartSceneConditionModel with an object of TuyaSmartSceneDPModel. In the following example, TuyaSmartSceneConditionModel is used to add a class method:

// Adds an initialization method.
- (instancetype)initWithSmartSceneDPModel:(TuyaSmartSceneDPModel *)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 scheduled task.
            NSString *value = dpModel.valueRangeJson[dpModel.selectedRow][0];
            self.extraInfo = @{@"delayTime" : value};
        } else {
            // The device condition.
            self.entityId = dpModel.devId;
            TuyaSmartDevice *device = [TuyaSmartDevice deviceWithDeviceId:dpModel.devId];
            self.entityName = device.deviceModel.name;
            self.entitySubIds = [NSString stringWithFormat:@"%ld", (long)dpModel.dpId];
        }
        // The following section shows the `expr` array of combined elements.
        self.expr = dpModel.expr;
    }
    return self;
}

Combine scene condition objects using expr

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

The outermost layer of the expr expression 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.

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

  • Examples of weather conditions specified by expr:

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

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

  • Examples of device conditions specified by expr:

    A device condition is specified with an array to represent a specific condition value. The combined conditions of expr can be expressed as @[@[@"$dp1",@"==",@YES]]. This expression shows the condition in which the light is switched on. dp1 is the name of the DP provided by TuyaSmartSceneDPModel.

Set scene actions

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

  • dpIssue: device
  • deviceGroupDpIssue: device group
  • ruleTrigger: triggered scene
  • ruleEnable: automation scene enabled
  • ruleDisable: automation scene disabled
  • delay: delayed action

After an object of TuyaSmartSceneActionModel is created, set its properties, especially entityId, actionExecutor, and executorProperty. These three properties describe the object, type, and specific content of an action.

Type Property
Devices
  • The entityId property is set to the value of devId.
  • actionExecutor is set to the value of dpIssue.
  • executorProperty is a dictionary. For example, {"1":YES} specifies DP 1 and the action is set to YES. This applies to DPs of Boolean type, such as the light switch status. You can call getActionDeviceDPList to get the ID and possible values of a specific DP.
Groups
  • The entityId property is set to the value of groupId.
  • actionExecutor is set to the value of deviceGroupDpIssue.
  • Other properties are the same as that of device actions
Trigger a scene
  • The entityId property is set to the value of sceneId for a smart scene.
  • actionExecutor is set to the value of ruleTrigger.
  • executorProperty is not required.
Automation scene enabled
  • The entityId property is set to the value of sceneId for an automation scene.
  • actionExecutor is set to the value of ruleEnable.
  • executorProperty is not required.
Automation scene disabled
  • The entityId property is set to the value of sceneId for an automation scene.
  • actionExecutor is set to the value of ruleDisable.
  • executorProperty is not required.
Delayed action
  • The entityId property is set to the value of delay.
  • actionExecutor is set to the value of delay.
  • executorProperty specifies a delay expressed with a 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.

TuyaSmartSceneDataFactory utility class set

TuyaSmartSceneDataFactory includes the following creation utility classes:

Class name Description
TuyaSmartScenePreConditionFactory Creates the preconditions of automation scenes, such as the effective period.
TuyaSmartSceneConditionFactory Creates the conditions of automation scenes, such as the weather conditions and device conditions.
TuyaSmartSceneActionFactory Creates an action for a smart scene, such as a device action.

The following two auxiliary classes are supported.

Class name Description
TuyaSmartSceneExprModel Stores the expr expressions that represent scene conditions.
TuyaSmartSceneConditionExprBuilder The utility class that generates conditional expressions for automation scenes.

The settings of effective periods, conditions, and actions and the supported types follow the comments in the SDK header files. Note: 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.

Example

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

  1. Use TuyaSmartSceneConditionExprBuilder to create an object of TuyaSmartSceneExprModel and generate the required conditional expression expr.
  2. Call the API method of TuyaSmartSceneConditionFactory, specify the object of TuyaSmartSceneExprModel generated in Step 1, and then set other required parameters to generate the condition object.

API description

// Creates `exprModel`.
+ (TuyaSmartSceneExprModel *)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

// Creates a device condition.
+ (TuyaSmartSceneConditionModel *)createDeviceConditionWithDevice:(TuyaSmartDeviceModel *)device
        dpModel:(TuyaSmartSceneDPModel *)dpModel
        exprModel:(TuyaSmartSceneExprModel *)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 TuyaSmartSceneConditionExprBuilder.

Example

TuyaSmartSceneExprModel *exprModel = [TuyaSmartSceneConditionExprBuilder createBoolExprWithType:dpModel.entitySubId
        isTrue:YES
        exprType:exprType];
TuyaSmartSceneConditionModel *conditionModel = [TuyaSmartSceneConditionFactory createDeviceConditionWithDevice:deviceModel
        dpModel:self.model
        exprModel:exprModel];

TuyaSmartScenePreConditionFactory and TuyaSmartSceneActionFactory provide the API methods to generate preconditions and actions.