diff --git a/.github/workflows/pr-sim.yml b/.github/workflows/pr-sim.yml index bf0e5a1..e6a5e99 100644 --- a/.github/workflows/pr-sim.yml +++ b/.github/workflows/pr-sim.yml @@ -97,4 +97,14 @@ jobs: echo echo "All per-screen before/after files are also in the \`sim-before-after\` artifact of [this run](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}). These per-run GIFs (\`*_r.gif\`, newest 40 kept) are archived on the [pr-sim-assets release](${{ github.server_url }}/${{ github.repository }}/releases/tag/pr-sim-assets). ASCII frames for one screen are in the job log above." } > /tmp/comment.md - gh pr comment "${{ github.event.pull_request.number }}" --repo "$GITHUB_REPOSITORY" --body-file /tmp/comment.md + # one standing comment per PR: edit the workflow's previous comment + # if it exists, create it only on the first run (re-runs would + # otherwise pile up one comment per run) + COMMENT_ID=$(gh api "repos/$GITHUB_REPOSITORY/issues/${{ github.event.pull_request.number }}/comments?per_page=100" \ + --jq '[.[] | select(.user.login == "github-actions[bot]" and (.body | startswith("Sim before/after")))][0].id') + if [ -n "$COMMENT_ID" ]; then + gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$COMMENT_ID" \ + -f body=@/tmp/comment.md > /dev/null + else + gh pr comment "${{ github.event.pull_request.number }}" --repo "$GITHUB_REPOSITORY" --body-file /tmp/comment.md + fi diff --git a/AGENTS.md b/AGENTS.md index 25f7c02..32269a9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,8 +11,9 @@ hi/lo screen. Variable contract + how to create it: `secrets.example.py` and README "Board configuration" — fill the template, upload host -> board, delete local. - Board code must stay MicroPython-compatible: no CPython-only stdlib, match - the existing `%`-formatting style, keep `src/render.py` free of board imports - (it also runs on the host in `sim/`). + the existing `%`-formatting style, keep the `src/` drawing modules + (`render.py`, `weather.py`, `matrix.py`, `scenes.py`) free of board imports + (they also run on the host in `sim/`). - The SCD41 driver is frozen into Pimoroni's MicroPython firmware (`breakout_scd41`, `pimoroni_i2c`) — do not vendor a copy; the sim mocks those two modules (sim/run_main.py). @@ -34,7 +35,7 @@ hi/lo screen. `skills/unicorn/`. - **Preview display changes in sim/ before deploying** — not as a fallback for a detached board, but because you can actually see what the matrix will - show, using the exact `src/render.py` code and real bitmap6 font metrics: + show, using the exact `src/` render code and real bitmap6 font metrics: `python3 sim/sim.py print --screen weather --code 61 --temp 21 --frames 8` writes plain ASCII frames to stdout for agent analysis; `python3 sim/sim.py play ...` animates in the terminal. Render the whole @@ -72,7 +73,7 @@ Most contributions here come from agents — this file is the contract: screen inline on the PR (artifact `sim-before-after`; screens pixel-identical to the base produce no GIFs). For icon changes, also do a HITL pass on the physical board: `python3 skills/unicorn/display.py --icons` after - `scripts/deploy.sh --no-reset` (so the board runs *your* render.py), then + `scripts/deploy.sh --no-reset` (so the board runs *your* render code), then `mpremote reset` to return to the clock. `micropython` is protected by a ruleset: one approving review and all threads resolved are required; merges are **rebase-only with required linear @@ -91,8 +92,11 @@ Most contributions here come from agents — this file is the contract: ## Layout -- `main.py` — board entry point (WiFi/NTP/open-meteo/SCD41 + screen loop), thin -- `src/render.py` — all drawing; pure functions taking a PicoGraphics-like `d` +- `main.py` — board entry point (WiFi/NTP/open-meteo/SCD41 + dashboard loop), thin +- `src/render.py` — core drawing (clock, CO2, hi/lo, boot); pure functions + taking a PicoGraphics-like `d` +- `src/weather.py` — weather icon art; `src/matrix.py` — matrix rain; + `src/scenes.py` — dashboard composition and widgets - `src/tz.py` — EU DST offset, pure integer math (no tzdata on the board) - `sim/` — host simulator: `sim.py`, `font6_data.py` (Pimoroni font6), `run_main.py` (mocked full run of main.py), `before_after.py` (PR GIFs) diff --git a/README.md b/README.md index a80291b..797161d 100644 --- a/README.md +++ b/README.md @@ -1,60 +1,50 @@ # galactic-clock -Pimoroni Galactic Unicorn (53x11 LED matrix) on a Raspberry Pi Pico W running -MicroPython. A weather clock that rotates four screens on the matrix: - -- **clock** — local time, RTC synced via NTP (EU DST computed in pure integer - math in `src/tz.py` — MicroPython has no tzdata), blinking colon; shown only - when the RTC is trustworthy (NTP-synced, or already reading >= 2026 after a - soft reset) — otherwise the slot shows `no ntp` -- **weather** — animated 10x11 icon + current temperature from open-meteo (no - API key); icons are hand-drawn pixel art per WMO code with day/night variants - (twinkling sun/moon, drifting fog bands, falling rain/snow, flashing storm bolt) -- **hi/lo** — today's high/low with up/down arrows -- **CO2** — ppm from an optional SCD41 sensor on the STEMMA QT connector, - color-coded green/amber/red by indoor air quality - -Buttons: **A** toggles the **matrix rain** mode — one anti-aliased drop per -column (subpixel motion, gradual brightness between rows) with a fading trail. -Five speed/brightness tiers (very dim crawl → full-brightness sprint) are -hashed across the columns, gaps between passes span 4–11 rows, and ~1 pass in -10 rests entirely, so the rain's density and tempo visibly breathe; each drop's -head cycles through a few subtle green variations as it falls and settles on -its hue -for the second half of the pass, and every pass mixes its hue and trail length -from a deterministic LCG (no randomness — sim and board render identically). -One press plays it full-screen for two minutes (a second press stops it early), -then the regular rotation resumes. With a trusted RTC the clock shows through -the rain (`sim/sim.py --screen rainclock`): the clock phases in over ~0.3 s -on entry; when the mode ends it dissolves right away — the dim box lifts, -the field pours across the still-bright digits, and the clock's ink converts -to falling drops pixel by pixel (staggered, organic); at full strength -the field dims to 35 % alpha inside -the clock's text box while bright white digits draw on top, so -the rain visibly -pours across the time; without a trusted RTC the rain runs alone (same rule as -the rotation's clock-hiding). The rain keeps a persistent frame tick -across runs, so it always continues where it left off. +A weather and air-quality clock for the Pico W and its 53x11 LED matrix, +written in MicroPython for the board. The rendering is pure, deterministic +functions, so a host simulator can drive the exact same code the board runs — +reproducing the matrix pixel-for-pixel. The GIF below is bit-identical to the +hardware. ![Display loop demo](docs/demo-rotation.gif) -The regular rotation (clock → animated weather → hi/lo → CO2), rendered by the -host sim from the real `main.py` — regenerate with +Rendered by the host sim from the real `main.py` — regenerate with `python3 sim/run_main.py --seconds 24 --delay 0.12 --preseed-co2 53 --gif docs/demo-rotation.gif` -(the preseed fills the CO2 history with ~2.6 h of canned readings so the -GIF's strip isn't empty; `micropython-check` verifies the tracked GIF -against this exact command; needs Pillow; these GIFs are tracked, all other -recordings stay uncommitted). +(`--preseed-co2` fills the CO2 history so the GIF's strip isn't empty; +`micropython-check` verifies the tracked GIF against this exact command; +needs Pillow). -![Rain-clock demo](docs/demo-rainclock.gif) +The dashboard: local time always on the left, one widget at a time on the +right, rotating every 8 s with a vertical roll: -The rain-clock mode as one press plays it: the bare field pours, the clock -phases in over ~0.3 s, holds steady with drops crossing the bright digits, -then the exit dissolves the ink into falling drops frame by frame. -`python3 sim/sim.py play --screen rainclock --delay 0.12 ---gif docs/demo-rainclock.gif` renders the whole episode (lengths ride the -render constants, so `--frames` doesn't apply); `sim/check_demo_gif.py` (CI) -enforces that both GIFs match the code. +- **clock** — 5x7 digits in fixed slots, so the colon holds one column, + blinking two-dot colon; RTC synced via NTP (EU DST computed in pure integer + math in `src/tz.py` — MicroPython has no tzdata); shown only + when the RTC is trustworthy (NTP-synced, or already reading >= 2026 after a + soft reset) — otherwise the slot shows `no ntp` +- **weather widget** — animated 10x11 icon + current temperature from + open-meteo (no API key); icons are hand-drawn pixel art per WMO code with + day/night variants (twinkling sun/moon, drifting fog bands, falling + rain/snow, flashing storm bolt) +- **hi/lo widget** — today's high/low with up/down arrows +- **CO2 widget** — ppm from an optional SCD41 sensor on the STEMMA QT + connector, color-coded green/amber/red by indoor air quality; readings stay + untrusted for ~3 min after boot (the sensor's startup settling) + +Buttons: **A** toggles the **matrix rain** mode — anti-aliased drops with +fading trails; column-by-column speed/brightness tiers and occasional rests +make the density and tempo visibly breathe, and the rendering is +deterministic, so sim and board match frame for frame. One press plays it +full-screen for two minutes (a second press stops it early), then the +dashboard resumes. With a trusted RTC the clock shows through the rain; +without one, the rain runs alone. + +![Matrix rain demo](docs/demo-matrix.gif) + +The rain-clock episode, rendered by +`python3 sim/sim.py play --screen rainclock --delay 0.12 --gif docs/demo-matrix.gif` +(the episode length rides the render constants, so `--frames` doesn't apply); +`sim/check_demo_gif.py` (CI) enforces that both GIFs match the code. ## Hardware & host setup @@ -115,7 +105,7 @@ weather values are CLI args (`--code/--temp/--hi/--lo/--night`). ``` python3 sim/sim.py print --screen weather --code 61 --temp 21 --frames 8 - # plain ASCII frames on stdout (for agent analysis) + # plain ASCII frames on stdout python3 sim/sim.py play --screen weather --code 61 --temp 21 # animate in terminal python3 sim/sim.py play --screen weather --code 0 --night # moon + stars python3 sim/sim.py play --screen icons --frames 8 # contact sheet: all icons @@ -123,45 +113,24 @@ python3 sim/sim.py play --screen hilo --hi 25 --lo 18 python3 sim/sim.py play --screen matrix --frames 60 # code rain ``` -See it in motion — render any screen, or the whole display loop of the real +See it in motion — render any screen, or the whole dashboard loop of the real `main.py` (fully mocked: WiFi/NTP/open-meteo/SCD41), to an animated GIF -(needs Pillow; GIFs are gitignored and generated on demand for PRs — the only -tracked one is the README demo above): +(needs Pillow; GIFs are gitignored): ``` -python3 sim/run_main.py --seconds 24 --gif /tmp/rotation.gif # clock -> weather -> hi/lo -> CO2 +python3 sim/run_main.py --seconds 24 --gif /tmp/rotation.gif # dashboard, widgets rolling python3 sim/sim.py play --screen matrix --frames 60 --gif /tmp/matrix.gif python3 sim/sim.py play --screen icons --frames 8 --gif /tmp/icons.gif python3 sim/sim.py play --screen weather --code 61 --temp 21 --frames 12 --gif /tmp/rain.gif ``` -HITL review on the physical board (see all icons before approving a PR): -`python3 skills/unicorn/display.py --icons` cycles every weather icon on the -matrix, 3 s each, WMO code labelled (`n` = night); then `--stop` and -`mpremote reset` return to the clock. - -The weather icon (10x11, left of the temperature) is animated per WMO code: -twinkling sun/moon, partly-cloudy sun+moon peeking behind a drifting cloud, -fog bands, falling rain streaks (drizzle/snow fall slower, showers pulse, -heavy variants denser), and a flashing bolt for storms. The icons are -hand-drawn 10x11 pixel art, tuned frame by frame in the sim. - -Recordings are generated on demand and never committed (gitignored). For PR -reviews, before/after GIFs of every screen (base ref vs PR head) are rendered -automatically: +For PR reviews, before/after GIFs of every changed screen (base ref vs PR +head) are rendered automatically: ``` python3 sim/before_after.py --ref origin/micropython --out /tmp/pr - # writes /tmp/pr__{before,after,compare}.gif per screen - # (weather/icons/clock/hilo/co2) plus pr_rotation_* — a full mocked - # run of the real main.py (sim/run_main.py), robust to screen changes. - # "icons" is a contact sheet of every animated weather icon - # (WMO code x day/night) in one GIF. --ref takes the PR base SHA - # (CI passes github.event.pull_request.base.sha); locally use - # origin/micropython. Screens pixel-identical to the base - # produce no GIFs at all, so the CI upload/PR comment skips - # them — the review only shows what changed. Attach the GIFs - # to the PR; CI does this automatically. + # writes /tmp/pr__{before,after,compare}.gif + # screens pixel-identical to the base produce no GIFs ``` ## Development @@ -185,8 +154,13 @@ python3 sim/before_after.py --ref origin/micropython --out /tmp/pr ## Layout - `AGENTS.md` — ramp-up essentials: golden rules, workflow, layout -- `main.py` — board entry point: WiFi/NTP/open-meteo/SCD41 + screen loop (thin) -- `src/render.py` — all drawing; pure functions, no board imports (also runs in the sim) +- `main.py` — board entry point: WiFi/NTP/open-meteo/SCD41 + dashboard loop (thin) +- `src/render.py` — core drawing (clock, CO2, hi/lo, boot); pure functions, no + board imports +- `src/weather.py` — animated weather icon art; `src/matrix.py` — matrix rain + and the rain-clock overlay; `src/scenes.py` — dashboard composition and widgets +- `src/co2.py` — SCD41 sampling with warmup gating and the history ring buffer +- `src/ntp.py` — periodic RTC re-sync while the clock runs - `src/tz.py` — EU DST offset in pure integer math (MicroPython has no tzdata) - `sim/` — host simulator: `sim.py` (play/print/GIF), `font6_data.py` (real bitmap6 font metrics), `run_main.py` (mocked full run of `main.py`), diff --git a/docs/demo-matrix.gif b/docs/demo-matrix.gif new file mode 100644 index 0000000..60c62f6 Binary files /dev/null and b/docs/demo-matrix.gif differ diff --git a/docs/demo-rainclock.gif b/docs/demo-rainclock.gif deleted file mode 100644 index a1a4f70..0000000 Binary files a/docs/demo-rainclock.gif and /dev/null differ diff --git a/docs/demo-rotation.gif b/docs/demo-rotation.gif index 678c315..5160475 100644 Binary files a/docs/demo-rotation.gif and b/docs/demo-rotation.gif differ diff --git a/main.py b/main.py index aba0f08..cbb9c74 100644 --- a/main.py +++ b/main.py @@ -3,24 +3,33 @@ Connects to WiFi (credentials in /secrets.py, not committed), syncs the RTC via NTP (clock on screen), fetches the forecast from open-meteo (no API key needed), reads a local SCD41 CO2 sensor over I2C (breakout_scd41 is frozen -into Pimoroni's MicroPython), and rotates the screens on the 53x11 matrix: -clock, weather icon + temperature, high/low, CO2 ppm. Button A toggles the +into Pimoroni's MicroPython), and shows the dashboard: the clock always +visible on the left on plain black, one widget (weather +icon + temp, hi/lo, CO2 ppm) rotating on the right every 8 s. Button A +toggles the matrix-rain animation mode (fragments of green code falling full-screen), which then runs for two minutes (a second press stops it early) before the -regular rotation resumes. The rain keeps a persistent frame tick across +dashboard resumes. The rain keeps a persistent frame tick across runs. Board telemetry -(ambient light, die temperature) is logged over UART each rotation, and +(ambient light, die temperature) is logged over UART each pass, and VSYS once at boot with the radio powered down (GP29 is the Pico W radio's -SPI CS, so it is only measurable with WLAN off). A boot/loading screen is +SPI CS, so it is only measurable with WLAN off). The panel is globally +dimmed to DISPLAY_BRIGHTNESS at boot (gu.set_brightness: a scanout-side +per-channel scale — the framebuffer, the sim and all pens are untouched). +A boot/loading screen is shown while WiFi connects so the matrix is never blank at startup. The clock -screen is only shown when the RTC is trustworthy — NTP-synced at least once +is only drawn when the RTC is trustworthy — NTP-synced at least once this boot, or already reading >= 2026 (a soft reset keeps the RTC running); -otherwise its slot shows "no ntp" instead of a wrong time. If WiFi could +otherwise the dashboard shows "no ntp" instead of a wrong time. If WiFi could not connect at boot (or drops later) it is retried periodically in the loop, and a reconnect re-runs the NTP sync. CO2 readings are logged to an in-RAM timestamped ring (no persistence: any reset or power cycle -rebuilds it from scratch) driving the bottom-edge hue strip on the -co2 screen. +rebuilds it from scratch), and the ring untrusts the sensor's readings +for the first minutes after boot — the SCD41 settles on its own +measurement clock, so the widget, the ring and the alarm all stay off +until ~3 min after a reset; the full co2 history screen runs only as +the alarm (fresh reading >= CO2_RED_PPM takes the whole screen and +beeps). All drawing lives in render.py (pure, board-independent) so it can also run in the host simulator: python3 sim/sim.py play --screen weather --code 61 @@ -45,6 +54,8 @@ SCD41_ALTITUDE_M = 0 import render +import matrix +import scenes import tz from co2 import Co2Ring from ntp import NTP_INTERVAL_S, NTP_RETRY_S, NtpSync @@ -52,6 +63,14 @@ RTC_TRUST_YEAR = 2026 # an unsynced RP2040 RTC boots at 2021-01-01; a synced one is >= 2026 WIFI_RETRY_S = 60 # retry a failed/dropped wifi connect at most this often +WIDGET_S = 8 # how long each dashboard widget shows before the next +WIDGET_ROLL_SLEEP = 0.02 # the roll's frame pace: 1 px per roll frame + # through all H+1 rows (~0.5 s), then back to the + # steady 0.2 s pace (the phase counts frames — + # time.time() is whole seconds on this build) +DISPLAY_BRIGHTNESS = 0.8 # the panel's global dimmer (scanout-side: scales + # every pixel per channel at update() — the fb and + # the sim never see it) # Button A toggles the matrix rain. The pin comes from the frozen galactic # class — the board's buttons are NOT GP6/7/8/9 (A=0, B=1, C=3, D=6; verified @@ -153,55 +172,88 @@ def connect_wifi(): return wlan -def show_weather(wx, seconds): - code = wx["current"]["weather_code"] - temp = "%dC" % round(wx["current"]["temperature_2m"]) - is_day = wx["current"].get("is_day", 1) - end = time.time() + seconds - frame = 0 - # every show loop polls the button-A deadline (see rain_pending): a - # press mid-rotation ends this screen within a frame and the rain - # starts right away instead of at the next slot boundary - while time.time() < end and not rain_pending(): - render.clear(d, W, H) - # frame must advance by exactly 1 per shown frame: time.time() is int - # seconds on this build, so int(time.time()*3) jumps 0,3,6,9... and - # the drops appear to fall upwards - render.draw_weather(d, W, H, code, temp, frame, is_day) - frame += 1 - gu.update(d) - time.sleep(0.15) +# the widget roll's state: [current widget index, dashboard frames since the +# step] — module-level because a wall-clock slot boundary can fall inside a +# show_dashboard call (and across calls) +_roll = [None, 0] -def show_clock(seconds): +def show_dashboard(seconds): + """The home screen and the only data screen: the clock always visible on + the left, ONE widget on the right that rotates on a fixed wall-clock + cadence (weather icon + temp, hi/lo pair, CO2 readout), each step + rolling the outgoing widget down and the next in from the top — on + plain black, + no backdrop scene (the sparse LED matrix reads those as gap artifacts; + the widgets carry the screen). Widgets whose backing service has no + data yet drop out of the rotation instead of drawing blanks; with none + at all (fresh boot, no wifi) the clock carries the screen alone.""" end = time.time() + seconds + frame = 0 while time.time() < end and not rain_pending(): # localtime() is UTC on this build — apply the TZ offset ourselves t = time.localtime(time.time() + tz.utc_offset(TZ, time.time())) - # 1 Hz blink from ticks_ms (time.time() is int on this build) + wx_now = weather.current() + ppm = co2.current() render.clear(d, W, H) - render.draw_clock(d, W, H, "%02d" % t[3], "%02d" % t[4], - time.ticks_ms() % 1000 < 500) - gu.update(d) - time.sleep(0.2) - - -def show_hilo(wx, seconds): - hi = "%d" % round(wx["daily"]["temperature_2m_max"][0]) - lo = "%d" % round(wx["daily"]["temperature_2m_min"][0]) - end = time.time() + seconds - while time.time() < end and not rain_pending(): - render.clear(d, W, H) - render.draw_hilo(d, W, H, hi, lo) + if wx_now is not None: + cur = wx_now["current"] + widgets = ( + {"kind": "wx", "code": cur["weather_code"], + "temp_f": cur["temperature_2m"], + "is_day": cur.get("is_day", 1)}, + {"kind": "hilo", + "hi": wx_now["daily"]["temperature_2m_max"][0], + "lo": wx_now["daily"]["temperature_2m_min"][0]}, + ) + else: + widgets = () + if ppm is not None: + widgets += ({"kind": "co2", "ppm": ppm},) + if rtc_trusted(): + # 1 Hz blink from ticks_ms (time.time() is int on this build) + render.draw_clock(d, W, H, "%02d" % t[3], "%02d" % t[4], + time.ticks_ms() % 1000 < 500, + x_bounds=(0, render.WIDGET_X0 - 2)) + else: + # a fresh boot before NTP: a wrong time is worse than a message + render.draw_message(d, W, H, "no ntp") + rolling = False + if widgets: + # rotate on the wall clock so the widget never depends on how + # long a pass sleeps; each step rolls the outgoing widget down + # out of the zone while the next drops in from the top (a + # fresh boot rolls the first in with nothing outgoing) + idx = (time.time() // WIDGET_S) % len(widgets) + if _roll[0] != idx: + first = _roll[0] is None + _roll[0] = idx + _roll[1] = 0 + else: + _roll[1] += 1 + first = False + n = _roll[1] + if n <= H and len(widgets) > 1: + rolling = True + if not first: + scenes.draw_widget(d, W, H, + widgets[(idx - 1) % len(widgets)], + frame, dy=n) + scenes.draw_widget(d, W, H, widgets[idx], frame, + dy=n - (H + 1)) + else: + scenes.draw_widget(d, W, H, widgets[idx], frame) gu.update(d) - time.sleep(0.2) + frame += 1 + time.sleep(WIDGET_ROLL_SLEEP if rolling else 0.2) -# --- CO2 history ring (in-RAM) ----------------------------------------------- -# The ring itself (bucket math, slot logic, the raw-reading cache) lives in -# co2.py; main.py only owns the single instance. +# --- service instances (module level: the view functions read them) --------- +# co2's ring math lives in co2.py, the forecast cache in weather.py; this +# file owns the single instances (and nothing else). co2 = Co2Ring() +weather = Weather(LOCATION_LAT, LOCATION_LON, TZ) def show_co2(ppm, seconds, alarm=False, hist=None): @@ -272,7 +324,7 @@ def rain_pending(): def maybe_show_rain(sensor=None): """While button A's rain deadline is in the future, run full-screen matrix rain instead of the following data screens, the clock - poured over the field (render.draw_rain_clock) when the RTC is trusted. + poured over the field (matrix.draw_rain_clock) when the RTC is trusted. Each rain frame first samples the SCD41 into the history ring (due- checked to CO2_INTERVAL_S) so the mode's two-minute takeover keeps the ~once-a-minute cadence. @@ -310,17 +362,17 @@ def maybe_show_rain(sensor=None): # re-arm the deadline and cancel the animation halfway rain_exiting = True if not rtc_trusted() or \ - dissolve >= render.MATRIX_DISSOLVE_STEPS: + dissolve >= matrix.MATRIX_DISSOLVE_STEPS: break if anim_frame % 2 == 0: dissolve += 1 # the whole exit: ~1 s total elif rtc_trusted(): # 4 dither levels, one every other frame: a ~0.3 s ramp. A step # allocates nothing (the Bayer dither just lights more of the - # existing dim pens — see render._BAYER4), so the ramp runs at + # existing dim pens — see matrix._BAYER4), so the ramp runs at # full fps instead of stuttering; the mode entry's collect # covers the only real burst (a level's first masked pixels) - if fade < render.MATRIX_FADE_STEPS and anim_frame % 2 == 0: + if fade < matrix.MATRIX_FADE_STEPS and anim_frame % 2 == 0: fade += 1 try: if rtc_trusted(): @@ -330,18 +382,18 @@ def maybe_show_rain(sensor=None): # rather than show a wrong time (same rule as the # rotation's clock-hiding) t = time.localtime(time.time() + tz.utc_offset(TZ, time.time())) - render.draw_rain_clock(d, W, H, "%02d" % t[3], "%02d" % t[4], + matrix.draw_rain_clock(d, W, H, "%02d" % t[3], "%02d" % t[4], time.ticks_ms() % 1000 < 500, anim_frame, fade=fade, dissolve=dissolve) else: render.clear(d, W, H) - render.draw_matrix(d, W, H, anim_frame) + matrix.draw_matrix(d, W, H, anim_frame) except MemoryError: # belt and braces: the pen memo is a rebuildable cache — if a # frame ever runs out of heap, drop it (the next frame # repopulates it) instead of erroring the whole loop - render._PEN_MEMO.clear() + matrix._PEN_MEMO.clear() gc.collect() anim_frame += 1 gu.update(d) @@ -419,37 +471,24 @@ def show_text(msg, seconds): def run_pass(sensor, wx): - """One full rotation pass, in fixed display order: the clock, the - weather pages, then the co2 readout. The per-screen freshness checks - live here (the screens themselves are pure renderers); adding a screen - means one line here, not a loop restructure. Keeps the pass as data: - (screen, args) pairs, so the sequence reviews as a unit.""" - if rtc_trusted(): - show_clock(5) - else: - # never NTP-synced and RTC still < 2026 (fresh boot): showing - # the clock would display a wrong time — message instead - show_text("no ntp", 5) - maybe_show_rain(sensor) - if wx is not None: - show_weather(wx, 5) - show_hilo(wx, 5) - else: - show_text("no weather", 5) - maybe_show_rain(sensor) + """One loop pass: sample the CO2 sensor, then show the dashboard (the + clock + one rotating widget — the whole rotation now lives inside the + dashboard's widget cadence). The co2 strip screen only runs as the + alarm: a fresh reading at/above CO2_RED_PPM takes the full screen + (reading + history strip) and beeps, then the dashboard resumes.""" + # sample first: the widget set exists as soon as the sensors do, so the + # FIRST dashboard pass already carries a co2 widget fresh_ppm = co2.sample(sensor, time) - hist = co2.history() - if co2.current() is not None: - # the number is the latest raw reading (up to 3 min fresher - # than the newest committed bucket — that lag lives in the - # strip only); the alarm fires inside show_co2 right after - # the first frame, so the beep overlaps the screen instead - # of preceding it and only rides a pass with a fresh reading - show_co2(co2.current(), 5, alarm=fresh_ppm is not None, - hist=hist) + if fresh_ppm is not None and fresh_ppm >= render.CO2_RED_PPM: + # the number is the latest raw reading (up to 3 min fresher than + # the newest committed bucket — that lag lives in the strip only) + show_co2(co2.current(), 5, alarm=True, hist=co2.history()) + show_dashboard(WIDGET_S) + maybe_show_rain(sensor) def main(): + gu.set_brightness(DISPLAY_BRIGHTNESS) tick_boot("boot") # measure VSYS before the radio comes up (GP29 is the radio's SPI CS # once WLAN is active — see read_vsys); re-measuring later would need a @@ -473,7 +512,6 @@ def main(): print("scd41: not found on i2c") except Exception as e: print("scd41 init failed:", e) - weather = Weather(LOCATION_LAT, LOCATION_LON, TZ) # re-syncs the RTC every 6 h while the clock runs; a boot sync that # failed only defers the first in-loop attempt by the back-off, not # a full interval (the clock slot must not blank for hours) diff --git a/scripts/deploy.sh b/scripts/deploy.sh index 16c6021..e047397 100755 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # Deploy the weather clock to the board. If the board is not usbipd-attached to # WSL yet (/dev/ttyACM0 missing), scripts/attach.sh is run automatically first. -# scripts/deploy.sh upload main.py + render.py, then reset the board +# scripts/deploy.sh upload main.py + the render modules, then reset # scripts/deploy.sh --no-reset upload only, keep the current REPL session # scripts/deploy.sh --no-attach never attach; fail if /dev/ttyACM0 is missing set -euo pipefail @@ -33,11 +33,13 @@ fi mpremote cp main.py :main.py mpremote cp src/render.py :render.py +mpremote cp src/scenes.py :scenes.py +mpremote cp src/matrix.py :matrix.py mpremote cp src/tz.py :tz.py mpremote cp src/co2.py :co2.py mpremote cp src/weather.py :weather.py mpremote cp src/ntp.py :ntp.py -echo "deployed main.py + render.py + tz.py + co2.py + weather.py + ntp.py (breakout_scd41 is frozen in the firmware)" +echo "deployed main.py + render.py + scenes.py + matrix.py + tz.py + co2.py + weather.py + ntp.py (breakout_scd41 is frozen in the firmware)" if [[ "$NO_RESET" == 0 ]]; then mpremote reset # reboots into /main.py diff --git a/sim/before_after.py b/sim/before_after.py index 0d27933..d41886c 100644 --- a/sim/before_after.py +++ b/sim/before_after.py @@ -39,9 +39,8 @@ sys.path.insert(0, os.path.join(REPO, "src")) sys.path.insert(0, HERE) -import render # noqa: E402 (current tree) +import sim as simmod # noqa: E402 (simmod.RENDER: the current tree's split modules) import run_main # noqa: E402 -import sim as simmod # noqa: E402 from gif import write_gif # noqa: E402 W, H = 53, 11 @@ -198,7 +197,7 @@ def main(): print("weather: before unavailable at %s (%s) — after-only" % (args.ref, e)) elif screen == "icons": - after = render_icons(render, ICON_ENTRIES, ICON_FRAMES) + after = render_icons(simmod.RENDER, ICON_ENTRIES, ICON_FRAMES) before = None if R_base is not None: try: @@ -207,7 +206,7 @@ def main(): print("icons: before unavailable at %s (%s) — after-only" % (args.ref, e)) elif screen == "rainclock": - after = simmod.render_rainclock_episode(render) + after = simmod.render_rainclock_episode(simmod.RENDER) before = None if R_base is not None: try: @@ -217,7 +216,7 @@ def main(): "— after-only" % (args.ref, e)) elif screen in SCREENS: n = SCREENS[screen][1] - after = render_frames(render, screen, n) + after = render_frames(simmod.RENDER, screen, n) if R_base is not None: try: before = render_frames(R_base, screen, n) @@ -227,6 +226,9 @@ def main(): else: raise SystemExit("unknown screen: %s (have: weather,icons,%s,rotation)" % (screen, ",".join(SCREENS))) + if not after: + print("%s: not rendered by HEAD — skipped, no GIFs" % screen) + continue print(write_screen_gifs(args.out, screen, after, before, args.ref, args.scale, delay_ms)) return 0 diff --git a/sim/check_demo_gif.py b/sim/check_demo_gif.py index 515b2d3..2249b99 100644 --- a/sim/check_demo_gif.py +++ b/sim/check_demo_gif.py @@ -23,7 +23,6 @@ sys.path.insert(0, os.path.join(REPO, "src")) sys.path.insert(0, HERE) -import render # noqa: E402 import run_main # noqa: E402 from gif import fb_to_image # noqa: E402 @@ -99,13 +98,13 @@ def check(gif_path=DEMO_GIF, seconds=DEMO_SECONDS, scale=DEMO_SCALE, # Keep in sync with the README rain-clock regenerate command below. -RAINCLOCK_GIF = os.path.join(REPO, "docs", "demo-rainclock.gif") +RAINCLOCK_GIF = os.path.join(REPO, "docs", "demo-matrix.gif") RAINCLOCK_DELAY_MS = 120 RAINCLOCK_SCALE = 8 def compare_rainclock_gif(): - """docs/demo-rainclock.gif check: frame count, size, tempo, pixels. + """docs/demo-matrix.gif check: frame count, size, tempo, pixels. The episode builder (sim.render_rainclock_episode) pins the exact frames — one fade level and one dissolve step per two 120 ms frames — so the tracked GIF must start bare, fade the clock in, hold it steady @@ -116,16 +115,16 @@ def compare_rainclock_gif(): got = gif_frames(RAINCLOCK_GIF) expected = [(fb_to_image(fb, RAINCLOCK_SCALE).tobytes(), (W * RAINCLOCK_SCALE, H * RAINCLOCK_SCALE)) - for fb in simmod.render_rainclock_episode(render)] + for fb in simmod.render_rainclock_episode(simmod.RENDER)] problems = [] if len(got) != len(expected): - problems.append("rainclock gif: %d frames, code renders %d" + problems.append("matrix gif: %d frames, code renders %d" % (len(got), len(expected))) for i, ((px, size, dur), (epx, esize)) in enumerate(zip(got, expected)): if size != esize: - problems.append("rainclock gif frame %d size %s" % (i, (size, esize))) + problems.append("matrix gif frame %d size %s" % (i, (size, esize))) elif px != epx: - problems.append("rainclock gif frame %d pixels differ" % i) + problems.append("matrix gif frame %d pixels differ" % i) return problems @@ -139,10 +138,10 @@ def main(): " --delay %g --preseed-co2 %d --gif docs/demo-rotation.gif" % (DEMO_SECONDS, DEMO_DELAY_MS / 1000.0, DEMO_PRESEED_CO2)) print(" and: python3 sim/sim.py play --screen rainclock" - " --delay %g --gif docs/demo-rainclock.gif" + " --delay %g --gif docs/demo-matrix.gif" % (RAINCLOCK_DELAY_MS / 1000.0)) return 1 - print("OK: docs/demo-rotation.gif + docs/demo-rainclock.gif match the" + print("OK: docs/demo-rotation.gif + docs/demo-matrix.gif match the" " current code") return 0 diff --git a/sim/run_main.py b/sim/run_main.py index 8a878fe..638e531 100644 --- a/sim/run_main.py +++ b/sim/run_main.py @@ -99,7 +99,11 @@ def _co2_script(): class FakeSCD41: """Mocked SCD41 serving CO2_SCRIPT sequentially (CANNED_CO2 pins every reading when set). 21.5 C, 45 %RH, always ready. Last instance is kept - on the class so tests can introspect what main.py configured.""" + on the class so tests can introspect what main.py configured. The mock + has no startup settling of its own, but Co2Ring still gates a fresh + ring's readings on CO2_WARMUP_S of mocked time — tests that need + trusted readings at once (alarm gate, co2 widget) must run with + preseed_co2, whose restore() models a warmed-up board.""" last = None SLOT_BASE = 0 # preseeded runs start the script here (seed_co2_ring) @@ -220,15 +224,22 @@ def seed_co2_ring(g, n): FakeSCD41.SLOT_BASE = READS_PER_BUCKET * n -def run_main_src(src, seconds, render_src=None, capture_func=None, - capture_out=None, out_globals=None, preseed_co2=None): +def run_main_src(src, seconds, module_srcs=None, capture_func=None, + capture_out=None, out_globals=None, preseed_co2=None, + capture_mod=None): """Exec one main.py source with all externals mocked; return frame list. - If capture_func is given (e.g. "draw_weather"), every call of that - render.* function appends a copy of the bitmap to capture_out — i.e. the - exact screen the ref's own main.py drew, with its own frame argument. - If out_globals is given, the exec'd namespace is copied into it after - the run (a test can then inspect main.py's module state). + module_srcs maps render-side module names (render/scenes/matrix) to + source — used by run_at/run_screen_at so a ref's main.py runs against + that ref's own modules; without it, main.py's `import render => scenes` + resolve to the working tree. If capture_func is given (e.g. + "draw_weather"), every call of that function appends a copy of the + bitmap to capture_out — i.e. the exact screen the ref's own main.py + drew, with its own frame argument. capture_mod hooks a module other + than the render one (the split moved some draw_* functions into + scenes.py / matrix.py). If out_globals is given, the exec'd namespace + is copied into it after the run (a test can then inspect main.py's + module state). """ state = {"t": BOOT_EPOCH, "start": None} real_time = sys.modules.get("time") @@ -280,6 +291,12 @@ class FakeGu: def __init__(self): self.frames = [] + self.brightness = None + + def set_brightness(self, value): + # board-faithful: the real driver stores the value and applies + # it at update() scanout — the framebuffer never sees it + self.brightness = value def update(self, d): if not booting["on"]: @@ -362,10 +379,14 @@ class FakeResp: "urequests": urequests, "ujson": ujson, "machine": machine, "pimoroni_i2c": pimoroni_i2c, "breakout_scd41": breakout_scd41} rmod = _render - if render_src is not None: - rmod = types.ModuleType("render_at_ref") - exec(compile(render_src, "render.py@ref", "exec"), rmod.__dict__) - stubs["render"] = rmod + for name, msrc in (module_srcs or {}).items(): + m = types.ModuleType(name + "_at_ref") + exec(compile(msrc, "%s.py@ref" % name, "exec"), m.__dict__) + stubs[name] = m + if name == "render": + rmod = m + if capture_mod is not None: + rmod = capture_mod # mark the boot phase: wrap every draw_* so FakeGu.update can skip those # frames (tolerant of refs whose render.py has no draw_boot) for name in [n for n in vars(rmod) if n.startswith("draw_")]: @@ -419,12 +440,32 @@ def wrapper(d, *a, _orig=orig, **k): return g["gu"].frames +# render-side modules a ref's main.py may import (the render split, plus the +# historical "rain" name before the matrix rename); each is stubbed from the +# ref itself when present, so ref runs stay self-consistent +MODULE_PATHS = {"render": "src/render.py", + "scenes": "src/scenes.py", + "matrix": "src/matrix.py", + "rain": "src/rain.py"} + + +def _ref_modules(ref): + """{module_name: source} for every render-side module the ref has.""" + out = {} + for name, path in MODULE_PATHS.items(): + s = _git_show(ref, path) + if s is not None: + out[name] = s + return out + + def run_at(ref, seconds): - """Frames from main.py (+ its own render.py) as of git ref; None if absent.""" + """Frames from main.py (+ its own render modules) as of git ref; None if + main.py is absent.""" src = _git_show(ref, "main.py") if src is None: return None - return run_main_src(src, seconds, render_src=_git_show(ref, "src/render.py")) + return run_main_src(src, seconds, module_srcs=_ref_modules(ref)) def run_current(seconds, out_globals=None, preseed_co2=None): @@ -444,17 +485,26 @@ def run_screen_at(ref, func, seconds): if src is None: return None out = [] - run_main_src(src, seconds, render_src=_git_show(ref, "src/render.py"), + run_main_src(src, seconds, module_srcs=_ref_modules(ref), capture_func=func, capture_out=out) return out or None -def run_screen_current(func, seconds): - """Same as run_screen_at but for the working tree.""" +def run_screen_current(func, seconds, preseed_co2=None): + """Same as run_screen_at but for the working tree. Capture hooks whichever + module owns the function now: the split moved art to scenes.py and the + rain family to matrix.py, so the function can live in any of the three.""" with open(os.path.join(REPO, "main.py")) as fh: src = fh.read() out = [] - run_main_src(src, seconds, capture_func=func, capture_out=out) + for mod in (_render, sys.modules.get("scenes"), sys.modules.get("matrix")): + if mod is not None and hasattr(mod, func): + run_main_src(src, seconds, capture_func=func, capture_out=out, + capture_mod=mod, preseed_co2=preseed_co2) + break + else: + run_main_src(src, seconds, capture_func=func, capture_out=out, + preseed_co2=preseed_co2) return out or None diff --git a/sim/sim.py b/sim/sim.py index 72a428e..e7d85da 100644 --- a/sim/sim.py +++ b/sim/sim.py @@ -37,11 +37,37 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import render # noqa: E402 +import scenes # noqa: E402 +import matrix # noqa: E402 import font6_data # noqa: E402 W, H = 53, 11 +class RenderFace: + """Attribute facade over the split render modules (refactor: art lives in + scenes.py, the matrix-rain family in matrix.py, screens/primitives in + render.py). + Lets the renderers that take a module `R` (render_icons, the rain-clock + episode, before_after's SCREENS) address the current tree's three modules + and a ref's self-contained render.py with the same call sites.""" + + def __init__(self, *mods): + self._mods = mods + + def __getattr__(self, name): + for m in self._mods: + try: + return getattr(m, name) + except AttributeError: + continue + raise AttributeError(name) + + +# the working tree's combined render surface +RENDER = RenderFace(render, scenes, matrix) + + class SimGraphics: """Drop-in replacement for the PicoGraphics subset used by render.py.""" @@ -137,6 +163,30 @@ def co2_script_ppm(i): CO2_READS_PER_BUCKET = 12 # co2_script_ppm readings per 3-minute slot (15 s) +# frames a dashboard preview shows one widget before rotating (print/previews +# want all of them in a short --frames run) +WIDGET_PREVIEW_FRAMES = 8 + + +def draw_dashboard_preview(d, f, args): + """--screen dashboard: the board's home screen with canned values, drawn + exactly like main.py's show_dashboard (plain black + clock + widget).""" + is_day = 0 if args.night else 1 + widgets = ( + {"kind": "wx", "code": args.code, "temp_f": args.temp, + "is_day": is_day}, + {"kind": "hilo", "hi": args.hi, "lo": args.lo}, + {"kind": "co2", "ppm": args.ppm}, + ) + render.draw_clock(d, W, H, "21", "%02d" % (f % 60), f % 2 == 0, + x_bounds=(0, render.WIDGET_X0 - 2)) + if args.widget: # pinned: preview one widget's layout in every frame + scenes.draw_widget(d, W, H, widgets[["wx", "hilo", "co2"].index( + args.widget)], f) + else: # rotate like the board does (8 s wall clock; here 8 frames) + scenes.draw_widget(d, W, H, widgets[f // WIDGET_PREVIEW_FRAMES % 3], + f) + def synth_co2_hist(): """Synthetic ring contents for the co2 screen preview: the canned @@ -154,8 +204,14 @@ def synth_co2_hist(): def make_screen_fn(args): + if args.screen == "dashboard": + # the board's home screen: render.draw_clock + scenes.draw_widget + # composed exactly like main.py's show_dashboard; the scene behind + # it depends on --code. With widget=None the three widgets rotate + # every WIDGET_FRAMES frames; --widget pins one for close inspection. + return lambda d, f: draw_dashboard_preview(d, f, args) if args.screen == "weather": - return lambda d, f: render.draw_weather(d, W, H, args.code, "%dC" % args.temp, f, + return lambda d, f: scenes.draw_weather(d, W, H, args.code, "%dC" % args.temp, f, 0 if args.night else 1) if args.screen == "clock": return lambda d, f: render.draw_clock(d, W, H, "21", "%02d" % (f % 60), f % 2 == 0) @@ -172,10 +228,10 @@ def make_screen_fn(args): if args.screen == "message": return lambda d, f: render.draw_message(d, W, H, args.message) if args.screen == "matrix": - return lambda d, f: render.draw_matrix(d, W, H, f) + return lambda d, f: matrix.draw_matrix(d, W, H, f) if args.screen == "rainclock": # the rain pours over the clock, exactly like the board's rain mode - return lambda d, f: render.draw_rain_clock( + return lambda d, f: matrix.draw_rain_clock( d, W, H, "21", "%02d" % (f % 60), f % 2 == 0, f) raise SystemExit("unknown screen: %s" % args.screen) @@ -288,14 +344,17 @@ def main(): help="play: animate in terminal; print: plain ASCII frames " "to stdout (no escape codes)") ap.add_argument("--screen", default="weather", - choices=["weather", "clock", "hilo", "co2", "boot", "message", - "matrix", "rainclock", "icons"]) + choices=["dashboard", "weather", "clock", "hilo", "co2", + "boot", "message", "matrix", "rainclock", "icons"]) ap.add_argument("--code", type=int, default=61, help="WMO weather code (weather screen)") ap.add_argument("--temp", type=int, default=21, help="current temperature C") ap.add_argument("--night", action="store_true", help="weather screen: night (moon)") ap.add_argument("--hi", type=int, default=25) ap.add_argument("--lo", type=int, default=18) ap.add_argument("--ppm", type=int, default=812, help="CO2 ppm (co2 screen)") + ap.add_argument("--widget", default=None, + help="dashboard screen: pin a widget (wx/hilo/co2) " + "instead of rotating") ap.add_argument("--label", default=None, help="fixed stage label (boot screen); default cycles boot/wifi/ntp/weather") ap.add_argument("--message", default="no weather") @@ -308,12 +367,12 @@ def main(): args = ap.parse_args() if args.screen == "icons": - frames = render_icons(render, ICON_ENTRIES, args.frames) + frames = render_icons(RENDER, ICON_ENTRIES, args.frames) elif args.screen == "rainclock": # the whole mode: fade-in -> steady pour -> exit dissolve. The - # episode builder derives its lengths from the render constants, + # episode builder derives its lengths from the rain constants, # so --frames does not apply here. - frames = render_rainclock_episode(render) + frames = render_rainclock_episode(RENDER) else: fn = make_screen_fn(args) frames = [render_frame(fn, f) for f in range(args.frames)] diff --git a/skills/mpremote/SKILL.md b/skills/mpremote/SKILL.md index 988dbc7..350ad32 100644 --- a/skills/mpremote/SKILL.md +++ b/skills/mpremote/SKILL.md @@ -17,6 +17,24 @@ Running `mpremote exec ...` takes over the REPL and **stops the running (or `scripts/deploy.sh`) to return the board to the clock. - Ctrl-C in the REPL also kills the main loop — avoid it. +## Handing the board back: soft-reset, and make it the LAST operation + +The clock runs unattended. Every host touch (exec, REPL attach, deploy) +must END with the program running again: + +- `mpremote soft-reset` (equivalent to the board receiving a raw CTRL-D, + `b"\x04"`) restarts `main.py` **without re-enumerating the USB device** — + no re-attach dance. Use it as the final action of any REPL session that + halted the loop. +- **Do not exec anything after the final soft-reset** — that halts main.py + again (this is how a display ends up dark after an otherwise clean + deploy/inspection). Verify via a PASSIVE serial listen instead: open + `/dev/ttyACM0` read-only and wait for output — a healthy boot prints + `MPY: soft reboot` hot on the heels of `sys: vsys=...` telemetry. +- A frozen/dark matrix after a session = the board is paused at the REPL; + one `mpremote soft-reset` (or CTRL-D) fixes it. `machine.reset()` also + works but re-enumerates USB and drops the WSL attach (see above). + ## Board attach / recovery Use when `/dev/ttyACM0` is missing or the REPL is unresponsive. diff --git a/src/co2.py b/src/co2.py index 832f235..1402a5e 100644 --- a/src/co2.py +++ b/src/co2.py @@ -10,15 +10,22 @@ CO2_INTERVAL_S = 15 CO2_BUCKET_S = 180 # one strip column = one averaged ring entry (3 min) CO2_LOG_N = 64 # ring slots: ~3.2 h of bucket means, 384 bytes total +CO2_WARMUP_S = 180 # readings untrusted this long past the first one: the + # SCD41 settles on its own 5 s clock however often it is + # polled (Sensirion: > 3 min before trusting the output); + # a boot transient must not reach readout, ring or alarm class Co2Ring: """The CO2 store: raw readings land here (via `sample()`), bucket means come out (via `history()`), and the big readout's number is `current()`. The ring owns its own cadence: `sample()` is cheap to - call often and no-ops unless CO2_INTERVAL_S has passed. The caller - passes its own `time` module: under sim/ main.py runs on the mocked - clock, and the ring must tick the same one it does.""" + call often and no-ops unless CO2_INTERVAL_S has passed. A fresh ring + untrusts readings until CO2_WARMUP_S past its first (the sensor's + startup settling — see the constant); `restore()` lifts the gate, + since a restored ring stands for a board that has been running. The + caller passes its own `time` module: under sim/ main.py runs on the + mocked clock, and the ring must tick the same one it does.""" def __init__(self): # 'i': epoch seconds; 'H': ppm — the SCD41's spec range is @@ -30,13 +37,15 @@ def __init__(self): self._open = None # the open bucket [slot, ppm sum, reads] self._last_t = None # epoch of the last logged reading self._reading = None # the latest raw reading (see current()) + self._warm_until = None # boot settling: readings before this + # epoch are the sensor warming up def sample(self, sensor, t): """Read the sensor once (skip when the cadence doesn't allow it) and add the reading to the rolling bucket. `t` is the time module — main.py's own import, so sim and board tick alike. - Returns the fresh reading, or None if no reading was taken this - call.""" + Returns the fresh reading, or None if no reading was taken (or, + during boot warm-up, stored) this call.""" now = int(t.time()) if self._last_t is not None and now - self._last_t < CO2_INTERVAL_S: return None @@ -52,6 +61,15 @@ def sample(self, sensor, t): # measure() returns floats on this build (the sim mocks them too; # this cast is the reason the ring stores ints safely) co2 = int(co2) + if self._warm_until is None: + # the first reading anchors the settling window — it lands + # within one cadence of the sensor start, close enough + self._warm_until = now + CO2_WARMUP_S + if now < self._warm_until: + # startup settling: stored nowhere — the readout, the ring + # and the alarm all stay off until the window ends + self._last_t = now + return None self._reading = co2 slot = now // CO2_BUCKET_S # this reading's wall-clock bucket if self._open is None: @@ -92,7 +110,8 @@ def current(self): def restore(self, readings): """Replace the ring's contents with a known history [(epoch_s, ppm)] — the test seed and any future state-reload path; the live - sample() flow never calls this.""" + sample() flow never calls this. A restored ring is a warmed-up + board: the settling gate does not apply to it.""" self._ts = array("i", (0,) * CO2_LOG_N) self._ppm = array("H", (0,) * CO2_LOG_N) for k, (t, ppm) in enumerate(readings): @@ -104,3 +123,4 @@ def restore(self, readings): # no _last_t seeding: the next live reading starts a fresh open # bucket; its cadence clock starts from that first sample self._last_t = None + self._warm_until = 0 diff --git a/src/matrix.py b/src/matrix.py new file mode 100644 index 0000000..11e967e --- /dev/null +++ b/src/matrix.py @@ -0,0 +1,425 @@ +"""The matrix family: the full-matrix digital-rain field with its pen/fade +machinery, and the rain-clock overlay (matrix mode's entry fade and exit +dissolve). Deterministic in the `frame` tick; no board imports here. +""" + +from render import (CLOCK_COLON, CLOCK_GLYPHS, CLOCK_SLOT, CLOCK_WHITE, + CLOCK_W, TEXT_Y, clear, clock_digit_x, draw_clock) + + +# --- matrix rain -------------------------------------------------------------- +# Full-matrix digital-rain fun screen. Same contract as the weather icons: no +# time, no randomness — everything derives from the `frame` tick, so sim and +# board stay identical. + +SUB = 16 # subpixel steps per row (fixed-point position) + +# Head-hue palette the falling head pixel cycles through. Tint 0 is the +# classic rain green — kept saturated rather than whitish so the field reads +# unmistakably green (~4 passes in 5, shimmering between the base tint and a +# subtle neighbor and settling back). The other passes cycle the subtle +# accent tints (compressed teal-ish and chartreuse-ish drifts, green channel +# pinned at 255, red/blue pulled down toward green) and settle on their +# assigned one. Still reads as green rain at a glance, just greener. +MATRIX_TINTS = ( + (170, 255, 130), + (150, 255, 150), + (128, 255, 170), + (198, 255, 100), + (218, 255, 88), +) +N_ACCENT = 4 # tints 1..N_ACCENT are the accent hues +MATRIX_CHURN_SUB = SUB // 4 # one hue step per quarter-row of travel: + # the head pixel cycles tints several times + # per row it drops (fast shimmer) +# tier = (rows, per, brightness %). Every tier's phase advances a +# non-integer number of rows per tick (per never divides rows*SUB), so +# anti-aliased heads glide instead of stepping. Brightness grows with +# speed: fast reads near, slow reads far. At the 1/30 s tick these are +# ~3.75 / 5 / 7.5 / 10 / 15 rows per second. +MATRIX_TIERS = ( + (1, 8, 50), # crawl, dim — the "far background" + (1, 6, 65), # slow + (1, 4, 80), # mid + (4, 12, 90), # brisk + (1, 2, 100), # sprint, full brightness +) + + +def _hash16(x, salt): + """16-bit multiplicative hash of (x, salt): adjacent inputs scatter and + every product stays a MicroPython small int (< 2**30, no bignum cost).""" + return ((x * 40503 & 0xFFFF) ^ (salt * 21649 & 0xFFFF)) & 0x3FFFFFFF + + +def _tier_of(x): + # per-column tier from a 16-bit hash — a plain modulo cycles too + # regularly; the hash scatters adjacent columns over all tiers + return (_hash16(x, 1) >> 4) % len(MATRIX_TIERS) + + +def _gap_of(x): + # blank stretch before respawn, per column, 4..11 rows: columns still + # differ in how densely they rain (duty 0.7..1.0 of the loop) but the + # board reads dense overall; the slower the tier, the longer the dark + # stretch lasts, which reads as depth + return 4 + (_hash16(x, 2) >> 6) % 8 + + +def matrix_col(x, h, frame): + """Subpixel drop state of column x at frame: (c16, L16, bright, seed) — + head position in 1/SUB-row steps (mod the column loop), trail length in + rows (0 = resting pass: the column drops nothing this pass, so local + density breathes), tier brightness, and the per-pass LCG seed for the + head-hue schedule. Exposed for tuning and exact tests; draw_matrix only + rasterizes what this state implies. Trail length and the resting/active + decision mix from a hash over (column index and the pass number — one + pass = one full drop travel), so density, speed mix, hue and trail vary + pass to pass while staying deterministic. Constants stay under 2**30 so + every product is a MicroPython small int — no bignum allocation per + column and frame (a 32-bit LCG constant measured ~16 ms/frame slower).""" + tier = _tier_of(x) + rows, per, bright = MATRIX_TIERS[tier] + gap = _gap_of(x) + loop16 = (h + gap) * SUB + u = (rows * SUB * frame) // per + (x * 37) * SUB # + per-column phase + pass_idx = u // loop16 # one pass = one full drop travel + mix = _hash16(x, pass_idx) + L = 4 + (mix >> 8) % 3 # 4..6 rows of trail per pass + if (mix >> 3) % 10 == 0: # ~1 pass in 10 rests: density breathes + L = 0 + # head hue: ~1 pass in 5 takes an accent tint (1..N_ACCENT), the rest + # stay classic green (seed 0) — every pass shimmers its bottom pixel + variant = (mix >> 5) % 5 + seed = 1 + (mix >> 11) % N_ACCENT if variant == 0 else 0 + return u % loop16, L * SUB, bright, seed + + +def tint_at(seed, pos16, settle_pos16): + """Head-hue schedule (the bottom-pixel shimmer). The head drops one + row and cycles several hues within that row (one churn step per + quarter-row), then — halfway down the pass — settles on its pass tint + for the rest of the fall. seed 0 = classic green pass, mostly the base + tint with a dip into a subtle neighbor on every 4th step; accent + passes (seed 1..N_ACCENT) cycle the accent tints. Trail pixels keep + the hue the head had when it passed them.""" + if pos16 >= settle_pos16: + return seed + step = pos16 // MATRIX_CHURN_SUB + if seed == 0: + if step % 4 != 3: + return 0 + return 1 if (step // 4) % 2 == 0 else 3 + return 1 + (step + seed - 1) % N_ACCENT + + +# Pen memo for draw_matrix: the pixel color depends on (tint, bright, L16, +# alpha bucket) — only ~89 alpha buckets exist per (L16, bright, tint) — so +# pens are cached in a dict keyed by one int +# (bucket | tint<<8 | bright<<12 | L16<<19) instead of re-creating a pen per +# pixel. The bucket quantization bounds the memo (~few thousand entries, a +# few KB); exact-alpha keys proved effectively unbounded (heap full in ~3 s +# on board with the sub-integer rows/tick tiers). Board benchmark of this +# loop: 41 ms/frame naive -> ~29 ms (scanout stays ~2 ms). +_PEN_MEMO = {} + +# Log-shaped trail-fade table: alpha weight per subpixel distance behind the +# head, exponential decay with a 2-row half-life (×2^(-1/32) per subpixel +# step, integer fixed point, ×251/256). Fades a bit faster early than the +# linear ramp it replaces, then levels off into a long dim tail — visually a +# log curve (linear's tail end is ~1.6% of head brightness, this keeps ~11%). +# The half-life can't be much shorter: the pixel holding the head sits at +# clamped dc 0..8, so f^8 sets its dimmest subpixel step (0.85 here) — steeper +# curves dip the "live" head well below the strongly-green threshold. Built +# at import for the only three trail lengths matrix_col ever yields +# (L = 4..6 rows → L16 = 64/80/96); draw_matrix indexes the dict directly, +# since a per-column builder call measured ~2.7 ms/frame extra. Weights stay +# <= L16 <= 96, so a byte holds each. Index is the clamped center distance +# dc the loop already computes; f[0] = L16 is the reference full brightness. +def _build_fade(L16): + f = bytearray(L16) + w = L16 << 8 + for i in range(L16): + f[i] = w >> 8 + w = w * 251 >> 8 + return f + + +# The rain-clock overlay: rain inside the clock's text box is dimmed toward +# MATRIX_DIM % of its alpha (draw_matrix's optional dim_mask, built by +# draw_rain_clock), so the bright digits read over the pouring field even +# where a drop head passes directly behind them. The level is a flag in the +# pen-memo key (bit 28, above L16's last bit 25) so the dimmed pens never +# collide with the full-brightness ones of the same alpha bucket. +MATRIX_DIM = 35 # % of full alpha at the overlay's full strength +_KEY_DIM = 1 << 28 +MATRIX_FADE_STEPS = 4 # dither levels: 0 = bare rain; STEPS = fully dim +# entry ramp: the dim does not re-press every in-box pixel with a level +# (that multiplied the pen space per level and stuttered the fade-in — +# burst-created pens + heap dips at dict growth); instead the box is dimmed +# through an ordered 4x4 Bayer pattern: at level L every box pixel whose +# threshold < L draws dim, so the dim patch spreads over the text box in a +# regular sweep while *no* pen is created for the fade itself — a level +# step costs nothing per frame and the ramp stays at full fps. +_BAYER4 = ((0, 2, 0, 2), (3, 1, 3, 1), (0, 2, 0, 2), (3, 1, 3, 1)) +# exit: no dedicated pour phase — the moment the mode ends, the dim box +# lifts, the full rain pours over the still-bright clock AND the clock's +# ink starts converting to droplets one pixel at a time (organic: each +# pixel's conversion step and fall speed come from a hash), falling off +# the bottom like the rest of the rain. +MATRIX_STAGGER_STEPS = 4 # the ink-to-drop conversion waves through: + # ~1/4 of the clock converts per step, so the + # crumble is obvious from the very first step + # (a finer 9-step spread read as a separate + # "pour" stage first, crumble later) +MATRIX_DISSOLVE_STEPS = (MATRIX_STAGGER_STEPS + 10) + # stagger - 1 (the last conversion step) + 9 rows + # of travel for the slowest stride-1 drop from the + # top ink row + 2 trail rows — exactly the step + # where the last trail pixel clears the bottom: + # the mode ends with the clock fully gone, no + # bare-rain epilogue after it + + +# bitmap6 digits, embedded (same bytes as sim/font6_data.py, itself a copy +# of Pimoroni's frozen font): the exit ramp needs per-pixel access to the +# glyph shapes and the board's PicoGraphics can't read its own text back. +# Each glyph is column bytes; bit r of byte c = pixel (c, r), 6 rows tall. +# tests/test_display.py pins this copy against the real font via the sim. +_DIGIT_GLYPHS = { + "0": (28, 34, 34, 34, 30, 0), "1": (2, 62, 0, 0, 0, 0), + "2": (50, 42, 42, 36, 0, 0), "3": (42, 42, 42, 22, 0, 0), + "4": (14, 16, 16, 62, 16, 0), "5": (46, 42, 42, 18, 0, 0), + "6": (60, 42, 42, 42, 18, 0), "7": (6, 2, 34, 18, 14, 0), + "8": (20, 42, 42, 42, 22, 0), "9": (4, 42, 42, 42, 30, 0), +} +_DIGIT_WIDTHS = (5, 2, 4, 4, 5, 4, 5, 5, 5, 5) # bitmap6 widths for 0..9 + + +_FADE_TAB = {L * SUB: _build_fade(L * SUB) for L in (4, 5, 6)} + + +def draw_matrix(d, w, h, frame, dim_mask=None): + """Green code-rain falling down the whole matrix: one anti-aliased drop + per column, staggered speeds and phases (five speed/brightness tiers, + see MATRIX_TIERS), head pixel cycling through MATRIX_TINTS and settling + to its pass hue halfway down; trail pixels keep their emission-time hue. + dim_mask (rain-clock overlay, draw_rain_clock) is a w*h bytearray + laid out [x * h + j] holding the fade level (0..MATRIX_FADE_STEPS): an + in-box pixel draws dim when its Bayer threshold is under that level + (level STEPS dims every box pixel); a bare rain has no mask at all. + Fixed-point math only — identical output on board and host sim. + Rasterizer is board-tuned: no min/max calls, memoized pens, bound + attribute lookups.""" + SUB2 = SUB // 2 + set_pen = d.set_pen + pixel = d.pixel + create_pen = d.create_pen + memo = _PEN_MEMO + mget = memo.get + mask = dim_mask + for x in range(w): + c16, L16, bright, seed_v = matrix_col(x, h, frame) + if L16 == 0: # resting pass: the cov math below would + continue # draw nothing anyway; skip its overhead + lo = c16 - L16 # streak top edge (may be < 0) + j0 = lo // SUB + if j0 < 0: + j0 = 0 + j1 = (c16 - 1) // SUB # row holding the head + if j1 > h - 1: + j1 = h - 1 + # the head settles at its pass hue halfway down the loop + settle_pos = ((h + _gap_of(x)) * SUB) // 2 + fade = _FADE_TAB[L16] + mo = x * h if mask else 0 # dim-mask column base + for j in range(j0, j1 + 1): + top = j * SUB + # coverage = overlap of pixel [j, j+1) with streak [lo, c16], + # inlined min/max + cov = (c16 if c16 < top + SUB else top + SUB) \ + - (lo if lo > top else top) + if cov <= 0: + continue + # hue: the head row uses the live position; rows the head has + # already passed freeze at their emission position + pos = c16 if c16 < top + SUB else top + SUB + # head-hue schedule (tint_at inlined): the head cycles hues + # several times per row of travel; base passes mostly stay on + # the classic green, accent passes cycle the accents + if pos >= settle_pos: + ti = seed_v + elif seed_v: + ti = 1 + (pos // MATRIX_CHURN_SUB + seed_v - 1) % N_ACCENT + elif (pos // MATRIX_CHURN_SUB) % 4 == 3: + ti = 1 if ((pos // MATRIX_CHURN_SUB) // 4) % 2 == 0 else 3 + else: + ti = 0 + # log-shaped fade with distance behind the head (center-based + # weight, clamped) — see _FADE_TAB above the pen memo + dc = c16 - top - SUB2 + if dc < 0: + dc = 0 + elif dc >= L16: + dc = L16 - 1 + a = cov * fade[dc] # 0..SUB*L16 alpha numerator + if mask: + # fade-level dither (see _BAYER4): the mask byte carries the + # ramp level; a pixel draws dim the moment the level sweeps + # past its Bayer threshold — no per-level pens exist at all + if mask[mo + j] > _BAYER4[x & 3][j & 3]: + a = a * MATRIX_DIM // 100 + is_dim = True + else: + is_dim = False + else: + is_dim = False + # memo key: alpha is quantized to its top 4 bits' index (q, at + # most ~89 levels) — without this the exact subpixel alpha set + # grows with every frame's fractional head position and the memo + # is effectively unbounded (filled the heap in ~3 s on board); + # pens are built from the bucket MIDPOINT so colors are + # order-independent and identical on sim and board. a < 2**11, + # so q < 2**7; ti < 8; bright <= 100, L16 < 2**7; bit 28 marks a + # dim-masked pixel (rain-clock overlay) so the darkened alpha + # space never shares a pen with the full-brightness one. + if is_dim: + # in-box dimmed pixels sit behind the dim mask and the + # digits: the 4-bit bucket count is invisible there, and a + # full 120 s rain once measured 4831 pens (2.3x the bare + # memo) and collapsed the heap at dict growth (the ERR-on- + # press bug). The 2-bit bucket count keeps the overlay's + # share of the memo small. + sh = 6 + else: + sh = 4 + q = a >> sh # bucket index (floor, as before) + key = (q | (ti << 8) | (bright << 12) | (L16 << 19) | + (_KEY_DIM if is_dim else 0)) + pen = mget(key) + if pen is None: + am = (q << sh) + (1 << (sh - 1)) # bucket midpoint alpha + den = SUB * L16 * 100 + tc = MATRIX_TINTS[ti] + pen = create_pen(tc[0] * am * bright // den, + tc[1] * am * bright // den, + tc[2] * am * bright // den) + memo[key] = pen + set_pen(pen) + pixel(x, j) + + +def _clock_ink(d, w, h, hh, mm): + """The clock's ink as [(x, y, convert_at, fall_speed)] over the same + layout math draw_clock uses (no blink dots): x/y from the embedded + digit glyphs, convert_at = the dissolve step this pixel turns into a + drop (hashed: staggered, organic — never the whole clock at once, and + never before the pour is over), fall_speed = 1 or 2 rows per step. + Cached per (hh, mm, w): it only changes once a minute.""" + global _INK_CACHE + key = (hh, mm, w) + if _INK_CACHE is not None and _INK_CACHE[0] == key: + return _INK_CACHE[1] + ink = [] + slots = clock_digit_x((w - CLOCK_W) // 2) + for base, s in ((slots[0], hh), (slots[2], mm)): + for i, ch in enumerate(s): + px0 = base + i * CLOCK_SLOT + for r, bits in enumerate(CLOCK_GLYPHS[ch]): + for c in range(5): + if bits >> (4 - c) & 1: + px = px0 + c + py = TEXT_Y + r + if py < h: + hs = _hash16(px + py * w, 4) + ink.append(( + px, py, + hs % MATRIX_STAGGER_STEPS, + 1 + (hs >> 7) % 2)) + _INK_CACHE = (key, ink) + return ink + + +def _dissolve_draw(d, w, h, hh, mm, frame, dissolve): + """The exit ramp's frames: the unconverted ink stays lit under the + pouring field (draw_matrix overdraws it — drops cross the digits); + converted pixels fall as bright drops with a dimming 2-row trail.""" + create_pen = d.create_pen + ink = create_pen(*CLOCK_WHITE) + # the converted pixel: a full-brightness drop in the classic rain green + hr, hg, hb = MATRIX_TINTS[0] + head_pen = create_pen(hr, hg, hb) + # trail pens: the drop's two previous positions, dimmer with distance + dim1 = create_pen(hr * 55 // 100, hg * 55 // 100, hb * 55 // 100) + dim2 = create_pen(hr * 25 // 100, hg * 25 // 100, hb * 25 // 100) + for (x, y, s, stride) in _clock_ink(d, w, h, hh, mm): + if dissolve <= s: # still part of the text: lit ink + d.set_pen(ink) + d.pixel(x, y) + continue + head = y + (dissolve - s) * stride + for back, pen in ((2, dim2), (1, dim1), (0, head_pen)): + yy = head - back * stride + if 0 <= yy < h: + d.set_pen(pen) + d.pixel(x, yy) + + +def draw_rain_clock(d, w, h, hh, mm, blink, frame, fade=MATRIX_FADE_STEPS, + dissolve=0): + """Clock rendered through the matrix rain (the mode shown while button + A's rain deadline is live): the field keeps falling everywhere, but its + alpha is scaled down inside the clock's padded text box so the bright + digits read clearly while drops visibly pour across them. fade phases + the overlay in (matrix mode's entry): 0 = bare rain, no digits; + MATRIX_FADE_STEPS = the full overlay. Digit brightness rides the same + fade, so the clock materializes out of the field instead of popping in. + dissolve phases it out (the exit, starting immediately): the dim box + lifts, the full-strength rain pours across the still-bright clock and + the ink converts to drops one pixel at a time (organic stagger) while + it falls off the bottom like the rest of the rain — no dedicated pour + step, the two happen together. Blink and the + HH/MM layout reuse draw_clock's math (via the embedded ink map); same + contract as the plain rain (frame tick only).""" + clear(d, w, h) # draw_matrix only paints the rain pixels + if dissolve > 0: # exit ramp: rain pours over, ink falls + _dissolve_draw(d, w, h, hh, mm, frame, dissolve) + draw_matrix(d, w, h, frame) # the rain overdraws ink + exit drops + return + if fade <= 0: # bare rain: no box, no digits + draw_matrix(d, w, h, frame) + return + # the digits brighten on the same quantized ramp as the box dithers in — + # one interpolated pen per frame (draw_clock converges blink pixels onto + # it) + dh = CLOCK_WHITE[0] * fade // MATRIX_FADE_STEPS + # the mask buffer is reused across frames — a fresh bytearray every + # frame poked the GC (which scans the big pen-memo dict) and showed up + # as fps drops on board; zeroing the cached one is a C-speed slice copy + global _RC_MASK, _RC_ZEROS + mask = _RC_MASK + if mask is None or len(mask) != w * h: + _RC_MASK = bytearray(w * h) + _RC_ZEROS = bytes(w * h) + mask = _RC_MASK + else: + mask[:] = _RC_ZEROS + # same layout math as draw_clock, padded a pixel on each side; each box + # pixel carries the fade level so draw_matrix can compare it against the + # pixel's Bayer threshold (see _BAYER4) — the dither dim is free of pens + colon_adv = 3 + tw = d.measure_text(hh, 1) + colon_adv + d.measure_text(mm, 1) + x0 = max(0, (w - tw) // 2 - 1) + x1 = min(w, x0 + tw + 2) + for x in range(x0, x1): + for j in range(1, min(h, TEXT_Y + 7)): + mask[x * h + j] = fade + draw_matrix(d, w, h, frame, dim_mask=mask) + draw_clock(d, w, h, hh, mm, blink, color=(dh, dh, dh)) + + +# rain-clock dim mask, reused across frames (see draw_rain_clock) +_RC_MASK = None +_RC_ZEROS = None +# the exit ramp's ink map, cached per clock text (see _clock_ink) +_INK_CACHE = None diff --git a/src/render.py b/src/render.py index e2a908b..a2596ff 100644 --- a/src/render.py +++ b/src/render.py @@ -6,6 +6,11 @@ (sim/sim.py, SimGraphics). No board imports in this module. `frame` is a monotonically increasing animation tick (board: int(time*3)). + +Split by concern: the palette, primitives and screen compositor live here; +the weather art (forecast icon + backdrop scenes) in scenes.py, and the +matrix-rain family (rain field + rain-clock overlay) in matrix.py. Both import +the palette from this module; nothing here imports them. """ # --- palette --------------------------------------------------------------- @@ -28,7 +33,10 @@ FOG = (150, 150, 165) HI = (255, 90, 60) LO = (90, 140, 255) -CLOCK = (120, 200, 255) +CLOCK_WHITE = (230, 230, 230) # the big clock's ink: slightly under full + # WHITE so the face with the most ink doesn't + # dominate the widgets (the room-level dimmer + # is main.py's gu.set_brightness) MSG = (255, 160, 40) CO2_WARN_PPM = 800 # at/above this the CO2 font goes amber CO2_RED_PPM = 1200 # at/above this it goes red — and the audible alarm fires @@ -38,699 +46,125 @@ TEXT_Y = 2 +# the dashboard's widget zone: one right-anchored widget (weather icon + +# temp, hi/lo pair, or the CO2 readout) that rotates every few seconds while +# the clock stays in [0, WIDGET_X0 - 2) — the zone keeps a fixed width so +# widgets never move when they rotate +WIDGET_X0 = 31 + def clear(d, w, h): d.set_pen(d.create_pen(*BLACK)) d.rectangle(0, 0, w, h) -def kind_of(code): - if code in (0, 1): - return "clear" - if code == 2: - return "partly" - if code == 3: - return "cloud" - if code in (45, 48): - return "fog" - if code >= 95: - return "storm" - if code in (85, 86): - return "snow" - if code >= 80: - return "showers" - if code == 75: - return "heavysnow" - if code >= 71: - return "snow" - if code == 65: - return "heavyrain" - if code in (51, 53, 55): - return "drizzle" - return "rain" - - -# --- animated weather icon, 10x11 in the left part of the matrix ----------- -# Hand-drawn 10x11 pixel icons (tuned visually in the sim), animated per kind: -# twinkling sun rays and stars, shaded cloud underside, drifting fog bands, -# falling rain/snow streaks, flashing bolt. - -# Cloud occupies rows 1..6, leaving rows 7..10 for precipitation: FALL_ROWS -# rows of falling drops, staggered per column so they never move in lockstep. -# y = CLOUD_BOTTOM + (frame//speed + phase) % FALL_ROWS increases every tick -# and wraps at the bottom -> drops always fall down and respawn at the top. -CLOUD_BOTTOM = 7 -FALL_ROWS = 4 # rows 7..10 - -# 10-wide cloud as (y, x_from, x_to, color): a darker back puff (CLOUD, -# shifted left, rows 1-3 plus one pixel below at (4,1) to round its bottom — -# a solid contiguous blob, so nothing protrudes) with the pure-white body on -# the right whose left side rises to row 2, plus a white pixel at 1-indexed -# (4,4) that rounds the top-left of the front puff, so the back cloud's left -# side stays visible; interior CLOUD_MID flecks; flat bottom, corners cut. -CLOUD_ROWS = ( - (1, 1, 3, CLOUD), - (2, 0, 4, CLOUD), - (3, 0, 2, CLOUD), - (4, 1, 1, CLOUD), # rounds the back puff's bottom - (1, 6, 7, WHITE), - (2, 4, 8, WHITE), - (3, 3, 9, WHITE), # includes the rounding pixel at 1-indexed (4,4) - (4, 2, 9, WHITE), - (5, 2, 9, WHITE), - (6, 3, 8, WHITE), - (4, 5, 5, CLOUD_MID), # texture flecks - (5, 6, 6, CLOUD_MID), -) - -# Same two-fluff cloud pushed right/down for partly cloudy (and night -# precipitation), so the sun/moon is tucked *behind* it — drawn first, the -# cloud covers its lower right, which reads as "peeking out". -PARTLY_CLOUD_ROWS = ( - (2, 6, 7, WHITE), - (3, 4, 9, WHITE), - (4, 3, 9, WHITE), - (5, 3, 9, WHITE), - (6, 4, 8, WHITE), - (4, 6, 6, CLOUD_MID), - (5, 5, 5, CLOUD_MID), -) - -# 5-wide sun disc (corners cut), symmetric about x=5, rows 3..7; single rays. -SUN_CORE_ROWS = ((3, 4, 6), (4, 3, 7), (5, 3, 7), (6, 3, 7), (7, 4, 6)) -SUN_RAYS = ((5, 1), (5, 9), (1, 5), (9, 5), (2, 2), (8, 2), (2, 8), (8, 8)) - -# Small 3x3 sun peeking out top-left for partly cloudy day. -SMALL_SUN_CORE_ROWS = ((1, 1, 3), (2, 1, 3), (3, 1, 3)) -SMALL_SUN_RAYS = ((2, 0), (0, 2), (4, 2)) - -# Round full moon (clear night) — a clean disc (no bite/knob, not C-shaped) -# plus its stars, which twinkle dim/bright (slow), not on/off. -MOON_PX = ((4, 2), (5, 2), (6, 2), - (3, 3), (4, 3), (5, 3), (6, 3), (7, 3), - (3, 4), (4, 4), (5, 4), (6, 4), (7, 4), - (3, 5), (4, 5), (5, 5), (6, 5), (7, 5), - (4, 6), (5, 6), (6, 6)) -MOON_STARS = ((8, 1), (1, 9)) -STAR_DIM = (110, 110, 100) - -# Small quarter moon for partly cloudy night / night precipitation, top-left: -# the full disc stays visible (dark half in MOON_DARK, high contrast) with -# the left half plus the other top pixel lit — reads as a quarter moon, -# not a "C". -SMALL_MOON_PX = ((2, 0), (3, 0), - (1, 1), (2, 1), (3, 1), (4, 1), - (1, 2), (2, 2), (3, 2), (4, 2), - (1, 3), (2, 3), (3, 3), (4, 3), - (2, 4), (3, 4)) -SMALL_MOON_LIT = tuple((x, y) for (x, y) in SMALL_MOON_PX if x <= 2) + ((3, 0),) -MOON_DARK = (55, 55, 52) - -# Lightning bolt, rows 7..10, 2-px zigzag (flashes on alternate frames). -BOLT_PX = ((6, 7), (5, 8), (6, 8), (4, 9), (5, 9), (4, 10), (5, 10)) - - -def _rows(d, ox, oy, rows, dx=0, dy=0): - for (y, xa, xb, col) in rows: - d.set_pen(d.create_pen(*col)) - d.rectangle(ox + xa + dx, oy + y + dy, xb - xa + 1, 1) - - -def _cloud(d, ox, oy, dark=False, dy=0): - # storm cloud: same shape, dark body, darker left bump, light flecks - tone = {WHITE: STORM_CLOUD, CLOUD: STORM_SHADE, CLOUD_MID: STORM_HI, - CLOUD_SHADE: STORM_SHADE} - rows = [] - for (y, xa, xb, col) in CLOUD_ROWS: - if dark: - col = tone[col] - rows.append((y, xa, xb, col)) - _rows(d, ox, oy, rows, dy=dy) - - -def _sun(d, ox, oy, frame): - _rows(d, ox, oy, [(y, xa, xb, SUN) for (y, xa, xb) in SUN_CORE_ROWS]) - for i, (x, y) in enumerate(SUN_RAYS): - # twinkle: alternate rays dim/bright - d.set_pen(d.create_pen(*(SUN if (i + frame) % 2 == 0 else SUN_DIM))) - d.pixel(ox + x, oy + y) - - -def _small_sun(d, ox, oy, frame): - _rows(d, ox, oy, [(y, xa, xb, SUN) for (y, xa, xb) in SMALL_SUN_CORE_ROWS]) - for i, (x, y) in enumerate(SMALL_SUN_RAYS): - d.set_pen(d.create_pen(*(SUN if (i + frame) % 2 == 0 else SUN_DIM))) - d.pixel(ox + x, oy + y) - - -def _moon(d, ox, oy, frame): - d.set_pen(d.create_pen(*MOON)) - for (x, y) in MOON_PX: - d.pixel(ox + x, oy + y) - for i, (x, y) in enumerate(MOON_STARS): - # stars twinkle dim/bright at half rate — no hard on/off blink - d.set_pen(d.create_pen(*(SNOW if (i + frame // 2) % 2 == 0 else STAR_DIM))) - d.pixel(ox + x, oy + y) - - -def _small_moon(d, ox, oy): - for (x, y) in SMALL_MOON_PX: - col = MOON if (x, y) in SMALL_MOON_LIT else MOON_DARK - d.set_pen(d.create_pen(*col)) - d.pixel(ox + x, oy + y) - - -def _fog(d, ox, oy, frame): - # fog = drifting bands only (no cloud, so it cannot be mistaken for rain); - # each band is two 4-px segments at staggered heights -> a wavy staircase - d.set_pen(d.create_pen(*FOG)) - for r, y in enumerate((2, 4, 6, 8)): - xa = (frame // 2 + r) % 3 - d.rectangle(ox + xa, oy + y, 4, 1) - d.rectangle(ox + xa + 4, oy + y + 1, 4, 1) - - -def _fall(d, ox, oy, frame, cols, color, speed=1, streak=1): - d.set_pen(d.create_pen(*color)) - for i, x in enumerate(cols): - top = (frame // speed + i) % FALL_ROWS - for s in range(streak): - if top + s < FALL_ROWS: # streak exits at the bottom, then respawns - d.pixel(ox + x, oy + CLOUD_BOTTOM + top + s) - - -def draw_icon(d, code, frame, ox=0, oy=0, is_day=1): - kind = kind_of(code) - if kind == "clear": - if is_day: - _sun(d, ox, oy, frame) - else: - _moon(d, ox, oy, frame) - return - if kind == "partly": - # no precipitation rows needed: shift the whole group down so the - # icon is vertically centered in the 11-row area - if is_day: - _small_sun(d, ox, oy + 2, frame) - else: - _small_moon(d, ox, oy + 2) - _rows(d, ox, oy, PARTLY_CLOUD_ROWS, dy=2) - return - if kind == "cloud": - _cloud(d, ox, oy, dy=2) # no rain: center vertically - return - if kind == "fog": - _fog(d, ox, oy, frame) - return - # precipitating kinds: cloud (dark for storm) + animated drops; at night a - # small moon is tucked behind the cloud and the drops fall under the cloud - if kind == "storm": - _cloud(d, ox, oy, dark=True) - if frame % 2 == 0: - d.set_pen(d.create_pen(*BOLT)) - for (x, y) in BOLT_PX: - d.pixel(ox + x, oy + y) - _fall(d, ox, oy, frame, (2, 8), RAIN, speed=2) - return - night = not is_day - if night: - _small_moon(d, ox, oy) - _rows(d, ox, oy, PARTLY_CLOUD_ROWS) - else: - _cloud(d, ox, oy) - if kind == "drizzle": - _fall(d, ox, oy, frame, (5, 8) if night else (3, 6), RAIN, speed=2) - elif kind == "heavyrain": - _fall(d, ox, oy, frame, (2, 4, 6, 8) if night else (1, 3, 5, 7, 9), - RAIN, streak=2) - elif kind == "showers": - if frame % 6 < 4: # intermittent - _fall(d, ox, oy, frame, (4, 6, 8) if night else (2, 5, 8), - RAIN, streak=2) - elif kind == "heavysnow": - _fall(d, ox, oy, frame, (3, 5, 7, 9) if night else (1, 3, 5, 7, 9), - SNOW, speed=2) - elif kind == "snow": - _fall(d, ox, oy, frame, (4, 6, 8) if night else (2, 4, 6, 8), SNOW, speed=2) - else: # rain - _fall(d, ox, oy, frame, (4, 6, 8) if night else (2, 4, 6, 8), RAIN, - streak=2) - - -# --- animation mode: matrix rain -------------------------------------------- -# Full-matrix digital-rain fun screen. Same contract as the weather icons: no -# time, no randomness — everything derives from the `frame` tick, so sim and -# board stay identical. - -SUB = 16 # subpixel steps per row (fixed-point position) - -# Head-hue palette the falling head pixel cycles through. Tint 0 is the -# classic rain green — kept saturated rather than whitish so the field reads -# unmistakably green (~4 passes in 5, shimmering between the base tint and a -# subtle neighbor and settling back). The other passes cycle the subtle -# accent tints (compressed teal-ish and chartreuse-ish drifts, green channel -# pinned at 255, red/blue pulled down toward green) and settle on their -# assigned one. Still reads as green rain at a glance, just greener. -MATRIX_TINTS = ( - (170, 255, 130), - (150, 255, 150), - (128, 255, 170), - (198, 255, 100), - (218, 255, 88), -) -N_ACCENT = 4 # tints 1..N_ACCENT are the accent hues -MATRIX_CHURN_SUB = SUB // 4 # one hue step per quarter-row of travel: - # the head pixel cycles tints several times - # per row it drops (fast shimmer) -# tier = (rows, per, brightness %). Every tier's phase advances a -# non-integer number of rows per tick (per never divides rows*SUB), so -# anti-aliased heads glide instead of stepping. Brightness grows with -# speed: fast reads near, slow reads far. At the 1/30 s tick these are -# ~3.75 / 5 / 7.5 / 10 / 15 rows per second. -MATRIX_TIERS = ( - (1, 8, 50), # crawl, dim — the "far background" - (1, 6, 65), # slow - (1, 4, 80), # mid - (4, 12, 90), # brisk - (1, 2, 100), # sprint, full brightness -) - - -def _hash16(x, salt): - """16-bit multiplicative hash of (x, salt): adjacent inputs scatter and - every product stays a MicroPython small int (< 2**30, no bignum cost).""" - return ((x * 40503 & 0xFFFF) ^ (salt * 21649 & 0xFFFF)) & 0x3FFFFFFF - - -def _tier_of(x): - # per-column tier from a 16-bit hash — a plain modulo cycles too - # regularly; the hash scatters adjacent columns over all tiers - return (_hash16(x, 1) >> 4) % len(MATRIX_TIERS) - - -def _gap_of(x): - # blank stretch before respawn, per column, 4..11 rows: columns still - # differ in how densely they rain (duty 0.7..1.0 of the loop) but the - # board reads dense overall; the slower the tier, the longer the dark - # stretch lasts, which reads as depth - return 4 + (_hash16(x, 2) >> 6) % 8 - - -def matrix_col(x, h, frame): - """Subpixel drop state of column x at frame: (c16, L16, bright, seed) — - head position in 1/SUB-row steps (mod the column loop), trail length in - rows (0 = resting pass: the column drops nothing this pass, so local - density breathes), tier brightness, and the per-pass LCG seed for the - head-hue schedule. Exposed for tuning and exact tests; draw_matrix only - rasterizes what this state implies. Trail length and the resting/active - decision mix from a hash over (column index and the pass number — one - pass = one full drop travel), so density, speed mix, hue and trail vary - pass to pass while staying deterministic. Constants stay under 2**30 so - every product is a MicroPython small int — no bignum allocation per - column and frame (a 32-bit LCG constant measured ~16 ms/frame slower).""" - tier = _tier_of(x) - rows, per, bright = MATRIX_TIERS[tier] - gap = _gap_of(x) - loop16 = (h + gap) * SUB - u = (rows * SUB * frame) // per + (x * 37) * SUB # + per-column phase - pass_idx = u // loop16 # one pass = one full drop travel - mix = _hash16(x, pass_idx) - L = 4 + (mix >> 8) % 3 # 4..6 rows of trail per pass - if (mix >> 3) % 10 == 0: # ~1 pass in 10 rests: density breathes - L = 0 - # head hue: ~1 pass in 5 takes an accent tint (1..N_ACCENT), the rest - # stay classic green (seed 0) — every pass shimmers its bottom pixel - variant = (mix >> 5) % 5 - seed = 1 + (mix >> 11) % N_ACCENT if variant == 0 else 0 - return u % loop16, L * SUB, bright, seed - - -def tint_at(seed, pos16, settle_pos16): - """Head-hue schedule (the bottom-pixel shimmer). The head drops one - row and cycles several hues within that row (one churn step per - quarter-row), then — halfway down the pass — settles on its pass tint - for the rest of the fall. seed 0 = classic green pass, mostly the base - tint with a dip into a subtle neighbor on every 4th step; accent - passes (seed 1..N_ACCENT) cycle the accent tints. Trail pixels keep - the hue the head had when it passed them.""" - if pos16 >= settle_pos16: - return seed - step = pos16 // MATRIX_CHURN_SUB - if seed == 0: - if step % 4 != 3: - return 0 - return 1 if (step // 4) % 2 == 0 else 3 - return 1 + (step + seed - 1) % N_ACCENT - - -# Pen memo for draw_matrix: the pixel color depends on (tint, bright, L16, -# alpha bucket) — only ~89 alpha buckets exist per (L16, bright, tint) — so -# pens are cached in a dict keyed by one int -# (bucket | tint<<8 | bright<<12 | L16<<19) instead of re-creating a pen per -# pixel. The bucket quantization bounds the memo (~few thousand entries, a -# few KB); exact-alpha keys proved effectively unbounded (heap full in ~3 s -# on board with the sub-integer rows/tick tiers). Board benchmark of this -# loop: 41 ms/frame naive -> ~29 ms (scanout stays ~2 ms). -_PEN_MEMO = {} - -# Log-shaped trail-fade table: alpha weight per subpixel distance behind the -# head, exponential decay with a 2-row half-life (×2^(-1/32) per subpixel -# step, integer fixed point, ×251/256). Fades a bit faster early than the -# linear ramp it replaces, then levels off into a long dim tail — visually a -# log curve (linear's tail end is ~1.6% of head brightness, this keeps ~11%). -# The half-life can't be much shorter: the pixel holding the head sits at -# clamped dc 0..8, so f^8 sets its dimmest subpixel step (0.85 here) — steeper -# curves dip the "live" head well below the strongly-green threshold. Built -# at import for the only three trail lengths matrix_col ever yields -# (L = 4..6 rows → L16 = 64/80/96); draw_matrix indexes the dict directly, -# since a per-column builder call measured ~2.7 ms/frame extra. Weights stay -# <= L16 <= 96, so a byte holds each. Index is the clamped center distance -# dc the loop already computes; f[0] = L16 is the reference full brightness. -def _build_fade(L16): - f = bytearray(L16) - w = L16 << 8 - for i in range(L16): - f[i] = w >> 8 - w = w * 251 >> 8 - return f - - -# The rain-clock overlay: rain inside the clock's text box is dimmed toward -# MATRIX_DIM % of its alpha (draw_matrix's optional dim_mask, built by -# draw_rain_clock), so the bright digits read over the pouring field even -# where a drop head passes directly behind them. The level is a flag in the -# pen-memo key (bit 28, above L16's last bit 25) so the dimmed pens never -# collide with the full-brightness ones of the same alpha bucket. -MATRIX_DIM = 35 # % of full alpha at the overlay's full strength -_KEY_DIM = 1 << 28 -MATRIX_FADE_STEPS = 4 # dither levels: 0 = bare rain; STEPS = fully dim -# entry ramp: the dim does not re-press every in-box pixel with a level -# (that multiplied the pen space per level and stuttered the fade-in — -# burst-created pens + heap dips at dict growth); instead the box is dimmed -# through an ordered 4x4 Bayer pattern: at level L every box pixel whose -# threshold < L draws dim, so the dim patch spreads over the text box in a -# regular sweep while *no* pen is created for the fade itself — a level -# step costs nothing per frame and the ramp stays at full fps. -_BAYER4 = ((0, 2, 0, 2), (3, 1, 3, 1), (0, 2, 0, 2), (3, 1, 3, 1)) -# exit: no dedicated pour phase — the moment the mode ends, the dim box -# lifts, the full rain pours over the still-bright clock AND the clock's -# ink starts converting to droplets one pixel at a time (organic: each -# pixel's conversion step and fall speed come from a hash), falling off -# the bottom like the rest of the rain. -MATRIX_STAGGER_STEPS = 4 # the ink-to-drop conversion waves through: - # ~1/4 of the clock converts per step, so the - # crumble is obvious from the very first step - # (a finer 9-step spread read as a separate - # "pour" stage first, crumble later) -MATRIX_DISSOLVE_STEPS = (MATRIX_STAGGER_STEPS + 10) - # stagger - 1 (the last conversion step) + 9 rows - # of travel for the slowest stride-1 drop from the - # top ink row + 2 trail rows — exactly the step - # where the last trail pixel clears the bottom: - # the mode ends with the clock fully gone, no - # bare-rain epilogue after it - - -# bitmap6 digits, embedded (same bytes as sim/font6_data.py, itself a copy -# of Pimoroni's frozen font): the exit ramp needs per-pixel access to the -# glyph shapes and the board's PicoGraphics can't read its own text back. -# Each glyph is column bytes; bit r of byte c = pixel (c, r), 6 rows tall. -# tests/test_display.py pins this copy against the real font via the sim. -_DIGIT_GLYPHS = { - "0": (28, 34, 34, 34, 30, 0), "1": (2, 62, 0, 0, 0, 0), - "2": (50, 42, 42, 36, 0, 0), "3": (42, 42, 42, 22, 0, 0), - "4": (14, 16, 16, 62, 16, 0), "5": (46, 42, 42, 18, 0, 0), - "6": (60, 42, 42, 42, 18, 0), "7": (6, 2, 34, 18, 14, 0), - "8": (20, 42, 42, 42, 22, 0), "9": (4, 42, 42, 42, 30, 0), +CLOCK_SLOT = 6 # every big-clock digit sits in its own fixed 6 px slot: + # bitmap6 ink is <= 5 wide, so a slot always keeps the + # 1 px minimum gap (two adjacent 5-wide digits — "48" — + # must not touch), and the layout cannot move when the + # displayed digits change +CLOCK_COLON = 2 # reserved px between the HH and MM blocks: 1 pad either + # side of the 1-ink-col dot — so the dot sits exactly 1 px + # from the digit ink on both sides +CLOCK_W = (2 * CLOCK_SLOT + CLOCK_COLON + 2 * CLOCK_SLOT) # 'HH:MM' block + + +def clock_digit_x(x0): + """Fixed columns (ink left edges) of the four clock digits from the + block origin x0: (hh_tens, hh_units, mm_tens, mm_units). Shared by + draw_clock and the rain-clock's dissolve ink map.""" + return (x0, + x0 + CLOCK_SLOT, + x0 + 2 * CLOCK_SLOT + CLOCK_COLON, + x0 + 3 * CLOCK_SLOT + CLOCK_COLON) + + +# 3x5 overlay glyphs for small secondary text (the dashboard's temperature +# and the like) — one row tuple per glyph, bit 2 of a row = the left pixel. +# Matches the design reference (docs/reference/, local); advance is a fixed +# 4 px (3 glyph + 1 space), so small_text_width() is exact. Embedded here +# rather than font6-sourced: this face is ours, not Pimoroni's. +_OVL_GLYPHS = { + "0": (7, 5, 5, 5, 7), "1": (2, 6, 2, 2, 7), + "2": (7, 1, 7, 4, 7), "3": (7, 1, 7, 1, 7), + "4": (5, 5, 7, 1, 1), "5": (7, 4, 7, 1, 7), + "6": (7, 4, 7, 5, 7), "7": (7, 1, 2, 2, 2), + "8": (7, 5, 7, 5, 7), "9": (7, 5, 7, 1, 7), + "-": (0, 0, 7, 0, 0), "°": (3, 3, 0, 0, 0), + "C": (7, 4, 4, 4, 7), "O": (7, 5, 5, 5, 7), } -_DIGIT_WIDTHS = (5, 2, 4, 4, 5, 4, 5, 5, 5, 5) # bitmap6 widths for 0..9 - - -_FADE_TAB = {L * SUB: _build_fade(L * SUB) for L in (4, 5, 6)} - - -def draw_matrix(d, w, h, frame, dim_mask=None): - """Green code-rain falling down the whole matrix: one anti-aliased drop - per column, staggered speeds and phases (five speed/brightness tiers, - see MATRIX_TIERS), head pixel cycling through MATRIX_TINTS and settling - to its pass hue halfway down; trail pixels keep their emission-time hue. - dim_mask (rain-clock overlay, draw_rain_clock) is a w*h bytearray - laid out [x * h + j] holding the fade level (0..MATRIX_FADE_STEPS): an - in-box pixel draws dim when its Bayer threshold is under that level - (level STEPS dims every box pixel); a bare rain has no mask at all. - Fixed-point math only — identical output on board and host sim. - Rasterizer is board-tuned: no min/max calls, memoized pens, bound - attribute lookups.""" - SUB2 = SUB // 2 - set_pen = d.set_pen - pixel = d.pixel - create_pen = d.create_pen - memo = _PEN_MEMO - mget = memo.get - mask = dim_mask - for x in range(w): - c16, L16, bright, seed_v = matrix_col(x, h, frame) - if L16 == 0: # resting pass: the cov math below would - continue # draw nothing anyway; skip its overhead - lo = c16 - L16 # streak top edge (may be < 0) - j0 = lo // SUB - if j0 < 0: - j0 = 0 - j1 = (c16 - 1) // SUB # row holding the head - if j1 > h - 1: - j1 = h - 1 - # the head settles at its pass hue halfway down the loop - settle_pos = ((h + _gap_of(x)) * SUB) // 2 - fade = _FADE_TAB[L16] - mo = x * h if mask else 0 # dim-mask column base - for j in range(j0, j1 + 1): - top = j * SUB - # coverage = overlap of pixel [j, j+1) with streak [lo, c16], - # inlined min/max - cov = (c16 if c16 < top + SUB else top + SUB) \ - - (lo if lo > top else top) - if cov <= 0: - continue - # hue: the head row uses the live position; rows the head has - # already passed freeze at their emission position - pos = c16 if c16 < top + SUB else top + SUB - # head-hue schedule (tint_at inlined): the head cycles hues - # several times per row of travel; base passes mostly stay on - # the classic green, accent passes cycle the accents - if pos >= settle_pos: - ti = seed_v - elif seed_v: - ti = 1 + (pos // MATRIX_CHURN_SUB + seed_v - 1) % N_ACCENT - elif (pos // MATRIX_CHURN_SUB) % 4 == 3: - ti = 1 if ((pos // MATRIX_CHURN_SUB) // 4) % 2 == 0 else 3 - else: - ti = 0 - # log-shaped fade with distance behind the head (center-based - # weight, clamped) — see _FADE_TAB above the pen memo - dc = c16 - top - SUB2 - if dc < 0: - dc = 0 - elif dc >= L16: - dc = L16 - 1 - a = cov * fade[dc] # 0..SUB*L16 alpha numerator - if mask: - # fade-level dither (see _BAYER4): the mask byte carries the - # ramp level; a pixel draws dim the moment the level sweeps - # past its Bayer threshold — no per-level pens exist at all - if mask[mo + j] > _BAYER4[x & 3][j & 3]: - a = a * MATRIX_DIM // 100 - is_dim = True - else: - is_dim = False - else: - is_dim = False - # memo key: alpha is quantized to its top 4 bits' index (q, at - # most ~89 levels) — without this the exact subpixel alpha set - # grows with every frame's fractional head position and the memo - # is effectively unbounded (filled the heap in ~3 s on board); - # pens are built from the bucket MIDPOINT so colors are - # order-independent and identical on sim and board. a < 2**11, - # so q < 2**7; ti < 8; bright <= 100, L16 < 2**7; bit 28 marks a - # dim-masked pixel (rain-clock overlay) so the darkened alpha - # space never shares a pen with the full-brightness one. - if is_dim: - # in-box dimmed pixels sit behind the dim mask and the - # digits: the 4-bit bucket count is invisible there, and a - # full 120 s rain once measured 4831 pens (2.3x the bare - # memo) and collapsed the heap at dict growth (the ERR-on- - # press bug). The 2-bit bucket count keeps the overlay's - # share of the memo small. - sh = 6 - else: - sh = 4 - q = a >> sh # bucket index (floor, as before) - key = (q | (ti << 8) | (bright << 12) | (L16 << 19) | - (_KEY_DIM if is_dim else 0)) - pen = mget(key) - if pen is None: - am = (q << sh) + (1 << (sh - 1)) # bucket midpoint alpha - den = SUB * L16 * 100 - tc = MATRIX_TINTS[ti] - pen = create_pen(tc[0] * am * bright // den, - tc[1] * am * bright // den, - tc[2] * am * bright // den) - memo[key] = pen - set_pen(pen) - pixel(x, j) - - -# --- screens -------------------------------------------------------------- - - -def _clock_ink(d, w, h, hh, mm): - """The clock's ink as [(x, y, convert_at, fall_speed)] over the same - layout math draw_clock uses (no blink dots): x/y from the embedded - digit glyphs, convert_at = the dissolve step this pixel turns into a - drop (hashed: staggered, organic — never the whole clock at once, and - never before the pour is over), fall_speed = 1 or 2 rows per step. - Cached per (hh, mm, w): it only changes once a minute.""" - global _INK_CACHE - key = (hh, mm, w) - if _INK_CACHE is not None and _INK_CACHE[0] == key: - return _INK_CACHE[1] - ink = [] - mhh = d.measure_text(hh, 1) - base_x = ((w - (mhh + 3 + d.measure_text(mm, 1))) // 2) - for base, s in ((base_x, hh), (base_x + mhh + 3, mm)): - cx = base - for ch in s: - o = ord(ch) - 48 - if 0 <= o <= 9: - cols = _DIGIT_GLYPHS[ch] - gw = _DIGIT_WIDTHS[o] - for col in range(gw): - bits = cols[col] - for row in range(6): - if bits >> row & 1: - px = cx + col - py = TEXT_Y + row - if py < h: - hs = _hash16(px + py * w, 4) - ink.append(( - px, py, - hs % MATRIX_STAGGER_STEPS, - 1 + (hs >> 7) % 2)) - cx += gw + 1 # one column of glyph + spacing, like font6 - else: - cx += 2 # gaps advance like measure_text - _INK_CACHE = (key, ink) - return ink - - -def _dissolve_draw(d, w, h, hh, mm, frame, dissolve): - """The exit ramp's frames: the unconverted ink stays white under the - pouring field (draw_matrix overdraws it — drops cross the digits); - converted pixels fall as bright drops with a dimming 2-row trail.""" - create_pen = d.create_pen - white = create_pen(255, 255, 255) - # the converted pixel: a full-brightness drop in the classic rain green - hr, hg, hb = MATRIX_TINTS[0] - head_pen = create_pen(hr, hg, hb) - # trail pens: the drop's two previous positions, dimmer with distance - dim1 = create_pen(hr * 55 // 100, hg * 55 // 100, hb * 55 // 100) - dim2 = create_pen(hr * 25 // 100, hg * 25 // 100, hb * 25 // 100) - for (x, y, s, stride) in _clock_ink(d, w, h, hh, mm): - if dissolve <= s: # still part of the text: white ink - d.set_pen(white) - d.pixel(x, y) - continue - head = y + (dissolve - s) * stride - for back, pen in ((2, dim2), (1, dim1), (0, head_pen)): - yy = head - back * stride - if 0 <= yy < h: - d.set_pen(pen) - d.pixel(x, yy) - - -def draw_rain_clock(d, w, h, hh, mm, blink, frame, fade=MATRIX_FADE_STEPS, - dissolve=0): - """Clock rendered through the matrix rain (the mode shown while button - A's rain deadline is live): the field keeps falling everywhere, but its - alpha is scaled down inside the clock's padded text box so the bright - digits read clearly while drops visibly pour across them. fade phases - the overlay in (matrix mode's entry): 0 = bare rain, no digits; - MATRIX_FADE_STEPS = the full overlay. Digit brightness rides the same - fade, so the clock materializes out of the field instead of popping in. - dissolve phases it out (the exit, starting immediately): the dim box - lifts, the full-strength rain pours across the still-bright clock and - the ink converts to drops one pixel at a time (organic stagger) while - it falls off the bottom like the rest of the rain — no dedicated pour - step, the two happen together. Blink and the - HH/MM layout reuse draw_clock's math (via the embedded ink map); same - contract as the plain rain (frame tick only).""" - clear(d, w, h) # draw_matrix only paints the rain pixels - if dissolve > 0: # exit ramp: rain pours over, ink falls - _dissolve_draw(d, w, h, hh, mm, frame, dissolve) - draw_matrix(d, w, h, frame) # the rain overdraws ink + exit drops - return - if fade <= 0: # bare rain: no box, no digits - draw_matrix(d, w, h, frame) - return - # the digits brighten on the same quantized ramp as the box dithers in — - # one interpolated pen per frame (draw_clock converges blink pixels onto - # it) - dh = 255 * fade // MATRIX_FADE_STEPS - # the mask buffer is reused across frames — a fresh bytearray every - # frame poked the GC (which scans the big pen-memo dict) and showed up - # as fps drops on board; zeroing the cached one is a C-speed slice copy - global _RC_MASK, _RC_ZEROS - mask = _RC_MASK - if mask is None or len(mask) != w * h: - _RC_MASK = bytearray(w * h) - _RC_ZEROS = bytes(w * h) - mask = _RC_MASK - else: - mask[:] = _RC_ZEROS - # same layout math as draw_clock, padded a pixel on each side; each box - # pixel carries the fade level so draw_matrix can compare it against the - # pixel's Bayer threshold (see _BAYER4) — the dither dim is free of pens - colon_adv = 3 - tw = d.measure_text(hh, 1) + colon_adv + d.measure_text(mm, 1) - x0 = max(0, (w - tw) // 2 - 1) - x1 = min(w, x0 + tw + 2) - for x in range(x0, x1): - for j in range(1, min(h, TEXT_Y + 7)): - mask[x * h + j] = fade - draw_matrix(d, w, h, frame, dim_mask=mask) - draw_clock(d, w, h, hh, mm, blink, color=(dh, dh, dh)) - - -# rain-clock dim mask, reused across frames (see draw_rain_clock) -_RC_MASK = None -_RC_ZEROS = None -# the exit ramp's ink map, cached per clock text (see _clock_ink) -_INK_CACHE = None - - -def draw_weather(d, w, h, code, temp_text, frame, is_day=1): - """Icon + temperature as one group, centered so no space is wasted right.""" - icon_w = 10 - gap = 3 - text_w = d.measure_text(temp_text, 1) - x0 = (w - (icon_w + gap + text_w)) // 2 - draw_icon(d, code, frame, ox=x0, oy=0, is_day=is_day) - d.set_pen(d.create_pen(*WHITE)) - d.text(temp_text, x0 + icon_w + gap, TEXT_Y, scale=1) +# per-glyph widths (everything else is 3): the degree sign is squeezed to +# 2 px so a 4-glyph minus temp (" -30°" family) stays narrow enough to +# leave a stable creature corridor between the gauge and the clock +_OVL_WIDTHS = {"°": 2} +_OVL_ADV = 4 # advance of a 3-wide glyph incl. its 1-px gap + +# the clock's digit face: a real 5x7 font — seven rows tall, ink left +# edge at the slot origin (see draw_clock); classic LED digit shapes, +# ours rather than Pimoroni's bitmap6 so the face is 7 rows (bitmap6's +# are 6) and the digits read bigger on the dashboard +CLOCK_GLYPHS = { + "0": (0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110), + "1": (0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110), + "2": (0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111), + "3": (0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110), + "4": (0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010), + "5": (0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110), + "6": (0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110), + "7": (0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000), + "8": (0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110), + "9": (0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100), +} + +def small_text_width(s): + """The pixel width of s drawn by draw_small_text() — 3-wide glyphs + advance 4, narrow glyphs (see _OVL_WIDTHS) advance width+1; the + trailing gap is subtracted. Unknown chars advance like a 3-wide + glyph, so widths stay predictable.""" + if not s: + return 0 + return sum(_OVL_WIDTHS.get(ch, 3) + 1 for ch in s) - 1 -def draw_clock(d, w, h, hh, mm, blink, color=None): - # color=None keeps the rotation's clock-cyan; the rain overlay passes the - # bright rain-white so the digits pop over the field - colon_adv = 3 # reserved px for the colon, keeps layout stable - tw = d.measure_text(hh, 1) + colon_adv + d.measure_text(mm, 1) - x = (w - tw) // 2 - d.set_pen(d.create_pen(*(color or CLOCK))) - d.text(hh, x, TEXT_Y, scale=1) + +def draw_small_text(d, w, h, s, x, y, color): + """Render s in the 3x5 overlay face at (x, y) = top-left pixel. + Chars missing from _OVL_GLYPHS (a literal space included) advance + like a 3-wide glyph. Clipped to the matrix like every other path.""" + d.set_pen(d.create_pen(*color)) + pixel = d.pixel + for ch in s: + g = _OVL_GLYPHS.get(ch) + gw = _OVL_WIDTHS.get(ch, 3) + if g is not None: + for r in range(5): + bits = g[r] + py = y + r + if not 0 <= py < h: + continue + for c in range(gw): + if bits >> (gw - 1 - c) & 1 and 0 <= x + c < w: + pixel(x + c, py) + x += gw + 1 + + +def draw_clock(d, w, h, hh, mm, blink, color=CLOCK_WHITE, x_bounds=None): + """The big clock: 5x7 digits in fixed slots (the layout never moves), + the colon as two drawn dots. x_bounds=(lo, hi): center inside [lo, hi] + instead of the full frame.""" + lo, hi = (0, w) if x_bounds is None else x_bounds + x0 = lo + (hi - lo - CLOCK_W) // 2 + d.set_pen(d.create_pen(*color)) + for ch, sx in zip(hh + mm, clock_digit_x(x0)): + for r, bits in enumerate(CLOCK_GLYPHS[ch]): + py = TEXT_Y + r + for c in range(5): + if bits >> (4 - c) & 1: + d.pixel(sx + c, py) if blink: # two pixels, 1 Hz blink driven by time.ticks_ms() on the board - cx = x + d.measure_text(hh, 1) + 1 - d.pixel(cx, 4) - d.pixel(cx, 7) - d.text(mm, x + d.measure_text(hh, 1) + colon_adv, TEXT_Y, scale=1) + cx = x0 + 2 * CLOCK_SLOT # 1 empty px after the HH ink, 1 before MM + d.pixel(cx, TEXT_Y + 2) + d.pixel(cx, TEXT_Y + 5) def _arrow(d, x, y, up): @@ -830,6 +264,10 @@ def draw_als(d, w, h, mn, mx, avg): d.text(text, x, TEXT_Y, scale=1) +# --- screens ---------------------------------------------------------------- +# (the art families live in scenes.py -- icons + backdrop scenes -- and +# matrix.py -- the matrix-rain field + rain-clock overlay) + def co2_color(ppm): """Indoor air quality: green below CO2_WARN_PPM, amber below CO2_RED_PPM, red at/above CO2_RED_PPM.""" diff --git a/src/scenes.py b/src/scenes.py new file mode 100644 index 0000000..f0adbcc --- /dev/null +++ b/src/scenes.py @@ -0,0 +1,459 @@ +"""Weather art: the animated 10x11 forecast icon and the animated backdrop +scenes the dashboard composes underneath its overlays. Same contract as the +rest of the rendering: pure, deterministic in the `frame` tick, draws into +any PicoGraphics-like `d`. No board imports here. +""" + +from render import (BOLT, CLOUD, CLOUD_MID, CLOUD_SHADE, FOG, HI, LO, MOON, + RAIN, SNOW, STORM_CLOUD, STORM_HI, STORM_SHADE, SUN, + SUN_DIM, TEXT_Y, WIDGET_X0, WHITE, co2_color, + draw_small_text, small_text_width) + + +def kind_of(code): + if code in (0, 1): + return "clear" + if code == 2: + return "partly" + if code == 3: + return "cloud" + if code in (45, 48): + return "fog" + if code >= 95: + return "storm" + if code in (85, 86): + return "snow" + if code >= 80: + return "showers" + if code == 75: + return "heavysnow" + if code >= 71: + return "snow" + if code == 65: + return "heavyrain" + if code in (51, 53, 55): + return "drizzle" + return "rain" + + +# --- animated weather icon, 10x11 in the left part of the matrix ----------- +# Hand-drawn 10x11 pixel icons (tuned visually in the sim), animated per kind: +# twinkling sun rays and stars, shaded cloud underside, drifting fog bands, +# falling rain/snow streaks, flashing bolt. + +# Cloud occupies rows 1..6, leaving rows 7..10 for precipitation: FALL_ROWS +# rows of falling drops, staggered per column so they never move in lockstep. +# y = CLOUD_BOTTOM + (frame//speed + phase) % FALL_ROWS increases every tick +# and wraps at the bottom -> drops always fall down and respawn at the top. +CLOUD_BOTTOM = 7 +FALL_ROWS = 4 # rows 7..10 + +# 10-wide cloud as (y, x_from, x_to, color): a darker back puff (CLOUD, +# shifted left, rows 1-3 plus one pixel below at (4,1) to round its bottom — +# a solid contiguous blob, so nothing protrudes) with the pure-white body on +# the right whose left side rises to row 2, plus a white pixel at 1-indexed +# (4,4) that rounds the top-left of the front puff, so the back cloud's left +# side stays visible; interior CLOUD_MID flecks; flat bottom, corners cut. +CLOUD_ROWS = ( + (1, 1, 3, CLOUD), + (2, 0, 4, CLOUD), + (3, 0, 2, CLOUD), + (4, 1, 1, CLOUD), # rounds the back puff's bottom + (1, 6, 7, WHITE), + (2, 4, 8, WHITE), + (3, 3, 9, WHITE), # includes the rounding pixel at 1-indexed (4,4) + (4, 2, 9, WHITE), + (5, 2, 9, WHITE), + (6, 3, 8, WHITE), + (4, 5, 5, CLOUD_MID), # texture flecks + (5, 6, 6, CLOUD_MID), +) + +# Same two-fluff cloud pushed right/down for partly cloudy (and night +# precipitation), so the sun/moon is tucked *behind* it — drawn first, the +# cloud covers its lower right, which reads as "peeking out". +PARTLY_CLOUD_ROWS = ( + (2, 6, 7, WHITE), + (3, 4, 9, WHITE), + (4, 3, 9, WHITE), + (5, 3, 9, WHITE), + (6, 4, 8, WHITE), + (4, 6, 6, CLOUD_MID), + (5, 5, 5, CLOUD_MID), +) + +# 5-wide sun disc (corners cut), symmetric about x=5, rows 3..7; single rays. +SUN_CORE_ROWS = ((3, 4, 6), (4, 3, 7), (5, 3, 7), (6, 3, 7), (7, 4, 6)) +SUN_RAYS = ((5, 1), (5, 9), (1, 5), (9, 5), (2, 2), (8, 2), (2, 8), (8, 8)) + +# Small 3x3 sun peeking out top-left for partly cloudy day. +SMALL_SUN_CORE_ROWS = ((1, 1, 3), (2, 1, 3), (3, 1, 3)) +SMALL_SUN_RAYS = ((2, 0), (0, 2), (4, 2)) + +# Round full moon (clear night) — a clean disc (no bite/knob, not C-shaped) +# plus its stars, which twinkle dim/bright (slow), not on/off. +MOON_PX = ((4, 2), (5, 2), (6, 2), + (3, 3), (4, 3), (5, 3), (6, 3), (7, 3), + (3, 4), (4, 4), (5, 4), (6, 4), (7, 4), + (3, 5), (4, 5), (5, 5), (6, 5), (7, 5), + (4, 6), (5, 6), (6, 6)) +MOON_STARS = ((8, 1), (1, 9)) +STAR_DIM = (110, 110, 100) + +# Small quarter moon for partly cloudy night / night precipitation, top-left: +# the full disc stays visible (dark half in MOON_DARK, high contrast) with +# the left half plus the other top pixel lit — reads as a quarter moon, +# not a "C". +SMALL_MOON_PX = ((2, 0), (3, 0), + (1, 1), (2, 1), (3, 1), (4, 1), + (1, 2), (2, 2), (3, 2), (4, 2), + (1, 3), (2, 3), (3, 3), (4, 3), + (2, 4), (3, 4)) +SMALL_MOON_LIT = tuple((x, y) for (x, y) in SMALL_MOON_PX if x <= 2) + ((3, 0),) +MOON_DARK = (55, 55, 52) + +# Lightning bolt, rows 7..10, 2-px zigzag (flashes on alternate frames). +BOLT_PX = ((6, 7), (5, 8), (6, 8), (4, 9), (5, 9), (4, 10), (5, 10)) + + +def _rows(d, ox, oy, rows, dx=0, dy=0): + for (y, xa, xb, col) in rows: + d.set_pen(d.create_pen(*col)) + d.rectangle(ox + xa + dx, oy + y + dy, xb - xa + 1, 1) + + +def _cloud(d, ox, oy, dark=False, dy=0): + # storm cloud: same shape, dark body, darker left bump, light flecks + tone = {WHITE: STORM_CLOUD, CLOUD: STORM_SHADE, CLOUD_MID: STORM_HI, + CLOUD_SHADE: STORM_SHADE} + rows = [] + for (y, xa, xb, col) in CLOUD_ROWS: + if dark: + col = tone[col] + rows.append((y, xa, xb, col)) + _rows(d, ox, oy, rows, dy=dy) + + +def _sun(d, ox, oy, frame): + _rows(d, ox, oy, [(y, xa, xb, SUN) for (y, xa, xb) in SUN_CORE_ROWS]) + for i, (x, y) in enumerate(SUN_RAYS): + # twinkle: alternate rays dim/bright + d.set_pen(d.create_pen(*(SUN if (i + frame) % 2 == 0 else SUN_DIM))) + d.pixel(ox + x, oy + y) + + +def _small_sun(d, ox, oy, frame): + _rows(d, ox, oy, [(y, xa, xb, SUN) for (y, xa, xb) in SMALL_SUN_CORE_ROWS]) + for i, (x, y) in enumerate(SMALL_SUN_RAYS): + d.set_pen(d.create_pen(*(SUN if (i + frame) % 2 == 0 else SUN_DIM))) + d.pixel(ox + x, oy + y) + + +def _moon(d, ox, oy, frame): + d.set_pen(d.create_pen(*MOON)) + for (x, y) in MOON_PX: + d.pixel(ox + x, oy + y) + for i, (x, y) in enumerate(MOON_STARS): + # stars twinkle dim/bright at half rate — no hard on/off blink + d.set_pen(d.create_pen(*(SNOW if (i + frame // 2) % 2 == 0 else STAR_DIM))) + d.pixel(ox + x, oy + y) + + +def _small_moon(d, ox, oy): + for (x, y) in SMALL_MOON_PX: + col = MOON if (x, y) in SMALL_MOON_LIT else MOON_DARK + d.set_pen(d.create_pen(*col)) + d.pixel(ox + x, oy + y) + + +def _fog(d, ox, oy, frame): + # fog = drifting bands only (no cloud, so it cannot be mistaken for rain); + # each band is two 4-px segments at staggered heights -> a wavy staircase + d.set_pen(d.create_pen(*FOG)) + for r, y in enumerate((2, 4, 6, 8)): + xa = (frame // 2 + r) % 3 + d.rectangle(ox + xa, oy + y, 4, 1) + d.rectangle(ox + xa + 4, oy + y + 1, 4, 1) + + +def _fall(d, ox, oy, frame, cols, color, speed=1, streak=1): + d.set_pen(d.create_pen(*color)) + for i, x in enumerate(cols): + top = (frame // speed + i) % FALL_ROWS + for s in range(streak): + if top + s < FALL_ROWS: # streak exits at the bottom, then respawns + d.pixel(ox + x, oy + CLOUD_BOTTOM + top + s) + + +def draw_icon(d, code, frame, ox=0, oy=0, is_day=1): + kind = kind_of(code) + if kind == "clear": + if is_day: + _sun(d, ox, oy, frame) + else: + _moon(d, ox, oy, frame) + return + if kind == "partly": + # no precipitation rows needed: shift the whole group down so the + # icon is vertically centered in the 11-row area + if is_day: + _small_sun(d, ox, oy + 2, frame) + else: + _small_moon(d, ox, oy + 2) + _rows(d, ox, oy, PARTLY_CLOUD_ROWS, dy=2) + return + if kind == "cloud": + _cloud(d, ox, oy, dy=2) # no rain: center vertically + return + if kind == "fog": + _fog(d, ox, oy, frame) + return + # precipitating kinds: cloud (dark for storm) + animated drops; at night a + # small moon is tucked behind the cloud and the drops fall under the cloud + if kind == "storm": + _cloud(d, ox, oy, dark=True) + if frame % 2 == 0: + d.set_pen(d.create_pen(*BOLT)) + for (x, y) in BOLT_PX: + d.pixel(ox + x, oy + y) + _fall(d, ox, oy, frame, (2, 8), RAIN, speed=2) + return + night = not is_day + if night: + _small_moon(d, ox, oy) + _rows(d, ox, oy, PARTLY_CLOUD_ROWS) + else: + _cloud(d, ox, oy) + if kind == "drizzle": + _fall(d, ox, oy, frame, (5, 8) if night else (3, 6), RAIN, speed=2) + elif kind == "heavyrain": + _fall(d, ox, oy, frame, (2, 4, 6, 8) if night else (1, 3, 5, 7, 9), + RAIN, streak=2) + elif kind == "showers": + if frame % 6 < 4: # intermittent + _fall(d, ox, oy, frame, (4, 6, 8) if night else (2, 5, 8), + RAIN, streak=2) + elif kind == "heavysnow": + _fall(d, ox, oy, frame, (3, 5, 7, 9) if night else (1, 3, 5, 7, 9), + SNOW, speed=2) + elif kind == "snow": + _fall(d, ox, oy, frame, (4, 6, 8) if night else (2, 4, 6, 8), SNOW, speed=2) + else: # rain + _fall(d, ox, oy, frame, (4, 6, 8) if night else (2, 4, 6, 8), RAIN, + streak=2) + + +def draw_weather(d, w, h, code, temp_text, frame, is_day=1): + """Icon + temperature as one group, centered so no space is wasted right.""" + icon_w = 10 + gap = 3 + text_w = d.measure_text(temp_text, 1) + x0 = (w - (icon_w + gap + text_w)) // 2 + draw_icon(d, code, frame, ox=x0, oy=0, is_day=is_day) + d.set_pen(d.create_pen(*WHITE)) + d.text(temp_text, x0 + icon_w + gap, TEXT_Y, scale=1) + + +# --- weather scenes (the dashboard's animated backdrop) ---------------------- +# Every scene is stateless: element positions derive from `frame` via +# integer arithmetic (the draw_matrix discipline), so board and sim render +# identical pixels, nothing allocates per frame, and there is no field to +# fill — sparse bright content on the black matrix (a solid gradient field +# reads as gap-artifacts on LED-matrix, so the elements carry the scene). + +_WMO = ( # weather_code groups; unknowns land on 'clouds' (a sane neutral) + (range(0, 2), "clear"), + (range(1, 4), "clouds"), # 1-3: mostly cloudy to overcast + ((45, 48), "fog"), + ((51, 53, 55, 56, 57, 61, 63, 65, 66, 67, 80, 81, 82), "rain"), + ((71, 73, 75, 77), "snow"), + ((85, 86), "snow"), # snow showers + ((95, 96, 99), "storm"), +) + +# the digits' band: rows the dashboard's overlays live in — scene pixels +# in this range draw dimmer, so the glyphs keep their contrast (_plot) +_BAND = (1, 9) + +_STARS = tuple((7 + (i * 31) % 39, (i * 17) % 6, i * 5) # (x, y, phase) + for i in range(10)) # 10 twinkling star positions +_RAIN_C = (60, 160, 255) # the rain drop ink (head + trail share it) +_STORM_C = (235, 235, 245) # the lightning frame's near-white flash + + +def scene_for_code(code, is_day=1): + """Map the open-meteo WMO weather_code to a scene id; `is_day` picks + clear-day vs starfield night (the API supplies it with the code).""" + for codes, scene in _WMO: + if code in codes: + if scene == "clear" and not is_day: + return "night" + return scene + return "clouds" + + +def _plot(d, x, y, level, rgb): + """One backdrop element pixel at brightness `level` (0..8, eighths of + full ink). Rows inside the digits' band dim to 60 percent — the white + clock glyphs keep their contrast against the moving rain.""" + if level <= 0 or y < 0 or x < 0: + return + if 1 <= y <= 9: + level = (level * 3) // 4 + if level <= 0: + return + r, g, b = rgb + pen = d.create_pen(r * level // 8, g * level // 8, b * level // 8) + d.set_pen(pen) + d.pixel(x, y) + + +def _draw_scene_clear(d, w, h, frame): + # sun: 3-bulge disc top-right, alone on black (no field: sparse reads + # clean on the matrix, and the ambient light does the sky's job) + d.set_pen(d.create_pen(255, 200, 40)) + for x, y in ((w - 8, 0), (w - 9, 1), (w - 8, 1), (w - 7, 1), + (w - 8, 2), (w - 9, 3), (w - 7, 3), (w - 8, 4)): + d.pixel(x, y) + d.set_pen(d.create_pen(255, 236, 120)) + d.pixel(w - 8, 1) + d.pixel(w - 8, 3) + + +def _draw_scene_night(d, w, h, frame): + d.set_pen(d.create_pen(200, 215, 255)) + for x, y, phase in _STARS: # each star twinkles on its own 6-frame beat + if (frame + phase) % 6 < 4: + d.pixel(x, y) + + +def _draw_scene_clouds(d, w, h, frame): + # cloud wisps: blobs drifting right-to-left, wrapping; sparse on black + for i, (x0, speed) in enumerate(((6, 1), (24, 2))): + x = (x0 - frame * speed) % (w + 4) - 4 + for k in range(3): + d.pixel(x + 3 + k, 1) + for k in range(2): + d.pixel(x + 3 + k // 2, 2) + + +def _draw_scene_rain(d, w, h, frame, n=14): + # one falling drop per lane; subpixel position (eighth-px steps) so + # the fall is fluid: a drop's ink splits across the two rows it + # straddles (the head fades in as the tail fades out — no stepping). + # Band rows draw dimmer (the digits live there — see _plot). + for k in range(n): + y8 = (k * 61 + frame * (3 + k % 3)) % (h * 8) + r8 = y8 >> 3 + f = y8 & 7 + _plot(d, (k * 11) % w, r8, 8 - f, _RAIN_C) + _plot(d, (k * 11) % w, r8 + 1, f, _RAIN_C) + + +def _draw_scene_snow(d, w, h, frame): + # flakes: slow fall + a side-to-side drift, deterministic + for i in range(18): + y = (i * 37 + frame * (2 + i % 3)) % (h + 3) + x = (i * 13 + (frame >> 1) * (1 if i % 2 else -1) + w) % w + if 0 <= y < h: + _plot(d, x, y, 8, (225, 235, 250)) + + +def _draw_scene_fog(d, w, h, frame): + # drifting dashes, two depths (a filled haze reads dead on the matrix; + # sparse bands carry the mood without the field) + d.set_pen(d.create_pen(96, 104, 120)) + for y, speed in ((2, 1), (5, 2), (8, 1)): + x0 = (frame * speed + y * 9) % (w + 8) - 8 + d.rectangle(x0, y, x0 + 4, y) + + +def _draw_scene_storm(d, w, h, frame): + _draw_scene_rain(d, w, h, frame, n=22) + # lightning: a 3-frame full-field flash every 40 (a bright frame + # carries the mood; the decay version read as noise) + k = frame % 40 + if k < 3: + d.set_pen(d.create_pen(*_STORM_C)) + d.rectangle(0, 0, w - 1, h) + + +SCENES = { + "clear": _draw_scene_clear, + "night": _draw_scene_night, + "clouds": _draw_scene_clouds, + "fog": _draw_scene_fog, + "rain": _draw_scene_rain, + "snow": _draw_scene_snow, + "storm": _draw_scene_storm, +} + + +def draw_scene(d, w, h, scene, frame): + """Paint one animated weather backdrop frame. Deterministic in + `frame` (no clocks, no randomness): safe to call at any fps, and + identical pixels on board and sim. `scene` is a key of SCENES.""" + SCENES[scene](d, w, h, frame) + + +# --- dashboard widgets -------------------------------------------------------- +# The dashboard's right zone (cols WIDGET_X0..): one widget at a time, +# right-anchored, rotating on the caller's schedule while the clock stays +# put. Each widget carries its data in a plain dict; missing backing data +# means the widget is simply not in the rotation. + +TEMP_COLD_C = 8 # at/below this the temp digit runs cold blue, else warm +TEMP_WARM = (255, 210, 140) # matches draw_icon's sun/hi hue family +TEMP_COLD = (140, 200, 255) # matches the icon's drizzle/frost hue family + +TEMP_Y = 3 # the weather widget's temp row (3x5 face, rows 3..7) + + +def _widget_wx(d, w, h, widget, frame, dy=0): + """Outside weather + temperature: the animated icon at the zone's left + edge, temp right-flush in the 3x5 face (vertically centered). Big + negative temps drop the degree sign rather than collide with the icon.""" + draw_icon(d, widget["code"], frame, ox=WIDGET_X0, oy=dy, + is_day=widget.get("is_day", 1)) + temp_f = round(widget["temp_f"]) + s = "%d°" % temp_f + if small_text_width(s) > w - (WIDGET_X0 + 11): + s = "%d" % temp_f # too wide with °: the icon keeps its columns + tint = TEMP_COLD if temp_f <= TEMP_COLD_C else TEMP_WARM + draw_small_text(d, w, h, s, w - small_text_width(s), TEMP_Y + dy, tint) + + +def _widget_hilo(d, w, h, widget, frame, dy=0): + """Today's hi/lo forecast in two rows of the 3x5 face: warm amber over + cold blue, right-flush.""" + hi = "%d°" % round(widget["hi"]) + lo = "%d°" % round(widget["lo"]) + draw_small_text(d, w, h, hi, w - small_text_width(hi), dy, HI) + draw_small_text(d, w, h, lo, w - small_text_width(lo), 6 + dy, LO) + + +def _widget_co2(d, w, h, widget, frame, dy=0): + """CO2: a small "CO2" label on top, the reading in the 3x5 face below + (four digits = 15 px, fits the zone). The label carries the air-quality + hue and the number white.""" + ppm = widget["ppm"] + draw_small_text(d, w, h, "CO2", w - small_text_width("CO2"), dy, + co2_color(ppm)) + draw_small_text(d, w, h, "%d" % ppm, w - small_text_width("%d" % ppm), + 6 + dy, WHITE) + + +WIDGETS = { + "wx": _widget_wx, + "hilo": _widget_hilo, + "co2": _widget_co2, +} + + +def draw_widget(d, w, h, widget, frame, dy=0): + """Paint one dashboard widget into the right zone, shifted dy rows down + (the rotation's roll transition; rows pushed off the matrix clip). + `widget` is a dict with a "kind" key of WIDGETS plus its data fields; + `frame` drives the wx icon's animation (same tick as the backdrop + scene).""" + WIDGETS[widget["kind"]](d, w, h, widget, frame, dy) diff --git a/tests/test_display.py b/tests/test_display.py index 5ced9bc..896d3a6 100644 --- a/tests/test_display.py +++ b/tests/test_display.py @@ -14,8 +14,10 @@ sys.path.insert(0, os.path.join(REPO, "sim")) import co2 # noqa: E402 (the headline constants live with the ring now) +import matrix # noqa: E402 import render # noqa: E402 import run_main # noqa: E402 +import scenes # noqa: E402 import sim as simmod # noqa: E402 W, H = 53, 11 @@ -47,7 +49,7 @@ def precip_cols(code, match, frames=8): one entry per frame (streaks are 2 px tall; only the leading edge moves).""" cols = {} for f in range(frames): - fb = frame(lambda d, f: render.draw_icon(d, code, f), f) + fb = frame(lambda d, f: scenes.draw_icon(d, code, f), f) for x in range(W): ys = [y for y in range(7, H) if match(fb[y][x])] if ys: @@ -81,6 +83,221 @@ def test_widths(self): self.assertEqual(d.measure_text("", 1), 0) +class TestSmallText(unittest.TestCase): + """The 3x5 overlay face (draw_small_text): pixel-exact glyphs, exact + widths via the fixed 4 px advance, and the exact ASCII shape.""" + + def test_widths(self): + self.assertEqual(render.small_text_width("21°"), 10) # 3+1+3+1+2 + self.assertEqual(render.small_text_width("-2C"), 11) + self.assertEqual(render.small_text_width(""), 0) + + def test_glyph_pixel_counts(self): + # on-counts from the row bitmaps: '0'=12, '-`=3, '°'=8, 'C'=9 + for s, n in (("0", 12), ("-", 3), ("°", 4), ("C", 9)): + fb = frame(lambda d, f: render.draw_small_text( + d, W, H, s, 2, 3, render.WHITE)) + got = sum(1 for y in range(H) for x in range(W) + if fb[y][x] != (0, 0, 0)) + self.assertEqual(got, n, "glyph %r inked %d px, not %d" + % (s, got, n)) + + def test_exact_shape_and_advance(self): + # '0-' at x=1: the zero spans x=1..3 rows 0..4; the minus is + # a 3-px dash 4 px later (advance), on the middle row only + fb = frame(lambda d, f: render.draw_small_text( + d, W, H, "0-", 1, 0, render.WHITE)) + for x in range(1, 4): + self.assertNotEqual(fb[0][x], (0, 0, 0), "0's top row at x=%d" % x) + self.assertNotEqual(fb[4][x], (0, 0, 0), "0's bottom row x=%d" % x) + self.assertEqual(fb[1][1], render.WHITE, "0's left wall") + self.assertEqual(fb[1][2], (0, 0, 0), "0 must be hollow at its core") + for x in range(5, 8): + self.assertEqual(fb[2][x], render.WHITE, "minus dash x=%d" % x) + self.assertEqual(fb[1][x], (0, 0, 0), "minus must be 1 row only") + + def test_unknown_char_advances_without_ink(self): + fb = frame(lambda d, f: render.draw_small_text( + d, W, H, "8 ", 0, 3, render.WHITE)) + self.assertEqual(lit_span(fb), (0, 2), "space must advance 4 but ink 3") + + +class TestDashboard(unittest.TestCase): + """The home screen: the clock stays inside [0, WIDGET_X0 - 2) and the + right zone carries one rotating widget (weather+temp, hi/lo pair, or + the CO2 readout) — right-flush, tinted, never touching the clock.""" + + def _clock(self, hh="21", mm="07"): + return frame(lambda d, f: render.draw_clock(d, W, H, hh, mm, False, + x_bounds=(0, + render.WIDGET_X0 - 2))) + + def _widget(self, widget, hh="21", mm="07"): + def draw(d, f): + render.draw_clock(d, W, H, hh, mm, False, + x_bounds=(0, render.WIDGET_X0 - 2)) + scenes.draw_widget(d, W, H, widget, f) + return frame(draw) + + def test_widget_rolls_with_dy(self): + # the rotation's roll transition: dy shifts the widget down within + # the zone, rows pushed off the matrix clip, and a full-zone dy + # empties it + base = frame(lambda d, f: scenes.draw_widget( + d, W, H, {"kind": "co2", "ppm": 950}, 0)) + rolled = frame(lambda d, f: scenes.draw_widget( + d, W, H, {"kind": "co2", "ppm": 950}, 0, dy=4)) + self.assertNotEqual(rolled, base, "dy=4 drew in place") + x0 = render.WIDGET_X0 # the clock owns the columns left of the zone + for y in range(H - 4): + self.assertEqual(rolled[y + 4][x0:], base[y][x0:], + "dy=4 is not a clean 4-row shift at row %d" % y) + gone = frame(lambda d, f: scenes.draw_widget( + d, W, H, {"kind": "co2", "ppm": 950}, 0, dy=H + 1)) + self.assertTrue(all(px == (0, 0, 0) for row in gone + for x, px in enumerate(row) if x >= x0), + "a fully rolled-out widget left ink in the zone") + + def test_clock_never_enters_the_widget_zone(self): + # all hour-width shapes (narrow "1", wide "0") must stay clear of + # the widget zone: the widgets never move when they rotate + for hh in ("01", "10", "23"): + fb = self._clock(hh) + whites = [x for x in range(W) for y in range(H) + if fb[y][x] == render.CLOCK_WHITE] + self.assertTrue(whites, "clock missing") + self.assertLessEqual(max(whites), render.WIDGET_X0 - 2, + "clock %s bleeds into the widget zone" % hh) + + def test_weather_widget_temp_right_flush_and_tinted(self): + fb = self._widget({"kind": "wx", "code": 0, "temp_f": 21, + "is_day": 1}) + ys, xs, tints = [], [], set() + for y in range(H): + for x in range(render.WIDGET_X0 + 11, W): # right of the icon + px = fb[y][x] + if px in ((0, 0, 0),): + continue + ys.append(y) + xs.append(x) + tints.add(px) + self.assertEqual(set(ys), set(range(3, 8)), + "temp must sit exactly on rows 3..7") + self.assertEqual(max(xs), W - 1, "temp must be right-flush") + self.assertEqual(tints, {scenes.TEMP_WARM}, "warm temp runs amber") + + def test_weather_widget_cold_tint(self): + fb = self._widget({"kind": "wx", "code": 0, "temp_f": -2, + "is_day": 1}) + cols = {fb[y][x] for y in range(H) + for x in range(render.WIDGET_X0 + 11, W) + if fb[y][x] != (0, 0, 0)} + self.assertEqual(cols, {scenes.TEMP_COLD}, "cold temp must run blue") + + def test_wide_negative_temp_drops_the_degree_sign(self): + # "-15°" is 14 px — too wide for the 11 px between icon and edge; + # it must drop the ° and stay right of the icon + fb = self._widget({"kind": "wx", "code": 0, "temp_f": -15, + "is_day": 1}) + slots = [y for y in range(3, 8)] # the temp row's band + ink = [x for x in range(render.WIDGET_X0, W) for y in range(3, 8) + if fb[y][x] != (0, 0, 0)] + self.assertTrue(ink, "no temp ink right of the icon") + self.assertGreaterEqual(min(ink), render.WIDGET_X0, + "temp must sit in the widget zone") + + def test_hilo_widget_two_rows_with_level_colors(self): + zn = render.WIDGET_X0 # widget zone starts here; clock is left of it + fb = self._widget({"kind": "hilo", "hi": 25, "lo": 18}) + top = {fb[y][x] for y in range(0, 5) for x in range(zn, W) + if fb[y][x] != (0, 0, 0)} + bot = {fb[y][x] for y in range(6, H) for x in range(zn, W) + if fb[y][x] != (0, 0, 0)} + self.assertEqual(top, {render.HI}, "hi row must run warm red") + self.assertEqual(bot, {render.LO}, "lo row must run cold blue") + self.assertEqual(max(x for y in range(0, 5) for x in range(zn, W) + if fb[y][x] != (0, 0, 0)), W - 1, + "hi row right-flush") + + def test_co2_widget_label_and_reading(self): + zn = render.WIDGET_X0 + fb = self._widget({"kind": "co2", "ppm": 950}) + label = {fb[y][x] for y in range(0, 5) for x in range(zn, W) + if fb[y][x] != (0, 0, 0)} + reading = {fb[y][x] for y in range(6, H) for x in range(zn, W) + if fb[y][x] != (0, 0, 0)} + self.assertEqual(label, {render.CO2_WARN}, + "CO2 label must carry the level hue (950 = amber)") + self.assertEqual(reading, {render.WHITE}, + "the reading itself stays white") + + def test_co2_widget_roi_width(self): + # 4 digits = 15 px must fit into the zone without clipping + fb = self._widget({"kind": "co2", "ppm": 1500}) + xs = [x for x in range(render.WIDGET_X0, W) for y in range(6, H) + if fb[y][x] == render.WHITE] + self.assertTrue(xs) + self.assertGreaterEqual(min(xs), render.WIDGET_X0, + "15 px of digits must still fit the zone") + self.assertEqual(max(xs), W - 1) + + def test_widget_known_kinds_render(self): + for widget in ({"kind": "wx", "code": 61, "temp_f": 12, "is_day": 1}, + {"kind": "hilo", "hi": 25, "lo": 18}, + {"kind": "co2", "ppm": 600}): + fb = self._widget(widget) + self.assertTrue(any(any(px != (0, 0, 0) for px in row) + for row in fb), + "widget %s drew nothing" % widget["kind"]) + + + +class TestScenes(unittest.TestCase): + """The weather backdrop scenes: correct mapping, real motion, and no + wandering pixels between frames (stateless render discipline).""" + + def test_scene_mapping(self): + self.assertEqual(scenes.scene_for_code(0), "clear") + self.assertEqual(scenes.scene_for_code(0, is_day=0), "night") + self.assertEqual(scenes.scene_for_code(2), "clouds") + self.assertEqual(scenes.scene_for_code(45), "fog") + self.assertEqual(scenes.scene_for_code(61), "rain") + self.assertEqual(scenes.scene_for_code(75), "snow") + self.assertEqual(scenes.scene_for_code(95), "storm") + self.assertEqual(scenes.scene_for_code(999), "clouds", + "unknown codes must fail neutral, not crash") + + def test_rain_moves_down_between_frames(self): + def drops(): + out = [] + for y in range(H): + row = "" + for x in range(W): + pass + return out + # frame0 vs frame1 (frame 0 has no trail yet) — the same drop + # column advances exactly one row: compare dark-blue ink columns + f0 = frame(lambda d, f: scenes.draw_scene(d, W, H, "rain", 0)) + f1 = frame(lambda d, f: scenes.draw_scene(d, W, H, "rain", 1)) + self.assertTrue(any(f0[y][x] != f1[y][x] for y in range(H) + for x in range(W)), "scene frame is static") + + def test_scene_renderer_is_deterministic(self): + # two renders of the same frame must be byte-identical (the + # scene must never depend on walls/loop counters) + a = frame(lambda d, f: scenes.draw_scene(d, W, H, "rain", 5)) + b = frame(lambda d, f: scenes.draw_scene(d, W, H, "rain", 5)) + self.assertEqual(a, b) + + def test_all_scenes_render(self): + # each registered scene + golden hook: renders without raising + # and paints at least the gradient (a lit backdrop row) + for scene in ("clear", "night", "clouds", "fog", "rain", + "snow", "storm"): + fb = frame(lambda d, f: scenes.draw_scene(d, W, H, scene, 2)) + self.assertTrue(any(fb[H // 2]), "scene %s empty" % scene) + + class TestPrecipitation(unittest.TestCase): def test_rain_falls_down(self): cols = precip_cols(61, lambda p: p[2] > 150 and p[0] < 150) @@ -100,7 +317,7 @@ def test_rain_columns_staggered(self): class TestLayout(unittest.TestCase): def test_weather_group_centered(self): - fb = frame(lambda d, f: render.draw_weather(d, W, H, 0, "21C", f)) + fb = frame(lambda d, f: scenes.draw_weather(d, W, H, 0, "21C", f)) lo, hi = margins(fb) self.assertLessEqual(abs(lo - hi), 1, "weather group off-center: %s" % ((lo, hi),)) @@ -122,7 +339,9 @@ def test_clock_centered_and_blink(self): off = frame(lambda d, f: render.draw_clock(d, W, H, "21", "07", False)) self.assertNotEqual(ascii_of(on), ascii_of(off), "colon blink has no effect") lo, hi = margins(on) - self.assertEqual(lo, hi, "clock off-center: %s" % ((lo, hi),)) + # fixed digit cells (the no-drift layout) can't hit exact center on + # the odd-width frame for every time; half a pixel is the grid limit + self.assertLessEqual(abs(lo - hi), 2, "clock off-center: %s" % ((lo, hi),)) # Golden ASCII dumps — exact rendered output. Update deliberately when the @@ -138,7 +357,7 @@ def _heads(self, frames): behind it, so the argmax is the head row).""" out = {} for f in frames: - fb = frame(lambda d, f: render.draw_matrix(d, W, H, f), f) + fb = frame(lambda d, f: matrix.draw_matrix(d, W, H, f), f) for x in range(W): ls = [fb[y][x][1] for y in range(H)] # g channel dominates ys = [y for y in range(H) if ls[y]] @@ -150,7 +369,7 @@ def test_matrix_is_green_rain(self): lit = set() strong = 0 for f in range(40): - fb = frame(lambda d, f: render.draw_matrix(d, W, H, f), f) + fb = frame(lambda d, f: matrix.draw_matrix(d, W, H, f), f) for p, _x in ((p, x) for row in fb for x, p in enumerate(row) if p != (0, 0, 0)): lit.add(p) @@ -171,15 +390,15 @@ def test_matrix_head_churns_hue_then_settles(self): # each pass settles on its own (LCG-mixed) hue x = 5 gap = 4 + (x * 3) % 6 - settle = ((H + gap) * render.SUB) // 2 + settle = ((H + gap) * matrix.SUB) // 2 pass_hues = [] # settled hue of each pass seen cur = set() for f in range(2100): - c16, L16, bright, seed_v = render.matrix_col(x, H, f) + c16, L16, bright, seed_v = matrix.matrix_col(x, H, f) if c16 < settle: continue - cur.add(render.tint_at(seed_v, c16, settle)) - nxt, _, _, _ = render.matrix_col(x, H, f + 1) + cur.add(matrix.tint_at(seed_v, c16, settle)) + nxt, _, _, _ = matrix.matrix_col(x, H, f + 1) if nxt < settle: # head wrapped to the next pass pass_hues.append(cur) cur = set() @@ -191,7 +410,7 @@ def test_matrix_head_churns_hue_then_settles(self): "every pass settles on the same hue") def test_matrix_tints_are_all_green_dominant(self): - for (r, g, b) in render.MATRIX_TINTS: + for (r, g, b) in matrix.MATRIX_TINTS: self.assertLess(r, g, "tint not green: %s" % ((r, g, b),)) self.assertLess(b, g, "tint not green: %s" % ((r, g, b),)) @@ -202,10 +421,10 @@ def test_matrix_is_subpixel_smooth(self): # non-stepping guarantee is asserted on the model in # test_matrix_motion_is_subpixel_continuous / tiers) mid = next(x for x in range(W) - if render.MATRIX_TIERS[render._tier_of(x)][0] == 4) + if matrix.MATRIX_TIERS[matrix._tier_of(x)][0] == 4) peaks = [] for f in range(400): - fb = frame(lambda d, f: render.draw_matrix(d, W, H, f), f) + fb = frame(lambda d, f: matrix.draw_matrix(d, W, H, f), f) p = [fb[y][mid][1] for y in range(H)] if max(p): peaks.append(max(p)) @@ -220,14 +439,14 @@ def test_matrix_tiers_differ_in_speed_and_brightness(self): # every tier must actually be configured, with visibly different # speeds (none a whole number of rows per tick) and strictly # increasing brightness - self.assertEqual(len(render.MATRIX_TIERS), 5) - for (rows, per, bright) in render.MATRIX_TIERS: + self.assertEqual(len(matrix.MATRIX_TIERS), 5) + for (rows, per, bright) in matrix.MATRIX_TIERS: self.assertIn(per, (2, 4, 6, 8, 12)) # the per-tick subpixel step must not be a whole row (stepped) - self.assertNotEqual((rows * render.SUB // per) % render.SUB, 0, + self.assertNotEqual((rows * matrix.SUB // per) % matrix.SUB, 0, "tier %s steps whole rows" % ((rows, per),)) - self.assertEqual([t[0] for t in render.MATRIX_TIERS], [1, 1, 1, 4, 1]) - lums = [(255 * t[2]) // 100 for t in render.MATRIX_TIERS] + self.assertEqual([t[0] for t in matrix.MATRIX_TIERS], [1, 1, 1, 4, 1]) + lums = [(255 * t[2]) // 100 for t in matrix.MATRIX_TIERS] self.assertEqual(lums, sorted(lums), "tiers not dark -> bright") def _runs(self, col_heads): @@ -264,16 +483,16 @@ def test_matrix_speeds_vary_between_columns(self): # 1, 1, 1, 4, 1 rows per 12, 6, 4, 12, 2 ticks (mod the wrap), all present speeds = set() for x in range(W): - tier = render._tier_of(x) - rows, per, _ = render.MATRIX_TIERS[tier] - loop = (H + render._gap_of(x)) * render.SUB + tier = matrix._tier_of(x) + rows, per, _ = matrix.MATRIX_TIERS[tier] + loop = (H + matrix._gap_of(x)) * matrix.SUB f0 = 100 - c0, *_ = render.matrix_col(x, H, f0) - c3, *_ = render.matrix_col(x, H, f0 + 3) + c0, *_ = matrix.matrix_col(x, H, f0) + c3, *_ = matrix.matrix_col(x, H, f0 + 3) adv = (c3 - c0) % loop self.assertEqual(adv, - ((rows * render.SUB * (f0 + 3)) // per - - (rows * render.SUB * f0) // per) % loop, + ((rows * matrix.SUB * (f0 + 3)) // per + - (rows * matrix.SUB * f0) // per) % loop, "col %d advances %s per 3 ticks" % (x, adv)) speeds.add(rows) self.assertEqual(speeds, {1, 4}, @@ -284,10 +503,10 @@ def test_matrix_motion_is_subpixel_continuous(self): # row-multiples), so anti-aliased heads glide instead of teleporting for x in range(W): for f in range(6): - c0, *_ = render.matrix_col(x, H, f) - c1, *_ = render.matrix_col(x, H, f + 1) - step = (c1 - c0) % ((H + render._gap_of(x)) * render.SUB) - self.assertNotEqual(step % render.SUB, 0, + c0, *_ = matrix.matrix_col(x, H, f) + c1, *_ = matrix.matrix_col(x, H, f + 1) + step = (c1 - c0) % ((H + matrix._gap_of(x)) * matrix.SUB) + self.assertNotEqual(step % matrix.SUB, 0, "col %d steps a whole row at f=%d" % (x, f)) def test_matrix_columns_are_staggered(self): @@ -300,7 +519,7 @@ def test_matrix_covers_the_board(self): # their gap for over a hundred frames, and ~1 pass in 10 rests whole cols = set() for f in range(400): - fb = frame(lambda d, f: render.draw_matrix(d, W, H, f), f) + fb = frame(lambda d, f: matrix.draw_matrix(d, W, H, f), f) for x in set(range(W)) - cols: if any(fb[y][x] != (0, 0, 0) for y in range(H)): cols.add(x) @@ -314,11 +533,11 @@ def test_matrix_rest_passes_breathe_density(self): frames_with_rests = 0 for f in range(600): resting = sum(1 for x in range(W) - if render.matrix_col(x, H, f)[1] == 0) + if matrix.matrix_col(x, H, f)[1] == 0) frames_with_rests += (resting > 0) self.assertLess(resting, W, "every column rests at once at f=%d" % f) - if len({render.matrix_col(x, H, f)[1] == 0 + if len({matrix.matrix_col(x, H, f)[1] == 0 for x in range(W)}) > 1: break self.assertGreater(frames_with_rests, 0, "no resting pass ever seen") @@ -329,12 +548,12 @@ def test_matrix_most_drops_stay_classic_green(self): # own accent. Count at pass boundaries (head position wraps). base = accents = 0 for x in range(0, W, 2): # every other column - prev_c16 = render.matrix_col(x, H, 0)[0] + prev_c16 = matrix.matrix_col(x, H, 0)[0] for f in range(1, 2200): - c16, L16, _, seed = render.matrix_col(x, H, f) + c16, L16, _, seed = matrix.matrix_col(x, H, f) if c16 < prev_c16: # wrapped -> new pass base += (seed == 0) - accents += (0 < seed <= render.N_ACCENT) + accents += (0 < seed <= matrix.N_ACCENT) # update every frame: skipping resting passes (L16 == 0) # leaves a stale prev and misreads every frame after the # wrap as a new pass @@ -342,10 +561,10 @@ def test_matrix_most_drops_stay_classic_green(self): self.assertGreater(base / max(1, accents), 2.0, "accent passes are not a minority " "(base %d, accents %d)" % (base, accents)) - for s in range(1, render.N_ACCENT + 1): - self.assertEqual(render.tint_at(s, 10 ** 9, 1000), s, + for s in range(1, matrix.N_ACCENT + 1): + self.assertEqual(matrix.tint_at(s, 10 ** 9, 1000), s, "accent heads must settle on their own tint") - self.assertEqual(render.tint_at(0, 12345, 100), 0, + self.assertEqual(matrix.tint_at(0, 12345, 100), 0, "classic-green passes must never churn") # -- rotation integration ---------------------------------------------- @@ -369,17 +588,17 @@ def test_matrix_plays_when_button_pressed(self): shots = self._with_presses((21.0,), "draw_matrix", 50.0) self.assertTrue(shots, "button press never started the rain") - def test_press_takes_over_the_rotation_immediately(self): - # a press mid-clock-slot ends the screen within a frame and the - # rain starts — the rest of that rotation (weather/hilo/co2) never - # plays; per-frame deadline polls in the show loops (rain_pending) - late = self._with_presses((21.0,), "draw_weather", 45.0) - early = self._with_presses((), "draw_weather", 45.0) - self.assertTrue(early, "control run: no weather screens at all") + def test_press_takes_over_the_dashboard_immediately(self): + # a press mid-pass interrupts the dashboard within a frame (per- + # frame deadline polls in show_dashboard): the widget captures of + # a run with a press are strictly fewer than the press-free control + late = self._with_presses((21.0,), "draw_widget", 45.0) + early = self._with_presses((), "draw_widget", 45.0) + self.assertTrue(early, "control run: dashboard never showed a widget") self.assertLess(len(late or []), len(early) - 10, - "the press did not cancel the rotation's remaining " - "screens immediately (%d vs %d)" % (len(late or []), - len(early))) + "the press did not cancel the remaining dashboard " + "frames immediately (%d vs %d)" % (len(late or []), + len(early))) def test_second_press_stops_rain_and_rotation_resumes(self): # press at 21 s (rain on), press again at 27 s (rain off): only a @@ -441,7 +660,7 @@ def test_rain_runs_at_30_frames_per_virtual_second(self): # -- rain-clock overlay -------------------------------------------------- # With a trusted RTC, rain mode pours the rain over the clock - # (render.draw_rain_clock); with the RTC untrusted it runs alone. + # (matrix.draw_rain_clock); with the RTC untrusted it runs alone. def test_rain_mode_shows_the_clock_over_the_rain(self): # default mock: NTP synced -> RTC trusted -> the clock overlays @@ -467,7 +686,7 @@ def test_rain_mode_without_rtc_runs_bare_rain(self): def test_rain_clock_dims_rain_behind_bright_digits(self): # inside the clock's padded text box the rain is dimmed to # MATRIX_DIM % alpha, so no rain pixel reads brighter than the - # (255,255,255) digits; outside the box it stays full brightness + # CLOCK_WHITE digits; outside the box it stays full brightness sim = simmod.SimGraphics(W, H) colon_adv = 3 tw = sim.measure_text("23", 1) + colon_adv + sim.measure_text("59", 1) @@ -476,12 +695,12 @@ def test_rain_clock_dims_rain_behind_bright_digits(self): y0, y1 = 1, min(H, render.TEXT_Y + 7) digits = brightest_outside = 0 for f in range(0, 60, 3): - fb = frame(lambda d, ff: render.draw_rain_clock( + fb = frame(lambda d, ff: matrix.draw_rain_clock( d, W, H, "23", "59", False, ff), f) for y in range(H): for x in range(W): r, g, b = fb[y][x] - if (r, g, b) == render.WHITE: + if (r, g, b) == render.CLOCK_WHITE: if x0 <= x < x1 and y0 <= y < y1: digits += 1 elif g > 120: # a rain pixel brighter than the dim cap @@ -497,12 +716,12 @@ def test_dim_mask_dims_the_whole_field(self): mask = bytearray(W * H) for x in range(W): for j in range(H): - mask[x * H + j] = render.MATRIX_FADE_STEPS # fully dimmed + mask[x * H + j] = matrix.MATRIX_FADE_STEPS # fully dimmed produced_rain = False for f in range(0, 90, 5): - dim_fb = frame(lambda d, ff: render.draw_matrix( + dim_fb = frame(lambda d, ff: matrix.draw_matrix( d, W, H, ff, dim_mask=mask), f) - full_fb = frame(lambda d, ff: render.draw_matrix(d, W, H, ff), f) + full_fb = frame(lambda d, ff: matrix.draw_matrix(d, W, H, ff), f) for row in dim_fb: for (r, g, b) in row: self.assertLessEqual(max(r, g, b), 120, @@ -517,17 +736,17 @@ def test_fade_dither_sweeps_the_box(self): # pixel dimmed at a level stays dimmed at all higher levels saw_leak = saw_partial = full = False for f in range(0, 90, 9): - for level in range(1, render.MATRIX_FADE_STEPS + 1): + for level in range(1, matrix.MATRIX_FADE_STEPS + 1): mask = bytearray(W * H) for x in range(W): for j in range(H): mask[x * H + j] = level - fb = frame(lambda d, ff: render.draw_matrix( + fb = frame(lambda d, ff: matrix.draw_matrix( d, W, H, ff, dim_mask=mask), f) bright_in_box = sum( 1 for y in range(H) for x in range(W) if fb[y][x][1] > 120) - if level == render.MATRIX_FADE_STEPS: + if level == matrix.MATRIX_FADE_STEPS: self.assertEqual( bright_in_box, 0, "level %d left bright pixels: dither never " @@ -554,10 +773,10 @@ def test_rain_clock_fades_in_and_out(self): x0 = max(0, (W - tw) // 2 - 1) x1 = min(W, x0 + tw + 2) y0, y1 = 1, min(H, render.TEXT_Y + 7) - maxdim = {f: 0 for f in range(render.MATRIX_FADE_STEPS + 1)} + maxdim = {f: 0 for f in range(matrix.MATRIX_FADE_STEPS + 1)} for f in range(0, 120, 7): - for fade in range(render.MATRIX_FADE_STEPS + 1): - fb = frame(lambda d, ff: render.draw_rain_clock( + for fade in range(matrix.MATRIX_FADE_STEPS + 1): + fb = frame(lambda d, ff: matrix.draw_rain_clock( d, W, H, "23", "59", False, ff, fade=fade), f) for y in range(y0, y1): for x in range(x0, x1): @@ -567,29 +786,29 @@ def test_rain_clock_fades_in_and_out(self): maxdim[fade] = max(maxdim[fade], max(r, g, b)) bare_max = 0 for f in range(0, 120, 7): - bare = frame(lambda d, ff: render.draw_matrix(d, W, H, ff), f) + bare = frame(lambda d, ff: matrix.draw_matrix(d, W, H, ff), f) for y in range(y0, y1): bare_max = max(bare_max, max(max(p) for p in bare[y][x0:x1])) self.assertEqual(maxdim[0], bare_max, "fade 0 is not bare rain inside the clock box") - self.assertGreater(maxdim[0], maxdim[render.MATRIX_FADE_STEPS] + 80, + self.assertGreater(maxdim[0], maxdim[matrix.MATRIX_FADE_STEPS] + 80, "the overlay does not dim the rain behind the " "clock at full strength") # monotonic dimming: the in-box rain never brightens as the overlay # strengthens - for fade in range(render.MATRIX_FADE_STEPS): + for fade in range(matrix.MATRIX_FADE_STEPS): self.assertGreaterEqual(maxdim[fade], maxdim[fade + 1], "in-box rain brightens as the overlay " "strengthens (fade=%d)" % fade) def test_faded_rain_clock_draws_digits_on_the_ramp(self): # each fade level draws digit pixels in exactly its ramp shade - # (255*fade//STEPS), until fade 0 removes them entirely + # (CLOCK_WHITE*fade//STEPS), until fade 0 removes them entirely for fade in (1, 3, 8): - dh = 255 * fade // render.MATRIX_FADE_STEPS + dh = render.CLOCK_WHITE[0] * fade // matrix.MATRIX_FADE_STEPS hits = 0 - fb = frame(lambda d, ff: render.draw_rain_clock( + fb = frame(lambda d, ff: matrix.draw_rain_clock( d, W, H, "23", "59", False, ff, fade=fade), 10) for row in fb: for px in row: @@ -597,38 +816,36 @@ def test_faded_rain_clock_draws_digits_on_the_ramp(self): hits += 1 self.assertGreater(hits, 0, "no digit pixels at shade %d " "(fade=%d)" % (dh, fade)) - gone = frame(lambda d, ff: render.draw_rain_clock( + gone = frame(lambda d, ff: matrix.draw_rain_clock( d, W, H, "23", "59", False, ff, fade=0), 10) - self.assertNotIn(render.WHITE, (px for row in gone for px in row), - "digits visible at fade 0") + self.assertNotIn(render.CLOCK_WHITE, + (px for row in gone for px in row), + "digits visible at fade 0") def test_exit_ink_matches_the_real_font(self): - # the embedded digit glyphs (render._DIGIT_GLYPHS) must be the same + # the embedded digit glyphs (matrix._DIGIT_GLYPHS) must be the same # shapes Pimoroni's bitmap6 draws — the exit ramps them into drops, # and a divergent copy would visibly snap the clock at the # conversion boundary. First the raw glyph data, then the ink map's # pixel positions against really drawn text. for ch in "0123456789": mine = {(col, row) for col in range(6) for row in range(6) - if render._DIGIT_GLYPHS[ch][col] >> row & 1} + if matrix._DIGIT_GLYPHS[ch][col] >> row & 1} spec = simmod.font6_data.GLYPHS[ch] real = {(col, row) for col in range(6) for row in range(6) if spec[col] >> row & 1} self.assertEqual(mine, real, "digit %r bytes diverge from " "font6" % ch) - self.assertEqual(render._DIGIT_WIDTHS[ord(ch) - 48], + self.assertEqual(matrix._DIGIT_WIDTHS[ord(ch) - 48], simmod.font6_data.WIDTHS[ord(ch) - 32], "digit %r width diverges" % ch) - # the ink map must land exactly where d.text puts the digits + # the ink map must land exactly where draw_clock puts the digits + # (draw_clock is the layout authority: fixed digit slots) d = simmod.SimGraphics(W, H) - mapped = set(render._clock_ink(d, W, H, "23", "59")) - mhh = d.measure_text("23", 1) - base = (W - (mhh + 3 + d.measure_text("59", 1))) // 2 - d.set_pen(d.create_pen(255, 255, 255)) - d.text("23", base, render.TEXT_Y) - d.text("59", base + mhh + 3, render.TEXT_Y) + mapped = set(matrix._clock_ink(d, W, H, "23", "59")) + render.draw_clock(d, W, H, "23", "59", False) real = {(x, y) for y in range(H) for x in range(W) - if d.fb[y][x] == render.WHITE} + if d.fb[y][x] == render.CLOCK_WHITE} self.assertEqual({(x, y) for (x, y, _, _) in mapped}, real, "the ink map does not match the drawn clock") @@ -640,24 +857,24 @@ def test_rain_clock_exit_pours_then_ink_falls_organically(self): # pure bare rain (no mid-air cutoff). Crossing drops transiently # cover ink pixels, so ink counts are sampled as the max over # several frames — the max is the least-obscured count. - last = frame(lambda d, ff: render.draw_rain_clock( + last = frame(lambda d, ff: matrix.draw_rain_clock( d, W, H, "23", "59", False, ff, - dissolve=render.MATRIX_DISSOLVE_STEPS), 10) - bare = frame(lambda d, ff: render.draw_matrix(d, W, H, ff), 10) + dissolve=matrix.MATRIX_DISSOLVE_STEPS), 10) + bare = frame(lambda d, ff: matrix.draw_matrix(d, W, H, ff), 10) self.assertEqual(last, bare, "the dissolved clock did not reduce to bare rain") sim = simmod.SimGraphics(W, H) - ink = render._clock_ink(sim, W, H, "23", "59") + ink = matrix._clock_ink(sim, W, H, "23", "59") all_px = {(x, y) for (x, y, s, f) in ink} self.assertGreater(len(all_px), 20, "ink map implausibly small") max_white = {} for step in (1, 2, 3, 4): best = 0 for f in range(0, 90, 7): # max over sampled frames - fb = frame(lambda d, ff: render.draw_rain_clock( + fb = frame(lambda d, ff: matrix.draw_rain_clock( d, W, H, "23", "59", False, ff, dissolve=step), f) n = sum(1 for y in range(H) for x in range(W) - if fb[y][x] == render.WHITE) + if fb[y][x] == render.CLOCK_WHITE) best = max(best, n) max_white[step] = best # immediate conversion, no dedicated pour phase: the very first @@ -665,8 +882,8 @@ def test_rain_clock_exit_pours_then_ink_falls_organically(self): # the full ink count), most of the clock still lit — with the # coarse 4-step stagger roughly a quarter of the ink converts # per step, each wave plainly visible - self.assertGreater(max_white[1], len(all_px) - 25, - "too much ink lost at the start of the exit") + self.assertGreaterEqual(max_white[1], len(all_px) - 25, + "too much ink lost at the start of the exit") self.assertLess(max_white[1], len(all_px), "no pixel converted at the first exit step") # organic stagger: the conversion waves through steps 1..3, never @@ -678,7 +895,7 @@ def test_rain_clock_exit_pours_then_ink_falls_organically(self): # stagger spans convert steps 0..3: past step 4 no ink is left self.assertEqual(max_white[4], 0, "ink left after all conversions") # and drops fall beside it: bright rain-green outside the ink too? - fb = frame(lambda d, ff: render.draw_rain_clock( + fb = frame(lambda d, ff: matrix.draw_rain_clock( d, W, H, "23", "59", False, ff, dissolve=6), 10) drops_anywhere = sum(1 for y in range(H) for x in range(W) if fb[y][x][1] > 120 and fb[y][x][0] < fb[y][x][1]) @@ -729,21 +946,22 @@ def test_rain_clock_exit_pours_then_ink_falls_organically(self): GOLDEN_CLOCK = ( ' \n' ' \n' - ' \n' - ' *** ** **** ***** \n' - ' * * * * * * * \n' - ' ** * * * * \n' - ' * * * * * \n' - ' **** * * *** * \n' - ' \n' + ' %%% % %%% %%%%% \n' + ' % % %% % % % \n' + ' % % % % % % \n' + ' % % % % % \n' + ' % % % % % \n' + ' % % % % % % \n' + ' %%%%% %%% %%% % \n' ' \n' ' ' ) + class TestGolden(unittest.TestCase): def test_weather_rain_frame0(self): - fb = frame(lambda d, f: render.draw_weather(d, W, H, 61, "21C", f), 0) + fb = frame(lambda d, f: scenes.draw_weather(d, W, H, 61, "21C", f), 0) self.assertEqual(ascii_of(fb), GOLDEN_WEATHER_RAIN_F0) def test_hilo(self): @@ -864,20 +1082,81 @@ def test_reading_is_vertically_centered_and_white(self): % (H // 2,)) +class _StubScd41: + """Deterministic SCD41 double: always ready, one fixed ppm reading.""" + + def __init__(self, ppm): + self.ppm = ppm + + def ready(self): + return True + + def measure(self): + return float(self.ppm), 21.5, 45.0 + + +class _StepClock: + """`time` double whose time() steps by `step` on every call — at the + default 16 s each sample() call clears the 15 s cadence guard.""" + + def __init__(self, step=16): + self.now = 1000000 + self.step = step + + def time(self): + self.now += self.step + return self.now + + class TestCO2Ring(unittest.TestCase): """The in-RAM CO2 ring: 3-minute bucket means, fed by the mocked - rotation, while the big readout tracks every raw reading.""" + rotation, while the big readout tracks every raw reading. A fresh + ring gates its readings on the sensor's startup settling.""" + + def test_warmup_gates_on_time_not_read_count(self): + # the SCD41 settles on its own 5 s clock however often it is + # polled, so the gate is wall-clock from the first reading: the + # ring's fastest cadence (15 s pulls) and a slow loop (60 s + # pulls) must lift it at the same epoch + for step in (15, 60): + ring = co2.Co2Ring() + clock = _StepClock(step) + self.assertIsNone(ring.sample(_StubScd41(1500), clock), + "the anchor reading was stored") + until = clock.now + co2.CO2_WARMUP_S + while clock.now < until - step: + self.assertIsNone(ring.sample(_StubScd41(1500), clock), + "a settling reading was stored") + self.assertIsNone(ring.current(), + "a settling reading reached the readout") + self.assertEqual(ring.history(), [], + "a settling reading reached the ring") + # the first reading at/after the epoch is stored + self.assertEqual(ring.sample(_StubScd41(1234), clock), 1234, + "the gate did not lift at CO2_WARMUP_S") + self.assertEqual(ring.current(), 1234, + "the readout must track raw reads once warm") + + def test_restore_lifts_the_warmup_gate(self): + # restore() models a board that has been running (sim preseed): + # the settling gate must not apply to it + ring = co2.Co2Ring() + ring.restore([(100000, 800)]) + self.assertEqual(ring.sample(_StubScd41(1234), _StepClock()), 1234, + "a restored ring still gated readings") def test_rotation_commits_bucket_means_every_three_minutes(self): run_main.CANNED_CO2 = 1000 # pin so each bucket mean is exact try: out = {} - run_main.run_current(470.0, out_globals=out) + # 590 s: the boot settling gate holds the first ~180 s; the + # remaining span must still cross two 3-minute buckets + run_main.run_current(590.0, out_globals=out) finally: run_main.CANNED_CO2 = None ring = out["co2"] self.assertGreaterEqual(len(ring.history()), 2, - "470 s of rotation committed <2 buckets") + "590 s of rotation committed <2 buckets") self.assertEqual([ppm for _, ppm in ring.history()], [1000] * len(ring.history()), "ring entries must be bucket means, not raw tags") @@ -888,8 +1167,12 @@ def test_rotation_commits_bucket_means_every_three_minutes(self): for g in gaps), "committed buckets off the wall-clock grid: %s" % (gaps,)) - def test_readout_tracks_raw_reads_before_first_bucket(self): - run_main.CANNED_CO2 = 1111 + def test_boot_warmup_gates_settling_readings(self): + # the SCD41's startup settling is untrustworthy (it can spike high + # shortly after boot): nothing may reach the readout, the ring, or + # the alarm while the settling window holds + run_main.CANNED_CO2 = 1500 # an alarm-grade transient at boot + run_main.FakeChannel.beeps = 0 try: out = {} run_main.run_current(40.0, out_globals=out) @@ -897,8 +1180,10 @@ def test_readout_tracks_raw_reads_before_first_bucket(self): run_main.CANNED_CO2 = None ring = out["co2"] self.assertEqual(len(ring.history()), 0, "a bucket committed inside 180 s") - self.assertEqual(ring.current(), 1111, - "the live readout missed the raw reading") + self.assertIsNone(ring.current(), + "a boot-transient reading reached the readout") + self.assertEqual(run_main.FakeChannel.beeps, 0, + "a boot-transient reading alarmed") def test_preseeded_ring_starts_with_history(self): out = {} @@ -1008,7 +1293,8 @@ def test_icons_entries_shared_with_sim(self): def test_icons_grid_shape_and_animation(self): import before_after - frames = before_after.render_icons(render, before_after.ICON_ENTRIES, 4) + frames = before_after.render_icons(simmod.RENDER, + before_after.ICON_ENTRIES, 4) self.assertEqual(len(frames), 4) self.assertEqual(len(frames[0]), 3 * 11) # 3 rows of 11 px cells self.assertEqual(len(frames[0][0]), 4 * 11) # 4 cols of 11 px cells @@ -1016,7 +1302,8 @@ def test_icons_grid_shape_and_animation(self): def test_stack_infers_dims(self): import before_after - a = before_after.render_icons(render, before_after.ICON_ENTRIES[:4], 2) + a = before_after.render_icons(simmod.RENDER, + before_after.ICON_ENTRIES[:4], 2) stacked, w, h = before_after.stack(a, a) self.assertEqual((w, h), (4 * 11, 11)) self.assertEqual(len(stacked[0]), 2 * 11 + 1) # + 1 px separator row @@ -1027,7 +1314,8 @@ def test_identical_screen_writes_no_gifs(self): import os import tempfile import before_after - frames = before_after.render_icons(render, before_after.ICON_ENTRIES[:4], 2) + frames = before_after.render_icons(simmod.RENDER, + before_after.ICON_ENTRIES[:4], 2) with tempfile.TemporaryDirectory() as td: out = os.path.join(td, "pr") msg = before_after.write_screen_gifs(out, "icons", frames, frames, @@ -1053,7 +1341,10 @@ def test_demo_gif_matches_code(self): class TestRunMainMocked(unittest.TestCase): - """The real main.py under full mocks (hardware/internet/time stubbed).""" + """The real main.py under full mocks (hardware/internet/time stubbed). + The alarm tests preseed the co2 ring: preseed's restore() models a + warmed-up board, and without it the boot settling gate would eat + every reading inside these short runs.""" def test_current_rotation_runs(self): frames = run_main.run_current(16.0) @@ -1076,17 +1367,79 @@ def test_ref_version_runs_self_consistent(self): self.assertIsNotNone(frames) self.assertGreater(len(frames), 20) + def test_colon_blink_ignores_the_roll_pace(self): + # the blink is ticks_ms-phased (absolute time, sampled per frame): + # the widget roll's fast frames must not add toggles. A frame-counted + # blink would toggle every ~2 frames at either pace and blow the count + frames = run_main.run_current(30.0) + # the colon's column: the run draws the clock in x_bounds=(0, 29) + cx = ((render.WIDGET_X0 - 2) - render.CLOCK_W) // 2 \ + + 2 * render.CLOCK_SLOT + states = [fb[render.TEXT_Y + 2][cx] != (0, 0, 0) for fb in frames] + toggles = sum(1 for a, b in zip(states, states[1:]) if a != b) + # ~2 toggles/s over ~27 clock-drawn seconds (the run's head is boot) + self.assertGreaterEqual(toggles, 50, + "blink barely toggles: phase not ticks_ms") + self.assertLessEqual(toggles, 65, + "blink toggles with the frame pace — the roll " + "sped it up") + + def test_widget_rotation_rolls_not_cuts(self): + # the widget step must interpolate: between two steady widget-zone + # ink profiles the rotation must pass through several intermediate + # (mid-roll) profiles. A jump-cut (the roll's phase accidentally + # read from whole-second time.time() once) has none + frames = run_main.run_current(30.0) + x0 = render.WIDGET_X0 # the zone; the clock owns the left + + def profile(fb): + return frozenset(y for y in range(H) + if any(px != (0, 0, 0) for px in fb[y][x0:])) + + runs = [] # [profile, frame count] of consecutive equal profiles + for fb in frames: + p = profile(fb) + if runs and runs[-1][0] == p: + runs[-1][1] += 1 + else: + runs.append([p, 1]) + steady = [i for i, (p, n) in enumerate(runs) if n >= 10] + self.assertGreaterEqual(len(steady), 2, "no two steady widget states") + # the roll visits every row (1 px per fast frame): many distinct + # single-frame intermediate profiles between steady states — a + # multi-px step roll or a jump-cut leaves only a few + self.assertTrue(any(steady[k + 1] - steady[k] >= 5 + for k in range(len(steady) - 1)), + "widget motion is not fluid: too few mid-roll " + "profiles between steady states") + def test_rotation_includes_co2(self): - # the mocked SCD41 must make the co2 screen appear in the rotation - frames = run_main.run_screen_current("draw_co2", 25.0) - self.assertTrue(frames, "co2 screen never appeared in the rotation") + # the mocked SCD41 must feed the dashboard's co2 widget (the strip + # screen only runs as the alarm now, so its draw is not reached in + # a normal pass). Capture draw_widget dispatches and require the + # co2 frame among them, so wx/hilo draws cannot mask a co2 + # regression; only the widget zone is compared (the clock owns the + # left). CANNED pins the reading so the co2 frame is reproducible, + # preseed skips the boot settling gate + run_main.CANNED_CO2 = 812 + try: + frames = run_main.run_screen_current("draw_widget", 30.0, + preseed_co2=1) + finally: + run_main.CANNED_CO2 = None + ref = frame(lambda d, f: scenes.draw_widget( + d, W, H, {"kind": "co2", "ppm": 812}, 0)) + x0 = render.WIDGET_X0 - 1 # right of the clock's x_bounds + self.assertIn([row[x0:] for row in ref], + [[row[x0:] for row in fb] for fb in frames], + "the co2 widget never drew") def test_co2_alarm_beeps_when_high_and_lit(self): run_main.CANNED_CO2 = 1500 run_main.CANNED_LIGHT = 100.0 run_main.FakeChannel.beeps = 0 try: - run_main.run_current(22.0) + run_main.run_current(22.0, preseed_co2=1) finally: run_main.CANNED_CO2 = None run_main.CANNED_LIGHT = 2048.0 @@ -1099,7 +1452,7 @@ def test_co2_alarm_silent_in_the_dark(self): run_main.CANNED_LIGHT = light run_main.FakeChannel.beeps = 0 try: - run_main.run_current(22.0) + run_main.run_current(22.0, preseed_co2=1) finally: run_main.CANNED_CO2 = None run_main.CANNED_LIGHT = 2048.0 @@ -1113,7 +1466,7 @@ def test_co2_alarm_threshold_boundary(self): run_main.CANNED_LIGHT = light run_main.FakeChannel.beeps = 0 try: - run_main.run_current(22.0) + run_main.run_current(22.0, preseed_co2=1) finally: run_main.CANNED_CO2 = None run_main.CANNED_LIGHT = 2048.0 @@ -1121,27 +1474,17 @@ def test_co2_alarm_threshold_boundary(self): "ALS=%s beeps=%s want %s" % (light, run_main.FakeChannel.beeps, want_beeps)) - def test_co2_alarm_silent_when_low(self): - run_main.CANNED_CO2 = 800 - run_main.CANNED_LIGHT = 100.0 - run_main.FakeChannel.beeps = 0 - try: - run_main.run_current(22.0) - finally: - run_main.CANNED_CO2 = None - run_main.CANNED_LIGHT = 2048.0 - self.assertEqual(run_main.FakeChannel.beeps, 0) - def test_co2_alarm_threshold_is_red_level(self): # the audible alarm must fire exactly at the ppm level that turns - # the CO2 font red (render.CO2_RED_PPM) + # the CO2 font red (render.CO2_RED_PPM); the RED-1 leg also covers + # "a normal room reading never alarms" (maximal below-threshold) for ppm, want_beeps in ((render.CO2_RED_PPM, True), (render.CO2_RED_PPM - 1, False)): run_main.CANNED_CO2 = ppm run_main.CANNED_LIGHT = 100.0 run_main.FakeChannel.beeps = 0 try: - run_main.run_current(22.0) + run_main.run_current(22.0, preseed_co2=1) finally: run_main.CANNED_CO2 = None run_main.CANNED_LIGHT = 2048.0 @@ -1155,8 +1498,8 @@ def test_run_main_wrappers_preserve_signatures(self): # icons lost the moon when weather/rotation ran before icons) import inspect run_main.run_current(1.0) - self.assertIn("is_day", inspect.signature(render.draw_icon).parameters) - self.assertIn("is_day", inspect.signature(render.draw_weather).parameters) + self.assertIn("is_day", inspect.signature(scenes.draw_icon).parameters) + self.assertIn("is_day", inspect.signature(scenes.draw_weather).parameters) def test_boot_animation_drawn_at_startup(self): # with wifi+weather mocked OK, draw_boot is only used for the @@ -1239,6 +1582,15 @@ def test_scd41_altitude_configured(self): run_main.run_current(2.0) self.assertEqual(run_main.FakeSCD41.last.altitude_m, 470) + def test_boot_dimmer_configured(self): + # main.py sets the panel dimmer once at boot; the scale is + # scanout-side (the fb never sees it), so assert the value + # reached the driver against main.py's own constant + out = {} + run_main.run_current(2.0, out_globals=out) + self.assertEqual(out["gu"].brightness, out["DISPLAY_BRIGHTNESS"], + "boot never set the panel dimmer") + if __name__ == "__main__": unittest.main()