"""Request and response shapes for the JSON APIs. FastAPI validates incoming JSON against these and documents them at /docs.""" import json from datetime import datetime from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field, field_validator MAX_EVENTS_PER_SYNC = 500 UNIX_2100 = 4_102_444_800 # ------------------------------------------------------------------ device API class DeviceEventIn(BaseModel): seq: int = Field(ge=0, le=2**31 - 1, description="Per-device counter, +1 for every press. Kept in NVS.") time: int = Field(ge=0, le=UNIX_2100, description="When pressed: UNIX seconds (UTC) from the RTC.") button: int = Field(ge=0, le=255, description="Button number, 1-8.") class SyncRequest(BaseModel): model_config = ConfigDict( json_schema_extra={ "example": { "device_time": 1760630400, "firmware": "0.1.0", "battery_mv": 3987, "charging": False, "rssi": -61, "boot_count": 42, "queue_len": 0, "events": [ {"seq": 101, "time": 1760620000, "button": 6}, {"seq": 102, "time": 1760627000, "button": 6}, {"seq": 103, "time": 1760627100, "button": 4}, ], } } ) device_time: int | None = Field( None, ge=0, le=UNIX_2100, description="The RTC's current time (UNIX s, UTC), read just before sending." ) firmware: str | None = Field(None, max_length=32) battery_mv: int | None = Field(None, ge=0, le=10_000, description="Cell voltage in millivolts.") charging: bool | None = Field(None, description="USB power present (MCP23017 GPB1).") rssi: int | None = Field(None, ge=-127, le=0, description="Wi-Fi signal, dBm.") boot_count: int | None = Field(None, ge=0) queue_len: int | None = Field(None, ge=0, description="Presses still waiting on the device after this batch.") events: list[DeviceEventIn] = Field(default_factory=list, max_length=MAX_EVENTS_PER_SYNC) diag: dict[str, Any] | None = Field(None, description="Anything else worth logging. Stored as-is, max 2 kB.") @field_validator("diag") @classmethod def _small_diag(cls, v: dict[str, Any] | None) -> dict[str, Any] | None: if v is not None and len(json.dumps(v)) > 2048: raise ValueError("diag is larger than 2 kB") return v class ButtonOut(BaseModel): button: int kind: str | None label: str short: str emoji: str mode: Literal["instant", "duration"] class LastOut(BaseModel): kind: str short: str time: int class OpenOut(BaseModel): kind: str short: str since: int class TodayOut(BaseModel): feeds: int wet: int dirty: int sleep_min: int class DisplayStatus(BaseModel): """Everything the e-paper needs. Times are UNIX seconds; the device turns them into "2h 10m ago" with its own clock, so the text stays right between syncs.""" baby_name: str last_feed: LastOut | None next_side: Literal["L", "R"] | None last_diaper: LastOut | None open: list[OpenOut] today: TodayOut class SyncResponse(BaseModel): ok: bool = True server_time: int = Field(description="UNIX seconds (UTC). Set the RTC from this if it's off.") ack_seq: int | None = Field( description="Highest seq in this batch. Everything you sent is stored: delete it from the queue." ) received: int stored: int duplicates: int clock_skew_s: int | None = Field(description="Server time minus device_time. Positive = device is behind.") clock_corrected: bool = Field(description="True if event times in this batch were shifted by clock_skew_s.") tz_offset_s: int = Field(description="Family's current UTC offset, for showing local time on the display.") sync_interval_s: int = Field(description="How long to wait before the next routine sync.") config_version: str = Field(description="Changes whenever the button layout changes.") buttons: list[ButtonOut] status: DisplayStatus # ------------------------------------------------------------------ dashboard API class KindOut(BaseModel): model_config = ConfigDict(from_attributes=True) slug: str label: str short: str emoji: str category: str mode: str max_minutes: int | None active: bool class EventOut(BaseModel): id: int kind: str label: str emoji: str category: str started_at: datetime ended_at: datetime | None duration_s: int | None note: str | None source: str device_id: int | None button: int | None clock_corrected: bool deleted: bool class EventCreate(BaseModel): kind: str started_at: datetime | None = Field(None, description="Defaults to now. Include a timezone offset.") ended_at: datetime | None = None note: str | None = Field(None, max_length=2000) class EventUpdate(BaseModel): kind: str | None = None started_at: datetime | None = None ended_at: datetime | None = None clear_end: bool = Field(False, description="Set true to reopen a session (remove its end time).") note: str | None = Field(None, max_length=2000) class DayOut(BaseModel): date: str feeds: int wet: int dirty: int pump: int sleep_min: int longest_sleep_min: int counts: dict[str, int]