AUDIO

Listen to this page

0:00
Chapters

    scenarios — home automations from device conditions

    A pre-built plugin that turns the home into a set of automations: a scenario watches INPUT data (device states from the device plugins, time of day) and, when its conditions hold, runs an action CASCADE (switch devices, wait between steps, push a message, call any other tool). Scenarios are created and run by voice and edited in the dashboard — the plugin page under #/pui/scenarios.

    Think of the classic two halves of every smart-home app, brought together: a device registry (what exists, what it reports) and an automation engine (WHEN something → DO something). holai already has the devices — this plugin adds the WHEN→DO layer on top of them.

    Scenario model

    {
      "name": "I go out",
      "phrases": ["leaving home"],
      "enabled": true,
      "trigger": { "type": "condition", "provider": "tuya", "device": "hallway sensor",
                   "attribute": "temperature", "op": ">", "value": 30, "forSeconds": 120 },
      "conditions": [ { "window": { "start": "08:00", "end": "23:00" } } ],
      "actions": [
        { "type": "device", "provider": "tuya", "device": "heater outlet", "command": "off" },
        { "type": "notify", "text": "It is hot in the hallway — the heater is off." }
      ],
      "cooldownSeconds": 600
    }
    
    part what
    trigger WHAT starts the scenario — exactly one of: condition (a device reading crosses a threshold: {device, provider, attribute, op, value, forSeconds?}), schedule ({kind:"daily", time:"22:00", weekdays:[1..7]?} or {kind:"interval", minutes:30}), manual (voice phrase or the dashboard's Run button)
    conditions optional guards that must ALL hold when the trigger wants to fire: device comparisons (same shape as a condition trigger) and/or a time window ({window:{start,end}}, overnight windows wrap midnight)
    actions the ordered cascade: {type:"device", …} (control a device), {type:"wait", seconds} (pause between steps, ≤ 300 s), {type:"notify", text} (push to the phones), {type:"tool", plugin, args} (call any other holai tool — media, orbit reminders, …), {type:"scenario", name} (run an existing scenario — chains cap at depth 3 and a scenario cannot run itself, so an accidental A→B→A loop terminates)
    phrases extra spoken aliases for the run-by-voice matching ("I go out", "goodnight" …)
    cooldownSeconds minimum seconds between two fires of the same scenario (default 300) — a flapping sensor must not machine-gun the cascade

    How the engine works

    • A timer tick (default every 20 s, checkSeconds in the plugin settings) evaluates the enabled scenarios in the core process — the same timezone-aware in-process scheduler pattern the orbit plugin uses. No sidecar, no external scheduler.
    • Device readings come from the device plugins: each tick the engine refreshes a snapshot through every configured provider (default: tuya) by calling its tool devices action (the snapshot is cached for a minute, so a quiet home costs one provider call).
    • Condition triggers fire on the TRANSITION: the reading must leave the threshold zone and enter it again before the scenario can fire once more (plus the cooldown). forSeconds requires the condition to hold that long continuously (e.g. "above 30° for 2 minutes") — a sensor blip does not trip the cascade.
    • Schedules fire once per matching minute (daily, with an optional weekday mask) or every N minutes (interval).
    • Actions run in order; a failed step is logged, the cascade continues (one offline device must not block the rest); every fire is recorded on the scenario (lastFiredAt, firedCount, lastError) and pushed as a scenarios.fired event to the phones.

    Providers — where devices come from

    The engine speaks ONE convention to every device plugin: the tool must accept devices (→ data.devices: rows with id, name, status DP map, online) and control ({device, command, value, outlet} — fuzzy-matched names). tuya implements it today; a future device integration only needs the same two actions, then its tool name goes into the provider list on the plugin page (Settings panel) and all of its devices immediately become scenario material.

    The devices tool action shows the live registry — every provider's devices with their attributes — which is also how the assistant learns what can be wired into a scenario.

    Device references survive renames: a scenario binds its devices by id (the name is kept for display), so renaming a device in its provider never blocks editing or firing — the editor shows the current names and the save canonicalizes the stored ones.

    By voice

    Typical phrases (the assistant composes the structured scenario; the tool validates names against the registry and answers with the closest existing devices when a name is off):

    • "Make a scenario: if the hallway temperature is above 30 degrees for two minutes, switch off the heater outlet and tell me about it."
    • "Every day at eleven in the evening turn off all the lights and close the curtains." (a schedule scenario; the assistant lists one device action per light)
    • "Run the scenario I go out." — and the short form works too: "I go out" / "goodnight" run a scenario whose NAME or phrases match the spoken words (exact → prefix → word overlap). If nothing matches, the answer lists the available scenario names, so the follow-up "create it" flows naturally.
    • "Which scenarios are there?", "Enable/Disable the scenario …", "Delete the scenario …".

    A scenario fires from voice even when its trigger is a condition or a schedule — the manual run simply executes the cascade now.

    Dashboard page (#/pui/scenarios)

    • Scenario cards — name, trigger summary, guards, action list, enabled toggle, Run now, last-fired info (time, count, last error), edit and delete.
    • Editor — name + voice aliases; trigger picker (manual / condition / daily / interval) with provider, device and attribute selects fed by the live registry; guard builder (extra conditions + time window); action builder (device step, wait, notify, generic tool call) with drag-free add/remove ordering; cooldown. The editor is registry-constrained: device lists show online devices only (an "include offline devices" checkbox lifts it everywhere), attributes offer exactly the codes the selected device reports, the comparison ops and the value field follow the attribute's type (booleans get =/≠ and an on/off pick, numbers get the full range and a numeric field), and device actions list only controllable devices — a sensor can be watched in a trigger or guard, but cannot be switched. The modal opens with a short guide explaining manual creation, "hold for", cooldown and the seconds convention.
    • Debug (dry run) — the Debug button (on the cards and in the editor) evaluates the scenario against the live registry: whether the trigger condition holds right now (with the device's current reading), which guards hold, and what each action would do — nothing is executed, nothing recorded. The editor has a "dry run" checkbox (on by default); untick it to start the cascade for real (in the background). The editor debug works on the UNSAVED state, so you can test before saving.
    • Settings (admin) — provider tool list (comma-separated) and the check interval.

    The scenarios tool

    POST /api/v1/tools/scenarios (roles user+):

    action args what
    list — the scenarios with their trigger/action summaries and last-fired state
    devices — the live device registry (per provider: devices + attribute codes/values)
    create name, trigger, actions, optional phrases, conditions, cooldownSeconds, enabled create a scenario (validated: unknown device/attribute names return the closest existing ones)
    run name or query run a scenario now (fuzzy-matched over names + phrases)
    enable / disable name toggle a scenario
    delete name remove a scenario

    Routes (plugin page backend)

    Method/Path Role What
    GET /api/v1/plugins/scenarios/scenarios user full scenario list
    POST /api/v1/plugins/scenarios/scenarios admin create/update (body carries id for updates)
    DELETE /api/v1/plugins/scenarios/scenarios?id= admin delete
    POST /api/v1/plugins/scenarios/run user {id} — run now
    POST /api/v1/plugins/scenarios/toggle admin {id, enabled}
    GET /api/v1/plugins/scenarios/registry user device snapshot per provider
    GET /api/v1/plugins/scenarios/settings user providers + check interval
    PUT /api/v1/plugins/scenarios/settings admin {providers: [tool names], checkSeconds}

    Storage and limits

    Everything lives in ctx.sqlStore('scenarios') (the central db — it travels in the backup zip with the rest of the home state); the engine keeps only in-memory runtime state (armed-since markers, running flags), so a restart re-arms condition triggers from scratch — the cooldown bookkeeping (lastFiredAt, lastFiredDay) is persisted and survives. Manual notify actions and the fired-event pushes reuse the core event bus (notify type) — phones receive them like any other home event.

    Testing

    server/tests/scenarios.js runs fully offline against a fake provider tool (node tests/scenarios.js): creation validation, transition + for-duration + cooldown semantics, guards and time windows, ordered action cascades with waits, fuzzy run matching over names and phrases, daily/interval schedules, enable/disable/delete and store persistence across engine restarts.

    Last updated: November 2026