Scene Creation

Last Updated on : 2024-08-20 02:42:08download

On top of Create Scene, this topic describes how to create and edit scene data models, including conditions, actions, and effective period.

Preparation

You have completed the Preparation and Integrated BizBundle SDK.

Condition

For more information, see Create Scene Conditions. The builder model varies by scene condition type.

  • Device, sensor, and calculation conditions are created based on device models, DP models, and conditional expression models.
  • The weather conditions and sunrise/sunset depend on the city information model.

Core models

Device model

Get the device model object through ThingSmartDeviceCoreKit in the Home SDK.

Example:

let deviceModel = ThingSmartDevice(deviceId: "Device ID")?.deviceModel

DP model

Get the list of DPs of a device through getCondicationDeviceDPList in ThingSmartSceneManager.

func fetchConditionDeviceDPList() {
    ThingSmartSceneManager.sharedInstance().getCondicationDeviceDPList(withDevId: "Device ID") { sceneDPModels in
        self.dpList = sceneDPModels
        self.tableView.reloadData()
    } failure: { error in
        let errorMessage = error?.localizedDescription ?? ""
        SVProgressHUD.showError(withStatus: errorMessage)
    }
}

Expression model

Generate the conditional expression object based on the type of the selected DP. The data type of the DP can be Boolean, enum, value, string, or raw.

Boolean DP

/// Boolean type
let deviceBoolExpr = ThingSmartSceneConditionExprBuilder.createBoolExpr(withType: dpModel.entitySubId, isTrue: true, exprType: .device)

Value DP

/// Value type
let deviceValueExpr = ThingSmartSceneConditionExprBuilder.createValueExpr(withType: dpModel.entitySubId, operater: "==", chooseValue: 100, exprType: .device)

Enum DP

/// Enum type
let deviceEnumExpr = ThingSmartSceneConditionExprBuilder.createEnumExpr(withType: dpModel.entitySubId, chooseValue: res, exprType: .device)

Raw DP

When the DP type is string or raw, call the following method to generate a conditional expression.

/// Raw type
let deviceRawExpr = ThingSmartSceneConditionExprBuilder.createRawExpr(withType: dpModel.entitySubId, exprType: .device)

City information model

If you obtain the latitude and longitude through location, you can use these coordinates to get the city information model.

ThingSmartSceneManager.sharedInstance().getCityInfo(withLatitude: "", longitude: "") { cityModel in
    print(cityModel)
} failure: { error in
    let errorMessage = error?.localizedDescription ?? ""
}

If users select their city from a list, you can use the city ID to get the city information model.

ThingSmartSceneManager.sharedInstance().getCityInfo(withCityId: "") { cityModel in
    print(cityModel)
} failure: { error in
    let errorMessage = error?.localizedDescription ?? ""
}

Construct conditions

Device condition

Example:

let deviceCondition = ThingSmartSceneConditionFactory.createDeviceCondition(withDevice: deviceModel, dpModel: dpModel, exprModel: deviceExpr) {
    self.conditions?.append(deviceCondition)
    self.tableView.reloadData()
}

Weather condition

Example:

let weatherCondition = ThingSmartSceneConditionFactory.createWhetherCondition(withCity: cityModel, dpModel: weatherDPModel, exprModel: weatherExpr)!

Schedule

Schedule conditions only rely on the schedule expression model. Construct a schedule expression before you can create a schedule condition.

Schedule expression model:

let timeExpr = ThingSmartSceneConditionExprBuilder.createTimerExpr(withTimeZoneId: NSTimeZone.default.identifier, loops: "1111111", date: "20231010", time: "20:30")

Schedule condition model:

let timerCondition = ThingSmartSceneConditionFactory.createTimerCondition(with: timeExpr)

PIR sensor

PIR sensor-specific conditions, derived from device conditions, rely on device models, DP models, and conditional expression models.

Construct the device model and DP model as instructed in the previous sections. This method is used to construct the PIR sensor-specific conditions.

let pirCondition = ThingSmartSceneConditionFactory.createPirCondition(withDevice: deviceModel, dpModel: dpModel, exprModel: enumExpr)

Geofence

Geofence conditions rely on the system services, such as latitude, longitude, and radius of the location.

let geofenceCondition = ThingSmartSceneConditionFactory.createGeoFenceCondition(withGeoType: .reach, geoLati: 30.30288959184809, geoLonti: 120.0640840491766, geoRadius: 100, geoTitle: "XX")

When home members come home

When home members come home rely on the ID and names of the home member associated with the device. The home member ID and name are associated with the selected device.

Example:

let memberGoingHomeCondition = ThingSmartSceneConditionFactory.memberBackHomeCondition(withDevId: "vdevo155919804483178", entitySubIds: "1,2,3,4,5,6,7", memberIds: "id1,id2,id3", memberNames: "name1,name2,name3")

Calculation

To create a calculation condition, the selected DP model must include condCalExtraInfo, with the calType set to duration. maxSeconds in condCalExtraInfo restricts the maximum duration you can set.

The calculation condition also relies on device models, DP models, expression models, and duration. Construct the device model and DP model as instructed in the previous sections.

let calcaulateCondition = ThingSmartSceneConditionFactory.calculateCondition(with: deviceModel, dpModel: dpModel, exprModel: expr, durationTime: 100)

Sunset and sunrise

The sunset and sunrise condition is created based on the city information model and the expression model.

Both the expression model and the condition model rely on the city information model. The city information model is created as instructed in the previous sections.

