"""Live device state. Weight channels kitchen — kitchen floor scale (ESP32 A) The return station (ESP32 B) is one of two layouts, chosen in settings["return_bins"]: two — rice, dish (dish bin with a strainer) five — children sort their own tray into five weighed bins: starch (rice, noodles, bread), veg, protein (meat, egg, tofu), fat (skin and visible fat pulled off the meat) and bone (bones, fish bones and other inedible parts of the dish, which are taken off what the dish served). Curry liquid goes through the strainer first; fruit and fruit peel go in the general bin, as fruit is not weighed when it is served either ESP32 boards POST readings. A channel with no device is fed by the simulator only after someone sets a value on /sim; a device that goes silent shows as offline and is never replaced by fake values. Voice box (legacy) The old 6-button box on ESP32 B. Teachers now tap opinions in the app; /api/vote stays for compatibility. """ from __future__ import annotations import os import random import threading import time TWO_BINS = ("rice", "dish") FIVE_BINS = ("starch", "veg", "protein", "fat", "bone") BIN_TH = {"starch": "ข้าว แป้ง", "veg": "ผัก", "protein": "เนื้อ ไข่", "fat": "หนัง มัน", "bone": "กระดูก"} CHANNELS = ("kitchen",) + TWO_BINS + FIVE_BINS def return_bins(layout: str) -> tuple[str, ...]: """The return station's weighed bins for settings["return_bins"].""" return FIVE_BINS if layout == "five" else TWO_BINS BUTTONS = ("ate_all", "too_much", "taste", "hard", "unfamiliar", "no_time") WINDOW_S = 1.2 # stability window STALE_S = 3.0 # device considered offline after this long without a reading SIM_TICK_S = 0.25 SETTLE_S = 0.6 # simulated wobble after a load change _lock = threading.Lock() _ch = {c: {"raw": 0.0, "ts": 0.0, "source": "sim", "mode": "sim", "hist": [], "sim_target": 0.0, "settle_until": 0.0, "tare": 0.0} for c in CHANNELS} _stable_band = 10.0 _last_press = 0.0 _sim_on = True # off with real school data: a channel without an ESP32 is offline, never a made-up 0 g def set_simulator(on: bool) -> None: global _sim_on _sim_on = bool(on) def simulator_on() -> bool: return _sim_on def set_stable_band(g: float) -> None: global _stable_band _stable_band = float(g) def _push(c: str, g: float, source: str) -> None: s = _ch[c] now = time.monotonic() s["raw"], s["ts"], s["source"] = g, now, source s["hist"].append((now, g)) while s["hist"] and s["hist"][0][0] < now - WINDOW_S: s["hist"].pop(0) def _stable(s: dict) -> bool: if len(s["hist"]) < 3 or time.monotonic() - s["ts"] > STALE_S: return False values = [g for _, g in s["hist"]] return max(values) - min(values) <= _stable_band def device_reading(readings: dict) -> list[str]: """From an ESP32: {"device": "return", "readings": {"rice": 1234.5, "dish": 2345.6}} or, five bins: {"device": "return", "readings": {"starch": g, "veg": g, "protein": g, "fat": g, "bone": g}}""" accepted = [] with _lock: for c, g in (readings or {}).items(): if c in _ch and isinstance(g, (int, float)) and g == g: _ch[c]["mode"] = "esp32" _push(c, float(g), "esp32") accepted.append(c) return accepted def sim_set(c: str, value_g=None, delta_g=None) -> float: if c not in _ch: raise KeyError(c) with _lock: s = _ch[c] base = s["sim_target"] if s["source"] == "sim" else s["raw"] nxt = float(value_g) if value_g is not None else base + float(delta_g or 0) s["sim_target"] = max(0.0, round(nxt, 1)) s["settle_until"] = time.monotonic() + SETTLE_S s["mode"] = "sim" return s["sim_target"] def sim_tick() -> None: """One simulator step for every channel that is not fed by an ESP32.""" if not _sim_on: return now = time.monotonic() with _lock: for c in CHANNELS: s = _ch[c] if s["mode"] != "sim": continue wobble = 30 if now < s["settle_until"] else 0.8 noise = 0 if (s["sim_target"] == 0 and wobble < 1) else random.uniform(-wobble, wobble) _push(c, round(s["sim_target"] + noise, 1), "sim") def _sim_loop() -> None: while True: sim_tick() time.sleep(SIM_TICK_S) # The browser build (static Space) has no threads; its worker calls sim_tick() on a timer instead. if not os.environ.get("EATBACK_BROWSER"): threading.Thread(target=_sim_loop, daemon=True, name="scale-sim").start() def reading(c: str) -> dict: with _lock: s = _ch[c] return { "raw": s["raw"], "net": s["raw"] - s["tare"], "stable": _stable(s), "source": s["source"], "online": time.monotonic() - s["ts"] < STALE_S, } def tare(c: str) -> float: with _lock: _ch[c]["tare"] = _ch[c]["raw"] return _ch[c]["tare"] def clear_tare(c: str) -> None: with _lock: _ch[c]["tare"] = 0.0 def snapshot() -> dict: out = {} for c in CHANNELS: r = reading(c) out[c] = { "raw": round(r["raw"], 1), "net": round(r["net"], 1), "tare": round(_ch[c]["tare"], 1), "stable": r["stable"], "source": r["source"], "online": r["online"], } return out def voice_locked(lockout_s: float) -> float: """Seconds left before the voice box accepts another press (0 when free).""" return max(0.0, _last_press + lockout_s - time.monotonic()) def voice_press() -> None: global _last_press _last_press = time.monotonic()