"""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), )