diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 257f4985..e554f6eb 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -10,7 +10,12 @@ python -m pytest -m "" # every test, the slow ones too (as CI ru python -m pytest -m slow # the slow ones alone python scripts/eval_prompts.py # the saved questions: the reasoning effort (made in code) and the tools' expectations, no key needed ``` -Plain `pytest` takes about 19 s on four cores; everything (`-m ""`) about 45 s. The slow tests, 0.5 s or more each run alone (the browser +Plain `pytest` takes about 19 s on four cores; everything (`-m ""`) about 51 s, and must stay under a minute: the browser tests are split +into parts that run side by side, and wait on the page (`calm` in `tests/web_dashboard_browser.js`) rather than for fixed times. +The weather's tests count its own frames and time, never the machine's: each of its frames is a fixed step of its time however long it +took to draw (`window.__skyTest`, see `weatherPage`), and most of its pages are driven (`driven`: the test makes the frames, one after +another, from the same start whatever the load, its randomness seeded: the same frames every run; `SKY_SEED=n` seeds it otherwise, to +see how near a check is to failing). A frame's cost is the page script's own CPU time (`frameCost`), not the clock's. The slow tests, 0.5 s or more each run alone (the browser tests of the web page, the service evals over every tool, the tests that start servers, the archive's own), are listed in `tests/slow_tests.txt` and marked `slow` by `tests/conftest.py`; `python scripts/slow_tests.py` measures every test again and rewrites the list (about two and a half minutes). The slowest fixture, the fake station's 18-month archive (`archived_cache` in `tests/conftest.py`), diff --git a/Dockerfile b/Dockerfile index 9a3f2478..36c206b8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -61,10 +61,14 @@ RUN if [ -n "$COMMIT" ]; then echo "$COMMIT" > .git/HEAD; fi ENV PATH=/opt/venv/bin:$PATH PYTHONUNBUFFERED=1 # ecobot-mcp. Importing it once writes the bytecode of every module it loads at start, and only those, and checks it needs nothing -# but its own packages (no Telegram, no model client: they are not in this venv) +# but its own packages (no Telegram, no model client: they are not in this venv). Besides the program's own imports, what main() and +# the first requests import (the tools, lib.service.*; uvicorn's HTTP protocol and lifespan; anyio's asyncio backend; the HTTP clients' +# connection pool and certificates): without their bytecode each start compiled them again before listening (its user can't write any) FROM app AS ecobot-mcp COPY --from=venv-mcp /opt/venv /opt/venv -RUN DATA_DIR=/tmp/build python -c "import sys, importlib.util; import ecobot_mcp.__main__, lib.mcp_server; \ +RUN DATA_DIR=/tmp/build python -c "import sys, importlib, importlib.util, pkgutil; import ecobot_mcp.__main__, lib.mcp_server, lib.service; \ +[importlib.import_module('lib.service.' + m.name) for m in pkgutil.iter_modules(lib.service.__path__)]; \ +import uvicorn.protocols.http.h11_impl, uvicorn.lifespan.on, anyio._backends._asyncio, httpcore, truststore, certifi; \ assert not {'telegram', 'openai'} & set(sys.modules), 'ecobot-mcp imported the bot'; \ assert importlib.util.find_spec('telegram') is None and importlib.util.find_spec('openai') is None" \ && rm -rf /tmp/build diff --git a/README.md b/README.md index ada6cd1a..23b6bc25 100644 --- a/README.md +++ b/README.md @@ -258,10 +258,10 @@ the internet), and fits every tile on the screen in portrait or landscape where updates by itself when a new reading arrives, and says "reconnecting…" while ecobot-mcp is away. This page is the dashboard: the Telegram bot has none of its own (its Status button sends a picture of the temperature, humidity and rain gauges alone). -Temperature, humidity, pressure, rain, UV index and the US AQI come first; then the weather station's other gauges, then the air +Temperature, humidity, pressure, rain, UV index and the AQI come first; then the weather station's other gauges, then the air sensor's (when there is one). The air sensor's bands are on US standards: -- **US AQI**, the higher of PM2.5's and PM10's (as AirNow gives it; "(PM10)" after the category when PM10 sets it), on a 0-500 dial with the EPA's six categories and colours (Good 0-50 green, Moderate 51-100 yellow, +- **AQI** (the tile's title; it is the US AQI, which the bot and ecobot-mcp's tools still call it), the higher of PM2.5's and PM10's (as AirNow gives it; "(PM10)" after the category when PM10 sets it), on a 0-500 dial with the EPA's six categories and colours (Good 0-50 green, Moderate 51-100 yellow, Unhealthy for Sensitive Groups 101-150 orange, Unhealthy 151-200 red, Very Unhealthy 201-300 purple, Hazardous 301-500 maroon), the category's name under the number; - **PM2.5** (µg/m³) on the EPA's 2024 breakpoints (9.0, 35.4, 55.4, 125.4, 225.4) and **PM10** on the EPA's (54, 154, 254, 354, @@ -274,7 +274,7 @@ sensor's (when there is one). The air sensor's bands are on US standards: On the air dials every category gets an equal share of the dial (as AirNow's AQI dial draws them), so "good" and "moderate" aren't squeezed into a sliver of a scale that runs to 500; the numbers round the dial are the breakpoints. The monitor's own temperature and -humidity repeat the station's outdoor ones, so they have no gauge. The US AQI and each category's name are of the reading now, so they +humidity repeat the station's outdoor ones, so they have no gauge. The AQI and each category's name are of the reading now, so they always agree with the needle and with the PM2.5 and PM10 dials (the alerts and the bot's words rate PM2.5 and PM10 on the last two readings, so a passing spike isn't called poor). The page's data never asks the air sensor: with its reading stale it shows the one it holds. @@ -283,10 +283,53 @@ A tile whose reading is missing just now (the station or the air sensor not send scale's low end where 0 isn't on it: pressure 950 hPa, CO₂ 400 ppm) with its highs and lows still beside it; when the reading comes back the tile brightens and its gauge rises in place. A reading the station or the monitor has never sent has no tile. +The tiles can be arranged to taste. Drag a tile by its gauge to move it (with a mouse, from anywhere on it but its title, its reading +and its table, which stay selectable for copying; on a touch screen, a long press picks it up, with a short buzz on Android); the +others make room. Its ×, shown on mouseover (or after a long press), hides it, as does dropping it on the "remove" zone that slides +down from the top while dragging. With a tile hidden, "reset preferences" beside the time at the bottom brings every tile back in the +usual order (and the units below back to metric). Fewer tiles grow to fill the window (a single one fills it), never smaller than the whole dashboard's. The arrangement +is kept in the browser (its local storage, per browser and device); nothing is sent to ecobot-mcp. A gauge added later takes its +usual place among yours. + +Four small switches at the bottom right, left of the time (just above it on a phone), choose the units: "°C | °F" for every +temperature tile (Temperature, Dew point, Feels like, Indoor temperature), "km/h | mph" for the Wind's, "hPa | inHg" for Atmospheric +pressure and "mm | in" for Rain and Rain rate (mm/h becomes in/h), the one in use lit (buttons, so Tab and Enter or Space work too). +The tile's reading, its scale and the numbers on it (0-40 °C becomes 32-104 °F, 0-100 km/h 0-60 mph, 950-1050 hPa 28-31 inHg, the +rain's 0-100 mm 0-4 in and its rate's 0-50 mm/h 0-2 in/h), its Daily, Monthly and Yearly figures, its unit and the red hand (the +Wind's gust, the rain rate's high) all change in place, with the same decimals (two in inHg and inches); the pressure's arrow (after +its reading: up and blue when it rose 0.3 hPa or more over the past hour, down and red when it fell as much, none when +steady (under 0.3 hPa either way) or with less than about an hour of readings) points the same way. ecobot-mcp still sends metric and the browser converts. The wind's direction stays in degrees. Each browser keeps its +choice with the arrangement, and "reset preferences" (shown while any is not metric) puts all four back to metric. The weather +behind the gauges goes by the metric readings whatever is shown (heat from 35 °C, leaves above 15 km/h, a flood above 30 mm/h). + +A click or tap on a gauge (or Enter or Space on a tile reached with Tab) zooms its title and gauge (its table hidden until you go +back) to fill the window, a single tile shown too. Zoomed, page through the tiles like a photo gallery, each still live: ← and →, Space (next) and Backspace (previous), a +swipe, a drag on the gauge, or a two-finger sideways swipe on a trackpad; it stops at the first and the last (with one tile, paging just nudges it and back). A click or tap (not on the text) or Esc goes back. + +Behind the gauges, the weather is drawn as faint pixel art while the readings call for it: rain while it rains, hazy clouds drifting across from the US +AQI's Moderate band up, UV beams at a UV index of 11, the glass fogging over at 90 % humidity (heavier to 100 %), beads condensing in the fog and running down it, wiping clear tracks, leaves blowing past +above 15 km/h of wind, faint red beams between the UV's from 35 °C (more and brighter to 43 °C) and ice below 0 °C. "stop" at the bottom left stops and clears them for that page view only, and ends any effect a temporary test link turned on; +nothing is saved, so a reload brings them back. `MCP_DASHBOARD_ANIMATIONS` sets how much moves, for everyone: `on` (the default) +animates everything; `low` keeps the gauges sweeping and the tiles rearranging animated but draws no weather (no "stop" or test links) +and zooms at once; `off` draws no weather and animates nothing (the gauges jump to each new reading, zooming and rearranging happen at +once). A browser asking for reduced motion gets `off`'s. + +On a phone or tablet the humidity's beads run downhill as it tilts: the page reads the motion sensor (gravity, turned for the screen's +rotation, so the true downhill whichever way it is held), smoothed; they run off whichever edge is lowest, and the steeper the +tilt the faster (sin of the angle off level: none under 5 degrees, rising smoothly to full speed at 40, which holds through upright, then +easing off again from 140 degrees). Lying flat, face up or face down (under 5 degrees), the water pools instead: nothing runs, no trails +are laid, and beads that touch (or sit a few px apart: a slight pull draws them together) keep merging into ever larger blobs, with no +size limit. Android's Chrome and Firefox give the sensor freely and it starts by itself; an iPhone's or +iPad's Safari asks first, so a small "tilt" link appears at the bottom left (a tap asks; gone once answered). Desktop browsers have no +sensor, so nothing changes there, and with `low` or `off` (or reduced motion) the sensor is never read. The browser needs the page +served over HTTPS for the sensor (behind a TLS proxy, not plain `http://` on the LAN, except on localhost). + It is read-only (the weather and air readings, nothing else), so it is open to anyone on your network: no token, and any name or address in the URL (`MCP_ALLOWED_HOSTS` is only for `/mcp`, which keeps its token). ecobot-mcp has to listen beyond the machine itself: Docker publishes port 8765 already; under systemd set `MCP_BIND=0.0.0.0:8765`. It is plain HTTP: keep it on your own network. To -turn it off, set `MCP_DASHBOARD=off`. +turn it off, set `MCP_DASHBOARD=off`. To keep your home's own readings off it (privacy), set `MCP_DASHBOARD_INDOOR=off`: the indoor +tiles (Indoor temperature, Indoor humidity) are then neither drawn nor sent, and nothing indoor leaves ecobot-mcp through the dashboard. +The bot, the MCP tools, the Status picture and the alerts still have them. To put it on a site of its own behind a reverse proxy, map the site's root to `/dashboard/` (it answers there too), e.g. with nginx `location / { proxy_pass http://deb1:8765/dashboard/; }`. The live updates need nothing more: they tell nginx not to buffer them. diff --git a/docs/configuration.md b/docs/configuration.md index 4d86edc1..d59a80a8 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -37,7 +37,7 @@ At least one of Ecowitt (cloud or Home Assistant) or AirGradient (cloud, local o | `MCP_AIRGRADIENT_API_TOKEN`, `MCP_AIRGRADIENT_LOCATION_ID` | – | Enables AirGradient via cloud API: history and gap fill | | `MCP_AIRGRADIENT_LOCAL_URL` | – | Sensor's local server, e.g. `http://airgradient_.local` or an IP. Live reading polled every 60 s, recorded as 5-min means (`pm02Compensated` over `pm02`). Cloud, if configured, only fills gaps. Without cloud vars: sensor + SQLite only, no cloud requests. `.local` resolved in-process (mDNS); in Docker needs the host network (README: Docker networking) or an IP. Sensor down → cloud fallback, retry after 5 min | | `MCP_AIRGRADIENT_SOURCE` | `auto` | `auto`: each that is set, the sensor itself first, then Home Assistant (if it has the sensor), then the cloud; `local`, `homeassistant` or `cloud`: that one alone | -| `MCP_HOMEASSISTANT_URL`, `MCP_HOMEASSISTANT_TOKEN` | – | Home Assistant (e.g. `http://192.168.1.219:8123`) and a long-lived access token (your profile page there). With its Ecowitt and AirGradient integrations the readings are read back to shade the recent charts between each 5 minutes' lowest and highest, for the days ecobot was not watching too (the last 31 days at most; Home Assistant keeps 10 unless its recorder says otherwise). Both needed. They also make Home Assistant a source of the station's readings (see `MCP_ECOWITT_SOURCE`): minute lines, a live reading every few seconds and rain alerts as the gauge reports; without them the shading comes from ecobot's own readings | +| `MCP_HOMEASSISTANT_URL`, `MCP_HOMEASSISTANT_TOKEN` | – | Home Assistant (e.g. `http://192.168.1.219:8123`) and a long-lived access token (your profile page there). With its Ecowitt and AirGradient integrations the readings are read back to shade the recent charts between each 5 minutes' lowest and highest, for the days ecobot was not watching too (the last 31 days at most; Home Assistant keeps 10 unless its recorder says otherwise). Both needed. They also make Home Assistant a source of the station's readings (see `MCP_ECOWITT_SOURCE`): minute lines, a live reading every 30 seconds and rain alerts as the gauge reports; without them the shading comes from ecobot's own readings | | `MCP_AIRGRADIENT_DASHBOARD_URL` | – | "live chart" link in air replies and alerts | | `MCP_PLACE` | `Melbourne` | Name in the Pollen & asthma and Forecast headings | | `MCP_POLLEN` | `off` | Melbourne grass pollen + thunderstorm asthma (melbournepollen.com.au): report, `pollen_asthma` tool, alert at High. Oct–Dec only | @@ -71,6 +71,8 @@ At least one of Ecowitt (cloud or Home Assistant) or AirGradient (cloud, local o | `MCP_CHART_BASE_URL` | none | Where people's browsers reach the chart links' pictures (`?charts=link`, below): the URL a reverse proxy serves `/charts` at, e.g. `https://api.example.org/ecobot-charts` with nginx's `location /ecobot-charts/ { proxy_pass http://127.0.0.1:8765/charts/; }`. Unset: the address the MCP request came to (`X-Forwarded-Proto` and `X-Forwarded-Host` when a proxy sends them) with `/charts` | | `MCP_CHART_LINK_HOURS` | `24` | How long a chart link's picture answers (1 to 720 hours). They are kept in memory (at most 500, 64 MB in all, the oldest dropped first): a restart forgets them, and an old link answers 404 | | `MCP_DASHBOARD` | `on` | The gauges' live web page at `/dashboard` beside `/mcp` (`http://deb1:8765/dashboard`): read-only, so it needs no token and answers any `Host` (open it by the machine's name or address from the LAN); `/mcp` keeps both checks. `off`: `/dashboard`, `/dashboard/`, `/dashboard/icon.png`, `/dashboard/data` and `/dashboard/events` answer 404 | +| `MCP_DASHBOARD_ANIMATIONS` | `on` | How much moves on the dashboard page, for every viewer. `on`: everything: the gauges' needles sweep to each new reading, the weather is drawn behind the gauges (pixel-art rain, haze, UV, humidity, wind, heat and ice while the readings call for them, something blown across in a gust over 99 km/h, with a "stop" link stopping them in that page view until a reload), zooming a tile and the tiles rearranging (one moved or hidden) are animated. `low`: the gauges sweep and the tiles rearrange animated as with `on`, but no weather at all (nothing drawn, no "stop" link, no test links) and zooming happens at once. `off`: no weather, and nothing animated: the gauges' needles and readings jump straight to each new reading, zooming and rearranging happen at once. New readings are applied as they come in each. A browser asking for reduced motion gets `off`'s, whatever this is | +| `MCP_DASHBOARD_INDOOR` | `on` | The page's indoor tiles (Indoor temperature, Indoor humidity: every indoor reading's). `off` (privacy, as the page needs no token): they are left out, neither drawn nor sent: `/dashboard/data` carries no indoor reading at all, as if the station had no indoor sensor, and `/dashboard/events` sends no event for an indoor change alone. Only the dashboard: the bot, the MCP tools, the Status picture and the alerts still read and show them. A browser's saved arrangement naming the indoor tiles does no harm. Any other value keeps `on`, with a warning | Every request to `/mcp` needs a token (`AUTH_TOKENS`, below). Chart images are not a setting of ecobot-mcp but of each client: a client whose MCP URL ends `?charts=png` (`http://127.0.0.1:8765/mcp?charts=png`) gets each chart as a PNG beside the figures, drawn in `DARKMODE`'s theme; a client whose URL ends `?charts=link` gets each chart as a link to its PNG (`/charts/.png`, served with no token and any `Host`, so anyone with the link can open it until it expires; `MCP_CHART_BASE_URL`, `MCP_CHART_LINK_HOURS`) and the model is asked to put it in its reply as a markdown image, for a chat app that shows those but not a tool's image (LibreChat); a call's request `_meta` `chart_image` (`"png"`, `"link"` or `"none"`) overrides its connection's ([ecobot-mcp.md](ecobot-mcp.md) 3.7). They need Pillow (`requirements-charts.txt`, in both Docker images): installed from `requirements-mcp.txt` alone ecobot-mcp answers with the charts' JSON and a note, and warns once. diff --git a/docs/ecobot-mcp.md b/docs/ecobot-mcp.md index 5f21b2f4..3535e23c 100644 --- a/docs/ecobot-mcp.md +++ b/docs/ecobot-mcp.md @@ -219,8 +219,8 @@ rain is summarised. **`current`'s result:** `{as_of, sensors: {"outdoor": {"temperature": {value, unit, text: "12.3 °C", [emoji], [today: {low, low_text, low_when, high…}], [month…], [year…]}}, "rainfall": {"rain": {…, [today: {total}], [month: {total, wettest_day}], [year…]}}, "wind": -{"wind_speed": {…, [today: {high_gust…}]}}, "air": {"pm2_5": {value, unit, rating, aqi_us, band}}}}`: with `context`, everything the -bot's gauges show (rain as totals and its wettest day, wind's highest gust); with `context` and no readings named, every gauge's reading +{"wind_speed": {…, [today: {high…, high_gust…}]}}, "air": {"pm2_5": {value, unit, rating, aqi_us, band}}}}`: with `context`, everything the +bot's gauges show (rain as totals and its wettest day, wind speed's highest and its highest gust); with `context` and no readings named, every gauge's reading the station sends now, those its file hasn't recorded yet (outside the catalogue) too, as the gauges show them. The air sensor's air-quality readings have their highs and lows with `context` too (from its day rows, with their day but no time of day), so a reading it lacks now, or the sensor not answering, still gives its figures with `value` null. @@ -631,8 +631,8 @@ Each step ships on its own, with the tests and evals green and the bot working t `ToolsListChanged` when the file's catalogue gains a reading (read every minute; the tools and instructions are then built again). `http_app`: `streamable_http_app` with `TransportSecuritySettings` over `MCP_ALLOWED_HOSTS` and the `TokenCheck` verifier over `AUTH_TOKENS` (`AuthSettings(issuer_url=…, resource_server_url=None)`). `ecobot_mcp/`: `core.py` is the service's startup - (`start_sources`, `Core`: the alert log, the tools, the alert rules, the keep-warm, and `warm_up`, the first fetch, the weather - rules, the live poll, the archive, the backfill and Home Assistant's imports, each loop's last success and failure kept for + (`start_sources`, each source started from what the data folder kept, nothing asked of the network before the port opens; `Core`: the alert log, the tools, the alert rules, the keep-warm, and `warm_up`, the first fetch (the station's device list in the background, its live reading first, then its history, the 5-minute and 30-minute tails first, a fetch a question waits for hurried to the urgent line; the air sensor's reading and the rest of its start; the forecast and pollen page if due), the weather + and particulates rules once their device has been read, the live poll, the archive, the backfill and Home Assistant's imports, each loop's last success and failure kept for `ecobot://health`), which `ecobot.py` now calls in-process, its behaviour unchanged; `__main__.py` runs it with the server under uvicorn (`MCP_BIND`; at first it refused a non-loopback address without tokens, and now it always has one, `AUTH_TOKENS` or the generated one); `lib/upstream.py` is the bot's one supervised client, pinned to 2026-07-28, that discovers by hand, listens and re-listens after a backoff (a stdio bridge was built on it and later removed). The image ships `ecobot_mcp/` and @@ -720,9 +720,11 @@ Each step ships on its own, with the tests and evals green and the bot working t sizes) from `/dashboard/data` (gauge_sheet's tiles from `current` with context) and redrawing them on each `/dashboard/events` event (Server-Sent Events, on the gauges' readings changing in ecobot://now/weather's and ecobot://now/air's change detection). Read-only, so no token and no Host check; `/mcp` keeps both. After the station's gauges come the air sensor's - (`lib/airgradient/dashboard.py`, on US standards: the US AQI and PM2.5 on the EPA's 2024 categories, PM10 on the EPA's, CO2 on + (`lib/airgradient/dashboard.py`, on US standards: the US AQI (its tile titled "AQI") and PM2.5 on the EPA's 2024 categories, PM10 on the EPA's, CO2 on the usual ASHRAE-based indoor guidance, the VOC and NOx indices on bands of Sensirion's index); a tile with no reading now is - dimmed at its floor. + dimmed at its floor. The UV index's, the AQI's and the particles' tables have a Max column alone (no Min); the Wind's, + Rain rate's, Solar radiation's and UV index's dials carry a thin red hand at today's highest (`/dashboard/data`'s + `today_highs`: their Daily Max, the Wind's Daily Gust, rising with the reading now). - **6b. Client only.** `BOT_MCP_URL` is required: the in-process mode (`LocalWeather`, the bot starting the sources, the syncers, the alert rules and the alert log itself) is deleted. Under systemd, `ecobot.service` wants and starts after `ecobot-mcp.service`; in Docker this is already the layout. The bot's image installs only its own packages (python-telegram-bot, openai, mcp, httpx). diff --git a/docs/features.md b/docs/features.md index 34327771..633b191b 100644 --- a/docs/features.md +++ b/docs/features.md @@ -6,7 +6,7 @@ Type a question in any chat the bot is in ("how hot is it?", "will it rain?", "r - **Charts:** any reading or several on one time axis, rain behind the lines, one colour per reading. Under a single chart are period buttons (1D, 7D, 1M, 3M, 1Y); pressing one redraws it in place (its other periods are fetched in the background as soon as the chart is sent, so a press is answered at once). Ask for "plot uv and solar on two axes" (or "dual axis", "overlay") to put two readings on one chart, each with its own scale: the left axis for the first, the right for the second. The AirGradient sensor's own temperature and humidity can be charted too, against the weather station's: "plot airgradient humidity over ecowitt humidity" draws both on one axis. They're offered to the AI model only when you name the AirGradient with temperature or humidity. "weather all week" draws every reading, a panel each. - **Status and the report:** the Status button (or `/status`) sends one message: a picture of three gauges, the temperature, humidity and rain now, with the report under it (the readings now, today's forecast and the pollen, written by ecobot-mcp in code, no AI model: `ecobot://status`), and a 🔄 that reads both again into the same message. `/report` asks the AI model for a report instead (ecobot-mcp's `report` prompt). -- **Dashboard:** every gauge, with its highest and lowest today, this month and this year, is ecobot-mcp's live web page (`/dashboard` beside `/mcp`, README); the chat has no dashboard picture any more (typing "dashboard" asks the AI model). +- **Dashboard:** every gauge, with its highest and lowest today, this month and this year (the UV index, the AQI (the US AQI, titled "AQI" on the page), PM2.5, PM10 and PM1: their highest alone), is ecobot-mcp's live web page (`/dashboard` beside `/mcp`, README), the wind's, rain rate's, sun's and UV's dials with a thin red hand at today's highest (the wind's: its gust); the chat has no dashboard picture any more (typing "dashboard" asks the AI model). - **Dark charts:** `DARKMODE=on` draws every chart on a dark background, or only between set times, e.g. `DARKMODE=8pm-8am` (docs/configuration.md). - **Readings at an interval:** "humidity each hour for the last 5 hours", "PM2.5 every 30 minutes this morning", "rain each hour today". Any reading, every minute to every day, each with its time, from the history the bot has stored. Rain is the millimetres that fell in each interval. A gap, such as a sensor that was off, is said, never filled in. Up to 300 rows a question: a longer period gets a coarser interval. - **Days and totals:** count or rank days by any reading ("how many days was UV 9 or more", "hottest day each year"), or total rain per month or year as bars. diff --git a/docs/how-it-works.md b/docs/how-it-works.md index f509b033..87013571 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -50,10 +50,10 @@ scripts/ ecowitt_metrics.py (which metrics the station reports), A design for tappable commands and buttons is in `TELEGRAM_UX.md` (not built yet). -The sources (ecobot-mcp's) have the same shape: `start()`, `warm()`, `close()`, and a `warmer` that refreshes them on a timer. +The sources (ecobot-mcp's) have the same shape: `start()`, `warm()`, `close()`, and a `warmer` that refreshes them on a timer. ecobot-mcp's start (`ecobot_mcp/core.py`) runs each `start()` without waiting on any server (`start(wait=False)`: it is more important to be listening and answering than to have the newest readings), then opens the port while each `warm()` runs once in the background (`Core.warm_up`), and the clients are told when the fresh readings come in (the MCP resources' `ResourceUpdated`, the dashboard's `/dashboard/events`). Each source starts from what the data folder kept: the station's device (its address, name, time zone, place and age, as its device list last gave them; else the station the file's readings are of, in the file's time zone) and its last live reading, the air sensor's last reading (both kept in the file at most once a minute), the last forecast and pollen page, Home Assistant's first state of the station (looked for once, a long history query, after the start). Until a device's first reading of this run comes in, `current` and the dashboard answer from the kept one, as of its time (the request for it made meanwhile), and the alerts of a device start only once it has been read. The station's device list is asked for in the background (the cloud's and Home Assistant's together), and again after a failure, sooner at first then every 5 minutes, until it answers: a station found in the file is used meanwhile, and a new address or time zone it names is taken at the next start. On a first start, with nothing kept, the station's time zone is the configured one (`TZ`) for that run, its readings "not in yet" until the device list answers; the forecast waits for the station's place. The station's live reading is asked for first, before its history (`Ecowitt.first_live`), so the dashboard's tiles and the first "weather now" are fresh within about a second of the port opening (Ecowitt's one request a second allowing), and a live reading being asked for is awaited by whoever else wants it rather than asked again (`Ecowitt._fetch_live`: a question waits only on one asked for a question, never on a background one queued behind the refreshes); the air sensor's reading, Home Assistant's entities of it, the cloud's name for it and today's gaps are its warm-up's (`AirGradient.settle`), and its first `warm()` keeps the reading just read (under 30 seconds old) instead of asking for it again. Home Assistant's `/api/states` answer is shared by everyone asking within 5 seconds (the station's and the air sensor's start ask at about the same moment). The public holiday calendar (`lib/public_holidays.py`) is built at the first holiday question, not at start: the station's start only checks the `holidays` package is installed and the time zone has a state. Every HTTP client shares one TLS context (`lib/tls.py`), made once, rather than each loading the certificates itself. The Docker image holds the bytecode of what the service imports at start and at its first requests (the Dockerfile's build step imports them), as its user can't write any. ## The pollen and forecast sources -Both are off by default. They are websites, not APIs (the pollen page is parsed), so they are fetched gently: only between 6 am and 6 pm local time, pollen every 30 minutes with a conditional request (a 304 costs the site almost nothing) and the forecast every 15 minutes (a failure is logged), and questions use the last fetch. The forecast's rain figure is the Bureau-style "chance of at least 1 mm": the share of Open-Meteo's ECMWF ensemble members (51) that put 1 mm or more on the day, to the nearest 5% (a second request to `ensemble-api.open-meteo.com`; if it is down, Open-Meteo's own figure, the chance of more than 0.1 mm in the wettest hour, is shown as "chance of rain"). The report never fetches them: it always uses the cache. When a forecast day that was sent to a chat (in a report or an answer) is later revised substantially (rain to dry or dry to rain, or the highest temperature more than 2 degrees different), that chat is told, once per revision (`lib/alerts/forecast.py`). What they returned is kept in `conditions_cache.sqlite` (one row per distinct result), so a restart, even at night, starts from the last fetch. One fetch is made at start (or at the first question) when nothing is cached, even at night. `python scripts/conditions.py --lat .. --lon ..` fetches both once and prints what the report would show: run it before switching them on. Grass pollen and the thunderstorm asthma forecast both run October to December, so the pollen source only fetches, shows (in the report or an answer) and alerts in those months; outside them it makes no requests (not even at start), the report has no Pollen & asthma block, and a pollen question is told they only run October to December. +Both are off by default. They are websites, not APIs (the pollen page is parsed), so they are fetched gently: only between 6 am and 6 pm local time, pollen every 30 minutes with a conditional request (a 304 costs the site almost nothing) and the forecast every 15 minutes (a failure is logged), and questions use the last fetch. The forecast's rain figure is the Bureau-style "chance of at least 1 mm": the share of Open-Meteo's ECMWF ensemble members (51) that put 1 mm or more on the day, to the nearest 5% (a second request to `ensemble-api.open-meteo.com`; if it is down, Open-Meteo's own figure, the chance of more than 0.1 mm in the wettest hour, is shown as "chance of rain"). The report never fetches them: it always uses the cache. When a forecast day that was sent to a chat (in a report or an answer) is later revised substantially (rain to dry or dry to rain, or the highest temperature more than 2 degrees different), that chat is told, once per revision (`lib/alerts/forecast.py`). What they returned is kept in `conditions_cache.sqlite` (one row per distinct result), so a restart, even at night, starts from the last fetch. One fetch is made just after the start (ecobot-mcp's warm-up, or the first question) when nothing is cached, even at night; a restart in the day fetches then only if the last fetch is due again. `python scripts/conditions.py --lat .. --lon ..` fetches both once and prints what the report would show: run it before switching them on. Grass pollen and the thunderstorm asthma forecast both run October to December, so the pollen source only fetches, shows (in the report or an answer) and alerts in those months; outside them it makes no requests (not even at start), the report has no Pollen & asthma block, and a pollen question is told they only run October to December. ## How it stays fast and cheap @@ -62,7 +62,7 @@ Both are off by default. They are websites, not APIs (the pollen page is parsed) - The model only reasons for predictions ("will it rain?") and "describe it" questions, or when asked to think, try, reason, predict, estimate, grind or whirl. - Simple highs/lows, chart and "air quality now" questions are fetched by the bot first, so the model is called once, at the end, just to word the answer. -- Recent readings are refreshed every minute (the weather station: written to its storage, those still settling as provisional readings the next fetch replaces) and every 4 minutes (the air sensor, in memory), by ecobot-mcp. A question never waits for a refresh in flight when the storage already holds what it needs (the newest readings for 5 minutes after they were fetched), and its own Ecowitt requests go before the background ones. +- Recent readings are refreshed every minute (the weather station: written to its storage, those still settling as provisional readings the next fetch replaces) and every 4 minutes (the air sensor, in memory), by ecobot-mcp. A question never waits for a refresh in flight when the storage already holds what it needs (the newest readings for 5 minutes after they were fetched), and its own Ecowitt requests go before the background ones. When it does wait for a fetch in flight (one fetch at a time per station and resolution, `Recent.turn` in `lib/ecowitt/fetch.py`), that fetch is hurried: its request still queued moves to the urgent line, and so do its later ones and those of a background fetch taking the resolution while the question waits. The keep-warm asks for the 5-minute and 30-minute tails before the 4-hour and daily ones, so a question on today, just after a start, waits for one request less. - A chart is drawn when it is asked for (a question, a button, an alert), and uploaded once: sending it again (to the next chat an alert goes to, toggling back to a period drawn lately, the next press of a button) uses Telegram's copy. Nothing is drawn ahead on a timer (step 6c): after a chart is sent, its other periods are fetched from ecobot-mcp in the background (and, with `BOT_TELEGRAM_PRELOAD_CHAT`, uploaded there), so its period buttons answer at once (`Bot.preload_soon`); a keyboard button's first press waits for ecobot-mcp, and the next press within a few minutes sends the chart kept. An alert's chart is kept with the bot's other charts (`lib/alerts/pictures.py`, `AlertCharts`): an alert whose chart the bot holds with the alert's newest reading sends that (Telegram's copy once it has been sent anywhere), and Refresh sends a chart kept since the message was last changed, else draws one and keeps it. - Each chart reply logs (at DEBUG) where its time went: `Chart ms: data 12, calc 6, draw 112, PNG 41 (22 KB), send 812`, or `Chart ms: drawn 40s ago, send 210 (Telegram's copy)` for one drawn lately. - The whole history of both sensors, and the last pollen page and forecast, are kept in one SQLite file, `ecobot.sqlite` (`lib/storage`, @@ -96,5 +96,5 @@ The system prompt starts with what never changes (the model provider caches the - `MCP_ECOWITT_SOURCE` picks where the readings come from (`auto` is Home Assistant if it is set, the cloud filling in if its keys are set too; `MCP_AIRGRADIENT_SOURCE` does the same for the air sensor, see above). `lib/ecowitt/hass_api.py` answers the three calls the bot makes of Ecowitt's cloud (`devices`, `realtime`, `history`) from Home Assistant, in the cloud's shapes and units, so the cache, archive, charts and alerts are the same code whichever answers. `lib/ecowitt/hass_map.py` is the table of entities (`sensor._`, found by name) and `hass_history.py` tells Home Assistant's recorded changes as the cloud's buckets (1 minute, 5, 30, 4 hours, a day), time-weighted means, the highest gust, the last rain counter, with the true lowest and highest of each bucket as `_low`/`_high`. - Both set: `lib/ecowitt/fallback.py`. Home Assistant answers; a live reading older than 10 minutes, or none, is replaced by the cloud's if newer; the buckets Home Assistant has none of (before it began recording, while it was down) are asked of the cloud in one request for the span they cover. A failure of either is logged once, with its recovery. -- Faster: the live reading is polled every 5 seconds (`Ecowitt.watch_live`), a reading newer than the last is kept for "weather now", the report and the gauges, and the rain alert looks at it at once (`WeatherMonitor.check_rain`) instead of at the next minute's refresh. The gateway itself reports about every minute, so the alert is within seconds of that. A chart of up to 8 hours is drawn a reading a minute (`1min`, Home Assistant only). The bot takes the minutes as they come (the last 9 hours at start, then at each new live reading) into the storage's `1min` rows (`lib/ecowitt/query.py` holds the constants) and drops what is older, so such a chart is drawn without asking Home Assistant; if the minutes don't reach back to its start it uses the 5-minute readings, as longer charts do. +- Faster: the live reading is polled every 30 seconds (`Ecowitt.watch_live`), a reading newer than the last is kept for "weather now", the report and the gauges, and the rain alert looks at it at once (`WeatherMonitor.check_rain`) instead of at the next minute's refresh. The gateway itself reports about every minute, so the alert is within 30 seconds of that. A chart of up to 8 hours is drawn a reading a minute (`1min`, Home Assistant only). The bot takes the minutes as they come (the last 9 hours at start, then at each new live reading) into the storage's `1min` rows (`lib/ecowitt/query.py` holds the constants) and drops what is older, so such a chart is drawn without asking Home Assistant; if the minutes don't reach back to its start it uses the 5-minute readings, as longer charts do. - Caveats: Home Assistant keeps 10 days of states unless its recorder is set otherwise, so older history comes from the cache the bot built, or from the cloud where it is set. An answer with nothing in it from Home Assistant alone is not recorded as fetched. diff --git a/docs/storage-plan.md b/docs/storage-plan.md index dd22ef73..0a27bd00 100644 --- a/docs/storage-plan.md +++ b/docs/storage-plan.md @@ -213,7 +213,7 @@ CREATE TABLE climate_day ( Every band is in the rows, so a chart's band comes with its line: - **Ecowitt's own lows and highs** (30 minutes and coarser) go in `_lo` and `_hi` when the readings are written. -- **The bot's live readings** (every few seconds from Home Assistant, once a minute from the cloud) are gathered per 5 minutes in +- **The bot's live readings** (every 30 seconds from Home Assistant, once a minute from the cloud) are gathered per 5 minutes in memory, as the AirGradient's are now (`AirGradient._average`), and each 5 minutes with two or more readings widens that 5-minute row's range when the bucket closes. This replaces `LiveRanges.add` and its `ranges` table. - **Home Assistant's ranges**, the station's and the AirGradient's, widen the same 5-minute rows. diff --git a/ecobot_mcp/__main__.py b/ecobot_mcp/__main__.py index b55bc047..0e080196 100644 --- a/ecobot_mcp/__main__.py +++ b/ecobot_mcp/__main__.py @@ -59,7 +59,8 @@ async def main(): chart_base_url=cfg.mcp_chart_base_url, chart_link_hours=cfg.mcp_chart_link_hours) hosts = tuple(dict.fromkeys(("127.0.0.1", "localhost", socket.gethostname(), *cfg.mcp_allowed_hosts))) # (its own name too: a container's hostname) app = http_app(server, tokens=tokens, allowed_hosts=hosts, issuer_url=f"http://{f'[{host}]' if ':' in host else host}:{port}", - dashboard=cfg.mcp_dashboard) + dashboard=cfg.mcp_dashboard, dashboard_animations=cfg.mcp_dashboard_animations, + dashboard_indoor=cfg.mcp_dashboard_indoor) core.log_startup() running = core.start_alerts() core.start_warmers() @@ -81,7 +82,10 @@ async def warm_up(): f"{len(tokens)} token(s) from AUTH_TOKENS" if cfg.auth_tokens else f"the token in {auth_token.path(cfg.state_path.parent)}", ", ".join(hosts)) if cfg.mcp_dashboard: - log.info("Dashboard: http://%s:%d/dashboard (read-only, no token, any Host; MCP_DASHBOARD=off turns it off)", shown, port) + log.info("Dashboard: http://%s:%d/dashboard (read-only, no token, any Host; MCP_DASHBOARD=off turns it off)%s", shown, port, + {"off": "; no weather behind its gauges, nothing animated (MCP_DASHBOARD_ANIMATIONS=off)", + "low": "; no weather behind its gauges, the zoom at once (MCP_DASHBOARD_ANIMATIONS=low)"}.get(cfg.mcp_dashboard_animations, "") + + ("" if cfg.mcp_dashboard_indoor else "; no indoor readings (MCP_DASHBOARD_INDOOR=off)")) log.info("Chart links (?charts=link): %s/.png, kept %d h in memory (no token: an id is its key)", cfg.mcp_chart_base_url or f"http://{shown}:{port}/charts (or as the MCP request reached it)", cfg.mcp_chart_link_hours) waiting = asyncio.create_task(stop.wait()) diff --git a/ecobot_mcp/core.py b/ecobot_mcp/core.py index aebbafdf..1cb9da84 100644 --- a/ecobot_mcp/core.py +++ b/ecobot_mcp/core.py @@ -2,12 +2,16 @@ bot is only ever its client (step 6b): 1. `configure(cfg)`: the settings the engines read as module values (the anti-spike rule, what "all" draws, what `about` says); - 2. `start_sources(cfg)`: every configured source that starts, the weather station first (its time zone wins); + 2. `start_sources(cfg)`: every configured source that starts, the weather station first (its time zone wins), none of them asking the + network for anything: each starts from what the data folder kept of it (the port opens without waiting on any server); 3. `Core.open(cfg, sources, stack, tasks)`: the alert log, the tools' Context and the ten tools (lib/service); 4. `core.log_startup()`: each source's startup line; 5. `core.start_alerts()`: the alert rules (lib/service/alerts.py), writing the alert log; `core.start_warmers()`: the keep-warm; - 6. `core.warm_up(running)`: the first fetch, then the weather alerts, the live poll, the archive, Home Assistant's imports, the air - sensor's history and backfill. + 6. `core.warm_up(running)`, once the port is open: the first fetch (the station's device list in the background, and on a first start + the station found by it; then its live reading first; the air sensor's reading and the rest of its start, then its line; the + forecast and the pollen page if due), then the alerts of each device once it has been read, the live poll, the archive, Home + Assistant's imports, the air sensor's history and backfill. Until then the tools and the dashboard answer from what was kept, as of + its time; the MCP resources and the dashboard's events tell the clients when the fresh readings come in. `Health` records each loop's last success and failure (ecobot://health).""" @@ -57,9 +61,11 @@ def configure(cfg: Config): async def start_sources(cfg: Config) -> tuple[list[Source], Config]: """Every configured data source that starts, and the settings in the time zone they run in. The weather station starts - first: it names its own time zone, which wins over TZ, so the air sensor and the optional website sources (pollen, - forecast, off unless switched on), and everything built after, use the station's; those three start side by side (each - waits on its own server). The forecast uses the station's location unless one is configured.""" + first: it names its own time zone (as the data folder kept it), which wins over TZ, so the air sensor and the optional website + sources (pollen, forecast, off unless switched on), and everything built after, use the station's; those three start side by side. + The forecast uses the station's location unless one is configured (on a first start, once its device list has given it). No start + asks the network for anything: each source starts from what the data folder kept (the station's device and its last live reading, + the air sensor's last reading, the last forecast and pollen page), and Core.warm_up fetches once the port is open.""" sources: list[Source] = [] took: dict[str, float] = {} @@ -68,7 +74,7 @@ async def start(kind: type[Source], *args, **kwargs) -> Source | None: source, started = None, time.monotonic() try: source = kind(*args, **kwargs) - await source.start() + await source.start(wait=False) return source except Exception as e: log.error("%s couldn't start (%s: %s) - continuing without it", kind.name, type(e).__name__, e, exc_info=isinstance(e, BUGS)) @@ -100,7 +106,7 @@ async def start(kind: type[Source], *args, **kwargs) -> Source | None: if cfg.pollen: starts.append(start(Pollen, cfg)) if cfg.forecast: - starts.append(start(Forecast, cfg, (eco.latitude, eco.longitude) if eco and None not in (eco.latitude, eco.longitude) else None)) + starts.append(start(Forecast, cfg, eco.location or (lambda: eco.location) if eco else None)) sources += [s for s in await asyncio.gather(*starts) if s is not None] # (in this order, whichever answers first) if storage is not None and not sources: storage.close() @@ -220,8 +226,17 @@ async def warm_up(self, running: list[str] | None = None): eco, air, tasks, health = self.by_name.get("Ecowitt"), self.by_name.get("AirGradient"), self.tasks, self.health async def ecowitt_part(): - # One request at a time (Ecowitt rate-limits): warm first, so the alerts' own look at the last 3 hours is answered - # from what was just fetched. A failed first refresh must not stop the alerts or the archive: safely() logs it + # One request at a time (Ecowitt rate-limits): the live reading first (the dashboard's tiles and the first "weather now" + # wait on it), then the device list in the background (the start took the station from the file; on a first start it goes + # first, as nothing is asked of the station until it has answered), then warm, so the alerts' own look at the last 3 hours + # is answered from what was just fetched. A failed first refresh must not stop the alerts or the archive: safely() logs it + if not eco.listed.is_set(): + tasks.start(eco.refresh_device()) + await eco.listed.wait() + await eco.first_live() + else: + await eco.first_live() + tasks.start(eco.refresh_device()) await safely(health.track("Ecowitt refresh", eco.warm), True) try: if self.rules is not None: @@ -230,6 +245,7 @@ async def ecowitt_part(): log.error("Weather alerts couldn't start (%s: %s)", type(e).__name__, e, exc_info=isinstance(e, BUGS)) if eco.fast is not None: tasks.start(eco.watch_live()) + await safely(eco.keep_earliest) # (Home Assistant's first state, the archive's start when no device list gave one) # The full history is copied into the cache in the background (a few minutes the first time), so questions rarely # need Ecowitt inline archive = Archive(eco, eco.archive_pace) @@ -239,6 +255,11 @@ async def ecowitt_part(): tasks.start(every(HA_IMPORT_SECONDS, health.track("Ecowitt Home Assistant import", eco.import_ranges))) async def air_part(): + await safely(air.settle) # its reading, and the rest of its start: Home Assistant's entities of it, the cloud's name for it + for line in air.startup_lines(): + log.info("%s", line) + if self.rules is not None: # (once it has been read) + self.rules.start_air(tasks, running) await safely(health.track("AirGradient refresh", air.warm), True) tasks.start(air_history()) # even if the sensor was unreachable just now @@ -258,8 +279,17 @@ async def air_backfill(): fetched, failed, total = await air.backfill() log.info("Backfill AirGradient: %d days fetched, %d failed, %d days held, %.0fs", fetched, failed, total, time.monotonic() - started) + async def website_part(source: Source): + """The forecast or the pollen page fetched if its last fetch (what it started from) is due again; its line again if that + changed it.""" + await safely(source.warmer.refresh, False) # (recorded as its timed refreshes are) + if (line := source.describe()) != source.summary: + source.summary = line + log.info("%s", line) + + websites = [s for s in (self.by_name.get("Forecast"), self.by_name.get("Pollen")) if s is not None] try: - await asyncio.gather(*([ecowitt_part()] if eco else []), *([air_part()] if air else [])) + await asyncio.gather(*([ecowitt_part()] if eco else []), *([air_part()] if air else []), *map(website_part, websites)) except Exception as e: log.error("Startup fetch failed (%s: %s); the regular refreshes will catch up", type(e).__name__, e, exc_info=isinstance(e, BUGS)) diff --git a/lib/airgradient/dashboard.py b/lib/airgradient/dashboard.py index 1a251d96..3ec9f71d 100644 --- a/lib/airgradient/dashboard.py +++ b/lib/airgradient/dashboard.py @@ -5,7 +5,7 @@ them), the needle placed in proportion within its band: so the bands that matter are as easy to read as the rest, and a scale that runs to 500 (or 600 µg/m³) doesn't squeeze "good" and "moderate" into a sliver. The numbers round the dial are the categories' breakpoints. - - US AQI (the higher of PM2.5's and PM10's now, as AirNow gives it, by the service's own lib/airgradient/metrics.py us_aqi, its band + - AQI, titled so on the dashboard but the US AQI (the higher of PM2.5's and PM10's now, as AirNow gives it, by the service's own lib/airgradient/metrics.py us_aqi, its band saying "(PM10)" when PM10 sets it; not the AirGradient's `aqi_us`, of PM2.5 alone and of the lower of the last two readings, so a dial of it could disagree with the PM2.5 and PM10 dials beside it): 0-500, the EPA's six categories and colours; - PM2.5 (µg/m³): the EPA's 2024 breakpoints, 0-9.0, 9.1-35.4, 35.5-55.4, 55.5-125.4, 125.5-225.4, 225.5+ (to 325.4, AQI 500); @@ -21,6 +21,9 @@ high, 300-500 very high (the EPA's first four colours). The edges at 150 and 250 (VOC) and 20 and 150 (NOx) are the service's own ratings (lib/series.py AIR). +Each table has a Max and a Min column, but the US AQI's and the particles' (PM2.5, PM10, PM1): their Max alone (`lowest`), as the +UV index's: how clean the air got says little beside how bad it got. + Left out: PM1 (no US standard for it), and the sensor's own temperature and humidity (it is outdoors: the station's outdoor gauges show the same air). """ @@ -46,6 +49,8 @@ class AirGauge: step: float # the breakpoints' resolution: a reading below an edge + step is still in the band below decimals: int = 0 aqi: bool = False # shows the US AQI (the higher of PM2.5's and PM10's now: metrics.us_aqi), not the reading itself + lowest: bool = True # its table has a Min column beside its Max (not the particles' and the AQI's: their lowest says + # nothing worth a column, as the UV index's doesn't) @property def reading(self) -> str: @@ -67,10 +72,10 @@ def band(self, value: float | None) -> str | None: AIR_GAUGES = ( - AirGauge("US AQI", "", "pm2_5", (0, *(a_hi for *_, a_hi, _ in PM25_AQI)), EPA, EPA_NAMES, 1, aqi=True), - AirGauge("PM2.5", "µg/m³", "pm2_5", (0, *(hi for _, hi, *_ in PM25_AQI)), EPA, EPA_NAMES, 0.1, 1), - AirGauge("PM10", "µg/m³", "pm10", (0, 54, 154, 254, 354, 424, 604), EPA, EPA_NAMES, 1), - AirGauge("PM1", "µg/m³", "pm1", (0, *(hi for _, hi, *_ in PM25_AQI)), EPA, EPA_NAMES, 0.1, 1), # (on PM2.5's bands: no standard of its own) + AirGauge("AQI", "", "pm2_5", (0, *(a_hi for *_, a_hi, _ in PM25_AQI)), EPA, EPA_NAMES, 1, aqi=True, lowest=False), + AirGauge("PM2.5", "µg/m³", "pm2_5", (0, *(hi for _, hi, *_ in PM25_AQI)), EPA, EPA_NAMES, 0.1, 1, lowest=False), + AirGauge("PM10", "µg/m³", "pm10", (0, 54, 154, 254, 354, 424, 604), EPA, EPA_NAMES, 1, lowest=False), + AirGauge("PM1", "µg/m³", "pm1", (0, *(hi for _, hi, *_ in PM25_AQI)), EPA, EPA_NAMES, 0.1, 1, lowest=False), # (on PM2.5's bands: no standard of its own) AirGauge("CO₂", "ppm", "co2", (400, 800, 1000, 1500, 2000, 2500), EPA[:5], ("Good", "Fair", "Poor", "Bad", "Very bad"), 0), AirGauge("VOC index", "", "voc_index", (1, 100, 150, 250, 400, 500), VOC_COLOURS, ("Low", "Average", "Elevated", "High", "Very high"), 0), diff --git a/lib/airgradient/local.py b/lib/airgradient/local.py index 72870cad..a31ab3f6 100644 --- a/lib/airgradient/local.py +++ b/lib/airgradient/local.py @@ -18,6 +18,7 @@ import httpx from ..netenv import local_name_hint +from ..tls import ssl_context log = logging.getLogger(__name__) @@ -79,7 +80,7 @@ def __init__(self, url: str, transport=None, resolve=address_of, clock=time.time self.base = url if "//" in url else f"http://{url}" parts = urlsplit(self.base) self.host, self.port = parts.hostname or "", parts.port - self.client = httpx.AsyncClient(timeout=TIMEOUT, transport=transport) + self.client = httpx.AsyncClient(timeout=TIMEOUT, transport=transport, verify=ssl_context()) self.resolve, self.clock, self.cloud = resolve, clock, cloud self.address: tuple[str, float] | None = None # (IP, when looked up) self.retry_at = 0.0 diff --git a/lib/airgradient/source.py b/lib/airgradient/source.py index 16470fa8..b47c167a 100644 --- a/lib/airgradient/source.py +++ b/lib/airgradient/source.py @@ -20,6 +20,7 @@ """ import asyncio +import json import statistics import logging import time @@ -40,6 +41,7 @@ from ..specs import Chart, Line from ..storage import Storage from ..storage.catalogue import BOT, CLOUD, HOME_ASSISTANT +from ..tls import ssl_context from ..timeutil import day_bounds, day_text, local_date, local_epoch, parse_local, to_local, when from ..tools import Turn from ..warm import Warmer @@ -57,6 +59,9 @@ MAX_REQUEST_DAYS = 9 # the API allows 10 days per request; a day of margin for clock changes MAX_INLINE_DAYS = 30 # missing days fetched while answering; more are left to the backfill FRESH_SECONDS = 300 # the current reading and today's history are reused this long +JUST_FETCHED_SECONDS = 30 # a refresh (warm) leaves a current reading this new as it is: settle() has just fetched it +KEEP_SECONDS = 60 # the current reading is kept in the file at most this often (a restart starts from it) +KEPT_KEY = "air_current:{loc}" # ... under this name (the file's meta): {"at", "row"} HA_RECENT_SECONDS = 3 * 3600 # Home Assistant's ranges are read back for the last few hours each time (RANGE_KEEP_DAYS the first time) SAMPLE_SECONDS = 60 # with the monitor's own server, or Home Assistant's states of it: how often it is read (the keep-warm interval) MIN_SAMPLES = 3 # a 5-minute average of fewer readings than this is not kept (the cloud fills that gap) @@ -98,7 +103,7 @@ def __init__(self, cfg: Config, transport=None, ha: HomeAssistant | None = None, self.token = cfg.airgradient_token self.cloud = cfg.airgradient_cloud # without an account (or with MCP_AIRGRADIENT_SOURCE saying not) the cloud is never asked self.link = ("live chart", cfg.airgradient_dashboard) if cfg.airgradient_dashboard else None - self.client = httpx.AsyncClient(timeout=15, transport=transport) + self.client = httpx.AsyncClient(timeout=15, transport=transport, verify=ssl_context()) self.local = LocalSensor(cfg.airgradient_local_url, cloud=self.cloud) if cfg.airgradient_local else None # the monitor's own server owned = (storage is None) if owned is None else owned storage = storage or Storage(cfg.storage_path, cfg.tz) @@ -121,16 +126,49 @@ def __init__(self, cfg: Config, transport=None, ha: HomeAssistant | None = None, self._ha_said: set[str] = set() # what was said once about it: no sensor, a metric that is another variant self._verdict: dict[int, dict[str, tuple[int, int]]] = {HOME_ASSISTANT: {}, CLOUD: {}} # per source, per metric: (five minutes compared, agreed) self._correction: str | None = None # how the monitor corrects its PM2.5, from its own configuration - - async def start(self): + self._settled = False # settle() has run: the rest of the start, its line + self._fresh = False # this run has read the sensor (until then a question is answered from the kept reading) + self._kept_at = 0.0 # when the current reading was last kept in the file + + async def start(self, wait: bool = True): + """The reading the file kept (the last before the restart), which questions and the dashboard are answered from, as of its time, + until this run's first comes in; then (wait) settle(): reading the sensor and the rest. ecobot-mcp's start doesn't wait (nothing + asked of the network: the port opens at once), and settles in the warm-up.""" + try: + kept = await self.store.storage.read(lambda r: r.meta(KEPT_KEY.format(loc=self.loc))) + kept = json.loads(kept) if kept else None + if isinstance(kept, dict) and isinstance(kept.get("row"), dict) and isinstance(kept.get("at"), (int, float)): + self._current = (kept["row"], float(kept["at"])) + except Exception as e: # (then it starts with none, as at a first start) + log.warning("AirGradient: the reading kept in the history file couldn't be read (%s: %s)", type(e).__name__, e) + if wait: + await self.settle() + + async def _keep(self, now: bool = False): + """The current reading kept in the file for the next start, at most every KEEP_SECONDS (unless `now`).""" + row, at = self._current + if at - self._kept_at < KEEP_SECONDS and not now: + return + self._kept_at, text = at, json.dumps({"at": at, "row": row}) + try: + await self.store.storage.write(lambda w: w.set_meta(KEPT_KEY.format(loc=self.loc), text)) + except Exception as e: # (only the next start's) + log.warning("AirGradient: couldn't keep the reading in the history file (%s: %s)", type(e).__name__, e) + + async def settle(self): + """Its start, in the warm-up (after the port opens): its reading now, Home Assistant's entities of the monitor (so its line says + whether Home Assistant has it), the cloud asked once (it names the sensor, and its token and location are checked) or, with + nothing to check its readings against, the monitor's own correction; today's gaps asked of the cloud (its check against what the + bot holds); then its line (startup_lines).""" try: row = await self._current_row(refresh=True) if self.ha is not None: - await self._ha_entities() # (found now, so the line below says whether Home Assistant has the monitor) - if self.cloud and (self.local or self._ha_ids): # the cloud is still asked once: it names the sensor, and its token and location are checked + await self._ha_entities() + if self.cloud and (self.local or self._ha_ids): self._names = {k: v for k, v in (await self._get("current")).items() if k in ("locationName", "locationType")} row = {**row, **self._names} self._current = (row, self._current[1]) + await self._keep(now=True) # (with the sensor's name) elif self.local and not self.cloud and not self._ha_ids: # nothing to check its readings against: say how it corrects them self._correction = self._correction_of(await self.local.config()) if self.cloud and self._sampled: # today's gaps asked of the cloud now (warm would in a moment): its check against what the bot holds, for the line @@ -138,6 +176,12 @@ async def start(self): self.summary = f"AirGradient: {self._summary(row)}" except Exception as e: # keep going: the sensor may just be briefly unreachable log.warning("AirGradient %s not readable yet: %s", f"location {self.loc}" if self.cloud else "sensor", e) + finally: + self._settled = True + + def startup_lines(self) -> list[str]: + """Its line once settle() has run (Core.warm_up logs it then).""" + return super().startup_lines() if self._settled else [] @staticmethod def _correction_of(config: dict | None) -> str | None: @@ -298,7 +342,8 @@ def _lock(self, key) -> asyncio.Lock: async def _current_row(self, refresh: bool = False) -> dict: async with self._lock("current"): if refresh or not self._current or time.time() - self._current[1] > FRESH_SECONDS: - self._current = (await self._fetch_current(), time.time()) + self._current, self._fresh = (await self._fetch_current(), time.time()), True + await self._keep() return self._current[0] async def _fetch_current(self) -> dict: @@ -402,7 +447,8 @@ async def _record(self) -> bool: if row is None: return False now = time.time() - self._current = (row, now) + self._current, self._fresh = (row, now), True + await self._keep() bucket = int(now) // BUCKET * BUCKET if self._bucket and (self._bucket[0] != bucket or self._bucket_src != src): await self._flush_bucket() @@ -495,7 +541,8 @@ async def warm(self, fresh: bool = True) -> str: """Current reading, today, and the last week of finished days.""" before, today = self.requests, self.now().date() if not ((self.local or self._ha_ids) and await self._record()): # (the monitor, or Home Assistant's states of it: the reading is also kept) - await self._current_row(fresh) + just = self._current is not None and time.time() - self._current[1] < JUST_FETCHED_SECONDS + await self._current_row(fresh and not just) await self._day_rows(today, fresh) week = [today - timedelta(days=n) for n in range(1, WARM_DAYS + 1)] await self._fetch_days((await self._held(week))[1]) # one request for all of them @@ -561,11 +608,13 @@ async def _previous_rows(self, ts: int, count: int, held: bool = False) -> list[ after = r["ts"] return got - async def latest(self, extras: list[str] = (), held: bool = False) -> Latest: + async def latest(self, extras: list[str] = (), held: bool = False, kept: bool = False) -> Latest: """The latest reading. A rating (and PM2.5's and PM10's AQI band) is the level the last two readings both reached, so a passing spike is not called poor until the next reading agrees; the value shown is always the latest one. The readings before it come from today's history: when that can't be read, the latest is rated alone. held: nothing fetched, the reading it keeps - whatever its age and the readings before it it already has (LookupError when it keeps none).""" + whatever its age and the readings before it it already has (LookupError when it keeps none). kept (a question's): until this run + has read the sensor (just after a start), the reading kept from before it, as with held (the warm-up is reading it).""" + held = held or kept and not self._fresh and self._current is not None if held: if not self._current: raise LookupError("no reading held") diff --git a/lib/alerts/weather.py b/lib/alerts/weather.py index bf92d636..1c3e9ba2 100644 --- a/lib/alerts/weather.py +++ b/lib/alerts/weather.py @@ -108,8 +108,8 @@ async def check(self): self.state.save() async def check_rain(self): - """Look at the rain alone, on a live reading that has just come in (the station is polled every few seconds, so this is the alert - within a few seconds of the gauge, not at the next minute's check).""" + """Look at the rain alone, on a live reading that has just come in (the station is polled every 30 seconds, so this is the alert + within 30 seconds of the gauge's report, not at the next minute's check).""" rows = await self.station.recent(3) live = await self.station.live_rain() if rows else None if rows and live and live[0] > rows[-1][0]: diff --git a/lib/config.py b/lib/config.py index 133e90a0..4f360e2e 100644 --- a/lib/config.py +++ b/lib/config.py @@ -55,6 +55,21 @@ def _flag(value: str, default: bool, name: str) -> bool: return default +ANIMATIONS = ("on", "off", "low") # MCP_DASHBOARD_ANIMATIONS's values + + +def _animations(value: str, default: str, name: str) -> str: + """The dashboard's motion: "on", "off" (an on/off word read as _flag reads it) or "low" (nothing moving: e-ink); unset or empty is + the default. Any other value keeps the default too, with a warning, so a typo changes nothing.""" + if value.lower() == "low": + return "low" + if value.lower() in ON or value.lower() in OFF: + return "on" if value.lower() in ON else "off" + if value: + log.warning("%s: %r is not on, off or low; keeping the default (%s)", name, value, default) + return default + + def _required(value: str, default: str, name: str) -> str: """A setting the bot can't run without; it stops with a message naming it when it is unset or blank.""" if value: @@ -320,6 +335,8 @@ class Config: mcp_bind: tuple[str, int] = _setting("MCP_BIND", ("127.0.0.1", 8765), _bind, old="MCP_SERVICE_BIND") # host:port ecobot-mcp listens on mcp_allowed_hosts: tuple[str, ...] = _setting("MCP_ALLOWED_HOSTS", ("127.0.0.1", "localhost"), _names, old="MCP_SERVICE_ALLOWED_HOSTS") # the Host names it answers (any port, unless one is given) mcp_dashboard: bool = _setting("MCP_DASHBOARD", True, _flag) # the gauges' live web page at /dashboard beside /mcp: read-only, no token, any Host (off: 404) + mcp_dashboard_animations: str = _setting("MCP_DASHBOARD_ANIMATIONS", "on", _animations) # on: everything animated, the weather drawn behind the gauges; low: no weather, the zoom at once (the gauges and tiles moving); off: no weather, nothing animated + mcp_dashboard_indoor: bool = _setting("MCP_DASHBOARD_INDOOR", True, _flag) # off: the page leaves out the indoor tiles, drawn nor sent (privacy); the bot, tools, Status picture and alerts unchanged mcp_chart_base_url: str = _setting("MCP_CHART_BASE_URL", "", _url) # where people's browsers reach the chart links' pictures (/charts beside /mcp, e.g. through a proxy: https://example.org/ecobot-charts); unset: the MCP request's own address with /charts mcp_chart_link_hours: int = _setting("MCP_CHART_LINK_HOURS", 24, _between(1, 720)) # how long a chart link's picture is kept (in memory: a restart forgets them) # The bot's (ecobot.py) diff --git a/lib/ecowitt/api.py b/lib/ecowitt/api.py index 76a65062..03f3dfb3 100644 --- a/lib/ecowitt/api.py +++ b/lib/ecowitt/api.py @@ -21,6 +21,8 @@ import httpx +from ..tls import ssl_context + log = logging.getLogger(__name__) BASE = "https://api.ecowitt.net/api/v3/device" @@ -122,6 +124,15 @@ def __init__(self, message: str, transient: bool = False): self.transient = transient +class NotInYet(EcowittError): + """The station isn't known yet: ecobot-mcp started with nothing kept of it (a first start) and its device list hasn't answered yet + (Ecowitt.refresh_device keeps asking). Nothing is asked of its readings until it has.""" + + def __init__(self): + super().__init__("the weather station's readings aren't in yet: ecobot-mcp has just started and is still finding the station " + "(it keeps trying)", transient=True) + + def _body(res: httpx.Response) -> dict | None: """The JSON object Ecowitt answered with ({"code": ..., "msg": ...}), or None if the reply isn't one.""" try: @@ -131,28 +142,64 @@ def _body(res: httpx.Response) -> dict | None: return body if isinstance(body, dict) and "code" in body else None +class Urgency: + """Whether someone is waiting for a job's requests, which can change while they wait: a background fetch a question comes to wait + for is hurried, and its request queued for the turn moves to the urgent line (as do its later ones). Passed as `urgent`; true + when urgent.""" + + def __init__(self, urgent: bool = False): + self.urgent = bool(urgent) + self._queued: tuple["_TurnLock", asyncio.Future] | None = None # its request waiting for the turn, if one is + + def __bool__(self) -> bool: + return self.urgent + + def __repr__(self) -> str: + return f"Urgency({self.urgent})" + + def hurry(self): + if not self.urgent: + self.urgent = True + if self._queued is not None: + self._queued[0].promote(self._queued[1]) + + class _TurnLock: """One request at a time, with an urgent line: a person waiting for a reading goes before the background refreshes - queued behind the request in flight (a keep-warm round can queue several requests, two seconds apart).""" + queued behind the request in flight (a keep-warm round can queue several requests, two seconds apart). A request + sent with an Urgency moves to the urgent line when it is hurried while it waits.""" def __init__(self): self._locked = False self._queues = {True: deque(), False: deque()} - async def acquire(self, urgent: bool = False): + async def acquire(self, urgent: "bool | Urgency" = False): if not self._locked and not self._queues[True] and not self._queues[False]: self._locked = True return waiter = asyncio.get_running_loop().create_future() - self._queues[urgent].append(waiter) + self._queues[bool(urgent)].append(waiter) + if isinstance(urgent, Urgency): + urgent._queued = (self, waiter) try: await waiter except asyncio.CancelledError: if waiter.done() and not waiter.cancelled(): # the turn was already handed to us: pass it on self.release() - elif waiter in self._queues[urgent]: # (a release since the cancel has already dropped it) - self._queues[urgent].remove(waiter) + else: # (a release since the cancel has already dropped it) + for queue in self._queues.values(): + if waiter in queue: + queue.remove(waiter) raise + finally: + if isinstance(urgent, Urgency) and urgent._queued and urgent._queued[1] is waiter: + urgent._queued = None + + def promote(self, waiter: asyncio.Future): + """A background waiter someone has come to wait for: to the back of the urgent line.""" + if waiter in self._queues[False]: + self._queues[False].remove(waiter) + self._queues[True].append(waiter) def release(self): for urgent in (True, False): @@ -167,7 +214,7 @@ def release(self): class EcowittAPI: def __init__(self, api_key: str, app_key: str, transport: httpx.AsyncBaseTransport | None = None): self.keys = {"application_key": app_key, "api_key": api_key} - self.client = httpx.AsyncClient(timeout=30, transport=transport) + self.client = httpx.AsyncClient(timeout=30, transport=transport, verify=ssl_context()) self._turn = _TurnLock() # one request at a time, spaced out; a person's request goes first self._last = 0.0 self.requests = 0 # sent so far, including retries @@ -175,11 +222,11 @@ def __init__(self, api_key: str, app_key: str, transport: httpx.AsyncBaseTranspo async def close(self): await self.client.aclose() - async def _get(self, path: str, urgent: bool = False, **params) -> dict | list: + async def _get(self, path: str, urgent: "bool | Urgency" = False, **params) -> dict | list: """The response's "data"; raises EcowittError. Asked again, up to BUSY_RETRIES times and waiting longer each time, when Ecowitt is busy, rate limited or erring (429, 5xx), not when it refuses the request or there is no answer at all. urgent: someone is waiting for it, so it goes before queued background requests (and the turn is free while a request - waits to be asked again).""" + waits to be asked again); an Urgency moves it there if it is hurried while it waits.""" loop = asyncio.get_running_loop() for attempt in range(BUSY_RETRIES + 1): await self._turn.acquire(urgent) diff --git a/lib/ecowitt/dashboard.py b/lib/ecowitt/dashboard.py index 6f256d04..a5526c70 100644 --- a/lib/ecowitt/dashboard.py +++ b/lib/ecowitt/dashboard.py @@ -20,6 +20,7 @@ SUN = ("#FBE79A", "#F5D45A", "#F2A53C", "#D27A2A", "#A9501F") UV = ("#A9E34B", "#F7E04A", "#F4A93B", "#E8562A", "#9A1F5A", "#7A2CF0") DEGREES = (40, 30, 20, 10, 0) # a thermometer's scale as it starts (THERMOMETER), before it widens to take in the reading +GUST = ("wind", "wind_gust") # the live gust: the Wind gauge's Gust column's, and its red hand's (today's highest gust) THERMOMETER = (0, 40, 10) # a thermometer's scale: its ends and its step, in °C; widened a step at a time to the reading @@ -33,6 +34,8 @@ def degree_colour(lower: float) -> str: @dataclass(frozen=True) class Gauge: + """A gauge: a thermometer, a dial, a rain beaker or a compass (the wind's direction: where it comes from, in degrees clockwise from + north, its needle pointing there; no figures beside it, as highs and lows of a direction mean nothing: lib/ecowitt/direction.py).""" title: str unit: str kind: str @@ -41,12 +44,14 @@ class Gauge: colours: tuple[str, ...] ticks: tuple[float, ...] live: tuple[str, str] # the live reading: (group, field) - highest: str # the day figure (days.FIELDS) whose highest is its Max + highest: str | None # the day figure (days.FIELDS) whose highest is its Max (none: no table at all, the compass) lowest: str | None = None # ... whose lowest is its Min (none: no Min column) decimals: int = 1 total: bool = False # rain: the Total column, the sum of the days' figures (its Max is the wettest day's) - counted: tuple[str, str] | None = None # the live reading counted into its Max and Min, when not `live` (wind: the gust, as its - # Max is the highest gust: the speed now would stand in for it before a day row has one) + gust: str | None = None # wind: the day figure whose highest is its Gust column (where Min usually is), the live gust + # (GUST) counted in, as the speed now is into its Max + high_hand: tuple[str, str] | None = None # the live reading whose highest today the web page's thin red hand shows (its table's + # Daily Max; wind: the gust, its Daily Gust; rain rate, solar radiation and UV: their own) @property def reading(self) -> str: @@ -60,15 +65,19 @@ def reading(self) -> str: Gauge("Temperature", "°C", "thermometer", 0, 40, COLD_TO_HOT, DEGREES, ("outdoor", "temperature"), "temp_max", "temp_min"), Gauge("Humidity", "%", "dial", 0, 100, WATER, (0, 20, 40, 60, 80, 100), ("outdoor", "humidity"), "humidity_max", "humidity_min", 0), Gauge("Atmospheric pressure", "hPa", "dial", 950, 1050, PRESSURE, (950, 970, 990, 1010, 1030, 1050), ("pressure", "relative"), - "pressure_max", "pressure_min"), + "pressure_max", "pressure_min", 0), # (whole hPa on the dashboard: "1026"; the bot's and the tools' figures keep the catalogue's) Gauge("Dew point", "°C", "thermometer", 0, 40, COLD_TO_HOT, DEGREES, ("outdoor", "dew_point"), "dew_point_max", "dew_point_min"), Gauge("Feels like", "°C", "thermometer", 0, 40, COLD_TO_HOT, DEGREES, ("outdoor", "feels_like"), "feels_like_max", "feels_like_min"), - Gauge("Wind", "km/h", "dial", 0, 100, WIND, (0, 20, 40, 60, 80, 100), ("wind", "wind_speed"), "wind_gust", None, 0, - counted=("wind", "wind_gust")), + Gauge("Wind", "km/h", "dial", 0, 100, WIND, (0, 20, 40, 60, 80, 100), ("wind", "wind_speed"), "wind_speed_max", None, 0, + gust="wind_gust", high_hand=GUST), + Gauge("Wind direction", "°", "compass", 0, 360, WIND, (0, 90, 180, 270), ("wind", "wind_direction"), None, None, 0), Gauge("Rain", "mm", "beaker", 0, 100, WATER, (100, 80, 60, 40, 20, 0), ("rainfall", "daily"), "rain", None, 1, True), - Gauge("Rain rate", "mm/h", "dial", 0, 50, WATER, (0, 10, 20, 30, 40, 50), ("rainfall", "rain_rate"), "rain_rate_max"), - Gauge("Solar radiation", "W/m²", "dial", 0, 1500, SUN, (0, 300, 600, 900, 1200, 1500), ("solar_and_uvi", "solar"), "solar_max", None, 0), - Gauge("UV index", "", "dial", 0, 12, UV, (0, 3, 6, 8, 11), ("solar_and_uvi", "uvi"), "uv_max"), + Gauge("Rain rate", "mm/h", "dial", 0, 50, WATER, (0, 10, 20, 30, 40, 50), ("rainfall", "rain_rate"), "rain_rate_max", + high_hand=("rainfall", "rain_rate")), + Gauge("Solar radiation", "W/m²", "dial", 0, 1500, SUN, (0, 300, 600, 900, 1200, 1500), ("solar_and_uvi", "solar"), "solar_max", None, 0, + high_hand=("solar_and_uvi", "solar")), + Gauge("UV index", "", "dial", 0, 12, UV, (0, 3, 6, 8, 11), ("solar_and_uvi", "uvi"), "uv_max", + high_hand=("solar_and_uvi", "uvi")), Gauge("Indoor temperature", "°C", "thermometer", 0, 40, COLD_TO_HOT, DEGREES, ("indoor", "temperature"), "indoor_temp_max", "indoor_temp_min"), Gauge("Indoor humidity", "%", "dial", 0, 100, WATER, (0, 20, 40, 60, 80, 100), ("indoor", "humidity"), "indoor_humidity_max", "indoor_humidity_min", 0), @@ -110,8 +119,9 @@ def live_value(live: dict, where: tuple[str, str]) -> float | None: return None -def figures(gauge: Gauge, values: dict, days: list[date], now: float | None) -> tuple[float | None, ...]: - """A row of a gauge's table: Max, then Min or Total, over these days (the live reading counted in for today's highs and lows).""" +def figures(gauge: Gauge, values: dict, days: list[date], now: float | None, gust: float | None = None) -> tuple[float | None, ...]: + """A row of a gauge's table: Max, then Min, Gust or Total, over these days (the live reading counted in for today's highs and lows, + the live gust for the wind's Gust).""" highs = [values[gauge.highest][d] for d in days if d in values.get(gauge.highest, {})] if gauge.total: return (max(highs) if len(days) > 1 and highs else None, round(sum(highs), 1) if highs else None) @@ -120,4 +130,7 @@ def figures(gauge: Gauge, values: dict, days: list[date], now: float | None) -> if gauge.lowest: lows = [values[gauge.lowest][d] for d in days if d in values.get(gauge.lowest, {})] + ([now] if now is not None else []) row.append(min(lows) if lows else None) + if gauge.gust: + gusts = [values[gauge.gust][d] for d in days if d in values.get(gauge.gust, {})] + ([gust] if gust is not None else []) + row.append(max(gusts) if gusts else None) return tuple(row) diff --git a/lib/ecowitt/fallback.py b/lib/ecowitt/fallback.py index c0b9e5ef..2105285e 100644 --- a/lib/ecowitt/fallback.py +++ b/lib/ecowitt/fallback.py @@ -5,10 +5,12 @@ - history: Home Assistant's buckets; those it has none of (before it began recording, while it or its Ecowitt integration was down) are asked of the cloud in one request for the span they cover, and the cloud's readings fill the gaps (Home Assistant's are kept where both have one). The cloud is never asked for a cycle only Home Assistant has (the minute's), or for a bucket that has not begun; - - devices: the cloud's, which knows the station's own address (the cache is keyed by it) and when it was made, else Home Assistant's. + - devices: the cloud's, which knows the station's own address (the cache is keyed by it) and when it was made, else Home Assistant's + (both asked at once). A failure of either is logged once for as long as it lasts. If both fail the error is raised, as for any one of them. """ +import asyncio import logging import time from datetime import datetime @@ -83,19 +85,18 @@ def _fine(self, which: str): self.trouble[which].ok() async def devices(self) -> list[dict]: - cloud, ours, failure = [], [], None - try: - cloud = await self.second.devices() - self._fine("second") - except EcowittError as e: - self._failed("second", "the device list", e) - failure = e - try: # (asked either way: it finds the station's entities and when its first reading was) - ours = await self.first.devices() - self._fine("first") - except EcowittError as e: - self._failed("first", "the device list", e) - failure = failure or e + async def ask(which: str, api) -> list[dict] | EcowittError: + try: + found = await api.devices() + except EcowittError as e: + self._failed(which, "the device list", e) + return e + self._fine(which) + return found + # (Home Assistant's asked either way, beside the cloud's: it finds the station's entities) + cloud, ours = await asyncio.gather(ask("second", self.second), ask("first", self.first)) + failure = next((r for r in (cloud, ours) if isinstance(r, EcowittError)), None) + cloud, ours = [r if isinstance(r, list) else [] for r in (cloud, ours)] if not (cloud or ours): raise failure or EcowittError("no Ecowitt device", transient=False) return cloud or ours diff --git a/lib/ecowitt/fetch.py b/lib/ecowitt/fetch.py index 1906b257..e97ac4e9 100644 --- a/lib/ecowitt/fetch.py +++ b/lib/ecowitt/fetch.py @@ -2,6 +2,7 @@ writes there), within Ecowitt's per-request limits.""" import asyncio +import contextlib import functools import logging import time @@ -10,7 +11,7 @@ from ..storage import Storage from ..storage.coverage import merge as merge_intervals from ..timeutil import local_epoch, naive_local -from .api import CYCLES, EcowittError +from .api import CYCLES, EcowittError, NotInYet, Urgency from .reads import rows_on log = logging.getLogger(__name__) @@ -33,15 +34,44 @@ class Recent: """The newest fetch of each station, cycle and group: the time it covered and when it was made. What it brought is in the storage (what is newer than the cycle's settle horizon as provisional readings, which the next fetch replaces), so for FRESH_SECONDS a question reads it there instead of asking Ecowitt again (the keep-warm refreshes it). And one fetch at a time per station and cycle, so a question - waits for one in flight instead of asking for the same thing.""" + waits for one in flight instead of asking for the same thing: a background fetch a question waits for is hurried (its requests go + in the urgent line), as is any that holds the cycle while a question waits.""" def __init__(self): self._fetched: dict[tuple[str, str, str], tuple[int, int, float]] = {} self._locks: dict[tuple[str, str], asyncio.Lock] = {} + self._holders: dict[tuple[str, str], Urgency] = {} # the urgency of the fetch holding each station and cycle + self._waiting: dict[tuple[str, str], int] = {} # questions waiting for it def lock(self, mac: str, cycle: str) -> asyncio.Lock: return self._locks.setdefault((mac, cycle), asyncio.Lock()) + @contextlib.asynccontextmanager + async def turn(self, mac: str, cycle: str, urgent: bool): + """Hold the fetch of this station and cycle; yields the Urgency to send its requests with. A question (urgent) that has to + wait hurries the fetch holding it, and any background one that takes it while the question still waits.""" + key, lock = (mac, cycle), self.lock(mac, cycle) + if urgent and lock.locked(): + self._waiting[key] = self._waiting.get(key, 0) + 1 + if (held := self._holders.get(key)) is not None: + held.hurry() + try: + await lock.acquire() + finally: + if not (left := self._waiting[key] - 1): + del self._waiting[key] + else: + self._waiting[key] = left + else: + await lock.acquire() + self._holders[key] = urgency = Urgency(urgent or bool(self._waiting.get(key))) + try: + yield urgency + finally: + if self._holders.get(key) is urgency: + del self._holders[key] + lock.release() + def covers(self, mac: str, cycle: str, group: str, start: int, end: int) -> bool: """Did a fresh enough fetch cover the whole of [start, end]? One that reached the present covers anything up to now (what is newer is at most FRESH_SECONDS late, by design).""" @@ -105,12 +135,14 @@ async def get(self, cycle: str, start: datetime, end: datetime, refresh: bool = s, e = self.epoch(start), self.epoch(end) if not refresh and (held := await self._read(cycle, s, e, load, fetch=False)) is not None: return held - async with self.recent.lock(self.mac, cycle): - return await self._read(cycle, s, e, load, fetch=True, refresh=refresh) + async with self.recent.turn(self.mac, cycle, self.urgent) as urgency: + return await self._read(cycle, s, e, load, fetch=True, refresh=refresh, urgency=urgency) - async def _read(self, cycle: str, s: int, e: int, load: bool, fetch: bool, refresh: bool = False) -> list | None: + async def _read(self, cycle: str, s: int, e: int, load: bool, fetch: bool, refresh: bool = False, + urgency: Urgency | None = None) -> list | None: """[s, e] (epoch seconds) from the storage, and (fetch) what it does not hold, nor a fresh fetch brought, from Ecowitt (written to - the storage first). None, with nothing counted, when fetch is False and some of it is neither held nor fresh.""" + the storage first). None, with nothing counted, when fetch is False and some of it is neither held nor fresh. urgency: what + its requests are sent with (else the fetcher's own).""" (missing,) = self.uncovered(cycle, [(s, e)]) gaps = merge_intervals([iv for ivs in missing.values() for iv in ivs]) from_memory = 0 @@ -122,7 +154,7 @@ async def _read(self, cycle: str, s: int, e: int, load: bool, fetch: bool, refre if not fetch: return None for a, b in spans(cycle, self.local(gap_start), self.local(gap_end)): # one request each, within Ecowitt's limit - data = await self._fetch(cycle, a, b, need) + data = await self._fetch(cycle, a, b, need, urgency) if data is None or not data and not getattr(self.api, "empty_is_final", True): continue # failed, or told nothing by an API that only has what it recorded: not recorded as fetched, so it's tried again piece = (self.epoch(a), self.epoch(b)) @@ -135,13 +167,15 @@ async def _read(self, cycle: str, s: int, e: int, load: bool, fetch: bool, refre return [] return await self.storage.read(rows_on, self.mac, self.groups, cycle, s, e) - async def _fetch(self, cycle: str, start: datetime, end: datetime, groups: list[str]) -> dict | None: + async def _fetch(self, cycle: str, start: datetime, end: datetime, groups: list[str], urgency: Urgency | None = None) -> dict | None: """One Ecowitt request: its data ({} if none), or None if it failed.""" if self.rejected >= REJECTIONS_STOP: # Ecowitt keeps saying no (a bad parameter): stop asking for the rest of this job return None self.calls += 1 try: - return await self.api.history(self.mac, cycle, start, end, ",".join(groups), urgent=self.urgent) + if not self.mac: # (the station not found yet: a first start, its device list still to answer) + raise NotInYet() + return await self.api.history(self.mac, cycle, start, end, ",".join(groups), urgent=self.urgent if urgency is None else urgency) except EcowittError as e: label = f"{cycle} {start:%d %b %Y} - {end:%d %b %Y}" log.warning("History request failed (%s): %s", label, e) diff --git a/lib/ecowitt/hass_api.py b/lib/ecowitt/hass_api.py index b8db4549..e3c80a69 100644 --- a/lib/ecowitt/hass_api.py +++ b/lib/ecowitt/hass_api.py @@ -2,13 +2,14 @@ The rest of the bot never knows the difference: the cache, the archive, the charts and the alerts all take what `EcowittAPI` gives, in the shapes it gives them (api.py; hass_history.py tells how the history is cut). What differs: its live reading is a request to a machine -on the network, so it is asked for every few seconds, not once a minute (source.watch_live); it has a "1min" history cycle (Ecowitt has +on the network, so it is asked for every 30 seconds, not once a minute (source.watch_live); it has a "1min" history cycle (Ecowitt has none); and empty_is_final is False, since Home Assistant only has what it recorded, so an answer with nothing in it does not prove there was nothing to know (the cloud may have it): the storage does not remember such a range as fetched, and a fallback asks the cloud for it. It is up as long as Home Assistant is: a failure is an EcowittError, as the cloud's are, passing (a network error, a restart) or not (a refused token). """ +import asyncio import logging import math import time @@ -56,7 +57,8 @@ def __init__(self, url: str, token: str, tz: tzinfo, mac: str = "HOMEASSISTANT", self.ha = HomeAssistant(url, token, transport) self.tz, self.mac, self.clock = tz, mac, clock self.earliest: float | None = None # when its first state of the station is (nothing is asked for before it) - self._looked = False # ... and whether that has been looked for + self._looked = False # ... and whether that has been looked for (or was known: the station keeps it in its file) + self._looking = asyncio.Lock() # (looked for once, whoever asks first) self.requests = 0 async def close(self): @@ -81,23 +83,35 @@ async def _asked(self, coro): except ValueError as e: # a reply that is not JSON raise EcowittError(f"Home Assistant gave an unreadable reply ({e})", transient=True) from None + def known_earliest(self, earliest: float): + """When its first state of the station is, as kept from an earlier start (it doesn't change): not looked for again.""" + self.earliest, self._looked = earliest, True + + @property + def looked(self) -> bool: + return self._looked + async def devices(self) -> list[dict]: - """The station, as Ecowitt's device list gives one: its name, time zone, place and when its first reading was.""" - config = await self._asked(self.ha.config()) - prefix = await self._asked(self.ha.station()) - await self._look(prefix) + """The station, as Ecowitt's device list gives one: its name, time zone and place (its settings and its states, asked for + together), and when its first reading was if that is known (look() finds it: a long history query, left out of the start).""" + config, prefix = await asyncio.gather(self._asked(self.ha.config()), self._asked(self.ha.station())) model = prefix.removeprefix("sensor.").strip("_").upper() or "Ecowitt" return [{"mac": self.mac, "name": model, "date_zone_id": config.get("time_zone"), "latitude": config.get("latitude"), "longitude": config.get("longitude"), **({"createtime": int(self.earliest)} if self.earliest else {})}] - async def _look(self, prefix: str): - """Find when Home Assistant's first state of the station is (its outdoor temperature's), once.""" - if not self._looked: - now = self.clock() - name = prefix + ENTITIES["outdoor.temperature"].suffix - found = await self._asked(self.ha.history([name], now - LOOKBACK_DAYS * 86400, now)) - self.earliest = found[name][0][0] if name in found else None - self._looked = True + async def look(self) -> float | None: + """When Home Assistant's first state of the station is (its outdoor temperature's): looked for once, LOOKBACK_DAYS back.""" + return await self._look(await self._asked(self.ha.station())) + + async def _look(self, prefix: str) -> float | None: + async with self._looking: + if not self._looked: + now = self.clock() + name = prefix + ENTITIES["outdoor.temperature"].suffix + found = await self._asked(self.ha.history([name], now - LOOKBACK_DAYS * 86400, now)) + self.earliest = found[name][0][0] if name in found else None + self._looked = True + return self.earliest async def realtime(self, mac: str, groups: str, urgent: bool = False) -> dict: prefix = await self._asked(self.ha.station()) diff --git a/lib/ecowitt/homeassistant.py b/lib/ecowitt/homeassistant.py index ec3fc72b..ca2ecddb 100644 --- a/lib/ecowitt/homeassistant.py +++ b/lib/ecowitt/homeassistant.py @@ -10,6 +10,7 @@ Entities are found by their names: the Ecowitt integration calls them sensor._outdoor_temperature, sensor._humidity ... """ +import asyncio import logging import math import time @@ -21,12 +22,15 @@ from ..netenv import local_name_hint from ..series import derives_range +from ..tls import ssl_context from .hass_map import ANCHOR, ENTITIES, NO_RANGE, convert, entity_ids from .live import BUCKET log = logging.getLogger(__name__) HALF = BUCKET // 2 +STATES_SHARE_SECONDS = 5.0 # one /api/states answer serves every caller this long (the station's and the air monitor's finding their entities + # and their live readings at start ask for it at about the same moment) RANGE_SERIES = [e.series for e in ENTITIES.values() if e.group != "rainfall" and e.series not in NO_RANGE and derives_range(e.field)] # what a chart shades @@ -96,13 +100,19 @@ def ok(self): class HomeAssistant: """Home Assistant's REST API: the station's entities (found by name), their states now and their history.""" - def __init__(self, url: str, token: str, transport=None): - self.client = httpx.AsyncClient(base_url=url.rstrip("/"), headers={"Authorization": f"Bearer {token}"}, timeout=60, transport=transport) + def __init__(self, url: str, token: str, transport=None, clock=time.monotonic): + self.client = httpx.AsyncClient(base_url=url.rstrip("/"), headers={"Authorization": f"Bearer {token}"}, timeout=60, transport=transport, + verify=ssl_context()) self.trouble = Trouble(url) self.prefix: str | None = None self.units: dict[str, str] = {} # entity id -> the unit Home Assistant shows it in (read with its states) + self.clock = clock + self._states: tuple[float, list[dict]] | None = None # (when it came, the last /api/states answer), shared STATES_SHARE_SECONDS + self._states_flight: asyncio.Future | None = None # the /api/states request out now, which every caller awaits async def close(self): + if self._states_flight is not None and not self._states_flight.done(): + self._states_flight.cancel() await self.client.aclose() async def _get(self, path: str, **params): @@ -112,11 +122,21 @@ async def _get(self, path: str, **params): async def states(self) -> list[dict]: """Every entity's state now ({"entity_id", "state", "attributes", "last_changed", "last_updated" ...}); the units of the station's - are kept for converting what its history says.""" + are kept for converting what its history says. One answer is shared: a request already out is awaited rather than sent again, + and an answer under STATES_SHARE_SECONDS old is used as it is (callers only read it).""" + if self._states is not None and self.clock() - self._states[0] < STATES_SHARE_SECONDS: + return self._states[1] + if self._states_flight is None or self._states_flight.done(): + self._states_flight = asyncio.ensure_future(self._fetch_states()) + self._states_flight.add_done_callback(lambda t: t.cancelled() or t.exception()) # (its failure is its callers') + return await asyncio.shield(self._states_flight) + + async def _fetch_states(self) -> list[dict]: found = await self._get("/api/states") for s in found: if isinstance(s, dict) and (unit := (s.get("attributes") or {}).get("unit_of_measurement")): self.units[s.get("entity_id", "")] = unit + self._states = (self.clock(), found) return found async def config(self) -> dict: diff --git a/lib/ecowitt/reads.py b/lib/ecowitt/reads.py index 2cefc71d..888fd342 100644 --- a/lib/ecowitt/reads.py +++ b/lib/ecowitt/reads.py @@ -8,13 +8,15 @@ catalogue's decimals: a 5-minute mean of the bot's live readings is drawn as the station would have sent it). """ +import bisect from dataclasses import dataclass, field from ..lines import Plotted, Sample from ..storage.catalogue import BY_NAME, KINDS, column_of, field_of from ..storage.read import Reader -from ..storage.schema import some_value +from ..storage.schema import q, some_value from .api import cycle_seconds +from .direction import sector from .period import Period, period_on type Store = dict[str, dict] # "group.field" -> {"unit": str, "pts": {epoch: Sample}} @@ -64,6 +66,49 @@ def first_minute_on(r: Reader, mac: str, groups: list[str], start: int, end: int return min((t for t in found if t is not None), default=None) +def directions_on(r: Reader, mac: str, start: int, end: int) -> list[int]: + """How long the wind blew from each of the 16 compass points (direction.sector: N first, clockwise) from start to end, in minutes, of + the wind's 5-minute readings (5 each) and its minutes (1 each) where no 5-minute reading covers them (300 s either side), in one query; + a calm reading (its speed 0) left out, one with no speed counted. All 0 with none (the web page's wind rose: today's).""" + counts = [0] * 16 + sensor = r.sensor(mac, "wind") + if sensor is None or sensor.kind != "wind": + return counts + got = r.db.execute(f"SELECT res, ts, {q('wind_direction')}, {q('wind_speed')} FROM wind WHERE sensor = ? AND res IN ('1min', '5min') " + f"AND ts BETWEEN ? AND ? AND {q('wind_direction')} IS NOT NULL ORDER BY ts", (sensor.id, start, end)).fetchall() + fives = [ts for res, ts, _, _ in got if res == "5min"] + for res, ts, degrees, speed in got: + if speed is not None and speed <= 0: + continue + if res == "1min": + i = bisect.bisect_left(fives, ts - 299) + if i < len(fives) and fives[i] < ts + 300: + continue + counts[sector(degrees)] += 5 if res == "5min" else 1 + return counts + + +def pressure_on(r: Reader, mac: str, start: int, end: int) -> list[tuple[int, float]]: + """The relative pressure (hPa) from start to end, oldest first, [(epoch, hPa)]: its 5-minute readings and its minutes where no 5-minute + reading covers them (300 s either side, as directions_on), in one query; [] with none, or no pressure sensor (the web page's pressure + arrow: its change over the past hour).""" + sensor, place = r.sensor(mac, "pressure"), column_of("pressure", "relative") + if sensor is None or sensor.kind not in KINDS or place is None: + return [] + column = q(place[0]) + got = r.db.execute(f"SELECT res, ts, {column} FROM {sensor.kind} WHERE sensor = ? AND res IN ('1min', '5min') AND ts BETWEEN ? AND ? " + f"AND {column} IS NOT NULL ORDER BY ts", (sensor.id, start, end)).fetchall() + fives = [ts for res, ts, _ in got if res == "5min"] + out = [] + for res, ts, value in got: + if res == "1min": + i = bisect.bisect_left(fives, ts - 299) + if i < len(fives) and fives[i] < ts + 300: + continue + out.append((ts, float(value))) + return out + + def newest_minute_on(r: Reader, mac: str) -> int | None: """The time of the newest minute held of the station (where the next pull of Home Assistant's starts), None for none.""" found = [r.db.execute(f"SELECT MAX(ts) FROM {s.kind} WHERE sensor = ? AND res = '1min'", (s.id,)).fetchone()[0] @@ -160,5 +205,5 @@ def history_on(r: Reader, mac: str, groups: list[str], plan: list[tuple[str, int return held -__all__ = ["Held", "Store", "buckets_on", "counts_on", "first_minute_on", "history_on", "newest_minute_on", "readings_on", "rows_on", +__all__ = ["Held", "Store", "buckets_on", "counts_on", "directions_on", "first_minute_on", "history_on", "newest_minute_on", "pressure_on", "readings_on", "rows_on", "slot_values_on"] diff --git a/lib/ecowitt/source.py b/lib/ecowitt/source.py index 871cfe85..783a7608 100644 --- a/lib/ecowitt/source.py +++ b/lib/ecowitt/source.py @@ -3,6 +3,7 @@ (lib/service) read its file and its live reading.""" import asyncio +import json import logging import os import time @@ -15,7 +16,7 @@ from ..sources import Source from ..timeutil import local_epoch, naive_local from ..warm import FAST_REFRESH_SECONDS, Warmer, safely -from .api import FINE_CYCLES, EcowittAPI, GROUPS, unit_text +from .api import FINE_CYCLES, EcowittAPI, GROUPS, NotInYet, unit_text from ..public_holidays import PublicHolidays from .fetch import Fetcher, Recent from .fallback import FallbackAPI, newest @@ -34,9 +35,13 @@ LIVE_GROUPS = list(READING_GROUPS) # what the once-a-minute live reading asks for: everything "weather now" and the report show HA_IMPORT_SECONDS = 900 # how often Home Assistant's readings are folded into the 5-minute ranges ... HA_RECENT_SECONDS = 3 * 3600 # ... the last few hours each time (the whole RANGE_KEEP_DAYS the first time) -LIVE_POLL_SECONDS = 5 # Home Assistant's live reading is asked for this often (a request to a machine on the network) +LIVE_POLL_SECONDS = 30 # Home Assistant's live reading is asked for this often (the gateway reports about once a minute) LIVE_RECORD_SECONDS = 30 # ... and counted into the ranges this often LIVE_FRESH_SECONDS = 90 # a question is answered from that reading while it is this young +DEVICE_RETRY_SECONDS = (10, 300) # a device list that failed is asked again after the first, doubling up to the second +LIVE_KEEP_SECONDS = 60 # the live reading is kept in the file at most this often (a restart starts from it) +DEVICE_KEY, EARLIEST_KEY, LIVE_KEY = "station", "ha_earliest", "live" # the file's meta: the station's device (as its API last listed + # it); Home Assistant's first state; the last live reading ({"at", "data"}) class LiveMarks: """The live readings of the newest 5-minute marks, each counted in the mark nearest it (as the old live ranges were): once a mark has two @@ -95,9 +100,10 @@ def __init__(self, cfg: Config, transport=None, ha_transport=None, storage: Stor ha_transport) if cfg.ecowitt_home_assistant else None cloud = EcowittAPI(cfg.ecowitt_api_key, cfg.ecowitt_app_key, transport) if cfg.ecowitt_cloud else None self.api = FallbackAPI(home, cloud, cfg.tz) if home and cloud else home or cloud + self.home = home # Home Assistant's API, if it is one of them (its first state is kept in the file) self.via = "HA/cloud" if home and cloud else "HA" if home else "cloud" self.has_minutes = home is not None # (only Home Assistant has minutes) - self.fast = home # the API that can be asked every few seconds, if any + self.fast = home # the API that can be asked every LIVE_POLL_SECONDS, if any self.ha = home.ha if home else HomeAssistant(cfg.homeassistant_url, cfg.homeassistant_token) if cfg.homeassistant else None # (shared with the air sensor) self._ha_ok: bool | None = None self.live_marks = LiveMarks() # the live readings' lows and highs, for the recent charts' bands @@ -105,47 +111,164 @@ def __init__(self, cfg: Config, transport=None, ha_transport=None, storage: Stor self.warmer = Warmer(self.warm, FAST_REFRESH_SECONDS) self._live_ok: bool | None = None # the live rain reading: None until first tried self._live: tuple[float, dict] | None = None # (fetched at, the real_time data) from the keep-warm's minute check + self._live_flight: tuple[bool, asyncio.Future] | None = None # (urgent, the request) of every group, while it is asked self.on_live: list = [] # called (no arguments) when the poll finds a reading newer than the last: the rain alert's self._seen = 0 # the time of the newest reading the poll has found self._polled: float = 0.0 # when the poll last had an answer self._recorded = 0.0 self.cache_line = "" + self.listed = asyncio.Event() # set once the station is known (its address): from the file at start, else its device list + self._live_now = False # this run has had a live reading (until then a question is answered from the kept one) + self._live_kept = 0.0 # when the live reading was last kept in the file self.mac = "" self.station_name = "" self.created: datetime | None = None self.latitude: float | None = None # the station's own location (the forecast uses it unless one is configured) self.longitude: float | None = None - async def start(self): - devices = await self.api.devices() - if not devices: - raise RuntimeError("no Ecowitt device on this account") - device = devices[0] + async def start(self, wait: bool = True): + """Find the station: its address, name, time zone, place and age: from what the file kept of it when its API last listed it (the + same API), else from the file's readings (the station they are of, in the file's time zone), else (a first start) from its + device list (wait; a failure raises) or, without waiting (ecobot-mcp's start: nothing asked of the network, so the port opens at + once), not yet: its time zone is the configured one and its readings aren't in until refresh_device, in the warm-up, has its + device list. ecobot-mcp asks for the list again in the background either way. The live reading kept in the file (the last + before the restart) is taken too: questions and the dashboard are answered from it, as of its time, until this run's first + comes in.""" + saved = await self._saved(DEVICE_KEY) + if self.home is not None and isinstance(earliest := await self._saved(EARLIEST_KEY), (int, float)): + self.home.known_earliest(float(earliest)) + if isinstance(saved, dict) and saved.get("via") == self.via and isinstance(saved.get("device"), dict) and saved["device"].get("mac"): + self._apply(saved["device"], int(saved.get("count") or 1)) + elif known := self._file_station(): + log.info("Ecowitt: starting from the history file's station (%s, %s); its device list is asked for in the background", + known["mac"], known["date_zone_id"]) + self._apply(known, 1) + elif wait: + devices = await self.api.devices() + if not devices: + raise RuntimeError("no Ecowitt device on this account") + await self._keep_device(devices[0], len(devices)) + self._apply(devices[0], len(devices)) + else: + self.summary = f"Ecowitt: not found yet ({self.via}, {self.warmer.interval:g}s): its device list is asked for in the background" + if self.mac: + await self._take_kept_live() + if self.created is None and self.home is not None and self.home.earliest is not None: # (Home Assistant's first state, kept) + self.created = datetime.fromtimestamp(int(self.home.earliest), UTC).astimezone(self.tz) + await self.storage.set_timezone(self.tz) # (so are the day rows) + if (problem := PublicHolidays(self.tz).problem()) and "package" in problem: + log.warning("Public holiday questions won't work: pip install holidays (then restart)") + try: + size = os.path.getsize(self.storage.path) if os.path.exists(self.storage.path) else 0 + self.cache_line = f"History: {self.storage.path} ({size / 1e6:.1f} MB)" + except Exception as e: # only a log line + log.warning("History file not readable: %s", e) + + def _file_station(self) -> dict | None: + """The station whose readings the file holds, as a device ({"mac", "date_zone_id"}: the file's days are in its zone), if just one.""" + mac = self.home.mac if isinstance(self.api, HomeAssistantAPI) else None + macs = sorted({s.device for s in self.storage.sensors.all() if s.kind != AIR[0]}) + if mac is None and len(macs) == 1: + mac = macs[0] + if mac is None or mac not in macs: + return None + return {"mac": mac, "date_zone_id": str(getattr(self.storage.tz, "key", self.storage.tz))} + + def _apply(self, device: dict, count: int, zone: bool = True): + """The station as a device list gives it: its address, name, time zone (its days are local to it; not with `zone` False), place + and creation time.""" self.mac = str(device["mac"]).upper() self.station_name = device.get("name") or "station" - if zone := device.get("date_zone_id"): # the station's own time zone ("Australia/Melbourne"): its days are local to it + if zone and (named := device.get("date_zone_id")): # the station's own time zone ("Australia/Melbourne"): its days are local to it try: - self.tz = ZoneInfo(zone) + self.tz = ZoneInfo(named) except (ValueError, ZoneInfoNotFoundError): - log.warning("Ecowitt names a time zone Python doesn't know, %r; using %s", zone, self.tz) + log.warning("Ecowitt names a time zone Python doesn't know, %r; using %s", named, self.tz) if hasattr(self.api, "set_timezone"): # (Home Assistant's history is cut in the station's days) self.api.set_timezone(self.tz) - await self.storage.set_timezone(self.tz) # (so are the day rows) for name, key, read in (("created", "createtime", lambda v: datetime.fromtimestamp(int(v), UTC).astimezone(self.tz)), ("longitude", "longitude", float), ("latitude", "latitude", float)): try: setattr(self, name, read(device[key])) except (KeyError, TypeError, ValueError): pass - if (problem := PublicHolidays(self.tz).problem()) and "package" in problem: - log.warning("Public holiday questions won't work: pip install holidays (then restart)") self.summary = (f"Ecowitt: '{self.station_name}' ({self.mac}): {self.via} ({self.warmer.interval:g}s)" - + (f", {len(devices)} devices" if len(devices) > 1 else "")) + + (f", {count} devices" if count > 1 else "")) + self.listed.set() + + @property + def location(self) -> tuple[float, float] | None: + """(lat, lon) as the station's device list gives it; None while it gives none (or, on a first start, hasn't answered yet).""" + return None if None in (self.latitude, self.longitude) else (self.latitude, self.longitude) + + async def _saved(self, key: str): + """A value the file keeps for the station (JSON), None when it has none or it can't be read.""" try: - size = os.path.getsize(self.storage.path) if os.path.exists(self.storage.path) else 0 - self.cache_line = f"History: {self.storage.path} ({size / 1e6:.1f} MB)" - except Exception as e: # only a log line - log.warning("History file not readable: %s", e) + text = await self.storage.read(lambda r: r.meta(key)) + return json.loads(text) if text else None + except Exception as e: # (then it is asked for, as at a first start) + log.warning("Ecowitt: the history file's %s couldn't be read (%s: %s)", key, type(e).__name__, e) + return None + + async def _keep(self, key: str, value): + try: + await self.storage.write(lambda w: w.set_meta(key, json.dumps(value))) + except Exception as e: # (only the next start's shortcut) + log.warning("Ecowitt: couldn't keep the station's %s in the history file (%s: %s)", key, type(e).__name__, e) + + async def _keep_device(self, device: dict, count: int): + kept = {k: device[k] for k in ("mac", "name", "date_zone_id", "latitude", "longitude", "createtime") if device.get(k) is not None} + await self._keep(DEVICE_KEY, {"via": self.via, "count": count, "device": kept}) + + async def refresh_device(self): + """The device list, asked for in the background after the start (which never waits on it), again after a failure (DEVICE_RETRY_SECONDS) + until it answers: what it says is kept in the file for the next start. A station found at start (from the file) takes its name, + place and creation time at once; a new address or time zone is said, and taken at the next start (the tools and the file's days + were set up in the old). A first start's station is found now (listed): its time zone is taken at the next start if it is + not the configured one, which this run keeps.""" + wait, said = DEVICE_RETRY_SECONDS[0], False + while True: + try: + devices = await self.api.devices() + if not devices: + raise RuntimeError("no Ecowitt device on this account") + break + except Exception as e: + if not said: + log.warning("Ecowitt: the device list failed (%s: %s); asked again in %gs, then less often%s", type(e).__name__, e, wait, + "" if self.mac else ": the station's readings aren't in until it answers") + said = True + await asyncio.sleep(wait) + wait = min(wait * 2, DEVICE_RETRY_SECONDS[1]) + device, count = devices[0], len(devices) + await self._keep_device(device, count) + if said: + log.info("Ecowitt: the device list answers again") + zone, ours = device.get("date_zone_id"), str(getattr(self.tz, "key", self.tz)) + if not self.mac: + self._apply(device, count, zone=False) + log.info("%s", self.summary) + if zone and zone != ours: + log.warning("Ecowitt: the station's time zone is %s; this run keeps %s (the configured one): restart ecobot-mcp to use the " + "station's", zone, ours) + return + if str(device["mac"]).upper() != self.mac or zone and zone != ours: + log.warning("Ecowitt: the device list now names %s in %s (this run is on %s in %s): restart ecobot-mcp to use it", + str(device["mac"]).upper(), zone or "no time zone", self.mac, self.tz) + return + self._apply(device, count) + + async def keep_earliest(self): + """When Home Assistant's first state of the station is, if not known from the file: looked for (a long history query, after + start), kept in the file; the station's creation time when no device list gave one (the archive starts from it).""" + if self.home is None: + return + looked = self.home.looked + earliest = await self.home.look() + if earliest is not None and not looked: + await self._keep(EARLIEST_KEY, earliest) + if earliest is not None and self.created is None: + self.created = datetime.fromtimestamp(int(earliest), UTC).astimezone(self.tz) def startup_lines(self) -> list[str]: return [*([self.cache_line] if self.cache_line else []), *super().startup_lines()] @@ -156,28 +279,79 @@ def archive_pace(self) -> float | None: None for the archive's own.""" return 0.0 if isinstance(self.api, HomeAssistantAPI) else None + async def _take_kept_live(self): + """The live reading the file kept (the last before the restart), as this run's until its own comes in.""" + kept = await self._saved(LIVE_KEY) + if isinstance(kept, dict) and isinstance(kept.get("data"), dict) and isinstance(kept.get("at"), (int, float)) and kept.get("mac") == self.mac: + self._live = self._live or (float(kept["at"]), kept["data"]) + + async def _keep_live(self, at: float, data: dict): + """The live reading kept in the file for the next start, at most every LIVE_KEEP_SECONDS (only a restart's first answers need it).""" + if at - self._live_kept >= LIVE_KEEP_SECONDS: + self._live_kept = at + await self._keep(LIVE_KEY, {"mac": self.mac, "at": at, "data": data}) + + def _got_live(self, data: dict): + """A live reading of this run's: kept for the next to ask (and, every LIVE_KEEP_SECONDS, in the file).""" + self._live, self._live_now = (time.time(), data), True + def fetcher(self, groups: list[str], urgent: bool = False) -> Fetcher: """urgent: for a question (its requests go before the background ones).""" return Fetcher(self.api, self.storage, self.fetches, self.mac, groups, self.tz, urgent, self.has_minutes) - async def _live_data(self, groups: list[str], max_age: float = LIVE_FRESH_SECONDS, urgent: bool = True) -> dict: + async def _live_data(self, groups: list[str], max_age: float = LIVE_FRESH_SECONDS, urgent: bool = True, kept: bool = True) -> dict: """The real_time data for these groups: the kept reading when it is under `max_age` old (a minute and a half for a question) and asked for them, or when Home Assistant's poll has just confirmed it is the newest; else a request of its own, ahead of the background - refreshes when someone is waiting (urgent).""" + refreshes when someone is waiting (urgent). Until this run has had a live reading (just after a start), the one kept from before + it answers at once whatever its age (its readings carry their times), one being asked for meanwhile, unless `kept` is False (the + rain alert's: it never acts on an old reading).""" fresh = self._live and (time.time() - self._live[0] <= max_age or time.time() - self._polled <= LIVE_POLL_SECONDS * 3) - if fresh and set(groups) <= set(LIVE_GROUPS): + if set(groups) <= set(LIVE_GROUPS) and (fresh or self._live and kept and not self._live_now): + if not fresh: + self._ask_live() return {g: self._live[1][g] for g in groups if g in self._live[1]} return await self._fetch_live(groups, urgent=urgent) + def _ask_live(self): + """The live reading asked for in the background, unless it already is (or the station isn't found yet: the warm-up asks then).""" + if self.mac and not ((flight := self._live_flight) and not flight[1].done()): + asyncio.ensure_future(self.first_live()) + async def _fetch_live(self, groups: list[str], urgent: bool = False) -> dict: """A real_time request for these groups, counted into the 5-minute bands; with every group in it, kept as the minute's own reading - for the next to ask (the report's gauges).""" + for the next to ask (the report's gauges). Single-flight: while a request of every group is out, a caller wanting no more than it + awaits that one instead of queueing another (a question joins a background one only once it is urgent too, so it never waits + behind the refreshes queued ahead of it).""" + wanted = set(groups) + if (flight := self._live_flight) and not flight[1].done() and wanted <= set(LIVE_GROUPS) and (flight[0] or not urgent): + data = await asyncio.shield(flight[1]) + return {g: data[g] for g in groups if g in data} + if not self.mac: + raise NotInYet() + if not wanted >= set(LIVE_GROUPS): + data = await self.api.realtime(self.mac, ",".join(groups), urgent=urgent) + await self._record_live(data) + return data + task = asyncio.ensure_future(self._fetch_every_live(groups, urgent)) + task.add_done_callback(lambda t: t.cancelled() or t.exception()) # (its failure is its callers'; none left is no warning) + self._live_flight = (urgent, task) + return await asyncio.shield(task) # (a caller that gives up leaves it to the others, and the reading is still kept) + + async def _fetch_every_live(self, groups: list[str], urgent: bool) -> dict: data = await self.api.realtime(self.mac, ",".join(groups), urgent=urgent) - if set(groups) >= set(LIVE_GROUPS): - self._live = (time.time(), data) + self._got_live(data) await self._record_live(data) + await self._keep_live(self._live[0], data) return data + async def first_live(self): + """The live reading at start, before the history: the dashboard's tiles and the first "weather now" wait on it (a question asked + meanwhile joins this request). Urgent: people are waiting. A failure is logged; the next minute's check asks again.""" + try: + await self._fetch_live(LIVE_GROUPS, urgent=True) + except Exception as e: + log.warning("Live reading at start failed: %s: %s", type(e).__name__, e) + @property def ranges_from_ha(self) -> bool: """Are the charts' 5-minute bands read back from Home Assistant's history (import_ranges)? Only when the station's readings come @@ -213,7 +387,7 @@ async def _record_live(self, data: dict): log.warning("Couldn't keep the live readings' ranges: %s", e) async def watch_live(self): - """Ask Home Assistant for the live reading every few seconds, for ever. A reading newer than the last one found is kept for "weather + """Ask Home Assistant for the live reading every LIVE_POLL_SECONDS, for ever. A reading newer than the last one found is kept for "weather now", the report and the rain alert (which is called at once, not at the next minute's refresh). A failure is logged once, with its recovery; the cloud, where there is one, answers the questions meanwhile.""" if self.fast is None: @@ -230,7 +404,9 @@ async def watch_live(self): self._polled = time.time() if (at := newest(data)) <= self._seen: continue - self._seen, self._live = at, (time.time(), data) + self._seen = at + self._got_live(data) + await self._keep_live(self._live[0], data) if time.time() - self._recorded >= LIVE_RECORD_SECONDS: self._recorded = time.time() await self._record_live(data) @@ -256,7 +432,7 @@ async def live_rain(self) -> tuple[int, dict] | None: by up to 5 minutes, this is about a minute old. The same request keeps every live reading ready for "weather now" and the report (self._live), one request a minute. None when unavailable.""" try: - data = await self._live_data(LIVE_GROUPS, max_age=0, urgent=False) # the newest minute: the poll's, else a request + data = await self._live_data(LIVE_GROUPS, max_age=0, urgent=False, kept=False) # the newest minute: the poll's, else a request group = data.get("rainfall") or {} row = {f"rainfall.{k}": float(group[k]["value"]) for k in ("rain_rate", "daily") if k in group} ts = max((int(group[k].get("time") or 0) for k in group if isinstance(group[k], dict)), default=0) @@ -276,11 +452,12 @@ async def live_rain(self) -> tuple[int, dict] | None: async def warm(self, fresh: bool = True) -> str: """Every resolution's newest readings for every group: the last 7 days at 30 minutes, yesterday and today at 5 minutes, the last 3 days at 4 hours and daily (only the unsettled tails go to Ecowitt; the archive keeps the - settled history).""" + settled history). Not before the station is found (a first start: the warm-up's device list).""" + await self.listed.wait() now = self.now() today = datetime.combine(now.date(), datetime.min.time()) - windows = {"30min": today - timedelta(days=6), "5min": today - timedelta(days=1), - "4hour": today - timedelta(days=3), "1day": today - timedelta(days=3)} + windows = {"5min": today - timedelta(days=1), "30min": today - timedelta(days=6), # (in this order: what questions on + "4hour": today - timedelta(days=3), "1day": today - timedelta(days=3)} # the last hours and days read first) fetchers = {cycle: self.fetcher(self.groups) for cycle in windows} await asyncio.gather(*(fetchers[cycle].get(cycle, start, now, refresh=fresh and cycle in FINE_CYCLES, load=False) @@ -298,6 +475,8 @@ async def recent(self, hours: float) -> list[tuple[int, dict]]: return await self.readings("5min", naive_local(local_epoch(now, self.tz) - hours * 3600, self.tz), now) async def close(self): + if (flight := self._live_flight) and not flight[1].done(): + flight[1].cancel() try: await self.api.close() finally: diff --git a/lib/forecast/source.py b/lib/forecast/source.py index 01f632ea..eb90a23c 100644 --- a/lib/forecast/source.py +++ b/lib/forecast/source.py @@ -1,9 +1,11 @@ """The forecast source: the daily forecast from Open-Meteo (open-meteo.com), kept warm and cached; fetched only from 6 am to 6 pm -local time (lib/warm.py SYNC_HOURS), every 15 minutes, and once at the start (or the first question) when nothing is cached.""" +local time (lib/warm.py SYNC_HOURS), every 15 minutes, and once just after the start (ecobot-mcp's warm-up, or the first question) when +nothing is cached.""" import logging import math import time +from collections.abc import Callable from datetime import date import httpx @@ -11,6 +13,7 @@ from ..config import Config from ..snapshots import Snapshots from ..sources import Source +from ..tls import ssl_context from ..warm import Warmer, in_sync_hours log = logging.getLogger(__name__) @@ -64,14 +67,15 @@ def day_label(day: date, today: date) -> str: class Forecast(Source): name = "Forecast" - def __init__(self, cfg: Config, location: tuple[float, float] | None = None, transport=None): - """location: (lat, lon), used when the config has none (the weather station's own).""" + def __init__(self, cfg: Config, location: tuple[float, float] | Callable[[], tuple[float, float] | None] | None = None, transport=None): + """location: (lat, lon), used when the config has none (the weather station's own); or what gives it when asked (the station's, + which a first start learns only once its device list answers).""" self.tz, self.place = cfg.tz, cfg.place configured = (cfg.forecast_lat, cfg.forecast_lon) if configured != (None, None) and None in configured: log.warning("MCP_FORECAST_LAT and MCP_FORECAST_LON go together: with only one set, the weather station's location is used") - self.location = configured if None not in configured else location if location and None not in location else None - self.client = httpx.AsyncClient(timeout=15, headers=HEADERS, follow_redirects=True, transport=transport) + self._location = configured if None not in configured else location + self.client = httpx.AsyncClient(timeout=15, headers=HEADERS, follow_redirects=True, transport=transport, verify=ssl_context()) self.days: list[dict] | None = None self.fetched_at = 0.0 self.requests = 0 @@ -79,14 +83,23 @@ def __init__(self, cfg: Config, location: tuple[float, float] | None = None, tra self._load() self.warmer = Warmer(self.warm, FORECAST_REFRESH_SECONDS) - async def start(self): - if not self.location: + @property + def location(self) -> tuple[float, float] | None: + """(lat, lon): the configured one, else the weather station's (None while it has none).""" + found = self._location() if callable(self._location) else self._location + return tuple(found) if found and None not in found else None + + async def start(self, wait: bool = True): + """From the last forecast fetched (kept in the file), nothing asked: the first fetch, if that one is due again, is the warm-up's + (ecobot_mcp/core.py Core.warm_up). Without a location, nor a station that may yet give one, it can't start.""" + if not self.location and not callable(self._location): raise RuntimeError("no location: set MCP_FORECAST_LAT and MCP_FORECAST_LON (or the weather station supplies one)") - try: - await self.warm(True) - self.summary = f"{SOURCE}: {len(self.days or [])} days (every {self.warmer.interval:g}s)" - except Exception as e: - log.warning("Forecast not readable yet: %s", e) + self.summary = self.describe() + + def describe(self) -> str: + """The start-up line: how many days it holds, and how often it is fetched.""" + held = f"{len(self.days)} days" if self.days is not None else "none kept yet" + return f"{SOURCE}: {held} (every {self.warmer.interval:g}s)" # ---------- kept on disk ---------- def _load(self): @@ -152,6 +165,8 @@ async def warm(self, fresh: bool = True) -> str: if self.days is not None and (not in_sync_hours(self.now()) or age < FRESH_SECONDS and not fresh): return "Forecast cached" before = self.requests + if not self.location: # (the station's, not given yet: a first start whose device list hasn't answered) + raise RuntimeError("no location yet: the weather station hasn't given one (or set MCP_FORECAST_LAT and MCP_FORECAST_LON)") self.days = await self._open_meteo() # a failure raises: the warmer logs it self.days = await self._with_chance(self.days) self.fetched_at = time.time() diff --git a/lib/gauge_look.py b/lib/gauge_look.py index b11d92d3..f73e46ad 100644 --- a/lib/gauge_look.py +++ b/lib/gauge_look.py @@ -4,24 +4,37 @@ from dataclasses import asdict +from .ecowitt.direction import POINTS # (the compass's 16 points, for the page to name a direction as its needle moves) from .specs import Tile BG = "#14191D" INK = "#E8EAED" # the titles, the figures SOFT = "#B8BDC2" # scale numbers, outlines CHIP = "#3A4046" # the row names' backing -MAX_CHIP, MIN_CHIP, TOTAL_CHIP = "#C62828", "#4FB3F6", "#5BC8F0" -CHIPS = {"Max": MAX_CHIP, "Min": MIN_CHIP, "Total": TOTAL_CHIP} -MARKS = {"Max": "▲", "Min": "▼", "Total": "+"} # in front of a column's name +MAX_CHIP, MIN_CHIP, TOTAL_CHIP, GUST_CHIP = "#C62828", "#4FB3F6", "#5BC8F0", "#7C8790" +CHIPS = {"Max": MAX_CHIP, "Min": MIN_CHIP, "Total": TOTAL_CHIP, "Gust": GUST_CHIP} +MARKS = {"Max": "▲", "Min": "▼", "Total": "+", "Gust": "»"} # in front of a column's name +HIGH_HAND = "#FF3B30" # a dial's red mark at its reading's highest today (the web page's: the wind's gust a thin hand; rain rate, + # sun and UV a limit mark, a small triangle outside the coloured band, pointing in) +HIGH_HAND_WIDTH = 1.4 # ... the hand: how wide (pixels) +LIMIT_MARK = (118, 138, 8.5) # ... the triangle: its tip's and its base's radius, its base's half-width (pixels; the band ends at 130, + # the outline at 138) + FILL = "#D32F27" # the thermometer's mercury TUBE_HALF, BULB_RADIUS = 28, 38 # the thermometer: half the tube's width, the bulb's radius (pixels, to the outline) MERCURY_GAP = 7 # the gap between the outline and the red, the same round the bulb as up the tube BAR_WIDTH, BAR_GAP = 13, 12 # the scale's coloured blocks beside a thermometer or beaker: how wide, and how far from its outline RING_OUTER, BAND_WIDTH = 130, 22 # a dial's coloured scale: its outer radius and how wide it is (the outline is at 138) LABEL_RADIUS = 84 # where a dial's numbers sit, just inside its scale -BAND_Y, BAND_SIZE = 157, 19 # a dial's band name ("Moderate"): how far below its centre (under its outline), and its size +COMPASS = (240, 188, 130) # the wind's direction, a compass: its centre and outline's radius (above the table's place: it has none) +COMPASS_LABEL_Y = 346 # ... its reading ("99° E") under it +COMPASS_BAND = "#262E34" # ... its ring, under the ticks and the letters N, E, S and W WATER = "#4FB3F6" # the rain beaker's water NEEDLE = "#3E86C0" +RISING, FALLING = NEEDLE, HIGH_HAND # the web page's pressure arrow after its reading (its way over the past hour): up, in the + # needle's blue; down, in the red hands' red (steady: none) +WIND_CHIPS = {**CHIPS, "Max": NEEDLE, "Gust": HIGH_HAND} # the web page's Wind table: its Max the needle's colour (the speed + # it shows), its Gust its limit mark's red (today's highest gust) CELL_W, CELL_H, MARGIN = 480, 575, 20 FADE = 0.4 # how much of its colour a tile with no reading keeps SWEEP, START = 250.0, 215.0 # the dial runs clockwise from START degrees (0 = right, 90 = up) through SWEEP degrees @@ -60,10 +73,11 @@ def share(tile: Tile, value: float) -> float: def look() -> dict: """The figures above as JSON, for the web page to draw with.""" - return {"bg": BG, "ink": INK, "soft": SOFT, "chip": CHIP, "chips": CHIPS, "marks": MARKS, "fill": FILL, "water": WATER, - "needle": NEEDLE, "tube_half": TUBE_HALF, "bulb_radius": BULB_RADIUS, "mercury_gap": MERCURY_GAP, "bar_width": BAR_WIDTH, + return {"bg": BG, "ink": INK, "soft": SOFT, "chip": CHIP, "chips": CHIPS, "wind_chips": WIND_CHIPS, "marks": MARKS, "fill": FILL, "water": WATER, + "needle": NEEDLE, "rising": RISING, "falling": FALLING, "high_hand": HIGH_HAND, "high_hand_width": HIGH_HAND_WIDTH, "limit_mark": list(LIMIT_MARK), "tube_half": TUBE_HALF, "bulb_radius": BULB_RADIUS, "mercury_gap": MERCURY_GAP, "bar_width": BAR_WIDTH, "bar_gap": BAR_GAP, "ring_outer": RING_OUTER, "band_width": BAND_WIDTH, "label_radius": LABEL_RADIUS, - "band_y": BAND_Y, "band_size": BAND_SIZE, "cell": [CELL_W, CELL_H], + "cell": [CELL_W, CELL_H], "compass": list(COMPASS), + "compass_label_y": COMPASS_LABEL_Y, "compass_band": COMPASS_BAND, "points": list(POINTS), "fade": FADE, "sweep": SWEEP, "start": START, "rows": list(ROWS)} diff --git a/lib/gauge_sheet.py b/lib/gauge_sheet.py index f4580383..58003fa9 100644 --- a/lib/gauge_sheet.py +++ b/lib/gauge_sheet.py @@ -1,14 +1,19 @@ """The gauges' sheet (specs.Dashboard), laid out from the service's own `current` (docs/ecobot-mcp.md 3.1, 4) for the web page's gauges (lib/web_dashboard.py) and the Status picture's three (lib/status.py, drawn by lib/gauges.py): each gauge's scale and colours (the weather station's, lib/ecowitt/dashboard.py GAUGES, then the air sensor's, lib/airgradient/dashboard.py AIR_GAUGES) filled from the service's `current` with `context`, its reading now and the highs and lows of -today, the month and the year beside it (rain: its totals and wettest day; wind: its highest gust; the US AQI: the higher of PM2.5's -and PM10's, as AQI). An air gauge's band is named from its own reading now, and the US AQI is worked out from PM2.5 and PM10 now, the -higher of the two, its band saying "(PM10)" when PM10 sets it: the dials agree with their needles (the service's `aqi_us` and `band` +today, the month and the year beside it (rain: its totals and wettest day; wind: its highest speed, and its highest gust in a Gust +column where Min usually is; the UV index, the US AQI and the particles (PM2.5, PM10, PM1): their highest alone, no Min; the US AQI: +the higher of PM2.5's and PM10's, as AQI). An air gauge's band is named from its own reading now, and the US AQI is worked out from +PM2.5 and PM10 now, the higher of the two, its band saying "(PM10)" when PM10 sets it: the dials agree with their needles (the service's `aqi_us` and `band` are of the lower of the last two readings, for its ratings). +The wind's direction is a compass (its needle where the wind comes from, its band the compass point current gives with it), with no +table: highs and lows of a direction mean nothing. It is left out only when current has no entry for it, and dimmed with no reading. + A tile is left out when current has neither a reading nor a figure for it (no indoor sensor, no air sensor, a reading the air sensor never sent), and drawn dimmed at its floor when it has figures but no reading now. The web page's dashboard is every gauge's; the -Status picture its three (STATUS). +Status picture its three (STATUS). `indoor` False (MCP_DASHBOARD_INDOOR off, the web page's only) leaves out every indoor reading's +tile (INDOOR: the indoor sensor's group), as if current had none. """ import math @@ -16,12 +21,14 @@ from .airgradient.dashboard import AIR_GAUGES, AirGauge, air_gauges_of from .airgradient.metrics import us_aqi from .ecowitt.dashboard import GAUGES, PERIODS, STATUS, Gauge, gauges_of, scale +from .ecowitt.direction import point from .gauge_look import CELL_H, CELL_W from .specs import Dashboard, Tile ROWS = dict(zip(PERIODS, ("today", "month", "year"))) # a tile's rows, as current's context names them STATION = "station" -FIRST = ("Temperature", "Humidity", "Atmospheric pressure", "Rain", "UV index", "US AQI") # the dashboard's first tiles, in this order; +INDOOR = "indoor" # the indoor sensor's readings' group (current's, the live reading's): Indoor temperature, Indoor humidity +FIRST = ("Temperature", "Humidity", "Atmospheric pressure", "Rain", "UV index", "AQI") # the dashboard's first tiles, in this order; # the rest follow in their own order (the weather station's, then the air sensor's) PER_ROW = 3 # tiles to a row, up to ROWS_OF_THREE rows; more tiles: the columns that make them largest on a square ROWS_OF_THREE = 4 @@ -38,14 +45,15 @@ def call(titles=None) -> dict: def _row(gauge: Gauge | AirGauge, figures: dict) -> tuple[float | None, ...]: - """A row of a tile's table from current's figures of that period: Max and Min, Max alone, or (rain) its wettest day and Total (the - US AQI's already worked out as AQI: _aqi_entry).""" + """A row of a tile's table from current's figures of that period: Max and Min, Max alone, (wind) Max and Gust, or (rain) its wettest + day and Total (the US AQI's already worked out as AQI: _aqi_entry).""" if isinstance(gauge, AirGauge): - return figures.get("high"), figures.get("low") + return (figures.get("high"), figures.get("low")) if gauge.lowest else (figures.get("high"),) if gauge.total: return (figures.get("wettest_day") or {}).get("rain"), figures.get("total") - high = figures.get("high", figures.get("high_gust")) # (the wind's Max is its highest gust) - return (high, figures.get("low")) if gauge.lowest else (high,) + if gauge.gust: + return figures.get("high"), figures.get("high_gust") + return (figures.get("high"), figures.get("low")) if gauge.lowest else (figures.get("high"),) def _value(entry: dict, key: str = "value") -> float | None: @@ -74,6 +82,10 @@ def _tile(gauge: Gauge | AirGauge, entry: dict) -> Tile | None: """A gauge's tile from its reading's entry in current's result (the US AQI's: _aqi_entry); None when it has neither a reading nor a figure.""" now = _value(entry) + if isinstance(gauge, Gauge) and gauge.kind == "compass": # (no figures: there whenever current has the reading, dimmed with none now) + compass = (entry.get("compass") or point(now)) if now is not None else None # (the service's compass point, as it gives it) + return Tile(gauge.title, gauge.unit, now, gauge.kind, gauge.low, gauge.high, gauge.colours, (), {}, gauge.ticks, gauge.decimals, + band=compass) rows = {row: _row(gauge, entry.get(key) or {}) for row, key in ROWS.items()} if now is None and all(f is None for figures in rows.values() for f in figures): return None @@ -82,9 +94,9 @@ def _tile(gauge: Gauge | AirGauge, entry: dict) -> Tile | None: if band and entry.get("from") == "PM10": band = f"{band} (PM10)" ticks = gauge.bounds - return Tile(gauge.title, gauge.unit, now, "dial", gauge.low, gauge.high, gauge.colours, ("Max", "Min"), rows, ticks, + return Tile(gauge.title, gauge.unit, now, "dial", gauge.low, gauge.high, gauge.colours, ("Max", "Min") if gauge.lowest else ("Max",), rows, ticks, gauge.decimals, gauge.bounds, band) - columns = ("Max", "Total") if gauge.total else ("Max", "Min") if gauge.lowest else ("Max",) + columns = ("Max", "Total") if gauge.total else ("Max", "Min") if gauge.lowest else ("Max", "Gust") if gauge.gust else ("Max",) low, high, colours, ticks = scale(gauge, now) # (a thermometer's widens to take in the reading) return Tile(gauge.title, gauge.unit, now, gauge.kind, low, high, colours, columns, rows, ticks, gauge.decimals) @@ -97,14 +109,21 @@ def per_row(n: int) -> int: return max(range(4, 7), key=lambda cols: min(1 / cols, CELL_W / CELL_H / math.ceil(n / cols))) -def sheet(result: dict, titles=None) -> Dashboard | None: - """The gauges of these titles (all when None) from current's result with context, FIRST's first; None when it has none of them (an - error, the station not answering, nothing read).""" +def is_indoor(gauge: Gauge | AirGauge) -> bool: + """Is this gauge an indoor reading's (the indoor sensor's group): left out of the web page with MCP_DASHBOARD_INDOOR off.""" + return gauge.reading.split(".", 1)[0] == INDOOR + + +def sheet(result: dict, titles=None, indoor: bool = True) -> Dashboard | None: + """The gauges of these titles (all when None) from current's result with context, FIRST's first, the indoor ones only with `indoor`; + None when it has none of them (an error, the station not answering, nothing read).""" if "error" in result or STATION in (result.get("unavailable") or {}): return None sensors = result.get("sensors") or {} tiles = [] for gauge in (*gauges_of(titles), *air_gauges_of(titles)): + if not indoor and is_indoor(gauge): + continue group, name = gauge.reading.split(".", 1) entry = (sensors.get(group) or {}).get(name) if isinstance(gauge, AirGauge) and gauge.aqi and (entry is not None or "pm10" in (sensors.get(group) or {})): @@ -115,4 +134,4 @@ def sheet(result: dict, titles=None) -> Dashboard | None: return Dashboard(tiles, per_row(len(tiles))) if tiles else None -__all__ = ["AIR_GAUGES", "GAUGES", "STATUS", "call", "per_row", "sheet"] +__all__ = ["AIR_GAUGES", "GAUGES", "INDOOR", "STATUS", "call", "is_indoor", "per_row", "sheet"] diff --git a/lib/gauges.py b/lib/gauges.py index 8aaa1543..fde49657 100644 --- a/lib/gauges.py +++ b/lib/gauges.py @@ -2,7 +2,7 @@ readings now, for a chat client to send with its Status (the Telegram bot). The highs and lows are not drawn: they are in the resource's text, and in the web page's tables (lib/web_dashboard.py, which draws every gauge in the browser). -A thermometer, a dial or a rain beaker per tile (specs.Tile), `per_row` to a row, drawn on one canvas laid out in pixels (the top left +A thermometer, a dial, a rain beaker or a compass (the wind's direction: never among the Status's three, drawn all the same) per tile (specs.Tile), `per_row` to a row, drawn on one canvas laid out in pixels (the top left is 0, 0), in lib/gauge_look.py's colours and sizes (the web page draws with them too), each tile CELL_W by TILE_H. A tile with no reading is dimmed, its gauge at its floor (lib/gauge_look.py floor: the mercury at the scale's low end, the needle at its start, the beaker empty) reading the floor's number. Only ecobot-mcp draws it (the bot draws nothing). Safe to call from several threads, as @@ -13,8 +13,9 @@ from .charts import _DRAWING, _blend from .draw import PT, Canvas, arc, clip_below, rounded_rect -from .gauge_look import (BAND_WIDTH, BAR_GAP, BAR_WIDTH, BG, BULB_RADIUS, CELL_W, FADE, FILL, INK, LABEL_RADIUS, MARGIN, MERCURY_GAP, - NEEDLE, RING_OUTER, SOFT, START, SWEEP, TUBE_HALF, WATER, faded, share, shown) +from .gauge_look import (BAND_WIDTH, BAR_GAP, BAR_WIDTH, BG, BULB_RADIUS, CELL_W, COMPASS, COMPASS_BAND, COMPASS_LABEL_Y, FADE, FILL, INK, + LABEL_RADIUS, MARGIN, MERCURY_GAP, NEEDLE, POINTS, RING_OUTER, SOFT, START, SWEEP, TUBE_HALF, WATER, faded, share, + shown) from .specs import Dashboard, Tile DPI = 100 @@ -118,7 +119,38 @@ def _dial(c: Canvas, tile: Tile, ox: float, oy: float, ink): c.circle(cx, cy, 25, BG, outline=ink(SOFT), width=_lw(3)) -DRAW = {"thermometer": _thermometer, "dial": _dial, "beaker": _beaker} +def _arrow(cx: float, cy: float, reach: float, bearing: float) -> list[tuple[float, float]]: + """The compass's arrow from (cx, cy) toward `bearing` (degrees clockwise from north), its tip `reach` out: a broad barbed head on a + shaft down to the hub (as the web page's arrow()).""" + a = math.radians(bearing) + shape = [(0, reach), (17, reach - 30), (5.5, reach - 23), (5.5, 0), (-5.5, 0), (-5.5, reach - 23), (-17, reach - 30)] + return [(cx + x * math.cos(a) + y * math.sin(a), cy + x * math.sin(a) - y * math.cos(a)) for x, y in shape] + + +def _compass(c: Canvas, tile: Tile, ox: float, oy: float, ink): + """The wind's direction: a compass rose's ring with its ticks and N, E, S and W, the needle an arrow pointing where the wind comes from + (degrees clockwise from north), the reading under it ("99° E"). As the web page draws it (web_dashboard.html compass()).""" + cx, cy, r = ox + COMPASS[0], oy + COMPASS[1], COMPASS[2] + outer, inner = r - 8, r - 8 - BAND_WIDTH + c.circle(cx, cy, r, outline=ink(SOFT), width=_lw(3)) + c.polygon(_band(cx, cy, inner, outer, 360, 0.01), ink(COMPASS_BAND)) + for b in range(0, 360, 10): # (fine ticks every 10 degrees, longer every 30; none where a point's name is) + if min(b % 45, 45 - b % 45) > 5: + a = 90 - b + c.line([_polar(cx, cy, outer - 4, a), _polar(cx, cy, outer - (12 if b % 30 == 0 else 7), a)], ink(SOFT), _lw(1.5 if b % 30 else 2.2)) + for i, name in enumerate(POINTS[::2]): # N, NE, E... on the ring: the four cardinal points large, the others small + x, y = _polar(cx, cy, (outer + inner) / 2, 90 - 45 * i) + _text(c, x, y, name, 13 if i % 2 else 20, ink(SOFT if i % 2 else INK), weight="normal" if i % 2 else "bold") + value = shown(tile) % 360 + a, reach = 90 - value, inner - 8 + c.line([(cx, cy), _polar(cx, cy, -reach * 0.3, a)], _blend(ink(SOFT), 0.5, BG), _lw(2)) # (a short, thin, dim tail) + c.polygon(_arrow(cx, cy, reach, value), ink(NEEDLE)) # (the arrow: where the wind comes from) + c.circle(cx, cy, 11, BG, outline=ink(SOFT), width=_lw(2.5)) + words = f"{value:.0f}° {tile.band}" if tile.value is not None and tile.band else "–" if tile.value is None else f"{value:.0f}°" + _text(c, cx, oy + COMPASS_LABEL_Y, words, 40, ink(INK)) + + +DRAW = {"thermometer": _thermometer, "dial": _dial, "beaker": _beaker, "compass": _compass} def _tile(c: Canvas, tile: Tile, ox: float, oy: float): diff --git a/lib/irrigation/tuya.py b/lib/irrigation/tuya.py index 7643a80a..f8ec9106 100644 --- a/lib/irrigation/tuya.py +++ b/lib/irrigation/tuya.py @@ -16,6 +16,7 @@ import httpx from ..config import Config +from ..tls import ssl_context from .common import DELAYS, MAX_MINUTES, IrrigationError, is_paused # noqa: F401 (is_paused: named here too) log = logging.getLogger(__name__) @@ -34,7 +35,7 @@ class Tuya: def __init__(self, cfg: Config, transport=None): self.device = cfg.tuya_device_id self.client_id, self.secret = cfg.tuya_client_id, cfg.tuya_client_secret - self.http = httpx.AsyncClient(base_url=cfg.tuya_base_url, timeout=20, transport=transport) + self.http = httpx.AsyncClient(base_url=cfg.tuya_base_url, timeout=20, transport=transport, verify=ssl_context()) self.token = "" self.token_expires = 0.0 diff --git a/lib/mcp_server.py b/lib/mcp_server.py index de0ddaa9..0d246932 100644 --- a/lib/mcp_server.py +++ b/lib/mcp_server.py @@ -89,7 +89,7 @@ "label, unit) and the words people use for them; each source's mode and how far back its history goes; the alert " "kinds, each with its rule and thresholds; the AirGradient dashboard link. Pushed when the readings change.", None), WEATHER_URI: ("now/weather", "The weather now", "The weather station's live reading: {as_of, sensors: {sensor: {reading: {value, " - "unit, text, [emoji], [compass]}}}, lines, heading}. Pushed on each new reading (every 5 s with Home Assistant, 60 s " + "unit, text, [emoji], [compass]}}}, lines, heading}. Pushed on each new reading (polled every 30 s with Home Assistant, 60 s " "from the cloud).", "eco"), AIR_URI: ("now/air", "The air now", "The air sensor's latest reading, with each reading's rating, PM2.5's and PM10's US AQI and band (the US AQI is the higher): {as_of, " "sensors: {air: {reading: {value, unit, text, [rating], [aqi_us, band]}}}, lines, heading}. Pushed on each new reading.", @@ -503,14 +503,17 @@ def prompt(name: str, arguments: dict | None = None) -> types.GetPromptResult: def http_app(server: EcobotServer, *, tokens=(), allowed_hosts=("127.0.0.1", "localhost"), issuer_url: str = "http://127.0.0.1:8765", - path: str = "/mcp", dashboard: bool = True): + path: str = "/mcp", dashboard: bool = True, dashboard_animations: bool | str = "on", + dashboard_indoor: bool = True): """The Streamable HTTP app (Starlette) at `path`: the Host header checked against `allowed_hosts`, and, with `tokens` (AUTH_TOKENS), every request's bearer token (TokenCheck). `issuer_url` is required by the SDK with auth but unused: no OAuth metadata is published (resource_server_url=None). With `dashboard` (MCP_DASHBOARD), the gauges' live page beside it at /dashboard (lib/web_dashboard.py): - read-only, no token, any Host; `app.state.closing` ends its event streams at shutdown. Always, the chart links' pictures at + read-only, no token, any Host, its weather behind the gauges only with `dashboard_animations` on, nothing animated with "off" (MCP_DASHBOARD_ANIMATIONS); + with `dashboard_indoor` False (MCP_DASHBOARD_INDOOR off) no indoor reading on it, drawn or sent; + `app.state.closing` ends its event streams at shutdown. Always, the chart links' pictures at /charts/.png (EcobotServer.chart_picture): no token, any Host either.""" check = TokenCheck(tokens) if tokens else None - web = WebDashboard(server, (WEATHER_URI, AIR_URI)) if dashboard else None + web = WebDashboard(server, (WEATHER_URI, AIR_URI), animations=dashboard_animations, indoor=dashboard_indoor) if dashboard else None app = server.server.streamable_http_app( streamable_http_path=path, transport_security=host_settings(allowed_hosts), auth=AuthSettings(issuer_url=issuer_url, resource_server_url=None) if check else None, token_verifier=check, diff --git a/lib/pollen/source.py b/lib/pollen/source.py index ccde9b22..9b151d8f 100644 --- a/lib/pollen/source.py +++ b/lib/pollen/source.py @@ -15,6 +15,7 @@ from ..snapshots import Snapshots from ..sources import Source from ..timeutil import day_text, local_date +from ..tls import ssl_context from ..warm import Warmer, in_sync_hours from .parse import DISTRICTS, LEVEL_EMOJI, parse_melbourne_pollen @@ -41,7 +42,7 @@ class Pollen(Source): def __init__(self, cfg: Config, transport=None): self.tz, self.district, self.place = cfg.tz, _district(cfg.pollen_district), cfg.place - self.client = httpx.AsyncClient(timeout=15, headers=HEADERS, follow_redirects=True, transport=transport) + self.client = httpx.AsyncClient(timeout=15, headers=HEADERS, follow_redirects=True, transport=transport, verify=ssl_context()) self.data: dict | None = None # the parsed page self.fetched_at = 0.0 # when (epoch) self._validators: dict = {} # ETag / Last-Modified for the conditional request @@ -50,15 +51,18 @@ def __init__(self, cfg: Config, transport=None): self._load() self.warmer = Warmer(self.warm, POLLEN_REFRESH_SECONDS) - async def start(self): + async def start(self, wait: bool = True): + """From the last page fetched (kept in the file), nothing asked: the first fetch, if that one is due again, is the warm-up's + (ecobot_mcp/core.py Core.warm_up).""" + self.summary = self.describe() + + def describe(self) -> str: + """The start-up line: the levels on the page it holds, and how often it is fetched.""" if not self.in_season(): - self.summary = "Melbourne Pollen: out of season (October to December)" - return - try: - await self.warm(True) - self.summary = f"Melbourne Pollen: {'/'.join(l.split(' forecast')[0] for l in self.lines()) or 'no levels on the page'} ({self.warmer.interval:g}s)" - except Exception as e: # the site may just be briefly unreachable - log.warning("Pollen not readable yet: %s", e) + return "Melbourne Pollen: out of season (October to December)" + if self.page is None: + return f"Melbourne Pollen: no page of this season kept yet ({self.warmer.interval:g}s)" + return f"Melbourne Pollen: {'/'.join(l.split(' forecast')[0] for l in self.lines()) or 'no levels on the page'} ({self.warmer.interval:g}s)" # ---------- kept on disk ---------- def _load(self): diff --git a/lib/public_holidays.py b/lib/public_holidays.py index a5ec0918..5b17924d 100644 --- a/lib/public_holidays.py +++ b/lib/public_holidays.py @@ -20,10 +20,12 @@ def __init__(self, tz: tzinfo): region = REGIONS.get(getattr(tz, "key", "")) self.region = region self.available = bool(holidays and region) - self._calendar = holidays.country_holidays(region[0], subdiv=region[1]) if self.available else {} + self._calendar = None # built on the first name(): the package loads every country's module (~0.05 s, ~0.4 s uncompiled) def name(self, day: date) -> str | None: """The holiday's name (e.g. "Australia Day"), or None on an ordinary day.""" + if self._calendar is None: + self._calendar = holidays.country_holidays(self.region[0], subdiv=self.region[1]) if self.available else {} return self._calendar.get(day) def problem(self) -> str: diff --git a/lib/service/alerts.py b/lib/service/alerts.py index 630dfb05..81e60010 100644 --- a/lib/service/alerts.py +++ b/lib/service/alerts.py @@ -29,11 +29,9 @@ def __init__(self, sources: dict, store, alerts, cooldown_seconds: int = ALERT_C self.pollen = PollenAndAsthmaMonitor(sources["Pollen"], store, alerts) if "Pollen" in sources else None def start(self, tasks) -> list[str]: - """Start every rule but the weather's (start_weather, once the station has been read): the alert types now running.""" + """Start every rule but the station's and the air sensor's (start_weather, start_air: once each has been read): the alert types now + running.""" running = [] - if self.particulates: - tasks.start(every(CHECK_SECONDS, self.particulates.check)) - running += ParticulatesMonitor.KINDS if self.forecast: self.sources["Forecast"].warmer.after.append(self.forecast.check) # after each refresh (in the day) running += ForecastMonitor.KINDS @@ -42,6 +40,13 @@ def start(self, tasks) -> list[str]: running += PollenAndAsthmaMonitor.KINDS return running + def start_air(self, tasks, running: list[str]): + """The particulates rule, once the air sensor has been read (its start in the warm-up): checked every CHECK_SECONDS; its alert + types added to `running`.""" + if self.particulates: + tasks.start(every(CHECK_SECONDS, self.particulates.check)) + running += ParticulatesMonitor.KINDS + async def start_weather(self, running: list[str]): """The weather rules, once the station has been read: their state from the recent readings (first run), a first check, then one after every refresh, and the rain on each live reading. Their alert types go first in `running` once they are hooked up.""" diff --git a/lib/service/current.py b/lib/service/current.py index c2483bb0..96a99671 100644 --- a/lib/service/current.py +++ b/lib/service/current.py @@ -9,8 +9,8 @@ band, and its text as the report writes it; - `context` is the gauges' figures (lib/ecowitt/dashboard.py figures(), over the day rows of the year so far, lib/ecowitt/days.day_values_on, the live reading counted in for today's highs and lows), each high and low with when it happened (the - day row's own time of it, worded as weather_history words a record) and its day; rain as its totals and its wettest day, wind as its - highest gust. With no readings named, every gauge's reading the station sends now is there, those its file hasn't recorded yet (not + day row's own time of it, worded as weather_history words a record) and its day; rain as its totals and its wettest day, wind + speed as its highest and its highest gust. With no readings named, every gauge's reading the station sends now is there, those its file hasn't recorded yet (not in the catalogue: unrecorded()) too, so a client lays out the gauges (lib/gauge_sheet.py) from this result alone. The air sensor's air-quality readings (not its own temperature and humidity) have their highs and lows too, from its day rows (air_context_of: each with its day, but not its time of day), so a reading it lacks now is there with its figures alone, as the station's are. @@ -30,8 +30,8 @@ from datetime import date, datetime, tzinfo from ..airgradient.metrics import EXTRA as AIR_OWN_METRICS -from ..ecowitt.api import MINUTE, unit_text -from ..ecowitt.dashboard import GAUGES, Gauge, figures, live_value, periods_of +from ..ecowitt.api import MINUTE, NotInYet, unit_text +from ..ecowitt.dashboard import GAUGES, GUST, Gauge, figures, live_value, periods_of from ..ecowitt.days import FIELDS, PARTS, day_values_on from ..ecowitt.direction import point from ..ecowitt.extremes import describe_time @@ -52,6 +52,7 @@ HEADINGS = {STATION: "Weather station", AIR_DEVICE: "Air quality"} # the report's sections (the old lib/report.py SECTIONS) NOT_AVAILABLE = "• not available right now" # ... and a section whose device didn't answer UNAVAILABLE = {STATION: "The weather station isn't answering right now.", AIR_DEVICE: "The air sensor isn't answering right now."} +NOT_IN_YET = "The weather station's reading isn't in yet: ecobot-mcp has just started and is still finding the station." NOTHING_HELD = {STATION: "No reading of the weather station is held (and `fetch` is off).", AIR_DEVICE: "No reading of the air sensor is held (and `fetch` is off)."} PERIODS = (("Daily", "today"), ("Monthly", "month"), ("Yearly", "year")) # a gauge's rows, as the result names them @@ -285,10 +286,12 @@ def station_entry(live: dict, now: dict, reading: Reading, field: str) -> dict: # ---------- the gauges' figures (context) ---------- def gauge_of(name: str) -> Gauge | None: """The gauge a reading's context comes from: the one whose live reading it is (rainfall.rain: the Rain gauge's "daily"); the gusts - get the Wind gauge's highest, with the live gust counted in.""" + get the Wind gauge's Gust column as their highest, with the live gust counted in. None for a reading with no gauge, or whose gauge has + no figures (the wind's direction: its compass).""" if name == "wind.wind_gust": - return replace(next(g for g in GAUGES if g.live == ("wind", "wind_speed")), live=("wind", "wind_gust"), counted=None) - return next((g for g in GAUGES if g.reading == name), None) + wind = next(g for g in GAUGES if g.live == ("wind", "wind_speed")) + return replace(wind, live=GUST, highest=wind.gust, gust=None, high_hand=None) + return next((g for g in GAUGES if g.reading == name and g.highest), None) def _times_on(r: Reader, mac: str, names: list[str], days: list[date]) -> dict[str, dict[date, tuple[int, str]]]: @@ -365,16 +368,17 @@ def _extreme(key: str, value: float, figure: str, days: list[date], values: dict def context_of(name: str, live: dict, values: dict, times: dict, today: date, tz: tzinfo) -> dict: """{today, month, year} beside one reading: the figures its gauge's rows give (dashboard.figures, the live reading counted in for its highs and lows, today's rain the gauge's own reading), each high and low with when it happened and its day; rain's totals and wettest - day; wind speed's highest as `high_gust`. {} for a reading with no gauge, or none of whose figures are held.""" + day; wind speed's highest (`high`) and its highest gust (`high_gust`, the gauge's Gust column, the live gust counted in). {} for a + reading with no gauge, or none of whose figures are held.""" gauge = gauge_of(name) if gauge is None: return {} days, unit = periods_of(today), gauge.unit now = Live(live, gauge) - counted = Live(live, replace(gauge, live=gauge.counted)) if gauge.counted else now # (wind: the gust now, not the speed) + gust = Live(live, replace(gauge, live=GUST)) if gauge.gust else None # (wind: the gust now, counted into its Gust) out = {} for row, key in PERIODS: - got = figures(gauge, values, days[row], None if gauge.total else counted.value) + got = figures(gauge, values, days[row], None if gauge.total else now.value, gust.value if gust else None) if gauge.total and row == "Daily" and now.value is not None: # today's rain is the gauge's own reading (as the gauge shows it) got = (None, now.value) entry: dict = {} @@ -386,11 +390,11 @@ def context_of(name: str, live: dict, values: dict, times: dict, today: date, tz day = next(d for d in days[row] if values.get(gauge.highest, {}).get(d) == wettest) entry["wettest_day"] = {"rain": wettest, "text": _figure_text(gauge, gauge.highest, wettest, unit), "date": day_text(day)} else: - high = "high_gust" if name == "wind.wind_speed" else "high" - pairs = [(high, gauge.highest, got[0])] + ([("low", gauge.lowest, got[1])] if gauge.lowest else []) - for key_, figure, value in pairs: + pairs = [("high", gauge.highest, got[0], now)] + ([("low", gauge.lowest, got[1], now)] if gauge.lowest else []) + pairs += [("high_gust", gauge.gust, got[-1], gust)] if gauge.gust else [] + for key_, figure, value, held in pairs: if value is not None: - entry.update(_extreme(key_, value, figure, days[row], values, times, counted, gauge, unit, tz, + entry.update(_extreme(key_, value, figure, days[row], values, times, held, gauge, unit, tz, dated=row != "Daily")) if entry: out[key] = entry @@ -492,6 +496,8 @@ async def _station(self, station: list[Reading], named: bool, context: bool, met live = await self._live(station, named, meta) except NothingHeld: return Part.down(STATION, NOTHING_HELD[STATION], today) + except NotInYet: + return Part.down(STATION, NOT_IN_YET, today) except Exception as e: log.warning("current: the weather station's reading failed: %s", e) return Part.down(STATION, UNAVAILABLE[STATION], today) @@ -585,11 +591,11 @@ async def _latest(self, extras: list[str], meta: dict): if getattr(self.ctx.air, "_current", None) is None: raise NothingHeld() return await self.ctx.air.latest(extras, held=True) - return await self.ctx.air.latest(extras) + return await self.ctx.air.latest(extras, kept=True) # (just after a start, the reading kept from before it: as of its time) async def _context(self, station: list[Reading]) -> tuple[dict, dict]: """The gauges' figures for the readings that have a gauge (context_on): their day rows of the year so far, in one read.""" - names = sorted({n for r in station if (g := gauge_of(r.name)) for n in (g.highest, g.lowest) if n}) + names = sorted({n for r in station if (g := gauge_of(r.name)) for n in (g.highest, g.lowest, g.gust) if n}) if not names: return {}, {} eco = self.ctx.eco diff --git a/lib/service/summary.py b/lib/service/summary.py index d84bf84e..4f11c97a 100644 --- a/lib/service/summary.py +++ b/lib/service/summary.py @@ -210,7 +210,7 @@ def _text(value, unit: str) -> str: class _HeldOnly(Fetcher): """A Fetcher that asks Ecowitt for nothing: request _meta fetch false answers from what is held.""" - async def _fetch(self, cycle, start, end, groups): + async def _fetch(self, cycle, start, end, groups, urgency=None): return None def sibling(self, groups: list[str]) -> "Fetcher": diff --git a/lib/sources.py b/lib/sources.py index 8eae984a..3062bf73 100644 --- a/lib/sources.py +++ b/lib/sources.py @@ -22,9 +22,11 @@ def startup_lines(self) -> list[str]: return [self.summary] if self.summary else [] @abstractmethod - async def start(self): + async def start(self, wait: bool = True): """Get ready: find the device, read the first page. A failure that leaves the source of no use raises (the bot then runs - without it); one that only means "not yet" is logged, and the next refresh tries again.""" + without it); one that only means "not yet" is logged, and the next refresh tries again. wait False (ecobot-mcp's start, so the + port opens at once): nothing is asked of the network, the source starts from what the data folder kept of it, and what it would + have asked for is the warm-up's (ecobot_mcp/core.py Core.warm_up).""" @abstractmethod async def warm(self, fresh: bool = True) -> str: diff --git a/lib/specs.py b/lib/specs.py index 4f53e9dd..948721d5 100644 --- a/lib/specs.py +++ b/lib/specs.py @@ -231,17 +231,18 @@ class Tile: title: str unit: str value: float | None # now; None (no reading now) draws it dimmed, at its floor - kind: str # "thermometer", "dial" or "beaker" + kind: str # "thermometer", "dial", "beaker" or "compass" (the wind's direction: no table, its band + # the compass point, its scale 0 to 360 degrees clockwise from north) low: float # the scale's ends high: float colours: tuple[str, ...] # the scale's bands, from the low end to the high one - columns: tuple[str, ...] = () # what the table under the gauge lists: "Max", "Min" or "Total" + columns: tuple[str, ...] = () # what the table under the gauge lists: "Max", "Min", "Gust" (wind) or "Total" rows: dict[str, tuple[float | None, ...]] = field(default_factory=dict) # "Daily" / "Monthly" / "Yearly" -> a figure per column ticks: tuple[float, ...] = () # the scale's labels decimals: int = 1 bounds: tuple[float, ...] = () # the bands' edges, when each band is an equal share of the scale (the air gauges' categories); # none: the scale is even, low to high - band: str | None = None # the name of the band the reading is in, shown under it + band: str | None = None # the name of the band the reading is in, shown under it (a compass: its compass point) @dataclass diff --git a/lib/tls.py b/lib/tls.py new file mode 100644 index 00000000..ca99cb5a --- /dev/null +++ b/lib/tls.py @@ -0,0 +1,14 @@ +"""One TLS context for every HTTP client the program makes. httpx builds a new one for each client otherwise, loading certifi's +certificates each time (about 35 ms apiece, on the event loop, up to six times before the service listens).""" + +import ssl +from functools import cache + +import httpx + + +@cache +def ssl_context() -> ssl.SSLContext: + """The context httpx would make for a client of its own (certifi's certificates, or SSL_CERT_FILE / SSL_CERT_DIR when set), made + once, on first use, and shared: pass it as `verify=`.""" + return httpx.create_ssl_context() diff --git a/lib/weather.py b/lib/weather.py index c54fef85..3c206f71 100644 --- a/lib/weather.py +++ b/lib/weather.py @@ -43,7 +43,7 @@ STATION_URI, ALERTS_URI = "ecobot://station", "ecobot://alerts" # (as lib/mcp_server.py's) STATUS_URI = "ecobot://status" # the Status picture (lib/status.py) -LISTENED = (STATION_URI, ALERTS_URI) # what the bot listens to (not the live readings, pushed every few seconds) +LISTENED = (STATION_URI, ALERTS_URI) # what the bot listens to (not the live readings, pushed with each new reading) CALL_WAIT = 5.0 # how long a question's call waits for the service while it is being reached again, before it is refused BACKGROUND = "background" # request _meta priority of a call nobody waits for (lib/service/common.py): refused at once while down AIR_LINK_LABEL = "live chart" # the AirGradient dashboard link's words (lib/airgradient/source.py) diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html index f69abf98..625af027 100644 --- a/lib/web_dashboard.html +++ b/lib/web_dashboard.html @@ -1,5 +1,5 @@ - + @@ -8,7 +8,20 @@ Weather Dashboard + colours and sizes (lib/gauge_look.py, sent with the data); redrawn on each /dashboard/events event, and every minute regardless. + The tiles can be rearranged in the browser: dragged to reorder (a long press on a touch screen), hidden with their × or the + remove zone, all put back with "reset preferences"; kept in localStorage ("ecobot.dashboard.v1"), nothing sent to the server. + The units' switches beside the strip ("°C | °F", "km/h | mph", "hPa | inHg", "mm | in"): the temperatures, the wind, the + pressure and the rain (its rate with it) shown in those, converted here + (the server sends metric), kept with the preferences, metric again on "reset preferences". + A click or tap on a gauge zooms its tile (title and gauge, no table) to fill the window, a gallery paged through by keys, swipes and drags; Esc goes back. + Behind everything, the weather as pixel art on one canvas (Sky): rain, haze, uv, humidity, wind, heat and ice, each while the + readings call for it, its tile framed in red; "stop" at the bottom left stops and clears them for this page view only + (nothing saved: a reload brings them back; the link gone till then). MCP_DASHBOARD_ANIMATIONS: the server sends + data-animations="on", "low" or "off" on (lib/web_dashboard.py), for every viewer. On: all of the above. Low: the gauges + sweep and the tiles reflow as on, but no weather (no canvas drawn, no loop, no "stop", no test links) and the zoom at once. Off: + no weather, and nothing animated: the gauges' needles and readings straight at their new place, the zoom and the reflow at once, + no transition. A browser asking for reduced motion: as off, whatever the setting. The data's updates as they come in each. --> +
+ +
+
+
loading…
+ + + +
+ + diff --git a/lib/web_dashboard.py b/lib/web_dashboard.py index 99280e5d..c527778f 100644 --- a/lib/web_dashboard.py +++ b/lib/web_dashboard.py @@ -2,7 +2,8 @@ - GET /dashboard (and /dashboard/, the same page): one self-contained HTML5 page (web_dashboard.html: no framework, nothing fetched from elsewhere) whose script draws the gauges as inline SVG, with HTML titles and tables, in lib/gauge_look.py's colours and sizes, as the Status picture's PNG - (lib/gauges.py) draws its three, without the tables; its tiles laid out to fill the window, portrait or landscape; + (lib/gauges.py) draws its three, without the tables; its tiles laid out to fill the window, portrait or landscape, and arranged + in the browser (dragged to reorder, hidden, reset; kept in its localStorage by the tiles' titles, nothing told to the server); - GET /dashboard/icon.png: the page's sun (its original, at ICON_SIZE px: lib/web_dashboard_icon.png) as a file, the page's own icon (favicon and apple-touch-icon), named relative to the path the page was asked for (/dashboard: "dashboard/icon.png", /dashboard/: "icon.png"), so it is right whatever path a proxy serves the page at. A file, not a data: URI in the page, because a @@ -13,12 +14,35 @@ for it. Only link previews fetch og:image: a browser opening the page fetches nothing from elsewhere; - GET /dashboard/data: the tiles as JSON: the gauges' sheet (lib/gauge_sheet.py) from the service's `current` with context, answered from what is held (fetch off: a request never asks the station; the keep-warm keeps the live reading), as the Status picture's, each - tile's specs.Tile fields and whether it is dimmed, with the time of the reading (`as_of`) and the look; + tile's specs.Tile fields and whether it is dimmed, with the time of the reading (`as_of`: the newer of the two devices'), each + device's own (`devices`: {"station", "air"}: its reading's time, ISO in the station's zone, null with none held; a device not + configured is not there), for the strip's stalled device greyed out, the look, and the station's rain rate now + (`rain_rate`, mm/h: its rain gauge's, or its piezo gauge's where that's the one reporting, which no tile shows; null with + neither), for the page's rain behind the tiles; today's highest of the dials with a thin red hand (`today_highs`, by title, + the station's day in its zone: Wind's gust, Rain rate's, Solar radiation's, UV index's: their tiles' Daily Max, the Wind's its + Daily Gust, the reading now counted in: today_highs()), the Wind direction tile's `rose` (today's + share of the wind's direction from each of the 16 compass points, N first, clockwise, from the file's readings, calm ones left out; + [] with none: rose()), the Atmospheric pressure tile's `tendency` (its change over the past hour, for the arrow after its reading: + {"change": hPa, "way": "up", "down" or "steady"}, the file's newest reading less its reading nearest an hour before it; null with + no reading about an hour old: tendency()), and + the gust now (`gust`, km/h: over 99, a new + reading sends a cow, a barn or a chicken across behind the tiles); - GET /dashboard/events: Server-Sent Events, a `readings` event whenever the gauges' readings in the station's kept live reading or the air sensor's latest change, told by the server's own change detection for ecobot://now/weather and ecobot://now/air (EcobotServer.publish_changes: nothing is fetched for it), so the page fetches the data again and moves its gauges in place. A comment every HEARTBEAT_SECONDS keeps a proxy from closing it. +MCP_DASHBOARD_ANIMATIONS: the page served with data-animations="on", "low" or "off" on its (ANIMATIONS), for every viewer. +On: the gauges sweep to their readings, the weather drawn behind them (its canvas, "stop", the test links), the zoom and the tiles' +reflow animated. Low: the gauges sweep and the tiles reflow as on, but no weather at all (nothing drawn, no loop, no "stop" or test +links) and the zoom at once. Off: no weather, and the gauges' needles and readings straight at their new place, the zoom and the reflow +at once. A browser asking for reduced motion gets off's, whatever the setting. + +MCP_DASHBOARD_INDOOR off (privacy: the page needs no token): no indoor reading leaves the server through it. Its tiles (Indoor temperature, +Indoor humidity: any gauge of the indoor sensor's group, gauge_sheet.INDOOR) are left out of /dashboard/data's sheet, as if the station had +no indoor sensor, and /dashboard/events counts none of them in, so an indoor change alone sends no event (nor tells one happened). The bot, +the MCP tools, the Status picture and the alerts are as ever. + No token is asked for (it is the weather and air readings only) and the Host isn't checked: a browser opens it by the machine's name. The MCP endpoint keeps both. MCP_DASHBOARD off: none of the four routes is served (404). `close()` ends the open streams, so uvicorn's graceful shutdown doesn't wait on them (ecobot_mcp's Uvicorn calls it once it stops accepting connections).""" @@ -27,6 +51,8 @@ import html import json import logging +import time +from datetime import datetime from pathlib import Path from starlette.requests import Request @@ -36,8 +62,11 @@ from . import gauge_sheet from .airgradient.dashboard import AIR_GAUGES from .airgradient.metrics import value_of -from .ecowitt.dashboard import GAUGES, live_value +from .service.common import iso +from .ecowitt.dashboard import GAUGES, GUST, live_value +from .ecowitt.reads import directions_on, pressure_on from .gauge_look import look, tile_json +from .timeutil import day_bounds, local_date log = logging.getLogger(__name__) @@ -45,6 +74,8 @@ ICON = Path(__file__).with_name("web_dashboard_icon.png") # the page's sun, drawn large (its original, 534 px, at 512): WhatsApp asks 300 px, Facebook 200 ICON_NAME, ICON_SIZE = "icon.png", 512 ICON_URL = "https://raw.githubusercontent.com/robdevops/ecobot/main/lib/web_dashboard_icon.png" # og:image: ICON as GitHub serves it (https, image/png) +ANIMATIONS = 'data-animations="on"' # on the page's : "off" or "low" there as MCP_DASHBOARD_ANIMATIONS is +MOTIONS = ("on", "off", "low") PREVIEW = "" # where the page's Open Graph tags go: first in its head, before its icons (Slack reads 32 KB of it) TITLE = "Weather Dashboard" DESCRIPTION = "The weather station's and the air sensor's gauges, live." @@ -52,14 +83,78 @@ RETRY_MS = 5000 # how soon a browser connects again after its stream ends QUEUED = 4 # events waiting on a stream that isn't read: more are dropped (one says it all: fetch again) NOT_ANSWERING = "The weather station isn't answering right now." +RAIN_RATES = ("rainfall", "rainfall_piezo") # where the station's rain rate is (current's groups): its rain gauge's first, then the piezo's +ROSE_SECONDS = 60 # the wind rose (today's directions) read from the file at most this often (the data asked for again sooner: the same) +ROSE_DECIMALS = 4 # its shares rounded so +TENDENCY_TITLE = "Atmospheric pressure" # the tile with an arrow after its reading: its change over the past hour (`tendency`: tendency()) +TENDENCY_SECONDS = 60 # the past hour's pressure read from the file at most this often (as the rose) +TENDENCY_AGO = (45 * 60, 60 * 60, 75 * 60) # ... the reading it is told from: the one nearest an hour before the newest, 45 to 75 min before it +TENDENCY_READ = 90 * 60 # ... read from this long before now (the newest more than 45 min old: no reading about an hour before it read) +TENDENCY_STEADY = 0.3 # ... a change under this (hPa) either way: steady (no arrow) +RED_HANDS = {g.title: "Gust" if g.gust else "Max" for g in GAUGES if g.high_hand} # the dials with a red hand at today's highest, +# and the column of their table whose Daily figure it is (the Wind's: its highest gust) -def readings_of(live: dict | None) -> tuple | None: - """What the gauges show now of a live reading ({group: {field: {value, ...}}}): each gauge's reading, and the gust counted into the - wind's Max. None without one.""" +def readings_of(live: dict | None, indoor: bool = True) -> tuple | None: + """What the gauges show now of a live reading ({group: {field: {value, ...}}}): each gauge's reading (the wind's direction's, its + compass, too; the indoor ones only with `indoor`), those their red hands count in (the wind's: the gust, counted into its Gust too), + and the piezo gauge's rain rate (the page's rain behind the tiles). None without one.""" if not live: return None - return tuple(live_value(live, where) for g in GAUGES for where in (g.live, *([g.counted] if g.counted else []))) + gauges = [g for g in GAUGES if indoor or not gauge_sheet.is_indoor(g)] + return (*(live_value(live, where) for g in gauges for where in dict.fromkeys((g.live, *([g.high_hand] if g.high_hand else [])))), + live_value(live, ("rainfall_piezo", "rain_rate"))) # (the piezo gauge's rain rate: the page's rain, with no gauge of its own) + + +def rain_rate_of(result: dict, live: dict | None = None) -> float | None: + """The station's rain rate now (mm/h): in current's result, its rain gauge's, or, with no reading there, its piezo gauge's; then the + piezo gauge's in the station's kept live reading (`live`), which current gives only when it is named. None with none of them.""" + sensors = result.get("sensors") or {} + for group in RAIN_RATES: + try: + return float(((sensors.get(group) or {}).get("rain_rate") or {})["value"]) + except (KeyError, TypeError, ValueError): + continue + return live_value(live or {}, ("rainfall_piezo", "rain_rate")) + + +def now_of(result: dict, live: dict | None, where: tuple[str, str]) -> float | None: + """A reading of the station's now: in the kept live reading (`live`), else in current's result. None with neither.""" + got = live_value(live or {}, where) + if got is None: + try: + got = float((((result.get("sensors") or {}).get(where[0]) or {}).get(where[1]) or {})["value"]) + except (KeyError, TypeError, ValueError): + return None + return got + + +def today_highs(tiles) -> dict[str, float | None]: + """{title: today's highest} of these tiles' dials with a thin red hand (RED_HANDS: Wind's gust, Rain rate's, Solar radiation's, UV + index's): their table's Daily figure (the Max; the Wind's Gust), which current gives for the station's day in its zone with the + reading now counted in, so the hand rises with it; None with none. Nothing read for it: the sheet already holds it.""" + out = {} + for tile in tiles: + if tile.title in RED_HANDS: + daily = dict(zip(tile.columns, tile.rows.get("Daily") or ())) + out[tile.title] = daily.get(RED_HANDS[tile.title]) + return out + + +def tendency_of(readings: list[tuple[int, float]]) -> dict | None: + """The pressure's change over the past hour from readings ([(epoch, hPa)], oldest first): {"change": the newest less the reading + nearest an hour (TENDENCY_AGO) before it, hPa to a tenth, "way": "up" (risen TENDENCY_STEADY or more), "down" (fallen as much) or + "steady"}; None with no reading 45 to 75 minutes before the newest.""" + if not readings: + return None + newest, now = readings[-1] + lo, mid, hi = TENDENCY_AGO + then = [(abs(newest - mid - t), v) for t, v in readings if lo <= newest - t <= hi] + if not then: + return None + change = now - min(then, key=lambda p: p[0])[1] + way = "up" if change >= TENDENCY_STEADY - 1e-9 else "down" if change <= -TENDENCY_STEADY + 1e-9 else "steady" + return {"change": round(change, 1), "way": way} def air_readings_of(row: dict | None) -> tuple | None: @@ -72,34 +167,116 @@ def air_readings_of(row: dict | None) -> tuple | None: class WebDashboard: """The page, its data and its event streams over an EcobotServer (its service's `current`, its bus and its context); `uris` the - resources whose updates are the station's live reading's and the air sensor's (ecobot://now/weather, ecobot://now/air).""" + resources whose updates are the station's live reading's and the air sensor's (ecobot://now/weather, ecobot://now/air); + `animations` (MCP_DASHBOARD_ANIMATIONS: "on", "off" or "low"; True and False are "on" and "off") off: the page draws no weather + behind its gauges and nothing moves on it; low: no weather and the zoom at once, the gauges and the tiles moving as on. `indoor` + (MCP_DASHBOARD_INDOOR) False: no indoor reading in its data or its events.""" - def __init__(self, server, uris: tuple[str, ...] = ("ecobot://now/weather", "ecobot://now/air")): - self.server, self.uris = server, tuple(uris) + def __init__(self, server, uris: tuple[str, ...] = ("ecobot://now/weather", "ecobot://now/air"), animations: bool | str = "on", + indoor: bool = True): + self.server, self.uris, self.indoor = server, tuple(uris), bool(indoor) + self.animations = ("on" if animations else "off") if isinstance(animations, bool) else animations + if self.animations not in MOTIONS: + raise ValueError(f"animations: {animations!r} is not one of {', '.join(MOTIONS)}") self._streams: set[asyncio.Queue] = set() + self._rose: tuple[float, int, list[float]] | None = None # (when read, the day's start, its shares): rose()'s, kept ROSE_SECONDS + self._tendency: tuple[float, dict | None] | None = None # (when read, the past hour's change): tendency()'s, kept TENDENCY_SECONDS self._shown = self._readings() self.closed = False server.bus.subscribe(self._on_event) # ---------- the data ---------- async def data(self) -> dict: - """{as_of, tiles, look}, or with `unavailable` (and no tiles) when the station gives nothing. From what is held, whatever its age + """{as_of, devices, tiles, look, rain_rate, gust, today_highs}, or with `unavailable` (and no tiles) when the station gives nothing. From what is held, whatever its age (fetch off): an open request on the LAN never asks the station (the keep-warm keeps the live reading, and the events come from it).""" tool = self.server.service.get("current") result = json.loads(await tool.call(gauge_sheet.call(), {"fetch": False})) if tool else {"error": "no current"} - sheet = gauge_sheet.sheet(result) - out = {"as_of": result.get("as_of"), "tiles": [tile_json(t) for t in sheet.tiles] if sheet else [], "look": look()} + sheet = gauge_sheet.sheet(result, indoor=self.indoor) # (indoor off: no indoor tile, nothing indoor sent) + live = self._kept_live() + tiles = [tile_json(t) for t in sheet.tiles] if sheet else [] + for tile in tiles: + if tile["kind"] == "compass": # (the wind's direction: today's rose under its needle) + tile["rose"] = await self.rose() + elif tile["title"] == TENDENCY_TITLE: # (the pressure: an arrow after its reading, its past hour's way) + tile["tendency"] = await self.tendency() + out = {"as_of": result.get("as_of"), "devices": self.device_times(), "tiles": tiles, "look": look(), + "rain_rate": rain_rate_of(result, live), "gust": now_of(result, live, GUST), + "today_highs": today_highs(sheet.tiles if sheet else [])} if sheet is None: out["unavailable"] = (result.get("unavailable") or {}).get("station") or NOT_ANSWERING return out + async def rose(self) -> list[float]: + """Today's wind rose (the station's day, in its zone): the share of today's readings of the wind's direction (its 5-minute + readings and minutes in the file, calm ones left out: directions_on) from each of the 16 compass points, N first, clockwise; + [] with none (or no file, or an error reading it). Read at most every ROSE_SECONDS (and again as the day turns), else kept.""" + eco, now = self.server.ctx.eco, time.time() + start = day_bounds(local_date(int(now), self.server.ctx.zone), self.server.ctx.zone)[0] + if self._rose and self._rose[1] == start and now - self._rose[0] < ROSE_SECONDS: + return self._rose[2] + shares: list[float] = [] + if getattr(eco, "storage", None) is not None and getattr(eco, "mac", None): + try: + counts = await eco.storage.read(directions_on, eco.mac, start, int(now) + 60) + total = sum(counts) + shares = [round(n / total, ROSE_DECIMALS) for n in counts] if total else [] + except Exception as e: # (no rose drawn) + log.warning("Dashboard: couldn't read today's wind directions: %s: %s", type(e).__name__, e) + self._rose = (now, start, shares) + return shares + + async def tendency(self) -> dict | None: + """The pressure's change over the past hour (tendency_of): the file's newest reading (its 5-minute readings and the minutes they + don't cover: pressure_on, as the station keeps it, in hPa) less its reading nearest an hour before that; None with none about an + hour old (or no file, or an error reading it). Read at most every TENDENCY_SECONDS, else kept.""" + eco, now = self.server.ctx.eco, time.time() + if self._tendency and now - self._tendency[0] < TENDENCY_SECONDS: + return self._tendency[1] + got = None + if getattr(eco, "storage", None) is not None and getattr(eco, "mac", None): + try: + got = tendency_of(await eco.storage.read(pressure_on, eco.mac, int(now) - TENDENCY_READ, int(now) + 60)) + except Exception as e: # (no arrow drawn) + log.warning("Dashboard: couldn't read the past hour's pressure: %s: %s", type(e).__name__, e) + self._tendency = (now, got) + return got + + def device_times(self) -> dict[str, str | None]: + """{"station", "air"}: the time of each configured device's reading as it is held (the station's: its newest reading's own time + in the kept live reading, else when that was kept; the air sensor's: its latest row's timestamp, else when that was fetched), ISO + in the station's zone; None for one holding none. A device not configured has no entry.""" + ctx, out = self.server.ctx, {} + if ctx.eco is not None: + kept = getattr(ctx.eco, "_live", None) + at = 0 + for fields in (kept[1] if kept else {}).values(): + for obj in (fields.values() if isinstance(fields, dict) else ()): + try: + at = max(at, int(obj.get("time") or 0) if isinstance(obj, dict) else 0) + except (TypeError, ValueError): + pass + out["station"] = iso(at or kept[0], ctx.zone) if kept else None + if ctx.air is not None: + held = getattr(ctx.air, "_current", None) + at = None + if held: + try: + at = datetime.fromisoformat(str(held[0]["timestamp"]).replace("Z", "+00:00")).timestamp() + except (KeyError, TypeError, ValueError): + at = held[1] + out["air"] = iso(at, ctx.zone) if at else None + return out + + def _kept_live(self) -> dict | None: + kept = getattr(self.server.ctx.eco, "_live", None) + return kept[1] if kept else None + # ---------- the events ---------- def _readings(self): """(the station's gauges' readings, the air sensor's) as they are kept.""" try: - kept = getattr(self.server.ctx.eco, "_live", None) air = getattr(self.server.ctx.air, "_current", None) - return readings_of(kept[1] if kept else None), air_readings_of(air[0] if air else None) + return readings_of(self._kept_live(), self.indoor), air_readings_of(air[0] if air else None) except Exception as e: # (never stops the publishing) log.warning("Dashboard: couldn't read the live reading: %s: %s", type(e).__name__, e) return None @@ -159,6 +336,7 @@ def preview(self, path: str) -> str: # ---------- the routes ---------- async def page(self, request: Request): page = PAGE.read_text(encoding="utf-8").replace(PREVIEW, self.preview(request.url.path), 1) + page = page.replace(ANIMATIONS, f'data-animations="{self.animations}"', 1) return HTMLResponse(page, headers={"Cache-Control": "no-cache"}) async def icon(self, request: Request): @@ -184,4 +362,5 @@ def routes(self, path: str = "/dashboard") -> list[Route]: Route(f"{path}/events", self.events, methods=["GET"])] -__all__ = ["WebDashboard", "air_readings_of", "readings_of"] +__all__ = ["RED_HANDS", "ROSE_SECONDS", "WebDashboard", "air_readings_of", "now_of", "rain_rate_of", "readings_of", "tendency_of", + "today_highs"] diff --git a/pytest.ini b/pytest.ini index c38ecf35..198594d7 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,7 +1,8 @@ [pytest] asyncio_mode = auto testpaths = tests -# run in parallel, each worker taking the next test as it frees up (pytest-xdist 3.2+, see requirements-dev.txt); `pytest -n0` runs in one process +# run in parallel, each worker taking the next test as it frees up (pytest-xdist 3.2+, see requirements-dev.txt); `pytest -n0` runs in one process; +# `auto`: two workers a CPU (tests/conftest.py: the browser tests and many others mostly wait), the browser tests dealt out first # plain `pytest` leaves out the slow tests (tests/slow_tests.txt, scripts/slow_tests.py): `pytest -m slow` runs them, `pytest -m ""` all addopts = -n auto --dist worksteal -m "not slow" # a test that hangs fails after 60 s with every thread's stack (pytest-timeout), rather than hold the run up until it is killed diff --git a/tests/chart_samples.py b/tests/chart_samples.py index 409c3329..8b55c0cc 100644 --- a/tests/chart_samples.py +++ b/tests/chart_samples.py @@ -119,7 +119,7 @@ def two_scales() -> Chart: def _station() -> tuple[dict, dict, date]: """A live reading and the days' figures for a cool October evening, with no indoor sensor: (live, values, today).""" live = {"outdoor": {"temperature": {"value": "12.9"}, "humidity": {"value": "70"}, "dew_point": {"value": "7.6"}, "feels_like": {"value": "12.9"}}, - "pressure": {"relative": {"value": "1026.0"}}, "wind": {"wind_speed": {"value": "5"}}, + "pressure": {"relative": {"value": "1026.0"}}, "wind": {"wind_speed": {"value": "5"}, "wind_direction": {"value": "99"}}, "rainfall": {"daily": {"value": "0.2"}, "rain_rate": {"value": "0"}}, "solar_and_uvi": {"solar": {"value": "0"}, "uvi": {"value": "0"}}} today = date(2026, 10, 27) days = {d: i for i, d in enumerate((today - timedelta(days=n) for n in range(300)))} diff --git a/tests/conftest.py b/tests/conftest.py index 5fe0c254..d9f86740 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,6 +5,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) os.environ.setdefault("TZ", "Australia/Melbourne") +import time # noqa: E402 +time.tzset() # (in this process too, not only in the workers it starts: `-n0`'s hour-named archive is the hour the workers name) from tests import clocks # noqa: E402 (ECOBOT_CLOCK: the whole suite at another time; before anything of lib/ is imported) CLOCK = clocks.install() @@ -24,11 +26,72 @@ @pytest.hookimpl(tryfirst=True) # (before -m deselects by the marks) def pytest_collection_modifyitems(items): """The slow tests (tests/slow_tests.txt, every parameter of one) marked `slow`: plain `pytest` leaves them out (pytest.ini). Then the - files with the slowest tests go first, so with several workers (pytest-xdist) none is left running one of them at the end.""" + files with the slowest tests go first, so with several workers (pytest-xdist) none is left running one of them at the end; and the + browser's (BROWSER) dealt out ahead of them, one at the head of each worker's share: the zoom's (ZOOM_TIMED) first, so they run + together at the start, before any of the weather's pages (theirs drawing every frame, some on a fast clock) are open to slow the + zoom's start on a busy machine.""" for item in items: if item.nodeid.split("[")[0] in SLOW: item.add_marker(pytest.mark.slow) items.sort(key=lambda item: (item.path.name not in HEAVY, HEAVY.index(item.path.name) if item.path.name in HEAVY else 0)) + deal_out(items, sorted((item for item in items if browser_test(item)), key=lambda item: not zoom_timed(item))) + + +def pytest_xdist_auto_num_workers(config): + """`-n auto` (pytest.ini): twice as many workers as there are CPUs. The browser's tests mostly wait on the page (its animations, a + long press, a swipe's end), and many of the rest on a server, a subprocess or a timeout, so a worker in one leaves its CPU mostly free + for the extra workers' tests (on 4 CPUs: 8 workers, about 4 s sooner than 6 as measured; 10, no sooner, more CPU).""" + return max(2, (os.cpu_count() or 1) * 2) + + +BROWSER = "test_web_dashboard.py" # its slow tests drive the page in Chromium: seconds each, mostly waiting on the page + + +def browser_test(item) -> bool: + return item.path.name == BROWSER and item.nodeid.split("[")[0] in SLOW + + +# The browser's zoom tests: two time the zoom's 200 ms (within 330 ms, on its animations' own timeline), all of them follow its frames +ZOOM_TIMED = ("test_a_click_on_a_gauge_zooms_", "test_zoomed_the_last_tile_", "test_a_double_click_esc_", "test_zoomed_the_gallery_") + + +def zoom_timed(item) -> bool: + return item.name.startswith(ZOOM_TIMED) + + +_niced = False + + +def pytest_runtest_setup(item): + """With several workers, a worker done with its browser tests (dealt out first) runs the rest at a lower priority (nice 10, for + good: a process can't raise its own again), so the pages still being driven, whose tests time their animations frame by frame, + get a CPU when they ask while the others keep every CPU busy. The run takes as long; only who waits changes.""" + global _niced + if not _niced and not browser_test(item) and os.environ.get("PYTEST_XDIST_WORKER") and hasattr(os, "nice"): + os.nice(10) + _niced = True + + +def deal_out(items: list, first: list) -> None: + """`first` dealt out across the workers (as many as there are CPUs), one at the head of each worker's share of the run in turn, the + rest after them: so they start together, each on its own worker, rather than queue on one. (pytest-xdist's worksteal gives each worker a run of the list + as it starts, the first len // workers to the first and so on, and a worker with nothing left takes from the end of another's.)""" + workers = int(os.environ.get("PYTEST_XDIST_WORKER_COUNT", "0")) # (set in each worker; all of them collect the same order) + if workers < 2 or not first: + return + taken = set(map(id, first)) + rest = [item for item in items if id(item) not in taken] + shares, left = [], len(items) + for w in range(workers): # (each share's length, as worksteal cuts them) + shares.append(left // (workers - w)) + left -= shares[-1] + browsers = min(workers, os.cpu_count() or 1) # (no more pages driven at once than there are CPUs: their timings stay true) + heads = [first[w::browsers] for w in range(browsers)] + [[]] * (workers - browsers) + out = [] + for size, head in zip(shares, heads): + out += head + rest[:size - len(head)] + rest = rest[size - len(head):] + items[:] = out + rest @pytest.fixture(autouse=True) @@ -56,6 +119,14 @@ def the_log_levels_as_they_were(): logging.getLogger(name).setLevel(level) +@pytest.fixture +def ha_states_unshared(monkeypatch): + """Home Assistant's /api/states asked afresh each time (lib/ecowitt/homeassistant.py STATES_SHARE_SECONDS 0; a request already out + is still shared): for the tests whose fake Home Assistant changes what it says from one request to the next, a few ms apart.""" + from lib.ecowitt import homeassistant + monkeypatch.setattr(homeassistant, "STATES_SHARE_SECONDS", 0) + + @pytest.fixture def alert_state(tmp_path): """The bot's chats and settings (an AlertState) in a file of the test's own: what a Bot is given, as in the running bot.""" diff --git a/tests/fakes.py b/tests/fakes.py index 8dc4a0ff..82bc7bf7 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -55,14 +55,18 @@ def gauges_result(live: dict, values: dict, today, air: dict | None = None, air_ import json from lib.airgradient.metrics import pm25_aqi from lib.ecowitt.dashboard import GAUGES, live_value + from lib.ecowitt.direction import point from lib.series import AIR from lib.service.current import air_context_of, air_entry, context_of sensors: dict = {} for gauge in GAUGES: value, beside = live_value(live, gauge.live), context_of(gauge.reading, live, values, {}, today, TZ) - if value is not None or beside: + sent = gauge.live[1] in (live.get(gauge.live[0]) or {}) # (the compass, with no figures: there whenever the station sends it) + if value is not None or beside or (gauge.kind == "compass" and sent): group, name = gauge.reading.split(".", 1) sensors.setdefault(group, {})[name] = {"value": value, "unit": gauge.unit, **beside} + if gauge.kind == "compass" and value is not None: # (as station_entry gives the wind's direction: its compass point) + sensors[group][name]["compass"] = point(value) for column, metric in AIR.items() if air is not None or air_values else (): entry = dict((air or {}).get(column) or {}) now = entry.get("value") diff --git a/tests/slow_tests.txt b/tests/slow_tests.txt index 533a8c00..dbbbf33b 100644 --- a/tests/slow_tests.txt +++ b/tests/slow_tests.txt @@ -56,5 +56,25 @@ tests/test_startup.py::test_a_failed_first_refresh_does_not_stop_the_alerts_or_t tests/test_startup.py::test_ecobot_mcp_starts_warms_archives_and_shuts_down_cleanly tests/test_startup.py::test_main_starts_as_ecobot_mcps_client_and_shuts_down_cleanly tests/test_startup.py::test_the_weather_alerts_that_could_not_start_are_named_as_not_running +tests/test_web_dashboard.py::test_a_click_on_a_gauge_zooms_its_tile_to_fill_the_window_the_tile_beside_it_live_and_the_keys_page +tests/test_web_dashboard.py::test_a_double_click_esc_the_bounce_cut_short_the_keyboard_and_esc_mid_zoom +tests/test_web_dashboard.py::test_a_flash_flood_fills_the_window_a_quarter_up_its_surface_choppy_what_falls_ending_at_it_and_a_frog_now_and_then +tests/test_web_dashboard.py::test_a_gust_over_99_kmh_blows_a_cow_a_barn_or_a_chicken_across_far_behind_the_tiles tests/test_web_dashboard.py::test_a_tile_with_no_reading_is_dimmed_at_its_floor_and_a_reading_coming_brightens_it_and_moves_it_up_in_place +tests/test_web_dashboard.py::test_effects_asked_for_as_the_page_opens_alone_on_a_phone_and_with_reduced_motion +tests/test_web_dashboard.py::test_heavy_humidity_alone_costs_no_more_as_its_trails_build_up_and_its_sweep_is_capped +tests/test_web_dashboard.py::test_heavy_rain_with_wind_and_haze_keeps_to_the_shared_particle_budget_and_is_cheap +tests/test_web_dashboard.py::test_the_haze_alone_in_each_band_clouds_dithered_lit_from_above_drifting_with_the_wind +tests/test_web_dashboard.py::test_the_ice_grown_all_the_way_in_is_cheap_with_its_frost_across_the_glass +tests/test_web_dashboard.py::test_fewer_tiles_grow_evenly_to_fill_the_window_and_never_shrink_below_the_full_dashboards_size +tests/test_web_dashboard.py::test_on_a_touch_screen_a_long_press_picks_a_tile_up_and_a_tap_or_a_swipe_is_left_alone +tests/test_web_dashboard.py::test_on_a_touch_screen_a_tap_zooms_a_swipe_pages_from_anywhere_and_a_tap_goes_back_where_the_page_was +tests/test_web_dashboard.py::test_several_effects_share_one_canvas_behind_the_see_through_tiles_zoomed_too tests/test_web_dashboard.py::test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overflow_and_no_console_error +tests/test_web_dashboard.py::test_the_temporary_test_links_turn_each_effect_on_and_stop_animation_ends_them_and_with_animations_off_nothing_is_drawn +tests/test_web_dashboard.py::test_the_weather_behind_the_tiles_comes_with_its_reading_at_its_mark_and_frames_its_tile_in_red +tests/test_web_dashboard.py::test_stop_animation_stops_and_clears_for_this_page_view_only_nothing_saved_a_reload_or_a_test_link_runs_them_again +tests/test_web_dashboard.py::test_tiles_are_dragged_to_reorder_hidden_by_the_x_or_the_remove_zone_kept_across_reloads_and_reset +tests/test_web_dashboard.py::test_zoomed_the_gallery_pages_by_mouse_drags_and_a_trackpads_swipes_springing_back_at_the_first +tests/test_web_dashboard.py::test_zoomed_the_last_tile_stops_paging_its_text_is_selectable_a_click_goes_back_and_a_single_tile_zooms_too +tests/test_web_dashboard.py::test_a_phone_or_tablet_turned_and_turned_back_lays_the_page_out_exactly_as_a_fresh_load_with_no_zoom_or_overflow diff --git a/tests/test_air_hass.py b/tests/test_air_hass.py index c5ebe3cd..bb295d80 100644 --- a/tests/test_air_hass.py +++ b/tests/test_air_hass.py @@ -5,6 +5,7 @@ from datetime import datetime, timezone import httpx +import pytest from lib.airgradient import AirGradient from lib.airgradient.homeassistant import checked, entity_ids, find_prefix, ranges @@ -12,6 +13,8 @@ from lib.timeutil import naive_local from tests.fakes import air_transport, config +pytestmark = pytest.mark.usefixtures("ha_states_unshared") # (its fake Home Assistant changes between requests) + PREFIX = "sensor.open_air_" @@ -82,6 +85,7 @@ async def air_with(tmp_path, fake): transport, _ = air_transport(rows_per_day=288) air = AirGradient(config(tmp_path), transport=transport, ha=HomeAssistant("http://ha", "tok", httpx.MockTransport(fake))) await air.start() + await air.settle() # (the rest of its start, in the warm-up: Home Assistant's entities of it, the cloud's name for it) return air diff --git a/tests/test_airgradient.py b/tests/test_airgradient.py index 99f70538..979c640f 100644 --- a/tests/test_airgradient.py +++ b/tests/test_airgradient.py @@ -108,6 +108,19 @@ async def test_warm_summary(tmp_path): await air.close() +async def test_the_warm_right_after_start_does_not_fetch_the_current_reading_again(tmp_path): + from lib.airgradient.source import JUST_FETCHED_SECONDS + air, calls = await make(tmp_path) + assert calls.count("current") == 1 + await air.warm(True) # (start fetched it a moment ago) + assert calls.count("current") == 1 + row, at = air._current + air._current = (row, at - JUST_FETCHED_SECONDS - 1) + await air.warm(True) # older than that: a timed refresh fetches it + assert calls.count("current") == 2 + await air.close() + + async def test_history_is_capped_at_14_days(tmp_path): air, _ = await make(tmp_path) out = json.loads(await engines.air_history(air, {"start_date": "2026-01-01 00:00:00", "chart": False, "end_date": "2026-03-01 00:00:00"})) diff --git a/tests/test_airgradient_local.py b/tests/test_airgradient_local.py index a19f63bc..16e0b9d9 100644 --- a/tests/test_airgradient_local.py +++ b/tests/test_airgradient_local.py @@ -77,10 +77,13 @@ async def test_the_air_source_uses_the_device_and_the_clouds_name_and_falls_back air = AirGradient(config(tmp_path, airgradient_local_url=URL), transport=transport) up = [True] air.local, _ = sensor(lambda request: httpx.Response(200, json=DEVICE) if up[0] else httpx.Response(500)) - await air.start() + await air.start(wait=False) # (ecobot-mcp's: nothing asked of the network) + assert calls == [] and air.startup_lines() == [] and air._current is None and not air.local.address # nothing kept yet + await air.settle() # (its start, in the warm-up) reading = (await air.latest()).reading assert reading["sensor"] == "Outdoor" and reading["pm2_5"]["value"] == 2.5 and reading["pm10"]["value"] == 6.0 # the device's figures - assert calls.count("current") == 1 # the cloud was asked once, at start, for the name + assert calls.count("current") == 1 # the cloud was asked once, after start, for the name + assert air.startup_lines()[0].startswith("AirGradient: 'Outdoor' (42): ") and "/cloud (60s)" in air.startup_lines()[0] up[0] = False reading = (await air.latest()).reading # (the reading is reused for a few minutes) assert reading["pm2_5"]["value"] == 2.5 diff --git a/tests/test_bot.py b/tests/test_bot.py index d73e199e..4dc09dc5 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -184,9 +184,11 @@ async def test_a_private_chat_shows_a_thinking_draft_that_streams_the_answer_the async def test_an_idle_draft_is_refreshed_before_telegram_drops_it(serve, alert_state, monkeypatch): monkeypatch.setattr("lib.bot.DRAFT_REFRESH_SECONDS", 0.02) - class Slow: - async def run(self, *a, on_text=None, **k): - await asyncio.sleep(0.15) + class Slow: # (idle, no text, till four drafts have gone out: waited on, at most 5 s, not slept a fixed 0.15 s that a busy machine's + async def run(self, *a, on_text=None, **k): # load can leave too short for them) + deadline = asyncio.get_running_loop().time() + 5 + while len(bot.drafts) < 4 and asyncio.get_running_loop().time() < deadline: + await asyncio.sleep(0.01) return "ok" bot = DraftBot() await ask_private(serve, alert_state, Slow(), bot) diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 5436e947..40d173d8 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -275,7 +275,8 @@ def day(w, d, low, high, band): "humidity": {"value": 94, "unit": "%", "text": "94 %", "today": {"high": 94, "low": 60}}}, "rainfall": {"rain": {"value": 6.3, "unit": "mm", "text": "6.3 mm", "today": {"total": 6.3}, "month": {"total": 49.8, "wettest_day": {"rain": 20.1}}, "year": {"total": 400.2, "wettest_day": {"rain": 41.0}}}}, - "wind": {"wind_speed": {"value": 14, "unit": "km/h", "today": {"high_gust": 31.0}}}, + "wind": {"wind_speed": {"value": 14, "unit": "km/h", "today": {"high": 18.0, "high_gust": 31.0}}, + "wind_direction": {"value": 99, "unit": "°", "text": "99°", "compass": "E"}}, "indoor": {"temperature": {"value": None, "unit": "°C", "year": {"high": 30.0, "low": 12.0}}}, # no reading now: dimmed "solar_and_uvi": {"uvi": {"value": None, "unit": ""}}}, # nothing at all: left out "lines": {"station": []}, "headings": {"station": "Weather station"}} @@ -285,13 +286,15 @@ def test_the_gauges_sheet_is_drawn_from_currents_readings_and_their_context(): from lib import gauge_sheet sheet = gauge_sheet.sheet(GAUGE_RESULT) tiles = {t.title: t for t in sheet.tiles} - assert list(tiles) == ["Temperature", "Humidity", "Rain", "Wind", "Indoor temperature"] # the dashboard's order (FIRST, then GAUGES') + assert list(tiles) == ["Temperature", "Humidity", "Rain", "Wind", "Wind direction", "Indoor temperature"] # the dashboard's order + # (FIRST, then GAUGES') t = tiles["Temperature"] assert (t.value, t.unit, t.kind, t.columns) == (12.3, "°C", "thermometer", ("Max", "Min")) assert t.rows == {"Daily": (14.0, 9.5), "Monthly": (21.0, 4.0), "Yearly": (38.0, -1.0)} assert tiles["Humidity"].value == 94.0 and isinstance(tiles["Humidity"].value, float) # as the station's reading was read assert tiles["Humidity"].rows["Monthly"] == (None, None) - assert tiles["Wind"].rows == {"Daily": (31.0,), "Monthly": (None,), "Yearly": (None,)} # its highest gust + assert tiles["Wind"].columns == ("Max", "Gust") # its highest speed, and gust where + assert tiles["Wind"].rows == {"Daily": (18.0, 31.0), "Monthly": (None, None), "Yearly": (None, None)} # Min usually is assert tiles["Rain"].rows == {"Daily": (None, 6.3), "Monthly": (20.1, 49.8), "Yearly": (41.0, 400.2)} assert tiles["Indoor temperature"].value is None and tiles["Indoor temperature"].rows["Yearly"] == (30.0, 12.0) status = gauge_sheet.sheet(GAUGE_RESULT, STATUS_TITLES) @@ -336,16 +339,16 @@ async def test_a_station_that_gives_nothing_sends_its_report_without_gauges(serv def test_the_air_gauges_scales_and_bands_are_the_epas_and_the_us_co2_guidance(): from lib.airgradient.dashboard import AIR_GAUGES, EPA, EPA_NAMES g = {x.title: x for x in AIR_GAUGES} - assert list(g) == ["US AQI", "PM2.5", "PM10", "PM1", "CO₂", "VOC index", "NOx index"] # no own temperature + assert list(g) == ["AQI", "PM2.5", "PM10", "PM1", "CO₂", "VOC index", "NOx index"] # no own temperature assert (g["PM1"].bounds, g["PM1"].colours, g["PM1"].names) == (g["PM2.5"].bounds, g["PM2.5"].colours, g["PM2.5"].names) # PM2.5's bands assert EPA == ("#00E400", "#FFFF00", "#FF7E00", "#FF0000", "#8F3F97", "#7E0023") assert EPA_NAMES == ("Good", "Moderate", "Unhealthy for Sensitive Groups", "Unhealthy", "Very Unhealthy", "Hazardous") - assert g["US AQI"].bounds == (0, 50, 100, 150, 200, 300, 500) and g["US AQI"].colours == EPA and g["US AQI"].aqi + assert g["AQI"].bounds == (0, 50, 100, 150, 200, 300, 500) and g["AQI"].colours == EPA and g["AQI"].aqi assert g["PM2.5"].bounds == (0, 9.0, 35.4, 55.4, 125.4, 225.4, 325.4) and g["PM2.5"].colours == EPA # the 2024 breakpoints assert g["PM10"].bounds == (0, 54, 154, 254, 354, 424, 604) and g["PM10"].colours == EPA assert g["CO₂"].bounds == (400, 800, 1000, 1500, 2000, 2500) for title, readings in { - "US AQI": ((0, 0), (50, 0), (51, 1), (100, 1), (101, 2), (150, 2), (151, 3), (200, 3), (201, 4), (300, 4), (301, 5), (480, 5)), + "AQI": ((0, 0), (50, 0), (51, 1), (100, 1), (101, 2), (150, 2), (151, 3), (200, 3), (201, 4), (300, 4), (301, 5), (480, 5)), "PM2.5": ((0, 0), (9.0, 0), (9.1, 1), (35.4, 1), (35.5, 2), (55.4, 2), (55.5, 3), (125.4, 3), (125.5, 4), (225.4, 4), (225.5, 5), (500, 5)), "PM10": ((54, 0), (55, 1), (154, 1), (155, 2), (254, 2), (255, 3), (354, 3), (355, 4), (424, 4), (425, 5), (700, 5))}.items(): @@ -366,21 +369,27 @@ def air_result(latest: dict | None, air_values: dict | None = None) -> dict: def test_the_air_sensors_tiles_come_after_the_stations_with_their_aqi_bands_and_figures(): - from lib.airgradient.metrics import pm10_aqi, pm25_aqi + from lib.airgradient.metrics import pm25_aqi latest = {"pm2_5": {"value": 40.0, "unit": "µg/m³"}, "pm10": {"value": 60.0, "unit": "µg/m³"}, "pm1": {"value": 20.0, "unit": "µg/m³"}, "co2": {"value": 1200, "unit": "ppm"}} values = {"pm2_5_max": {date(2026, 10, 2): 70.0, TODAY: 30.0}, "pm2_5_min": {TODAY: 5.0}, "co2_max": {TODAY: 900}, "co2_min": {TODAY: 410}} sheet = gauge_sheet.sheet(air_result(latest, values)) tiles = {t.title: t for t in sheet.tiles} - assert list(tiles) == ["Temperature", "US AQI", "PM2.5", "PM10", "PM1", "CO₂"] # no VOC nor NOx sent: left out - aqi = tiles["US AQI"] + assert list(tiles) == ["Temperature", "AQI", "PM2.5", "PM10", "PM1", "CO₂"] # no VOC nor NOx sent: left out + aqi = tiles["AQI"] assert (aqi.value, aqi.band, aqi.kind, aqi.low, aqi.high, aqi.columns) == (pm25_aqi(40.0)[0], "Unhealthy for Sensitive Groups", "dial", - 0, 500, ("Max", "Min")) - assert aqi.rows["Daily"] == (pm25_aqi(40.0)[0], pm10_aqi(60.0)[0]) and aqi.rows["Monthly"][0] == pm25_aqi(70.0)[0] # (the higher of each) + 0, 500, ("Max",)) + assert aqi.rows["Daily"] == (pm25_aqi(40.0)[0],) and aqi.rows["Monthly"] == (pm25_aqi(70.0)[0],) # (the higher of each; no Min) assert aqi.ticks == aqi.bounds == (0, 50, 100, 150, 200, 300, 500) pm = tiles["PM2.5"] - assert (pm.value, pm.band, pm.decimals, pm.rows["Monthly"]) == (40.0, "Unhealthy for Sensitive Groups", 1, (70.0, 5.0)) + assert (pm.value, pm.band, pm.decimals, pm.rows["Monthly"]) == (40.0, "Unhealthy for Sensitive Groups", 1, (70.0,)) assert (tiles["PM10"].band, tiles["CO₂"].band, tiles["CO₂"].rows["Daily"]) == ("Moderate", "Poor", (1200.0, 410.0)) + # the US AQI's and the particles' tables: their Max alone, as the UV index's; the rest a Min beside their Max + from tests.chart_samples import _air, _station + live, days, today = _station() + columns = {t.title: t.columns for t in gauge_sheet.sheet(gauges_result(live, days, today, *_air(today))).tiles} + assert {t for t, c in columns.items() if c == ("Max",)} == {"AQI", "PM2.5", "PM10", "PM1", "UV index", "Rain rate", "Solar radiation"} + assert columns["CO₂"] == columns["Temperature"] == ("Max", "Min") and all(len(r) == len(t.columns) for t in sheet.tiles for r in t.rows.values()) assert [t.title for t in gauge_sheet.sheet(air_result(None)).tiles] == ["Temperature"] # no air sensor: no air gauges @@ -392,13 +401,13 @@ def test_the_aqi_and_pm25_tiles_name_the_band_their_needle_is_in_on_a_rise(): from lib.gauge_look import share latest = {"pm2_5": {"value": 40.0, "unit": "µg/m³", "aqi_us": pm25_aqi(8.0)[0], "band": "good"}} # (as latest() gives it after 8.0) tiles = {t.title: t for t in gauge_sheet.sheet(air_result(latest)).tiles} - aqi, pm = tiles["US AQI"], tiles["PM2.5"] + aqi, pm = tiles["AQI"], tiles["PM2.5"] assert (aqi.value, aqi.band, pm.value, pm.band) == (pm25_aqi(40.0)[0], "Unhealthy for Sensitive Groups", 40.0, "Unhealthy for Sensitive Groups") assert 2 / 6 <= share(pm, pm.value) < 3 / 6 and 2 / 6 <= share(aqi, aqi.value) < 3 / 6 # both needles in the orange band for value in (4.0, 9.1, 20.0, 35.5, 45.0, 55.5, 90.0, 125.5, 175.0, 225.5, 300.0): # each band, and just over each edge tiles = {t.title: t for t in gauge_sheet.sheet(air_result({"pm2_5": {"value": value, "unit": "µg/m³"}})).tiles} - pm, aqi = tiles["PM2.5"], tiles["US AQI"] + pm, aqi = tiles["PM2.5"], tiles["AQI"] assert pm.band == aqi.band == EPA_NAMES[min(int(share(pm, value) * 6), 5)] == EPA_NAMES[min(int(share(aqi, aqi.value) * 6), 5)] @@ -407,13 +416,13 @@ def test_the_us_aqi_is_the_higher_of_pm25s_and_pm10s_and_says_when_pm10_sets_it( PM10 sets it. PM2.5 the higher: its band alone, as ever. PM10 with no PM2.5 still gives a US AQI.""" from lib.airgradient.metrics import pm10_aqi, pm25_aqi dust = {"pm2_5": {"value": 5.0, "unit": "µg/m³"}, "pm10": {"value": 200.0, "unit": "µg/m³"}} - aqi = {t.title: t for t in gauge_sheet.sheet(air_result(dust)).tiles}["US AQI"] + aqi = {t.title: t for t in gauge_sheet.sheet(air_result(dust)).tiles}["AQI"] assert (aqi.value, aqi.band) == (pm10_aqi(200.0)[0], "Unhealthy for Sensitive Groups (PM10)") smoke = {"pm2_5": {"value": 40.0, "unit": "µg/m³"}, "pm10": {"value": 50.0, "unit": "µg/m³"}} - aqi = {t.title: t for t in gauge_sheet.sheet(air_result(smoke)).tiles}["US AQI"] + aqi = {t.title: t for t in gauge_sheet.sheet(air_result(smoke)).tiles}["AQI"] assert (aqi.value, aqi.band) == (pm25_aqi(40.0)[0], "Unhealthy for Sensitive Groups") alone = {t.title: t for t in gauge_sheet.sheet(air_result({"pm10": {"value": 60.0, "unit": "µg/m³"}})).tiles} - assert (alone["US AQI"].value, alone["US AQI"].band) == (pm10_aqi(60.0)[0], "Moderate (PM10)") + assert (alone["AQI"].value, alone["AQI"].band) == (pm10_aqi(60.0)[0], "Moderate (PM10)") def test_a_tile_with_no_reading_is_dimmed_at_its_floor_in_its_json(): @@ -424,7 +433,7 @@ def test_a_tile_with_no_reading_is_dimmed_at_its_floor_in_its_json(): {"humidity_max": {TODAY: 80.0}, "humidity_min": {TODAY: 50.0}, "pressure_max": {TODAY: 1020.0}}, TODAY, latest, values)) tiles = {t.title: t for t in sheet.tiles} - humidity, co2, aqi = tiles["Humidity"], tiles["CO₂"], tiles["US AQI"] + humidity, co2, aqi = tiles["Humidity"], tiles["CO₂"], tiles["AQI"] assert humidity.value is None and co2.value is None and co2.band is None # figures, no reading now assert (floor(humidity), floor(co2), floor(tiles["Atmospheric pressure"]), floor(aqi)) == (0, 400, 950, 0) assert shown(co2) == 400 and share(co2, shown(co2)) == 0 and share(humidity, 0) == 0 @@ -461,3 +470,31 @@ def test_the_png_draws_a_tile_with_no_reading_as_its_floor_dimmed(): mean, worst = sum(i * n for i, n in enumerate(off)) / sum(off), max(i for i, n in enumerate(off) if n) assert mean < 0.15 and worst <= 20, (tile.title, mean, worst) # (but the edges' anti-aliasing; the gauge anywhere else: 80+) assert bright.getdata() != dimmed.getdata() + + +def test_the_winds_direction_is_a_compass_with_no_table_its_point_the_services_dimmed_with_no_reading_and_drawn_in_the_png_too(): + """A compass right after Wind: the station's wind_direction in degrees (where the wind comes from), its band the compass point the + service gives with it, no table (highs and lows of a direction mean nothing; current gives it no figures: gauge_of has none). There + whenever current has the reading, dimmed with no value now; never among the Status's three, but the PNG draws it all the same.""" + from lib import gauge_sheet + from lib.gauge_look import faded, floor, tile_json + from lib.service.current import gauge_of + tile = next(t for t in gauge_sheet.sheet(GAUGE_RESULT).tiles if t.title == "Wind direction") + assert (tile.kind, tile.value, tile.unit, tile.band, tile.low, tile.high, tile.decimals) == ("compass", 99.0, "°", "E", 0, 360, 0) + assert tile.columns == () and tile.rows == {} and not faded(tile) and floor(tile) == 0 + assert tile_json(tile)["columns"] == [] and tile_json(tile)["rows"] == {} + north = {**GAUGE_RESULT["sensors"]["wind"]["wind_direction"], "value": 350, "compass": "N"} # (as the service names it) + sensors = {**GAUGE_RESULT["sensors"], "wind": {"wind_direction": north}} + assert next(t for t in gauge_sheet.sheet({"sensors": sensors}).tiles if t.kind == "compass").band == "N" + gone = {**GAUGE_RESULT["sensors"], "wind": {"wind_direction": {"value": None, "unit": "°"}}} + dim = next(t for t in gauge_sheet.sheet({"sensors": gone}).tiles if t.kind == "compass") + assert dim.value is None and dim.band is None and faded(dim) # no reading: dimmed, no point claimed + absent = {**GAUGE_RESULT["sensors"], "wind": {}} + assert all(t.kind != "compass" for t in gauge_sheet.sheet({"sensors": absent}).tiles) # not sent at all: left out + assert "Wind direction" not in STATUS_TITLES and all(t.kind != "compass" for t in gauge_sheet.sheet(GAUGE_RESULT, STATUS_TITLES).tiles) + assert gauge_of("wind.wind_direction") is None and gauge_of("wind.wind_speed").title == "Wind" # (no figures beside it) + picture = Image.open(io.BytesIO(gauges.render(Dashboard([tile, dim], 2)))).convert("RGB") + assert picture.size[0] > 900 + left, right = picture.crop((0, 0, picture.size[0] // 2, picture.size[1])), picture.crop((picture.size[0] // 2, 0, picture.size[0], picture.size[1])) + blue = lambda im: sum(1 for r, g, b in im.getdata() if b > 150 and b > r + 60) # (the needle's head) + assert blue(left) > 200 and blue(right) == 0 # dimmed: its colours faded diff --git a/tests/test_days.py b/tests/test_days.py index eba12a3e..ec272989 100644 --- a/tests/test_days.py +++ b/tests/test_days.py @@ -224,6 +224,22 @@ async def test_a_missing_holidays_package_is_explained_not_guessed(station, monk assert "pip install holidays" in out["error"] +def test_the_holiday_calendar_is_built_on_first_use_not_by_the_start_up_check(monkeypatch): + """Ecowitt's start asks problem(): only whether the package is there and the time zone has a region. Building the calendar loads + every country's module (most of a second where the image has no bytecode for them), so it waits for the first holiday question.""" + from datetime import date + from lib import public_holidays as calendar + built = [] + real = calendar.holidays.country_holidays + monkeypatch.setattr(calendar.holidays, "country_holidays", lambda *a, **k: built.append(a) or real(*a, **k)) + melbourne = calendar.PublicHolidays(TZ) + assert melbourne.problem() == "" and melbourne.available and built == [] + assert melbourne.name(date(2026, 12, 25)) == "Christmas Day" and melbourne.name(date(2026, 12, 23)) is None + assert built == [("AU",)] # once, for the station's state + monkeypatch.setattr(calendar, "holidays", None) + assert "pip install holidays" in calendar.PublicHolidays(TZ).problem() + + async def test_one_known_day_can_be_looked_up_with_no_conditions(station): """'Did it rain on Sat 5 Sep?': the day's own figures, not a search of the month that says nothing about it.""" eco, _ = station diff --git a/tests/test_ecowitt.py b/tests/test_ecowitt.py index 38f58959..ad52e4f7 100644 --- a/tests/test_ecowitt.py +++ b/tests/test_ecowitt.py @@ -253,6 +253,14 @@ async def watch(path, urgent=False, **params): assert marked and not any(marked) # a chart drawn ahead: nobody is waiting for it +async def test_the_keep_warm_asks_for_the_last_hours_and_days_first(station): + eco, fake = station + await eco.warm(True) + asked = [c["cycle_type"] for c in fake.calls if c["path"] == "history"] + first = list(dict.fromkeys(asked)) + assert first[:2] == ["5min", "30min"] and set(first) == {"5min", "30min", "4hour", "1day"} + + async def test_the_refresh_builds_no_result_it_would_not_read(station, monkeypatch): from lib.ecowitt import fetch eco, fake = station @@ -1331,6 +1339,87 @@ async def use(name, urgent=False): assert order[-1] == "after" and not lock._locked +async def test_a_background_request_hurried_while_it_waits_moves_to_the_urgent_line(): + from lib.ecowitt.api import Urgency, _TurnLock + lock, order = _TurnLock(), [] + hurried = Urgency() + + async def use(name, urgent=False): + await lock.acquire(urgent) + try: + order.append(name) + await asyncio.sleep(0.01) + finally: + lock.release() + running = asyncio.create_task(use("in flight")) + await asyncio.sleep(0) + tasks = [asyncio.create_task(use(name, urgent)) for name, urgent in + (("background 0", False), ("person", True), ("background 1", False), ("waited for", hurried))] + await asyncio.sleep(0) + hurried.hurry() # a question has come to wait for it + await asyncio.gather(running, *tasks) + assert order == ["in flight", "person", "waited for", "background 0", "background 1"] # behind the person already waiting + assert hurried and hurried._queued is None and not lock._locked + + +async def test_a_hurried_waiter_that_is_cancelled_leaves_no_trace_in_the_urgent_line(): + from lib.ecowitt.api import Urgency, _TurnLock + lock, urgency = _TurnLock(), Urgency() + await lock.acquire() + waiting = asyncio.create_task(lock.acquire(urgency)) + await asyncio.sleep(0) + urgency.hurry() + waiting.cancel() + await asyncio.gather(waiting, return_exceptions=True) + assert not lock._queues[True] and not lock._queues[False] + lock.release() + await asyncio.wait_for(lock.acquire(), 1) + lock.release() + + +async def test_a_question_waiting_for_a_background_fetch_hurries_its_requests_ahead_of_the_other_background_ones(station): + eco, fake = station + now = eco.now() + start = now - timedelta(days=2) + await eco.api._turn.acquire() # a request in flight: everything after it queues + background = [asyncio.create_task(eco.fetcher(["outdoor"]).get(cycle, start, now, load=False)) + for cycle in ("4hour", "1day", "30min")] + await asyncio.sleep(0.01) # each holds its cycle, its request queued in the background line + fake.calls.clear() + question = eco.fetcher(["outdoor"], urgent=True) + asked = asyncio.create_task(question.get("30min", start, now)) + await asyncio.sleep(0.01) # waiting for the background 30-minute fetch + eco.api._turn.release() + rows = await asyncio.wait_for(asked, 2) + assert [c["cycle_type"] for c in fake.calls][:1] == ["30min"] # the fetch it waits for went first + assert rows and question.calls == 0 # and it brought what the question reads + await asyncio.gather(*background) + assert sorted(c["cycle_type"] for c in fake.calls) == ["1day", "30min", "4hour"] + + +async def test_a_background_fetch_taking_a_cycle_while_a_question_waits_for_it_is_hurried_too(tmp_path): + from lib.ecowitt.fetch import Recent + recent, seen = Recent(), [] + first = recent.turn("m", "5min", False) + held = await first.__aenter__() # a background fetch holds the cycle + behind = asyncio.create_task(_hold(recent, False, seen)) # another background one waits for it ... + await asyncio.sleep(0) + question = asyncio.create_task(_hold(recent, True, seen)) # ... then a question + await asyncio.sleep(0) + assert held # the holder was hurried + await first.__aexit__(None, None, None) + await asyncio.gather(behind, question) + assert seen == [True, True] # the background one taking it next sends urgently: the question waits on it + async with recent.turn("m", "5min", False) as later: # nobody waiting any more + assert not later + + +async def _hold(recent, urgent: bool, seen: list): + async with recent.turn("m", "5min", urgent) as urgency: + seen.append(bool(urgency)) + await asyncio.sleep(0) + + async def test_a_cancelled_waiter_does_not_block_the_lock(): from lib.ecowitt.api import _TurnLock lock = _TurnLock() @@ -1543,3 +1632,78 @@ def test_a_reading_with_figures_but_no_readings_in_the_window_draws_no_line_rath q = object.__new__(HistoryQuery) q.drawing, q.store, q.units = ("raw", 0), {}, {"outdoor.temperature": "°C"} assert q._series_entry("outdoor.temperature") is None + + +class HeldLive: + """The station's real_time requests held until let go: (urgent, groups) of each one asked, and a gate to answer them all.""" + + def __init__(self, eco, fail: Exception | None = None): + self.asked, self.gate, self.fail, self.real = [], asyncio.Event(), fail, eco.api.realtime + eco.api.realtime = self.realtime + + async def realtime(self, mac, groups, urgent=False): + self.asked.append((urgent, groups)) + await self.gate.wait() + if self.fail: + raise self.fail + return await self.real(mac, groups, urgent=urgent) + + +async def started(*coros): + tasks = [asyncio.ensure_future(c) for c in coros] + for _ in range(5): + await asyncio.sleep(0) # (each is in flight or waiting on one) + return tasks + + +async def test_a_question_awaits_the_live_reading_already_being_asked_for_rather_than_asking_again(station): + from lib.ecowitt.source import LIVE_GROUPS + eco, _ = station + held = HeldLive(eco) + first, question, second = await started(eco.first_live(), eco._live_data(["outdoor"]), eco._live_data(LIVE_GROUPS)) + assert held.asked == [(True, ",".join(LIVE_GROUPS))] # the start's urgent request, every group; the questions wait on it + held.gate.set() + await first + out, every = await question, await second + assert list(out) == ["outdoor"] and out["outdoor"] == eco._live[1]["outdoor"] and every == eco._live[1] + assert len(held.asked) == 1 + + +async def test_a_question_does_not_wait_on_a_background_live_reading_but_a_background_check_does(station): + from lib.ecowitt.source import LIVE_GROUPS + eco, _ = station + held = HeldLive(eco) + rain, = await started(eco.live_rain()) # the minute check's request is out + check, question = await started(eco._fetch_live(LIVE_GROUPS), eco._live_data(["outdoor"], max_age=0)) + assert [urgent for urgent, _ in held.asked] == [False, True] # the minute check's, then the question's own, ahead of the queue + held.gate.set() + await rain # (the fake station has no rain gauge: None, and logged) + assert await check == eco._live[1] and list(await question) == ["outdoor"] + assert len(held.asked) == 2 + + +async def test_a_caller_that_gives_up_leaves_the_live_reading_to_the_others_and_it_is_kept(station): + from lib.ecowitt.source import LIVE_GROUPS + eco, _ = station + held = HeldLive(eco) + gives_up, waits = await started(eco._fetch_live(LIVE_GROUPS, urgent=True), eco._live_data(["outdoor"])) + gives_up.cancel() + await asyncio.sleep(0) + held.gate.set() + assert list(await waits) == ["outdoor"] and eco._live is not None and len(held.asked) == 1 + with pytest.raises(asyncio.CancelledError): + await gives_up + + +async def test_a_failed_live_reading_fails_each_waiting_caller_and_the_next_asks_again(station, caplog): + from lib.ecowitt.source import LIVE_GROUPS + eco, _ = station + held = HeldLive(eco, fail=ecowitt_api.EcowittError("busy", transient=True)) + first, question = await started(eco.first_live(), eco._live_data(["outdoor"])) + held.gate.set() + await first # the start's own failure is only logged + with pytest.raises(ecowitt_api.EcowittError): + await question + assert "Live reading at start failed: EcowittError: busy" in caplog.text and eco._live is None + held.fail = None + assert "outdoor" in await eco._live_data(LIVE_GROUPS) and len(held.asked) == 2 diff --git a/tests/test_forecast.py b/tests/test_forecast.py index a9f33c03..ee5eab69 100644 --- a/tests/test_forecast.py +++ b/tests/test_forecast.py @@ -6,6 +6,7 @@ from lib.forecast import Forecast from lib.forecast.source import WMO, day_label, describe_day, temps from tests.fakes import TZ, config +from tests.test_pollen import started def ensemble_body(per_day): @@ -77,7 +78,7 @@ def test_days_after_today_are_named_by_their_weekday(): async def test_today_and_the_next_days_come_from_open_meteo_by_local_date(tmp_path): forecast, calls = make(tmp_path) - await forecast.start() + await started(forecast) today = datetime.now(TZ).date() assert forecast.lines() == ["Today: 🌧️ Rain. 11–16°C, 50% chance of at least 1 mm", f"{today + timedelta(days=1):%A}: ☀️ Clear. 12–20°C, 0% chance of at least 1 mm"] @@ -90,7 +91,7 @@ async def test_today_and_the_next_days_come_from_open_meteo_by_local_date(tmp_pa async def test_the_place_is_the_configured_name(tmp_path): forecast, _ = make(tmp_path, place="Geelong") - await forecast.start() + await started(forecast) assert forecast.place == "Geelong" assert forecast.fetched_at # when it was fetched, for the text's heading await forecast.close() @@ -98,7 +99,7 @@ async def test_the_place_is_the_configured_name(tmp_path): async def test_the_forecast_is_fetched_only_in_the_day_and_not_again_while_young(tmp_path): forecast, calls = make(tmp_path, hour=22) - await forecast.start() + await started(forecast) n = len(calls) assert n > 0 await forecast.warm(True) @@ -124,7 +125,7 @@ async def test_the_station_location_is_used_when_none_is_configured_and_without_ async def test_the_lines_are_every_day_open_meteo_gave_unless_fewer_are_asked_for(tmp_path): forecast, _ = make(tmp_path) - await forecast.start() + await started(forecast) assert len(forecast.lines(7)) == 3 # every day Open-Meteo gave (the test data has three) assert len(forecast.lines(2)) == 2 assert len(forecast.lines(30)) == 3 @@ -136,7 +137,7 @@ async def test_the_chance_of_at_least_1_mm_is_the_share_of_ensemble_members_to_t 1: [1.0] + [0.0] * 6, # 1 of 7: 14.3 -> 15 2: [None, None, 5.0, 5.0]} # members with no data are not counted: 2 of 2 -> 100 forecast, calls = make(tmp_path, ensemble=odd) - await forecast.start() + await started(forecast) assert [d["rain_1mm_pct"] for d in forecast.days] == [50, 15, 100] asked = next(c for c in calls if isinstance(c, dict)) assert asked["hourly"] == "precipitation" and asked["models"] == "ecmwf_ifs025" and asked["latitude"] == "-37.8" @@ -145,7 +146,7 @@ async def test_the_chance_of_at_least_1_mm_is_the_share_of_ensemble_members_to_t async def test_a_day_the_ensemble_has_too_few_hours_for_keeps_open_meteos_own_figure(tmp_path): forecast, _ = make(tmp_path, ensemble={0: [0.0, 2.0]}) # only today; the other two days have no members - await forecast.start() + await started(forecast) today, tomorrow = forecast.days[0], forecast.days[1] assert today["rain_1mm_pct"] == 50 and "rain_1mm_pct" not in tomorrow assert describe_day(tomorrow).endswith("0% chance of rain") @@ -154,6 +155,6 @@ async def test_a_day_the_ensemble_has_too_few_hours_for_keeps_open_meteos_own_fi async def test_when_the_ensemble_is_down_the_forecast_still_works_with_open_meteos_own_figure(tmp_path): forecast, _ = make(tmp_path, ensemble=None) - await forecast.start() + await started(forecast) assert forecast.lines()[0] == "Today: 🌧️ Rain. 11–16°C, 40% chance of rain" await forecast.close() diff --git a/tests/test_hass_api.py b/tests/test_hass_api.py index fe9c0463..385046c1 100644 --- a/tests/test_hass_api.py +++ b/tests/test_hass_api.py @@ -10,6 +10,8 @@ from lib.ecowitt.hass_api import HomeAssistantAPI, live_data from tests.fakes import HA_PREFIX, MAC, TZ, config, ecowitt_transport, home_assistant_transport +pytestmark = pytest.mark.usefixtures("ha_states_unshared") # (its fake Home Assistant changes between requests) + def local_now() -> datetime: return datetime.now(TZ).replace(tzinfo=None, microsecond=0) @@ -24,8 +26,17 @@ async def test_the_station_is_found_by_its_entities_names_and_says_when_it_began api, fake = api_for(history_days=10) (device,) = await api.devices() assert device["mac"] == "MAC" and device["name"] == "WS2900" and device["date_zone_id"] == "Australia/Melbourne" - assert abs(device["createtime"] - fake.begins) < 70 and device["latitude"] == -37.8 + assert "createtime" not in device and device["latitude"] == -37.8 and not any(c["path"].startswith("/api/history") for c in fake.calls) + assert [c["path"] for c in fake.calls] == ["/api/config", "/api/states"] # (asked together) + assert abs(await api.look() - fake.begins) < 70 and api.looked # looked for when asked: a long history query, once + (device,) = await api.devices() + assert abs(device["createtime"] - fake.begins) < 70 and await api.look() == api.earliest + assert len([c for c in fake.calls if c["path"].startswith("/api/history")]) == 1 + kept = HomeAssistantAPI("http://ha", "tok", TZ, "MAC", home_assistant_transport(fake)[0]) + kept.known_earliest(fake.begins) # known from the file: never looked for + assert await kept.look() == fake.begins and len([c for c in fake.calls if c["path"].startswith("/api/history")]) == 1 await api.close() + await kept.close() async def test_a_home_assistant_that_cannot_be_used_says_why_as_the_clouds_errors_do(): @@ -96,7 +107,7 @@ async def test_a_history_is_cut_in_the_clouds_buckets_and_asks_home_assistant_a_ async def test_nothing_is_asked_of_home_assistant_for_a_time_before_it_began_recording(): api, fake = api_for(history_days=2) - await api.devices() + await api.look() fake.calls.clear() now = local_now() assert await api.history("x", "5min", now - timedelta(days=60), now - timedelta(days=30), "outdoor") == {} diff --git a/tests/test_hass_live.py b/tests/test_hass_live.py index d08b10ce..62089015 100644 --- a/tests/test_hass_live.py +++ b/tests/test_hass_live.py @@ -2,9 +2,13 @@ import logging import time +import pytest + from lib.ecowitt import Ecowitt, source from tests.fakes import config, ecowitt_transport, home_assistant_transport +pytestmark = pytest.mark.usefixtures("ha_states_unshared") # (its fake Home Assistant changes between requests) + async def home_station(tmp_path, monkeypatch, both=False): monkeypatch.setattr(source, "LIVE_POLL_SECONDS", 0.02) @@ -25,8 +29,11 @@ async def alert(): seen.append(time.time()) eco.on_live.append(alert) task = asyncio.create_task(eco.watch_live()) - await asyncio.sleep(1.1) # the fake's readings are a second apart: two of them + deadline = time.monotonic() + 3 # the fake's readings are a second apart: two of them + while len(seen) < 2 and time.monotonic() < deadline: # (waited on, not slept for: under a busy machine's load + await asyncio.sleep(0.02) # the first poll can come late, past a fixed 1.1 s's reach) task.cancel() + await asyncio.gather(task, return_exceptions=True) # (ended: no poll of its own still on its way) assert len(seen) >= 2 and eco._live and time.time() - eco._live[0] < 1 # a reading kept for "weather now" and the report before = len([c for c in home.calls if c["path"] == "/api/states"]) ts, row = await eco.live_rain() # the alert's reading: the poll's, no request of its own diff --git a/tests/test_mcp_listen.py b/tests/test_mcp_listen.py index c662a491..7dc96bb1 100644 --- a/tests/test_mcp_listen.py +++ b/tests/test_mcp_listen.py @@ -263,9 +263,9 @@ async def test_ecobot_mcp_down_for_a_moment_isnt_a_warning_but_down_for_longer_o monkeypatch.setattr(upstream, "QUIET_SECONDS", 0.6) port = free_port() task = asyncio.create_task(Upstream(f"http://127.0.0.1:{port}/mcp", TOKENS["bot"]).run()) # (nothing listens there yet) - await asyncio.sleep(0.3) warned = lambda: [r.getMessage() for r in caplog.records if r.levelname == "WARNING" and r.name == "lib.upstream"] - assert not warned() and "isn't reachable yet" in caplog.text + await until(lambda: "isn't reachable yet" in caplog.text, what="the first try, said quietly") # (polled: a busy machine may be slow) + assert not warned() await until(warned, what="the warning, once it has been QUIET_SECONDS") # (0.6 s on: polled, so a slow machine can't miss it) assert "for 0s" not in warned()[0] async with Serving(http_app(service, tokens=TOKENS.values()), port): diff --git a/tests/test_minute_lines.py b/tests/test_minute_lines.py index ecc9458c..a33e47b1 100644 --- a/tests/test_minute_lines.py +++ b/tests/test_minute_lines.py @@ -97,6 +97,8 @@ async def test_home_assistant_alone_is_kept_warm_and_backfilled_like_the_cloud(t asked = len(ha.calls) await eco.warm(False) assert len(ha.calls) - asked <= 1 # warm: the newest is in memory (at most the one tail that a new day or hour opens) + await eco.keep_earliest() # (as the warm-up does before the archive starts) + assert eco.created is not None and abs(eco.created.timestamp() - ha.begins) < 70 # Home Assistant's first state: the archive starts there fetched, failed = await Archive(eco, eco.archive_pace).run_once() assert fetched > 10 and not failed # a day at a time, 5-minute, then the coarser for cycle in ("5min", "30min", "1day"): diff --git a/tests/test_packaging.py b/tests/test_packaging.py index e547a99f..c3baab82 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -4,6 +4,8 @@ secrets, by their new and old names, and the bot's wanting and started after ecobot-mcp's. (Read as text: the CI workflow docker.yml builds and runs the images themselves.)""" +import json +import os import re from dataclasses import fields from pathlib import Path @@ -69,6 +71,26 @@ def test_compose_runs_each_program_from_its_own_image(): assert "BOT_MCP_URL=http://ecobot-mcp:8765/mcp" in (ROOT / "docker" / "bot.env").read_text() +def test_the_ecobot_mcp_image_compiles_what_its_start_and_first_requests_import(tmp_path): + """The image's user can't write bytecode, so what the build step doesn't import is compiled again at every start: the tools + (lib.service.*), uvicorn's HTTP protocol and lifespan, anyio's asyncio backend, the clients' connection pool and certificates. The + step itself is run here (bar its check that Telegram and the model client are not installed, which they are in a dev venv).""" + import subprocess + import sys + text = (ROOT / "Dockerfile").read_text().split("FROM app AS ecobot-mcp")[1].split("FROM app AS irrigation-mcp")[0] + program = re.search(r'RUN DATA_DIR=/tmp/build python -c "(.*?)" \\\n', text, re.S)[1].replace("\\\n", "") + program = program.split("; assert importlib.util.find_spec")[0] + shown = "import json; print(json.dumps(sorted(sys.modules)))" + out = subprocess.run([sys.executable, "-c", f"{program}; {shown}"], cwd=ROOT, env={**os.environ, "DATA_DIR": str(tmp_path)}, + capture_output=True, text=True, check=True).stdout + loaded = set(json.loads(out.splitlines()[-1])) + service = {f"lib.service.{p.stem}" for p in (ROOT / "lib" / "service").glob("*.py") if p.stem != "__init__"} + assert service <= loaded + assert {"uvicorn.protocols.http.h11_impl", "uvicorn.lifespan.on", "anyio._backends._asyncio", "httpcore", "truststore", "certifi", + "ecobot_mcp.__main__", "lib.mcp_server"} <= loaded + assert not {"telegram", "openai"} & loaded + + def test_the_ecobot_mcp_unit_drops_the_bots_secrets_by_their_new_and_old_names(): text = (ROOT / "ecobot-mcp.service").read_text() unset = set(re.search(r"^UnsetEnvironment=(.*)$", text, re.M)[1].split()) diff --git a/tests/test_pollen.py b/tests/test_pollen.py index 3a19dabc..21af50ad 100644 --- a/tests/test_pollen.py +++ b/tests/test_pollen.py @@ -4,12 +4,19 @@ import httpx from lib.pollen import LEVEL_EMOJI, LEVELS, Pollen, parse_melbourne_pollen -from lib.warm import in_sync_hours +from lib.warm import in_sync_hours, safely from tests.fakes import TZ, config SEASON_DAY = date(2026, 11, 10) # a day in the pollen season (October to December), whatever day the tests run +async def started(source): + """Started as ecobot-mcp starts it, from what the file kept (nothing asked), then its first fetch if that is due, as the warm-up + makes it (a failure logged, not raised).""" + await source.start(wait=False) + await safely(source.warm, False) + + def page(grass="Low", day=None, asthma="Low", season=True, district_extra=""): day = day or SEASON_DAY asthma_block = f"""

Thunderstorm Asthma Forecast

  • Central
  • {asthma}
  • Wimmera
  • High
@@ -53,7 +60,7 @@ def test_outside_the_asthma_season_there_is_no_asthma_forecast_and_an_unknown_pa async def test_the_lines_have_a_level_emoji_and_never_name_the_district(tmp_path): pollen, _ = make(tmp_path, lambda: page(grass="High", asthma="High")) - await pollen.start() + await started(pollen) assert pollen.lines() == ["Grass pollen forecast: 🔴 High", "Thunderstorm asthma forecast: 🔴 High"] assert "Central" not in json.dumps(pollen.lines()) and pollen.current()["asthma"]["updated"] == "1 Oct 2026 4:00pm" await pollen.close() @@ -62,7 +69,7 @@ async def test_the_lines_have_a_level_emoji_and_never_name_the_district(tmp_path async def test_a_forecast_for_another_day_and_a_missing_asthma_forecast_are_said_so(tmp_path, caplog): pollen, _ = make(tmp_path, lambda: page(grass="Moderate", day=SEASON_DAY + timedelta(days=1), season=False)) with caplog.at_level("WARNING"): - await pollen.start() + await started(pollen) assert pollen.lines() == ["Grass pollen forecast: 🟠 Moderate (forecast for Wed 11 Nov)"] assert pollen.current()["asthma"] is None # (no asthma level to show) assert "no thunderstorm asthma level for Central on the page" in caplog.text # in season the page should have one @@ -89,7 +96,7 @@ async def test_the_district_is_the_sites_whatever_its_case_and_one_it_lacks_is_w async def test_the_page_is_fetched_conditionally_and_not_again_while_fresh(tmp_path): pollen, calls = make(tmp_path) - await pollen.start() + await started(pollen) assert len(calls) == 1 and "if-none-match" not in calls[0].headers and "ecobot" in calls[0].headers["user-agent"] await pollen.warm(False) # a question: the data is young, no request assert len(calls) == 1 @@ -101,7 +108,7 @@ async def test_the_page_is_fetched_conditionally_and_not_again_while_fresh(tmp_p async def test_nothing_is_fetched_outside_6am_to_6pm_except_once_when_nothing_is_cached(tmp_path): pollen, calls = make(tmp_path, hour=22) - await pollen.start() + await started(pollen) assert len(calls) == 1 # empty cache: one fetch, even at night await pollen.warm(True) await pollen.warm(False) @@ -122,7 +129,7 @@ def handler(request): return httpx.Response(500) pollen = Pollen(config(tmp_path, pollen=True), httpx.MockTransport(handler)) pollen.now = lambda: datetime.combine(SEASON_DAY, dtime(12, 0)) - await pollen.start() + await started(pollen) assert pollen.lines() == [] await pollen.close() @@ -144,7 +151,7 @@ def test_the_season_is_october_to_december(tmp_path): async def test_out_of_season_nothing_is_fetched_not_even_at_start_with_an_empty_cache(tmp_path): pollen, calls = make_on(tmp_path, date(2027, 2, 10)) - await pollen.start() + await started(pollen) assert await pollen.warm(True) == "Pollen out of season" and await pollen.warm(False) == "Pollen out of season" assert calls == [] and pollen.lines() == [] and not pollen.in_season() await pollen.close() @@ -152,12 +159,12 @@ async def test_out_of_season_nothing_is_fetched_not_even_at_start_with_an_empty_ async def test_last_seasons_page_is_not_shown(tmp_path): pollen, _ = make_on(tmp_path, date(2026, 12, 20), html=lambda: page(grass="High", day=date(2026, 12, 20))) - await pollen.start() + await started(pollen) assert pollen.lines()[0].startswith("Grass pollen forecast: 🔴 High") assert pollen.current()["fetched_at"] # when the page was fetched, for the text's heading await pollen.close() january, calls = make_on(tmp_path, date(2027, 1, 5)) # the saved page is still in the database - await january.start() + await started(january) assert january.data is not None and january.lines() == [] and january.current()["grass"] is None and calls == [] await january.close() @@ -165,7 +172,7 @@ async def test_last_seasons_page_is_not_shown(tmp_path): async def test_last_seasons_page_is_never_shown_on_the_first_of_october_and_is_fetched_again_even_at_night(tmp_path): december = lambda: page(grass="High", asthma="High", day=date(2025, 12, 31)) pollen, _ = make_on(tmp_path, date(2025, 12, 31), html=december) - await pollen.start() + await started(pollen) await pollen.close() october, calls = make_on(tmp_path, date(2026, 10, 1), hour=3, html=december) # a restart at 3 am, the saved page December's assert october.data is not None and october.current()["grass"] is None and october.current()["asthma"] is None @@ -180,7 +187,7 @@ async def test_the_first_warm_on_the_first_of_october_fetches_without_a_restart( clock = {"day": date(2026, 9, 30)} pollen, calls = make(tmp_path) pollen.now = lambda: datetime.combine(clock["day"], dtime(12, 0)) - await pollen.start() + await started(pollen) await pollen.warm(True) assert calls == [] clock["day"] = date(2026, 10, 1) diff --git a/tests/test_service_current.py b/tests/test_service_current.py index 4b650361..e686b703 100644 --- a/tests/test_service_current.py +++ b/tests/test_service_current.py @@ -256,15 +256,15 @@ def test_the_heading_has_the_time_of_the_reading_with_its_day_when_that_isnt_tod # ---------- context: the gauges' figures ---------- async def gauge_rows(eco, data: dict) -> dict: """{title: {row: figures}}: each gauge's rows as the station's own dashboard drew them before step 2 (dashboard.figures over the - year's day rows, the live reading counted in; today's rain the gauge's own reading).""" - from lib.ecowitt.dashboard import GAUGES, PERIODS, figures, live_value, periods_of + year's day rows, the live reading counted in, the wind's gust into its Gust; today's rain the gauge's own reading).""" + from lib.ecowitt.dashboard import GAUGES, GUST, PERIODS, figures, live_value, periods_of days = periods_of(eco.now().date()) - names = sorted({n for g in GAUGES for n in (g.highest, g.lowest) if n}) + names = sorted({n for g in GAUGES for n in (g.highest, g.lowest, g.gust) if n}) values, _ = await eco.storage.read(day_values_on, eco.mac, names, days["Yearly"]) out = {} for g in GAUGES: - now = live_value(data, g.counted or g.live) - out[g.title] = {row: figures(g, values, days[row], None if g.total else now) for row in PERIODS} + now, gust = live_value(data, g.live), live_value(data, GUST) if g.gust else None + out[g.title] = {row: figures(g, values, days[row], None if g.total else now, gust) for row in PERIODS} if g.total and now is not None: out[g.title]["Daily"] = (None, now) return out @@ -287,7 +287,10 @@ async def test_context_is_the_gauges_figures_with_when_each_happened(tmp_path, d assert s["outdoor"]["temperature"]["year"]["high_text"] == f"{s['outdoor']['temperature']['year']['high']:.1f} °C" assert s["outdoor"]["humidity"]["year"]["low_text"] == f"{s['outdoor']['humidity']['year']['low']:.0f} %" wind = s["wind"]["wind_speed"] - assert [wind[k]["high_gust"] for _, k in cur.PERIODS] == [tiles["Wind"][row][0] for row, _ in cur.PERIODS] + assert tiles["Wind"]["Yearly"][1] > tiles["Wind"]["Yearly"][0] # (a gust is above the speed's highest) + assert [wind[k]["high"] for _, k in cur.PERIODS] == [tiles["Wind"][row][0] for row, _ in cur.PERIODS] # Max: its speed's + assert [wind[k]["high_gust"] for _, k in cur.PERIODS] == [tiles["Wind"][row][1] for row, _ in cur.PERIODS] # Gust: its gusts' + assert WHEN.match(wind["today"]["high_when"]) and WHEN.match(wind["today"]["high_gust_when"]), wind["today"] assert s["wind"]["wind_gust"]["year"]["high"] == wind["year"]["high_gust"] # the gusts' own: the same figure rain = s["rainfall"]["rain"] assert rain["today"] == {"total": 6.3, "total_text": "6.3 mm"} # the gauge's own reading @@ -353,6 +356,7 @@ async def test_just_after_midnight_the_highest_gust_is_the_gust_now_not_the_wind for key in rows: assert s["wind_speed"][key]["high_gust"] == s["wind_gust"][key]["high"] == 31.0, key assert s["wind_speed"][key]["high_gust_when"] == f"at {clock_text(when, whole_hours=True)}" + assert s["wind_speed"][key]["high"] >= 14.0, key # (its own highest: the speed now counted in, not the gust) await close(tool) diff --git a/tests/test_service_days.py b/tests/test_service_days.py index 57a96157..d4d438cc 100644 --- a/tests/test_service_days.py +++ b/tests/test_service_days.py @@ -361,14 +361,21 @@ async def test_a_moment_is_the_reading_at_that_time_each_day(world): async def test_a_night_across_midnight_belongs_to_the_day_it_ends_on_and_today_counts_once_it_is_over(world): - out = await ask(world, hours="night", period="this week", sort_by="temp_min", order="asc", limit=20) - over_now = over(parse_stretch("night"), ago(0), TZ, datetime.now(TZ).timestamp()) - days = [datetime.strptime(r["date"], "%a %d %b %Y").date() for r in out["days"]] - assert out["days_checked"] == 7 and (ago(0) in days) == over_now and (ago(7) in days) == (not over_now) - assert ("cut" in out["period"]) == (not over_now) - d = days[0] - night = range(local_epoch(datetime.combine(d - timedelta(days=1), time(22)), TZ), local_epoch(datetime.combine(d, time(6)), TZ), 300) - assert out["days"][0]["temp_min"] == pytest.approx(min(temp(t) for t in night), abs=0.06) + """At 5:30am last night isn't over: the week is the 7 whole days to yesterday. At 6:30am it is: the week ends today. (Each at a fixed + time of day, yesterday's, that the archive holds every reading of: at the real clock, just after 6am, the hour's archive may not yet + hold the night's last minutes.)""" + for hour, over_now in ((5, False), (6, True)): + when = yesterday_at(hour, 30, TZ) + assert over(parse_stretch("night"), when.date(), TZ, when.timestamp()) == over_now + out = await ask(dataclasses.replace(world, clock=when.timestamp), hours="night", period="this week", sort_by="temp_min", + order="asc", limit=20) + days = [datetime.strptime(r["date"], "%a %d %b %Y").date() for r in out["days"]] + today = when.date() + assert out["days_checked"] == 7 and (today in days) == over_now and (today - timedelta(days=7) in days) == (not over_now), hour + assert ("cut" in out["period"]) == (not over_now), hour + d = days[0] + night = range(local_epoch(datetime.combine(d - timedelta(days=1), time(22)), TZ), local_epoch(datetime.combine(d, time(6)), TZ), 300) + assert out["days"][0]["temp_min"] == pytest.approx(min(temp(t) for t in night), abs=0.06), hour async def test_a_whole_day_stretch_gives_the_day_rows_figures_and_leaves_out_days_held_only_as_daily_records(world): diff --git a/tests/test_settings.py b/tests/test_settings.py index 9f48145f..7613747b 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -19,7 +19,8 @@ MCP_ONLY = {"ecowitt_api_key", "ecowitt_app_key", "ecowitt_source", "airgradient_token", "airgradient_location", "airgradient_dashboard", "airgradient_local_url", "airgradient_source", "homeassistant_url", "homeassistant_token", "place", "pollen", "pollen_district", "forecast", "forecast_lat", "forecast_lon", "rain_quiet_hours", "alert_cooldown_minutes", "antispike_require_consecutive", - "chart_all_feels_like", "chart_all_vpd", "mcp_bind", "mcp_allowed_hosts", "mcp_dashboard", + "chart_all_feels_like", "chart_all_vpd", "mcp_bind", "mcp_allowed_hosts", "mcp_dashboard", "mcp_dashboard_animations", + "mcp_dashboard_indoor", "mcp_chart_base_url", "mcp_chart_link_hours"} IRRIGATION_ONLY = {"tuya_device_id", "tuya_client_id", "tuya_client_secret", "tuya_base_url", "irrigation_check_hour", "irrigation_bind", "irrigation_allowed_hosts", "irrigation_ecobot_mcp_url"} diff --git a/tests/test_snapshots.py b/tests/test_snapshots.py index cc99fdc0..891a2305 100644 --- a/tests/test_snapshots.py +++ b/tests/test_snapshots.py @@ -6,7 +6,7 @@ from lib.warm import safely from tests.fakes import TZ, config from tests.test_forecast import transport as forecast_transport -from tests.test_pollen import SEASON_DAY, make as make_pollen, page +from tests.test_pollen import SEASON_DAY, make as make_pollen, page, started def rows(store, kind: str) -> int: @@ -41,11 +41,11 @@ def test_each_source_has_its_own_connection_to_the_one_file(tmp_path): async def test_a_restart_in_the_evening_starts_from_the_saved_pollen_page_without_fetching(tmp_path): first, calls = make_pollen(tmp_path, lambda: page(grass="High", asthma="High")) - await first.start() + await started(first) assert len(calls) == 1 await first.close() again, more = make_pollen(tmp_path, lambda: page(grass="Low"), hour=22) - await again.start() + await started(again) assert more == [] and again.lines() == ["Grass pollen forecast: 🔴 High", "Thunderstorm asthma forecast: 🔴 High"] assert again.current()["fetched_at"] == first.fetched_at again.now = lambda: datetime.combine(SEASON_DAY, dtime(9, 0)) @@ -58,7 +58,7 @@ async def test_a_restart_in_the_evening_starts_from_the_saved_pollen_page_withou async def test_the_pollen_history_keeps_one_row_per_change(tmp_path): level = {"now": "Low"} pollen, _ = make_pollen(tmp_path, lambda: page(grass=level["now"]).replace('', f'')) - await pollen.start() + await started(pollen) await pollen.warm(True) assert rows(pollen.store, "pollen") == 1 level["now"] = "High" @@ -72,13 +72,13 @@ async def test_the_forecast_survives_a_restart_and_a_night_start_needs_no_reques calls = [] first = Forecast(config(tmp_path, forecast=True, forecast_lat=-37.8, forecast_lon=144.9), None, forecast_transport(calls)) first.now = lambda: datetime.combine(datetime.now(TZ).date(), dtime(12, 0)) - await first.start() + await started(first) lines = first.lines(3) await first.close() calls.clear() again = Forecast(config(tmp_path, forecast=True, forecast_lat=-37.8, forecast_lon=144.9), None, forecast_transport(calls)) again.now = lambda: datetime.combine(datetime.now(TZ).date(), dtime(22, 0)) - await again.start() + await started(again) assert calls == [] and again.lines(3) == lines and rows(again.store, "forecast") == 1 await again.close() @@ -109,7 +109,7 @@ async def test_a_forecast_saved_by_the_older_bom_version_still_loads(tmp_path): "days": [{"date": str(today), "min_c": 11, "max_c": 17, "summary": "Rain.", "rain_chance_pct": 90}]}) forecast = Forecast(config(tmp_path, forecast=True, forecast_lat=-37.8, forecast_lon=144.9), None, forecast_transport([])) forecast.now = lambda: datetime.combine(today, dtime(22, 0)) - await forecast.start() + await started(forecast) assert forecast.lines() == ["Today: Rain. 11–17°C, 90% chance of rain"] await forecast.close() store.close() diff --git a/tests/test_start_offline.py b/tests/test_start_offline.py new file mode 100644 index 00000000..8ae9ccf1 --- /dev/null +++ b/tests/test_start_offline.py @@ -0,0 +1,220 @@ +"""ecobot-mcp opens its port without waiting on any server (step 3 of making it start quicker): each source starts from what the data +folder kept (the station's device and live reading, the air sensor's reading, the last forecast and pollen page), the tools answer from +it as of its time until the fresh readings come in, which the clients are then told of; a first start answers "not in yet"; the +station's device list, asked for in the background, is asked again until it answers.""" + +import asyncio +import json +import time +from datetime import datetime + +import httpx +import pytest + +from ecobot_mcp import core +from lib.airgradient import AirGradient +from lib.ecowitt import Ecowitt, source as eco_source +from lib.ecowitt.fallback import FallbackAPI +from lib.ecowitt.homeassistant import HomeAssistant +from lib.mcp_server import WEATHER_URI, EcobotServer +from lib.service import current as cur +from lib.service.alerts import AlertRules +from lib.service.context import Context +from lib.service.current import CurrentTool +from lib.warm import Tasks +from tests.fakes import air_transport, config, ecowitt_transport +from tests.test_airgradient_local import DEVICE, URL, sensor +from tests.test_forecast import transport as forecast_transport +from tests.test_pollen import page, transport as pollen_transport + + +async def until(check, seconds: float = 2): + for _ in range(int(seconds / 0.01)): + if check(): + return + await asyncio.sleep(0.01) + raise AssertionError("never came") + + +def hanging(calls: list): + """A server that never answers (each request recorded): a start that waited on it would never open the port.""" + async def handler(request: httpx.Request) -> httpx.Response: + calls.append(request.url.path) + await asyncio.Event().wait() + return httpx.MockTransport(handler) + + +INITS = {cls: cls.__init__ for cls in (core.Ecowitt, core.AirGradient, core.Forecast, core.Pollen)} + + +def wire(monkeypatch, eco_t, air_t, forecast_t=None, pollen_t=None): + """The sources start_sources makes, on these transports.""" + for cls, t in ((core.Ecowitt, eco_t), (core.AirGradient, air_t)): + monkeypatch.setattr(cls, "__init__", lambda self, c, transport=None, orig=INITS[cls], t=t, **kw: orig(self, c, t, **kw)) + if forecast_t is not None: + monkeypatch.setattr(core.Forecast, "__init__", lambda self, c, place=None: INITS[core.Forecast](self, c, place, forecast_t)) + if pollen_t is not None: + monkeypatch.setattr(core.Pollen, "__init__", lambda self, c: INITS[core.Pollen](self, c, pollen_t)) + + +async def current(eco, air=None, **meta) -> dict: + return json.loads(await CurrentTool(Context(eco=eco, air=air)).tool().call({}, meta or None)) + + +async def close(sources): + for s in sources: + await s.close() + + +async def test_a_first_start_asks_no_server_and_says_the_station_is_not_in_yet(tmp_path, monkeypatch): + """Every server hangs: the sources still start at once, having asked nothing, the station not found yet (the configured zone) + and "not in yet" said of it; the forecast waits for the station's place rather than being left out.""" + calls = [] + wire(monkeypatch, hanging(calls), hanging(calls), hanging(calls), hanging(calls)) + cfg = config(tmp_path, pollen=True, forecast=True) + sources, cfg = await asyncio.wait_for(core.start_sources(cfg), 2) + try: + assert calls == [] and [s.name for s in sources] == ["Ecowitt", "AirGradient", "Pollen", "Forecast"] + eco = sources[0] + assert eco.mac == "" and not eco.listed.is_set() and eco.summary.startswith("Ecowitt: not found yet") + assert sources[3].location is None and sources[3].summary == "Open-Meteo: none kept yet (every 900s)" + answer = await asyncio.wait_for(current(eco), 2) + assert answer["unavailable"][cur.STATION] == cur.NOT_IN_YET and calls == [] + assert eco.fetcher(["outdoor"]).mac == "" and await eco.fetcher(["outdoor"])._fetch("5min", datetime.now(), datetime.now(), ["outdoor"]) is None + assert calls == [] # (a history request is refused before it is sent: "not in yet") + finally: + await close(sources) + + +async def test_a_failed_device_list_is_asked_again_in_the_background_until_the_station_is_found_and_kept(tmp_path, monkeypatch, caplog): + """A first start whose device list fails (the network down) keeps asking, less and less often; once it answers the station is + found (its address, name, place), kept in the file, and the next start finds it there without asking.""" + monkeypatch.setattr(eco_source, "DEVICE_RETRY_SECONDS", (0.01, 0.02)) + caplog.set_level("INFO") + transport, _ = ecowitt_transport(history_days=3) + eco = Ecowitt(config(tmp_path), transport) + await eco.start(wait=False) + real, failures = eco.api.devices, [2] + + async def devices(): + if failures[0]: + failures[0] -= 1 + raise httpx.ConnectError("the network is down") + return await real() + eco.api.devices = devices + await asyncio.wait_for(eco.refresh_device(), 2) + assert eco.listed.is_set() and eco.mac and eco.location == (-37.8, 145.0) and failures == [0] + assert caplog.text.count("the device list failed") == 1 and "the device list answers again" in caplog.text + mac = eco.mac + await eco.close() + calls = [] + again = Ecowitt(config(tmp_path), hanging(calls)) + await again.start(wait=False) + assert again.mac == mac and again.listed.is_set() and str(again.tz) == "Australia/Melbourne" and calls == [] + await again.close() + + +async def test_a_restart_answers_from_the_kept_readings_as_of_their_time_and_the_clients_are_told_of_the_fresh_ones(tmp_path, monkeypatch): + """The first run keeps the station's device, its live reading and the air sensor's reading in the file. The restart, every server + hanging, starts from them having asked nothing: `current` (and the dashboard's, with fetch off) answers at once from them, as of + their time, the live reading being asked for meanwhile; when fresh readings come in, the pushed resources change.""" + eco_t, _ = ecowitt_transport(history_days=3) + air_t, _ = air_transport() + wire(monkeypatch, eco_t, air_t) + cfg = config(tmp_path) + sources, cfg = await core.start_sources(cfg) + eco, air = sources + await eco.refresh_device() + await eco.first_live() + await air.settle() + kept_station, kept_air = eco._live, air._current + assert kept_station and kept_air + await close(sources) + + calls = [] + wire(monkeypatch, hanging(calls), hanging(calls)) + sources, cfg = await asyncio.wait_for(core.start_sources(cfg), 2) + eco, air = sources + try: + assert calls == [] and eco.mac and str(cfg.tz) == "Australia/Melbourne" + assert eco._live == (pytest.approx(kept_station[0]), kept_station[1]) and air._current[0] == kept_air[0] + eco._live = (eco._live[0] - 600, eco._live[1]) # (kept ten minutes before the restart: no longer fresh) + held = await current(eco, air, fetch=False) # the dashboard's + asked = await asyncio.wait_for(current(eco, air), 2) # a client's, with fetch on: not waiting on the hung servers + assert asked["sensors"] == held["sensors"] and asked["as_of"] == held["as_of"] and "unavailable" not in asked + await until(lambda: any(c.endswith("real_time") for c in calls)) # ... the live reading asked for in the background + server = EcobotServer(Context(eco=eco, air=air)) + assert await server.publish_changes() == [] # (the kept readings: what a client reads now) + newer = json.loads(json.dumps(eco._live[1])) + newer["outdoor"]["temperature"] = {**newer["outdoor"]["temperature"], "value": "31.5", "time": str(int(time.time()))} + eco._got_live(newer) # the fresh reading comes in + assert await server.publish_changes() == [WEATHER_URI] + assert (await current(eco, air))["sensors"]["outdoor"]["temperature"]["value"] == 31.5 + finally: + await close(sources) + + +async def test_the_air_sensor_starts_from_its_kept_reading_and_reads_the_sensor_in_the_warm_up(tmp_path): + transport, calls = air_transport() + air = AirGradient(config(tmp_path, airgradient_local_url=URL), transport=transport) + air.local, _ = sensor(lambda request: httpx.Response(200, json=DEVICE)) + await air.start() # (wait: as before, the sensor read at once) + assert air._current and air._fresh + kept = air._current + await air.close() + again = AirGradient(config(tmp_path, airgradient_local_url=URL), transport=transport) + asked = [] + again.local, _ = sensor(lambda request: asked.append(request) or httpx.Response(200, json=DEVICE)) + calls.clear() + await again.start(wait=False) + assert asked == [] and calls == [] and again._current == (kept[0], pytest.approx(kept[1])) and not again._fresh + latest = await again.latest(kept=True) # a question just after the start: the kept reading, nothing asked + assert latest.reading["pm2_5"]["value"] == 2.5 and asked == [] and calls == [] + await again.settle() + assert len(asked) == 1 and again._fresh + await again.close() + + +async def test_the_particulates_alert_starts_once_the_air_sensor_has_been_read(tmp_path): + transport, _ = air_transport() + air = AirGradient(config(tmp_path), transport=transport) + rules = AlertRules({"AirGradient": air}, store=None, alerts=None) + tasks = Tasks() + running = rules.start(tasks) + assert running == [] and not tasks.running + rules.start_air(tasks, running) + assert running == ["particulates"] and len(tasks.running) == 1 + await tasks.close() + await air.close() + + +async def test_home_assistants_states_are_asked_once_for_everyone_wanting_them_at_about_the_same_moment(): + asked, now = [], [100.0] + + async def handler(request): + asked.append(request.url.path) + await asyncio.sleep(0.01) + return httpx.Response(200, json=[{"entity_id": "sensor.x", "state": "1", "attributes": {"unit_of_measurement": "°C"}}]) + ha = HomeAssistant("http://ha", "tok", httpx.MockTransport(handler), clock=lambda: now[0]) + first, second = await asyncio.gather(ha.states(), ha.states()) # one request out: both await it + assert first == second and asked == ["/api/states"] and ha.units == {"sensor.x": "°C"} + now[0] += 1 + await ha.states() # a few seconds old: shared + now[0] += 10 + await ha.states() # older: asked again + assert asked == ["/api/states"] * 2 + await ha.close() + + +async def test_the_clouds_and_home_assistants_device_lists_are_asked_together(): + class Slow: + def __init__(self, name): + self.name = name + + async def devices(self): + await asyncio.sleep(0.2) + return [{"mac": self.name}] + api = FallbackAPI(Slow("ha"), Slow("cloud"), None) + started = time.monotonic() + assert await api.devices() == [{"mac": "cloud"}] and time.monotonic() - started < 0.35 + diff --git a/tests/test_startup.py b/tests/test_startup.py index 603dc9bb..540603fa 100644 --- a/tests/test_startup.py +++ b/tests/test_startup.py @@ -118,6 +118,18 @@ async def test_ecobot_mcp_starts_warms_archives_and_shuts_down_cleanly(tmp_path, assert "Alerts NOT running" not in log and "Telegram" not in log +async def test_the_stations_live_reading_is_asked_for_first_after_start_ahead_of_the_history(tmp_path, monkeypatch, caplog): + """The dashboard's tiles and the first "weather now" wait on it: it goes before the warm-up's history requests (a second or more + apart), not after them.""" + eco_t, fake = ecowitt_transport(history_days=10) + eco_init = core.Ecowitt.__init__ + ecobot_mcp_settings(tmp_path, monkeypatch) + monkeypatch.setattr(core.Ecowitt, "__init__", lambda self, c, transport=None, **kw: eco_init(self, c, eco_t, **kw)) + await run_ecobot_mcp_until_archived(caplog) + paths = [call.get("path") for call in fake.calls] + assert paths[:3] == ["list", "real_time", "history"] and "Live reading at start failed" not in caplog.text + + async def test_the_weather_alerts_that_could_not_start_are_named_as_not_running(tmp_path, monkeypatch, caplog): from lib.alerts.weather import WeatherMonitor caplog.set_level("INFO") @@ -162,7 +174,12 @@ def broken(self, cfg, transport=None, **kw): assert [s.name for s in sources] == ["Ecowitt"] and "AirGradient couldn't start (OSError: the cache folder is read-only) - continuing without it" in caplog.text -async def test_pollen_and_forecast_start_only_when_switched_on_and_the_forecast_uses_the_stations_location(tmp_path, monkeypatch): +async def test_pollen_and_forecast_start_only_when_switched_on_from_their_last_fetch_and_the_warm_up_fetches(tmp_path, monkeypatch, caplog): + """They start from what the file kept (nothing asked before the port opens); the warm-up fetches them when that is due again, and + logs their lines anew. The forecast uses the station's location.""" + import contextlib + from lib.warm import Tasks + caplog.set_level("INFO") from lib.forecast import Forecast from lib.pollen import Pollen from tests.test_forecast import transport as forecast_transport @@ -178,11 +195,28 @@ async def test_pollen_and_forecast_start_only_when_switched_on_and_the_forecast_ assert [s.name for s in off] == ["Ecowitt"] for s in off: await s.close() - on, _ = await core.start_sources(config(tmp_path, airgradient_token="", airgradient_location="", pollen=True, forecast=True)) + cfg = config(tmp_path, airgradient_token="", airgradient_location="", pollen=True, forecast=True) + on, cfg = await core.start_sources(cfg) assert [s.name for s in on] == ["Ecowitt", "Pollen", "Forecast"] - assert on[2].location == (-37.8, 145.0) and on[2].lines() and on[1].lines() + assert on[2].location is None and calls == [] and not on[2].lines() and not on[1].lines() # nothing kept yet, nothing asked + await on[0].refresh_device() # (the warm-up's: the station's device list gives its place) + assert on[2].location == (-37.8, 145.0) + assert [s.summary for s in on[1:]] == ["Melbourne Pollen: no page of this season kept yet (1800s)", "Open-Meteo: none kept yet (every 900s)"] + async with contextlib.AsyncExitStack() as stack: + tasks = Tasks() + warm = await core.Core.open(cfg, on, stack, tasks) + stack.push_async_callback(tasks.close) + await warm.warm_up([]) + assert on[2].lines() and on[1].lines() and calls # the page, the forecast and its ensemble + assert "Open-Meteo: 3 days (every 900s)" in caplog.text and "Melbourne Pollen: Grass pollen" in caplog.text + assert {"Forecast refresh", "Pollen refresh"} <= set(warm.health.loops) for s in on: await s.close() + calls.clear() + again, _ = await core.start_sources(cfg) # a restart: from the last fetch, nothing asked + assert again[2].lines() and again[1].lines() and calls == [] and again[2].summary == "Open-Meteo: 3 days (every 900s)" + for s in again: + await s.close() async def test_the_other_sources_run_in_the_weather_station_s_time_zone(tmp_path, monkeypatch, caplog): @@ -192,7 +226,15 @@ async def test_the_other_sources_run_in_the_weather_station_s_time_zone(tmp_path for cls, transport in ((core.Ecowitt, eco_t), (core.AirGradient, air_t)): monkeypatch.setattr(cls, "__init__", lambda self, c, transport=None, orig=cls.__init__, t=transport, **kw: orig(self, c, t, **kw)) monkeypatch.setenv("TZ", "UTC") + caplog.set_level("INFO") sources, cfg = await core.start_sources(config(tmp_path, tz=ZoneInfo("UTC"))) # TZ says UTC; the station is in Melbourne + assert str(cfg.tz) == "UTC" and not sources[0].mac # a first start: the station is found after the port opens (its device list) + await sources[0].refresh_device() + assert sources[0].mac and str(sources[0].tz) == "UTC" # ... this run keeps the configured zone, the next takes the station's + assert "the station's time zone is Australia/Melbourne; this run keeps UTC (the configured one)" in caplog.text + for s in sources: + await s.close() + sources, cfg = await core.start_sources(config(tmp_path, tz=ZoneInfo("UTC"))) # the restart: from the device kept in the file for s in sources: await s.close() assert [s.name for s in sources] == ["Ecowitt", "AirGradient"] and str(cfg.tz) == "Australia/Melbourne" diff --git a/tests/test_tls.py b/tests/test_tls.py new file mode 100644 index 00000000..f93a2eba --- /dev/null +++ b/tests/test_tls.py @@ -0,0 +1,35 @@ +"""One TLS context, made once and shared by every HTTP client the programs make (lib/tls.py): httpx would otherwise load certifi's +certificates afresh for each client, about 35 ms apiece on the event loop before the service listens.""" + +import re +import ssl +from pathlib import Path + +from lib.tls import ssl_context + +LIB = Path(__file__).resolve().parent.parent / "lib" + + +def test_the_context_is_made_once_and_checks_certificates_as_httpx_would(): + ctx = ssl_context() + assert ssl_context() is ctx + assert ctx.verify_mode == ssl.CERT_REQUIRED and ctx.check_hostname + + +def test_every_http_client_is_given_the_shared_context(): + made = {str(p.relative_to(LIB)): re.findall(r"httpx\.AsyncClient\((.*?)\)\n", p.read_text(), re.S) for p in LIB.rglob("*.py")} + made = {k: v for k, v in made.items() if v} + assert len(made) >= 7 # the station, Home Assistant, AirGradient (both), forecast, pollen, Tuya + assert all("verify=ssl_context()" in c for calls in made.values() for c in calls), made + + +async def test_a_client_made_without_a_test_transport_connects_with_it(tmp_path): + from lib.ecowitt.homeassistant import HomeAssistant + from lib.pollen.source import Pollen + from tests.fakes import config + clients = [Pollen(config(tmp_path)).client, HomeAssistant("http://ha", "t").client] + try: + assert all(c._transport._pool._ssl_context is ssl_context() for c in clients) + finally: + for c in clients: + await c.aclose() diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py index 432e71a0..18ff6be9 100644 --- a/tests/test_web_dashboard.py +++ b/tests/test_web_dashboard.py @@ -1,33 +1,52 @@ """The gauges' live web page beside /mcp (lib/web_dashboard.py), under uvicorn as tests/test_mcp_listen.py serves the app: the page, its data (the tiles gauge_sheet lays out from current with context), its events (one when the live reading's gauges change, from the -server's own change detection), no token and any Host for it while /mcp still asks for both, MCP_DASHBOARD off (404), the request log, +server's own change detection), no token and any Host for it while /mcp still asks for both, MCP_DASHBOARD off (404), MCP_DASHBOARD_INDOOR +off (no indoor reading drawn, in the data or in the events), the request log, and a shutdown that doesn't wait on an open stream. Then the page in a browser (Playwright's Chromium, through node, skipped without it) at a phone's, a tablet's and a desktop's sizes: every tile on the screen where the size allows, nothing wider than the window, no -console error. With ECOBOT_SCREENSHOTS set, its screenshots are kept in that folder.""" +console error; the tiles rearranged (dragged with a mouse and with a touch's long press, hidden by the × and the remove zone, kept +across reloads, reset), the strip's reading time with a device's reading over an hour old (greyed out), the drag's text left selectable, the fill of fewer tiles, and the tiles' clear backgrounds; a tile zoomed to +fill the window and the gallery through the others (keys, mouse drags, a trackpad's swipe, touch swipes, both ends, the text still +selectable, live readings); the weather behind the tiles (each effect at its reading's mark, its tile framed in red, several at once on +one canvas behind the tiles, "stop", the temporary test links and ?fx=, MCP_DASHBOARD_ANIMATIONS on, low and off and reduced motion +(what moves in each), uv's beams swaying slowly in place +with no particles, the wind's leaves within the budget and blowing right to left, rain in the wind bunched into curtains, its drops +knocking the leaves they hit, humidity's fog and its beads, heavy rain's drops sticking to the glass, a flash flood filling the window +a quarter up, its waves, its leaves and its frog, a cow, a barn or a chicken blown across in a gust over 99 km/h), the data's rain +rate, and the +dials' thin red hands at today's highest (the wind's gust, rain rate, sun, UV: their tiles' Daily figures, the reading now counted in, +moving smoothly) with the wind's Gust column. +With ECOBOT_SCREENSHOTS set, its screenshots are kept in that folder.""" import asyncio import base64 +import functools import html import io import json +import math import re import os import shutil import subprocess import time from pathlib import Path -from datetime import date +from datetime import date, datetime from types import SimpleNamespace as NS import httpx import pytest -from lib import gauge_sheet +from lib import gauge_sheet, web_dashboard +from lib.ecowitt.direction import POINTS from lib.gauge_look import look, tile_json from lib.mcp_server import AIR_URI, EcobotServer, WEATHER_URI, http_app from lib.service.context import Context from lib.service.names import Catalogue -from lib.web_dashboard import DESCRIPTION, ICON, ICON_URL, PAGE, WebDashboard, air_readings_of, readings_of +from lib.ecowitt.reads import directions_on, pressure_on +from lib.gauge_look import CHIPS, MAX_CHIP, START, SWEEP +from lib.web_dashboard import (DESCRIPTION, ICON, ICON_URL, PAGE, RED_HANDS, WebDashboard, air_readings_of, rain_rate_of, readings_of, + today_highs) from tests.chart_samples import _air, _station from tests.fakes import TZ, StandInService, gauges_result from tests.test_mcp_listen import Serving, free_port, until @@ -50,10 +69,11 @@ def __init__(self): self.latest, self.air_values = _air(self.today) self.eco = NS(_live=(time.time(), self.live), storage=None, tz=TZ) self.air = NS(_current=None) + self.air_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) # (its latest's time: now, fresh; air_from moves it) self._keep_air() def _keep_air(self): - row = {"timestamp": "2026-10-27T07:42:00Z", **{RAW[k]: e["value"] for k, e in self.latest.items()}} + row = {"timestamp": self.air_at, **{RAW[k]: e["value"] for k, e in self.latest.items()}} self.air._current = (row, time.time()) def current(self, args, meta): @@ -62,9 +82,36 @@ def current(self, args, meta): def reads(self, group: str, field: str, value: str): self.live = json.loads(json.dumps(self.live)) - self.live[group][field]["value"] = value + self.live.setdefault(group, {}).setdefault(field, {})["value"] = value self.eco._live = (time.time(), self.live) + def air_from(self, at: float): + """The air sensor's latest was taken at this epoch.""" + self.air_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(at)) + self._keep_air() + + def held(self, rose: list[int] | None = None, pressure: list[tuple[float, float]] | None = None): + """The station's file holds today's wind directions (directions_on's: minutes from each of the 16 compass points; none: all + 0) and the past hour and a half's pressure (pressure_on's, given as [(minutes before now, hPa)], oldest first; none: no + reading), as the dashboard reads them (nothing else: the red hands' highs are the sheet's).""" + async def read(fn, mac, *args): + assert mac == "fake" and fn in (directions_on, pressure_on) + start, end = args + assert abs(end - 60 - time.time()) < 5 + if fn is pressure_on: # (the past 90 minutes: TENDENCY_READ) + assert end - 60 - start == web_dashboard.TENDENCY_READ == 90 * 60, (start, end) + return [(int(end - 60 - m * 60), v) for m, v in (pressure or [])] + assert datetime.fromtimestamp(start, TZ).time() == datetime.min.time() # (today's: from the station's midnight to now) + assert datetime.fromtimestamp(start, TZ).date() == datetime.now(TZ).date() + return list(rose or [0] * 16) + self.eco.storage, self.eco.mac = NS(read=read), "fake" + + def highs_today(self, highs: dict): + """Today's day rows hold these highest ({day figure: value}, e.g. {"wind_gust": 37.0}), as current's context gives them.""" + self.values = {k: dict(v) for k, v in self.values.items()} + for figure, value in highs.items(): + self.values.setdefault(figure, {})[self.today] = value + def air_reads(self, column: str, value: float | None): """The air sensor's latest has this reading (None: it hasn't).""" self.latest = {k: e for k, e in self.latest.items() if k != column} @@ -112,12 +159,14 @@ async def test_the_page_and_its_data_are_served_without_a_token_to_any_host_and_ assert data.status_code == 200 got = data.json() sheet = gauge_sheet.sheet(station.current(gauge_sheet.call(), {"fetch": False})) - assert got["tiles"] == [tile_json(t) for t in sheet.tiles] and got["as_of"] == AS_OF and got["look"] == look() + assert got["tiles"] == [{**tile_json(t), **({"rose": []} if t.kind == "compass" else {}), # (no file: no rose, no + **({"tendency": None} if t.title == "Atmospheric pressure" else {})} for t in sheet.tiles] # arrow) + assert got["as_of"] == AS_OF and got["look"] == look() titles = [t["title"] for t in got["tiles"]] - assert titles[:6] == ["Temperature", "Humidity", "Atmospheric pressure", "Rain", "UV index", "US AQI"] # gauge_sheet.FIRST + assert titles[:6] == ["Temperature", "Humidity", "Atmospheric pressure", "Rain", "UV index", "AQI"] # gauge_sheet.FIRST assert titles[-6:] == ["PM2.5", "PM10", "PM1", "CO₂", "VOC index", "NOx index"] # the rest in their order: the air sensor's after tiles = {t["title"]: t for t in got["tiles"]} - aqi, nox = tiles["US AQI"], tiles["NOx index"] + aqi, nox = tiles["AQI"], tiles["NOx index"] assert (aqi["value"], aqi["band"], aqi["bounds"], aqi["faded"]) == (56, "Moderate", [0, 50, 100, 150, 200, 300, 500], False) assert (nox["value"], nox["faded"], nox["floor"], nox["rows"]["Daily"]) == (None, True, 1, [12, 1]) # no reading now: dimmed assert tiles["Atmospheric pressure"]["floor"] == 950 and tiles["Temperature"]["floor"] == 0 @@ -127,6 +176,188 @@ async def test_the_page_and_its_data_are_served_without_a_token_to_any_host_and_ assert mcp.status_code == 421 and no_token.status_code == 401 # /mcp: the Host, then the token, as before +async def test_the_data_carries_the_stations_rain_rate_now_its_rain_gauges_or_else_its_piezo_gauges(server, station): + """The page's rain behind the tiles: the rain rate now (mm/h), the rain gauge's, or the piezo gauge's where that's the one reporting + (in current's result, or in the kept live reading, where current gives it only when it is named); null with neither.""" + page = WebDashboard(server) + assert (await page.data())["rain_rate"] == 0.0 # (the October evening: dry) + station.reads("rainfall", "rain_rate", "2.4") + assert (await page.data())["rain_rate"] == 2.4 + station.live = {**station.live, "rainfall": {"daily": {"value": "0.2"}}, "rainfall_piezo": {"rain_rate": {"value": "0.6"}}} + station.eco._live = (time.time(), station.live) # no rain gauge's rate: the piezo's, as kept + assert (await page.data())["rain_rate"] == 0.6 + station.live = {k: v for k, v in station.live.items() if k != "rainfall_piezo"} + station.eco._live = (time.time(), station.live) + assert (await page.data())["rain_rate"] is None + piezo = {"sensors": {"rainfall": {"rain": {"value": 1.0}}, "rainfall_piezo": {"rain_rate": {"value": 3.2, "unit": "mm/h"}}}} + assert rain_rate_of(piezo) == 3.2 and rain_rate_of({"sensors": {"rainfall": {"rain_rate": {"value": None}}}}) is None + assert rain_rate_of({"sensors": {"rainfall": {"rain_rate": {"value": 0.0}}, "rainfall_piezo": {"rain_rate": {"value": 3.2}}}}) == 0.0 + live = {"rainfall_piezo": {"rain_rate": {"value": "1.5"}}} + assert readings_of({**station.live, **live}) != readings_of(station.live) # the piezo's rate changing: an event, the page fetches it + + +async def test_the_data_carries_todays_highest_of_the_wind_gust_rain_rate_sun_and_uv_and_the_gust_now(server, station): + """The dials' thin red hands: each one's reading's highest today (the station's day; Wind: its gust), its tile's Daily figure (Max; + the Wind's Gust), which counts the reading now in, so it rises with it; null with none. Nothing read from the file for it. And the + gust now.""" + page = WebDashboard(server) + assert RED_HANDS == {"Wind": "Gust", "Rain rate": "Max", "Solar radiation": "Max", "UV index": "Max"} + got = await page.data() # (the October evening: today's day rows, the sun down) + assert got["today_highs"] == {"Wind": 28.0, "Rain rate": 8.0, "Solar radiation": 700.0, "UV index": 6.0} and got["gust"] is None + tiles = {t["title"]: t for t in got["tiles"]} + assert all(got["today_highs"][t] == dict(zip(tiles[t]["columns"], tiles[t]["rows"]["Daily"]))[c] for t, c in RED_HANDS.items()) + station.highs_today({"wind_gust": 37.0, "rain_rate_max": 4.2, "solar_max": 820.0, "uv_max": 2.0}) + station.reads("wind", "wind_gust", "12") # (a gust now below today's highest) + got = await page.data() + assert got["today_highs"] == {"Wind": 37.0, "Rain rate": 4.2, "Solar radiation": 820.0, "UV index": 2.0} and got["gust"] == 12.0 + station.reads("wind", "wind_gust", "41") # a gust above today's highest: it is the highest, + station.reads("solar_and_uvi", "uvi", "3") # as is the UV now + got = await page.data() + assert (got["today_highs"]["Wind"], got["today_highs"]["UV index"], got["gust"]) == (41.0, 3.0, 41.0) + station.values = {k: {d: v for d, v in days.items() if d != station.today or k not in ("rain_rate_max", "solar_max")} + for k, days in station.values.items()} # no day row today for the rain rate and the sun, + station.live = {k: v for k, v in station.live.items() if k != "rainfall"} # nor a rain rate now: null, its tile dimmed with the + station.eco._live = (time.time(), station.live) # month's (the sun's: its reading now, 0) + got = await page.data() + assert got["today_highs"] == {"Wind": 41.0, "Rain rate": None, "Solar radiation": 0.0, "UV index": 3.0}, got["today_highs"] + assert today_highs([]) == {} + station.reads("wind", "wind_gust", "9") + assert readings_of(station.live) != readings_of({**station.live, "wind": {**station.live["wind"], "wind_gust": {"value": "10"}}}) + + +async def test_the_data_carries_todays_wind_rose_on_the_wind_direction_tile_read_from_the_file_and_kept_a_minute(server, station, + monkeypatch, caplog): + """The Wind direction tile's `rose`: the share of today's readings of the wind's direction (the station's day, in its zone; the + file's: directions_on) from each of the 16 compass points, N first; [] with no file, no reading today, or the file not read. Read at + most every ROSE_SECONDS, else kept; no other tile has one, and the sheet's tiles are as ever.""" + page = WebDashboard(server) + compass = lambda got: next(t for t in got["tiles"] if t["kind"] == "compass") + got = await page.data() + assert compass(got)["rose"] == [] and all("rose" not in t for t in got["tiles"] if t["kind"] != "compass") # (no file) + assert [{k: v for k, v in t.items() if k not in ("rose", "tendency")} for t in got["tiles"]] == [tile_json(t) for t in gauge_sheet.sheet( + station.current(gauge_sheet.call(), {"fetch": False})).tiles] + minutes = [10, 4, 2, 0, 30, 12, 6, 0, 0, 0, 3, 0, 0, 0, 5, 8] + station.held(minutes) + assert compass(await page.data())["rose"] == [] and web_dashboard.ROSE_SECONDS == 60 # (kept: read under a minute ago) + page._rose = None + got = compass(await page.data())["rose"] + assert len(got) == 16 and got == [round(n / 80, 4) for n in minutes] and got[4] == 0.375, got + station.held([0] * 16) # read again a minute on: none today + page._rose = (page._rose[0] - 61, *page._rose[1:]) + assert compass(await page.data())["rose"] == [] + + async def broken(*a): + raise OSError("disk") + station.eco.storage = NS(read=broken) + monkeypatch.setattr(web_dashboard, "ROSE_SECONDS", 0) + assert compass(await page.data())["rose"] == [] and "couldn't read today's wind directions: OSError: disk" in caplog.text + + +async def test_todays_wind_directions_are_counted_from_the_5_minute_readings_and_the_minutes_they_dont_cover_calm_left_out(tmp_path): + """directions_on: minutes from each of the 16 compass points from start to end: a 5-minute reading counts 5, a minute 1 where no + 5-minute reading is within 300 s of it (never counted twice); a calm one (its speed 0) left out, one with no speed counted; nothing + older or newer, nor a 30-minute reading; all 0 with none, or no wind sensor.""" + from lib.storage import Storage + storage = Storage(tmp_path / "s.sqlite", TZ) + mac, now = "AA:BB", 1_794_279_900 + start = now - 6 * 3600 + assert await storage.read(directions_on, mac, start, now) == [0] * 16 + fives = {now - 3600: ("90", "5"), now - 3300: ("95", "0"), now - 3000: ("180", "3"), now - 7 * 3600: ("0", "4")} # (calm; too old) + wind = lambda rows: {"wind": {"wind_direction": {"unit": "º", "list": {str(t): d for t, (d, _) in rows.items()}}, + "wind_speed": {"unit": "km/h", "list": {str(t): v for t, (_, v) in rows.items()}}}} + with storage.writer.transaction() as w: + w.put_ecowitt(mac, "5min", ["wind"], wind(fives), now - 8 * 3600, now - 2000, now=now) + w.put_ecowitt(mac, "30min", ["wind"], wind({now - 1800: ("270", "4")}), now - 1800, now - 1800, now=now) + w.put_minutes(mac, wind({now - 3060: ("200", "2"), # (within the 5-minute readings: theirs) + now - 600: ("350", "6"), now - 540: ("5", "6"), now - 480: ("22", "1"), now - 420: ("300", "0"), + now + 120: ("90", "9")}), now) # (newer than `end`) + w.put_minutes(mac, {"wind": {"wind_direction": {"unit": "º", "list": {str(now - 360): "135"}}}}, now) # (no speed: counted) + got = await storage.read(directions_on, mac, start, now) + want = [0] * 16 + want[4] += 5; want[8] += 5; want[0] += 2; want[1] += 1; want[6] += 1 # (E, S; N twice, NNE, SE) + assert got == want, got + storage.close() + + +async def test_the_data_carries_the_pressures_change_over_the_past_hour_on_its_tile_only_read_from_the_file_and_kept_a_minute( + server, station, monkeypatch, caplog): + """The Atmospheric pressure tile's `tendency`: its change over the past hour, {"change": hPa, "way"} (tendency_of: the file's newest + reading less the one nearest an hour before it, in hPa, from the past 90 minutes' 5-minute readings and minutes: pressure_on); null + with no file, too little history, or the file not read. Read at most every TENDENCY_SECONDS, else kept; no other tile has one.""" + page = WebDashboard(server) + pressure = lambda got: next(t for t in got["tiles"] if t["title"] == "Atmospheric pressure") + got = await page.data() + assert pressure(got)["tendency"] is None and [t["title"] for t in got["tiles"] if "tendency" in t] == ["Atmospheric pressure"] # (no file) + assert pressure(got)["decimals"] == 0 and next(g for g in web_dashboard.GAUGES if g.title == "Atmospheric pressure").decimals == 0 + station.held(pressure=pressure_hour(-1.4)) + assert pressure(await page.data())["tendency"] is None and web_dashboard.TENDENCY_SECONDS == 60 # (kept: read under a minute ago) + page._tendency = None + assert pressure(await page.data())["tendency"] == {"change": -1.4, "way": "down"} + station.held(pressure=pressure_hour(0.8)) # read again a minute on: risen + page._tendency = (page._tendency[0] - 61, page._tendency[1]) + assert pressure(await page.data())["tendency"] == {"change": 0.8, "way": "up"} + station.held(pressure=[(m, 1012.0) for m in range(40, -1, -5)]) # only 40 minutes held: none + page._tendency = None + assert pressure(await page.data())["tendency"] is None + + async def broken(*a): + raise OSError("disk") + station.eco.storage = NS(read=broken) + monkeypatch.setattr(web_dashboard, "TENDENCY_SECONDS", 0) + assert pressure(await page.data())["tendency"] is None and "couldn't read the past hour's pressure: OSError: disk" in caplog.text + + +def test_the_pressures_change_over_the_past_hour_is_its_newest_reading_less_the_one_nearest_an_hour_before(): + """tendency_of: [(epoch, hPa)] oldest first: the newest less the reading nearest 60 minutes before it (45 to 75 minutes before it; + none there: None), to a tenth; up 0.3 hPa or more: "up", down as much: "down", less either way: "steady".""" + t = 1_794_200_000 + hour = lambda *pairs: [(t - m * 60, v) for m, v in pairs] # ((minutes before the newest, hPa), ...), oldest first + assert web_dashboard.tendency_of(hour((60, 1010.0), (30, 1010.9), (0, 1011.2))) == {"change": 1.2, "way": "up"} # rising + assert web_dashboard.tendency_of(hour((60, 1012.0), (0, 1010.5))) == {"change": -1.5, "way": "down"} # falling + assert web_dashboard.tendency_of(hour((60, 1012.0), (0, 1012.2))) == {"change": 0.2, "way": "steady"} # steady + assert web_dashboard.tendency_of(hour((60, 1012.0), (0, 1011.8))) == {"change": -0.2, "way": "steady"} + assert web_dashboard.tendency_of(hour((60, 1012.0), (0, 1012.3)))["way"] == "up" # (0.3: the mark) + assert web_dashboard.tendency_of(hour((60, 1013.3), (0, 1013.0)))["way"] == "down" + assert web_dashboard.tendency_of(hour((60, 1012.0), (0, 1012.29)))["way"] == "steady" + # the reading nearest an hour before the newest: 63 minutes (3 off) rather than 55 (5 off), or 80 (out of reach) and 50 (10 off) + assert web_dashboard.tendency_of(hour((80, 1000.0), (63, 1011.0), (55, 1013.0), (0, 1012.0))) == {"change": 1.0, "way": "up"} + assert web_dashboard.tendency_of(hour((80, 1000.0), (50, 1013.0), (0, 1012.0))) == {"change": -1.0, "way": "down"} + assert web_dashboard.tendency_of(hour((60, 1012.0), *((m, 1013.0) for m in range(59, -1, -1)))) == {"change": 1.0, "way": "up"} + # too little history: none about an hour old (only 40 minutes; nothing between 45 and 75 minutes before the newest; none at all) + assert web_dashboard.tendency_of(hour((40, 1012.0), (20, 1011.0), (0, 1010.0))) is None + assert web_dashboard.tendency_of(hour((90, 1012.0), (76, 1012.0), (44, 1011.0), (0, 1010.0))) is None + assert web_dashboard.tendency_of(hour((75, 1012.0), (0, 1011.0))) == {"change": -1.0, "way": "down"} # (75: still) + assert web_dashboard.tendency_of(hour((0, 1012.0))) is None and web_dashboard.tendency_of([]) is None + + +@functools.cache +def pressure_hour(change: float) -> list[tuple[float, float]]: + """The past 90 minutes' pressure, a reading every 5 minutes ([(minutes before now, hPa)], oldest first), changing `change` hPa + over the last hour, steadily.""" + return [(m, round(1013.2 - change * m / 60, 2)) for m in range(90, -1, -5)] + + +async def test_todays_pressure_is_read_from_the_5_minute_readings_and_the_minutes_they_dont_cover(tmp_path): + """pressure_on: the relative pressure from start to end, [(epoch, hPa)] oldest first: the 5-minute readings, and the minutes where + no 5-minute reading is within 300 s (never counted twice); nothing older or newer, nor a 30-minute reading; [] with none.""" + from lib.storage import Storage + storage = Storage(tmp_path / "s.sqlite", TZ) + mac, now = "AA:BB", 1_794_279_900 + start = now - 6 * 3600 + assert await storage.read(pressure_on, mac, start, now) == [] + hpa = lambda rows: {"pressure": {"relative": {"unit": "hPa", "list": {str(t): v for t, v in rows.items()}}, + "absolute": {"unit": "hPa", "list": {str(t): "990.0" for t in rows}}}} + with storage.writer.transaction() as w: + w.put_ecowitt(mac, "5min", ["pressure"], hpa({now - 3600: "1012.3", now - 3300: "1012.5", now - 7 * 3600: "1000.0"}), # (too old) + now - 8 * 3600, now - 3000, now=now) + w.put_ecowitt(mac, "30min", ["pressure"], hpa({now - 1800: "1020.0"}), now - 1800, now - 1800, now=now) + w.put_minutes(mac, hpa({now - 3240: "1050.0", # (within the 5-minute readings: theirs) + now - 600: "1012.9", now - 540: "1013.0", now + 120: "1013.4"}), now) # (newer than `end`) + got = await storage.read(pressure_on, mac, start, now) + assert got == [(now - 3600, 1012.3), (now - 3300, 1012.5), (now - 600, 1012.9), (now - 540, 1013.0)], got + storage.close() + + async def test_the_page_answers_at_dashboard_slash_too_so_a_proxy_mapping_a_sites_root_there_gets_no_redirect_to_the_lan(server): # nginx's `location / { proxy_pass http://deb1:8765/dashboard/; }` sends the site's root as /dashboard/ with ecobot-mcp's own Host: # a redirect to /dashboard would be built from that Host, the LAN address, and break the page from the internet @@ -194,6 +425,37 @@ def test_the_icon_is_the_pages_own_sun_at_512_px(): assert ICON_URL.endswith("/main/" + ICON.relative_to(Path(__file__).resolve().parent.parent).as_posix()) # og:image: this file on GitHub +async def test_the_data_carries_each_devices_own_reading_time_and_none_for_a_device_not_configured(server, station): + """Beside as_of (the newer of the two), each device's own reading time, for the strip's stalled device: the station's newest reading's + own time in its kept live reading (else when that was kept), the air sensor's latest's; fresh, one stale (each), both, recovered.""" + port = free_port() + base = f"http://127.0.0.1:{port}" + local = lambda at: datetime.fromtimestamp(int(at), TZ).isoformat() + now = time.time() + async with Serving(http_app(server, tokens=(TOKEN,)), port): + data = lambda: get(f"{base}/dashboard/data") + station.eco._live = (now, station.live) # both fresh (the station's reading with no time of its own) + station.air_from(now - 60) + assert (await data()).json()["devices"] == {"station": local(now), "air": local(now - 60)} + station.air_from(now - 5400) # the air sensor stalled + assert (await data()).json()["devices"] == {"station": local(now), "air": local(now - 5400)} + stamped = json.loads(json.dumps(station.live)) # the station stalled: its readings' own times, the newest + stamped["outdoor"]["temperature"]["time"], stamped["wind"]["wind_speed"]["time"] = str(int(now - 7300)), str(int(now - 7200)) + station.eco._live = (now, stamped) + station.air_from(now - 30) + assert (await data()).json()["devices"] == {"station": local(now - 7200), "air": local(now - 30)} + station.air_from(now - 9000) # both stalled + assert (await data()).json()["devices"] == {"station": local(now - 7200), "air": local(now - 9000)} + station.eco._live = (now, station.live) # both reporting again + station.air_from(now) + assert (await data()).json()["devices"] == {"station": local(now), "air": local(now)} + station.eco._live, station.air._current = None, None # nothing held + assert (await data()).json()["devices"] == {"station": None, "air": None} + server.ctx.air = None # no air sensor configured: never named + station.eco._live = (now, station.live) + assert (await data()).json()["devices"] == {"station": local(now)} + + async def test_the_data_says_so_when_the_station_gives_nothing(server): server._service = StandInService(current={"sensors": {}, "unavailable": {"station": "The weather station isn't answering right now."}}) port = free_port() @@ -278,6 +540,7 @@ def test_what_the_events_compare_is_the_gauges_readings_with_the_gust(): shown = readings_of(live) assert 12.9 in shown and 1026.0 in shown assert readings_of({**live, "wind": {"wind_speed": {"value": "5"}, "wind_gust": {"value": "11"}}}) != shown + assert readings_of({**live, "wind": {**live["wind"], "wind_direction": {"value": "300"}}}) != shown # (the compass's) async def test_with_mcp_dashboard_off_there_is_no_page_and_mcp_is_as_it_was(server, caplog): @@ -303,25 +566,199 @@ def test_mcp_dashboard_is_read_as_on_or_off(monkeypatch, tmp_path): assert Config.from_env(bot=False).mcp_dashboard is False +INDOOR_TITLES = ["Indoor temperature", "Indoor humidity"] + + +async def test_with_mcp_dashboard_indoor_off_no_indoor_reading_is_drawn_or_sent_in_the_data_or_the_events(server, station): + """MCP_DASHBOARD_INDOOR (privacy: the page needs no token): on (the default), the indoor tiles as any other's; off, none of them in + /dashboard/data (no indoor value anywhere in it: as with no indoor sensor) and an indoor change alone sends no event, the events + carrying nothing indoor; the rest of the data, and the page itself, as with it on.""" + station.reads("indoor", "temperature", "23.7") + station.reads("indoor", "humidity", "47") + got, pages = {}, {} + port = free_port() + async with Serving(http_app(server, tokens=(TOKEN,)), port): # on: the default + got[True] = (await get(f"http://127.0.0.1:{port}/dashboard/data")).text + pages[True] = (await get(f"http://127.0.0.1:{port}/dashboard")).text + port = free_port() + events, opened, raw = [], asyncio.Event(), [] + async with Serving(http_app(server, tokens=(TOKEN,), dashboard_indoor=False), port) as serving: + got[False] = (await get(f"http://127.0.0.1:{port}/dashboard/data")).text + pages[False] = (await get(f"http://127.0.0.1:{port}/dashboard")).text + + # the events: an indoor change alone sends none (nor tells one happened); an outdoor one does, and nothing indoor in it + async def read(): + async with httpx.AsyncClient(timeout=None) as http, http.stream("GET", f"http://127.0.0.1:{port}/dashboard/events") as response: + async for line in response.aiter_lines(): + opened.set() + raw.append(line) + if line.startswith("event: "): + events.append(line[len("event: "):]) + reader = asyncio.create_task(read()) + await asyncio.wait_for(opened.wait(), 5) + await server.publish_changes() + station.reads("indoor", "temperature", "24.9") + assert await server.publish_changes() == [WEATHER_URI] # (published to MCP clients as ever) + station.reads("indoor", "humidity", "52") + assert await server.publish_changes() == [WEATHER_URI] + station.reads("outdoor", "temperature", "13.4") + await server.publish_changes() + await until(lambda: events == ["readings"], what="the outdoor change's event") + await serving.stop() + await asyncio.wait_for(reader, 5) + on, off = json.loads(got[True]), json.loads(got[False]) + titles = [t["title"] for t in on["tiles"]] + assert set(INDOOR_TITLES) <= set(titles) and WebDashboard(server).indoor is True + assert [t["title"] for t in off["tiles"]] == [t for t in titles if t not in INDOOR_TITLES] + assert off["tiles"] == [t for t in on["tiles"] if t["title"] not in INDOOR_TITLES] + assert {k: v for k, v in off.items() if k != "tiles"} == {k: v for k, v in on.items() if k != "tiles"} + assert "indoor" not in got[False].lower() and "23.7" not in got[False] and "indoor" in got[True].lower() + assert pages[False] == pages[True] and "indoor" not in re.sub(r"|//[^\n]*", "", pages[False]).lower() + assert events == ["readings"] and not any("indoor" in line.lower() or "24.9" in line or "52" in line for line in raw), raw + # ... and with it on, an indoor change alone sends one + assert readings_of(station.live) != readings_of({**station.live, "indoor": {"temperature": {"value": "30"}}}) + assert readings_of(station.live, False) == readings_of({**station.live, "indoor": {"temperature": {"value": "30"}}}, False) + dashboard = WebDashboard(server, (WEATHER_URI, AIR_URI)) + queue = asyncio.Queue() + dashboard._streams.add(queue) + station.reads("indoor", "temperature", "26.1") + await server.publish_changes() + assert queue.qsize() == 1 + + +def test_mcp_dashboard_indoor_is_read_as_on_or_off_on_by_default_and_a_typo_keeps_it_on_with_a_warning(monkeypatch, tmp_path, caplog): + from lib.config import Config + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + monkeypatch.setenv("MCP_ECOWITT_API_KEY", "a") + monkeypatch.setenv("MCP_ECOWITT_APP_KEY", "b") + monkeypatch.delenv("MCP_DASHBOARD_INDOOR", raising=False) + assert Config.from_env(bot=False).mcp_dashboard_indoor is True + for value, want in (("off", False), ("no", False), ("FALSE", False), ("0", False), ("on", True), ("yes", True), ("", True)): + monkeypatch.setenv("MCP_DASHBOARD_INDOOR", value) + assert Config.from_env(bot=False).mcp_dashboard_indoor is want, value + caplog.set_level("WARNING", logger="lib.config") + monkeypatch.setenv("MCP_DASHBOARD_INDOOR", "hidden") + assert Config.from_env(bot=False).mcp_dashboard_indoor is True + assert any("MCP_DASHBOARD_INDOOR" in r.getMessage() and "'hidden'" in r.getMessage() for r in caplog.records), caplog.records + + +def test_mcp_dashboard_animations_is_read_as_on_off_or_low_on_by_default_and_a_typo_keeps_it_on_with_a_warning(monkeypatch, tmp_path, caplog): + from lib.config import Config + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + monkeypatch.setenv("MCP_ECOWITT_API_KEY", "a") + monkeypatch.setenv("MCP_ECOWITT_APP_KEY", "b") + monkeypatch.delenv("MCP_DASHBOARD_ANIMATIONS", raising=False) + assert Config.from_env(bot=False).mcp_dashboard_animations == "on" + for value, want in (("off", "off"), ("OFF", "off"), ("no", "off"), ("on", "on"), ("true", "on"), ("", "on"), ("low", "low"), ("LOW", "low")): + monkeypatch.setenv("MCP_DASHBOARD_ANIMATIONS", value) + assert Config.from_env(bot=False).mcp_dashboard_animations == want, value + caplog.set_level("WARNING", logger="lib.config") + monkeypatch.setenv("MCP_DASHBOARD_ANIMATIONS", "sometimes") + assert Config.from_env(bot=False).mcp_dashboard_animations == "on" + assert any("MCP_DASHBOARD_ANIMATIONS" in r.getMessage() and "'sometimes'" in r.getMessage() for r in caplog.records), caplog.records + + +async def test_the_page_is_told_whether_to_draw_the_weather_behind_its_gauges_and_whether_anything_moves(server): + """MCP_DASHBOARD_ANIMATIONS: the page served with data-animations="on" on its (the default), "off" or "low"; + nothing else changes. (True and False, as earlier: "on" and "off"; anything else refused.)""" + pages = {} + for animations in ("on", "off", "low", True, False, None): + port = free_port() + async with Serving(http_app(server, tokens=(TOKEN,), **({} if animations is None else {"dashboard_animations": animations})), port): + pages[animations] = (await get(f"http://127.0.0.1:{port}/dashboard")).text + assert pages["on"].count('') == 1 and '' not in pages["on"] + assert pages["off"].count('') == 1 + assert pages["low"].count('') == 1 + for value in ("off", "low"): + assert pages[value].replace(f'data-animations="{value}"', 'data-animations="on"', 1) == pages["on"], value + assert pages[True] == pages[None] == pages["on"] and pages[False] == pages["off"] + with pytest.raises(ValueError, match="sometimes"): + WebDashboard(server, animations="sometimes") + + # ---------- the page in a browser ---------- SIZES = {"phone-portrait": (390, 844), "phone-landscape": (844, 390), "tablet-landscape": (1024, 768), "tablet-portrait": (768, 1024), "desktop": (1920, 1080)} +@functools.cache def browser_there() -> bool: if not shutil.which("node"): - return False - return subprocess.run(["node", "-e", "require('playwright')"], capture_output=True, timeout=60).returncode == 0 + return False # (Playwright found, not loaded: loading it is most of a script's start) + return subprocess.run(["node", "-e", "require.resolve('playwright')"], capture_output=True, timeout=60).returncode == 0 -async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overflow_and_no_console_error(server, station, tmp_path): - if not browser_there(): # (asked here, by the one worker that runs it, not by every worker as it collects the tests) +@pytest.fixture +def chromium(): + """Skips the test without node and Playwright's Chromium: asked as a test runs, once in a worker (not as every worker collects the + tests: a node each, a third of a second).""" + if not browser_there(): pytest.skip("needs node with Playwright's Chromium") + + +needs_browser = pytest.mark.usefixtures("chromium") + + +def rgb(colour: str) -> str: + return "rgb({}, {}, {})".format(*(int(colour[i:i + 2], 16) for i in (1, 3, 5))) + + +def one_end_to_read(compass: dict): + """The compass's needle (compassLook's, in its own px): its head a slim blade to a sharp tip in the red hands' red (not the rose's + blue), solid; its tail a short, dim taper of another colour; never two ends alike.""" + head, tail = compass["ends"] + assert head["colour"] == rgb(look()["high_hand"]) != rgb(look()["needle"]) and tail["colour"] != head["colour"], compass + assert head["opacity"] == 1 and tail["opacity"] <= 0.6, compass + assert compass["hubColour"] == head["colour"], compass # (its hub ringed in the same red) + assert head["length"] > 4 * tail["length"] and head["area"] > 3 * tail["area"] and head["width"] <= 12, compass # (slim) + + +ROSE = [10, 4, 2, 0, 30, 12, 6, 0, 0, 0, 3, 0, 0, 0, 5, 8] # today's minutes from each compass point (N first): mostly from the east +ROSE_LATER = [0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 10, 0, 40, 20, 0, 0] # ... later: from the west + + +def compass_as_a_dial(c: dict): + """The compass (compassLook's) the size of a dial, lined up with them: its ring a dial's (centre and radius in the tile's own px, its + line as thin), as wide drawn; the layers from the bottom: the rose, the reading, the face (its ring, ticks and N, E, S and W), the + needle, its hub; the reading inside the ring, in its lower half, centred.""" + assert c["circle"] == c["dialCircle"] == [240, 203, 138] and c["ringStroke"] == pytest.approx(3 * 100 / 72), c + if not c["zoomed"]: # (in the grid: as large as its neighbours' drawn) + assert c["ring"]["width"] == pytest.approx(c["dialRing"]["width"], abs=0.5), c + assert c["layers"] == ["rose", "reading", "face", "needle", "hub"], c + reading = next(r for r in c["texts"] if r["width"] and abs((r["left"] + r["right"]) / 2 - (c["ring"]["left"] + c["ring"]["right"]) / 2) < 1 + and r["top"] > (c["ring"]["top"] + c["ring"]["bottom"]) / 2) + assert c["readingBelow"] > 30 and c["readingAt"] + 20 < 138 and c["ring"]["left"] < reading["left"] and reading["right"] < c["ring"]["right"], c + assert reading["bottom"] < c["ring"]["bottom"] - c["ring"]["height"] * 0.1, (reading, c) + + +def rose_drawn(c: dict, minutes: list[int]): + """Today's rose as drawn (compassLook's petals): a petal for each compass point with any share, in the dials' needles' blue, see-through, + its reach from the centre in proportion to its share, the longest 80% of the radius.""" + total, most = sum(minutes), max(minutes) + want = {POINTS[i]: n / total for i, n in enumerate(minutes) if n} + petals = c["petals"] + assert {p["point"]: p["share"] for p in petals} == pytest.approx(want, abs=1e-4), petals + for p in petals: + assert p["reach"] == pytest.approx(138 * 0.8 * minutes[POINTS.index(p["point"])] / most, abs=0.05), p + assert p["colour"] == rgb(look()["needle"]) and 0.15 <= p["opacity"] <= 0.5, p + + +@needs_browser +async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overflow_and_no_console_error(server, station, tmp_path, + monkeypatch): shots = Path(os.getenv("ECOBOT_SCREENSHOTS") or tmp_path) shots.mkdir(parents=True, exist_ok=True) port = free_port() url = f"http://127.0.0.1:{port}/dashboard" - async with Serving(http_app(server, tokens=(TOKEN,)), port): + monkeypatch.setattr(web_dashboard, "ROSE_SECONDS", 0) # (today's rose read again with each data: it changes below) + station.reads("wind", "wind_gust", "12") + station.highs_today({"wind_gust": 37.0, "rain_rate_max": 4.2, "solar_max": 820.0, "uv_max": 6.5}) # (today's highest: above the + station.held(ROSE, pressure_hour(1.2)) # readings now, all but 0; today's rose, and the pressure + monkeypatch.setattr(web_dashboard, "TENDENCY_SECONDS", 0) # risen over the past hour; read again: it falls below) + wind = next(t for t in gauge_sheet.sheet(station.current(gauge_sheet.call(), {"fetch": False})).tiles if t.title == "Wind") + station.reads("indoor", "temperature", "23.7") # an indoor sensor, served with MCP_DASHBOARD_INDOOR off: + station.reads("indoor", "humidity", "47") # its tiles never drawn (the same tiles as with none) + async with Serving(http_app(server, tokens=(TOKEN,), dashboard_indoor=False), port): sizes = await asyncio.create_subprocess_exec("node", str(BROWSER), url, str(shots), json.dumps(SIZES), stdout=subprocess.PIPE, stderr=subprocess.PIPE) # (not asyncio.to_thread: the tests run it inline) out, err = await asyncio.wait_for(sizes.communicate(), 180) @@ -332,20 +769,122 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl stderr=subprocess.PIPE) before = json.loads(await asyncio.wait_for(live.stdout.readline(), 60)) station.reads("outdoor", "temperature", "21.5") + station.reads("wind", "wind_direction", "300") # (and the wind backs from the east to WNW) + station.highs_today({"wind_gust": 60.0, "uv_max": 9.0, "rain_rate_max": 0.0}) # (and today's highest gust and UV rise, rain + # rate's a dry day's 0, and today's + station.held(ROSE_LATER, pressure_hour(-1.5)) # rose turns to the west; the pressure falls) await server.publish_changes() live.stdin.write(b"go\n") await live.stdin.drain() out, err = await asyncio.wait_for(live.communicate(), 60) assert live.returncode == 0, err.decode() after = json.loads(out) - n = len(gauge_sheet.sheet(Station().current(gauge_sheet.call(), {"fetch": False})).tiles) + sheet = gauge_sheet.sheet(Station().current(gauge_sheet.call(), {"fetch": False})).tiles + n, kinds = len(sheet), [t.kind for t in sheet] for name, (width, height) in SIZES.items(): got = report[name] assert got["errors"] == [], (name, got["errors"]) assert got["tiles"] == n and got["scrollWidth"] <= width, (name, got) - assert got["status"] == "updated 18:42", (name, got) + assert [g["title"] for g in got["gauges"]] == [t.title for t in sheet], (name, got["gauges"]) # (no indoor tile drawn) + assert got["status"] == "last reading 18:42", (name, got) # (the US AQI's 56, Moderate: haze behind the tiles) assert all(r["right"] <= width + 0.5 and r["left"] >= -0.5 for r in got["rects"]), (name, got) - assert (shots / f"dashboard-{name}.png").exists() + assert (shots / f"dashboard-{name}.png").exists() and (shots / f"dashboard-{name}-zoomed.png").exists() + assert got["zoomed"]["zoomed"], (name, got["zoomed"]) + fills(got["zoomed"], width, height) # zoomed: its title and gauge fill the window, no table + # no band word ("Good", "Moderate"...) under any dial: its words are its scale's numbers, its unit and its reading alone; every + # gauge drawn lower than it was, the same for every kind (its top this far further below the title's bottom), all of it above + # the table's place + for g in got["gauges"]: + t = next(t for t in sheet if t.title == g["title"]) + assert g["bands"] == 0, (name, g) + if g["kind"] == "dial": # (besides its reading) + assert sorted(g["words"]) == sorted([*(str(int(x)) if float(x).is_integer() else str(x) for x in t.ticks), t.unit]), (name, g) + assert g["gap"] >= GAPS_BEFORE[g["kind"]] + 12 and g["gap"] >= 15, (name, g) + assert g["bottom"] <= TABLE_TOP + 0.5, (name, g) + # the thermometers' glass catches the light: one straight line down the tube (no curve on the bulb, no second line); no dial + # or beaker has it + assert sorted(k for k, _ in got["glass"]) == sorted(kinds) and {"thermometer", "dial", "beaker"} <= set(kinds), got["glass"] + assert all(len(g) == (1 if k == "thermometer" else 0) for k, g in got["glass"]), got["glass"] + for _, (d,) in (g for g in got["glass"] if g[0] == "thermometer"): + m = re.fullmatch(r"M([\d.]+),([\d.]+) L([\d.]+),([\d.]+)", d) # (a straight line, upright: one segment) + assert m and m[1] == m[3] and float(m[4]) - float(m[2]) > 100, d + tile, glass = got["zoomed"]["box"], got["zoomed"]["glass"] # (the first tile, Temperature) zoomed: the glass with it + assert len(glass) == 1 and all(g["height"] > 0 and tile["left"] <= g["left"] and g["right"] <= tile["right"] for g in glass) + assert glass[0]["height"] > tile["width"] * 0.2 and glass[0]["width"] < glass[0]["height"] * 0.06, (glass, tile) + # the wind's direction, a compass: N, E, S and W named (all four alike: no red N), its needle's head turned to where the wind comes + # from (99°, east), its reading "99°" (the degrees only; its label keeps the compass point); no table, the same size as its neighbours + c, rects = got["compass"], got["rects"] + assert (c["label"], c["reading"], c["turn"], c["faded"]) == ("Wind direction 99° E", "99°", "rotate(99.00 240 203)", False), c + assert c["points"] == ["N", "E", "S", "W"] and c["table"] == 0, c + assert c["pointColours"] == [look()["soft"]] * 4 and "compass_north" not in look(), c + assert any(near(c["box"], r, 0.5) for r in rects) and len({(round(r["width"]), round(r["height"])) for r in rects}) == 1, c + compass_as_a_dial(c) + ring, head = c["ring"], c["head"] + assert (head["left"] + head["right"]) / 2 > (ring["left"] + ring["right"]) / 2 + ring["width"] * 0.1 and abs((head["top"] + head["bottom"]) / 2 - (ring["top"] + ring["bottom"]) / 2) < ring["height"] * 0.1, c + # ... the end to read unmistakable: the head a slim sharp blade in the red hands' red, the tail a short, dim taper of another + one_end_to_read(c) + # ... today's rose under it all, a petal per compass point blown from, as long as its share (the longest 80% of the radius) + rose_drawn(c, ROSE) + assert all(c["box"]["left"] <= r["left"] and r["right"] <= c["box"]["right"] and r["bottom"] <= c["box"]["top"] + c["box"]["width"] * TABLE_TOP / look()["cell"][0] + for r in c["texts"]), c # (all of it above where a table would start) + # zoomed: the compass and its reading fill the zoomed place, as any tile's title and gauge + z = got["compassZoomed"] + assert z["zoomed"] and z["shown"] and near(z["box"], zoomed_rect(width, height), 1.5), (name, z) + for r in [z["title"], z["ring"], *z["texts"]]: + assert z["box"]["left"] - 1 <= r["left"] and r["right"] <= z["box"]["right"] + 1 and z["box"]["top"] - 1 <= r["top"] and r["bottom"] <= z["box"]["bottom"] + 1, (r, z) + assert z["ring"]["width"] > z["box"]["width"] * 0.45, z + one_end_to_read(z) # (zoomed too) + compass_as_a_dial(z) + rose_drawn(z, ROSE) + assert (shots / f"dashboard-{name}-compass.png").exists() + # the dials with a red mark at today's highest (Wind's gust, Rain rate's, Solar radiation's, UV's), over the dial and the + # needle, under the hub; none on any other tile; the Wind's table: its highest speed, and its highest gust beside it + hands = got["hands"] + assert {t for t, h in hands.items() if h} == set(RED_HANDS), hands + for title, value in {"Wind": 37.0, "Rain rate": 4.2, "Solar radiation": 820.0, "UV index": 6.5}.items(): + h, tile = hands[title], next(t for t in sheet if t.title == title) + assert h["turn"] == hand_turn(tile, value) and h["shown"], (name, title, h) + assert h["order"][0] < h["order"][1] < h["order"][2], (name, title, h) + limit_mark(h, name, title) # (every one, the Wind's gust too: no hand, a limit mark (rim triangle) pointing in) + # ... zoomed, the UV's the same, scaled with the tile + z, grid = got["uvZoomed"], hands["UV index"] + assert z["zoomed"] and z["turn"] == grid["turn"] and z["limit"]["tileWidth"] > grid["limit"]["tileWidth"], (name, z) + limit_mark(z, name, "UV index (zoomed)") + assert (z["limit"]["drawnWidth"] / z["limit"]["tileWidth"] == pytest.approx(grid["limit"]["drawnWidth"] / grid["limit"]["tileWidth"], rel=0.05)), (z, grid) + assert (shots / f"dashboard-{name}-uv.png").exists() + assert hands["Wind"]["heads"] == ["▲ Max", "» Gust"] and wind.columns == ("Max", "Gust"), hands["Wind"] + # ... its heads: Max grey, Gust in the red hand's very red (the hand and its column go together); every other tile's Max red + assert hands["Wind"]["headColours"] == [rgb(look()["needle"]), rgb(look()["high_hand"])], hands["Wind"] + others = got["headColours"] + assert others["Wind"] == [["▲ Max", rgb(look()["needle"])], ["» Gust", rgb(look()["high_hand"])]], others + assert any(t != "Wind" and heads for t, heads in others.items()), others + assert all(c == rgb(CHIPS[n.split()[-1]]) for t, heads in others.items() if t != "Wind" for n, c in heads), others + assert all(c == rgb(MAX_CHIP) for t, heads in others.items() if t != "Wind" for n, c in heads if n.endswith("Max")), others + assert hands["Wind"]["daily"] == [f"{v:.0f}" for v in wind.rows["Daily"]] and wind.rows["Daily"][1] >= 12, (hands["Wind"], wind) + # every round dial's hub small (about half the old 25), its outline as thin, its needle pivoting on its centre; the compass's + # smaller still; the pressure in whole hPa, its reading and its table; its arrow after its reading (risen over the past hour: up, blue), no other's + dials = got["dials"] + assert {d["kind"] for d in dials.values()} == {"dial", "compass"} and len(dials) >= 6, dials + for title, d in dials.items(): + assert d["hub"][:2] == [240, 203] and d["pivot"] == pytest.approx([240, 203], abs=0.01), (name, title, d) + if d["kind"] == "dial": + assert d["hub"][2] == 13 and d["hub"][3] == pytest.approx(1.5 * 100 / 72), (name, title, d) + else: + assert d["hub"][2] <= 13, (name, title, d) + assert (d["arrow"] is not None) == (title == "Atmospheric pressure"), (name, title, d) + p = dials["Atmospheric pressure"] + assert re.fullmatch(r"\d{3,4}", p["reading"]) and p["figures"] and all(re.fullmatch(r"\d{3,4}|-|", f) for f in p["figures"]), p + arrow_drawn(p, "up", name) + z = got["pressureZoomed"] # ... zoomed: the same, scaled with the tile + assert z["zoomed"] and z["arrow"]["d"] == p["arrow"]["d"] and z["hub"] == p["hub"], (name, z) + arrow_drawn(z, "up", f"{name}, zoomed") + drawn = lambda d: (d["arrow"]["rect"][3] - d["arrow"]["rect"][1]) / d["arrow"]["tileWidth"] + assert drawn(z) == pytest.approx(drawn(p), rel=0.05) and z["arrow"]["tileWidth"] > p["arrow"]["tileWidth"], (name, z) + assert (shots / f"dashboard-{name}-pressure.png").exists() + # ... in inHg (zoomed, its switch pressed): its reading in inHg, wider: the arrow the same way, kept just after it + h = got["pressureInHg"] + assert re.fullmatch(r"\d\d\.\d\d", h["reading"]) and h["arrow"]["box"][0] > z["arrow"]["box"][0] + 5, (name, h) + arrow_drawn(h, "up", f"{name}, inHg") for name in ("tablet-landscape", "tablet-portrait", "desktop"): # these fit every tile without scrolling got = report[name] assert got["scroll"] == "no" and got["scrollHeight"] <= SIZES[name][1], (name, got) @@ -356,23 +895,114 @@ async def test_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overfl assert before["label"] == "Temperature 12.9 °C" and after["label"] == "Temperature 21.5 °C", (before, after) assert after["same_page"] and after["errors"] == [], after assert after["same_tile"] and "21.5 °C" in after["shown"], after # the gauge moved in place to the new reading + # the compass's needle swung from 99° to 300° the short way round, through north (never through the south), the reading WNW + c = after["compass"] + assert (c["label"], c["reading"], c["turn"]) == ("Wind direction 300° WNW", "300°", "rotate(300.00 240 203)"), c + rose_drawn(c, ROSE_LATER) # (today's rose redrawn in place with it) + arrow_drawn(before["pressure"], "up", "live, before") # ... and the pressure's arrow turned down, in place + arrow_drawn(after["pressure"], "down", "live, after") + assert after["pressure"]["same"], after["pressure"] + turns = c["turns"] + assert all(t <= 99.01 or t >= 299.99 for t in turns) and any(t < 30 for t in turns) and any(t > 330 for t in turns), turns + # the Wind's red hand moved smoothly, frame by frame, from today's highest gust before (37) to the new one (60) + windy = next(t for t in sheet if t.title == "Wind") + h, frames = after["hands"]["Wind"], after["hands"]["frames"] + assert h["turn"] == hand_turn(windy, 60.0) and frames[0] == turn_of(windy, 37.0) and frames[-1] == turn_of(windy, 60.0), h + between = [f for f in frames if turn_of(windy, 37.0) < f < turn_of(windy, 60.0)] + assert len(set(between)) >= 8 and all(a <= b for a, b in zip(frames, frames[1:])), frames + # ... and the UV's limit mark, eased the same way from today's highest before (6.5) to the new one (9), still a limit mark + uv = next(t for t in sheet if t.title == "UV index") + h, frames = after["hands"]["UV index"], after["hands"]["limitFrames"] + assert h["kind"] == "limit" and h["turn"] == hand_turn(uv, 9.0) and frames[0] == turn_of(uv, 6.5) and frames[-1] == turn_of(uv, 9.0), (h, frames) + between = [f for f in frames if turn_of(uv, 6.5) < f < turn_of(uv, 9.0)] + assert len(set(between)) >= 8 and all(a <= b for a, b in zip(frames, frames[1:])), frames + # ... and Rain rate's hidden while today's highest is 0 (a dry day: nothing to mark) + assert after["hands"]["Rain rate"]["kind"] == "limit" and not after["hands"]["Rain rate"]["shown"], after["hands"]["Rain rate"] + + +def arrow_drawn(p: dict, way: str | None, name: str): + """The pressure's arrow after its reading (dialsLook's), its way over the past hour: none (`way` None: hidden), or a fine, + instrument-style arrow: one thin straight shaft and a small, narrow, sharp open head (two short strokes from its tip, back and + out to either side: a slim chevron, narrower than 45 degrees), no fill, no outline; up and blue (the needle's) when rising, down + and red (the red hands') when falling, none when steady (`way` None), about the digits' height; just after the reading (its + head's back 2 px from the last digit's ink), vertically centred on its digits' ink; clear of the hub, the unit, the tick numbers, + the title and the table (and, in hPa, inside the dial's outline; inHg's wider reading reaches the ring and the arrow is drawn over it).""" + a = p["arrow"] + if way is None: + assert a is not None and not a["shown"] and a["way"] == "", (name, a) + return + assert a["shown"] and a["way"] == way and a["fill"] == "none" and "edge" not in a, (name, a) + assert a["stroke"] == rgb({"up": look()["needle"], "down": look()["high_hand"]}[way]), (name, a) + assert look()["rising"] == look()["needle"] == "#3E86C0" and look()["falling"] == look()["high_hand"] == "#FF3B30", look() + assert 1 <= a["width"] <= 2 and a["width"] < a["hubWidth"], (name, a) # (fine: about 1.2) + assert re.fullmatch(r"M[\d.]+,[\d.]+ L[\d.]+,[\d.]+ M[\d.]+,[\d.]+ L[\d.]+,[\d.]+ L[\d.]+,[\d.]+", a["d"]), (name, a["d"]) + x0, y0, x1, y1, hx0, hy0, tx, ty, hx1, hy1 = map(float, re.findall(r"[\d.]+", a["d"])) # (the shaft, then the head) + assert (tx, ty) == (x1, y1), (name, a["d"]) # the head at the shaft's tip + k, back = abs(hx0 - tx), abs(hy0 - ty) + assert 2 <= k <= 5 and 1.6 * k <= back <= 3 * k, (name, a["d"]) # a slim chevron: longer than wide (under 32 degrees a side) + assert x0 == x1 and hy0 == hy1 and (hx1 - tx) == pytest.approx(tx - hx0), (name, a["d"]) + assert hy0 == pytest.approx(ty + back if way == "up" else ty - back), (name, a["d"]) + ink_top, ink_bottom = a["ink"] + tall = ink_bottom - ink_top # (the digits' height: about 38 px at 50 px) + assert (y1 < y0) == (way == "up") and 0.7 * tall <= abs(y1 - y0) <= tall, (name, a["d"], tall) + bx0, by0, bx1, by1 = a["box"] + assert bx0 - a["inkRight"] == pytest.approx(2, abs=0.5), (name, a["box"], a["inkRight"]) # a 2 px gap after the last digit's ink + assert (by0 + by1) / 2 == pytest.approx((ink_top + ink_bottom) / 2, abs=1), (name, a["box"], a["ink"]) # centred on its digits + pad = a["width"] / 2 + clear = lambda b: b[2] < bx0 - pad or b[0] > bx1 + pad or b[3] < by0 - pad or b[1] > by1 + pad + assert clear(a["hub"]) and clear(a["unit"]) and all(map(clear, a["ticks"])), (name, a["box"], [t for t in a["ticks"] if not clear(t)]) + rx0, ry0, rx1, ry1 = a["rect"] + assert all(r[2] <= rx0 or r[0] >= rx1 or r[3] <= ry0 or r[1] >= ry1 for r in a["words"]), (name, a["rect"], a["words"]) # (window px) + cx, cy, r, w = a["ring"] + reach = max(math.hypot(x - cx, y - cy) for x, y in a["along"]) + a["width"] / 2 + if "inHg" not in name: + assert reach < r - w / 2 - 1, (name, reach, a["ring"]) # inside the outline, clear of it + else: + assert reach < r + w / 2 + 6, (name, reach, a["ring"]) # (inHg: at most across it, over the ring) + + +def limit_mark(h, name, title): + """A dial's limit mark at today's highest (handsLook's): a small solid triangle in the red hands' red, no hand; its base flush with + the dial's outer edge (the outline), its tip reaching into the coloured band, pointing in at the centre; small (about 4 % of the + tile's width); clear of the title's text and of every tick number.""" + m = h["limit"] + assert h["kind"] == "limit" and h["colour"] is None and m["fill"] == look()["high_hand"], (name, title, h) + tip, *base = m["radii"] # (the base flush with the dial's outer edge, the tip reaching into the coloured band) + assert tip < look()["ring_outer"] < min(base) and abs(min(base) - m["ring"]) <= 1 and m["inward"], (name, title, m) + assert 12 <= m["size"]["width"] <= 24 and 12 <= m["size"]["height"] <= 24, (name, title, m) + assert 0.02 < m["drawnWidth"] / m["tileWidth"] < 0.06, (name, title, m) + assert m["clearOfTitle"] and m["clearOfTicks"], (name, title, m) + + +def turn_of(tile, value: float) -> float: + """A red hand's turn (degrees, SVG's: clockwise) at this reading on a dial (gauge_look's START and SWEEP; drawn pointing right).""" + return round(-(START - SWEEP * min(max((value - tile.low) / (tile.high - tile.low), 0), 1)), 2) + + +def hand_turn(tile, value: float) -> str: + return f"rotate({turn_of(tile, value):.2f} 240 203)" -@pytest.mark.skipif(not browser_there(), reason="needs node with Playwright's Chromium") +@needs_browser @pytest.mark.parametrize("comes", [True, False]) async def test_a_tile_with_no_reading_is_dimmed_at_its_floor_and_a_reading_coming_brightens_it_and_moves_it_up_in_place(server, station, comes): """The air sensor sends no NOx index: its tile is dimmed (L.fade), its needle at the dial's start and its number the floor (1). A reading arriving: the same tile brightens and its gauge moves up from the floor, frame by frame, nothing drawn again (no flash). A - reading going away (the VOC index): it dims and drops to its floor.""" + reading going away (the VOC index): it dims and drops to its floor; the wind's direction gone with it, its compass dims, its needle + back at north and no figure claimed.""" title, column, value = ("NOx index", "nox_index", 60) if comes else ("VOC index", "voc_index", None) + station.held(pressure=pressure_hour(0.1) if comes else [(m, 1012.0) for m in range(40, -1, -5)]) # (the pressure steady over + # the past hour; or only 40 minutes of it: no arrow) port = free_port() - async with Serving(http_app(server, tokens=(TOKEN,)), port): + async with Serving(http_app(server, tokens=(TOKEN,)), port): # (no weather: as run_page's weather=False) page = await asyncio.create_subprocess_exec("node", str(BROWSER), f"http://127.0.0.1:{port}/dashboard", "--arrive", title, - stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=NO_WEATHER) before = json.loads(await asyncio.wait_for(page.stdout.readline(), 60)) station.air_reads(column, value) - assert await server.publish_changes() == [AIR_URI] # the air sensor's change: the page is told + if not comes: # (the wind's direction gone too: the station's) + station.reads("wind", "wind_direction", "--") + assert sorted(await server.publish_changes()) == sorted([AIR_URI] if comes else [AIR_URI, WEATHER_URI]) # the page is told page.stdin.write(b"go\n") await page.stdin.drain() out, err = await asyncio.wait_for(page.communicate(), 60) @@ -380,6 +1010,7 @@ async def test_a_tile_with_no_reading_is_dimmed_at_its_floor_and_a_reading_comin got = json.loads(out) after, frames = got["after"], got["frames"] assert got["errors"] == [] and got["same_tile"], got # moved in place: the same tile, not drawn again + arrow_drawn(got["pressure"], None, f"arrive, {comes}") # (the pressure's arrow: none, steady or without an hour of readings) numbers = [float(f["number"]) for f in frames] opacities = [f["opacity"] for f in frames] if comes: @@ -390,11 +1021,16 @@ async def test_a_tile_with_no_reading_is_dimmed_at_its_floor_and_a_reading_comin assert opacities == sorted(opacities) and opacities[0] < 1, opacities # brightening, never a flash assert before["needle"] != after["needle"] else: - assert not before["faded"] and before["number"] == "112" and "Average" in before["shown"], before + assert not before["faded"] and before["number"] == "112" and "Average" not in before["shown"], before # (no band word, ever) assert after["faded"] and after["opacity"] == pytest.approx(look()["fade"]) and after["number"] == "1", after assert "Average" not in after["shown"] and after["label"] == "VOC index: no reading" # no category without a reading assert numbers == sorted(numbers, reverse=True) and numbers[-1] == 1, numbers # down to the floor assert opacities == sorted(opacities, reverse=True), opacities + # the compass with no reading: dimmed, its needle back at north, no figure or point claimed + was, now = got["compass"] + assert not was["faded"] and was["reading"] == "99°", was + assert now["faded"] and (now["label"], now["reading"], now["turn"]) == ("Wind direction: no reading", "–", "rotate(0.00 240 203)"), now + assert was["petals"] == [] == now["petals"] and was["layers"][0] == "rose", was # (no file: no rose drawn, nothing else in its place) async def test_an_event_is_sent_when_the_air_sensors_gauges_readings_change(server, station): @@ -424,3 +1060,1937 @@ def test_what_the_events_compare_of_the_air_is_its_gauges_readings(): assert air_readings_of(None) is None and air_readings_of({}) is None assert air_readings_of(row) == (12.0, 18.0, 7.0, 520, 112, None) # PM2.5 (the AQI's too), PM10, PM1, CO2, VOC, NOx assert air_readings_of({**row, "atmp": 99}) == air_readings_of(row) # its own temperature: no gauge + + +# ---------- arranging the tiles (drag, hide, reset, preferences) and their fill ---------- +# The browser script's environment for a page with no weather behind the tiles, the rest animated (web_dashboard_browser.js's NO_WEATHER) +NO_WEATHER = {**os.environ, "DASHBOARD_NO_WEATHER": "1"} +async def run_page(server, *args, timeout=120, weather=True, parts=None, nice=0) -> dict: + """The page served, driven by the browser script with these arguments; its report. With `parts`, each part after the arguments, + side by side (each its own page, in one browser: one script's start, not one a part): their reports in one, the first part's + where two report the same, their errors together. (`weather` False: no weather drawn behind the tiles, everything else animated as + with MCP_DASHBOARD_ANIMATIONS on (NO_WEATHER): for the pages that drive the tiles and time their moves, not the weather, so the + machine's time goes to those moves. The weather's own tests drive the tiles over it, zoomed too.) `nice`: the browser run at that + lower priority.""" + port = free_port() + async with Serving(http_app(server, tokens=(TOKEN,)), port): + lower = ["nice", "-n", str(nice)] if nice and shutil.which("nice") else [] + page = await asyncio.create_subprocess_exec(*lower, "node", str(BROWSER), f"http://127.0.0.1:{port}/dashboard", *args, + *(["+".join(parts)] if parts else []), stdout=subprocess.PIPE, stderr=subprocess.PIPE, + env=None if weather else NO_WEATHER) + out, err = await asyncio.wait_for(page.communicate(), timeout) + assert page.returncode == 0, err.decode() + reports = json.loads(out) + if parts is None: + return reports + if len(parts) == 1: + reports = [reports] + got = {"errors": []} + for report in reports: + got["errors"] += report.pop("errors") + got |= {k: v for k, v in report.items() if k not in got} + return got + + +def titles_of(station) -> list[str]: + return [t.title for t in gauge_sheet.sheet(station.current(gauge_sheet.call(), {"fetch": False})).tiles] + + +def moved(titles, title, after): + """The titles with `title` taken out and put back just after `after`.""" + out = [t for t in titles if t != title] + out.insert(out.index(after) + 1, title) + return out + + +TEMPERATURES = ("Temperature", "Dew point", "Feels like") # (the fixture's tiles in °C; Indoor temperature's the same, by its unit) + + +def in_units(figure: str, convert, decimals: int) -> str: + """A figure as the page shows it in the other unit: converted, the same decimals ("-" and "" as they are).""" + return figure if figure in ("-", "") else f"{convert(float(figure)):.{decimals}f}" + + +def units_switched(seen: dict): + """The units' switches (unitsSwitched's): °F converts every temperature tile (its reading, scale, ticks, figures and unit), mph the + Wind's (its reading, dial, ticks, figures, unit and gust hand), inHg Atmospheric pressure's (its arrow's way as it was), in the + Rain's and the Rain rate's (its limit mark too), the same decimals (two in inHg and inches), the rest untouched; the gauges eased + there; kept across a reload; km/h again from the keyboard; "reset preferences" metric again, nothing kept.""" + f, mph, inhg, inch = (lambda c: c * 9 / 5 + 32), (lambda k: k / 1.609344), (lambda h: h / 33.8639), (lambda m: m / 25.4) + metric, fahrenheit, both = seen["metric"], seen["fahrenheit"], seen["mph"] + pairs = (("°C", "°F"), ("km/h", "mph"), ("hPa", "inHg"), ("mm", "in")) + switch = lambda *on: [[u, str(o if i else not o).lower()] for (pair, o) in zip(pairs, [*on, False, False][:4]) for i, u in enumerate(pair)] + RAINS = ("Atmospheric pressure", "Rain", "Rain rate") + assert metric["pressed"] == switch(False, False) and metric["status"] == "last reading 18:42" and metric["stored"] is None, metric + for title in TEMPERATURES: + was, now = metric["tiles"][title], fahrenheit["tiles"][title] + number, unit = was["reading"].split() + assert unit == "°C" and now["reading"] == f"{f(float(number)):.1f} °F" and now["label"] == f"{title} {now['reading']}", (title, now) + assert was["words"] == ["40", "30", "20", "10", "0"] and now["words"] == ["100", "80", "60", "40"], (title, now) # (0-40 °C: 32-104 °F) + assert was["unit"] == "°C" and now["unit"] == "°F", now + assert now["figures"] == [in_units(x, f, 1) for x in was["figures"]] and len(now["figures"]) == 6, (title, was, now) + assert fahrenheit["tiles"]["Temperature"]["reading"] == "55.2 °F" # (spot values: 12.9 °C, its Daily Max 20.0 °C) + assert fahrenheit["tiles"]["Temperature"]["figures"][0] == "68.0" + assert fahrenheit["tiles"]["Wind"] == metric["tiles"]["Wind"] and fahrenheit["tiles"]["Humidity"] == metric["tiles"]["Humidity"] + assert fahrenheit["pressed"] == switch(True, False) and fahrenheit["focused"] == "°F", fahrenheit + assert fahrenheit["status"] == "last reading 18:42" and fahrenheit["stored"] == {"order": [], "hidden": [], "temperature": "°F"} + # mph: the Wind's reading, dial (0-60 mph, every 10), figures, unit and gust hand; the temperatures still °F, Humidity untouched + was, now = metric["tiles"]["Wind"], both["tiles"]["Wind"] + assert was["words"] == ["0", "20", "40", "60", "80", "100", "km/h"] and now["words"] == ["0", "10", "20", "30", "40", "50", "60", "mph"], now + assert now["reading"] == in_units(was["reading"], mph, 0) and now["unit"] == "mph" and now["label"] == f"Wind {now['reading']} mph", now + assert now["figures"] == [in_units(x, mph, 0) for x in was["figures"]] and (was["figures"][1], now["figures"][1]) == ("28", "17"), (was, now) + share = mph(28) / 60 # (the red hand: today's highest gust, its Daily Gust) + assert now["hand"] == f"rotate({-(look()['start'] - look()['sweep'] * share):.2f} 240 203)" != was["hand"], (was, now) + assert seen["needleSteps"] > 3, seen["needleSteps"] # (eased there, frame by frame) + assert {t: both["tiles"][t] for t in TEMPERATURES} == {t: fahrenheit["tiles"][t] for t in TEMPERATURES} + assert both["tiles"]["Humidity"] == metric["tiles"]["Humidity"] and both["pressed"] == switch(True, True) + assert both["stored"] == {"order": [], "hidden": [], "temperature": "°F", "wind": "mph"}, both["stored"] + assert {t: fahrenheit["tiles"][t] for t in RAINS} == {t: both["tiles"][t] for t in RAINS} == {t: metric["tiles"][t] for t in RAINS} + # inHg: Atmospheric pressure's reading, dial (950-1050 hPa: 28-31 inHg, every 0.5), figures (two decimals) and unit; its arrow's + # way the same; the rest as they were + was, now = metric["tiles"]["Atmospheric pressure"], seen["inHg"]["tiles"]["Atmospheric pressure"] + assert was["words"] == ["950", "970", "990", "1010", "1030", "1050", "hPa"], was + assert now["words"] == ["28", "28.5", "29", "29.5", "30", "30.5", "31", "inHg"], now + assert (was["reading"], now["reading"]) == ("1026", "30.30") and now["label"] == "Atmospheric pressure 30.30 inHg", now + assert now["figures"] == [in_units(x, inhg, 2) for x in was["figures"]] and now["figures"][-1] == "29.47", (was, now) # (998 hPa) + assert (was["unit"], now["unit"]) == ("hPa", "inHg") and now["arrow"] == was["arrow"], now # (its arrow: the sizes' test's) + assert {t: v for t, v in seen["inHg"]["tiles"].items() if t != "Atmospheric pressure"} == \ + {t: v for t, v in both["tiles"].items() if t != "Atmospheric pressure"} + assert seen["inHg"]["pressed"] == switch(True, True, True) + assert seen["inHg"]["stored"] == {"order": [], "hidden": [], "temperature": "°F", "wind": "mph", "pressure": "inHg"} + # in: the Rain's reading, beaker (0-100 mm: 0-4 in), figures and unit; the Rain rate's reading, dial (0-50 mm/h: 0-2 in/h, every + # 0.5), figures, unit and limit mark (today's high, 8 mm/h); two decimals; the rest as they were + inches = seen["inches"] + was, now = metric["tiles"]["Rain"], inches["tiles"]["Rain"] + assert was["words"] == ["100", "80", "60", "40", "20", "0"] and now["words"] == ["4", "3", "2", "1", "0"], now + assert (was["reading"], now["reading"]) == ("0.2 mm", "0.01 in") and now["label"] == "Rain 0.01 in" and now["unit"] == "in", now + assert now["figures"] == [in_units(x, inch, 2) for x in was["figures"]] and now["figures"][-1] == "9.14", (was, now) # (232.2 mm) + was, now = metric["tiles"]["Rain rate"], inches["tiles"]["Rain rate"] + assert was["words"] == ["0", "10", "20", "30", "40", "50", "mm/h"] and now["words"] == ["0", "0.5", "1", "1.5", "2", "in/h"], now + assert (was["reading"], now["reading"]) == ("0.0", "0.00") and now["label"] == "Rain rate 0.00 in/h" and now["unit"] == "in/h", now + assert now["figures"] == [in_units(x, inch, 2) for x in was["figures"]] and now["figures"][0] == "0.31", (was, now) # (8.0 mm/h) + turned = lambda share: f"rotate({-(look()['start'] - look()['sweep'] * share):.2f} 240 203)" + assert was["hand"] == turned(8 / 50) and now["hand"] == turned(inch(8) / 2), (was, now) + assert {t: v for t, v in inches["tiles"].items() if t not in ("Rain", "Rain rate")} == \ + {t: v for t, v in seen["inHg"]["tiles"].items() if t not in ("Rain", "Rain rate")} + assert inches["pressed"] == switch(True, True, True, True) and inches["focused"] == "in", inches + assert inches["status"] == "last reading 18:42" + assert inches["stored"] == {"order": [], "hidden": [], "temperature": "°F", "wind": "mph", "pressure": "inHg", "rain": "in"} + # reloaded: as it was left + assert seen["reloaded"]["tiles"] == inches["tiles"] and seen["reloaded"]["pressed"] == switch(True, True, True, True), seen["reloaded"] + # km/h from the keyboard (Enter): the Wind metric again, the rest as they were, the focus kept on the switch + keyboard = seen["keyboard"] + assert keyboard["tiles"]["Wind"] == metric["tiles"]["Wind"] and keyboard["pressed"] == switch(True, False, True, True) + assert keyboard["focused"] == "km/h" + assert {t: v for t, v in keyboard["tiles"].items() if t != "Wind"} == {t: v for t, v in inches["tiles"].items() if t != "Wind"} + assert keyboard["stored"] == {"order": [], "hidden": [], "temperature": "°F", "pressure": "inHg", "rain": "in"} + # "reset preferences": all four metric, nothing kept, the link gone + assert seen["reset"]["tiles"] == metric["tiles"] and seen["reset"]["pressed"] == switch(False, False), seen["reset"] + assert seen["reset"]["stored"] is None and seen["reset"]["status"] == "last reading 18:42" + + +@needs_browser +async def test_tiles_are_dragged_to_reorder_hidden_by_the_x_or_the_remove_zone_kept_across_reloads_and_reset(server, station): + got = await run_page(server, "--arrange", weather=False, parts=("dragged", "hidden", "prefs", "stale", "reset")) + default = titles_of(station) + assert got["errors"] == [] and got["initial"] == default, got["errors"] + # mouseover: the grip and the × on the tile under the mouse only + assert got["hover"] == [{"grip": "0", "close": "0"}, {"grip": "1", "close": "1"}, {"grip": "0", "close": "0"}] + # the grip: 15 by 20 px (dots 5 px apart: three across, four down), in the tile's top left corner + assert got["grip"] == {"width": 15, "height": 20, "left": 8, "top": 6, "dots": "5px 5px"}, got["grip"] + # dragged from its gauge: the others make room as it goes (transforms), the remove zone shows; the order kept + assert got["during"] == {"zone": "none", "over": False, "dragging": True, "moved": ["Humidity", "Atmospheric pressure"]} + reordered = moved(default, "Temperature", "Atmospheric pressure") + assert got["dragged"] == reordered and got["transforms"] == 0 + assert got["storedAfterDrag"] == {"order": reordered, "hidden": []} + # a drag starting on the title, the table or the reading moves nothing: it selects the text + assert got["text"] == {"title": {"same": True, "dragging": False, "selected": "Rain"}, + "table": {"same": True, "dragging": False, "selected": "85"}, + "reading": {"same": True, "dragging": False, "selected": "70"}} + # the ×, then the remove zone, hide; the reset link shows beside the time + assert got["closed"] == {"titles": [t for t in reordered if t != "Rain"], "status": "last reading 18:42"} + assert got["removing"]["over"] and got["removing"]["zone"] == "none" + shown = [t for t in reordered if t not in ("Rain", "Wind")] + assert got["removed"] == {"titles": shown, "stored": {"order": reordered, "hidden": ["Rain", "Wind"]}} + assert got["reloaded"] == {"titles": shown, "status": "last reading 18:42"} + # reset: every tile, in the default order, nothing kept, no link + assert got["reset"] == {"titles": default, "status": "last reading 18:42", "stored": None} + units_switched(got["units"]) + # "reset preferences" left of the units' switches, in the bar with them: the switches never move for it (their boxes the same + # with it shown and gone), the link left of the first switch (or above them when the row is full), on screen, over nothing, + # not in the strip; clicking it puts the tiles, units and order back + bar = got["resetBar"] + assert sorted(bar["widths"], key=int) == ["320", "390", "768", "1024", "1440"], list(bar["widths"]) + for width, seen in bar["widths"].items(): + assert seen["first"]["link"] is None and seen["gone"]["link"] is None, (width, seen) + assert seen["shown"]["name"] == "reset preferences" and not seen["shown"]["linkInStrip"], (width, seen["shown"]) + assert seen["shown"]["units"] == seen["first"]["units"] == seen["gone"]["units"], (width, seen) # (identical boxes) + assert seen["shown"]["strip"] == seen["first"]["strip"] and seen["shown"]["status"] == "last reading 18:42", (width, seen) + assert seen["shown"]["onScreen"] and seen["shown"]["clear"], (width, seen["shown"]) + link, first = seen["shown"]["link"], seen["shown"]["units"][0] + if seen["shown"]["reset"] == "row": # (left of the switches, in their row, touching their bar) + assert link["right"] <= first["left"] and link["top"] < first["bottom"] and first["top"] < link["bottom"], (width, seen["shown"]) + assert seen["shown"]["bar"]["left"] - link["right"] < 12, (width, seen["shown"]) + else: # (a full row: on its own line above, never over the switches) + assert link["bottom"] <= seen["shown"]["bar"]["top"], (width, seen["shown"]) + assert seen["restored"] and seen["stored"] is None, (width, seen) + assert {w: s["shown"]["reset"] for w, s in bar["widths"].items()}["1440"] == "row" # (side by side where there's room) + assert bar["hidden"]["link"] == 1 and "Rain" not in bar["hidden"]["titles"] and bar["back"]["link"] == 0 and bar["back"]["same"], bar + # unreadable preferences: the defaults; a tile new to the saved order in its usual place (Rain, after Atmospheric pressure; the + # wind's direction, after Wind); an + # absent tile's place and a later stage's keys kept + assert got["corrupt"] == default + # a layout saved while the AQI tile was titled "US AQI": carried over to "AQI", the tile moved or hidden as it was left + assert "AQI" in default and got["renamedMoved"] == ["AQI"] + [t for t in default if t != "AQI"] + assert got["renamedHidden"] == [t for t in default if t not in ("AQI", "Rain")] + saved = [t for t in default if t not in ("Rain", "Temperature", "Wind direction")] + ["Temperature"] # (saved before the compass) + assert got["newTile"] == moved(moved(saved, "Rain", "Atmospheric pressure"), "Wind direction", "Wind") + assert got["keptOthers"] == {"order": moved(got["newTile"], "Humidity", "Rain") + ["Gone sensor"], "hidden": ["Gone sensor"], "later": True} + # a click 150 ms after a drop reaches the page (only the drop's own click, if the browser sends one, is swallowed) + assert got["clickAfterDrop"] == ["tile"] and got["zoomedAfterDrop"] + # the × pressed from the keyboard: the focus moves on to the next tile's ×, or with no tile left, to the reset link + order = moved(got["newTile"], "Humidity", "Rain") + assert got["keyboardHide"] == [f"Hide {order[0]}", f"Hide {order[1]}", "Hide Rain", "reset preferences"] + assert got["keyboardTile"].startswith("Rain ") # (Tab reaches the tile itself before its ×) + # storage blocked: it all works, nothing saved, no error + assert got["blocked"] == {"titles": [t for t in moved(default, "Temperature", "Humidity") if t != "Rain"], "errors": []} + # see-through: the tile's own background clear, its foreground (title, reading, frame) opaque, the page its dark colour + look_ = got["look"] + assert look_["background"] == "rgba(0, 0, 0, 0)" and look_["image"] == "none" and look_["grid"] == "rgba(0, 0, 0, 0)" + assert look_["opacity"] == "1" and look_["body"] == "rgb(20, 25, 29)" + assert all(look_[k].startswith("rgb(") for k in ("title", "reading")) and look_["frameWidth"] == "1px", look_ + # the frame unseen, the mouse over its tile too; shown while it is picked up, and with the keyboard's focus + assert look_["frame"] == "rgba(0, 0, 0, 0)", look_ + assert got["hoverFrames"] == ["rgba(0, 0, 0, 0)"] * 3, got["hoverFrames"] + assert got["shownFrames"] == {"lifted": "rgb(90, 102, 112)", "focused": rgb(look()["soft"]), "after": "rgba(0, 0, 0, 0)"}, got["shownFrames"] + # the strip's reading time with a device's reading over an hour old ("stale", its data's devices altered on the way): both fresh, + # as ever; one stale, its name and own time first, greyed out, then the fresh one's; both stale (or the only device), all greyed out + stale = got["stale"] + hm = lambda step, device: stale[step]["sent"][device][11:16] + assert stale["real"] == {"text": "last reading 18:42", "grey": [], "sent": None}, stale["real"] # (the fixture's devices: fresh) + for step in ("fresh", "recovered", "onlyFresh"): + assert (stale[step]["text"], stale[step]["grey"]) == ("last reading 18:42", []), (step, stale[step]) + for step, old, new, name in (("airStale", "air", "station", "air sensor"), ("stationStale", "station", "air", "weather station")): + assert stale[step]["text"] == f"{name} {hm(step, old)} · last reading {hm(step, new)}", (step, stale[step]) + assert stale[step]["grey"] == [f"{name} {hm(step, old)}"] and hm(step, old) != hm(step, new), (step, stale[step]) + assert stale["noReading"]["text"] == f"weather station no reading · last reading {hm('noReading', 'air')}", stale["noReading"] + assert stale["noReading"]["grey"] == ["weather station no reading"], stale["noReading"] + for step in ("bothStale", "only"): # (only: no air sensor configured, never named) + assert (stale[step]["text"], stale[step]["grey"]) == ("last reading 18:42", ["last reading 18:42"]), (step, stale[step]) + assert stale["colours"][0] != stale["colours"][1], stale["colours"] # greyed: not the strip's own colour + # the station's reading turning an hour old with no new data: the strip greys out by itself, then + turning = stale["turning"] + assert turning["before"]["text"] == f"air sensor {turning['before']['sent']['air'][11:16]} · last reading {turning['before']['sent']['station'][11:16]}" + assert turning["after"]["grey"] == ["last reading 18:42"] and turning["after"]["text"] == "last reading 18:42", turning + assert 800 < turning["ms"] < 5000, turning + + +@needs_browser +async def test_on_a_touch_screen_a_long_press_picks_a_tile_up_and_a_tap_or_a_swipe_is_left_alone(server, station): + got = await run_page(server, "--touch", weather=False, parts=("taps", "edge", "held")) + default = titles_of(station) + assert got["errors"] == [] and got["initial"] == default + # a short tap: a click (it zooms the tile), nothing picked up; a swipe: the page scrolls + assert got["tap"] == {"buzz": [], "clicks": 1, "scrollY": 0, "zone": False, "armed": [], "close": None, "titles": default, "zoomed": True} + assert got["swipe"]["scrollY"] > 100 and got["swipe"]["armed"] == [] and got["swipe"]["titles"] == default + # held (on a page of its own, beside the tap's): a buzz, its grip and ×, the remove zone, no click; moved without scrolling the + # page; dropped in its new place, still no click + assert got["held"] == {"buzz": [15], "clicks": 0, "scrollY": 0, "zone": True, "armed": ["Temperature"], "close": "1"} + assert got["moving"]["scrollY"] == 0 and got["moving"]["during"]["moved"] == ["Humidity", "Atmospheric pressure"] + reordered = moved(default, "Temperature", "Atmospheric pressure") + assert got["dropped"]["titles"] == reordered and not got["dropped"]["zone"] and got["dropped"]["clicks"] == 0 + # held and let go in place: the grip and × stay, and a tap on the × hides it + assert got["armed"]["armed"] == ["Humidity"] and got["armed"]["close"] == "1" + assert got["closed"] == {"titles": [t for t in reordered if t != "Humidity"], "status": "last reading 18:42"} + # held at the bottom edge (on a page of its own, beside them): the page scrolls to its end, never past it, and stays there once let go + edge = got["edge"] + assert edge["seen"][-1] == pytest.approx(edge["end"], abs=1) and max(edge["seen"]) <= edge["end"] + 1, edge + assert edge["after"] <= edge["end"] + 1, edge + + +@needs_browser +async def test_fewer_tiles_grow_evenly_to_fill_the_window_and_never_shrink_below_the_full_dashboards_size(server, station): + every = titles_of(station) + but = lambda *keep: [t for t in every if t not in keep] + cases = {"desktop-all": (1920, 1080, []), "desktop-one": (1920, 1080, but("Temperature")), + "tablet-all": (1024, 768, []), "tablet-three": (1024, 768, but("Temperature", "Wind", "AQI")), + "tablet-many": (1024, 768, ["Rain", "Wind"]), + "phone-all": (390, 844, []), "phone-one": (390, 844, but("Humidity")), "phone-eight": (390, 844, every[:-8])} + got = await run_page(server, "--fill", json.dumps(cases), weather=False) + assert all(c["errors"] == [] and c["scrollWidth"] <= cases[name][0] for name, c in got.items()), got + width = lambda name: {round(r["width"]) for r in got[name]["rects"]} + aspect = look()["cell"][0] / look()["cell"][1] + # one tile fills the window: its whole height (less the margins and the strip), or its width on a phone, centred + (one,) = got["desktop-one"]["rects"] + assert one["height"] == pytest.approx(1080 - 16 - 18, abs=1) and one["width"] == pytest.approx(one["height"] * aspect, abs=1) + assert (one["left"] + one["right"]) / 2 == pytest.approx(1920 / 2, abs=1) + (one,) = got["phone-one"]["rects"] + assert one["width"] == pytest.approx(390 - 16, abs=1) and got["phone-one"]["scroll"] == "no" + # a few grow, evenly, all on the screen and centred + three = got["tablet-three"]["rects"] + assert len(width("tablet-three")) == 1 and min(width("tablet-three")) > 1.5 * min(width("tablet-all")), got["tablet-three"] + assert all(r["bottom"] <= 768 and r["right"] <= 1024 for r in three) + assert (min(r["left"] for r in three) + max(r["right"] for r in three)) / 2 == pytest.approx(512, abs=1) + # many: at least the full dashboard's size; a phone's scrolling tiles stay at theirs rather than shrink to fit + assert min(width("tablet-many")) >= min(width("tablet-all")) and len(got["tablet-many"]["rects"]) == len(every) - 2 + assert width("phone-eight") == width("phone-all") and got["phone-eight"]["columns"] == "2" and len(got["phone-eight"]["rects"]) == 8 + + +@needs_browser +async def test_a_phone_or_tablet_turned_and_turned_back_lays_the_page_out_exactly_as_a_fresh_load_with_no_zoom_or_overflow(server, station): + got = await run_page(server, "--rotate") + for device, report in got.items(): + assert report["errors"] == [], (device, report["errors"]) + for step in report["steps"]: + now, orientation = step["now"], step["orientation"] + assert now["fit"] == {**now["fit"], "scrollWidth": now["fit"]["clientWidth"], "innerWidth": now["fit"]["clientWidth"], "scale": 1, + "scrollX": 0, "inside": True, "skyCovers": True}, (device, orientation, now["fit"]) + assert now["snapshot"] == report["fresh"][orientation]["snapshot"], (device, orientation) + late = report["stale"] # (the real size arriving late, the page shifted sideways meanwhile: laid out as a fresh load, put back) + assert late["landscape"]["fit"] == {**late["landscape"]["fit"], "scrollWidth": late["landscape"]["fit"]["clientWidth"], "scale": 1, + "scrollX": 0, "inside": True, "skyCovers": True}, (device, late["landscape"]["fit"]) + assert late["landscape"]["snapshot"] == report["fresh"]["landscape"]["snapshot"] and late["sideways"] == 0, (device, late) + assert late["wide"] >= 0, (device, late["wide"]) + for orientation, fresh in report["fresh"].items(): # (a fresh load fits too) + assert fresh["fit"]["scrollWidth"] == fresh["fit"]["clientWidth"] and fresh["fit"]["inside"] and fresh["fit"]["skyCovers"], (device, orientation) + + +# ---------- the zoomed view and its gallery ---------- +ZOOM_MS = 200 +GAPS_BEFORE = {"dial": 2, "thermometer": 21.7, "beaker": 16.7, "compass": 2} # (the gap under the title, each kind, before the gauges + # were moved down: the tile's own px) +TABLE_TOP = 372 # (the web page's: where a tile's table starts, in its own pixels; above it the title and gauge, all a zoomed tile shows) + + +def zoomed_rect(width, height): + """The zoomed tile's place at this window size: its title and gauge (no table) as large as fits beside the margins and the status + strip, centred.""" + aspect = look()["cell"][0] / TABLE_TOP + w = min(width - 16, (height - 16 - 18) * aspect) + h = w / aspect + return {"left": (width - w) / 2, "top": 8 + (height - 16 - 18 - h) / 2, "width": w, "height": h} + + +def near(rect, want, tolerance=1.0): + return all(abs(rect[k] - want[k]) <= tolerance for k in ("left", "top", "width", "height")) + + +def fills(zl, width, height): + """A zoomed tile's look (__look) at this window size: no table; its box (the title and gauge) as large as fits, its limiting axis + within a few px of the window's room (less the margins and the status strip), centred, clear of the strip; its text inside it.""" + box, room = zl["box"], (width - 16, height - 16 - 18) + assert zl["table"] == ["hidden 0"], zl + assert box["width"] <= room[0] + 1 and box["height"] <= room[1] + 1, zl + assert room[0] - box["width"] <= 3 or room[1] - box["height"] <= 3, zl # (one axis filled) + assert box["width"] / box["height"] == pytest.approx(look()["cell"][0] / TABLE_TOP, rel=0.01), zl # (its proportions kept) + assert (box["left"] + box["right"]) / 2 == pytest.approx(width / 2, abs=1), zl + assert (box["top"] + box["bottom"]) / 2 == pytest.approx(8 + room[1] / 2, abs=1) and box["bottom"] <= height - 18, zl + for r in [zl["title"], *zl["texts"]]: # (the reading, the scale's words) + assert box["left"] - 1 <= r["left"] and r["right"] <= box["right"] + 1 and box["top"] - 1 <= r["top"] and r["bottom"] <= box["bottom"] + 1, (r, zl) + + +@needs_browser +async def test_a_click_on_a_gauge_zooms_its_tile_to_fill_the_window_the_tile_beside_it_live_and_the_keys_page(server, station): + port = free_port() + async with Serving(http_app(server, tokens=(TOKEN,)), port): # (no weather: as run_page's weather=False) + page = await asyncio.create_subprocess_exec("node", str(BROWSER), f"http://127.0.0.1:{port}/dashboard", "--zoom", "in", stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=NO_WEATHER) + before = json.loads(await asyncio.wait_for(page.stdout.readline(), 60)) + station.reads("outdoor", "temperature", "21.5") # Temperature: beside the tile shown, off the screen + await server.publish_changes() + page.stdin.write(b"go\n") + await page.stdin.drain() + out, err = await asyncio.wait_for(page.communicate(), 120) + assert page.returncode == 0, err.decode() + got = json.loads(out) + default = titles_of(station) + at = default.index + full = zoomed_rect(1024, 768) + assert got["errors"] == [] and got["initial"] == default, got["errors"] + assert default[:2] == ["Temperature", "Humidity"] and before["label"] == "Temperature 12.9 °C" + # the cursor: a magnifier with + over a gauge, the usual one over the text; zoomed, a magnifier with − (around the tile too) + assert got["cursor"] == {"gauge": "zoom-in", "title": "auto", "figure": "auto", "reading": "auto"} + assert got["zoomedCursor"] == {"gauge": "zoom-out", "margin": "zoom-out", "title": "auto"} + # a click on the gauge: its title and gauge (the grid tile's top part) grow from their place to fill the window, in 200 ms (a FLIP: + # transforms only), ending exactly there; the title moving with the tile all the way (no jump); the table gone from the start + zoom_in = got["zoomIn"] + assert zoom_in["zoomed"] and zoom_in["shown"] == "Humidity" and ZOOM_MS in zoom_in["anims"], zoom_in + grid_rect = got["gridRect"] | {"left": got["gridRect"]["x"], "top": got["gridRect"]["y"]} + assert near(zoom_in["first"], grid_rect | {"height": grid_rect["width"] * TABLE_TOP / look()["cell"][0]}, 2), zoom_in + assert near(zoom_in["last"], full) and zoom_in["between"] and 150 <= zoom_in["settledMs"] <= 330, zoom_in + assert all(t == pytest.approx(zoom_in["titles"][0], abs=0.002) for t in zoom_in["titles"]), zoom_in["titles"] # (in the tile's terms) + tables = zoom_in["tables"] + assert tables and set(tables) == {0}, tables + assert got["grip"] == "none" # (no grip or × in the zoomed view) + # zoomed: no table (the gallery's others neither); the title and gauge fill the window, centred, clear of the strip + fills(got["zoomedLook"], 1024, 768) + assert got["neighbourTable"] == ["hidden 0"], got["neighbourTable"] + # live: the tile beside it, off the screen, takes the new reading in place, and shows it as it slides in + assert got["live"] == {"label": "Temperature 21.5 °C", "sameTile": True, "zoomed": True, "shown": "Humidity", "track": -1024} + keys = got["keys"] + assert keys["left"]["shown"] == "Temperature" and keys["left"]["between"] and 150 <= keys["left"]["settledMs"] <= 330, keys + assert keys["leftReading"] == "21.5 °C" + # each key's default prevented: Backspace never goes back a page, Space never scrolls + # ← at the first: a nudge and back, still the first + assert keys["pastFirst"]["shown"] == "Temperature" and keys["pastFirst"]["track"] == 0 and keys["pastFirst"]["extreme"] >= 20, keys + assert [keys[k]["shown"] for k in ("space", "right", "backspace")] == default[1:3] + default[1:2], keys + assert all(k["zoomed"] for k in keys.values() if isinstance(k, dict)) and keys["url"] # (Backspace: still this page) + assert keys["prevented"] == [["ArrowLeft", True], ["ArrowLeft", True], [" ", True], ["ArrowRight", True], ["Backspace", True]], keys + + +ZOOM_PARTS = {"pager": ("pager", "wheel"), "last": ("last", "text", "single", "lone"), "out": ("out", "keys")} # (the browser script's, side by side) + + +async def zoomed(server, station, part: str) -> tuple[dict, list[str], dict]: + """A part of the zoom at 1024x768 (its own pages, side by side in one browser): its report, no error; the + tiles' titles; a tile's rect zoomed.""" + got = await run_page(server, "--zoom", weather=False, parts=ZOOM_PARTS[part]) + default = titles_of(station) + assert got["errors"] == [] and got["initial"] == default, got["errors"] + return got, default, zoomed_rect(1024, 768) + + +@needs_browser +async def test_zoomed_the_gallery_pages_by_mouse_drags_and_a_trackpads_swipes_springing_back_at_the_first(server, station): + got, default, full = await zoomed(server, station, "pager") + # mouse drags on the gauge: followed directly; let go past halfway, the next; a short slow one back; a quick short flick on + drag = got["drag"] + assert drag["start"]["shown"] == default[1] + assert drag["far"]["shown"] == default[2] and drag["far"]["during"] == pytest.approx(-1024 - 600, abs=12), drag + assert drag["short"]["shown"] == default[2] and drag["short"]["track"] == -2048, drag + assert drag["flick"]["shown"] == default[3] and drag["back"]["shown"] == default[2], drag + # at the first, dragged on: it gives (less than the drag), springs back + assert drag["pastFirst"]["shown"] == default[0] and 20 < drag["pastFirst"]["during"] < 300 * 0.6 and drag["pastFirst"]["track"] == 0, drag + assert all(d["zoomed"] for d in drag.values()) # (the click ending a drag doesn't go back) + # a trackpad's two-finger swipe (wheel deltaX), from the first (on a page of its own, beside that one): the next, or back if short; + # never reaching the browser + wheel = got["wheel"] + assert wheel["from"] == {"zoomed": True, "shown": default[0], "track": 0}, wheel + assert [wheel[k]["shown"] for k in ("far", "short", "back")] == [default[1], default[1], default[0]], wheel + assert wheel["prevented"] and all(wheel["prevented"]), wheel + + +@needs_browser +async def test_zoomed_the_last_tile_stops_paging_its_text_is_selectable_a_click_goes_back_and_a_single_tile_zooms_too(server, station): + got, default, full = await zoomed(server, station, "last") + # the last: → past it nudges and stays, as do a swipe and a drag on + last = got["last"] + assert last["reached"]["shown"] == default[-1] and last["pastLast"]["shown"] == default[-1] and last["pastLast"]["extreme"] >= 20, last + assert last["wheeled"]["shown"] == default[-1] and last["dragged"]["shown"] == default[-1], last + assert last["wheeled"]["track"] == last["dragged"]["track"] == -1024 * (len(default) - 1) + # a drag on the text selects it: no paging, still zoomed (on a page of its own, beside that one, the last reached the same way) + text = got["text"] + assert got["textOn"] == default[-1], got["textOn"] + assert {k: (v["selected"], v["shown"], v["zoomed"]) for k, v in text.items()} == { + "title": (default[-1], default[-1], True), "reading": (text["reading"]["selected"], default[-1], True)}, text + assert text["reading"]["selected"].strip(), text + # a click without moving: back to the dashboard in 200 ms, the tile in its place in the grid + zoom_out = got["zoomOut"] + whole = full | {"height": full["width"] * look()["cell"][1] / look()["cell"][0]} # (the whole tile, from there: its row height rounded, scaled up) + assert not zoom_out["zoomed"] and near(zoom_out["first"], whole, 3) and zoom_out["between"] and 150 <= zoom_out["settledMs"] <= 330, zoom_out + assert near(zoom_out["last"], got["outRect"] | {"left": got["outRect"]["x"], "top": got["outRect"]["y"]}) + assert zoom_out["last"]["width"] == pytest.approx(got["gridRect"]["width"], abs=0.5) + tables = zoom_out["tables"] # (its table back: hidden as it shrinks, then fading in) + assert tables[0] == 0 and tables[-1] == 1 and all(a <= b for a, b in zip(tables, tables[1:])) and got["outTable"] == ["visible 1"], (tables, got["outTable"]) + # a single tile (Humidity, the others hidden) zooms too, a gallery of one + one = got["single"] + # the magnifier over its gauge; a click zooms it to its title and gauge alone, filling the window + assert one["cursor"] == "zoom-in" and one["zoomed"] | {"look": None} == {"zoomed": True, "shown": "Humidity", "track": 0, + "cursor": "zoom-out", "look": None}, one + fills(one["zoomed"]["look"], 1024, 768) + assert near(one["zoomed"]["look"]["box"], full), one["zoomed"] + # a gallery of one: the keys nudge it and back, a drag either way gives a little and springs back, as does a trackpad's swipe (on a + # page of its own, beside that one, zoomed the same way) + lone = got["lone"] + for name, key in one["keys"].items(): + assert key["zoomed"] and key["shown"] == "Humidity" and key["track"] == 0 and key["extreme"] >= 20, (name, key) + for name, drag in one["dragged"].items(): + assert drag["zoomed"] and drag["shown"] == "Humidity" and drag["track"] == 0 and 20 < abs(drag["during"]) < 400 * 0.6, (name, drag) + assert lone["wheeled"] | {"prevented": None} == {"zoomed": True, "shown": "Humidity", "track": 0, "prevented": None}, lone["wheeled"] + assert lone["wheeled"]["prevented"] and all(lone["wheeled"]["prevented"]), lone["wheeled"] + # a click goes back, the tile in its place; Esc too + box = lambda r: r | {"left": r["x"], "top": r["y"]} + rect = lone["back"].pop("rect") + assert lone["back"] == {"zoomed": False, "shown": "Humidity", "track": 0} and near(box(rect), box(lone["gridRect"])), (lone["back"], rect) + assert near(box(lone["gridRect"]), box(one["gridRect"])), (lone["gridRect"], one["gridRect"]) + assert lone["esc"]["zoomed"] is False, lone["esc"] + + +@needs_browser +async def test_a_double_click_esc_the_bounce_cut_short_the_keyboard_and_esc_mid_zoom(server, station): + got, default, full = await zoomed(server, station, "out") + # Esc: back too, the order as it was + assert got["esc"]["before"]["zoomed"] and got["esc"]["before"]["shown"] == "Wind" and not got["esc"]["after"]["zoomed"] + assert got["esc"]["titles"] == default + # (a double-click: its second click ignored, so Esc above found it still zoomed; and a click on a gauge doesn't take the focus, so + # a key pressed after it shows no × on that tile) + assert got["esc"]["close"] == {"focused": False, "opacity": "0"}, got["esc"] + # the bounce past the last, cut short: by a key, that step slides from the start; by Esc, the dashboard at once in its place + cut = got["bounceCut"] + last_x = -1024 * (len(default) - 1) + assert cut["step"]["shown"] == default[-2] and cut["step"]["mid"] and all(last_x + 100 < x < last_x + 1024 for x in cut["step"]["mid"]), cut # (on its way, ~100 ms in) + assert cut["esc"]["grid"] == "none" and not cut["esc"]["zoomed"] and 0 <= cut["esc"]["firstLeft"] < 100, cut + # the keyboard: Enter on a focused tile zooms it; the focus goes along, the other tiles out of reach (inert); Esc back, Space too + kb = got["keyboard"] + assert kb["tabbable"] and kb["focusedClose"] == "1", kb + assert kb["enter"] | {"track": 0} == {"zoomed": True, "shown": "Temperature", "track": 0, "focus": "Temperature", "reachable": ["Temperature"]}, kb + assert kb["right"]["shown"] == kb["right"]["focus"] == "Humidity" and kb["right"]["reachable"] == ["Humidity"], kb + assert kb["tab"]["focus"] != "Temperature" and kb["tab"]["focus"] not in default[2:] and kb["tab"]["zoomed"], kb + assert not kb["esc"]["zoomed"] and kb["esc"]["focus"] == "Humidity" and kb["esc"]["reachable"] == default, kb + assert kb["space"]["zoomed"] and kb["space"]["shown"] == "Humidity" == kb["space"]["focus"], kb + # Esc mid-way through a zoom-in: back from where the tile is drawn (no jump on to the full size), its table hidden until it's in its + # grid place; the others keep their tables while they fade out (not all gone at once on the first frame) + esc = got["escMid"] + assert esc["others"] == ["visible 1"] and not esc["zoomed"], esc + assert esc["atEsc"] < full["width"] - 50 and esc["peakAfter"] < esc["atEsc"] * 1.15, esc + assert esc["tableWhileLarge"] == 0 and esc["tableEnd"] == 1, esc + assert esc["last"]["width"] == pytest.approx(got["gridRect"]["width"], abs=0.5), esc + + +@needs_browser +async def test_on_a_touch_screen_a_tap_zooms_a_swipe_pages_from_anywhere_and_a_tap_goes_back_where_the_page_was(server, station): + got = await run_page(server, "--zoom-touch", weather=False, parts=("back", "swipes", "later", "return")) + default = titles_of(station) + assert got["errors"] == [] and got["initial"] == default, got["errors"] + t = default.index(got["tapped"]) + assert got["swipesTapped"] == got["laterTapped"] == got["returnTapped"] == got["tapped"], got # (the swipes' pages, beside it: the same tile tapped) + assert got["scrolled"] > 100 + assert got["zoomed"]["zoomed"] and got["zoomed"]["shown"] == got["tapped"] + assert not got["backStraight"]["zoomed"] and abs(got["backStraight"]["scrollY"] - got["scrolled"]) <= 2, got["backStraight"] + assert near(got["zoomed"]["rect"] | {"left": got["zoomed"]["rect"]["x"], "top": got["zoomed"]["rect"]["y"]}, zoomed_rect(390, 844)) + fills(got["zoomed"]["look"], 390, 844) + assert [got[k]["shown"] for k in ("next", "previous", "flick", "fromTitle")] == [default[t + 1], default[t], default[t + 1], default[t + 2]], got + # (on pages of their own, beside them, the same tile tapped and two on: there,) a vertical swipe, a long press: nothing; three + # swipes back, and a tap back to the dashboard + assert got["vertical"]["shown"] == default[t + 2] and got["vertical"]["zoomed"] + assert got["returnFrom"] == got["vertical"], (got["returnFrom"], got["vertical"]) + assert got["held"] == {"zoomed": True, "shown": default[t + 2], "track": got["vertical"]["track"], "buzz": [], "zone": False} + assert got["backAt"]["shown"] == default[t - 1] + assert not got["out"]["zoomed"] and got["out"]["titles"] == default and got["out"]["lastShown"], got["out"] + + +# ---------- the weather behind the tiles ---------- +STREAK = [[142, 157, 168], [76, 88, 97], [239, 250, 255]] # a trail's thin streak on clear glass: its film, grime, glint +DROPLET = [[166, 215, 242], [239, 250, 255]] # a tiny droplet left on a trail, its spark +TRACK = 25.6 # px/s: down a trail, every running bead at least this fast (a freshly landed rain bead's there, r 3: 1.6 times its 16 on fog) +EFFECTS = {"rain": "Rain", "haze": "AQI", "uv": "UV index", "humidity": "Humidity", "wind": "Wind", "heat": "Temperature", + "ice": "Temperature"} + + +# The weather's parts whose pages are driven (tests/web_dashboard_browser.js, weatherPage): what they see doesn't depend on the time +# their frames take, so they run a little behind the rest (nice 5): the pages whose own timing is tested (a frame rate, the zoom's +# moves) get a CPU first when the machine is busy; the rest of the suite (conftest: nice 10) after them +DRIVEN = {"trails", "frost", "budget", "flood", "opened", "gust", "over"} + + +async def weather(server, part: str) -> dict: + """One part of the weather behind the tiles, its own page in its own browser (the parts run side by side): its report, no error.""" + got = await run_page(server, "--weather", part, nice=5 if part in DRIVEN else 0) + assert got["errors"] == [], got["errors"] + return got + + +@needs_browser +async def test_the_weather_behind_the_tiles_comes_with_its_reading_at_its_mark_and_frames_its_tile_in_red(server, station): + got = await weather(server, "marks") + # nothing called for (the US AQI Good): no effect, no frame, no link, no loop, nothing drawn + assert got["nothing"] == {"effects": [], "levels": {k: 0 for k in got["nothing"]["levels"]}, "running": False, "framed": [], + "link": None, "frames": 0, "ink": 0} + # each effect at its mark and not just short of it (rain above 0 mm/h, the AQI's Moderate band from 51, UV 11, 90 %, wind above + # 15 km/h, 35 °C, below 0 °C, not at it), its tile framed in red, the strip's link with it + for name, mark in got["marks"].items(): + effect = "ice" if name == "iceAtZero" else name + assert mark["below"] | {"levels": None} == {"effects": [], "levels": None, "running": mark["below"]["running"], "framed": [], + "link": None}, (name, mark) + assert mark["at"]["effects"] == [effect] and mark["at"]["framed"] == [EFFECTS[effect]], (name, mark) + assert mark["at"]["link"] == "stop" and mark["at"]["running"], (name, mark) + assert got["hazeBands"] == [2, 3, 4, 5, 5] # thicker with each band: USG to Hazardous + assert got["rainStrength"][0] < 0.4 and got["rainStrength"][1:] == [1, 1] # light at 0.5 mm/h, heavy from 8 + assert got["humidityStrength"] == pytest.approx([0.1, 0.5, 1]) # heavier from 90 % to 100 % + assert got["iceDepth"] == [0.5, 5] # further in the colder + assert got["heatStrength"] == pytest.approx([0.3, 0.65, 1, 1]) # stronger from 35 °C to 43 °C + # shown in °F, mph, inHg and in: the same marks, of the readings in °C, km/h and mm/h (heat from 35 °C, leaves above 15 km/h, ice + # below 0 °C, rain above 0 mm/h, heavy from 8, a flood above 30 mm/h, not at it) + calm = lambda m: {**m, "below": m["below"] | {"running": None}} # (just short: whether the last effect's still fading out aside) + assert {k: calm(m) for k, m in got["unitsMarks"].items()} == {k: calm(got["marks"][k]) for k in ("heat", "wind", "ice", "rain")} + assert got["unitsRain"][0][0] < 0.4 and [r for r, _ in got["unitsRain"][1:]] == [1, 1, 1], got["unitsRain"] + assert [bool(f) for _, f in got["unitsRain"]] == [False, False, False, True], got["unitsRain"] + # the thermometer's scale widened as the server widens it in °C (-10 to 40 °C: 14 to 104 °F; 0 to 50 °C: 32 to 122 °F) + assert got["widened"] == ["Temperature 23.0 °F", ["100", "80", "60", "40", "20"]], got["widened"] + assert got["widenedHot"] == ["Temperature 109.4 °F", ["120", "100", "80", "60", "40"]], got["widenedHot"] + + +@needs_browser +async def test_several_effects_share_one_canvas_behind_the_see_through_tiles_zoomed_too(server, station): + got = await weather(server, "several") + # several at once: one canvas, one loop, at most 30 frames drawn a second + several = got["several"] + assert several["effects"] == ["haze", "uv", "rain", "wind", "humidity", "ice"] and several["canvases"] == 3, several # (the weather's canvas and its two margins: see test_the_weather_reaches_past...) + assert sorted(several["framed"]) == sorted({EFFECTS[k] for k in several["effects"]}) and several["ink"] > 0, several + assert 20 <= several["drawn"] <= 32 and several["frames"] <= 64, several # (a second's: one request a display frame, every other one drawn) + # the canvas: filling the window, fixed, first, behind the tiles, never in the pointer's way, its pixels crisp + # (#sky now reaches OVER = 100 px past the window's top and bottom: the weather's own canvas is still the window's size) + assert got["canvas"] == {"rect": [0, -100, 1024, 968], "canvas": [True, True], "position": "fixed", "z": "0", "events": "none", + "first": True, "pixelated": "pixelated", "under": True} + # the tiles see-through (what's behind shows in a tile's margin), their foreground opaque; zoomed too + assert got["through"] == {"differs": True, "still": True} + assert got["look"] == {"background": "rgba(0, 0, 0, 0)", "opacity": "1", "title": "rgb(232, 234, 237)", "frame": "rgba(0, 0, 0, 0)", + "alertFrame": "rgba(0, 0, 0, 0)", # (the red frame off for now; the class still set) + # dragged, a framed tile shows the drag's frames as any other: lifted grey, then the remove zone's red + "dragFrames": {"lifted": "rgb(90, 102, 112)", "doomed": "rgb(229, 72, 77)", "after": "rgba(0, 0, 0, 0)"}} + assert got["zoomed"] == {"zoomed": True, "title": "UV index", "background": "rgba(0, 0, 0, 0)", "grid": "rgba(0, 0, 0, 0)", + "alert": True, "running": True} + + +def test_the_page_and_its_browser_bars_are_the_dark_colour_and_the_weather_reaches_past_the_window_in_css(): + page = PAGE.read_text() + assert re.search(r"--bg: #14191D", page) and re.search(r"html, body \{[^}]*background: var\(--bg\)", page) + assert '' in page + assert re.search(r"#sky \{[^}]*--over: 100px;[^}]*top: calc\(-1 \* var\(--over\)\); bottom: calc\(-1 \* var\(--over\)\)", page) + + +@needs_browser +async def test_the_weather_reaches_past_the_windows_top_and_bottom_so_a_hiding_address_bar_shows_no_bare_strip(server, station): + got = await weather(server, "over") + OVER = 100 + for name in ("first", "grown", "relaid"): + seen = got[name] + h = seen["inner"][1] + assert seen["canvases"] == 3, (name, seen) + # the weather's canvas and its margins: at least OVER past the top and the bottom of the window, the whole width, even with the + # viewport made taller before any relayout (the bar hidden); the margins end where the window's canvas begins + # (made taller before any relayout, the margins still cover the whole window; only the margin's own reach is what is left) + assert seen["above"][0] <= -OVER and seen["below"][1] >= (h if name == "grown" else h + OVER), (name, seen) + # (the weather's own canvas alone covers the window but when it was made taller; then it and the margin below it do together) + assert seen["canvas"][0] <= 0 and (seen["canvas"][1] >= h or (name == "grown" and seen["below"][1] >= h)), (name, seen) + assert abs(seen["above"][1] - seen["canvas"][0]) < 0.01 and abs(seen["below"][0] - seen["canvas"][1]) < 0.01, (name, seen) + assert seen["canvas"][2] <= 0 and seen["canvas"][3] >= seen["inner"][0], (name, seen) + # the weather's own world is the window's size alone (the flood's level, the gust's height: from the visible bottom): the + # margins are only the first and last rows mirrored + width, rows, p = seen["size"] + assert (name == "grown" or rows == -(-seen["client"][1] // p)) and seen["flood"] == rows, (name, seen) + assert seen["mirrored"] == {"top": True, "bottom": True, "top2": True}, (name, seen) + assert seen["ink"][1] > 0 and seen["ink"][0] > 0 and seen["ink"][2] > 0, (name, seen) + # the page's own colour all round, and the browser's bars the same + assert seen["bg"] == ["rgb(20, 25, 29)", "rgb(20, 25, 29)"] and seen["theme"] == "#14191D", (name, seen) + assert got["grown"]["inner"][1] == got["first"]["inner"][1] + 90 and got["grown"]["size"] == got["first"]["size"], got + assert got["relaid"]["size"][1] > got["first"]["size"][1], got + + +@needs_browser +async def test_stop_animation_stops_and_clears_for_this_page_view_only_nothing_saved_a_reload_or_a_test_link_runs_them_again(server, station): + got = await weather(server, "stop") + # "stop" (a test link's wind on too), its tooltip naming the setting for good + assert got["simulating"]["effects"] == ["uv", "wind"] and got["simulating"]["link"] == "stop", got["simulating"] + assert got["simulating"]["title"] == "stop until reload; set MCP_DASHBOARD_ANIMATIONS=off to turn off for good", got["simulating"] + assert got["simulating"]["label"] == "stop the animation until reload", got["simulating"] # (it reads just "stop") + # ... nothing drawn, no loop, the test link's effect ended (?fx= gone), the frame stays; the link gone (no "start animation"); + # nothing saved + assert got["stopped"] | {"levels": None} == {"effects": ["uv"], "levels": None, "running": False, "framed": ["UV index"], + "link": None, "frames": 0, "ink": 0, "stored": None, "url": "", + "pressed": 0}, got["stopped"] + # the readings calling for more, and "reset preferences": still stopped, nothing drawn, no link + reset = got["reset"] + assert reset["link"] is None and not reset["running"] and reset["frames"] == 0 and reset["ink"] == 0, reset + assert set(reset["framed"]) == {"UV index", "Wind"}, reset + # a reload: running as normal (an earlier version's saved {animations: false} ignored and dropped, the arrangement kept) + reloaded = got["reloaded"] + assert reloaded["link"] == "stop" and reloaded["running"] and reloaded["frames"] > 10, reloaded + assert reloaded["stored"] == {"order": [], "hidden": ["Rain"]}, reloaded + # stopped again, then a test link (heat): on again, its effect and the readings' with it, the link back + resumed = got["resumed"] + assert resumed["link"] == "stop" and resumed["running"] and resumed["frames"] > 10, resumed + assert set(resumed["effects"]) == {"uv", "wind", "heat"} and resumed["url"] == "?fx=heat", resumed + # from the keyboard: Enter on it stops them, the link gone (the focus not left on it) + assert got["keyboard"]["link"] is None and not got["keyboard"]["running"] and got["keyboard"]["focused"] == "BODY", got["keyboard"] + + +@needs_browser +async def test_the_temporary_test_links_turn_each_effect_on_and_stop_animation_ends_them_and_with_animations_off_nothing_is_drawn(server, station): + got = await weather(server, "links") + # the temporary test links: each its effect and frame (the gauges keep their readings), the URL following; haze steps through its + # bands, rain light then heavy; ice melts back; "stop" ends them all (no "clear"); no "all" link, but ?fx=all + links = got["links"] + assert links["buttons"] == ["rain", "haze", "uv", "humidity", "wind", "heat", "ice", "gust"], links["buttons"] + on = [] + for name in ("uv", "humidity", "wind", "heat", "ice"): + on.append(name) + assert set(links[name]["effects"]) == set(on) and EFFECTS[name] in links[name]["framed"], (name, links[name]) + assert links[name]["url"] == "?fx=" + ",".join(on) + assert links["label"] == "UV index 0.0" # (the stand-in's reading, not the simulated one) + # "stop" at the bottom left, just right of the row's last link, beside the strip (at the window's bottom), clear of it; + # the row (no "test:" label any more), all of it in sight + corner = links["corner"] + assert corner["link"] == "stop" and corner["apart"] and corner["onScreen"], corner + just_right_of_the_row(corner) + assert not corner["tag"] and corner["fits"], corner + assert corner["row"]["left"] == 0 and corner["motion"]["bottom"] == corner["window"][1] == corner["strip"]["bottom"], corner + assert links["haze"] == [1, 2, 3, 4, 5, 0] + assert links["rain"] == [[0.35, 0], [1, 0], [1, 2], [0, 0]] # (light, heavy, heavy with a flash flood (the test's own), off) + melting = links["melting"] + assert melting["grown"] > 2 and 0 < melting["reach"] < melting["grown"] and "ice" not in melting["effects"] and melting["running"], melting + # "stop" with only test links on: every one off, ?fx= gone, the animations stopped (nothing saved), the link gone + assert links["cleared"] | {"levels": None, "running": None} == {"effects": [], "levels": None, "running": None, "framed": [], + "link": None, "url": "", "pressed": 0, "stored": None} + assert links["all"]["effects"] == EVERY and links["all"]["url"] == "?fx=rain2,haze3,uv,humidity2,wind,heat,ice" + # humidity light (91 %) first, then heavy (100 %), then off + assert links["humiditySteps"] == [{"level": 1, "url": "?fx=uv,humidity2,wind,heat", "label": "humidity: heavy"}, + {"level": 0, "url": "?fx=uv,wind,heat", "label": "humidity"}], links["humiditySteps"] + assert links["role"] == "group" and links["pressed"] == {"rain": "false", "haze": "false", "uv": "true", "humidity": "true", + "wind": "true", "heat": "true", "ice": "false"}, links["pressed"] + # on a phone (360x740, 390x844), every effect on (its links' longest): no "test:", each link ("gust" too) and "stop" in sight, + # unscrolled, with room for one more short link (some 30 px); a link's step a raised figure, its full words its label + for phone in (got["phone360"], got["phone390"]): + assert not phone["tag"] and phone["fits"] and phone["spare"] >= 30 and phone["apart"] and phone["onScreen"], phone + just_right_of_the_row(phone) + for phone in (got["phone360"], got["phone390"]): + assert phone["errors"] == [] and phone["link"] == "stop", phone + assert phone["buttons"] == ["rain²", "haze³", "uv", "humidity²", "wind", "heat", "ice", "gust"], phone["buttons"] + assert phone["labels"] == ["rain: heavy", "haze 3", "uv", "humidity: heavy", "wind", "heat", "ice", "gust"], phone["labels"] + assert phone["motion"]["bottom"] == pytest.approx(phone["strip"]["top"], abs=0.5), phone # (above the strip) + assert phone["flood"] == ["rain³", "rain: flood"], phone["flood"] # (rain's third step) + # MCP_DASHBOARD_ANIMATIONS off (the page as served then, data-animations="off"), every effect asked for (?fx=all) and called for by + # the readings (a gust over 99 km/h and ?fx=gust too), the animations not stopped in the browser: no loop, nothing drawn, nothing + # blown across, no link, no test links; the tiles and the strip as ever + off = got["off"] + assert off["off"] == {"effects": off["off"]["effects"], "levels": off["off"]["levels"], "running": False, "framed": off["off"]["framed"], + "link": None, "frames": 0, "ink": 0, "gust": 0, "sky": "none", "corner": "none", "row": False}, off["off"] + assert off["off"]["effects"] == EVERY, off["off"] # (asked for all the same: just never drawn) + assert off["tiles"] == titles_of(station) and off["strip"] == "last reading 18:42", off + # a tile hidden: "reset preferences" in the strip as ever; still nothing drawn + assert off["hidden"] == {"strip": "last reading 18:42", "frames": 0, "ink": 0, "running": False}, off["hidden"] + + +@needs_browser +async def test_the_motion_setting_on_low_and_off_and_reduced_motion_as_off(server, station): + """MCP_DASHBOARD_ANIMATIONS, each page as served with it, and a browser asking for reduced motion (served with on): on, everything + animated; low, the gauges sweeping and the tiles reflowing but no weather at all and the zoom at once; off and reduced motion, no + weather and nothing animated.""" + got = await weather(server, "motion") + tiles = len(titles_of(station)) - 1 # (Rain hidden) + called = [e for e in EVERY if e != "heat"] # (every effect called for but the heat: below 0 °C) + for mode in ("on", "low", "off", "reduced"): + seen = got[mode] + weather_on, sweeps, zooms = mode == "on", mode in ("on", "low"), mode == "on" + # the gauges: Humidity's new reading (97 %) swept to, through the values between, or straight there, its one change + gauge = seen["gauge"] + assert gauge[-1].startswith("97"), (mode, gauge) + assert (len(gauge) > 3) if sweeps else (len(gauge) == 1), (mode, gauge) + # the weather: drawn and its loop running, "stop" and the test links shown, a gust sending something across; or none at all: + # no canvas shown, not one frame, nothing on it, nothing blown across, no "stop", no test links (asked for all the same) + w = seen["weather"] + assert [e for e in w["effects"] if e != "gust"] == called, (mode, w) # (the gust on while one crosses) + if weather_on: + assert w["running"] and w["frames"] > 0 and w["ink"] > 0 and w["gust"] >= 1, (mode, w) + assert w["link"] == "stop" and w["shownLink"] and w["row"] and w["sky"] != "none" and w["corner"] != "none", (mode, w) + else: + assert w | {"effects": None, "levels": None, "framed": None} == { + "effects": None, "levels": None, "framed": None, "running": False, "frames": 0, "ink": 0, "gust": 0, "link": None, + "shownLink": False, "row": False, "sky": "none", "corner": "none"}, (mode, w) + # the zoom: animated (its animations running just after the click and after Esc, the gallery's step a transition), or at once + assert seen["zoomed"]["zoomed"] and not seen["back"]["zoomed"], (mode, seen) + if zooms: + assert seen["zoomed"]["animations"] > 0 and seen["back"]["animations"] > 0 and seen["paged"]["transition"] != "0s", (mode, seen) + else: + assert seen["zoomed"]["animations"] == seen["back"]["animations"] == 0 and seen["paged"]["transition"] == "0s", (mode, seen) + # a tile hidden: the others gliding to their places (on their way the next frame), or there at once + hidden = seen["hidden"] + assert hidden["tiles"] == tiles, (mode, hidden) + if sweeps: + assert hidden["moved"] > 0 and hidden["gliding"] > 0, (mode, hidden) + else: + assert hidden["moved"] == hidden["gliding"] == 0, (mode, hidden) + + +EVERY = ["haze", "heat", "uv", "rain", "wind", "humidity", "ice"] +# humidity's beads' colours, [r, g, b, alpha] (alpha 0-255): the glass's pale body (#A6D7F2, 34) and crescent (105), the white glint +# (#EFFAFF, 240), the deep blue rim (#2C5573, 110); the faintest first +BEAD_COLOURS = [[166, 215, 242, 34], [166, 215, 242, 105], [44, 85, 115, 110], [239, 250, 255, 240]] + + +def just_right_of_the_row(corner): + """ "stop" right after the test row, on its line, a few pixels right of its last link (the row's end, in sight).""" + motion, row, last = corner["motion"], corner["row"], corner["last"] + assert motion["left"] == pytest.approx(row["right"], abs=0.5) and -1 <= motion["left"] - last["right"] <= 10, corner + assert row["left"] <= last["left"] and last["right"] <= row["right"] + 1, corner # (-1, +1: the row scrolled to a whole px) + assert motion["bottom"] == pytest.approx(row["bottom"], abs=0.5) and motion["top"] == pytest.approx(row["top"], abs=0.5), corner + + +@needs_browser +async def test_the_haze_alone_in_each_band_clouds_dithered_lit_from_above_drifting_with_the_wind(server, station): + got = await weather(server, "haze") + # the haze (the particulates), each band alone: soft clouds over the whole window, more of it under them with each band (at + # Moderate a few scattered ones, under a quarter of it; at Hazardous most of it), and denser + levels = got["haze"]["levels"] + assert [lv["level"] for lv in levels] == [1, 2, 3, 4, 5], levels + covers = [round(lv["cover"], 3) for lv in levels] + assert 0.03 < covers[0] < 0.25 and covers[-1] > 0.6 and all(a * 1.15 < b for a, b in zip(covers, covers[1:])), covers + assert all(a["mean"] * 1.2 < b["mean"] for a, b in zip(levels, levels[1:])), [lv["mean"] for lv in levels] + # ... dithered irregularly: no grid in its pixels (its strongest fine frequency's power, over the median's: under 400; the even + # veil's ordered dither, 75000 and more) + assert all(lv["grid"] < 400 for lv in levels), [round(lv["grid"]) for lv in levels] + # ... each cloud lit from above: its upper half lighter than its lower (by 15 % or more: its lit top over its darker core and + # underside) + looks = [look for lv in levels for look in lv["looks"]] + assert all(len(lv["looks"]) >= 2 for lv in levels) and all(upper > 1.15 * lower for upper, lower in looks), looks + # ... drifting right to left, the wind's way: every cloud and mote leftward (about 3 px/s), its drift too; faster in the wind + calm, windy = got["haze"]["calm"], got["haze"]["windy"] + assert calm["n"] >= 20 and calm["left"] == calm["n"] and 1.5 < calm["speed"] < 6 and calm["slide"] > 2, calm + assert windy["n"] >= 20 and windy["left"] == windy["n"] and windy["speed"] > 2 * calm["speed"] and windy["slide"] > 2 * calm["slide"], windy + for clouds in (calm["clouds"], windy["clouds"]): + assert clouds["n"] >= 20 and clouds["left"] == clouds["n"] and clouds["speed"] > 1, clouds + assert windy["clouds"]["speed"] > 2 * calm["clouds"]["speed"], (calm, windy) + + +@needs_browser +async def test_heavy_humidity_alone_costs_no_more_as_its_trails_build_up_and_its_sweep_is_capped(server, station): + got = await weather(server, "trails") + # (the cost: the script's own time a frame, the main thread's CPU time, however busy the machine) + # after minutes of the weather's time (over 200 s, the trails and beads built up: tens of thousands of trail pixels): no dearer + # than twice the start's plus 1.5 ms (its cost not growing with the trails; the start's itself about 1-2 ms); and with its time 20 times as fast, the trails' sweep capped (a + # slice of them a frame, never all), still cheap + late, fast = got["late"], got["fast"] + assert got["cost"] < 8, got["cost"] + assert late["clock"] > 200 and late["trails"] > 15000 and late["beads"] > 100 and late["cost"] < 2 * got["cost"] + 1.5, (got["cost"], late) + assert fast["trails"] > 15000 and 0 < fast["swept"] <= fast["most"] == 2500 and fast["cost"] < 20, fast # (20x time: several times the work a frame, 8-12 ms here; the sweep cap above is the real check) + + +@needs_browser +async def test_the_ice_grown_all_the_way_in_is_cheap_with_its_frost_across_the_glass(server, station): + got = await weather(server, "frost") + assert got["frosted"]["cost"] < 8 and got["frosted"]["crystals"] > 0.15, got["frosted"] + + +@needs_browser +async def test_heavy_rain_with_wind_and_haze_keeps_to_the_shared_particle_budget_and_is_cheap(server, station): + got = await weather(server, "budget") + assert got["cost"] < 8, got["cost"] + together = got["particles"] + assert together["wind"] > 0 and together["rain"] > 0, together + # ... the shared budget kept by every effect but humidity's beads (their own limits bound them: heavy rain keeps every drop) + assert sum(v for k, v in together.items() if k not in ("budget", "humidity")) <= together["budget"] + 3, together # (each rounded) + + +def _whole_streaks(looks): + """Each bead's clear-glass streak, from all the looks at it (each its latest rows as it ran on): each row as first looked at + (fresh), in order down the glass; its width (w) the rows' mean.""" + rows = {} + for t in looks: + if t["kind"] != "clear": + continue + mine = rows.setdefault(t["id"], {}) + for k, y in enumerate(t["ys"]): + mine.setdefault(y, (t["widths"][k], t["paused"][k], t["w"])) + streaks = [] + for bead, mine in rows.items(): + ys = sorted(mine) + streaks.append({"id": bead, "kind": "clear", "ys": ys, "widths": [mine[y][0] for y in ys], "paused": [mine[y][1] for y in ys], + "w": sum(mine[y][2] for y in ys) / len(ys)}) + return streaks + + +@needs_browser +async def test_effects_asked_for_as_the_page_opens_alone_and_on_a_phone(server, station): + got = await weather(server, "opened") + # ?fx= when the page opens + assert got["param"]["levels"] == {"gust": 0, "haze": 3, "heat": 0, "uv": 0, "rain": 0, "wind": 1, "humidity": 0, "flood": 0, "ice": 5} + assert sorted(got["param"]["framed"]) == ["AQI", "Temperature", "Wind"] and got["param"]["errors"] == [] + # (the effects' earlier names, in links saved before, still work: as wind, uv, humidity, and smog4 as haze4) + assert got["paramOld"]["effects"] == ["haze", "uv", "wind", "humidity"] and got["paramOld"]["errors"] == [], got["paramOld"] + assert got["paramOld"]["levels"]["haze"] == 4, got["paramOld"] + assert got["paramAll"]["effects"] == EVERY and got["paramRain"]["levels"]["rain"] == 1 + # the particles: uv's beams none (no motes); the wind's leaves alone within the shared budget + assert got["particles"]["uv"] == {"uv": 0, "budget": got["particles"]["uv"]["budget"]}, got["particles"] + wind = got["particles"]["wind"] + assert 0 < wind["wind"] <= wind["budget"], wind + # uv's beams over 40 s: each swaying a pixel or so about its own place (not travelling on), so slowly that it turns back at most + # once in that time (a sway in 80 s or more), still brightening and dimming + uv = got["uv"] + assert uv["errors"] == [] and uv["frames"] >= 300 and len(uv["beams"]) >= 4, uv + assert all(b["most"] - b["least"] <= 4 and b["turns"] <= 1 and b["bright"] - b["faint"] > 0.2 for b in uv["beams"]), uv + assert any(b["most"] > b["least"] for b in uv["beams"]), uv # (swaying all the same) + assert all(a["most"] < b["least"] for a, b in zip(uv["beams"], uv["beams"][1:])), uv # (each in its own place, apart) + # ... their glow dithered irregularly: no grid in its pixels (as gridPeak sees it: under 100; ordered, about 660) + assert uv["grid"] < 100, uv["grid"] + # heavy rain in the wind: its drops blown leftward, faster than with no wind; bunched by the gust bands into curtains and gaps, + # their density across uneven, and changing as the bands pass, far more than the rain alone (scattered evenly: about 1) + alone, windy = got["rain"]["alone"], got["rain"]["windy"] + assert alone["errors"] == windy["errors"] == [] and alone["looks"] >= 20 and windy["looks"] >= 20, got["rain"] + assert windy["vx"] < alone["vx"] < 0 and alone["drops"] > 30 and windy["drops"] > 30, got["rain"] + assert alone["across"] < 1.4 and alone["overTime"] < 1.4, got["rain"] + assert windy["across"] > max(2, 1.6 * alone["across"]) and windy["overTime"] > max(2, 1.6 * alone["overTime"]), got["rain"] + # ... on a phone too (its art narrow, the bands shorter so a curtain and a gap still fit across: about 1.6-3; alone there, about 0.8) + rain_phone = got["rain"]["phone"] + assert rain_phone["errors"] == [] and rain_phone["looks"] >= 20 and rain_phone["drops"] > 5, rain_phone + assert rain_phone["vx"] < alone["vx"] and rain_phone["across"] > 1.3 and rain_phone["overTime"] > 1.3, rain_phone + # heavy drops knock the leaves they hit (a push along their slant, a burst of spin): many hits, each a bash; light rain's (before + # it turned heavy) barely nudge them; the rain alone (no leaves) and the wind alone (no drops), none + assert alone["leaves"]["hits"] == 0, alone["leaves"] + for heavy, many in ((windy, 25), (rain_phone, 5)): # (in 3 s or so: about 50-65; on a phone, its art small, about 15-30) + assert heavy["leaves"]["hits"] >= many and heavy["leaves"]["push"] > 25, heavy["leaves"] + assert heavy["leaves"]["kick"] == pytest.approx(heavy["leaves"]["push"], rel=0.01), heavy["leaves"] # (each leaf's velocity: so changed) + assert windy["leaves"]["whirl"] > 2, windy["leaves"] + assert windy["light"]["hits"] >= 3 and 0 < windy["light"]["push"] < 10, windy["light"] + assert windy["light"]["kick"] == pytest.approx(windy["light"]["push"], rel=0.01), windy["light"] + assert windy["leaves"]["kick"] > 2.5 * windy["light"]["kick"], (windy["leaves"], windy["light"]) # (heavy rain's knocks: far harder) + # humidity (heavy: 100 %): condensation beading all over the glass in its fog (3.6 minutes of it, on a small page, its time run on + # fast), the beads condensing at every height (more toward the top), tiny, and only where the fog shows; never a line of water + # along the top edge. One set of rules for every bead (BEAD_RULES below): its speed rising gradually with its size (on fog, by + # size: each band faster than the one before); down only, never back up, well down; most wandering a little either side of where + # each began (never further than its bound), the lot not drifting either way; reaching the window's bottom edge and running off it + # (none left there); its trail behind it. On fog it grows (gathering the fog), on a trail it keeps its size: neither ever shrinks a + # bead (only dry glass does: heavy rain's beads, below). Beads that touch merge, their water adding up exactly, however big: no + # largest bead. Glass: mostly see-through (a faint body; they were opaque, about 217 of 255 as drawn), a crisp glint. The same + # with the wind on: water on the glass isn't blown + for name, beads in got["humidity"].items(): + assert beads["errors"] == [] and beads["runners"] >= 10 and beads["up"] == 0 and beads["down"] > 50, (name, beads) + assert 2 <= beads["wander"] <= beads["meander"] and beads["wandered"] >= beads["runners"] / 2, (name, beads) + assert abs(beads["offset"]) < 3, (name, beads) # (about 1 or less; blown, many px) + assert beads["lowest"] >= 1 and beads["ranOff"] >= 5 and beads["under"] == 0, (name, beads) # (run off the bottom: gone) + born = beads["born"] # (each condensed: its radius, the fog shown where it showed, its height, of the window's) + thirds = [sum(lo <= b["y"] < lo + 1 / 3 for b in born) for lo in (0, 1 / 3, 2 / 3)] + assert len(born) >= 20 and min(thirds) >= 2 and sum(b["y"] > 0.5 for b in born) >= 0.15 * len(born), (name, thirds, born) + assert thirds[0] >= 0.3 * len(born), (name, thirds) # (more toward the top) + assert all(b["r"] <= 0.75 and b["fog"] >= 0.06 for b in born), (name, born) # (tiny, and in the fog only) + assert beads["behind"] > 0.95 and beads["trails"] > 200, (name, beads) + glass = beads["glass"] + assert glass["fog"]["gained"] > 0 and glass["fog"]["lost"] == 0, (name, glass) # (on fog: growing, never shrinking) + assert glass["trail"]["moves"] > 100 and glass["trail"]["gained"] == glass["trail"]["lost"] == 0, (name, glass) # (a trail: kept) + assert glass["dry"]["lost"] == 0, (name, glass) + # (the same size, r 1.8-3.2: faster down a trail than on fog (water on water), each bead's px against what it'd have run on fog + # at its size then, so the sizes that happened to run on each don't count; any size, faster down a trail than 1.6 times fog's + # (every running bead there at least a fresh rain bead's speed, TRACK: the smaller far faster than that); each glass, about its + # own speed (pace: px it'd have run at its glass's mean speed for its size, TRACK's floor and all): no faster, no slower) + speed = {g: o["px"] / o["band"] for g, o in glass.items() if o["band"] > 0} + assert speed["trail"] > 1.6 * speed["fog"], (name, speed) + assert 0.75 < glass["fog"]["all"] / glass["fog"]["norm"] < 1.3 and 1.6 < glass["trail"]["all"] / glass["trail"]["norm"], (name, glass) + assert all(0.75 < glass[g]["all"] / glass[g]["pace"] < 1.3 for g in ("fog", "trail")), (name, glass) + # (down a trail, r 1.8-3.2, all at about TRACK: seen over all three, below) + on_fog = [px / s for px, s in beads["sizes"] if s > 0] # (by size: under 1, 1-1.6, 1.6-2.4, 2.4-3.2, 3.2 and over) + assert beads["sizes"][0] == [0, 0], (name, beads["sizes"]) # (under r 1: none running, they run from r 1.4) + assert len(on_fog) == 4 and on_fog == sorted(on_fog) and on_fog[0] < 1 and on_fog[-1] > 5, (name, beads["sizes"]) # (1.4-1.6: creeping) + # (merges: each bead's water the two's together, exactly, however big) + assert beads["merges"] >= 3 and beads["merged"], (name, beads) + for m in beads["merged"]: + assert m["into"] == pytest.approx(sum(m["vol"]), rel=1e-12) and m["intoR"] ** 3 == pytest.approx(m["into"]), (name, m) + assert m["intoR"] > max(m["r"]), (name, m) + assert beads["largest"] >= max(m["intoR"] for m in beads["merged"]) - 1e-9, (name, beads["largest"]) + # (looked at as drawn: the still beads whole, every frame; their own alpha, the fog under them taken out) + assert beads["look"]["beads"] >= 20 and beads["look"]["mean"] < 110 and beads["look"]["most"] > 170, (name, beads["look"]) + # (the glass well beaded: more beads on it still at a time than running, many: about 60 at once) + assert beads["showing"]["still"] > beads["showing"]["running"] > 0, (name, beads["showing"]) + assert beads["showing"]["still"] > 36, (name, beads["showing"]) + # (lasting: many on the glass 25 s or more by the end) + assert sum(age > 25 for age in beads["aged"]) >= 10, (name, sorted(beads["aged"])) + # (nothing left showing on the fog's canvas where no trail is any more; no bead vanishing (each merged into another, run off + # the bottom, shrunk to nothing or dried away) + assert beads["stray"] == 0 and beads["popped"] == 0 and beads["landed"] == 0, (name, beads) + # (a long run on fog, no rain: no bead on fog dries away (faded: the cap, the budget or otherwise), none but a bead stopped + # on dry glass shrinks; none condenses in a run) + assert beads["faded"] == 0, (name, beads["faded"]) + # (tiny beads never moving but to snap together, many snapping; condensing on and on, more and more of them, up to the most + # there may be (the cap; it shrinks as small beads take their room), never more; beads from r 1.4, the run size, to 1.6 running) + assert beads["crept"] == 0 and beads["snaps"] >= 10, (name, beads["crept"], beads["snaps"]) + # (heavy humidity condensing them fast, its glass beaded up a while first (150 frames): full from the watch's start; light's + # watched from the first, below: more and more of them) + assert beads["tinies"][1]["n"] >= beads["tinies"][1]["cap"] - 3, (name, beads["tinies"]) + # (the biggest (r 2.5 and up) now and then elongating as they set off again after a pause: about one restart in three, as + # seen over all three, below; never a smaller one (as followed here, the weather's time 6 times as fast: a stretch is over + # within a frame, seen in rain's, below)) + assert beads["watched"]["small"] == 0 and all(e["r"] >= 2.5 for e in beads["watched"]["stretches"]), (name, beads["watched"]) + assert any(t["n"] >= t["cap"] - 3 for t in beads["tinies"]), (name, beads["tinies"]) + # (none condensing at the cap; the cap falling as small beads take room, tiny ones on fog never dried for it: never past the most it was, before) + assert all(t["n"] <= 1.4 * max(u["cap"] for u in beads["tinies"]) + 4 for t in beads["tinies"]), (name, beads["tinies"]) + assert beads["sizes"][1][0] > 0, (name, beads["sizes"]) + # (tiny beads sitting on the fog swelling slowly with it, each its own rate (as thick as the fog is under it): in a minute or + # two (as felt here, about 0.4) small beads, no longer tiny (from then on as small ones are); never quicker than their rate) + swells, rate, spread = beads["swells"], beads["swell"]["rate"], beads["swell"]["spread"] + assert beads["swelled"] >= 20 and len(swells) >= 20, (name, beads["swelled"]) + assert all(s["r0"] <= beads["tiny"] < s["vol"] ** (1 / 3) and 0 < s["fogged"] <= s["took"] + 1e-6 for s in swells), (name, swells) + rates = [(s["vol"] - s["r0"] ** 3) / s["soaked"] for s in swells] # (water gained for each s on fog as thick as 1) + assert all(rate * spread[0] - 1e-9 <= k <= rate * spread[1] + 1e-9 for k in rates), (name, rates) + assert max(rates) - min(rates) > 0.4 * rate, (name, rates) # (each its own) + took = sorted(s["took"] for s in swells) + assert 40 <= took[len(took) // 2] <= 200 and took[0] >= 8 and took[-1] <= 400, (name, took) + # (down a trail, r 1.8-3.2, all at about TRACK (a rain bead's least there, about 25.6 px/s; r 3.2: 31), not their size's 2-20: + # seen over all three pages' together, a page's own a second or two of them, too few for a mean, its pauses one way or another) + px, s = (sum(beads["glass"]["trail"][k] for beads in got["humidity"].values()) for k in ("px", "s")) + assert s >= 3 and 0.75 * TRACK < px / s < 1.3 * 31, {n: b["glass"]["trail"] for n, b in got["humidity"].items()} + # (about one restart in three elongating: seen over all of each page's beads since it opened (the glass beading up first too) + # together, a hundred restarts or more, so a watch's handful more or fewer is no matter) + restarts, stretches = (sum(beads["since"][k] for beads in got["humidity"].values()) for k in ("restarts", "stretches")) + assert restarts >= 20 * len(got["humidity"]) and 0.15 * restarts <= stretches <= 0.55 * restarts, {n: b["since"] for n, b in got["humidity"].items()} + # (the biggest sprites (r 3.6 and up) never stop-start on fog or in a trail: no paused time there, however long they run; on dry glass + # they may pause (here or there), and the others still do) + big = {k: [sum(beads["since"]["big"][k][i] for beads in got["humidity"].values()) for i in (0, 1)] for k in ("fog", "trail", "dry")} + assert big["fog"][0] > 0 and big["fog"][1] == 0 and big["trail"][1] == 0, big + # ... nothing at all drawn in the canvas's top two rows (humidity alone: no water along the top edge) + assert got["humidity"]["alone"]["top"] == 0, got["humidity"]["alone"] + # ... two tiny beads put close together (not touching, within the snap): snapped into one small bead (not tiny) in a few frames, + # their water adding up (then growing on the fog as ever), where the lower one was (none pulled up the glass); two further apart, beside them: still there, unmoved + snapped = got["humidity"]["alone"]["snapped"] + assert snapped["spot"] and len(snapped["at"]) == 4 and all(b["r"] <= snapped["tinyR"] for b in snapped["at"]), snapped + pair, apart = snapped["placed"][:2], snapped["placed"][2:] + assert pair[0] is None and pair[1] and not pair[1]["tiny"] and pair[1]["r"] > snapped["tinyR"], snapped + together = snapped["at"][0]["vol"] + snapped["at"][1]["vol"] # (and since, as it sat on the fog, growing a very little) + assert together <= pair[1]["vol"] < 1.05 * together, snapped + assert snapped["snap"] == 1, snapped # (a pixel's gap between their edges or less: the pair 1.6 across snapped, the two 2.5 across not) + assert pair[1]["y"] >= snapped["at"][1]["y"] and len(snapped["near"]) == 1, snapped + assert [(b["x"], b["y"], b["tiny"]) for b in apart] == [(b["x"], b["y"], True) for b in snapped["at"][2:]], snapped + # ... one of the largest (r 4.2) taking in a tiny one, beside it (its water added exactly): swelling a size (a px or two wider and taller than + # its own, its lower edge where it was) for a few tenths of a second at most, then round again; a smaller one (r 3.4) taking in the same: no swell + gulped = got["humidity"]["alone"]["gulped"] + assert gulped["spot"], gulped + big, smaller = gulped["pairs"] + first = big["frames"][0] + assert first["vol"] == pytest.approx(sum(big["before"]), rel=0.01) and first["r"] ** 3 == pytest.approx(first["vol"]), big + swollen = [f for f in big["frames"] if f["w"] > f["rw"] and f["h"] > f["rh"]] + assert swollen and all(f["w"] - f["rw"] <= 2 and f["h"] - f["rh"] <= 2 and f["low"] == f["bottom"] for f in swollen), big + lasted = [f["t"] for f in big["frames"] if f["gulp"] > 0] + assert 1 <= len(lasted) <= 6 and lasted == list(range(lasted[0], lasted[-1] + 1)) and max(f["gulp"] for f in big["frames"]) == 1, big # (up, then back down, eased) + after = [f for f in big["frames"] if f["t"] > lasted[-1] + 1] + assert after and all((f["w"], f["h"]) == (f["rw"], f["rh"]) and f["gulp"] == 0 for f in after), big # (settled: round again) + assert smaller["frames"] and all(f["gulp"] == 0 for f in smaller["frames"]), smaller + # ... the fog: forming first (the first bead only once it has, there and on the glass at large), its trails wiped clear through it + # about as wide as the bead was there (its edges soft: a px or so either way; a px more where another's beside it), clearer than the + # fog beside them (where there is fog); the beads' colours as ever (the glass: the deep blue rim, a faint pale body, a crescent, a + # white glint) + for name, beads in got["humidity"].items(): + first = beads["first"] + assert first["after"] >= 2 and first["cover"] >= 0.3 and first["fog"] > 0.2 and first["formed"]["edge"] > 0.2, (name, first) + wiped = beads["wiped"] + # (wiped clear, or near its soft edge all but: the fog already creeping back there a little) + assert len(wiped) >= 8 and all(t["shown"] <= 0.25 * t["fog"] and t["wet"] > 0.85 for t in wiped), (name, wiped) + assert sum(t["shown"] == 0 for t in wiped) >= 0.3 * len(wiped), (name, wiped) + assert all(-1 <= t["across"] - t["w"] <= 3 for t in wiped), (name, [t for t in wiped if not -1 <= t["across"] - t["w"] <= 3]) + fogged = [t for t in wiped if t["fog"] > 0.05 and t["beside"] > 0.05] + assert len(fogged) >= 5 and all(t["beside"] > t["shown"] for t in fogged), (name, wiped) + assert sum(t["end"]["wet"] < t["wet"] for t in wiped) >= 0.75 * len(wiped), (name, wiped) # (fogging over again, slowly) + # (natural trails through the fog, as they look while fresh: about the bead's width all along (its width as it grew), never + # a gap; their edges smooth: soft (partly wiped px), each wandering gently down the trail, a px over many rows, never row to + # row; not all straight) + fog_trails = [t for t in beads["looks"] if t["kind"] == "fog"] + assert len(fog_trails) >= 6, (name, beads["looks"]) + for t in fog_trails: + assert min(t["widths"]) >= 1 and abs(sum(t["widths"]) / len(t["widths"]) - t["w"]) <= 1.5, (name, t) + # (each edge, on the glass, row by row: shifting a px now and then as the trail wanders, never hopping out and back + # (a px over for a row, then back: once in a trail at most), never shifting most rows; its soft edge px partly wiped, + # the fog's own shades between, in most rows) + edges = [e for e in t["edges"] if e] + for side in (0, 1): + edge = [e[side] for e in edges] + hops = sum(edge[k - 1] == edge[k + 1] != edge[k] for k in range(1, len(edge) - 1)) + moves = sum(a != b for a, b in zip(edge, edge[1:])) + assert hops <= 1 and moves <= 0.4 * len(edge), (name, t["id"], side, edge) + assert sum(k >= 1 for k in t["soft"]) >= 0.7 * len(t["soft"]), (name, t["id"], t["soft"]) + # (clean inside: no droplet, glint or other trail's look in it, only the fog's faint shades (FOG's two thinnest at most: + # residueShades, the residue's own) as residue or as the fog coming back; and no + # dots: whatever shows inside it, not touching the fog beside it, is a streak of residue down it (3 rows or more, 2 px + # wide at most, taller than wide), never a lone pixel or a small blob) + inside = t["inside"] + assert inside["odd"] == [] and all(1 <= k <= inside["residueShades"][1] for d in inside["patches"] for k in d["shows"]), (name, t["id"], inside) + dots = [d for d in inside["patches"] if d["tall"] < 3 or d["wide"] > 2 or d["tall"] <= d["wide"]] + assert dots == [], (name, t["id"], dots) + # (most wandering, not ruled straight) + assert sum(len({e[0] for e in t["edges"] if e}) > 1 for t in fog_trails) >= 0.5 * len(fog_trails), (name, fog_trails) + # (a little streaky residue in them all told: some, under a tenth of the wiped px) + residue, px = sum(t["inside"]["residue"] for t in fog_trails), sum(t["inside"]["px"] for t in fog_trails) + assert 0 < residue < 0.1 * px, (name, residue, px) + colours = sorted(beads["colours"], key=lambda c: c[3]) + assert len(colours) == len(BEAD_COLOURS) and all(c == pytest.approx(want, abs=3) for c, want in zip(colours, BEAD_COLOURS)), (name, colours) + # ... the trails through the fog, their time run on fast: each fogging over again all the way in 3 to 10 minutes (each trail its + # own: some sooner, some later), wiped clear only a short while first, the fog coming back over the rest; the fog then as if never + # wiped + refog = got["humidity"]["windy"]["refog"] + lasted = [t["lasted"] for t in refog] + assert len(refog) >= 10 and all(170 <= t <= 610 for t in lasted) and max(lasted) - min(lasted) > 150, refog + assert all(t["crispTill"] is not None and t["crispTill"] < 0.25 * t["lasted"] for t in refog), refog + assert all(t["fog"][0] == t["fog"][1] > 0 for t in refog), refog + # (as it was picked, in the middle of the trail's row, fresh: wiped clear mostly; here and there a streak of the fog left + # unwiped (FOG's two faintest shades, or the fine ones between and below them), no more: no droplet left in it) + assert sum(t["look"] == [0, 0, 0, 0] for t in refog) >= 0.5 * len(refog), refog + assert all(t["look"] == [0, 0, 0, 0] or ([50, 60, 67] <= t["look"][:3] <= [74, 85, 92] and t["look"][3] <= 69) for t in refog), refog + # ... light (91 %): a thinner fog than heavy (100 %), the fog first all the same; its tiny ones condensing a little slower (0.95 + # of MISTING, heavy 1.35) and swelling slower on its thinner fog (so more of them stay tiny a while: heavy's glass mostly small + # beads by then, a small one a whole particle of the budget, a tiny one a quarter); far fewer running + light, heavy = got["humidityLight"], got["humidity"]["alone"] + assert light["errors"] == [] and light["popped"] == 0 and light["stray"] == 0, light + tinies = [t["n"] for t in light["tinies"]] # (condensing on and on, more and more of them) + assert tinies[1] < tinies[4] < tinies[8], light["tinies"] + assert 0.1 < light["fog"]["haze"] < 0.7 * heavy["fog"]["haze"], (light["fog"], heavy["fog"]) + assert light["showing"]["still"] > 0, light["showing"] + per_s = {k: sorted((s["vol"] - s["r0"] ** 3) / s["fogged"] for s in b["swells"]) for k, b in (("light", light), ("heavy", heavy))} + assert len(per_s["light"]) >= 3 and per_s["light"][len(per_s["light"]) // 2] < 0.85 * per_s["heavy"][len(per_s["heavy"]) // 2], per_s + assert light["showing"]["running"] < 0.5 * heavy["showing"]["running"], (light["showing"], heavy["showing"]) + # ... but heavy's glass shows more still beads than light's after the same time (clearly: grown beads cost their whole particle of + # the budget, so a heavy glass of them showed fewer than light's mostly tiny ones; heavy's budget is the larger) + still_light, still_heavy = got["stillBeads"] + assert still_heavy > 1.1 * still_light > 0, got["stillBeads"] + # the fog dithered irregularly: no grid in its pixels (as gridPeak sees it: under 100; ordered, about 420) + assert heavy["grid"] < 100, heavy["grid"] + # ... and only faintly: in fine steps (6 between each two of FOG's 5 shades), dithered a third of a step, it reads as smooth + # translucency with a faint grain: between pixels side by side, the alpha changing far less than in FOG's 5 shades dithered + # whole, as before (about 1.5 of 255 against about 5), and hardly ever by a whole shade of those (under 1 %; before, about a + # third of the time) + for fog in (light["fog"], heavy["fog"]): + now, before = fog["grain"]["now"], fog["grain"]["before"] + assert now["mean"] < 0.4 * before["mean"] and now["jumps"] < 0.01 and before["jumps"] > 0.1, fog["grain"] + assert light["first"]["after"] >= 2 and light["first"]["fog"] > 0.1 and light["first"]["formed"]["edge"] > 0.1, light["first"] + # ... then heavy rain on it too (3 minutes): its splashes' droplets left on the fog as tiny beads, a few a landing, staying there + # (snapping, swept up, growing with the fog as tiny ones do) well past the 40 s they'd last on clear glass, never drying away on + # the fog (only once a trail is wiped through it under one, 15 s or more after it was left) + splashed = light["splashed"] + on_fog = splashed["splashes"] + assert splashed["s"] >= 170 and splashed["landed"] >= 20 and len(on_fog) >= 3 * splashed["landed"], {k: v for k, v in splashed.items() if k != "splashes"} + assert all(d["moved"] == 0 for d in on_fog) and sum(d["fogged"] > 45 for d in on_fog) >= 10, on_fog + assert all(d["glass"] != "fog" and d["fadedAt"] >= 15 for d in on_fog if d["fadedAt"] is not None), on_fog + assert sum(d["end"] == "on" and d["fogged"] > 45 for d in on_fog) >= 3, on_fog # (there still, long after) + # ... in each, the fog a fairly even haze (gently varied, no gaps: its spread inside, about 0.1; it was patchy, about 0.4, with + # gaps), a little denser at the edges (the sides and the bottom) than in the middle; dense (its mean opacity as drawn: heavy about + # 0.28, light about 0.28 (a little less wiped)), see-through all the same (no fog pixel more than half opaque) + for fog in (light["fog"], heavy["fog"]): + assert fog["cover"] == 1 and fog["spread"] < 0.2 and fog["gaps"] == 0, fog + assert 1.1 * fog["middle"] < fog["edge"] < 2 * fog["middle"], fog + assert heavy["fog"]["opacity"] > 0.19 and light["fog"]["opacity"] > 0.15 and heavy["fog"]["most"] < 0.5, (light["fog"], heavy["fog"]) + # ... and the humidity then below 90 % (heavy, in the wind): the fog clearing as from a demister, the middle first, the edges + # still fogged then, all gone in the end (the effect off, the wind on); the slow beads drying away (shrinking, fading: none + # vanishing), those in the middle sooner than those at the edges; the rest running off or shrinking away on the clear glass + clears = got["humidity"]["windy"]["clears"] + assert clears["start"] >= 5 and clears["middleGone"] is not None and clears["edgeGone"] is not None, clears + assert clears["middleGone"] < clears["edgeGone"] and clears["edgeThen"] > 0.3, clears + assert clears["left"] == {"cover": 0, "thickness": 0, "beads": 0} and clears["effects"] == ["wind"], clears + assert clears["popped"] == 0 and clears["shrank"] > clears["start"], clears + # (the condensed beads' trails going with the fog as it clears: none of them ever showing a clear-glass streak's look (film, + # grime, glint, droplet) while it clears, and once it has cleared nothing of them on the glass, many still listed (fresh still: + # about a hundred or more px of them, how many as the beads happened to run just before)) + assert clears["looks"] == 0, clears + assert clears["cleared"]["trails"] > 60 and clears["cleared"]["ink"] == 0 and clears["cleared"]["looks"] == 0, clears["cleared"] + assert clears["end"]["ink"] == 0 and clears["end"]["looks"] == 0, clears["end"] + middle = [g["frame"] for g in clears["gone"] if g["far"] < 0.4] + edges = [g["frame"] for g in clears["gone"] if g["far"] > 0.7] + assert middle and edges and sum(middle) / len(middle) < sum(edges) / len(edges), clears["gone"] + # ... every other effect then on too: humidity's beads outside the shared budget (their own limits bound them), so none squeezed + # out (as many, give or take a few run off), none vanishing. (This checked fewer before, from when they shared it; since they + # haven't, it held only while heavy humidity's beads were short of their most and a few ran off. Heavy now condenses enough to + # keep them at their most.) + squeezed = got["humidity"]["alone"]["squeezed"] + assert squeezed["count"][1] >= squeezed["count"][0] - 3 and squeezed["popped"] == 0 and squeezed["stray"] == 0, squeezed + # ... then all off (trails there as it went), faded out all the way: every trail and bead forgotten, its canvas clear; and + # humidity on again: the glass fresh + again = got["humidity"]["alone"]["again"] + assert again["before"] > 0 and again == {"before": again["before"], "trails": 0, "beads": 0, "stray": 0, "gone": again["gone"], "marks": again["marks"]}, again + clean_glass(again["gone"]) + clean_glass(again["marks"]) + # ... then its beads leaving trails, and "stop", humidity on again (as a test link after it): the glass fresh too + marked = got["humidity"]["alone"]["marked"] + assert marked["trails"] > 30 and marked["ink"] > 0 and marked["cover"] > 0, marked + started_afresh(got["humidity"]["alone"]["restarted"], "humidity") + # BEAD_RULES, the physics every bead runs by: its speed on each glass, dry slowest (0.3 of fog's: crawling), fog quicker, a trail + # fastest (1.6 times fog's: water on water; the user: fog beads move fast down tracks like with rain), for the same size, and down + # a trail never under TRACK (a freshly landed rain bead's speed there, r 3: a condensed one as quick as a rain one down a track); + # still under the run size (about sixteen tiny ones' water: r 1.4), from there creeping extremely slowly, rising gradually with + # its size (then faster and faster, no fastest); after 20 px in 5 s: on fog bigger (however big already: no largest), on a trail + # the same, on dry glass smaller, a small one shrunk to nothing (gone) + physics = got["humidity"]["alone"]["physics"] + speed, after, sizes = physics["speed"], physics["after"], physics["sizes"] + track = speed["trail"][sizes.index(3)] + assert track == pytest.approx(1.6 * speed["fog"][sizes.index(3)]) and track == pytest.approx(TRACK, abs=0.1), speed + for i, r in enumerate(sizes): + if r < physics["run"]: # (under the size a bead runs from, about large: it stays put on any glass) + assert speed["dry"][i] == speed["trail"][i] == speed["fog"][i] == 0, (r, speed) + else: + assert speed["dry"][i] < speed["fog"][i] < speed["trail"][i], (r, speed) + assert speed["trail"][i] == pytest.approx(max(1.6 * speed["fog"][i], track)), (r, speed) + assert speed["dry"][i] == pytest.approx(0.3 * speed["fog"][i]), (r, speed) + assert after["fog"][i] > r and after["trail"][i] == r and after["dry"][i] < r, (r, after) + assert [v for r, v in zip(sizes, speed["trail"]) if physics["run"] <= r <= 3] == [track] * 4, speed["trail"] # (r 1.4-3: TRACK) + for g in ("dry", "trail", "fog"): + moving = [v for r, v in zip(sizes, speed[g]) if r >= (physics["run"] if g != "trail" else 3)] # (from the run size up: under it, still) + assert speed[g] == sorted(speed[g]) and len(set(moving)) == len(moving) >= (8 if g != "trail" else 5), (g, speed[g]) + steps = [b / a for a, b in zip(moving, moving[1:])] + assert all(1 < k < 15 for k in steps), (g, steps) # (gradually: no jump from creeping to running) + assert 1.35 <= physics["run"] <= 1.45, physics["run"] # (about sixteen tiny ones' water) + assert physics["sizes"][:5] == [0.6, 1, 1.1, 1.3, 1.4] and physics["run"] <= 1.4, physics # (r 0.6 to 1.3 still; 1.4 running, creeping) + assert speed["fog"][3] == 0 and 0.2 < speed["fog"][4] < 0.6 and speed["fog"][-1] > 100, speed["fog"] + assert after["dry"][0] == 0 and after["fog"][-1] > sizes[-1], after + # heavy rain's beads: light rain none; heavy, a drop sticking every few s (one in 3 s), a dozen or so (14) on the glass at most, each landing at once + # (no fading in) as a large bead (r 3 or more), hard: squashed flat and wide a frame or two, wobbling back to round, with a splash + # (a ring of 14 to 20 droplets thrown out fast, lopsided, some of them spray streaks, 4 to 8 of them left on the glass as tiny + # beads); on dry glass crawling (about 0.3 of its speed on fog, the same size), down a trail at TRACK or more (its own size's + # speed there), shrinking only (its water left behind), never growing; none vanishing; their wet streaks on the + # clear glass drying over 3 to 10 minutes, each its own: thin streaks (a third of the bead's width or less: a px or two), faint + # (a greyish film, grime along an edge, a glint, a tiny droplet), uneven along their length (thicker and thinner, now and then + # broken for a px or three, never more, no regular pattern of gaps: no dashes), their thin parts drying first (gone from view + # well before the trail is dry), the thick ones last. The rain light again: none sticking; those there running off or shrinking away + sticking = got["rainBeads"] + assert sticking["errors"] == [] and sticking["light"] == {"landed": 0, "levels": 0.35}, sticking + heavy_rain = sticking["heavy"] + # (75 s of heavy rain at one in 3 s: about 26; more than the handful (5) there were at most before, up to 14) + assert 12 <= heavy_rain["landed"] <= 42 and 6 <= heavy_rain["rainMost"] <= 14 and heavy_rain["popped"] == 0, heavy_rain + # (each landing seen: shown at once, or, landing on a bead already there, merged into it at once (in its absorbed)) + assert len(sticking["stuck"]) == heavy_rain["landed"], sticking["stuck"] + assert all(s["r"] >= 3 and (s["alpha"] == 1 or s.get("merged")) and 14 <= s["dots"] <= 20 and len(s["thrown"]) == s["dots"] and s["phase"] == "heavy" + for s in sticking["stuck"]), sticking["stuck"] + assert len({s["dots"] for s in sticking["stuck"]}) >= 4, sticking["stuck"] + # (the burst lopsided: its droplets' mean throw a fifth or so of their speed or more one way, a direction of its own each landing; + # some of them (a third or so all told, at least two a splash) spray streaks; squashed 0.5 to 0.75 wider at first) + for s in sticking["stuck"]: + vx, vy = (sum(v * f(a) for a, v, *_ in s["thrown"]) for f in (math.cos, math.sin)) + s["lean"], s["aim"] = math.hypot(vx, vy) / sum(v for _, v, *_ in s["thrown"]), math.atan2(vy, vx) + assert all(s["lean"] >= 0.12 for s in sticking["stuck"]), [s["lean"] for s in sticking["stuck"]] + assert len({int((s["aim"] + math.pi) // (math.pi / 2)) for s in sticking["stuck"]}) == 4, [s["aim"] for s in sticking["stuck"]] + sprays = [sum(t[2] for t in s["thrown"]) for s in sticking["stuck"]] + assert min(sprays) >= 2 and 0.2 <= sum(sprays) / sum(s["dots"] for s in sticking["stuck"]) <= 0.5, sprays + assert all(0.5 <= s["squash"] <= 0.75 for s in sticking["stuck"]), sticking["stuck"] + # (followed frame by frame (a 30th of a second each) as they land: as wide as that, as much shorter, held a frame or two; then + # within 0.2 s wobbling back (taller and narrower a moment), round again from there on (but elongated as it sets off, as below); its water no different for it (but what + # it leaves on dry glass as it runs, or a tiny bead it sweeps up)) + landings = sticking["landings"] + assert len(landings) == 4 and all(len(l["frames"]) >= 10 for l in landings), landings + for l in landings: + f = l["frames"] + held = [x for x in f if x["impact"] < 0.05] + assert f[0]["impact"] == 0 and 1 <= len(held) <= 2 and all((x["w"], x["h"]) == (f[0]["w"], f[0]["h"]) for x in held), l + assert f[0]["w"] >= 1.4 * f[0]["rw"] and f[0]["h"] <= 0.7 * f[0]["rh"], l + assert any(x["w"] < x["rw"] and x["h"] > x["rh"] for x in f if 0.05 <= x["impact"] < 0.2), l + assert all((x["w"], x["h"]) == (x["rw"], x["rh"]) for x in f if x["impact"] >= 0.2 - 1e-9 and not x["stretch"]), l # (round, but as + # it sets off, elongating) + assert all(0.75 <= x["w"] * x["h"] / (x["rw"] * x["rh"]) <= 1.3 for x in f), l + assert all(abs(x["vol"] - f[0]["vol"]) <= 0.03 * f[0]["vol"] for x in f if x["impact"] < 0.2), l + # (4 to 8 of its droplets meant to stay, all of them left but those thrown off the window or into a flood (off), as many as the + # beads' own most had room for as it landed (room): none cut while there was room, every one past it cut) + assert all(4 <= s["meant"] <= 8 and s["stay"] + s["cut"] + s["off"] == s["meant"] and s["stay"] == min(s["meant"] - s["off"], s["room"]) + for s in sticking["stuck"]), sticking["stuck"] + # (... where there was room, 4 or more left, as ever, but one now and then thrown off the window by a drop landing near its edge + # (scattered further out, more of the landings lose one so, but hardly any of their droplets)) + roomy = [s for s in sticking["stuck"] if s["room"] >= s["meant"]] + assert roomy and all(s["stay"] >= 4 for s in roomy if not s["off"]) and sum(s["off"] for s in roomy) <= 0.1 * sum(s["meant"] for s in roomy), sticking["stuck"] + assert len({s["meant"] for s in sticking["stuck"]}) >= 3, sticking["stuck"] + dry, trail = heavy_rain["glass"]["dry"], heavy_rain["glass"]["trail"] + assert dry["lost"] > 0 and dry["gained"] == 0 and 0.2 < dry["all"] / dry["norm"] < 0.4, dry + assert trail["moves"] > 100 and all(0.75 < o["all"] / o["pace"] < 1.3 for o in (dry, trail)), heavy_rain["glass"] + assert 0.75 * TRACK < trail["px"] / trail["s"] < 1.3 * 31, trail # (r 1.8-3.2 down a trail: about TRACK, not their size's) + # (the splash's droplets left on the glass: tiny beads (r 0.55) like any other, from the splash's end on, as many as were left; + # never moving but to snap (merged into a neighbour, or swept up by a runner passing: as many as eight thrown out, now and then + # three of them together at most); on the clear glass, nothing taking them, drying away after 15 to 40 s each) + left_on = sticking["watched"]["splashes"] + assert sum(s["stay"] for s in sticking["stuck"]) - 8 <= len(left_on) <= sum(s["stay"] for s in sticking["stuck"]), (len(left_on), sticking["stuck"]) + assert all(d["moved"] == 0 and d["r"] < 0.85 for d in left_on) and sum(d["tiny"] for d in left_on) >= 0.9 * len(left_on), left_on + assert all(d["r"] == pytest.approx(0.55) for d in left_on if d["tiny"]), left_on # (no fog to swell with: as left, tiny) + ends = {end: [d for d in left_on if d["end"] == end] for end in ("faded", "taken", "on", "other")} + assert len(ends["faded"]) >= 10 and len(ends["taken"]) >= 10, {end: len(d) for end, d in ends.items()} + assert all(15 <= d["fadedAt"] <= 41 and d["glass"] != "fog" for d in ends["faded"]), ends["faded"] + assert len({round(d["fadedAt"]) for d in ends["faded"]}) >= 8, ends["faded"] # (each its own time) + # (thrown past the drop's edge every way, up and down too: none landing on its drop, or close enough to snap back into it at + # once (they did, about one in ten); those thrown up or to the sides (no further down than half as far across) hardly ever + # taken back the moment they're left (by a runner passing); those below it may be: its drop, running at once, runs down through + # them) + # (each left in the heavy rain, as followed here and on, below, as its biggest beads set off again: every one once) + every = list({d["id"]: d for d in left_on + sticking["stretching"]["splashes"]}.values()) + across = [d for d in every if d["thrown"][1] <= abs(d["thrown"][0]) / 2] + assert len(every) >= 120 and len(across) >= 60, every + assert sum(d["end"] == "taken" and d["aged"] <= 0.45 for d in across) <= 0.05 * len(across), across + # (none outstaying its drying (shown 0.4 s in, 40 s at most, half a second drying away): gone, a merged one shrunk away) + assert all(d["aged"] <= 42 for d in ends["on"] + ends["other"]), left_on + # (the biggest (r 2.5 and up: here most) setting off again after a pause (heavy rain's own time, 30 s): about one restart in three + # elongating a little: a row or two taller, a column narrower, its lower edge where it was, eased in and held, round again within + # 0.75 s or so (sooner, paused again); never a smaller one) + stretching = sticking["stretching"] + stretches = stretching["stretches"] + assert stretching["s"] == pytest.approx(30, abs=0.5) and stretching["restarts"] >= 15, {k: v for k, v in stretching.items() if k != "splashes"} + assert 0.15 * stretching["restarts"] <= stretching["begun"] <= 0.55 * stretching["restarts"], stretching + assert stretching["begun"] - 2 <= len(stretches) <= stretching["begun"] and stretching["small"] == 0, stretching + assert all(e["r"] >= 2.5 and 0 < e["most"] <= 1 and 0 <= e["rows"] <= 2 and 0 <= e["cols"] <= 1 and e["low"] == 0 for e in stretches), stretches + assert sum(e["most"] == 1 and e["rows"] >= 1 and e["cols"] == 1 for e in stretches) >= 3, stretches # (all the way, now and then) + assert all(e["lasted"] is None or e["lasted"] <= 0.85 for e in stretches) and sum(e["lasted"] is not None for e in stretches) >= 3, stretches + # (a bead that has steered into another's run and reached it locks on: it follows the run's middle row by row, wherever it + # wanders, to the bottom (never off partway: none let go with the run still under or just ahead of it), till it merges, runs + # off the bottom, or the run ends) + locks = stretching["locks"] + assert len(locks) >= 2 and sum(k["rows"] for k in locks) >= 30, locks + assert all(k["off"] <= 2 for k in locks), locks + assert not any(k["dropped"] for k in locks), locks + assert heavy_rain["glass"]["fog"]["moves"] == 0, heavy_rain["glass"] # (no fog: rain alone) + drying = [t["lasted"] for t in sticking["drying"]] + assert len(drying) >= 2 and all(170 <= t <= 610 for t in drying), sticking["drying"] + assert all(t["look"][:3] in STREAK + DROPLET and 0 < t["look"][3] <= (150 if t["look"][:3] in DROPLET else 80) for t in sticking["drying"]), sticking["drying"] + hidden = sorted(t["hidden"] for t in sticking["drying"]) + assert hidden[0] < 0.75 and hidden[-1] > 0.7, sticking["drying"] + assert all(t["kind"] == "clear" for t in sticking["looks"]), sticking["looks"] + streaks = list({t["id"]: t for t in reversed(sticking["looks"])}.values()) # (each bead's first look, as it had run 20 px) + whole = {t["id"]: t for t in _whole_streaks(sticking["looks"])} # (... and all its looks together: its trail as far as it ran) + assert len(streaks) >= 2, sticking["looks"] + # (thin: all told a third of the beads' width or less; each a px or two (2 at most on the whole, but where it paused: a little + # wider there, a blob; a bead shrunk on dry glass to under 6 px wide keeps its streak's width, so a third of its own width may + # be under 2); a blob) + rows = [w for t in streaks for w in t["widths"]] + assert sum(rows) / len(rows) <= sum(t["w"] for t in streaks) / len(streaks) / 3, streaks + # (their width where they ran, on the whole: over all their trails, as far as each ran, each row held to its own bead's most + # (a mean over one bead's rows alone, a dozen or two of them, is a px or two's wobble)); a px or two everywhere + ran, most = [], 0 + for t in whole.values(): + rows = [w for w, paused in zip(t["widths"], t["paused"]) if not paused] + ran += rows + most += len(rows) * (2 if t["w"] >= 5.5 else max(1.6, t["w"] / 3)) + assert len(ran) >= 100 and sum(ran) <= most, list(whole.values()) + for t in streaks: + widths = t["widths"] + assert max(widths) <= t["w"] / 2 + 1.5, t + assert len(set(widths)) >= 2 and max(widths) - min(widths) >= 1, t # (uneven along it) + empty = [w == 0 for w in widths] + runs = [len(r) for r in "".join("x" if e else "." for e in empty).split(".") if r] + assert sum(empty) <= 0.25 * len(widths) and max(runs, default=0) <= 3, t # (broken a little, at most) + starts = [i for i, e in enumerate(empty) if e and (i == 0 or not empty[i - 1])] + assert len(starts) < 3 or len({b - a for a, b in zip(starts, starts[1:])}) > 1, t # (no regular dashes) + eased, gone = sticking["eased"], sticking["after"] + assert gone["landed"] == eased["landed"] and gone["beads"] == 0 and gone["popped"] == 0, (eased, gone) + # (each run off or shrunk to nothing, or merged into one that was: none dried away otherwise but the splashes' droplets, each + # after 15 to 40 s (some within a frame there: gone between two looks), unless swept up first by a runner passing (taken), as + # ever; two snapped together (too small to run) the same, or shrunk away first on dry glass, never faded) + assert gone["ranOff"] + gone["shrunk"] > eased["ranOff"] + eased["shrunk"] and eased["beads"] > 0, (eased, gone) + dried = sticking["afterWatched"]["splashes"] + assert dried and all(d["end"] in ("faded", "other", "taken") and d["aged"] <= 42 and d["glass"] != "fog" for d in dried), dried + shrunk = [d for d in dried if d["end"] == "other" and d["fadedAt"] is None and not d["tiny"]] + assert len(shrunk) <= gone["shrunk"] - eased["shrunk"], shrunk + assert gone["faded"] - eased["faded"] == sum(d["end"] != "taken" for d in dried) - len(shrunk) > 0, (eased, gone, dried) + assert all(15 <= d["fadedAt"] <= 41 for d in dried if d["fadedAt"] is not None), dried + # ... their streaks, the rain still on, drying on their own time: there still 6 s after the last bead had gone + easing = sticking["easing"] + assert easing["at"]["beads"] == 0 and easing["at"]["trails"] > 0, easing + assert easing["after"]["trails"] > 0 and easing["after"]["ink"] > 0 and easing["after"]["amount"] == 1, easing + # heavy again, streaks on the glass; off, faded out all the way: every streak and stain forgotten, its canvas clear; heavy + # again: clean glass, nothing from before (no trail, no stain, no bead, no drop); and the same with the animations stopped + # and started between + for streaked in (sticking["streaked"], sticking["streakedAgain"]): + assert streaked["trails"] >= 30 and streaked["ink"] > 0, streaked + cleared = sticking["cleared"] + clean_glass(cleared["gone"]) + clean_glass(cleared["again"]) + assert cleared["stray"] == 0 and cleared["drops"] == 0, cleared + started_afresh(sticking["restarted"], "rain") + # the wind blows right to left: its leaves leftward overall, as drawn on the canvas too (each one's middle, frame to frame, over 20 s + # of its time: its gusts and lulls); some caught in a loop going rightward a moment (on a phone too) + for seen in (got["wind"], got["phoneWind"]): + assert seen["vx"] < -10 and seen["against"] > 0 and seen["frames"] > 20 and seen["left"] > 3 * seen["right"] > 0, seen + assert seen["hits"] == 0 and seen["whirl"] == 0, seen # (no rain: nothing knocks the leaves) + # the strip at the bottom right: its links, then the time at the far right; on a phone with both its links, the test row + # beside it or above it, never over it + phone = got["phone"] + assert phone["strip"] == "last reading 18:42" and phone["right"], phone + assert phone["apart"] and phone["onScreen"], phone + # "reset preferences" on its own, left of the switches (or above them), on screen, right of the test row or clear of it + assert phone["resetRight"] and phone["resetAfterRow"], phone + # "stop" at the bottom left, just right of the test row's last link (with the row above the strip on a phone, both clear + # of it); without the test row (the page as it will be), at the bottom left on its own, at 1024x768 and on a phone + corner = got["phoneCorner"] + assert corner["link"] == "stop" and corner["apart"] and corner["onScreen"], corner + just_right_of_the_row(corner) + # (above the strip; the units' four switches there too, at the right, too wide for the row beside them: just above those) + # (the strip is only the time now: the units' switches fit beside it at the bottom, "reset preferences" (a tile is hidden) on a line + # of its own just above them, at the right; the test row and "stop" too wide for what's left of that line: on the line above it) + assert corner["units"]["bottom"] == corner["window"][1] and corner["units"]["right"] == pytest.approx(corner["strip"]["left"], abs=0.5), corner + assert corner["reset"]["right"] == corner["window"][0] and corner["reset"]["bottom"] == pytest.approx(corner["units"]["top"], abs=0.5), corner + assert corner["motion"]["bottom"] == pytest.approx(corner["reset"]["top"], abs=0.5), corner + # (no "test:" there, all of it unscrolled, room for one more short link: as with every effect on, in the links' test) + assert not corner["tag"] and corner["fits"] and corner["spare"] >= 30, corner + for bare in (got["bare"], got["barePhone"]): + assert bare["errors"] == [] and bare["row"] is None and bare["link"] == "stop", bare + assert bare["motion"]["left"] == 0 and bare["apart"] and bare["onScreen"], bare + if bare is got["bare"]: # (the bottom left, on its own) + assert bare["motion"]["bottom"] == bare["window"][1], bare + else: # (a phone: the bottom row is the switches and the time; "stop" on the line above, left of "reset preferences") + assert bare["motion"]["bottom"] == pytest.approx(bare["reset"]["bottom"], abs=0.5) and bare["motion"]["right"] <= bare["reset"]["left"], bare + # the frost: fern-like crystals from the window's edges, further in and faster the colder, over minutes; melting back from the + # tips, the edges last. Just below 0 °C (-0.5) a fringe at the edges, grown in a minute or two; then gone again, the loop with it + frost = got["frost"] + assert frost["errors"] == [], frost["errors"] + slight, cold, minute = frost["slight"], frost["cold"], frost["minute"] + assert 40 <= slight["took"] <= 180 and slight["deepest"] < 0.2 and 0.01 < slight["crystals"] < 0.1 and slight["rim"] > 0.4, slight + assert slight["fresh"] == 0 and not slight["growing"], slight # (the fresh tips only while it grows) + assert frost["slightGone"]["extent"] == 0 and not frost["slightGone"]["running"], frost["slightGone"] + # -5 °C: a minute in, growing on (its fresh tips, white, at the front), past the fringe already but not half way to where it goes + assert minute["growing"] and minute["fresh"] > 20 and minute["extent"] < 0.5 * minute["target"], minute + assert minute["deepest"] > slight["deepest"] and minute["crystals"] > slight["crystals"], (minute, slight) + # ... as far as it goes some 3 to 5 minutes in: well across the glass, frost over much of it; uneven fingers, some reaching far + # in, others stopping short; sparkles catching the light now and then + assert 180 <= cold["took"] <= 300 and not cold["growing"] and cold["fresh"] == 0, cold + assert cold["deepest"] > 0.4 and cold["crystals"] > 0.18 and cold["frosted"] > 0.3 and cold["rim"] > 0.9, cold + fingers = sorted(cold["fingers"]) + assert fingers[-1] > 0.35 and fingers[0] < 0.6 * fingers[-1] and fingers[-1] - fingers[len(fingers) // 2] > 0.05, fingers + assert frost["sparkles"] >= 1, frost["sparkles"] + # ... its haze dithered irregularly: its commonest shade (the haze's faint one) on no grid, about a third of its pixels in their + # 4 commonest places of 16 (x mod 4, y mod 4: on an ordered 4x4 dither, as it was, over 0.8) + assert cold["grid"]["n"] > 500 and cold["grid"]["share"] < 0.5, cold["grid"] + # ... and varied, as real frost on a window: fern fronds, short plumes, needles radiating from a point; ahead of the front only a + # sparse dusting of tiny specks (a pixel or two each: no snowflake-shaped stars or plates), a few fronds from a little way in (as if from a scratch); the fronds' lengths and their branches' spacing spread widely, the + # branches mostly near 60° to their stems (ice's hexagonal habit), each frond its own; the seeds along the edges uneven, crowded + # in some stretches with bare gaps in others; the shading uneven: ridges brighter than side branches, those than the fine + # barbs, the shades spread widely and in several tints + made, shades = cold["made"], cold["shades"] + assert set(made["forms"]) == {"fern", "plume", "needles", "speck"}, made["forms"] + assert all(made["forms"][k] >= 5 for k in ("fern", "plume", "needles")) and made["scratches"] >= 1, made["forms"] + specks = made["specks"] + assert len(specks) == made["forms"]["speck"] >= 5 and set(specks) <= {1, 2} and 1 in specks and 2 in specks, specks + assert len(specks) < cold["size"][0] * cold["size"][1] / 1000, (len(specks), cold["size"]) # (sparse) + q = lambda v, p: sorted(v)[int(p * (len(v) - 1))] + lengths = [f["length"] for f in made["fronds"]] + spacings, angles = [f["spacing"] for f in made["fronds"] if f["spacing"]], [f["angle"] for f in made["fronds"] if f["angle"]] + assert len(lengths) >= 40 and q(lengths, 0.9) > 5 * q(lengths, 0.1) and max(lengths) > 60, sorted(lengths) + assert len(spacings) >= 30 and q(spacings, 0.9) > 2.5 * q(spacings, 0.1), sorted(spacings) + assert 55 <= q(angles, 0.5) <= 65 and q(angles, 0.1) > 45 and q(angles, 0.9) < 75 and q(angles, 0.9) - q(angles, 0.1) > 6, sorted(angles) + gaps = [b[1] - a[1] for a, b in zip(made["seeds"], made["seeds"][1:]) if a[0] == b[0]] + assert len(gaps) >= 40 and q(gaps, 0.9) > 4 * q(gaps, 0.1) and max(gaps) > 4 * q(gaps, 0.5), sorted(gaps) + assert shades["stem"] > shades["side"] + 20 > shades["barb"] + 40 and shades["spread"] > 35 and shades["tints"] >= 3, shades + # ... faint (the tiles read over it), pale cyan to white + shown = cold["pixels"] + assert shown["drawn"] > 0.3 and shown["alpha"] < 0.15 and shown["strong"] < 0.002, shown + assert shown["light"] > 180 and shown["bluer"] > 0.95, shown + # melting: back from the tips, the edges last: half a minute in, fewer crystals, the rim still frosted; then gone, the loop too + melting = frost["melting"] + assert melting["extent"] < cold["extent"] and melting["crystals"] < 0.9 * cold["crystals"], (melting, cold) + assert melting["rim"] >= 0.97 * cold["rim"] and melting["fresh"] == 0, (melting, cold) + assert frost["gone"]["extent"] == 0 and frost["gone"]["frosted"] == 0 and not frost["gone"]["running"], frost["gone"] + # ... and on again, nothing from before (its canvas clear, no sparkle); grown half a minute, then the animations stopped and + # started again, and on: the same + assert frost["again"] == {"extent": 0, "ink": 0, "sparkles": 0}, frost["again"] + assert frost["grown"]["extent"] > 0 and frost["grown"]["ink"] > 0, frost["grown"] + started_afresh(frost["restarted"], "ice") + assert frost["restarted"]["frost"] == {"extent": 0, "ink": 0, "sparkles": 0}, frost["restarted"] + # the heat (?fx=heat): soft shafts of faint red light from the top, as the UV's: one in each gap between the UV's places (halfway + # between two, one past the last), each 40 % longer than the UV's to its left; more of them and brighter the hotter + hot = got["heat"] + assert hot["errors"] == [] and hot["cost"] < 4, hot + looks = hot["looks"] + for look in looks: + uv, shafts = look["uv"], look["shafts"] + assert len(shafts) == len(uv) >= 4, look + assert all(a < s["x"] < b for a, s, b in zip(uv, shafts, uv[1:])) and shafts[-1]["x"] > uv[-1], (uv, shafts) + assert all(s["long"] == round(1.4 * s["uvLong"]) for s in shafts), shafts + # (about the level's share of them on, at least one; each on drawn) + on = [s for s in shafts if s["on"] == 1] + assert len(on) == max(1, round(len(shafts) * look["level"])) and all(s["at"] is not None for s in on), shafts + # (red, from the top: the top third warm (red over green and blue), the shafts' tops inked, the UV's places' tops (between + # them) far fainter) + r, g, b = look["top"]["colour"] + assert r > 1.5 * b and r > 1.5 * g and 0.01 < look["top"]["alpha"] < 0.25, look["top"] + r, g, b = look["atHeat"]["colour"] + assert r > 1.5 * b and look["atHeat"]["alpha"] > 3 * look["atUv"]["alpha"], (look["atHeat"], look["atUv"]) + # (a deep, saturated crimson, infrared imagery's red, not an orange ember: the red far over the green, little blue) + assert g < 0.15 * r and b < 0.35 * r, look["atHeat"] + # ... stronger the hotter: from 35 °C to 43 °C more of them, brighter + cool, warm, hottest = looks + count = [sum(s["on"] == 1 for s in l["shafts"]) for l in looks] + assert count[0] < count[1] < count[2] == len(hottest["shafts"]), count + assert cool["drawn"] < warm["drawn"] < hottest["drawn"] and cool["top"]["alpha"] < warm["top"]["alpha"] < hottest["top"]["alpha"], looks + # ... dithered irregularly (no grid: under 100, as gridPeak sees it; ordered, about 200) + assert hot["grid"] < 100, hot["grid"] + # ... swaying as the UV's: over 24 s each a pixel or so either side of its place, never more than a pixel a second, never drifting + columns = list(zip(*hot["moving"])) + assert all(max(c) - min(c) <= 4 and all(abs(a - b) <= 1 for a, b in zip(c, c[1:])) for c in columns), columns + assert any(max(c) > min(c) for c in columns), columns + # with the UV on too: the two interleaving, the heat's tops warmer than the UV's (red over the UV's violet glow along the top), + # the UV's violet (blue over red), within the cap + over = got["heatOver"] + assert over["errors"] == [] and over["looks"][0]["drawn"] < hottest["drawn"], over + there = over["looks"][0] + assert [s["x"] for s in there["shafts"]] == [s["x"] for s in hottest["shafts"]], there + (hr, _, hb), (ur, _, ub) = there["atHeat"]["colour"], there["atUv"]["colour"] + assert ub > ur and hr / hb > 1.3 * ur / ub and there["atUv"]["alpha"] > 0.1, (there["atHeat"], there["atUv"]) + +def clean_glass(marks): + """Nothing on the glass (Sky.state().humidity.marks()): no trail, no stain on its canvas, no bead, no fog""" + assert {k: marks[k] for k in ("trails", "listed", "ink", "beads", "cover")} == {"trails": 0, "listed": 0, "ink": 0, "beads": 0, "cover": 0}, marks + + +def started_afresh(seen, effect): + """"stop", then `effect` on (as a test link after it: restarted() in the browser script): the loop stopped and the link + gone between, then running again with the link back, and nothing from before: the glass clean, no drop, no stray pixel""" + assert seen["link"] == "stop" and seen["stopped"]["link"] is None and not seen["stopped"]["running"], seen + assert seen["again"] == {"running": True, "link": "stop"}, seen + clean_glass(seen["stopped"]["marks"]) + clean_glass(seen["marks"]) + assert seen["stray"] == 0 and seen["drops"] == 0 and effect in seen["effects"], seen + + +@needs_browser +async def test_a_flash_flood_fills_the_window_a_quarter_up_its_surface_choppy_what_falls_ending_at_it_and_a_frog_now_and_then(server, station): + got = await weather(server, "flood") + # the station's rain rate over 30 mm/h, not at 30: a flash flood (the rain's too); the Rain tile its tile + assert got["at30"]["effects"] == ["rain"] and got["at30"]["levels"]["flood"] == 0, got["at30"] + assert got["over"]["effects"] == ["rain", "flood"] and got["over"]["levels"]["flood"] == 1 and got["over"]["framed"] == ["Rain"], got["over"] + # the water rising from the bottom at a steady pace to a quarter of the window's height, in 3 to 5 s + rising = got["rising"] + assert rising["full"] == round(rising["height"] / 4), rising["full"] + speeds = rising["speeds"] + assert len(speeds) >= 20 and max(speeds) - min(speeds) < 0.05 * max(speeds), speeds + assert 3 <= rising["full"] / speeds[0] <= 5, speeds[0] + # its surface choppy all across (many crests, about one every 8 px; each third of the width as choppy), higher at the sides + # (waves piling up and slapping there: about 1.6 times the middle's), the chop up while it pours; the rain ending at it (none + # drawn below it), every drop a ripple there, the near ones a splash + assert rising["crests"] > rising["width"] / 20 and rising["middle"] > 0.8, rising + assert min(rising["thirds"]) > max(0.15, 0.5 * max(rising["thirds"])), rising["thirds"] # (about 0.3 to 0.5 px each) + assert rising["edges"] > 1.25 * rising["middle"], rising + assert rising["chop"] > 0.8 and rising["under"] == 0 and rising["hits"] > 200 and rising["splashes"] > 3, rising + # (no frog for a real flood's first 30 s; after that only now and then, at random) + assert not rising["test"] and rising["nextFrog"] >= 30 and rising["frog"] is None, rising + # its waves (a damped wave equation): one push travelling both ways at their speed, reflecting off a side, dying away slowly + waves = rising["waves"] + there = lambda xs, x: any(abs(t - x) <= 5 for t in xs) + assert there(waves["at1"], 60 - waves["speed"]) and there(waves["at1"], 60 + waves["speed"]), waves + assert there(waves["at3"], 3 * waves["speed"] - 60) and there(waves["at3"], 60 + 3 * waves["speed"]), waves # (back from the left) + assert -1.5 < waves["deepest3"] < -0.25, waves + # the rate 30 again: draining in about 6 s, the chop calming slowly (still much of it half way down); then gone, the rain on + draining = got["draining"] + assert 5 <= draining["took"] <= 7 and draining["surface"] == 0 and got["drained"]["effects"] == ["rain"], (draining, got["drained"]) + assert draining["half"]["chop"] > 0.7 * draining["chop0"], draining + # the test link (every other effect on): rain light, heavy, then heavy with a flash flood (rain3; the test's own flood level, 2), + # then off (the wind turned off before it): draining + linked = got["linked"] + assert [(s["url"].split(",")[-1], s["label"], s["rain"], s["flood"]) for s in linked["steps"]] == [ + ("rain", "rain: light", 0.35, 0), ("rain2", "rain: heavy", 1, 0), ("rain3", "rain: flood", 1, 2)], linked["steps"] + assert linked["off"]["url"] == "?fx=haze3,uv,humidity2,heat,ice" and linked["off"]["flood"] == linked["off"]["rain"] == 0, linked["off"] + # ... its first frog some 30 s after the water started rising, not before; one, crossing right to left, on the waves (bobbing) + assert 29 <= linked["before"] < 30 <= linked["first"] <= 31 and linked["frogs"] == 1, linked + track = linked["track"] + assert len(track) > 15 and track[0][0] > 0.9 * got["rising"]["width"] and track[-1][0] < 0.1 * got["rising"]["width"], track[::10] + assert all(b[0] <= a[0] for a, b in zip(track, track[1:])), track # (two looks a frame drawn, at times) + assert all(abs(y - surface) <= 1 for _, y, surface in track) and max(t[1] for t in track) - min(t[1] for t in track) >= 2, track + # ... paddling: it went through every stroke of its kick on the way across (4 or more, all of them in time) + assert len(linked["strokes"]) >= 4 and set(linked["strokes"]) <= set(range(len(FROG_FRAMES))), linked["strokes"] + # ... the leaves: landing on it and lying there (on the surface line, or a px into it), then sinking and resting on the bottom (on + # the pile of those before, 6 px high at most); within the budget (those resting none of it), a third of them or more flying on the whole + leaves = linked["leaves"] + assert leaves["float"] >= 2 and leaves["sink"] >= 1 and leaves["rest"] >= 1, leaves + assert linked["gaps"] and set(linked["gaps"]) <= {0, 1}, sorted(set(linked["gaps"])) + assert linked["resting"] and all(-8 <= r <= 0 for r in linked["resting"]), sorted(set(linked["resting"])) + assert 0 < linked["most"] < 1 and linked["over"] <= 3, (linked["most"], linked["over"]) + assert linked["fewest"] > 0 and linked["flying"] >= 1 / 3, (linked["fewest"], linked["flying"]) # (never all in the water) + # ... every one stuck on it sinking and resting on the bottom, none lost over the long run (the wind's, the heavy rain's, 100 s + # and more): every one it took still in it at the end, those it took all resting but those still floating or sinking; and every + # one resting showing on the bottom all along (its px never fewer) + kept = linked["kept"] + assert kept["took"] >= 30 and kept["ids"] == kept["took"] and kept["missing"] == [], kept + assert kept["took"] == kept["rested"] + kept["float"] + kept["sink"] and kept["rested"] >= 20, kept + assert kept["looks"] >= 10 and kept["hidden"] == 0 and kept["shrank"] == 0 and kept["last"]["shown"] == kept["last"]["of"] >= 20, kept + # ... every leaf its wavy surface reaches stuck on it (many, in the wind, the heavy rain knocking them about): none flying drawn + # touching it or under it, none flying again, above it or going back a state (floating, sinking, resting, in that order); those + # seen flying the frame before it took them, all of them above it then (some well above: crossing it between frames); none + # vanishing near it but into it + stuck = linked["stuck"] + assert stuck["wet"] >= 8 and stuck["seen"] >= 0.6 * stuck["wet"] and stuck["near"] >= 5 and stuck["hits"] > 0, stuck + assert stuck["touching"] == 0 and stuck["back"] == 0 and stuck["above"] == 0 and stuck["backwards"] == 0, stuck + assert stuck["lost"] == [] and all(g is None or g >= 1 for g in stuck["lastGaps"]), stuck + assert sum(g is None or g > 3 for g in stuck["lastGaps"]) >= 3, stuck # (crossing it between frames: from well above it) + # ... the drips: joining it as they reach it, none below it; each running on down to the waves' own height where it is (its + # sprite's bottom at the surface there, ripples and all, or under a crest risen over it), never joining it short of that, its + # trail all the way down with it, wet to the water + assert linked["joined"] >= 1 and linked["under"] == 0, linked + joins = linked["joins"] + assert joins and all(j["bottom"] >= j["surface"] for j in joins), joins + assert all(j["trail"] == j["bottom"] and j["wet"] > 0 for j in joins if j["trail"] is not None) and any(j["trail"] for j in joins), joins + # ... and nothing on the glass cut off in a straight line at its level: where a trough dips 3 px or more under it, the rows just + # under the level as drawn on as those just above (the haze, the heat, the fog, all down to the wavy surface) + cut = linked["cut"] + assert cut["n"] >= 100 and cut["at"] >= 0.8 * cut["above"], cut + # ... its body dithered irregularly: no grid in its pixels (as gridPeak sees it, its bottom 32 rows: under 100; ordered, about 200) + assert linked["grid"] < 100, linked["grid"] + # ... the wind off (and gone): the leaves in the water its own, staying (those resting still resting), the floating ones sinking + # or resting by 16 s on, none flying; then every one resting, showing on the bottom, none of them particles + off = linked["windOff"] + before, after = {i: st for i, st, _ in off["before"]}, {i: st for i, st, _ in off["after"]} + assert "wind" not in off["effects"] and off["flyers"] == 0, off + assert "rest" in before.values() and "float" in before.values() and set(before) <= set(after), off + assert all(after[i] == "rest" for i, st in before.items() if st == "rest"), off + assert all(after[i] in ("sink", "rest") for i, st in before.items() if st == "float"), off + settled = off["settled"] + assert settled["took"] == settled["rested"] == settled["all"] == len(after) == settled["shows"]["shown"] and settled["particles"] == 0, settled + # ... off: draining in about 6 s, its leaves all there till its last few px, then gone with it; a new flood: none from before + drained = linked["drained"] + assert 5 <= drained["took"] <= 7 and drained["wet"] == drained["all"] == 0 and drained["frog"] is None, drained + assert drained["low"] == drained["n0"] == len(after), drained + assert drained["effects"] == ["haze", "heat", "uv", "humidity", "ice"], drained + again = linked["again"] + assert again["url"].endswith(",rain3") and again["leaves"]["all"] == 0 and again["leaves"]["wet"] == [], again + # every effect on with the flood (full): as cheap as ever (the script's own time a frame, the main thread's CPU time, whatever else + # the machine is doing: about 2 ms), within the budget (kept by every effect but humidity's beads, heavy rain's among them: their + # own limits bound them) + costly = linked["costly"] + assert costly["effects"] == ["haze", "heat", "uv", "rain", "wind", "humidity", "flood", "ice"] and costly["cost"] < 8, costly + assert sum(v for k, v in costly["particles"].items() if k != "humidity") <= costly["budget"] + 3, costly + + +@needs_browser +async def test_a_gust_over_99_kmh_blows_a_cow_a_barn_or_a_chicken_across_far_behind_the_tiles(server, station): + got = await weather(server, "gust") + # the live gust: at 99 nothing; just over, one sent; the same reading fetched again, no more; a new one over, another; under, none + assert got["live"] == [0, 1, 1, 2, 2] and got["liveEffects"] == ["gust"], got["live"] + assert set(got["liveKinds"]) <= {"cow", "barn", "chicken"}, got["liveKinds"] + # a cow, a barn and a chicken at once: each right to left all the way across (in at the right, out at the left), every frame + # further left, in the window's upper part; large (a sixth of the window across or so) and faint (most pixels under half + # opaque), on the back layer, alone here; crossing in some 6-14 s of the weather's time + crossing = got["crossing"] + width, height, _ = crossing["size"] + assert crossing["kinds"] == ["cow", "barn", "chicken"] and crossing["effects"] == ["gust"], crossing + for kind, track in crossing["tracks"].items(): + xs, ys = [p[0] for p in track], [p[1] for p in track] + assert len(track) >= 30 and xs[0] > width and xs[-1] < 0 and all(b < a for a, b in zip(xs, xs[1:])), (kind, xs) + assert all(0 < y < 0.6 * height for y in ys), (kind, ys) + assert track[0][5] >= 50 and track[0][5] >= width / 7, (kind, track[0]) + assert 6 <= track[-1][6] - track[0][6] <= 14, (kind, track[0], track[-1]) + # the cow and the barn tumbling end over end, slowly (anticlockwise, rolling over leftward: 0.3-1 rad/s, more than a turn + # across); the chicken not: facing out, swaying a little (under 0.2 rad either way), its head turning a touch each way, its legs + # swinging through all their frames + for kind in ("cow", "barn"): + track = crossing["tracks"][kind] + angles, took = [p[2] for p in track], track[-1][6] - track[0][6] + assert all(b < a for a, b in zip(angles, angles[1:])), (kind, angles) + assert 0.3 <= (angles[0] - angles[-1]) / took <= 1 and angles[0] - angles[-1] > 3.2, (kind, angles[0], angles[-1], took) + chicken = crossing["tracks"]["chicken"] + assert all(abs(p[2]) <= 0.2 for p in chicken) and max(p[2] for p in chicken) - min(p[2] for p in chicken) > 0.1, chicken + assert {p[3] for p in chicken} == {-1, 0, 1} and {p[4] for p in chicken} == {0, 1, 2, 3}, chicken + assert crossing["inked"] > 1500 and 60 <= crossing["median"] <= 130, crossing + assert crossing["cost"] < 8, crossing["cost"] + # once they're gone: nothing left, nothing drawn, the loop ended + assert crossing["after"]["flyers"] == [] and crossing["after"]["bits"] == 0 and crossing["ink"] == 0 and not crossing["running"], crossing + # the test link: each click one more, at random (all three kinds in five clicks); a one-off, never in the URL (so a reload + # sends none), "wind" clicked after it: only ?fx=wind; not a switch: never pressed + link = got["link"] + assert link["sent"] == 5 and set(link["kinds"]) == {"cow", "barn", "chicken"} and link["flying"] >= 1, link + assert link["url"] == "" and link["afterWind"] == "?fx=wind", link + assert link["pressed"] is None and "on" not in link["classes"].split(), link + # "stop": gone at once, nothing drawn, ?fx= gone; stopped, a live gust over 99 km/h sends none; the gust link after it + # starts them again, one sent + assert got["stopped"] == {"flyers": 0, "running": False, "url": "", "ink": 0, "sent": 5}, got["stopped"] + assert got["resumed"] == {"sent": 6, "running": True}, got["resumed"] + # ?fx=gust as the page opens: ignored, nothing sent (a reload after a click on "gust" no chicken), the word gone from the URL; + # beside an effect (?fx=wind,gust): that effect on, nothing sent, ?fx=wind + opened = got["opened"] + assert opened["sent"] == 0 and opened["effects"] == [] and opened["url"] == "" and opened["errors"] == [], opened + assert opened["beside"] == {"sent": 0, "effects": ["wind"], "url": "?fx=wind"}, opened["beside"] + # on a phone, every effect on and "gust" clicked: one sent; no "test:", every link ("gust" too) and "stop" in sight + phone = got["phone"] + assert phone["sent"] == 1 and phone["buttons"][-1] == "gust" and not phone["tag"] and phone["fits"] and phone["onScreen"], phone + just_right_of_the_row(phone) + assert got["errors"] == [] and phone["errors"] == [], (got["errors"], phone["errors"]) + + +@needs_browser +async def test_a_phones_gravity_turns_the_humidity_beads_downhill_by_the_screens_rotation_and_nothing_else_changes(server, station): + got = await weather(server, "tilt") + cases = got["cases"] + # (synthetic devicemotion readings, the spec's (what Android sends: upright, y +9.8) at screen angles 0, 90, 180 and 270: the beads' + # mean move while running, the window 134 by 100 px) + down = ["upright", "landscape", "landscapeFlipped", "upsideDown"] + for name in down: # (held so the screen's down is down: as ever, the same run as with no sensor at all) + c = cases[name] + assert not c["tilt"]["tilted"] and c["tilt"]["epoch"] == 0 and c["tilt"]["mode"] == 0 and c["tilt"]["readings"] == 1, (name, c) + assert (c["dx"], c["dy"], c["ranOff"]) == (got["none"]["dx"], got["none"]["dy"], got["none"]["ranOff"]), (name, c, got["none"]) + assert not cases["upright"]["tilt"]["flat"] and not cases["upright"]["tilt"]["pool"] and cases["upright"]["tilt"]["steep"] == 1 + # (the steepness, sin of the screen's angle off level: pooling under 5 degrees, not at all above 7 on the way up; smoothstep to 1 at + # 40 degrees, the same at 60, 90 and 120, down again, symmetric about 90, to pooling again face down; the readings' size and the + # beads' own speed aside, the factor is the beads' speed against upright's) + pools = got["pools"] + for theta in ["0", "3", "175", "177", "180"]: # (flat, face up or down: nothing runs, no trail, nothing off the window, merging into ever larger blobs) + c = pools[theta] + assert c["ran"] == 0 and c["off"] == 0 and c["ranOff"] == 0 and c["trailsAfter"] == 0 and c["tilt"]["flat"], (theta, c) # (175: right at the 5 degree edge: pooled by its factor) + assert c["merges"] > 1000 and c["largest"] > 2 * c["early"] and c["largest"] > 4.52, (theta, c) # (past the biggest sprite: no cap) + assert c["tilt"]["steep"] == 0 and not c["tilt"]["tilted"], (theta, c) + full = pools["90"]["factor"] + assert full > 0.5 and all(pools[t]["ran"] > 100 and not pools[t]["tilt"]["pool"] for t in ["10", "30", "60", "90", "120", "150"]), pools + ratio = {t: pools[t]["factor"] / full for t in ["10", "30", "60", "90", "120", "150"]} + assert ratio["10"] == pytest.approx(0.064, abs=0.04), ratio # (smoothstep((sin 10 - sin 5) / (sin 40 - sin 5))) + assert ratio["30"] == pytest.approx(0.845, abs=0.12) and ratio["10"] < ratio["30"] < 1, ratio + assert ratio["60"] == ratio["90"] == ratio["120"] == 1, ratio # (full speed, the same) + assert ratio["150"] == pytest.approx(ratio["30"], abs=0.03) and 0 < ratio["150"] < 1, ratio # (symmetric about 90: 150 as 30) + assert pools["10"]["ranOff"] < pools["60"]["ranOff"] and pools["10"]["off"] == 0 == pools["60"]["off"], pools + # (the pure turn, by readings worked out from the physics, at every screen angle and both signs: the lowered edge is the downhill one; + # the user's iPad landscape regressions: left tilted -> left, the top raised -> the bottom, the top lowered -> the top) + want = {"left": (-9.8, 0), "right": (9.8, 0), "top": (0, -9.8), "bottom": (0, 9.8)} + assert len(got["pure"]) == 5 * 2 * 4 + for key, (x, y) in got["pure"].items(): + angle, sign, edge = key.split("/") + assert (x, y) == pytest.approx(want[edge], abs=0.02), (key, x, y) + assert len(got["ipads"]) == 16 + 3 + 1 + 2 + for name, c in got["ipads"].items(): + t, edge = c["tilt"], c["edge"] + if edge == "flat": # (flat on a table, screen up: pooling, no direction to run) + assert t["flat"] and t["pool"] and not t["tilted"] and t["steep"] == 0, (name, c) + continue + ux, uy = {"left": (-1, 0), "right": (1, 0), "top": (0, -1), "bottom": (0, 1)}[edge] + tol = 0.15 if name.startswith("real/") else 0.05 # (the real readings are a little off the axis: left-edge-down is (-1.81, 0.18)) + assert t["tilted"] == (edge != "bottom") and t["x"] == pytest.approx(ux, abs=tol), (name, c) # (the bottom: straight down, as ever) + assert t["y"] == pytest.approx(uy, abs=tol), (name, c) + assert "window.orientation 90" in got["debugIos"] and "used angle 90 (from window.orientation)" in got["debugIos"], got["debugIos"] + assert "screen.orientation.angle 0 type landscape-primary" in got["debugIos"] and "ios true" in got["debugIos"], got["debugIos"] + assert got["debugOff"] and "raw x 1.50 y 9.50 z 0.50" in got["debugText"] and "window.orientation" in got["debugText"], got["debugText"] + # (no sensor: straight down, no reading taken; an empty event (a desktop's) ignored) + none = got["none"] + assert none["tilt"] == {"x": 0, "y": 1, "angle": 0, "tilted": False, "mode": 0, "readings": 0, "raw": None, "flat": True, "pool": False, "steep": 1, "epoch": 0}, none + assert none["running"] >= 20 and abs(none["dx"]) < 3 and none["dy"] > 30 and none["ranOff"] > 0, none + assert got["empty"] == none["tilt"], got["empty"] + # (leaning: sideways as well as down, by the screen's own right and down however it's turned) + for name, side, edge in [("rolledRight", 1, 0), ("rolledLeft", -1, 0), ("landscapeLeaning", 1, 0), ("landscapeFlippedLeaning", 1, 0), + ("upsideDownLeaning", 1, 0)]: + c = cases[name] + assert c["tilt"]["tilted"] and c["tilt"]["mode"] == edge and 30 <= abs(c["tilt"]["angle"]) <= 40, (name, c) + assert c["running"] >= 15 and side * c["dx"] > 20 and c["dy"] > 30 and c["ranOff"] > 0, (name, c) + assert cases["rolledRight"]["dx"] == pytest.approx(-cases["rolledLeft"]["dx"], rel=0.3) + # (on a side: the beads run along the screen's row to the edge, off it; upside down on its top: up and off the top) + right, top = cases["onItsRight"], cases["onItsTop"] + assert right["tilt"]["mode"] == 2 and right["tilt"]["angle"] == pytest.approx(90) and right["dx"] > 60 and abs(right["dy"]) < 5 and right["ranOff"] > 0, right + assert top["tilt"]["mode"] == 1 and abs(top["tilt"]["angle"]) == pytest.approx(180) and top["dy"] < -40 and abs(top["dx"]) < 5 and top["ranOff"] > 0, top + # (window.orientation, the old way, when there's no screen.orientation) + assert got["oldWay"]["tilt"]["readings"] == 1 and not got["oldWay"]["tilt"]["tilted"], got["oldWay"] + # (the animations low and off: nothing listened to; "stop": ignored, straight down) + for mode, seen in got["ignored"].items(): + assert seen["tilt"]["readings"] == 0 and not seen["tilt"]["tilted"] and seen["link"] == "" and not seen["running"], (mode, seen) + assert got["stopped"]["before"]["tilted"] and not got["stopped"]["after"]["tilted"] and got["stopped"]["after"]["raw"] is None, got["stopped"] + # (an iPhone: no link at first, a "tilt" link a moment later, asked from its tap, gone at once; granted: its readings (its sign the + # other way about: the pull to the right edge) taken; denied, or an error: not; no link where readings came, with the animations + # low, or on a desktop) + ios = got["ios"] + for answer, listening in [("granted", True), ("denied", False), ("error", False)]: + seen = ios[answer] + assert seen["early"]["link"] == "" and seen["was"]["link"] == "tilt" and seen["was"]["asked"] == 0, (answer, seen) + assert seen["now"]["link"] == "" and seen["now"]["asked"] == 1 and (seen["now"]["tilt"]["readings"] == 1) == listening, (answer, seen) + assert ios["granted"]["now"]["tilt"]["raw"] == [pytest.approx(6), pytest.approx(7.7), pytest.approx(0)] and ios["granted"]["now"]["tilt"]["tilted"] + assert ios["free"]["link"] == "" and ios["free"]["asked"] == 0 and ios["free"]["tilt"]["readings"] == 1, ios["free"] + assert ios["low"] == "" and ios["desktop"] == "", ios + # (smoothed: a sudden turn eased in over a fraction of a second, then all of the way; a hand's tremor makes no change; within 4 degrees + # of straight down, down; laid flat, pooling (steepness 0, its direction kept; 6 degrees from flat pools, 8 runs, and 6 then runs on; a zero reading ignored); a reading that isn't numbers ignored; level(): down) + f = got["filter"] + assert 5 < f["eased"][0] < 30 and f["eased"][1] == pytest.approx(90, abs=3), f + assert f["still"]["epoch"] == 0, f + assert not f["snapped"]["tilted"] and f["flat"]["flat"] and f["flat"]["pool"] and f["flat"]["steep"] < 0.01 and f["bad"] == [False] * 3, f + assert f["flat"]["tilted"] and f["flat"]["angle"] == pytest.approx(f["still"]["angle"], abs=2), f # (flat: the last direction kept, nothing runs) + assert f["hyst"] == [True, False, False, True], f + assert not f["level"]["tilted"] and f["level"]["raw"] is None, f + assert got["errors"] == [], got["errors"] + + +@needs_browser +async def test_a_bead_that_pooled_and_runs_again_lays_its_trail_at_once_from_its_own_back_edge(server, station): + got = await weather(server, "tilt") + import math + recs = [r for r in got["restarts"] if "ys" in r] + assert {r["edge"] for r in recs} == {0, 1, 2, 3} and {r["cycle"] for r in recs if r["cycle"] > 0} == {1, 2, 3, 4}, got["restarts"][:3] + for r in recs: + # (the rows (columns, running sideways) laid since it set off again: the last unbroken run of them, counted from its back edge: + # edge 0 runs down (its top the back edge), 1 up (its bottom), 2 left (its right edge), 3 right (its left edge)) + ys, back = r["ys"], {0: math.floor(r["y0"]), 1: r["bottom0"] - 1, 2: r["right0"] - 1, 3: r["left0"]}[r["edge"]] + run = [ys[-1]] + for y in reversed(ys[:-1]): + if abs(y - run[0]) > 1: + break + run.insert(0, y) + # (from its own back edge: no first rows skipped; a px of leeway for where it first ran from, its half-length (2 px or more) is not) + ahead = (run[0] <= back + 1) if r["edge"] in (0, 3) else (run[0] >= back - 1) + assert ahead, (r["ys"], r, back) + assert len(run) >= max(1, math.floor(r["along"]) - 1), r # (and rows enough for the way it has gone: within 2 px of travel, at once) + + +# The frog's head at 2/3 of what it was (rows 0-8, 21 wide in the 65 x 52 sprite; now 15 x 7 in 47 x 40) +OLD_FROG_HEAD = [".....kkkk...kkkk.....", "....klwwwk.kllggk....", "....kwwwwkkkkkkkk....", "....kwwwpk.kwwwpk....", + "...kkgkkkgkgkkkgkk...", "..kgggggggggggggggk..", "..kglllllllllllllgk..", "..kgkkkkkkkkkkkkkgk..", + "..kggggggggggggkdgk.."] +HEAD_AT, HEAD_W, HEAD_H = 16, 15, 7 # (the head's first column, its width and rows in the sprite) +OLD_SPRITE = (65, 52) +SPRITE_W, SPRITE_H, CX = 47, 40, 23 + + +def frog_frames() -> list[list[str]]: + html = (Path(__file__).parent.parent / "lib" / "web_dashboard.html").read_text() + body = html.split("const FROG_FRAMES = [", 1)[1].split("\n ];", 1)[0] + rows = re.findall(r'"([^"]+)"', body) + return [rows[i:i + SPRITE_H] for i in range(0, len(rows), SPRITE_H)] + + +FROG_FRAMES = frog_frames() +HTML = (Path(__file__).parent.parent / "lib" / "web_dashboard.html").read_text() + + +def test_the_frog_is_two_thirds_the_size_with_its_head_as_designed_and_no_lily_pad(): + assert len(FROG_FRAMES) >= 6 and all(len(f) == SPRITE_H and all(len(r) == SPRITE_W for r in f) for f in FROG_FRAMES) + assert 0.55 <= SPRITE_W / OLD_SPRITE[0] <= 0.8 and 0.55 <= SPRITE_H / OLD_SPRITE[1] <= 0.8 + for rows in FROG_FRAMES: + head = [r[HEAD_AT:HEAD_AT + HEAD_W] for r in rows[:HEAD_H]] + assert all(r[:HEAD_AT] == r[HEAD_AT + HEAD_W:][::-1] for r in rows[:HEAD_H]) # (hands raised beside the head mirror too) + # two eyes: one wide (white over pupil, two rows), one half-lidded (a lid line over a sliver) + assert head[1][1:7].count("w") >= 3 and head[2][1:7].count("p") == 1 and head[2][1:7].count("w") >= 3, head + assert head[1][8:14] == "kkkkkk" and head[2][8:14].count("w") >= 3 and head[2][8:14].count("p") == 1, head # (the lid, the sliver) + assert head[1][1:7].count("w") > head[2][8:14].count("w") - 1 + # the long flat drooping mouth, one end lower + mouth = max((len(m) for m in re.findall(r"k+", head[5][1:-1])), default=0) + assert mouth >= 8 and "kd" in head[6], head + assert not set("".join(rows)) & set("QPRS"), "no lily pad colours" + assert all([r[HEAD_AT:HEAD_AT + HEAD_W] for r in f[:HEAD_H]] == [r[HEAD_AT:HEAD_AT + HEAD_W] for r in FROG_FRAMES[0][:HEAD_H]] for f in FROG_FRAMES) # (the same head every frame) + assert len({tuple(f) for f in FROG_FRAMES}) >= 6 + joined = HTML.split("const FROG = {", 1)[1].split("};", 1)[0] + assert not re.search(r"\b[QPRS]:", joined) + + +def test_every_frame_of_the_frog_is_an_exact_mirror_image_below_the_head(): + for rows in FROG_FRAMES: + for y in range(HEAD_H, SPRITE_H): + assert rows[y] == rows[y][::-1], (y, rows[y]) # (the trunk and every limb) + assert all(r[:HEAD_AT] == r[HEAD_AT + HEAD_W:][::-1] for r in rows[:HEAD_H]) # (the head alone may be lopsided: its eyes and mouth) + # (the blink changes only the eyes' own rows) + assert 'y >= 1 && y <= 2 ? row.replace(/[wp]/g, "g")' in HTML + + +def test_the_frog_has_a_long_soft_teardrop_belly_wide_under_the_head_narrow_at_the_hips(): + for rows in FROG_FRAMES: + trunk = sum(1 for r in rows[HEAD_H:] if "y" in r[CX - 4:CX + 5]) # (rows of pale belly) + assert trunk >= 10, trunk + belly = [max((len(m) for m in re.findall(r"y+", r)), default=0) for r in rows[7:23]] + belly = belly[next(i for i, n in enumerate(belly) if n):] + assert 7 <= max(belly) <= 10 and belly.index(max(belly)) <= 4, belly + assert all(a >= b - 1 for a, b in zip(belly, belly[1:])) and belly[-3] <= 4, belly + + +def test_the_frogs_limbs_are_short_tapering_and_curved_as_in_the_references(): + for rows in FROG_FRAMES: + px = {(x, y) for y in range(7, SPRITE_H) for x in range(SPRITE_W) if rows[y][x] in "gl"} + assert all(math.dist((x, y), (CX + (2 if x > CX else -2), 20)) <= 27 for x, y in px if y > 21), rows + assert all(math.dist((x, y), (CX + (5 if x > CX else -5), 9)) <= 18 for x, y in px if abs(x - CX) > 7 and y < 20), rows + limb = thick = 0 + tips = [(x, y) for y in range(7, SPRITE_H) for x in range(SPRITE_W) if rows[y][x] == "l"] + for x, y in px: + if abs(x - CX) <= 7 and y < 22 or any(abs(x - tx) <= 4 and abs(y - ty) <= 4 for tx, ty in tips): + continue + across = len(re.search(r"[gl]*$", rows[y][:x + 1]).group()) + len(re.match(r"[gl]*", rows[y][x + 1:]).group()) - 1 + col = "".join(r[x] for r in rows) + top = y + while top > 7 and col[top - 1] in "gl": top -= 1 + bot = y + while bot < SPRITE_H - 1 and col[bot + 1] in "gl": bot += 1 + limb += 1 + thick += min(across, bot - top + 1) > 3 + assert len(px) > 40 and thick <= 0.25 * max(limb, 1), (limb, thick) + + +def test_the_frog_is_drawn_only_within_the_flood_and_only_when_it_is_deep_enough(): + assert "depth >= 0.7 * full" in HTML + assert "Math.min(pic.under.height, H - frog.y)" in HTML and "pic.under, 0, 0, pic.under.width, rowsBelow" in HTML + assert 0.7 * 192 > SPRITE_H - 8 # (the sprite's underwater rows fit above the floor of a 768 px window's flood) + + +def test_the_frog_swims_a_steady_breast_stroke_one_smooth_cycle(): + beats = [float(v) for v in re.search(r"FROG_BEATS = \[([\d., ]+)\]", HTML).group(1).split(",")] + assert len(beats) == len(FROG_FRAMES) and all(0.15 <= b <= 0.5 for b in beats) and 1.5 <= sum(beats) <= 2.1, beats + assert beats[0] == max(beats) and max(beats[1:]) <= 0.25 # (a long glide, then even beats) + bob = [int(v) for v in re.search(r"FROG_BOB = \[([\d, ]+)\]", HTML).group(1).split(",")] + assert len(bob) == len(beats) and set(bob) <= {0, 1} and bob[0] == 1 and bob[1] == 0 # (down on the glide, up on the pull) + pace = [float(v) for v in re.search(r"FROG_SURGE = \[([\d., ]+)\]", HTML).group(1).split(",")] + assert max(pace) <= 1.25 and min(pace) >= 0.75 # (a mild surge with the kick) + assert "FROG_RIPPLES" in HTML and "for (const d of [-1, 1])" in HTML # (a ripple each side) + + +def test_every_limb_of_the_frog_shows_separate_toes_or_fingers(): + for rows in FROG_FRAMES: + tips = [(x, y) for y in range(SPRITE_H) for x in range(SPRITE_W) if rows[y][x] == "l" and not (y < HEAD_H and HEAD_AT <= x < HEAD_AT + HEAD_W)] + assert all(max(abs(a - c), abs(b - d)) >= 2 for i, (a, b) in enumerate(tips) for c, d in tips[i + 1:]), tips + for side in (lambda x: x < CX, lambda x: x > CX): + mine = [t for t in tips if side(t[0])] + hand, foot = [t for t in mine if t[1] < 24], [t for t in mine if t[1] >= 24] + assert len(hand) >= 2 and len(foot) >= 3, (hand, foot) # (a hand of 2+ fingers, a foot of 3+ toes) + + +def _right_limbs(rows): + return {(x, y) for y in range(HEAD_H, SPRITE_H) for x in range(CX + 1, SPRITE_W) if rows[y][x] in "gl"} + + +def _belly_edge(rows, y): # (the belly's outer column on the right at row y: its last pale pixel + 1 for the outline) + pale = [x for x in range(CX, SPRITE_W) if rows[y][x] == "y"] + return max(pale) + 1 if pale else None + + +def test_in_the_recover_and_knees_up_frames_the_knees_sit_beside_the_belly_not_below_the_hips(): + for n in (3, 4): + rows = FROG_FRAMES[n] + belly_rows = [y for y in range(HEAD_H, SPRITE_H) if _belly_edge(rows, y)] + legs = {(x, y) for x, y in _right_limbs(rows) if y >= 15} # (below the hands) + # the knee: the leg's topmost pixel out beside the belly (the thigh runs up and out to it) ... + knee = min((p for p in legs if p[0] >= CX + 6), key=lambda p: (p[1], -p[0])) + assert belly_rows[0] + 6 <= knee[1] <= belly_rows[-1] - 3, (n, knee, belly_rows) # (level with the belly) + assert knee[0] - _belly_edge(rows, knee[1]) >= 3, (n, knee) # (and clear of it: a gap of outline-coloured pixels) + # ... the shin folded back down under it, the foot drawn in by the hips (not out below, as in the glide) + assert max(y for x, y in legs if x <= CX + 8 and y <= 26) >= knee[1] + 5, n + # nothing of the leg touches the arm above it + arm = {(x, y) for x, y in _right_limbs(rows) if y < 15 and x > CX + 4} + assert all(max(abs(x - a), abs(y - b)) >= 2 for x, y in legs if y <= knee[1] + 1 for a, b in arm), n + assert knee[1] < 22 # (above the hips' row) + + +def _toe_lengths(rows, side_of): + """each light tip and how far it is from the limb's thick part (the pixels in a 2 x 2 block: the shin): the toe's length""" + px = {(x, y) for y in range(HEAD_H, SPRITE_H) for x in range(SPRITE_W) if rows[y][x] in "gl" and side_of(x)} + thick = {q for (x, y) in px if {(x, y), (x + 1, y), (x, y + 1), (x + 1, y + 1)} <= px for q in ((x, y), (x + 1, y), (x, y + 1), (x + 1, y + 1))} + tips = [(x, y) for (x, y) in px if rows[y][x] == "l" and y >= 24] + return tips, [3 + min(max(abs(x - a), abs(y - b)) for a, b in thick) for x, y in tips] # (+3: the toes' roots fuse into a small blob at the ankle) + + +def test_the_frogs_toes_are_short_thin_light_tipped_and_webbed(): # (toes ~7-8 px; the web 'v' between them out to only ~60 % of their length: about 3 px of every toe's tip is free) + kick = None + for n, rows in enumerate(FROG_FRAMES): + tips, lens = _toe_lengths(rows, lambda x: x > CX) + assert len(tips) == 4, (n, tips) # (four toes a foot) + assert 6 <= min(lens) and max(lens) <= 9, (n, lens) + assert all(max(abs(a - c), abs(b - d)) >= 2 for i, (a, b) in enumerate(tips) for c, d in tips[i + 1:]), (n, tips) # (the tips separated; the web fills between the toes below them) + assert all(rows[y][x] == "l" for x, y in tips) + # the web reaches about 0.55-0.7 of the toe length, leaving the tips free + px = {(x, y) for y in range(HEAD_H, SPRITE_H) for x in range(SPRITE_W) if rows[y][x] in "gl" and x > CX} + thick = {q for (x, y) in px if {(x, y), (x + 1, y), (x, y + 1), (x + 1, y + 1)} <= px for q in ((x, y), (x + 1, y), (x, y + 1), (x + 1, y + 1))} + web = [3 + min(max(abs(x - a), abs(y - b)) for a, b in thick) for y in range(HEAD_H, SPRITE_H) for x in range(SPRITE_W) if rows[y][x] == "v" and x > CX] + assert 0.55 <= max(web) / max(lens) <= 0.7, (n, max(web), lens) + assert sum(lens) / 4 - max(web) >= 1.5, (n, max(web), lens) # (on average a toe's last 2 px or so are free; the +3 convention is only approximate) + if n == 5: + kick = lens + assert min(kick) >= 7, kick + # splayed widest in the kick, closed while the legs sweep in, spread again by the glide's end + width = lambda n: (lambda t: max(x for x, _ in t) - min(x for x, _ in t))(_toe_lengths(FROG_FRAMES[n], lambda x: x > CX)[0]) + assert width(5) > width(6) and width(0) > width(6) - 1 and width(5) >= 7, [width(n) for n in range(7)] + # the tucked feet's toes show beside the hips, out from the belly's line, not hidden behind the shin + for n in (3, 4): + tips, _ = _toe_lengths(FROG_FRAMES[n], lambda x: x > CX) + assert all(24 <= y <= 36 for _, y in tips) and all(x >= CX + 2 for x, _ in tips), (n, tips) + + +def test_the_frog_blinks_over_the_same_head(): + assert 'y >= 1 && y <= 2 ? row.replace(/[wp]/g, "g")' in HTML + + +def _webs(rows, side_of): + """per foot, the web pixels ('v'): for each pair of adjacent toe tips, how many lie in the gap between them (in the toe direction)""" + tips, _ = _toe_lengths(rows, side_of) + web = [(x, y) for y in range(HEAD_H, SPRITE_H) for x in range(SPRITE_W) if rows[y][x] == "v" and side_of(x)] + tips = sorted(tips) + return tips, web + + +def test_the_frogs_feet_are_webbed_between_the_toes_and_the_hands_are_not(): + for n, rows in enumerate(FROG_FRAMES): + for side in (lambda x: x > CX, lambda x: x < CX): + tips, web = _webs(rows, side) + assert len(tips) == 4, (n, tips) + cx = sum(x for x, _ in tips) / 4 + cy = sum(y for _, y in tips) / 4 + # each web pixel is a foot's (lower part of the sprite); for each neighbouring pair of tips (by angle about the foot's base) the web lies between them + base = (sum(x for x, _ in web) / len(web), min(y for _, y in web)) if web else None + assert web and all(y >= 24 for _, y in web), (n, web) + assert len(web) >= 3, (n, len(web)) + ordered = sorted(tips, key=lambda t: math.atan2(t[1] - cy, t[0] - cx)) + for a, b in zip(ordered, ordered[1:]): + mx, my = (a[0] + b[0]) / 2, (a[1] + b[1]) / 2 + near = [w for w in web if math.dist(w, (mx, my)) <= max(6, math.dist(a, b))] + assert len(near) >= 2, (n, a, b, near) # (web between each pair of toes) + # the web never touches the hands (above the feet's rows), and the webs are lighter than the limb but not the tip colour + assert all(c != "v" for f in FROG_FRAMES for r in f[:24] for c in r) + assert re.search(r'v: rgb\("#5F9C47"\)', HTML) + # wider webbing in the kick (the fan open) than while the legs sweep together + span = lambda n: (lambda w: max(x for x, _ in w) - min(x for x, _ in w))(_webs(FROG_FRAMES[n], lambda x: x > CX)[1]) + assert span(5) > span(6), (span(5), span(6)) + n_web = lambda n: len(_webs(FROG_FRAMES[n], lambda x: x > CX)[1]) + assert n_web(5) > n_web(6), (n_web(5), n_web(6)) + for n in (3, 4): # (it shows on the tucked feet too) + assert n_web(n) >= 3, n diff --git a/tests/web_dashboard_browser.js b/tests/web_dashboard_browser.js index 992ca7a3..602bdda0 100644 --- a/tests/web_dashboard_browser.js +++ b/tests/web_dashboard_browser.js @@ -1,33 +1,104 @@ // The dashboard page in Playwright's Chromium, for tests/test_web_dashboard.py. // node web_dashboard_browser.js URL SHOTS SIZES: the page at each size ({name: [width, height]}): a screenshot of each (SHOTS/dashboard- -// NAME.png, device scale factor 2) and, on stdout, {name: {tiles, rects, columns, scroll, scrollWidth, scrollHeight, status, errors}}. +// NAME.png, device scale factor 2) and, on stdout, {name: {tiles, rects, columns, scroll, scrollWidth, scrollHeight, status, glass (each +// tile's [kind, its glass highlights' paths]), errors, +// zoomed, compass, compassZoomed}}; then the first tile zoomed (Enter): its look, and a screenshot (SHOTS/dashboard-NAME-zoomed.png); +// then the compass (the wind's direction) zoomed: its look (compassLook), and a screenshot (SHOTS/dashboard-NAME-compass.png); +// every dial's hub and pivot and the pressure's arrow (dials: dialsLook), and the pressure zoomed (pressureZoomed, and a screenshot: +// SHOTS/dashboard-NAME-pressure.png). // node web_dashboard_browser.js URL --live: the page open at 800x600; prints {label} (the first tile's), waits for a line on stdin -// (the test has changed the reading), then prints {label, same_page, errors} once the tile shows it, or after 15 s. +// (the test has changed the reading, and the wind's direction), then prints {label, same_page, compass (its look, and its needle's +// turn every frame since), pressure (dialsLook's, and whether its arrow is the same element), errors} once the tile shows it, or +// after 15 s. // node web_dashboard_browser.js URL --arrive TITLE: the page open at 1024x768; prints the tile's state ({label, faded, opacity, shown, // needle}), waits for a line on stdin (the test has given it a reading, or taken it away), then, once its label changes, samples it -// every frame for 1.5 s and prints {before, after, frames: [{opacity, number}], same_tile, errors}. +// every frame for 1.5 s and prints {before, after, frames: [{opacity, number}], same_tile, compass: [before, after] (compassLook), +// pressure (dialsLook's), errors}. +// node web_dashboard_browser.js URL --arrange PART: the page at 1024x768 with a mouse, a part of the arranging (arrangeMode): +// "dragged" (dragging to reorder, the drag's text zones, the grip and the × on mouseover, the tiles' see-through look), "hidden" +// (the ×, the remove zone, the reset link, the preferences across a reload), "prefs" (the preferences corrupt or from elsewhere (a +// tile new to them), a click soon after a drop, the focus after the × pressed from the keyboard; beside it, storage blocked), +// "stale" (the strip's reading time with a device's reading over an hour old, arrangedStale); prints +// {step: what was seen}. +// node web_dashboard_browser.js URL --touch PART: the page at 390x844 with touch (CDP touch events), a part (touchMode): "taps" (a +// short tap is a click; a swipe scrolls), "edge" (held at the bottom edge it scrolls to the page's end only), "held" (a long press +// picks a tile up (buzz, grip and ×, remove zone) and moves it; held in place, its × hides it); prints {step: what was seen}. +// node web_dashboard_browser.js URL --zoom PART: the page at 1024x768 with a mouse and keys, a part of the zoom (zoomMode): "in" (the +// zoom cursors, a click zooming a tile; zoomed, prints {label} (Temperature's, beside the tile shown), waits for a line on stdin (the +// test has changed its reading), then pages with the keys past the first), "pager" (mouse drags), "wheel" (wheel deltaX), "last" +// (past the last), "text" (drags across the text, a click back), "single" (a single tile zoomed, the keys and drags bouncing), +// "lone" (a single tile zoomed: a swipe bouncing, back by a click and by Esc), "out" (a double-click, Esc, the bounce cut short), +// "keys" (the keyboard, Esc mid-zoom); prints {step: what was seen}. +// node web_dashboard_browser.js URL --zoom-touch PART: the page at 390x844 with touch, a part (zoomTouchMode): "back" (a tap zooms, a +// tap goes back where the page was scrolled), "swipes" (zoomed by a tap, swipes (slow, a flick, on the text) page), "later" (a +// vertical swipe and a long press do nothing), "return" (swiped back, a tap back from another tile); prints {step: what was seen}. +// (--arrange, --touch, --zoom and --zoom-touch: PART, or several joined by "+" (dragged+hidden+prefs), side by side, each its own page +// in this one browser: a list of their reports, in that order.) +// node web_dashboard_browser.js URL --weather PART: the page at 1024x768, its data altered on the way, a part of the weather behind the +// tiles (WEATHER): each reading at, and just short of, the mark that calls up its effect; the canvas behind the tiles and the tiles' +// red frames; "stop"; the temporary test links (beside them, MCP_DASHBOARD_ANIMATIONS off); on, low, off and reduced motion; the haze alone, heavy humidity's trails, the ice grown in, and rain with wind and haze (frame time, particle budget); +// a flash flood; +// ?fx= as the page opens, a phone; prints {step: what was seen}. +// node web_dashboard_browser.js URL --rotate: a phone (412x839) and a tablet (820x1180), touch, scale 2: the page as a fresh load in each +// orientation, then portrait, landscape, portrait, landscape (orientationchange, the viewport turned, orientationchange, 400 ms); +// prints {device: {fresh: {portrait, landscape}, steps: [{orientation, now (what the screen shows), snapshot (what the fresh load +// of that orientation shows)}]}}. +// node web_dashboard_browser.js URL --fill CASES: for each case {name: [width, height, hidden titles]}, the page with those hidden; +// prints {name: {rects, columns, scroll}}. "use strict"; +require("module").enableCompileCache?.(); // (Playwright's code compiled once, kept in the temp folder: most of a run's start, each part's) const { chromium } = require("playwright"); const readline = require("readline"); -async function open(browser, url, width, height) { - const context = await browser.newContext({ viewport: { width, height }, deviceScaleFactor: 2 }); +// The gauges drawn at their readings as the page opens (and each time it's loaded), not rising there from their floor: the page reads +// as hidden (document.hidden, as a tab in the background) till it has drawn its first data, as it then skips every move. For the pages +// that drive the tiles, not their rise (a second of every gauge redrawn each frame, waited out); the rise's own tests, and the weather's +// pages, see it as ever +const RISEN = () => { + let drawn = false; + Object.defineProperty(document, "hidden", { configurable: true, get: () => !drawn }); + const get = window.fetch.bind(window); + window.fetch = async (...args) => { + const response = await get(...args); + if (!drawn && /\/dashboard\/data$/.test(String(args[0]))) { + const json = response.json.bind(response); + response.json = async () => { const data = await json(); setTimeout(() => { drawn = true; }); return data; }; // (drawn by then) + } + return response; + }; +}; + +// No weather behind the tiles, the rest animated as served (MCP_DASHBOARD_ANIMATIONS on): the environment's DASHBOARD_NO_WEATHER set +// (tests/test_web_dashboard.py's run_page, weather False), for the pages that drive the tiles and time their moves, not the weather, so +// the machine's time goes to those moves. Once the page's scripts have run, Sky never set going nor sent anything across, and its +// canvas, "stop" and the test links not shown: as low motion's weather, without its zoom at once +const NO_WEATHER = () => document.addEventListener("DOMContentLoaded", () => { + const set = Sky.set; + Object.assign(Sky, { set: (want) => set(want, false), fling: () => null }); + document.head.append(Object.assign(document.createElement("style"), { textContent: "#sky, #corner { display: none !important; }" })); +}); + +async function open(browser, url, width, height, options = {}) { + const context = await browser.newContext({ viewport: { width, height }, deviceScaleFactor: 2, ...(options.context || {}) }); + if (process.env.DASHBOARD_NO_WEATHER) await context.addInitScript(NO_WEATHER); + if (options.risen) await context.addInitScript(RISEN); + if (options.init) await context.addInitScript(options.init.fn, options.init.arg); const page = await context.newPage(); const errors = []; page.on("console", (m) => { if (m.type() === "error") errors.push(m.text()); }); page.on("pageerror", (e) => errors.push(String(e))); await page.goto(url, { waitUntil: "load" }); - await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0 && /updated/.test(document.getElementById("status").textContent), - null, { timeout: 15000 }); + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0 && /last reading/.test(document.getElementById("status").textContent), + null, { timeout: 15000 }).catch(async (e) => { throw new Error(`${e.message} ${errors} ${await page.evaluate(() => document.body.innerText.slice(0, 300))}`); }); return { context, page, errors }; } async function sizes(browser, url, shots, wanted) { const report = {}; - for (const [name, [width, height]] of Object.entries(wanted)) { + await Promise.all(Object.entries(wanted).map(async ([name, [width, height]]) => { // (side by side, a page each) const { context, page, errors } = await open(browser, url, width, height); await page.evaluate(() => document.fonts.ready); - await page.waitForTimeout(1200); // (the gauges' rise from their floor when the page opens, RISE_MS) + await calm(page, 5000); // (the gauges' rise from their floor when the page opens, RISE_MS) await page.screenshot({ path: `${shots}/dashboard-${name}.png`, fullPage: true }); report[name] = { ...await page.evaluate(() => ({ tiles: document.querySelectorAll(".tile").length, @@ -37,18 +108,223 @@ async function sizes(browser, url, shots, wanted) { scrollWidth: document.documentElement.scrollWidth, scrollHeight: document.documentElement.scrollHeight, status: document.getElementById("status").textContent, + glass: [...document.querySelectorAll(".tile")].map((t) => [t.dataset.kind, [...t.querySelectorAll("svg .glass")].map((e) => e.getAttribute("d"))]), + // each tile's gauge, in its own px (480 wide): its kind and title, how far its drawing's top is below the title's bottom, the + // lowest of its drawing and its words, its words (svg text) but its reading, and any band word's element + gauges: [...document.querySelectorAll(".tile")].map((t) => { + const box = t.getBoundingClientRect(), k = 480 / box.width; + const drawn = [...t.querySelector("svg g.gauge").children].filter((e) => !e.matches(".limit, defs")).map((e) => e.getBoundingClientRect()) + .filter((r) => r.width || r.height); // (the gauge's drawing, but a limit mark outside its ring: handsLook's, clear of the title) + const g = { top: Math.min(...drawn.map((r) => r.top)), bottom: Math.max(...drawn.map((r) => r.bottom)) }; + const texts = [...t.querySelectorAll("svg text")]; + return { kind: t.dataset.kind, title: t.querySelector(".title").textContent, gap: (g.top - t.querySelector(".title").getBoundingClientRect().bottom) * k, + bottom: Math.max(g.bottom, ...texts.map((e) => e.getBoundingClientRect().bottom)) * k - box.top * k, + words: texts.filter((e) => !e.classList.contains("reading")).map((e) => e.textContent), bands: t.querySelectorAll("svg .band").length }; + }), })), errors }; + await handsSettled(page); + report[name].hands = await handsLook(page); // the dials' thin red hands: today's highest + report[name].headColours = await page.evaluate(() => Object.fromEntries([...document.querySelectorAll("#grid .tile")].map((t) => // every + [t.querySelector(".title").textContent, [...t.querySelectorAll(".chip.head")].map((e) => [e.textContent, getComputedStyle(e).backgroundColor])]))); // table's heads + await compassSettled(page); + report[name].compass = await compassLook(page); // the wind's direction in the grid: its compass, no table + report[name].dials = await dialsLook(page); // every round dial's hub and pivot, and the pressure's arrow + // zoomed (Enter on the first tile): its look (box, title, text, table) and a screenshot (SHOTS/dashboard-NAME-zoomed.png) + await page.focus(".tile"); + await page.keyboard.press("Enter"); + await calm(page, 400); + await page.screenshot({ path: `${shots}/dashboard-${name}-zoomed.png` }); + report[name].zoomed = await page.evaluate(() => { + const t = document.querySelector("#grid .tile"), rect = (e) => e.getBoundingClientRect().toJSON(); + const table = [...t.querySelectorAll(".unit, .chip, .figure, .tablearea")].map((e) => getComputedStyle(e)); + return { zoomed: document.body.classList.contains("zoomed"), box: rect(t), title: rect(t.querySelector(".title")), + texts: [...t.querySelectorAll("svg text")].map(rect).filter((r) => r.width), + glass: [...t.querySelectorAll("svg .glass")].map(rect), + table: [...new Set(table.map((c) => `${c.visibility} ${c.opacity}`))] }; + }); + // back, then the compass zoomed (Enter): its look as the first's, and a screenshot (SHOTS/dashboard-NAME-compass.png) + await page.keyboard.press("Escape"); + await page.waitForFunction(() => !document.body.classList.contains("zoomed") && !document.querySelector(".tile.zooming, .tile.fading")); + await page.focus('.tile[data-kind="compass"]'); + await page.keyboard.press("Enter"); + await calm(page, 400); + await page.screenshot({ path: `${shots}/dashboard-${name}-compass.png` }); + report[name].compassZoomed = await compassLook(page); + // back, then the UV index zoomed: its limit mark as in the grid, scaled with it (SHOTS/dashboard-NAME-uv.png) + await page.keyboard.press("Escape"); + await page.waitForFunction(() => !document.body.classList.contains("zoomed") && !document.querySelector(".tile.zooming, .tile.fading")); + await page.evaluate(() => [...document.querySelectorAll("#grid .tile")].find((t) => t.querySelector(".title").textContent === "UV index").focus()); + await page.keyboard.press("Enter"); + await calm(page, 400); + await page.screenshot({ path: `${shots}/dashboard-${name}-uv.png` }); + report[name].uvZoomed = { zoomed: await page.evaluate(() => document.body.classList.contains("zoomed")), ...(await handsLook(page))["UV index"] }; + // back, then the pressure zoomed: its hub and arrow as in the grid, scaled with it (SHOTS/dashboard-NAME-pressure.png) + await page.keyboard.press("Escape"); + await page.waitForFunction(() => !document.body.classList.contains("zoomed") && !document.querySelector(".tile.zooming, .tile.fading")); + await page.evaluate(() => [...document.querySelectorAll("#grid .tile")].find((t) => t.querySelector(".title").textContent === "Atmospheric pressure").focus()); + await page.keyboard.press("Enter"); + await calm(page, 400); + await page.screenshot({ path: `${shots}/dashboard-${name}-pressure.png` }); + report[name].pressureZoomed = { zoomed: await page.evaluate(() => document.body.classList.contains("zoomed")), ...(await dialsLook(page))["Atmospheric pressure"] }; + await page.evaluate(() => document.querySelector("#units button[data-unit='inHg']").click()); // (in inHg: its arrow after the wider reading) + await calm(page, 1200); + report[name].pressureInHg = (await dialsLook(page))["Atmospheric pressure"]; await context.close(); - } - process.stdout.write(JSON.stringify(report)); + })); + process.stdout.write(JSON.stringify(Object.fromEntries(Object.keys(wanted).map((name) => [name, report[name]])))); } +// Each tile's red mark at today's highest (null without one): its turn, shown or not, where it is among the dial's parts (after the +// needle, before the hub: [needle, mark, hub] indexes). A hand (the Wind's): its colour and width, its drawn box's narrower side against +// the needle's. A limit mark (a triangle: the others'): its fill, its corners' distances from the dial's centre (its own px, unturned), +// whether its tip points at the centre (its first corner, on the line through the centre it is turned on), the ring's radius, its own +// box; whether, drawn, it is clear of the title's text and of every tick number; its drawn width and its tile's (window px). With the +// Wind tile's table +const handsLook = (page) => page.evaluate(() => Object.fromEntries([...document.querySelectorAll("#grid .tile")].map((t) => { + const hand = t.querySelector("svg .high"), title = t.querySelector(".title").textContent; + if (!hand) return [title, null]; + const parts = [...t.querySelector("svg > g.gauge").children], line = hand.querySelector("path"), mark = hand.querySelector("polygon"); + const hub = parts.filter((e) => e.tagName === "circle").pop(), needle = t.querySelector("svg > g.gauge > polygon"); + const apart = (a, b) => a.right <= b.left || b.right <= a.left || a.bottom <= b.top || b.bottom <= a.top; + const range = document.createRange(); + range.selectNodeContents(t.querySelector(".title")); + const ring = parts.find((e) => e.tagName === "circle"), [cx, cy] = [Number(ring.getAttribute("cx")), Number(ring.getAttribute("cy"))]; + const corners = mark && mark.getAttribute("points").split(" ").map((p) => p.split(",").map(Number)); + const limit = mark && { fill: mark.getAttribute("fill"), radii: corners.map(([x, y]) => Math.hypot(x - cx, y - cy)), + inward: Math.abs(corners[0][1] - cy) < 0.01 && corners[0][0] > cx, + ring: Number(ring.getAttribute("r")), size: (({ width, height }) => ({ width, height }))(mark.getBBox()), + clearOfTitle: apart(mark.getBoundingClientRect(), range.getBoundingClientRect()), + clearOfTicks: [...t.querySelectorAll("svg > g.gauge > text")].filter((e) => /^[\d.]+$/.test(e.textContent)) + .every((e) => apart(mark.getBoundingClientRect(), e.getBoundingClientRect())), + tileWidth: t.getBoundingClientRect().width, drawnWidth: mark.getBoundingClientRect().width }; + return [title, { turn: hand.getAttribute("transform"), shown: hand.style.display !== "none", kind: mark ? "limit" : "hand", + colour: line ? line.getAttribute("stroke") : null, width: line ? Number(line.getAttribute("stroke-width")) : null, + limit, needleWidth: needle.getBBox().width, + order: [parts.indexOf(needle), parts.indexOf(hand), parts.indexOf(hub)], + heads: title === "Wind" ? [...t.querySelectorAll(".chip.head")].map((e) => e.textContent) : undefined, + headColours: title === "Wind" ? [...t.querySelectorAll(".chip.head")].map((e) => getComputedStyle(e).backgroundColor) : undefined, + daily: title === "Wind" ? [...t.querySelectorAll(".figure")].slice(0, 2).map((e) => e.textContent) : undefined }]; +}))); +// Every round dial's (and the compass's) hub and its needle's pivot, in its own px: the hub's centre, radius and outline width; the +// needle's pivot (a dial's: the midpoint of its polygon's two side corners; the compass's: the centre its turn is about). Its arrow +// after the reading (the pressure's way over the past hour; null without one: its group's absence): whether it shows, its way +// (data-way), its path (d, the stroke's colour and width, its box (getBBox, the gauge's px), points along it every px), the reading's box (getBBox: its advance width; the font's line box), its last digit's ink's right edge and its digits' ink (the +// reading's text measured on a canvas in its own font, its middle baseline at the reading's y: [top, bottom]), the dial's outline +// ([cx, cy, r, width]), the hub's, the unit's and the tick numbers' boxes, and in window px the arrow's box and those of the tile's +// title and table (its chips and figures), the tile's width +const dialsLook = (page) => page.evaluate(() => Object.fromEntries([...document.querySelectorAll("#grid .tile")] + .filter((t) => t.dataset.kind === "dial" || t.dataset.kind === "compass").map((t) => { + const title = t.querySelector(".title").textContent, gauge = t.querySelector("svg > g.gauge"), parts = [...gauge.children]; + const hub = t.dataset.kind === "compass" ? gauge.querySelector(":scope > .hub") : parts.filter((e) => e.tagName === "circle").pop(); + const n = (e, k) => Number(e.getAttribute(k)); + let pivot; + if (t.dataset.kind === "compass") pivot = /rotate\([-\d.]+ ([-\d.]+) ([-\d.]+)\)/.exec(gauge.querySelector(".needle").getAttribute("transform")).slice(1).map(Number); + else { + const pts = gauge.querySelector(":scope > polygon").getAttribute("points").split(" ").map((p) => p.split(",").map(Number)); + pivot = [(pts[1][0] + pts[3][0]) / 2, (pts[1][1] + pts[3][1]) / 2]; + } + const g = gauge.querySelector(":scope > g.tendency"); + let arrow = null; + if (g) { + const path = g.querySelector("path.arrow"), shown = getComputedStyle(g).display !== "none"; + const box = (e) => { const b = e.getBBox(); return [b.x, b.y, b.x + b.width, b.y + b.height]; }; + const rect = (e) => { const b = e.getBoundingClientRect(); return [b.left, b.top, b.right, b.bottom]; }; + const reading = gauge.querySelector(":scope > text.reading"), ring = parts.find((e) => e.tagName === "circle"); + const c = document.createElement("canvas").getContext("2d"), style = getComputedStyle(reading); + c.font = `${style.fontWeight} ${reading.getAttribute("font-size")}px ${style.fontFamily}`; + c.textBaseline = "middle"; c.textAlign = "center"; + const m = c.measureText(reading.textContent), y = n(reading, "y"), inkRight = n(reading, "x") + m.actualBoundingBoxRight; + const along = []; + if (shown && path.getAttribute("d")) for (let s = 0, len = path.getTotalLength(); s <= len; s += 1) { const q = path.getPointAtLength(s); along.push([q.x, q.y]); } + arrow = { shown, way: g.dataset.way, d: path.getAttribute("d"), stroke: getComputedStyle(path).stroke, fill: getComputedStyle(g).fill, + width: parseFloat(getComputedStyle(path).strokeWidth), box: shown ? box(path) : null, along, + hubWidth: n(hub, "stroke-width"), reading: box(reading), inkRight, ink: [y - m.actualBoundingBoxAscent, y + m.actualBoundingBoxDescent], + ring: [n(ring, "cx"), n(ring, "cy"), n(ring, "r"), n(ring, "stroke-width")], hub: box(hub), + unit: box(parts.find((e) => e.tagName === "text" && /^(hPa|inHg)$/.test(e.textContent))), + ticks: parts.filter((e) => e.tagName === "text" && e !== reading && /^[\d.]+$/.test(e.textContent)).map(box), + rect: shown ? rect(path) : null, words: [t.querySelector(".title"), ...t.querySelectorAll(".chip, .figure, .unit")].map(rect), + tileWidth: t.getBoundingClientRect().width }; + } + return [title, { kind: t.dataset.kind, hub: [n(hub, "cx"), n(hub, "cy"), n(hub, "r"), n(hub, "stroke-width")], pivot, arrow, + reading: (gauge.querySelector(":scope > text.reading") || {}).textContent, + figures: title === "Atmospheric pressure" ? [...t.querySelectorAll(".figure")].map((e) => e.textContent) : undefined }]; + }))); +// The red hands at rest (the opening's rise or a move over): none turned since the last look, 150 ms before, rather than a fixed wait +const handsSettled = (page) => page.waitForFunction(() => { + const now = [...document.querySelectorAll("#grid .tile svg .high")].map((h) => h.getAttribute("transform")).join("|"); + const still = now && now === window.__hands; + window.__hands = now; + return still; +}, null, { timeout: 5000, polling: 150 }).catch(() => { /* reported as it is */ }); + +// The compass tile's look: its label, reading, needle's turn, the points named, any table, where its parts are (the window's px) and +// its needle's head and tail; its ring's centre and radius in its own px beside a dial's (the first dial tile's ring); its layers, bottom +// to top (the gauge's children's classes); its rose's petals (compass point, share, reach in its own px, colour, opacity); its reading's +// centre's distance from the ring's centre, in its own px +const compassLook = (page) => page.evaluate(() => { + const t = document.querySelector('.tile[data-kind="compass"]'), rect = (e) => e.getBoundingClientRect().toJSON(); + const ring = t.querySelector("svg .ring"), dialRing = document.querySelector('.tile[data-kind="dial"] svg g.gauge > circle'); + const circle = (c) => c && ["cx", "cy", "r"].map((k) => Number(c.getAttribute(k))); + const [cx, cy] = circle(ring), reading = t.querySelector("svg text.reading"); + return { label: t.getAttribute("aria-label"), reading: reading.textContent, faded: t.classList.contains("faded"), + turn: t.querySelector(".needle").getAttribute("transform"), points: [...t.querySelectorAll("svg text.point")].map((e) => e.textContent), + pointColours: [...t.querySelectorAll("svg text.point")].map((e) => e.getAttribute("fill")), + table: t.querySelectorAll(".unit, .chip, .figure, .tablearea").length, zoomed: document.body.classList.contains("zoomed"), + shown: !t.inert, box: rect(t), title: rect(t.querySelector(".title")), texts: [...t.querySelectorAll("svg text")].map(rect), + ring: rect(ring), head: rect(t.querySelector(".needle .head")), hubColour: getComputedStyle(t.querySelector("svg .hub")).stroke, circle: circle(ring), dialCircle: circle(dialRing), + dialRing: dialRing && rect(dialRing), ringStroke: Number(ring.getAttribute("stroke-width")), + layers: [...t.querySelector("svg g.gauge").children].map((e) => e.getAttribute("class") || e.tagName), + readingAt: Math.hypot(Number(reading.getAttribute("x")) - cx, Number(reading.getAttribute("y")) - cy), + readingBelow: Number(reading.getAttribute("y")) - cy, + petals: [...t.querySelectorAll("svg .rose .petal")].map((e) => { + const [x, y] = e.getAttribute("d").match(/L([-\d.]+),([-\d.]+)/).slice(1).map(Number), c = getComputedStyle(e); + return { point: e.dataset.point, share: Number(e.dataset.share), reach: Math.hypot(x - cx, y - cy), colour: c.fill, + opacity: Number(c.fillOpacity) }; + }), + // (its needle's two ends: their fill and how opaque, their size in its own px (the shape's box, not turned) and on the window) + ends: [".head", ".tail"].map((k) => { + const e = t.querySelector(`.needle ${k}`), c = getComputedStyle(e), b = e.getBBox(); + return { colour: c.fill, opacity: Number(c.fillOpacity) * Number(c.opacity), area: b.width * b.height, length: b.height, + width: b.width }; + }) }; +}); + +// The compass at rest: its needle turned all the way to the reading its label gives (north with none), rather than a fixed wait +const compassSettled = (page) => page.waitForFunction(() => { + const t = document.querySelector('.tile[data-kind="compass"]'), turn = t.querySelector(".needle").getAttribute("transform"); + const m = /(\d+)° /.exec(t.getAttribute("aria-label")); + return turn.startsWith(`rotate(${m ? m[1] : 0}.00 `); +}, null, { timeout: 5000 }).catch(() => { /* reported as it is */ }); + async function live(browser, url) { const { page, errors } = await open(browser, url, 800, 600); const label = () => page.evaluate(() => document.querySelector(".tile").getAttribute("aria-label")); - await page.evaluate(() => { window.__mark = 1; document.querySelector(".tile").__mark = 1; }); + await page.evaluate(() => { + window.__mark = 1; document.querySelector(".tile").__mark = 1; + window.__pressureTile = () => [...document.querySelectorAll(".tile")].find((t) => t.querySelector(".title").textContent === "Atmospheric pressure"); + window.__pressure = window.__pressureTile().querySelector("g.tendency"); // (the pressure's arrow: the same group after) + }); + const pressureBefore = (await dialsLook(page))["Atmospheric pressure"]; + // (the compass's needle, every frame from now, the opening's rise over: the wind's direction changes with the temperature) + await compassSettled(page); + await handsSettled(page); + await page.evaluate(() => { + window.__turns = []; + window.__hand = []; // (and the Wind's red hand, every frame: today's highest gust rises; and the UV's limit mark: its highest rises) + window.__limit = []; + const needle = document.querySelector('.tile[data-kind="compass"] .needle'); + const high = (title) => [...document.querySelectorAll(".tile")].find((t) => t.querySelector(".title").textContent === title).querySelector("svg .high"); + const wind = high("Wind"), uv = high("UV index"); + const sample = () => { + window.__turns.push(Number(/rotate\(([-\d.]+)/.exec(needle.getAttribute("transform"))[1])); + window.__hand.push(Number(/rotate\(([-\d.]+)/.exec(wind.getAttribute("transform"))[1])); + window.__limit.push(Number(/rotate\(([-\d.]+)/.exec(uv.getAttribute("transform"))[1])); + requestAnimationFrame(sample); + }; + requestAnimationFrame(sample); + }); const before = await label(); - process.stdout.write(JSON.stringify({ label: before }) + "\n"); + process.stdout.write(JSON.stringify({ label: before, pressure: pressureBefore }) + "\n"); await new Promise((resolve) => readline.createInterface({ input: process.stdin }).once("line", resolve)); try { await page.waitForFunction((was) => document.querySelector(".tile").getAttribute("aria-label") !== was, before, { timeout: 15000 }); @@ -57,7 +333,13 @@ async function live(browser, url) { const sameTile = await page.evaluate(() => document.querySelector(".tile").__mark === 1); // moved in place, not drawn again await page.waitForTimeout(1200); // (the gauge's move to the new reading, MOVE_MS) const shown = await page.evaluate(() => [...document.querySelectorAll(".tile")[0].querySelectorAll("svg text")].map((t) => t.textContent).join("|")); - process.stdout.write(JSON.stringify({ label: await label(), same_page: same, same_tile: sameTile, shown, errors }) + "\n"); + await compassSettled(page); + const compass = { ...await compassLook(page), turns: await page.evaluate(() => window.__turns) }; + await handsSettled(page); + const hands = { ...await handsLook(page), frames: await page.evaluate(() => window.__hand), limitFrames: await page.evaluate(() => window.__limit) }; + const pressureSame = await page.evaluate(() => window.__pressure.isConnected && window.__pressure === window.__pressureTile().querySelector("g.tendency")); + const pressure = { ...(await dialsLook(page))["Atmospheric pressure"], same: pressureSame }; // (its arrow turned in place) + process.stdout.write(JSON.stringify({ label: await label(), same_page: same, same_tile: sameTile, shown, compass, hands, pressure, errors }) + "\n"); } async function arrive(browser, url, title) { @@ -72,7 +354,8 @@ async function arrive(browser, url, title) { await page.evaluate((title) => { window.__tile = [...document.querySelectorAll(".tile")].find((t) => t.querySelector(".title").textContent === title); }, title); - const before = await state(); + await compassSettled(page); + const before = await state(), compassBefore = await compassLook(page); process.stdout.write(JSON.stringify(before) + "\n"); await new Promise((resolve) => readline.createInterface({ input: process.stdin }).once("line", resolve)); try { @@ -90,7 +373,3212 @@ async function arrive(browser, url, title) { })); const sameTile = await page.evaluate((title) => window.__tile.isConnected && [...document.querySelectorAll(".tile")].find((t) => t.querySelector(".title").textContent === title) === window.__tile, title); - process.stdout.write(JSON.stringify({ before, after: await state(), frames, same_tile: sameTile, errors }) + "\n"); + await compassSettled(page); + process.stdout.write(JSON.stringify({ before, after: await state(), frames, same_tile: sameTile, compass: [compassBefore, await compassLook(page)], + pressure: (await dialsLook(page))["Atmospheric pressure"], errors }) + "\n"); +} + +// ---------- arranging ---------- +const KEY = "ecobot.dashboard.v1"; +const titles = (page) => page.evaluate(() => [...document.querySelectorAll("#grid .tile .title")].map((t) => t.textContent)); +const tileOf = (page, title) => page.locator(".tile", { has: page.locator(".title", { hasText: new RegExp(`^${title}$`) }) }); +// The page at rest, rather than a fixed wait: nothing in its document changed (a gauge's needle, a tile's transform, a class) for 50 ms +// and two frames (a busy machine's frames come far apart: a gauge moving changes something every frame), and no animation or transition +// running (an endless one aside); at most `cap` ms: the fixed wait it stands for where that was a margin, longer for the gauges' rise +// and moves (which the frames counted after them must not include, however slow the machine is just then). (Not for what a timer +// starts later, a long press or a swipe's end: a wait for that.) +const calm = (page, cap = 450) => page.evaluate((cap) => new Promise((resolve) => { + const start = performance.now(); + let changed = start, changes = 0, was = -1, quiet = 0; + const seen = new MutationObserver(() => { changed = performance.now(); changes++; }); + seen.observe(document.documentElement, { subtree: true, attributes: true, childList: true, characterData: true }); + const moving = () => document.getAnimations().some((a) => a.playState === "running" && a.effect.getComputedTiming().endTime !== Infinity); + const check = (now) => { + if (moving()) changed = Math.max(changed, now); + quiet = moving() || changes !== was ? 0 : quiet + 1; + was = changes; + if ((quiet >= 2 && performance.now() - changed >= 50) || now - start >= cap) { seen.disconnect(); resolve(); } else requestAnimationFrame(check); + }; + requestAnimationFrame(check); +}), cap); + +async function at(page, title, fx, fy) { // a point of a tile, as fractions of it + const r = await tileOf(page, title).boundingBox(); + return [r.x + r.width * fx, r.y + r.height * fy]; +} +async function centreOf(page, locator) { + const r = await locator.boundingBox(); + return [r.x + r.width / 2, r.y + r.height / 2]; +} +async function mouseDrag(page, [x0, y0], [x1, y1], during) { + await page.mouse.move(x0, y0); + await page.mouse.down(); + for (let i = 1; i <= 12; i++) await page.mouse.move(x0 + (x1 - x0) * i / 12, y0 + (y1 - y0) * i / 12); + await calm(page); // (the others made room) + const seen = during ? await during() : null; + await page.mouse.up(); + await calm(page); + return seen; +} +const selection = (page) => page.evaluate(() => { const s = String(window.getSelection()); window.getSelection().removeAllRanges(); return s; }); +const statusText = (page) => page.evaluate(() => document.getElementById("status").textContent); +const stored = (page) => page.evaluate((key) => localStorage.getItem(key), KEY); +const midDrag = (page) => page.evaluate(() => ({ + zone: getComputedStyle(document.getElementById("remove")).transform, over: document.getElementById("remove").classList.contains("over"), + dragging: document.body.classList.contains("dragging"), + moved: [...document.querySelectorAll("#grid .tile:not(.lifted)")].filter((t) => t.style.transform).map((t) => t.querySelector(".title").textContent), +})); + +// In three parts (each its own page: the tests run them side by side): "dragged" (dragged, and drags on the text), "hidden" (dragged, +// then hidden, reloaded and reset) and "prefs" (preferences unreadable or from elsewhere, a click soon after a drop and the × from the +// keyboard; then storage blocked, on a page of its own beside it), and "stale" (the strip with a device's reading over an hour old). +async function arrangeMode(browser, url, part) { + const out = {}, errors = []; + if (part === "dragged") await arranged(browser, url, out, errors); + else if (part === "hidden") await arrangedHidden(browser, url, out, errors); + else if (part === "stale") await arrangedStale(browser, url, out, errors); + else if (part === "reset") await arrangedReset(browser, url, out, errors); + else await Promise.all([arrangedFromPrefs(browser, url, out, errors), arrangedBlocked(browser, url, out)]); + out.errors = errors; + return out; +} +async function arranged(browser, url, out, allErrors) { + const { context, page, errors } = await open(browser, url, 1024, 768, { risen: true }); + await calm(page); // (at rest: drawn at their readings, risen) + out.initial = await titles(page); + // the look: the tile's own background clear, its foreground opaque + out.look = await page.evaluate(() => { + const tile = [...document.querySelectorAll(".tile")].find((t) => !t.classList.contains("faded")); + const style = getComputedStyle(tile), frame = getComputedStyle(tile, "::before"); + return { background: style.backgroundColor, image: style.backgroundImage, opacity: style.opacity, title: getComputedStyle(tile.querySelector(".title")).color, + reading: getComputedStyle(tile.querySelector("svg text.reading")).fill, frame: frame.borderTopColor, frameWidth: frame.borderTopWidth, + grid: getComputedStyle(document.getElementById("grid")).backgroundColor, body: getComputedStyle(document.body).backgroundColor }; + }); + // mouseover: the grip and the × show on the tile under the mouse only + await page.mouse.move(...await at(page, "Humidity", 0.5, 0.4)); + await calm(page); + // mouseover: no frame, the tile under the mouse too (shown only picked up, or with the keyboard's focus) + out.hoverFrames = await page.evaluate(() => [...document.querySelectorAll(".tile")].slice(0, 3).map((t) => getComputedStyle(t, "::before").borderTopColor)); + out.hover = await page.evaluate(() => [...document.querySelectorAll(".tile")].slice(0, 3).map((t) => ({ + grip: getComputedStyle(t.querySelector(".grip")).opacity, close: getComputedStyle(t.querySelector(".close")).opacity }))); + // the grip under the mouse: its size and place in its tile (px), its dots' spacing + out.grip = await page.evaluate(() => { + const t = [...document.querySelectorAll(".tile")][1], g = t.querySelector(".grip"), r = g.getBoundingClientRect(), b = t.getBoundingClientRect(); + return { width: r.width, height: r.height, left: r.left - b.left, top: r.top - b.top, dots: getComputedStyle(g).backgroundSize }; + }); + // the frame shown on the tile under the mouse picked up, then (the mouse gone) with the keyboard's focus, then neither + const frameOf = (title) => page.evaluate((title) => getComputedStyle([...document.querySelectorAll(".tile")].find((t) => t.querySelector(".title").textContent === title), "::before").borderTopColor, title); + const humidity = (how) => page.evaluate((how) => [...document.querySelectorAll(".tile")].find((t) => t.querySelector(".title").textContent === "Humidity").classList[how]("lifted"), how); + out.shownFrames = {}; + await humidity("add"); + out.shownFrames.lifted = await frameOf("Humidity"); + await humidity("remove"); + await page.mouse.move(1, 1); + await page.keyboard.press("Shift"); // (the keyboard in use: the focus seen) + await page.evaluate(() => [...document.querySelectorAll(".tile")].find((t) => t.querySelector(".title").textContent === "Humidity").focus()); + out.shownFrames.focused = await frameOf("Humidity"); + await page.evaluate(() => document.activeElement.blur()); + out.shownFrames.after = await frameOf("Humidity"); + await page.mouse.move(...await at(page, "Humidity", 0.5, 0.4)); + await calm(page); + // a drag from the gauge: Temperature to Atmospheric pressure's place, the others making room meanwhile + out.during = await mouseDrag(page, await at(page, "Temperature", 0.85, 0.3), await at(page, "Atmospheric pressure", 0.5, 0.4), () => midDrag(page)); + out.dragged = await titles(page); + out.transforms = await page.evaluate(() => [...document.querySelectorAll(".tile")].filter((t) => getComputedStyle(t).transform !== "none").length); + out.storedAfterDrag = JSON.parse(await stored(page)); + // drags starting on the text: nothing moves, the text is selected + out.text = {}; + for (const [name, locator] of [["title", tileOf(page, "Rain").locator(".title")], ["table", tileOf(page, "Humidity").locator(".figure").first()], + ["reading", tileOf(page, "Humidity").locator("svg text.reading")]]) { + const r = await locator.boundingBox(), y = r.y + r.height / 2; // (across it, end to end) + const before = await titles(page); + const during = await mouseDrag(page, [r.x + 2, y], [r.x + r.width - 1, y + 1], () => midDrag(page)); + out.text[name] = { same: JSON.stringify(before) === JSON.stringify(await titles(page)), dragging: during.dragging, selected: await selection(page) }; + } + allErrors.push(...errors); + await context.close(); +} +// "reset preferences" left of the units' switches, in the bar with them (reset | switches | strip): the switches' boxes the same with the +// link shown (a unit switched) and gone (reset), at a desktop's, a tablet's and two phones' widths; the link left of the first +// switch, on screen, over nothing; clicking it puts the tiles, the units and the order back. +async function arrangedReset(browser, url, all, allErrors) { + const out = all.resetBar = {}; + out.widths = {}; + for (const [width, height] of [[1440, 900], [1024, 768], [768, 1024], [390, 800], [320, 600]]) { + const { context, page, errors } = await open(browser, url, width, height, { risen: true }); + await calm(page); + const look = () => page.evaluate(() => { + const box = (e) => { const r = e.getBoundingClientRect(); return { left: r.left, top: r.top, right: r.right, bottom: r.bottom }; }; + const units = [...document.querySelectorAll("#units button")].map(box), link = document.querySelector("#reset .link"); + const apart = (a, b) => a.right <= b.left || b.right <= a.left || a.bottom <= b.top || b.bottom <= a.top; + const strip = box(document.getElementById("status")), bar = box(document.getElementById("units")); + return { units, bar, strip, link: link && box(link), linkInStrip: !!document.querySelector("#status .reset"), name: link && link.textContent, + layout: document.body.dataset.units, reset: document.body.dataset.reset, status: document.getElementById("status").textContent, + onScreen: !link || (link.getBoundingClientRect().left >= 0 && link.getBoundingClientRect().right <= innerWidth && link.getBoundingClientRect().bottom <= innerHeight), + clear: !link || [...units, strip].every((u) => apart(box(link), u)), width: innerWidth }; + }); + const first = await look(); + await page.locator("#units button", { hasText: "°F" }).click(); + await calm(page); + const shown = await look(); + if (process.env.RESET_SHOTS) await page.screenshot({ path: `${process.env.RESET_SHOTS}/reset-${width}.png`, clip: { x: 0, y: height - 90, width, height: 90 } }); + const order = await titles(page); + await page.getByText("reset preferences").click(); + await calm(page); + const gone = await look(); + out.widths[width] = { first, shown, gone, restored: JSON.stringify(order) === JSON.stringify(await titles(page)), stored: await stored(page) }; + allErrors.push(...errors); + await context.close(); + } + // a tile hidden: the link, the tiles back on reset + const { context, page, errors } = await open(browser, url, 1024, 768, { risen: true }); + await calm(page); + const before = await titles(page); + await page.mouse.move(...await at(page, "Rain", 0.5, 0.4)); + await calm(page); + await tileOf(page, "Rain").locator(".close").click(); + await calm(page); + out.hidden = { titles: await titles(page), link: await page.locator("#reset .link").count() }; + await page.getByText("reset preferences").click(); + await calm(page); + out.back = { titles: await titles(page), link: await page.locator("#reset .link").count(), same: JSON.stringify(before) === JSON.stringify(await titles(page)) }; + allErrors.push(...errors); + await context.close(); +} +async function arrangedHidden(browser, url, out, allErrors) { + const { context, page, errors } = await open(browser, url, 1024, 768, { risen: true }); + await calm(page); // (at rest: drawn at their readings, risen) + // (dragged as on the other page: Temperature to Atmospheric pressure's place) + await mouseDrag(page, await at(page, "Temperature", 0.85, 0.3), await at(page, "Atmospheric pressure", 0.5, 0.4)); + // the ×: Rain hidden, the reset link shown + await page.mouse.move(...await at(page, "Rain", 0.5, 0.4)); + await calm(page); + await tileOf(page, "Rain").locator(".close").click(); + await calm(page); + out.closed = { titles: await titles(page), status: await statusText(page) }; + // dropped on the remove zone: Wind hidden + out.removing = await mouseDrag(page, await at(page, "Wind", 0.5, 0.3), [500, 20], () => midDrag(page)); + out.removed = { titles: await titles(page), stored: JSON.parse(await stored(page)) }; + // reloaded: the same order and hidden tiles + await page.reload({ waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0); + await calm(page, 300); + out.reloaded = { titles: await titles(page), status: await statusText(page) }; + // reset: every tile back in the default order, the link gone, nothing kept + await page.getByText("reset preferences").click(); + await calm(page); + out.reset = { titles: await titles(page), status: await statusText(page), stored: await stored(page) }; + await unitsSwitched(page, out); + allErrors.push(...errors); + await context.close(); +} +// The units' switches (on the "hidden" part's page, after its reset): the temperature tiles, the Wind, Atmospheric pressure, Rain, +// Rain rate and Humidity (untouched) as they look (unitsLook) in metric, then °F (clicked), then mph too (the Wind's needle sampled +// each frame as it eases), then inHg, then in; reloaded; km/h again from the keyboard; then "reset preferences" (metric again). Each: +// the looks (the pressure's arrow's way too), the switches' pressed state and the strip +const UNIT_TILES = ["Temperature", "Dew point", "Feels like", "Wind", "Humidity", "Atmospheric pressure", "Rain", "Rain rate"]; +const unitsLook = (page) => page.evaluate((names) => { + const look = {}; + for (const t of document.querySelectorAll("#grid .tile")) { + const title = t.querySelector(".title").textContent; + if (!names.includes(title)) continue; + const high = t.querySelector("svg .high"), arrow = t.querySelector("svg g.tendency"); + look[title] = { arrow: arrow ? arrow.dataset.way : null, label: t.getAttribute("aria-label"), reading: t.querySelector("svg text.reading").textContent, + words: [...t.querySelectorAll("svg text:not(.reading)")].map((e) => e.textContent), + unit: t.querySelector(".unit").textContent, figures: [...t.querySelectorAll(".figure")].map((e) => e.textContent), + hand: high ? high.getAttribute("transform") : null }; + } + return { tiles: look, pressed: [...document.querySelectorAll("#units button")].map((b) => [b.textContent, b.getAttribute("aria-pressed")]), + status: document.getElementById("status").textContent, stored: JSON.parse(localStorage.getItem("ecobot.dashboard.v1")), + focused: document.activeElement && document.activeElement.closest("#units") ? document.activeElement.textContent : null }; +}, UNIT_TILES); +async function unitsSwitched(page, out) { + const seen = out.units = {}; + await calm(page, 2000); + seen.metric = await unitsLook(page); + await page.click("#units button[data-unit='°F']"); + await calm(page, 2000); + seen.fahrenheit = await unitsLook(page); + const needle = () => page.evaluate(() => new Promise((resolve) => { // (the Wind's needle each frame for 1.2 s: its points) + const all = [], start = performance.now(); + const tile = () => [...document.querySelectorAll("#grid .tile")].find((t) => t.querySelector(".title").textContent === "Wind"); + const step = (now) => { all.push(tile().querySelector("svg polygon").getAttribute("points")); if (now - start < 1200) requestAnimationFrame(step); else resolve(all); }; + requestAnimationFrame(step); + })); + const [, frames] = await Promise.all([page.click("#units button[data-unit='mph']"), needle()]); + seen.needleSteps = new Set(frames).size; + await calm(page, 2000); + seen.mph = await unitsLook(page); + await page.click("#units button[data-unit='inHg']"); + await calm(page, 2000); + seen.inHg = await unitsLook(page); + await page.click("#units button[data-unit='in']"); + await calm(page, 2000); + seen.inches = await unitsLook(page); + await page.reload({ waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0 && /last reading/.test(document.getElementById("status").textContent)); + await calm(page, 2000); + seen.reloaded = await unitsLook(page); + await page.focus("#units button[data-unit='km/h']"); // the keyboard: km/h again (Enter) + await page.keyboard.press("Enter"); + await calm(page, 2000); + seen.keyboard = await unitsLook(page); + await page.getByText("reset preferences").click(); + await calm(page, 2000); + seen.reset = await unitsLook(page); +} +async function arrangedFromPrefs(browser, url, out, allErrors) { + const { context, page, errors } = await open(browser, url, 1024, 768, { risen: true }); + const initial = await titles(page); + // preferences corrupt: the defaults; a tile new to the saved order: in its usual place (after the tile before it by default) + await page.evaluate((key) => localStorage.setItem(key, "{not json"), KEY); + await page.reload({ waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0); + out.corrupt = await titles(page); + // a layout saved while the AQI tile was titled "US AQI": that tile moved first, then hidden, as it was left + const renamed = async (prefs) => { + await page.evaluate(([key, prefs]) => localStorage.setItem(key, JSON.stringify(prefs)), [KEY, prefs]); + await page.reload({ waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0); + return titles(page); + }; + out.renamedMoved = await renamed({ order: ["US AQI", ...initial.filter((t) => t !== "AQI")], hidden: [] }); + out.renamedHidden = await renamed({ order: [], hidden: ["US AQI", "Rain"] }); + const saved = initial.filter((t) => !["Rain", "Temperature", "Wind direction"].includes(t)).concat(["Temperature", "Gone sensor"]); + await page.evaluate(([key, order]) => localStorage.setItem(key, JSON.stringify({ order, hidden: ["Gone sensor"], later: true })), [KEY, saved]); + await page.reload({ waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0); + out.newTile = await titles(page); + // (dropped on another tile, so the browser sends no click for the drop; a click on a tile 150 ms later arrives) + await page.evaluate(() => { window.__clicks = []; addEventListener("click", (e) => window.__clicks.push(e.target.closest(".tile") ? "tile" : "page")); }); + const [h0, r0] = [await at(page, "Humidity", 0.5, 0.3), await at(page, "Rain", 0.5, 0.4)]; + await page.mouse.move(...h0); + await page.mouse.down(); + for (let i = 1; i <= 12; i++) await page.mouse.move(h0[0] + (r0[0] - h0[0]) * i / 12, h0[1] + (r0[1] - h0[1]) * i / 12); + await page.mouse.up(); + await page.waitForTimeout(150); + await page.mouse.click(...await at(page, "Wind", 0.5, 0.3)); + await calm(page); + out.clickAfterDrop = await page.evaluate(() => window.__clicks); + out.zoomedAfterDrop = await page.evaluate(() => document.body.classList.contains("zoomed")); // (that click zoomed Wind: back) + await page.keyboard.press("Escape"); + await calm(page); + out.keptOthers = JSON.parse(await stored(page)); + // the × pressed from the keyboard: the focus goes on to the next tile's ×; with the last tile hidden, to the reset link + await calm(page); + await page.keyboard.press("Shift"); // (the keyboard in use: the first tile's × focused as by the keyboard) + await page.evaluate(() => document.querySelector(".close").focus()); + const focused = () => page.evaluate(() => document.activeElement.getAttribute("aria-label") || document.activeElement.textContent); + out.keyboardHide = [await focused()]; + await page.keyboard.press("Enter"); + await calm(page); + out.keyboardHide.push(await focused()); + const allBut = initial.filter((t) => t !== "Rain"); + await page.evaluate(([key, hidden]) => localStorage.setItem(key, JSON.stringify({ order: [], hidden })), [KEY, allBut]); + await page.reload({ waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0); + await page.keyboard.press("Tab"); // (the tile itself first, then its ×) + out.keyboardTile = await focused(); + await page.keyboard.press("Tab"); + out.keyboardHide.push(await focused()); + await page.keyboard.press("Enter"); + await calm(page); + out.keyboardHide.push(await focused()); + allErrors.push(...errors); + await context.close(); +} +// The strip's reading time as the devices' readings age: the data's `devices` replaced on the way in by readings this old (ms; null: none +// held; a device left out: not configured), fetched again (as the page does when it is shown again); each step's {text, grey (the +// greyed-out parts), sent (the devices as sent)}. Last, a device turning stale with no new data: {before, after, ms (till it did)}. +const STALE_STEPS = { fresh: { station: 0, air: 60e3 }, airStale: { station: 0, air: 2 * 3600e3 }, recovered: { station: 0, air: 0 }, + stationStale: { station: 3 * 3600e3, air: 30e3 }, bothStale: { station: 3 * 3600e3, air: 2 * 3600e3 }, + noReading: { station: null, air: 0 }, only: { station: 2 * 3600e3 }, onlyFresh: { station: 0 } }; +async function arrangedStale(browser, url, out, allErrors) { + const { context, page, errors } = await open(browser, url, 1024, 768, { init: { fn: () => { + window.__fetched = 0; + const get = window.fetch.bind(window); + window.fetch = async (...args) => { + const response = await get(...args); + if (/\/dashboard\/data$/.test(String(args[0]))) { + const json = response.json.bind(response); + response.json = async () => { + const data = await json(); + if (window.__ages) data.devices = window.__sent = Object.fromEntries(Object.entries(window.__ages).map(([d, age]) => + [d, age === null ? null : new Date(Date.now() - age).toISOString()])); + window.__fetched++; + return data; + }; + } + return response; + }; + } } }); + const strip = () => page.evaluate(() => ({ text: document.getElementById("status").textContent, sent: window.__sent || null, + grey: [...document.querySelectorAll("#status .stale")].map((e) => e.textContent) })); + const send = async (ages) => { + const n = await page.evaluate((ages) => { window.__ages = ages; document.dispatchEvent(new Event("visibilitychange")); return window.__fetched; }, ages); + await page.waitForFunction((n) => window.__fetched > n, n); + return strip(); + }; + out.stale = { real: await strip() }; + for (const [name, ages] of Object.entries(STALE_STEPS)) { + out.stale[name] = await send(ages); + if (name === "airStale") out.stale.colours = await page.evaluate(() => [getComputedStyle(document.getElementById("status")).color, + getComputedStyle(document.querySelector("#status .stale")).color]); + } + // the station's reading turning an hour old 1.5 s from now, the air sensor's already stale: no new data, the strip greys out by itself + const turning = { before: await send({ station: 3600e3 - 1500, air: 2 * 3600e3 }) }; + const t0 = Date.now(); + await page.waitForFunction(() => [...document.querySelectorAll("#status .stale")].some((e) => /^last reading/.test(e.textContent)), null, { timeout: 6000 }); + turning.ms = Date.now() - t0; + turning.after = await strip(); + out.stale.turning = turning; + allErrors.push(...errors); + await context.close(); +} +async function arrangedBlocked(browser, url, out) { + // storage blocked: the page works, nothing saved, no error + const blocked = await open(browser, url, 1024, 768, { risen: true, init: { fn: () => { + Object.defineProperty(window, "localStorage", { get() { throw new DOMException("blocked", "SecurityError"); } }); + } } }); + await calm(blocked.page, 300); + await mouseDrag(blocked.page, await at(blocked.page, "Temperature", 0.85, 0.3), await at(blocked.page, "Humidity", 0.5, 0.4)); + await blocked.page.mouse.move(...await at(blocked.page, "Rain", 0.5, 0.4)); + await calm(blocked.page); + await tileOf(blocked.page, "Rain").locator(".close").click(); + await calm(blocked.page); + out.blocked = { titles: await titles(blocked.page), errors: blocked.errors }; + await blocked.context.close(); +} + +// Touch through the browser's own input (CDP), as a finger: the browser decides on scrolling, long presses and taps. In three parts (each +// its own page: the tests run them side by side): "taps" (a tap and a swipe), "edge" (a long press at the bottom edge) and "held" (a +// tile picked up, moved and dropped, then one held in place and hidden by its ×). +async function touchMode(browser, url, part) { + const out = {}, errors = []; + await touchPage(browser, url, part, out, errors); + out.errors = errors; + return out; +} +async function touchPage(browser, url, part, out, allErrors) { + const { context, page, errors } = await open(browser, url, 390, 844, { risen: true, + context: { hasTouch: true, isMobile: true }, + init: { fn: () => { + window.__buzz = []; + navigator.vibrate = (ms) => { window.__buzz.push(ms); return true; }; + window.__clicks = 0; + addEventListener("click", (e) => { if (e.target.closest && e.target.closest(".tile")) window.__clicks++; }); + } }, + }); + const cdp = await context.newCDPSession(page); + const touch = (type, points) => cdp.send("Input.dispatchTouchEvent", { type, touchPoints: points.map(([x, y]) => ({ x, y })) }); + const state = () => page.evaluate(() => ({ + buzz: window.__buzz, clicks: window.__clicks, scrollY: window.scrollY, + zone: document.getElementById("remove").classList.contains("on"), + armed: [...document.querySelectorAll(".tile.armed")].map((t) => t.querySelector(".title").textContent), + close: (() => { const c = document.querySelector(".tile.armed .close"); return c ? getComputedStyle(c).opacity : null; })(), + })); + await calm(page); // (at rest: drawn at their readings, risen) + if (part === "held") await touchHeld(page, touch, state, out); + else if (part === "edge") await touchEdge(page, touch, out); + else { + out.initial = await titles(page); + await touchTaps(page, touch, state, out); + } + allErrors.push(...errors); + await context.close(); +} +async function touchTaps(page, touch, state, out) { + // a short tap: a click, nothing picked up + const t0 = await at(page, "Temperature", 0.85, 0.3); + await touch("touchStart", [t0]); + await page.waitForTimeout(80); + await touch("touchEnd", []); + await page.waitForTimeout(600); + out.tap = { ...await state(), titles: await titles(page), zoomed: await page.evaluate(() => document.body.classList.contains("zoomed")) }; + await page.keyboard.press("Escape"); // (the tap zoomed the tile: back) + await calm(page, 400); + // a swipe up before the long press: the page scrolls, nothing picked up + const s0 = await at(page, "Humidity", 0.5, 0.3); + await touch("touchStart", [s0]); + for (let i = 1; i <= 10; i++) { await touch("touchMove", [[s0[0], s0[1] - 30 * i]]); await page.waitForTimeout(16); } + await touch("touchEnd", []); + await page.waitForTimeout(700); + out.swipe = { ...await state(), titles: await titles(page) }; +} +async function touchEdge(page, touch, out) { + // held near the bottom edge: the page scrolls to its end and no further (the lifted tile mustn't stretch it without end) + const end = await page.evaluate(() => document.documentElement.scrollHeight - innerHeight); + const e0 = await at(page, "Temperature", 0.85, 0.3); + await touch("touchStart", [e0]); + await page.waitForTimeout(700); + for (let i = 1; i <= 6; i++) { await touch("touchMove", [[e0[0], e0[1] + (830 - e0[1]) * i / 6]]); await page.waitForTimeout(16); } + const seen = []; + for (let i = 0; i < 12; i++) { await page.waitForTimeout(250); seen.push(await page.evaluate(() => window.scrollY)); } + await touch("touchEnd", []); + await calm(page); + out.edge = { end, seen, after: await page.evaluate(() => window.scrollY) }; +} +async function touchHeld(page, touch, state, out) { + // a long press: picked up (buzz, grip and ×, the remove zone), then moved to Atmospheric pressure's place + const p0 = await at(page, "Temperature", 0.85, 0.3), p1 = await at(page, "Atmospheric pressure", 0.5, 0.4); + await touch("touchStart", [p0]); + await page.waitForTimeout(700); + out.held = await state(); + for (let i = 1; i <= 12; i++) { await touch("touchMove", [[p0[0] + (p1[0] - p0[0]) * i / 12, p0[1] + (p1[1] - p0[1]) * i / 12]]); await page.waitForTimeout(16); } + await calm(page, 300); // (the others made room) + out.moving = { ...await state(), during: await midDrag(page) }; + await touch("touchEnd", []); + await calm(page); + out.dropped = { ...await state(), titles: await titles(page) }; + // a long press let go in place: its grip and × stay; a tap on the × hides it + const h0 = await at(page, "Humidity", 0.85, 0.3); + await touch("touchStart", [h0]); + await page.waitForTimeout(700); + await touch("touchEnd", []); + await calm(page, 300); + out.armed = await state(); + const c = await centreOf(page, tileOf(page, "Humidity").locator(".close")); + await touch("touchStart", [c]); + await page.waitForTimeout(50); + await touch("touchEnd", []); + await calm(page); + out.closed = { titles: await titles(page), status: await statusText(page) }; +} + +// ---------- the zoomed view and its gallery ---------- +// In the page: the tile shown (the one wholly on the screen), the strip's offset, and a recorder of either, frame by frame +const ZOOM_HELPERS = () => { + const titleOf = (t) => t.querySelector(".title").textContent; + window.__shown = () => { + const t = [...document.querySelectorAll("#grid .tile")].find((t) => { const r = t.getBoundingClientRect(); return r.left >= -1 && r.right <= innerWidth + 1; }); + return t ? titleOf(t) : null; + }; + window.__track = () => new DOMMatrixReadOnly(getComputedStyle(document.getElementById("grid")).transform).m41; + window.__state = () => ({ zoomed: document.body.classList.contains("zoomed"), shown: window.__shown(), track: Math.round(window.__track()) }); + window.__tile = (title) => [...document.querySelectorAll("#grid .tile")].find((t) => titleOf(t) === title); + // every frame for `ms`, and on till no animation is left to finish (one held paused too: at most 5 s): the tile's rect (title given) + // or the strip's offset; when the last click or key came; and the animations it started there and then, as it was handled + // (window.__timed): how long they run on their own timeline, and whether they finished, by the end + const going = () => document.getAnimations().some((a) => !["finished", "idle"].includes(a.playState) && a.effect && a.effect.getComputedTiming().endTime !== Infinity); + window.__record = (title, ms) => new Promise((resolve) => { + const frames = [], start = performance.now(); + window.__timed = null; + const step = (now) => { + if (title) { // (and its title's place, and its table's opacity: a figure's, as drawn) + const t = window.__tile(title), r = t.getBoundingClientRect(), h = t.querySelector(".title").getBoundingClientRect(); + const f = getComputedStyle(t.querySelector(".figure")); + frames.push({ t: now, left: r.left, top: r.top, width: r.width, height: r.height, titleTop: h.top, titleSize: h.height, + table: f.visibility === "hidden" ? 0 : +f.opacity }); + } + else frames.push({ t: now, x: window.__track() }); + window.__drawn = now; + if (now - start < ms || (going() && now - start < 5000)) return requestAnimationFrame(step); + const timed = window.__timed && { end: window.__timed.end, finished: window.__timed.anims.every((a) => a.playState === "finished") }; + resolve({ frames, at: window.__at, timed }); + }; + requestAnimationFrame(step); + }); + // (the animations a click or a key started as it was handled, in its own task (not a frame or a timer later), and how long they run + // on their own timeline (Animation's: their delay and duration), from their start) + window.__started = (anims) => { + window.__timed = { end: Math.max(...anims.map((a) => a.effect.getComputedTiming().endTime)), anims }; + }; + addEventListener("click", () => { window.__at = performance.now(); }, true); + addEventListener("click", () => { // (after the page's own: the zoom's animations started) + window.__anims = document.getAnimations().filter((a) => !(a instanceof CSSTransition)).map((a) => a.effect.getTiming().duration); + const zoom = document.getAnimations().filter((a) => a.id === "zoom" && a.playState !== "finished"); + if (zoom.length) window.__started(zoom); + }); + addEventListener("keydown", (e) => { window.__at = performance.now(); setTimeout(() => window.__keys.push([e.key, e.defaultPrevented])); }); + addEventListener("wheel", (e) => { setTimeout(() => window.__wheels.push(e.defaultPrevented)); }, { passive: true }); + window.__keys = []; window.__wheels = []; + // A tile's look: its box; its title, reading and the gauge's other words, each on the screen; its table's visibility and opacity + window.__look = (title) => { + const t = window.__tile(title), rect = (e) => e && e.getBoundingClientRect().toJSON(); + const table = [...t.querySelectorAll(".unit, .chip, .figure, .tablearea")].map((e) => getComputedStyle(e)); + return { box: rect(t), title: rect(t.querySelector(".title")), reading: rect(t.querySelector("svg text.reading")), + texts: [...t.querySelectorAll("svg text")].map(rect).filter((r) => r.width), + table: [...new Set(table.map((c) => `${c.visibility} ${c.opacity}`))] }; + }; +}; +// A recording summed up: where it started and ended, whether it passed through between, and how long after the click or key it came to +// rest: on the page's own clock, the animations the click or key started as it was handled, their length on their own timeline, once +// they finished there (null if none started then, they didn't finish, or it never came to rest) - not the frames' times, which a busy +// machine spaces out as it likes, nor the handler's, which it slows as it likes +function motion(rec, key) { + const f = rec.frames, last = f[f.length - 1], same = (a, b) => key.every((k) => Math.abs(a[k] - b[k]) < 0.5); + const after = f.filter((x) => x.t >= rec.at); + const rest = after.find((x, i) => after.slice(i).every((y) => same(y, last))); + const { timed } = rec; + return { first: after[0], last, between: after.some((x) => !same(x, after[0]) && !same(x, last)), + settledMs: rest && timed && timed.finished ? Math.round(timed.end) : null, + extreme: key[0] === "x" ? Math.max(...after.map((x) => Math.abs(x.x - last.x))) : null }; +} +async function zoomClick(page, title, point) { // a click, the tile's rect recorded through the zoom + const recording = page.evaluate((title) => window.__record(title, 700), title); // (to the table's fade back in, after the zoom out) + await page.waitForTimeout(50); + await page.mouse.click(...point); + const rec = await recording; + const after = rec.frames.filter((x) => x.t >= rec.at); + return { ...motion(rec, ["left", "top", "width", "height"]), anims: await page.evaluate(() => window.__anims), ...await page.evaluate(() => window.__state()), + tables: after.map((x) => x.table), titles: after.map((x) => [(x.titleTop - x.top) / x.width, x.titleSize / x.width]) }; +} +async function keyStep(page, key, wait = 400) { // a key, the strip recorded as it slides + const recording = page.evaluate(() => window.__record(null, 450)); + await page.evaluate(() => addEventListener("keydown", () => { // (after the page's own: the slide or nudge it started) + getComputedStyle(document.getElementById("grid")).transform; // (its transition made now, as the next frame would) + const anims = document.getElementById("grid").getAnimations().filter((a) => a.playState !== "finished"); + if (anims.length) window.__started(anims); + }, { once: true })); + await page.waitForTimeout(50); + await page.keyboard.press(key); + const rec = await recording; + await page.waitForTimeout(Math.max(0, wait - 400)); + const m = motion(rec, ["x"]); + return { ...await page.evaluate(() => window.__state()), settledMs: m.settledMs, between: m.between, extreme: Math.round(m.extreme) }; +} +// Input on a clock of its own (CDP's timestamps, the events' timeStamp in the page): each event `gap` ms after the one before as the +// page sees it, however late it reaches the page on a busy machine, so a quick flick stays quick and a slow drag slow (the page's +// velocities are of its events' times); a gesture starting at the time now +async function clocked(page) { + const cdp = page.__cdp || (page.__cdp = await page.context().newCDPSession(page)); + let t = Math.max(Date.now(), page.__inputT || 0); + const at = (gap) => { t += gap; page.__inputT = t; return t / 1000; }; + return { + mouse: (type, [x, y], gap, more = {}) => cdp.send("Input.dispatchMouseEvent", { type, x, y, timestamp: at(gap), ...more }), + wheel: ([x, y], deltaX, gap) => cdp.send("Input.dispatchMouseEvent", { type: "mouseWheel", x, y, deltaX, deltaY: 0, timestamp: at(gap) }), + touch: (type, points, gap) => cdp.send("Input.dispatchTouchEvent", { type, touchPoints: points.map(([x, y]) => ({ x, y })), timestamp: at(gap) }), + }; +} +async function pagerDrag(page, [x0, y], dx, { steps = 12, pause = 300 } = {}) { // a mouse drag sideways; the strip's offset midway + const input = await clocked(page), held = { button: "left", buttons: 1 }; + await input.mouse("mouseMoved", [x0, y], 0); + await input.mouse("mousePressed", [x0, y], 8, { ...held, clickCount: 1 }); + for (let i = 1; i <= steps; i++) await input.mouse("mouseMoved", [x0 + dx * i / steps, y], 8, held); // (one after another, quickly) + const during = await page.evaluate(() => window.__track()); + await page.waitForTimeout(pause); + await input.mouse("mouseReleased", [x0 + dx, y], Math.max(pause, 8), { button: "left", buttons: 0, clickCount: 1 }); + await calm(page); + return { during: Math.round(during), ...await page.evaluate(() => window.__state()) }; +} +// a trackpad's swipe: n wheel events of deltaX dx, `gap` ms apart (on the input's clock, and waited); then (no wheel event for +// WHEEL_IDLE_MS, the strip settling) at rest +async function wheelSwipe(page, n, dx, gap) { + const input = await clocked(page); + for (let i = 0; i < n; i++) { await input.wheel([800, 300], dx, i ? gap : 0); await page.waitForTimeout(gap); } + await swiped(page); +} +const swiped = async (page) => { await page.waitForTimeout(160); await calm(page); }; +const cursorAt = (page, [x, y]) => page.evaluate(([x, y]) => getComputedStyle(document.elementFromPoint(x, y)).cursor, [x, y]); + +// The zoom in nine parts, each its own page (the tests run them side by side): "in" (the cursors, a click zooming a tile, the live +// reading beside it, the keys), "pager" (zoomed: mouse drags), "wheel" (zoomed, the first: a trackpad's swipes), "last" (zoomed: the last tile, paging past it), +// "text" (zoomed, the last tile: a drag across the text, a click back out), "single" (a single tile zoomed, the keys and drags only +// bouncing), "lone" (a single tile zoomed: a trackpad's swipe bouncing, a click back, Esc back), "out" (a double-click, Esc, the +// bounce cut short), "keys" (the keyboard, Esc mid-way through a zoom-in) +async function zoomMode(browser, url, part) { + const out = {}, errors = []; + await zoomPage(browser, url, part, out, errors); + out.errors = errors; + return out; +} +async function zoomPage(browser, url, part, out, allErrors) { + const { context, page, errors } = await open(browser, url, 1024, 768, { risen: true, init: { fn: ZOOM_HELPERS } }); + await calm(page); // (at rest: drawn at their readings, risen) + out.initial = await titles(page); + out.gridRect = (await tileOf(page, "Humidity").boundingBox()); + if (part === "in") { + const textPoint = async (title, selector) => centreOf(page, tileOf(page, title).locator(selector).first()); + out.cursor = { gauge: await cursorAt(page, await at(page, "Humidity", 0.85, 0.3)), title: await cursorAt(page, await textPoint("Humidity", ".title")), + figure: await cursorAt(page, await textPoint("Humidity", ".figure")), reading: await cursorAt(page, await textPoint("Humidity", "svg text.reading")) }; + // a click on Humidity's gauge: zoomed, in 200 ms, to fill the window + out.zoomIn = await zoomClick(page, "Humidity", await at(page, "Humidity", 0.85, 0.3)); + out.zoomedCursor = { gauge: await cursorAt(page, await at(page, "Humidity", 0.85, 0.3)), margin: await cursorAt(page, [20, 384]), + title: await cursorAt(page, await textPoint("Humidity", ".title")) }; + out.grip = await page.evaluate(() => getComputedStyle(window.__tile("Humidity").querySelector(".close")).display); + out.zoomedLook = await page.evaluate(() => window.__look("Humidity")); // (its title and gauge filling the window, no table) + out.neighbourTable = await page.evaluate(() => window.__look("Temperature").table); // (the gallery's others: no table either) + // live: a new reading for Temperature, the tile beside it off the screen, reaches it in place + await page.evaluate(() => { window.__mark = window.__tile("Temperature"); }); + process.stdout.write(JSON.stringify({ label: await page.evaluate(() => window.__mark.getAttribute("aria-label")) }) + "\n"); + await new Promise((resolve) => readline.createInterface({ input: process.stdin }).once("line", resolve)); + try { await page.waitForFunction(() => /21\.5/.test(window.__mark.getAttribute("aria-label")), null, { timeout: 15000 }); } catch (e) { /* (reported) */ } + await calm(page, 1000); // (the gauge's move, MOVE_MS) + out.live = { label: await page.evaluate(() => window.__mark.getAttribute("aria-label")), sameTile: await page.evaluate(() => window.__mark === window.__tile("Temperature")), + ...await page.evaluate(() => window.__state()) }; + // the keys: ← to Temperature (now showing the new reading), ← again: the first, a bounce; Space, →, Backspace + out.keys = {}; + out.keys.left = await keyStep(page, "ArrowLeft"); + out.keys.leftReading = await page.evaluate(() => window.__mark.querySelector("svg text.reading").textContent); + out.keys.pastFirst = await keyStep(page, "ArrowLeft"); + out.keys.space = await keyStep(page, " "); + out.keys.right = await keyStep(page, "ArrowRight"); + out.keys.backspace = await keyStep(page, "Backspace"); + out.keys.url = page.url() === url; + out.keys.prevented = await page.evaluate(() => window.__keys); + } else if (part === "wheel") { + // (on a page of its own:) zoomed on Humidity, by a click on its gauge, then ← to the first; a trackpad's two-finger swipe: wheel + // deltaX, kept from the browser + await page.mouse.click(...await at(page, "Humidity", 0.85, 0.3)); + await calm(page); + await page.keyboard.press("ArrowLeft"); + await calm(page, 500); + out.wheel = { from: await page.evaluate(() => window.__state()) }; + await wheelSwipe(page, 8, 50, 16); + out.wheel.far = await page.evaluate(() => window.__state()); + await wheelSwipe(page, 6, 10, 60); // (slowly: no flick) + out.wheel.short = await page.evaluate(() => window.__state()); + await wheelSwipe(page, 8, -50, 16); + out.wheel.back = await page.evaluate(() => window.__state()); + out.wheel.prevented = await page.evaluate(() => window.__wheels); + } else if (part === "pager") { + // zoomed on Humidity, by a click on its gauge + await page.mouse.click(...await at(page, "Humidity", 0.85, 0.3)); + await calm(page); + // a mouse drag on the gauge: followed as it goes; let go past halfway: the next; a short slow one: back; a short quick one: the next + const gauge = () => at(page, "Humidity", 0.85, 0.3); + const g = await page.evaluate(() => window.__state()); + out.drag = { start: g }; + out.drag.far = await pagerDrag(page, [900, 300], -600); + out.drag.short = await pagerDrag(page, [800, 300], -100); + out.drag.flick = await pagerDrag(page, [800, 300], -120, { steps: 3, pause: 0 }); + out.drag.back = await pagerDrag(page, [200, 300], 600); + // the first tile, dragged on rightwards: it gives less and less, then springs back + await page.keyboard.press("ArrowLeft"); await page.keyboard.press("ArrowLeft"); + await calm(page, 500); + out.drag.pastFirst = await pagerDrag(page, [300, 300], 300); + } else if (part === "last" || part === "text") { + // zoomed on Humidity, by a click on its gauge + await page.mouse.click(...await at(page, "Humidity", 0.85, 0.3)); + await calm(page); + // the last tile: → past it bounces, as does a swipe on + const n = (await titles(page)).length; + for (let i = 1; i < n; i++) { await page.keyboard.press("ArrowRight"); await page.waitForTimeout(30); } // (from the second: once past the last) + await calm(page, 500); + const reached = await page.evaluate(() => window.__state()); + if (part === "last") { + out.last = { reached, pastLast: await keyStep(page, "ArrowRight") }; + await wheelSwipe(page, 8, 50, 16); + out.last.wheeled = await page.evaluate(() => window.__state()); + out.last.dragged = await pagerDrag(page, [800, 300], -400); + allErrors.push(...errors); + await context.close(); + return; + } + // (on a page of its own, beside that one, the last reached the same way:) a drag on the text selects it: no paging, still zoomed + const shown = reached.shown; + out.textOn = shown; + out.text = {}; + for (const [name, selector] of [["title", ".title"], ["reading", "svg text.reading"]]) { + const r = await tileOf(page, shown).locator(selector).first().boundingBox(), y = r.y + r.height / 2; + await mouseDrag(page, [r.x + 2, y], [r.x + r.width - 1, y + 1]); + out.text[name] = { selected: await selection(page), ...await page.evaluate(() => window.__state()) }; + } + // a click without moving on the gauge: back to the dashboard, in 200 ms, the tile in its place + out.zoomOut = await zoomClick(page, shown, await at(page, shown, 0.85, 0.3)); + out.outRect = await tileOf(page, shown).boundingBox(); + out.outTable = await page.evaluate((shown) => window.__look(shown).table, shown); // (its table back) + } else if (part === "single" || part === "lone") { + // one tile only: the zoom cursor, a click zooms it (title and gauge, no table); the keys, a drag and a trackpad's swipe only + // bounce (a gallery of one); a click goes back, Esc too + await page.evaluate((key) => localStorage.setItem(key, JSON.stringify({ order: [], hidden: [...document.querySelectorAll(".tile .title")].map((t) => t.textContent).filter((t) => t !== "Humidity") })), KEY); + await page.reload({ waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile").length === 1); + await calm(page); // (at rest: drawn at its reading, risen) + const one = await at(page, "Humidity", 0.85, 0.3); + const gridRect = await tileOf(page, "Humidity").boundingBox(); + const single = part === "single" ? (out.single = { cursor: await cursorAt(page, one), gridRect }) : (out.lone = { gridRect }); + await page.mouse.click(...one); + await calm(page); + if (part === "single") { + single.zoomed = { ...await page.evaluate(() => window.__state()), cursor: await cursorAt(page, one), + look: await page.evaluate(() => window.__look("Humidity")) }; + single.keys = { right: await keyStep(page, "ArrowRight"), left: await keyStep(page, "ArrowLeft"), space: await keyStep(page, " ") }; + single.dragged = { left: await pagerDrag(page, [800, 300], -400), right: await pagerDrag(page, [200, 300], 400) }; + allErrors.push(...errors); + await context.close(); + return; + } + // (on a page of its own, beside that one, zoomed the same way:) a trackpad's swipe; a click back; zoomed again, Esc back + await wheelSwipe(page, 8, 50, 16); + single.wheeled = { ...await page.evaluate(() => window.__state()), prevented: await page.evaluate(() => window.__wheels) }; + await page.mouse.click(...one); + await calm(page); + single.back = { ...await page.evaluate(() => window.__state()), rect: await tileOf(page, "Humidity").boundingBox() }; + await page.mouse.click(...one); + await calm(page); + await page.keyboard.press("Escape"); + await calm(page); + single.esc = await page.evaluate(() => window.__state()); + } else if (part === "out") { + // a double-click (its clicks 300 ms apart, slower than the zoom): zoomed, not zoomed and straight back out + const wind = await at(page, "Wind", 0.85, 0.3); + await page.mouse.move(...wind); + await page.mouse.down(); await page.mouse.up(); + await page.waitForTimeout(300); + await page.mouse.down({ clickCount: 2 }); await page.mouse.up({ clickCount: 2 }); + await calm(page); + // Esc: back too + out.esc = { before: await page.evaluate(() => window.__state()) }; + await page.keyboard.press("Escape"); + await calm(page); + out.esc.after = await page.evaluate(() => window.__state()); + out.esc.titles = await titles(page); + // a click on the gauge doesn't take the focus: no × once the pointer has gone + await page.mouse.move(1020, 4); + await calm(page); + out.esc.close = await page.evaluate(() => ({ focused: document.activeElement === window.__tile("Wind"), + opacity: getComputedStyle(window.__tile("Wind").querySelector(".close")).opacity })); + // the bounce at the last tile, cut short by Esc: the dashboard back in its place at once; or by a key: that step slides + const n2 = (await titles(page)).length; + await page.mouse.click(...await at(page, "Wind", 0.85, 0.3)); + await calm(page); + for (let i = 0; i < n2; i++) { await page.keyboard.press("ArrowRight"); await page.waitForTimeout(30); } + await calm(page); + // (on the animations' own timelines, not by waits around round trips to the page: the bounce held 30 ms in till the next key + // comes; the step that key starts, where it is 90-130 ms in, read as it starts) + const holdBounce = () => page.evaluate(() => addEventListener("keydown", () => { + for (const a of document.getElementById("grid").getAnimations()) if (!(a instanceof CSSTransition)) { a.pause(); a.currentTime = 30; } + }, { once: true })); + await holdBounce(); + await page.keyboard.press("ArrowRight"); // (past the last: the bounce) + await page.evaluate(() => addEventListener("keydown", () => { + const grid = document.getElementById("grid"); + getComputedStyle(grid).transform; // (its transition made now, as the next frame would) + const step = grid.getAnimations().find((a) => a instanceof CSSTransition); + window.__mid = []; + if (!step) return; + for (const t of [90, 100, 110, 120, 130]) { step.currentTime = t; window.__mid.push(Math.round(window.__track())); } + step.currentTime = 0; + }, { once: true })); + await page.keyboard.press("ArrowLeft"); + const near100 = await page.evaluate(() => window.__mid); + await calm(page); + out.bounceCut = { step: { mid: near100, ...await page.evaluate(() => window.__state()) } }; + await page.keyboard.press("ArrowRight"); await calm(page); + await holdBounce(); + await page.keyboard.press("ArrowRight"); // (the bounce again) + await page.keyboard.press("Escape"); + await page.waitForTimeout(60); + out.bounceCut.esc = await page.evaluate(() => ({ grid: getComputedStyle(document.getElementById("grid")).transform, + firstLeft: Math.round(document.querySelector("#grid .tile").getBoundingClientRect().left), + zoomed: document.body.classList.contains("zoomed") })); + await calm(page); + } else if (part === "keys") { + await page.keyboard.press("Shift"); // (the keyboard in use: a focused tile's × shown as by the keyboard) + // the keyboard: every tile takes the focus; Enter on one zooms it, the focus going along as it pages, the others out of reach; Esc + // back, the focus on the tile shown last; Space zooms too + const focusState = () => page.evaluate(() => ({ ...window.__state(), focus: document.activeElement.classList.contains("tile") ? document.activeElement.querySelector(".title").textContent : document.activeElement.tagName, + reachable: [...document.querySelectorAll("#grid .tile")].filter((t) => !t.inert).map((t) => t.querySelector(".title").textContent) })); + out.keyboard = { tabbable: await page.evaluate(() => [...document.querySelectorAll("#grid .tile")].every((t) => t.tabIndex === 0)) }; + await page.evaluate(() => window.__tile("Temperature").focus()); + await calm(page); + out.keyboard.focusedClose = await page.evaluate(() => getComputedStyle(window.__tile("Temperature").querySelector(".close")).opacity); + await page.keyboard.press("Enter"); + await calm(page); + out.keyboard.enter = await focusState(); + await page.keyboard.press("ArrowRight"); + await calm(page); + out.keyboard.right = await focusState(); + await page.keyboard.press("Tab"); + out.keyboard.tab = await focusState(); + await page.evaluate(() => window.__tile("Humidity").focus()); + await page.keyboard.press("Escape"); + await calm(page); + out.keyboard.esc = await focusState(); + await page.keyboard.press(" "); + await calm(page); + out.keyboard.space = await focusState(); + await page.keyboard.press("Escape"); + await calm(page); + // Esc 100 ms into a zoom-in: back from where the tile is drawn (no jump to the full size), its table hidden until it's in its grid place + // (never drawn large); the others keep their tables as they fade out, gone only once they're in the gallery + await calm(page); + { + const recording = page.evaluate(() => window.__record("Humidity", 700)); + // (on the zoom's own timeline, not by waits around round trips to the page: as the click is handled, its animations 30 ms in, + // the others' tables then; then 100 ms in, held there till the Esc comes, however long that takes) + await page.evaluate(() => addEventListener("click", () => { + const zoom = document.getAnimations().filter((a) => a.id === "zoom"); + for (const a of zoom) { a.pause(); a.currentTime = 30; } + window.__others = window.__look("Temperature").table; + for (const a of zoom) a.currentTime = 100; + }, { once: true })); + await page.waitForTimeout(50); + await page.mouse.click(...await at(page, "Humidity", 0.85, 0.3)); + const others = await page.evaluate(() => window.__others); + await page.waitForFunction(() => window.__drawn > window.__at); // (recorded there, drawn) + await page.keyboard.press("Escape"); + const { frames: f, at: esc } = await recording, last = f[f.length - 1], after = f.filter((x) => x.t >= esc); + out.escMid = { others, last, zoomed: await page.evaluate(() => document.body.classList.contains("zoomed")), + atEsc: f.filter((x) => x.t < esc).pop().width, peakAfter: Math.max(...after.map((x) => x.width)), + tableWhileLarge: Math.max(...after.filter((x) => x.width > last.width + 1).map((x) => x.table)), tableEnd: last.table }; + await calm(page); + } + } + allErrors.push(...errors); + await context.close(); +} + +// The zoomed view on a phone, with a finger (CDP touch events) +// In four parts (each its own page: the tests run them side by side): "back" (a tap zooming the tile, a tap straight back), "swipes" +// (the same tile zoomed by a tap, then the swipes), "later" (the same tile zoomed by a tap and two on, then a vertical swipe and a long +// press) and "return" (the same tile zoomed by a tap and two on, then three swipes back and a tap back from there). +async function zoomTouchMode(browser, url, part) { + const out = {}; + const { context, page, errors } = await open(browser, url, 390, 844, { risen: true, context: { hasTouch: true, isMobile: true }, init: { fn: () => { + window.__buzz = []; + navigator.vibrate = (ms) => { window.__buzz.push(ms); return true; }; + } } }); + await page.evaluate(ZOOM_HELPERS); + const cdp = await context.newCDPSession(page); + const touch = (type, points) => cdp.send("Input.dispatchTouchEvent", { type, touchPoints: points.map(([x, y]) => ({ x, y })) }); + const tap = async ([x, y]) => { // (then its click, and the zoom it starts or ends at rest) + const before = await page.evaluate(() => window.__at); + await touch("touchStart", [[x, y]]); await page.waitForTimeout(60); await touch("touchEnd", []); + await page.waitForFunction((before) => window.__at !== before, before, { timeout: 450 }).catch(() => {}); + await calm(page, 450); + }; + const swipe = async ([x, y], dx, { steps = 10, pause = 250, dy = 0 } = {}) => { // (on the input's clock: a flick stays quick) + const input = await clocked(page), gap = pause ? 16 : 8; + await input.touch("touchStart", [[x, y]], 0); + for (let i = 1; i <= steps; i++) { await input.touch("touchMove", [[x + dx * i / steps, y + dy * i / steps]], gap); if (pause) await page.waitForTimeout(16); } + await page.waitForTimeout(pause); + await input.touch("touchEnd", [], Math.max(pause, 8)); + await calm(page, 500); + return page.evaluate(() => window.__state()); + }; + await calm(page); // (at rest: drawn at their readings, risen) + out.initial = await titles(page); + // scrolled down a row or two: the tile at the top left tapped + const scrolled = await page.evaluate(() => { const t = document.querySelectorAll("#grid .tile")[4]; scrollTo(0, t.getBoundingClientRect().top + scrollY - 8); return scrollY; }); + await page.waitForTimeout(300); + out.scrolled = scrolled; + out.tapped = await page.evaluate(() => document.elementFromPoint(100, 150).closest(".tile").querySelector(".title").textContent); + await tap(await at(page, out.tapped, 0.85, 0.3)); + if (part === "back") { + out.zoomed = { ...await page.evaluate(() => window.__state()), rect: await tileOf(page, out.tapped).boundingBox(), + look: await page.evaluate((title) => window.__look(title), out.tapped) }; + // a tap straight back: the page scrolled where it was + await page.waitForTimeout(400); // (not a double tap) + await tap([200, 300]); + out.backStraight = { ...await page.evaluate(() => window.__state()), scrollY: await page.evaluate(() => scrollY) }; + } else if (part === "swipes") await zoomTouchSwipes(page, touch, tap, swipe, out); + else await zoomTouchLater(page, touch, tap, swipe, part, out); + out.errors = errors; + await context.close(); + return out; +} +async function zoomTouchSwipes(page, touch, tap, swipe, out) { + out.swipesTapped = out.tapped; + out.next = await swipe([300, 300], -250); + out.previous = await swipe([90, 300], 250); + out.flick = await swipe([300, 300], -80, { steps: 4, pause: 0 }); + const title = await centreOf(page, tileOf(page, out.flick.shown).locator(".title")); + out.fromTitle = await swipe([title[0] + 100, title[1]], -250); +} +async function zoomTouchLater(page, touch, tap, swipe, part, out) { + // (on a page of its own, beside that one: the same tile tapped, then two on, as there; by the keys, quicker than swipes) + out[`${part}Tapped`] = out.tapped; + for (let i = 0; i < 2; i++) { await page.keyboard.press("ArrowRight"); await calm(page, 500); } + if (part === "later") { + out.vertical = await swipe([200, 400], 10, { dy: -250 }); + // held still: nothing picked up while zoomed + await touch("touchStart", [[200, 300]]); + await page.waitForTimeout(700); + await touch("touchEnd", []); + await calm(page, 300); + out.held = { ...await page.evaluate(() => window.__state()), buzz: await page.evaluate(() => window.__buzz), + zone: await page.evaluate(() => document.getElementById("remove").classList.contains("on")) }; + return; + } + // (on a third page:) swiped back three, then a tap + out.returnFrom = await page.evaluate(() => window.__state()); + await swipe([90, 300], 250); + await swipe([90, 300], 250); + await swipe([90, 300], 250); + out.backAt = await page.evaluate(() => window.__state()); + // a tap, paged away: back to the dashboard, the tile shown last on the screen + await page.waitForTimeout(400); // (not a double tap) + await tap([200, 300]); + out.out = { ...await page.evaluate(() => window.__state()), scrollY: await page.evaluate(() => scrollY), titles: await titles(page), + lastShown: await page.evaluate((title) => { const r = window.__tile(title).getBoundingClientRect(); return r.top >= 0 && r.bottom <= innerHeight; }, out.backAt.shown) }; +} + +async function fillMode(browser, url, cases) { + const out = {}; + for (const [name, [width, height, hidden]] of Object.entries(cases)) { + const { context, page, errors } = await open(browser, url, width, height, { risen: true, init: { fn: ([key, hidden]) => { + try { localStorage.setItem(key, JSON.stringify({ order: [], hidden })); } catch (e) { /* (about:blank) */ } + }, arg: [KEY, hidden] } }); + await page.waitForTimeout(300); + out[name] = { ...await page.evaluate(() => ({ + rects: [...document.querySelectorAll("#grid .tile")].map((t) => t.getBoundingClientRect().toJSON()), + columns: document.body.dataset.columns, scroll: document.body.dataset.scroll, + scrollWidth: document.documentElement.scrollWidth })), errors }; + await context.close(); + } + process.stdout.write(JSON.stringify(out)); +} + +// ---------- a rotated screen ---------- +// What the page shows: the grid's columns and rows, the tiles' rounded rects, the weather's canvas, and the page's own fit to the screen +const shown = () => { + const el = document.documentElement, g = document.getElementById("grid"), c = document.querySelector("#sky canvas"), vv = window.visualViewport; + const round = (r) => [r.left, r.top, r.width, r.height].map(Math.round); + return { + snapshot: { columns: getComputedStyle(g).gridTemplateColumns, rows: getComputedStyle(g).gridAutoRows, bodyColumns: document.body.dataset.columns, + tiles: [...g.children].map((t) => round(t.getBoundingClientRect())), sky: [c.width, c.height, c.style.width, c.style.height] }, + fit: { scrollWidth: el.scrollWidth, clientWidth: el.clientWidth, innerWidth: window.innerWidth, scale: vv ? vv.scale : 1, scrollX: window.scrollX, + inside: [...g.children].every((t) => { const r = t.getBoundingClientRect(); return r.left >= 0 && r.right <= el.clientWidth + 0.5; }), + skyCovers: parseFloat(c.style.width) >= el.clientWidth && parseFloat(c.style.height) >= el.clientHeight } }; +}; + +async function rotateMode(browser, url) { + const out = {}; + const devices = { pixel7: [412, 839], ipadAir: [820, 1180], ipadPro13: [1032, 1376] }; + const sized = (name, landscape) => { const [w, h] = devices[name]; return landscape ? { width: h, height: w } : { width: w, height: h }; }; + const settle = async (page) => { await page.evaluate(() => new Promise((ok) => requestAnimationFrame(() => requestAnimationFrame(ok)))); await page.waitForTimeout(400); }; + for (const name of Object.keys(devices)) { + const fresh = {}, steps = [], errors = []; + for (const orientation of ["portrait", "landscape"]) { // (a fresh load of each) + const opened = await open(browser, url, 1, 1, { context: { viewport: sized(name, orientation === "landscape"), isMobile: true, hasTouch: true } }); + await settle(opened.page); + fresh[orientation] = await opened.page.evaluate(shown); + errors.push(...opened.errors); + await opened.context.close(); + } + const { context, page, errors: more } = await open(browser, url, 1, 1, { context: { viewport: sized(name, false), isMobile: true, hasTouch: true } }); + await settle(page); + for (const orientation of ["portrait", "landscape", "portrait", "landscape"]) { + const landscape = orientation === "landscape"; + await page.evaluate(() => window.dispatchEvent(new Event("orientationchange"))); + await page.setViewportSize(sized(name, landscape)); + await page.evaluate(() => window.dispatchEvent(new Event("orientationchange"))); + await settle(page); + steps.push({ orientation, now: await page.evaluate(shown) }); + } + errors.push(...more); + // Turned into landscape with the size reported late: the events come while the page still reads the portrait size (and the page + // has been shifted sideways, as a browser can), the real size arriving only some time after + const stale = {}; + await page.setViewportSize(sized(name, false)); await settle(page); + await page.evaluate(() => { window.dispatchEvent(new Event("orientationchange")); window.dispatchEvent(new Event("resize")); }); + await page.waitForTimeout(150); + await page.setViewportSize(sized(name, true)); + await page.evaluate(() => { document.body.style.overflowX = "scroll"; window.scrollTo(40, 0); document.body.style.overflowX = ""; }); + await page.waitForTimeout(1200); + stale.landscape = await page.evaluate(shown); + stale.sideways = await page.evaluate(() => window.scrollX); + // a grid wider than the screen starts at its left edge (never overflows to the unreachable left) + stale.wide = await page.evaluate(() => { const g = document.getElementById("grid"); g.style.gridTemplateColumns = "repeat(4, 600px)"; + return g.firstElementChild.getBoundingClientRect().left; }); + out[name] = { fresh, steps, errors, stale }; + await context.close(); + } + process.stdout.write(JSON.stringify(out)); +} + +// ---------- the weather behind the tiles ---------- +// The weather's own clock (window.__skyTest, see the page's loop): every frame of it exactly a 30th of a second on (0.1 s with +// `pace`: as much as a frame of the page's fast time is, Sky's longest step), however long a busy machine took to draw it, so what a +// test sees is counted in the weather's frames and time, never the machine's. `driven`: the weather makes no frames of its own; the +// test makes them (drive(), driveUntil() below), one after another as fast as they're drawn: the same frames from the same start, +// whatever the load. Its watchers go frame by frame with window.__next(f) (f called once the next frame is drawn: on a driven page +// made at once, else the page's next). +// The page with its data altered on the way: `readings` {title: value} for the tiles' readings, rain_rate as it is; the US AQI Good +// unless given (the stand-in's is Moderate) +async function weatherPage(browser, url, options = {}) { + const state = { readings: {} }; + const context = await browser.newContext({ viewport: { width: 1024, height: 768 }, deviceScaleFactor: 1, ...(options.context || {}) }); + await context.addInitScript(([pace, driven, seed]) => { // (every frame the page asks for, counted; and every fetch's data read) + window.__skyTest = { step: pace === 1 ? 1 / 30 : 0.1, driven, seed }; + const port = new MessageChannel(), queued = []; + port.port1.onmessage = () => queued.shift()(); + window.__next = driven ? (f) => { Sky.advance(1); queued.push(f); port.port2.postMessage(0); } : (f) => requestAnimationFrame(f); + window.__frames = 0; + const ask = window.requestAnimationFrame.bind(window); + window.requestAnimationFrame = (f) => { window.__frames++; return ask(pace === 1 ? f : (ts) => f(ts * pace)); }; // (its time `pace` times as fast) + window.__fetched = 0; + const get = window.fetch.bind(window); + window.fetch = async (...args) => { + const response = await get(...args), json = response.json.bind(response); + response.json = async () => { const data = await json(); window.__fetched++; return data; }; // (counted before the page renders it) + return response; + }; + }, [options.pace || 1, !!options.driven, (Number(process.env.SKY_SEED) || (options.seed ? 1115 : 0)) + (options.seed || 0)]); // (SKY_SEED: the + // weather's randomness seeded otherwise; `seed`: this page's seeded that much further on, another sample of the same weather) + if (options.init) await context.addInitScript(options.init.fn, options.init.arg); + if (options.animations) await context.route((u) => u.pathname.endsWith("/dashboard"), async (route) => { // (as served with + const response = await route.fetch(), page = await response.text(); // MCP_DASHBOARD_ANIMATIONS) + await route.fulfill({ response, body: page.replace('data-animations="on"', `data-animations="${options.animations}"`) }); + }); + if (options.bare) await context.route((u) => u.pathname.endsWith("/dashboard"), async (route) => { // (the page as it will be: + const response = await route.fetch(), page = await response.text(); // no temporary test links) + await route.fulfill({ response, body: page.replace(//, "") }); + }); + await context.route(/\/dashboard\/data$/, async (route) => { + const response = await route.fetch(), data = await response.json(); + const readings = { "AQI": 40, ...state.readings }; + for (const t of data.tiles) if (t.title in readings) t.value = readings[t.title]; + if ("rain_rate" in readings) data.rain_rate = readings.rain_rate; + if ("gust" in readings) data.gust = readings.gust; // (the gust now, km/h) + if (readings.asOf) data.as_of = { ...data.as_of, time: readings.asOf }; // (a new reading: its time) + if (readings.high) Object.assign(data.today_highs, readings.high); // (the red hands': today's highest) + for (const t of data.tiles) if (readings.scales && t.title in readings.scales) Object.assign(t, readings.scales[t.title]); // (as the server + // widens a thermometer's scale) + await route.fulfill({ response, json: data }); + }); + const page = await context.newPage(); + const errors = []; + page.on("console", (m) => { if (m.type() === "error") errors.push(m.text()); }); + page.on("pageerror", (e) => errors.push(String(e))); + await page.goto(url + (options.query || ""), { waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0 && /last reading/.test(document.getElementById("status").textContent)); + // The readings now these (fetched again: the page fetches when it's shown again) + const reads = async (readings) => { + state.readings = readings; + const fetched = await page.evaluate(() => { const n = window.__fetched; document.dispatchEvent(new Event("visibilitychange")); return n; }); + await page.waitForFunction((n) => window.__fetched > n, fetched); // (fetched and drawn) + }; + return { context, page, errors, reads }; +} +// On a driven page (weatherPage's `driven`): the script's time (the main thread's own CPU time, not the clock's: a busy machine taking +// turns doesn't count) n of the weather's frames take, ms a frame: the median of five runs of n / 5 (a run's mean: the drawing's cost; +// the median: never the run a garbage collection fell in) +async function frameCost(page, n = 60) { + const cdp = await page.context().newCDPSession(page); + await cdp.send("Performance.enable", { timeDomain: "threadTicks" }); + const script = async () => (await cdp.send("Performance.getMetrics")).metrics.find((m) => m.name === "ScriptDuration").value; + const runs = []; + for (let i = 0; i < 5; i++) { + const before = await script(); // (made in a task of the page's own: what the page's script time counts) + const made = await page.evaluate((n) => new Promise((resolve) => setTimeout(() => { const made = Sky.advance(n); setTimeout(() => resolve(made)); })), Math.ceil(n / 5)); + const after = await script(); + runs.push((after - before) * 1000 / Math.max(made, 1)); + } + await cdp.detach(); + return runs.sort((a, b) => a - b)[2]; +} +// ... n of the weather's frames now (how many made: fewer once nothing is left to draw); or frames till until(arg) holds in the page +// (at most `most`, else an error): how many +const drive = (page, n) => page.evaluate((n) => Sky.advance(n), n); +const driveUntil = (page, until, arg, most = 3000) => page.evaluate(([until, arg, most]) => { + const holds = (0, eval)(`(${until})`); + let n = 0; + while (!holds(arg) && n < most && Sky.advance(1)) n++; + if (!holds(arg)) throw new Error(`not so after ${n} frames: ${until}`); + return n; +}, [until.toString(), arg ?? null, most]); +const weatherSeen = (page) => page.evaluate(() => { + const s = Sky.state(), link = document.querySelector("#motion .animations"); + return { effects: s.effects, levels: s.levels, running: s.running, + framed: [...document.querySelectorAll("#grid .tile.alert .title")].map((t) => t.textContent), + link: link ? link.textContent : null }; +}); +// The bottom corners: "stop" (its words, its box), the test row's and its last link's boxes (null without them), the strip's; +// the row's links' words, whether its "test:" shows, whether all of it fits unscrolled, the room left right of the link; whether the +// link is clear of the strip (and of the units' switches: their box), and on the screen +const cornerSeen = (page) => page.evaluate(() => { + const box = (e) => e ? e.getBoundingClientRect().toJSON() : null, link = document.querySelector("#motion .animations"); + const row = document.getElementById("fxtest"), buttons = row ? [...row.querySelectorAll("button")] : []; + const m = box(document.getElementById("motion")), s = box(document.getElementById("status")), u = box(document.getElementById("units")), rs = box(document.getElementById("reset")); + const clear = (s) => m.right <= s.left || s.right <= m.left || m.bottom <= s.top || s.bottom <= m.top; + return { units: u, reset: rs, link: link ? link.textContent : null, motion: m, row: box(row), last: box(buttons.at(-1)), strip: s, + buttons: buttons.map((b) => b.textContent), tag: row ? !!row.querySelector(".tag") : null, // (no "test:" label any more) + fits: row ? row.scrollWidth <= row.clientWidth && row.scrollLeft === 0 : null, spare: innerWidth - m.right, + window: [innerWidth, innerHeight], apart: clear(s) && clear(u), + onScreen: m.left >= 0 && m.right <= innerWidth && m.bottom <= innerHeight }; +}); +const canvasInk = (page) => page.evaluate(() => { // how many of the canvas's pixels have anything drawn + const c = document.querySelector("#sky canvas"), d = c.getContext("2d").getImageData(0, 0, c.width, c.height).data; + let n = 0; + for (let i = 3; i < d.length; i += 4) if (d[i]) n++; + return n; +}); +const canvasLight = (page) => page.evaluate(() => { // how bright the canvas is, all told: its pixels' luminance by their alpha, averaged + const c = document.querySelector("#sky canvas"), d = c.getContext("2d").getImageData(0, 0, c.width, c.height).data; + let sum = 0; + for (let i = 0; i < d.length; i += 4) sum += (0.2126 * d[i] + 0.7152 * d[i + 1] + 0.0722 * d[i + 2]) * d[i + 3] / 255; + return sum / (d.length / 4); +}); +// The canvas's strongest regular pattern (an ordered dither's grid shows as one): in `rect` of it (power-of-two sides; the largest +// square from its top left if none), what one sees (each pixel's luminance by its alpha) less its 5x5 neighbourhood's mean (the fine +// texture only: the dithering), windowed (Hann) and through a 2D FFT; of its frequencies of wavelengths 8 px or shorter, the +// strongest's power over their median's ({ratio, at: [u, v]}). Irregular dithering: under a hundred or so; an ordered 4x4 one, thousands +const gridPeak = (page, rect) => page.evaluate((rect) => { + const c = document.querySelector("#sky canvas"), side = 1 << Math.floor(Math.log2(Math.min(c.width, c.height))); + const [X, Y, w, h] = rect || [0, 0, side, side]; + const d = c.getContext("2d").getImageData(X, Y, w, h).data, v = new Float64Array(w * h); + for (let i = 0; i < w * h; i++) v[i] = (0.2126 * d[i * 4] + 0.7152 * d[i * 4 + 1] + 0.0722 * d[i * 4 + 2]) * d[i * 4 + 3] / 255; + const re = new Float64Array(w * h), im = new Float64Array(w * h); + for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { + let sum = 0, n = 0; + for (let yy = Math.max(0, y - 2); yy <= Math.min(h - 1, y + 2); yy++) for (let xx = Math.max(0, x - 2); xx <= Math.min(w - 1, x + 2); xx++) { sum += v[yy * w + xx]; n++; } + re[y * w + x] = (v[y * w + x] - sum / n) * (0.5 - 0.5 * Math.cos(2 * Math.PI * (x + 0.5) / w)) * (0.5 - 0.5 * Math.cos(2 * Math.PI * (y + 0.5) / h)); + } + const fft = (n, off, stride) => { // (in place, radix 2) + for (let i = 1, j = 0; i < n; i++) { + let bit = n >> 1; + for (; j & bit; bit >>= 1) j ^= bit; + j ^= bit; + if (i < j) { const a = off + i * stride, b = off + j * stride; [re[a], re[b]] = [re[b], re[a]]; [im[a], im[b]] = [im[b], im[a]]; } + } + for (let len = 2; len <= n; len <<= 1) { + const wr = Math.cos(-2 * Math.PI / len), wi = Math.sin(-2 * Math.PI / len); + for (let i = 0; i < n; i += len) { + let cr = 1, ci = 0; + for (let k = 0; k < len / 2; k++) { + const a = off + (i + k) * stride, b = off + (i + k + len / 2) * stride; + const tr = re[b] * cr - im[b] * ci, ti = re[b] * ci + im[b] * cr; + re[b] = re[a] - tr; im[b] = im[a] - ti; re[a] += tr; im[a] += ti; + const nr = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = nr; + } + } + } + }; + for (let y = 0; y < h; y++) fft(w, y * w, 1); + for (let x = 0; x < w; x++) fft(h, x, w); + const powers = []; + let most = 0, at = null; + for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { + const u = Math.min(x, w - x), t = Math.min(y, h - y); + if (u < w / 8 && t < h / 8) continue; // (wavelengths over 8 px: the shapes, not their dithering) + const p = re[y * w + x] ** 2 + im[y * w + x] ** 2; + powers.push(p); + if (p > most) { most = p; at = [u, t]; } + } + powers.sort((a, b) => a - b); + return { ratio: most / Math.max(powers[powers.length >> 1], 1e-9), at }; +}, rect || null); +// How regularly the canvas's commonest colour (RGBA) sits on a 4 px grid: the share of its pixels in their 4 commonest places of the +// 16 (x mod 4, y mod 4), and how many there are (an ordered 4x4 dither's shade: near 1; irregular dithering: about 0.3) +const gridShare = (page) => page.evaluate(() => { + const c = document.querySelector("#sky canvas"), d = c.getContext("2d").getImageData(0, 0, c.width, c.height).data, by = new Map(); + for (let y = 0; y < c.height; y++) for (let x = 0; x < c.width; x++) { + const i = (y * c.width + x) * 4; + if (!d[i + 3]) continue; + const key = ((d[i] << 24) | (d[i + 1] << 16) | (d[i + 2] << 8) | d[i + 3]) >>> 0; + if (!by.has(key)) by.set(key, new Uint32Array(16)); + by.get(key)[(y & 3) * 4 + (x & 3)]++; + } + let bins = new Uint32Array(16), n = 0; + for (const b of by.values()) { const all = b.reduce((s, v) => s + v, 0); if (all > n) { n = all; bins = b; } } + return { share: [...bins].sort((a, b) => b - a).slice(0, 4).reduce((s, v) => s + v, 0) / Math.max(n, 1), n }; +}); +// The haze alone (faded in), at each band in turn, 1 to 5, once its clouds are lit in the band's shades and done fading in or out: +// the share of the canvas drawn (its cover) and its mean alpha (0-255), its strongest regular pattern (gridPeak), and each cloud's +// look as lit (on show: the mean light of its upper half and of its lower). Then on a clock 4 times as fast, the haze 5 with no wind, +// then with it (faded in): over 20 frames its motes' moves and its clouds' (each the same one, not come in again at the right), how +// many went left, right, their mean speed leftward (px/s of the weather's time); and its drift's (slide), the same +const hazeSeen = async (page) => { + const out = { levels: [] }; + for (let level = 1; level <= 5; level++) { + await page.evaluate((level) => document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { haze: level } })), level); + await driveUntil(page, (level) => { const h = Sky.state().haze; return h.level === level && !h.pending && !h.settling; }, level); + const seen = await page.evaluate(() => { + const c = document.querySelector("#sky canvas"), d = c.getContext("2d").getImageData(0, 0, c.width, c.height).data, h = Sky.state().haze; + let drawn = 0, alpha = 0; + for (let i = 3; i < d.length; i += 4) { drawn += d[i] > 0; alpha += d[i]; } + const looks = h.clouds.filter(([, , x, y, w, hh]) => x < c.width && x + w > 0 && y < c.height && y + hh > 0).map(([id]) => h.look(id)); + return { level: h.level, cover: drawn / (d.length / 4), mean: alpha / (d.length / 4), looks: looks.filter(Boolean).map((l) => [l.upper, l.lower]) }; + }); + seen.grid = (await gridPeak(page)).ratio; + out.levels.push(seen); + } + return page.evaluate(async (out) => { + const frames = (n) => new Promise((resolve) => { const end = Sky.state().frames + n; const on = () => Sky.state().frames >= end ? resolve() : __next(on); on(); }); + const fx = (detail) => document.dispatchEvent(new CustomEvent("ecobot-fx", { detail })); + Sky.timeScale(4); + const moved = (a, b, dt, key, at) => { // (at: where its x is in each entry) + const was = new Map(a[key].map((m) => [m[0], m[at]])), dx = []; + for (const m of b[key]) if (was.has(m[0])) dx.push(m[at] - was.get(m[0])); + return { n: dx.length, left: dx.filter((v) => v < 0).length, right: dx.filter((v) => v > 0).length, + speed: -dx.reduce((s, v) => s + v, 0) / Math.max(dx.length, 1) / dt }; + }; + const moves = async () => { + const a = Sky.state(); + await frames(20); + const b = Sky.state(), dt = b.clock - a.clock; + return { ...moved(a.haze, b.haze, dt, "motes", 1), clouds: moved(a.haze, b.haze, dt, "clouds", 2), slide: (b.haze.slide - a.haze.slide) / dt }; + }; + out.calm = await moves(); + fx({ haze: 5, wind: 1 }); + await frames(15); // (the wind faded in: 1.5 s of the weather's time) + out.windy = await moves(); + Sky.timeScale(1); + return out; + }, out); +}; +// The wind's leaves for `ms` of the weather's own time (Sky's clock: as much of it, however long a busy machine takes to draw it), every +// frame: their mean speed across on screen (negative: leftward), how many at most went against the wind (rightward: in a +// loop); and where each was drawn on the canvas (with the wind alone, every sprite drawn is a leaf: its middle, so a leaf turning +// over, its sprite narrower, isn't a step), frame to frame: how many steps it made leftward and how many rightward. From 45 frames in, as rainSeen (1.5 s of the weather's time: the wind faded in, under way) +const windSeen = (page, ms) => page.evaluate((ms) => new Promise((resolve) => { + const g = document.querySelector("#sky canvas").getContext("2d"), drawImage = g.drawImage, clearRect = g.clearRect, drawn = []; + const vx = []; + let against = 0, end = 0; + const begun = () => { + if (Sky.clock().frames < 45) return __next(begun); + g.clearRect = function (...args) { drawn.push([]); return clearRect.apply(this, args); }; // (a frame begins) + g.drawImage = function (...args) { if (drawn.length) drawn[drawn.length - 1].push(args[1] + args[0].width / 2); return drawImage.apply(this, args); }; + end = Sky.clock().clock + ms / 1000; + __next(step); + }; + const step = () => { + const w = Sky.state().wind; + vx.push(w.vx); + against = Math.max(against, w.against); + if (Sky.state().clock < end) return __next(step); + delete g.drawImage; delete g.clearRect; + let left = 0, right = 0; + for (let i = 1; i < drawn.length; i++) { + const [a, b] = [drawn[i - 1], drawn[i]]; + if (a.length !== b.length) continue; + for (let j = 0; j < a.length; j++) { const dx = b[j] - a[j]; if (Math.abs(dx) < 30) { if (dx < 0) left++; else if (dx > 0) right++; } } + } + const { hits, whirl } = Sky.state().wind; // (the rain's knocks on the leaves: none without it) + resolve({ vx: vx.reduce((a, b) => a + b, 0) / vx.length, against, left, right, frames: drawn.length, hits, whirl }); + }; + begun(); +}), ms); +// The rain's drops for `ms` of the weather's own time (Sky's clock: as much of it, however long a busy machine takes to draw it), a look +// every 100 ms of it: where they are across in the window's lower half, counted in columns 32 art px wide; how uneven that is +// across (each look's columns: their variance over their mean, averaged over the looks) and over time (each column's counts, look to +// look: the same, averaged over the columns); scattered evenly at random both are about 1. And the drops' mean speed across (px/s, +// negative leftward), averaged. +const rainSeen = (page, ms) => page.evaluate((ms) => new Promise((resolve) => { + const looks = [], vx = []; + let start = 0, next = 0; + const spread = (counts) => { // variance over mean + const mean = counts.reduce((a, b) => a + b, 0) / counts.length; + return mean ? counts.reduce((a, b) => a + (b - mean) ** 2, 0) / counts.length / mean : 0; + }; + const look = () => { + const clock = Sky.state().clock; + if (clock < next) return __next(look); + start = start || clock; + next = clock + 0.1 - 1e-6; + const { xs, width, vx: v } = Sky.state().rain, counts = new Array(Math.floor(width / 32)).fill(0); + for (const x of xs) if (x < counts.length * 32) counts[Math.floor(x / 32)]++; + looks.push(counts); + vx.push(v); + if (clock - start < ms / 1000) return __next(look); + const columns = looks[0].map((_, i) => looks.map((c) => c[i])); + resolve({ looks: looks.length, drops: looks.reduce((a, c) => a + c.reduce((x, y) => x + y, 0), 0) / looks.length, + across: looks.reduce((a, c) => a + spread(c), 0) / looks.length, + overTime: columns.reduce((a, c) => a + spread(c), 0) / columns.length, vx: vx.reduce((a, b) => a + b, 0) / vx.length }); + }; + // (from 50 frames in, 1.5 s or more of the page's time: the effects faded in, the wind's gusts under way) + const begun = () => Sky.clock().frames >= 50 ? look() : __next(begun); + begun(); +}), ms); +// The heat's red shafts on a driven page, with each of `levels` in turn (the effects on: {heat: its strength, 0.3 at 35 °C to 1 +// at 43 °C, and any others}), each 60 frames after it's set: Sky's heat probe (the UV's places, its shafts), the canvas's mean alpha +// (0-1) and colour (alpha-weighted) over the window's top third, and its mean alpha and colour in the top 4 rows within 2 px of each +// shown shaft's top and of each UV shaft's top (where it would be, unswayed); then, at the last level, 24 looks a second apart: each shaft's left as drawn +const heatSeen = (page, levels) => page.evaluate(async (levels) => { + const c = document.querySelector("#sky canvas"), g = c.getContext("2d"); + const looks = []; + for (const detail of levels) { + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail })); + Sky.advance(60); + const h = Sky.state().heat, W = c.width, H = c.height, d = g.getImageData(0, 0, W, H).data; + const mean = (inside) => { + let n = 0, alpha = 0, rgb = [0, 0, 0]; + for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { + if (!inside(x, y)) continue; + const i = (y * W + x) * 4, a = d[i + 3]; + n++; alpha += a / 255; + rgb[0] += d[i] * a; rgb[1] += d[i + 1] * a; rgb[2] += d[i + 2] * a; + } + return { alpha: alpha / Math.max(n, 1), colour: rgb.map((v) => Math.round(v / Math.max(alpha * 255, 1))) }; + }; + const tops = (xs) => mean((x, y) => y < 4 && xs.some((t) => Math.abs(x - t) <= 2)); + const shown = h.shafts.filter((s) => s.top !== null); + looks.push({ level: detail.heat, size: h.size, uv: h.uv, shafts: h.shafts, drawn: Sky.state().drawn.heat, + top: mean((x, y) => y < H / 3), atHeat: tops(shown.map((s) => s.top)), + atUv: tops(h.uvTops) }); + } + const moving = []; + for (let i = 0; i < 24; i++) { + Sky.advance(30); + moving.push(Sky.state().heat.shafts.map((s) => s.at)); + } + return { looks, moving, cost: Sky.state().cost }; +}, levels); +// uv's beams over 40 s of the page's time (on a page whose clock runs on fast: `pace`, below; each frame drawn 0.1 s on, Sky's +// longest step): where each beam's halo was drawn (with uv alone, the glow, then each beam's halo and core), its least and greatest x +// (art px), how many times it turned back (from going one way to the other), and how faint and bright it was +const uvSeen = (page) => page.evaluate(() => new Promise((resolve) => { + const g = document.querySelector("#sky canvas").getContext("2d"), drawImage = g.drawImage, clearRect = g.clearRect, drawn = []; + g.clearRect = function (...args) { drawn.push([]); return clearRect.apply(this, args); }; // (a frame begins) + g.drawImage = function (...args) { if (drawn.length) drawn[drawn.length - 1].push([args[1], this.globalAlpha]); return drawImage.apply(this, args); }; + const step = () => { + if (drawn.length < 400) return __next(step); + const frames = drawn.filter((f) => f.length === drawn[0].length), beams = (frames[0].length - 1) / 2; + resolve({ frames: frames.length, beams: Array.from({ length: beams }, (_, b) => { + const at = frames.map((f) => f[1 + 2 * b]); + let turns = 0, way = 0; + for (let i = 1; i < at.length; i++) { + const now = Math.sign(at[i][0] - at[i - 1][0]); + if (now && way && now !== way) turns++; + if (now) way = now; + } + return { least: Math.min(...at.map((d) => d[0])), most: Math.max(...at.map((d) => d[0])), turns, + faint: Math.min(...at.map((d) => d[1])), bright: Math.max(...at.map((d) => d[1])) }; + }) }); + }; + __next(step); +})); +// humidity's beads condensing on the glass and running down it, every frame over `frames` of Sky's (each 0.1 s of the page's time, +// its clock run on fast: `pace`; times Sky.timeScale's, if set): how many ran (moved 10 px or more); any that went up (between two +// frames, by more than nothing); the furthest one went down from where it showed; the furthest one wandered either side of where it +// showed, and how many wandered 2 px or more; their mean offset from where they began (px, negative leftward); the lowest any sprite +// reached (its bottom row + 1, of the window's height); how many ran off the bottom edge, and any seen with its top at or below that +// edge (a frame's worth: gone at once); how often a bead that had moved had its trail behind it; the most trail pixels at once; the +// beads condensed ({r as it showed, fog: the fog shown there, y: its height, of the window's}); merges ({vol: the two's water, into: +// the one's}); px run and s taken, and water gained and lost, on each glass (fog, trail, dry; the px and s of beads of r 1.8-3.2), and +// on fog by size; how many pixels showed on the fog's canvas where no trail is any more, at the end; how many beads vanished (gone +// at a radius of 1 or more, not faded, not merged into another, not run off the bottom: shrinking to nothing, a bead goes small); the +// beads at the start and at the end; any tiny bead's place changing between two frames (not snapping then: crept); every 10th +// frame, how many tiny beads (not drying away, not snapping) and the most there may be (cap); how many snaps; the tiny beads grown +// on the fog into small ones since the page opened (swelled: how many; swells: the latest, see the probe's; swell: the rate); every frame, the most pixels drawn in the canvas's top two rows, and the still beads drawn +// whole (r 2 or more, under 1 px/s, not drying): of the canvas's pixels in their sprites, the alpha (0-255) of the bead's own drawn +// there (the fog under it taken out), mean and most; the still beads (under 1 px/s) and the running ones, each's mean count; and of each bead's trail (through the fog, off another +// trail) as it passed 20 px down, a pixel of it: how many px across around it were wiped clear (crisp) as it was (its own, not +// another beside it), the bead's width as it wiped it, its fog as shown (and not wiped) then, the fog shown beside the trail (a few px either +// side of it), and at the end its fog as shown and how fresh +// A bead's trail as it looks (Sky.state().humidity h, a bead b of h.beads), its fresh rows (fresher than 0.88): on clear glass (no +// fog there), each row's streak (its own pixels shown, from a px left of the bead's sprite to a px right of it); through the fog (fog +// there, not wiped, 0.1 or more at its middle), each row's wiped pixels (its own: the fog shown under half what it'd be): how many, the first +// and the last against the sprite's left and right; each kind with 12 rows or more (a streak on clear glass 16: a thin one's mean +// width needs them): {id, kind ("clear", "fog"), w: the bead's mean +// width, widths, paused: each row where it had paused (a blob there), lefts, rights, ys, and through the fog inside: what shows inside it, see inside(), +// and soft: each row's px partly wiped (its soft edges), edges: each row's first and last wiped px, on the glass (null: none)}. +// (Put in the page as window.__trailLook, see lookable()) +const trailLook = (h, b) => { + const kinds = { clear: [], fog: [] }; + for (const r of h.trailOf(b.id)) { + if (!(r.wet > 0.88) || !r.mine) continue; // (fresh, its own: not another bead's since, over it) + const mid = 3 + ((r.w - 1) >> 1), fogs = r.fog.slice(2, r.w + 4); + if (fogs.every(([, f]) => f < 0.06)) { + kinds.clear.push({ y: r.y, w: r.w, paused: r.paused, width: r.alpha.filter((a, k) => k >= 2 && k < r.w + 4 && a > 0 && r.life[k] === r.life[mid]).length }); + } else if (r.fog[mid][1] >= 0.1) { + const wiped = r.fog.map(([s, f], k) => (f > 0 && s < 0.5 * f && r.life[k] === r.life[mid] ? k : -1)).filter((k) => k >= 0); + // (its soft edges: the px its own trail partly wiped, the fog shown there between a tenth and nine tenths of what it'd be) + const soft = r.fog.filter(([s, f], k) => f > 0 && s > 0.1 * f && s < 0.9 * f && r.life[k] === r.life[mid]).length; + kinds.fog.push({ y: r.y, w: r.w, at: r.left, width: wiped.length, soft, left: wiped.length ? wiped[0] - 3 : null, + right: wiped.length ? wiped[wiped.length - 1] - 3 - (r.w - 1) : null, + // (each px across, at x: wiped (its own), what it shows) + px: r.fog.map((_, k) => ({ x: r.left - 3 + k, wiped: wiped.includes(k), shows: r.shows[k], residue: r.residue[k] > 0 })), + shades: r.fogShades, residueShades: r.residueShades }); + } + } + // (through the fog, what shows inside the wiped streak: each patch of it (8-connected) not touching the fog beside it (not + // wiped: the soft edge, its fog partly there) and wholly within the rows looked at: {px, tall, wide, shows: what its + // pixels show, at: a pixel of it}; anything else than a fog shade shown in the wiped streak; its residue shown (px) and its px + // wiped) + const inside = (rows) => { + const byY = new Map(rows.map((r) => [r.y, new Map(r.px.map((p) => [p.x, p]))])); + const patches = [], done = new Set(), odd = []; + for (const r of rows) for (const p of r.px) if (p.wiped && p.shows > r.shades) odd.push(p.shows); + for (const r of rows) for (const p of r.px) { + if (!p.wiped || !p.shows || done.has(`${p.x},${r.y}`)) continue; + const todo = [[p.x, r.y]], got = []; + let whole = true; + done.add(`${p.x},${r.y}`); + while (todo.length) { + const [x, y] = todo.pop(); + got.push([x, y]); + for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) { + if (!dx && !dy) continue; + const q = byY.get(y + dy)?.get(x + dx); + if (!q) { whole = false; continue; } // (beyond the rows or columns looked at: can't tell) + if (!q.wiped) { whole = false; continue; } // (at the soft edge: the fog partly there, or coming back) + if (!q.shows) continue; + if (!done.has(`${x + dx},${y + dy}`)) { done.add(`${x + dx},${y + dy}`); todo.push([x + dx, y + dy]); } + } + } + if (!whole) continue; + const gx = got.map(([x]) => x), gy = got.map(([, y]) => y); + patches.push({ px: got.length, tall: Math.max(...gy) - Math.min(...gy) + 1, wide: Math.max(...gx) - Math.min(...gx) + 1, + shows: got.map(([x, y]) => byY.get(y).get(x).shows), at: got[0] }); + } + const residue = rows.reduce((n, r) => n + r.px.filter((p) => p.wiped && p.residue && p.shows).length, 0); + return { patches, odd, residue, px: rows.reduce((n, r) => n + r.px.filter((p) => p.wiped).length, 0), residueShades: rows[0].residueShades }; + }; + return Object.entries(kinds).filter(([kind, rows]) => rows.length >= (kind === "clear" ? 16 : 12)).map(([kind, rows]) => ({ + id: b.id, kind, w: rows.reduce((s, r) => s + r.w, 0) / rows.length, widths: rows.map((r) => r.width), ys: rows.map((r) => r.y), + paused: rows.map((r) => !!r.paused), lefts: rows.map((r) => r.left), rights: rows.map((r) => r.right), + ...(kind === "fog" ? { inside: inside(rows), soft: rows.map((r) => r.soft), + edges: rows.map((r) => (r.width ? [r.at + r.left, r.at + r.w - 1 + r.right] : null)) } : {}) })); +}; +// The beads followed frame by frame (window.__beadWatch(), see lookable(); each frame .step(Sky.state()), then .result()): +// stretches: each time one elongated (its stretch from 0 to more), {r: its radius then, most: its stretch at most (0-1), rows: the +// most rows its sprite was drawn taller than its own, cols: the most columns narrower, low: the most its drawn lower edge was off +// its own (px), lasted: s (the weather's) till round again (null: gone first)}, small: frames a bead under 2.5 showed elongated +// with none set going while it was 2.5 or more; +// splashes: each heavy-rain splash's droplet left on the glass {r: its radius at most, tiny: tiny always while it was one, moved: +// frames it moved (not snapping), glass: the glass under it as it last sat (before fading), fogged: s on fog, aged: s shown in +// all, fadedAt: its age as it began drying away (null: never), thrown: [dx, dy] from where its drop struck, end: "faded" (dried away), "taken" (merged into another: snapped +// or swept up by a runner), "on" (still there at the end) or "other"}; +// locks: the beads locked on another's run (lock), each {id, rows: frames it was locked in a row it could see the run under it, +// off: the most px its middle was from the run's middle there, dropped: it let go (not gone, not merged) with the run still +// under it or a few rows on (within 2 px), end: "gone" (merged or run off), "dropped", "on"} +const beadWatch = () => { + const stretching = new Map(), stretches = [], splashes = new Map(), last = new Map(), locks = new Map(); + let small = 0, clock = null; + return { + step(state) { + const h = state.humidity, t = state.clock, dt = clock === null ? 0 : t - clock, absorbed = new Set(h.absorbed), now = new Set(); + clock = t; + for (const b of h.beads) { + now.add(b.id); + if (b.lock) { + let k = locks.get(b.id); + if (!k) { k = { id: b.id, rows: 0, off: 0, dropped: false, end: "on", bottom: 0 }; locks.set(b.id, k); } + const x = Math.round(b.x), y = b.bottom, wet = (xx, yy) => h.glassAt(xx, yy) === "trail"; + if (y !== k.bottom && wet(x, y)) { + let l = x, r = x; + while (x - l < 6 && wet(l - 1, y)) l--; + while (r - x < 6 && wet(r + 1, y)) r++; + k.rows++; + if (x - l < 6 && r - x < 6) k.off = Math.max(k.off, Math.abs(b.x - (l + r) / 2)); // (a run of its own: not two joined) + } + k.bottom = y; + } + let e = stretching.get(b.id); + if (b.stretch > 0 && !b.fading) { + if (!e) { e = { r: b.r, most: 0, rows: 0, cols: 0, low: 0, from: t, lasted: null }; stretching.set(b.id, e); stretches.push(e); } + e.most = Math.max(e.most, b.stretch); + if (b.drawn && b.drawn[2] <= b.w) { // (as drawn: not its pop, a size bigger, after a merge) + const [, y, w, hh] = b.drawn; + e.rows = Math.max(e.rows, hh - (b.bottom - Math.floor(b.y))); + e.cols = Math.max(e.cols, b.w - w); + e.low = Math.max(e.low, Math.abs(y + hh - b.bottom)); + } + if (b.r < 2.5 && e.r < 2.5) small++; + } else if (e) { e.lasted = t - e.from; stretching.delete(b.id); } + if (b.kind === "splash") { + let d = splashes.get(b.id); + const before = last.get(b.id); + if (!d) { d = { id: b.id, r: b.r, tiny: true, moved: 0, glass: null, fogged: 0, aged: 0, fadedAt: null, end: "other", thrown: b.thrown }; splashes.set(b.id, d); } + d.r = Math.max(d.r, b.r); + if (!b.tiny) d.tiny = false; + if (before && b.tiny && !b.snapping && !before.snapping && (b.x !== before.x || b.y !== before.y)) d.moved++; + if (b.fading) { if (d.fadedAt === null) d.fadedAt = b.age; } + else { d.glass = b.glass; if (b.glass === "fog") d.fogged += dt; } + d.aged = b.age; + } + } + for (const [id, b] of last) { + const k = locks.get(id); + if (!k || k.end !== "on") continue; + if (!now.has(id)) k.end = "gone"; + else { + const c = h.beads.find((o) => o.id === id); + if (c.lock) continue; + k.end = "dropped"; // (looked at where it is now, the rows ahead of it: its own trail is behind) + const x = Math.round(c.x), lead = h.beads.some((o) => o.id !== id && Math.abs(o.x - x) <= c.r + o.r + 2 && o.cy - c.bottom > -1 && o.cy - c.bottom < 7); // (a bead ahead on it: its body there) + for (let dy = 0; dy <= 5; dy++) for (let dx = -2; dx <= 2; dx++) if (!lead && h.glassAt(x + dx, c.bottom + dy) === "trail") k.dropped = true; + } + } + for (const id of last.keys()) if (!now.has(id)) { + stretching.delete(id); + const d = splashes.get(id); + if (d && d.end === "other") d.end = absorbed.has(id) ? "taken" : d.fadedAt !== null ? "faded" : "other"; + } + last.clear(); + for (const b of h.beads) last.set(b.id, b); + }, + result() { + for (const id of last.keys()) { const d = splashes.get(id); if (d && d.end === "other") d.end = "on"; } + return { stretches: stretches.map(({ from, ...e }) => e), small, splashes: [...splashes.values()], locks: [...locks.values()].map(({ bottom, ...k }) => k) }; + }, + }; +}; +// The beads followed (window.__beadWatch()) for `frames` frames: what it saw, the weather's s taken, the drops landed, and the +// biggest beads' restarts after a pause and their stretches set going the while (begun) +const beadsWatched = (page, frames) => page.evaluate((frames) => new Promise((resolve) => { + const watch = window.__beadWatch(), from = Sky.state(); + let n = 0; + const step = () => { + const state = Sky.state(); + watch.step(state); + if (++n < frames) return __next(step); + const h = state.humidity, h0 = from.humidity; + resolve({ ...watch.result(), s: state.clock - from.clock, landed: h.landed - h0.landed, restarts: h.restarts - h0.restarts, + begun: h.stretches - h0.stretches }); // (begun: the stretches set going) + }; + __next(step); +}), frames); +const lookable = (page) => page.evaluate(`window.__trailLook = ${trailLook.toString()}; window.__beadWatch = ${beadWatch.toString()}`); +const humiditySeen = (page, frames) => page.evaluate((frames) => new Promise((resolve) => { + const last = new Map(), first = Sky.state().frames, count = Sky.state().particles.humidity, h0 = Sky.state().humidity; + const from = { ranOff: h0.ranOff, faded: h0.faded, shrunk: h0.shrunk, merges: h0.merges, glass: h0.glass, sizes: h0.sizes, restarts: h0.restarts, stretches: h0.stretches }; + const watch = window.__beadWatch ? window.__beadWatch() : null; + let up = 0, down = 0, wander = 0, offset = 0, samples = 0, lowest = 0, moved = 0, behind = 0, trails = 0, popped = 0, under = 0; + let top = 0, inked = 0, alphas = 0, most = 0, looked = 0, still = 0, running = 0, counts = 0, crept = 0, tinies = []; + const snaps = h0.snaps; + const ran = new Set(), wandered = new Set(), wiped = new Map(), looks = [], traced = new Set(); + const canvas = document.querySelector("#sky canvas"), g = canvas.getContext("2d"); + const step = () => { + const state = Sky.state(), h = state.humidity, now = new Map(h.beads.map((b) => [b.id, b])), absorbed = new Set(h.absorbed), left = new Set(h.left); + for (const [id, b] of last) if (!now.has(id) && !absorbed.has(id) && !left.has(id) && b.r >= 1 && b.alpha > 0.15) popped++; + if (watch) watch.step(state); + for (const b of h.beads) { + const before = last.get(b.id); + if (before && b.y < before.y - 1e-9) up++; + if (before && before.tiny && b.tiny && !before.snapping && !b.snapping && (b.x !== before.x || b.y !== before.y)) crept++; + if (b.fading) continue; + down = Math.max(down, b.y - b.y0); + if (b.y - b.y0 >= 10) ran.add(b.id); + wander = Math.max(wander, Math.abs(b.x - b.x0)); + if (Math.abs(b.x - b.x0) >= 2) wandered.add(b.id); + if (b.y - b.y0 > 5) { offset += b.x - b.x0; samples++; } + lowest = Math.max(lowest, b.bottom / h.height); + if (Math.floor(b.y) >= h.height) under++; + if (b.y - b.y0 > 10) { moved++; if (b.behind) behind++; } + if (b.y - b.y0 > 30 && !traced.has(b.id) && traced.size < 16 && window.__trailLook) { // (its trail's looks, once) + traced.add(b.id); + looks.push(...window.__trailLook(h, b)); + } + if (b.y - b.y0 > 20 && b.trail && !wiped.has(b.id) && b.glass === "fog") { + // (its own trail: wiped clear as it passed, as this pixel was, not another's close beside it, wiped at another time) + // (or a bead's since, close by, wiping it again: fresher) + const [x, y] = b.trail, own = h.wetAt(x, y); + const crisp = (x) => h.wetAt(x, y) > h.crisp && (h.lifeAt(x, y) === h.lifeAt(...b.trail) || h.wetAt(x, y) > own + 1e-6); + if (crisp(x)) { + let a = x, c = x; + while (crisp(a - 1)) a--; + while (crisp(c + 1)) c++; + const side = [a - 3, a - 2, c + 2, c + 3].map((x) => h.fogAt(x, y)[0]); + wiped.set(b.id, { across: c - a + 1, w: b.laidW, at: [x, y], shown: h.fogAt(x, y)[0], fog: h.fogAt(x, y)[1], wet: h.wetAt(x, y), + beside: side.reduce((s, v) => s + v, 0) / side.length }); + } + } + } + trails = Math.max(trails, h.trails); + if ((state.frames - first) % 10 === 0) tinies.push({ n: h.beads.filter((b) => b.tiny && !b.fading && !b.snapping).length, cap: h.cap }); + last.clear(); + for (const [id, b] of now) last.set(id, b); + { // (the canvas as drawn this frame: read back once) + const cw = canvas.width, ch = canvas.height, all = g.getImageData(0, 0, cw, ch).data; + let k = 0; + for (let i = 3; i < cw * 2 * 4; i += 4) if (all[i]) k++; + top = Math.max(top, k); + still += h.beads.filter((b) => b.v < 1).length; running += h.beads.filter((b) => b.v >= 1).length; counts++; + for (const b of h.beads) if (b.r >= 1.5 && b.v < 1 && b.alpha === 1 && b.drawn) { // (big enough to look at: fewer reach r 2 now they run from about large) + const [x0, y0, w, hh, drawn] = b.drawn; + for (let y = Math.max(0, y0); y < Math.min(ch, y0 + hh); y++) for (let x = Math.max(0, x0); x < Math.min(cw, x0 + w); x++) { + // (the bead's own alpha, the fog drawn under it taken out: the canvas's alpha over it is 1 - (1 - fog)(1 - bead)) + const under = h.shownAt(x, y)[3] / 255 * drawn, a = Math.round(255 * (1 - (1 - all[(y * cw + x) * 4 + 3] / 255) / (1 - under))); + if (a > 2) { inked++; alphas += a; most = Math.max(most, a); } + } + looked++; + } + } + if (state.frames - first < frames) return __next(step); + const glass = Object.fromEntries(Object.entries(h.glass).map(([k, o]) => [k, Object.fromEntries(Object.entries(o).map(([q, v]) => [q, v - from.glass[k][q]]))])); + resolve({ runners: ran.size, up, down, wander, meander: h.meander, wandered: wandered.size, offset: offset / Math.max(samples, 1), lowest, + ranOff: h.ranOff - from.ranOff, faded: h.faded - from.faded, shrunk: h.shrunk - from.shrunk, under, behind: behind / Math.max(moved, 1), trails, popped, count: [count, Sky.state().particles.humidity], + born: h.born.filter((b) => b.kind === "fog"), merges: h.merges - from.merges, merged: h.merged, largest: h.largest, top, + glass, sizes: h.sizes.map(([px, s], i) => [px - from.sizes[i][0], s - from.sizes[i][1]]), bands: h.bands, stray: h.stray(), + look: { beads: looked, mean: alphas / Math.max(inked, 1), most }, + showing: { still: still / Math.max(counts, 1), running: running / Math.max(counts, 1) }, + wiped: [...wiped.values()].map((t) => ({ ...t, end: { shown: h.fogAt(...t.at)[0], wet: h.wetAt(...t.at) } })), + fog: h.fog(true), first: h.first, colours: h.colours(), aged: h.beads.filter((b) => !b.fading).map((b) => b.age), + landed: h.landed, looks, crept, tinies, snaps: h.snaps - snaps, tiny: h.tiny, + restarts: h.restarts - from.restarts, stretches: h.stretches - from.stretches, watched: watch && watch.result(), + since: { restarts: h.restarts, stretches: h.stretches, big: h.big }, // (since the page opened: its beading up first too) + swelled: h.swelled, swells: h.swells, swell: h.swell }); + }; + __next(step); +}), frames); +// Tiny beads put on the glass in the fog, a clear spot (no bead within 6 px): two close (1.6 px across and 1 down: not touching, +// their edges under a px apart, within the snap) and, 20 px on, two just beyond it (2.5 px across: their edges about 1.4 px apart); +// then 6 frames: each placed one as it is (gone, or {x, y, r, vol, +// tiny}), and every bead then within 3 px of the close two's +const snapped = (page) => page.evaluate(() => { + const h0 = Sky.state().humidity, [W, H] = [h0.width, h0.height]; + let spot = null; + for (let y = Math.round(H * 0.3); y < H * 0.7 && !spot; y += 3) for (let x = 20; x < W - 40 && !spot; x += 3) { + if (h0.glassAt(x, y) !== "fog" || h0.glassAt(x + 25, y) !== "fog") continue; + if (h0.beads.every((b) => Math.hypot(b.x - x - 1, b.cy - y) > 6 && Math.hypot(b.x - x - 21, b.cy - y) > 6)) spot = [x, y]; + } + if (!spot) return { spot }; + const [x, y] = spot, placed = h0.place([{ x, y }, { x: x + 1.6, y: y + 1 }, { x: x + 20, y }, { x: x + 22.5, y }]); + const at = Sky.state().humidity.beads.filter((b) => placed.includes(b.id)).map((b) => ({ x: b.x, y: b.y, r: b.r, vol: b.vol })); + Sky.advance(6); + const h = Sky.state().humidity, byId = new Map(h.beads.map((b) => [b.id, b])); + return { spot, at, placed: placed.map((id) => { const b = byId.get(id); return b ? { x: b.x, y: b.y, r: b.r, vol: b.vol, tiny: b.tiny } : null; }), + near: h.beads.filter((b) => Math.hypot(b.x - x - 1, b.cy - y - 0.5) <= 3).map((b) => ({ id: b.id, r: b.r, vol: b.vol, tiny: b.tiny })), + snap: h.snap, tinyR: h.tiny }; +}); +// A big bead (r 4.2) and a smaller one (r 3.4), each with a tiny one a px off its edge (placed on fog, 30 px apart), then 40 frames one +// by one: for each pair, the big one's (the one left, the water of both) frames {gulp (0-1 swell), w, h (as drawn), rw, rh (its own +// sprite's), bottom (its own lower edge), low (the drawn lower edge), vol, stretch}, and the two's water before +const gulped = (page) => page.evaluate(() => { + const h0 = Sky.state().humidity, [W, H] = [h0.width, h0.height]; + let spot = null; + for (let y = 12; y < H - 30 && !spot; y += 2) for (let x = 12; x < W - 50 && !spot; x += 2) { + if (h0.beads.every((b) => Math.hypot(b.x - x - 3, b.cy - y) > 11 && Math.hypot(b.x - x - 33, b.cy - y) > 11)) spot = [x, y]; + } + if (!spot) return { spot, W, H, n: h0.beads.length }; + const [x, y] = spot, out = { spot, pairs: [] }; + for (const [i, r] of [4.2, 3.4].entries()) { + const ids = h0.place([{ x: x + 30 * i, y, r }, { x: x + 30 * i + r + 1.2, y, r: 0.55 }]); + out.pairs.push({ r, ids, before: Sky.state().humidity.beads.filter((b) => ids.includes(b.id)).map((b) => b.vol), frames: [] }); + } + for (let n = 0; n < 40; n++) { + Sky.advance(1); + const h = Sky.state().humidity, byId = new Map(h.beads.map((b) => [b.id, b])); + for (const p of out.pairs) { + const b = byId.get(p.ids[0]); + if (!b || !b.drawn) continue; + p.frames.push({ gulp: b.gulp, w: b.drawn[2], h: b.drawn[3], rw: b.w, rh: b.bottom - Math.floor(b.y), bottom: b.bottom, + low: b.drawn[1] + b.drawn[3], vol: b.vol, r: b.r, stretch: b.stretch, t: n }); + } + } + return out; +}); +// humidity off (the humidity below 90 %), every frame after till the fog has cleared and no bead is left (at most `frames`): +// the fog's mean thickness in the window's middle and at its edges as it clears (the first frame each is gone, and the edges' then); +// the slow beads (under 1 px/s) showing at the start; each slow one as it went (gone at a radius of 1 or more, not faded: popped; +// else: where it was, its distance from the middle, 0 there to 1 at the edges, and the frame); the frames taken and what was left; +// every 10th frame while it clears, the most pixels showing a trail's look on clear glass (looks: the condensed beads' trails none); +// and the glass as the fog had just cleared (cleared: its marks, the trails still listed) and at the end (end) +const humidityClears = (page, frames) => page.evaluate((frames) => new Promise((resolve) => { + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { wind: 1 } })); + const last = new Map(), gone = [], start = Sky.state().humidity.beads.filter((b) => b.v < 1).length, [W, H] = Sky.state().size; + let n = 0, popped = 0, middleGone = null, edgeGone = null, edgeThen = null, shrank = 0, looks = 0, cleared = null; + const step = () => { + const h = Sky.state().humidity, fog = h.fog(), beads = new Map(h.beads.map((b) => [b.id, b])), absorbed = new Set(h.absorbed), left = new Set(h.left); + for (const [id, b] of last) if (!beads.has(id) && !absorbed.has(id) && !left.has(id)) { + if (b.r >= 1 && b.alpha > 0.15) popped++; + if (b.v < 1) gone.push({ far: Math.max(Math.abs(2 * b.x / W - 1), Math.abs(2 * b.cy / H - 1)), frame: n }); + } + for (const [id, b] of beads) if (last.has(id) && b.r < last.get(id).r - 1e-9) shrank++; + last.clear(); + for (const [id, b] of beads) last.set(id, b); + if (middleGone === null && fog.middle < 0.005) { middleGone = n; edgeThen = fog.edge; } + if (edgeGone === null && fog.edge < 0.005) edgeGone = n; + if (n % 10 === 0 && fog.cover > 0) looks = Math.max(looks, h.marks().looks); + if (!cleared && fog.cover === 0) cleared = h.marks(); + n++; + if (n < frames && (fog.cover > 0 || beads.size)) return __next(step); + resolve({ start, middleGone, edgeGone, edgeThen, gone, popped, shrank, frames: n, left: { cover: fog.cover, thickness: fog.thickness, + beads: beads.size }, effects: Sky.state().effects, looks, cleared, end: h.marks() }); + }; + __next(step); +}), frames); +// The trails as their time runs on fast (Sky.state().humidity.hasten(k): k times as fast; each frame 0.1 s of the page's): up to +// `most` trail pixels, each of a trail of its own (on clear glass, fresh still, on its streak as shown, a few px apart down it; or through the fog, `through`, +// still crisp, inside it, in the middle of its row there: its own on either side), each followed till it's gone (fogged over again +// all the way, or dry) or a bead wipes it afresh (dropped): how fresh it was at the start, how long it lasted all told, on the trails' clock (from how fresh it was), +// how long it stayed crisp (no fog shown) from the start, how long it showed at all (hidden: shown nothing from then on, as a fraction +// of how long it lasted from the start), and at the end its fog shown against the fog not wiped there; and its look at the start +// ([r, g, b, alpha] on the fog's canvas) +const trailsAge = (page, k, through, most) => page.evaluate(([k, through, most]) => new Promise((resolve) => { + const h0 = Sky.state().humidity, [W, H] = Sky.state().size, picked = []; + for (let y = 4; y < H && picked.length < most; y += 1) for (let x0 = 2; x0 < W && picked.length < most; x0 += 1) { + // (through the fog: the middle of the trail's row there, not the first of it met from the left, a px in from its edge: like + // with like, wherever the trail is) + let x = x0; + if (through && h0.lifeAt(x0, y) > 0) { + let a = x0, c = x0; + while (h0.lifeAt(a - 1, y) === h0.lifeAt(x0, y)) a--; + while (h0.lifeAt(c + 1, y) === h0.lifeAt(x0, y)) c++; + x = (a + c) >> 1; + } + const wet = h0.wetAt(x, y), fog = h0.fogAt(x, y)[1], life = h0.lifeAt(x, y); + // (through the fog: inside the trail, its own on either side; on clear glass: on its streak, shown) + const inside = through ? [x - 1, x + 1].every((x) => h0.lifeAt(x, y) === life) : h0.shownAt(x, y)[3] > 0; + if (wet > (through ? h0.crisp + 0.03 : 0.3) && (through ? fog > 0.1 : fog === 0) && inside && + !picked.some((p) => Math.abs(p.life - life) < 1 && (through || Math.abs(p.at[1] - y) < 4))) { // (on clear glass: a few down a streak) + picked.push({ at: [x, y], wet, life, start: h0.clock(), last: wet, look: h0.shownAt(x, y), crispTill: null, shownTill: 0 }); + } + } + h0.hasten(k); + let n = 0; + const step = () => { + const h = Sky.state().humidity, t = h.clock(); + for (const p of picked) if (!p.done && !p.dropped) { + const wet = h.wetAt(...p.at); + if (wet > p.last + 1e-6) { p.dropped = true; continue; } + p.last = wet; + if (p.crispTill === null && h.fogAt(...p.at)[0] > 0) p.crispTill = t - p.start; + if (h.shownAt(...p.at)[3] > 0) p.shownTill = t - p.start; + if (wet <= 0) { p.done = true; p.lasted = (t - p.start) / p.wet; p.fog = h.fogAt(...p.at); p.hidden = p.shownTill / (t - p.start); } + } + n++; + if (n < 400 && picked.some((p) => !p.done && !p.dropped)) return __next(step); + h.hasten(1); + resolve(picked.filter((p) => p.done).map((p) => ({ lasted: p.lasted, crispTill: p.crispTill, wet: p.wet, fog: p.fog, look: p.look, + hidden: p.hidden }))); + }; + __next(step); +}), [k, through, most]); +// Heavy rain's beads: light rain first, `light` frames (none sticking), then heavy, `heavy` frames: the drops that stuck (each as it +// first showed: its radius, its alpha, its splash's droplets), the most on the glass at once, the beads' water gained and lost on each +// glass and their px run and s taken there (r 1.8-3.2), any bead vanishing (as humiditySeen), the trails at the end; then (`after` +// frames, the weather's time `scale` times as fast; unless `phase` "heavy": from there, once one is on the glass (the drops landing +// at their own pace, the beads outside the shared budget: those there may all have run off or shrunk away already; the trails' +// clock held the while, so they're no older for it)) the rain light again: no new one sticking, and those there run off or +// shrunk away +const rainBeads = (page, light, heavy, after, scale, from = "light") => page.evaluate(([light, heavy, after, scale, from]) => new Promise((resolve) => { + const out = { stuck: [], looks: [] }, seenIds = new Set(), last = new Map(), looked = new Map(), h0 = Sky.state().humidity; + const watch = window.__beadWatch ? window.__beadWatch() : null, counts = { restarts: h0.restarts, stretches: h0.stretches }; + let n = 0, phase = from, popped = 0, start = Sky.state().frames; + const end = () => { // (the beads followed, and the biggest's restarts after a pause and their stretches the while) + const h = Sky.state().humidity; + return { watched: watch && watch.result(), restarts: h.restarts - counts.restarts, stretches: h.stretches - counts.stretches }; + }; + const step = () => { + const state = Sky.state(), h = state.humidity, absorbed = new Set(h.absorbed), left = new Set(h.left), now = new Map(h.beads.map((b) => [b.id, b])); + for (const [id, b] of last) if (!now.has(id) && !absorbed.has(id) && !left.has(id) && b.r >= 1 && b.alpha > 0.15) popped++; + if (watch) watch.step(state); + last.clear(); + for (const b of h.beads) { + last.set(b.id, b); + // (its trail's looks: once it has run 20 px, and again each 40 px further on (its latest rows, up to 80): all its trail, as far + // as it runs, looked at) + if (b.kind === "rain" && b.y - b.y0 > 20 && b.y - (looked.has(b.id) ? looked.get(b.id) : -Infinity) >= 40 && window.__trailLook) { + looked.set(b.id, b.y); + out.looks.push(...window.__trailLook(h, b)); + } + if (b.kind === "rain" && !seenIds.has(b.id)) { + seenIds.add(b.id); + const s = h.splashes.find((s) => s.id === b.id); + out.stuck.push({ r: s ? s.r : 0, alpha: b.alpha, dots: s ? s.dots : 0, stay: s ? s.stay : 0, meant: s ? s.meant : 0, cut: s ? s.cut : 0, + off: s ? s.off : 0, room: s ? s.room : 0, squash: s ? s.squash : 0, thrown: s ? s.thrown : [], phase }); // (r: as it landed) + } + } + for (const s of h.splashes) if (!seenIds.has(s.id) && absorbed.has(s.id)) { // (one landing on a bead there, merged at once: never + seenIds.add(s.id); // shown on its own) + out.stuck.push({ r: s.r, alpha: null, dots: s.dots, stay: s.stay, meant: s.meant, cut: s.cut, off: s.off, room: s.room, squash: s.squash, + thrown: s.thrown, phase, merged: true }); + } + n = state.frames - start; + if (phase === "light" && n >= light) { + out.light = { landed: h.landed, levels: state.levels.rain }; + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { rain: 1 } })); + phase = "heavy"; start = state.frames; + } else if (phase === "heavy" && n >= heavy && from === "heavy" && !h.beads.some((b) => b.kind === "rain") && n < 900) { + h.hasten(0); // (waiting for one to land: the trails' clock held) + } else if (phase === "heavy" && n >= heavy) { + h.hasten(1); + out.heavy = { landed: h.landed, rainMost: h.rainMost, glass: h.glass, trails: h.trails, beads: h.beads.length, popped }; + if (!after) return resolve({ ...out, ...end() }); + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { rain: 0.35 } })); + Sky.timeScale(scale); + out.eased = { landed: h.landed, beads: h.beads.length, ranOff: h.ranOff, shrunk: h.shrunk, faded: h.faded }; + phase = "after"; start = state.frames; + } else if (phase === "after" && (n >= after || !h.beads.length)) { + Sky.timeScale(1); + out.after = { landed: h.landed, beads: h.beads.length, frames: n, ranOff: h.ranOff, shrunk: h.shrunk, faded: h.faded, popped }; + return resolve({ ...out, ...end() }); + } + __next(step); + }; + __next(step); +}), [light, heavy, after, scale, from]); +// Heavy rain's drops landing, each followed frame by frame (the weather's time a 30th of a second a frame) from the frame it landed +// in till 0.35 s on: `landings` of them (up to `most` frames): each {id, frames: [{impact: s since it landed, squash, w, h: as drawn, +// rw, rh: its round sprite's, r, vol, stretch: elongated as it sets off (see beadWatch)}]} (till it merges or goes) +const landingsWatched = (page, landings, most) => page.evaluate(([landings, most]) => new Promise((resolve) => { + const followed = new Map(), done = []; + let n = 0; + Sky.timeScale(1 / 3); + const step = () => { + const h = Sky.state().humidity; + for (const b of h.beads) if (b.kind === "rain" && b.impact !== null && b.impact <= 0.35 && b.drawn) { + if (!followed.has(b.id)) { if (b.impact > 0 || followed.size + done.length >= landings) continue; followed.set(b.id, { id: b.id, frames: [] }); } + followed.get(b.id).frames.push({ impact: b.impact, squash: b.squash, w: b.drawn[2], h: b.drawn[3], rw: b.w, rh: b.bottom - Math.floor(b.y), r: b.r, vol: b.vol, + stretch: b.stretch }); + } + for (const [id, f] of followed) if (f.frames.at(-1).impact >= 0.33 || !h.beads.some((b) => b.id === id)) { done.push(f); followed.delete(id); } + if ((done.length < landings || followed.size) && ++n < most) return __next(step); + Sky.timeScale(1); + resolve(done); + }; + __next(step); +}), [landings, most]); +// "stop" (an effect on: the link shows; it ends the test links' effects; the link gone), then `detail` on (as a test link +// clicked after it: the animations on again), all at once (no frame between): the loop, the link and the glass (humidity's marks) as +// stopped, and once started again, the glass, the frost and the rain's drops then +const restarted = (page, detail) => page.evaluate((detail) => { + const linkNow = () => { const a = document.querySelector("#motion .animations"); return a ? a.textContent : null; }, seen = {}; + seen.link = linkNow(); + document.querySelector("#motion .animations").click(); + seen.stopped = { running: Sky.state().running, link: linkNow(), marks: Sky.state().humidity.marks() }; + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail })); + seen.again = { running: Sky.state().running, link: linkNow() }; + const f = Sky.frost(); + return { ...seen, marks: Sky.state().humidity.marks(), stray: Sky.state().humidity.stray(), drops: Sky.state().particles.rain, + frost: f && { extent: f.extent, ink: f.ink, sparkles: f.sparkles }, effects: Sky.state().effects }; +}, detail); +const framesIn = async (page, ms) => { // the frames the page asked for in this long + const before = await page.evaluate(() => window.__frames); + await page.waitForTimeout(ms); + return (await page.evaluate(() => window.__frames)) - before; +}; + +// MCP_DASHBOARD_ANIMATIONS off (the page as ecobot-mcp serves it then: data-animations="off" on its ): every effect asked for +// and called for, nothing drawn; the rest as ever +async function animationsOff(browser, url, out) { + const { context, page, errors, reads } = await weatherPage(browser, url, { query: "?fx=all,gust", animations: "off" }); + await reads({ "UV index": 11, Wind: 60, Temperature: -3, rain_rate: 2, Humidity: 97, "AQI": 160, gust: 130 }); + const seen = async () => ({ ...await weatherSeen(page), frames: await page.evaluate(() => Sky.state().frames), ink: await canvasInk(page), + gust: await page.evaluate(() => Sky.state().gust.sent), // (a gust over 99 km/h, and ?fx=gust: none sent) + ...await page.evaluate(() => ({ sky: getComputedStyle(document.getElementById("sky")).display, + corner: getComputedStyle(document.getElementById("corner")).display, + row: !!document.getElementById("fxtest") && document.getElementById("fxtest").checkVisibility() })) }); + await page.waitForTimeout(500); // (time for frames, were any drawn) + out.off = await seen(); + out.tiles = await titles(page); + out.strip = await statusText(page); + await page.mouse.move(...await at(page, "Rain", 0.5, 0.4)); + await calm(page); + await tileOf(page, "Rain").locator(".close").click(); + await page.waitForTimeout(300); + const { frames, ink, running } = await seen(); + out.hidden = { strip: await statusText(page), frames, ink, running }; + out.errors = errors; + await context.close(); +} + +// MCP_DASHBOARD_ANIMATIONS on, low and off (the page as ecobot-mcp serves it with each: data-animations on its ), and a browser +// asking for reduced motion (served with on): each its own page, side by side. In each, what moves: a gauge's new reading (its reading's +// text as it goes: every value it shows, in order: swept, or straight there), the weather called for (every effect, a gust over 99 km/h +// and the test link's: drawn, its loop, or nothing at all: no canvas shown, no frame, no ink, nothing blown across), "stop" and the test +// links (shown or not), a zoom and the gallery's step (animated, or at once), and a tile hidden (the others gliding to their places, or +// at once) +const MOTIONS = { on: { animations: "on" }, low: { animations: "low" }, off: { animations: "off" }, + reduced: { animations: "on", context: { reducedMotion: "reduce" } } }; +async function motionSeen(browser, url, options) { + const { context, page, errors, reads } = await weatherPage(browser, url, options); + await calm(page, 5000); // (the gauges' rise, where they rise) + const out = {}; + // a new reading: Humidity's reading's text, every value it shows from now (a MutationObserver: each change, however quick) + await page.evaluate(() => { + const t = [...document.querySelectorAll(".tile")].find((e) => e.querySelector(".title").textContent === "Humidity"); + const reading = () => t.querySelector("svg text.reading").textContent; + window.__shown = []; + new MutationObserver(() => { const r = reading(); if (window.__shown.at(-1) !== r) window.__shown.push(r); }) + .observe(t, { subtree: true, attributes: true, childList: true, characterData: true }); + }); + await reads({ "UV index": 11, Wind: 60, Temperature: -3, rain_rate: 2, Humidity: 97, "AQI": 160, gust: 130 }); + await page.waitForTimeout(1500); // (the sweep over: MOVE_MS; and time for the weather's frames, were any drawn) + out.gauge = await page.evaluate(() => window.__shown); + await page.evaluate(() => { // (the test link's gust, and the page's own event for it) + document.dispatchEvent(new Event("ecobot-gust")); + const b = document.querySelector("#fxtest button[data-gust]"); + if (b && b.checkVisibility()) b.click(); + }); + out.weather = { ...await weatherSeen(page), frames: await page.evaluate(() => Sky.state().frames), ink: await canvasInk(page), + gust: await page.evaluate(() => Sky.state().gust.sent), + ...await page.evaluate(() => ({ sky: getComputedStyle(document.getElementById("sky")).display, + corner: getComputedStyle(document.getElementById("corner")).display, + shownLink: !!document.querySelector("#motion .animations") && document.querySelector("#motion .animations").checkVisibility(), + row: document.getElementById("fxtest").checkVisibility() })) }; + // zoomed (a click on Humidity), a step to the next (→), back (Esc): the zoom's animations running just after, #grid's transition + const zoomAnimations = () => page.evaluate(() => document.getAnimations().filter((a) => a.id === "zoom" && a.playState === "running").length); + await page.mouse.click(...await at(page, "Humidity", 0.5, 0.4)); + out.zoomed = { zoomed: await page.evaluate(() => document.body.classList.contains("zoomed")), animations: await zoomAnimations() }; + await calm(page); + await page.keyboard.press("ArrowRight"); + out.paged = { transition: await page.evaluate(() => getComputedStyle(document.getElementById("grid")).transitionDuration) }; + await calm(page); + await page.keyboard.press("Escape"); + out.back = { zoomed: await page.evaluate(() => document.body.classList.contains("zoomed")), animations: await zoomAnimations() }; + await calm(page); + // Rain hidden (its ×): the next frame, the tiles still on their way to their places (a transform), and the transform transitions running + out.hidden = await page.evaluate(() => new Promise((resolve) => { + const t = [...document.querySelectorAll(".tile")].find((e) => e.querySelector(".title").textContent === "Rain"); + t.querySelector(".close").click(); + requestAnimationFrame(() => resolve({ + moved: [...document.querySelectorAll(".tile")].filter((b) => getComputedStyle(b).transform !== "none").length, + gliding: document.getAnimations().filter((a) => a.transitionProperty === "transform" && a.playState === "running").length, + tiles: document.querySelectorAll(".tile").length })); + })); + out.errors = errors; + await context.close(); + return out; +} + +// The weather in parts, each its own page (and process: the tests run them side by side): "marks" (nothing called for, each effect at +// its mark and just short of it, haze's bands, rain's strength, the ice's depth), "several" (several at once, the canvas, the tiles see- +// through, their look, zoomed), "stop" ("stop", the readings, a reload, a test link after it, the reset), "links" (the temporary test links; +// and beside them, MCP_DASHBOARD_ANIMATIONS off: nothing drawn), "motion" (MCP_DASHBOARD_ANIMATIONS on, low and off, and reduced +// motion: what moves in each), +// "haze" (Hazardous haze alone), "trails" (heavy humidity alone: its cost as the trails build up), "frost" (the ice grown all the way in: +// its cost), "budget" (heavy rain, wind and haze: the shared particle budget), "opened" (?fx= when the page opens, uv +// and the wind alone, heavy rain alone and in the wind (on a phone too), uv's beams over 40 s, humidity's beads running down the +// glass alone and in the wind, a phone's strip), "flood" (a flash flood: its mark, its rise, its surface and waves, +// what ends at it, the test link's rain3, its leaves and its frog, its cost), "gust" (something big blown across in a gust over 99 km/h), +// "tilt" (a phone's gravity: the humidity's beads running downhill, by synthetic devicemotion at screen angles) +const WEATHER = { + async marks(browser, url, out) { + const { context, page, errors, reads } = await weatherPage(browser, url); + await calm(page, 5000); // (the gauges' rise) + out.nothing = { ...await weatherSeen(page), frames: await framesIn(page, 800), ink: await canvasInk(page) }; + // each mark: just short of it, then at it + const marks = { rain: [{ rain_rate: 0 }, { rain_rate: 0.1 }], haze: [{ "AQI": 50 }, { "AQI": 51 }], + uv: [{ "UV index": 10.9 }, { "UV index": 11 }], humidity: [{ Humidity: 89.9 }, { Humidity: 90 }], + wind: [{ Wind: 15 }, { Wind: 15.1 }], heat: [{ Temperature: 34.9 }, { Temperature: 35 }], + ice: [{ Temperature: 0.1 }, { Temperature: -0.1 }], iceAtZero: [{ Temperature: 0 }, { Temperature: -0.1 }] }; + out.marks = {}; + for (const [name, [below, at]] of Object.entries(marks)) { + await reads(below); + const short = await weatherSeen(page); + await reads(at); + out.marks[name] = { below: short, at: await weatherSeen(page) }; + } + out.hazeBands = []; + for (const aqi of [101, 151, 201, 301, 500]) { await reads({ "AQI": aqi }); out.hazeBands.push((await weatherSeen(page)).levels.haze); } + out.rainStrength = []; + for (const rate of [0.5, 8, 20]) { await reads({ rain_rate: rate }); out.rainStrength.push((await weatherSeen(page)).levels.rain); } + out.humidityStrength = []; + for (const rh of [91, 95, 100]) { await reads({ Humidity: rh }); out.humidityStrength.push((await weatherSeen(page)).levels.humidity); } + out.heatStrength = []; + for (const t of [35, 39, 43, 48]) { await reads({ Temperature: t }); out.heatStrength.push((await weatherSeen(page)).levels.heat); } + out.iceDepth = []; + for (const t of [-0.5, -5]) { await reads({ Temperature: t }); out.iceDepth.push((await weatherSeen(page)).levels.ice); } + // in °F, mph, inHg and in (the switches): the marks the same, of the readings in °C, km/h and mm/h (the rain above 0, heavy from + // 8 mm/h, the flood above 30 mm/h); the thermometer's scale widened as in °C + for (const unit of ["°F", "mph", "inHg", "in"]) await page.click(`#units button[data-unit='${unit}']`); + out.unitsRain = []; + for (const rate of [0.5, 8, 30, 30.1]) { + await reads({ rain_rate: rate }); + const { levels } = await weatherSeen(page); + out.unitsRain.push([levels.rain, levels.flood]); + } + out.unitsMarks = {}; + for (const name of ["heat", "wind", "ice", "rain"]) { + const [below, at] = marks[name]; + await reads(below); + const short = await weatherSeen(page); + await reads(at); + out.unitsMarks[name] = { below: short, at: await weatherSeen(page) }; + } + const temperature = () => page.evaluate(() => { + const t = [...document.querySelectorAll("#grid .tile")].find((e) => e.querySelector(".title").textContent === "Temperature"); + return [t.getAttribute("aria-label"), [...t.querySelectorAll("svg text:not(.reading)")].map((e) => e.textContent)]; + }); + const widened = (low, high) => ({ low, high, ticks: Array.from({ length: (high - low) / 10 + 1 }, (_, i) => high - 10 * i), + colours: Array((high - low) / 10).fill("#888888") }); + await reads({ Temperature: -5, scales: { Temperature: widened(-10, 40) } }); + out.widened = await temperature(); + await reads({ Temperature: 43, scales: { Temperature: widened(0, 50) } }); + out.widenedHot = await temperature(); + out.errors = errors; + await context.close(); + }, + async several(browser, url, out) { + const { context, page, errors, reads } = await weatherPage(browser, url); + await calm(page, 5000); // (the gauges' rise) + // several at once: one canvas, one loop (at most 30 frames a second) + await reads({ "UV index": 11, Wind: 60, Temperature: -3, rain_rate: 2, Humidity: 97, "AQI": 160 }); + await calm(page, 5000); // (the gauges' move to their new readings, MOVE_MS: frames of their own) + // (the frames asked for and drawn in a second, counted in the page: by its own clock, so no round trip's delay counts) + const rate = await page.evaluate(() => new Promise((resolve) => { + const asked = window.__frames, drawn = Sky.state().frames, start = performance.now(); + setTimeout(() => { + const per = 1000 / (performance.now() - start); + resolve({ frames: (window.__frames - asked) * per, drawn: (Sky.state().frames - drawn) * per }); + }, 1000); + })); + out.several = { ...await weatherSeen(page), canvases: await page.evaluate(() => document.querySelectorAll("canvas").length), + ...rate, ink: await canvasInk(page) }; + // the canvas: the window's size, fixed, first in the page, behind the tiles (which come after it), clicks through it. (Behind: its + // pointer-events on for a moment, so hit-testing sees it, a tile's middle is still the tile's) + out.canvas = await page.evaluate(() => { + const sky = document.getElementById("sky"), c = sky.querySelector("canvas"), r = sky.getBoundingClientRect(), cr = c.getBoundingClientRect(); + const st = getComputedStyle(sky); + return { rect: [r.left, r.top, r.width, r.height], canvas: [cr.width >= innerWidth, cr.height >= innerHeight], + position: st.position, z: st.zIndex, events: st.pointerEvents, first: document.body.firstElementChild === sky, + pixelated: getComputedStyle(c).imageRendering, + under: (() => { + const r = [...document.querySelectorAll("#grid .tile")][3].getBoundingClientRect(); + sky.style.pointerEvents = "auto"; + const hit = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); + sky.style.pointerEvents = ""; + return hit !== null && hit.closest(".tile") !== null; + })() }; + }); + // the tiles see-through: a tile's blank margin shows what's drawn behind it (haze, Hazardous, over the bottom row) + await reads({ "AQI": 500 }); + await page.waitForTimeout(1800); + const margin = async () => { + const r = await tileOf(page, "PM10").boundingBox(); + return page.screenshot({ clip: { x: r.x + r.width * 0.04, y: r.y + r.height * 0.45, width: r.width * 0.12, height: r.height * 0.15 } }); + }; + const hazegy = await margin(); + await reads({}); + await page.waitForFunction(() => !Sky.state().running); // (faded out: the loop ended) + await calm(page); + const clear1 = await margin(), clear2 = await margin(); + out.through = { differs: !hazegy.equals(clear1), still: clear1.equals(clear2) }; + out.look = await page.evaluate(() => { + const tile = document.querySelector(".tile"), before = getComputedStyle(tile, "::before"); + return { background: getComputedStyle(tile).backgroundColor, opacity: getComputedStyle(tile).opacity, + title: getComputedStyle(tile.querySelector(".title")).color, frame: before.borderTopColor }; + }); + await reads({ "UV index": 11 }); + out.look.alertFrame = await page.evaluate(() => getComputedStyle(document.querySelector(".tile.alert"), "::before").borderTopColor); + out.look.dragFrames = await page.evaluate(() => { // a framed tile dragged: lifted, then over the remove zone, its frame as any other's + const tile = document.querySelector(".tile.alert"), frame = () => getComputedStyle(tile, "::before").borderTopColor; + tile.classList.add("lifted"); + const lifted = frame(); + tile.classList.add("doomed"); + const doomed = frame(); + tile.classList.remove("lifted", "doomed"); + return { lifted, doomed, after: frame() }; + }); + // zoomed: the tile still see-through, its frame still red, the effect still behind it + const [zx, zy] = await at(page, "UV index", 0.85, 0.3); + await page.mouse.click(zx, zy); + await calm(page); + out.zoomed = await page.evaluate(() => { + const shown = [...document.querySelectorAll("#grid .tile")].find((t) => !t.inert); + return { zoomed: document.body.classList.contains("zoomed"), title: shown.querySelector(".title").textContent, + background: getComputedStyle(shown).backgroundColor, grid: getComputedStyle(document.getElementById("grid")).backgroundColor, + alert: shown.classList.contains("alert"), running: Sky.state().running }; + }); + out.errors = errors; + await context.close(); + }, + async stop(browser, url, out) { + const { context, page, errors, reads } = await weatherPage(browser, url); + await calm(page, 5000); // (the gauges' rise) + await reads({ "UV index": 11 }); + await calm(page, 5000); // (the gauge's move: frames of its own) + // "stop" (a test link's effect on too): nothing drawn, no loop, the test link's effect ended, the frames stay, the link + // gone (no "start animation"), nothing saved + await page.locator("#fxtest button[data-fx='wind']").click(); + out.simulating = { ...await weatherSeen(page), ...await page.evaluate(() => { const a = document.querySelector("#motion .animations"); return { title: a.title, label: a.getAttribute("aria-label") }; }) }; + await page.locator("#motion .animations").click(); + await page.waitForTimeout(200); + out.stopped = { ...await weatherSeen(page), frames: await framesIn(page, 600), ink: await canvasInk(page), stored: await stored(page), + url: await page.evaluate(() => location.search), + pressed: await page.evaluate(() => document.querySelectorAll("#fxtest button.on").length) }; + // the readings calling for more (wind too) and a tile hidden and "reset preferences": still stopped (the reset not about them) + await reads({ "UV index": 11, Wind: 20 }); + await calm(page, 5000); + await page.mouse.move(...await at(page, "Rain", 0.5, 0.4)); + await calm(page); + await tileOf(page, "Rain").locator(".close").click(); + await calm(page); + await page.getByText("reset preferences").click(); + await page.waitForTimeout(100); + out.reset = { ...await weatherSeen(page), frames: await framesIn(page, 500), ink: await canvasInk(page) }; + // a reload (an earlier version's saved {animations: false} kept beside the arrangement): running as normal, that value dropped + await page.evaluate((key) => localStorage.setItem(key, JSON.stringify({ order: [], hidden: ["Rain"], animations: false })), KEY); + await page.reload({ waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile.alert").length > 0); + await calm(page, 5000); // (the gauges' rise) + out.reloaded = { ...await weatherSeen(page), frames: await framesIn(page, 500), stored: JSON.parse(await stored(page)) }; + // stopped again, then a test link: the animations on again, its effect and the readings' with it, the link back + await page.locator("#motion .animations").click(); + await page.waitForFunction(() => !document.querySelector("#motion .animations")); + await page.locator("#fxtest button[data-fx='heat']").click(); + await page.waitForTimeout(100); + out.resumed = { ...await weatherSeen(page), frames: await framesIn(page, 500), url: await page.evaluate(() => location.search) }; + // from the keyboard: Enter on the link stops them; the link gone, the focus with it (not left on a removed element) + await page.focus("#motion .animations"); + await page.keyboard.press("Enter"); + out.keyboard = { ...await weatherSeen(page), focused: await page.evaluate(() => document.activeElement.tagName) }; + out.errors = errors; + await context.close(); + }, + async links(browser, url, out) { + const off = animationsOff(browser, url, out.off = {}); // (beside the rest) + // phones (360x740, 390x844), every effect on (their links' longest): the row without "test:", all of it and "stop" in + // sight, unscrolled (beside the rest, as the off page) + const phones = Promise.all([[360, 740], [390, 844]].map(async ([width, height]) => { + const p = await weatherPage(browser, url, { query: "?fx=all", driven: true, context: { viewport: { width, height }, hasTouch: true, isMobile: true } }); + const seen = { ...await cornerSeen(p.page), labels: await p.page.evaluate(() => [...document.querySelectorAll("#fxtest button")] + .map((b) => b.getAttribute("aria-label"))), errors: p.errors }; + await p.page.locator("#fxtest button[data-fx='rain']").click(); // (rain's third step, the flood: its link's figure and label) + seen.flood = await p.page.evaluate(() => { const b = document.querySelector("#fxtest button[data-fx='rain']"); return [b.textContent, b.getAttribute("aria-label")]; }); + await p.context.close(); + return seen; + })); + // the temporary test links: each turns its effect and frame on (the gauges keep their readings), "stop" ends them (and + // stops the animations); the URL follows + const { context, page, errors } = await weatherPage(browser, url); + await calm(page, 5000); // (the gauges' rise) + const fx = (name) => page.locator("#fxtest button", { hasText: new RegExp(`^${name}`) }).first().click(); + const label = () => page.evaluate(() => document.querySelector(".tile[data-id='UV index']").getAttribute("aria-label")); + out.links = { buttons: await page.evaluate(() => [...document.querySelectorAll("#fxtest button")].map((b) => b.textContent)) }; + for (const name of ["uv", "humidity", "wind", "heat", "ice"]) { + await fx(name); + out.links[name] = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; + } + out.links.label = await label(); + out.links.corner = await cornerSeen(page); + out.links.haze = []; + for (let i = 0; i < 6; i++) { await fx("haze"); out.links.haze.push((await weatherSeen(page)).levels.haze); } + out.links.rain = []; // (rain: light, heavy, heavy with a flash flood (the test's own flood level), off: [rain, flood]) + for (let i = 0; i < 4; i++) { await fx("rain"); const { levels } = await weatherSeen(page); out.links.rain.push([levels.rain, levels.flood]); } + await page.waitForFunction(() => Sky.state().iceReach > 2.5); // (the ice grown in a little) + const grown = await page.evaluate(() => { // (as far as it had grown as it's turned off (one step: none growing between, the + const reach = Sky.state().iceReach; // machine however slow)); off: it melts back, the loop running on until it's gone + [...document.querySelectorAll("#fxtest button")].find((b) => /^ice/.test(b.textContent)).click(); + return reach; + }); + await page.waitForTimeout(300); + out.links.melting = { grown, reach: await page.evaluate(() => Sky.state().iceReach), ...await weatherSeen(page) }; + out.links.pressed = await page.evaluate(() => Object.fromEntries([...document.querySelectorAll("#fxtest button[data-fx]")] + .map((b) => [b.dataset.fx, b.getAttribute("aria-pressed")]))); + out.links.role = await page.evaluate(() => document.getElementById("fxtest").getAttribute("role")); + out.links.humiditySteps = []; // (humidity, on: light; then heavy, then off) + for (let i = 0; i < 2; i++) { + await fx("humidity"); + out.links.humiditySteps.push({ level: (await weatherSeen(page)).levels.humidity, url: await page.evaluate(() => location.search), + label: await page.evaluate(() => document.querySelector("#fxtest button[data-fx='humidity']").textContent) }); + } + await page.locator("#motion .animations").click(); + await page.waitForFunction(() => !document.querySelector("#motion .animations")); + out.links.cleared = { ...await weatherSeen(page), url: await page.evaluate(() => location.search), + pressed: await page.evaluate(() => document.querySelectorAll("#fxtest button.on").length), + stored: await stored(page) }; + // every effect at once: ?fx=all (no link of its own) + await page.goto(url + "?fx=all", { waitUntil: "load" }); + await page.waitForFunction(() => document.querySelectorAll(".tile").length > 0 && /last reading/.test(document.getElementById("status").textContent)); + out.links.all = { ...await weatherSeen(page), url: await page.evaluate(() => location.search) }; + await off; + [out.phone360, out.phone390] = await phones; + out.errors = [...errors, ...out.off.errors]; + await context.close(); + }, + async motion(browser, url, out) { + const seen = await Promise.all(Object.values(MOTIONS).map((options) => motionSeen(browser, url, options))); + Object.keys(MOTIONS).forEach((k, i) => { out[k] = seen[i]; }); + out.errors = seen.flatMap((m) => m.errors); + }, + // The haze alone (each band, the clouds' look and drift; Hazardous haze: the wind's way) + async haze(browser, url, out) { + const { context, page, errors } = await weatherPage(browser, url, { query: "?fx=haze5", driven: true }); + await drive(page, 56); // (faded in: 1.5 s) + out.haze = await hazeSeen(page); + out.errors = errors; + await context.close(); + }, + // Heavy humidity alone: the frame cost early, after minutes of the weather's time (the trails and beads built up), and with its + // time 20 times as fast (the sweep of the trails capped) + async trails(browser, url, out) { + const { context, page, errors } = await weatherPage(browser, url, { query: "?fx=humidity2", driven: true }); + await drive(page, 90); // (3 s of the weather's time) + out.cost = await frameCost(page, 60); + await page.evaluate(() => Sky.timeScale(100)); + await driveUntil(page, () => { const s = Sky.state(); return s.clock > 220 && s.humidity.trails > 16000; }); + await page.evaluate(() => Sky.timeScale(1)); + await drive(page, 45); + out.late = { cost: await frameCost(page, 60), ...await page.evaluate(() => ({ clock: Sky.state().clock, trails: Sky.state().humidity.trails, + beads: Sky.state().humidity.beads.length })) }; + await page.evaluate(() => Sky.timeScale(20)); + out.fast = { cost: await frameCost(page, 60), ...await page.evaluate(() => { const h = Sky.state().humidity; return { trails: h.trails, swept: h.swept, most: h.sweepMost, beads: h.beads.length }; }) }; + await page.evaluate(() => Sky.timeScale(1)); + out.errors = errors; + await context.close(); + }, + // The ice alone, grown all the way in: its frame cost and its frost across the glass + async frost(browser, url, out) { + const { context, page, errors } = await weatherPage(browser, url, { query: "?fx=ice", driven: true }); + await page.evaluate(() => Sky.timeScale(100)); + await driveUntil(page, () => { const f = Sky.frost(true); return f && f.target > 0 && f.extent === f.target; }); + await page.evaluate(() => Sky.timeScale(1)); + await drive(page, 45); + out.frosted = { cost: await frameCost(page, 60), crystals: await page.evaluate(() => Sky.frost().crystals) }; + out.errors = errors; + await context.close(); + }, + // Heavy rain, wind and haze together (what can occur together in practice): the shared particle budget + async budget(browser, url, out) { + const { context, page, errors } = await weatherPage(browser, url, { query: "?fx=rain2,wind,haze3", driven: true }); + await drive(page, 90); + out.cost = await frameCost(page, 60); + out.particles = await page.evaluate(() => ({ ...Sky.state().particles, budget: Sky.state().budget })); + out.errors = errors; + await context.close(); + }, + // A flash flood: the station's rain rate over 30 mm/h (not at 30): the water rising steadily to a quarter of the window's height, + // its surface choppy all across and higher at the sides, the rain ending at it in ripples and splashes; its waves alone (one + // push: travelling both ways, reflecting off a side); draining at 30, its chop calming slowly. Beside it, every other effect on + // and the test link's rain3 (rain light, heavy, flood, off): the frame time and the particles with the flood full; then on a fast + // clock, leaves landing on it, floating, sinking and resting on the bottom; the drips joining it (each as it did), and where the + // surface is down in a trough, what's drawn just under its level against what's just above; its first frog 30 s after the water + // starts rising, drifting right to left on the waves; off, draining. + // The weather past the window's top and bottom (a phone's address bar sliding away shows more than the layout viewport was): the + // canvas and its two margins reach at least OVER (100 px) past each edge; the viewport made taller (the bar hidden), with the + // window's resize event or without, still covered before any relayout; the weather's own world (the flood's level, the gust's + // height) is still the window's size, not the margins' too; the margins carry on the first and last rows, mirrored + async over(browser, url, out) { + const { context, page, errors } = await weatherPage(browser, url, { query: "?fx=haze3,humidity2,ice,heat,uv", driven: true, + context: { viewport: { width: 390, height: 700 }, hasTouch: true, isMobile: true } }); + await drive(page, 40); + const look = () => page.evaluate(() => { + const rect = (e) => { const r = e.getBoundingClientRect(); return [r.top, r.bottom, r.left, r.right]; }; + const [c, a, b] = document.querySelectorAll("#sky canvas"), s = Sky.state(), h = document.documentElement.clientHeight; + const rows = (cv, ys) => { const g = cv.getContext("2d"); return ys.map((y) => [...g.getImageData(0, y, cv.width, 1).data]); }; + const same = (x, y) => x.length === y.length && x.every((v, i) => v === y[i]); + const ink = (cv) => { const d = cv.getContext("2d").getImageData(0, 0, cv.width, cv.height).data; let n = 0; for (let i = 3; i < d.length; i += 4) if (d[i]) n++; return n; }; + return { inner: [innerWidth, innerHeight], client: [document.documentElement.clientWidth, h], canvas: rect(c), above: rect(a), below: rect(b), + sky: rect(document.getElementById("sky")), size: s.size, canvases: document.querySelectorAll("canvas").length, + mirrored: { top: same(rows(a, [a.height - 1])[0], rows(c, [0])[0]), bottom: same(rows(b, [0])[0], rows(c, [c.height - 1])[0]), + top2: same(rows(a, [a.height - 2])[0], rows(c, [1])[0]) }, + ink: [ink(a), ink(c), ink(b)], flood: s.flood.height, gustFrom: s.gust ? null : null, + bg: [getComputedStyle(document.documentElement).backgroundColor, getComputedStyle(document.body).backgroundColor], + theme: document.querySelector("meta[name=theme-color]").content }; + }); + out.first = await look(); + await page.setViewportSize({ width: 390, height: 790 }); // (the bar hidden: 90 px more, no event, no relayout yet) + await page.evaluate(() => new Promise((ok) => requestAnimationFrame(() => requestAnimationFrame(ok)))); + out.grown = await look(); + await page.evaluate(() => window.dispatchEvent(new Event("resize"))); + await page.waitForTimeout(500); + await drive(page, 5); + out.relaid = await look(); + out.errors = errors; + await context.close(); + }, + async flood(browser, url, out) { + const linked = (async () => { + const { context, page, errors } = await weatherPage(browser, url, { query: "?fx=haze3,uv,humidity2,wind,heat,ice", driven: true }); + const seen = { steps: [] }; + const rain = () => page.evaluate(() => { + const b = document.querySelector("#fxtest button[data-fx='rain']"); + return { url: location.search, label: b.getAttribute("aria-label"), text: b.textContent, rain: Sky.state().levels.rain, + flood: Sky.state().levels.flood }; + }); + const click = () => page.locator("#fxtest button[data-fx='rain']").click(); + for (let i = 0; i < 3; i++) { await click(); seen.steps.push(await rain()); } + await page.evaluate(() => Sky.timeScale(4)); // (full, then 80 frames as ever: the last 60's cost, the page's start long past) + await driveUntil(page, () => Sky.state().flood.depth >= Sky.state().flood.full); + await page.evaluate(() => Sky.timeScale(1)); + await drive(page, 20); + seen.costly = { cost: await frameCost(page, 60), ...await page.evaluate(() => ({ effects: Sky.state().effects, + particles: Sky.state().particles, budget: Sky.state().budget })) }; + await page.evaluate(() => Sky.timeScale(10)); + // every frame, until the first frog has crossed (or 100 s of the page's time): the frog, the leaves in the water, the drips + Object.assign(seen, await page.evaluate(() => new Promise((resolve) => { + const r = { before: null, first: null, track: [], leaves: { float: 0, sink: 0, rest: 0 }, gaps: [], resting: [], wet: 0, most: 0, + over: 0, under: 0, strokes: [], joined: 0, joins: [], frogs: 0, fullAt: null, fewest: Infinity, flown: [], + // (every leaf it took, by id: still in it at the end, or not; its count of them, those come to rest, those resting + // shown on the bottom (and its px) each 5 frames (each 5 s of its time here): any not shown, any look with fewer px than the last) + kept: { ids: new Set(), missing: [], took: 0, rested: 0, float: 0, sink: 0, looks: [], hidden: 0, shrank: 0 }, + // (the leaves and the water, every frame: flying ones drawn touching it or under it; those stuck in it, and of them + // the ones seen flying just before (and how near the water they were then); any flying again, any above the surface + // or going back a state; flying ones vanishing other than into it, last seen near the water and away from the + // window's edges (further than it went in a frame); flying ones seen within 3 px of it; the rain's hits on leaves meanwhile) + stuck: { touching: 0, wet: 0, seen: 0, lastGaps: [], back: 0, above: 0, backwards: 0, lost: [], near: 0, hits0: null, hits: 0 } }; + const flyers = new Map(), states = new Map(), ORDER = ["float", "sink", "rest"]; + let then = null; // (the clock the frame before) + const step = () => { + const s = Sky.state(), f = s.flood, w = s.wind, k = r.stuck; + if (f.depth >= f.full) { + if (k.hits0 === null) k.hits0 = w.hits; + k.hits = w.hits - k.hits0; + const now = new Map(w.flyers.map(([id, gap, x, y]) => [id, [gap, x, y]])); + for (const [id, [gap]] of now) { + if (gap !== null && gap <= 0) k.touching++; + if (gap !== null && gap <= 3) k.near++; + if (states.has(id)) k.back++; + } + for (const [id, state, gap] of w.wet) { + if (gap < 0) k.above++; + if (!states.has(id)) { + k.wet++; + if (flyers.has(id)) { k.seen++; k.lastGaps.push(flyers.get(id)[0]); } + } else if (ORDER.indexOf(state) < ORDER.indexOf(states.get(id))) k.backwards++; + states.set(id, state); + } + // (away from the edges: 16 px, or further than it could have gone this frame, at 1.5 times its last frame's speed) + const dt = then === null ? 0 : s.clock - then; + for (const [id, [gap, x, y, speed]] of flyers) { + if (now.has(id) || states.has(id)) continue; + const edge = Math.max(16, 1.5 * speed * dt + 4); + if (gap !== null && gap <= 8 && x > edge && x < f.width - edge) k.lost.push([id, gap, x, y]); + } + for (const [id, v] of now) v.push(flyers.has(id) && dt > 0 ? Math.abs(v[1] - flyers.get(id)[1]) / dt : 400); + then = s.clock; + flyers.clear(); + for (const [id, v] of now) flyers.set(id, v); + } + if (f.depth >= f.full && r.fullAt === null) r.fullAt = f.since; + if (!f.frog && !r.first) r.before = f.since; + if (f.frog) { + if (!r.first) r.first = f.since; + const x = Math.round(f.frog.x), under = [-6, -3, 0, 3, 6].map((dx) => f.surface[Math.min(Math.max(x + dx, 0), f.width - 1)]); + if (f.frog.stroke !== null && !r.strokes.includes(f.frog.stroke)) r.strokes.push(f.frog.stroke); + if (f.frog.y !== null && x >= 0 && x < f.width) r.track.push([f.frog.x, f.frog.y, under.reduce((a, b) => a + b) / 5]); // (the surface under its pad) + } + for (const k of ["float", "sink", "rest"]) r.leaves[k] = Math.max(r.leaves[k], w.water[k]); + r.gaps.push(...w.floating); + r.resting.push(...w.resting); + const wet = w.water.float + w.water.sink; // (those resting: drawn on the bottom, no particles) + r.wet = Math.max(r.wet, wet); + r.most = Math.max(r.most, wet / w.leaves); + if (f.depth >= f.full) { r.fewest = Math.min(r.fewest, w.flyers.length / w.leaves); r.flown.push(w.flyers.length / w.leaves); } + for (const [id] of w.wet) r.kept.ids.add(id); + if (s.frames % 5 === 0 && w.rested) { + const shows = w.shows(), last = r.kept.looks.at(-1); + if (shows.shown < shows.of) r.kept.hidden++; + if (last && shows.px < last.px) r.kept.shrank++; + r.kept.looks.push(shows); + } + const used = Object.entries(s.particles).filter(([k]) => !(s.own || []).includes(k)).reduce((a, [, b]) => a + b, 0); // (humidity's beads their own) + r.over = Math.max(r.over, used - s.budget); + if (f.depth >= f.full) { // (the drips: none below the surface, beyond a crest's rise in a frame on this fast clock) + r.under = Math.max(r.under, s.humidity.beads.filter((b) => b.bottom > f.surface[Math.round(Math.min(Math.max(b.x, 0), f.width - 1))] + 3).length); + } + r.joined = s.humidity.joined; + r.joins = s.humidity.joins; + r.frogs = f.frogs; + if ((r.first && !f.frog) || f.since > 100) { + r.gaps = r.gaps.slice(-400); r.resting = r.resting.slice(-400); r.stuck.lastGaps = r.stuck.lastGaps.slice(-200); + r.flying = r.flown.reduce((a, b) => a + b, 0) / Math.max(r.flown.length, 1); + delete r.flown; + const now = new Set(w.wet.map(([id]) => id)), k = r.kept; + k.missing = [...k.ids].filter((id) => !now.has(id)); + Object.assign(k, { ids: k.ids.size, took: w.took, rested: w.rested, float: w.water.float, sink: w.water.sink, + looks: k.looks.length, last: k.looks.at(-1), first: k.looks[0] }); + return resolve(r); + } + __next(step); + }; + __next(step); + }))); + // (still full: where the surface is down in a trough, 3 px or more below its level, the canvas's alpha in the two rows just + // under the level beside two rows a little above it, those columns all summed, frame by frame till 400 of them; last, as reading + // the canvas back can slow its drawing) + seen.cut = await page.evaluate(() => new Promise((resolve) => { + const g = document.querySelector("#sky canvas").getContext("2d"), cut = { n: 0, above: 0, at: 0 }; + let frames = 0; + const step = () => { + const f = Sky.state().flood, level = f.height - f.depth, d = g.getImageData(0, level - 4, f.width, 6).data; + const alpha = (row, x) => d[(row * f.width + x) * 4 + 3]; + for (let x = 0; x < f.width; x++) if (Math.round(f.surface[x]) >= level + 3) { + cut.n++; cut.above += alpha(0, x) + alpha(1, x); cut.at += alpha(4, x) + alpha(5, x); + } + if (cut.n >= 400 || ++frames >= 150) resolve(cut); else __next(step); + }; + __next(step); + })); + // (still full: its body's dithering, in its bottom 32 rows, the middle 256 px across) + const [cw, ch] = await page.evaluate(() => Sky.state().size); + seen.grid = (await gridPeak(page, [Math.floor((cw - 256) / 2), ch - 32, 256, 32])).ratio; + // the wind off, some leaves resting on the bottom and some floating: those in the water staying, the floating ones sinking + // (once the wind is gone: then the weather's time 20 times as fast for 16 s of it, and on till every one has come to rest) + await driveUntil(page, () => { const w = Sky.state().wind.water; return w.rest >= 1 && w.float >= 2; }); + await page.locator("#fxtest button[data-fx='wind']").click(); + await driveUntil(page, () => !Sky.state().effects.includes("wind") && Sky.state().particles.wind === 0); + seen.windOff = { before: await page.evaluate(() => Sky.state().flood.leaves.wet) }; + await page.evaluate(() => Sky.timeScale(20)); + const gone = await page.evaluate(() => Sky.state().clock); + await driveUntil(page, (c) => Sky.clock().clock >= c + 16, gone); + Object.assign(seen.windOff, await page.evaluate(() => ({ after: Sky.state().flood.leaves.wet, flyers: Sky.state().wind.flyers.length, + effects: Sky.state().effects }))); + await driveUntil(page, () => { const w = Sky.state().flood.leaves.water; return w.float + w.sink === 0; }); + seen.windOff.settled = await page.evaluate(() => { const l = Sky.state().flood.leaves; return { took: l.took, rested: l.rested, all: l.all, shows: l.shows(), particles: Sky.state().particles.flood ?? 0 }; }); + // off: draining, the leaves in it staying till it's nearly gone, then gone with it (the weather's time four times as fast) + await page.evaluate(() => Sky.timeScale(4)); + const n0 = await page.evaluate(() => Sky.state().flood.leaves.all); + await click(); + seen.off = await rain(); + seen.drained = await page.evaluate((n0) => new Promise((resolve) => { + const c0 = Sky.state().clock, depth0 = Sky.state().flood.depth; + let low = null; // (how many leaves in it as it got down to its last 8 px) + const step = () => { + const s = Sky.state(); + if (s.flood.depth > 0) { + if (s.flood.depth <= 8 && low === null) low = s.flood.leaves.all; + return __next(step); + } + __next(() => __next(() => { + const w = Sky.state().wind; + resolve({ took: s.clock - c0, depth0, effects: Sky.state().effects, wet: w.water.float + w.water.sink + w.water.rest, + all: Sky.state().flood.leaves.all, frog: Sky.state().flood.frog, n0, low }); + })); + }; + __next(step); + }), n0); + // a new flood (rain3 again): none of the leaves from before in it + for (let i = 0; i < 3; i++) await click(); + await driveUntil(page, () => Sky.state().flood.depth > 0); + seen.again = await page.evaluate(() => ({ url: location.search, leaves: Sky.state().flood.leaves })); + seen.errors = errors; + await context.close(); + return seen; + })(); + // the station's rain rate: 30 mm/h, then just over it (the weather's time four times as fast) + const { context, page, errors, reads } = await weatherPage(browser, url, { driven: true }); + await reads({ rain_rate: 30 }); + out.at30 = await weatherSeen(page); + await page.evaluate(() => Sky.timeScale(4)); + await reads({ rain_rate: 30.1 }); + out.over = await weatherSeen(page); + out.rising = await page.evaluate(() => new Promise((resolve) => { + const rise = [], looks = [], splashes = []; + let under = 0, hits = null; + const mean = (a) => a.reduce((s, v) => s + v, 0) / Math.max(a.length, 1); + const step = () => { + const s = Sky.state(), f = s.flood; + under = Math.max(under, s.rain.under); + if (f.depth < f.full) { if (!rise.length || s.clock > rise.at(-1)[0]) rise.push([s.clock, f.depth]); return __next(step); } + if (hits === null) hits = f.hits; + splashes.push(f.splashes); + if (looks.length < 90) { looks.push(f.surface.map((y) => y - (f.height - f.depth))); return __next(step); } + // the rise: its speed (art px/s of the weather's time) frame to frame, while it rose (not its first frame or its last) + const speeds = rise.slice(1).map(([c, d], i) => (d - rise[i][1]) / (c - rise[i][0])).slice(1, -1); + const W = looks[0].length, rms = (xs) => Math.sqrt(mean(looks.flatMap((l) => xs.map((x) => l[x] ** 2)))); + const middle = Array.from({ length: Math.floor(W / 3) }, (_, i) => i + Math.floor(W / 3)); + // (the waves alone: a still surface 200 px wide pushed down 4 px at 60, each 0.1 s for 3 s: its troughs' places at 1 s and + // 3 s, and its deepest then) + const alone = f.waves(200, 60, 4, 3, 0.1), troughs = (h) => h.flatMap((v, x) => (x > 0 && x < h.length - 1 && v < -0.15 && + v <= h[x - 1] && v <= h[x + 1] ? [x] : [])); + resolve({ full: f.full, height: f.height, width: W, speeds, test: f.test, nextFrog: f.nextFrog, frog: f.frog, under, hits: f.hits - hits, + splashes: Math.max(...splashes), chop: f.chop, + crests: mean(looks.map((l) => l.filter((v, x) => x > 0 && x < W - 1 && v < l[x - 1] && v <= l[x + 1]).length)), + middle: rms(middle), edges: rms([0, 1, 2, W - 3, W - 2, W - 1]), + // (the chop in each third of the width: the surface against its own mean over 9 px about each column, so the + // longer sloshes passing don't count) + thirds: [0, 1, 2].map((k) => Math.sqrt(mean(looks.flatMap((l) => Array.from({ length: Math.floor(W / 3) - 8 }, (_, i) => { + const x = i + 4 + k * Math.floor(W / 3); + return (l[x] - mean(l.slice(x - 4, x + 5))) ** 2; + }))))), + waves: { speed: f.wave, at1: troughs(alone[10]), at3: troughs(alone[30]), deepest3: Math.min(...alone[30]) } }); + }; + __next(step); + })); + await reads({ rain_rate: 30 }); + out.draining = await page.evaluate(() => new Promise((resolve) => { + const f0 = Sky.state().flood, c0 = Sky.state().clock, effects = Sky.state().effects; + let half = null; + const step = () => { + const s = Sky.state(), f = s.flood; + if (half === null && f.depth <= f.full / 2) half = { chop: f.chop, after: s.clock - c0 }; + if (f.depth > 0) return __next(step); + resolve({ effects, took: s.clock - c0, chop0: f0.chop, half, surface: f.surface.length }); + }; + __next(step); + })); + out.drained = await weatherSeen(page); + out.errors = errors; + await context.close(); + out.linked = await linked; + out.errors.push(...out.linked.errors); + }, + async opened(browser, url, out) { + const particles = (p) => p.evaluate(() => ({ ...Sky.state().particles, budget: Sky.state().budget })); + // uv's beams over 40 s of the page's time, on a page of their own beside the rest: each swaying about its place + // ... then, on that page, the frost (its page's time 10 times as fast and its weather's 40 times that: 4 s a frame): just below + // 0 °C (-0.5) as far as it goes, then melted; then -5 °C from nothing, a minute in and as far as it goes; then melting, half a + // minute in, and gone. Each: Sky.frost() and the weather's time it took; as far as it goes, the canvas's pixels: their alphas + // and colours + const frostSeen = async (p) => { + const fx = (detail) => p.page.evaluate((d) => { document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: d })); return Sky.state().clock; }, detail); + const frost = () => p.page.evaluate(() => ({ ...Sky.frost(), clock: Sky.state().clock, running: Sky.state().running })); + const until = (test, arg) => driveUntil(p.page, test, arg); + const settled = () => until(() => { const f = Sky.frost(true); return f && f.extent === f.target; }); + // the canvas: the share of it drawn, its pixels' mean alpha (0-1), the share over 100 (of 255); of those drawn, their mean + // light (luminance, 0-255) and the share as blue as red or bluer + const pixels = () => p.page.evaluate(() => { + const c = document.querySelector("#sky canvas"), d = c.getContext("2d").getImageData(0, 0, c.width, c.height).data; + let drawn = 0, alpha = 0, strong = 0, light = 0, bluer = 0; + for (let i = 0; i < d.length; i += 4) { + if (!d[i + 3]) continue; + drawn++; alpha += d[i + 3]; strong += d[i + 3] > 100; + light += 0.2126 * d[i] + 0.7152 * d[i + 1] + 0.0722 * d[i + 2]; + bluer += d[i + 2] >= d[i] && d[i + 1] >= d[i]; + } + const n = d.length / 4; + return { drawn: drawn / n, alpha: alpha / n / 255, strong: strong / n, light: light / Math.max(drawn, 1), bluer: bluer / Math.max(drawn, 1) }; + }); + const seen = {}; + await p.page.evaluate(() => Sky.timeScale(40)); + let from = await fx({ ice: 0.5 }); + await settled(); + seen.slight = await frost(); + seen.slight.took = seen.slight.clock - from; + await fx({}); + await until(() => !Sky.state().running); + seen.slightGone = await frost(); + from = await fx({ ice: 5 }); + await until((t) => Sky.state().clock >= t, from + 60); + seen.minute = await frost(); + const sparkles = p.page.evaluate(() => new Promise((resolve) => { // (the most sparkles at once, while it grows on) + let most = 0; + const look = () => { const f = Sky.frost(true); most = Math.max(most, f.sparkles); if (f.extent === f.target) resolve(most); else __next(look); }; + look(); + })); + seen.sparkles = await sparkles; + await settled(); + seen.cold = await frost(); + seen.cold.took = seen.cold.clock - from; + seen.cold.pixels = await pixels(); + seen.cold.grid = await gridShare(p.page); // (its commonest shade: its haze's faint one) + seen.cold.size = await p.page.evaluate(() => { const c = document.querySelector("#sky canvas"); return [c.width, c.height]; }); + from = await fx({}); + await until((t) => Sky.state().clock >= t, from + 30); + seen.melting = await frost(); + await until(() => !Sky.state().running); + seen.gone = await frost(); + // (on again: nothing from before, its canvas clear, no sparkle; then grown half a minute, and "stop", "start + // animation" and on again: the same) + seen.again = await p.page.evaluate(() => { + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { ice: 5 } })); + const f = Sky.frost(); + return { extent: f.extent, ink: f.ink, sparkles: f.sparkles }; + }); + from = await p.page.evaluate(() => Sky.state().clock); + await until((t) => Sky.state().clock >= t, from + 30); + seen.grown = await frost(); + seen.restarted = await restarted(p.page, { ice: 5 }); + return seen; + }; + const swaying = (async () => { + const uv = await weatherPage(browser, url, { query: "?fx=uv", pace: 10, driven: true, context: { viewport: { width: 640, height: 480 } } }); // (small: cheap) + const seen = await uvSeen(uv.page); + seen.grid = (await gridPeak(uv.page)).ratio; // (its glow's dithering) + const frost = await frostSeen(uv); + seen.errors = frost.errors = uv.errors; + await uv.context.close(); + return [seen, frost]; + })(); + // the heat's red shafts at 35 °C, between and at 43 °C; and at 43 °C with the UV's shafts on too (small: cheap) + const hot = Promise.all([["heat", [{ heat: 0.3 }, { heat: 0.65 }, { heat: 1 }]], ["heat,uv", [{ heat: 1, uv: 1 }]]].map(async ([name, levels]) => { + const p = await weatherPage(browser, url, { query: `?fx=${name}`, driven: true, context: { viewport: { width: 640, height: 480 } } }); + const seen = await heatSeen(p.page, levels); + seen.grid = (await gridPeak(p.page)).ratio; // (its shafts' dithering) + seen.errors = p.errors; + await p.context.close(); + return seen; + })); + // humidity's beads condensing on the glass and running down it over 3.6 minutes of the page's time (its weather's time 6 times as + // fast), alone and with the wind, beside the rest (small: cheap) (heavy: 100 %); and light (91 %), watched for 2 minutes + // light (91 %) and heavy (100 %) humidity's still beads after the same time (1500 frames, then the mean of ten counts 20 frames + // apart): heavy's more (a grown bead costs a whole particle of the budget, a tiny one a quarter; heavy's budget the larger) + const counting = Promise.all(["humidity", "humidity2"].map(async (name) => { + const p = await weatherPage(browser, url, { query: `?fx=${name}`, pace: 10, driven: true, context: { viewport: { width: 640, height: 480 } } }); + await p.page.evaluate(() => Sky.timeScale(6)); + await drive(p.page, 1500); + let sum = 0; + for (let k = 0; k < 10; k++) { await drive(p.page, 20); sum += await p.page.evaluate(() => Sky.state().humidity.beads.filter((b) => b.v < 1).length); } + await p.context.close(); + return sum / 10; + })); + const beading = Promise.all(["humidity2", "humidity2,wind", "humidity"].map(async (name) => { + // (the wind's page another glass than humidity's alone, its own seed: the wind blows no water on the glass, so seeded alike it + // would be the very same beads, nothing more seen) + const p = await weatherPage(browser, url, { query: `?fx=${name}`, pace: 10, driven: true, seed: name.includes("wind") ? 1 : 0, + context: { viewport: { width: 640, height: 480 } } }); + await p.page.evaluate(() => Sky.timeScale(6)); + await lookable(p.page); + if (name !== "humidity") await drive(p.page, 150); // (beaded up a while first: beads run only from about large) + const seen = await humiditySeen(p.page, name === "humidity" ? 200 : 540); // (beads run only from about large: watched longer) + if (name === "humidity2") seen.grid = (await gridPeak(p.page)).ratio; // (its fog's dithering) + if (name === "humidity") { // (then heavy rain too, its weather's time as fast: its splashes' droplets left on the fog) + await p.page.evaluate(() => document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { humidity: 1, rain: 1 } }))); + seen.splashed = await beadsWatched(p.page, 300); + } + await p.page.evaluate((k) => Sky.timeScale(k), name === "humidity2,wind" ? 1 : 2); + if (name === "humidity2") seen.snapped = await snapped(p.page); + if (name === "humidity2") { // (a big bead swallowing a tiny one: its time as it is, a frame a 30th of a second) + await p.page.evaluate(() => Sky.timeScale(1)); + seen.gulped = await gulped(p.page); + await p.page.evaluate(() => Sky.timeScale(2)); + } + if (name === "humidity2,wind") { // (then its trails' time 60 times as fast, through the fog; then humidity off: the fog clearing) + // (beads running only from about large, a few at a time: the fresh trails then, a few, and again after the beads have run on + // a while (their weather's time 6 times as fast), till a dozen or so) + seen.refog = []; + for (let k = 0; k < 4 && seen.refog.length < 12; k++) { + if (k) { await p.page.evaluate(() => Sky.timeScale(6)); await drive(p.page, 60); await p.page.evaluate(() => Sky.timeScale(1)); } + seen.refog.push(...await trailsAge(p.page, 60, true, 60)); + } + await p.page.evaluate(() => Sky.timeScale(2)); + seen.clears = await humidityClears(p.page, 300); + } + if (name === "humidity2") { // (then every other effect on too, its share of the budget shrinking: watched 8 s more) + await p.page.evaluate(() => document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { rain: 1, haze: 3, uv: 1, humidity: 1, wind: 1, heat: 1, ice: 5 } }))); + seen.squeezed = await humiditySeen(p.page, 40); + // (then all off, faded out all the way, and humidity on again: the glass fresh, nothing left from before) + const before = await p.page.evaluate(() => { // (the trails as it's turned off) + const trails = Sky.state().humidity.trails; + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: {} })); + return trails; + }); + await driveUntil(p.page, () => !Sky.clock().running); + seen.again = await p.page.evaluate((before) => { + const gone = Sky.state().humidity.marks(); // (faded out all the way: forgotten) + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { humidity: 1 } })); + const h = Sky.state().humidity; + return { before, trails: h.trails, beads: h.beads.length, stray: h.stray(), gone, marks: h.marks() }; + }, before); + // (then its beads running and leaving trails (the weather's time 30 times as fast), and "stop", then the effect on again + // and humidity on again: the glass fresh too) + await p.page.evaluate(() => Sky.timeScale(30)); + await driveUntil(p.page, () => Sky.state().humidity.trails > 30); + seen.marked = await p.page.evaluate(() => { Sky.timeScale(1); return Sky.state().humidity.marks(); }); + seen.restarted = await restarted(p.page, { humidity: 1 }); + // (and the physics the beads run by: a bead's mean speed on each glass, by size; its size after running 20 px in 5 s there) + seen.physics = await p.page.evaluate(() => { + const { speed, after, gone, run } = Sky.state().humidity.physics, sizes = [0.6, 1, 1.1, 1.3, 1.4, 2, 2.8, 3, 3.4, 4, 6, 10]; + return { sizes, gone, run, speed: Object.fromEntries(["dry", "trail", "fog"].map((g) => [g, sizes.map((r) => speed(r, g))])), + after: Object.fromEntries(["dry", "trail", "fog"].map((g) => [g, sizes.map((r) => after(r, g, 20, 5))])) }; + }); + } + seen.errors = p.errors; + await p.context.close(); + return seen; + })); + // heavy rain's beads (rain alone, light first; 30 s, then heavy, 75 s: its time 30 times as fast, small: cheap), and on clear + // glass their trails drying (their time 120 times as fast), beside the rest + const sticking = (async () => { + const p = await weatherPage(browser, url, { query: "?fx=rain", pace: 10, driven: true, context: { viewport: { width: 480, height: 360 } } }); + await p.page.evaluate(() => Sky.timeScale(3)); + await lookable(p.page); + const seen = await rainBeads(p.page, 100, 250, 0, 1); + await p.page.evaluate(() => Sky.timeScale(1)); + // (heavy still, its weather's own time (a frame 0.1 s: a stretch over a few), 30 s: the biggest setting off again after pauses) + seen.stretching = await beadsWatched(p.page, 300); + // (a few drops landing, frame by frame: squashed and back to round) + seen.landings = await landingsWatched(p.page, 4, 900); + let looks; + // (the rain eased: watched till the last bead has gone, up to 1100 frames (11 minutes of its weather's time): one shrunk on + // dry glass under the run size and sitting on a wet trail keeps its size till that trail dries, 3 to 10 minutes) + ({ eased: seen.eased, after: seen.after, looks, watched: seen.afterWatched } = await rainBeads(p.page, 0, 0, 1100, 6, "heavy")); + seen.looks.push(...looks); // (the trails' looks, those running on too) + // the rain easing, still on (light): its streaks drying on their own time, there still 6 s (of its weather's time) after + // (the heavy rain's streaks: a minute old at most, none dried yet) + seen.easing = await p.page.evaluate(() => new Promise((resolve) => { + const at = Sky.state().humidity.marks(), from = Sky.state().clock; + Sky.timeScale(6); + const look = () => { + if (Sky.state().clock < from + 6) return __next(look); + Sky.timeScale(1); + resolve({ at, after: Sky.state().humidity.marks() }); + }; + __next(look); + })); + seen.drying = await trailsAge(p.page, 120, false, 30); // (those streaks, still fresh: their time 120 times as fast) + // heavy again (its weather's time 10 times as fast) till more streaks; off, faded out all the way (the loop over, its time 30 + // times as fast); heavy + // again: the glass clean, nothing from before (its trails, its canvas, its beads; the rain's drops) + const heavyTill = (more) => p.page.evaluate((more) => new Promise((resolve) => { + const from = Sky.state().humidity.marks().trails; + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { rain: 1 } })); + Sky.timeScale(10); + let n = 0; + const look = () => { + const m = Sky.state().humidity.marks(); + if (m.trails < from + more && n++ < 900) return __next(look); + Sky.timeScale(1); + resolve(m); + }; + __next(look); + }), more); + seen.streaked = await heavyTill(30); + await p.page.evaluate(() => { document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: {} })); Sky.timeScale(30); }); + await driveUntil(p.page, () => !Sky.clock().running); + seen.cleared = await p.page.evaluate(() => { + Sky.timeScale(1); + const gone = Sky.state().humidity.marks(); + document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { rain: 1 } })); + const s = Sky.state(); + return { gone, again: s.humidity.marks(), stray: s.humidity.stray(), drops: s.particles.rain }; + }); + // ... and the same with "stop" between, then the effect on again + seen.streakedAgain = await heavyTill(30); + seen.restarted = await restarted(p.page, { rain: 1 }); + seen.errors = p.errors; + await p.context.close(); + return seen; + })(); + // heavy rain, alone and in the wind (and in the wind on a phone), its drops watched for 3 s, beside the rest; with the wind, the + // leaves the drops knocked. (In the wind, the window's size: first light rain, as it fades in, its first few hits on the leaves.) + const phoneSize = { viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true }; + const raining = Promise.all([["rain2"], ["rain2,wind"], ["rain2,wind", phoneSize]].map(async ([name, context], i) => { + const p = await weatherPage(browser, url, { query: `?fx=${i === 1 ? "rain,wind" : name}`, context, driven: true }); + let light = null; + if (i === 1) { + await driveUntil(p.page, () => Sky.state().wind.hits >= 3); + light = await p.page.evaluate(() => Sky.state().wind); + await p.page.evaluate(() => document.dispatchEvent(new CustomEvent("ecobot-fx", { detail: { rain: 1, wind: 1 } }))); + } + const seen = { ...await rainSeen(p.page, 3000), leaves: await p.page.evaluate(() => Sky.state().wind), errors: p.errors }; + if (light) { // (the heavy rain's hits alone: how many, their mean push, the mean change they made in a leaf's velocity) + const { hits, push, kick } = seen.leaves, heavy = Math.max(hits - light.hits, 1); + seen.leaves = { ...seen.leaves, hits: hits - light.hits, push: (hits * push - light.hits * light.push) / heavy, + kick: (hits * kick - light.hits * light.kick) / heavy }; + seen.light = { hits: light.hits, push: light.push, kick: light.kick }; + } + await p.context.close(); + return seen; + })); + // without the temporary test links (the page as it will be), at 1024x768 and on a phone with a tile hidden: "stop" at + // the bottom left on its own + const bare = Promise.all([{}, { viewport: { width: 360, height: 740 }, hasTouch: true, isMobile: true }].map(async (context) => { + const p = await weatherPage(browser, url, { bare: true, driven: true, context, + init: { fn: (key) => localStorage.setItem(key, JSON.stringify({ order: [], hidden: ["Rain"] })), arg: KEY } }); + await p.reads({ "UV index": 11 }); + const seen = { ...await cornerSeen(p.page), errors: p.errors }; + await p.context.close(); + return seen; + })); + // ?fx= when the page opens (each a page of its own, side by side, beside the rest; small: cheap) + const params = Promise.all([["param", "?fx=haze3,wind,ice"], ["paramAll", "?fx=all"], ["paramRain", "?fx=rain2"], + ["paramOld", "?fx=leaves,radiation,drips,smog4"]].map(async ([name, query]) => { + const opened = await weatherPage(browser, url, { query, driven: true, context: { viewport: { width: 480, height: 360 } } }); + await opened.page.waitForTimeout(200); + out[name] = { ...await weatherSeen(opened.page), errors: opened.errors }; + await opened.context.close(); + })); + // uv alone: its beams, no particles; the wind alone: its leaves within the budget, blowing right to left (and looping), watched + // for 20 s of its time (several gusts and lulls: 2.5 s could fall in a lull, its eddies' loops then much of what moves) beside + // the rest + out.particles = {}; + out.rain = {}; + out.humidity = {}; + const alone = Promise.all(["uv", "wind"].map(async (name) => { + const alone = await weatherPage(browser, url, { query: `?fx=${name}`, driven: true }); + if (name === "wind") out.wind = await windSeen(alone.page, 20000); + else await drive(alone.page, 20); // (under way) + const p = await particles(alone.page); + out.particles[name] = { [name]: p[name], budget: p.budget }; + await alone.context.close(); + })); + // a phone, a tile hidden, an effect on (the wind, its leaves looping there too): the strip (reset preferences · last reading) at + // the bottom right, the time last; the test row and "stop" not over it (beside the rest) + const phoned = (async () => { + const phone = await weatherPage(browser, url, { query: "?fx=wind", driven: true, context: { viewport: { width: 360, height: 740 }, hasTouch: true, isMobile: true }, + init: { fn: (key) => localStorage.setItem(key, JSON.stringify({ order: [], hidden: ["Rain"] })), arg: KEY } }); + out.phoneWind = await windSeen(phone.page, 20000); + out.phoneCorner = await cornerSeen(phone.page); + out.phone = await phone.page.evaluate(() => { + const a = document.getElementById("fxtest").getBoundingClientRect(), b = document.getElementById("status").getBoundingClientRect(); + const r = document.querySelector("#reset").getBoundingClientRect(), u = document.getElementById("units").getBoundingClientRect(); + return { strip: document.getElementById("status").textContent, resetRight: r.right <= innerWidth && r.left >= 0 && r.width > 0 && (r.bottom <= u.top || r.right <= u.left), + resetAfterRow: r.bottom <= a.top || r.left >= a.right, right: Math.abs(b.right - innerWidth) < 1 && Math.abs(b.bottom - innerHeight) < 1, + apart: a.right <= b.left || b.right <= a.left || a.bottom <= b.top || b.bottom <= a.top, onScreen: a.left >= 0 && a.bottom <= innerHeight }; + }); + await phone.context.close(); + })(); + await Promise.all([params, alone, phoned]); + [out.uv, out.frost] = await swaying; + [out.humidity.alone, out.humidity.windy, out.humidityLight] = await beading; + out.stillBeads = await counting; // ([light, heavy]) + out.rainBeads = await sticking; + [out.heat, out.heatOver] = await hot; + [out.rain.alone, out.rain.windy, out.rain.phone] = await raining; + [out.bare, out.barePhone] = await bare; + out.errors = []; + }, + // A gust over 99 km/h: the live gust at 99 (nothing), just over (one sent), the same reading fetched again (no more), a new one over + // (another), one under (none); then a cow, a barn and a chicken sent at once, watched every frame as they cross (the weather's time + // 5 times as fast): where each is, its angle, the chicken's frames, the canvas's pixels while they cross (alone: theirs and their + // bits'), the loop ending once they're gone; the test link (five clicks, its URL, never pressed), "stop" (the wind's +// link on too, so it shows: they're gone at once), + // ?fx=gust as the page opens (ignored: nothing sent, the word dropped from the URL; and beside "wind"), and on a phone the row + // (every link, "gust" too, and "stop" in sight unscrolled). A frame + // sequence of the three crossing kept as screenshots (SHOTS, when given) + // tilt: a phone's gravity turning the humidity's beads' way (the page's own devicemotion listener, Sky.tilt): synthetic readings at + // screen angles (the spec's convention, as Android's: at rest upright, y +9.8), where the beads run (the mean of their moves while + // running: dx, dy; which edge, how many ran off), a phone flat (pooling: nothing runs, the beads merge into ever larger blobs) and the speed at angles from flat + // through upright to face down, no reading (as ever), the animations low and off + // (ignored), an iPhone's link (its permission asked from a tap: granted, denied; the sign turned), and the low-pass and dead zone + async tilt(browser, url, out) { + const turned = (angle) => ({ fn: (a) => { + Object.defineProperty(window.screen.orientation, "angle", { configurable: true, get: () => window.__angle }); + window.__angle = a; + }, arg: angle }); + const shake = (page, x, y, z) => page.evaluate(([x, y, z]) => window.dispatchEvent(new DeviceMotionEvent("devicemotion", { accelerationIncludingGravity: { x, y, z } })), [x, y, z]); + // the beads' mean move while running, over a stretch of the weather's time (30 times as fast) + const run = async (page, frames = 400) => page.evaluate((frames) => { + Sky.timeScale(30); + const first = new Map(), last = new Map(), steps = new Map(); + let n = 0; + while (n++ < frames && Sky.advance(1)) { + for (const b of Sky.state().humidity.beads) if (b.kind === "fog" && b.v > 0) { + if (!first.has(b.id)) first.set(b.id, [b.x, b.cy]); + last.set(b.id, [b.x, b.cy]); + steps.set(b.id, (steps.get(b.id) || 0) + 1); + } + } + const moves = [...last].filter(([id]) => steps.get(id) >= 8).map(([id, [x, y]]) => [x - first.get(id)[0], y - first.get(id)[1]]); + const sum = (i) => moves.reduce((t, m) => t + m[i], 0) / Math.max(moves.length, 1); + const h = Sky.state().humidity, t = Sky.state().tilt; + return { running: moves.length, dx: sum(0), dy: sum(1), ranOff: h.ranOff, tilt: t, size: Sky.state().size }; + }, frames); + const opts = (angle, extra = {}) => ({ query: "?fx=humidity2", pace: 10, driven: true, context: { viewport: { width: 400, height: 300 } }, init: turned(angle), ...extra }); + // (readings: [angle, x, y, z], the phone held so) + const cases = { upright: [0, 0, 9.8, 0], rolledRight: [0, -6, 7.7, 0], rolledLeft: [0, 6, 7.7, 0], onItsRight: [0, -9.8, 0, 0], onItsTop: [0, 0, -9.8, 0], + landscape: [90, 9.8, 0, 0], landscapeLeaning: [90, 9, 5.7, 0], landscapeFlipped: [270, -9.8, 0, 0], landscapeFlippedLeaning: [270, -9, -5.7, 0], + upsideDown: [180, 0, -9.8, 0], upsideDownLeaning: [180, 6, -7.7, 0] }; + out.cases = {}; + out.errors = []; + await Promise.all(Object.entries(cases).map(async ([name, [angle, x, y, z]]) => { + const p = await weatherPage(browser, url, opts(angle)); + await shake(p.page, x, y, z); + out.cases[name] = await run(p.page); + out.errors.push(...p.errors); + await p.context.close(); + })); + // the pure turn (the page's screenGravity(ax, ay, angle, ios) -> the pull in the screen's x right, y down), against readings worked out + // here from the physics, not from the page's table: the device turned a quarter COUNTER-clockwise `angle` degrees (screen.orientation.angle: + // 90 is the device's top to the viewer's left), its axes in the viewer's world (x right, y up) x = (cos a, sin a), y = (-sin a, cos a); + // the screen's own edge `dir` (left, right, top, bottom) lowered, the pull in the world that way; the reading by the spec is minus the + // pull in the device's axes, iOS's the pull itself + const pure = await (await weatherPage(browser, url, opts(0))).page.evaluate(() => { + const world = { left: [-1, 0], right: [1, 0], top: [0, 1], bottom: [0, -1] }, got = {}; + for (const angle of [0, 90, 180, 270, -90]) for (const ios of [false, true]) for (const [edge, [wx, wy]] of Object.entries(world)) { + const t = angle * Math.PI / 180, dx = Math.cos(t) * wx + Math.sin(t) * wy, dy = -Math.sin(t) * wx + Math.cos(t) * wy; // (the pull in the device's axes) + const k = ios ? 1 : -1, [x, y] = window.__screenGravity(k * 9.8 * dx, k * 9.8 * dy, angle, ios); + got[`${angle}/${ios ? "ios" : "spec"}/${edge}`] = [Math.round(x * 100) / 100 + 0, Math.round(y * 100) / 100 + 0]; + } + return got; + }); + out.pure = pure; + // end to end on an iPad (its user agent: the sign turned), the window shaped as the screen is. iPadOS Safari's screen.orientation.angle + // is relative to the iPad's natural LANDSCAPE (0 for landscape-primary, as a real iPad's ?tiltdebug=1 showed), so the page must use + // window.orientation (0, 90, -90, 180: 90 is the device turned counter-clockwise) and ignore that angle; the readings are the pull itself + // in the PORTRAIT device frame (x to its right edge, y to its top, z out of the screen). + const ipad = (w, h) => ({ viewport: { width: w, height: h }, hasTouch: true, isMobile: true, + userAgent: "Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1" }); + const reported = (angle, extra) => ({ fn: ([angle, extra]) => { + Object.defineProperty(window.screen.orientation, "angle", { configurable: true, get: () => angle }); + if ("windowOrientation" in extra) Object.defineProperty(window, "orientation", { configurable: true, value: extra.windowOrientation }); + if (extra.type) Object.defineProperty(window.screen.orientation, "type", { configurable: true, get: () => extra.type }); + }, arg: [angle, extra] }); + // the iOS reading worked out from the physics: the iPad turned `wo` degrees counter-clockwise from upright (the device's x and y axes in + // the viewer's world (x right, y up): x = (cos, sin), y = (-sin, cos)); the screen's `edge` down, the pull that way; the reading is the + // pull's share along each device axis + const world = { left: [-1, 0], right: [1, 0], top: [0, 1], bottom: [0, -1] }; + const iosReading = (wo, edge) => { + const t = wo * Math.PI / 180, [wx, wy] = world[edge], r = (v) => Math.round(v * 98) / 10 + 0; + return [r(Math.cos(t) * wx + Math.sin(t) * wy), r(-Math.sin(t) * wx + Math.cos(t) * wy), 0]; + }; + const ipads = {}; + for (const wo of [0, 90, -90, 180]) for (const edge of Object.keys(world)) { + // (what iPadOS likely reports: its angle 0 in landscape, 90 in portrait; the type from the way up) + ipads[`wo${wo}/${edge}`] = { sa: wo === 0 || wo === 180 ? 90 : 0, wo, type: { 0: "portrait-primary", 90: "landscape-primary", "-90": "landscape-secondary", 180: "portrait-secondary" }[wo], + w: wo === 0 || wo === 180 ? 300 : 400, h: wo === 0 || wo === 180 ? 400 : 300, reading: iosReading(wo, edge), edge }; + } + // the user's three real readings (iPad, iPadOS 18.7, landscape: angle 0, landscape-primary, window.orientation 90) + const real = { flat: [-0.47, 0.44, -9.56], leftDown: [-0.18, 1.81, -9.48], topRaised: [-6.56, 0.06, -6.64] }; + for (const [name, reading] of Object.entries(real)) ipads[`real/${name}`] = { sa: 0, wo: 90, type: "landscape-primary", w: 400, h: 300, reading, edge: { flat: "flat", leftDown: "left", topRaised: "bottom" }[name] }; + // portrait with the angle iPadOS likely reports (90), window.orientation 0: the top raised must give down + ipads["portrait/topRaised"] = { sa: 90, wo: 0, type: "portrait-primary", w: 300, h: 400, reading: [0, -9.8, 0], edge: "bottom" }; + // no window.orientation: the orientation type (landscape-primary is 90 here, whatever the angle says) + ipads["type/leftDown"] = { sa: 0, wo: null, type: "landscape-primary", w: 400, h: 300, reading: iosReading(90, "left"), edge: "left" }; + ipads["type/secondaryLeftDown"] = { sa: 0, wo: null, type: "landscape-secondary", w: 400, h: 300, reading: iosReading(-90, "left"), edge: "left" }; + out.ipads = {}; + await Promise.all(Object.entries(ipads).map(async ([name, c]) => { + const p = await weatherPage(browser, url, { ...opts(c.sa), context: ipad(c.w, c.h), init: reported(c.sa, { windowOrientation: c.wo, type: c.type }) }); + await shake(p.page, ...c.reading); + out.ipads[name] = { edge: c.edge, tilt: await p.page.evaluate(() => Sky.state().tilt) }; + out.errors.push(...p.errors); + await p.context.close(); + })); + // ?tiltdebug=1: the readout of the raw numbers appears with a reading; without it, none + { + const dbg = await weatherPage(browser, url, { ...opts(90), query: (opts(90).query || "") + "?tiltdebug=1" }); + const off = await weatherPage(browser, url, opts(90)); + await shake(dbg.page, 1.5, 9.5, 0.5); await shake(off.page, 1.5, 9.5, 0.5); + out.debugText = await dbg.page.evaluate(() => (document.getElementById("tiltdebug") || {}).textContent || null); + const dbgIos = await weatherPage(browser, url, { ...opts(0), query: "?fx=humidity2&tiltdebug=1", context: ipad(400, 300), init: reported(0, { windowOrientation: 90, type: "landscape-primary" }) }); + await shake(dbgIos.page, -0.18, 1.81, -9.48); + out.debugIos = await dbgIos.page.evaluate(() => (document.getElementById("tiltdebug") || {}).textContent || null); + await dbgIos.context.close(); + out.debugOff = await off.page.evaluate(() => !document.getElementById("tiltdebug")); + await dbg.context.close(); await off.context.close(); + } + // no sensor reading: as ever (every bead straight down, no reading taken) + const none = await weatherPage(browser, url, opts(0)); + out.none = await run(none.page); + out.errors.push(...none.errors); + // (a reading with nothing in it, as a desktop browser's one empty event: ignored) + await none.page.evaluate(() => window.dispatchEvent(new DeviceMotionEvent("devicemotion", {}))); + out.empty = await none.page.evaluate(() => Sky.state().tilt); + await none.context.close(); + // the window's own rotation (window.orientation, the old way) when screen.orientation says nothing + const old = await weatherPage(browser, url, { ...opts(0), init: { fn: () => { + Object.defineProperty(window.screen, "orientation", { configurable: true, value: undefined }); + Object.defineProperty(window, "orientation", { configurable: true, value: 90 }); + }, arg: null } }); + await shake(old.page, 9.8, 0, 0); + out.oldWay = await run(old.page); + out.errors.push(...old.errors); + await old.context.close(); + // the animations low and off: no listener, nothing taken + out.ignored = {}; + for (const mode of ["low", "off"]) { + const p = await weatherPage(browser, url, { ...opts(0), query: "", animations: mode }); + await shake(p.page, -9.8, 0, 0); + out.ignored[mode] = await p.page.evaluate(() => ({ tilt: Sky.state().tilt, link: document.getElementById("tilt").textContent, running: Sky.state().running })); + out.errors.push(...p.errors); + await p.context.close(); + } + // ... and after "stop": ignored too, straight down again; a test link after it, the readings taken again + const stopped = await weatherPage(browser, url, opts(0)); + await shake(stopped.page, -9.8, 0, 0); + const before = await stopped.page.evaluate(() => Sky.state().tilt); + await stopped.page.click("#motion .animations"); + await shake(stopped.page, -9.8, 0, 0); + const after = await stopped.page.evaluate(() => Sky.state().tilt); + out.stopped = { before, after }; + out.errors.push(...stopped.errors); + await stopped.context.close(); + // an iPhone's (a touch screen, permission asked first, nothing sent till it's granted): the link a moment after, its permission + // asked from the tap, gone at once; granted, denied, an error; its sign the other way about (upright: y -9.8) + const ios = (answer) => ({ fn: ([answer]) => { + Object.defineProperty(window.screen.orientation, "angle", { configurable: true, get: () => 0 }); + Object.defineProperty(window, "orientation", { configurable: true, value: 0 }); // (iOS's rotation is window.orientation: upright) + const asked = window.__asked = []; + DeviceMotionEvent.requestPermission = () => { asked.push(1); return answer === "error" ? Promise.reject(new Error("no")) : Promise.resolve(answer); }; + }, arg: [answer] }); + const phone = { viewport: { width: 400, height: 300 }, hasTouch: true, isMobile: true, + userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1" }; + const seen = (page) => page.evaluate(() => ({ link: document.getElementById("tilt").textContent, asked: window.__asked.length, tilt: Sky.state().tilt })); + out.ios = {}; + for (const answer of ["granted", "denied", "error"]) { + const p = await weatherPage(browser, url, { ...opts(0), context: phone, init: ios(answer) }); + const early = await seen(p.page); // (not yet: it may be sent without asking) + await p.page.waitForSelector("#tilt .link"); + const was = await seen(p.page); + await p.page.click("#tilt .link"); + await p.page.waitForFunction(() => document.getElementById("tilt").textContent === ""); + await p.page.evaluate(() => new Promise((r) => setTimeout(r, 50))); + if (answer === "granted") await shake(p.page, 6, -7.7, 0); // (as sent: the pull to the device's right edge, upright) + out.ios[answer] = { early, was, now: await seen(p.page) }; + out.errors.push(...p.errors); + await p.context.close(); + } + // ... no link once readings came by themselves (it asks nothing, as Chrome's), nor with the animations low, nor on a desktop + const free = await weatherPage(browser, url, { ...opts(0), context: phone, init: ios("granted") }); + await shake(free.page, 0, 9.8, 0); + await free.page.evaluate(() => new Promise((r) => setTimeout(r, 1800))); + out.ios.free = await seen(free.page); + await free.context.close(); + const lowIos = await weatherPage(browser, url, { ...opts(0), query: "", animations: "low", context: phone, init: ios("granted") }); + await lowIos.page.evaluate(() => new Promise((r) => setTimeout(r, 1800))); + out.ios.low = await lowIos.page.evaluate(() => document.getElementById("tilt").textContent); + await lowIos.context.close(); + const desk = await weatherPage(browser, url, { ...opts(0), init: ios("granted") }); + await desk.page.evaluate(() => new Promise((r) => setTimeout(r, 1800))); + out.ios.desktop = await desk.page.evaluate(() => document.getElementById("tilt").textContent); + await desk.context.close(); + // the low-pass and the dead zone, in the weather's own terms (Sky.tilt(x, y, z, dt)): a turn eased in over time and held a + // moment, noise inside a few degrees (no change of epoch), 4 degrees of straight down kept straight, flat blended + const sky = await weatherPage(browser, url, opts(0)); + out.filter = await sky.page.evaluate(() => { + const t = () => Sky.state().tilt, seen = {}; + Sky.tilt(0, 9.8, 0); + seen.start = t(); + Sky.tilt(9.8, 0, 0, 0.05); // (a sudden 90 degree turn: a fifth of the way in 0.05 s at TAU 0.25) + seen.eased = [t().angle]; + for (let i = 0; i < 30; i++) Sky.tilt(9.8, 0, 0, 0.1); + seen.eased.push(t().angle); + const epoch = t().epoch; + for (let i = 0; i < 100; i++) Sky.tilt(9.8 + 0.1 * Math.sin(i), 0.1 * Math.cos(i * 1.7), 0, 0.03); // (a hand's tremor) + seen.still = { epoch: t().epoch - epoch, angle: t().angle }; + for (let i = 0; i < 30; i++) Sky.tilt(0.6, 9.8, 0, 0.1); // (3.5 degrees off straight down: down) + seen.snapped = t(); + for (let i = 0; i < 30; i++) Sky.tilt(9.8, 0, 0.1, 0.1); + for (let i = 0; i < 30; i++) Sky.tilt(0.5, 0.5, 9.8, 0.1); // (laid flat) + seen.flat = t(); + // (hysteresis: from flat, 6 degrees is still pooling, 8 runs, and then 6 runs still; the readings' size aside) + const at = (deg) => { const r = deg * Math.PI / 180; Sky.tilt(0, 3 * Math.sin(r), 3 * Math.cos(r), Infinity); return Sky.state().tilt.pool; }; + seen.hyst = [at(6), at(8), at(6), at(4)]; + seen.bad = [Sky.tilt(NaN, 1, 1), Sky.tilt(undefined, 1, 1), Sky.tilt(0, 0, 0)]; + Sky.level(); + seen.level = t(); + return seen; + }); + out.errors.push(...sky.errors); + await sky.context.close(); + // the screen's angle off level, theta (0 lying face up, 90 upright, 180 face down): the steepness sin(theta) is a speed factor (0 under + // 5 degrees: the water pools, beads stay and merge; smoothstep to 1 at 40; the same through 90 and down again to 0 at 180). The readings are + // (0, g sin, g cos) in any magnitude. Per angle: how fast the beads run (v against what the physics gives them: the factor), whether + // any ran, the merges and the largest bead (against the largest early on), and whether any left the window + const pools = {}; + out.pools = pools; + await Promise.all([0, 3, 180, 177, 10, 30, 60, 90, 120, 150, 175].map(async (theta) => { + const p = await weatherPage(browser, url, opts(0)); + pools[theta] = await p.page.evaluate((theta) => { + const g = theta === 3 ? 3 : 9.8, t = theta * Math.PI / 180; // (3: a weak reading of the same angle: only the ratio counts) + Sky.tilt(0, g * Math.sin(t), g * Math.cos(t)); + Sky.timeScale(30); + const out = { factor: 0, n: 0, ran: 0, early: 0, largest: 0, off: 0, trails: 0 }; + const stat = () => { + const h = Sky.state().humidity, [W, H] = Sky.state().size; + for (const b of h.beads) { + if (b.kind !== "fog") continue; + if (b.v > 0) { out.ran++; if (out.n < 400) { out.factor += b.v / h.physics.speed(b.r, b.glass); out.n++; } } + if (b.x < 0 || b.x > W || b.y >= H) out.off++; + out.largest = Math.max(out.largest, b.r); + } + return h; + }; + let n = 0, h0; + while (n++ < 600 && Sky.advance(1)) { h0 = stat(); if (n === 60) out.early = out.largest; } + const h = Sky.state().humidity; + return { ...out, factor: out.factor / Math.max(out.n, 1), merges: h.merges, ranOff: h.ranOff, beads: h.beads.length, tilt: Sky.state().tilt, trailsAfter: h.trails }; + }, theta); + out.errors.push(...p.errors); + await p.context.close(); + })); + // stop-start: flat (pooled) then tilted, several times over: each time a bead runs again its trail begins at once, from its own back edge + // (no gap, no half-length missing): within 2 px of travel its rows reach from where its top stood to its top now, with none missing + const restarts = []; + out.restarts = restarts; + await Promise.all([0, 1, 2, 3].map(async (edge) => { + const p = await weatherPage(browser, url, opts(0)); + const got = await p.page.evaluate((edge) => { + const g = 9.8, flat = () => Sky.tilt(0, 0, g, Infinity); + // (the downhill edge: 0 the bottom, 1 the top, 2 the left, 3 the right; the screen up, steepest, tipped that way) + const tip = () => Sky.tilt(...[[0, g, 0], [0, -g, 0], [-g, 0, 0], [g, 0, 0]][edge], Infinity); + Sky.timeScale(30); + const rows = []; + for (let cycle = 0; cycle < 5; cycle++) { + flat(); + for (let n = 0; n < 40; n++) Sky.advance(1); + const pooledTrails = Sky.state().humidity.trails; + tip(); + Sky.timeScale(3); + // (the beads that run: where each first ran from, then each step until one has moved 2 px along its way) + const h0 = Sky.state().humidity; + const start = new Map(), ids = new Set(h0.beads.filter((b) => b.kind === "fog" && !b.fading && b.r >= 1.5).map((b) => b.id)); + const done = new Set(), bad = []; + for (let n = 0; n < 600 && done.size < 6; n++) { + Sky.advance(1); + const h = Sky.state().humidity; + for (const b of h.beads) { + if (!ids.has(b.id) || done.has(b.id) || !(b.v > 0)) continue; + if (!start.has(b.id)) start.set(b.id, [b.x0, b.y0, Math.floor(b.y0) + b.bottom - Math.floor(b.y)]); // (its first running frame: where it set off from) + const [x0, y0, bottom0] = start.get(b.id), along = edge === 0 ? b.y - y0 : edge === 1 ? bottom0 - b.bottom : edge === 3 ? b.x - x0 : x0 - b.x; + if (along < 2 || along > 6) { if (along > 6) done.add(b.id); continue; } + done.add(b.id); + const tr = h.laidOf(b.id); + rows.push({ edge, cycle, id: b.id, along, rows: tr.length, ys: tr, y0, bottom0, x0, left0: Math.round(x0) - (b.w >> 1), right0: Math.round(x0) - (b.w >> 1) + b.w }); + } + } + Sky.timeScale(30); + rows.push({ edge, cycle, pooledTrails, trails: Sky.state().humidity.trails, mode: Sky.state().tilt.mode, ran: done.size, seen: ids.size }); + } + return rows; + }, edge); + restarts.push(...got); + out.errors.push(...p.errors); + await p.context.close(); + })); + }, + async gust(browser, url, out) { + const opened = (async () => { // (beside the rest) + const p = await weatherPage(browser, url, { query: "?fx=gust", driven: true }); + await drive(p.page, 30); + const seen = { ...await p.page.evaluate(() => ({ sent: Sky.state().gust.sent, kinds: Sky.state().gust.kinds, effects: Sky.state().effects })), + url: await p.page.evaluate(() => location.search), errors: p.errors }; + // ... and with an effect beside it (?fx=wind,gust): the wind on, nothing sent, only "wind" left in the URL + const q = await weatherPage(browser, url, { query: "?fx=wind,gust", driven: true }); + await drive(q.page, 30); + seen.beside = { ...await q.page.evaluate(() => ({ sent: Sky.state().gust.sent, effects: Sky.state().effects })), + url: await q.page.evaluate(() => location.search) }; + seen.errors = [...seen.errors, ...q.errors]; + await q.context.close(); + await p.context.close(); + return seen; + })(); + const phone = (async () => { + const p = await weatherPage(browser, url, { query: "?fx=all", driven: true, context: { viewport: { width: 360, height: 740 }, hasTouch: true, isMobile: true } }); + await p.page.locator("#fxtest button[data-gust]").click(); + const seen = { ...await cornerSeen(p.page), sent: await p.page.evaluate(() => Sky.state().gust.sent), errors: p.errors }; + await p.context.close(); + return seen; + })(); + const { context, page, errors, reads } = await weatherPage(browser, url, { driven: true }); + const sent = () => page.evaluate(() => Sky.state().gust.sent); + out.live = []; + for (const [gust, asOf] of [[99, "2026-11-16T10:00:00+11:00"], [99.1, "2026-11-16T10:01:00+11:00"], [99.1, "2026-11-16T10:01:00+11:00"], + [140, "2026-11-16T10:02:00+11:00"], [60, "2026-11-16T10:03:00+11:00"]]) { + await reads({ gust, asOf }); + out.live.push(await sent()); + } + out.liveKinds = await page.evaluate(() => Sky.state().gust.kinds); + out.liveEffects = await page.evaluate(() => Sky.state().effects); + // (the two on their way off first: the time on fast till they're gone) + await page.evaluate(() => Sky.timeScale(8)); + await driveUntil(page, () => !Sky.clock().running); + // a cow, a barn and a chicken at once, every frame till they're gone + out.crossing = await page.evaluate(() => new Promise((resolve) => { + Sky.timeScale(5); + const kinds = ["cow", "barn", "chicken"].map((k) => Sky.fling(k)), c = document.querySelector("#sky canvas"), g = c.getContext("2d"); + const tracks = { cow: [], barn: [], chicken: [] }, size = Sky.state().size; + const alphas = new Array(256).fill(0); // (the canvas's pixels by their alpha, while all three cross: how faint) + let frames = 0, inked = 0, effects = null, first = Sky.state().frames, last = first; + const look = () => { + const s = Sky.state(); + if (s.frames > last) { // (a frame drawn since the last look) + last = s.frames; + frames++; + for (const f of s.gust.flyers) tracks[f.kind].push([f.x, f.y, f.angle, f.turn, f.legs, f.size, s.clock]); + if (s.gust.flyers.length === 3 && frames % 8 === 1) { // (the canvas read now and then: reading it is slow) + effects = effects || s.effects; + const d = g.getImageData(0, 0, c.width, c.height).data; + let n = 0; + for (let i = 3; i < d.length; i += 4) if (d[i]) { n++; alphas[d[i]]++; } + inked = Math.max(inked, n); + } + } + if (s.running || frames === 0) return __next(look); + Sky.timeScale(1); + const all = alphas.reduce((a, b) => a + b, 0); + let median = 0; + for (let k = 0, n = 0; k < 256; k++) if ((n += alphas[k]) >= all / 2) { median = k; break; } + resolve({ kinds, tracks, size, frames, median, strong: alphas.slice(160).reduce((a, b) => a + b, 0) / all, inked, effects, after: s.gust, running: s.running, + ink: (() => { const d = g.getImageData(0, 0, c.width, c.height).data; let n = 0; for (let i = 3; i < d.length; i += 4) if (d[i]) n++; return n; })() }); + }; + __next(look); + })); + // (a frame's cost with the three crossing: sent again, a second on, its script's time; till they're gone) + await page.evaluate(() => ["cow", "barn", "chicken"].forEach((k) => Sky.fling(k))); + await drive(page, 30); + out.crossing.cost = await frameCost(page, 30); + await driveUntil(page, () => !Sky.clock().running); + // the test link: each click one, the three kinds in three clicks; the URL untouched (a reload sends none); never pressed; with + // an effect's link clicked after it, only that effect in the URL; "stop": gone at once + const before = await sent(); + for (let i = 0; i < 5; i++) await page.locator("#fxtest button[data-gust]").click(); + out.link = { sent: await sent() - before, kinds: (await page.evaluate(() => Sky.state().gust.kinds)).slice(-5), + flying: await page.evaluate(() => Sky.state().gust.flyers.length), url: await page.evaluate(() => location.search), + pressed: await page.evaluate(() => document.querySelector("#fxtest button[data-gust]").getAttribute("aria-pressed")), + classes: await page.evaluate(() => document.querySelector("#fxtest button[data-gust]").className) }; + await page.locator("#fxtest button[data-fx='wind']").click(); // (an effect on: "stop" shows) + out.link.afterWind = await page.evaluate(() => location.search); + await page.locator("#motion .animations").click(); + out.stopped = { ...await page.evaluate(() => ({ flyers: Sky.state().gust.flyers.length, running: Sky.state().running })), + url: await page.evaluate(() => location.search), ink: await canvasInk(page) }; + await reads({ gust: 150, asOf: "2026-11-16T10:30:00+11:00" }); // (stopped: a live gust over 99 km/h sends none) + out.stopped.sent = await sent() - before; + await page.locator("#fxtest button[data-gust]").click(); // (the test link after a stop: on again, one sent) + out.resumed = { sent: await sent() - before, running: await page.evaluate(() => Sky.state().running) }; + out.errors = errors; + await context.close(); + out.opened = await opened; + out.phone = await phone; + }, +}; + +const PARTED = { "--arrange": arrangeMode, "--touch": touchMode, "--zoom": zoomMode, "--zoom-touch": zoomTouchMode }; + +async function weatherMode(browser, url, part) { + const out = {}; + await WEATHER[part](browser, url, out); + process.stdout.write(JSON.stringify(out)); } (async () => { @@ -99,6 +3587,13 @@ async function arrive(browser, url, title) { try { if (second === "--live") await live(browser, url); else if (second === "--arrive") await arrive(browser, url, third); + else if (PARTED[second]) { // (PART, or several joined by "+": side by side, each its own page, a report each, in a list) + const reports = await Promise.all(third.split("+").map((part) => PARTED[second](browser, url, part))); + process.stdout.write(JSON.stringify(third.includes("+") ? reports : reports[0]) + "\n"); + } + else if (second === "--rotate") await rotateMode(browser, url); + else if (second === "--fill") await fillMode(browser, url, JSON.parse(third)); + else if (second === "--weather") await weatherMode(browser, url, third); else await sizes(browser, url, second, JSON.parse(third)); } finally { await browser.close();