Skip to content

REST API

Chieh-Min Wang edited this page Nov 24, 2026 · 10 revisions

REST API

This is the contract between the firmware, the web dashboard (web/), the host tools (tools/aqtool.py, aq) and your home automation. Field names are identical everywhere (REST, MQTT, console status).

Quick curl Examples

All examples below use HOST=http://stuffymeter-a1b2c3.local (replace with your monitor's hostname or IP).

Read live status (public)

curl -s "$HOST/api/status" | jq .

Query history: 1 h, 24 h, or 7 days (public)

# Last hour at 1-minute resolution (60 points, served from RAM)
curl -s "$HOST/api/history?minutes=60&step=1"

# Last 24 hours at 5-minute resolution (288 points, served from RAM)
curl -s "$HOST/api/history?minutes=1440&step=5"

# Last 7 days at 30-minute resolution (336 points, merges 15-min flash rollups + RAM)
curl -s "$HOST/api/history?minutes=10080&step=30"

Read and change settings (admin)

When admin_pass is set, pass -u admin:<password>. Every admin POST must include -H 'Content-Type: application/json' (otherwise the device returns 415).

# List all current settings (secrets are masked)
curl -s -u admin:<password> "$HOST/api/config" | jq .

# Inspect the schema (public: keys, types, ranges, defaults, help text)
curl -s "$HOST/api/config/schema" | jq .

# Change backlight brightness and CO2 alert threshold
curl -s -u admin:<password> -H 'Content-Type: application/json' \
     -d '{"bl_bright": 35, "co2_t3": 1500}' "$HOST/api/config"

Identify, calibrate, and test Telegram

# Blink LED and flash screen for 10 s (public)
curl -s -X POST -H 'Content-Type: application/json' -d '{"seconds": 10}' "$HOST/api/identify"

# Send a test Telegram alert using saved tg_* settings (admin)
curl -s -u admin:<password> -X POST -H 'Content-Type: application/json' -d '{}' "$HOST/api/telegram/test"

# Forced CO2 recalibration after 3+ min in fresh air (admin)
curl -s -u admin:<password> -H 'Content-Type: application/json' -d '{"ppm": 420}' "$HOST/api/calibrate/co2"

Check for updates or upload firmware (admin)

# Check GitHub releases without installing
curl -s -u admin:<password> -H 'Content-Type: application/json' \
     -d '{"install": false}' "$HOST/api/ota/check"

# Upload a board image directly (board 3.2: USB edition, board 4.1: Battery edition)
curl -u admin:<password> -H 'Content-Type: application/octet-stream' \
     --data-binary @stuffy_meter_fw2.0.2_board4.1.bin "$HOST/api/ota"

REST API (port 80)

  • JSON in and out (Content-Type: application/json), UTF-8.
  • Errors: HTTP 4xx/5xx with {"ok": false, "error": "human readable"}.
  • Auth: HTTP Basic, user admin, password = the admin_pass setting. When admin_pass is empty, auth is off (device.auth = false, the dashboard warns). Unauthorized requests get 401 + WWW-Authenticate: Basic.
  • Access levels: public (read-only data), admin (changes, commands, OTA, logs), setup (admin, but open for clients on the setup access point while the Wi-Fi setup portal is active, or while no Wi-Fi is configured yet; never for LAN clients while auth is on).
  • POST /api/wifi may also carry "admin_pass", an optional boolean "telemetry", and optional first-time onboarding strings "lang", "tz", and "device_name" (stored in the same update as the Wi-Fi credentials; 400 and nothing stored if a value is invalid). "admin_pass" is taken only while no admin password is set, or with admin credentials; otherwise the answer is 403, so the open setup portal of a configured monitor cannot change the password.
  • Cross-origin access: GET /api/status and POST /api/identify may be used by web pages of other origins, for example a page that finds the monitors on the LAN. Their responses carry Access-Control-Allow-Origin: * and Access-Control-Allow-Private-Network: true (the Private Network Access opt-in for a public site asking a device on the private network; newer Chrome versions ask the user for Local Network Access permission instead, and the page still needs the CORS header to read the reply), and OPTIONS on these two paths answers the browser's preflight with 204 and Access-Control-Allow-Methods (GET, OPTIONS or POST, OPTIONS), Access-Control-Allow-Headers: Content-Type and Access-Control-Max-Age: 86400. No other path sends these headers, so browsers keep other sites from reading the settings or sending commands, and the auth of the admin and setup endpoints is unchanged. Any page the user opens can therefore read /api/status: it holds no passwords or keys, but it shows the readings, the Wi-Fi name, the IP and MAC addresses, the firmware version and whether an admin password is set.
  • Content type of commands: a POST to an admin or setup endpoint must carry Content-Type: application/json, also without a body (application/octet-stream for the firmware image of POST /api/ota). No type, or one that a web form can send (text/plain, application/x-www-form-urlencoded, multipart/form-data), gets 415 before the password check and before anything changes, so a page on another site cannot change settings with a hidden form even while auth is off. The public POST /api/identify takes any type. With curl, add -H 'Content-Type: application/json'.
