Advanced Rules API Tutorial
We will use the rules API to create a trigger that will evaluate a condition then schedule to evaluate that condition again after a defined period of time. This rule could replace SmartApps like “Notify Me When” that were previously complex groovy apps.
Requirements:
Postman
PAT Token
Getting Started
Open Postman and add your PAT token to the header
Refresher
If you are new to the Rules API, you will need to supply the locationId you want to work with for most requests
GET https://api.smartthings.com/v1/rules?locationId=yourID
Will return a list of your existing rules
Let’s Go
Use Postman in a new tab to GET some device IDs. You will need to get a contact sensor and a light bulb.
Once you have these, we are going to be sending a POST command with the Rule.
We are going to post the following to the Rules endpoint
POST https://api.smartthings.com/v1/rules?locationId=your-location-id
{
"name": "Notify Me When Door Left Open 2",
"actions": [
{
"if": {
"equals": {
"left": {
"device": {
"devices": [
"your-contact-id"
],
"component": "main",
"capability": "contactSensor",
"attribute": "contact"
}
},
"right": {
"string": "open"
}
},
"then": [
{
"sleep": {
"duration": {
"value": {
"integer": 30
},
"unit": "Second"
}
}
},
{
"if": {
"equals": {
"left": {
"device": {
"devices": [
"your-contact-id"
],
"component": "main",
"capability": "contactSensor",
"attribute": "contact"
}
},
"right": {
"string": "open"
}
},
"then": [
{
"command": {
"devices": [
"your-light-id"
],
"commands": [
{
"component": "main",
"capability": "switch",
"command": "on",
"arguments": []
}
]
}
}
]
}
}
]
}
}
]
}
Let’s break down what is happening here.
We are first using a door open event as a trigger, that is the first IF block. If the door opens we will schedule to sleep for 30 seconds.
{
"if": {
"equals": {
"left": {
"device": {
"devices": [
"your-contact-id"
],
"component": "main",
"capability": "contactSensor",
"attribute": "contact"
}
},
"right": {
"string": "open"
}
},
"then": [
{
"sleep": {
"duration": {
"value": {
"integer": 30
},
"unit": "Second"
}
}
},
After 30 Seconds, we will check the door again. If it is open we will turn on a light as a notification that the door has been left open.
{
"if": {
"equals": {
"left": {
"device": {
"devices": [
"your-contact-id"
],
"component": "main",
"capability": "contactSensor",
"attribute": "contact"
}
},
"right": {
"string": "open"
}
},
"then": [
{
"command": {
"devices": [
"your-light-id"
],
"commands": [
{
"component": "main",
"capability": "switch",
"command": "on",
"arguments": []
}
]
}
}
]
}
}
]
}
}
]
}
This simple example shows off the power of the rules engine. Soon you will be able to schedule notifications and trigger scenes just like this.