"""Devices, their command queue, their telemetry and the firmware images. Field names follow firmware/API.md, which is the contract the firmware actually implements. Where SPEC.md 3 and API.md disagree, API.md wins and the difference is noted inline. """ from __future__ import annotations from datetime import datetime from sqlalchemy import ( BigInteger, Boolean, CheckConstraint, DateTime, Float, ForeignKey, Index, Integer, String, Text, func, ) from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.orm import Mapped, mapped_column, relationship from .base import Base COMMAND_TYPES = ( "apply_config", "capture_now", "report_status", "wake_and_hold", "sleep_now", "stream_start", "stream_stop", "ota_update", "reboot", ) STATUS_REASONS = ( "heartbeat", "periodic", "after_event", "before_sleep", "before_night_sleep", "on_request", ) class Device(Base): __tablename__ = "devices" id: Mapped[int] = mapped_column(Integer, primary_key=True) # eFuse MAC in hex. Survives reflashing, which is what makes it an # identity rather than a name (API.md, Enrollment). device_uid: Mapped[str] = mapped_column(String(32), unique=True, index=True) name: Mapped[str] = mapped_column(String(64)) mac: Mapped[str | None] = mapped_column(String(32)) hw_revision: Mapped[str | None] = mapped_column(String(64)) fw_version: Mapped[str | None] = mapped_column(String(32)) # Only the hash is stored. The token is high-entropy, so a fast hash is # defensible here (API.md). # # Indexed because every authenticated device request resolves a bearer # token by this column: it is the hottest lookup in the device API. # # Unique so that two devices can never end up sharing a token. NULLs stay # distinct in Postgres, so any number of devices may sit here un-enrolled # or revoked. token_hash: Mapped[str | None] = mapped_column(String(128), unique=True, index=True) # Per-device re-enrollment credential, so a rotated token cannot strand a # camera that has no USB access once mounted (SPEC 0). reenroll_secret_hash: Mapped[str | None] = mapped_column(String(128)) # --- last-known conditions, denormalised from device_status for the list view last_seen_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) battery_mv: Mapped[int | None] = mapped_column(Integer) battery_pct: Mapped[int | None] = mapped_column(Integer) # false means NOT MEASURED, not empty. No divider is wired by default. # Render as an em dash, never as a low-battery alarm (API.md, SPEC 0). battery_valid: Mapped[bool] = mapped_column(Boolean, default=False) rssi: Mapped[int | None] = mapped_column(Integer) temp_c: Mapped[float | None] = mapped_column(Float) # Reported every heartbeat so the UI can show command latency honestly (SPEC 0). awake: Mapped[bool] = mapped_column(Boolean, default=True) # --- settings surface # One JSONB document rather than forty columns. This mirrors GET /config # exactly: every key is optional and the device merges and clamps partial # documents, so a strict column-per-key schema would be a migration every # time the firmware gains a tunable. The UI edits it as a form; validation # lives in a Pydantic model, not in the DDL. config: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}") # The only thing the device compares. Bump on every config change. config_version: Mapped[int] = mapped_column(Integer, default=1, server_default="1") heartbeat_interval_s: Mapped[int] = mapped_column(Integer, default=300, server_default="300") status_interval_s: Mapped[int] = mapped_column(Integer, default=900, server_default="900") responsive_mode: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false") enabled: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true") created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) commands: Mapped[list[DeviceCommand]] = relationship( back_populates="device", cascade="all, delete-orphan" ) class DeviceCommand(Base): """SPEC C1: the device is never pushed to, it drains this queue. Commands ride along on the /ingest and /heartbeat response, so a capture that was going to happen anyway also delivers the queue at no extra cost. /status deliberately returns nothing actionable (API.md). """ __tablename__ = "device_commands" __table_args__ = ( CheckConstraint( "type IN " + str(COMMAND_TYPES), name="type_valid", ), CheckConstraint( "ack_status IS NULL OR ack_status IN ('done', 'failed', 'rejected')", name="ack_status_valid", ), Index("ix_device_commands_pending", "device_id", "created_at"), ) id: Mapped[int] = mapped_column(Integer, primary_key=True) device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE")) type: Mapped[str] = mapped_column(String(32)) payload: Mapped[dict | None] = mapped_column(JSONB) created_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL")) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) delivered_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) acked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) ack_status: Mapped[str | None] = mapped_column(String(16)) result: Mapped[str | None] = mapped_column(Text) expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) device: Mapped[Device] = relationship(back_populates="commands") class Firmware(Base): __tablename__ = "firmware" id: Mapped[int] = mapped_column(Integer, primary_key=True) version: Mapped[str] = mapped_column(String(32), unique=True) semver: Mapped[str | None] = mapped_column(String(32)) file_path: Mapped[str] = mapped_column(Text) sha256: Mapped[str] = mapped_column(String(64)) size_bytes: Mapped[int] = mapped_column(BigInteger) release_notes: Mapped[str | None] = mapped_column(Text) # SPEC C6 / API.md: the device refuses to flash below this. min_battery_pct: Mapped[int] = mapped_column(Integer, default=50, server_default="50") uploaded_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL")) uploaded_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now() ) is_target: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false") class DeviceStatus(Base): """Time series, one row per conditions report (SPEC 0). The flat columns are the ones worth querying and charting. ``raw`` keeps the whole posted body so nothing is lost when the firmware grows a field before the server learns about it. """ __tablename__ = "device_status" __table_args__ = ( CheckConstraint("reason IN " + str(STATUS_REASONS), name="reason_valid"), Index("ix_device_status_device_at", "device_id", "at"), ) id: Mapped[int] = mapped_column(BigInteger, primary_key=True) device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE")) at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) reason: Mapped[str] = mapped_column(String(32)) battery_mv: Mapped[int | None] = mapped_column(Integer) battery_pct: Mapped[int | None] = mapped_column(Integer) battery_valid: Mapped[bool | None] = mapped_column(Boolean) awake_ms: Mapped[int | None] = mapped_column(BigInteger) boot_count: Mapped[int | None] = mapped_column(Integer) wake_cause: Mapped[str | None] = mapped_column(String(16)) last_sleep_s: Mapped[int | None] = mapped_column(Integer) total_sleep_s: Mapped[int | None] = mapped_column(BigInteger) # The device's opinion, not the truth: these live in RTC memory and reset # on power loss. `captures` is authoritative. Their real value is the GAP # between captured and delivered, which is an upload-health signal. captured_today: Mapped[int | None] = mapped_column(Integer) delivered_today: Mapped[int | None] = mapped_column(Integer) failed_today: Mapped[int | None] = mapped_column(Integer) events_today: Mapped[int | None] = mapped_column(Integer) # Days since epoch, local time; stays 0 until the clock syncs, so the # pre-sync bucket is a phantom day. Do not chart it (API.md). day_index: Mapped[int | None] = mapped_column(Integer) is_night: Mapped[bool | None] = mapped_column(Boolean) nightlight_on: Mapped[bool | None] = mapped_column(Boolean) cam_profile: Mapped[str | None] = mapped_column(String(16)) # 0 here means no valid frame was decoded at any rate: wiring or a dead # module, and worth an alert (API.md). radar_baud: Mapped[int | None] = mapped_column(Integer) radar_uart_ok: Mapped[bool | None] = mapped_column(Boolean) stream_active: Mapped[bool | None] = mapped_column(Boolean) rssi: Mapped[int | None] = mapped_column(Integer) ip: Mapped[str | None] = mapped_column(String(45)) free_heap: Mapped[int | None] = mapped_column(BigInteger) free_psram: Mapped[int | None] = mapped_column(BigInteger) ring_depth: Mapped[int | None] = mapped_column(Integer) time_synced: Mapped[bool | None] = mapped_column(Boolean) device_time: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) fw_version: Mapped[str | None] = mapped_column(String(32)) config_version: Mapped[int | None] = mapped_column(Integer) raw: Mapped[dict | None] = mapped_column(JSONB)