Automations
Automations
An automation is kept and run by the hub: when something happens, if conditions hold, it takes these steps. It runs on the hub, so it works while the hub is offline from the cloud. It can be started from the API, and it can send an event to your app, which delivers any notification itself.
An automation
curl -X PUT https://api.1keyplatform.dev/v1/hubs/1key-xfy2-nmf4-5xwp/automations/lobby-door-left-open \
-H "Authorization: Bearer $ONEKEY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Lobby door left open",
"triggers": [{ "id": "opened", "type": "channel", "device_id": 12, "key": "contact", "to": false }],
"conditions": [{ "type": "time", "after": "22:00", "before": "06:00" }],
"actions": [
{ "type": "wait_for", "trigger": { "type": "channel", "device_id": 12, "key": "contact", "to": true },
"timeout_s": 300, "on_timeout": "continue" },
{ "type": "if", "condition": { "type": "wait", "completed": false },
"then": [{ "type": "emit", "name": "door_left_open", "severity": "warning", "data": { "device_id": 12 } }] }
]
}'
When the lobby door opens at night and is still open five minutes later, the hub writes an automation.emitted event named door_left_open to your event log. Times are the site's local time, and sunrise and sunset are the site's: set the site's time_zone and location. Until the hub has a time zone and a trusted clock, time triggers don't fire and time, day, date and calendar conditions don't hold.
| Field | |
|---|---|
key |
In the path: 1–64 lowercase letters, digits, - and _. Saving the same key again replaces it |
name |
1–100 characters |
enabled |
Default true |
mode |
What a trigger does while a run is under way: single (default) drops it, restart stops the run and starts again, queued waits its turn, parallel runs at once |
max_runs |
1–10: runs queued or under way at once. Default 1, or 10 for queued and parallel |
cooldown_s |
0–86400: least seconds between run starts. Default 0 |
allow_unlock |
Must be true for an automation that unlocks or opens anything, and the API key needs automations:unlock. Default false |
variables |
Named values steps use as {"var": "name"} |
template |
The template it was deployed from, as "<key>@<version>": 1–64 characters |
triggers |
At least one; any of them starts a run |
conditions |
All must hold for a run to go on |
actions |
At least one step, in order |
revision |
Send the one you read to save only if it's unchanged: see revisions |
Every object in an automation is closed: a field not listed for it is refused. The hub adds revision, digest (the SHA-256 of the document in canonical JSON, without revision and digest) and suspended; sent back on a save, digest and suspended are dropped. GET /hubs/{hub_id}/automations lists each in brief: key, name, enabled, suspended, revision, digest, template.
Values
Where a step takes a value, it is a literal, or {"var": "name"}: a variable from variables or one a set_variable step sets, or trigger.<field> from what started the run (trigger.value, trigger.data.reason). A var that names neither is refused.
Triggers
Any trigger may carry an id (1–64 characters), which a trigger condition tests.
type |
Fields | Fires |
|---|---|---|
channel |
device_id, key, endpoint?, to?, from?, above?, below?, for_s? |
When the channel changes to satisfy them; a threshold on crossing it; with for_s (1–86400) once it has held that long |
access |
device_id, result (granted, denied), method? (keypad, rfid, biometric), credential_id? |
When a credential unlocks the lock, or the lock refuses one |
button |
device_id, endpoint?, button?, event? |
On a press; endpoint names the button channel on a device with more than one, button is a number, and event is one of the button channel's events |
device |
device_id, event (unavailable, battery_low) |
When the device drops off or runs low |
time |
at (HH:MM), days?, calendar?, except_calendar?, missed?, grace_s? |
At a local time; calendar limits it to that calendar's dates, except_calendar leaves them out. A time missed while the hub was off is skipped, or with missed: "run_once" run once within grace_s (default 900) |
sun |
event (sunrise, sunset), offset_s? (−14400 to 14400), days?, calendar?, except_calendar?, missed?, grace_s? |
At sunrise or sunset, at the site's location; the rest as for time |
remote |
name |
When POST /hubs/{hub_id}/triggers/{name} fires it |
hub |
event (started, cloud_lost, cloud_restored) |
When the hub starts, or loses or regains the cloud |
days is a list of mon … sun. grace_s is 1–86400, and calendar and except_calendar are calendar keys. A value in to or from is checked against the channel type; above and below need a number channel.
{ "type": "channel", "device_id": 5, "key": "temperature", "above": 28, "for_s": 600 }
{ "type": "access", "device_id": 31, "result": "granted", "method": "rfid" }
{ "type": "button", "device_id": 7, "button": 1, "event": "initial_press" }
{ "type": "device", "device_id": 7, "event": "battery_low" }
{ "type": "time", "at": "07:30", "days": ["mon", "tue", "wed", "thu", "fri"], "except_calendar": "holidays", "missed": "run_once" }
{ "type": "sun", "event": "sunset", "offset_s": -1800 }
{ "type": "remote", "id": "drill", "name": "building.lockdown" }
{ "type": "hub", "event": "cloud_lost" }
Conditions
type |
Fields | Holds when |
|---|---|---|
channel |
device_id, key, endpoint?, is?, not?, above?, below?, in? (a list of values) |
The channel's value is is, isn't not, is above above, below below, and one of in |
time |
after?, before? (HH:MM) |
Local time is in the window; after later than before wraps midnight |
days |
days |
Today is one of them |
date_range |
from, to (MM-DD or YYYY-MM-DD, a real date; 02-29 is one) |
Today is in the range; MM-DD wraps the year |
calendar |
calendar, in? (true or false, default true) |
Today is (or, with in: false, isn't) one of the calendar's dates |
variable |
name, equals?, not_equals?, above?, below? (numbers), in? (a list of values) |
The variable, or trigger.<field>, is equals, isn't not_equals, is above above, below below, and one of in |
trigger |
id |
The run was started by the trigger with that id |
wait |
completed |
The last wait_for heard its trigger (true) or timed out (false) |
all, any |
conditions |
All of them hold, or any |
not |
condition |
It doesn't hold |
{ "type": "channel", "device_id": 31, "key": "lock_state", "in": ["locked", "unlatched"] }
{ "type": "date_range", "from": "12-20", "to": "01-05" }
{ "type": "calendar", "calendar": "holidays", "in": false }
{ "type": "variable", "name": "trigger.data.reason", "in": ["drill", "test"] }
{ "type": "any", "conditions": [{ "type": "days", "days": ["sat", "sun"] }, { "type": "calendar", "calendar": "holidays" }] }
Steps
type |
Fields | Does |
|---|---|---|
set |
device_id, key, endpoint?, value, transition? (0–7620 seconds), relock_after_s? (1–3600) |
Sets a channel, as a command does. The value is checked against the channel type |
set_many |
commands: each a set without type |
Each in order |
delay |
seconds (more than 0, up to 86400) |
Waits; a delay survives the hub restarting |
wait_for |
trigger, timeout_s (up to 86400), on_timeout? (continue, default, or stop) |
Waits for a trigger, as any trigger is written |
if |
condition, then, else? |
Takes then if the condition holds, else else |
choose |
options: each {condition, actions}, default? |
Takes the first option whose condition holds, else default |
parallel |
branches: lists of steps |
Starts each branch on its own and goes on |
emit |
name, severity? (info, default, warning, critical), data? |
Writes automation.emitted to your event log; values in data may be vars |
set_variable |
name, value |
Sets a variable for the rest of the run |
run |
key |
Runs another automation, its chain continued |
credential |
action (suspend, resume), credential_id |
Suspends or resumes the credential's lock user: its credentials are cleared from the lock, or written back |
stop |
reason? (up to 200 characters) |
Ends the run |
{ "type": "set", "device_id": 9, "key": "level", "value": { "var": "trigger.data.level" }, "transition": 2 }
{ "type": "set_many", "commands": [{ "device_id": 9, "key": "level", "value": 0 }, { "device_id": 10, "key": "switch", "value": false }] }
{ "type": "choose", "options": [{ "condition": { "type": "time", "before": "12:00" }, "actions": [{ "type": "emit", "name": "morning" }] }],
"default": [{ "type": "stop", "reason": "afternoon" }] }
{ "type": "parallel", "branches": [[{ "type": "delay", "seconds": 60 }, { "type": "emit", "name": "late" }], [{ "type": "emit", "name": "now" }]] }
{ "type": "credential", "action": "suspend", "credential_id": 12 }
Checking before it runs
The API checks every field strictly and answers 400 naming the first that's wrong (actions[1].then[0].value: must be at most 100 %). The hub then checks the automation against its devices and against every other automation on the hub; an error refuses the save, and warnings are saved and returned in problems. POST /hubs/{hub_id}/automations/validate checks one without saving it.
code |
Severity | |
|---|---|---|
invalid_document |
error | A shape the hub doesn't take; target is the path |
unknown_channel, not_writable, bad_value, unknown_variable |
error | A device, key or value the registry or the device doesn't allow, or a variable never declared |
unlock_not_allowed, untrusted_unlock, unbounded_unlock, late_unlock |
error | An unlock or open without allow_unlock (unlock_not_allowed), from a trigger other than remote or access granted, here or reached through a chain of automations (untrusted_unlock), after any delay or wait_for (late_unlock), or an unlock without relock_after_s (unbounded_unlock); a credential resume without allow_unlock (unlock_not_allowed) |
oscillation |
error | Automations that set each other off, writing a channel with different values |
cycle |
warning | Automations that set each other off, each writing the same value |
conflict |
error on a lock or garage door, else warning | One trigger driving a channel to different values, directly or through a chain |
impossible_conditions |
error | Conditions that can never all hold |
no_hysteresis |
warning | A threshold trigger with no for_s that its own writes feed back into |
When the hub refuses one
{
"error": {
"type": "automation_rejected",
"message": "The hub refused the automation: 1 problem(s).",
"problems": [
{ "code": "oscillation", "severity": "error", "automations": ["hall-on", "hall-off"],
"target": { "device_id": 9, "endpoint": null, "key": "switch" },
"chain": ["hall-on", "hall-off", "hall-on"],
"message": "hall-on turns the hall light on, and hall-off turns it off again." }
]
}
}
422. Each problem is {code, severity, automations, target, chain, message}: the automations involved, the path or the channel, and the chain from the automation that starts it to where it happens.
Revisions
Each save increments revision. Send the revision you read in the document, or 0 for one that must be new, to save only if nobody changed it since: a mismatch is 409 conflict, its message naming the revision the hub holds.
Locks and garage doors
An automation or schedule may unlock a lock or open a garage door, but never quietly: saving one always returns an unlocks warning in problems naming the devices, and it runs under these rules. Locking and closing are always allowed. To let only some people in during set hours, give them credentials with a schedule instead of unlocking the door for everyone.
| Rule |
|---|
An automation that unlocks or opens (lock to false, barrier to true, anywhere in its steps) needs allow_unlock, and an API key with automations:unlock. A var value on a lock or a garage door counts |
Only remote triggers and access triggers with result: "granted" may lead to an unlock; every trigger of an automation that unlocks must be one |
An unlock or open goes out within 30 seconds of what started the run, so it may not follow a delay or a wait_for on any trigger. A delay or wait_for after it is fine, a step in a branch counts one before the branch, and a step after an if, choose or parallel counts one in any of its branches |
An automation started by run from one with any other trigger, or from one that waits for any other trigger, may not unlock or open. The hub checks this across its automations when one is saved |
An unlock needs relock_after_s (1–3600). The relock is a put-back, written before the unlock goes out: three attempts a minute apart, each confirmed by the lock's report, then device.not_secured. It ends early only when a person changes the lock at the door or the lock acknowledges another command; no attempt is spent while the radio is down, and an unlock that never went out withdraws it. Its cause is the automation's {automation, run_id, chain} |
A credential step that resumes needs allow_unlock and automations:unlock, from any trigger |
An automation with a run step needs automations:unlock when any automation it runs, directly or through others, unlocks or opens, or doesn't exist on the hub. Saving one that unlocks or opens names, in an unlock_runners warning, the automations that already run it |
A schedule that unlocks or opens needs allow_unlock and automations:unlock. A schedule's default for a lock or garage door is always locked or closed |
An unlock or open runs only from a trusted trigger (remote, access granted, or a run from a run that had one), on a trusted clock, within 30 seconds of what started the run however long the run took to reach it; it is never retried and never resumed after a restart. Each one writes automation.unlocked |
| A garage door closes from an automation only while it has failed to close fewer than two times; a person operating it resets that |
Running and testing
| Request | |
|---|---|
POST /hubs/{hub_id}/automations/{key}/runs |
Runs it now, its conditions included: variables. 202 with its run_id. Needs automations:run. A manual run can't unlock: its trigger is manual, which isn't trusted, so its unlocks and opens are refused: untrusted_trigger and a credential resume is refused: manual_run, in it and in any automation it runs |
POST /hubs/{hub_id}/triggers/{name} |
Fires every remote trigger named name: data, which the run sees as trigger.data. 202 with matched keys and runs |
POST /hubs/{hub_id}/automations/{key}/test |
Runs it against live state, sending nothing to devices: delays pass at once and a wait_for times out. trigger, optional, is what the run sees as its trigger, {"type": "test"} without it; an unlock or open is refused: untrusted_trigger unless the trigger is remote or access granted. Answers {trace: {run_id, result, steps}}, each step's result would_send where it would act |
GET /hubs/{hub_id}/automations/{key}/traces |
Its last 20 runs, newest first: run_id, revision, trigger, steps, result, started_at, finished_at. ?run_id= answers one |
POST /hubs/{hub_id}/automations/{key}/enable, …/disable |
Switches it on or off, answering it in brief. Enabling lifts a suspension |
A run's result is completed, conditions_failed, stopped, timeout, crashed, disabled, missed or dropped_after_restart. A step's is sent, refused: <why>, failed: <why> or untrusted_clock. A step is refused for:
refused: |
|
|---|---|
manual_hold |
A person changed the channel at the device in the last ten minutes |
conflict |
Another automation wrote the channel less than five seconds before, with a different value |
rate_limited |
The channel was written 20 times in the last minute |
barrier_close_stopped |
The garage door has failed to close twice |
untrusted_trigger |
An unlock or open in a manual run, or in a run chained from one without a trusted trigger |
too_late |
An unlock or open more than 30 seconds after the run's trigger |
no_relock |
An unlock whose relock could not be written |
manual_run |
A credential resume in a manual run |
Runs and triggers aren't queued for an offline hub: they fail at once with 503 hub_offline.
While it runs
| Guard | |
|---|---|
| Loops | Every command carries the chain of automations that led to it. Deeper than 8, or an automation a third time in one chain, is dropped with automation.loop_blocked; three in ten minutes suspend the automation (automation.suspended, reason: "loop") until it's enabled again |
| A person's change | A channel changed at the device (by hand, keypad, button, card or fingerprint) holds against automations for ten minutes; a lock locking is never held |
| Two automations | One writing a channel another wrote less than five seconds before, with a different value, is refused; on a lock, a conflict ends locked |
| Rates | An automation starts at most 30 runs a minute; automations write one channel at most 20 times a minute |
| After a restart | A waiting run is taken up again, one whose time passed only within five minutes; changes the hub didn't see aren't replayed |
Schedules
A schedule is a state the hub holds on one device through the week: a door's hours, lights, a thermostat's program. In a period its values hold, and out of every period its default. The hub applies each period once, at its start, checking every 30 seconds, so a restart or a missed edge lands where the schedule stands; a person's or an automation's change in the middle of a period stands until the next.
curl -X PUT https://api.1keyplatform.dev/v1/hubs/1key-xfy2-nmf4-5xwp/schedules/gym-door-hours \
-H "Authorization: Bearer $ONEKEY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Gym door hours",
"type": "channel_state",
"device_id": 31,
"allow_unlock": true,
"periods": [
{ "days": ["mon", "tue", "wed", "thu", "fri"], "from": "06:00", "to": "22:00", "values": { "lock": false } },
{ "days": ["sat", "sun"], "from": "08:00", "to": "20:00", "values": { "lock": false } }
],
"default": { "lock": true }
}'
| Field | |
|---|---|
key |
In the path, as an automation's |
name |
1–100 characters |
type |
channel_state sets one channel key, the same in every period and in default; setpoint_program sets a thermostat's heating_setpoint, cooling_setpoint, mode and fan_mode |
device_id, endpoint? |
The device; without endpoint, its one endpoint with each key |
enabled |
true or false; default true |
allow_unlock |
true or false; must be true for a schedule that unlocks or opens |
periods |
At least one {days, from, to, values}, local times; a period whose from is later than its to runs past midnight |
default |
The values out of every period |
Each value is checked against the channel type, and a field not listed is refused. A lock or garage door's default is always locked or closed. A schedule that unlocks a lock or opens a garage door leaves it open to anyone during its periods: it needs allow_unlock: true (400 without it) and automations:unlock (403 insufficient_scope without it), and it is saved with an unlocks warning in problems. A schedule's lock or close is a put-back: three attempts a minute apart for a lock, one confirmed within 90 seconds for a garage door, then device.not_secured. It ends early only when a person changes the device or the device acknowledges another command, and waits while the radio is down. Each value of a period is sent once: a value held off is tried again at the next check, a value already sent isn't, and an unlock or open is never retried. A schedule's commands carry the cause {"source": "schedule", "schedule": key}. On an untrusted clock, or with no site time zone, a schedule falls back to its default; taken up after a restart it applies where it stands, except an unlock, which waits for its period's next start. A person's change at the device holds it off for ten minutes, a lock locking excepted. Needs automations:write. The answer is {schedule, problems}; the hub's refusals come back as 422 automation_rejected with problems. Deleting a schedule leaves the device as it is.
Calendars
PUT /calendars/{key} with {name, dates} keeps a list of dates (YYYY-MM-DD, the site's local dates) for every hub of the organization: a time trigger's calendar and except_calendar, and the calendar condition, name it by its key.
Templates
To run the same automation at many hubs, save it once as a template with parameters, then deploy it with each hub's values.
curl -X PUT https://api.1keyplatform.dev/v1/automation-templates/door-left-open \
-H "Authorization: Bearer $ONEKEY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "Door left open",
"parameters": {
"door": { "type": "device", "description": "The door's contact sensor" },
"limit_s": { "type": "integer", "minimum": 30, "maximum": 3600, "default": 300 }
},
"automation": {
"name": "Door left open",
"triggers": [{ "type": "channel", "device_id": { "param": "door" }, "key": "contact", "to": false }],
"actions": [
{ "type": "delay", "seconds": { "param": "limit_s" } },
{ "type": "emit", "name": "door_left_open", "data": { "device_id": { "param": "door" } } }
]
}
}'
A template's key is 1–56 lowercase letters, digits, - and _. {"param": name} anywhere in the automation is replaced by that parameter's value. Parameter types: device, integer, number (with minimum and maximum), text, boolean, each with an optional default of that type and description. Each save adds a version; versions don't change. A template that can't render is refused when it's saved.
curl -X POST https://api.1keyplatform.dev/v1/automation-templates/door-left-open/deployments \
-H "Authorization: Bearer $ONEKEY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"targets": [
{ "hub_id": "1key-xfy2-nmf4-5xwp", "key": "lobby-door-left-open", "parameters": { "door": 12 } },
{ "hub_id": "1key-k3gt-9bp4-ga4t", "parameters": { "door": 7, "limit_s": 600 } }
]
}'
Every target's automation is rendered and checked before anything is saved: a target whose parameters don't fit, or whose automation doesn't pass, refuses the whole deployment with 400 naming it (targets[1].parameters.limit_s: …). Each is then saved on its hub with template: "door-left-open@2". key defaults to the template's. GET /deployments/{id} reports each target:
status |
|
|---|---|
applied |
Saved on the hub, with its revision |
queued |
The hub is offline; it gets it when it connects |
rejected |
The hub refused it: problems |
failed |
The hub answered an error: problems |
superseded |
Still queued when a later deployment of the same key to the hub replaced it; never sent |
Deploying a template that unlocks or opens needs automations:unlock, as does one whose run steps reach an automation that does; a hub that was offline is checked again when it gets it, and a target refused then is rejected with an unlock_scope problem. A newer version is deployed the same way, replacing the automation under the same key.
Events
automation.created, automation.updated, automation.deleted, automation.suspended, automation.loop_blocked, automation.run_finished, automation.emitted, automation.unlocked, schedule.updated, schedule.deleted, schedule.applied, calendar.updated, calendar.deleted and site.time_zone_set: see the event reference.