Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
"""Device command queue (calibration, reboot, OTA relays to sub-devices)."""
from typing import Any, Optional
import psycopg
from fastapi import APIRouter, Depends, HTTPException, Query
from auth import require_api_key, require_device_key
from config import PUBLIC_BASE_URL
from db import get_conn
from devices import ensure_device_config, get_device_owner_id
from firmware import (
latest_release_for_owner,
parse_version,
reported_subdevice_version,
)
from schemas import MAX_HIVES, DeviceCommandIn, DeviceCommandResult
router = APIRouter()
# A claim older than this with no result is treated as abandoned. It has to clear
# the slowest legitimate case comfortably: the HiveHub only polls once per wake
# cycle, and a HiveInside relay streams a few hundred KB over BLE synchronously,
# so a genuine relay occupies the device for minutes — not tens of minutes.
STALE_CLAIM_MINUTES = 20
# How many times one command may be handed out before it is failed for good, so a
# command that reliably crashes the device cannot be retried forever.
MAX_COMMAND_ATTEMPTS = 3
# Only these are safe to hand out again after an abandoned claim. Re-running a
# relay is harmless — worst case the node receives the same image twice, and the
# version gate already refuses a pointless one. Everything else is left alone:
# silently repeating a factory_reset or reset_wifi because a result POST was lost
# would destroy device state the operator asked for exactly once.
RETRYABLE_COMMAND_TYPES = ("update_hiveinside", "update_beecounter")
# Relay targets, and the command each is delivered by. Both stream an image to a
# BLE sub-device through the same firmware path, differing only in UUIDs, so
# everything below is keyed off this rather than duplicated per target.
RELAY_COMMAND_TYPES = {
"hiveinside": "update_hiveinside",
"beecounter": "update_beecounter",
}
# What to call each target when explaining a refusal to a human.
RELAY_LABELS = {
"hiveinside": "HiveInside",
"beecounter": "HiveTraffic counter",
}
def expire_stale_claimed_commands() -> None:
"""Recover commands a device claimed and never reported on.
``next_command`` serves only ``pending`` rows, so a claim that is never
completed is invisible to every later poll: the command is never retried and
never fails. The device does not have to crash for this — ``postCommandResult``
is fire-and-forget, so a WiFi hiccup right after a multi-minute BLE relay
loses the outcome and strands the row just the same.
Retryable commands go back on the queue until ``MAX_COMMAND_ATTEMPTS``, then
fail with a stated reason; everything else fails on the first timeout rather
than being repeated. Either way the row reaches a terminal state, so the
dashboard can show what happened instead of a permanent "relaying…".
Cheap and idempotent — called before serving a command and before reading
relay state, so no background job is needed.
"""
with get_conn() as conn:
with conn.cursor() as cur:
# Hand it back to the queue for another try.
cur.execute(
"""
UPDATE device_commands
SET status = 'pending', claimed_at = NULL
WHERE status = 'claimed'
AND claimed_at < now() - (%s || ' minutes')::interval
AND command_type = ANY(%s)
AND attempts < %s;
""",
(STALE_CLAIM_MINUTES, list(RETRYABLE_COMMAND_TYPES), MAX_COMMAND_ATTEMPTS),
)
# Out of retries, or not safe to repeat: record why it ended.
cur.execute(
"""
UPDATE device_commands
SET status = 'failed',
completed_at = now(),
result = jsonb_build_object(
'success', false,
'message', 'timed out: claimed by the device '
|| attempts || ' time(s) without reporting a result')
WHERE status = 'claimed'
AND claimed_at < now() - (%s || ' minutes')::interval;
""",
(STALE_CLAIM_MINUTES,),
)
conn.commit()
def create_command(device_id: str, payload: DeviceCommandIn) -> dict:
ensure_device_config(device_id)
with get_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"""
INSERT INTO device_commands (device_id, command_type, payload)
VALUES (%s, %s, %s)
RETURNING id, status;
""",
(device_id, payload.command_type, psycopg.types.json.Jsonb(payload.payload)),
)
r = cur.fetchone()
conn.commit()
return {"id": r[0], "status": r[1]}
@router.post("/api/v1/devices/{device_id}/commands", dependencies=[Depends(require_api_key)])
def queue_command(device_id: str, payload: DeviceCommandIn):
result = create_command(device_id, payload)
return {"status": result["status"], "id": result["id"]}
def check_relay_slot(slot: int) -> int:
"""Validate the hive index an OTA relay targets.
`slot` is the hive index (1..MAX_HIVES): the HiveHub resolves it against its
hive registry, so every hive can be updated. It used to be capped at the two
legacy bleSensorMac0/1 globals, which is why hives 3+ could not be reached.
"""
if not 1 <= slot <= MAX_HIVES:
raise HTTPException(
status_code=400,
detail=f"slot must be a hive index between 1 and {MAX_HIVES}",
)
return slot
# Backwards-compatible alias (older name).
check_hiveinside_slot = check_relay_slot
def check_relay_is_newer(target: str, device_id: str, slot: int, version: str,
force: bool) -> Optional[str]:
"""Refuse to relay an image that is not newer than what the sub-device runs.
The node reports its running version, so a relay that would install the same
or an older build is a pointless multi-minute BLE transfer plus a reboot of a
healthy device — and for a HiveTraffic counter it also stops the counting for
the duration. It is refused with 409 rather than queued.
Returns the version currently reported for the slot (None when unknown). An
unknown version never blocks: a node that has never reported one cannot be
compared against, and an update may be exactly what it needs. `force` skips
the comparison entirely, for reflashing the same version after a reverted or
interrupted update.
"""
current = reported_subdevice_version(target, device_id, slot)
if force or current is None:
return current
if parse_version(version) > parse_version(current):
return current
label = RELAY_LABELS[target]
raise HTTPException(
status_code=409,
detail=(
f"{label} on hive {slot} already runs {current}; release {version} "
f"is not newer. Upload a higher version, or pass force=true to relay "
f"it anyway."
),
)
def check_hiveinside_is_newer(device_id: str, slot: int, version: str,
force: bool) -> Optional[str]:
"""Backwards-compatible wrapper (older name) for the hiveinside target."""
return check_relay_is_newer("hiveinside", device_id, slot, version, force)
def queue_relay_firmware_update(device_id: str, target: str,
command_type: str, slot: int,
force: bool = False) -> dict:
"""Queue a command telling the HiveHub to relay the active firmware for
``target`` to the sub-device in the given slot.
The image URL and its CRC-32 are looked up server-side (the latest active
release for the target) and embedded in the command payload so the HiveHub
can verify the download before relaying it. The CRC-32 is checked end-to-end
on the receiving device before it swaps slots, so a corrupted relay never
bricks it. Shared by the device-authenticated and HivePal-authenticated
command endpoints.
The release is resolved owner-first (the relaying HiveHub's owner), falling
back to a global release, so a sub-device only ever receives an image its
owner published or an official build.
Both relay targets are single-board, so no per-board matching is needed:
``hiveinside`` is unambiguously the nRF54LM20A and ``beecounter`` the
HiveTraffic ESP32-C6. Both are additionally gated on the version the target
node reports — see check_relay_is_newer — so only a genuinely newer image is
queued.
"""
owner_id = get_device_owner_id(device_id)
is_relay = target in RELAY_COMMAND_TYPES
if is_relay:
check_relay_slot(slot)
r = latest_release_for_owner(target, owner_id)
if not r:
raise HTTPException(status_code=404, detail=f"No active {target} firmware release")
version, filename, crc32 = r[0], r[1], r[2]
current = None
if is_relay:
current = check_relay_is_newer(target, device_id, slot, version, force)
url = f"{PUBLIC_BASE_URL}/firmware/{filename}" if PUBLIC_BASE_URL else f"/firmware/{filename}"
result = create_command(device_id, DeviceCommandIn(
command_type=command_type,
payload={"slot": slot, "url": url, "version": version, "crc32": int(crc32 or 0)},
))
# Echo what the relay will replace, so a caller can tell "0.4.0 -> 0.4.1" from
# "unknown -> 0.4.1" (a node that never reported a version) without a second
# request.
if is_relay:
result = {**result, "version": version, "current_version": current, "slot": slot}
return result
@router.post("/api/v1/devices/{device_id}/commands/update-hiveinside",
dependencies=[Depends(require_api_key)])
def queue_hiveinside_update(device_id: str, slot: int = Query(1),
force: bool = Query(False)):
"""Queue a relay of the active HiveInside firmware to the HiveInside sensor
on hive ``slot`` (any hive index, 1..MAX_HIVES) over BLE GATT. The HiveHub
resolves the BLE MAC from its hive registry, so only slot + image URL +
CRC-32 are sent.
Refused with 409 when the release is not newer than the version that node
advertises; ``force=true`` relays it regardless."""
return queue_relay_firmware_update(
device_id, "hiveinside", "update_hiveinside", slot, force
)
@router.post("/api/v1/devices/{device_id}/commands/update-beecounter",
dependencies=[Depends(require_api_key)])
def queue_beecounter_update(device_id: str, slot: int = Query(1),
force: bool = Query(False)):
"""Queue a relay of the active HiveTraffic firmware to the bee counter on
hive ``slot`` over BLE GATT.
Same contract as update-hiveinside above. Note the counter stops counting
bees for the duration of the transfer — it parks the IR emitters and pauses
gate polling while writing flash — so an unnecessary relay costs real data,
which is what the version gate exists to prevent. Refused with 409 when the
release is not newer than the version the counter reports; ``force=true``
relays it regardless."""
return queue_relay_firmware_update(
device_id, "beecounter", "update_beecounter", slot, force
)
def latest_relays(device_id: str, target: str) -> dict:
"""The most recent relay command for `target` per hive slot.
The relay already records a specific cause in ``result`` on failure
(``invalid firmware content length -1``, ``HiveInside not found in scan``,
``No HiveTraffic counter paired in slot N`` …), but nothing surfaced it: a
node that never updated looked identical whether the relay was queued and
pending, still running, or failing every single attempt with the same error.
Feeding this to the dashboard makes the difference visible without a database
query.
Keyed by slot as a string, since it comes from the JSON payload.
"""
command_type = RELAY_COMMAND_TYPES[target]
# Sweep first, so an abandoned relay reads as "timed out" (or is back on the
# queue) rather than showing "relaying…" indefinitely.
expire_stale_claimed_commands()
with get_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT DISTINCT ON (payload->>'slot')
payload->>'slot', status, result->>'message',
payload->>'version', created_at, completed_at
FROM device_commands
WHERE device_id = %s AND command_type = %s
ORDER BY payload->>'slot', created_at DESC;
""",
(device_id, command_type),
)
rows = cur.fetchall()
return {
r[0]: {
"status": r[1],
"message": r[2],
"version": r[3],
"created_at": r[4],
"completed_at": r[5],
}
for r in rows if r[0]
}
def latest_hiveinside_relays(device_id: str) -> dict:
"""Backwards-compatible wrapper (older name)."""
return latest_relays(device_id, "hiveinside")
def latest_beecounter_relays(device_id: str) -> dict:
return latest_relays(device_id, "beecounter")
@router.get("/api/v1/devices/{device_id}/commands/next", dependencies=[Depends(require_device_key)])
def next_command(device_id: str):
# Reclaim anything a device abandoned before looking for new work, so a lost
# result cannot park a command in 'claimed' forever.
expire_stale_claimed_commands()
with get_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT id, command_type, payload FROM device_commands
WHERE device_id = %s AND status = 'pending'
ORDER BY created_at ASC
LIMIT 1
FOR UPDATE SKIP LOCKED;
""",
(device_id,),
)
r = cur.fetchone()
if not r:
conn.commit()
return {"command": False}
cur.execute(
"UPDATE device_commands SET status = 'claimed', claimed_at = now(), "
"attempts = attempts + 1 WHERE id = %s;",
(r[0],),
)
conn.commit()
return {"command": True, "id": r[0], "command_type": r[1], "payload": r[2]}
def apply_command_result_to_config(device_id: str, result: dict[str, Any]):
allowed = {
"scale1_offset",
"scale1_factor",
"scale2_offset",
"scale2_factor",
"tempco_enabled",
"tempco_source",
"tempco_ref_temp_c",
"scale1_tempco_kg_per_c",
"scale2_tempco_kg_per_c",
}
fields = {k: v for k, v in result.items() if k in allowed and v is not None}
if not fields:
return
assignments = [f"{k} = %({k})s" for k in fields]
assignments.append("config_version = config_version + 1")
assignments.append("updated_at = now()")
fields["device_id"] = device_id
with get_conn() as conn:
with conn.cursor() as cur:
cur.execute(
f"UPDATE device_configs SET {', '.join(assignments)} WHERE device_id = %(device_id)s;",
fields,
)
conn.commit()
@router.post("/api/v1/devices/{device_id}/commands/{command_id}/result", dependencies=[Depends(require_device_key)])
def command_result(device_id: str, command_id: int, payload: DeviceCommandResult):
if payload.success:
apply_command_result_to_config(device_id, payload.result)
with get_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"""
UPDATE device_commands
SET status = %s, result = %s, completed_at = now()
WHERE id = %s AND device_id = %s;
""",
(
"done" if payload.success else "failed",
psycopg.types.json.Jsonb(payload.model_dump()),
command_id,
device_id,
),
)
conn.commit()
return {"status": "ok"}
695b4ef90This file is pinned to the selected release. Download the original to open it in your design tool.