let sunsetriseExpr = ThingSmartSceneConditionExprBuilder.createSunsetriseTimerExpr(withCity: cityModel, type: .set, deltaMinutes: 30)
let sunsetriseCondition = ThingSmartSceneConditionFactory.createSunsetriseTimerCondition(withCity: cityModel, exprModel: sunsetriseExpr)

Action

For more information, see Create Scene Actions.

Device actions and group actions rely on the feature model ThingSmartSceneCoreFeatureModel. Get the list of devices and groups before requesting the feature model. After users select a specific device or group, open the list of features.

Get the list of devices and groups in the home using getActionGroupListAndDeviceList in ThingSmartSceneManager.

func fetchActionDeviceList() {
    guard let homeID = Home.current?.homeId else {
        SVProgressHUD.showError(withStatus: "HomeID is Empty")
        return
    }
    ThingSmartSceneManager.sharedInstance().getActionGroupListAndDeviceList(withHomeId: homeID) { deviceMap in
        if let groupList = deviceMap?["groupList"] as? [ThingSmartGroupModel] {
            for groupModel in groupList {
                let nodeModel = SceneDeviceNode(groupModel: groupModel)
                self.deviceList?.append(nodeModel)
            }
        }
        if let deviceList = deviceMap?["deviceList"] as? [ThingSmartDeviceModel] {
            for deviceModel in deviceList {
                let nodeModel = SceneDeviceNode(deviceModel: deviceModel)
                self.deviceList?.append(nodeModel)
            }
        }
        self.tableView.reloadData()
    } failure: { error in
        let errorMessage = error?.localizedDescription ?? ""
        SVProgressHUD.showError(withStatus: errorMessage)
    }
}

Get the feature model by device ID using getNewActionDeviceDPList in ThingSmartSceneManager.

func fetchActionDeviceDPList() {
    ThingSmartSceneManager.sharedInstance().getNewActionDeviceDPList(withDevId: "Device ID") { featureModels in
        self.dpList = featureModels
        self.tableView.reloadData()
    } failure: { error in
        let errorMessage = error?.localizedDescription ?? ""
        SVProgressHUD.showError(withStatus: errorMessage)
    }
}

Get the feature model by group ID using getNewActionGroupDPList in ThingSmartSceneManager.

func fetchActionGroupDPList() {
    ThingSmartSceneManager.sharedInstance().getNewActionGroupDPList(withGroupId: "Group ID") { featureModels in
        self.dpList = featureModels
        self.tableView.reloadData()
    } failure: { error in
        let errorMessage = error?.localizedDescription ?? ""
        SVProgressHUD.showError(withStatus: errorMessage)
    }
}

Device action

With the feature model obtained by the device ID, create the device action model based on the selected feature.

func buildDeviceAction() {
    let deviceAction = ThingSmartSceneActionFactory.deviceAction(withFeature: featureModel, devId: deviceModel.devId, deviceName: deviceModel.name)
}

Group action

With the feature model obtained by the group ID, create the group action model based on the selected feature.

func buildGroupAction() {
    let groupAction = ThingSmartSceneActionFactory.groupAction(withFeature: featureModel, groupId: groupModel.groupId, groupName: groupModel.name)
}

Existing scene action

Select an existing Tap-to-Run or automation as the action.

  • To create a Tap-to-Run scene, the Tap-to-Run is not allowed to act as its action.
  • An automation action can only be used to enable or disable the automation, rather than execute it.

Tap-to-Run action

func buildSelectTapToRunAction() {
    let selectTapToRunAction = ThingSmartSceneActionFactory.createTriggerSceneAction(withSceneId: "scene ID", sceneName: "scene name")
}

Automation action

func buildSelectAutomationAction() {
    let automationAction = ThingSmartSceneActionFactory.createSwitchAutoAction(withSceneId: "scene ID", sceneName: "scene name", type: AutoSwitchType(rawValue: 0)!)
}

Delay an action

Specify the hour, minute, and second for delaying an action.

func buildDelayAction() {
    let delayAction = ThingSmartSceneActionFactory.createDelayAction(withHours: "0", minutes: "0", seconds: "60")
}

Notification

Send a notification through the message center, SMS, or phone call. SMS and phone calls are value-added services that can be purchased on the Tuya Developer Platform before they can be used.

Message center

func buildNotificationAction() {
    let notificaitonAction = ThingSmartSceneActionFactory.createSendNotificationAction()
}

SMS message

func buildSendSMSAction() {
    let sendSMSAction = ThingSmartSceneActionFactory.createSmsAction()
}

Phone call

func buildSendCallAction() {
    let sendCallAction = ThingSmartSceneActionFactory.createCallAction()
}

Effective period

Enable users to specify the time range for an automation to be executed. Four types of time ranges are available: all day, daytime, nighttime, and custom.

All four types of time ranges require the city and time zone information. The city information model is created as instructed in the previous sections. Only the custom type can set the start and end times.

The generic method to create an effective period:

func buildPrecondition() {
    let precondParam = TSmartScenePreconditionParam()
    precondParam.sceneID = currentPrecondition?.scenarioId ?? ""
    precondParam.conditionID = currentPrecondition?.conditionId ?? ""
    precondParam.preconditionType = .custom
    precondParam.cityId = "5621253"
    precondParam.cityName = "Hangzhou"
    precondParam.loops = "1111111"
    precondParam.timeZoneId = TimeZone.current.identifier
    precondParam.beginDate = "07:00"
    precondParam.endDate = "20:00"

    let precondition = ThingSmartScenePreConditionFactory.scenePrecondition(with: precondParam)
}