Initial commit with webpage
This commit is contained in:
commit
26875de1dd
55 files changed
+5726
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,114 @@
|
||||
"""Built-in event kinds, the default button layout, and first-run setup."""
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import get_settings
|
||||
from ..models import ButtonMap, Kind, Profile
|
||||
|
||||
NUM_BUTTONS = 8
|
||||
|
||||
# Category order is fixed: it decides each category's chart colour (series-1..7
|
||||
# in style.css). Sleep, feeding and diaper take the first three slots because
|
||||
# they share the rhythm chart, and those three stay distinguishable for
|
||||
# colour-blind readers.
|
||||
CATEGORIES: dict[str, str] = {
|
||||
"sleep": "Sleep",
|
||||
"feeding": "Feeding",
|
||||
"diaper": "Diapers",
|
||||
"pump": "Pumping",
|
||||
"health": "Health",
|
||||
"activity": "Activity",
|
||||
"other": "Other",
|
||||
}
|
||||
|
||||
DEFAULT_KINDS: list[dict] = [
|
||||
dict(slug="nurse_left", label="Nursing (left)", short="Nurse L", emoji="🤱", category="feeding"),
|
||||
dict(slug="nurse_right", label="Nursing (right)", short="Nurse R", emoji="🤱", category="feeding"),
|
||||
dict(slug="bottle", label="Bottle", short="Bottle", emoji="🍼", category="feeding"),
|
||||
dict(slug="solids", label="Solids", short="Solids", emoji="🥣", category="feeding"),
|
||||
dict(slug="wet", label="Wet diaper", short="Wet", emoji="💧", category="diaper"),
|
||||
dict(slug="dirty", label="Dirty diaper", short="Dirty", emoji="💩", category="diaper"),
|
||||
dict(slug="sleep", label="Sleep", short="Sleep", emoji="😴", category="sleep",
|
||||
mode="duration", max_minutes=12 * 60),
|
||||
dict(slug="pump", label="Pumping", short="Pump", emoji="🥛", category="pump"),
|
||||
dict(slug="medicine", label="Medicine", short="Meds", emoji="💊", category="health"),
|
||||
dict(slug="tummy_time", label="Tummy time", short="Tummy", emoji="🧸", category="activity",
|
||||
mode="duration", max_minutes=60),
|
||||
dict(slug="bath", label="Bath", short="Bath", emoji="🛁", category="activity"),
|
||||
dict(slug="other", label="Other", short="Other", emoji="📝", category="other"),
|
||||
]
|
||||
|
||||
# Button 1..8 on the board (SW1..SW8 = MCP23017 GPA0..GPA6, GPB0).
|
||||
DEFAULT_BUTTONS = ["nurse_left", "nurse_right", "bottle", "wet", "dirty", "sleep", "pump", "medicine"]
|
||||
|
||||
FALLBACK_KIND = "other" # presses from unassigned buttons land here
|
||||
|
||||
# Kinds the "next side" suggestion looks at.
|
||||
NURSE_SIDES = {"nurse_left": "L", "nurse_right": "R"}
|
||||
|
||||
|
||||
def ensure_defaults(db: Session) -> None:
|
||||
"""Create the profile row, built-in kinds and button layout if missing.
|
||||
|
||||
Safe to run on every start: it only adds what isn't there and never
|
||||
overwrites the parent's edits.
|
||||
"""
|
||||
if db.get(Profile, 1) is None:
|
||||
db.add(Profile(id=1, timezone=get_settings().default_timezone))
|
||||
|
||||
existing = set(db.scalars(select(Kind.slug)))
|
||||
for order, spec in enumerate(DEFAULT_KINDS):
|
||||
if spec["slug"] not in existing:
|
||||
db.add(Kind(**{"mode": "instant", "max_minutes": None, "sort_order": order * 10, **spec}))
|
||||
db.flush()
|
||||
|
||||
have_buttons = set(db.scalars(select(ButtonMap.button)))
|
||||
for n, slug in enumerate(DEFAULT_BUTTONS, start=1):
|
||||
if n not in have_buttons:
|
||||
db.add(ButtonMap(button=n, kind_slug=slug))
|
||||
db.commit()
|
||||
|
||||
|
||||
def get_profile(db: Session) -> Profile:
|
||||
profile = db.get(Profile, 1)
|
||||
if profile is None:
|
||||
ensure_defaults(db)
|
||||
profile = db.get(Profile, 1)
|
||||
return profile
|
||||
|
||||
|
||||
def all_kinds(db: Session, *, active_only: bool = False) -> list[Kind]:
|
||||
q = select(Kind).order_by(Kind.sort_order, Kind.label)
|
||||
if active_only:
|
||||
q = q.where(Kind.active.is_(True))
|
||||
return list(db.scalars(q))
|
||||
|
||||
|
||||
def button_map(db: Session) -> dict[int, Kind | None]:
|
||||
rows = db.scalars(select(ButtonMap).order_by(ButtonMap.button))
|
||||
mapping: dict[int, Kind | None] = {n: None for n in range(1, NUM_BUTTONS + 1)}
|
||||
for row in rows:
|
||||
mapping[row.button] = row.kind
|
||||
return mapping
|
||||
|
||||
|
||||
# Resting voltage -> charge for a single-cell LiPo. Approximate (the curve
|
||||
# varies with cell, temperature and load), but good enough for a gauge.
|
||||
_LIPO_CURVE = [
|
||||
(4200, 100), (4150, 95), (4110, 90), (4080, 85), (4020, 80), (3980, 75),
|
||||
(3950, 70), (3910, 65), (3870, 60), (3850, 55), (3840, 50), (3820, 45),
|
||||
(3800, 40), (3790, 35), (3770, 30), (3750, 25), (3730, 20), (3710, 15),
|
||||
(3690, 10), (3610, 5), (3270, 0),
|
||||
]
|
||||
|
||||
|
||||
def battery_percent(mv: int | None) -> int | None:
|
||||
if mv is None or mv <= 0:
|
||||
return None
|
||||
if mv >= _LIPO_CURVE[0][0]:
|
||||
return 100
|
||||
for (v_hi, p_hi), (v_lo, p_lo) in zip(_LIPO_CURVE, _LIPO_CURVE[1:]):
|
||||
if v_lo <= mv <= v_hi:
|
||||
return round(p_lo + (p_hi - p_lo) * (mv - v_lo) / (v_hi - v_lo))
|
||||
return 0
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Creating, editing and querying events. Shared by the device API, the JSON
|
||||
API and the dashboard, so a button press and a tap on the website behave the same."""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import Device, Event, Kind
|
||||
from ..timeutil import utcnow
|
||||
|
||||
# Longest session the queries look back for when a range starts mid-session.
|
||||
LOOKBACK = timedelta(days=1)
|
||||
|
||||
|
||||
def live() -> object:
|
||||
"""WHERE clause for events that haven't been deleted."""
|
||||
return Event.deleted_at.is_(None)
|
||||
|
||||
|
||||
def find_open_session(db: Session, kind: Kind, at: datetime) -> Event | None:
|
||||
"""The unfinished session of `kind` that a press at `at` would end, if any."""
|
||||
q = (
|
||||
select(Event)
|
||||
.where(live(), Event.kind_slug == kind.slug, Event.ended_at.is_(None), Event.started_at <= at)
|
||||
.order_by(Event.started_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
if kind.max_duration:
|
||||
q = q.where(Event.started_at >= at - kind.max_duration)
|
||||
return db.scalars(q).first()
|
||||
|
||||
|
||||
def apply_press(
|
||||
db: Session,
|
||||
kind: Kind,
|
||||
at: datetime,
|
||||
*,
|
||||
source: str,
|
||||
device: Device | None = None,
|
||||
button: int | None = None,
|
||||
note: str | None = None,
|
||||
clock_corrected: bool = False,
|
||||
) -> tuple[Event, str]:
|
||||
"""Record one press of `kind` at `at`. Returns (event, role).
|
||||
|
||||
Instant kinds: a new event (role "instant").
|
||||
Duration kinds: ends the open session if there is one ("end"), otherwise
|
||||
starts a new one ("start").
|
||||
"""
|
||||
if kind.is_duration:
|
||||
open_ev = find_open_session(db, kind, at)
|
||||
if open_ev is not None:
|
||||
open_ev.ended_at = at
|
||||
db.flush()
|
||||
return open_ev, "end"
|
||||
|
||||
ev = Event(
|
||||
kind=kind,
|
||||
started_at=at,
|
||||
source=source,
|
||||
device_id=device.id if device else None,
|
||||
button=button,
|
||||
note=note,
|
||||
clock_corrected=clock_corrected,
|
||||
)
|
||||
db.add(ev)
|
||||
db.flush()
|
||||
return ev, "start" if kind.is_duration else "instant"
|
||||
|
||||
|
||||
def events_between(
|
||||
db: Session,
|
||||
start: datetime,
|
||||
end: datetime,
|
||||
*,
|
||||
categories: set[str] | None = None,
|
||||
) -> list[Event]:
|
||||
"""Live events that overlap [start, end), oldest first."""
|
||||
q = (
|
||||
select(Event)
|
||||
.join(Event.kind)
|
||||
.where(live(), Event.started_at < end, Event.started_at >= start - LOOKBACK)
|
||||
.order_by(Event.started_at)
|
||||
)
|
||||
if categories:
|
||||
q = q.where(Kind.category.in_(categories))
|
||||
out = []
|
||||
for ev in db.scalars(q):
|
||||
if ev.started_at >= start or effective_end(ev) > start:
|
||||
out.append(ev)
|
||||
return out
|
||||
|
||||
|
||||
def effective_end(ev: Event, now: datetime | None = None) -> datetime:
|
||||
"""Where to draw/count a session up to. Open sessions run until now, capped
|
||||
at the kind's maximum so a forgotten stop doesn't count as 3 days of sleep."""
|
||||
if ev.ended_at is not None:
|
||||
return ev.ended_at
|
||||
if not ev.kind.is_duration:
|
||||
return ev.started_at
|
||||
end = now or utcnow()
|
||||
if ev.kind.max_duration:
|
||||
end = min(end, ev.started_at + ev.kind.max_duration)
|
||||
return max(end, ev.started_at)
|
||||
|
||||
|
||||
def is_stale(ev: Event, now: datetime | None = None) -> bool:
|
||||
"""An open session that has run past its kind's maximum: probably a forgotten stop."""
|
||||
if not ev.is_open or not ev.kind.max_duration:
|
||||
return False
|
||||
return (now or utcnow()) - ev.started_at > ev.kind.max_duration
|
||||
|
||||
|
||||
def open_sessions(db: Session) -> list[Event]:
|
||||
q = (
|
||||
select(Event)
|
||||
.join(Event.kind)
|
||||
.where(live(), Event.ended_at.is_(None), Kind.mode == "duration")
|
||||
.order_by(Event.started_at.desc())
|
||||
)
|
||||
return list(db.scalars(q))
|
||||
|
||||
|
||||
def recent_events(db: Session, limit: int = 10) -> list[Event]:
|
||||
q = select(Event).where(live()).order_by(Event.started_at.desc()).limit(limit)
|
||||
return list(db.scalars(q))
|
||||
|
||||
|
||||
def search_events(
|
||||
db: Session,
|
||||
*,
|
||||
before: datetime | None = None,
|
||||
after: datetime | None = None,
|
||||
categories: set[str] | None = None,
|
||||
kinds: set[str] | None = None,
|
||||
include_deleted: bool = False,
|
||||
limit: int = 200,
|
||||
) -> list[Event]:
|
||||
"""Newest first."""
|
||||
q = select(Event).join(Event.kind).order_by(Event.started_at.desc()).limit(limit)
|
||||
if not include_deleted:
|
||||
q = q.where(live())
|
||||
if before:
|
||||
q = q.where(Event.started_at < before)
|
||||
if after:
|
||||
q = q.where(or_(Event.started_at >= after, Event.ended_at >= after))
|
||||
if categories:
|
||||
q = q.where(Kind.category.in_(categories))
|
||||
if kinds:
|
||||
q = q.where(Event.kind_slug.in_(kinds))
|
||||
return list(db.scalars(q))
|
||||
|
||||
|
||||
class EventError(ValueError):
|
||||
"""Invalid input from a form or the API; the message is shown to the user."""
|
||||
|
||||
|
||||
def validate_times(kind: Kind, started_at: datetime, ended_at: datetime | None) -> None:
|
||||
now = utcnow()
|
||||
if started_at > now + timedelta(minutes=5):
|
||||
raise EventError("That time is in the future.")
|
||||
if ended_at is not None:
|
||||
if not kind.is_duration:
|
||||
raise EventError(f"{kind.label} doesn't have an end time.")
|
||||
if ended_at < started_at:
|
||||
raise EventError("The end is before the start.")
|
||||
if ended_at > now + timedelta(minutes=5):
|
||||
raise EventError("The end time is in the future.")
|
||||
|
||||
|
||||
def create_manual(
|
||||
db: Session, kind: Kind, started_at: datetime, ended_at: datetime | None, note: str | None
|
||||
) -> Event:
|
||||
validate_times(kind, started_at, ended_at)
|
||||
ev = Event(kind=kind, started_at=started_at, ended_at=ended_at, note=note or None, source="manual")
|
||||
db.add(ev)
|
||||
db.commit()
|
||||
return ev
|
||||
|
||||
|
||||
def update_event(
|
||||
db: Session,
|
||||
ev: Event,
|
||||
*,
|
||||
kind: Kind,
|
||||
started_at: datetime,
|
||||
ended_at: datetime | None,
|
||||
note: str | None,
|
||||
) -> Event:
|
||||
if not kind.is_duration:
|
||||
ended_at = None
|
||||
validate_times(kind, started_at, ended_at)
|
||||
ev.kind = kind
|
||||
ev.started_at = started_at
|
||||
ev.ended_at = ended_at
|
||||
ev.note = note or None
|
||||
db.commit()
|
||||
return ev
|
||||
|
||||
|
||||
def end_session(db: Session, ev: Event, at: datetime | None = None) -> Event:
|
||||
if not ev.is_open:
|
||||
raise EventError("That event is already finished.")
|
||||
ev.ended_at = max(at or utcnow(), ev.started_at)
|
||||
db.commit()
|
||||
return ev
|
||||
|
||||
|
||||
def delete_event(db: Session, ev: Event) -> None:
|
||||
ev.deleted_at = utcnow()
|
||||
db.commit()
|
||||
|
||||
|
||||
def restore_event(db: Session, ev: Event) -> None:
|
||||
ev.deleted_at = None
|
||||
db.commit()
|
||||
@@ -0,0 +1,262 @@
|
||||
"""Device sync: store a batch of presses exactly once, turn them into events,
|
||||
and tell the device what to show.
|
||||
|
||||
The contract with the firmware, in one line: **HTTP 200 means every press in
|
||||
the batch is safely stored, so delete them all from the device's queue.**
|
||||
Anything else (timeout, 5xx, no Wi-Fi) means keep them and retry later;
|
||||
retries are harmless because duplicates are recognised and skipped.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import secrets
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import Device, DeviceReport, Kind, Press, Profile
|
||||
from ..schemas import (
|
||||
ButtonOut,
|
||||
DisplayStatus,
|
||||
LastOut,
|
||||
OpenOut,
|
||||
SyncRequest,
|
||||
SyncResponse,
|
||||
TodayOut,
|
||||
)
|
||||
from ..timeutil import from_unix, safe_zone, unix, utcnow
|
||||
from .catalog import FALLBACK_KIND, button_map, get_profile
|
||||
from .events import apply_press
|
||||
from .stats import build_summary, is_stale
|
||||
|
||||
log = logging.getLogger("mamadachi.sync")
|
||||
|
||||
# Below this the device clock is "right" (RV-3028 drifts ~1 ppm, a few s/month).
|
||||
CLOCK_TOLERANCE = timedelta(minutes=2)
|
||||
|
||||
TOKEN_PREFIX = "mmd_"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- tokens
|
||||
|
||||
|
||||
def hash_token(token: str) -> str:
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
return TOKEN_PREFIX + secrets.token_urlsafe(24)
|
||||
|
||||
|
||||
def create_device(db: Session, name: str) -> tuple[Device, str]:
|
||||
"""Register a device. Returns (device, token); the token is shown once and never stored."""
|
||||
token = new_token()
|
||||
dev = Device(name=name.strip() or "Mamadachi", token_hash=hash_token(token), token_hint=token[-4:])
|
||||
db.add(dev)
|
||||
db.commit()
|
||||
return dev, token
|
||||
|
||||
|
||||
def rotate_token(db: Session, dev: Device) -> str:
|
||||
token = new_token()
|
||||
dev.token_hash = hash_token(token)
|
||||
dev.token_hint = token[-4:]
|
||||
dev.revoked_at = None
|
||||
db.commit()
|
||||
return token
|
||||
|
||||
|
||||
def device_for_token(db: Session, token: str) -> Device | None:
|
||||
if not token:
|
||||
return None
|
||||
dev = db.scalars(select(Device).where(Device.token_hash == hash_token(token))).first()
|
||||
return dev if dev is not None and dev.active else None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- sync
|
||||
|
||||
|
||||
@dataclass
|
||||
class IngestResult:
|
||||
received: int
|
||||
stored: int
|
||||
duplicates: int
|
||||
skew_s: int | None
|
||||
corrected: bool
|
||||
ack_seq: int | None
|
||||
|
||||
|
||||
def ingest(db: Session, device: Device, req: SyncRequest, received_at: datetime | None = None) -> IngestResult:
|
||||
"""Store a sync batch. Commits once at the end, so it's all-or-nothing."""
|
||||
t0 = utcnow()
|
||||
received_at = received_at or t0
|
||||
|
||||
skew = None
|
||||
if req.device_time is not None:
|
||||
skew = round((received_at - from_unix(req.device_time)).total_seconds())
|
||||
corrected = skew is not None and abs(skew) > CLOCK_TOLERANCE.total_seconds()
|
||||
|
||||
# The same press twice in one batch is a firmware bug, but harmless.
|
||||
batch = {(e.seq, e.time): e for e in req.events}
|
||||
existing: set[tuple[int, datetime]] = set()
|
||||
if batch:
|
||||
rows = db.execute(
|
||||
select(Press.seq, Press.device_time).where(
|
||||
Press.device_id == device.id,
|
||||
Press.seq.in_(sorted({seq for seq, _ in batch})),
|
||||
)
|
||||
)
|
||||
existing = {(seq, t) for seq, t in rows}
|
||||
|
||||
buttons = button_map(db)
|
||||
fallback: Kind | None = None
|
||||
new_presses: list[tuple[Press, int]] = []
|
||||
for (seq, t), e in batch.items():
|
||||
device_time = from_unix(t)
|
||||
if (seq, device_time) in existing:
|
||||
continue
|
||||
occurred = device_time + timedelta(seconds=skew) if corrected else device_time
|
||||
press_corrected = corrected
|
||||
if occurred > received_at + CLOCK_TOLERANCE:
|
||||
# A press "in the future" can't be right. Best guess: it just happened.
|
||||
occurred, press_corrected = received_at, True
|
||||
press = Press(
|
||||
device_id=device.id,
|
||||
seq=seq,
|
||||
button=e.button,
|
||||
device_time=device_time,
|
||||
occurred_at=occurred,
|
||||
received_at=received_at,
|
||||
clock_corrected=press_corrected,
|
||||
)
|
||||
new_presses.append((press, e.button))
|
||||
|
||||
# Oldest first, so a sleep start is seen before its stop.
|
||||
new_presses.sort(key=lambda pb: (pb[0].occurred_at, pb[0].seq))
|
||||
for press, button in new_presses:
|
||||
kind = buttons.get(button)
|
||||
note = None
|
||||
if kind is None or not kind.active:
|
||||
if fallback is None:
|
||||
fallback = db.get(Kind, FALLBACK_KIND)
|
||||
note = f"Button {button} has no event type assigned."
|
||||
kind = fallback
|
||||
ev, role = apply_press(
|
||||
db,
|
||||
kind,
|
||||
press.occurred_at,
|
||||
source="device",
|
||||
device=device,
|
||||
button=button,
|
||||
note=note,
|
||||
clock_corrected=press.clock_corrected,
|
||||
)
|
||||
press.role = role
|
||||
press.event_id = ev.id
|
||||
db.add(press)
|
||||
|
||||
device.last_seen_at = received_at
|
||||
device.firmware = req.firmware or device.firmware
|
||||
device.battery_mv = req.battery_mv
|
||||
device.charging = req.charging
|
||||
device.rssi = req.rssi
|
||||
device.clock_skew_s = skew
|
||||
device.boot_count = req.boot_count
|
||||
db.add(
|
||||
DeviceReport(
|
||||
device_id=device.id,
|
||||
received_at=received_at,
|
||||
firmware=req.firmware,
|
||||
battery_mv=req.battery_mv,
|
||||
charging=req.charging,
|
||||
rssi=req.rssi,
|
||||
clock_skew_s=skew,
|
||||
boot_count=req.boot_count,
|
||||
queue_len=req.queue_len,
|
||||
events_received=len(req.events),
|
||||
events_new=len(new_presses),
|
||||
duration_ms=round((utcnow() - t0).total_seconds() * 1000),
|
||||
extra=req.diag,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
result = IngestResult(
|
||||
received=len(req.events),
|
||||
stored=len(new_presses),
|
||||
duplicates=len(req.events) - len(new_presses),
|
||||
skew_s=skew,
|
||||
corrected=corrected,
|
||||
ack_seq=max((e.seq for e in req.events), default=None),
|
||||
)
|
||||
log.info(
|
||||
"sync device=%s received=%d stored=%d dup=%d skew=%ss battery=%smV rssi=%s",
|
||||
device.id, result.received, result.stored, result.duplicates, skew, req.battery_mv, req.rssi,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- response
|
||||
|
||||
|
||||
def config_for_device(db: Session) -> tuple[str, list[ButtonOut]]:
|
||||
buttons = []
|
||||
for n, kind in button_map(db).items():
|
||||
if kind is None or not kind.active:
|
||||
buttons.append(ButtonOut(button=n, kind=None, label="Unassigned", short="-", emoji="", mode="instant"))
|
||||
else:
|
||||
buttons.append(
|
||||
ButtonOut(button=n, kind=kind.slug, label=kind.label, short=kind.short, emoji=kind.emoji, mode=kind.mode)
|
||||
)
|
||||
blob = json.dumps([b.model_dump() for b in buttons], sort_keys=True, ensure_ascii=False)
|
||||
return hashlib.sha1(blob.encode()).hexdigest()[:8], buttons
|
||||
|
||||
|
||||
def display_status(db: Session, profile: Profile, now: datetime) -> DisplayStatus:
|
||||
s = build_summary(db, profile, now)
|
||||
last_feed = None
|
||||
if s.last_feed:
|
||||
first = s.last_feed.events[0]
|
||||
last_feed = LastOut(kind=first.kind_slug, short=first.kind.short, time=unix(s.last_feed.start))
|
||||
last_diaper = None
|
||||
if s.last_diaper:
|
||||
d = s.last_diaper
|
||||
last_diaper = LastOut(kind=d.kind_slug, short=d.kind.short, time=unix(d.started_at))
|
||||
return DisplayStatus(
|
||||
baby_name=profile.baby_name,
|
||||
last_feed=last_feed,
|
||||
next_side=s.next_side,
|
||||
last_diaper=last_diaper,
|
||||
open=[
|
||||
OpenOut(kind=e.kind_slug, short=e.kind.short, since=unix(e.started_at))
|
||||
for e in s.open
|
||||
if not is_stale(e, now)
|
||||
],
|
||||
today=TodayOut(
|
||||
feeds=s.today.feeds, wet=s.today.wet, dirty=s.today.dirty, sleep_min=round(s.today.sleep_min)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def sync_response(db: Session, result: IngestResult) -> SyncResponse:
|
||||
now = utcnow()
|
||||
profile = get_profile(db)
|
||||
offset = now.astimezone(safe_zone(profile.timezone)).utcoffset()
|
||||
version, buttons = config_for_device(db)
|
||||
return SyncResponse(
|
||||
server_time=unix(now),
|
||||
ack_seq=result.ack_seq,
|
||||
received=result.received,
|
||||
stored=result.stored,
|
||||
duplicates=result.duplicates,
|
||||
clock_skew_s=result.skew_s,
|
||||
clock_corrected=result.corrected,
|
||||
tz_offset_s=int(offset.total_seconds()) if offset else 0,
|
||||
sync_interval_s=profile.sync_interval_min * 60,
|
||||
config_version=version,
|
||||
buttons=buttons,
|
||||
status=display_status(db, profile, now),
|
||||
)
|
||||
@@ -0,0 +1,386 @@
|
||||
"""Turning the event log into answers: when did she last eat, how much did she
|
||||
sleep, what does a typical day look like. All computed in Python from a few
|
||||
hundred rows, so it works the same on SQLite and Postgres."""
|
||||
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, timedelta
|
||||
from statistics import mean, median
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import get_settings
|
||||
from ..models import Device, Event, Kind, Profile
|
||||
from ..timeutil import Formatter, fmt_duration, local_day_bounds, local_today, safe_zone, utcnow
|
||||
from .catalog import CATEGORIES, NURSE_SIDES, battery_percent
|
||||
from .events import effective_end, events_between, is_stale, live, open_sessions, recent_events
|
||||
|
||||
# Feeding presses this close together are one feed (left side, then right side).
|
||||
FEED_GAP = timedelta(minutes=30)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- feeds
|
||||
|
||||
|
||||
@dataclass
|
||||
class Feed:
|
||||
events: list[Event]
|
||||
|
||||
@property
|
||||
def start(self) -> datetime:
|
||||
return self.events[0].started_at
|
||||
|
||||
@property
|
||||
def sides(self) -> list[str]:
|
||||
return [NURSE_SIDES[e.kind_slug] for e in self.events if e.kind_slug in NURSE_SIDES]
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
parts: list[str] = []
|
||||
sides = self.sides
|
||||
if sides:
|
||||
parts.append("Nursing " + " → ".join(_dedupe_runs(sides)))
|
||||
for e in self.events:
|
||||
if e.kind_slug not in NURSE_SIDES and e.kind.label not in parts:
|
||||
parts.append(e.kind.label)
|
||||
return " + ".join(parts)
|
||||
|
||||
|
||||
def _dedupe_runs(items: list[str]) -> list[str]:
|
||||
out: list[str] = []
|
||||
for it in items:
|
||||
if not out or out[-1] != it:
|
||||
out.append(it)
|
||||
return out
|
||||
|
||||
|
||||
def group_feeds(events: list[Event]) -> list[Feed]:
|
||||
"""Group feeding events into feeds: a new feed starts after a FEED_GAP pause."""
|
||||
feeds: list[Feed] = []
|
||||
last: Event | None = None
|
||||
for ev in sorted((e for e in events if e.kind.category == "feeding"), key=lambda e: e.started_at):
|
||||
if last is None or ev.started_at - last.started_at > FEED_GAP:
|
||||
feeds.append(Feed([ev]))
|
||||
else:
|
||||
feeds[-1].events.append(ev)
|
||||
last = ev
|
||||
return feeds
|
||||
|
||||
|
||||
def next_side(feeds: list[Feed]) -> str | None:
|
||||
"""Suggest the breast to start on: the opposite of the last nursing feed's first side."""
|
||||
for feed in reversed(feeds):
|
||||
if feed.sides:
|
||||
return "R" if feed.sides[0] == "L" else "L"
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- per-day stats
|
||||
|
||||
|
||||
@dataclass
|
||||
class DayStats:
|
||||
day: date
|
||||
feeds: int = 0
|
||||
wet: int = 0
|
||||
dirty: int = 0
|
||||
pump: int = 0
|
||||
sleep_min: float = 0.0
|
||||
longest_sleep_min: float = 0.0
|
||||
naps: int = 0
|
||||
counts: Counter = field(default_factory=Counter)
|
||||
has_data: bool = False
|
||||
|
||||
@property
|
||||
def sleep_h(self) -> float:
|
||||
return self.sleep_min / 60
|
||||
|
||||
|
||||
def _days(first: date, last: date) -> list[date]:
|
||||
return [first + timedelta(days=i) for i in range((last - first).days + 1)]
|
||||
|
||||
|
||||
def daily_stats(db: Session, tz: ZoneInfo, first: date, last: date, now: datetime | None = None) -> list[DayStats]:
|
||||
now = now or utcnow()
|
||||
start, _ = local_day_bounds(first, tz)
|
||||
_, end = local_day_bounds(last, tz)
|
||||
events = events_between(db, start - FEED_GAP, end)
|
||||
stats = {d: DayStats(d) for d in _days(first, last)}
|
||||
|
||||
for feed in group_feeds(events):
|
||||
d = feed.start.astimezone(tz).date()
|
||||
if d in stats:
|
||||
stats[d].feeds += 1
|
||||
|
||||
for ev in events:
|
||||
start_day = ev.started_at.astimezone(tz).date()
|
||||
if start_day in stats:
|
||||
stats[start_day].has_data = True
|
||||
stats[start_day].counts[ev.kind_slug] += 1
|
||||
if ev.kind.is_duration:
|
||||
s, e = ev.started_at, effective_end(ev, now)
|
||||
minutes = (e - s).total_seconds() / 60
|
||||
if ev.kind.category == "sleep":
|
||||
if start_day in stats:
|
||||
stats[start_day].naps += 1
|
||||
stats[start_day].longest_sleep_min = max(stats[start_day].longest_sleep_min, minutes)
|
||||
# A night's sleep counts towards each day it covers.
|
||||
for d in _days(max(first, start_day), min(last, e.astimezone(tz).date())):
|
||||
d0, d1 = local_day_bounds(d, tz)
|
||||
overlap = (min(e, d1) - max(s, d0)).total_seconds() / 60
|
||||
if overlap > 0:
|
||||
stats[d].sleep_min += overlap
|
||||
stats[d].has_data = True
|
||||
elif start_day in stats:
|
||||
ds = stats[start_day]
|
||||
if ev.kind_slug == "wet":
|
||||
ds.wet += 1
|
||||
elif ev.kind_slug == "dirty":
|
||||
ds.dirty += 1
|
||||
elif ev.kind.category == "pump":
|
||||
ds.pump += 1
|
||||
|
||||
return [stats[d] for d in sorted(stats)]
|
||||
|
||||
|
||||
def averages(days: list[DayStats]) -> dict[str, float | None]:
|
||||
"""Mean per day over the days that have any data (so the days before the
|
||||
device arrived don't drag the averages down)."""
|
||||
with_data = [d for d in days if d.has_data]
|
||||
if not with_data:
|
||||
return {"feeds": None, "sleep_min": None, "wet": None, "dirty": None, "days": 0}
|
||||
return {
|
||||
"feeds": mean(d.feeds for d in with_data),
|
||||
"sleep_min": mean(d.sleep_min for d in with_data),
|
||||
"wet": mean(d.wet for d in with_data),
|
||||
"dirty": mean(d.dirty for d in with_data),
|
||||
"days": len(with_data),
|
||||
}
|
||||
|
||||
|
||||
def feed_intervals(feeds: list[Feed]) -> list[float]:
|
||||
"""Minutes between the starts of consecutive feeds (gaps over 12 h are ignored:
|
||||
those are missing data, not a real interval)."""
|
||||
gaps = [(b.start - a.start).total_seconds() / 60 for a, b in zip(feeds, feeds[1:])]
|
||||
return [g for g in gaps if g <= 12 * 60]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- rhythm chart
|
||||
|
||||
|
||||
@dataclass
|
||||
class Mark:
|
||||
cat: str # sleep | feeding | diaper | other
|
||||
shape: str # bar | dot | diamond | ring | tick
|
||||
left: float # % across the day
|
||||
width: float = 0.0
|
||||
tip: str = ""
|
||||
open: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class RhythmRow:
|
||||
day: date
|
||||
marks: list[Mark]
|
||||
now_pct: float | None = None
|
||||
|
||||
|
||||
RHYTHM_CATS = {"sleep", "feeding", "diaper"} # everything else is drawn as grey "other"
|
||||
|
||||
|
||||
def rhythm(db: Session, tz: ZoneInfo, f: Formatter, first: date, last: date, now: datetime | None = None) -> list[RhythmRow]:
|
||||
"""One row per day (newest first): sleep as bars, feeds as dots, diapers as diamonds."""
|
||||
now = now or utcnow()
|
||||
start, _ = local_day_bounds(first, tz)
|
||||
_, end = local_day_bounds(last, tz)
|
||||
events = events_between(db, start - FEED_GAP, end)
|
||||
rows = []
|
||||
for d in reversed(_days(first, last)):
|
||||
d0, d1 = local_day_bounds(d, tz)
|
||||
span = (d1 - d0).total_seconds() # 23 or 25 h on DST days
|
||||
|
||||
def pct(t: datetime) -> float:
|
||||
return max(0.0, min(100.0, (t - d0).total_seconds() / span * 100))
|
||||
|
||||
marks: list[Mark] = []
|
||||
for ev in events:
|
||||
cat = ev.kind.category
|
||||
if ev.kind.is_duration:
|
||||
s, e = ev.started_at, effective_end(ev, now)
|
||||
if e <= d0 or s >= d1:
|
||||
continue
|
||||
dur = fmt_duration((e - s).total_seconds())
|
||||
tip = f"{ev.kind.emoji} {ev.kind.label} · {f.time(s)}–{f.time(e) if ev.ended_at else 'now'} · {dur}"
|
||||
marks.append(
|
||||
Mark(
|
||||
cat=cat if cat == "sleep" else "other",
|
||||
shape="bar",
|
||||
left=pct(s),
|
||||
width=max(0.4, pct(e) - pct(s)),
|
||||
tip=tip,
|
||||
open=ev.ended_at is None,
|
||||
)
|
||||
)
|
||||
elif d0 <= ev.started_at < d1 and cat != "feeding":
|
||||
shape = "tick"
|
||||
if cat == "diaper":
|
||||
shape = "diamond" if ev.kind_slug == "dirty" else "ring"
|
||||
marks.append(
|
||||
Mark(
|
||||
cat=cat if cat in RHYTHM_CATS else "other",
|
||||
shape=shape,
|
||||
left=pct(ev.started_at),
|
||||
tip=f"{ev.kind.emoji} {ev.kind.label} · {f.time(ev.started_at)}",
|
||||
)
|
||||
)
|
||||
for feed in group_feeds(events):
|
||||
if d0 <= feed.start < d1:
|
||||
marks.append(
|
||||
Mark(
|
||||
cat="feeding",
|
||||
shape="dot",
|
||||
left=pct(feed.start),
|
||||
tip=f"{feed.events[0].kind.emoji} {feed.label} · {f.time(feed.start)}",
|
||||
)
|
||||
)
|
||||
# Bars first so dots and diamonds sit on top of them.
|
||||
marks.sort(key=lambda m: (m.shape != "bar", m.left))
|
||||
rows.append(RhythmRow(day=d, marks=marks, now_pct=pct(now) if d0 <= now < d1 else None))
|
||||
return rows
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the "Today" summary
|
||||
|
||||
|
||||
@dataclass
|
||||
class Alert:
|
||||
level: str # info | warning | serious
|
||||
text: str
|
||||
href: str | None = None
|
||||
link_text: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Summary:
|
||||
now: datetime
|
||||
tz: ZoneInfo
|
||||
last_feed: Feed | None
|
||||
next_side: str | None
|
||||
last_diaper: Event | None
|
||||
last_sleep: Event | None
|
||||
open: list[Event]
|
||||
today: DayStats
|
||||
avg: dict[str, float | None]
|
||||
feed_interval_min: float | None
|
||||
recent: list[Event]
|
||||
device: Device | None
|
||||
alerts: list[Alert]
|
||||
|
||||
@property
|
||||
def sleeping(self) -> Event | None:
|
||||
return next((e for e in self.open if e.kind.category == "sleep" and not is_stale(e, self.now)), None)
|
||||
|
||||
|
||||
def latest_in_category(db: Session, category: str, limit: int = 1) -> list[Event]:
|
||||
q = (
|
||||
select(Event)
|
||||
.join(Event.kind)
|
||||
.where(live(), Kind.category == category)
|
||||
.order_by(Event.started_at.desc())
|
||||
.limit(limit)
|
||||
)
|
||||
return list(db.scalars(q))
|
||||
|
||||
|
||||
def build_summary(db: Session, profile: Profile, now: datetime | None = None) -> Summary:
|
||||
now = now or utcnow()
|
||||
tz = safe_zone(profile.timezone)
|
||||
today = local_today(tz, now)
|
||||
|
||||
recent_feeding = list(reversed(latest_in_category(db, "feeding", limit=40)))
|
||||
feeds = group_feeds(recent_feeding)
|
||||
diapers = latest_in_category(db, "diaper")
|
||||
sleeps = latest_in_category(db, "sleep")
|
||||
|
||||
week = daily_stats(db, tz, today - timedelta(days=7), today, now)
|
||||
feeds_7d = [f for f in feeds if f.start >= now - timedelta(days=7)]
|
||||
intervals = feed_intervals(feeds_7d)
|
||||
|
||||
devices = list(db.scalars(select(Device).where(Device.revoked_at.is_(None))))
|
||||
devices.sort(key=lambda d: d.last_seen_at or d.created_at, reverse=True)
|
||||
opens = open_sessions(db)
|
||||
|
||||
return Summary(
|
||||
now=now,
|
||||
tz=tz,
|
||||
last_feed=feeds[-1] if feeds else None,
|
||||
next_side=next_side(feeds),
|
||||
last_diaper=diapers[0] if diapers else None,
|
||||
last_sleep=sleeps[0] if sleeps else None,
|
||||
open=opens,
|
||||
today=week[-1],
|
||||
avg=averages(week[:-1]),
|
||||
feed_interval_min=median(intervals) if intervals else None,
|
||||
recent=recent_events(db, 8),
|
||||
device=devices[0] if devices else None,
|
||||
alerts=build_alerts(devices, opens, profile, now),
|
||||
)
|
||||
|
||||
|
||||
def build_alerts(devices: list[Device], opens: list[Event], profile: Profile, now: datetime) -> list[Alert]:
|
||||
f = Formatter(safe_zone(profile.timezone), profile.clock_24h)
|
||||
alerts: list[Alert] = []
|
||||
settings = get_settings()
|
||||
if settings.is_production and not settings.login_required:
|
||||
alerts.append(Alert("serious", "This dashboard has no password. Set DASHBOARD_PASSWORD on your host."))
|
||||
|
||||
for ev in opens:
|
||||
if is_stale(ev, now):
|
||||
alerts.append(
|
||||
Alert(
|
||||
"warning",
|
||||
f"{ev.kind.label} started {f.when(ev.started_at)} was never stopped.",
|
||||
href=f"/events/{ev.id}",
|
||||
link_text="Fix the end time",
|
||||
)
|
||||
)
|
||||
|
||||
if not devices:
|
||||
alerts.append(Alert("info", "No Mamadachi is connected yet.", href="/device", link_text="Add a device"))
|
||||
for dev in devices:
|
||||
if dev.last_seen_at is None:
|
||||
alerts.append(Alert("info", f"{dev.name} hasn't synced yet.", href="/device", link_text="Setup steps"))
|
||||
continue
|
||||
silent = now - dev.last_seen_at
|
||||
if silent > timedelta(hours=max(24, 3 * profile.sync_interval_min / 60)):
|
||||
alerts.append(
|
||||
Alert(
|
||||
"warning",
|
||||
f"{dev.name} last synced {f.ago(dev.last_seen_at, now)}. Presses since then are still on the device.",
|
||||
href="/device",
|
||||
link_text="Device details",
|
||||
)
|
||||
)
|
||||
pct = battery_percent(dev.battery_mv)
|
||||
if pct is not None and not dev.charging and pct <= 20:
|
||||
alerts.append(
|
||||
Alert(
|
||||
"serious" if pct <= 10 else "warning",
|
||||
f"{dev.name} battery is at {pct}%. Charge it over USB-C.",
|
||||
)
|
||||
)
|
||||
if dev.clock_skew_s is not None and abs(dev.clock_skew_s) > 120:
|
||||
alerts.append(
|
||||
Alert(
|
||||
"info",
|
||||
f"{dev.name}'s clock was {fmt_duration(abs(dev.clock_skew_s))} off at its last sync; "
|
||||
"its event times were corrected.",
|
||||
)
|
||||
)
|
||||
return alerts
|
||||
|
||||
|
||||
def category_label(cat: str) -> str:
|
||||
return CATEGORIES.get(cat, cat.title())
|
||||
Reference in new issue
Block a user