Method Path Access Owner Purpose
GET / public aq_web dashboard (gzipped single page app)
GET /manifest.webmanifest, /sw.js, /icon.svg, /apple-touch-icon.png, /icon-192.png, /icon-512.png public aq_web PWA manifest, shell service worker and app icons
GET /api/status public aq_web full status, see below
GET /api/history public aq_web 1-minute history, see below
GET /metrics public aq_web Prometheus text format
GET /api/config admin aq_web all settings (secrets masked)
GET /api/config/schema public aq_web settings schema (type, range, default, help, group)
POST /api/config admin aq_web partial update {"bl_bright": 40}
PUT /api/device-name-glyph admin aq_web raw AQG1 alpha bitmap (application/octet-stream, <= 972 bytes) for displaying device_name on the TFT status bar
DELETE /api/device-name-glyph admin aq_web clear any stored device_name glyph bitmap
GET /api/wifi/scan setup aq_web {"networks":[{"ssid","rssi","channel","secure"}]}, strongest first; 501 without Wi-Fi (QEMU)
POST /api/wifi setup aq_web {"ssid","password"} - store and connect; optional "admin_pass", "lang", "tz", "device_name", "telemetry" (see above)
POST /api/portal admin aq_web {"enable": true} - open/close the setup portal; 501 without Wi-Fi
POST /api/identify public aq_web {"seconds": 10} (1..600, default 10) - blink LED + flash screen
POST /api/reboot admin aq_web reboot after 1 s
POST /api/factory-reset admin aq_web erase settings + history, reboot
POST /api/calibrate/co2 admin aq_web {"ppm": 420} -> {"ok":true,"correction_ppm":-12}
POST /api/calibrate/temperature admin aq_web {"reference_c": 23.4} -> {"ok":true,"temp_offset_c":5.1}
POST /api/sensors/selftest admin aq_web ~11 s -> {"ok":true,"scd41":true,"sgp40":true}
POST /api/sensors/power-cycle admin aq_web power-cycle the sensor rail
POST /api/telegram/test admin aq_telemetry send a test Telegram notification using the saved tg_* settings
DELETE /api/history admin aq_web clear the history
GET /api/logs?cursor=N admin aq_web {"cursor":M,"truncated":false,"text":"..."}; start with cursor=0, up to ~6 KB per call, repeat with M
POST /api/log-level admin aq_web {"tag":"*","level":"debug"}
GET /api/ota public aq_ota slots, versions, OTA state, automatic updates (auto)
POST /api/ota admin aq_ota raw firmware .bin body (application/octet-stream), optional X-OTA-SHA256 header
POST /api/ota/pull admin aq_ota {"url": "...", "sha256": "..."} -> 202, progress in /api/status
POST /api/ota/check admin aq_ota {"install": false} -> {"ok":true,"current","available","update","installing"}; installs only with "install": true (any time of day)
POST /api/ota/confirm admin aq_ota confirm the running image now
POST /api/ota/rollback admin aq_ota reboot into the previous image
GET /api/coredump admin aq_ota last crash dump (raw core dump partition data, application/octet-stream; decode with esp-coredump --core-format raw, see OTA.md), 404 if none
DELETE /api/coredump admin aq_ota erase it
GET /api/sim public aq_web QEMU builds only: simulator overrides and model state, see below
POST /api/sim admin aq_web QEMU builds only: {"co2": 2500, "fault": "scd41", "voc": null, "reset": true}

