Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
# HiveHub API reference
The HiveHub backend exposes a FastAPI REST API and Swagger UI at `http://<host>:31115/docs`.
---
## Base URL
```text
http://<host>:31115
```
Replace `<host>` with the server IP address or domain name.
> **TLS:** the ESP32 firmware now verifies the backend's TLS certificate (it
> ships the ISRG Root X1 / Let's Encrypt root CA in `firmware/include/ca_cert.h`
> and syncs time over NTP for validity checks). Production devices must reach
> the API over **HTTPS with a valid certificate** — put the API behind a reverse
> proxy that terminates TLS. Plain-HTTP examples below are for host-side `curl`
> testing only.
---
## Authentication
HiveHub uses separate credentials for device traffic and HivePal app traffic.
### Device key
ESP32 firmware and administrative device tooling use `X-API-Key`.
```text
X-API-Key: your-api-key
```
There are two kinds of device key:
- **Per-device key** — each device has its own unique key (set as `API_KEY` in
that device's `secrets.h`). On the first request from a new `device_id`, the
backend stores a hash of the presented key and binds it to that device.
Every later request for that device must present the same key, so a leaked
key only affects the one device it belongs to. Used by the device-initiated
endpoints: `POST /api/v1/measurements`, `GET/PATCH …/config`,
`GET …/firmware`, `GET …/commands/next`, and `POST …/commands/{id}/result`.
- **Master/admin key** — the value of the server `API_KEY` environment
variable. Used for server-to-server / tooling endpoints that no device
calls: `GET /api/v1/measurements/latest`, `POST /api/v1/firmware/releases`,
`POST …/commands` (queueing), `…/commands/update-hiveinside`, and
`GET /api/v1/time`.
> A device's per-device key no longer has to match the server `API_KEY`. To
> rotate or re-register a device key, clear its stored hash with
> `UPDATE devices SET api_key_hash = NULL WHERE device_id = '…';` and the next
> request re-registers whatever key the device presents.
### HivePal service key + user token
HivePal uses `X-HivePal-Service-Key` plus a per-user JWT on all app endpoints.
```text
X-HivePal-Service-Key: your-hivepal-service-key
Authorization: Bearer <hivepal-jwt>
```
The service key must match HiveHub's `HIVEPAL_SERVICE_API_KEY`. The JWT is the
access token HivePal issues to its own users; HiveHub verifies its signature
with the shared `HIVEPAL_JWT_SECRET` (HS256) and reads the user ID from the
token's `sub` claim to enforce per-device ownership and roles. The legacy
plaintext `X-User-Id` header is no longer accepted.
---
## General endpoints
### `GET /health`
Health check. No authentication required. `version` is the backend server
version (`SERVER_VERSION` in `server/config.py`).
```json
{ "status": "ok", "version": "0.3.1" }
```
### `GET /api/v1/time`
Returns current UTC server time for RTC sync.
**Auth:** `X-API-Key` (master/admin key)
```json
{
"timestamp": "2026-05-01T12:00:00+00:00",
"unix": 1777636800,
"timezone": "UTC"
}
```
---
## Measurements
### `POST /api/v1/measurements`
Submit a measurement from a device. On the first measurement from a new `device_id`, the backend creates a device record and a default config row, and registers the presented `X-API-Key` as that device's per-device key. If a `claim_code` is included, it is hashed and stored so a HivePal user can claim the device.
Current firmware includes an immutable `measurement_id` in every measurement.
The backend uses `(device_id, measurement_id)` as an idempotency key: replaying
the exact same cached JSON returns success with `duplicate: true` rather than
creating a second row or re-publishing a retained MQTT state. Older clients
without this field remain supported but cannot get this delivery guarantee.
**Auth:** `X-API-Key` (per-device key — registered on first contact, enforced thereafter)
> **Multi-hive payload (firmware v0.20.0+).** Devices now report up to 16 hives in
> a `hives` array (see below); the flat `scale_1/2_*` / `hive_1/2_*` fields are the
> legacy two-hive form and remain accepted. The server stores per-hive data in the
> `hive_readings` table, mirrors hives 1–2 onto the legacy columns, and on read
> returns **both** a `hives` array and synthesized `scale_N_*`/`hive_N_*` flat keys
> for every hive. See [multi-hive.md](multi-hive.md).
>
> ```json
> {
> "device_id": "hive_scale_18_01",
> "hive_count": 2,
> "hives": [
> { "index": 1, "weight_kg": 41.2, "raw_weight": 8345012, "scale_source": "nau7802",
> "temp_c": 34.1, "temp_source": "ds18b20", "humidity_percent": 55.0,
> "accel": { "ok": true, "rms_mg": 12.5 },
> "ble": { "present": true, "sensor_type": "HolyIot 25015", "pressure_hpa": 1011.2 } },
> { "index": 2, "weight_kg": 38.0, "scale_source": "nau7802", "temp_c": 33.0,
> "bee_counter": { "ok": true, "total_in": 1200, "total_out": 1190 } }
> ]
> }
> ```
>
> Per-hive object fields: `index` (1–18, required), `name`, `weight_kg`,
> `raw_weight`, `scale_source`, `temp_c`, `temp_source`, `humidity_percent`, and
> nested `accel{}`, `ble{}`, `mic{}`, `bee_counter{}` objects.
#### Request fields
| Field | Type | Required | Description |
|---|---|---:|---|
| `device_id` | string | Yes | Unique device identifier |
| `hives` | array | No | Per-hive readings (up to 16); see the multi-hive note above |
| `hive_count` | int | No | Number of hives the device has configured |
| `claim_code` | string | No | Pairing code; the firmware keeps sending it until the server confirms the device is claimed (via the `claimed` field in the response below), after which it is omitted to limit exposure. This means a rebuilt/restored backend automatically re-learns the code and the device stays claimable. |
| `timestamp` | ISO datetime | No | Measurement time; server receive time is used if omitted |
| `scale_1_weight_kg` | number | No | Scale 1 weight in kilograms |
| `scale_2_weight_kg` | number | No | Scale 2 weight in kilograms |
| `hive_1_temp_c` | number | No | Hive 1 internal temperature |
| `hive_2_temp_c` | number | No | Hive 2 internal temperature |
| `hive_1_humidity_percent` | number | No | Hive 1 internal relative humidity (from a paired in-hive BLE sensor) |
| `hive_2_humidity_percent` | number | No | Hive 2 internal relative humidity (from a paired in-hive BLE sensor) |
| `ambient_temp_c` | number | No | Ambient temperature (SHT4x by default; SHT3x or BME280 if configured) |
| `ambient_humidity_percent` | number | No | Ambient relative humidity (SHT4x/SHT3x/BME280) |
| `ambient_pressure_hpa` | number | No | Ambient barometric pressure. Only sent when a pressure-capable ambient sensor (BME280) is compiled in; currently not persisted to a dedicated column, so the ingest schema ignores it |
| `battery_voltage` | number | No | Legacy battery/supply voltage field |
| `battery_voltage_v` | number | No | Battery voltage from MAX17048; preferred off-grid field |
| `battery_soc_percent` | number | No | LiPo state-of-charge percentage |
| `battery_alert` | boolean | No | MAX17048 alert state |
| `battery_monitor_ok` | boolean | No | Whether MAX17048 was detected/read successfully |
| `solar_monitor_ok` | boolean | No | Legacy INA219 solar monitor detected/read successfully (no longer part of the recommended build) |
| `solar_bus_voltage_v` | number | No | Legacy INA219 bus voltage |
| `solar_shunt_voltage_mv` | number | No | Legacy INA219 shunt voltage |
| `solar_load_voltage_v` | number | No | Calculated load voltage |
| `solar_current_ma` | number | No | Solar/load current |
| `solar_power_mw` | number | No | Solar/load power |
| `network_transport` | string | No | `wifi` (current firmware), `sim7080g`, or another future transport label |
| `calibration_mode` | boolean | No | Whether firmware was in calibration mode for this reading |
| `inspection` | boolean | No | The hub believes a beekeeper has the hive open. The hive readings in the same payload are still stored; the flag opens/closes a window that keeps them out of charts, insights and alerts. See [inspection-mode.md](inspection-mode.md) |
| `inspection_started_at` | int | No | Unix seconds at which the hub started the inspection, so the window is back-dated to the button press rather than to the first upload reporting it |
| `boot_count` | integer | No | ESP32 RTC boot counter |
| `time_source` | string | No | Time source such as `rtc`, `server`, `cellular`, or `compile` |
| `rssi_dbm` | integer | No | Wi-Fi RSSI or CSQ-derived approximate RSSI |
| `firmware_version` | string | No | Running firmware version |
| `config_version` | integer | No | Config version currently applied by the device |
| `sd_ok` | boolean | No | SD card status |
| `rtc_ok` | boolean | No | RTC status |
| `sht_ok` | boolean | No | Whether the current cycle produced a valid ambient measurement (SHT4x/SHT3x/BME280; false when `ambient_temp_c`/`ambient_humidity_percent` are null because the read failed). Field name kept `sht_*` for backward compatibility |
| `sht_detected` | boolean | No | Whether the ambient sensor was detected/initialized at boot (diagnostic; ignored by the backend, retained in the raw upload) |
| `scale_1_raw` | integer | No | Raw HX711 reading for scale 1 |
| `scale_2_raw` | integer | No | Raw HX711 reading for scale 2 |
#### Acoustic fields (INMP441 stereo mics)
| Field | Type | Required | Description |
|---|---|---:|---|
| `mic_ok` | boolean | No | At least one microphone was read successfully |
| `mic_sample_rate_hz` | integer | No | I2S sample rate used for the capture |
| `mic_sample_frames` | integer | No | Number of stereo frames captured |
| `mic_left_ok` / `mic_right_ok` | boolean | No | Per-channel read status |
| `mic_left_rms_dbfs` / `mic_right_rms_dbfs` | number | No | Broadband RMS level in dBFS |
| `mic_left_peak_dbfs` / `mic_right_peak_dbfs` | number | No | Peak level in dBFS |
| `mic_left_rms_normalized` / `mic_right_rms_normalized` | number | No | Linear RMS as a fraction of full scale (0–1) |
| `mic_{left,right}_band_sub_bass_dbfs` | number | No | 50–150 Hz band energy (dBFS) |
| `mic_{left,right}_band_hum_dbfs` | number | No | 150–300 Hz colony-hum band energy |
| `mic_{left,right}_band_piping_dbfs` | number | No | 300–550 Hz piping/tooting band energy |
| `mic_{left,right}_band_stress_dbfs` | number | No | 550–1500 Hz agitation band energy |
| `mic_{left,right}_band_high_dbfs` | number | No | 1500–3000 Hz band energy |
#### Entrance-counter fields (HiveTraffic BeeCounter — BLE/GATT only)
One HiveTraffic counter may be paired per hive; it is read over **BLE/GATT**
(the only supported bee-counter transport — the wired I2C path was removed).
Each block is independent; a paired-but-unreachable unit reports
`bee_counter_N_ok=false` and the rest of its fields null; an unpaired hive
sends no bee-counter fields at all. Current firmware reports **lifetime totals
only** — the interval columns are backfilled server-side by differencing
consecutive totals. For `N` in `1`, `2`:
| Field | Type | Description |
|---|---|---|
| `bee_counter_N_ok` | boolean | Counter reached and parsed this cycle |
| `bee_counter_N_protocol_version` | integer | Counter **wire-format** revision (BLE `fw` field) — not its firmware version, which is `hives[].bee_counter.version` |
| `bee_counter_N_status_flags` | integer | Status bitfield |
| `bee_counter_N_uptime_s` | integer | Counter uptime in seconds. 32-bit as of wire revision 3; a `fw:2` counter clamps it at 65535 (18 h 12 min) |
| `bee_counter_N_num_gates` | integer | Gates wired to the counter (24) |
| `bee_counter_N_gates_healthy` | integer | **Legacy, wired-era only.** Despite the name this counted MCP23017 port expanders, 0..3 — never gates. BLE counters do not write this column; see below |
| `bee_counter_N_total_in` / `_total_out` | integer | Cumulative (lifetime) in/out counts, saturating at 4294967295 |
| `bee_counter_N_glitch_count` | integer | Diagnostics. 32-bit and saturating as of wire revision 3; a `fw:2` counter pins at 65535 |
BLE counters report their expander health as `hives[].bee_counter.mcps_healthy`
(0..3, **not** a count of working gates — each healthy expander covers eight of
the 24). It was called `gates_healthy` before HiveTraffic wire revision 3, and
readings stored before that change carry the old key in
`hive_readings.raw_json` with the same meaning. The value is live health: it
moves during a deployment as expanders fail and recover, so nothing may treat it
as constant after boot.
`bee_counter_N_interval_in` / `_interval_out` are also accepted and are fully
live — the BLE path leaves them null on ingest and the read APIs backfill them
by differencing consecutive totals.
The wired-only telemetry — `_busy_retries`, `_read_attempts`,
`_latch_succeeded`, and the per-gate 24-byte arrays
(`bee_counter_N_per_gate_in` / `_per_gate_out`) — is **no longer accepted**. It
described the I2C transport (bus retries, whether `CMD_LATCH` landed), which no
firmware speaks anymore; a payload carrying these fields has them ignored rather
than stored. The `measurements` columns are deliberately kept and the read APIs
still return them, so readings recorded during the wired era stay retrievable.
Every row written since is null there.
#### Vibration fields (in-hive accelerometer)
Per-hive vibration, populated from a paired in-hive **BLE sensor** (a HiveInside
nRF54LM20A supplies the full FFT bands; a HolyIot 25015 / RuuviTag beacon supplies
only broadband `accel_N_rms_mg` / `accel_N_peak_mg`) — see
[accelerometer.md](accelerometer.md). (The old wired LIS3DH/LIS2DH12 driver has
been removed; vibration is BLE-only.) Each block is independent; a missing
source reports `accel_N_ok=false` and the rest of its fields are null. All
band/RMS values are AC (gravity removed), in milli-g (mg). For `N` in `1`, `2`:
| Field | Type | Description |
|---|---|---|
| `accel_N_ok` | boolean | Vibration source present and read this cycle |
| `accel_N_sample_rate_hz` | integer | Output data rate used for the capture |
| `accel_N_sample_count` | integer | Samples fed into the FFT |
| `accel_N_range_g` | integer | Full-scale range (±2/4/8/16 g) |
| `accel_N_rms_mg` | number | Broadband AC RMS of the vector magnitude |
| `accel_N_peak_mg` | number | Peak deviation from the mean |
| `accel_N_band_swarm_mg` | number | 8–30 Hz energy — ~20 Hz pre-swarm signal (consumed by Insights) |
| `accel_N_band_fanning_mg` | number | 30–100 Hz fanning/ventilation energy |
| `accel_N_band_activity_mg` | number | 100–200 Hz general activity energy |
See [accelerometer.md](accelerometer.md) for the rationale and wiring.
The full payload is also stored as JSONB in `raw_json`. The request model uses
`extra="ignore"`, so **only fields declared on `MeasurementIn` are stored** —
any field the model does not know about is silently dropped, not preserved in
`raw_json`. When adding a new telemetry field (e.g. a new GATT field), declare
it on `MeasurementIn` or it will be discarded on ingest.
> `network_transport` is accepted and stored for the future Power Module. The
> current ESP32 firmware is Wi-Fi only and reports `network_transport: "wifi"`.
> The old `cellular_ok` / `cellular_csq` fields were **removed from the schema**
> and are silently ignored if sent (`extra="ignore"`).
#### Example Wi-Fi payload
```json
{
"device_id": "hive_scale_dual_01",
"claim_code": "ABCD-1234",
"timestamp": "2026-05-01T12:00:00Z",
"scale_1_weight_kg": 42.5,
"scale_2_weight_kg": 38.2,
"hive_1_temp_c": 34.1,
"hive_2_temp_c": 33.7,
"ambient_temp_c": 18.4,
"ambient_humidity_percent": 61.2,
"network_transport": "wifi",
"rssi_dbm": -65,
"firmware_version": "0.9.2",
"config_version": 3,
"sd_ok": true,
"rtc_ok": true,
"sht_ok": true,
"scale_1_raw": -298450,
"scale_2_raw": -271900
}
```
#### Example off-grid payload
```json
{
"device_id": "hive_scale_offgrid_01",
"claim_code": "ABCD-1234",
"timestamp": "2026-05-01T12:00:00Z",
"scale_1_weight_kg": 42.5,
"scale_2_weight_kg": 38.2,
"network_transport": "sim7080g",
"rssi_dbm": -77,
"battery_voltage_v": 3.94,
"battery_soc_percent": 73.2,
"battery_alert": false,
"battery_monitor_ok": true,
"solar_monitor_ok": true,
"solar_bus_voltage_v": 5.22,
"solar_shunt_voltage_mv": 12.4,
"solar_load_voltage_v": 5.232,
"solar_current_ma": 184.0,
"solar_power_mw": 960.0,
"calibration_mode": false,
"boot_count": 128,
"time_source": "cellular"
}
```
#### Response
```json
{
"status": "ok",
"id": 1042,
"measured_at": "2026-05-01T12:00:00+00:00",
"claimed": false
}
```
`claimed` is `true` once a HivePal user has claimed the device. The firmware keeps
sending its `claim_code` until it sees `claimed: true`, so that a backend that has
lost the device record (fresh install, DB restore) re-learns the claim code and the
device can be claimed again without a re-flash.
### `GET /api/v1/measurements/latest`
Returns recent measurements across all devices, newest-first.
**Auth:** `X-API-Key` (master/admin key)
| Query parameter | Default | Max | Description |
|---|---:|---:|---|
| `limit` | 50 | 500 | Number of rows to return |
The response includes the core fields and the optional off-grid fields listed above.
---
## Device configuration
### `GET /api/v1/devices/{device_id}/config`
Returns the current config for a device. A default config is created if none exists.
**Auth:** `X-API-Key` (per-device key)
```json
{
"device_id": "hive_scale_dual_01",
"send_interval_seconds": 600,
"scale1_offset": 0,
"scale1_factor": -7050.0,
"scale2_offset": 0,
"scale2_factor": -7050.0,
"config_version": 3,
"tempco_enabled": false,
"tempco_source": "ambient",
"tempco_ref_temp_c": 20.0,
"scale1_tempco_kg_per_c": 0.0,
"scale2_tempco_kg_per_c": 0.0,
"beecounter_night_mode_enabled": false,
"beecounter_night_start_minute": 1200,
"beecounter_night_end_minute": 360,
"beecounter_night_max_traffic": 0,
"timezone": "",
"beecounter_bank1_enabled": true,
"beecounter_bank2_enabled": true,
"beecounter_bank3_enabled": true,
"inspection_timeout_minutes": 60
}
```
`inspection_timeout_minutes` (1–1440, default 60) caps how long an inspection
may run before the device ends it by itself — see
[inspection-mode.md](inspection-mode.md#auto-end). Applied on every config fetch
and persisted in NVS, so a hub that boots without WiFi still ends its
inspections. It is a safety net, not a schedule: without it one forgotten button
press blanks a hive's charts indefinitely, which looks exactly like a dead
sensor.
The `beecounter_night_*` fields configure **HiveTraffic night mode** — see
[hivetraffic-bee-counter.md](hivetraffic-bee-counter.md#night-mode). Unlike the
calibration fields below, the device applies them on **every** config fetch
rather than only when `config_version` changes: there is no portal-side
counterpart to protect, and turning the window off has to take effect on the
next cycle rather than waiting for an unrelated edit to bump the version.
| Field | Meaning |
| --- | --- |
| `beecounter_night_mode_enabled` | Master switch. `false` by default, so an existing device is unaffected until it is turned on. |
| `beecounter_night_start_minute` / `beecounter_night_end_minute` | The window, in **local** minutes since midnight (0–1439). `start > end` wraps midnight, which the 20:00–06:00 default does. `start == end` is an **empty** window, not a 24-hour one — the firmware refuses it, so a single mis-set field cannot stop a counter for good. |
| `beecounter_night_max_traffic` | Crossings (in + out) in the last upload cycle above which night mode is postponed to the next cycle. `0` disables the check. |
| `timezone` | POSIX TZ string, e.g. `CET-1CEST,M3.5.0,M10.5.0/3`. Empty means UTC. |
The `beecounter_bank*_enabled` fields configure **HiveTraffic emitter banks** —
see [hivetraffic-bee-counter.md](hivetraffic-bee-counter.md#emitter-banks).
Applied on every config fetch for the same reason the night-mode fields are.
| Field | Meaning |
| --- | --- |
| `beecounter_bank1_enabled` | Emitter MOSFET for gates 00–07. `true` by default. |
| `beecounter_bank2_enabled` | Emitter MOSFET for gates 10–17. `true` by default. |
| `beecounter_bank3_enabled` | Emitter MOSFET for gates 20–27. `true` by default. |
A counter's 48 IR emitters sit behind three MOSFETs, one per group of eight
gates, and they dominate its power draw. Measured on the counter's 3.3 V rail:
one bank ~0.14 A, two ~0.22 A, three ~0.30 A — roughly 80 mA per bank on top of
a ~60 mA floor. Switching one off stops its eight gates being counted at all, so
the totals drop in proportion; the counter reports the mask back as
`hives[].bee_counter.banks` so a deliberately dark bank is distinguishable from
a failed one.
A PATCH that would leave **all three** disabled is rejected with `400`. The
counter refuses a mask of zero outright — it keeps the mask it had — so storing
one would only leave the dashboard and the hardware permanently disagreeing. A
counter that should count nothing is unpaired instead.
The device requires HiveTraffic firmware 0.3.0 (wire revision 5) or newer to
apply the mask; on an older counter the write is skipped and all three banks
stay on.
`timezone` is load-bearing rather than cosmetic. The device clock is UTC, so
without it a window entered as 20:00 fires at 21:00 local in summer — discarding
an hour of foraging on exactly the long evenings that have most of it. It is a
POSIX string rather than an IANA name because the ESP32 carries no tz database;
newlib parses this form directly, DST rules included. The dashboard offers
presets for the common zones and a free-text field for anything else.
The `tempco_*` fields drive backend load-cell temperature compensation. They are
informational for the device (which keeps sending raw weights); the correction is
applied in the backend on read. See
[temperature-compensation.md](temperature-compensation.md).
Since firmware 0.23.5 the device applies the `scale*_offset`/`scale*_factor`
fields to its hive registry **only when `config_version` differs from the last
version it applied** (stored in NVS). A calibration done locally on the
provisioning portal's `/calibrate` page therefore survives config fetches; to
override it from the backend, change the values here (any `PATCH` bumps
`config_version`, which makes the device adopt them on its next cycle).
Since firmware 0.23.7 the device also **reports a portal calibration back to the
server**. The provisioning AP is offline, so a tare/span done there (and a
"Save and reboot" that carries one) only sets a pending flag in NVS. On the first
cycle with WiFi after the reboot, the device `PATCH`es its live calibration so the
backend no longer holds only defaults: hives 1–2 in the `scale1/2_offset` +
`factor` fields, and **hives 3+ in the `hive_scales` array** (below). That
`PATCH` bumps `config_version`; the device records the returned version as its
last-applied one, so the config fetch in the same cycle does not bridge those
values straight back.
The GET response includes a `hive_scales` array carrying the stored calibration
for hives 3+ (hives 1–2 stay in the `scale1/2_*` fields):
```json
"hive_scales": [
{ "index": 5, "scale": 0, "offset": 123, "factor": -7100.0, "tempco_kg_per_c": -0.004 }
]
```
A `PATCH` may send the same array to set them; each entry updates one hive
(omitted `offset`/`factor`/`tempco_kg_per_c` keep their current value). These are
stored per hive in `device_configs.scale_offsets_by_hive` and, like the legacy
fields, are bridged into the firmware's hive registry when `config_version`
changes — except `tempco_kg_per_c`, which is a backend read-time correction the
device never consumes (the hives 3+ counterpart of `scale1/2_tempco_kg_per_c`,
sharing the device-wide `tempco_enabled` / `tempco_source` / `tempco_ref_temp_c`
settings).
### `PATCH /api/v1/devices/{device_id}/config`
Updates one or more config fields and increments `config_version`.
**Auth:** `X-API-Key` (per-device key)
```json
{
"send_interval_seconds": 300,
"scale1_factor": -7200.0
}
```
---
## Firmware OTA
### `GET /api/v1/devices/{device_id}/firmware`
Checks whether a newer active firmware release is available for the given target.
The release is resolved **owner-first**: the backend looks up the device's owner
and serves that owner's most recent active release, falling back to a global /
"official" release (one with no owner) when the owner has none. A scale therefore
only ever sees firmware its own owner uploaded, or an official build.
For the `hivescale` self-update this endpoint is also **accept-to-apply**: it
returns `update: true` only once the owner has approved that exact version for the
device (`POST /api/v1/app/devices/{device_id}/firmware/approve`). Until then it
reports no update, so publishing firmware never auto-flashes a whole fleet. The
sub-device target (`hiveinside`) is relayed explicitly via commands and is not
gated here.
**Auth:** `X-API-Key` (per-device key)
| Query parameter | Default | Description |
|---|---|---|
| `version` | `0.0.0` | Current device firmware version |
| `target` | `hivescale` | `hivescale` (the ESP32 itself) or `hiveinside`. The `hivehub` alias is also accepted and treated as `hivescale`. |
No update:
```json
{ "update": false, "update_available": false }
```
Update available:
```json
{
"update": true,
"update_available": true,
"version": "0.9.3",
"url": "https://your-domain.example.com/firmware/hivescale-0.9.3.bin",
"size": 1276928,
"crc32": 2843490522
}
```
> The response carries both `update` and `update_available` with the same value:
> the ESP32 reads `update`, while older clients read `update_available`.
>
> `size` (bytes) and `crc32` (unsigned CRC-32 of the image file) let the device
> flash safely even when the download arrives without a `Content-Length` header
> — a reverse proxy/CDN (e.g. Cloudflare) may deliver the binary with
> `Transfer-Encoding: chunked` — and verify the received image before rebooting.
> `0` means unknown; firmware ≤ 0.23.5 ignores both fields.
### `POST /api/v1/firmware/releases`
Registers or updates a firmware release. The binary must already exist in `FIRMWARE_DIR`. The server computes and stores the image CRC-32.
**Auth:** `X-API-Key` (master/admin key)
```json
{
"version": "0.9.3",
"filename": "hivescale-0.9.3.bin",
"active": true,
"target": "hivescale"
}
```
`target` defaults to `hivescale` and may also be `hiveinside` or `beecounter`
(the HiveTraffic counter). Response:
```json
{ "status": "ok", "version": "0.9.3", "target": "hivescale", "crc32": 2882343476 }
```
### `GET /firmware/{filename}`
Downloads a firmware binary. This endpoint has no API-key requirement; the URL is normally obtained from the firmware check endpoint.
### `POST /api/v1/devices/{device_id}/commands/update-hiveinside`
Queues an `update_hiveinside` command that tells the HiveHub to relay the active
HiveInside firmware image to the HiveInside sensor paired in the given slot over
BLE GATT. The image URL, version, and CRC-32 are looked up server-side and embedded
in the command payload; the HiveHub resolves the BLE MAC locally.
**Auth:** `X-API-Key` (master/admin key)
| Query parameter | Default | Description |
|---|---|---|
| `slot` | `1` | Hive index (`1`..`18`) carrying the HiveInside to update |
| `force` | `false` | Relay even when the release is not newer than the running version |
`slot` is the **hive index**: the HiveHub resolves it against its hive registry
and matches only HiveInside pairings, so any hive can be updated. (Before 0.24.6
the slot addressed the legacy two-element `bleSensorMac0/1` globals, which held
the first beacon of *any* type — hives 3+ were unreachable and a hive whose first
pairing was a HolyIot/RuuviTag aimed the relay at the wrong device.)
The relay is **version-gated**: the release must be strictly newer than the
firmware version that node last advertised (`hives[].ble.firmware_version`, seen
within the last 30 days). A node that has never advertised a version is not
gated, since there is nothing to compare against.
Returns `400` for a slot outside `1..18`, `404` if there is no active
`hiveinside` release, and `409` when the release is not newer:
```json
{ "detail": "HiveInside on hive 1 already runs 0.4.1; release 0.4.1 is not newer. Upload a higher version, or pass force=true to relay it anyway." }
```
### `POST /api/v1/devices/{device_id}/commands/update-beecounter`
Queues an `update_beecounter` command that tells the HiveHub to relay the active
`beecounter` firmware image to the HiveTraffic counter paired in the given slot
over BLE GATT. Identical mechanics to `update-hiveinside` above — same
server-side URL/CRC lookup, same local MAC resolution, same query parameters,
same `400`/`404`/`409` responses.
**Auth:** `X-API-Key` (master/admin key)
| Query parameter | Default | Description |
|---|---|---|
| `slot` | `1` | Hive index (`1`..`18`) carrying the counter to update |
| `force` | `false` | Relay even when the release is not newer than the running version |
The version compared is the counter's own image version, reported as
`hives[].bee_counter.version` (the `"ver"` field of its measurement JSON). A
counter on firmware that predates that field reports none and is therefore never
gated.
**The counter stops counting bees for the whole transfer.** It parks its IR
emitters and pauses gate polling while writing flash, so an unnecessary relay
costs real traffic data — which is what the version gate exists to prevent.
Prefer relaying at night or in poor flying weather.
Response on success — `current_version` is the version being replaced (`null`
when the node never advertised one):
```json
{ "id": 72, "status": "pending", "slot": 1, "version": "0.4.1", "current_version": "0.4.0" }
```
> The HiveHub reports the command result **after** the relay finishes, so the
> command transitions `pending` → `claimed` → `done`/`failed` reflecting the real
> outcome. A failed relay records a specific cause in the command result message
> (e.g. `HiveInside not found in scan (asleep or out of range?)`,
> `firmware download failed (HTTP 404)`, `HiveInside rejected image (… CRC/size
> mismatch?)`). The HiveInside must be awake/advertising during the locate scan.
---
## Remote commands
Commands are queued server-side and claimed by the device on a later cycle. A
command is picked up **once per upload cycle**, in every mode — there is no
separate command poll.
### Lifecycle and abandoned claims
A command moves `pending` → `claimed` → `done`/`failed`. Because
`commands/next` only ever serves `pending` rows, a claim the device never
reports on would otherwise be invisible to every later poll — never retried and
never failed. The device does not have to crash for that to happen: the result
POST is fire-and-forget, so a Wi-Fi hiccup right after a multi-minute BLE relay
strands the row just the same.
The backend therefore sweeps stale claims (cheap and idempotent, run before
serving a command — no background job):
| Setting | Value | Meaning |
|---|---|---|
| `STALE_CLAIM_MINUTES` | `20` | A claim older than this with no result is abandoned |
| `MAX_COMMAND_ATTEMPTS` | `3` | How often one command may be handed out before it is failed for good |
| `RETRYABLE_COMMAND_TYPES` | `update_hiveinside`, `update_beecounter` | Only these go back on the queue |
Retryable commands return to `pending` until the attempt limit, then fail with
`timed out: claimed by the device N time(s) without reporting a result`.
Everything else fails on the **first** timeout rather than being repeated —
silently re-running a `factory_reset` or `reset_wifi` because a result POST was
lost would destroy state the operator asked to change exactly once. Either way
the row reaches a terminal state, so the dashboard shows an outcome instead of a
permanent "relaying…". The attempt counter lives in `device_commands.attempts`
(migration `021_device_command_attempts.sql`).
### `POST /api/v1/devices/{device_id}/commands`
**Auth:** `X-API-Key` (master/admin key)
```json
{
"command_type": "start_calibration_mode",
"payload": {"interval_seconds": 5, "timeout_seconds": 600}
}
```
| Command type | Payload | Description |
|---|---|---|
| `calibrate_scale_1` | `{"known_weight_kg": 10.0}` | Set scale 1 calibration factor using a known weight |
| `calibrate_scale_2` | `{"known_weight_kg": 10.0}` | Set scale 2 calibration factor using a known weight |
| `start_calibration_mode` | `{"interval_seconds": 5, "timeout_seconds": 600}` | Temporarily use fast cycles for calibration |
| `stop_calibration_mode` | `{}` | Return to the normal configured interval |
| `start_inspection` | `{}` | Flag hive readings as taken with the hive open — see [inspection-mode.md](inspection-mode.md). Prefer the `/inspections/start` endpoints below, which also record the window |
| `stop_inspection` | `{}` | End inspection mode |
| `reboot` | `{}` | Restart ESP32 |
| `reset_preferences` | `{}` | Clear stored preferences and reboot |
| `factory_reset` | `{}` | Factory reset stored preferences and reboot |
| `reset_wifi` | `{}` | Clear saved Wi-Fi credentials and reboot |
| `check_ota` / `ota_update` | `{}` | Trigger immediate OTA check/update |
| `update_hiveinside` | `{"slot": 1, "url": "...", "version": "...", "crc32": 123}` | Relay a firmware image to a HiveInside sensor over BLE GATT (normally queued via the `update-hiveinside` helper above) |
| `update_beecounter` | `{"slot": 1, "url": "...", "version": "...", "crc32": 123}` | Relay a firmware image to a HiveTraffic counter over BLE GATT (normally queued via the `update-beecounter` helper above) |
| `start_provisioning` | `{}` | Start provisioning AP |
Response:
```json
{ "status": "queued", "id": 55 }
```
### `GET /api/v1/devices/{device_id}/commands/next`
Claims the next pending command and marks it as claimed.
**Auth:** `X-API-Key` (per-device key)
No command:
```json
{ "command": false }
```
Command returned:
```json
{
"command": true,
"id": 55,
"command_type": "start_calibration_mode",
"payload": {"interval_seconds": 5, "timeout_seconds": 600}
}
```
### `POST /api/v1/devices/{device_id}/commands/{command_id}/result`
Reports command success or failure. Calibration command results can include updated offset/factor values; the server applies them to `device_configs`.
**Auth:** `X-API-Key` (per-device key)
```json
{
"success": true,
"message": "Calibration applied",
"result": {
"scale1_factor": -7050.0
}
}
```
---
## App endpoints for HivePal
All app endpoints require both `X-HivePal-Service-Key` and an `Authorization: Bearer <hivepal-jwt>` header. The user is identified by the verified token's `sub` claim.
| Role | Permissions |
|---|---|
| `owner` | Full access, including member management and removal |
| `admin` | Read plus config/channel writes |
| `viewer` | Read-only access |
### `POST /api/v1/app/devices/claim`
Claims an unclaimed device by claim code. The device must have sent at least one measurement containing that claim code.
```json
{
"claim_code": "ABCD-1234",
"display_name": "Back garden scale",
"scale_1_display_name": "Hive A",
"scale_2_display_name": "Hive B"
}
```
Failure modes are reported separately, because they need different fixes:
| Status | Meaning |
|---|---|
| `404` | No device on this server has ever sent that claim code. Check the code, and check the device has uploaded at least once. |
| `409` | The code matches a device that is already claimed. If you are already a member it is in your device list; otherwise its owner must release it first (see below). |
### `GET /api/v1/app/devices`
Lists all devices the current user can access. Device objects include `device_id`, `display_name`, `claimed_at`, `last_seen_at`, `last_firmware_version`, `role`, and `channels`.
### `DELETE /api/v1/app/devices/{device_id}`
Removes the current user's membership. When that was the last member, the device is released — `claimed_at` is cleared and its claim code pairs it again.
```json
{ "status": "removed", "device_id": "hive_scale_01", "released": true }
```
`released` is `false` when other members still hold the device; it stays claimed for them and the claim code will not work until they leave too (or the owner releases it outright).
Measurements, config and channel names are kept, so re-claiming restores the history. To erase the data as well, use the local dashboard's device delete.
### `DELETE /api/v1/app/devices/{device_id}/claim`
Owner only. Releases the device outright: removes **every** member and clears `claimed_at`, so it can be claimed again with its claim code. Use this instead of removing yourself when a shared device needs to be re-paired or handed on — otherwise it stays claimed until each member happens to remove themselves.
```json
{ "status": "released", "device_id": "hive_scale_01", "members_removed": 3 }
```
Readings, config and channel names are untouched; only the pairing is undone.
### `GET /api/v1/app/devices/{device_id}/channels`
Returns channel display names for scale 1 and scale 2.
### `PATCH /api/v1/app/devices/{device_id}/channels`
Updates channel display names. Requires `owner` or `admin`.
```json
{
"scale_1_display_name": "Buckfast colony",
"scale_2_display_name": "Carnica colony"
}
```
### `GET /api/v1/app/devices/{device_id}/config`
Returns the same device config schema as the device-facing config endpoint. Any role may read.
### `PATCH /api/v1/app/devices/{device_id}/config`
Updates config fields. Requires `owner` or `admin`. Accepts the `tempco_*`
temperature-compensation fields in addition to the calibration fields.
### `POST /api/v1/app/devices/{device_id}/temp-compensation/fit`
Fits a load-cell temperature coefficient from the device's own history by
regressing a scale's raw weight against an EMA-smoothed temperature channel (the
same smoothing applied at read time). A plain fit needs
`viewer`; persisting it (`apply: true`) needs `owner`/`admin`. See
[temperature-compensation.md](temperature-compensation.md).
```json
{
"scale": 1,
"lookback_days": 3,
"temp_source": "ambient",
"calibration_mode_only": false,
"apply": true,
"set_ref_temp": false
}
```
`scale` is a hive index, 1–18. Hives 1–2 are fitted from the `measurements`
table's weight columns, hives 3+ from their `hive_readings` rows.
Returns the fit (`coeff_kg_per_c`, `ref_temp_c`, `r_squared`, sample count and
temperature span). When `apply` is true and the fit succeeds, the coefficient and
source are written to the config and compensation is enabled — into
`scale{1,2}_tempco_kg_per_c` for hives 1–2, and into that hive's `hive_scales`
entry for hives 3+.
`tempco_ref_temp_c` is **not** touched unless `set_ref_temp` is true. The
reference is the temperature at which the scale reads true (the one it was tared
and spanned at), which a regression cannot recover; the returned `ref_temp_c` is
just the window's mean temperature, offered as a fallback when the calibration
temperature is unknown.
### `GET /api/v1/app/devices/{device_id}/measurements`
Returns measurements for one device.
| Query parameter | Default | Max | Description |
|---|---:|---:|---|
| `limit` | 200 | 10000 | Number of rows |
| `start_at` | - | - | ISO datetime lower bound |
| `end_at` | - | - | ISO datetime upper bound |
The response includes off-grid fields when the firmware sends them, plus
`scale_{n}_weight_kg_compensated` for every hive (mirrored onto each `hives[]`
entry as `weight_kg_compensated`) and a `tempco_applied` flag. The compensated values apply the per-device coefficient to
an EMA-smoothed temperature (see
[temperature-compensation.md](temperature-compensation.md)). When compensation is
disabled the compensated values equal the raw weights and `tempco_applied` is
`false`.
### `GET /api/v1/app/devices/{device_id}/measurements/latest`
Returns the newest measurements for one device.
| Query parameter | Default | Max | Description |
|---|---:|---:|---|
| `limit` | 50 | 500 | Number of rows |
### `POST /api/v1/app/devices/{device_id}/measurements/import`
Bulk-imports measurements parsed from a device's SD card backup
(`measurements.ndjson` / the AP-mode `hivescale-sd-data.tar` download). Used by
the HivePal web UI's "Import SD card data" button. Requires `owner` or `admin`
on the device — devices are never auto-created from uploaded data.
The request body is the same measurement objects as `POST /api/v1/measurements`,
wrapped in a list (max 20000 per request; `device_id` is taken from the URL and
forced onto every row):
```json
{
"measurements": [
{ "timestamp": "2025-01-15T14:30:45Z", "scale_1_weight_kg": 42.1 },
{ "timestamp": "2025-01-15T14:40:45Z", "scale_1_weight_kg": 42.3 }
]
}
```
Import is idempotent: `(device_id, measured_at)` is the natural key, so rows that
already exist — and rows repeated within the file — are skipped, not duplicated.
#### Response
```json
{
"status": "ok",
"device_id": "hive_scale_dual_01",
"received": 2,
"inserted": 2,
"duplicates": 0
}
```
### `GET /api/v1/app/devices/{device_id}/members`
Lists members and roles.
### `POST /api/v1/app/devices/{device_id}/members`
Shares a device with another HivePal user ID. Requires `owner`.
```json
{
"user_id": "user-002",
"role": "viewer"
}
```
### `DELETE /api/v1/app/devices/{device_id}/members/{user_id}`
Revokes another user's access. Requires `owner`.
### `POST /api/v1/app/devices/{device_id}/calibration/start`
Queues a `start_calibration_mode` command. Requires `owner` or `admin`. The body is optional.
| Field | Type | Default | Constraints |
|---|---|---|---|
| `interval_seconds` | int | 5 | 1 ≤ value ≤ 3600 |
| `timeout_seconds` | int | 600 | 1 ≤ value ≤ 86400 |
```json
{ "status": "pending", "id": 42, "command_type": "start_calibration_mode", "payload": { "interval_seconds": 5, "timeout_seconds": 600 } }
```
> The backend validates the ranges above; the firmware additionally clamps the
> interval to 2–30 s and the timeout to at most 30 minutes. See
> [calibration-mode.md](calibration-mode.md).
### `POST /api/v1/app/devices/{device_id}/calibration/stop`
Queues a `stop_calibration_mode` command. Requires `owner` or `admin`. No body.
```json
{ "status": "pending", "id": 43, "command_type": "stop_calibration_mode", "payload": {} }
```
<a id="inspections"></a>
## Inspections
The window while a beekeeper has a hive open, during which its own readings
measure the inspection rather than the colony. The hub keeps measuring and
uploading throughout; the backend records the window and keeps the readings
inside it out of charts, insights and alert rules. **Nothing is deleted** — the
export and each row's `raw_json` still carry the raw numbers. Full behaviour:
[inspection-mode.md](inspection-mode.md).
Each endpoint exists twice: under `/api/v1/devices/...` with the master
`X-API-Key`, and under `/api/v1/app/devices/...` with the HivePal service key
plus a user with the right role. The bodies and responses are identical.
Inspections are also readable and controllable from the local dashboard at
`/api/v1/local/devices/{device_id}/inspections[...]` (reads: any dashboard
session; start/stop/patch: admin).
### `POST /api/v1/devices/{device_id}/inspections/start`
**Auth:** `X-API-Key` · app variant requires `owner` or `admin`.
Body optional.
| Field | Type | Default | Meaning |
|---|---|---|---|
| `hives` | int[] | all hives | Scope the inspection to these hive indexes (1–18). Omit for the whole hub, which is what the physical button always means |
| `note` | string | – | Free text, e.g. `"removed 2 supers"` |
| `started_at` | ISO-8601 | now | Back-date the start. HivePal knows when the beekeeper actually opened the hive; the request may arrive minutes later over a bad rural connection |
Opens the window **and** queues a `start_inspection` command for the device.
Idempotent: calling it while an inspection is already open returns that
inspection and queues nothing.
```json
{
"id": 17, "device_id": "hive_scale_dual_01", "hives": null,
"started_at": "2026-06-01T12:00:00Z", "ended_at": null, "active": true,
"source": "api", "end_reason": null,
"requested_at": "2026-06-01T12:00:00Z", "acknowledged_at": null,
"note": "removed 2 supers", "created_by": "user-123"
}
```
`acknowledged_at` is `null` until the hub picks the command up. **That
distinction matters:** the hub deep-sleeps between cycles, so an inspection is
*requested* for up to a whole send interval before it is *running*. A UI that
renders the two the same is claiming something that has not happened yet.
### `POST /api/v1/devices/{device_id}/inspections/stop`
**Auth:** `X-API-Key` · app variant requires `owner` or `admin`.
Body optional: `note` (string), `ended_at` (ISO-8601, back-dates the end).
Closes the open window and queues a `stop_inspection` command. Returns the
closed inspection, or `null` if none was open — the command is queued either
way, because a hub still flagging its readings with no matching record is the
one failure mode that silently blanks a hive.
### `GET /api/v1/devices/{device_id}/inspections/status`
Is this hub inspecting, and does it know it yet?
```json
{
"device_id": "hive_scale_dual_01",
"active": false,
"pending": true,
"inspection": { "id": 17, "...": "as above" },
"timeout_minutes": 60
}
```
| Field | Meaning |
|---|---|
| `active` | The hub has confirmed it: readings are being masked right now |
| `pending` | Requested, not yet picked up by the hub |
| `timeout_minutes` | After this long, hub and server both end the inspection (`end_reason: "timeout"`). Configured per device as `inspection_timeout_minutes` |
### `GET /api/v1/devices/{device_id}/inspections`
Inspections **overlapping** a time range — what a chart shades.
| Query | Default | Meaning |
|---|---|---|
| `start_at` / `end_at` | unbounded | ISO-8601 range. Overlap, not containment: an inspection that started before the window is exactly the one explaining the step at its left edge |
| `limit` | 200 | 1–2000 |
### `PATCH /api/v1/devices/{device_id}/inspections/{inspection_id}`
Sets the `note` on a recorded inspection. Requires `owner` or `admin` on the app
variant.
```json
{ "note": "removed 2 supers, replaced queen excluder" }
```
### `POST /api/v1/app/devices/{device_id}/firmware`
Uploads a firmware binary as `multipart/form-data` and registers it as a release.
Requires `owner` or `admin`. Unlike `POST /api/v1/firmware/releases` (device key,
file must already be in `FIRMWARE_DIR`), this endpoint accepts the binary itself,
writes it into `FIRMWARE_DIR`, computes its CRC-32, and upserts the release.
The release is **scoped to the device's owner** (`owner_user_id`), so only scales
owned by the same user are offered it — the upload no longer reaches the whole
fleet. Pushing a global / official build is still done with the master-key
`POST /api/v1/firmware/releases`, which leaves the release un-owned.
| Form field | Required | Description |
|---|---:|---|
| `file` | Yes | The firmware binary |
| `version` | Yes | Release version string |
| `target` | No | `hivescale` (default), `hiveinside` or `beecounter`. **`hivehub` is accepted as an alias for `hivescale`** and is stored as `hivescale`, so HiveHub firmware needs no special handling. |
| `active` | No | Whether the release is active (default `true`) |
```json
{
"status": "ok",
"version": "0.9.3",
"filename": "hivescale-0.9.3.bin",
"target": "hivescale",
"active": true,
"size_bytes": 1048576,
"crc32": 2882343476
}
```
> **Uploading only registers the release; it does not start a relay or auto-flash.**
> For a `hivescale` target the owner must still approve the update per device (see
> `firmware/status` and `firmware/approve` below) before any scale installs it. For
> a `hiveinside` target, queue the OTA with the trigger endpoint
> below after the upload. Releases are unique per `(owner, target, version)`, so the
> same version number can coexist across owners and across
> `hivescale`/`hiveinside`.
### `GET /api/v1/app/devices/{device_id}/firmware/status`
Reports the device's firmware-update status for the HivePal setup panel. Any role
may read. `current_version` is what the device last reported; `latest_version` is
the newest active `hivescale` release resolved owner-first (the owner's own build,
else a global/official one). `update_available` means `latest_version` is newer
than `current_version`; `pending_approval` means an update is available but the
owner has not approved it yet, so the device will **not** auto-flash until they do.
```json
{
"device_id": "hive_scale_dual_01",
"target": "hivescale",
"current_version": "0.9.2",
"latest_version": "0.9.3",
"latest_is_official": false,
"approved_version": null,
"update_available": true,
"pending_approval": true
}
```
### `POST /api/v1/app/devices/{device_id}/firmware/approve`
Approves the latest available `hivescale` firmware so this device may install it —
the accept-to-apply step behind the HivePal panel's "Apply update" button. Records
the approved version (so the device-facing firmware check starts returning
`update: true` for this device) and queues an `ota_update` command to nudge the
scale to update on its next check-in instead of waiting for its scheduled OTA poll.
Requires `owner` or `admin`. Returns `404` if there is no release available.
```json
{ "status": "approved", "device_id": "hive_scale_dual_01", "version": "0.9.3", "command_id": 88 }
```
### `POST /api/v1/app/devices/{device_id}/commands/update-hiveinside`
Queues an `update_hiveinside` command so the HiveHub relays the active HiveInside
release to the paired sensor over BLE. This is the app-facing counterpart of the
device-key `…/commands/update-hiveinside` helper; it authenticates with the HivePal
service key + user JWT and requires `owner` or `admin` on the device.
| Query parameter | Default | Description |
|---|---|---|
| `slot` | `1` | Hive index (`1`..`18`) carrying the HiveInside to update |
| `force` | `false` | Relay even when the release is not newer than the running version |
Same slot semantics and version gate as the device-key endpoint above: `400` for
a slot outside `1..18`, `404` when no active `hiveinside` release exists, `409`
when the release is not newer than the version the node advertises.
```json
{ "status": "pending", "id": 72, "command_type": "update_hiveinside", "payload": { "slot": 1 }, "version": "0.4.1", "current_version": "0.4.0" }
```
### `POST /api/v1/app/devices/{device_id}/commands/update-beecounter`
The HiveTraffic counter equivalent of the endpoint above: same auth (HivePal
service key + user JWT, `owner`/`admin` on the device), same query parameters,
same slot semantics and version gate. Note the counter stops counting for the
duration of the transfer.
```json
{ "status": "pending", "id": 73, "command_type": "update_beecounter", "payload": { "slot": 1 }, "version": "0.2.0", "current_version": "0.1.0" }
```
### `GET /api/v1/app/devices/{device_id}/insights`
Computes rule-based colony alerts over recent measurements. Any role may read.
See [insights.md](insights.md) for the detector catalogue and literature sources.
| Query parameter | Default | Constraints | Description |
|---|---|---|---|
| `lookback_days` | 14 | 1 ≤ value ≤ 90 | Days of history evaluated |
```json
{
"device_id": "hive_scale_dual_01",
"computed_at": "2026-05-01T12:00:00+00:00",
"lookback_days": 14,
"measurement_count": 1280,
"alerts": [ { "severity": "watch", "category": "swarm", "title": "Pre-swarm watch", "...": "..." } ]
}
```
### `GET /api/v1/app/devices/{device_id}/insights/summary`
Highest-severity summary of current alerts (fixed 14-day lookback), suitable for dashboard cards.
```json
{
"device_id": "hive_scale_dual_01",
"computed_at": "2026-05-01T12:00:00+00:00",
"alert_count": 3,
"highest_severity": "warning",
"highest_alert": { "severity": "warning", "category": "swarm", "...": "..." },
"categories": { "swarm": 1, "foraging": 1, "brood": 1 }
}
```
### `GET /api/v1/app/devices/{device_id}/insights/history`
Persisted **history** of insight alerts for the device. Unlike `/insights`
(which recomputes the *current* state on each call and stores nothing), this
returns the stored lifecycle of every alert the backend has observed —
including ones that have since resolved — newest first. Any role may read.
Alert lifecycle is reconciled by a background thread (see
`INSIGHTS_RECONCILE_*` in [.env.example](../server/.env.example)) and
opportunistically whenever `/insights/summary` is hit. While a detector keeps
firing the same row is updated (`last_seen_at` bumped, `peak_severity`
tracked); when it stops firing the row is resolved (`resolved_at` set). A later
recurrence of the same detector starts a new row.
| Query parameter | Default | Constraints | Description |
|---|---|---|---|
| `status` | `all` | `all` \| `active` \| `resolved` | Filter by lifecycle state |
| `category` | — | swarm, queenless, robbing, … | Filter by detector category |
| `since` | — | ISO 8601 | Only alerts last seen at/after this time |
| `limit` | 100 | 1 ≤ value ≤ 500 | Max rows returned |
```json
{
"device_id": "hive_scale_dual_01",
"lookback_days": 14,
"count": 2,
"active_count": 1,
"alerts": [
{
"id": 42,
"alert_key": "swarm-watch-ch1",
"category": "swarm",
"channel": 1,
"severity": "watch",
"peak_severity": "warning",
"title": "Pre-swarm watch (hive 1)",
"description": "...",
"confidence": 0.65,
"evidence": { "...": "..." },
"source": "project spec Phase 1; MSPB arXiv 2311.10876",
"window_start": "2026-04-30T00:00:00+00:00",
"window_end": "2026-05-01T12:00:00+00:00",
"first_seen_at": "2026-04-30T08:15:00+00:00",
"last_seen_at": "2026-05-01T12:00:00+00:00",
"resolved_at": null,
"status": "active",
"update_count": 7
}
]
}
```
---
## Database schema
The backend auto-creates and updates the schema on startup.
| Table | Description |
|---|---|
| `devices` | Device identity, claim status, per-device API key hash, display name, last seen, firmware version, and the owner-approved firmware version (accept-to-apply gate) |
| `device_members` | Users with `owner`, `admin`, or `viewer` role per device |
| `device_channels` | Display names for scale channel 1 and 2 |
| `device_configs` | Send interval, offsets, calibration factors, config version, bee-counter night mode |
| `measurements` | Measurement records, including power/acoustic/bee-counter columns and `raw_json` |
| `firmware_releases` | Firmware versions available for OTA, with `target`, `crc32`, and `owner_user_id` (NULL = global/official; otherwise the owner the release is private to) |
| `device_commands` | Pending, claimed, done, and failed commands, with the `attempts` counter used to recover abandoned claims |
| `insight_alerts` | Persisted lifecycle of insight alerts (first/last seen, peak severity, resolution) powering the history endpoint |
The backend creates the full schema on startup and runs idempotent `ALTER TABLE … ADD COLUMN IF NOT EXISTS` statements, so existing deployments upgrade automatically. Columns cover power telemetry (battery/solar), calibration mode, boot count, time source, INMP441 acoustic levels + FFT bands, per-hive HiveTraffic bee-counter counts (BLE/GATT), load-cell temperature-compensation config, per-hive vibration bands, in-hive BLE humidity/pressure, the beehivemonitoring.com `hiveheart_*` / `hivescale_*` fields, the normalized per-hive `hive_readings` table (multi-hive payloads), and the dashboard-auth tables (`dashboard_users`, `dashboard_settings`, `push_subscriptions`); `firmware_releases` gains `target`, `crc32`, `owner_user_id`, and `board`; `device_commands` gains `attempts`. The SQL files in `server/migrations/` (`001_offgrid_telemetry.sql` through `021_device_command_attempts.sql`) can also be applied manually. All fields remain available in `raw_json` for forward compatibility.
---
## Error responses
FastAPI errors are returned as JSON:
```json
{ "detail": "No unclaimed device found with that claim code" }
```
| Status | Meaning |
|---:|---|
| 400 | Bad request or invalid command payload |
| 401 | Missing or invalid API key / service key / bearer token |
| 403 | Insufficient device role |
| 404 | Resource not found |
| 500 | Server misconfiguration or unexpected backend error |
695b4ef90This file is pinned to the selected release. Download the original to open it in your design tool.