GET / POST /api/sim (simulated sensors, QEMU builds)

Only in builds with CONFIG_AQ_SENSORS_SIMULATE (the QEMU flavour); 404 on real boards. GET returns the pinned values (null = the room model decides) and the model state:

{"co2": 2500, "temp": null, "rh": null, "voc": null, "occupied": null,
 "fault": "none", "speed": 1, "model": {"occupied": true, "seconds": 734}}

POST applies all keys as one change (a 400 with the reason changes nothing) and answers like GET:

Key Values Effect
co2 400..10000 CO2 in ppm, exact (no noise)
temp -10..50 room temperature in C (reads back exactly with the default temp_offset)
rh 0..100 room humidity in %
voc 1..500 VOC index (after the 46 s warm-up)
occupied true / false people in the room: CO2 rises to ~1900 ppm or decays to ~430 ppm
fault none, scd41, sgp40, both the sensor stops answering and goes through the recovery ladder
speed 1..60 model seconds per real second (faster occupancy cycles and drift)
vbat 0 or 2.0..4.4 board 4.x QEMU builds: battery voltage in volts (0 = no cell, auto = 4.05)
usb on / off board 4.x QEMU builds: USB power present (auto = on)
clock unix seconds, or null the wall clock runs on from that time (to test the nightly update window); null = the real clock again; gone after a restart
reset true clear every override first

null or "auto" hands a value back to the model; CO2 and VOC then continue from the pinned level. Numbers may also be sent as strings. On board 4.x QEMU builds GET also returns vbat and usb (the simulated battery behind the power service, which also simulates the low-battery shutdown: no deep sleep, a restart noted low_battery once usb is on again). GET returns clock (the simulated time, null when the real clock runs).

While the setup portal is active, any other GET that arrives over the setup access point (and the OS captive-portal probes /generate_204, /hotspot-detect.html, /ncsi.txt, /connecttest.txt) is redirected with 302 to http://192.168.4.1/, as is / requested with a foreign Host. Otherwise unknown /api/... URLs get the JSON 404, a wrong method on a known path 405, and other unknown GETs the dashboard (404 for file names such as /favicon.ico).

GET /api/status

{
  "device":   {"id": "a1b2c3", "name": "Living Room", "hostname": "stuffymeter-a1b2c3", "lang": "en",
               "model": "Stuffy Meter",
               "manufacturer": "cmwang.dev", "hw_rev": "3.2", "board": "3.2", "fw_version": "1.1.0",
               "idf_version": "v5.5.6", "build_time": "Nov  7 2026 10:00:00", "elf_sha256": "...",
               "uptime_s": 3600, "boot_count": 12, "reset_reason": "power_on", "last_reboot": "ota",
               "time": "2026-11-07T18:00:00+0800", "unix_time": 1793959200,
               "heap_free": 150000, "heap_min_free": 120000, "heap_largest_block": 90000, "auth": true},
  "readings": {"co2_ppm": 612, "temperature_c": 24.31, "humidity_rh": 51.2, "dew_point_c": 13.6,
               "abs_humidity_gm3": 11.4, "voc_index": 104, "voc_raw": 30512,
               "co2_level": "good", "voc_level": "good", "level": "good",
               "co2_age_s": 2, "voc_age_s": 0, "seq": 7201},
  "sensors":  {"scd41": {"state": "ok", "serial": "a1b2c3d4e5f6", "errors": 0, "reinits": 0,
                         "asc": true, "low_power": false, "temp_offset_c": 4.0, "altitude_m": 0},
               "sgp40": {"state": "ok", "serial": "0123456789ab", "errors": 0, "reinits": 0, "warmup_left_s": 0},
               "i2c_recoveries": 0, "power_cycles": 0, "busy": false, "last_error": ""},
  "network":  {"state": "connected", "ssid": "MyWiFi", "ip": "192.168.1.42", "gateway": "192.168.1.1",
               "hostname": "stuffymeter-a1b2c3", "mac": "...", "rssi": -58, "channel": 6, "disconnects": 0,
               "time_synced": true, "mdns": true, "portal_active": false, "portal_ssid": "", "ethernet": false},
  "mqtt":     {"enabled": true, "connected": true, "published": 120, "failed": 0, "commands": 1, "last_error": ""},
  "ota":      {"state": "idle", "progress": 0, "bytes": 0, "total": 0, "pending_verify": false,
               "rollback_possible": true, "running_partition": "ota_0", "new_version": "",
               "available_version": "", "last_error": ""},
  "display":  {"enabled": true, "ok": true, "backlight_pct": 50, "page": 0, "asleep": false, "reinits": 0,
               "temp_f": false},
  "power":    {"state": "battery", "usb": false, "on_battery": true, "battery_present": true,
               "battery_v": 3.86, "battery_pct": 63, "charging": false, "low": false,
               "battery_s": 1520, "power_losses": 1}
}

Readings are null while invalid (sensor missing, stale, VOC warm-up). Levels are unknown|good|moderate|poor|bad (thresholds: co2_t1..3, voc_t1..3). Enums: sensor state unknown|absent|starting|ok|error|simulated; network state off|unprovisioned|connecting|connected|disconnected; OTA state idle|receiving|downloading|verifying|success|failed.

device.board is the hardware revision the firmware was built for (3.2 or 4.1; firmware 1.0.x has no such field and runs only on 3.2). power exists only on board 4.1:

Field Meaning
state full (USB, cell at or above 4.00 V), charging (USB, below 4.00 V, or a top-up after a cut), battery (no USB), no_battery (no cell or the slide switch OFF), empty (low-battery shutdown under way)
usb, on_battery, battery_present, charging, low booleans; low = on battery at 10 % or less
battery_v, battery_pct cell voltage and an estimate of the charge from it (0 without a cell)
battery_s, power_losses seconds on battery and USB -> battery switches since boot

The charger is not wired to the MCU, so charging is inferred: USB present and the cell below 4.00 V (the BQ25170 recharges at 4.00 V). After a power cut the charger tops the cell up even from 4.05 V, so charging stays on after USB returns until the cell has held 4.07 V for 2 minutes (at most 3 hours). Percent comes from a Li-ion table for a cell charged to 4.10 V: 4.10 V = 100 %, 3.30 V = 0 %; while charging it shows at most 99 %.

GET /api/history?minutes=1440&step=5

minutes (1..10080, default 1440) of history averaged into points of step minutes (1..120, default 1 for minutes <= 1440 and 15 for minutes > 1440). The newest 24 h are kept at 1-minute resolution in RAM and Tier 1 flash; older data up to 7 days is persisted as 15-minute rollups in Tier 2 flash inside the same 32 KB history partition, so minutes > 1440 requires step >= 15. Columns, oldest first, null = no data:

{"step_s": 300, "end": 1793959200, "count": 288,
 "co2_ppm": [612, 615, null], "temperature_c": [24.3, 24.3, null],
 "humidity_rh": [51.2, 51.0, null], "voc_index": [104, 101, null]}

end is the unix time at the end of the newest point (null if the clock is not set; then the newest point ends "now").

GET /api/ota

{"state": "idle", "progress": 0, "pending_verify": false, "rollback_possible": true,
 "last_error": "", "available_version": "", "running": "ota_0", "boot": "ota_0",
 "auto": {"enabled": true,
          "url": "https://github.com/chiehmin/stuffy-meter-releases/releases/latest/download/manifest.json",
          "window_start": 2, "window_end": 5, "time_valid": true, "in_window": false,
          "now": 1795062600, "next_attempt": 1795117020, "waiting": "outside_window", "failed_version": "",
          "failed_kind": "", "failed_retry_at": 0,
          "last_result": "update_available", "last_check": 1795062000, "manifest_version": "1.6.1",
          "release": "<release tag>",
          "notes_url": "https://github.com/chiehmin/stuffy-meter-releases/releases/tag/<release tag>",
          "error": ""},
 "slots": [
   {"label": "ota_0", "running": true, "boot": true, "state": "valid", "version": "1.0.0",
    "project": "stuffymeter", "idf": "v5.5.6", "build": "Nov  7 2026 10:00:00", "elf_sha256": "..."},
   {"label": "ota_1", "running": false, "boot": false, "state": "empty", "version": "",
    "project": "", "idf": "", "build": "", "elf_sha256": ""}]}

Slot state: empty (no valid app image), or the bootloader state new|pending_verify|valid|invalid|aborted|undefined. boot is the slot the next reset will start.

auto describes the automatic updates (OTA.md, "Automatic updates"):

Field Meaning
enabled, window_start, window_end the settings ota_auto, ota_win_start, ota_win_end (local hours, the window is [start, end))
url the ota_url manifest URL ("" if unset)
time_valid, in_window the clock is set; the local time is inside the window
now the monitor's clock (unix time, 0 if not set), to show the other times relative to it
next_attempt unix time of tonight's install attempt, 0 if none is planned
waiting why no automatic install starts now: off, no_url, dev_build, time_not_set, up_to_date, major_update, failed_before, no_sha256 (the manifest entry has no sha256), outside_window, on_battery, pending_verify, busy, or ""
failed_version a version rolled back on this monitor ("" if none)
failed_kind hard: never installed automatically again; soft (the network or the update check failed during probation): tried once more at failed_retry_at; "" if none
failed_retry_at soft marks: unix time from which the nightly attempt tries that version again, 0 otherwise (or until the clock is set)
last_result the last manifest check, manual or automatic: "" (none yet), up_to_date, update_available, installing, error (reason in error; also when the install the check started failed, as install failed: ...)
last_check when it ran (unix time, 0 if the clock was not set)
manifest_version, release, notes_url the manifest's version and, from GitHub releases, the release tag and the release page

POST /api/ota

Body: the raw application image (build/stuffymeter.bin on board 3.2, build-4.1/stuffymeter_hw4.bin on board 4.1), Content-Type: application/octet-stream, optional header X-OTA-SHA256: <64 hex> of the whole body. The image is checked as it streams in (magic, ESP32-C3 chip id, project stuffymeter on 3.2 or stuffymeter_hw4 on 4.1) and written to the inactive slot. Replies:

  • 200 {"ok": true, "version": "1.0.1", "rebooting": true} - the device then reboots by itself ~1.5 s later and runs the new image in pending_verify until its health checks pass (or it rolls back).
  • 400 invalid image / hash mismatch / an image for the other circuit (image is for hardware 4.x, this monitor is hardware 3.2), 409 another update is running, 413 larger than the slot, 500 flash error - all with the error JSON.

OTA manifest (aq release / aq serve, setting ota_url)

{"project": "stuffymeter", "version": "2.0.2", "url": "hw3.2/stuffymeter-2.0.2.bin",
 "sha256": "<64 hex>", "size": 1234567, "idf": "v5.5.6", "date": "2026-11-14",
 "images": [
   {"board": "3.2", "project": "stuffymeter", "version": "2.0.2", "url": "hw3.2/stuffymeter-2.0.2.bin",
    "sha256": "<64 hex>", "size": 1234567},
   {"board": "4.1", "project": "stuffymeter_hw4", "version": "2.0.2", "url": "hw4.1/stuffymeter_hw4-2.0.2.bin",
    "sha256": "<64 hex>", "size": 1254551}]}

url may be relative to the manifest URL (ota_url, also after redirects). An update is offered when version is newer than the running one (semver, build metadata ignored). Firmware 1.3 takes the images entry with its own board and project, else the first one with its project (4.0 and 4.1 run each other's images); 1.1 and 1.2 take the first entry with their project; 1.0.x reads only the top level, which is therefore the board 3.2 image. A manifest without an entry for the monitor's app name is refused (manifest has no image for hardware 4.1).

The public GitHub releases (the default ota_url, https://github.com/chiehmin/stuffy-meter-releases/releases/latest/download/manifest.json) use the same format with absolute urls pinned to the release, e.g. https://github.com/chiehmin/stuffy-meter-releases/releases/download/<release>/stuffy_meter_fw<version>_board4.1.bin, and two optional top-level fields that older firmware ignores: release (the release tag) and notes_url (the release page, an https:// URL). Firmware 1.6 and later follow up to 5 redirects for the manifest (GitHub uses two) and for an image URL (GitHub uses one), and read manifests up to 8 KB; request lines (GitHub's signed download URLs run to about 900 characters) may be up to 4 KB. From an https:// URL a redirect must lead to an absolute https:// URL (redirect refused: not an absolute https:// URL). The nightly attempt only installs an entry with a sha256; manual installs check it when present.

Clone this wiki locally