diff --git a/.dockerignore b/.dockerignore index c4f0d639..a96c3414 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,9 +2,16 @@ # in the container: docker compose exec ecobot python scripts/...) * !ecobot.py +!ecobot_mcp/ +!irrigation_mcp/ !lib/ +!schemas/ !scripts/ !requirements.txt +!requirements-bot.txt +!requirements-mcp.txt +!requirements-irrigation.txt +!requirements-charts.txt # the commit the log says it is running is read from these (a clone; the files are a few hundred bytes) !.git/HEAD !.git/refs/heads/ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cd22f5e3..9defa924 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,12 +21,12 @@ concurrency: cancel-in-progress: true env: - TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} # optional: set both secrets to get failures as a Telegram message - TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }} + NOTIFY_TELEGRAM_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} # optional: set both secrets to get failures as a Telegram message (not the bot's + NOTIFY_TELEGRAM_CHAT: ${{ secrets.TELEGRAM_CHAT_ID }} # BOT_TELEGRAM_TOKEN setting: CI's own names) jobs: test: - # The gate: the exact versions in requirements.txt (the ones production runs), tests and chart images included. + # The gate: the exact versions in requirements.txt and requirements-charts.txt (the ones production runs), tests and chart images included. if: github.event_name != 'schedule' runs-on: ubuntu-latest steps: @@ -38,7 +38,7 @@ jobs: cache-dependency-path: requirements*.txt - run: pip install -r requirements-dev.txt - name: Tests - run: python -m pytest -q # pytest.ini runs them in parallel (-n auto) + run: python -m pytest -q -m "" # every test, the slow ones too; pytest.ini runs them in parallel (-n auto) - name: Prompt and routing evals run: python scripts/eval_prompts.py - name: Chart pictures that differ @@ -50,15 +50,15 @@ jobs: if-no-files-found: ignore retention-days: 14 - name: Tell me on Telegram (main only) - if: failure() && github.ref == 'refs/heads/main' && env.TELEGRAM_BOT_TOKEN != '' + if: failure() && github.ref == 'refs/heads/main' && env.NOTIFY_TELEGRAM_TOKEN != '' run: | - curl -fsS "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \ - --data-urlencode "chat_id=${TELEGRAM_CHAT_ID}" \ + curl -fsS "https://api.telegram.org/bot${NOTIFY_TELEGRAM_TOKEN}/sendMessage" \ + --data-urlencode "chat_id=${NOTIFY_TELEGRAM_CHAT}" \ --data-urlencode "text=CI failed on main: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" || true newest: # Advisory, never blocks: the same tests with the newest Pillow. If the chart pictures differ, a new release - # draws things differently: look at the artifact, then bump the pins in requirements.txt and run scripts/update_charts.py. + # draws things differently: look at the artifact, then bump the pin in requirements-charts.txt and run scripts/update_charts.py. if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest continue-on-error: true @@ -70,7 +70,7 @@ jobs: - run: pip install -r requirements-dev.txt && pip install --upgrade pillow - run: pip list | grep -i -E "^pillow " - name: Tests (not the chart pictures) - run: python -m pytest -q -m "not golden" + run: python -m pytest -q -m "not golden" # (the slow ones too: -m replaces pytest.ini's "not slow") - name: Chart pictures id: pictures continue-on-error: true @@ -84,15 +84,15 @@ jobs: if-no-files-found: ignore retention-days: 30 - name: Tell me on Telegram - if: (failure() || steps.pictures.outcome == 'failure') && env.TELEGRAM_BOT_TOKEN != '' + if: (failure() || steps.pictures.outcome == 'failure') && env.NOTIFY_TELEGRAM_TOKEN != '' run: | - curl -fsS "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \ - --data-urlencode "chat_id=${TELEGRAM_CHAT_ID}" \ + curl -fsS "https://api.telegram.org/bot${NOTIFY_TELEGRAM_TOKEN}/sendMessage" \ + --data-urlencode "chat_id=${NOTIFY_TELEGRAM_CHAT}" \ --data-urlencode "text=The newest Pillow changes something: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" || true live-evals: # Advisory, never blocks: asks the real model the few questions in tests/evals/weekly.txt and checks which tool it calls. Needs the - # repository secret OPENROUTER_API_KEY (skipped without it); OPENROUTER_MODEL is optional, for when production runs another model than deepseek/deepseek-v4.1-flash-1017. A failure is run once more before it is reported. + # repository secret OPENROUTER_API_KEY (skipped without it; the eval script's own names, not the bot's BOT_OPENROUTER_*); OPENROUTER_MODEL is optional, for when production runs another model than deepseek/deepseek-v4.1-flash-1017. A failure is run once more before it is reported. if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest continue-on-error: true @@ -115,8 +115,8 @@ jobs: if [ "$ALL_CASES" != "true" ]; then ids=(--ids "$(paste -sd, tests/evals/weekly.txt)"); fi python scripts/eval_prompts.py --live "${ids[@]}" || { echo "Failed: asking once more"; python scripts/eval_prompts.py --live "${ids[@]}"; } - name: Tell me on Telegram - if: failure() && env.TELEGRAM_BOT_TOKEN != '' + if: failure() && env.NOTIFY_TELEGRAM_TOKEN != '' run: | - curl -fsS "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \ - --data-urlencode "chat_id=${TELEGRAM_CHAT_ID}" \ + curl -fsS "https://api.telegram.org/bot${NOTIFY_TELEGRAM_TOKEN}/sendMessage" \ + --data-urlencode "chat_id=${NOTIFY_TELEGRAM_CHAT}" \ --data-urlencode "text=The model answers differently to the saved questions: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" || true diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 7891d7f3..80fd2a88 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -1,8 +1,8 @@ -name: Docker image +name: Docker images on: push: # any branch, so a pull request's commits carry the check too - paths: [Dockerfile, .dockerignore, requirements.txt, .github/workflows/docker.yml] + paths: [Dockerfile, .dockerignore, requirements.txt, requirements-bot.txt, requirements-mcp.txt, requirements-irrigation.txt, requirements-charts.txt, .github/workflows/docker.yml] workflow_dispatch: permissions: @@ -10,20 +10,37 @@ permissions: jobs: image: - # The image builds from the Dockerfile, the bot starts in it, and the charts it draws there are the approved ones, in Inter + # The three images build from the Dockerfile (each target's build imports its program, ecobot-mcp's with no Telegram and no model + # client in it, irrigation-mcp's with neither and no Pillow or source, the bot's with no Pillow, no source and none of + # irrigation-mcp's controller), each program starts in its image, and the charts ecobot-mcp draws are the approved ones, in Inter runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - - name: Build - run: docker build --build-arg COMMIT="$GITHUB_SHA" -t ecobot . + - name: Build ecobot-mcp + run: docker build --target ecobot-mcp --build-arg COMMIT="$GITHUB_SHA" -t ecobot-mcp . + - name: Build irrigation-mcp + run: docker build --target irrigation-mcp --build-arg COMMIT="$GITHUB_SHA" -t irrigation-mcp . + - name: Build ecobot (the bot) + run: docker build --target ecobot --build-arg COMMIT="$GITHUB_SHA" -t ecobot . + - name: ecobot-mcp starts and names this commit + run: | + docker run --rm --network none ecobot-mcp > start-mcp.log 2>&1 || true # stops: no data source set + cat start-mcp.log + grep -q "Starting ecobot-mcp ${GITHUB_SHA::7}" start-mcp.log + - name: irrigation-mcp starts and names this commit + run: | + docker run --rm --network none irrigation-mcp > start-irrigation.log 2>&1 || true # stops: no Tuya settings + cat start-irrigation.log + grep -q "Starting irrigation-mcp ${GITHUB_SHA::7}" start-irrigation.log - name: The bot starts and names this commit run: | - docker run --rm --network none -e TELEGRAM_BOT_TOKEN=0:x -e OPENROUTER_API_KEY=x ecobot > start.log 2>&1 || true # stops: no data source set + docker run --rm --network none -e BOT_TELEGRAM_TOKEN=0:x -e BOT_OPENROUTER_API_KEY=x ecobot > start.log 2>&1 || true # stops: no BOT_MCP_URL cat start.log grep -q "Starting ecobot ${GITHUB_SHA::7}" start.log - - name: Charts drawn in the image + - name: "Charts drawn in ecobot-mcp's image (the bot's draws none: it has no Pillow)" run: | - docker run --rm --network none -v "$PWD/tests:/app/tests:ro" ecobot python -c ' + for image in ecobot-mcp; do + docker run --rm --network none -v "$PWD/tests:/app/tests:ro" "$image" python -c ' from PIL import Image from lib import charts from tests import chart_samples, imagecmp @@ -32,8 +49,11 @@ jobs: share = imagecmp.difference(imagecmp.snapshot(make(), name.endswith("_dark")), Image.open(imagecmp.GOLDEN / f"{name}.png"))[0] assert share <= imagecmp.TOLERANCE, f"{name}: {share:.2%} of the pixels differ from tests/charts/{name}.png" print("Inter with semibold titles; every sample chart matches its reference image")' + done - name: Size run: | - unpacked=$(docker run --rm --network none --user 0 --entrypoint du ecobot -sx --apparent-size --block-size=1M / | cut -f1) - compressed=$(docker save ecobot | gzip -c | wc -c) - echo "The image: ${unpacked} MB unpacked, $((compressed / 1000000)) MB compressed" | tee -a "$GITHUB_STEP_SUMMARY" + for image in ecobot-mcp irrigation-mcp ecobot; do + unpacked=$(docker run --rm --network none --user 0 --entrypoint du "$image" -sx --apparent-size --block-size=1M / | cut -f1) + compressed=$(docker save "$image" | gzip -c | wc -c) + echo "The image ${image}: ${unpacked} MB unpacked, $((compressed / 1000000)) MB compressed" | tee -a "$GITHUB_STEP_SUMMARY" + done diff --git a/.gitignore b/.gitignore index fe6a78c5..c4098450 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ bot_state.json.tmp *.db *.db-* *.env +!docker/*.env mcp_ecowitt.json chart-diffs/ !tests/data/*.sqlite diff --git a/CLAUDE.md b/CLAUDE.md index ceb119cb..78b73de9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,4 +1,4 @@ # Working in this repo - **Iterating:** the "dev branch" is whichever branch the session is on, any branch except `main`. Keep using it between iterations: commit and push each change to it, so the user can pull it into their test environment. Never reset or recreate it. -- **Checks before pushing:** `python -m pytest -q` and `python scripts/eval_prompts.py` (see `DEVELOPMENT.md`). +- **Checks before pushing:** `python -m pytest -q -m ""` (every test, the slow ones too) and `python scripts/eval_prompts.py` (see `DEVELOPMENT.md`). diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index c4093606..257f4985 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -4,31 +4,158 @@ How to test the bot and what the GitHub checks do. (Running it is in `README.md` ## Tests ``` -pip install -r requirements-dev.txt -python -m pytest # runs in parallel (pytest.ini); `-n0` for one process -python scripts/eval_prompts.py # the saved questions: decisions made in code, no key needed +pip install -r requirements-dev.txt # requirements.txt (requirements-mcp.txt and requirements-bot.txt), requirements-charts.txt (Pillow) and pytest +python -m pytest # runs in parallel (pytest.ini); `-n0` for one process; the slow tests left out +python -m pytest -m "" # every test, the slow ones too (as CI runs them): before pushing +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 ``` -The suite takes about 25 s on four cores. The slowest fixture, the fake station's 18-month archive (`archived_cache` in `tests/conftest.py`), +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 +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`), is built once an hour and shared by the workers and by later runs: it lives under pytest's own temp folder (`/tmp/pytest-of-/ecobot-archive-*.sqlite`), named for the hour and for the code that shapes it, so a change to `lib/storage`, `lib/ecowitt` or `tests/fakes.py` rebuilds it. The first run after that pays about 15 s more. Tests of the archive itself use a station a few weeks old (`ecowitt_transport(history_days=...)`); the storage's reader and writer threads, and `asyncio.to_thread`, run inline in tests (the `threaded_storage` fixture puts the threads back for the tests of them). +The clock: most tests run at the real time, so some answers (just after midnight, late in the evening, on the 1st of a month or of the year) +are only tested when the suite happens to run then. To run the whole suite at such a time on purpose, set `ECOBOT_CLOCK` to a Melbourne +wall-clock time: the clock starts there and runs on, for lib/ and the tests, the archive included (`tests/clocks.py`): +``` +ECOBOT_CLOCK="2026-11-11 00:05" python -m pytest -q -m "" # also 23:55 or 23:59, and 00:05 on the 1st of a month and on 1 Jan +``` +A test whose answer depends on the time of day or the date pins its own clock instead: `daytime_archive` (2:05pm on Tue 10 Nov 2026) or +`pinned_archive(when)` with `clocks.pin(monkeypatch, when)`, the fake station's archive as it was then, built once for the code that shapes +it and kept (`ecobot-archive-pinned-*.sqlite`); a tool's answer to words alone can take `Context(clock=...)` (`clocks.yesterday_at`). + +The engines the service's tools wrap are tested directly where that is simpler: `tests/engines.py` drives the station's +`HistoryQuery`, `link()` and the air sensor's history and reading now. The old tools' handlers and the bot's old words, the oracle the +service was ported against, are gone (step 6c): `tests/test_history.py` and `tests/test_days.py` hold the service's `readings` and `days` +tools to the stored rows and the fake station's own figures, and current's words are pinned in `tests/current_words.json`. + The code targets Python 3.13.5 (`.python-version`). Claude Code sessions build the same Python into `.venv` with uv (`.claude/hooks/session-start.sh`). +## ecobot-mcp +ecobot-mcp, the MCP server on its own (`python -m ecobot_mcp`, the package `ecobot_mcp/`; [docs/ecobot-mcp.md](docs/ecobot-mcp.md) 3.8, +step 5): the sources and their syncers, the alert rules writing the alert log, and the MCP server (`lib/mcp_server.py`) at +`http://MCP_BIND/mcp` (Streamable HTTP, protocol 2026-07-28 and the older one). It reads the `MCP_` settings and the shared ones +([docs/configuration.md](docs/configuration.md)), the bot's (`BOT_`) not at all; its packages are `requirements-mcp.txt` (no Telegram, +no model client) and Pillow (`requirements-charts.txt`); the bot's are `requirements-bot.txt`; `requirements.txt` is both, for a +systemd install's one venv: +``` +set -a; . <(sudo cat /etc/ecobot.env); set +a # the settings +DATA_DIR=/tmp/ecobot python -m ecobot_mcp # http://127.0.0.1:8765/mcp +sudo docker compose up -d ecobot-mcp # in Docker (compose.yaml), on the host's port 8765 +``` +Every request needs a bearer token: one of `AUTH_TOKENS`, or, with that unset, the one it generates at its first start and keeps in +the data folder (`lib/auth_token.py`: `DATA_DIR/auth_token`, mode 0600, made whole and then linked into place; its path is logged, +never its value). Only one ecobot-mcp runs on a data folder: it holds `mcp.lock` there, so a second refuses to start. +Claude Code connects over HTTP: `claude mcp add --transport http ecobot http://127.0.0.1:8765/mcp --header "Authorization: Bearer $(cat /tmp/ecobot/auth_token)"`. +A client that shows pictures can have the charts as images: `http://127.0.0.1:8765/mcp?charts=png` (or, per call, request `_meta` +`chart_image: "png"`; docs 3.7). Pillow (`requirements-charts.txt`) is imported only then: installed from `requirements-mcp.txt` alone +ecobot-mcp answers with the charts' JSON and a `chart_image_note`, and warns once. +To look at it by hand: `npx @modelcontextprotocol/inspector` against the URL with the header `Authorization: Bearer `. + +Its tests: `tests/test_mcp_server.py` (the SDK's in-memory transport: every tool listed and answering as the ServiceTool does, each resource, +the alerts' template, the prompts, the publishing, the tokens; the chart images asked per call and, under uvicorn, by the URL's +`?charts=png`, without Pillow, and that importing the server imports no Pillow), `tests/test_mcp_listen.py` (the real app under uvicorn +on a free localhost port: a client that listens loses its listen when ecobot-mcp stops and reads what it missed when it is back; the +token and Host checks over HTTP; `python -m ecobot_mcp` with the fake sources, a tool call through a proxy's Host name), +`tests/test_settings.py` (each setting's owner prefix, the old names, the generated token, the bot reading only its own) and +`tests/test_packaging.py` (the two images, compose, the systemd units). + +### The bot as ecobot-mcp's client +The bot is only ever ecobot-mcp's client ([docs/ecobot-mcp.md](docs/ecobot-mcp.md) step 6b): `BOT_MCP_URL` is required (it stops at +start without it, saying to run ecobot-mcp and set it). It runs no sources, syncers or alert rules of its own, never opens the readings +file, reads none of the `MCP_` settings, and reaches ecobot-mcp over MCP +(`lib/weather.RemoteWeather`, [docs/ecobot-mcp.md](docs/ecobot-mcp.md) 3.8), sending the first of `AUTH_TOKENS`, or, with that unset, +the token ecobot-mcp generated in the data folder they share (read again for each connection, so the bot may start first; +`ecobot.mcp_token`): one client pinned to protocol 2026-07-28, kept by one supervisor task (`lib/upstream.Upstream`), which discovers by +hand for the instructions and listens to `ecobot://alerts` and `ecobot://station`; when the connection fails or the +listen is lost it builds a new client after a backoff, listens again and reads the alerts after the last id it handled. Everything the +bot asks for goes through `lib/weather.py`: the model's tools and instructions, the prompts it offers as commands, the keyboard's +charts (each a fixed call, `lib/templates.py` `CALLS`), the Status picture, the period buttons and the charts' other periods fetched in +the background, Help and `/usage` and the alerts (lib/alerts/notify.AlertDelivery). The bot answers no typed question in code (step 6c): everything typed goes to the model, and only +its reasoning effort is read from the words (`lib/intent.py`). +The bot draws nothing ([docs/ecobot-mcp.md](docs/ecobot-mcp.md) step 6a): every chart it sends comes drawn by ecobot-mcp +(`call_images`, `chart_image`: the remote one sends its PNGs, `chart_image: "png"` in the request's `_meta`, in the bot's own theme, +`chart_dark` from `DARKMODE`, `lib/theme.py`), the model's answers' charts too (the model is sent the text alone), and the Status +picture of three gauges is ecobot-mcp's `ecobot://status` (`lib/status.py`, drawn by `lib/gauges.py`), with the report it writes. Importing the bot, and building +it with both alert deliveries, imports neither Pillow nor `lib/charts.py`, `lib/draw.py` or `lib/gauges.py`, nor any source module +(`lib/ecowitt`, `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/storage`), nor irrigation-mcp's controller (`lib/irrigation/tuya`, +`watchdog`, `check`, `server`; `tests/test_bot.py`); its packages are `requirements-bot.txt` alone (python-telegram-bot, openai, mcp, +httpx), and its Docker image has nothing else. + +With `BOT_IRRIGATION_MCP_URL` the bot is irrigation-mcp's client too (below; `lib/irrigation_remote.RemoteIrrigation`, its own +`Upstream`, the same token): the Irrigation button, the menu (`lib/irrigation_menu.py`, the bot's UI) and the `ir:` buttons call its +tools through `status`/`water`/`delay`/`set_switch`, any failure an `IrrigationError` ("Couldn't reach the irrigation controller"), and a +second `AlertDelivery` reads `irrigation://alerts` (`lib/weather.RemoteAlerts` given its URI), its last id a `ReadMark` of its own in +`bot_state.json`. Without it the bot has no irrigation at all. +``` +set -a; . <(sudo cat /etc/ecobot.env); set +a +export DATA_DIR=/tmp/ecobot +python -m ecobot_mcp & # ecobot-mcp, with the sources' settings (it writes the token) +python -m irrigation_mcp & # irrigation-mcp, with the IRRIGATION_TUYA_ settings (optional) +BOT_MCP_URL=http://127.0.0.1:8765/mcp BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp python ecobot.py # the bot, their client +``` +In Docker (compose.yaml) this is how they run, each from its own image (the Dockerfile's targets `ecobot-mcp`, `ecobot` and +`irrigation-mcp`): +`ecobot-mcp` always, and the bot (the `bot` profile) as its client, its `BOT_MCP_URL` from docker/bot.env (the container's name, +`ecobot-mcp`; 127.0.0.1 with compose.host-network.yaml), the token from the data folder both mount. ecobot-mcp answers its own +hostname, so no `MCP_ALLOWED_HOSTS` is needed for the bot. irrigation-mcp is the `irrigation` profile (its own image, `irrigation-mcp`), and the bot +reaches it only with `BOT_IRRIGATION_MCP_URL=http://irrigation-mcp:8766/mcp` in /etc/ecobot.env (docker/bot.env leaves it empty). Under +systemd, `ecobot.service` wants `ecobot-mcp.service` and starts after it, and `irrigation-mcp.service` the same way when it is installed +(Wants= of a unit that isn't there changes nothing). + +Its tests run the bot against ecobot-mcp in memory: the `serve` fixture (`tests/served.py`) starts the real server +(`lib/mcp_server.EcobotServer`) over a test's Context (the fake sources, or none) or a test's stand-in tools (`tests.fakes.StandInService`, +with `sources=` naming the sources ecobot://station lists), and connects the bot's own client (`RemoteWeather`) to it through the SDK's +in-memory transport: `bot = Bot(cfg, agent, state, service=await serve(...))`. A test of the Telegram side alone, which asks ecobot-mcp +nothing, builds the bot over `tests.served.unreached()`. A keyboard button is `bot.press(update, context, sentence)`; a chart over +any period as a button answers it, `bot.respond(update, context, text, call=(tool, args))`. `tests/test_bot_remote.py` is the bot +against the real server (in memory: a question answered with the remote tools and the instructions from discover, ecobot-mcp's prompts +as Telegram commands, Status as one message (the gauges with the report as their caption), a chart from a remote result with its buttons, ecobot-mcp's +PNG of a chart byte for byte as its renderer draws it, an alert through the listen, irrigation-mcp's check's inputs; under uvicorn: a +dropped connection rebuilt and the alerts after the last id read once, ecobot-mcp down, `ecobot.main()`); `tests/test_startup.py` runs +both programs' main(): ecobot-mcp's over the fake sources, the bot's against ecobot-mcp (and irrigation-mcp) under uvicorn. The bot's +irrigation tests (`tests/test_irrigation.py`, `tests/test_admin_only.py`) run it against irrigation-mcp in memory the same way: the +`serve_irrigation` fixture starts its real server over the fake controller and connects the bot's `RemoteIrrigation` +(`irrigation.server.device` is the controller, `irrigation.server.watchdog` its watchdog). + +## irrigation-mcp +`python -m irrigation_mcp` (`irrigation_mcp/__main__.py`) is the irrigation controller's MCP server (docs/ecobot-mcp.md 3.9, step 8): +`lib/irrigation/server.py` (its four tools and `irrigation://alerts`, the low-level SDK as `lib/mcp_server.py`), `watchdog.py` and +`check.py` (the watchdog and the daily check it runs), `ecobot.py` (its client of ecobot-mcp, `lib/upstream.Upstream`), `state.py` +(`irrigation_state.json`), `tuya.py`, and `common.py` (what the bot's menu shares with it, without httpx: `lib/irrigation` loads nothing +until asked, so the bot importing `common` never loads Tuya). Under systemd it is `irrigation-mcp.service`, in Docker the +`irrigation-mcp` container. What it shares with ecobot-mcp over HTTP (the token and Host checks, the request log, uvicorn, the +generated token, the data folder's lock) is `lib/mcp_http.py`. It imports nothing of the bot's and none of ecobot-mcp's sources or tools +(`tests/test_irrigation_mcp.py` checks it in a subprocess, as the Docker build does). Its tests run its server over the SDK's in-memory +transport with a fake controller (`tests.fakes.FakeController`, or the fake Tuya cloud `FakeTuya`), and its daily check against +ecobot-mcp in memory (`tests/served.py`); the controller's own code (Tuya, the check, the watchdog) is tested without Telegram in +`tests/test_irrigation_controller.py`. + +### Settings +Each is a field of `lib/config.Config`, named for the program that reads it (`MCP_`, `IRRIGATION_`, `BOT_`, or none when all do; +docs/configuration.md), with its old name or names, newest first (`_setting(..., old=...)`, `old=("NEWER", "OLDER")`), still read when +the new one is unset and named in one warning at start. Scripts that read one directly use `lib.config.env(name)`, which knows the old names too. The test suite unsets every setting's +variable, new and old, before each test (`tests/conftest.py`). `scripts/eval_prompts.py --live` has its own names, `OPENROUTER_API_KEY`, +`OPENROUTER_BASE_URL` and `OPENROUTER_MODEL` (the CI secrets'), not the bot's `BOT_OPENROUTER_*`. + ## GitHub Actions (`.github/workflows/ci.yml`, and `docker.yml` for `image`) | Job | When | What | |---|---|---| -| `test` | every push to `main` and every pull request | the exact versions in `requirements.txt`: pytest (chart pictures included) and the offline evals. The gate. | +| `test` | every push to `main` and every pull request | the exact versions in `requirements.txt` and `requirements-charts.txt`: pytest (chart pictures included) and the offline evals. The gate. | | `newest` | Sundays 21:17 UTC, or the Run workflow button | the tests with the newest Pillow. Advisory. | -| `live-evals` | Sundays 21:17 UTC, or the Run workflow button | asks the real model the six questions in `tests/evals/weekly.txt` (`python scripts/eval_prompts.py --live`) and checks which tool it calls; a failure is asked once more before it is reported. Advisory. The button's "all cases" box asks all 87. Skipped until the secrets below exist. | -| `image` | pushes that change `Dockerfile`, `.dockerignore` or `requirements.txt` (any branch), or the Run workflow button | builds the Docker image, checks the bot starts in it and names the commit, draws the sample charts in it (they must be in Inter and match `tests/charts`); the image's size goes in the run's summary. | +| `live-evals` | Sundays 21:17 UTC, or the Run workflow button | asks the real model the six questions in `tests/evals/weekly.txt` as the bot asks it (`python scripts/eval_prompts.py --live`: its prompt and the ten tools) and checks which tool it calls against `tests/evals/service_cases.json`; a failure is asked once more before it is reported. Advisory. The button's "all cases" box asks all 94. Skipped until the secrets below exist. | +| `image` | pushes that change `Dockerfile`, `.dockerignore`, `requirements.txt`, `requirements-bot.txt`, `requirements-mcp.txt`, `requirements-irrigation.txt` or `requirements-charts.txt` (any branch), or the Run workflow button | builds the three Docker images (`ecobot-mcp`, `irrigation-mcp` and `ecobot`; each build imports its program, ecobot-mcp's with no Telegram or model client in it, irrigation-mcp's with neither and no Pillow or source, the bot's with no Pillow and no source module), checks each program starts in its image and names the commit, draws the sample charts in ecobot-mcp's (they must be in Inter and match `tests/charts`); the images' sizes go in the run's summary. | Repository secrets (Settings, Secrets and variables, Actions, New repository secret): - `OPENROUTER_API_KEY`: for `live-evals`. `OPENROUTER_MODEL` is optional (default `deepseek/deepseek-v4.1-flash-1017`): add it only if production runs another model. -- `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID`: optional; failures of `newest` and `live-evals`, and of `test` on `main`, are then sent to Telegram. +- `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID`: optional (CI's own: the workflow passes them on as `NOTIFY_TELEGRAM_TOKEN` and `NOTIFY_TELEGRAM_CHAT`, not the bot's settings); failures of `newest` and `live-evals`, and of `test` on `main`, are then sent to Telegram. Dependabot (`.github/dependabot.yml`) opens weekly pull requests for the Python packages and the actions. `Pillow` comes in a group of its own, because the chart pictures depend on it. ## Chart pictures -Ten fixed sample charts and dashboards (`tests/chart_samples.py`, made-up data, no clock) are drawn and compared with reference images in `tests/charts/` (`tests/test_chart_images.py`, marker `golden`). They are drawn with Pillow's own font (so they match on any machine; it lacks a few characters, such as ₂ and µ, shown as boxes there only), shrunk to 40% and cut to 64 colours, so each is 7 to 46 KB (about 220 KB in all). A chart passes when under 0.1% of its pixels differ noticeably; a failure leaves the new picture and a red-on-grey picture of the difference in `chart-diffs/` (CI uploads it as the `chart-diffs` artifact). After an intended change to how charts look, run `python scripts/update_charts.py` (or name charts: `... wind air`) and commit the changed images: GitHub shows old and new side by side in the pull request. `Pillow` is pinned in `requirements.txt` because the pictures depend on it (charts and the dashboard are drawn with it, `lib/draw.py`); a Dependabot update whose chart test fails is the cue to redo the images. +Ten fixed sample charts and the Status picture (`tests/chart_samples.py`, made-up data, no clock) are drawn and compared with reference images in `tests/charts/` (`tests/test_chart_images.py`, marker `golden`). They are drawn with Pillow's own font (so they match on any machine; it lacks a few characters, such as ₂ and µ, shown as boxes there only), shrunk to 40% and cut to 64 colours, so each is 7 to 46 KB (about 220 KB in all). A chart passes when under 0.1% of its pixels differ noticeably; a failure leaves the new picture and a red-on-grey picture of the difference in `chart-diffs/` (CI uploads it as the `chart-diffs` artifact). After an intended change to how charts look, run `python scripts/update_charts.py` (or name charts: `... wind air`) and commit the changed images: GitHub shows old and new side by side in the pull request. `Pillow` is pinned in `requirements-charts.txt` because the pictures depend on it (charts and the Status picture are drawn with it, `lib/draw.py`; ecobot-mcp needs it only for its pictures, the bot not at all, so it is a file of its own); a Dependabot update whose chart test fails is the cue to redo the images. diff --git a/Dockerfile b/Dockerfile index 3a1aa967..9a3f2478 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,40 +1,101 @@ -# The bot as a small image: python:3.13-slim with the runtime packages in a venv that has no pip, no pip cache and no test suites, -# and bytecode for only what the bot imports at start (bytecode for everything is 48 MB more; none adds ~2 s to every start). -# docker build -t ecobot . -# docker compose up -d --build (compose.yaml) +# Three images from one Dockerfile, each python:3.13-slim with its runtime packages in a venv that has no pip, no pip cache and no test +# suites, and bytecode for only what its program imports at start (bytecode for everything is 48 MB more; none adds ~2 s to every start): +# ecobot-mcp (target ecobot-mcp): python -m ecobot_mcp, the sources, the alert rules and the MCP server; requirements-mcp.txt and +# Pillow (requirements-charts.txt), no Telegram and no model client; +# ecobot (target ecobot, the default): the Telegram bot, python ecobot.py, a client of ecobot-mcp (BOT_MCP_URL) and, with +# BOT_IRRIGATION_MCP_URL, of irrigation-mcp; requirements-bot.txt +# alone (Telegram, the model's client, the MCP client, httpx): it draws nothing and runs no source, so no Pillow and no source's +# packages (docs/ecobot-mcp.md step 6b). +# irrigation-mcp (target irrigation-mcp): python -m irrigation_mcp, the irrigation controller's MCP server, its watchdog and daily +# check (docs/ecobot-mcp.md 3.9); requirements-irrigation.txt alone: no Telegram, no model client, no Pillow, no source. +# docker build --target ecobot-mcp -t ecobot-mcp . +# docker build --target irrigation-mcp -t irrigation-mcp . +# docker build --target ecobot -t ecobot . +# docker compose up -d --build (compose.yaml builds the ones its profiles run) # Settings come from the environment, as under systemd (README); the state and caches are kept in /data, the folder mounted from the host. FROM python:3.13-slim AS base -FROM base AS build +FROM base AS fonts # Inter for the charts, in the three weights they use (text, semibold titles, bold labels); the rest of the package stays here RUN apt-get update \ && apt-get install -y --no-install-recommends fonts-inter \ && mkdir /fonts \ && find /usr/share/fonts -name 'Inter-Regular.*' -o -name 'Inter-SemiBold.*' -o -name 'Inter-Bold.*' | xargs cp -t /fonts -COPY requirements.txt /tmp/ + # The base image's pip installs into a venv made without one +FROM base AS venv-mcp +COPY requirements-mcp.txt requirements-charts.txt /tmp/ +RUN python -m venv --without-pip /opt/venv \ + && pip --python /opt/venv/bin/python install --no-cache-dir --no-compile --root-user-action=ignore -r /tmp/requirements-mcp.txt -r /tmp/requirements-charts.txt \ + && find /opt/venv -type d -name tests -prune -exec rm -rf {} + + +FROM base AS venv-bot +COPY requirements-bot.txt /tmp/ +RUN python -m venv --without-pip /opt/venv \ + && pip --python /opt/venv/bin/python install --no-cache-dir --no-compile --root-user-action=ignore -r /tmp/requirements-bot.txt \ + && find /opt/venv -type d -name tests -prune -exec rm -rf {} + + +FROM base AS venv-irrigation +COPY requirements-irrigation.txt /tmp/ RUN python -m venv --without-pip /opt/venv \ - && pip --python /opt/venv/bin/python install --no-cache-dir --no-compile --root-user-action=ignore -r /tmp/requirements.txt \ + && pip --python /opt/venv/bin/python install --no-cache-dir --no-compile --root-user-action=ignore -r /tmp/requirements-irrigation.txt \ && find /opt/venv -type d -name tests -prune -exec rm -rf {} + -FROM base -COPY --from=build /opt/venv /opt/venv -COPY --from=build /fonts/ /usr/share/fonts/inter/ +# What they all run: the user, the fonts, the shared code. The program reads the running commit for its start-up log line from .git (HEAD, +# the branch's ref, packed-refs: .dockerignore lets only these through), so building from a clone needs nothing more; COMMIT, if given, +# is used instead (a build from files that are not a clone). +FROM base AS app +COPY --from=fonts /fonts/ /usr/share/fonts/inter/ RUN groupadd --system --gid 10001 ecobot \ && useradd --system --uid 10001 --gid 10001 --no-create-home --home-dir /data ecobot \ && mkdir /data && chown 10001:10001 /data WORKDIR /app -COPY ecobot.py ./ +COPY ecobot_mcp ecobot_mcp +COPY irrigation_mcp irrigation_mcp COPY lib lib +COPY schemas schemas COPY scripts scripts -ENV PATH=/opt/venv/bin:$PATH PYTHONUNBUFFERED=1 -# The bot reads the running commit for its start-up log line from .git (HEAD, the branch's ref, packed-refs: .dockerignore lets only these -# through), so building from a clone needs nothing more; COMMIT, if given, is used instead (a build from files that are not a clone). -# Importing the bot once writes the bytecode of every module it loads at start, and only those. COPY .git* .git/ ARG COMMIT= -RUN if [ -n "$COMMIT" ]; then echo "$COMMIT" > .git/HEAD; fi \ - && DATA_DIR=/tmp/build python -c "import lib.bot, ecobot" \ +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) +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; \ +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 +ENV DATA_DIR=/data +USER 10001:10001 +CMD ["python", "-m", "ecobot_mcp"] + +# irrigation-mcp. The same: the bytecode of what it loads at start, and a check that it needs nothing but its own packages and imports no +# Telegram, no model client, no Pillow and no source +FROM app AS irrigation-mcp +COPY --from=venv-irrigation /opt/venv /opt/venv +RUN DATA_DIR=/tmp/build python -c "import sys, importlib.util; import irrigation_mcp.__main__, lib.irrigation.server, lib.irrigation.check, \ +lib.irrigation.ecobot, lib.irrigation.state, lib.alert_log; \ +assert not [m for m in sys.modules if m.split('.')[0] in ('telegram', 'openai', 'PIL', 'ecobot_mcp') or m.startswith(('lib.ecowitt', \ +'lib.airgradient', 'lib.forecast', 'lib.pollen', 'lib.storage', 'lib.service', 'lib.mcp_server', 'lib.bot'))], 'irrigation-mcp imported another program'; \ +assert importlib.util.find_spec('telegram') is None and importlib.util.find_spec('PIL') is None" \ + && rm -rf /tmp/build +ENV DATA_DIR=/data +USER 10001:10001 +CMD ["python", "-m", "irrigation_mcp"] + +# The bot (the default target). The same: the bytecode of what it loads at start, and a check that it needs nothing but its own packages +# and imports no source, no drawing (no Pillow: it is not in this venv) and none of irrigation-mcp's controller (it is its client) +FROM app AS ecobot +COPY --from=venv-bot /opt/venv /opt/venv +COPY ecobot.py ./ +RUN DATA_DIR=/tmp/build python -c "import sys, importlib.util; import lib.bot, ecobot, lib.upstream, lib.weather, lib.irrigation_remote; \ +assert not [m for m in sys.modules if m.split('.')[0] == 'PIL' or m.startswith(('lib.ecowitt', 'lib.airgradient', 'lib.forecast', \ +'lib.pollen', 'lib.storage', 'lib.charts', 'lib.draw', 'lib.gauges', 'lib.irrigation.tuya', 'lib.irrigation.watchdog', \ +'lib.irrigation.check', 'lib.irrigation.server'))], 'the bot imported a source, the drawing or the irrigation controller'; \ +assert importlib.util.find_spec('PIL') is None" \ && rm -rf /tmp/build ENV DATA_DIR=/data USER 10001:10001 diff --git a/README.md b/README.md index d5c00c56..86ef28bc 100644 --- a/README.md +++ b/README.md @@ -19,25 +19,30 @@ A Telegram bot for your Ecowitt weather station and AirGradient air sensor. Ask - [Docker](#docker) - [Docker logging](#docker-logging) - [Docker networking](#docker-networking) + - [Irrigation](#irrigation) +- [Web dashboard](#web-dashboard) - [Upgrading](#upgrading) + - [Renamed settings](#renamed-settings) - [systemd](#systemd-1) - [Docker](#docker-1) - [Configuration](#configuration) ## Features -- **Ask in plain words:** "how hot is it?", "will it rain?", "how many days was UV over 9 this year?" +- **Ask in plain words:** "how hot is it?", "will it rain?", "how many days was UV over 9 this year?" Anything you type is answered by the AI model with ecobot-mcp's tools. - **Charts on request:** any reading, with 1D, 7D, 1M, 3M and 1Y buttons to change the period, or two readings on one chart with a scale each. -- **One-tap report:** `/report` shows weather, air quality, pollen and the forecast in one message, under gauges of the temperature, humidity and rain. `/dashboard` draws the station's gauges with the day's, month's and year's highs and lows. +- **Buttons for the usual:** in a private chat a keyboard of instant charts (Rain, Weather, Temperature, Humidity, Air Quality, Particulates, Wind), and Status: one message, a picture of the temperature, humidity and rain gauges with a report of the weather, air quality, forecast and pollen under it, and a 🔄 to read it again (no AI model: it's instant). Each is a command too (`/rain`, `/status` ...). +- **Commands from ecobot-mcp:** its prompts appear in Telegram's `/` menu: `/report`, `/now`, `/will_it_rain`, `/chart rain 7d`, `/rainfall last week` ... The words after the command fill the prompt in, and a prompt added to ecobot-mcp appears with no change to the bot. +- **Web dashboard:** the gauges as a live page in any browser on your network, laid out to fill a phone, a tablet or a screen. - **Alerts:** rain, strong gusts, high UV, unhealthy air and temperature changes. Silent unless you turn sound on. -- **Irrigation:** water or pause a Tuya controller from the chat, and have it paused automatically when rain has fallen or is forecast. -- **Cheap to run:** most answers are worked out by the bot itself, and the AI model is only called when it's needed. +- **Irrigation:** water or pause a Tuya controller from the chat, and have it paused automatically when rain has fallen or is forecast. The controller has an MCP server of its own, irrigation-mcp, which the bot (and any other MCP client) talks to. +- **A thin client:** the bot only talks to Telegram and the model; ecobot-mcp reads the sources, runs the alert rules and draws every picture. The buttons and alerts work without the model. ## Install Already installed? See [Upgrading](#upgrading). -You need a Telegram bot token from [@BotFather](https://t.me/BotFather), and optionally an [OpenRouter API key](https://openrouter.ai/keys) for questions that need the AI model. Either way, start by putting your keys in one private file: +You need a Telegram bot token from [@BotFather](https://t.me/BotFather), and optionally an [OpenRouter API key](https://openrouter.ai/keys) for typed questions and the `/report`-style commands (without one, the buttons and the alerts still work). Either way, start by putting your keys in one private file: ``` sudo install -m 600 -o root -g root /dev/null /etc/ecobot.env @@ -49,26 +54,33 @@ sudoedit /etc/ecobot.env ``` # Telegram bot token from @BotFather -TELEGRAM_BOT_TOKEN= +BOT_TELEGRAM_TOKEN= # Your Telegram user id (ask @userinfobot), so the bot answers you -ADMIN_CHAT_IDS= +BOT_ADMIN_CHAT_IDS= # AI model (optional) -OPENROUTER_API_KEY= +BOT_OPENROUTER_API_KEY= # Weather station (optional) -ECOWITT_API_KEY= -ECOWITT_APP_KEY= +MCP_ECOWITT_API_KEY= +MCP_ECOWITT_APP_KEY= # AirGradient sensor (optional) -AIRGRADIENT_API_TOKEN= -AIRGRADIENT_LOCATION_ID= +MCP_AIRGRADIENT_API_TOKEN= +MCP_AIRGRADIENT_LOCATION_ID= ``` +Settings that start with `MCP_` are read by ecobot-mcp (the part that fetches the readings and runs the alert rules), the ones that +start with `BOT_` by the Telegram bot, the `IRRIGATION_` ones by irrigation-mcp ([Irrigation](#irrigation), optional); the few without +any, such as `TZ`, by all of them. + ### systemd -Needs Python 3.13. +Needs Python 3.13. Two units run from one checkout and one venv: `ecobot-mcp` (`python -m ecobot_mcp`: the readings, the alerts, and an +MCP server at `http://127.0.0.1:8765/mcp` that the bot and [other MCP clients](#other-mcp-clients) use) and `ecobot`, the Telegram bot, +its client. The bot's unit pulls ecobot-mcp's in and starts after it. (A third, `irrigation-mcp`, is for an irrigation controller: +[Irrigation](#irrigation).) ``` sudo git clone https://github.com/robdevops/ecobot /opt/ecobot @@ -79,31 +91,50 @@ sudo python3.13 -m venv /opt/ecobot/.venv ``` ``` -sudo /opt/ecobot/.venv/bin/pip install -r /opt/ecobot/requirements.txt +sudo /opt/ecobot/.venv/bin/pip install -r /opt/ecobot/requirements.txt -r /opt/ecobot/requirements-charts.txt ``` +Tell the bot where ecobot-mcp is: add to `/etc/ecobot.env` (`sudoedit /etc/ecobot.env`) + ``` -sudo cp /opt/ecobot/ecobot.service /etc/systemd/system/ && sudo systemctl daemon-reload +BOT_MCP_URL=http://127.0.0.1:8765/mcp ``` +No token is needed between them: at its first start ecobot-mcp makes one and keeps it in the data folder +(`/var/lib/private/ecobot/auth_token`), where the bot reads it. To choose your own instead, set `AUTH_TOKENS=` (both read it; +the bot sends the first). + +Install both units, ecobot-mcp first: + ``` -sudo systemctl enable --now ecobot +sudo cp /opt/ecobot/ecobot-mcp.service /opt/ecobot/ecobot.service /etc/systemd/system/ && sudo systemctl daemon-reload +``` + +``` +sudo systemctl enable --now ecobot-mcp.service ecobot.service ``` Watch the logs: ``` -journalctl -fu ecobot +journalctl -fu ecobot-mcp -u ecobot ``` -Warnings and errors alone: `journalctl -p warning -u ecobot`. +Warnings and errors alone: `journalctl -p warning -u ecobot-mcp -u ecobot`. -Then message `/report` to your Telegram bot. +Both run sandboxed as one user of their own, and keep their data in `/var/lib/private/ecobot`. Check that they run as the same user +and the folder's owner is unchanged (the three numbers match): `systemctl show -p UID --value ecobot-mcp ecobot; stat -c %u /var/lib/private/ecobot`. +The token for [other MCP clients](#other-mcp-clients): `sudo cat /var/lib/private/ecobot/auth_token`. -The service runs sandboxed as its own user, and keeps its data in `/var/lib/private/ecobot`. +Then message `/status` to your Telegram bot. ### Docker +Docker runs two containers, each from its own image built from this repository: `ecobot-mcp` (the readings, the alerts, and an MCP +server that the bot and other AI clients use) and `ecobot`, the Telegram bot, which is optional (and a third, `irrigation-mcp`, with an +irrigation controller: [Irrigation](#irrigation)). No token is needed between them: at +its first start ecobot-mcp makes one and keeps it in the data folder, where the bot reads it. + ``` sudo mkdir -p /var/lib/private/ecobot && sudo chown -R 10001:10001 /var/lib/private/ecobot ``` @@ -116,26 +147,59 @@ sudo git clone https://github.com/robdevops/ecobot /opt/ecobot cd /opt/ecobot ``` +To run the Telegram bot too (leave this out for ecobot-mcp alone): + +``` +echo "COMPOSE_PROFILES=bot" | sudo tee -a /opt/ecobot/.env +``` + ``` sudo docker compose up -d --build ``` -Watch the logs: +Watch the logs: `sudo docker logs -tf ecobot-mcp` shows `MCP: http://...:8765/mcp`, and `sudo docker logs -tf ecobot` shows +`ecobot-mcp: connected`. Then message `/status` to your Telegram bot. + +Docker uses the same data folder as the systemd units, so you can switch between them, one at a time. To go back to systemd: +`sudo docker compose --profile bot down && sudo systemctl start ecobot-mcp ecobot`, with `BOT_MCP_URL=http://127.0.0.1:8765/mcp` added to +`/etc/ecobot.env`. Take that line out again before going back to Docker: Docker sets its own, and one in `/etc/ecobot.env` wins over it. +Only one ecobot-mcp runs on the data folder: a second stops at start, saying so in its log. + +#### Other MCP clients + +ecobot-mcp is published on port 8765 of every address your machine has, so other devices on your network (Claude Code on a laptop, +say) can use it with a token: the one it generated (`sudo cat /var/lib/private/ecobot/auth_token`), or, better, one each: set +`AUTH_TOKENS=,` in `/etc/ecobot.env` (made with `openssl rand -hex 16`; the bot sends the first, and a +token taken out is refused from the next start). Add your machine's IP address or name, as they write it in the URL, to +`MCP_ALLOWED_HOSTS`, e.g. `http://192.168.1.5:8765/mcp` needs `192.168.1.5`. For Claude Code: +`claude mcp add --transport http ecobot http://192.168.1.5:8765/mcp --header "Authorization: Bearer "`. It is plain HTTP: keep it +on your own network. Docker's published ports go around ufw's rules. To keep it to this machine only, change `8765:8765` in +`compose.yaml` to `127.0.0.1:8765:8765`. A client that shows pictures can have the charts as images: add `?charts=png` to its URL. + +#### Charts in LibreChat (and other chat apps): `?charts=link` + +Some clients (LibreChat, with an Ollama endpoint, say) don't show an image a tool sends, but do show a markdown image in the model's +reply. For those, add `?charts=link` to the MCP URL (`https://api.example.org/ecobot/mcp?charts=link`): each chart then comes as a +link to its picture, `/charts/.png` on ecobot-mcp's port, and the model is asked to put it in its reply as a markdown image. Your +browser loads the picture, so the link has to be one it can reach: set `MCP_CHART_BASE_URL` to where your reverse proxy serves +`/charts`, e.g. with nginx ``` -sudo docker logs -tf ecobot +location /ecobot-charts/ { proxy_pass http://127.0.0.1:8765/charts/; } ``` -Then message `/report` to your Telegram bot. - -Docker uses the same data folder as the systemd service, so you can switch between them, one at a time. To go back to systemd: `sudo docker rm -f ecobot && sudo systemctl start ecobot`. +and `MCP_CHART_BASE_URL=https://api.example.org/ecobot-charts`. Unset, the link is built from the address the MCP request came to +(the proxy's `X-Forwarded-Proto` and `X-Forwarded-Host` when it sends them) with `/charts`. The pictures need no token and answer any +`Host`: anyone who has a link can open it until it expires, so treat links as you would the chart itself. Each link's id is random +and unguessable; the pictures are kept in memory for `MCP_CHART_LINK_HOURS` (24 by default), at most 500 of them and 64 MB in all +(the oldest go first), and a restart of ecobot-mcp forgets them all (an old link then answers 404). #### Docker logging -Logs go to Docker's own rotated log; to send them to the journal instead (kept across upgrades, read with `journalctl -f CONTAINER_NAME=ecobot`): +Logs go to Docker's own rotated log; to send them to the journal instead (kept across upgrades, read with `journalctl -f CONTAINER_NAME=ecobot-mcp` or `CONTAINER_NAME=ecobot`): ``` -echo "COMPOSE_FILE=compose.yaml:compose.journald.yaml" | sudo tee /opt/ecobot/.env +echo "COMPOSE_FILE=compose.yaml:compose.journald.yaml" | sudo tee -a /opt/ecobot/.env ``` The bot writes warnings and errors to stderr and the rest to stdout, which Docker files in the journal at the priorities err and info, so `journalctl -p warning CONTAINER_NAME=ecobot` shows the warnings and errors alone. @@ -144,15 +208,139 @@ To use both this and [Docker host network](#docker-networking), set `COMPOSE_FIL #### Docker networking -`.local` names (mDNS) can't be found from Docker's private network: use IP addresses for config values, or reconfigure the container for host network (then run the `docker compose` command again): +`.local` names (mDNS) can't be found from Docker's private network: use IP addresses for config values, or put the containers on the host's network (then run the `docker compose` command again; the bot then reaches ecobot-mcp at 127.0.0.1, and irrigation-mcp, if you run it, with `BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp`): ``` -echo "COMPOSE_FILE=compose.yaml:compose.host-network.yaml" | sudo tee /opt/ecobot/.env +echo "COMPOSE_FILE=compose.yaml:compose.host-network.yaml" | sudo tee -a /opt/ecobot/.env ``` +`/opt/ecobot/.env` holds one `COMPOSE_FILE=` line: to use more than one of these files, list them all in it, separated by `:`. + +### Irrigation + +Optional, for a Tuya smart irrigation timer. The controller has its own program, **irrigation-mcp** (`python -m irrigation_mcp`): an +MCP server on port 8766 with the tools `irrigation_status`, `water`, `stop` and `delay`, which also closes the valve after every run +(even across a restart) and checks once a day, at 18:00, whether to pause watering for rain (asking ecobot-mcp for the rain measured and +the forecast) and whether the battery is low. The bot is its client: with `BOT_IRRIGATION_MCP_URL` set, the keyboard's Wind button +becomes 🌱 Irrigation (status, water for 5 to 30 minutes, switch off, pause for 24 to 72 hours) and its battery and pause alerts reach +the chats that want them. Without it the bot has no irrigation at all. + +Add the controller's Tuya cloud keys to `/etc/ecobot.env` ([docs/configuration.md](docs/configuration.md#irrigation-mcps-settings-irrigation_)): + +``` +IRRIGATION_TUYA_DEVICE_ID= +IRRIGATION_TUYA_CLIENT_ID= +IRRIGATION_TUYA_CLIENT_SECRET= +``` + +**systemd:** add `BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp` to `/etc/ecobot.env`, then install and start its unit beside the +others (the bot's unit starts after it when it is installed, and runs without it when it isn't): + +``` +sudo cp /opt/ecobot/irrigation-mcp.service /etc/systemd/system/ && sudo systemctl daemon-reload +``` + +``` +sudo systemctl enable --now irrigation-mcp.service && sudo systemctl restart ecobot +``` + +Its log: `journalctl -fu irrigation-mcp`. + +**Docker:** add `BOT_IRRIGATION_MCP_URL=http://irrigation-mcp:8766/mcp` to `/etc/ecobot.env`, and the `irrigation` profile to +`/opt/ecobot/.env` (`COMPOSE_PROFILES=bot,irrigation`), then `sudo docker compose up -d --build`. Its log: `sudo docker logs -tf +irrigation-mcp`. Leave `IRRIGATION_ECOBOT_MCP_URL` out of `/etc/ecobot.env`: Docker sets it to the ecobot-mcp container. + +## Web dashboard + +ecobot-mcp also serves the station's and the air sensor's gauges as a live web page at `/dashboard` on its port, e.g. `http://deb1:8765/dashboard` +(your machine's name or IP address). It shows every gauge with the day's, month's and year's highs and lows, drawn by the browser (plain HTML5, nothing fetched from +the internet), and fits every tile on the screen in portrait or landscape where they stay readable (on a phone it scrolls). It +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 +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, + 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, + 424), in the same colours; **PM1** on PM2.5's (it has no standard of its own, and is part of PM2.5); +- **CO₂** (ppm): there is no EPA standard, so the usual US indoor guidance (from ASHRAE's): under 800 good, 800-1000 fair, 1000-1500 + poor, 1500-2000 bad, 2000 and over very bad; +- **VOC index** and **NOx index**, when the monitor reports them (Sensirion's indices, learnt from its own air: VOC 100 is its + average, NOx 1 its baseline): VOC under 100 low, 100-150 average, then elevated, high (250) and very high (400); NOx up to 20 low, + then elevated, high (150) and very high (300). + +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 +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. + +A tile whose reading is missing just now (the station or the air sensor not sending it) is dimmed, its gauge at its floor (0, or the +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. + +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`. + +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. + ## Upgrading -Your keys in `/etc/ecobot.env` and the bot's data (`/var/lib/private/ecobot`) are kept. The log's first line, `Starting ecobot `, says which version is running. +Your keys in `/etc/ecobot.env` and the bot's data (`/var/lib/private/ecobot`) are kept; settings with an old name still work +([Renamed settings](#renamed-settings)). The log's first line, `Starting ecobot `, says which version is running. + +### Renamed settings + +In November 2026 every setting got the name of the program that reads it: `MCP_` for ecobot-mcp's, `BOT_` for the bot's, +`IRRIGATION_` for irrigation-mcp's, and none for the few all read. The old names still work: when a new name is unset and its old one is set, the old one is used, and the log says +once at start which to rename (never their values). Rename them in `/etc/ecobot.env` when convenient, by hand from the table, or with the script, which shows what it +would change (secrets masked) and changes the file only with `--write`, keeping a backup beside it: + +``` +sudo python3 /opt/ecobot/scripts/migrate_env.py /etc/ecobot.env +``` + +``` +sudo python3 /opt/ecobot/scripts/migrate_env.py /etc/ecobot.env --write +``` + +Then restart ecobot-mcp and the bot (and irrigation-mcp). Beyond the renames it moves `WEATHER_MCP_TOKEN` into `AUTH_TOKENS` (first, the token the bot +sends), changes the old container name `ecobot-service` in a URL or allowed host to `ecobot-mcp`, and, where the irrigation +controller's device id is set and `BOT_IRRIGATION_MCP_URL` isn't, adds `BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp` (systemd's; +`http://irrigation-mcp:8766/mcp` in a file that names ecobot-mcp's container, `ecobot-mcp` or `ecobot-service`, as Docker's do); it stops, changing nothing, where +an old and a new name are both set to different values. + + +| Old name | New name | +|---|---| +| `ECOWITT_API_KEY`, `ECOWITT_APP_KEY`, `ECOWITT_SOURCE` | `MCP_ECOWITT_API_KEY`, `MCP_ECOWITT_APP_KEY`, `MCP_ECOWITT_SOURCE` | +| `AIRGRADIENT_API_TOKEN`, `AIRGRADIENT_LOCATION_ID`, `AIRGRADIENT_DASHBOARD_URL`, `AIRGRADIENT_LOCAL_URL`, `AIRGRADIENT_SOURCE` | the same with `MCP_` in front | +| `HOMEASSISTANT_URL`, `HOMEASSISTANT_TOKEN` | `MCP_HOMEASSISTANT_URL`, `MCP_HOMEASSISTANT_TOKEN` | +| `PLACE`, `POLLEN`, `POLLEN_DISTRICT`, `FORECAST`, `FORECAST_LAT`, `FORECAST_LON` | the same with `MCP_` in front | +| `RAIN_QUIET_HOURS`, `ALERT_COOLDOWN_MINUTES`, `ANTISPIKE_REQUIRE_CONSECUTIVE` | the same with `MCP_` in front | +| `CHART_ALL_FEELS_LIKE`, `CHART_ALL_VPD` | `MCP_CHART_ALL_FEELS_LIKE`, `MCP_CHART_ALL_VPD` | +| `MCP_SERVICE_BIND`, `MCP_SERVICE_ALLOWED_HOSTS` | `MCP_BIND`, `MCP_ALLOWED_HOSTS` | +| `MCP_SERVICE_TOKENS` | `AUTH_TOKENS` | +| `TELEGRAM_BOT_TOKEN`, `TELEGRAM_PRELOAD_CHAT` | `BOT_TELEGRAM_TOKEN`, `BOT_TELEGRAM_PRELOAD_CHAT` | +| `OPENROUTER_API_KEY`, `OPENROUTER_BASE_URL`, `OPENROUTER_MODEL` | `BOT_OPENROUTER_API_KEY`, `BOT_OPENROUTER_BASE_URL`, `BOT_OPENROUTER_MODEL` | +| `ADMIN_ONLY`, `ADMIN_CHAT_IDS`, `LOG_WIDTH` | `BOT_ADMIN_ONLY`, `BOT_ADMIN_CHAT_IDS`, `BOT_LOG_WIDTH` | +| `TUYA_DEVICE_ID`, `TUYA_CLIENT_ID`, `TUYA_CLIENT_SECRET`, `TUYA_BASE_URL`, and their names with `BOT_` in front (November 2026) | the same with `IRRIGATION_` in front (irrigation-mcp's) | +| `BOT_IRRIGATION_CHECK_HOUR` (November 2026) | `IRRIGATION_CHECK_HOUR` again (irrigation-mcp's) | +| (none: the bot ran the controller itself) | `BOT_IRRIGATION_MCP_URL`, the bot's way to irrigation-mcp ([Irrigation](#irrigation)) | +| `WEATHER_MCP_URL` | `BOT_MCP_URL` | +| `WEATHER_MCP_TOKEN` | retired: the bot sends the first of `AUTH_TOKENS`. Still sent, with a warning, while `AUTH_TOKENS` is unset | + +`TZ`, `DATA_DIR`, `LOG_LEVEL` and `DARKMODE` keep their names. In Docker, `docker/bot.env` sets `BOT_MCP_URL`, so an old +`WEATHER_MCP_URL` in `/etc/ecobot.env` no longer overrides it: rename it if you set one. + +### Your data The weather station's and the air sensor's history lives in one file, `ecobot.sqlite`. A version from before 29 October 2026 kept it in `ecowitt_cache.sqlite`, the two files beside it, `airgradient_cache.sqlite` and `conditions_cache.sqlite`; the releases of that week moved them into the one file at start, so upgrade through one of those (commit 56a998c or earlier that week) if you still have the old files, then delete them. @@ -163,13 +351,49 @@ cd /opt/ecobot && sudo git pull ``` ``` -sudo /opt/ecobot/.venv/bin/pip install -r /opt/ecobot/requirements.txt +sudo /opt/ecobot/.venv/bin/pip install -r /opt/ecobot/requirements.txt -r /opt/ecobot/requirements-charts.txt ``` +Copy both units in again (they change now and then), then restart ecobot-mcp and the bot: + ``` -sudo systemctl restart ecobot +sudo cp /opt/ecobot/ecobot-mcp.service /opt/ecobot/ecobot.service /etc/systemd/system/ && sudo systemctl daemon-reload && sudo systemctl restart ecobot-mcp ecobot ``` +(Before November 2026 ecobot-mcp's unit ran `python -m ecobot_service`, its old name, and dropped the bot's secrets only by their old +names: an old unit not yet copied in still starts, with a warning in its log saying to copy the new one.) + +With [irrigation-mcp](#irrigation) installed, copy its unit in again too and restart it: +`sudo cp /opt/ecobot/irrigation-mcp.service /etc/systemd/system/ && sudo systemctl daemon-reload && sudo systemctl restart irrigation-mcp`. + +**From a bot that ran the irrigation controller itself (its `BOT_TUYA_...` or `TUYA_...` settings, before irrigation-mcp, November +2026):** the bot no longer runs the controller: irrigation-mcp does, and the bot is its client. Until you set it up the bot has no +Irrigation button and says so at start (nothing waters or pauses by itself meanwhile). After the `git pull` and `pip install` above, run +the [settings script](#renamed-settings) with `--write`: it renames the Tuya settings to `IRRIGATION_TUYA_...` and adds +`BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp`. Then install irrigation-mcp's unit and restart the bot, as in [Irrigation](#irrigation). +At its first start irrigation-mcp takes over the bot's watchdog and daily-check state from `bot_state.json` (a run the old bot started +is still closed, and no day is checked twice or skipped), and says so in its log. + +**From a bot that ran alone (no `ecobot-mcp.service` installed):** the bot no longer runs the sources and the alerts +itself: ecobot-mcp does, and the bot is its client. Without `BOT_MCP_URL` the new bot stops at start, saying so. Your `MCP_` settings +stay where they are: ecobot-mcp reads them from the same `/etc/ecobot.env` (the bot no longer does), and it uses the bot's data folder +(the readings, the alert log and the rules' state carry over; both units run as the same user). Back that up first: +`sudo cp -a /var/lib/private/ecobot /var/lib/private/ecobot.bak`. Then, after the `git pull` and `pip install` above: + +1. Add to `/etc/ecobot.env`: + ``` + BOT_MCP_URL=http://127.0.0.1:8765/mcp + ``` +2. Install ecobot-mcp's unit beside the bot's, and start it, then the bot: + ``` + sudo cp /opt/ecobot/ecobot-mcp.service /opt/ecobot/ecobot.service /etc/systemd/system/ && sudo systemctl daemon-reload + ``` + ``` + sudo systemctl enable --now ecobot-mcp.service && sudo systemctl restart ecobot + ``` +3. Check that both run as the same user and the folder's owner is unchanged (the three numbers match): + `systemctl show -p UID --value ecobot-mcp ecobot; stat -c %u /var/lib/private/ecobot` + ### Docker ``` @@ -177,32 +401,62 @@ cd /opt/ecobot && sudo git pull ``` ``` -sudo docker compose up -d --build +sudo docker rm -f ecobot-service 2>/dev/null; sudo docker compose up -d --build ``` -Compose replaces the container only if the image or the settings changed. To remove the old images and build cache that upgrades leave behind: +(The first part removes the container ecobot-mcp had before November 2026, `ecobot-service`, which would keep port 8765; once it's gone +it does nothing.) + +Compose replaces a container only if its image or settings changed. To remove the old images and build cache that upgrades leave behind: ``` sudo docker image prune -f && sudo docker builder prune -f ``` +**From the layout with a container named `ecobot-service` (November 2026):** that container is now `ecobot-mcp`, from an image of +its own (`ecobot-mcp`; the bot's is still `ecobot`). The command above removes the old container first, which would otherwise keep port 8765. + +Your token lines still work (`MCP_SERVICE_TOKENS` is read as `AUTH_TOKENS`, and `WEATHER_MCP_TOKEN` is ignored once that is set, with +a warning): rename `MCP_SERVICE_TOKENS` to `AUTH_TOKENS` and delete `WEATHER_MCP_TOKEN`, or delete both to use the token ecobot-mcp +generates. See [Renamed settings](#renamed-settings). + +**From a version before ecobot-mcp ran on its own (November 2026):** the bot ran everything itself; now `ecobot-mcp` does, and the +bot is its client, under the `bot` profile. Back up first (`sudo cp -a /var/lib/private/ecobot /var/lib/private/ecobot.bak`), remove +any `BOT_MCP_URL` (or `WEATHER_MCP_URL`) line from `/etc/ecobot.env` (Docker sets it), replace any `COMPOSE_PROFILES=service` in +`/opt/ecobot/.env` with `COMPOSE_PROFILES=bot` (or add it), then: + +``` +sudo docker compose --profile bot down && sudo docker compose up -d --build +``` + +**From a bot that ran the irrigation controller itself (its `BOT_TUYA_...` or `TUYA_...` settings, before irrigation-mcp, November +2026):** the controller is now the `irrigation-mcp` container's, under the `irrigation` profile, and the bot its client. Until it runs the +bot has no Irrigation button and says so at start. Rename the Tuya settings to `IRRIGATION_TUYA_...` (by hand, or with the +[settings script](#renamed-settings), which also adds `BOT_IRRIGATION_MCP_URL`, as `http://irrigation-mcp:8766/mcp` when the file names +ecobot-mcp's container), make sure `/etc/ecobot.env` has `BOT_IRRIGATION_MCP_URL=http://irrigation-mcp:8766/mcp`, +set `COMPOSE_PROFILES=bot,irrigation` in `/opt/ecobot/.env`, and run `sudo docker compose up -d --build`. At its first start +irrigation-mcp takes over the bot's watchdog and daily-check state from `bot_state.json`, and says so in its log. + ## Configuration Settings are environment variables in `/etc/ecobot.env`. The ones you're most likely to change: | Variable | What it does | |---|---| -| `TELEGRAM_BOT_TOKEN` | Required. | -| `ADMIN_CHAT_IDS` | Telegram user ids allowed to use the bot, besides the admins of groups it is in. | -| `OPENROUTER_API_KEY` | Enables the AI model. Without it the bot still does reports, charts, lookups and alerts. | -| `ECOWITT_API_KEY`, `ECOWITT_APP_KEY` | Weather station through Ecowitt's cloud. | -| `HOMEASSISTANT_URL`, `HOMEASSISTANT_TOKEN` | Weather station through Home Assistant (instead of the cloud, or with it as a fallback; `ECOWITT_SOURCE`). | -| `AIRGRADIENT_API_TOKEN`, `AIRGRADIENT_LOCATION_ID` | Air sensor, via AirGradient's cloud. | -| `AIRGRADIENT_LOCAL_URL` | Read the AirGradient sensor directly on your network e.g. `http://airgradient_.local` (use a fixed IP address for the URL in Docker, or see [Docker networking](#docker-networking)) | -| `AIRGRADIENT_SOURCE` | Where the air sensor's readings come from: `auto` (the default) is each that is set, the sensor itself first, then Home Assistant (if it has the sensor), then the cloud, each filling only what the ones before it lack; `local`, `homeassistant` or `cloud` is that one alone. | -| `POLLEN`, `FORECAST` | `on` to add pollen and thunderstorm asthma, or the daily forecast. | - -After editing the file, restart: `sudo systemctl restart ecobot`, or for Docker `sudo docker compose up -d --force-recreate` (`docker restart` keeps the old settings). +| `BOT_TELEGRAM_TOKEN` | Required. | +| `BOT_ADMIN_CHAT_IDS` | Telegram user ids allowed to use the bot, besides the admins of groups it is in. | +| `BOT_OPENROUTER_API_KEY` | Enables the AI model, which answers everything typed (and the prompt commands such as `/report`). Without it the buttons (their charts and the Status gauges) and the alerts still work, and a typed question is told the model isn't set up. | +| `MCP_ECOWITT_API_KEY`, `MCP_ECOWITT_APP_KEY` | Weather station through Ecowitt's cloud. | +| `MCP_HOMEASSISTANT_URL`, `MCP_HOMEASSISTANT_TOKEN` | Weather station through Home Assistant (instead of the cloud, or with it as a fallback; `MCP_ECOWITT_SOURCE`). | +| `MCP_AIRGRADIENT_API_TOKEN`, `MCP_AIRGRADIENT_LOCATION_ID` | Air sensor, via AirGradient's cloud. | +| `MCP_AIRGRADIENT_LOCAL_URL` | Read the AirGradient sensor directly on your network e.g. `http://airgradient_.local` (use a fixed IP address for the URL in Docker, or see [Docker networking](#docker-networking)) | +| `MCP_AIRGRADIENT_SOURCE` | Where the air sensor's readings come from: `auto` (the default) is each that is set, the sensor itself first, then Home Assistant (if it has the sensor), then the cloud, each filling only what the ones before it lack; `local`, `homeassistant` or `cloud` is that one alone. | +| `MCP_POLLEN`, `MCP_FORECAST` | `on` to add pollen and thunderstorm asthma, or the daily forecast. | +| `BOT_MCP_URL` | Required by the bot (systemd: `http://127.0.0.1:8765/mcp`; Docker sets it). ecobot-mcp's address: the bot is its client, fetches nothing and runs no alert rules itself, and reads none of the `MCP_` settings above. See [DEVELOPMENT.md](DEVELOPMENT.md#the-bot-as-ecobot-mcps-client). | +| `BOT_IRRIGATION_MCP_URL` | Optional: irrigation-mcp's address (systemd `http://127.0.0.1:8766/mcp`, Docker `http://irrigation-mcp:8766/mcp`), for the Irrigation button and its alerts. See [Irrigation](#irrigation). | +| `AUTH_TOKENS` | Optional. The tokens ecobot-mcp accepts (`token,token,...`, one per client); the bot sends the first. Unset, ecobot-mcp generates one at its first start and keeps it in the data folder (`auth_token`), where the bot reads it. | + +After editing the file, restart: `sudo systemctl restart ecobot-mcp ecobot`, or for Docker `sudo docker compose up -d --force-recreate` (`docker restart` keeps the old settings). Every setting is in [docs/configuration.md](docs/configuration.md). diff --git a/TELEGRAM_UX.md b/TELEGRAM_UX.md index 8173bc49..4a6d0581 100644 --- a/TELEGRAM_UX.md +++ b/TELEGRAM_UX.md @@ -1,5 +1,10 @@ # Telegram: using the bot by tapping (design) +> **Historical.** This is an early design, kept for its reasoning. Much of it was built differently and step 6 (docs/ecobot-mcp.md) changed +> the rest: nothing typed is answered in code any more (`intent.read`'s fast path is gone), `/report` and the other question commands are +> ecobot-mcp's prompts, the report written in code (and its 🔄) is gone, and Status is one message: ecobot-mcp's gauges with the report it writes (no model) under them, and a 🔄. +> What the bot does now: README.md and docs/features.md. + Not built yet. This is the plan for making commands and common questions tappable, in three phases. Each phase stands on its own. ## What exists today diff --git a/TODO.md b/TODO.md index 6bc9fde8..6465d74d 100644 --- a/TODO.md +++ b/TODO.md @@ -9,7 +9,7 @@ Does the sensor's `pm02Compensated` equal the cloud's `pm02_corrected`? Both rea meet the cloud's. When the air has real particles in it (smoke, incense, a dusty day), run these within a minute of each other, with `TOKEN` set to the -`AIRGRADIENT_API_TOKEN` and the sensor's address in place of the name if `.local` does not resolve: +`MCP_AIRGRADIENT_API_TOKEN` and the sensor's address in place of the name if `.local` does not resolve: ``` curl -s "https://api.airgradient.com/public/api/v1/locations/153523/measures/current?token=$TOKEN" | jq '{timestamp, pm02, pm02_corrected}' @@ -21,17 +21,17 @@ the interval) before deciding which to trust. ## Try on the real machines -- The sensor's own server: `AIRGRADIENT_LOCAL_URL` on a bot on the sensor's network. Check the log says "live readings from the sensor itself", that "air now" is +- The sensor's own server: `MCP_AIRGRADIENT_LOCAL_URL` on a bot on the sensor's network. Check the log says "live readings from the sensor itself", that "air now" is fresh, and that a chart of today has no step where the bot's readings begin. -- Without a cloud account (no `AIRGRADIENT_API_TOKEN`): nothing should be asked of the cloud, and the first charts only reach back to when the bot began recording. +- Without a cloud account (no `MCP_AIRGRADIENT_API_TOKEN`): nothing should be asked of the cloud, and the first charts only reach back to when the bot began recording. - `ecobot.service` as a real unit (`MemoryDenyWriteExecute`, `AF_NETLINK` for finding the sensor by name, `StateDirectory`, `CacheDirectory`): start it, then ask for a chart, an analysis question and something that reads the caches. - The Docker image with `zeroconf` in it: the `image` check on a pull request builds it. -- `ALERT_COOLDOWN_MINUTES` in the production env file: the default is now 60; a line setting it to 30 keeps 30. +- `MCP_ALERT_COOLDOWN_MINUTES` in the production env file: the default is now 60; a line setting it to 30 keeps 30. ## Try Home Assistant as the weather station's source, then redesign the storage -Set `HOMEASSISTANT_URL` and `HOMEASSISTANT_TOKEN` (and leave `ECOWITT_SOURCE` at `auto`, or try `homeassistant` with no Ecowitt keys) and run it for a week or two. +Set `MCP_HOMEASSISTANT_URL` and `MCP_HOMEASSISTANT_TOKEN` (and leave `MCP_ECOWITT_SOURCE` at `auto`, or try `homeassistant` with no Ecowitt keys) and run it for a week or two. It has only been run against a fake Home Assistant. Check in the log and the charts: - the start-up line says where the readings come from, and the live poll and minute pulls don't warn (or warn once and recover); - a chart of a few hours is drawn a reading a minute, a day or a week looks right, and a chart past Home Assistant's 10 days still has its bands (from the cache); @@ -41,4 +41,4 @@ It has only been run against a fake Home Assistant. Check in the log and the cha Then the storage redesign: [docs/storage-plan.md](docs/storage-plan.md) has the measurements, the design, the migration and the steps (the requirements that were here are its section 2, the decisions its section 6.1). Steps 0 and 1 are done (the measurements, and the new storage checked on the real cache); next is step 2, the station on it. Its step 4 takes the AirGradient's readings from the monitor itself first, -Home Assistant as the fallback and the cloud last (`AIRGRADIENT_SOURCE`; section 3.12 has how each source's PM2.5 is checked). +Home Assistant as the fallback and the cloud last (`MCP_AIRGRADIENT_SOURCE`; section 3.12 has how each source's PM2.5 is checked). diff --git a/compose.host-network.yaml b/compose.host-network.yaml index ae673a2e..ba69a0f2 100644 --- a/compose.host-network.yaml +++ b/compose.host-network.yaml @@ -1,3 +1,20 @@ services: + # On the host's network (its sources may be .local names), on port 8765 of every address the host has, as compose.yaml publishes + # it: the bot reaches it at http://127.0.0.1:8765/mcp, and other machines at the host's address. (No hostname of its own here: the + # host's name is its name, and it answers that.) + ecobot-mcp: + network_mode: host + hostname: !reset null + ports: !reset [] ecobot: network_mode: host + environment: + BOT_MCP_URL: http://127.0.0.1:8765/mcp + # irrigation-mcp (the `irrigation` profile) on the host's network too, on port 8766: it reaches ecobot-mcp at 127.0.0.1, and the bot + # reaches it with BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp in /etc/ecobot.env (not set here: the bot runs without it). + irrigation-mcp: + network_mode: host + hostname: !reset null + ports: !reset [] + environment: + IRRIGATION_ECOBOT_MCP_URL: http://127.0.0.1:8765/mcp diff --git a/compose.journald.yaml b/compose.journald.yaml index a6962faf..53889ca9 100644 --- a/compose.journald.yaml +++ b/compose.journald.yaml @@ -2,3 +2,9 @@ services: ecobot: logging: !override driver: journald + ecobot-mcp: + logging: !override + driver: journald + irrigation-mcp: + logging: !override + driver: journald diff --git a/compose.yaml b/compose.yaml index c30e7307..2d36c7ca 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,17 +1,94 @@ -# The bot in Docker: `sudo docker compose up -d --build` builds the image and starts the bot, and replaces a running one only when its -# image or settings changed (README). The commit the log's first line names is read from the clone's .git (see the Dockerfile). -# Logs: Docker's `local` driver (README: "Docker logging", compose.journald.yaml for the journal), which compresses and rotates its files (5 of 10 MB here); read them with `docker logs -tf ecobot`. +# ecobot in Docker (README). `sudo docker compose up -d --build` builds the images and starts ecobot-mcp; the Telegram bot is +# optional, under the `bot` profile: `sudo docker compose --profile bot up -d --build`, or COMPOSE_PROFILES=bot in /opt/ecobot/.env; +# so is irrigation-mcp, under the `irrigation` profile (COMPOSE_PROFILES=bot,irrigation for both). +# Three images from the one Dockerfile: ecobot-mcp (its target ecobot-mcp: no Telegram, no model client), irrigation-mcp (its own +# packages alone) and ecobot (the bot: its own packages alone, no Pillow and no source). +# Compose replaces a running container only when its image or settings changed. The commit the log's first line names is read from +# the clone's .git (see the Dockerfile). Logs: Docker's `local` driver (README: "Docker logging", compose.journald.yaml for the +# journal), which compresses and rotates its files (5 of 10 MB here); read them with `docker logs -tf ecobot-mcp` (or `ecobot`, +# `irrigation-mcp`). +# Settings (/etc/ecobot.env, docs/configuration.md): MCP_ ones are ecobot-mcp's, IRRIGATION_ ones irrigation-mcp's, BOT_ ones the bot's, +# the rest all read. services: + # ecobot-mcp, the MCP server (docs/ecobot-mcp.md 3.8, DEVELOPMENT.md "ecobot-mcp"): the sources and their syncers, the alert rules + # and the MCP server, on port 8765 of every address the host has, so other machines on the network can reach it too (plain HTTP, + # with a token; put TLS in front of it, e.g. Caddy, to reach it over the internet; for this host only, publish 127.0.0.1:8765:8765). + # Every request needs a token: one of AUTH_TOKENS (token,token,..., in /etc/ecobot.env), or, with that unset, the one it generates + # at its first start in the data folder (/var/lib/private/ecobot/auth_token on the host), which the bot reads from there. It answers + # its own name (hostname, below), 127.0.0.1 and localhost; MCP_ALLOWED_HOSTS adds more: the host's IP address or name, as LAN + # clients write it in their URL, and a proxy's name. + ecobot-mcp: + image: ecobot-mcp + container_name: ecobot-mcp + hostname: ecobot-mcp + build: + context: . + target: ecobot-mcp + args: + COMMIT: ${COMMIT:-} + restart: unless-stopped + # Docker's default network is private, where .local names (mDNS) can't be found (README: "Docker networking", compose.host-network.yaml) + env_file: /etc/ecobot.env + environment: + MCP_BIND: 0.0.0.0:8765 + ports: + - 8765:8765 + volumes: + - /var/lib/private/ecobot:/data + logging: + driver: local + options: + max-size: 10m + max-file: "5" + + # irrigation-mcp, the irrigation controller's MCP server (docs/ecobot-mcp.md 3.9), optional, under the `irrigation` profile: + # `sudo docker compose --profile irrigation up -d --build` (or COMPOSE_PROFILES=irrigation, or bot,irrigation, in /opt/ecobot/.env). + # It needs IRRIGATION_TUYA_DEVICE_ID, _CLIENT_ID and _CLIENT_SECRET in /etc/ecobot.env, runs the controller's watchdog and daily + # check, asks ecobot-mcp for the rain and the forecast (by its name on the project's network), and answers on port 8766 with the same + # tokens (AUTH_TOKENS, or the generated one in the data folder they share). Its state and alert log are kept in the same folder. + # The bot reaches it only with BOT_IRRIGATION_MCP_URL=http://irrigation-mcp:8766/mcp in /etc/ecobot.env (docker/bot.env leaves it + # empty: no Irrigation button without this container). IRRIGATION_ECOBOT_MCP_URL is set in docker/irrigation.env; a systemd value + # (127.0.0.1) in /etc/ecobot.env would win over it and point at this container itself: leave it out (it says so in its log). + irrigation-mcp: + image: irrigation-mcp + container_name: irrigation-mcp + hostname: irrigation-mcp + build: + context: . + target: irrigation-mcp + args: + COMMIT: ${COMMIT:-} + profiles: [irrigation] + restart: unless-stopped + depends_on: [ecobot-mcp] + env_file: [docker/irrigation.env, /etc/ecobot.env] + environment: + IRRIGATION_BIND: 0.0.0.0:8766 + ports: + - 8766:8766 + volumes: + - /var/lib/private/ecobot:/data + logging: + driver: local + options: + max-size: 10m + max-file: "5" + + # The Telegram bot, a client of ecobot-mcp (BOT_MCP_URL, docker/bot.env), sending the first of AUTH_TOKENS, or, with that unset, the + # token ecobot-mcp generated in the data folder they share; and, with BOT_IRRIGATION_MCP_URL set, of irrigation-mcp (the same token). + # It keeps its own state (chats, alert settings) in the same folder. ecobot: image: ecobot container_name: ecobot build: context: . + target: ecobot args: COMMIT: ${COMMIT:-} + profiles: [bot] restart: unless-stopped - # Docker's default network is private, where .local names (mDNS) can't be found (README: "Docker networking", compose.host-network.yaml) - env_file: /etc/ecobot.env + depends_on: [ecobot-mcp] + env_file: [docker/bot.env, /etc/ecobot.env] volumes: - /var/lib/private/ecobot:/data logging: diff --git a/docker/bot.env b/docker/bot.env new file mode 100644 index 00000000..d4d9eaa0 --- /dev/null +++ b/docker/bot.env @@ -0,0 +1,8 @@ +# The bot's defaults in Docker (compose.yaml reads this before /etc/ecobot.env, so a setting there wins): the bot is a client of +# the ecobot-mcp container, reached by its name on the project's network. +# (An old WEATHER_MCP_URL in /etc/ecobot.env no longer overrides this: rename it BOT_MCP_URL.) +BOT_MCP_URL=http://ecobot-mcp:8765/mcp +# irrigation-mcp (the `irrigation` profile): none by default, so no Irrigation button. With that container running, set +# BOT_IRRIGATION_MCP_URL=http://irrigation-mcp:8766/mcp in /etc/ecobot.env (a systemd install's http://127.0.0.1:8766/mcp would be the +# bot's own container here: the bot's log says so). +BOT_IRRIGATION_MCP_URL= diff --git a/docker/irrigation.env b/docker/irrigation.env new file mode 100644 index 00000000..f56f65bc --- /dev/null +++ b/docker/irrigation.env @@ -0,0 +1,3 @@ +# irrigation-mcp's defaults in Docker (compose.yaml reads this before /etc/ecobot.env, so a setting there wins): its daily check asks +# the ecobot-mcp container, reached by its name on the project's network. +IRRIGATION_ECOBOT_MCP_URL=http://ecobot-mcp:8765/mcp diff --git a/docs/configuration.md b/docs/configuration.md index 4bad7926..2be8c159 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1,6 +1,15 @@ # Configuration -The bot is configured only through environment variables. They live in one file, `/etc/ecobot.env`, which the systemd unit (`EnvironmentFile=`) and Docker (`--env-file`) both read. Each data source switches on when its variables are set. +ecobot is configured only through environment variables. They live in one file, `/etc/ecobot.env`, which the systemd units (`EnvironmentFile=`) and Docker (`env_file:`) read. Each data source switches on when its variables are set. + +Each setting is named for the program that reads it: + +- `MCP_...`: read by **ecobot-mcp** (`python -m ecobot_mcp`: the sources, the alert rules, the MCP server) alone. The bot, its client, doesn't read them. +- `IRRIGATION_...`: read by **irrigation-mcp** (`python -m irrigation_mcp`: the irrigation controller's MCP server, its watchdog and daily check) alone. The bot, its client (`BOT_IRRIGATION_MCP_URL`), doesn't read them. +- `BOT_...`: read by the **bot** (`ecobot.py`: Telegram, the model) alone. +- No prefix: read by **all** of them. + +Settings were renamed in November 2026 (README: [Renamed settings](../README.md#renamed-settings)), the irrigation controller's twice (`TUYA_...`, then `BOT_TUYA_...`, now `IRRIGATION_TUYA_...`). An old name still works when the new one is unset: it is used, and one warning at start names the new name (never the value). Where both are set, the new one wins and the old one is named as ignored (of two old names, the newer wins). Only the program that reads a setting reads its old names too: since step 8b the bot reads none of the irrigation controller's, by any name (irrigation-mcp does), so a bot left with `BOT_TUYA_...` and no `BOT_IRRIGATION_MCP_URL` has no Irrigation button and says so at start. ## The environment file @@ -11,71 +20,126 @@ sudo install -m 600 -o root -g root /dev/null /etc/ecobot.env sudoedit /etc/ecobot.env ``` -One `NAME=value` per line, no `export`; a line starting with `#` is a comment (not text after a value). systemd reads it as root before it drops to the service's own user, so the service itself needs no access to the file, and nobody else on the machine can read your keys. To run the bot by hand from your own shell, load it with `set -a; . <(sudo cat /etc/ecobot.env); set +a`. (Docker reads the file as the person who runs `docker`, so use `sudo docker compose`, or give your user read access with `sudo chown root:youruser /etc/ecobot.env && sudo chmod 640 /etc/ecobot.env`. It also keeps quotes around a value that systemd would drop.) - -## Settings +One `NAME=value` per line, no `export`; a line starting with `#` is a comment (not text after a value). systemd reads it as root before it drops to the unit's own user, so the programs themselves need no access to the file, and nobody else on the machine can read your keys. ecobot-mcp's unit drops the bot's secrets (`UnsetEnvironment=`). To run the bot by hand from your own shell, load it with `set -a; . <(sudo cat /etc/ecobot.env); set +a`. (Docker reads the file as the person who runs `docker`, so use `sudo docker compose`, or give your user read access with `sudo chown root:youruser /etc/ecobot.env && sudo chmod 640 /etc/ecobot.env`. It also keeps quotes around a value that systemd would drop.) `on|off` values: `on yes true 1` / `off no false 0`. Any other value → default (logged). Blank → default. -### Required and model +## ecobot-mcp's settings (`MCP_`) + +At least one of Ecowitt (cloud or Home Assistant) or AirGradient (cloud, local or Home Assistant) must be configured. + +### Sources | Variable | Default | Description | |---|---|---| -| `TELEGRAM_BOT_TOKEN` | – | Required. Bot token (@BotFather) | -| `OPENROUTER_API_KEY` | – | [OpenRouter](https://openrouter.ai/keys) API key. Unset → no model: `/report`, chart commands, plain lookups ("how hot is it?", "rain chart 7d", "forecast") and all alerts work; anything needing the model gets a "no model" reply | -| `OPENROUTER_MODEL` | `deepseek/deepseek-v4.1-flash-1017` | Model, by its OpenRouter name | -| `OPENROUTER_BASE_URL` | `https://openrouter.ai/api/v1` | API endpoint | +| `MCP_ECOWITT_API_KEY`, `MCP_ECOWITT_APP_KEY` | – | Enables Ecowitt through its cloud. Station's time zone is used | +| `MCP_ECOWITT_SOURCE` | `auto` | Where the station's readings come from. `auto`: Home Assistant if `MCP_HOMEASSISTANT_URL`/`TOKEN` are set, with Ecowitt's cloud (if its keys are set too) making up what it lacks; `cloud`: Ecowitt's cloud only; `homeassistant`: Home Assistant only (no Ecowitt keys needed) | +| `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_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 | +| `MCP_POLLEN_DISTRICT` | `Central` | East Gippsland, Mallee, North Central, North East, Northern Country, South West, West and South Gippsland, Wimmera. Case-insensitive; unknown → warning | +| `MCP_FORECAST` | `off` | Open-Meteo daily forecast: report, `weather_forecast` tool, forecast-change alert | +| `MCP_FORECAST_LAT`, `MCP_FORECAST_LON` | station's | Forecast location | -At least one of Ecowitt, AirGradient (cloud or local) must be configured. +### Alerts -### Sources +| Variable | Default | Description | +|---|---|---| +| `MCP_ALERT_COOLDOWN_MINUTES` | `60` (5–150) | Rain: dry time before "stopped" (rain that starts again sooner is the same spell; "started" is never held). Temperature crossing: minimum gap between alerts; a change inside the cooldown is held, then sent if still different | +| `MCP_RAIN_QUIET_HOURS` | `0-6` | Local hours with no rain alerts; summarised afterwards. `22-6` wraps midnight, `off` disables | +| `MCP_ANTISPIKE_REQUIRE_CONSECUTIVE` | `2` | Readings in a row a PM1/PM2.5/PM10 rise needs to count (spike ≥ 2.5× and +5 µg/m³ over neighbours otherwise dropped from charts, figures, unhealthy-air alert). `1` / `off` disables. Live "air now" unaffected | + +### Charts + +| Variable | Default | Description | +|---|---|---| +| `MCP_CHART_ALL_FEELS_LIKE` | `off` | Add feels-like panel to "weather all week" | +| `MCP_CHART_ALL_VPD` | `off` | Add VPD panel to "weather all week" | + +### The MCP server + +`python -m ecobot_mcp` ([ecobot-mcp.md](ecobot-mcp.md) 3.8, `DEVELOPMENT.md`): | Variable | Default | Description | |---|---|---| -| `ECOWITT_API_KEY`, `ECOWITT_APP_KEY` | – | Enables Ecowitt through its cloud. Station's time zone is used | -| `ECOWITT_SOURCE` | `auto` | Where the station's readings come from. `auto`: Home Assistant if `HOMEASSISTANT_URL`/`TOKEN` are set, with Ecowitt's cloud (if its keys are set too) making up what it lacks; `cloud`: Ecowitt's cloud only; `homeassistant`: Home Assistant only (no Ecowitt keys needed) | -| `AIRGRADIENT_API_TOKEN`, `AIRGRADIENT_LOCATION_ID` | – | Enables AirGradient via cloud API: history and gap fill | -| `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 | -| `HOMEASSISTANT_URL`, `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 bot reads the readings back to shade the recent charts between each 5 minutes' lowest and highest, for the days it 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 `ECOWITT_SOURCE`): minute lines, a live reading every few seconds and rain alerts as the gauge reports; without them the shading comes from the bot's own readings | -| `AIRGRADIENT_DASHBOARD_URL` | – | "live chart" link in air replies and alerts | -| `TZ` | system zone | Only used without Ecowitt (the station's zone wins; a mismatch is logged). IANA name, e.g. `Australia/Melbourne` | -| `PLACE` | `Melbourne` | Name in the Pollen & asthma and Forecast headings | -| `POLLEN` | `off` | Melbourne grass pollen + thunderstorm asthma (melbournepollen.com.au): report, `pollen_asthma` tool, alert at High. Oct–Dec only | -| `POLLEN_DISTRICT` | `Central` | East Gippsland, Mallee, North Central, North East, Northern Country, South West, West and South Gippsland, Wimmera. Case-insensitive; unknown → warning | -| `FORECAST` | `off` | Open-Meteo daily forecast: report, `weather_forecast` tool, forecast-change alert | -| `FORECAST_LAT`, `FORECAST_LON` | station's | Forecast location | -| `TUYA_DEVICE_ID`, `TUYA_CLIENT_ID`, `TUYA_CLIENT_SECRET` | – | Enables the irrigation controller (Tuya cloud): Irrigation button, rain delay check, pause/battery alerts | -| `TUYA_BASE_URL` | `https://openapi.tuyaeu.com` | Tuya data centre | -| `IRRIGATION_CHECK_HOUR` | `18` | Local hour of the daily rain-delay check (0–23) | +| `MCP_BIND` | `127.0.0.1:8765` | `host:port` it listens on (`[::1]:8765` for IPv6; Docker sets `0.0.0.0:8765`). Serve it to other machines through TLS (a reverse proxy such as Caddy) | +| `MCP_ALLOWED_HOSTS` | none | More `Host` names it answers, besides `127.0.0.1`, `localhost` and its own hostname (in Docker, `ecobot-mcp`), any port unless one is given (`weather.lan`, `192.168.1.5:8765`); any other is refused (421), against DNS rebinding. Add the name or IP address a proxy or a LAN client uses | +| `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/data` and `/dashboard/events` answer 404 | + +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. + +## The bot's settings (`BOT_`) + +### Telegram and the model + +| Variable | Default | Description | +|---|---|---| +| `BOT_TELEGRAM_TOKEN` | – | Required by the bot (not by ecobot-mcp). Bot token (@BotFather) | +| `BOT_OPENROUTER_API_KEY` | – | [OpenRouter](https://openrouter.ai/keys) API key. Everything typed, and ecobot-mcp's prompts as commands (`/report`, `/chart` ...), go to the model. Unset → no model: the buttons and their commands (the charts, Status's gauges) and all alerts work; a typed question gets one line saying the model isn't set up | +| `BOT_OPENROUTER_MODEL` | `deepseek/deepseek-v4.1-flash-1017` | Model, by its OpenRouter name | +| `BOT_OPENROUTER_BASE_URL` | `https://openrouter.ai/api/v1` | API endpoint | +| `BOT_TELEGRAM_PRELOAD_CHAT` | off | Chat id (negative: group/channel) to pre-upload charts to. After a chart is sent, its other periods are always fetched from ecobot-mcp in the background; with this set they are uploaded here too, so a period button sends Telegram's copy. Bot must be able to post there. Copies used for 30 min. Refused upload → no retry until restart | +| `BOT_LOG_WIDTH` | `24` | Characters of a chat message kept in the log, then `…`; `0` keeps all. No other line is cut | ### Access | Variable | Default | Description | |---|---|---| -| `ADMIN_ONLY` | `off` | `on`: answer only admins/creators of groups the bot is in. Others get "only group admins" when addressed. `/alerts` is openable by anyone in a group (changes stay admin-only). Admin list cached 10 min | -| `ADMIN_CHAT_IDS` | – | Extra allowed ids, comma/space separated. User id: allowed before any group exists. Group id (negative): adds its admins and anonymous admins | +| `BOT_ADMIN_ONLY` | `off` | `on`: answer only admins/creators of groups the bot is in. Others get "only group admins" when addressed. `/alerts` is openable by anyone in a group (changes stay admin-only). Admin list cached 10 min | +| `BOT_ADMIN_CHAT_IDS` | – | Extra allowed ids, comma/space separated. User id: allowed before any group exists. Group id (negative): adds its admins and anonymous admins | -### Alerts + +### The bot as ecobot-mcp's client | Variable | Default | Description | |---|---|---| -| `ALERT_COOLDOWN_MINUTES` | `60` (5–150) | Rain: dry time before "stopped" (rain that starts again sooner is the same spell; "started" is never held). Temperature crossing: minimum gap between alerts; a change inside the cooldown is held, then sent if still different | -| `RAIN_QUIET_HOURS` | `0-6` | Local hours with no rain alerts; summarised afterwards. `22-6` wraps midnight, `off` disables | -| `ANTISPIKE_REQUIRE_CONSECUTIVE` | `2` | Readings in a row a PM1/PM2.5/PM10 rise needs to count (spike ≥ 2.5× and +5 µg/m³ over neighbours otherwise dropped from charts, figures, unhealthy-air alert). `1` / `off` disables. Live "air now" unaffected | +| `BOT_MCP_URL` | required (Docker: `http://ecobot-mcp:8765/mcp`) | ecobot-mcp's endpoint (systemd: `http://127.0.0.1:8765/mcp`; or its TLS address behind a proxy). The bot is only ever ecobot-mcp's client ([ecobot-mcp.md](ecobot-mcp.md) steps 5 and 6b): it starts no sources, syncers or alert rules of its own and never opens the readings file, so the `MCP_` settings are ecobot-mcp's and the bot reads none of them; its tools, the server's instructions, the station (time zone, sensors, which alerts there are), the alerts and every picture come from ecobot-mcp. Unset: the bot stops at start, saying to run ecobot-mcp and set it | -### Charts +The bot asks ecobot-mcp for the picture of every chart it sends, the model's answers' included (request `_meta` `chart_image: "png"`, in its own `DARKMODE` theme), and for the Status picture (`ecobot://status`), so its `BOT_MCP_URL` needs no `?charts=png`; it draws nothing itself. + +While ecobot-mcp can't be reached the bot tells whoever asks so, and reconnects by itself (1, 2, 5, 10, then every 30 seconds); the +alerts sent meanwhile that are still news are delivered once it is back. + +### The bot as irrigation-mcp's client | Variable | Default | Description | |---|---|---| -| `CHART_ALL_FEELS_LIKE` | `off` | Add feels-like panel to "weather all week" | -| `CHART_ALL_VPD` | `off` | Add VPD panel to "weather all week" | -| `TELEGRAM_PRELOAD_CHAT` | off | Chat id (negative: group/channel) to pre-upload charts to: the other periods of each chart asked for, and, while the bot has been used in the last 15 minutes, the keyboard's charts every 5 minutes. Bot must be able to post there. Copies used for 30 min. Refused upload → no retry until restart | -| `DARKMODE` | `off` | The charts' colours. `off`: light; `on`: dark; a time range, e.g. `8pm-8am`, `20:00-8:00` or `20-8`: dark between those times in the bot's time zone (the weather station's), light the rest of the day. The dashboard's gauges are dark whatever this says. | +| `BOT_IRRIGATION_MCP_URL` | none: no irrigation in the bot | irrigation-mcp's endpoint (below): systemd `http://127.0.0.1:8766/mcp`, Docker `http://irrigation-mcp:8766/mcp` (Docker's `docker/bot.env` leaves it empty, so set it in `/etc/ecobot.env` when you run the `irrigation` profile; on the host's network, `compose.host-network.yaml`, it is `http://127.0.0.1:8766/mcp`). Set, the bot is irrigation-mcp's client as it is ecobot-mcp's (the same token): the keyboard's Irrigation button (in Wind's place), typing "irrigation" or "water", the irrigation menu and its buttons call irrigation-mcp's tools, and its alerts (`irrigation://alerts`: `irrigation_battery`, `irrigation_pause`) go to the chats subscribed to them as ecobot-mcp's do; the alert menus, `/usage` and Help offer them. While irrigation-mcp can't be reached the button says it couldn't reach the controller and the rest of the bot carries on; it reconnects by itself, and alerts that are still news are delivered once it is back. The bot runs no controller, watchdog or daily check itself and reads none of the `IRRIGATION_` settings (a Tuya setting left with this unset is a warning at start) | + +(Before step 8b, November 2026, the bot ran the controller itself from the `BOT_TUYA_*` settings; `scripts/migrate_env.py` renames them +and adds `BOT_IRRIGATION_MCP_URL` when the device id is there: `http://127.0.0.1:8766/mcp`, or `http://irrigation-mcp:8766/mcp` in a file +that names ecobot-mcp's container, as Docker's do.) + +## irrigation-mcp's settings (`IRRIGATION_`) + +irrigation-mcp (`python -m irrigation_mcp`, [ecobot-mcp.md](ecobot-mcp.md) 3.9) is the irrigation controller's own MCP server: the tools `irrigation_status`, `water`, `stop` and `delay`, and `irrigation://alerts`; it runs the valve's watchdog and the daily check whatever any client does. It stops at start, saying which, without the three Tuya settings. Its state is `DATA_DIR/irrigation_state.json` (at its first start, the bot's irrigation entries in `bot_state.json` are copied over once), its alert log `DATA_DIR/irrigation_alerts.sqlite`; one irrigation-mcp runs per data folder (`irrigation.lock`). + +| Variable | Default | Description | +|---|---|---| +| `IRRIGATION_TUYA_DEVICE_ID`, `IRRIGATION_TUYA_CLIENT_ID`, `IRRIGATION_TUYA_CLIENT_SECRET` | – (required) | The irrigation controller (Tuya cloud). Old names: `BOT_TUYA_...`, and before those `TUYA_...` | +| `IRRIGATION_TUYA_BASE_URL` | `https://openapi.tuyaeu.com` | Tuya data centre | +| `IRRIGATION_CHECK_HOUR` | `18` | Local hour of the daily check (0–23): a battery under 5% is an `irrigation_battery` alert; more than 1 mm of rain in the last 24 hours, or a 50% or better chance of at least 1 mm today or tomorrow, pauses the timer for 24 hours (an `irrigation_pause` alert), leaving a delay someone set alone. Old name: `BOT_IRRIGATION_CHECK_HOUR` | +| `IRRIGATION_BIND` | `127.0.0.1:8766` | host:port its MCP server listens on (`http://IRRIGATION_BIND/mcp`, Streamable HTTP; put TLS in front of it to reach it from elsewhere) | +| `IRRIGATION_ALLOWED_HOSTS` | `127.0.0.1`, `localhost` | The Host names it answers (any port unless one is given), beside its own hostname, as `MCP_ALLOWED_HOSTS` is ecobot-mcp's | +| `IRRIGATION_ECOBOT_MCP_URL` | `http://127.0.0.1:8765/mcp` (Docker: `http://ecobot-mcp:8765/mcp`) | ecobot-mcp, which the daily check asks for the rain measured (`summary`) and the forecast (`ecobot://forecast`), and whose station names the time zone. It sends the first of `AUTH_TOKENS`, else the generated token in the data folder. While ecobot-mcp can't be reached the check goes on the forecast it last read, without the measured rain | + +It accepts the same tokens as ecobot-mcp: one of `AUTH_TOKENS`, or with that unset the one generated in the data folder they share. Under +systemd it runs from `irrigation-mcp.service` (optional; the bot's unit wants it only if it is installed), in Docker from the +`irrigation-mcp` container (the `irrigation` profile, port 8766, its `IRRIGATION_ECOBOT_MCP_URL` set by `docker/irrigation.env`: leave +a systemd value of it out of `/etc/ecobot.env`, or it points the container at itself; its log says so). -### Storage and logging +## Shared settings (no prefix) | Variable | Default | Description | |---|---|---| -| `DATA_DIR` | `$STATE_DIRECTORY`, else app dir | State (`bot_state.json`) and SQLite caches. Relative paths from the working dir. Created if missing. | -| `LOG_WIDTH` | `24` | Characters of a chat message kept in the log, then `…`; `0` keeps all. No other line is cut | -| `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING`, `ERROR`. `DEBUG` adds the bot's own lines (chart timings) | +| `AUTH_TOKENS` | generated | `token,token`: the bearer tokens ecobot-mcp accepts (each client sends one as `Authorization: Bearer `), one per client so one can be revoked alone (take it out and restart); the bot sends the first, to ecobot-mcp and to irrigation-mcp, which accepts the same ones, and irrigation-mcp sends the first to ecobot-mcp. Compared in constant time; a token is never logged. Unset: ecobot-mcp generates one at its first start and keeps it in the data folder (`DATA_DIR/auth_token`, mode 0600, the same one every start after; its path is logged, never its value), and the bot, with `AUTH_TOKENS` unset too, reads it from there (the same data folder: systemd's units and Docker's containers share it), warning when it can't. For another client: `sudo cat /var/lib/private/ecobot/auth_token`. (Replaces `MCP_SERVICE_TOKENS` and the bot's `WEATHER_MCP_TOKEN`; the latter, if set, is still sent while `AUTH_TOKENS` is unset, with a warning to move it into `AUTH_TOKENS`, and is ignored, with a warning, once `AUTH_TOKENS` is set) | +| `TZ` | system zone | Only used without Ecowitt (the station's zone wins; a mismatch is logged). IANA name, e.g. `Australia/Melbourne`. With `BOT_MCP_URL`, ecobot-mcp's station's zone wins once read (and is kept for a start while ecobot-mcp is down); `TZ` only until it has ever been read | +| `DATA_DIR` | `$STATE_DIRECTORY`, else app dir | The bot's state (`bot_state.json`); ecobot-mcp's alert log, SQLite caches and generated token; irrigation-mcp's state (`irrigation_state.json`) and alert log (`irrigation_alerts.sqlite`). Relative paths from the working dir. Created if missing. Every program uses the same one | +| `DARKMODE` | `off` | The charts' colours. `off`: light; `on`: dark; a time range, e.g. `8pm-8am`, `20:00-8:00` or `20-8`: dark between those times in the station's time zone, light the rest of the day. The gauges (the Status picture, the web dashboard) are dark whatever this says. ecobot-mcp reads it for the chart images it sends a client that asks for them (a call may say `chart_dark`); the bot as its client asks for its own theme, so this is the bot's setting for its pictures either way | +| `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING`, `ERROR`. `DEBUG` adds the program's own lines (chart timings) | diff --git a/docs/ecobot-mcp.md b/docs/ecobot-mcp.md new file mode 100644 index 00000000..5f21b2f4 --- /dev/null +++ b/docs/ecobot-mcp.md @@ -0,0 +1,911 @@ +# MCP service plan (ecobot-mcp) + +> **Names today.** The program this plan calls "the service" is **ecobot-mcp**: the package `ecobot_mcp` (`python -m ecobot_mcp`), +> the systemd unit `ecobot-mcp.service`, the Docker image and container `ecobot-mcp`. Its settings start with `MCP_`, the bot's with +> `BOT_`, the shared ones have neither (`AUTH_TOKENS`, which replaced `MCP_SERVICE_TOKENS` and `WEATHER_MCP_TOKEN`): see +> [configuration.md](configuration.md). Every request needs a token: with `AUTH_TOKENS` unset, ecobot-mcp generates one in the data +> folder, which the bot reads, so it no longer refuses a non-loopback address for want of tokens. The plan below keeps its history. + +The plan for turning this repository into a weather and air-quality service that any MCP client can use: the readings file, the +syncers that fill it, and an MCP server over them. Claude Desktop, Claude Code, ChatGPT, Open WebUI or anyone's bot asks it questions +and gets answers it can pass on. Today's Telegram bot becomes ecobot-mcp's first client while the tools move over, and stays as a +slim client (step 6): Telegram's chats, buttons and alerts, with everything else from ecobot-mcp. Irrigation becomes a second MCP server, irrigation-mcp, in this repository as its own package and Docker image (decided November 2026). This is a design and a sequence of +steps, each shipped on its own, in the manner of [storage-plan.md](storage-plan.md). + +Decided: +- **The end state is the service alone.** No bot of ours; nothing in the interface may assume one. +- **Charts are data.** Tools return a chart's data; the client draws it (or its model does). +- **Alerts are decided by the service and published over MCP only**, as a log clients listen to. +- **This repository becomes ecobot-mcp**, keeping its history; the bot stays as a slim client of it (step 6), its in-process code + gone. Irrigation moves to its own server (irrigation-mcp: its own package and image, in this repository). +- **Separate hosts** are possible: the service runs near Home Assistant and the sensors; clients connect over the network. + +## 1. Why + +- The archive, the live poll and the backfills run only while the bot runs: a restart, a crash or a Telegram outage leaves holes. As a + service, the data keeps coming whatever any client is doing. +- Any assistant can ask about the station and the air sensor and get the same careful answers the bot gives today: records with when + they happened, days ranked and counted, readings at an interval, rain against pressure, whether it will rain. Other Ecowitt MCP + servers (brendo/ecowitt-mcp) pass Ecowitt's raw cloud JSON through: 90 days at 5 minutes, running rain totals the model must + difference, no air sensor. +- The bot has grown a second brain in front of the model: regex shortcuts, period hints, rewritten arguments, a 200-line prompt of + rules about the tools. A service any model can use has to carry that knowledge itself, in its tools and its results. + +## 2. What is there now + +What the bot was when this plan began, before step 1; section 3 says what each part became (irrigation: 3.9 and 3.10, step 8). + +### 2.1 Who asks for data + +| Asker | How | Lives in | +|---|---|---| +| The model | 12 tools: `weather_now`, `weather_history`, `weather_days`, `weather_link`, `air_quality`, `air_days`, `plot_chart`, `air_link`, `air_scan`, `readings`, `weather_forecast`, `pollen_asthma` | `lib/ecowitt`, `lib/airgradient`, `lib/compose.py`, `lib/history.py`, `lib/forecast`, `lib/pollen` | +| Shortcuts in code | `intent.fast_call`, `report_calls`, `model_prefetch`: the same tools through `Tools.call_all`, their JSON parsed by `lib/report.py` | `lib/intent.py`, `lib/bot.py` | +| Report, dashboard, period buttons, charts drawn ahead | the shortcuts, `Ecowitt.dashboard()`, the same tools with new dates | `lib/report.py`, `lib/ecowitt/dashboard.py`, `lib/bot.py` | +| Alerts, their charts and 🔄 | `station.recent()`, `live_rain()`, `air.latest()`, `forecast.days`, `pollen.current()`; the charts through the shortcuts' sentences ("Wind chart 1d") | `lib/alerts` | +| Irrigation | `station.recent(24)` and the forecast, once a day; the valve watchdog every minute; buttons to water, stop and pause | `lib/alerts/irrigation.py` (since step 8 irrigation-mcp's `lib/irrigation/check.py`), `lib/irrigation`, `lib/bot.py` | + +### 2.2 What fills the file + +The station's warm (60 s: 5-minute and 30-minute readings, 4-hour and daily records), the Home Assistant live poll (5 s; minutes, live +bands), the nightly archive, the Home Assistant range import (15 min), the AirGradient's warm (1–4 min), import and backfill, and the +pollen and forecast refreshes (30 and 15 min). Questions fetch too: `weather_history` and the air tools ask Ecowitt or the AirGradient +cloud for what the file lacks, inline. + +### 2.3 What the model is told outside the tools + +All of this is what a client other than the bot would not know, so it has to move into the service: +1. **The prompt** (`lib/prompt.py`): + - the devices and the names people use for them ("ecowitt", "ag"), what they measure and in which units, Indoor and Outdoor; + - what "this week", "last month", "3m", "on record" mean; + - one call per period, not many; when to use which tool; how to read each result (`_when`, `_date`, notes); that a record with when + it happened is `weather_history`, a ranking of days `weather_days`; a period with no date named, for days, is the whole record; + - fetch again for every question and every follow-up, never reuse earlier figures; the resolution is chosen for you; + - a weather emoji before each day, inferred from that day's figures; the caption rules under a chart; + - "will it rain?": the station read (pressure tendency over 3 hours from whether the high or the low came first; down more than + 3 hPa likely, 1–3 possible, under 1 or rising unlikely; under 1005 hPa unsettled, over 1020 settled; humidity 90% or more, or the + temperature within 2°C of the dew point; recent rain; wind picking up), then the forecast; + - what the bot can't do: no lightning, soil channels, indoor air quality or other places; custom alerts can't be added; the alerts + there are and their thresholds; how far back the history goes. +2. **The date** (the prompt's "RIGHT NOW", `intent.period_hints`): today's date and time, and every date range the words name, worked + out by the bot because models get calendar maths wrong. +3. **Hidden inputs** (`Turn`): the reading charted, a chart asked for, an average asked for, the air reading the conversation was about, + a holiday filter, "weather all week" (every reading, in a set order): the bot's regexes decide these beside the model's arguments, + sometimes overruling them. +4. **Bot-side writing** (`lib/report.py`): the report's lines, the chart captions, the plain lookups' answers, written by the bot from + the tools' JSON. +5. **Prefetching** (`intent.model_prefetch`): for "will it rain" the bot fetches the reading now, the last 3 hours and the forecast before + the model starts. + +## 3. Design + +### 3.1 The service + +| Stays (the service) | Leaves | +|---|---| +| `lib/storage`, `lib/ecowitt` (less the gauges' look), `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py`, `lib/specs.py` (chart data), the alert rules (`lib/alerts/weather.py`, `particulates.py`, `forecast.py`, `pollen_and_asthma.py`, `rules.py`), and new: `lib/mcp_server.py`, `lib/periods_text.py` (3.2), `lib/service/` (the tools of 3.3 and what they share), `lib/service/outlook.py` (3.3), `lib/alert_log.py` (3.6) | **To each client:** Telegram, the model loop, the persona and style of answers, drawing (`lib/charts.py`, `lib/draw.py`, `lib/gauges.py`, and the gauges' layout and colours, `GAUGES` from `lib/ecowitt/dashboard.py` and `lib/gauge_sheet.py`), delivering alerts, per-chat state. **To the irrigation server's repository:** `lib/irrigation`, `lib/alerts/irrigation.py`. **Deleted with the bot:** `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/report.py`, the menus and keyboards | + +### 3.2 An interface any model can use + +The test of every tool, argument, result and note: would a model that has never seen this repository, given only the tool list, +answer the question right in one round of calls? Section 7's evals ask exactly that, of more than one model. + +- **The tool descriptions and the results are the contract.** Every rule a choice of tool or the reading of a result depends on is in + that tool's description (which questions it answers, an example call for each, how to read what comes back) or in the result itself + (`value_is`, `how_to_read`, `note_*`, `missing`, `warning`). The server's `instructions` repeat a short summary (the devices and their + nicknames, Indoor and Outdoor, the readings' names, units, and that every question, a follow-up or a challenge too, is fetched afresh: a client may drop earlier tool turns, and with them `fresh`), but nothing depends on them: on the 2026-07-28 protocol a client only gets them by asking + (`server/discover`), and many don't pass them to their model. The persona (a friendly Telegram bot, plain text, bullets) is the + client's. +- **Periods in words, worked out by the service.** Every tool that takes a period takes `period`, the person's own words for it, passed + unchanged ("this week", "in the last year", "past two years", "yesterday afternoon"), or `start` (and `end`). The service reads them + by the table below, in the station's time zone, and every result begins with how it read them (`period: {asked: "this week", text: + "the last 7 days: Wed 4 – Tue 10 Nov 2026", start, end}`) and the time of the figures (`as_of`). The model never needs today's date: + every relative form is in the table, and the descriptions carry the table. The bot's period hints and its "RIGHT NOW" block go. +- **One naming scheme.** Readings are `sensor.reading`: `outdoor.temperature`, `indoor.humidity`, `pressure.relative`, + `wind.wind_speed`, `rainfall.rain` (mm that fell), `solar_and_uvi.uvi`, `air.pm2_5`, `air.temperature` (the AirGradient's own). + Tools that take readings also take the words people use, resolved by the service and listed in each description: a bare reading is + the weather station's (`temperature` and `humidity` are outdoor and indoor; the AirGradient's own are only ever `air.temperature` + and `air.humidity`), `pressure` is relative pressure, `uv`, `solar`, `rain` the main gauge, `wind` its speed shaded up to the gusts + (and the compass rose on a chart); a sensor's name (`outdoor`, `indoor`, `wind`, `air`) is its usual set; `all` is every reading. + The device nicknames ("ecowitt", "weather station", "ag", "airgradient", "air gradient") are in the descriptions too. `days` keeps + its day-figure names (`temp_max` is outdoor, `indoor_temp_max`, `rain`, `pm2_5_max`), listed in its schema. +- **Answers ready to pass on.** Every figure comes with its wording: a value with its unit (`"12.3 °C"`), a record with when + (`"around 3:30pm"`) and its day (`"Fri 9 Jan 2026"`), ratings and AQI for the air, and each day's look (`day_look: {word: "wet", + emoji: "🌧️"}`), worked out by the service from that day's rain, highest gust, highest and lowest temperature and solar radiation, by + a rule with its thresholds in the code (step 2). A model quotes; it never formats a time or works out a day's weather. +- **Every choice is an argument**, with a plain name and a default that suits the commonest question. Nothing about the question reaches + a tool except its arguments: no hidden inputs, and no client rewrites them. +- **Fresh every time.** Every result says its figures are as of `as_of` and that a follow-up or a challenge ("that's wrong, it was + cooler") needs the tool called again. The resolution is the service's choice, never an argument: a record is refined to the 5-minute + reading where it is held, and `low_note` or `high_note` says when it isn't. +- **Errors that teach.** A wrong name lists the right ones; a period that isn't in the table lists the forms with what each means now + (which also tells the model today's date); too many rows names the interval that fits; a period the data doesn't reach says what it + does reach; a future period points to `forecast`. A model corrects its call once, from the error alone. +- **Small results.** A result is what a model needs to answer, not everything held: a summary's breakdown is by day or by month by the + period's length, a chart's data is bucketed to a budget (3.7), `readings` caps at 300 rows. Full detail is a further call. +- **Read-only, and honest about fetching.** Every tool is `readOnlyHint`; those that fetch what the file lacks say so + (`openWorldHint`); request `_meta` `fetch: false` answers from what is held. + +**Periods.** `period` must match a form below as a whole phrase (case aside; N a digit or a word up to twelve). There is no partial match +and no falling back to a default: anything else is an error that lists the forms. Examples are as asked on Tue 10 Nov 2026 at 14:05. + +| `period` | Means | +|---|---| +| `today` | 00:00 today to now | +| `yesterday` | yesterday 00:00–24:00 | +| `last N minutes`, `N min` | the last N minutes (`m` alone never means minutes) | +| `last N hours`, `Nh`, `last 24 hours`, `1d`, `last day` | the last N hours | +| `last N days`, `Nd` (N ≥ 2) | today and the N−1 whole days before it (`last 7 days`: Wed 4 Nov 00:00 to now) | +| `this week`, `past week`, `the last week`, `week`, `1w` | the last 7 days, as above | +| `last N weeks`, `Nw`, `fortnight` | the last 7N days | +| `past month`, `the last month`, `month`, `1m`, `last 30 days` | the last 30 days | +| `last N months`, `Nm`, `N mo` | the last round(N×365/12) days (`3m`: 12 Aug to now) | +| `past year`, `the last year`, `year`, `1y`, `last 12 months` | the last 365 days | +| `last N years`, `Ny` | the last 365N days | +| `week to date`, `since Monday` | Monday 00:00 to now (Mon 9 Nov) | +| `last week` | the previous Monday to Sunday (Mon 2 – Sun 8 Nov) | +| `this month`, `last month` | 1 Nov to now; all of October | +| `this year`, `last year` | 1 Jan 2026 to now; all of 2025 | +| `2025` | that year (to now if it is this one) | +| `October 2025`, `October` | that month; with no year, the latest that has begun (`December` is December 2025) | +| `A to B`, `between A and B`, `June to August 2026` | from the start of A to the end of B | +| `2026-09-05`, `5 Sep`, `5 September 2025`, `Sat 5 Sep` | that day; with no year, the latest not after today; a weekday that doesn't match the date is an error naming the right one | +| `Monday` … `Sunday`, `last Saturday` | the latest such day before today | +| `Christmas Day`, `Melbourne Cup` (any public holiday), with or without a year | that day, from the service's holiday calendar; the latest not after today | +| `this morning`, `yesterday afternoon`, `Tuesday evening` | 06:00–12:00, 12:00–18:00, 18:00–24:00 of that day | +| `last night`, `Tuesday night`, `overnight` | 22:00 the evening before to 06:00 that day | +| `since 6am`, `since Monday` | from the latest such time (or that day's 00:00) to now | +| `on record`, `all time`, `ever` | from the first reading held, for the sensors asked about, to now | + +- **`period` or `start`**: models fill in every argument they see, sometimes with junk, so when both are sent: `start` and `end` that + aren't dates or times (`count_only`), or that read as the same span as the period (within 15 minutes at each end), are set aside, the + period is read and the result's `period.note` says so; dates that read as another span are refused, naming both spans as read ("`period` + 'on record' is Sat 1 Oct 2022 – Mon 9 Nov 2026 but `start`/`end` say Wed 1 Jan 2025 – now: send one of them"), since real dates are the + person's; a period that can't be read beside readable dates is refused with its forms, saying the dates were set aside because `period` + was sent and to send them without it to use them. A note on the period keeps a chart from being complete (3.7): the model reads it. + `start` and `end` are the station's local time, `YYYY-MM-DD` or `YYYY-MM-DD HH:MM`; one with an offset or `Z` is moved into local time. An `end` that is a date includes that whole day; one with a time stops at + it. No `end` means to now; `end` without `start` is an error. +- **Whole-day tools** (`days`, `relate`, `scan`) take whole days ending yesterday, because today is still settling: a rolling phrase is + that many whole days to yesterday (`last 7 days`: Tue 3 – Mon 9 Nov), a calendar one runs to yesterday, and the result's `period` + says it was cut ("to Mon 9 Nov: today isn't over"). A phrase that leaves nothing (`today`, `last 5 hours`, `this month` on the 1st) + is an error that points to `summary` or `readings`. They take dates only; a time is refused with the same pointer. +- **A future period** is an error that points to `forecast`. + +### 3.3 Tools + +Ten tools in place of twelve: one per kind of question, each over both sensors where both have the reading. + +| Tool | Answers | Replaces | Arguments (default) | +|---|---|---|---| +| `current` | how it is now: every reading, or the ones named; with `context`, today's, this month's and this year's highs and lows beside each reading, and rain's totals | `weather_now`, `air_quality` without dates, the gauges | `readings` (all), `context` | +| `summary` | a period's highs and lows with when; averages; day or month breakdown; wind direction; rain total; air ratings and AQI; a chart of any readings from either sensor or both | `weather_history`, `air_quality` with dates, `plot_chart` | `readings`, `period` (today; a chart with no period, the last 24 hours), `average`, `every_day`, `chart`, `chart_readings`, `layout`, `invert_second_axis`, `chart_answers_it` | +| `readings` | values at an interval, each with its time | `readings` | `reading`, `period` (the last 24 hours), `interval` | +| `days` | days found, ranked or counted by their figures; a figure per month or year, as bars; holidays and weekends; the same over part of each day (the 3pm temperature, the overnight low) | `weather_days`, `air_days` | today's day-tool arguments over one field list, `period` (on record; with `hours`, the last 30 days), `hours`, `chart_answers_it` | +| `relate` | rain against one reading: for pressure, humidity or wind, does rain follow a change in it; for PM2.5 or PM10, is the air cleaner after rain | `weather_link`, `air_link` | `reading`, `period` (90 days; 60 for air), `chart` | +| `scan` | each air reading against every weather reading: which go together | `air_scan` | `reading` (or all), `period` (90 days, at most 400), `chart` | +| `outlook` | will it rain in the next few hours: the station's read and the forecast's | the prompt's outlook rules, `model_prefetch` | none | +| `forecast` | today and the days ahead | `weather_forecast` | `period` (the next 7 days: `today`, `tomorrow`, `next 3 days`, `this weekend`) | +| `pollen` | grass pollen and thunderstorm asthma | `pollen_asthma` | none | +| `about` | what the service measures and doesn't, how far back each kind of history goes, the alerts there are with their thresholds, that alerts can't be added or changed by asking | the prompt's capabilities and limits | none | + +**Which tool, in their descriptions.** Each description says what it is not for and where that goes: +- the highest or lowest reading of a period with when it happened (the hottest, coldest, fastest gust, "on record") is `summary`; + a day's total, or days ranked, counted or filtered on a day's figures (the wettest day, the windiest day, the hottest day it also + rained, days over 35°C, rain per month) is `days`; +- any chart over time is `summary`'s (one reading, several, both sensors, ratings); a figure per month or year is `days.group_by`; + "X against rain" is `relate`; +- values at set times or per interval are `readings`; +- "report", "status", "sitrep": `current`, `forecast` (today) and `pollen`, called together; "will it rain" is `outlook`. + +**`summary`'s figures and charts:** +- `readings` is what to summarise (default: the weather station's usual set, outdoor and indoor temperature and humidity); + `chart_readings` is what to draw, defaulting to all of `readings`. +- `layout`: `auto` draws one reading as a line for each sensor that has it, plus the compass rose when wind direction is among them; + more than one reading as panels, one each, on one time axis; `two_axes` puts two on one panel with a scale each; `same_axis` two of + one unit over each other; `invert_second_axis` modifies `two_axes`. A reading can be drawn as its traffic-light rating + (`air.pm2_5:rating`), in `chart_readings` or in `readings` (summarised as the reading, and drawn as its rating when + `chart_readings` isn't sent; a model sends it either way). `all` draws every reading in the station's usual order (temperature, humidity, solar, pressure, rain, dew point, + then feels-like and VPD where configured, then wind), as "weather all week" does today. +- `chart` defaults to on for periods of 3 days or more. `average: true` adds each reading's average to the figures and draws the chart + as each day's average. +- `every_day` lists every day of a period up to 31 days (by day or by month still follows the period's length). + +**`summary`'s result** is one shape for both sensors: `{period, as_of, series: {"outdoor.temperature": {unit, low, low_text, low_when, +low_date, low_day_look, [low_note], high…, [average], [daily|monthly: each row with its day_look]}, "air.pm2_5": {unit, low…, high…, +average, high_rating, average_rating, high_aqi_us, high_band, average_aqi_us, average_band}, "wind.wind_direction": {most_common, then, +steadiness, [daily]}}, [rain_total_mm], [monthly_note], [notes: {sensor: {…}}], [charts], [missing], [warning]}`. The breakdown and +`monthly_note` are the station's; ratings, AQI and the 400-day cap (30 days fetched inline) the air sensor's; `rain_total_mm` whenever +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 +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. + +**`outlook`'s result** is the prompt's outlook rules, worked out by the service (`lib/service/outlook.py`) from the reading now and +the last 3 hours: `{as_of, verdict: "likely"|"possible"|"unlikely", reason: "pressure down 2.4 hPa in 3 hours, humidity 91%", +pressure: {change_hpa, tendency, level, text}, moisture: {humidity, dew_point_spread}, recent_rain, wind_trend, forecast: [today's and +tomorrow's lines, when the forecast is on]}`. With the forecast off, the station's read is the whole answer. + +**`days` over both sensors:** the fields shown and the default sort come from the sensor of the fields named (an air-only question +shows and ranks by `pm2_5_max`); `days_checked` counts the days on which every sensor named has a day row; each listed day carries each +sensor's source and its `day_look`; the result keeps both sensors' notes (`note_daily`, `exact_from`, `note_trace`, `note_averaged`; +`note_hourly`, `note_missing`). A condition mixing the two sensors leaves out the days whose station figures come from Ecowitt's daily +records (10am to 10am, not the air sensor's midnight to midnight) and says how many. With no period, every day on record: "per year", +"how many times", "the windiest day ever". + +**Part of each day (`days.hours`, new; no tool can answer these today).** `hours` works out each day's figures over a stretch of local +time instead of the whole day, and the rest of `days` then works on those figures: "the typical overnight low this month" is +`{hours: "night", stat: "avg", of: "temp_min"}`, "nights below 5°C" `{hours: "night", where: temp_min < 5}`, "the average 3pm +temperature in October" `{hours: "15:00", stat: "avg", of: "temp_avg"}`. +- **Named stretches:** `night` (22:00–06:00), `morning` (06:00–12:00), `afternoon` (12:00–18:00), `evening` (18:00–24:00), `daytime` + (06:00–18:00), as the periods table has them. The result states the stretch it used. +- **Times on the half hour.** A stretch starts and ends on the half hour ("15:00-16:00", "22:30-06:00"): the figures take each half + hour's mean, and a 30-minute reading's own lowest and highest run to the end of its half hour, so part of a half hour would be + counted as all of it. Any other time is refused, but for a moment: a single time on the hour or half hour ("15:00", or "15:00-15:05"). + On a day held at 5 minutes a moment is that reading; on a day held only at 30 minutes it is the half hour from it (on the air + sensor's hourly days, the hour), and the result says so. +- **Which stretch.** `[start, end)` in local wall time, read as `start` to `end - 1` (the SQL's `BETWEEN` includes the end). "24:00" is + the next local midnight, so a whole day is 23 or 25 hours on a clock-change day. A stretch that crosses midnight starts the evening + before and belongs to the day it ends on (Monday 22:00 to Tuesday 06:00 is Tuesday's night): one stretch per sensor and day. A + stretch the clock change removes (02:00–03:00 on the first Sunday of October) is left out and counted. +- **Which readings.** Each sensor's stretch is read at the first of the day rows' own resolutions that holds all of it, by the + coverage (`Reader.held`): the station's 5-minute, then 30-minute readings; the air sensor's 5-minute, then hourly ones; never the + minutes. A stretch held at neither (a day held only as Ecowitt's daily or 4-hour records, a night whose evening is before the + 30-minute archive) is left out and counted in a note; one that is held but has no readings (the station was off) counts as missing. + This is not `lib/ecowitt/period.py`'s choice for a period's part days, which falls back to whatever readings there are. +- **The figures** come from the day rows' own SQL over one window a day (`Reader.part_days`), so a stretch's mean, lowest, highest and + their times are worked out as a whole day's are, the air sensor's glitches taken out. Except rain: the day's `rain` is the highest + of the running daily total, which over a stretch would be the rain since midnight up to its end. Over a stretch, `rain` is the mm + that fell in it, the total's rise from the last reading before the stretch to its last reading in it, a fall counted as the midnight + reset (`lib/rain.rain_slots`, as `readings` works it out), computed beside `part_days`. +- **The period.** As `days`' (to yesterday), except that today counts once today's stretch is over and held: asked this morning, + "nights below 5°C this week" includes last night. At most 400 days, as `scan`'s: the stretches cost far more than day rows (over + four years of 5-minute readings a night takes about 1 s for a climate sensor, 3.4 s for the air sensor with its glitch rule, against + 0.01 s for the day rows; the default 30 days under 0.1 s), and a stretch that is the whole day reads the day rows. + +**Averages**, wherever the question asks for one: + +| Tool | Averages | +|---|---| +| `summary` | `average: true` adds each reading's average over the period, and one per day or month in its breakdown, and draws the chart as each day's average. The average is weighted by time: a part day at either end of the period counts for its hours, and an air day held only as hourly averages for its hours (until step 0 the station's average was the mean of its days' means, a part day counting as a whole one, and the air sensor's the mean of its stored readings, an hourly reading counting as one twelfth of a 5-minute hour). An air reading always has its average; its six air-quality readings also their `average_rating`, and PM2.5 its `average_aqi_us` and `average_band`; the air sensor's own temperature and humidity have no rating. Rain is a total, not an average; rain rate has an average (`weather_history` has given it one since step 0); wind direction has its most common direction instead. A chart's panels report each line's average beside the lowest and highest of its half-hour averages, a rain panel its total. | +| `readings` | for a reading that is averaged, each row is its interval's average with its lowest and highest: hourly averages at `1hour`; at `1day` the day's average, lowest and highest, and when those two happened; at `1min` and `5min` the stored reading itself. Rain is the mm that fell in the interval (at `1day`, the day's total); gusts the interval's highest (at `1day`, with when); wind direction the reading at the interval's end (at `1day`, the day's last). Those three have no lowest and highest. | +| `days` | a field for each day's average of every reading but rain, gusts and wind direction (`temp_avg`, `humidity_avg`, `pressure_avg`, `wind_speed_avg`, `rain_rate_avg`, `indoor_temp_avg` …; the air sensor's `pm2_5_avg`, `co2_avg` … for its six air-quality readings), and `stat: "avg"` over the matching days, overall or per month or year ("average humidity per year"). Rain is a day's total (`rain`), so "average daily rain in June" is `stat: "avg", of: "rain"`. With `hours`, the same over that part of each day (rain: the mm that fell in it). | + +**What becomes of the bot's hidden inputs.** Today the bot reads the question with regexes and the tools use that reading beside the +model's arguments: some fill an argument the model left out, three overrule the model (the reading charted, the readings stacked, a +holiday filter). Each was added for a mistake the production model made (the eval cases `humidity-chart`, `temperature-and-rain`, +`days-over-limit-by-year`, `rain-by-month-two-years`), several of them because the choice was a hidden input, an easily missed argument +or a default that suited the wrong question. In the service each is an argument with a plain name and a default that suits the +question, and the model sets it: + +| Today (`Turn`) | In the service | +|---|---| +| `chart_field`, `chart_fields` (overrule the model) | `summary.chart_readings`, defaulting to every reading summarised, drawn as panels | +| `readings` (which readings the words name) | `summary.readings` | +| `two_axes` | `layout: "two_axes"` | +| `average_asked` (the chart drawn as daily means; the model can't ask for that today) | `average` (figures and chart together) | +| `per_day` | `every_day` | +| `chart_asked` | `chart` | +| `text`: rain by month, grouping (fill), holidays (overrule) | `days.group_by`, `days.only`; the rain bars' grouping follows the period's length | +| `air_named` (the air reading charted when none is named) | `readings` (the conversation is in the model's context) | +| "weather all week" (`ALL_ORDER`, `CHART_ALL_*`) | `chart_readings: "all"`, in the service's order and settings | +| `ahead` (a chart drawn ahead, nobody waiting) | request `_meta.priority: "background"` | +| `Tool.asked` (the air sensor's own temperature and humidity offered only when named) | always listed, only as `air.temperature` and `air.humidity`, described as the AirGradient's own | +| `forecast_shown` (the forecast days a chat was shown) | gone: the forecast alert is the service's (3.6) | +| `CHART_SOURCE` | the chart data names its sources (3.7) | + +### 3.4 Resources + +For applications that keep an eye on the station rather than ask about it; a model doesn't read them (what it needs is in the tools). + +| URI | Holds | Pushed | +|---|---|---| +| `ecobot://station` | name, time zone, latitude and longitude, created; the sensors, their readings with labels, units and the words people use for them; each source's mode (HA, cloud, local) and retention; the alert kinds, what each means and its threshold; the AirGradient dashboard link | when the catalogue gains a reading | +| `ecobot://now/weather` | the live reading as kept, in the service's names (`current`'s, nothing fetched for it): `{as_of, sensors: {sensor: {reading: {value, unit, text, [emoji], [compass]}}}, lines, heading, [unavailable]}` | each new reading (5 s with HA, 60 s cloud only) | +| `ecobot://now/air` | the latest air reading, the same shape: its time, each reading's rating, PM2.5's and PM10's AQI and band (the US AQI is the higher) | each new reading | +| `ecobot://alerts` (in the resource list) and `ecobot://alerts{?since,expired}` (a template) | the alerts, newest last, kept 30 days; `since` an alert id: those after it; unexpired ones only unless `expired=true` (3.6) | each new alert, on the bare URI | +| `ecobot://forecast` | the forecast days, structured (min and max, rain chance, chance of at least 1 mm, summary), with `fetched_at` and `place` | each new forecast | +| `ecobot://pollen` | grass and asthma levels with their days, `fetched_at`, `in_season` | each new page | +| `ecobot://status` | the Status picture (step 6): the station's temperature, humidity and rain gauges in a row as a PNG (a blob, `image/png`, `lib/gauges.py`), after their readings as JSON text (`{gauges: [{title, value, unit, rows}], lines}`: the reading now and the day's, month's and year's highs and lows, which the picture leaves out); from `current` with context, read as a call is; without Pillow, the text with `image_note` | no | +| `ecobot://health` | each loop's last success and failure, archive progress, the file's size | no | +| `ecobot://schema/chart` | the chart data's JSON Schema (3.7) | no | + +Dates are ISO strings. On the 2026-07-28 protocol (MCP SDK 2.3), changes are delivered on a `subscriptions/listen` stream: each event +says "this URI changed, read it again", with no replay. The low-level server serves it with `Server(…, +on_subscriptions_listen=ListenHandler(bus))` and a `bus = InMemorySubscriptionBus()`; the service's loops `await +bus.publish(ResourceUpdated(uri))` for each URI above when it changes (repeats of an unchanged reading not sent), and +`ToolsListChanged()` when a sensor sends a field it never sent. Subscriptions match exact URIs, so clients subscribe to the bare URIs +the resource list gives. Only clients on the 2026-07-28 revision can listen; older ones read the resources and poll. + +### 3.5 Prompts + +The service also offers MCP prompts, the templates clients show as commands or buttons, each a question in words with its period as an +argument: `now`, `report`, `will_it_rain`, `weather_chart` (every reading, a panel each), `chart` (a reading and a period), +`rainfall`, `air`. They hold no logic: the client's model answers them with the tools, as any question. Their names are chat +commands too (step 6c: the bot offers each as a Telegram `/command`), so they keep to Telegram's form (lowercase letters, digits and +`_`, at most 32) and none takes the name of one of the bot's own commands (`/rain`, `/weather`, …: the keyboard's instant charts). + +### 3.6 Alerts + +The rules move to the service: rain starting and stopping (with the quiet-hours note), gusts, UV, indoor and outdoor temperature +crossings, particulates (mask on, safe again), pollen and thunderstorm asthma, a forecast revised. Their thresholds, quiet hours and +cooldowns are the service's config, and their state its own store (`alert_state.json`, out of the bot's `bot_state.json`). Each runs +on the triggers it has today: a new live reading or 5-minute row, a new forecast or pollen page, and its own clock (the weather alerts +every 60 seconds, particulates every 30 minutes and only then, since its two-readings rule counts readings across checks). +- **An alert is an event:** `{id, kind, time, expires, title, text, data, [link: {label, url}], [chart]}`. `text` is ready to send + ("🌧️ It's started raining: 0.4 mm so far"); `data` the figures behind it; `link` the page that goes with it (the AirGradient + dashboard for particulates, the pollen site for pollen); `chart` its chart data when it has one (gusts, UV, temperature, + particulates), which like every chart carries the call that drew it (`drawn_by`, 3.7), so a client's 🔄 calls it again for the + latest readings with no knowledge of the kinds. +- **Alerts go stale:** `expires` is set by the rule (rain and gusts about an hour, UV its rearm time, particulates the next check, + pollen the end of its day, a forecast the day it is about), and `ecobot://alerts?since=` returns only unexpired alerts unless asked. + A client back after a gap sends what is still true, never the morning's rain as news. +- **Delivery is the client's.** A client listens, reads `ecobot://alerts?since=`, and sends each alert to whoever + it serves. Our bot does this for its subscribed chats. +- **The forecast alert is station-wide:** for today and tomorrow, it compares each new forecast with the first one fetched after 6am + that day (its baseline), alerts when the maximum moves by more than 2°C or the chance of rain rises past 50% (or falls from there to 30% or less: the band + keeps a chance hovering around 50% from alerting each way on every refresh), and makes the forecast it + alerted on the new baseline. Its text says what changed ("The forecast for tomorrow has changed: was 24°C and dry, now 19°C with + rain likely"), not "since I sent it", which only the bot could say. +- **Only listening clients get alerts.** Most chat clients don't keep an MCP listen stream open: the bot is the client that listens + and delivers them (a short script with the SDK, or Home Assistant, could too). Section 8. + +### 3.7 Charts + +Charts are data: the client draws them, or its model does from the numbers. +- **`summary` and `days` (with `group_by`) draw** (and `relate` and `scan` when asked); they build the chart as now (`specs.Chart`), next + to the reads that chose its resolution, buckets and rose, and return it in the result: `charts: [{title, period, source, drawn_by, + panels: [{unit, [label], series: [{name, kind: "line"|"band"|"bars"|"rating", points: [[time, value, (low, high)]]}], [zones], + [compass]}]}]`. Times are ISO local times; `source` names the devices ("Ecowitt weather station and AirGradient sensor"). The JSON + Schema is in the repository (`schemas/chart.json`) and at `ecobot://schema/chart`, versioned. +- **Every chart says how to draw it again:** `drawn_by: {tool, arguments}` is the call that drew it as the service read it, with the + readings' names resolved, every default filled in and the period stated, so the same call with only `period` changed draws the same + chart over another period, and the same call again draws it with the latest readings. A client's period buttons, or an alert's 🔄, + replay it; they need no knowledge of which tool or readings made the chart, and never the model. +- **And the periods it makes sense over:** `drawn_by.periods: [{period, label}]`, decided by the service for that chart, so a client + offers only buttons that draw something worth having. A chart of readings over time: `1d` "1D", `7d` "7D", `1m` "1M", `3m` "3M", + `1y` "1Y". A count or total per month (`days` with `group_by`): `3m`, `1y`, `on record` "All"; per year: `on record` alone, so no + buttons. Rain against a reading (`relate`) and `scan`: `1m`, `3m`, `1y`. A chart that can't be redrawn over another period lists + none. +- **Small enough for a model to read and redraw:** each line is bucketed to at most 150 points (the bands with it), so a model can turn + it into a plot with its own tools and an application can draw it directly. An application that draws for itself asks for more with + request `_meta` `chart_points` (at most 500, today's budget); the bot asks for 500, so its pictures and golden images don't change. + Full detail is `readings`. +- **The note to the model:** a result with a chart says so in one line (`chart_note`: the chart's data is in `charts`; draw it if you + can, and keep the text to the figures; don't describe the chart), so a model neither ignores it nor repeats every point. +- **When the chart is the answer, the reply comes ready.** `summary` and `days` take `chart_answers_it`, described as "true only when + the question is just to see this chart and its figures: nothing else to answer" ("plot pressure this week", not "plot pressure this + week: is a storm coming?"). The model judges that; no regex does. When it is set and a chart is made, the result carries a finished + reply for the person (the period, each reading's high and low with when, any note about missing data) as a text block annotated + `audience: ["user"]` (MCP's mark for content meant for the person, not the model), and result `_meta` `{"ecobot/complete": true}`. + Only a client can save the model's second call, since it runs the model loop and MCP gives a server no way to keep a result from a + client's model; the service makes it one generic rule: *if a result is complete, send its user text and its chart, and end the + turn*. Our bot follows the rule while it lives, and any bot can; a client that doesn't (a desktop assistant) gives the result to its + model as usual, which then has the reply ready to repeat. A result with no chart, an error or a note that needs the model's words is + never complete. +- **Or as images, for a client that asks.** A client that shows pictures but can't draw JSON asks for the charts drawn: per connection + with its MCP URL's query, `/mcp?charts=png` (any client can set a URL; not all can set headers), or per call with request `_meta` + `chart_image: "png"` (or `"none"`, which overrides the connection's). Off by default: without it the result is as above, unchanged. + With it, a result with charts carries its JSON text with each chart's data replaced by `{title, period}` and a `chart_note` that fits + the image (the chart is the image attached: keep the text to the figures, don't describe it), then one `ImageContent` (`image/png`, + base64) per chart, in order; the full chart JSON, each with its `drawn_by` (what the period buttons replay), is in result `_meta` + `"ecobot/charts"`, for applications, and the theme in `"ecobot/chart_dark"`. A complete answer keeps its `reply` block for the + person, after the images, and `"ecobot/complete"`. The pictures are the bot's: the same renderer (`lib/charts.render_data`, Pillow, + run off the event loop), from every point (`chart_points` `"drawn"` unless the call says otherwise), so they and the golden images + don't change; dark per `DARKMODE`, or request `_meta` `chart_dark: true|false`. Pillow is optional on the service + (`requirements-charts.txt`) and imported at the first image asked for: without it the warning is logged once, and the result is the + JSON as if no image had been asked for, with `chart_image_note` saying images aren't available on this service. +- **Or as links, for a client that shows a markdown image but not a tool's.** Some chat apps (LibreChat with an Ollama endpoint) give + a tool's image to the model as text, but show a markdown image in the model's reply. Such a client asks with `/mcp?charts=link`, or + per call `chart_image: "link"`. So there are three modes, the connection's from its URL (`?charts=png`, `?charts=link`, neither + for none) and each call's `chart_image` (`"png"`, `"link"`, `"none"`) overriding it; off by default. With links the charts are + drawn as for images (the same renderer, off the event loop; without Pillow, the same JSON and note) and kept in memory under a + random, unguessable id (`secrets.token_urlsafe(16)`), for `MCP_CHART_LINK_HOURS` (24) and at most 500 pictures and 64 MB (the + oldest dropped first): a restart forgets them. The result's text carries each chart as `{title, period, url, markdown}` + (`markdown` is `![](<url>)`) with a `chart_note` asking the model to put each chart in its reply as that markdown image, + exactly as given, and keep its text to the figures; then one `ResourceLink` per chart (`uri` the URL, `name` the title, + `image/png`), with no image bytes; result `_meta` `"ecobot/charts"` and `"ecobot/chart_dark"` as with images. A complete answer's + `reply` (in the JSON and its block for the person) ends with the markdown images, so a client that shows the complete reply shows + the chart. The pictures are served at `GET /charts/<id>.png` beside `/mcp`, with no token and any `Host` (read-only, like the + dashboard; the id is the key: anyone with a link can open it until it expires), `Cache-Control: private` for at most the link's + remaining life, and 404 once it has gone; the request log names them by the id's first characters. The URL is + `MCP_CHART_BASE_URL`'s (where a proxy serves `/charts` to browsers, e.g. nginx's `location /ecobot-charts/ { proxy_pass + http://127.0.0.1:8765/charts/; }`), else the MCP request's own scheme and host (`X-Forwarded-Proto`, `X-Forwarded-Host` when + present) with `/charts`. +- **Our bot** has every chart it sends drawn by the service (step 6a), as images + (`chart_image: "png"`, in its own theme, `chart_dark`, which it keeps with each picture in its image cache): the charts drawn ahead, + the period buttons, the alerts' pictures and their 🔄, a sentence answered in code and the model's answers' charts (each call the + model makes asks for its pictures; the bot keeps them and the charts' JSON from `_meta` for the period buttons, and the model is sent + the text alone, the charts' titles, never an image). The Status picture is `ecobot://status`'s. The bot draws nothing and imports no + Pillow: a service that sends no image gives an answer without its picture. + +### 3.8 Connecting + +- **One program:** `python -m ecobot_mcp` runs the syncers, the alert rules and the server, at `https://<service>/mcp` + (Streamable HTTP, `streamable_http_app`, under uvicorn behind TLS: a reverse proxy such as Caddy, or uvicorn's own certificate). The + server is the SDK's low-level `Server`, so each tool's input schema is hand-written JSON with its description; the list is built when + asked, so it follows the file's metrics. The app is built with `TransportSecuritySettings(allowed_hosts=MCP_ALLOWED_HOSTS)`: by + default it answers only `Host: 127.0.0.1` or `localhost`, and refuses the name a proxy or a LAN client uses. +- **No stdio:** clients connect over HTTP (Claude Code: `claude mcp add --transport http ...` with the bearer header). A stdio bridge + for clients that can only start a local command was built in step 5 and removed: nothing here needs it. +- **Auth:** the service's own `TokenVerifier` (the SDK has only the protocol): a constant-time compare against `AUTH_TOKENS` + (`token,token,…`, one per client, so one can be revoked alone), passed with `auth=AuthSettings(issuer_url="https://<service>", + resource_server_url=None)` (`issuer_url` is required but unused without an OAuth provider; no OAuth metadata is published). Bind to + the LAN or a tailnet; nothing needs the internet to reach it. +- **A client that listens** (our bot, an alert forwarder): `Client(…, mode="2026-07-28")`, pinning the protocol revision (the default + probes, and a proxy's 502 during a restart can land it on the older revision, which cannot listen). A pinned client skips + `server/discover`, so it calls it once itself (`session.send_discover`, then `session.adopt`) to get the instructions and + capabilities. In the SDK a connection failure on any request ends the whole client, so one supervisor task owns it: it discards the + client when it exits with a transport error or the listen is lost or ends, builds a new one after a backoff, discovers and listens + again, and reads the alerts after its last id. A read timeout of about 45 seconds (three of the server's 15-second pings) notices a + silently dead link. + +### 3.9 Irrigation, its own server + +The irrigation controller (`lib/irrigation`: the Tuya client, the watchdog, the daily check) is its own MCP server, irrigation-mcp +(`python -m irrigation_mcp`, `irrigation-mcp.service`, its own Docker image `irrigation-mcp` under compose's `irrigation` profile), +built in step 8. It stays in this repository as its own package (decided November 2026: not a repository of its own), sharing +`lib/upstream.py`, the alert log and the token helpers (`lib/mcp_http.py`), and importing nothing of the bot's or of ecobot-mcp's sources +and tools (`requirements-irrigation.txt`: the MCP SDK, uvicorn, httpx). It listens at `http://IRRIGATION_BIND/mcp` (127.0.0.1:8766), with the same +token check (`AUTH_TOKENS`, or the generated token) and Host check (`IRRIGATION_ALLOWED_HOSTS`) as ecobot-mcp; one runs per data folder +(`irrigation.lock`); its state is `irrigation_state.json` (the bot's entries copied over once at its first start). +- **Tools:** `irrigation_status` (`readOnlyHint`: `switch`, `countdown` seconds left, `weather_delay` and `paused`, + `battery_percentage`, `work_state`, and the watchdog's `off_at` while a run is watched), `water {minutes: 1..60}` (refused while a + weather delay is on, with an error that says so; the watchdog armed first), `stop` (the valve off, the watchdog disarmed), `delay + {duration: 24h|48h|72h|cancel}`; the last three `destructiveHint`, so a client asks before it calls them. Each answers JSON as one text + block, as ecobot-mcp's tools do; a refusal or the controller unreachable is `isError` with `{"error": ...}`, a message safe to show, + a refusal with `"refused"` too (`"paused"` or `"arguments"`: the bot says why, not that it couldn't reach the controller). +- **The watchdog** (a run must end; a restart mid-run still closes the valve) and the daily check (pause when it rained or will) run in + that server whatever any client does. +- **Rain and forecast** come from the weather service, as its client: the measured rain from `summary{readings: ["rain"], period: "last + 24 hours"}`, the forecast from `ecobot://forecast` (its days' chance of at least 1 mm and `fetched_at`). When the weather service is + unreachable, the check runs on the forecast it last read and skips the measured rain. +- **Its alerts** (battery low, paused for rain: `irrigation_battery`, `irrigation_pause`) are its own `irrigation://alerts`, in the same + shape and with the same listen as `ecobot://alerts`, from an alert log of its own (`irrigation_alerts.sqlite`, its own identity); a + client listens to both servers. +- **The time zone** is ecobot://station's once read, `TZ` before. It reaches ecobot-mcp at `IRRIGATION_ECOBOT_MCP_URL`, sending the + first of `AUTH_TOKENS` (else the generated token), as the bot does. +- **The bot is its client** (`BOT_IRRIGATION_MCP_URL`, `lib/irrigation_remote.py`), as it is ecobot-mcp's: the same token, a supervisor + of its own (`lib/upstream.Upstream`), its Irrigation button, menu and `ir:` buttons calling the four tools (`lib/irrigation_menu.py` + is the bot's UI; `lib/irrigation/common.py` what both sides share, without the Tuya client), and a second alert delivery reading + `irrigation://alerts` after its own last id (kept apart in `bot_state.json`). Unset, the bot has no irrigation: no button, no + irrigation alert types. irrigation-mcp unreachable, the button says it couldn't reach the controller and the bot carries on. + +### 3.10 Configuration + +`MCP_ECOWITT_*`, `MCP_HOMEASSISTANT_*`, `MCP_AIRGRADIENT_*`, `MCP_ANTISPIKE_REQUIRE_CONSECUTIVE`, `MCP_POLLEN*`, `MCP_FORECAST_*`, `MCP_PLACE`, `TZ` (until the +station names one), `DATA_DIR`, the alert settings (cooldowns, quiet hours, thresholds), `MCP_CHART_ALL_FEELS_LIKE`, `MCP_CHART_ALL_VPD`, +`AUTH_TOKENS`, `MCP_BIND`, `MCP_ALLOWED_HOSTS`. The irrigation server: `IRRIGATION_TUYA_*` (old names `BOT_TUYA_*`, then `TUYA_*`), +`IRRIGATION_CHECK_HOUR` (old `BOT_IRRIGATION_CHECK_HOUR`), `IRRIGATION_BIND`, `IRRIGATION_ALLOWED_HOSTS`, `IRRIGATION_ECOBOT_MCP_URL`, and +the shared `AUTH_TOKENS`, `DATA_DIR`, `TZ`, `LOG_LEVEL`. The bot: `BOT_IRRIGATION_MCP_URL` (none: no irrigation), and none of the +`IRRIGATION_` settings; `scripts/migrate_env.py` adds `BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp` where the Tuya settings are. + +## 4. The bot (as it was before step 6) + +The bot is the service's first client, and the measure of each step: it keeps answering in Telegram while its insides move to the +service. Beyond what the steps need, it gets no new features. While it lives it: +- offers the model the service's tools as they are, with the server's instructions, adding only its persona (a friendly Telegram bot, + plain text, bullets, the caption length a photo allows); +- ends the turn on a complete result (3.7), sending the ready reply and the chart without a second model call; +- keeps a few shortcuts for its buttons and commonest typed requests (a named reading's chart and a period, weather now, the report, + the gauges), each a fixed call to a service tool whose result is already worded, so it writes nothing itself; +- draws `charts` and the gauges (`current` with `context`) with its renderer; +- listens to `ecobot://alerts` (and, from step 8b, `irrigation://alerts`, irrigation-mcp's) and sends each alert to the chats + subscribed to its kind, with its chart, its link and a 🔄 that replays its chart's `drawn_by`; +- builds `/usage`, Help and its alert menu from `ecobot://station` (and whether irrigation-mcp is configured: `BOT_IRRIGATION_MCP_URL`); +- keeps per-chat state: subscriptions, admins, and each chart's `drawn_by` behind its period buttons (a press replays it with a new + `period`). + +The plan was to retire it once another client did its job; in November 2026 it was decided to keep it, slimmed down to a client of +ecobot-mcp alone: step 6 says what it keeps and what goes. + +## 5. What does not change + +The readings file, its tables and its day rows; how each tool chooses its resolution and fetches what it lacks; the alert rules +themselves; the charts' content. + +## 6. Steps + +Each step ships on its own, with the tests and evals green and the bot working the whole way. The model's tool list changes once +(step 3): old and new names are never offered together, and no tool interface is rewritten before it is replaced. + +0. **Fixes the service needs anyway**, in today's code (done: `lib/partday.py`, the averages, `chart_answers_it`): + - **Part of each day** (3.3): the engine (stretches through `Reader.part_days`, rain over a stretch, the coverage choice) with tests + against stretches worked out by hand (a night across midnight, a clock-change day, a moment on a 5-minute and on a 30-minute day, + a day held only as daily records, a night with rain in the evening only, an air glitch inside the stretch). The `hours` argument + comes with `days` (step 2). + - **Averages weighted by time** (3.3): `weather_history`'s and `air_quality`'s averages over the period's time, not its days or its + rows, and rain rate's average; tests with a part day at each end and an air period across its hourly history. + - **The chart that answers itself** (3.7): `chart_answers_it` on `weather_history`, `air_quality` and the day tools, the finished + reply (today's `report.chart_caption`) and the complete mark in the result, and the bot's early end of the turn on it; an eval pair + (a question that is just the chart, where the model sets it; one with something else to answer, where it doesn't). Shipped on the + live evals; the log's `LLM 2` lines show the calls it saves. It carries over to `summary` and `days` in step 2. +1. **Charts as data, periods in words** (done: `specs.to_json`/`from_json`, `schemas/chart.json`, `lib/periods_text.py`). The chart + builders return 3.7's JSON with its schema, and the bot's renderer reads the JSON (at 500 points, so the golden images don't change). + `lib/periods_text.py` reads the periods table, tested by hand against it at fixed times (a Monday, a Tuesday, the 1st of a month, 1 + January, 29 February, 00:30, both clock-change days), with whole-day tools cut to yesterday and errors for phrases outside the table + and for the future. No tool interface changes. +2. **The ten tools, beside the twelve** (done). The tools of 3.3, built once with their arguments, periods, worded results + (`day_look`, ready lines, captions), charts, descriptions and errors, in `lib/service/` (what they share: `common.py`, `names.py`, + `daylook.py`, `context.py`; the outlook's rules in `outlook.py`), registered (`__init__.py`: `build`, `Service`), built in + `ecobot.py` and handed to the bot; offered to no model yet. Contract tests per tool; every chart validates against + `schemas/chart.json`, `drawn_by` included, and replays to the same chart and over each of its `periods` without a refusal. The + evals have the service's expectations (`tests/evals/service_cases.json`, every case) and `scripts/eval_prompts.py --service` checks + offline that the tools accept each expected call; `--live --service` asks a model with the tool list alone, and `--instructions` + adds the server's instructions (`lib/service/instructions.py`) after the neutral line. First full runs (10 Nov 2026, one run each): + deepseek-v4.1-flash 92/94 alone and 92/94 with the instructions, gpt-6-luna 89/94 alone. The gate's second round (the same day, after the period rule and the descriptions above): deepseek 90/94 alone and 90/94 with the instructions, gpt-6-luna 90/94 and 87/94; each failure asked 3 times more, those that failed 2 of 3 or worse fixed in the descriptions (wind 3m, a rating against rain, lowest and highest, air quality against rain, today against yesterday) and then passing 3 of 3. The bot's own code paths call the ten instead of the twelve: its shortcuts, report, lookups, Help, gauges and + alert charts, through `lib/service/legacy.py` (the old call and the `Turn`'s inputs read as the service's call, in one place, + deleted whole in step 3), quoting their words; its answers pinned before and after (`tests/test_service_switch.py`), unchanged but + for the deliberate changes below. Its gauges (the dashboard, the report's three) are `current` with `context` and the gauges' + readings named (the air sensor isn't read), laid out bot-side (`lib/gauge_sheet.py`); `Ecowitt.dashboard()` and `sheet()` are gone. + It asks for its charts as drawn (request `_meta` `chart_points: "drawn"`), since a chart of each day's average over years has more + points than 500. Period buttons replay the chart's `drawn_by` with a new `period` (the buttons, their keyboard and the picture + cache stay in the bot; the service knows nothing of buttons), one button per `drawn_by.periods` entry with the service's label; + when it lists none, a 🔄 that replays the call as it is if its period runs to now (through yesterday for a whole-day tool), else + nothing; the chart's own shaded 1D, when it runs to now, draws it again with the latest readings (a longer period's does nothing); + a replay the service refuses shows its refusal on the button, and one that fails after "Drawing ..." says so in the chat. What the + bot draws ahead replays calls at background priority: the other periods after a chart is sent, the keyboard's charts every 5 + minutes, recent alerts' charts. The picture cache and the pre-upload are keyed by the call, so two wordings or two chats share a + picture. Deliberate changes: a count per month offers 3M, 1Y and All (never 1D), per year a 🔄 (its period runs to now); whole-day + `1y` is the 365 days to yesterday (364 and today before); alert charts name their source. Until step 3, a chart the model draws + through the twelve gets a `drawn_by` from `legacy.py` when its call translates and lists periods; otherwise (`plot_chart`, the + links and the scan, a period given as times) its buttons ask its question again, as before. Left for later: `current` and `outlook` + read the sources' kept live readings through private members (`Ecowitt._live`, `AirGradient._current`); `fetch: false` doesn't stop + the air sensor's inline fetch; `tests/report_words.py` keeps the old report's words as the tests' reference, deleted with the bot. +3. **The swap** (done), gated on the live evals (all cases, the production model and one other, with the tool list alone and with + the instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the + period hints, the prefetch and the corrections from the words go. The bot offers the ten as they are (`lib/model_tools.py`: each + result kept whole for drawing and its buttons, the model sent it with each chart as its title and period and the bot's own + `chart_note`: the bot sends the chart, the reply its caption), with its persona, the server's instructions and the time + (`lib/prompt.py`); tool_choice is the model's own, the reasoning effort still comes from the words. Its shortcuts (`lib/intent.py`) + are fixed calls built directly: a named reading's chart and a period (summary with the person's words for both, the keyboard's and + the alerts' sentences among them; with no chart word, over more than a day or a day given as a number, "co2 1d"), weather now, the + report (current, pollen, the next 3 days' forecast) and the gauges; everything else it answered in code goes to the model. The turn + ends on a step whose every result is complete. The live-chart link goes under an answer whose calls read the air (`bot.reads_air`), + and the forecast days shown, by `forecast` or `outlook`, are recorded for the forecast alert. `lib/service/legacy.py` is gone; the + `Turn` is only the engines' options, set by the service from its arguments. `--live` asks the model as the bot does (its prompt, + the ten tools; a question answered in code is scored by its fixed calls). The gate, one run each of 94 cases (DeepSeek v4.1 flash, + the production model, and gpt-6-luna): the bot as it runs 90 and 92 (today's bot with the twelve: 90); the tool list alone 91 and + 92; with the instructions 91 and 93. What fails is mostly a model leaving `group_by` out of a figure per month or year (the twelve + had it filled in from the words): `days` says so in its result (`note_group_by`) and the model calls again; the rest are one-off or + refusals a model corrects in its next call. Expectations are widened where another call answers as well, not the descriptions + tightened. The instructions say every question is fetched afresh, a follow-up or a challenge too. +4. **Alerts in the service** (done). The rules, their state and config move service-side and append events to the alert log, with + `expires`, `link` and `chart` (with its `drawn_by`); the forecast alert gets its station-wide baseline. The bot delivers from the log. + - **The log** (`lib/alert_log.py`): 3.6's events, `since(id, expired=False)`, `get(id)`, `last_id()`, and `wait(after)`, an asyncio + notification on each append that step 5's listen will use. Its own SQLite file in `DATA_DIR` (`alerts.sqlite`), not the readings + file: it must exist whatever sources run (pollen and the forecast need no readings file), it is written in tiny rows from the event + loop while the readings file takes bulk writes from worker threads, and it can be looked at or deleted alone. Ids are + AUTOINCREMENT, so they never go back; events older than 30 days are dropped when it opens. Times are ISO local with their offset. + - **The rules** (`lib/alerts/`: weather, particulates, pollen and asthma, forecast) append events and know nothing of chats or + Telegram; `lib/service/alerts.py` (`AlertRules`) starts them on today's triggers. Their texts are today's, byte for byte, but the + forecast's. `expires`: rain (started, stopped, the overnight summary) an hour, gusts and UV their rearm time (an hour), the + temperature crossing its cooldown, particulates the next check (30 minutes), pollen the end of the day it is about, a forecast the + end of the day it is about. `link`: the AirGradient dashboard (particulates), the pollen site. `chart`: the alert chart as the + service gives it (`pictures.chart_data`: the button sentence's `summary` call, every point as drawn, as the bot's pictures were), + `drawn_by` included; made when the alert fires, whoever is listening (before, only when some chat got the alert). `data`: the + figures behind each. + - **Their state** is the service's (`lib/alerts/store.py`, `alert_state.json` beside `bot_state.json`): the first start with no + `alert_state.json` moves the rules' keys out of `bot_state.json`'s `monitor` (once), so nothing re-fires after the upgrade; the + irrigation controller's stay in the bot's file. **Config**: the quiet hours and the cooldown stay `MCP_RAIN_QUIET_HOURS` and + `MCP_ALERT_COOLDOWN_MINUTES`, handed to the rules (and `about`) by the service; the thresholds stay the rules' own constants, which + `about` reads, as no setting changes them today. + - **The forecast alert is station-wide** (deliberate): the first forecast fetched from 6 am is the day's baseline for today and + tomorrow (no alert); a later one alerts, one event per day, when the high moves by more than 2°C or the chance of at least 1 mm + rises from under 50% to 50% or more, or falls from 50% or more to 30% or less, and becomes that day's baseline. The 30% band is + kept: without it a chance hovering around 50% (rounded to 5%, refetched every 15 minutes) alerts likely, unlikely, likely through + the day. Its text says what changed: "🔄 The forecast for tomorrow has changed: the high is now 19°C (was 24°C) and rain is + now likely (80%, was 10%).\nNow: 🌧️ Rain. 10–19°C, 80% chance of rain". The bot no longer records the forecast days each answer + showed (`record_forecast`, `forecast_sent`, `shown` through the turn): nothing needs them, and the old record is dropped. + - **The bot delivers** (`lib/alerts/notify.AlertDelivery`): it waits on the log in process, sends each unexpired event after the last + id it handled (kept in `bot_state.json` as `alerts_read`, with the log's identity as `alerts_log`, so a log removed or replaced + starts it afresh after that log's newest, with a warning, rather than waiting for the new ids to pass the old) through the + Notifier as before (the chats subscribed to its kind, silent unless the chat turned sound on, the bell, the link as the footer), + with the chart drawn from the event's data, uploaded once. Its + first start begins after the newest event; after a gap it skips what expired. The 🔄 under a chart names the event + (`al:refresh:<kind>:<id>`) and replays the chart's `drawn_by` from the log (a chart drawn ahead since the message changed is still + sent first); an alert sent before the log, or one dropped from it, draws its type's chart as before. Irrigation alerts are sent by + the bot as before. + - Tests: the rules' tests assert events appended (`tests/test_alerts.py`), the log and the delivery (`tests/test_alert_log.py`), the + forecast baseline (`tests/test_forecast_alert.py`). +5. **MCP, and the service on its own.** `lib/mcp_server.py` serves the tools, resources and prompts (the bus and listen handler, the + transport settings, the token check); the service starts as its own program (`python -m ecobot_mcp`, its compose file); the bot becomes a client over the network (the supervisor, discover for the instructions, `charts` from results, the + alert log; `schemas/` goes into the image, which `.dockerignore` keeps out today). `ecobot.py`'s `warm_up()` is split: the first + fetch, the archive, the backfill, the Home Assistant imports and the startup line go to the service; the bot keeps only its charts + drawn ahead, as `summary` calls at background priority, failing quietly until the service has warmed. The bot's poke of the sources + when a question arrives goes: the service's keep-warm and the tools' own fetches cover it. Then the irrigation server is built in its own + repository against it, the bot connects to both, and `lib/irrigation` goes from here. The service's scripts (`edit_readings`, + `cache_status`, `refill_airgradient`, `check_rain`, `bench_storage`, `conditions`, `ecowitt_metrics`, `dump_specs`) stay; + `show_request` becomes an MCP client (`report_inputs`, what the report written in code was made from, went with it in step 6c). + - **The service side (done).** `lib/mcp_server.py` (`EcobotServer`): the SDK's low-level `Server` with the ten tools (their + hand-written schemas, `readOnlyHint` and `openWorldHint` from each ServiceTool, the list built from the current catalogue; a call + runs the ServiceTool with the request's `_meta` and answers its JSON unchanged as one text block, `isError` for a refusal, a + complete answer with its `reply` as a second block for `audience: ["user"]` and result `_meta` `{"ecobot/complete": true}`), + 3.4's resources and the alerts' template, 3.5's prompts, the instructions, and `subscriptions/listen` (`InMemorySubscriptionBus`, + `ListenHandler`): `ResourceUpdated` for the live resources when what the sources keep changes (compared every 2 s, nothing fetched + for it; a reading asked for again and unchanged is not sent), the alerts on each new event (`AlertLog.wait`), the station and + `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 + `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 + `schemas/`; compose has `ecobot-mcp`, off unless its profile is asked for. Tests: `tests/test_mcp_server.py` (in memory) and + `tests/test_mcp_listen.py` (uvicorn on a localhost port: the lost listen and the reading after the last id, auth, hosts, the service started with the fakes and called through a proxy's Host name). Settings: `Config.from_env(bot=False)` needs + no Telegram token. + - **The bot as a client (done).** `BOT_MCP_URL` set (the token: the first of `AUTH_TOKENS`, or the generated one): the bot starts no sources, syncers or alert rules + (`ecobot.connect`); unset: it runs the service in-process, unchanged. Both go through one interface, `lib/weather.py` + (`LocalWeather` over lib/service and the sources; `RemoteWeather` over MCP): the tools as `Service` lists them (each `call(args, + meta)` answering the tool's JSON), the sources there are (`names`), the catalogue, the instructions, the AirGradient link, the + alert feed and one alert by id, a resource, and whether it can be reached. `RemoteWeather` is 3.8's client: `lib/upstream.Upstream` + (pinned to 2026-07-28, `send_discover` and `adopt` for the instructions, one supervisor task that drops the client on a transport + error or a lost or ended listen and builds another after a backoff, the 45-second read timeout), listening to the station, the + alerts and the forecast; each connection reads the tool list and the station again (`ToolsListChanged` and the station's + `ResourceUpdated` too). The station gives the time zone, the sources (`names`: the alert menu, the report's calls, the gauges, Help + and `/usage`), the catalogue the shortcuts read their words against (`Catalogue.listed`) and the AirGradient dashboard. The model's + tools follow the service's list (`model_tools.ServiceTools`), charts stripped for the model as before; the shortcuts, report, + gauges, period buttons and 🔄 replays, charts drawn ahead and preloads call the same tools. Alert delivery + (`AlertDelivery`) reads `ecobot://alerts?since=<last id handled>`, woken by the listen's `ResourceUpdated` for `ecobot://alerts` + and by each new connection (nothing is replayed), resuming from the id kept in `bot_state.json` as before; the 🔄 under an alert + finds its event with the template (`since` the id before it, `expired=true`). Each read is checked against the log's identity, so + the service back on another `alerts.sqlite` while the bot runs (removed, moved, redeployed) is noticed at once: delivery goes on in + the new log with its events from after the old one was last read, with a warning. The station's time zone is the bot's whenever + it is read: one read after the start (the service not up within 30 seconds) moves the bot's settings, the charts, the alert + delivery and the irrigation check (its wait for the check time timed again) into it; it is kept in `bot_state.json` + (`station_zone`), and a start while the service can't be reached runs in the zone last read, `TZ` only before any. A question's call waits up to 5 seconds while the + client is being built again, a background one not at all; a question while the service can't be reached is answered that it can't + (`bot.SERVICE_DOWN`), without the model. The bot's `warm_up` is its charts drawn ahead, every 5 minutes, quietly nothing while the + service is away; the poke of the sources is gone (there are none). Irrigation stays in the bot until step 8: its daily check reads the + measured rain from `summary {readings: ["rain"], period: "last 24 hours"}` (`ServiceRain`) and the forecast from `ecobot://forecast` + (`ServiceForecast`, read again at each check and on each `ResourceUpdated`; the one last read stands when the service can't be + reached). Tests: `tests/test_bot_remote.py` (the bot against the real server, in memory and under uvicorn: a question answered with + the remote tools and the instructions from discover, a chart from a remote result with its buttons, an alert through the listen, a + dropped connection rebuilt and the alerts after the last id read once, the service down, `ecobot.main()` as a client); the path + with the setting unset is the rest of the suite, unchanged. + - **Chart images (done).** The service draws a result's charts as PNGs for a client that asks (3.7: `?charts=png` on its URL, or + request `_meta` `chart_image`; `chart_dark`; the full JSON in result `_meta` `"ecobot/charts"`, the theme in `"ecobot/chart_dark"`), + with `lib/chart_images.py`, which imports Pillow and the renderer only at the first image (Pillow is `requirements-charts.txt`; + without it, the JSON with a note and one warning). `lib/weather.py` gains `chart_image(name, args, meta)` and `picture(chart)` + (`ChartImage`: the PNG, the chart's JSON, the theme): `LocalWeather` draws in-process with `lib/charts.render_data`, + `RemoteWeather` asks the service and takes the PNG from the `ImageContent` and the chart and theme from `_meta` (an alert's + chart by replaying its `drawn_by`; a service that sends no image has it drawn here). The bot's `_draw_call` (charts drawn ahead, + preloads, the 🔄 under an alert), the period buttons and the alerts' pictures (`lib/alerts/pictures.py`, `AlertDelivery`) use it; + the image cache keeps the theme the service drew in. The model path is unchanged; a question's charts and the dashboard are still + drawn by the bot. Tests: `tests/test_mcp_server.py` (in memory and under uvicorn: off unchanged, the URL's `?charts=png`, the + per-call override both ways, without Pillow, no Pillow imported by the server), `tests/test_bot_remote.py` (the service's PNG + byte for byte the bot's own, for a call and an alert's chart). Then **chart links** (3.7, `?charts=link`, for LibreChat and other + chat apps that show a markdown image in the reply but not a tool's image): the same PNGs kept in memory and served at + `/charts/<id>.png` (`chart_images.Links`, `MCP_CHART_BASE_URL`, `MCP_CHART_LINK_HOURS`), the text with each chart's `url` and + `markdown`, a `ResourceLink` per chart. Tests: `tests/test_mcp_server.py` (in memory and under uvicorn: the link served byte for + byte as png mode's image, without a token or an allowed Host, `/mcp` still needing both; the override both ways; 404 for an + unknown or expired id; the base URL from the setting and the proxy's headers; the store's bounds; the bot unaffected). + - **Left:** the irrigation server, now step 8; and `show_request` as an MCP client. +6. **The slim bot** (done; decided November 2026, in place of retiring it: section 4 describes the bot as it was). The Telegram bot is kept, but only as a thin client of ecobot-mcp: it does what only a Telegram bot can do + (chats, buttons, pushing alerts), and everything about the weather, the air, the alerts' rules and the pictures comes from + ecobot-mcp over MCP. It never opens the readings file and draws nothing. Sub-steps, each its own change with the checks green: + + - **6a. Every picture from ecobot-mcp.** The charts in the model's answers and in the keyboard's answers come from ecobot-mcp as + images (request `_meta` `chart_image: "png"`): the bot keeps the image blocks and `ecobot/charts` (for the period buttons) and + gives the model only the text (`for_model`, as today). The bot then imports neither Pillow nor `lib/charts.py`, + `lib/draw.py` or `lib/gauges.py`. + *Done:* `lib/weather.py` `call_images` (every chart of a call, as `ChartImage`s; remote from the `ImageContent`s and `_meta`, + in-process drawn by ecobot-mcp's part with `lib/chart_images.render`) is what the model's tools call (`lib/model_tools.py`: the + pictures kept on `Turn.pictures`, the model sent `for_model` of the text) and what a typed chart uses; a service that sends no + image gives the answer without its picture (the bot no longer draws one itself, nor an alert's). `DARKMODE` moved to + `lib/theme.py`, so the bot keeps its theme without the renderer; in-process, `ecobot.py` hands the bot a `LocalWeather`. Tests: + `tests/test_bot.py` (the bot's modules, imported and built as a client, import no Pillow and no drawing module, in a subprocess), + `tests/test_bot_remote.py` (the model's chart is the service's PNG, asked with `chart_image: "png"`, the model sent the text + alone; a service without Pillow: no picture). + - **The gauges.** The Telegram dashboard goes: the Dashboard button, `/dashboard`, the whole gauge sheet as a picture and its + tables. The dashboard is the web page now (below). Kept: the Status picture's three gauges (Temperature, Humidity, Rain), + without the Daily/Monthly/Yearly Max/Min tables under them. ecobot-mcp draws it (a `status` picture: a tool or resource that + returns the PNG, its readings as text), and the bot sends it with Status (`/status`), the report ecobot-mcp + writes as its caption. The PNG drawing (`lib/gauges.py`) then lives only in ecobot-mcp and draws only those + three; `lib/gauge_sheet.py`'s tiles still feed the web page, which keeps every gauge and its tables. + *Done:* a resource, `ecobot://status` (3.4, `lib/status.py`): its readings as JSON text, then the PNG as a blob. A resource, not + a tool, because it is for the client, not the model: a tool would join every client's tool list (and the evals'), and a model + has `current` for the readings; a resource is read by the client when its person asks for Status, and a model never sees it. + The picture has no tables (`lib/gauges.py`, tiles `TILE_H` high); the resource's text keeps the highs and lows. The Telegram + dashboard's button, command, words, picture and 🔄 are gone ("dashboard" typed goes to the model; an old 🔄 says it is out + of date). Tests: `tests/test_mcp_server.py` (the resource, its PNG and JSON, without Pillow), `tests/test_bot_remote.py` (Status + sends ecobot://status's PNG byte for byte), `tests/test_dashboard.py`, the reference image `tests/charts/status.png`. + The gauges' live page is already ecobot-mcp's: `/dashboard` beside `/mcp` (`lib/web_dashboard.py`, `MCP_DASHBOARD`, on by + default) is a self-contained HTML5 page drawing the same tiles in the browser (inline SVG, `lib/gauge_look.py`'s colours and + 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 + 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. + - **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). + *Done:* without `BOT_MCP_URL` the bot stops at start, saying to run ecobot-mcp and set it (`lib/config.py` `NO_SERVICE`); the bot + reads only its own settings (`BOT_`) and the shared ones, ecobot-mcp's (`MCP_`) keeping their defaults in its `Config`. + `ecobot.py` only connects (`connect`, `RemoteWeather`): `LocalWeather`, the bot's start of the sources, the syncers, the alert rules + and the alert log, the keep-warm, the archive, the backfills, Home Assistant's imports and the data-folder lock from the bot's side are + gone, with what only they used (the sources' `wants` and `poke`, the warmer's question-started refresh, `Core.start_alerts`'s move + of the rules' state out of the bot's file, the irrigation check reading the station's own rows: it asks `summary` for the rain). + `Bot(cfg, agent, state, irrigation, tasks, service=weather)` takes ecobot-mcp as the bot reaches it and nothing else; an alert's + picture is always ecobot-mcp's (`lib/alerts/pictures.chart(text, tz, weather)`, `picture_of(data, tz, weather)`). The bot's modules + import no source module: `lib/ecowitt/calendar.py` is `lib/public_holidays.py` (the period reader's), `version()` is + `lib/version.py`, `RAIN_FROM_PCT` is `lib/alerts/kinds.py`'s. Under systemd `ecobot.service` has `Wants=` and `After=` + `ecobot-mcp.service`, and the README installs and enables both, ecobot-mcp first (with upgrade notes for a bot that ran alone). The + bot's Docker image installs `requirements-bot.txt` alone (python-telegram-bot, openai, mcp, httpx; `requirements.txt` is both + programs', for a systemd install's one venv) and its build checks the bot imports no Pillow and no source module. Tests: the + `serve` fixture (`tests/served.py`: the real server over a test's Context or stand-in tools, the bot's `RemoteWeather` connected in + memory) is what every test of the bot runs it against; `tests/test_bot.py` (the bot's modules, imported and built with its alert + delivery and irrigation check, import no Pillow, no drawing module and no source module, in a subprocess), + `tests/test_settings.py` (the bot reads only its own and the shared settings, and stops without `BOT_MCP_URL`), + `tests/test_startup.py` (ecobot-mcp's main over the fake sources; the bot's against ecobot-mcp under uvicorn), + `tests/test_packaging.py` (requirements-bot.txt, the bot's image, the units and the README's install). + - **6c. Less code in the bot.** + - Typed shortcuts go: anything typed goes to the model (`lib/intent.py`'s pattern matching, `chart_call`, the dashboard and + report words). Buttons stay instant because each is a fixed call. + - **ecobot-mcp's prompts become Telegram commands.** On connecting, the bot reads the prompt list and sets Telegram's command + menu (`setMyCommands`) to its own commands (`/start`, `/alerts`, `/usage`, `/keyboard`, `/reset`, and the keyboard's + instant charts: `/rain`, `/weather`, `/temperature`, …) and one command per prompt, with its description; again whenever + ecobot-mcp says its prompts changed (`PromptsListChanged`, which the bot already listens for). `/<prompt> <text>` gets the + prompt with the words after the command as its arguments, in order, the last taking the rest (`/chart rain 7d` is `chart` + with `reading` "rain" and `period` "7d"; `/rainfall last week` is `rainfall` with `period` "last week"; none: the + prompt's defaults), and asks the model with it, as a typed question. A prompt whose + name isn't a valid Telegram command, or is one of the bot's own, is left out with a warning. So a prompt added to ecobot-mcp + appears in Telegram, as in any other client, with no change to the bot. + - `/report` is the `report` prompt: the report written in code (`lib/report.py`, `lib/report_menu.py`) is deleted. + - The charts drawn ahead every 5 minutes go (`draw_buttons_ahead`). Kept: after a chart is sent, its other periods are fetched + (and, with `BOT_TELEGRAM_PRELOAD_CHAT`, uploaded) in the background, so its period buttons answer at once. A keyboard button's + first press waits for ecobot-mcp, about half a second. + - Without `BOT_OPENROUTER_API_KEY` the bot answers the buttons and sends alerts; a typed question gets one line saying the + model isn't set up (the no-model fallbacks go). + - The test-only oracles from step 3 (`tests/old_tools.py`, `tests/report_words.py`) are deleted. + *Done:* `lib/intent.py` keeps only the reasoning effort (`intent.effort`): its patterns for the report, "weather now", the + dashboard and a named reading's chart (`chart_call`) are gone, and anything typed goes to the model. The keyboard's chart buttons + are fixed calls (`lib/templates.py` `CALLS`, the calls they were read as before), answered by `Bot.press` with no model (a chart the + service can't draw says why); the alerts' charts are the same calls (`lib/alerts/pictures.py` `CHARTS`), so neither the bot nor + ecobot-mcp's rules read words. `RemoteWeather` reads ecobot-mcp's prompts on each connection and on `PromptsListChanged` + (`prompts`, `on_prompts`, `prompt(name, arguments)`); `Bot.publish_commands` sets Telegram's menu to the bot's own commands + (`templates.MENU`: `/status`, the charts, `/alerts`, `/usage`, `/keyboard`, `/reset`) with one per prompt after the charts', and + again when it changes (a prompt whose name Telegram won't take, or that is one of the bot's own, left out with a warning); + `Bot.on_command` answers `/<prompt> <words>` (`prompt_arguments`: in order, the last taking the rest; a refusal such as `/chart` + with no reading is said in the chat; another bot's command is left alone). `/report` is the `report` prompt; Status is a + keyboard button, so a fixed read with no model: one message, `ecobot://status`'s picture with the report ecobot-mcp writes in + code as its caption (its `report`: current's sections, today's forecast, the pollen) and a 🔄 that reads it again in place + (`Bot.status`, `Bot.on_status_button`). (Built first as the picture, then the report prompt's answer as a second message: two + messages, no 🔄 and a model call for a button; changed.) `lib/report.py`, `lib/report_menu.py` and + `scripts/report_inputs.py` are deleted (an old report's 🔄 is out of date). `draw_buttons_ahead`, its loop and the alert charts kept + warm are gone; after any chart is sent its other periods are fetched in the background, with or without + `BOT_TELEGRAM_PRELOAD_CHAT` (`Bot.preload_soon`). Without the model a typed question gets `NO_MODEL`, one line. The evals' cases + keep only the effort (now pinned for every case); the cases answered in code before (the report, "sitrep", "weather now" and 13 + named charts: 3m-wind-chart, weather-week, weather-4-months, pressure-week, wind-3m, ecowitt-week, ag-week, button-rain-chart, + button-humidity-chart, chart-pressure-30d, chart-weather-90d, chart-all-90d, chart-only-answers-itself) go to the model in bot + mode, their expected calls unchanged (`tests/evalkit.py` lost `SHORTCUT_LEAVES` and `in_code`). The oracles' tests now run + against the service's tools or lib's engines (`tests/engines.py`), and current's words are pinned (`tests/current_words.json`). + Tests: `tests/test_bot_remote.py` (prompts as commands over MCP, their arguments and refusals, the menu set again on + `PromptsListChanged`, Status's gauges and the report prompt), `tests/test_dashboard.py` (Status with and without its gauges or + the model), `tests/test_bot.py`, `tests/test_templates.py`, `tests/test_periods.py` (the other periods fetched without the preload + chat), `tests/test_startup.py` (the menu at start), `tests/test_admin_only.py` (a stranger refused a prompt command). + + **What the bot keeps:** + - **Telegram:** who may use it (`BOT_ADMIN_ONLY`, `BOT_ADMIN_CHAT_IDS`, group admins), private and group chats, the keyboard, the + per-chat state (`bot_state.json`: chats, alert subscriptions and sound, each chart message's `drawn_by`, the last alert read). + - **Questions:** the model loop with ecobot-mcp's tools, its instructions (from discover) and a short persona prompt (tone, + Telegram formatting, group-chat names, the chart caption rule). + - **Alerts:** listening to `ecobot://alerts`, sending each to the chats subscribed to its kind with its picture, the alert menus + (on/off and sound per kind), 🔄 under an alert's chart. + - **Charts:** the keyboard's chart buttons (each a fixed call), the period buttons and 🔄 (replaying `drawn_by`), Status's picture + of three gauges (from ecobot-mcp), and Help from `about`. + + **What it leaves** (measured: the bot's files went from 3,676 lines of code to 3,413; steps 3 to 5 had already moved the weather + work to ecobot-mcp, so what was left was mostly Telegram's): `lib/bot.py`, `lib/weather.py` (the remote half), + `lib/upstream.py`, `lib/model_tools.py`, `lib/llm.py`, `lib/prompt.py`, `lib/alerts/notify.py` and `menu.py`, `lib/periods.py` + (the buttons), `lib/templates.py` (the keyboard), `lib/admins.py`, `lib/buttons.py`, `lib/config.py` (its `BOT_` settings). + + **Gates:** the offline evals (every typed case now goes to the model: the "answered in code" cases become model cases, their + expected calls unchanged); a live eval run on the production model only after asking (the typed shortcuts' cases are the ones + that change); the remote-bot tests over uvicorn; a check that the bot imports no Pillow and no source module. + + **Risks:** a typed chart request ("rain chart 7d") now costs a model call and a second or two, where it was instant; a keyboard + button's first press waits for ecobot-mcp; the bot does nothing without ecobot-mcp (it says so, as today). +7. **Faster: the storage, and the test suite.** The suite (1793 tests, `python -m pytest -q`, 4 workers) takes 46-49 s with the fake + archive cached (about 65 s when it is rebuilt after a change to lib/storage, lib/ecowitt or tests/fakes.py), against a wish of + 20 s. Its setup is cheap now (a test's copy of the archive and its station: 30 ms); the time is the tests' own work, about 154 s of + it, much of it the storage code the service runs for real questions, so speeding that up speeds up both. From a profile of the + whole suite run serially (November 2026), each its own change, every test and assertion kept: + - **7a. Rows into columns in one step** (`lib/storage/read.py` `rows`: 12 s, 42 million list appends): `itertools.groupby` over + the rows by sensor and `zip(*rows)`, in C. Written and passing the storage tests; set aside until this step. + - **7b. The queries** (21 s in SQLite over 94,000 queries): the largest is writing day rows (`lib/storage/days.py` `_insert`, + 13 s over 12,800 queries), then the roll-ups (`write.py` `roll_up`, 2 s) and `read.py` `part_days` (1.5 s). EXPLAIN QUERY PLAN + each for a table scan or a missing index, and look for the same work done twice within one write or one question. + - **7c. Closing the file** (4.5 s over 3,000 closes): likely a WAL checkpoint at each close; any change here touches how writes + are made durable, so it needs care. + - **7d. Python loops over every reading** for the day figures and summaries (`lib/lines.py` `_summarise`, `lib/ecowitt/reads.py` + `readings_on`: about 10 s): the riskiest, as they make the figures people see; checked against a full-size archive before and + after, not only the tests. + Measured after each. Also waiting (about 42 s of the serial run on timers, servers stopping and a browser; the browser test alone is + 11 s). If still short of 20 s after 7a-7d: mark the heaviest groups (the browser tests, the reference images, the benchmark, the + tests that start servers) `slow`, so plain `pytest` leaves them to `pytest -m slow` and CI, which runs all. The hangs are fixed and + a stuck test fails after 60 s (pytest-timeout). + + *Done* (measured warm, four workers; serially the tests' own time was 137 s): + - 7a as written: 48-50 s to 44.9 s. + - 7b: every query reads by the primary key (EXPLAIN QUERY PLAN: no table scan, no missing index); the day rows' cost is the work + itself, done after every write a test makes. Nothing changed. + - 7c: closing a copy of the archive takes 3 ms (the `PRAGMA optimize` and the close); in the profile of the heaviest test files + closes were 0.06 s. Nothing changed. + - 7d: `daily_summary` places each reading in its day by the day's span (`lines.day_of`, the same day as `local_date` in every zone, + tested), the station's readings rounded inline (`ecowitt/reads.py`) and a row's column names worked out once (`write.py` `put`): a + year of 5-minute readings' days in 0.010 s instead of 0.062 s; within the noise for the suite (45.4 s). + - The fallback: the 60 tests of 0.5 s or more (`tests/slow_tests.txt`, written by `scripts/slow_tests.py`) are marked `slow` and + left out of plain `pytest`: 1731 tests in 19 s. `pytest -m slow` runs them (32 s), `pytest -m ""` everything (about 45 s), as CI + does. +8. **Irrigation on its own** (was 5b): the irrigation server as its own package, MCP server and Docker image in this repository (3.9). + *Done.* + - **8a (done):** irrigation-mcp (`irrigation_mcp/`, `lib/irrigation/server.py`): its tools, the watchdog and the daily check + (`lib/irrigation/check.py`, moved from `lib/alerts/irrigation.py`) as ecobot-mcp's client (`lib/irrigation/ecobot.py`), + `irrigation://alerts`, its state with the one-time copy from `bot_state.json`, its settings (`IRRIGATION_*`, a setting may have + several old names, `scripts/migrate_env.py` too), its image (`--target irrigation-mcp`, compose's `irrigation` profile). What the + two servers share over HTTP moved to `lib/mcp_http.py`. The bot kept its own irrigation meanwhile, reading `IRRIGATION_TUYA_*`. + - **8b (done):** the bot connects to it as a second server (`BOT_IRRIGATION_MCP_URL`, `lib/irrigation_remote.RemoteIrrigation` over + `lib/upstream.Upstream`, which now names its server in its log and refusals) and delivers `irrigation://alerts` as it delivers + `ecobot://alerts` (`lib/weather.RemoteAlerts` given the URI; its last id a `ReadMark` of its own in `bot_state.json`). Its own Tuya + client, watchdog and check wiring went from `ecobot.py`; the menu moved to `lib/irrigation_menu.py` (the bot's UI), with what it + shares with irrigation-mcp in `lib/irrigation/common.py`, and `lib/irrigation` loads nothing until asked, so the bot never loads + Tuya: the bot's import test (and its Docker build) keeps `lib/irrigation/tuya`, `watchdog`, `check` and `server` out. The bot reads + no `IRRIGATION_` setting (a Tuya setting left without `BOT_IRRIGATION_MCP_URL` is a warning at start), nor the forecast (the check's). + Packaging: `irrigation-mcp.service` (wants ecobot-mcp's, before the bot's; the bot's unit wants it only as a wish, and drops the + Tuya secrets), compose's host-network and journald files cover irrigation-mcp, `docker/bot.env` leaves `BOT_IRRIGATION_MCP_URL` + empty, and `scripts/migrate_env.py` adds it for systemd where the Tuya settings are. Tests: the bot's irrigation tests run against + irrigation-mcp in memory over the fake controller (`tests/served.py`), an irrigation alert reaches the chats through the listen once, + irrigation-mcp down is said; the controller's own tests (Tuya, the check, the watchdog) are `tests/test_irrigation_controller.py`, + without Telegram. + +## 7. Testing + +- **Any model can use it.** The evals are the service's: each question is asked of a model given only the tool list (no prompt of + ours), and again with the server's instructions, and checked for the tools and arguments it picks and, where it matters, the answer. + They run against the production model and at least one other, so the interface isn't tuned to one model's habits. The cases carry + over from `tests/evals/cases.json`, with their periods checked as the service reads them, and gain one for each periods form, each + routing rule (a record or a day, a chart or a figure per month), `outlook`, `about` and `chart_answers_it`. The tools-alone runs + answer every call "no data" and score every call of the turn (what the descriptions lead to); the bot's run (`--live`) answers + each call from the real tools over a frozen world (the fake station's archive, copied fresh for each run of each case, and the other + sources' fakes at the cases' fixed time), so the model sees real results, notes and refusals and is scored over its whole turn: any + call that was not refused may meet the expectation, none may be a forbidden tool, and more than 8 calls, an empty or fallback reply, + or a refused call that no call to the same tool answered in a later step corrects fails. +- **The contract:** a test per tool and resource for the arguments it takes and the shape it returns (`test_contract`); the periods + table at its fixed times (step 1); charts against their schema; every chart's `drawn_by`, replayed, draws the same chart, + and with only `period` changed to each of its `periods`, the same chart over that period, never an error; `day_look` against its rule. +- `days.hours` gives, for a stretch that is the whole day ("00:00-24:00"), the same figures as its day row for every day held whole at + 5 or 30 minutes (the air sensor's at 5 minutes or an hour), a clock-change day included; a day from a daily record, or from whatever + readings there were, is left out and counted. +- **Alerts:** the rules' tests move with them; the log keeps order and survives a restart; a client that reconnects reads what it + missed, once, and nothing that has expired; the forecast alert's baseline. +- **A client that listens:** against the real app under uvicorn on a localhost port the test stops and starts (not in memory: a + connection can't fail there, and the in-memory HTTP transport buffers a listen stream): the listen is lost, the client listens again + and reads the alerts after its last id; the bot's model request carries the instructions from discover. +- **A deploy check:** a tool call through the proxy's name succeeds (the allowed hosts and the token). +- **Chart images:** off, a result is as it was; asked by the URL (under uvicorn) or per call, each chart comes as a PNG byte for byte + the bot's own render, its JSON in `_meta`; a call overrides its connection both ways; without Pillow, the JSON with a note and one + warning; importing the server imports no Pillow. + +## 8. Risks + +- **Alerts reach only listening clients.** With alerts over MCP only (3.6), nobody gets them unless a client that listens is running: + the bot, which stays (step 6), or another. +- **Charts only where a client can draw.** A client that neither draws the chart data nor lets its model draw gets the figures without + a picture. +- **Models other than ours.** A client's model may be weaker, or tuned differently, than the one the evals were built on; some clients + never pass the instructions on. The descriptions and results as the contract, and the evals across models with and without the + instructions, are the defence, and every answer still rests on figures the model quotes, not works out. +- **Every question through a model.** Without the bot's shortcuts each question costs at least one model call; that is the client's + choice and cost. A chart that answers the question costs only one where the client ends the turn on a complete result (3.7). +- **A chart sent without the answer.** If a model sets `chart_answers_it` on a question that needed words, the person gets the chart + and its figures but not the answer: the description limits it to a question that is only the chart, the eval pair checks both + sides, and a follow-up goes to the model as usual. +- **A protocol still settling.** `subscriptions/listen` is the 2026-07-28 revision; listening clients pin it, and the SDK is upgraded + on both sides together. diff --git a/docs/features.md b/docs/features.md index bc588dc8..34327771 100644 --- a/docs/features.md +++ b/docs/features.md @@ -2,17 +2,18 @@ ## Ask it anything about your weather or air -Type a question in any chat the bot is in ("how hot is it?", "will it rain?", "rain by month for 2 years", "air quality 30d"). Simple lookups, reports and charts are worked out by the bot itself, instantly; only questions that need reasoning go to the AI model. +Type a question in any chat the bot is in ("how hot is it?", "will it rain?", "rain by month for 2 years", "air quality 30d"). Everything typed goes to the AI model, which answers with ecobot-mcp's tools (and asks it for any chart); the buttons and their commands are answered at once without it. With no model set up (`BOT_OPENROUTER_API_KEY` unset), a typed question gets one line saying so, and the buttons and alerts still work. -- **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. 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. -- **Reports:** `/report` (or the Status button, or typing "report", "status" or "weather now") lays out the weather station, the air quality and, if switched on, pollen and the forecast, with a 🔄 button. With the weather station it comes as the caption of a picture of three gauges (temperature, humidity and rain, each with its highs and lows today, this month and this year, as on `/dashboard`); Refresh redraws the picture too. A report too long for a caption goes as its own message after the picture, and its Refresh redraws only the text. -- **Dashboard:** `/dashboard` (or typing "dashboard" or "gauges") draws the weather station as one picture of gauges: temperature, humidity, pressure, dew point, feels like, wind, rain, rain rate, solar radiation and UV index (and the indoor sensor, if there is one). Each shows the reading now and its highest and lowest today, this month and this year (rain: the wettest day and the total), worked out from the history the bot has stored. No AI model is needed. Its 🔄 draws the gauges again with the latest readings, in the same message. +- **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). - **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. - **Analysis:** whether rain follows a reading, or how air quality relates to everything else, over the stored history. -- **Commands:** each chart or report button also works as a command, in private chats and groups: `/report` (or `/status`), `/dashboard`, `/rain`, `/weather`, `/temperature`, `/humidity`, `/air_quality`, `/particulates`, `/wind`. -- The commands also appear in Telegram's `/` menu beside the message box. +- **Commands:** each button also works as a command, in private chats and groups: `/status`, `/rain`, `/weather`, `/temperature`, `/humidity`, `/air_quality`, `/particulates`, `/wind` (the chart buttons are the last day; the period buttons under the chart change that). +- **ecobot-mcp's prompts as commands:** each of ecobot-mcp's prompts is a command too, with its description in the menu: `/report`, `/now`, `/will_it_rain`, `/weather_chart`, `/chart`, `/rainfall`, `/air`. The words after the command fill the prompt in, in order, the last taking the rest: `/chart rain 7d` charts rain over 7 days, `/rainfall last week` is last week's rain, and with no words the prompt's own defaults are used. The question is then answered by the AI model, as if typed. When ecobot-mcp's prompts change, the menu follows; a prompt whose name Telegram won't take as a command, or that has the name of one of the bot's own, is left out (the log says which). +- The commands appear in Telegram's `/` menu beside the message box. - **Private chats** also get a button keyboard (Help & Alerts, Status, Rain, Weather, Temperature, Humidity, Air Quality, Particulates, Wind) and show Telegram's "Thinking…" while the answer is written. ## Alerts @@ -26,18 +27,18 @@ Alerts go to every chat the bot is in, silently unless you turn sound on: - unhealthy air (two readings in a row), and when it is safe again, with the particulates chart - grass pollen or thunderstorm asthma risk reaching High (optional) - a forecast day you were told about changing substantially (optional) -- irrigation battery low, and the bot pausing watering for rain (optional) +- irrigation battery low, and irrigation-mcp pausing watering for rain (optional) -Every alert carries a 🔔 button that opens its toggles: **Alert** (on or off in this chat) and, in a private chat while that is on, **Sound**. An alert with a chart also has **🔄**, which puts the chart with the latest readings in the same message, the alert's text as it was (anyone in the chat can press it): for six hours after an alert its chart is kept drawn ahead with the keyboard's, so the press is answered at once. Every toggle in the bot is a blue button while on and a plain one with its name struck through while off. +Every alert carries a 🔔 button that opens its toggles: **Alert** (on or off in this chat) and, in a private chat while that is on, **Sound**. An alert with a chart also has **🔄**, which puts the chart with the latest readings in the same message, the alert's text as it was (anyone in the chat can press it). Every toggle in the bot is a blue button while on and a plain one with its name struck through while off. `/alerts` opens a menu with 🔔 Alerts and (in a private chat) 🔊 Sound. Each lists the alert types as toggles; while one is open only its own button shows (press it to close the list). `/alerts on` or `/alerts off` switches every type. A chat that blocks or removes the bot keeps its settings, which apply again when it comes back. In a group anyone can open `/alerts`, but only admins can change anything. ## Who can use it -By default the bot answers everyone who messages it. `ADMIN_ONLY=on` answers only the admins of the groups it is in, plus any ids in `ADMIN_CHAT_IDS`; everyone else is told it is for group admins. A refused sender is logged once, with their id, so the owner can add them to `ADMIN_CHAT_IDS`. See [configuration.md](configuration.md). +By default the bot answers everyone who messages it. `BOT_ADMIN_ONLY=on` answers only the admins of the groups it is in, plus any ids in `BOT_ADMIN_CHAT_IDS`; everyone else is told it is for group admins. A refused sender is logged once, with their id, so the owner can add them to `BOT_ADMIN_CHAT_IDS`. See [configuration.md](configuration.md). ## Optional extras -- **Pollen and thunderstorm asthma** for Melbourne (October to December), from melbournepollen.com.au: `POLLEN=on`. -- **Daily forecast** from Open-Meteo, with the chance of at least 1 mm of rain: `FORECAST=on`. -- **Irrigation controller** (a Tuya smart timer): an Irrigation button with its status and buttons to water for 5 to 30 minutes, switch off, pause for 24 to 72 hours, and its own alert toggles. A daily check at 18:00 delays watering 24 hours when rain fell or is likely. Set the `TUYA_*` variables. +- **Pollen and thunderstorm asthma** for Melbourne (October to December), from melbournepollen.com.au: `MCP_POLLEN=on`. +- **Daily forecast** from Open-Meteo, with the chance of at least 1 mm of rain: `MCP_FORECAST=on`. +- **Irrigation controller** (a Tuya smart timer): an Irrigation button with its status and buttons to water for 5 to 30 minutes, switch off, pause for 24 to 72 hours, and its own alert toggles. A daily check at 18:00 delays watering 24 hours when rain fell or is likely. The controller is its own MCP server, irrigation-mcp (README: Irrigation): set the `IRRIGATION_TUYA_*` variables for it, run it, and set `BOT_IRRIGATION_MCP_URL` for the bot. While irrigation-mcp can't be reached the button says it couldn't reach the controller; the rest of the bot carries on. diff --git a/docs/how-it-works.md b/docs/how-it-works.md index a1c4d47c..f509b033 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -9,22 +9,27 @@ The bot logs DEBUG and INFO lines to stdout and WARN and ERROR lines to stderr ( ## Layout ``` -ecobot.py wiring and lifecycle +ecobot.py the bot's wiring and lifecycle: ecobot-mcp's client (BOT_MCP_URL), and irrigation-mcp's (BOT_IRRIGATION_MCP_URL); it runs no source and no controller of its own +irrigation_mcp/ irrigation-mcp (python -m irrigation_mcp): the irrigation controller's MCP server, its watchdog and daily check (lib/irrigation) +ecobot_mcp/ ecobot-mcp (python -m ecobot_mcp): its startup (core.py: the sources, their syncers, the alert rules), the MCP server +lib/weather.py ecobot-mcp as the bot reaches it, over MCP (RemoteWeather); lib/upstream.py keeps the connection lib/config.py settings -lib/logs.py how log lines look: the module that spoke, and quoted requests and chat messages cut to LOG_WIDTH +lib/logs.py how log lines look: the module that spoke, and quoted requests and chat messages cut to BOT_LOG_WIDTH lib/bot.py Telegram handlers and replies; every button press comes in through one entry point that checks it first -lib/admins.py who may use the bot with ADMIN_ONLY: the admins of the groups it is in, plus ADMIN_CHAT_IDS +lib/admins.py who may use the bot with BOT_ADMIN_ONLY: the admins of the groups it is in, plus BOT_ADMIN_CHAT_IDS lib/llm.py, prompt.py tool-calling loop; system prompt -lib/intent.py intent.read(text) -> one Reading: effort, needs data, fast path, chart asks, period hints +lib/intent.py intent.effort(text): the reasoning effort of a typed question (nothing else is decided in code) lib/tools.py, warm.py tool registry and the per-question Turn; keep-warm helper shared by both sources lib/series.py the weather readings a chart can plot (one table) lib/lines.py the one rule that turns readings into a chart line (raw, bucketed, daily band, smoothing) lib/rain.py rain per slot, spells and bars from the daily total lib/analysis/ pairs (rain vs a reading, rain vs air quality), scan (air quality vs everything) lib/compose.py plot_chart / air_link / air_scan: any series on one time axis -lib/specs.py what a chart is (typed: Chart > Panel > Line/Bars/Shares), validated when built; stack() titles a stacked chart +lib/specs.py what a chart is (typed: Chart > Panel > Line/Bars/Shares), validated when built; stack() titles a stacked chart; + to_json / from_json: the chart as JSON (schemas/chart.json, versioned), times local with their offset lib/panels.py how a reading becomes a panel (title, unit, colour key, zones): every chart producer uses it -lib/charts.py the one renderer: panels on a shared time axis, rain behind the lines, one colour per reading +lib/charts.py the one renderer: panels on a shared time axis, rain behind the lines, one colour per reading; ecobot-mcp + draws every chart from its JSON (render_data) for a client that asks for pictures (the bot draws nothing) lib/captions.py when a chart is drawn, and the hint that makes the model's reply its caption lib/ecowitt/ api, fetch (what a job reads, from the storage or Ecowitt), reads and period (what a question reads of the storage: its period's days, readings, lines), extremes, query (one history question), link (weather_link), days (rank/count @@ -33,8 +38,10 @@ lib/airgradient/ metrics, readings (its readings in the bot's file), loca history of the monitor), days (air_days), source lib/storage/ the bot's one file, ecobot.sqlite (docs/storage-plan.md): both sensors' readings, their day rows, the pollen page and the forecast; catalogue, schema, coverage, write, days, read -lib/alerts/ notify (chats, silent send), rules (when an alert may repeat), weather, particulates, pollen_and_asthma, irrigation (battery and rain delay) -lib/irrigation/ the optional Tuya irrigation controller: tuya (signed API client), menu (status text and buttons), watchdog (closes the valve after a run) +lib/alerts/ notify (chats, silent send, the alert deliveries), rules (when an alert may repeat), weather, particulates, pollen_and_asthma +lib/irrigation/ irrigation-mcp's (python -m irrigation_mcp, the optional Tuya irrigation controller's own MCP server): tuya (signed API client), + watchdog (closes the valve after a run), check (battery and rain delay), server, state, ecobot (its client of ecobot-mcp), common +lib/irrigation_menu.py the bot's irrigation status text and buttons; lib/irrigation_remote.py: the bot as irrigation-mcp's client lib/pollen/, forecast/ the optional website sources: pollen + thunderstorm asthma, Open-Meteo forecast (fetched only 6 am-6 pm, see warm.py SYNC_HOURS) tests/ pytest, against fake Ecowitt/AirGradient/Telegram; tests/evals holds the routing cases, tests/charts the chart reference images scripts/ ecowitt_metrics.py (which metrics the station reports), cache_status.py (what ecobot.sqlite holds, and its gaps), edit_readings.py (find a spike, e.g. a sensor breathed on, see it among the readings either side, and change it in ecobot.sqlite for good: a dry run unless --apply), bench_storage.py (how long typical requests take on a copy of the bot's file; in the Docker image too; tests/bench_cache.py builds a data folder like a real one for it), refill_airgradient.py (one-off: fetch the whole AirGradient history again), eval_prompts.py, show_request.py (exactly what is @@ -43,20 +50,20 @@ scripts/ ecowitt_metrics.py (which metrics the station reports), A design for tappable commands and buttons is in `TELEGRAM_UX.md` (not built yet). -Both sources have the same shape: `start()`, `tools`, `warm()`, `poke()`, `close()`. +The sources (ecobot-mcp's) have the same shape: `start()`, `warm()`, `close()`, and a `warmer` that refreshes them on a timer. ## 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. ## How it stays fast and cheap -- Private chats also get a persistent button keyboard (`lib/templates.py`): tapping one sends its label as a message (a 3x3 grid: Help & Alerts = what the bot can do, then the alert settings, Status, Rain; Weather = every reading, a panel each, Temperature, Humidity; Air Quality = every air metric, Particulates = PM1, PM2.5 and PM10 on one chart, Wind, which the Irrigation button replaces when the controller is configured; every chart button is the last day). `/keyboard` shows it, `/keyboard off` hides it. When the buttons change, each private chat gets the new keyboard with its next reply (the bot remembers which version each chat has; a chat that hid it keeps it hidden). Typed "weather now" shows every reading the station has. Weather lines of 31 days or fewer are drawn with no shaded min–max range (except wind's gusts; AirGradient charts keep theirs); longer periods are daily with the range. Every line ends with its latest value beside it (zero included). A single-panel chart's caption is one line ("Temperature, since Tue 7 Jul 2026" when the period runs up to today, else "Temperature, Wed 24 – Tue 30 Sep 2026"); a chart of several panels has its title and then its time range on a second line; one chart and a short answer go as one message (the answer under the chart's title in its caption), a longer answer is a message of its own sent just before the chart. A single chart carries period buttons under it (1D, 7D, 1M, 3M and 1Y, the chart's own marked with ●; pressing it does nothing): pressing one redraws that chart in place for the new period (`lib/periods.py`, `Bot.on_period_button`). The bot keeps the question behind its last 300 charts in its state file, so the buttons keep working across restarts; an older chart answers "out of date, please ask again". A reply with period buttons doesn't carry the persistent keyboard; that follows on the next reply. A group of several charts has no buttons. Charts drawn in the last 10 minutes are kept (the newest 60), so toggling between periods brings a chart back instantly without a new question. Any reading or "weather" with a period of two days or more ("humidity 7d", "weather 30d", "particulates 7d") is a chart, sent with no text. +- Private chats also get a persistent button keyboard (`lib/templates.py`): tapping one sends its label as a message (a 3x3 grid: Help & Alerts = what the bot can do, then the alert settings, Status, Rain; Weather = every reading, a panel each, Temperature, Humidity; Air Quality = every air metric, Particulates = PM1, PM2.5 and PM10 on one chart, Wind, which the Irrigation button replaces when irrigation-mcp is configured, BOT_IRRIGATION_MCP_URL; every chart button is the last day). `/keyboard` shows it, `/keyboard off` hides it. When the buttons change, each private chat gets the new keyboard with its next reply (the bot remembers which version each chat has; a chat that hid it keeps it hidden). Weather lines of 31 days or fewer are drawn with no shaded min–max range (except wind's gusts; AirGradient charts keep theirs); longer periods are daily with the range. Every line ends with its latest value beside it (zero included). A single-panel chart's caption is one line ("Temperature, since Tue 7 Jul 2026" when the period runs up to today, else "Temperature, Wed 24 – Tue 30 Sep 2026"); a chart of several panels has its title and then its time range on a second line; one chart and a short answer go as one message (the answer under the chart's title in its caption), a longer answer is a message of its own sent just before the chart. A single chart carries period buttons under it (1D, 7D, 1M, 3M and 1Y, the chart's own marked with ●; pressing it does nothing): pressing one redraws that chart in place for the new period (`lib/periods.py`, `Bot.on_period_button`). The bot keeps the question behind its last 300 charts in its state file, so the buttons keep working across restarts; an older chart answers "out of date, please ask again". A reply with period buttons doesn't carry the persistent keyboard; that follows on the next reply. A group of several charts has no buttons. Charts drawn in the last 10 minutes are kept (the newest 60), so toggling between periods brings a chart back instantly without a new question. - In private chats the bot shows Telegram's "Thinking..." draft (sendMessageDraft, re-sent every 20 s, as drafts expire after 30) and streams the answer into it before sending the real message; groups show "typing...". A "message generation stopped" update is only logged. - 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); a question that may need them starts a refresh as it arrives (a chart made in code doesn't: it reads just what it needs). 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. -- 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. The keyboard's charts, and the chart of each alert type sent in the last 6 hours, are drawn afresh every 5 minutes once the sources are warm, so a press, or the Refresh under an alert, is answered with a chart already drawn (`Bot.draw_buttons_ahead`); with `TELEGRAM_PRELOAD_CHAT` they are uploaded ahead too while the bot has been used in the last 15 minutes, as are the other periods of any chart asked for, so the press sends Telegram's copy. 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 the chart drawn ahead since the message was last changed, else draws one and keeps it. +- 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. +- 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`, docs/storage-plan.md). A background archive copies every Ecowitt cycle (5-minute, 30-minute, 4-hour, daily) before Ecowitt expires it, and backfills @@ -64,16 +71,20 @@ Both are off by default. They are websites, not APIs (the pollen page is parsed) local days are worked out as its readings are written (the air sensor's with its glitches taken out), so `weather_days`, `air_days`, the dashboard and the long charts read a row a day. - A chart of 5-minute readings is shaded between each five minutes' lowest and highest, as Home Assistant's history graph is. Ecowitt's own 5-minute history has one number per reading and no range, so the bot keeps the ranges itself, as the bands of the 5-minute readings in `ecobot.sqlite` (`Ecowitt.live_marks`): every live reading it takes (about one a minute, Ecowitt's real_time) is counted in the five minutes around the nearest 5-minute mark, and a stretch with two or more readings has a range, which widens that 5-minute reading's band. Temperature, humidity, dew point, feels like, pressure, solar, UV and the indoor readings are kept; wind has its gusts as its range and rain is bars. Every weather line is shaded, whatever the period (the old rule that left the lines of 31 days or fewer clean is gone). The ranges are promoted into wider buckets as a chart needs them: a 5-minute reading takes its own five minutes', a 30-minute reading (a week's or a month's chart) takes the lowest and highest of the half hour (its band widened from the 5-minute readings inside it whenever they are written, so a chart reads a few hundred rows a reading; it only ever widens Ecowitt's own range, or the lowest and highest of the 5-minute values), and a wider bucket the extremes of the 30-minute ones it holds. Only where the bot was watching: before that the band is Ecowitt's own range, as ever, and past 31 days it is Ecowitt's daily record. The gauges' Daily and Monthly highs and lows take in the recorded ranges too (the year's row takes in the month's). Only a chart asks for them, at a cost of a few milliseconds a reading. About a reading a minute is as fine as Ecowitt's cloud gives, so a range is made of a handful of readings, fewer than Home Assistant's local feed. -- With the station's readings coming from the cloud and Home Assistant set (`HOMEASSISTANT_URL`, `HOMEASSISTANT_TOKEN`), the Ecowitt ranges come from it (`lib/ecowitt/homeassistant.py`); with Home Assistant as the station's source its history carries the bands with the readings, so nothing is read back. Its Ecowitt integration is sent every reading the gateway makes (every 16 to 60 seconds) and keeps each change for 10 days by default, which is finer than the cloud and covers the time the bot was down. The bot finds the station's entities by name (`sensor.<station>_outdoor_temperature` and so on), reads their history over the REST API (`/api/history/period`, at start for the last 31 days at most and then the last 3 hours every 15 minutes) and folds it into the same 5-minute ranges: a stretch's range is the values it changed to in that time and the one it held as it began. Home Assistant only records a change of state, so a stretch where nothing changed has a range of nothing, which counts. Temperature, humidity, dew point, feels like, VPD, pressure, solar and UV, and the indoor readings, are read. If Home Assistant can't be reached it is logged once and the bot's own readings carry on. -- The air sensor has three sources (`AIRGRADIENT_SOURCE`; `lib/airgradient/source.py`, docs/storage-plan.md 3.12), each filling only what the ones before it lack, which the file's write rules do (a reading from the bot itself ranks above Home Assistant's, Home Assistant's above the cloud's; a lower one fills only a cell a higher one left empty). The sensor's own server (`AIRGRADIENT_LOCAL_URL`) is read every minute: each 5 minutes' readings are a row (their mean, with their lowest and highest as its band, loaded as a reading's `_range` and shaded on the charts), and each reading is kept as a minute (`1min`, 10 days), so a chart of up to 8 hours is drawn a reading a minute, as the station's are. Home Assistant (`lib/airgradient/homeassistant.py`), when it has the sensor (its entities are found by name: `sensor.<device>_voc_index`, `_pm2_5`, `_carbon_dioxide` ...; with several sensors, the one whose reading is nearest), is read the same way while the sensor does not answer the bot (its states, every minute: the live reading, and the rows and minutes), and its history (`/api/history/period`: 31 days at start, as far back as it has them, then the last 3 hours every 15 minutes) is read back for the times the bot did not read the sensor at all: each 5 minutes' mean with its lowest and highest as the band, the bands of the buckets the bot has, and the minutes of the last 9 hours. The cloud fills what neither has: the history before Home Assistant's 10 days (the backfill), the times both were down, and the sensor's name. Its current reading is the live one only when neither answers. +- With the station's readings coming from the cloud and Home Assistant set (`MCP_HOMEASSISTANT_URL`, `MCP_HOMEASSISTANT_TOKEN`), the Ecowitt ranges come from it (`lib/ecowitt/homeassistant.py`); with Home Assistant as the station's source its history carries the bands with the readings, so nothing is read back. Its Ecowitt integration is sent every reading the gateway makes (every 16 to 60 seconds) and keeps each change for 10 days by default, which is finer than the cloud and covers the time the bot was down. The bot finds the station's entities by name (`sensor.<station>_outdoor_temperature` and so on), reads their history over the REST API (`/api/history/period`, at start for the last 31 days at most and then the last 3 hours every 15 minutes) and folds it into the same 5-minute ranges: a stretch's range is the values it changed to in that time and the one it held as it began. Home Assistant only records a change of state, so a stretch where nothing changed has a range of nothing, which counts. Temperature, humidity, dew point, feels like, VPD, pressure, solar and UV, and the indoor readings, are read. If Home Assistant can't be reached it is logged once and the bot's own readings carry on. +- The air sensor has three sources (`MCP_AIRGRADIENT_SOURCE`; `lib/airgradient/source.py`, docs/storage-plan.md 3.12), each filling only what the ones before it lack, which the file's write rules do (a reading from the bot itself ranks above Home Assistant's, Home Assistant's above the cloud's; a lower one fills only a cell a higher one left empty). The sensor's own server (`MCP_AIRGRADIENT_LOCAL_URL`) is read every minute: each 5 minutes' readings are a row (their mean, with their lowest and highest as its band, loaded as a reading's `_range` and shaded on the charts), and each reading is kept as a minute (`1min`, 10 days), so a chart of up to 8 hours is drawn a reading a minute, as the station's are. Home Assistant (`lib/airgradient/homeassistant.py`), when it has the sensor (its entities are found by name: `sensor.<device>_voc_index`, `_pm2_5`, `_carbon_dioxide` ...; with several sensors, the one whose reading is nearest), is read the same way while the sensor does not answer the bot (its states, every minute: the live reading, and the rows and minutes), and its history (`/api/history/period`: 31 days at start, as far back as it has them, then the last 3 hours every 15 minutes) is read back for the times the bot did not read the sensor at all: each 5 minutes' mean with its lowest and highest as the band, the bands of the buckets the bot has, and the minutes of the last 9 hours. The cloud fills what neither has: the history before Home Assistant's 10 days (the backfill), the times both were down, and the sensor's name. Its current reading is the live one only when neither answers. - Each metric of a lower source is checked against what the bot holds from the ones above it before it fills a gap, over the five minutes both hold (within 2 µg/m³ or 15%, in four in five of them, is the same reading). The sensor corrects its PM2.5 as it is set to (the dashboard's correction when it takes its configuration from there, else its own, none by default) and Home Assistant shows that; the cloud gives the dashboard's. So a metric that differs (the raw PM2.5 against the corrected one) fills no gaps of the sources above it (they are drawn as gaps), and is said once in the log with the fix: set the sensor's PM2.5 correction to the dashboard's, or have it take its configuration from the dashboard. The cloud is asked for the whole of each finished day the bot read itself (one request): the day's check, and its readings fill what the bot lacked. With the sensor alone, nothing to check against, the start-up line says which correction it applies (from its `/config`). -## The report and plain lookups -"report" (and "status", "sitrep") and "weather now" are written in code, with no model call (`lib/report.py`): the bot fetches the tools' results together and lays them out, so they are quick and always the same. Sun, UV and wind are left out when zero (night, calm). The report is: Weather station, Air quality, and Pollen & asthma and Forecast when those sources are on (pollen and forecast always come from the cache). The report carries a 🔄 Refresh button that reads everything again and redraws it in the same message (`lib/report_menu.py`). With the weather station, the report is the caption of a picture of its temperature, humidity and rain gauges (`ecowitt.dashboard.STATUS`, drawn by `lib/gauges.py` while the report is fetched); Refresh redraws both. The gauges' highs and lows are the year's day rows, read in one go (today's from its readings so far). A report longer than a caption (1,024 characters) goes after the picture as a message of its own; a refreshed one that has grown too long keeps its first sections. - -A plain chart request ("rain chart 7d", "plot temperature and humidity", "air quality 30d", the chart buttons) is also drawn and written up in code, with no model call (the chart goes out with just its title as the caption; the write-up is kept in the chat's memory, not sent) (`intent.weather_chart`, `report.chart_caption`): the period, then low and high per reading (the average first if one was asked), the peak and rating for air quality, and for a rain chart the least and most rain and whether more is expected. Anything that asks for correlation, analysis, a forecast, thinking or a description, or compares readings or names a particular date or time, still goes to the model. - -Other plain lookups are answered in code too, from the one tool result (`intent.plain_lookup`, `report.lookup`): a single reading now ("how hot is it", "is it raining", "uv"), the air ("how's the air", "pm10"), pollen, the plain forecast ("forecast", "7 day forecast"), the highs, lows or average of a short period ("hottest today", "average temp yesterday", "highest humidity yesterday") and what the bot can do ("what can you do"). Any question with forecast, correlation, thinking, analysis or description words, a comparison, or anything beyond the reading itself goes to the model; so does a lookup whose result can't be used. +## Typed questions, buttons, Status and the commands +Since step 6c of docs/ecobot-mcp.md the bot answers no typed question in code: everything typed goes to the model with ecobot-mcp's +tools, and only its reasoning effort is read from the words (`lib/intent.py`). The keyboard's chart buttons and their commands stay +instant: each is a fixed call to ecobot-mcp (`lib/templates.py` `CALLS`: summary of a named reading over the last day, as a chart), +sent with just its title (`Bot.press`); the alerts' charts are the same calls (`lib/alerts/pictures.py` `CHARTS`). Status (the button, +`/status`) is ecobot-mcp's Status picture (`ecobot://status`: the temperature, humidity and rain gauges, `lib/status.py`), sent at once, +then the model's answer to ecobot-mcp's `report` prompt. ecobot-mcp's prompts are Telegram commands (`/report`, `/now`, `/chart rain +7d` ...): the bot sets Telegram's menu to its own commands and one per prompt when it connects and whenever the prompts change +(`Bot.publish_commands`), and `/<prompt> <words>` fills the prompt's arguments in order, the last taking the rest, and asks the model +(`Bot.on_command`). Without the model a typed question gets one line saying it isn't set up; the buttons and alerts still work. `weather_days` can count and rank days by any reading (a day's highest or lowest humidity, pressure, UV, solar, wind, dew point and so on), from the cache, so "how many days was UV 9 or more" is one cheap call (`count_only` returns just the counts; `group_by` month or year adds a count for each and draws them as a bar chart, a number above every bar; `stat` and `of` give a total, average, highest or lowest of any reading per month or year the same way, e.g. rain per month or the hottest day each year). A plain "rain by month for 2 years" or "average temperature per year" (one reading, a figure for each month or year) is worked out in code the same way (`weather_days`/`air_days` with `stat`, `of`, `group_by`): one bar for each month or year, a one-line caption with the figure for the whole period. A rain chart reaching back past the 30-minute readings (about a year) uses the daily records for the older days, and one asked for by month or year is monthly or yearly bars, even if the model answers it. A plain "days over UVI 10 by year" or "count days over PM2.5 of 90 per year" (one reading against one limit, optionally per year or month, over the whole record unless a period is named) is worked out in code without the model, so it always gives the same bar chart; if the model is asked instead and leaves out the by-year or by-month grouping the words ask for, it is added. `air_days` does the same for the air sensor's metrics (days PM2.5 passed 25, the worst day each month), from the stored readings. A question that pulls in a lot of data is not refused: when the tool results of one question pass twice what a 500-point query returns (about 10,000 tokens of input, on every later step too), the bot sends a one-line heads-up to the chat before the model is sent them, then carries on without waiting for a reply (`lib/timeutil.py` `WARN_TOKENS`). @@ -83,7 +94,7 @@ The system prompt starts with what never changes (the model provider caches the ## Home Assistant as the weather station's source -- `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; `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.<station>_<reading>`, 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`. +- `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.<station>_<reading>`, 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. - 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/simplification-review.md b/docs/simplification-review.md index 028b7f00..e3072322 100644 --- a/docs/simplification-review.md +++ b/docs/simplification-review.md @@ -34,7 +34,7 @@ the contracts. | where | lines | what | recommendation | |---|---|---|---| -| lib/storage/migrate.py (whole), write.py `exact=` 219-227, __init__.py `bulk` 82-109/162-163, ecobot.py 76-79, `open_storage` in both sources | ~510 (+122 scripts/migrate_storage.py, +300 tests, conftest `old_archived_cache`) | the one-off move of the old files into ecobot.sqlite, its checks, and the merge of a part into an existing file | Retire once the old files have been moved on every deployment and deleted. Until then it still fires when a part is enabled later (POLLEN switched on with conditions_cache.sqlite still present). Carries a second upsert SQL and a second "hourly day" rule that go with it | +| lib/storage/migrate.py (whole), write.py `exact=` 219-227, __init__.py `bulk` 82-109/162-163, ecobot.py 76-79, `open_storage` in both sources | ~510 (+122 scripts/migrate_storage.py, +300 tests, conftest `old_archived_cache`) | the one-off move of the old files into ecobot.sqlite, its checks, and the merge of a part into an existing file | Retire once the old files have been moved on every deployment and deleted. Until then it still fires when a part is enabled later (MCP_POLLEN switched on with conditions_cache.sqlite still present). Carries a second upsert SQL and a second "hourly day" rule that go with it | | lib/counts.py (whole), ecobot.py:225, bot.py:1071/1199/1025, warm.py:256, storage `counts.connect`/`uncounted` (6 sites), tools timing fields | ~110 | SQL-statement and thread-hop counters via a sqlite3 Connection subclass and a monkeypatched `asyncio.to_thread`, for the DEBUG `Chart ms` line and the bench script | The redesign it measured is done. Remove from the production path (the monkeypatch of `asyncio.to_thread` at start is the riskiest line in the repo for its value); keep wall-clock timing in scripts/bench_storage.py | | lib/config.py:190-192, 290-291 | 6 | the three old file paths on Config | go with the migration | | ecobot.py:252-253 | 2 | "XAI_API_KEY is no longer used" hint | removed | @@ -43,13 +43,13 @@ the contracts. | feature | lines | where | note | |---|---|---|---| -| ADMIN_ONLY | ~120 | lib/admins.py, bot.py:53-54,334-335,364-394 and the `_allowed` calls, ecobot.py:255-259, config.py:109-119,221-222 | documented and tested. If kept, `_is_group_admin` (bot.py:390-394) should use `Admins`' cache (one `get_chat_member` call per press saved) | -| TELEGRAM_PRELOAD_CHAT | ~95 | bot.py:339-348,997-1063,1203-1204; periods.py:80,112-115,130-132; config.py:142-150,224 | self-contained; `_draw_ahead`, `has_copy`, PRELOAD_TTL have no other caller | +| BOT_ADMIN_ONLY | ~120 | lib/admins.py, bot.py:53-54,334-335,364-394 and the `_allowed` calls, ecobot.py:255-259, config.py:109-119,221-222 | documented and tested. If kept, `_is_group_admin` (bot.py:390-394) should use `Admins`' cache (one `get_chat_member` call per press saved) | +| BOT_TELEGRAM_PRELOAD_CHAT | ~95 | bot.py:339-348,997-1063,1203-1204; periods.py:80,112-115,130-132; config.py:142-150,224 | self-contained; `_draw_ahead`, `has_copy`, PRELOAD_TTL have no other caller | | "Thinking..." draft preview | ~45 | bot.py:207-241,50-51,987,1089-1091,1124; llm.py streaming branch | the newest Telegram feature; without it `keep_typing` suffices and llm.py loses a code path (always stream: -8) | | AirGradient's own temperature/humidity on charts | ~60 | compose.py:60-68,33,192-208; panels.py:49-69; series.py:64-69; intent.py:382-389; tools.py `asked=`/`schemas_for`; airgradient extras | one eval case; the `Tool.asked` mechanism exists for it | -| mDNS for a `.local` AIRGRADIENT_LOCAL_URL | 33 + the zeroconf dependency | lib/airgradient/local.py:32-64 | drop if the URL is an IP or a DNS name | +| mDNS for a `.local` MCP_AIRGRADIENT_LOCAL_URL | 33 + the zeroconf dependency | lib/airgradient/local.py:32-64 | drop if the URL is an IP or a DNS name | | PM2.5 correction note on the start-up line | 28 | airgradient/source.py:176-185,71,167-168,202-203; local.py:126-138 | only when the monitor is the sole source; informational | -| Home Assistant's bands via `import_ranges` | ~55 | ecowitt/homeassistant.py:29-30,52-67,156-167; ecowitt/source.py:86-87,276-293; ecobot.py:172-173 | only needed for ECOWITT_SOURCE=cloud with HOMEASSISTANT_URL set; in auto/homeassistant modes `hass_api.history` already writes the same bands, with a different bucket alignment (mark-centred vs bucket-start). Pick one alignment, then gate or drop | +| Home Assistant's bands via `import_ranges` | ~55 | ecowitt/homeassistant.py:29-30,52-67,156-167; ecowitt/source.py:86-87,276-293; ecobot.py:172-173 | only needed for MCP_ECOWITT_SOURCE=cloud with MCP_HOMEASSISTANT_URL set; in auto/homeassistant modes `hass_api.history` already writes the same bands, with a different bucket alignment (mark-centred vs bucket-start). Pick one alignment, then gate or drop | | `invert_second_axis` | ~10 | compose.py:52-53,197-202; panels two_axes; specs Panel.flip_right; charts `_right_axis(flip)` | no eval, one test | | FEELS_LIKE_IN_ALL / VPD_IN_ALL | ~10 | intent.py:362-368, config.py:214-215, ecobot.py:232-233 | runtime flags for which panels "weather all week" draws | | Several AirGradients in Home Assistant | ~12 | airgradient/homeassistant.py:38-57; source.py:217,225-227 | the nearest-reading tie-break; one monitor in practice | @@ -97,11 +97,11 @@ Each handles a real path; most have a test. Line counts are approximate. Telegram and the bot (bot.py, notify.py, logs.py): `answer_query` swallowing "query is too old" after a restart (11); `ChatMigrated` on a press under an old alert (4); `_press` refusing callback data not on the message's own keyboard (18, security); messages older than 10 minutes ignored (4); the `_send` error ladder in notify.py:252-283 (ChatMigrated, Forbidden and "chat not found" marking a chat gone, RetryAfter and NetworkError one retry, catch-all so other chats still get the alert; ~30, all tested); photo refused falls back to text (7); file-id reuse so a chart is uploaded once (15); the `_flood_wait` int-or-timedelta shim (4, until the PTB upgrade settles); state file moved aside as `.damaged-…` when unreadable (5); group-to-supergroup baseline move (3); reply-keyboard versioning so a changed keyboard reaches phones (~30; only the startup `refresh_keyboards` is redundant); the after-timeout retry at one reasoning step lower (19); `shorten_old` and the identical-tool-call cache in llm.py (37); topic memory (33, what keeps the prompt short and cacheable); `commit_in` reading .git by hand (15); TZ and token/network exits in ecobot.py (11); journald priorities and the httpx line strip (22). -Alerts: quiet hours across midnight with the overnight summary (~50, configured by RAIN_QUIET_HOURS); "rain ended while not watching" closing a spell after downtime (3, required: without it `wet_times[0]` raises; worth a test); `_fell` re-reading a long spell's start (6); gusts only newer than the last check (2); `check_rain` on the live reading with its lock (13, Home Assistant only); irrigation's 24-hour delay renewal (7, needed: the check runs when the delay lapses); stale forecast and controller-unreachable rules (14); the watchdog closing a valve after a run (47, safety); Tuya signing, token retry and shape checks (20). +Alerts: quiet hours across midnight with the overnight summary (~50, configured by MCP_RAIN_QUIET_HOURS); "rain ended while not watching" closing a spell after downtime (3, required: without it `wet_times[0]` raises; worth a test); `_fell` re-reading a long spell's start (6); gusts only newer than the last check (2); `check_rain` on the live reading with its lock (13, Home Assistant only); irrigation's 24-hour delay renewal (7, needed: the check runs when the delay lapses); stale forecast and controller-unreachable rules (14); the watchdog closing a valve after a run (47, safety); Tuya signing, token retry and shape checks (20). Ecowitt: `_TurnLock` one request at a time with an urgent lane (31; "Operation too frequent" is real); retries with backoff and key redaction (38); `UNIT_FIXES` for VPD in inHg (27, about the live API, not only old files); `daily_run` DST wording (7); archive probing groups singly after a refusal and dropping the piezo gauge (20); `OUTAGE_STOP` and the settle edge snapped to whole buckets (13); `Recent` freshness and provisional/final handling in fetch.py (~45); the HA-cloud fallback itself (~70, this is auto mode); `_look` for HA's first state (11); unit conversion from HA (19); DNS-failure hint (9); the bot's own 5-minute bands from live polling (~70, the only band source in cloud-only mode); parts of days at the finest held resolution and `_exact` (27); `only=` dropped when the question never said holiday (6); `DERIVED` fields hidden unless asked (12); `_in_focus`, `rain_from_daily`, `monthly_note` (30); HA-only mode adopting the file's MAC and archive pace (8). -Storage and AirGradient: `NewerFile` refusing a newer schema (6); ALTER TABLE for new catalogue columns (8); unknown time zone name (7); unknown Ecowitt group kept in `extra` (8); UV written whole or with one decimal (3); refetch when a group gains a field (6); the coverage rules of a fetch (10); day rows recomputed when the zone changes (15); a band arriving before its reading (10); daily records taking lo/hi times from the 4-hour readings (20); 23/25-hour days and UTC-day labels (13); half hours with finer readings bucketed from those alone (3); the spike rule in SQL and in Python (55: the SQL feeds the day rows at write time, the Python filters read-back rows for charts; a test checks they agree); a day refetched at the other resolution (4); cloud 404 as empty (2); backfill empty-day stop rules (14); the per-metric gap rule and the agreement verdicts (~90, plan 3.12); rating on the last two readings and `sustained` for the particulates alert (30); AIRGRADIENT_SOURCE modes (10). +Storage and AirGradient: `NewerFile` refusing a newer schema (6); ALTER TABLE for new catalogue columns (8); unknown time zone name (7); unknown Ecowitt group kept in `extra` (8); UV written whole or with one decimal (3); refetch when a group gains a field (6); the coverage rules of a fetch (10); day rows recomputed when the zone changes (15); a band arriving before its reading (10); daily records taking lo/hi times from the 4-hour readings (20); 23/25-hour days and UTC-day labels (13); half hours with finer readings bucketed from those alone (3); the spike rule in SQL and in Python (55: the SQL feeds the day rows at write time, the Python filters read-back rows for charts; a test checks they agree); a day refetched at the other resolution (4); cloud 404 as empty (2); backfill empty-day stop rules (14); the per-metric gap rule and the agreement verdicts (~90, plan 3.12); rating on the last two readings and `sustained` for the particulates alert (30); MCP_AIRGRADIENT_SOURCE modes (10). Charts and intent: rain behind the lines, zero floor, negative bars (25); DST-correct time axis, local-midnight bars, clock slots (25); smoothing and the 10am daily records (9); `_pills` collision resolution (14); `model_prefetch` for "will it rain" (28, saves a model round trip); OPINION/RIGHT_NOW (6); plot_chart validation of model-supplied arguments (14); `grouping_in` fallback when the model omits group_by (18). @@ -121,5 +121,5 @@ archive, the alerts, irrigation, pollen, forecast, the charts, the LLM routing. so much as wide; shrinking it further means dropping features, not cleaning code. Suggested order: (1) the dead batch and the counts instrumentation, one commit, no risk; (2) the no-behaviour-change simplifications in -intent.py, bot.py and query.py, which also fix the `MAX_ROWS` fallback; (3) the owner decides on ADMIN_ONLY, TELEGRAM_PRELOAD_CHAT, the +intent.py, bot.py and query.py, which also fix the `MAX_ROWS` fallback; (3) the owner decides on BOT_ADMIN_ONLY, BOT_TELEGRAM_PRELOAD_CHAT, the draft preview, mDNS and the other optional features; (4) retire the migration after the old files are deleted from the data folder. diff --git a/docs/storage-plan.md b/docs/storage-plan.md index 8546af78..dd22ef73 100644 --- a/docs/storage-plan.md +++ b/docs/storage-plan.md @@ -314,8 +314,8 @@ Left to Python on purpose: ### 3.12 The AirGradient's sources: the monitor, then Home Assistant, then the cloud -`AIRGRADIENT_SOURCE` does for the air monitor what `ECOWITT_SOURCE` does for the station. `auto` (the default) uses each source that is -set, in this order: the monitor's own server (`AIRGRADIENT_LOCAL_URL`), Home Assistant (when it has the monitor, found by its entities' +`MCP_AIRGRADIENT_SOURCE` does for the air monitor what `MCP_ECOWITT_SOURCE` does for the station. `auto` (the default) uses each source that is +set, in this order: the monitor's own server (`MCP_AIRGRADIENT_LOCAL_URL`), Home Assistant (when it has the monitor, found by its entities' names as its ranges are now: `airgradient.homeassistant.find_prefix`), and AirGradient's cloud (its token and location). `local`, `homeassistant` or `cloud` is that one alone. Each source fills only what the ones before it lack, which the write rules already do (3.8): the bot's own readings rank above Home Assistant's, Home Assistant's above the cloud's, and a lower one only fills a cell a higher one left @@ -351,7 +351,7 @@ The PM2.5, and the other readings the monitor corrects: dashboard. The history from before stays as it came from the cloud, so a chart across the bot's first days can show the step until the fix. The check runs again each day on the newest day, so a correction changed on the monitor or the dashboard is followed. - **With nothing to check against** (one source alone), its values are taken as they are, and the start-up line says which correction the - monitor applies, from its `/config` when `AIRGRADIENT_LOCAL_URL` is set ("PM2.5: the monitor's EPA 2021 correction", "PM2.5: as + monitor applies, from its `/config` when `MCP_AIRGRADIENT_LOCAL_URL` is set ("PM2.5: the monitor's EPA 2021 correction", "PM2.5: as measured, no correction"). ## 4. How each request reads @@ -500,7 +500,7 @@ Each step is a commit (or a few) pushed to the dev branch with the tests and eva (`test_every_air_day_row_is_what_the_glitch_rule_in_python_gives`). On the stand-in: `air_days` over 4 years 15 ms (was 584 ms, 662 at the start), one statement; the air charts still load every reading of their period and filter it in Python (1M: 314 ms), the lines bucketed by the database, as the station's are, being step 4's, with its rewrite of what the source reads. -4. **The AirGradient from the monitor, Home Assistant and the cloud** (3.12). `AIRGRADIENT_SOURCE`; its readings, minutes and live +4. **The AirGradient from the monitor, Home Assistant and the cloud** (3.12). `MCP_AIRGRADIENT_SOURCE`; its readings, minutes and live reading from the monitor itself, Home Assistant filling what the bot did not read and the cloud what neither has, each metric checked against the source ranked above it before it fills a gap; the settings table and the start-up line. After step 3, since it writes the `air` table's rows, minutes and bands by the same rules as the station's, and its readings back to Home Assistant's first state need the diff --git a/ecobot-mcp.service b/ecobot-mcp.service new file mode 100644 index 00000000..10a646b6 --- /dev/null +++ b/ecobot-mcp.service @@ -0,0 +1,82 @@ +# ecobot-mcp, the MCP server (python -m ecobot_mcp, docs/ecobot-mcp.md step 5): the sources and their syncers, the alert rules and +# the MCP server at http://127.0.0.1:8765/mcp. Installed with ecobot.service, from the same checkout and venv (see that file), and +# enabled first: the bot is its client (BOT_MCP_URL), and its unit pulls this one in and starts after it. +# sudo cp /opt/ecobot/ecobot-mcp.service /opt/ecobot/ecobot.service /etc/systemd/system/ && sudo systemctl daemon-reload +# sudo systemctl enable --now ecobot-mcp.service ecobot.service +# Only one ecobot-mcp runs on a data folder (mcp.lock): a second stops at start, saying so. +# The data folder is the bot's own, /var/lib/private/ecobot (StateDirectory=ecobot): User=ecobot gives this unit the same dynamic user +# as ecobot.service, so the two share the folder's owner and neither takes it from the other when it starts. The token: the first of +# AUTH_TOKENS, which the bot sends and this accepts; with AUTH_TOKENS unset, the one this generates at its first start in the data +# folder (/var/lib/private/ecobot/auth_token, readable by that user only), which the bot reads from there. +# It reads /etc/ecobot.env as the bot does, less the bot's and irrigation-mcp's secrets, by their names and their old ones (UnsetEnvironment=): its +# settings are the MCP_ ones and the shared ones (docs/configuration.md). MCP_BIND defaults to 127.0.0.1:8765; to reach it from other +# machines set MCP_BIND=0.0.0.0:8765 and put TLS in front of it. +[Unit] +Description=ecobot-mcp (the ecobot MCP server: sources, alert rules) +After=network-online.target +Wants=network-online.target +Before=ecobot.service irrigation-mcp.service + +[Service] +DynamicUser=yes +User=ecobot +Group=ecobot +WorkingDirectory=/opt/ecobot +EnvironmentFile=/etc/ecobot.env +UnsetEnvironment=BOT_TELEGRAM_TOKEN TELEGRAM_BOT_TOKEN BOT_OPENROUTER_API_KEY OPENROUTER_API_KEY IRRIGATION_TUYA_CLIENT_ID BOT_TUYA_CLIENT_ID TUYA_CLIENT_ID IRRIGATION_TUYA_CLIENT_SECRET BOT_TUYA_CLIENT_SECRET TUYA_CLIENT_SECRET WEATHER_MCP_TOKEN +Environment=PYTHONUNBUFFERED=1 +Environment=PYTHONPYCACHEPREFIX=/var/cache/ecobot/pycache +StateDirectory=ecobot +CacheDirectory=ecobot +ExecStart=/opt/ecobot/.venv/bin/python -m ecobot_mcp +Restart=on-failure +RestartSec=10 +TimeoutStopSec=30 +StandardOutput=journal +StandardError=journal +SyslogIdentifier=ecobot-mcp + +# Filesystem isolation +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +InaccessiblePaths=/boot /media /mnt +UMask=0077 + +# Privilege restrictions +AmbientCapabilities= +CapabilityBoundingSet= +LockPersonality=yes +MemoryDenyWriteExecute=yes +NoNewPrivileges=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +SystemCallArchitectures=native +SystemCallErrorNumber=EPERM +SystemCallFilter=@system-service + +# Kernel and system protection +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes + +# Process isolation +ProtectProc=invisible +RestrictNamespaces=yes + +# Network: HTTPS to the weather, air, pollen and forecast APIs and Home Assistant, and its own MCP port (AF_UNIX: the local name +# resolver; AF_NETLINK: listing the network interfaces, which finding the air sensor by its .local name needs) +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK + +# Resource limits +TasksMax=64 +MemoryAccounting=yes +MemoryHigh=300M +MemoryMax=450M + +[Install] +WantedBy=multi-user.target diff --git a/ecobot.py b/ecobot.py index 01f9e063..1cc49d00 100644 --- a/ecobot.py +++ b/ecobot.py @@ -1,6 +1,15 @@ """Telegram bot for a personal weather station (Ecowitt) and air-quality sensor (AirGradient), answered by a model through OpenRouter, with proactive alerts. Settings come from environment variables (see lib/config.py); run it under systemd with the unit's EnvironmentFile set. + +The bot is a client of ecobot-mcp (python -m ecobot_mcp, docs/ecobot-mcp.md 3.8 and step 6), reached over MCP at BOT_MCP_URL, which +it can't start without (lib/weather.RemoteWeather): ecobot-mcp runs the sources, the alert log and the alert rules, and draws every +picture; the bot's tools, instructions, station and alerts come from it. The bot does what only a Telegram bot can: the chats and their +buttons, the model, and delivering the alerts. + +With BOT_IRRIGATION_MCP_URL set it is irrigation-mcp's client too (python -m irrigation_mcp, docs/ecobot-mcp.md 3.9 and step 8b, +lib/irrigation_remote.py): its Irrigation button and menu call irrigation-mcp's tools, and irrigation://alerts is delivered as +ecobot://alerts is. The controller itself (Tuya, the watchdog, the daily check) is irrigation-mcp's alone. """ import asyncio @@ -9,200 +18,166 @@ import logging import os import signal -import time +from urllib.parse import urlsplit +from zoneinfo import ZoneInfo -from lib.config import ROOT, Config +from lib import auth_token +from lib.config import RETIRED_TOKEN, Config from telegram import Update from telegram.error import InvalidToken, NetworkError from telegram.ext import Application, Defaults -from lib import charts, intent -from lib.airgradient import AirGradient -from lib.airgradient import metrics as air_metrics -from lib.alerts.forecast import ForecastMonitor -from lib.alerts.irrigation import IrrigationMonitor -from lib.alerts.menu import LABELS, available_kinds -from lib.alerts.notify import AlertState, Notifier -from lib.alerts.particulates import CHECK_SECONDS as PARTICULATES_CHECK_SECONDS, ParticulatesMonitor -from lib.alerts.pollen_and_asthma import PollenAndAsthmaMonitor -from lib.alerts.weather import WeatherMonitor -from lib.bot import AHEAD_SECONDS, TURN_SECONDS, Bot, Tasks, polling_error -from lib.ecowitt import Archive, Ecowitt -from lib.ecowitt.source import HA_IMPORT_SECONDS -from lib.forecast import Forecast -from lib.irrigation import Tuya -from lib.irrigation.watchdog import CHECK_SECONDS as VALVE_CHECK_SECONDS +from lib import theme # (DARKMODE: the bot asks ecobot-mcp for charts in its own theme) +from lib.alerts.notify import AlertDelivery, AlertState, Notifier, ReadMark +from lib.bot import TURN_SECONDS, Bot, Tasks, polling_error +from lib.irrigation_remote import NAME as IRRIGATION_MCP, RemoteIrrigation from lib.llm import Agent -from lib.logs import BUGS, LogFormat, on_journal, stream_handlers -from lib.pollen import Pollen -from lib.compose import Composer -from lib.history import History -from lib.sources import Source -from lib.storage import Storage -from lib.tools import Tools -from lib.warm import every, safely +from lib.netenv import docker_private_network +from lib.logs import LogFormat, on_journal, stream_handlers +from lib import model_tools +from lib.version import commit_in, version # noqa: F401 (commit_in: named here for the tests) +from lib.warm import safely +from lib.weather import RemoteWeather _format = LogFormat("%(levelname)s %(message)s", priority=on_journal()) # DEBUG and INFO to stdout, WARN and ERROR to stderr logging.basicConfig(level=logging.INFO, handlers=stream_handlers(_format)) logging.getLogger("httpx").setLevel(logging.WARNING) +logging.getLogger("httpx2").setLevel(logging.WARNING) # the MCP client's: a line per request otherwise logging.getLogger("telegram.ext.Application").setLevel(logging.WARNING) # "Application started" etc. log = logging.getLogger("ecobot") +STARTUP_WAIT = 30.0 # seconds the bot waits for ecobot-mcp at start (its station names the time zone) before it carries on without -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.""" - sources: list[Source] = [] - took: dict[str, float] = {} - - async def start(kind: type[Source], *args, **kwargs) -> Source | None: - """A source made and started; one that fails either way is logged and left out (None).""" - source, started = None, time.monotonic() - try: - source = kind(*args, **kwargs) - await source.start() - 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)) - if source is not None: - await safely(source.close) - return None - finally: - took[kind.name] = time.monotonic() - started - storage = None - if cfg.ecowitt or cfg.airgradient: - try: # (in a thread: opening makes or upgrades its tables) - storage = await asyncio.to_thread(Storage, cfg.storage_path, cfg.tz) - except Exception as e: - log.error("The history file %s couldn't be opened (%s: %s) - continuing without the weather station and the air sensor", - cfg.storage_path, type(e).__name__, e, exc_info=isinstance(e, BUGS)) - if cfg.ecowitt and storage is not None and (eco := await start(Ecowitt, cfg, storage=storage)): - sources.append(eco) - eco = sources[0] if sources else None - if eco and str(eco.tz) != str(cfg.tz): - if os.getenv("TZ"): - log.warning("TZ=%s is not the weather station's time zone; using the station's, %s", os.getenv("TZ"), eco.tz) - cfg = dataclasses.replace(cfg, tz=eco.tz) - if not getattr(cfg.tz, "key", None): - log.warning("The time zone has no name, only an offset (%s), so daylight saving will put the times out: set TZ, " - "e.g. TZ=Australia/Melbourne", cfg.tz) - starts = [] - if cfg.airgradient and storage is not None: # (one file and one Home Assistant client for both; the file is the station's to close, else the sensor's) - starts.append(start(AirGradient, cfg, storage=storage, owned=eco is None, **({"ha": eco.ha} if eco and eco.ha else {}))) - 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)) - 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() - if took: - log.debug("Sources started in %.1fs: %s", sum(took.values()), ", ".join(f"{name} {seconds:.1f}" for name, seconds in took.items())) - return sources, cfg - - -def start_alerts(cfg: Config, bot: Bot, notify: Notifier, tasks: Tasks) -> tuple[list[str], WeatherMonitor | None]: - """Hook up the alert monitor of every source that started and of the irrigation controller. The weather alerts start in - warm_up, once the station has been read. Returns the alert types now running, and the weather monitor.""" - eco, air, pollen, forecast = (bot.by_name.get(name) for name in ("Ecowitt", "AirGradient", "Pollen", "Forecast")) - running: list[str] = [] - weather = WeatherMonitor(eco, bot.state, notify, cfg.alert_cooldown_minutes * 60, cfg.rain_quiet_hours) if eco else None - if air: - tasks.start(every(PARTICULATES_CHECK_SECONDS, ParticulatesMonitor(air, bot.state, notify).check)) - running += ParticulatesMonitor.KINDS - if forecast: - forecast.warmer.after.append(ForecastMonitor(forecast, bot.state, notify).check) # after each refresh (in the day) - running += ForecastMonitor.KINDS - if pollen: - pollen.warmer.after.append(PollenAndAsthmaMonitor(pollen, bot.state, notify).check) # after each refresh (in the day) - running += PollenAndAsthmaMonitor.KINDS - if bot.irrigation: # the daily check (rain delay, battery) and the watchdog that closes the valve after a run - tasks.start(IrrigationMonitor(bot.irrigation, bot.state, notify, cfg.tz, cfg.irrigation_check_hour, eco, forecast).run()) - tasks.start(every(VALVE_CHECK_SECONDS, bot.watchdog.check)) - running += IrrigationMonitor.KINDS - return running, weather - - -async def warm_up(bot: Bot, weather: WeatherMonitor | None, running: list[str], tasks: Tasks, tg_bot=None): - """Fetch everything once, together, and log one summary line; then start what waited for it: the weather alerts, the - archives (copying each source's history into its cache), the keyboard's charts drawn ahead every few minutes.""" - eco, air = bot.by_name.get("Ecowitt"), bot.by_name.get("AirGradient") - - 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 - await safely(eco.warm, True) - try: - await weather.init() - eco.warmer.after.append(weather.check) # checked on every fresh refresh - running[:0] = WeatherMonitor.KINDS - await weather.check() - if eco.fast is not None: # Home Assistant: the rain alert looks at each new reading as it comes in, not only at the minute's refresh - eco.on_live.append(weather.check_rain) - except Exception as e: - 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()) - # The full history is copied into the cache in the background (a few minutes the first time), so questions rarely - # need Ecowitt inline - tasks.start(Archive(eco, eco.archive_pace).loop()) - if eco.ranges_from_ha: # the cloud's readings get their 5-minute bands from what Home Assistant kept, the days the bot was not watching too - tasks.start(every(HA_IMPORT_SECONDS, eco.import_ranges)) - - async def air_part(): - await safely(air.warm, True) - tasks.start(air_history()) # even if the sensor was unreachable just now - - async def air_history(): - """What Home Assistant kept of the monitor (the readings the bot lacks, their bands, the minutes), then the days the cache lacks, then - Home Assistant again every HA_IMPORT_SECONDS.""" - if air.ha: # (first: it is quick, and holds the last days; the backfill can take minutes the first time) - await safely(air.import_history) - if air.cloud: - await safely(air_backfill) - if air.ha: - await every(HA_IMPORT_SECONDS, air.import_history) - - async def air_backfill(): - started = time.monotonic() - 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) - try: - await asyncio.gather(*([ecowitt_part()] if eco else []), *([air_part()] if air else [])) - 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)) - if missing := [LABELS[k] for k in available_kinds(bot.by_name, bot.irrigation is not None) if k not in running]: - log.warning("Alerts NOT running: %s (see the error above)", ", ".join(missing)) - if tg_bot is not None: - tasks.start(every(AHEAD_SECONDS, lambda: bot.draw_buttons_ahead(tg_bot))) +def start_alerts(cfg: Config, bot: Bot, notify: Notifier, tasks: Tasks, weather: RemoteWeather, + irrigation: RemoteIrrigation | None = None) -> list: + """The alerts are the servers': ecobot-mcp's alert log read over MCP (ecobot://alerts) and, with irrigation-mcp, its own + (irrigation://alerts), each delivered (AlertDelivery) to the chats subscribed to its kinds, each with its own last id handled in + bot_state.json. Returns what keeps the time zone (the deliveries: follow_zone).""" + delivery = AlertDelivery(weather.alerts, notify, bot.state, cfg.tz, weather=weather) # (its charts drawn by ecobot-mcp) + zoned: list = [delivery] + tasks.start(delivery.run()) + if irrigation is not None: # (its alerts have no chart) + watering = AlertDelivery(irrigation.alerts, notify, bot.state, cfg.tz, mark=ReadMark(bot.state, IRRIGATION_MCP), + unexpired_first=True) # (at the first start: the battery or pause alerts of a check that came before) + zoned.append(watering) + tasks.start(watering.run()) + return zoned -def version() -> str: - """The checked-out commit, so the log shows which code is running.""" - return commit_in(ROOT / ".git") +def _zone(name: str | None): + try: + return ZoneInfo(name) if name else None + except Exception: + return None -def commit_in(git_dir) -> str: - """The short hash HEAD points at, read from the repository's files rather than by running git (which refuses a folder owned by - another user, as when the service runs as its own user). "unknown" when it cannot be read.""" - try: - head = (git_dir / "HEAD").read_text().strip() - if head.startswith("ref:"): - ref = head.split(None, 1)[1] +def follow_zone(weather: RemoteWeather, bot: Bot, state: AlertState, zoned: list): + """The bot in the station's time zone whenever it is read (the first read, if ecobot-mcp couldn't be reached at start, or + another zone later): the bot's settings, the charts, the alerts' charts, and what start_alerts started (`zoned`: AlertDelivery, + IrrigationMonitor, whose wait for the check time is timed again). The zone is kept in bot_state.json, for a start while ecobot-mcp + can't be reached (connect).""" + def apply(zone): + if state.zone != str(zone): + state.zone = str(zone) try: - head = (git_dir / ref).read_text().strip() - except FileNotFoundError: # after `git pack-refs` or gc the branch is a line in packed-refs - head = next(line.split()[0] for line in (git_dir / "packed-refs").read_text().splitlines() - if line.endswith(f" {ref}")) - return head[:7] if len(head) >= 7 and all(c in "0123456789abcdef" for c in head.lower()) else "unknown" - except Exception: - return "unknown" + state.save() + except Exception as e: + log.warning("Couldn't save the station's time zone (%s: %s)", type(e).__name__, e) + if str(zone) == str(bot.cfg.tz): + return + log.info("The weather station's time zone is %s: the bot runs in it from now on (it was %s)", zone, bot.cfg.tz) + bot.cfg = dataclasses.replace(bot.cfg, tz=zone) + bot.alert_charts.tz = zone + theme.configure(bot.cfg.dark_mode, zone) + for keeper in zoned: + keeper.tz = zone + weather.on_zone = apply + if weather.station_tz is not None: # (read before this was hooked up) + apply(weather.station_tz) + + +def mcp_token(cfg: Config): + """The token the bot sends ecobot-mcp: the first of AUTH_TOKENS; else the retired WEATHER_MCP_TOKEN, with a warning; else the one + ecobot-mcp generated in the data folder they share, read again for each connection (a function: ecobot-mcp may write it after the + bot starts: at a start of both, the bot may look before ecobot-mcp has written it). Never logged: only where it is.""" + if cfg.auth_tokens: + if cfg.retired_mcp_token: + log.warning("%s is retired and ignored: the bot sends the first of AUTH_TOKENS", RETIRED_TOKEN) + return cfg.auth_tokens[0] + if cfg.retired_mcp_token: + log.warning("%s is retired: the bot sends it for now, but move it into AUTH_TOKENS (and into ecobot-mcp's AUTH_TOKENS, " + "if it isn't there already)", RETIRED_TOKEN) + return cfg.retired_mcp_token + folder = cfg.state_path.parent + return lambda: auth_token.read(folder) + + +def no_token_yet(cfg: Config, token) -> bool: + """Said (a warning) when ecobot-mcp couldn't be reached in time and the bot has no token to send it: the generated one isn't in the + data folder. Only then: at a start of both, the file can appear a moment after the bot first looks.""" + if not callable(token) or token() is not None: + return False + log.warning("AUTH_TOKENS is not set and there is no token at %s: ecobot-mcp writes it there at its first start, on the same data " + "folder. Until it can be read the bot sends none and is refused; set AUTH_TOKENS (the same in both) if ecobot-mcp keeps " + "another folder", auth_token.path(cfg.state_path.parent)) + return True + + +async def connect(cfg: Config, stack: contextlib.AsyncExitStack, state: AlertState) -> tuple[RemoteWeather, Config]: + """The bot as ecobot-mcp's client (BOT_MCP_URL): the supervisor started (closed by `stack`), the first connection waited for up to + STARTUP_WAIT seconds; the settings in the station's time zone once it has been read, else in the one last read (kept in + bot_state.json), else in TZ's, with a warning. Read later, it is followed then (follow_zone).""" + kept = _zone(state.zone) + token = mcp_token(cfg) + weather = RemoteWeather(cfg.mcp_url, token, kept or cfg.tz) + supervisor = asyncio.create_task(weather.run()) + + async def stop(): + supervisor.cancel() + await asyncio.gather(supervisor, return_exceptions=True) + await weather.close() + stack.push_async_callback(stop) + try: + await asyncio.wait_for(weather.listening.wait(), STARTUP_WAIT) + except TimeoutError: + no_token_yet(cfg, token) + log.warning("ecobot-mcp at %s isn't reachable yet: questions are told so until it is (the time zone is %s, %s, " + "until its station is read)", cfg.mcp_url, "the station's last read" if kept else "TZ's", weather.tz) + if str(weather.tz) != str(cfg.tz): + cfg = dataclasses.replace(cfg, tz=weather.tz) + return weather, cfg + + +TUYA_NAMES = ("IRRIGATION_TUYA_DEVICE_ID", "BOT_TUYA_DEVICE_ID", "TUYA_DEVICE_ID") # (any of them set: the bot once ran the controller) + + +def connect_irrigation(cfg: Config, stack: contextlib.AsyncExitStack, token) -> RemoteIrrigation | None: + """irrigation-mcp's client (BOT_IRRIGATION_MCP_URL), its supervisor started (closed by `stack`), not waited for: a press while it + can't be reached is told so. None without the setting (no Irrigation button, no irrigation alerts); then a Tuya setting still in the + environment (the bot ran the controller itself before step 8b) is a warning saying what to do.""" + if not cfg.irrigation_mcp_url: + if any(os.getenv(name, "").strip() for name in TUYA_NAMES): + log.warning("The irrigation controller's settings are set but BOT_IRRIGATION_MCP_URL isn't: the controller is irrigation-mcp's " + "now (python -m irrigation_mcp, the irrigation-mcp.service unit, or the irrigation-mcp container). Run it and set " + "BOT_IRRIGATION_MCP_URL (systemd: http://127.0.0.1:8766/mcp) for the Irrigation button and its alerts " + "(docs/configuration.md)") + return None + if urlsplit(cfg.irrigation_mcp_url).hostname in ("127.0.0.1", "localhost", "::1") and docker_private_network(): + log.warning("BOT_IRRIGATION_MCP_URL is %s, but in a container on Docker's own network that is the bot's container, not " + "irrigation-mcp's: set it to http://irrigation-mcp:8766/mcp (README: Docker)", cfg.irrigation_mcp_url) + irrigation = RemoteIrrigation(cfg.irrigation_mcp_url, token) + supervisor = asyncio.create_task(irrigation.run()) + + async def stop(): + supervisor.cancel() + await asyncio.gather(supervisor, return_exceptions=True) + await irrigation.close() + stack.push_async_callback(stop) + return irrigation AsyncOpenAI = Timeout = None # openai's, imported when the model's client is made (_client): the import takes half a second, more than all of lib @@ -220,50 +195,38 @@ def _client(cfg: Config): async def main(): log.info("Starting ecobot %s", version()) - cfg = Config.from_env() + cfg = Config.from_env() # (stops, saying so, without BOT_MCP_URL: the bot is ecobot-mcp's client and nothing else) _format.width = cfg.log_width # a chat message in the log is cut to it from here on for name in ("ecobot", "lib"): # the bot's own lines: the libraries keep theirs logging.getLogger(name).setLevel(cfg.log_level) - air_metrics.REQUIRE_CONSECUTIVE = cfg.antispike_require_consecutive - intent.FEELS_LIKE_IN_ALL = cfg.chart_all_feels_like - intent.VPD_IN_ALL = cfg.chart_all_vpd # Whatever starts is closed on the way out, the last started first, however the bot stops (a failure part-way included) async with contextlib.AsyncExitStack() as stack: app = (Application.builder().token(cfg.telegram_token).concurrent_updates(True) .defaults(Defaults(disable_notification=True)) # silent messages .connect_timeout(10).read_timeout(15).write_timeout(15) # default 5s is tight .build()) - handshake = asyncio.create_task(app.initialize()) # Telegram is asked who the bot is while the sources start + handshake = asyncio.create_task(app.initialize()) # Telegram is asked who the bot is while ecobot-mcp is reached + state = AlertState(cfg.state_path) try: - sources, cfg = await start_sources(cfg) # in the weather station's time zone from here on + weather, cfg = await connect(cfg, stack, state) # in the weather station's time zone from here on, once it is read except BaseException: handshake.cancel() raise - for source in sources: - stack.push_async_callback(safely, source.close) - if not sources: - handshake.cancel() - raise SystemExit("No data source is working - nothing to talk about") - by_name = {s.name: s for s in sources} - eco, air = by_name.get("Ecowitt"), by_name.get("AirGradient") - charts.configure(cfg.dark_mode, cfg.tz) # DARKMODE (in the station's time zone, as everything from here on) - composer = Composer(eco, air) if eco and air else None # charts and comparisons across the two sources - history = await History.open(eco, air) if eco or air else None # the readings tool: values at an interval, from the file - tools = Tools([t for s in sources for t in s.tools] + (composer.tools if composer else []) + (history.tools if history else [])) - client = _client(cfg) if cfg.openrouter_api_key else None # without a key the bot answers only what it works out in code + theme.configure(cfg.dark_mode, cfg.tz) # DARKMODE (in the station's time zone, as everything from here on) + client = _client(cfg) if cfg.openrouter_api_key else None # without a key the bot answers its buttons and sends alerts, no more if client: stack.push_async_callback(safely, client.close) else: - log.warning("OPENROUTER_API_KEY is not set: running without the model, so answers are limited") - state = AlertState(cfg.state_path) + log.warning("BOT_OPENROUTER_API_KEY is not set: running without the model, so the bot answers its buttons and sends alerts, " + "and a typed question is told the model isn't set up") if cfg.admin_only and not cfg.admin_chat_ids and not any(chat < 0 for chat in state.chats): - log.warning("Admin only is on but no group is known yet and ADMIN_CHAT_IDS is empty, so nobody can use the bot: " - "add it to a group, list your user id in ADMIN_CHAT_IDS, or set ADMIN_ONLY=off") - irrigation = Tuya(cfg) if cfg.irrigation else None - if irrigation: - stack.push_async_callback(safely, irrigation.close) + log.warning("Admin only is on but no group is known yet and BOT_ADMIN_CHAT_IDS is empty, so nobody can use the bot: " + "add it to a group, list your user id in BOT_ADMIN_CHAT_IDS, or set BOT_ADMIN_ONLY=off") tasks = Tasks() # everything that runs in the background, the bot's own uploads among it; cancelled first on the way out (tasks.close, below) - bot = Bot(cfg, Agent(client, cfg.openrouter_model, tools), sources, state, irrigation, tasks) + irrigation = connect_irrigation(cfg, stack, mcp_token(cfg)) # irrigation-mcp's client (BOT_IRRIGATION_MCP_URL), or None + # ecobot-mcp's tools over MCP (lib/weather.py): the model is offered them (lib/model_tools.py), and the bot's own code paths + # call them (the keyboard's charts, the Status picture, the alert charts and the period buttons) + bot = Bot(cfg, Agent(client, cfg.openrouter_model, model_tools.tools(weather)), state, irrigation, tasks, service=weather) bot.register(app) stop = asyncio.Event() @@ -273,7 +236,7 @@ async def main(): await handshake stack.push_async_callback(app.shutdown) # one task runs everything, so connections open and close cleanly except InvalidToken: # (its message names the token, so it is not shown) - raise SystemExit("TELEGRAM_BOT_TOKEN was rejected by Telegram: check it is the token @BotFather gave for this bot") from None + raise SystemExit("BOT_TELEGRAM_TOKEN was rejected by Telegram: check it is the token @BotFather gave for this bot") from None except NetworkError as e: # (the host's network or DNS, most often): one line, not the library's pages of stack raise SystemExit(f"Can't reach Telegram ({type(e).__name__}: {e}): check the network and DNS of the machine or container") from None await app.start() @@ -282,19 +245,18 @@ async def main(): error_callback=polling_error) # messages sent while starting are answered (lib.bot.PENDING_MAX_SECONDS) stack.push_async_callback(app.updater.stop) stack.push_async_callback(tasks.close) - for source in sources: - stack.push_async_callback(source.warmer.stop) log.info("Telegram: @%s, Model: %s", app.bot.username, cfg.openrouter_model if client else "none") - for source in sources: # what each is reading, in the order they are listed - for line in source.startup_lines(): - log.info("%s", line) + log.info("ecobot-mcp: %s (%s)", cfg.mcp_url, ", ".join(sorted(weather.names)) or "not reached yet") + if irrigation: + log.info("irrigation-mcp: %s", cfg.irrigation_mcp_url) notify = Notifier(app.bot, state, bot.alert_charts) # the alerts' charts, kept with the bot's - await bot.publish_commands(app.bot) # the / menu - running, weather = start_alerts(cfg, bot, notify, tasks) - for source in sources: # keeping warm: everything questions need, refreshed before they arrive - tasks.start(source.warmer.run()) - tasks.start(warm_up(bot, weather, running, tasks, app.bot)) + # the / menu: the bot's own commands and ecobot-mcp's prompts, set again whenever the prompts are read (each connection, and + # when ecobot-mcp says they changed) + weather.on_prompts = lambda: tasks.start(bot.publish_commands(app.bot)) + await bot.publish_commands(app.bot) + zoned = start_alerts(cfg, bot, notify, tasks, weather, irrigation) + follow_zone(weather, bot, state, zoned) await stop.wait() diff --git a/ecobot.service b/ecobot.service index 3ae0ee0d..9c3dc7ec 100644 --- a/ecobot.service +++ b/ecobot.service @@ -1,24 +1,34 @@ -# Install as /etc/systemd/system/ecobot.service, with the code outside every home directory: +# Install as /etc/systemd/system/ecobot.service, beside ecobot-mcp.service (README: "systemd"), with the code outside every home directory: # sudo git clone <repo> /opt/ecobot && cd /opt/ecobot -# sudo python3.13 -m venv .venv && sudo .venv/bin/pip install -r requirements.txt # Python 3.13.5 (.python-version) -# The files stay owned by root and readable by all: the service runs as a throw-away user (DynamicUser=) that cannot write to them, +# sudo python3.13 -m venv .venv && sudo .venv/bin/pip install -r requirements.txt -r requirements-charts.txt # Python 3.13.5 (.python-version) +# sudo cp ecobot-mcp.service ecobot.service /etc/systemd/system/ && sudo systemctl daemon-reload +# sudo systemctl enable --now ecobot-mcp.service ecobot.service +# With the irrigation controller, irrigation-mcp.service too (see that file), and BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp. +# The bot is ecobot-mcp's client (docs/ecobot-mcp.md step 6b): it runs no source and no alert rule of its own, and can't start without +# BOT_MCP_URL=http://127.0.0.1:8765/mcp in /etc/ecobot.env. This unit pulls ecobot-mcp.service in and starts after it (Wants=, After=), +# so the bot finds it up; ecobot-mcp restarting doesn't stop the bot, which waits for it and says so to anyone who asks meanwhile. It +# wants irrigation-mcp.service and starts after it the same way, but only if that unit is installed: Wants= on a unit that isn't there +# changes nothing, so the bot starts without it (and has no Irrigation button without BOT_IRRIGATION_MCP_URL). +# The files stay owned by root and readable by all: the bot runs as a throw-away user (DynamicUser=) that cannot write to them, # so its bytecode goes to /var/cache/ecobot (CacheDirectory=, PYTHONPYCACHEPREFIX=) and is rebuilt on its own after an update. # Any other place needs only the WorkingDirectory and ExecStart lines changed. -# The bot never opens the environment file itself: systemd loads it (TZ, OPENROUTER_*, ECOWITT_*, AIRGRADIENT_*, TUYA_*, -# TELEGRAM_BOT_TOKEN, ...). -# StateDirectory= gives the bot /var/lib/ecobot (the state file and the SQLite caches): the bot finds it through -# STATE_DIRECTORY, so no DATA_DIR is needed, and it is the only place the sandbox below lets it write. Files an older install kept in -# the checkout (bot_state.json, *_cache.sqlite) are not read from there: with the service stopped, copy them into /var/lib/ecobot once; -# systemd hands the folder to the dynamic user when it starts. +# The bot never opens the environment file itself: systemd loads it (docs/configuration.md: its BOT_ settings and the shared ones such +# as TZ and AUTH_TOKENS; the MCP_ ones are ecobot-mcp's and the IRRIGATION_ ones irrigation-mcp's, read by their units from the same +# file). The irrigation controller's Tuya secrets are dropped here by every name they have had (UnsetEnvironment=): the bot never uses them. +# StateDirectory= gives the bot /var/lib/ecobot (its state file, bot_state.json, and ecobot-mcp's token, which it reads there): the bot +# finds it through STATE_DIRECTORY, so no DATA_DIR is needed, and it is the only place the sandbox below lets it write. Files an older +# install kept in the checkout (bot_state.json, *_cache.sqlite) are not read from there: with both units stopped, copy them into +# /var/lib/ecobot once; systemd hands the folder to the dynamic user when it starts. [Unit] -Description=ecobot (Telegram weather and air-quality bot) -After=network-online.target -Wants=network-online.target +Description=ecobot (Telegram weather and air-quality bot, a client of ecobot-mcp) +After=network-online.target ecobot-mcp.service irrigation-mcp.service +Wants=network-online.target ecobot-mcp.service irrigation-mcp.service [Service] DynamicUser=yes WorkingDirectory=/opt/ecobot EnvironmentFile=/etc/ecobot.env +UnsetEnvironment=IRRIGATION_TUYA_CLIENT_ID BOT_TUYA_CLIENT_ID TUYA_CLIENT_ID IRRIGATION_TUYA_CLIENT_SECRET BOT_TUYA_CLIENT_SECRET TUYA_CLIENT_SECRET Environment=PYTHONUNBUFFERED=1 Environment=PYTHONPYCACHEPREFIX=/var/cache/ecobot/pycache StateDirectory=ecobot @@ -62,8 +72,8 @@ ProtectHostname=yes ProtectProc=invisible RestrictNamespaces=yes -# Network: HTTPS to the weather, air, pollen, Tuya, Telegram and model APIs (AF_UNIX: the local name resolver; AF_NETLINK: listing -# the network interfaces, which finding the air sensor by its .local name on the network needs) +# Network: HTTPS to Telegram and the model, and ecobot-mcp's and irrigation-mcp's MCP ports (AF_UNIX: the local name resolver; AF_NETLINK: listing the +# network interfaces) RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK # Resource limits diff --git a/ecobot_mcp/__init__.py b/ecobot_mcp/__init__.py new file mode 100644 index 00000000..a73313f3 --- /dev/null +++ b/ecobot_mcp/__init__.py @@ -0,0 +1,6 @@ +"""ecobot-mcp, the MCP server on its own (docs/ecobot-mcp.md 3.8, step 5): the readings file, the sources and syncers that fill it, the +alert rules that write the alert log, and the MCP server over them (lib/mcp_server.py). + + - `python -m ecobot_mcp` (__main__.py): ecobot-mcp, Streamable HTTP at http://MCP_BIND/mcp; + - core.py: its startup (the sources, the alert log, the tools, the alert rules, the keep-warm, the first fetch, the archive, the + backfills and Home Assistant's imports). The bot (ecobot.py) is only ever its client, over MCP (step 6b).""" diff --git a/ecobot_mcp/__main__.py b/ecobot_mcp/__main__.py new file mode 100644 index 00000000..b55bc047 --- /dev/null +++ b/ecobot_mcp/__main__.py @@ -0,0 +1,107 @@ +"""python -m ecobot_mcp: ecobot-mcp, the MCP server on its own (docs/ecobot-mcp.md 3.8). It runs the sources and their syncers +(ecobot_mcp/core.py: the keep-warm, the first fetch, the archive, the backfills, Home Assistant's imports), the alert rules writing +the alert log, and the MCP server (lib/mcp_server.py) at http://MCP_BIND/mcp, Streamable HTTP under uvicorn: put it behind TLS (a +reverse proxy such as Caddy) to reach it from elsewhere. + +Settings come from the environment (lib/config.py, docs/configuration.md): the MCP_ ones and the shared ones; the bot's (BOT_) are not +needed. Among them MCP_BIND (host:port, default 127.0.0.1:8765), MCP_ALLOWED_HOSTS (the Host names it answers, default 127.0.0.1 and +localhost) and AUTH_TOKENS (token,token,..., one per client). Every request needs one of the tokens: with AUTH_TOKENS unset, the one +it generates at its first start and keeps in the data folder (lib/auth_token.py).""" + +import asyncio +import contextlib +import logging +import signal +import socket + +from lib import auth_token, chart_images, mcp_http +from lib.config import Config +from lib.logs import LogFormat, on_journal, stream_handlers +from lib.mcp_http import Uvicorn + +from .core import Core, configure, start_sources, version + +log = logging.getLogger("ecobot.mcp") +SHUTDOWN_SECONDS = mcp_http.SHUTDOWN_SECONDS # how long uvicorn waits for open connections (a listen stream) to end when ecobot-mcp stops + + +def server_config(app, host: str, port: int): + """uvicorn's settings for the app (lib/mcp_http.server_config), an open listen stream given SHUTDOWN_SECONDS to end.""" + return mcp_http.server_config(app, host, port, SHUTDOWN_SECONDS) + + +def generated_token(cfg: Config) -> str: + """AUTH_TOKENS unset: the token kept in the data folder, made at the first start (its place is logged, never its value).""" + return mcp_http.generated_token(cfg.state_path.parent, log) + + +async def main(): + from lib.mcp_server import EcobotServer, http_app + log.info("Starting ecobot-mcp %s", version()) + cfg = Config.from_env(bot=False) + for name in ("ecobot", "lib"): + logging.getLogger(name).setLevel(cfg.log_level) + host, port = cfg.mcp_bind + tokens = cfg.auth_tokens or (generated_token(cfg),) + configure(cfg) + async with contextlib.AsyncExitStack() as stack: + sources, cfg = await start_sources(cfg) # in the weather station's time zone from here on + chart_images.configure(cfg.dark_mode, cfg.tz) # DARKMODE for the charts' images, when a client asks for them (Pillow not imported yet) + for source in sources: + stack.push_async_callback(source.close) + if not sources: + raise SystemExit("No data source is working - nothing to serve") + from lib.warm import Tasks + tasks = Tasks() + core = await Core.open(cfg, sources, stack, tasks) + stack.push_async_callback(tasks.close) + server = EcobotServer(core.ctx, core.alert_log, health=core.health.report, version=version(), + 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) + core.log_startup() + running = core.start_alerts() + core.start_warmers() + tasks.start(server.run()) + + async def warm_up(): + await core.warm_up(running) + if missing := core.missing_alerts(running): + log.warning("Alerts NOT running: %s (see the error above)", ", ".join(missing)) + tasks.start(warm_up()) + + stop = asyncio.Event() + for sig in (signal.SIGINT, signal.SIGTERM): + asyncio.get_running_loop().add_signal_handler(sig, stop.set) + web = Uvicorn(server_config(app, host, port)) + serving = asyncio.create_task(web.serve()) + shown = host if ":" not in host else f"[{host}]" + log.info("MCP: http://%s:%d/mcp, %s; answering Host %s", shown, port, + 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("Chart links (?charts=link): %s/<id>.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()) + await asyncio.wait({serving, waiting}, return_when=asyncio.FIRST_COMPLETED) + server.listen.close() # (the listen streams end gracefully: their clients know to listen again) + web.should_exit = True + await serving + waiting.cancel() + if not stop.is_set(): + raise SystemExit(f"The MCP server stopped: is {host}:{port} free?") + + +def run(): + _format = LogFormat("%(levelname)s %(message)s", priority=on_journal()) + logging.basicConfig(level=logging.INFO, handlers=stream_handlers(_format)) + logging.getLogger("httpx").setLevel(logging.WARNING) + logging.getLogger("httpx2").setLevel(logging.WARNING) + with contextlib.suppress(KeyboardInterrupt): + asyncio.run(main()) + + +if __name__ == "__main__": + run() diff --git a/ecobot_mcp/core.py b/ecobot_mcp/core.py new file mode 100644 index 00000000..aebbafdf --- /dev/null +++ b/ecobot_mcp/core.py @@ -0,0 +1,283 @@ +"""ecobot-mcp's startup (docs/ecobot-mcp.md step 5: "ecobot.py's warm_up() is split"), run by ecobot-mcp (python -m ecobot_mcp): the +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); + 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. + +`Health` records each loop's last success and failure (ecobot://health).""" + +import asyncio +import dataclasses +import functools +import logging +import os +import time +from collections.abc import Awaitable, Callable +from dataclasses import dataclass, field +from datetime import datetime + +from lib.airgradient import AirGradient +from lib.airgradient import metrics as air_metrics +from lib.alert_log import AlertLog +from lib.alerts.kinds import LABELS, available_kinds +from lib.alerts.store import AlertStore +from lib.compose import Composer +from lib.config import Config +from lib.ecowitt import Archive, Ecowitt +from lib.ecowitt.source import HA_IMPORT_SECONDS +from lib.forecast import Forecast +from lib.logs import BUGS +from lib.pollen import Pollen +from lib.service import Service +from lib.service import about as service_about +from lib.service import names as service_names +from lib.service.alerts import AlertRules +from lib.service.context import Context +from lib.sources import Source +from lib.storage import Storage +from lib.version import commit_in, version # noqa: F401 (the running commit: ecobot-mcp's and the bot's) +from lib.warm import Tasks, every, safely + +log = logging.getLogger("ecobot.mcp") # (under the bot's own logger: LOG_LEVEL reaches it) + + +def configure(cfg: Config): + """The settings the engines read as module values: the anti-spike rule, what "all" draws, what `about` says of the alerts.""" + air_metrics.REQUIRE_CONSECUTIVE = cfg.antispike_require_consecutive + service_names.FEELS_LIKE_IN_ALL = cfg.chart_all_feels_like # "all" (and "weather all week") draws these too + service_names.VPD_IN_ALL = cfg.chart_all_vpd + service_about.RAIN_QUIET_HOURS = cfg.rain_quiet_hours # what `about` says of the rain alert's quiet hours ... + service_about.ALERT_COOLDOWN_MINUTES = cfg.alert_cooldown_minutes # ... and of the alerts' cooldown + + +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.""" + sources: list[Source] = [] + took: dict[str, float] = {} + + async def start(kind: type[Source], *args, **kwargs) -> Source | None: + """A source made and started; one that fails either way is logged and left out (None).""" + source, started = None, time.monotonic() + try: + source = kind(*args, **kwargs) + await source.start() + 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)) + if source is not None: + await safely(source.close) + return None + finally: + took[kind.name] = time.monotonic() - started + storage = None + if cfg.ecowitt or cfg.airgradient: + try: # (in a thread: opening makes or upgrades its tables) + storage = await asyncio.to_thread(Storage, cfg.storage_path, cfg.tz) + except Exception as e: + log.error("The history file %s couldn't be opened (%s: %s) - continuing without the weather station and the air sensor", + cfg.storage_path, type(e).__name__, e, exc_info=isinstance(e, BUGS)) + if cfg.ecowitt and storage is not None and (eco := await start(Ecowitt, cfg, storage=storage)): + sources.append(eco) + eco = sources[0] if sources else None + if eco and str(eco.tz) != str(cfg.tz): + if os.getenv("TZ"): + log.warning("TZ=%s is not the weather station's time zone; using the station's, %s", os.getenv("TZ"), eco.tz) + cfg = dataclasses.replace(cfg, tz=eco.tz) + if not getattr(cfg.tz, "key", None): + log.warning("The time zone has no name, only an offset (%s), so daylight saving will put the times out: set TZ, " + "e.g. TZ=Australia/Melbourne", cfg.tz) + starts = [] + if cfg.airgradient and storage is not None: # (one file and one Home Assistant client for both; the file is the station's to close, else the sensor's) + starts.append(start(AirGradient, cfg, storage=storage, owned=eco is None, **({"ha": eco.ha} if eco and eco.ha else {}))) + 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)) + 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() + if took: + log.debug("Sources started in %.1fs: %s", sum(took.values()), ", ".join(f"{name} {seconds:.1f}" for name, seconds in took.items())) + return sources, cfg + + +# ---------- health ---------- +class Health: + """Each loop's last success and failure (`track`), and the archive's last run (`archived`), for ecobot://health.""" + + def __init__(self, tz=None): + self.tz = tz + self.loops: dict[str, dict] = {} + self.archive: dict = {} + self.extra: dict[str, Callable[[], dict]] = {} # name -> figures read when asked (the live poll's last answer) + + def track(self, name: str, fn: Callable[..., Awaitable]) -> Callable[..., Awaitable]: + """fn, its every run recorded under `name`: when it last succeeded, when it last failed and why. It raises as before, and keeps + its name (safely() logs a failure by it).""" + @functools.wraps(fn) + async def run(*args, **kwargs): + entry = self.loops.setdefault(name, {}) + try: + out = await fn(*args, **kwargs) + except Exception as e: + entry.update(last_failure=time.time(), error=f"{type(e).__name__}: {e}") + raise + entry["last_ok"] = time.time() + return out + return run + + def _time(self, t: float | None) -> str | None: + return None if not t else datetime.fromtimestamp(t, self.tz).isoformat(timespec="seconds") + + def report(self) -> dict: + loops = {name: {k: self._time(v) if k.startswith("last_") else v for k, v in entry.items()} for name, entry in self.loops.items()} + for name, read in self.extra.items(): + try: + loops[name] = {k: self._time(v) if k.startswith("last_") else v for k, v in read().items()} + except Exception as e: # (only a figure) + loops[name] = {"error": f"{type(e).__name__}: {e}"} + archive = {k: self._time(v) if k.startswith("last_") else v for k, v in self.archive.items()} + return {"loops": loops, **({"archive": archive} if archive else {})} + + +# ---------- ecobot-mcp ---------- +def hold_data_folder(cfg: Config, stack): + """One ecobot-mcp per data folder: two on the same folder would both fetch and both write each alert (sent twice). The lock is the + kernel's, so it goes with the process, however that ends.""" + from lib.mcp_http import hold_folder + hold_folder(cfg.state_path.parent, "mcp.lock", "ecobot-mcp", "python -m ecobot_mcp", stack) + + +@dataclass +class Core: + """ecobot-mcp as it runs: its settings, sources, alert log, tools and their Context, the alert rules once started.""" + cfg: Config + sources: list[Source] + alert_log: AlertLog + ctx: Context + service: Service + tasks: Tasks + health: Health + rules: AlertRules | None = None + running: list[str] = field(default_factory=list) # the alert types running (the weather's go first once they start) + + @property + def by_name(self) -> dict[str, Source]: + return {s.name: s for s in self.sources} + + @classmethod + async def open(cls, cfg: Config, sources: list[Source], stack, tasks: Tasks) -> "Core": + """The alert log (closed by `stack`) and the ten tools over the sources that started.""" + hold_data_folder(cfg, stack) + by_name = {s.name: s for s in sources} + eco, air = by_name.get("Ecowitt"), by_name.get("AirGradient") + composer = Composer(eco, air) if eco and air else None # charts and comparisons across the two sources + alert_log = AlertLog(cfg.alert_log_path, cfg.tz) # the alerts the rules decide, which clients deliver + stack.callback(alert_log.close) + ctx = await Context.open(eco=eco, air=air, composer=composer, forecast=by_name.get("Forecast"), pollen=by_name.get("Pollen"), + tz=cfg.tz) + service = Service.of(ctx) + log.info("Tools: %s", ", ".join(t.name for t in service)) + health = Health(cfg.tz) + for source in sources: # (the keep-warm's refreshes, recorded) + source.warmer.refresh = health.track(f"{source.name} refresh", source.warmer.refresh) + if eco is not None and eco.fast is not None: + health.extra["Ecowitt live poll"] = lambda: {"last_ok": eco._polled or None} + return cls(cfg, sources, alert_log, ctx, service, tasks, health) + + def log_startup(self): + """Each source's startup line, in the order they are listed.""" + for source in self.sources: + for line in source.startup_lines(): + log.info("%s", line) + + def start_alerts(self) -> list[str]: + """The alert rules over every source that started (lib/service/alerts.py), writing the alert log; the weather's start in + warm_up, once the station has been read. Returns the alert types now running (a list warm_up adds the weather's to).""" + store = AlertStore(self.cfg.alert_state_path) + self.rules = AlertRules(self.by_name, store, self.alert_log, self.cfg.alert_cooldown_minutes * 60, self.cfg.rain_quiet_hours, + self.service) + self.running = self.rules.start(self.tasks) + return self.running + + def start_warmers(self): + """Keeping warm: everything questions need, refreshed before they arrive.""" + for source in self.sources: + self.tasks.start(source.warmer.run()) + + async def warm_up(self, running: list[str] | None = None): + """Fetch everything once, together; then start what waited for it: the weather alerts, the live poll, the archives (copying each + source's history into its file), Home Assistant's imports.""" + running = self.running if running is None else running + 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 + await safely(health.track("Ecowitt refresh", eco.warm), True) + try: + if self.rules is not None: + await self.rules.start_weather(running) + except Exception as e: + 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()) + # 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) + archive.run_once = self._archived(archive, archive.run_once) + tasks.start(archive.loop()) + if eco.ranges_from_ha: # the cloud's readings get their 5-minute bands from what Home Assistant kept, the days the bot was not watching too + tasks.start(every(HA_IMPORT_SECONDS, health.track("Ecowitt Home Assistant import", eco.import_ranges))) + + async def air_part(): + await safely(health.track("AirGradient refresh", air.warm), True) + tasks.start(air_history()) # even if the sensor was unreachable just now + + async def air_history(): + """What Home Assistant kept of the monitor (the readings the service lacks, their bands, the minutes), then the days the cache + lacks, then Home Assistant again every HA_IMPORT_SECONDS.""" + imported = health.track("AirGradient Home Assistant import", air.import_history) + if air.ha: # (first: it is quick, and holds the last days; the backfill can take minutes the first time) + await safely(imported) + if air.cloud: + await safely(health.track("AirGradient backfill", air_backfill)) + if air.ha: + await every(HA_IMPORT_SECONDS, imported) + + async def air_backfill(): + started = time.monotonic() + 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) + + try: + await asyncio.gather(*([ecowitt_part()] if eco else []), *([air_part()] if air else [])) + 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)) + + def _archived(self, archive: Archive, run_once): + """The archive's run, its outcome recorded (Health.archive): when it last ran, what it fetched and failed, and what is held.""" + tracked = self.health.track("Ecowitt archive", run_once) + + @functools.wraps(run_once) + async def run(): + fetched, failed = await tracked() + self.health.archive = {"last_run": time.time(), "fetched": fetched, "failed": failed, "held": archive.held()} + return fetched, failed + return run + + def missing_alerts(self, running: list[str] | None = None) -> list[str]: + """The alert types the sources have that are not running (their labels): a rule that could not start.""" + running = self.running if running is None else running + return [LABELS[k] for k in available_kinds(self.by_name) if k not in running] + + +__all__ = ["Core", "Health", "commit_in", "configure", "start_sources", "version"] diff --git a/ecobot_service/__main__.py b/ecobot_service/__main__.py new file mode 100644 index 00000000..9f688bee --- /dev/null +++ b/ecobot_service/__main__.py @@ -0,0 +1,29 @@ +"""python -m ecobot_service: the old name of ecobot-mcp (python -m ecobot_mcp), kept so that an ecobot-mcp.service copied into +/etc/systemd/system before the rename keeps starting until the new unit is copied in (README, Upgrading > systemd). That old unit +drops the bot's secrets only by their old names (UnsetEnvironment=), so this drops them by their new ones too before ecobot-mcp +starts, and logs a warning saying what to do.""" + +import logging +import os + +# The bot's secrets by their new names, which the old unit's UnsetEnvironment= doesn't list (the new unit lists them itself) +BOT_SECRETS = ("BOT_TELEGRAM_TOKEN", "BOT_OPENROUTER_API_KEY", "BOT_TUYA_CLIENT_ID", "BOT_TUYA_CLIENT_SECRET") + + +def drop_bot_secrets(environ=os.environ) -> None: + for name in BOT_SECRETS: + environ.pop(name, None) + + +def run(): + drop_bot_secrets() + from ecobot_mcp.__main__ import run as run_mcp + logging.getLogger("ecobot.mcp").warning( + "Started as python -m ecobot_service, ecobot-mcp's old name: copy the new unit in " + "(sudo cp /opt/ecobot/ecobot-mcp.service /etc/systemd/system/ && sudo systemctl daemon-reload && " + "sudo systemctl restart ecobot-mcp), which runs python -m ecobot_mcp") + run_mcp() + + +if __name__ == "__main__": + run() diff --git a/irrigation-mcp.service b/irrigation-mcp.service new file mode 100644 index 00000000..29065949 --- /dev/null +++ b/irrigation-mcp.service @@ -0,0 +1,88 @@ +# irrigation-mcp, the irrigation controller's MCP server (python -m irrigation_mcp, docs/ecobot-mcp.md 3.9 and step 8): the Tuya +# controller, the watchdog that closes the valve after a run, the daily check (rain, battery) and the MCP server at +# http://127.0.0.1:8766/mcp. Optional: install it beside ecobot-mcp.service and ecobot.service, from the same checkout and venv (see +# ecobot.service), only if you have the controller: +# sudo cp /opt/ecobot/irrigation-mcp.service /etc/systemd/system/ && sudo systemctl daemon-reload +# sudo systemctl enable --now irrigation-mcp.service && sudo systemctl restart ecobot +# It needs IRRIGATION_TUYA_DEVICE_ID, IRRIGATION_TUYA_CLIENT_ID and IRRIGATION_TUYA_CLIENT_SECRET in /etc/ecobot.env (it stops at start, +# saying so, without them, and isn't restarted until it is started again), and the bot BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp there to show the Irrigation button and deliver +# its alerts. Its daily check asks ecobot-mcp (IRRIGATION_ECOBOT_MCP_URL, default http://127.0.0.1:8765/mcp) for the rain and the +# forecast: this unit pulls ecobot-mcp's in and starts after it, and before the bot (the bot's unit wants this one only if it is installed). +# Only one irrigation-mcp runs on a data folder (irrigation.lock): a second stops at start, saying so. +# The data folder is the bot's own, /var/lib/private/ecobot (StateDirectory=ecobot), shared with the same dynamic user (User=ecobot) as +# the other two units: irrigation-mcp keeps irrigation_state.json and irrigation_alerts.sqlite there, and the generated token (with +# AUTH_TOKENS unset) is the one all three use. +# It reads /etc/ecobot.env as the others do, less the bot's and ecobot-mcp's secrets, by their names and their old ones +# (UnsetEnvironment=): its settings are the IRRIGATION_ ones and the shared ones (docs/configuration.md). IRRIGATION_BIND defaults to +# 127.0.0.1:8766; to reach it from other machines set IRRIGATION_BIND=0.0.0.0:8766 and put TLS in front of it. +[Unit] +Description=irrigation-mcp (the ecobot irrigation controller's MCP server) +After=network-online.target ecobot-mcp.service +Wants=network-online.target ecobot-mcp.service +Before=ecobot.service + +[Service] +DynamicUser=yes +User=ecobot +Group=ecobot +WorkingDirectory=/opt/ecobot +EnvironmentFile=/etc/ecobot.env +UnsetEnvironment=BOT_TELEGRAM_TOKEN TELEGRAM_BOT_TOKEN BOT_OPENROUTER_API_KEY OPENROUTER_API_KEY WEATHER_MCP_TOKEN MCP_ECOWITT_API_KEY ECOWITT_API_KEY MCP_ECOWITT_APP_KEY ECOWITT_APP_KEY MCP_AIRGRADIENT_API_TOKEN AIRGRADIENT_API_TOKEN MCP_HOMEASSISTANT_TOKEN HOMEASSISTANT_TOKEN +Environment=PYTHONUNBUFFERED=1 +Environment=PYTHONPYCACHEPREFIX=/var/cache/ecobot/pycache +StateDirectory=ecobot +CacheDirectory=ecobot +ExecStart=/opt/ecobot/.venv/bin/python -m irrigation_mcp +Restart=on-failure +RestartSec=10 +# Its settings missing or wrong (the Tuya ones, say), it exits 78 and is not restarted: fix /etc/ecobot.env, then start it again +RestartPreventExitStatus=78 +TimeoutStopSec=30 +StandardOutput=journal +StandardError=journal +SyslogIdentifier=irrigation-mcp + +# Filesystem isolation +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +InaccessiblePaths=/boot /media /mnt +UMask=0077 + +# Privilege restrictions +AmbientCapabilities= +CapabilityBoundingSet= +LockPersonality=yes +MemoryDenyWriteExecute=yes +NoNewPrivileges=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +SystemCallArchitectures=native +SystemCallErrorNumber=EPERM +SystemCallFilter=@system-service + +# Kernel and system protection +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes + +# Process isolation +ProtectProc=invisible +RestrictNamespaces=yes + +# Network: HTTPS to the Tuya cloud, ecobot-mcp's MCP port, and its own (AF_UNIX: the local name resolver; AF_NETLINK: listing the +# network interfaces) +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK + +# Resource limits +TasksMax=32 +MemoryAccounting=yes +MemoryHigh=150M +MemoryMax=250M + +[Install] +WantedBy=multi-user.target diff --git a/irrigation_mcp/__init__.py b/irrigation_mcp/__init__.py new file mode 100644 index 00000000..40145398 --- /dev/null +++ b/irrigation_mcp/__init__.py @@ -0,0 +1,4 @@ +"""irrigation-mcp, the irrigation controller's MCP server (docs/ecobot-mcp.md 3.9, step 8): `python -m irrigation_mcp` (__main__.py) +runs the controller's watchdog and daily check and serves its tools and irrigation://alerts at http://IRRIGATION_BIND/mcp. Its code is +lib/irrigation (the Tuya client, the watchdog, the check, its state, its client of ecobot-mcp, the server); it imports nothing of +ecobot-mcp's sources or tools and nothing of the bot.""" diff --git a/irrigation_mcp/__main__.py b/irrigation_mcp/__main__.py new file mode 100644 index 00000000..3d54a2b5 --- /dev/null +++ b/irrigation_mcp/__main__.py @@ -0,0 +1,140 @@ +"""python -m irrigation_mcp: irrigation-mcp, the irrigation controller's MCP server (docs/ecobot-mcp.md 3.9). It runs, whatever any +client does: + + - the watchdog (lib/irrigation/watchdog.py), from the start (it doesn't wait for ecobot-mcp) every CHECK_SECONDS, sooner when a run + is due: a run it started is closed when it should have ended, a restart mid-run included (its end time is kept in + irrigation_state.json); + - the daily check at IRRIGATION_CHECK_HOUR (lib/irrigation/check.py): a low battery, and a 24 hour pause when it rained or rain is + likely, asking ecobot-mcp (IRRIGATION_ECOBOT_MCP_URL) as its MCP client for the rain measured and the forecast; its alerts go to + irrigation://alerts; + - the MCP server (lib/irrigation/server.py) at http://IRRIGATION_BIND/mcp (default 127.0.0.1:8766), Streamable HTTP under uvicorn: put + it behind TLS to reach it from elsewhere. + +Settings come from the environment (lib/config.py, docs/configuration.md): the IRRIGATION_ ones and the shared ones (AUTH_TOKENS, DATA_DIR, +TZ, LOG_LEVEL). It needs IRRIGATION_TUYA_DEVICE_ID, IRRIGATION_TUYA_CLIENT_ID and IRRIGATION_TUYA_CLIENT_SECRET. Every request needs one +of AUTH_TOKENS, or with that unset the token generated in the data folder (lib/auth_token.py, the one ecobot-mcp uses); it sends ecobot-mcp +the first of AUTH_TOKENS, or that same generated token. One irrigation-mcp runs per data folder (irrigation.lock).""" + +import asyncio +import contextlib +import logging +import signal +import socket +from urllib.parse import urlsplit + +from lib import auth_token, mcp_http +from lib.config import Config +from lib.logs import LogFormat, on_journal, stream_handlers +from lib.mcp_http import Uvicorn +from lib.netenv import docker_private_network +from lib.version import version + +log = logging.getLogger("lib.irrigation.main") # (under "lib": LOG_LEVEL reaches it) +LOCK = "irrigation.lock" +STARTUP_WAIT = 15.0 # seconds the daily check waits for ecobot-mcp at start (its station names the time zone) before it goes without +SHUTDOWN_SECONDS = mcp_http.SHUTDOWN_SECONDS +SETTINGS_EXIT = 78 # the exit status when its settings won't do (sysexits' EX_CONFIG): its unit doesn't restart it (RestartPreventExitStatus) + + +def ecobot_token(cfg: Config): + """The token sent to ecobot-mcp: the first of AUTH_TOKENS; else the one generated in the data folder they share, read again for each + connection (a function: ecobot-mcp may write it after this starts). Never logged.""" + if cfg.auth_tokens: + return cfg.auth_tokens[0] + folder = cfg.state_path.parent + return lambda: auth_token.read(folder) + + +async def main(): + from lib.alert_log import AlertLog + from lib.irrigation import Tuya, Watchdog + from lib.irrigation.check import IrrigationMonitor + from lib.irrigation.ecobot import EcobotWeather + from lib.irrigation.server import IrrigationServer, http_app + from lib.irrigation.state import IrrigationState + from lib.irrigation.watchdog import CHECK_SECONDS + from lib.warm import Tasks, every, safely + log.info("Starting irrigation-mcp %s", version()) + try: + cfg = Config.from_env(program="irrigation") # (stops, saying so, without the controller's Tuya settings) + except SystemExit as e: + if not isinstance(e.code, str): + raise + log.error("%s", e.code) + raise SystemExit(SETTINGS_EXIT) from None # (restarting won't help until the settings change) + for name in ("ecobot", "lib"): + logging.getLogger(name).setLevel(cfg.log_level) + host, port = cfg.irrigation_bind + folder = cfg.state_path.parent + async with contextlib.AsyncExitStack() as stack: + mcp_http.hold_folder(folder, LOCK, "irrigation-mcp", "python -m irrigation_mcp", stack) + tokens = cfg.auth_tokens or (mcp_http.generated_token(folder, log, "irrigation-mcp"),) + state = IrrigationState(cfg.irrigation_state_path, cfg.state_path) + device = Tuya(cfg) + stack.push_async_callback(safely, device.close) + watchdog = Watchdog(device, state) + if urlsplit(cfg.irrigation_ecobot_mcp_url).hostname in ("127.0.0.1", "localhost", "::1") and docker_private_network(): + log.warning("IRRIGATION_ECOBOT_MCP_URL is %s, but in a container on Docker's own network that is irrigation-mcp's container, " + "not ecobot-mcp's: set it to http://ecobot-mcp:8765/mcp, or leave it out of /etc/ecobot.env (docker/irrigation.env " + "sets it)", cfg.irrigation_ecobot_mcp_url) + weather = EcobotWeather(cfg.irrigation_ecobot_mcp_url, ecobot_token(cfg), cfg.tz) + stack.push_async_callback(weather.close) + alert_log = AlertLog(cfg.irrigation_alert_log_path, weather.tz) + stack.callback(alert_log.close) + server = IrrigationServer(device, watchdog, alert_log, version=version(), tz=weather.tz) + monitor = IrrigationMonitor(device, state, server.notify, weather.tz, cfg.irrigation_check_hour, weather.rain, weather.forecast) + + def zone(z): # the station's time zone, read (late, or another one): the check's time, the alerts' and the tools' times in it + if str(z) != str(monitor.tz): + log.info("The weather station's time zone is %s: irrigation-mcp runs in it from now on (it was %s)", z, monitor.tz) + monitor.tz = alert_log.tz = server.tz = z + weather.on_zone = zone + tasks = Tasks() + stack.push_async_callback(tasks.close) + tasks.start(every(watchdog.next_check, watchdog.check)) # (at once: a run left armed before a restart is closed without waiting) + tasks.start(weather.run()) + tasks.start(server.run()) + hosts = tuple(dict.fromkeys(("127.0.0.1", "localhost", socket.gethostname(), *cfg.irrigation_allowed_hosts))) + app = http_app(server, tokens=tokens, allowed_hosts=hosts, issuer_url=f"http://{f'[{host}]' if ':' in host else host}:{port}") + stop = asyncio.Event() + for sig in (signal.SIGINT, signal.SIGTERM): + asyncio.get_running_loop().add_signal_handler(sig, stop.set) + web = Uvicorn(mcp_http.server_config(app, host, port, SHUTDOWN_SECONDS)) + serving = asyncio.create_task(web.serve()) # (the tools answer while ecobot-mcp is waited for) + shown = host if ":" not in host else f"[{host}]" + log.info("MCP: http://%s:%d/mcp, %s; answering Host %s; ecobot-mcp at %s", shown, port, + f"{len(tokens)} token(s) from AUTH_TOKENS" if cfg.auth_tokens else f"the token in {auth_token.path(folder)}", + ", ".join(hosts), cfg.irrigation_ecobot_mcp_url) + waiting = asyncio.create_task(stop.wait()) + # the daily check waits a while for the station's time zone (its hour is the station's); the watchdog and the tools don't + listening = asyncio.create_task(weather.listening.wait()) + await asyncio.wait({listening, serving, waiting}, timeout=STARTUP_WAIT, return_when=asyncio.FIRST_COMPLETED) + listening.cancel() + if not serving.done() and not stop.is_set(): + if not weather.listening.is_set(): + log.warning("ecobot-mcp at %s isn't reachable yet: the daily check goes without the rain measured and on the forecast " + "last read until it is (the time zone is TZ's, %s, until its station is read)", cfg.irrigation_ecobot_mcp_url, + weather.tz) + tasks.start(monitor.run()) + log.info("Irrigation: the daily check at %02d:00 (%s), the watchdog every %ds%s", cfg.irrigation_check_hour, monitor.tz, + CHECK_SECONDS, f"; a run is watched until {server._time(watchdog.off_at)}" if watchdog.off_at else "") + await asyncio.wait({serving, waiting}, return_when=asyncio.FIRST_COMPLETED) + server.listen.close() # (the listen streams end gracefully: their clients know to listen again) + web.should_exit = True + await serving + waiting.cancel() + if not stop.is_set(): + raise SystemExit(f"The MCP server stopped: is {host}:{port} free?") + + +def run(): + _format = LogFormat("%(levelname)s %(message)s", priority=on_journal()) + logging.basicConfig(level=logging.INFO, handlers=stream_handlers(_format)) + logging.getLogger("httpx").setLevel(logging.WARNING) + logging.getLogger("httpx2").setLevel(logging.WARNING) + with contextlib.suppress(KeyboardInterrupt): + asyncio.run(main()) + + +if __name__ == "__main__": + run() diff --git a/lib/admins.py b/lib/admins.py index 207d5252..ec4fe3e7 100644 --- a/lib/admins.py +++ b/lib/admins.py @@ -1,8 +1,8 @@ -"""Who may talk to the bot when ADMIN_ONLY is on: the admins of the groups it is in, and the ids listed in ADMIN_CHAT_IDS. +"""Who may talk to the bot when BOT_ADMIN_ONLY is on: the admins of the groups it is in, and the ids listed in BOT_ADMIN_CHAT_IDS. A "known admin" is anyone Telegram lists as an administrator or creator of a group the bot knows (a group becomes known when the bot is -added to it or someone speaks in it) or of a group named by a negative id in ADMIN_CHAT_IDS. The lists are asked for once and kept for -ten minutes. ADMIN_CHAT_IDS is added to that, never instead of it: a positive id is a user (it bootstraps a bot that is in no group yet), +added to it or someone speaks in it) or of a group named by a negative id in BOT_ADMIN_CHAT_IDS. The lists are asked for once and kept for +ten minutes. BOT_ADMIN_CHAT_IDS is added to that, never instead of it: a positive id is a user (it bootstraps a bot that is in no group yet), a negative id is a group, whose own admins are then looked up and whose anonymous admins are let in: a message an admin sends "as the group" carries the group as its `sender_chat` and no real user, so it is allowed only when that group's id is listed. The groups' lists are asked for together, and messages that arrive together while a list is being fetched wait for that one lookup. @@ -26,7 +26,7 @@ def __init__(self, state, extra_ids=(), ttl: float = TTL_SECONDS, clock=time.mon self._looking: dict[int, asyncio.Lock] = {} # group -> held while its list is fetched def groups(self) -> list[int]: - """The groups whose admins count: the ones the bot is in (not one that removed it), and the ones ADMIN_CHAT_IDS names.""" + """The groups whose admins count: the ones the bot is in (not one that removed it), and the ones BOT_ADMIN_CHAT_IDS names.""" known = {c for c in self.state.present() if c < 0} return sorted(known | {i for i in self.extra if i < 0}) diff --git a/lib/airgradient/dashboard.py b/lib/airgradient/dashboard.py new file mode 100644 index 00000000..1a251d96 --- /dev/null +++ b/lib/airgradient/dashboard.py @@ -0,0 +1,86 @@ +"""The air sensor's gauges (AIR_GAUGES): what each shows and its scale, on US standards, drawn after the weather station's (lib/ecowitt/ +dashboard.py GAUGES) by lib/gauge_sheet.py from the service's `current` with context. + +Every air gauge is a dial whose coloured bands are its categories, each band an equal share of the dial (as AirNow's AQI dial draws +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 + 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); + - PM10 (µg/m³): the EPA's breakpoints, 0-54, 55-154, 155-254, 255-354, 355-424, 425+ (to 604, AQI 500); + - PM1 (µg/m³): no standard sets bands for it (not the US, Australia or the WHO); it is drawn on PM2.5's, as many air-quality apps do: + PM1 is part of PM2.5, so its reading is never above PM2.5's and the scale is a fair, if lenient, guide, not an official rating; + - CO2 (ppm): there is no EPA standard for it; the bands are the usual US indoor guidance, from ASHRAE's (ventilation keeps a room + within about 700 ppm of outdoors): under 800 good, 800-1000 fair, 1000-1500 poor, 1500-2000 bad, 2000+ very bad, on a 400-2500 dial + (400: outdoor air); + - VOC index and NOx index: Sensirion's indices the AirGradient reports (1-500, learnt from this sensor's own air): VOC's 100 is its + average, so under 100 low, 100-150 average, 150-250 elevated, 250-400 high, 400-500 very high (green, a paler green, then + the EPA's yellow, orange and red); NOx's baseline is 1, so 1-20 low (as the service rates it good), 20-150 elevated, 150-300 + 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). + +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). +""" + +from dataclasses import dataclass + +from .metrics import PM25_AQI + +# The EPA's colours for the AQI's categories, good to hazardous, and their names +EPA = ("#00E400", "#FFFF00", "#FF7E00", "#FF0000", "#8F3F97", "#7E0023") +EPA_NAMES = ("Good", "Moderate", "Unhealthy for Sensitive Groups", "Unhealthy", "Very Unhealthy", "Hazardous") +VOC_COLOURS = ("#00E400", "#9BE564", "#FFFF00", "#FF7E00", "#FF0000") # (its average, 100-150, a paler green: the usual air) + + +@dataclass(frozen=True) +class AirGauge: + title: str + unit: str + column: str # the air sensor's reading (air.<column>, lib/service/names.py) + bounds: tuple[float, ...] # the bands' edges, low to high: one more than the colours + colours: tuple[str, ...] + names: tuple[str, ...] # each band's name, shown under the reading + 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 + + @property + def reading(self) -> str: + return f"air.{self.column}" + + @property + def low(self) -> float: + return self.bounds[0] + + @property + def high(self) -> float: + return self.bounds[-1] + + def band(self, value: float | None) -> str | None: + """The name of the band a reading is in (None for none).""" + if value is None: + return None + return next((name for edge, name in zip(self.bounds[1:], self.names) if value < edge + self.step), self.names[-1]) + + +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("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), + AirGauge("NOx index", "", "nox_index", (1, 20, 150, 300, 500), EPA[:4], ("Low", "Elevated", "High", "Very high"), 1), +) + + +def air_gauges_of(titles=None) -> list[AirGauge]: + """The air gauges with these titles, in the dashboard's order (all of them when None).""" + return [g for g in AIR_GAUGES if titles is None or g.title in titles] + + +__all__ = ["AIR_GAUGES", "AirGauge", "EPA", "EPA_NAMES", "air_gauges_of"] diff --git a/lib/airgradient/days.py b/lib/airgradient/days.py index fa8469b0..194a3382 100644 --- a/lib/airgradient/days.py +++ b/lib/airgradient/days.py @@ -1,55 +1,9 @@ -"""air_days: find, rank, count and total days by the air-quality sensor's readings, from the day rows alone (it never asks -AirGradient; storage.days works each day out as its readings are written, the sensor's glitches taken out). The same fields as a day's -highest (_max), lowest (_min) or mean (_avg) of each metric, e.g. pm2_5_max > 25 for the days particles passed 25 µg/m³. The counting, -ranking, grouping and bar charts are shared with weather_days (lib/daytable.py).""" +"""The air-quality sensor's day fields, for the service's `days` (lib/service/days.py, which reads the day rows itself: storage.days works +each day out as its readings are written, the sensor's glitches taken out): a day's highest (_max), lowest (_min) or mean (_avg) of each +metric, e.g. pm2_5_max > 25 for the days particles passed 25 µg/m³.""" -import logging -from datetime import datetime, tzinfo - -from ..daytable import analyse, grouped_as_asked, parameters, prepare -from ..timeutil import now_local -from ..tools import json_result from .metrics import ALL_METRICS, CHART_UNITS -log = logging.getLogger(__name__) - SUFFIX_KIND = ("max", "min", "avg") FIELDS = {f"{m}_{kind}": CHART_UNITS[m] for m in ALL_METRICS for kind in SUFFIX_KIND} ALWAYS_SHOWN = ("pm2_5_max",) # every listed day shows it; days rank by it when nothing else is named - -PARAMETERS = parameters(list(FIELDS), "pm2_5_max > 25 and co2_max > 800") -DESCRIPTION = ("Find, rank or count DAYS by the air-quality sensor's readings, from the stored history (any period, fast): for " - "questions like \"how many days was PM2.5 over 25\", \"the worst air day each month\", \"days CO2 passed 800\". " - "Fields: for each of pm1, pm2_5, pm10, co2, voc_index, nox_index a day's highest (_max), lowest (_min) or mean (_avg), " - "e.g. pm2_5_max >= 25 (µg/m³; a rating's limits are 9 and 55.4 for PM2.5). For \"how many\" use count_only; group_by " - "month or year breaks it down and draws a bar chart. For a highest, lowest, average or total per month or year use stat " - "and of (\"worst PM2.5 each month\": stat max, of pm2_5_max; \"average CO2 per year\": stat avg, of co2_avg). Returns the " - "total of matching days and the top ones.") - - -async def find_air_days(store, tz: tzinfo, args: dict, now: datetime, turn=None) -> dict: - """The answer, from one read of the day rows (readings.AirReadings.day_figures).""" - asked = prepare(args, FIELDS, ALWAYS_SHOWN, now.date()) - if isinstance(asked, str): - return {"error": asked} - days, shown = asked.days, asked.shown - figures = await store.day_figures(asked.first, asked.last, shown) - values, counts = figures.values, figures.counts - checked = [d for d in days if any(d in values[n] for n in shown)] - got = analyse(values, asked, checked, tz, turn) - out = got.out - hourly = [d for d in checked if d in figures.hourly] - if hourly and any(n.endswith(("_max", "_min")) for n in shown): - out["note_hourly"] = (f"{len(hourly)} of these days only exist as hourly averages, so their highs and lows are hourly " - "averages and a short spike is smoothed. Say so briefly if it matters.") - missing = sum(1 for d in days if not counts.get(d)) - if missing: - out["note_missing"] = f"{missing} day(s) in this period have no stored readings (not downloaded yet, or the sensor was off) and are not counted." - if not checked: - out["note"] = "No stored readings for this period yet (the bot may still be downloading history)." - log.info("Air days %s to %s: %d checked, %d match", asked.first, asked.last, len(checked), len(got.matches)) - return out - - -async def air_days_tool(store, tz: tzinfo, args: dict, turn=None) -> str: - return json_result(await find_air_days(store, tz, grouped_as_asked(args, turn), now_local(tz), turn)) diff --git a/lib/airgradient/local.py b/lib/airgradient/local.py index bc1f4720..72870cad 100644 --- a/lib/airgradient/local.py +++ b/lib/airgradient/local.py @@ -1,4 +1,4 @@ -"""The sensor's own web server, for the live reading: GET http://<device>/measures/current on the local network (AIRGRADIENT_LOCAL_URL, +"""The sensor's own web server, for the live reading: GET http://<device>/measures/current on the local network (MCP_AIRGRADIENT_LOCAL_URL, e.g. http://airgradient_d83bda1c1e08.local). Nothing is asked of the cloud for it, and it is as fresh as the device's last measurement. The device only knows "now", so history, charts and the archive still come from the cloud. @@ -117,7 +117,7 @@ async def read(self) -> dict | None: self.address, self.retry_at = None, self.clock() + RETRY_SECONDS if self.working is not False: log.warning("AirGradient: (%s) did not answer (%s: %s); %strying again in %d min%s", self.describe(), type(e).__name__, e, - "using the cloud, " if self.cloud else "", RETRY_SECONDS // 60, local_name_hint(self.host, "AIRGRADIENT_LOCAL_URL")) + "using the cloud, " if self.cloud else "", RETRY_SECONDS // 60, local_name_hint(self.host, "MCP_AIRGRADIENT_LOCAL_URL")) self.working = False return None self.working = True diff --git a/lib/airgradient/metrics.py b/lib/airgradient/metrics.py index cbd0dc5b..d576f1ce 100644 --- a/lib/airgradient/metrics.py +++ b/lib/airgradient/metrics.py @@ -1,5 +1,6 @@ """What AirGradient measures, how it is rated, and how a raw reading is normalised.""" +import math from datetime import datetime from ..series import AIR, AIR_EXTRA @@ -38,7 +39,7 @@ SPIKE_RATIO = 2.5 # a particle reading that is this many times the readings either side of it ... SPIKE_RISE = 5.0 # ... and this far (µg/m³) above both, with nothing like it next to it, is a glitch of the sensor, not the air SPIKE_NEIGHBOUR = 900 # the readings either side must be within this many seconds -REQUIRE_CONSECUTIVE = 2 # ANTISPIKE_REQUIRE_CONSECUTIVE: readings in a row a rise needs to be the air (set at startup); 1 turns the rule off +REQUIRE_CONSECUTIVE = 2 # MCP_ANTISPIKE_REQUIRE_CONSECUTIVE: readings in a row a rise needs to be the air (set at startup); 1 turns the rule off def without_spikes(rows: list[dict], require: int | None = None) -> list[dict]: @@ -73,6 +74,17 @@ def without_spikes(rows: list[dict], require: int | None = None) -> list[dict]: (225.5, 325.4, 301, 500, "hazardous"), ] +# US EPA PM10 breakpoints (µg/m³, a 24-hour average truncated to a whole number): the same bands +PM10_AQI = [ + (0, 54, 0, 50, "good"), + (55, 154, 51, 100, "moderate"), + (155, 254, 101, 150, "unhealthy for sensitive groups"), + (255, 354, 151, 200, "unhealthy"), + (355, 424, 201, 300, "very unhealthy"), + (425, 604, 301, 500, "hazardous"), +] +AQI_FROM = {"pm2_5": "PM2.5", "pm10": "PM10"} # the particles the US AQI is worked out from, as each is named + ZONES = ("good", "poor", "very poor") _ZONE_EMOJI = ("\U0001f7e2", "\U0001f7e1", "\U0001f534") @@ -91,14 +103,35 @@ def rating(name: str, value: float) -> str | None: return f"{_ZONE_EMOJI[z]} {ZONES[z]}" -def pm25_aqi(conc: float) -> tuple[int, str]: - c = round(conc, 1) - for lo, hi, a_lo, a_hi, band in PM25_AQI: +def _aqi(table: list, c: float) -> tuple[int, str]: + for lo, hi, a_lo, a_hi, band in table: if c <= hi: return round(a_lo + (a_hi - a_lo) * (max(c, lo) - lo) / (hi - lo)), band return 500, "hazardous" +def pm25_aqi(conc: float) -> tuple[int, str]: + """PM2.5's US AQI and band (its sub-index).""" + return _aqi(PM25_AQI, round(conc, 1)) + + +def pm10_aqi(conc: float) -> tuple[int, str]: + """PM10's US AQI and band (its sub-index).""" + return _aqi(PM10_AQI, math.floor(conc)) + + +def particle_aqi(name: str, conc: float) -> tuple[int, str]: + """The US AQI and band of "pm2_5" or "pm10" (AQI_FROM).""" + return (pm25_aqi if name == "pm2_5" else pm10_aqi)(conc) + + +def us_aqi(pm2_5: float | None, pm10: float | None) -> tuple[int, str, str] | None: + """The US AQI as AirNow gives it: the higher of PM2.5's and PM10's (PM2.5's on a tie), its band, and which it is from ("PM2.5", + "PM10"). None with neither.""" + found = [(*particle_aqi(name, v), AQI_FROM[name]) for name, v in (("pm2_5", pm2_5), ("pm10", pm10)) if v is not None] + return max(found, key=lambda f: f[0]) if found else None # (max keeps the first of equals: PM2.5) + + def value_of(row: dict, name: str) -> float | None: """One metric from a raw reading (corrected value first), or None.""" for field in STORED[name][0]: diff --git a/lib/airgradient/source.py b/lib/airgradient/source.py index 6c355a1a..16470fa8 100644 --- a/lib/airgradient/source.py +++ b/lib/airgradient/source.py @@ -2,7 +2,7 @@ start() checks the monitor, tools are what the model can call, warm()/poke() keep recent readings ready, backfill() caches the monitor's whole history, current() feeds the alert monitor. -Its readings come from each of its sources that is set (AIRGRADIENT_SOURCE; docs/storage-plan.md 3.12), each filling only what the ones +Its readings come from each of its sources that is set (MCP_AIRGRADIENT_SOURCE; docs/storage-plan.md 3.12), each filling only what the ones before it lack: the monitor's own server (local.py: read every minute, each 5 minutes' readings averaged into a row with their lowest and highest as its band, and each reading kept as a minute), Home Assistant (homeassistant.py: its states of the monitor sampled the same way while the monitor does not answer the bot, and its history read back for the times the bot did not read it at all), and AirGradient's @@ -16,11 +16,10 @@ Finished days are kept in the bot's file (readings.py, lib/storage), so questions are answered without asking AirGradient unless a day is missing. Reports AirGradient's corrected (calibrated) values -where available, plus a US EPA AQI and band for PM2.5. +where available, plus a US EPA AQI and band for PM2.5 and for PM10 (the US AQI is the higher). """ import asyncio -import copy import statistics import logging import time @@ -30,24 +29,22 @@ import httpx -from .. import intent from ..captions import CHART_HINT, wants_chart from ..config import Config from ..sources import Source from ..ecowitt.homeassistant import HomeAssistant from ..ecowitt.live import BUCKET from ..ecowitt.query import KEEP_HOURS, MINUTE_HOURS -from ..lines import RANGE_KEEP_DAYS, Plotted, Sample, build_line +from ..lines import RANGE_KEEP_DAYS, Plotted, Sample, build_line, readings_mean from ..panels import panel_for -from ..specs import AIR_SOURCE, Chart, Line +from ..specs import Chart, Line from ..storage import Storage from ..storage.catalogue import BOT, CLOUD, HOME_ASSISTANT from ..timeutil import day_bounds, day_text, local_date, local_epoch, parse_local, to_local, when -from ..tools import Tool, Turn, json_result +from ..tools import Turn from ..warm import Warmer -from .days import DESCRIPTION as DAYS_DESCRIPTION, PARAMETERS as DAYS_PARAMETERS, air_days_tool from . import metrics -from .metrics import AIR_PANELS, ALL_METRICS, EXTRA, EXTRA_LABELS, EXTRA_UNITS, MARK_LOW, LABELS, METRICS, STORED, normalise, pm25_aqi, rating, value_of, without_spikes +from .metrics import AIR_PANELS, ALL_METRICS, EXTRA, EXTRA_LABELS, EXTRA_UNITS, MARK_LOW, LABELS, METRICS, STORED, normalise, AQI_FROM, particle_aqi, rating, value_of, without_spikes from .homeassistant import (ANCHORS, MIN_COMPARED, checked, entity_ids, find_prefix, live as ha_live, minutes as ha_minutes, ranges as ha_ranges, same_reading, verdicts) from .local import LocalSensor @@ -78,36 +75,8 @@ BACKFILL_FAIL_STOP = 3 # this many failed requests in a row: give up until the next start BACKFILL_MAX_DAYS = 1460 -PARAMETERS = { - "type": "object", - "properties": { - "chart": {"type": "boolean", "description": "Set true to send a chart (graph) with the answer. Without dates, " - "it covers the last 24 hours."}, - "metrics": {"type": "array", "items": {"type": "string", "enum": list(LABELS)}, - "description": "Which metrics to chart (several are drawn as panels in one image; " - "for 'all', list all six). Default: the reading the person named, else pm2_5."}, - "start_date": {"type": "string", "description": "Start of a past period, 'YYYY-MM-DD HH:MM:SS' local time. " - "Omit (with end_date) for the current reading."}, - "end_date": {"type": "string", "description": "End of the past period, 'YYYY-MM-DD HH:MM:SS' local time."}, - }, -} -DESCRIPTION = ("Air quality from the owner's AirGradient outdoor sensor: PM2.5 (with US AQI and band), PM10, " - "PM1, CO2, VOC and NOx indexes, each with a traffic-light rating. No dates: the current reading. " - "With start_date/end_date (up to about a year): lowest, highest and average of each, with when they " - "happened. chart=true sends a graph.") - - -def asked() -> tuple[str, dict]: - """air_quality as a question about the sensor's own temperature or humidity is offered it: those two as metrics too.""" - parameters = copy.deepcopy(PARAMETERS) - parameters["properties"]["metrics"]["items"]["enum"] = [*LABELS, *EXTRA] - parameters["properties"]["metrics"]["description"] += " air_temperature and air_humidity are the sensor's own temperature and humidity." - return (DESCRIPTION + " With metrics air_temperature / air_humidity it gives the sensor's own temperature (°C) and humidity (%), only " - "when the question names the AirGradient's.", parameters) - - class Latest(NamedTuple): - """The latest reading as the air_quality tool gives it, and what the particulates alert also needs.""" + """The latest reading (as the service's current reads it), and what the particulates alert also needs.""" reading: dict # the sensor, the time, and each metric's value, unit and rating at: datetime | None # when it was taken (UTC) sustained: dict[str, float] # each metric's lowest over the last REQUIRE_CONSECUTIVE readings: what the air has been that long @@ -127,7 +96,7 @@ def __init__(self, cfg: Config, transport=None, ha: HomeAssistant | None = None, owned: the file is this source's to close (so when it opened it, or no station has it).""" self.loc, self.tz = cfg.airgradient_location or "local", cfg.tz # (the stored readings are kept under this) self.token = cfg.airgradient_token - self.cloud = cfg.airgradient_cloud # without an account (or with AIRGRADIENT_SOURCE saying not) the cloud is never asked + 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.local = LocalSensor(cfg.airgradient_local_url, cloud=self.cloud) if cfg.airgradient_local else None # the monitor's own server @@ -152,8 +121,6 @@ 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 - self.tools = [Tool("air_quality", DESCRIPTION, PARAMETERS, self.handle, asked=asked, source=AIR_SOURCE), - Tool("air_days", DAYS_DESCRIPTION, DAYS_PARAMETERS, self._days, source=AIR_SOURCE)] async def start(self): try: @@ -306,13 +273,6 @@ def _judge(self, src: int, rows: list[dict], others: list[dict]) -> list[dict]: SOURCE_NAMES[src], label, v[1], v[0], FIX.get(name, "check the correction each applies")) return [row for r in rows if len(row := self._allowed(r, src)) > 1] - def describe(self) -> str: - return f"AirGradient outdoor air-quality sensor (location {self.loc}) (people say \"ag\", \"airgradient\", \"air gradient\", \"aq\" or \"air quality\")" - - def wants(self, text: str) -> bool: - """Should a question start refreshing this source? Only air-quality questions.""" - return intent.mentions_air(text) - async def _get(self, kind: str, **params) -> dict | list: """The reply: an object for "current", a list of readings for "past". A period with no readings is an empty list (AirGradient says so with a 404); a reply of any other shape raises, so it is never stored as days without readings.""" @@ -342,7 +302,7 @@ async def _current_row(self, refresh: bool = False) -> dict: return self._current[0] async def _fetch_current(self) -> dict: - """The live reading: from the monitor's own server when AIRGRADIENT_LOCAL_URL answers, else Home Assistant's states of it (each + """The live reading: from the monitor's own server when MCP_AIRGRADIENT_LOCAL_URL answers, else Home Assistant's states of it (each with the cloud's name for the sensor, last heard), else the cloud.""" row, _ = await self._sample() if row is not None: @@ -488,6 +448,20 @@ async def _fill(self, day: date, start: int, end: int): others = await self.store.load(lo, hi, srcs=(BOT, HOME_ASSISTANT)) await self.store.merge(self._judge(CLOUD, got, others), self._final(day)) + async def _held_day_rows(self, day: date) -> list[dict]: + """A day's readings as far as they are kept, whatever their age, nothing fetched: the stored ones (with the bucket being + averaged) when the bot keeps the readings itself or the day is finished, else the cloud's last fetch of it ([] when none).""" + if self._final(day) or self._sampled or (not self.cloud and (self.local or self._ha_ids)): + return self._with_bucket(day, await self.store.load_day(day)) + cached = self._recent.get(day) + return cached[0] if cached else [] + + def _with_bucket(self, day: date, rows: list[dict]) -> list[dict]: + """A day's stored readings with the bucket being averaged as the last one, when it is that day's and not stored yet.""" + if self._bucket and self._bucket[1] and local_date(self._bucket[0], self.tz) == day and self._bucket[0] not in {r["ts"] for r in rows}: + rows = [*rows, self._average(*self._bucket)] + return rows + async def _recorded_day_rows(self, day: date) -> list[dict]: """An unfinished day (today, or one that has just ended) while the monitor or Home Assistant answers: the stored readings, the bucket being averaged as the last one, and the cloud asked, at most every GAP_RETRY_SECONDS, for the span of the buckets that are @@ -500,9 +474,7 @@ async def _recorded_day_rows(self, day: date) -> list[dict]: rows = await self.store.load_day(day) except Exception as e: # the stored readings still stand log.warning("AirGradient: couldn't fill the gaps of %s from the cloud: %s", day, e) - if self._bucket and self._bucket[1] and local_date(self._bucket[0], self.tz) == day and self._bucket[0] not in {r["ts"] for r in rows}: - rows = [*rows, self._average(*self._bucket)] - return rows + return self._with_bucket(day, rows) async def _complete_day(self, day: date) -> Held: """A finished day the bot holds readings of from the monitor or Home Assistant: the cloud is asked for the whole day once (one @@ -576,29 +548,12 @@ async def backfill(self, pace: float | None = None, empty_stop: int | None = Non return fetched, failed, total return fetched, failed, total - # ---------- the tool ---------- - async def handle(self, args: dict, turn: Turn | None = None) -> str: - """The air_quality tool: current reading, or a summary of a past period.""" - turn = turn or Turn() - try: - turn.air_extra_used = turn.air_extra_used or any(m in EXTRA for m in args.get("metrics") or []) - chart = wants_chart(args, turn) - if args.get("start_date") or args.get("end_date") or chart: - return json_result(await self.history(args.get("start_date"), args.get("end_date"), - chart=chart, metrics=args.get("metrics"), turn=turn)) - return json_result(await self.current([m for m in args.get("metrics") or [] if m in EXTRA])) - except Exception as e: - log.warning("AirGradient request failed: %s", e) - return f"Error: couldn't read the air-quality sensor ({e})" - - async def _days(self, args: dict, turn: Turn | None = None) -> str: - """The air_days tool: count, rank and total days from the stored readings.""" - return await air_days_tool(self.store, self.tz, args, turn) - - async def _previous_rows(self, ts: int, count: int) -> list[dict]: - """Up to `count` of today's cached readings just before `ts`, each within MAX_GAP_SECONDS of the next, oldest first.""" + async def _previous_rows(self, ts: int, count: int, held: bool = False) -> list[dict]: + """Up to `count` of today's cached readings just before `ts`, each within MAX_GAP_SECONDS of the next, oldest first (held: + only those already kept, nothing fetched).""" today = to_local(ts, self.tz).date() - earlier, got, after = [r for r in await self._day_rows(today) if r["ts"] < ts], [], ts + rows = await (self._held_day_rows(today) if held else self._day_rows(today)) + earlier, got, after = [r for r in rows if r["ts"] < ts], [], ts for r in reversed(earlier): if len(got) >= count or after - r["ts"] > MAX_GAP_SECONDS: break @@ -606,15 +561,21 @@ async def _previous_rows(self, ts: int, count: int) -> list[dict]: after = r["ts"] return got - async def latest(self, extras: list[str] = ()) -> Latest: - """The latest reading. A rating (and PM2.5's AQI band) is the level the last two readings both reached, so a passing + async def latest(self, extras: list[str] = (), held: 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.""" - row = await self._current_row() + 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).""" + if held: + if not self._current: + raise LookupError("no reading held") + row = self._current[0] + else: + row = await self._current_row() at = datetime.fromisoformat(row["timestamp"].replace("Z", "+00:00")) if row.get("timestamp") else None need = metrics.REQUIRE_CONSECUTIVE - 1 # the readings before the latest that `sustained` takes in try: - earlier = await self._previous_rows(int(at.timestamp()), max(need, 1)) if at else [] + earlier = await self._previous_rows(int(at.timestamp()), max(need, 1), held) if at else [] except Exception as e: # only the history failing: the latest reading still stands log.warning("AirGradient: today's readings unavailable (%s); rating the latest alone", e) earlier = [] @@ -630,8 +591,8 @@ async def latest(self, extras: list[str] = ()) -> Latest: reading[name] = {"value": v, "unit": unit, "rating": rating(name, rated)} if reading[name]["rating"] != rating(name, v): reading[name]["rating_note"] = "rated on the last two readings: the previous one was lower" - if name == "pm2_5": - aqi, band = pm25_aqi(rated) + if name in AQI_FROM: # (each particle's own US AQI: the US AQI is the higher, us_aqi) + aqi, band = particle_aqi(name, rated) reading[name].update(aqi_us=aqi, band=band) sustained[name] = min([v, *(r[name] for r in held if name in r)]) for name in extras: # the sensor's own temperature and humidity, only when asked for: no rating @@ -639,10 +600,6 @@ async def latest(self, extras: list[str] = ()) -> Latest: reading[name] = {"value": v, "unit": EXTRA_UNITS[name]} return Latest(reading, at, sustained) - async def current(self, extras: list[str] = ()) -> dict: - """The latest reading as the air_quality tool gives it (see latest); `extras`: the sensor's own temperature and humidity, if asked.""" - return (await self.latest(extras)).reading - async def rows(self, t0: datetime, t1: datetime) -> tuple[list[dict], int, list[date]]: """(readings in [t0, t1] (naive local times), days that only exist as hourly averages, older days still waiting for the backfill and left out). Finished days not yet stored are fetched first, up to MAX_INLINE_DAYS. A single-reading spike @@ -669,7 +626,8 @@ async def _with_spreads(self, rows: list[dict], day: date) -> list[dict]: return [{**r, "_range": {**ranges[r["ts"]], **r.get("_range", {})}} if r["ts"] in ranges else r for r in rows] async def history(self, start: str | None, end: str | None, chart: bool = False, - metrics: list[str] | None = None, turn: Turn | None = None) -> dict: + metrics: list[str] | None = None, turn: Turn | None = None, daily: bool = False) -> dict: + """daily: the chart draws each whole day's average, one point a day (an average was asked for: the summary tool's `average`).""" turn = turn or Turn() now = self.now() try: # a date the model sends, with or without an offset; a bad one is its mistake, not the sensor's @@ -691,9 +649,10 @@ async def history(self, start: str | None, end: str | None, chart: bool = False, "readings": len(rows)} units = {**{name: unit for name, (_, unit) in METRICS.items()}, **{name: EXTRA_UNITS[name] for name in metrics or [] if name in EXTRA}} # the sensor's own temperature and humidity, only when asked for + span = local_epoch(t0, self.tz), local_epoch(t1, self.tz) for name, unit in units.items(): if pts := [(r["ts"], r[name]) for r in rows if name in r]: - out[name] = self._entry(name, pts, unit) + out[name] = self._entry(name, pts, unit, span) if trimmed: out["note_period"] = f"Only the last {MAX_DAYS} days can be covered per question; this covers {out['period']}." if hourly: @@ -708,26 +667,28 @@ async def history(self, start: str | None, end: str | None, chart: bool = False, if chart and rows: asked = metrics or turn.air_named or ["pm2_5"] # unnamed: the reading the person is asking about chart_spec = self._chart([m for m in (*ALL_METRICS, *EXTRA) if m in asked] or ["pm2_5"], rows, out["period"], - (t0.date(), t1.date())) + (t0.date(), t1.date()), daily) if chart_spec: turn.charts.append(chart_spec) out["chart"] = CHART_HINT return out - def _entry(self, name: str, pts: list[tuple[int, float]], unit: str) -> dict: - """A metric's lowest, highest and average over these readings ((ts, value)), with when the extremes happened; a rated metric - (METRICS) with the ratings of its high and average, and PM2.5 with their AQI and band too.""" + def _entry(self, name: str, pts: list[tuple[int, float]], unit: str, span: tuple[int, int]) -> dict: + """A metric's lowest, highest and average over these readings ((ts, value)) of the period `span` (epochs), with when the extremes + happened; a rated metric (METRICS) with the ratings of its high and average, and PM2.5 and PM10 with their AQI and band too. The average is + by time, as the day rows take a day's (lines.readings_mean): an hourly reading of the older history counts for its hour, not as one + reading among a 5-minute hour's twelve.""" lo, hi = min(pts, key=lambda p: p[1]), max(pts, key=lambda p: p[1]) entry = {"unit": unit, "low": lo[1], "low_time": when(lo[0], self.tz), "high": hi[1], "high_time": when(hi[0], self.tz), - "average": round(statistics.fmean(v for _, v in pts), 1)} + "average": round(readings_mean(pts, *span, self.tz), 1)} if name in METRICS: entry["high_rating"], entry["average_rating"] = rating(name, hi[1]), rating(name, entry["average"]) - if name == "pm2_5": - entry["high_aqi_us"], entry["high_band"] = pm25_aqi(hi[1]) - entry["average_aqi_us"], entry["average_band"] = pm25_aqi(entry["average"]) + if name in AQI_FROM: + entry["high_aqi_us"], entry["high_band"] = particle_aqi(name, hi[1]) + entry["average_aqi_us"], entry["average_band"] = particle_aqi(name, entry["average"]) return entry - def _line(self, name: str, rows: list[dict]) -> tuple[Line, Plotted] | None: + def _line(self, name: str, rows: list[dict], daily: bool = False) -> tuple[Line, Plotted] | None: """One metric as a chart line, in its own units, and how it was drawn. The record high/low are the true readings. The readings themselves while they fit the point budget; more than that are bucketed (30 minutes ... a day): each bucket's mean, its range shaded.""" @@ -737,19 +698,21 @@ def _line(self, name: str, rows: list[dict]) -> tuple[Line, Plotted] | None: gap = max(60, round(statistics.median(b[0] - a[0] for a, b in pairwise(pts)))) spread = {r["ts"]: r["_range"][name] for r in rows if name in r and name in r.get("_range", {})} # what the bot saw in a bucket it recorded plotted = build_line([Sample(t, v, *(((min(spread[t][0], v), max(spread[t][1], v)) if t in spread else (None, None))), gap) - for t, v in pts], self.tz, pts[-1][0] - pts[0][0]) + for t, v in pts], self.tz, pts[-1][0] - pts[0][0], force_daily=daily, + until=self.now().date() if daily else None) if plotted is None: return None lo, hi = min(pts, key=lambda p: p[1]), max(pts, key=lambda p: p[1]) line = plotted.spec(LABELS.get(name) or EXTRA_LABELS[name], {"high": hi, **({"low": lo} if name in MARK_LOW else {})}, name) - line.on_line = True # the readings themselves marked where they peak, as the answer gives them, not the top of the shading (one sample inside a reading) + line.on_line = not daily # the readings themselves marked where they peak, as the answer gives them, not the top of the shading (one sample inside a reading); a day's average has the day's range as its band return line, plotted - def _chart(self, names: list[str], rows: list[dict], period: str, days: tuple[date, date] | None = None) -> Chart | None: + def _chart(self, names: list[str], rows: list[dict], period: str, days: tuple[date, date] | None = None, + daily: bool = False) -> Chart | None: """These metrics as one chart. One metric is drawn large, with its rating zones. Several go into panels on a shared time axis, grouped by AIR_PANELS (the particles together, the rest each alone). `period` is the subtitle's text for it, `days` its first and last day (for the caption).""" - drawn = {n: got for n in names if (got := self._line(n, rows))} + drawn = {n: got for n in names if (got := self._line(n, rows, daily))} if not drawn: return None if len(drawn) == 1: diff --git a/lib/alert_log.py b/lib/alert_log.py new file mode 100644 index 00000000..1fd52fe8 --- /dev/null +++ b/lib/alert_log.py @@ -0,0 +1,127 @@ +"""The alert log (docs/ecobot-mcp.md 3.6): every alert the service's rules decide, as an event a client reads and delivers. + +An event is {id, kind, time, expires, title, text, data, [link: {label, url}], [chart]}: + - id: monotonic (1, 2, ...), never reused, so a client resumes from the last one it handled; + - kind: the alert type (lib/alerts/menu.py TYPES: rain, gusts, uv, temps, particulates, pollen_and_asthma, forecast); + - time, expires: ISO local times with their offset; after `expires` the event is no longer news (a client back after a gap skips it); + - title: a few words; text: ready to send as it is; data: the figures behind it; + - link: the page that goes with it; chart: its chart as data (3.7), with the call that draws it again (`drawn_by`). + +Kept in its own SQLite file in DATA_DIR (alerts.sqlite), not the readings file: the log exists whatever sources are configured (the pollen +and forecast alerts need no readings file), it is written from the event loop in tiny rows while the readings file is written in bulk from +worker threads, and it can be looked at or removed on its own. Events older than KEEP_SECONDS are dropped when it opens; the ids carry on. +A new file starts its ids at 1 again, so each file has a random `identity` (kept in its meta table) beside the ids: a reader that kept +the last id it handled keeps the identity with it, and starts afresh when the file is another (lib/alerts/notify.AlertDelivery). + +A reader in the same process waits for new events with `wait(after)` (an asyncio notification on each append): the bot's delivery today, +the MCP listen of step 5.""" + +import asyncio +import json +import logging +import secrets +import sqlite3 +import threading +import time as clock +from datetime import datetime, tzinfo + +log = logging.getLogger(__name__) + +KEEP_SECONDS = 30 * 86400 + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS alerts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + kind TEXT NOT NULL, + time REAL NOT NULL, + expires REAL, + title TEXT NOT NULL, + text TEXT NOT NULL, + data TEXT, + link TEXT, + chart TEXT +); +CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); +""" + + +def _iso(ts: float | None, tz: tzinfo) -> str | None: + return None if ts is None else datetime.fromtimestamp(ts, tz).isoformat(timespec="seconds") + + +class AlertLog: + def __init__(self, path, tz: tzinfo, now=clock.time): + """path: the log's file (made when there is none). tz: the zone its times are written in. now: the epoch clock (tests).""" + self.tz, self.now = tz, now + self._lock = threading.Lock() + self.db = sqlite3.connect(path, check_same_thread=False, timeout=30) + self.db.execute("PRAGMA journal_mode=WAL") + self.db.executescript(SCHEMA) + self.db.execute("DELETE FROM alerts WHERE time < ?", (self.now() - KEEP_SECONDS,)) + self.db.execute("INSERT OR IGNORE INTO meta (key, value) VALUES ('identity', ?)", (secrets.token_hex(8),)) + self.db.commit() + self.identity: str = self.db.execute("SELECT value FROM meta WHERE key='identity'").fetchone()[0] + self._new = asyncio.Event() + + def close(self): + with self._lock: + self.db.close() + + def append(self, kind: str, text: str, title: str, data: dict | None = None, expires: float | None = None, + link: tuple[str, str] | None = None, chart: dict | None = None, time: float | None = None) -> dict: + """Record an alert (expires: an epoch, None for never; link: (label, url); chart: the chart's data with its drawn_by) and wake the + readers waiting. Returns the event.""" + at = self.now() if time is None else time + with self._lock: + cur = self.db.execute("INSERT INTO alerts (kind, time, expires, title, text, data, link, chart) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + (kind, at, expires, title, text, json.dumps(data or {}, ensure_ascii=False), + json.dumps({"label": link[0], "url": link[1]}, ensure_ascii=False) if link else None, + json.dumps(chart, ensure_ascii=False) if chart else None)) + self.db.commit() + event_id = cur.lastrowid + woken, self._new = self._new, asyncio.Event() + woken.set() + log.info("Alert %d (%s): %s", event_id, kind, title) + return self.get(event_id) + + def _event(self, row) -> dict: + event_id, kind, at, expires, title, text, data, link, chart = row + event = {"id": event_id, "kind": kind, "time": _iso(at, self.tz), "expires": _iso(expires, self.tz), "title": title, "text": text, + "data": json.loads(data) if data else {}} + if link: + event["link"] = json.loads(link) + if chart: + event["chart"] = json.loads(chart) + return event + + def get(self, event_id: int) -> dict | None: + """One event by its id (None when there is none, or it was dropped), expired or not.""" + with self._lock: + row = self.db.execute("SELECT * FROM alerts WHERE id=?", (event_id,)).fetchone() + return self._event(row) if row else None + + def since(self, after: int = 0, expired: bool = False) -> list[dict]: + """The events after the id `after`, oldest first; only those not yet expired unless `expired`.""" + query, args = "SELECT * FROM alerts WHERE id > ?", [after] + if not expired: + query += " AND (expires IS NULL OR expires > ?)" + args.append(self.now()) + with self._lock: + rows = self.db.execute(query + " ORDER BY id", args).fetchall() + return [self._event(row) for row in rows] + + def last_id(self) -> int: + """The newest event's id (0 when there has been none): what a reader starting now has already seen.""" + with self._lock: + row = self.db.execute("SELECT seq FROM sqlite_sequence WHERE name='alerts'").fetchone() + return row[0] if row else 0 + + async def wait(self, after: int, timeout: float | None = None) -> bool: + """Until there is an event after the id `after` (True), or `timeout` seconds have passed (False).""" + try: + async with asyncio.timeout(timeout): + while self.last_id() <= after: + await self._new.wait() + return True + except TimeoutError: + return False diff --git a/lib/alerts/forecast.py b/lib/alerts/forecast.py index 82287805..caeafd7c 100644 --- a/lib/alerts/forecast.py +++ b/lib/alerts/forecast.py @@ -1,58 +1,103 @@ -"""A forecast changed after it was sent: told to the chat that was sent it. - -When a chat has been shown a day's forecast (in the report or an answer) and a later refresh revises that day substantially, -that chat gets one message with the old and the new line for each changed day. Substantial is: - - rain flips: it was rainy (chance of at least 1 mm of 50% or more) and is now dry (30% or less), or the other way round (the - gap between 30 and 50 stops small wobbles flip-flopping); a day with only Open-Meteo's older "chance of rain" figure is - compared on that; - - the highest temperature differs by more than 2 degrees. -After the alert, the day as now forecast is the chat's new baseline, so the same revision never repeats, a further one does. -The forecast only refreshes from 6 am to 6 pm, so that is when this can fire. +"""The forecast revised: station-wide, for today and tomorrow (docs/ecobot-mcp.md 3.6). + +Each day, the first forecast fetched after 6 am is the baseline for today and tomorrow. Every later fetch is compared with it, day by +day, and a day that changed substantially is an alert, saying what changed: + - the chance of rain becomes likely (it was under 50% and is now 50% or over) or unlikely (it was 50% or over and is now 30% or + under); the chance of at least 1 mm, or, for a day with only Open-Meteo's older "chance of rain" figure on either side, that one. + The band between keeps a chance that hovers around 50% (the ensemble's, rounded to 5%, moving 45 / 50 / 45 between model runs) from + alerting likely, unlikely, likely on every refresh; + - the highest temperature moves by more than 2 degrees. +The forecast alerted on becomes that day's new baseline, so the same revision never repeats and a further one does. The forecast only +refreshes from 6 am to 6 pm, so that is when this can fire. Each alert is an event in the alert log (lib/alert_log.py), news until the +end of the day it is about. """ import logging +from datetime import date, datetime, timedelta -from ..forecast.source import day_label, describe_day -from .menu import kinds_of +from ..forecast.source import describe_day +from ..timeutil import at_hour +from .kinds import RAIN_FROM_PCT, kinds_of log = logging.getLogger(__name__) -RAIN_FROM_PCT = 50 -DRY_BELOW_PCT = 30 +DRY_BELOW_PCT = 30 # rain unlikely again (from likely: RAIN_FROM_PCT, lib/alerts/kinds.py) only at or under this one (from likely) TEMP_CHANGE_C = 2.0 +BASELINE_HOUR = 6 # the first forecast fetched from this hour (local) is the day's baseline +DAYS = 2 # today and tomorrow -def revised(old: dict, new: dict) -> bool: - """Is `new` a substantial revision of what was sent (`old`)?""" - key = "rain_1mm_pct" if old.get("rain_1mm_pct") is not None and new.get("rain_1mm_pct") is not None else "rain_chance_pct" - before, after = old.get(key), new.get(key) - if before is not None and after is not None and ( - (before >= RAIN_FROM_PCT and after <= DRY_BELOW_PCT) or (before <= DRY_BELOW_PCT and after >= RAIN_FROM_PCT)): - return True +def _chance_key(old: dict, new: dict) -> str: + return "rain_1mm_pct" if old.get("rain_1mm_pct") is not None and new.get("rain_1mm_pct") is not None else "rain_chance_pct" + + +def changes(old: dict, new: dict) -> list[str]: + """What changed substantially from `old` (the baseline) to `new`, in words ("the high is now 19°C (was 24°C)"); [] for nothing.""" + out = [] hot_before, hot_after = old.get("max_c"), new.get("max_c") - return hot_before is not None and hot_after is not None and abs(hot_after - hot_before) > TEMP_CHANGE_C + if hot_before is not None and hot_after is not None and abs(hot_after - hot_before) > TEMP_CHANGE_C: + out.append(f"the high is now {hot_after:.0f}°C (was {hot_before:.0f}°C)") + key = _chance_key(old, new) + before, after = old.get(key), new.get(key) + if before is not None and after is not None: + if before < RAIN_FROM_PCT <= after: + out.append(f"rain is now likely ({after}%, was {before}%)") + elif before >= RAIN_FROM_PCT and after <= DRY_BELOW_PCT: + out.append(f"rain is now unlikely ({after}%, was {before}%)") + return out + + +def revised(old: dict, new: dict) -> bool: + """Is `new` a substantial revision of the baseline `old`?""" + return bool(changes(old, new)) + + +def _stored(d: dict) -> dict: + return {**d, "date": d["date"].isoformat()} class ForecastMonitor: KINDS = kinds_of("Forecast") - def __init__(self, forecast, state, notify): - """notify: the Notifier (chats=[chat] sends to that one).""" - self.forecast, self.state, self.notify = forecast, state, notify + def __init__(self, forecast, state, alerts): + """state: the rules' store (AlertStore). alerts: the alert log.""" + self.forecast, self.state, self.alerts = forecast, state, alerts async def check(self): - """After each forecast refresh: tell each chat (with alerts on) about the days it was sent that have since changed.""" - today = self.forecast.now().date() - current = {d["date"]: d for d in self.forecast.days or []} - if not current: + """After each forecast refresh: today's baseline once a forecast fetched from 6 am is there; then an alert for each of today and + tomorrow that has changed substantially from its baseline, which it then replaces.""" + now = self.forecast.now() + today = now.date() + tz = getattr(self.forecast, "tz", None) + if now.hour < BASELINE_HOUR or not self.forecast.days: return - for chat_id in self.state.forecast_chats(): - if not self.state.subscribed(chat_id, "forecast"): - continue - changes = [(day, old, current[day]) for day, old in sorted(self.state.forecast_sent(chat_id).items()) - if day >= today and day in current and revised(old, current[day])] - if not changes: + fetched = getattr(self.forecast, "fetched_at", None) + if fetched is not None and tz is not None and fetched < at_hour(today, BASELINE_HOUR, tz): + return # (the forecast held is from before 6 am: not yet today's) + current = {d["date"]: d for d in self.forecast.days if 0 <= (d["date"] - today).days < DAYS} + m = self.state.monitor.setdefault("forecast", {}) + if m.get("day") != today.isoformat(): # the first forecast of the day: the baseline, nothing to compare + m.clear() + m.update(day=today.isoformat(), baseline={d.isoformat(): _stored(new) for d, new in current.items()}) + log.info("Forecast alert: today's baseline set (%s)", ", ".join(sorted(m["baseline"]))) + self.state.save() + return + baseline = m.setdefault("baseline", {}) + for day, new in sorted(current.items()): + old = baseline.get(day.isoformat()) + if old is None: + baseline[day.isoformat()] = _stored(new) continue - lines = [f"• {day_label(day, today)}: was {describe_day(old)}\n now {describe_day(new)}" for day, old, new in changes] - if await self.notify("\U0001f504 The forecast has changed since I sent it:\n" + "\n".join(lines), kind="forecast", chats=[chat_id]): - self.state.record_forecast(chat_id, [new for _, _, new in changes], today) + if said := changes(old, new): + self._emit(day, today, old, new, said, tz) + baseline[day.isoformat()] = _stored(new) + self.state.save() + + def _emit(self, day: date, today: date, old: dict, new: dict, said: list[str], tz): + label = "today" if day == today else "tomorrow" + text = f"\U0001f504 The forecast for {label} has changed: {' and '.join(said)}.\nNow: {describe_day(new)}" + key = _chance_key(old, new) + data = {"date": day.isoformat(), "was": {"max_c": old.get("max_c"), key: old.get(key), "summary": old.get("summary")}, + "now": {"max_c": new.get("max_c"), key: new.get(key), "summary": new.get("summary")}} + ends = at_hour(day + timedelta(days=1), 0, tz) if tz else datetime.combine(day + timedelta(days=1), datetime.min.time()).timestamp() + self.alerts.append("forecast", text, f"The forecast for {label} changed", data, expires=ends) diff --git a/lib/alerts/kinds.py b/lib/alerts/kinds.py new file mode 100644 index 00000000..fd121da9 --- /dev/null +++ b/lib/alerts/kinds.py @@ -0,0 +1,21 @@ +"""The alert types: their names and which source sends each. Shared by the service (its alert rules, `about`) and the bot (its alert +menus, lib/alerts/menu.py), with nothing of Telegram in it, so the service doesn't load the Telegram library.""" + +# kind -> (the name on its button, the source that sends it: a source's name, or Irrigation for the controller), in the order listed +TYPES = {"rain": ("rain", "Ecowitt"), "gusts": ("gusts", "Ecowitt"), "uv": ("UV", "Ecowitt"), "temps": ("temperature crossing", "Ecowitt"), + "particulates": ("particulates", "AirGradient"), "pollen_and_asthma": ("pollen & asthma", "Pollen"), + "forecast": ("forecast changes", "Forecast"), + "irrigation_battery": ("irrigation battery", "Irrigation"), "irrigation_pause": ("irrigation pause", "Irrigation")} +LABELS = {kind: label for kind, (label, _) in TYPES.items()} +RAIN_FROM_PCT = 50 # a day's rain is likely from this chance of at least 1 mm (the forecast alert's, and the irrigation check's) + + +def kinds_of(source: str) -> tuple[str, ...]: + """The alert types a source (by name) sends: a monitor's KINDS.""" + return tuple(kind for kind, (_, sender) in TYPES.items() if sender == source) + + +def available_kinds(sources, irrigation: bool = False) -> list[str]: + """The alert types the bot sends: those of its sources (by name), and the irrigation ones with a controller configured.""" + names = {*sources, *(["Irrigation"] if irrigation else [])} + return [kind for kind, (_, source) in TYPES.items() if source in names] diff --git a/lib/alerts/menu.py b/lib/alerts/menu.py index 37b7b129..bed3c1be 100644 --- a/lib/alerts/menu.py +++ b/lib/alerts/menu.py @@ -11,7 +11,9 @@ al:on|off:<kind>:alerts al:snd:<kind>:on|off a type's alerts, or its sound, on or off al:open:bell:<kind> al:close:<kind> the bell under an alert of that type al:on|off:<kind>:bell:<kind> al:snd:<kind>:on|off:<kind> its two toggles - al:refresh:<kind> the chart of an alert of that type, drawn again + al:refresh:<kind>[:<id>] the chart of an alert of that type, drawn again: the alert <id>'s + (in the alert log), its chart's drawn_by replayed; without one (an + alert sent before the log), the type's chart """ from itertools import batched @@ -19,13 +21,8 @@ from telegram import InlineKeyboardMarkup from ..buttons import button, opener, toggle_button +from .kinds import LABELS, TYPES, available_kinds, kinds_of # noqa: F401 (named here too: the menus are built from them) -# kind -> (the name on its button, the source that sends it: a source's name, or Irrigation for the controller), in the order listed -TYPES = {"rain": ("rain", "Ecowitt"), "gusts": ("gusts", "Ecowitt"), "uv": ("UV", "Ecowitt"), "temps": ("temperature crossing", "Ecowitt"), - "particulates": ("particulates", "AirGradient"), "pollen_and_asthma": ("pollen & asthma", "Pollen"), - "forecast": ("forecast changes", "Forecast"), - "irrigation_battery": ("irrigation battery", "Irrigation"), "irrigation_pause": ("irrigation pause", "Irrigation")} -LABELS = {kind: label for kind, (label, _) in TYPES.items()} ALL = "all" TITLE = "🔔 Alerts in this chat" PER_ROW = 2 @@ -33,27 +30,18 @@ MENUS = {ALERTS: "🔔 Alerts", SOUND: "🔊 Sound"} # the /alerts buttons -def kinds_of(source: str) -> tuple[str, ...]: - """The alert types a source (by name) sends: a monitor's KINDS.""" - return tuple(kind for kind, (_, sender) in TYPES.items() if sender == source) - - -def available_kinds(sources, irrigation: bool = False) -> list[str]: - """The alert types the bot sends: those of its sources (by name), and the irrigation ones with a controller configured.""" - names = {*sources, *(["Irrigation"] if irrigation else [])} - return [kind for kind, (_, source) in TYPES.items() if source in names] - - def _verb(on: bool) -> str: return "on" if on else "off" -def alert_keyboard(kind: str, muted: set[str], loud: set[str] | None, open: str | None = None, refresh: bool = False) -> InlineKeyboardMarkup: +def alert_keyboard(kind: str, muted: set[str], loud: set[str] | None, open: str | None = None, refresh: bool = False, + event: int | None = None) -> InlineKeyboardMarkup: """The buttons under an alert of type `kind`: one bell (🔔 ▸, ▾ once `open` is BELL) that opens up to two toggles, Alert (this type's alerts in this chat) and, only while that is on and in a private chat (`loud` is not None), Sound (whether they make a notification - sound). refresh (the alert carries a chart): 🔄 beside the bell, which draws the chart again.""" + sound). refresh (the alert carries a chart): 🔄 beside the bell, which draws the chart again (event: the alert's id in the log, whose + chart's drawn_by it replays).""" is_open = open == BELL - rows = [[opener("🔔", is_open, f"al:open:{BELL}:{kind}", f"al:close:{kind}"), *([button("🔄", f"al:refresh:{kind}")] if refresh else [])]] + rows = [[opener("🔔", is_open, f"al:open:{BELL}:{kind}", f"al:close:{kind}"), *([button("🔄", f"al:refresh:{kind}" + (f":{event}" if event is not None else ""))] if refresh else [])]] if is_open: on = kind not in muted rows.append([toggle_button("Alert", on, lambda turn_on: f"al:{_verb(turn_on)}:{kind}:{BELL}:{kind}")]) diff --git a/lib/alerts/notify.py b/lib/alerts/notify.py index 2e9c2b7c..95dafeb4 100644 --- a/lib/alerts/notify.py +++ b/lib/alerts/notify.py @@ -2,25 +2,29 @@ Alerts go to every chat the bot knows about (Telegram can't list a bot's chats, so they are remembered as messages arrive) unless it unsubscribed (per alert type, with the buttons under each alert or /alerts). A chat that -blocked or removed the bot is marked gone: it gets nothing, and has its settings back when it next writes. Chats and -monitor state live in a small JSON file, so restarts neither forget chats nor repeat alerts. Alerts are sent silently, with the -settings buttons and, when there is one, a small italic footer with a link label. +blocked or removed the bot is marked gone: it gets nothing, and has its settings back when it next writes. Chats, their +settings and the last alert delivered live in a small JSON file (bot_state.json), so restarts neither forget chats nor repeat alerts. +Alerts are sent silently, with the settings buttons and, when there is one, a small italic footer with a link label. + +The alerts themselves are the servers': ecobot-mcp's rules append them to its alert log (lib/alert_log.py, ecobot://alerts), and +irrigation-mcp's daily check to its own (irrigation://alerts); an AlertDelivery for each sends every new one to the chats subscribed to +its kind, keeping the last id it handled (ecobot-mcp's in AlertState.read, irrigation-mcp's in a ReadMark of its own). """ import asyncio -import json import logging -import os import time from collections.abc import Awaitable, Callable, Collection -from datetime import date, timedelta +from datetime import datetime, timedelta from telegram.error import BadRequest, ChatMigrated, Forbidden, NetworkError, RetryAfter, TelegramError, TimedOut from ..entities import with_link from ..logs import QUOTES from .menu import ALL, LABELS, alert_keyboard -from .pictures import CHARTS, AlertCharts, Picture +from .pictures import CHARTS, AlertCharts, Picture, picture_of +from .store import load, write +from ..weather import value log = logging.getLogger(__name__) @@ -28,19 +32,12 @@ FLOOD_WAIT_MAX = 60 # Telegram's flood limit asks to wait: a longer wait is not waited out (that chat misses the alert) -def _load(path) -> dict: - """The saved state, {} when there is none. A file that can't be read is moved aside, as the next save would replace it, - so its chats and settings can still be recovered by hand.""" +def _epoch(iso: str | None) -> float: + """An event's time (ISO, with its offset) as an epoch; 0 when it has none.""" try: - with open(path) as f: - return json.load(f) - except FileNotFoundError: - return {} - except (OSError, ValueError) as e: - aside = f"{path}.damaged-{time.strftime('%Y%m%d-%H%M%S')}" - os.replace(path, aside) - log.error("Couldn't read %s (%s): moved it to %s and starting with no known chats", path, e, aside) - return {} + return datetime.fromisoformat(iso).timestamp() if iso else 0.0 + except ValueError: + return 0.0 def _flood_wait(e: RetryAfter) -> float: @@ -50,23 +47,30 @@ def _flood_wait(e: RetryAfter) -> float: class AlertState: - """Known chats (with alerts on/off) and monitor state, saved to a JSON file.""" + """Known chats (with alerts on/off) and the last alert delivered of each server's log, saved to a JSON file (bot_state.json). The + alert rules keep theirs apart (lib/alerts/store.py: alert_state.json), and irrigation-mcp its own (irrigation_state.json).""" def __init__(self, path): self.path = path - data = _load(path) + data = load(path) or {} self.chats: dict[int, dict] = {int(k): v for k, v in data.get("chats", {}).items()} - self.monitor: dict = data.get("monitor", {}) + self.monitor: dict = data.get("monitor", {}) # what the bot kept when it ran the irrigation controller itself: kept as it + # was, for irrigation-mcp's first start, which copies it (lib/irrigation/state.py) self.charts: dict[str, str] = data.get("charts", {}) # the question behind each chart sent, for its period buttons + self.read: int | None = data.get("alerts_read") # the id of the last alert in the log the bot handled (AlertDelivery) + self.read_log: str | None = data.get("alerts_log") # ... and that log's identity (AlertLog.identity): ids start again in a new one + self.zone: str | None = data.get("station_zone") # the remote service's station's time zone, last read (ecobot.py: a start + # while the service can't be reached runs in it, not in TZ's) + marks = data.get("alerts_read_by") + self.marks: dict[str, dict] = marks if isinstance(marks, dict) else {} # another server's log (irrigation-mcp's): ReadMark def save(self): """Written in full to a new file that then replaces the old one, on disk first, so a crash leaves one or the other whole.""" - tmp = f"{self.path}.tmp" - with open(tmp, "w") as f: - json.dump({"chats": {str(k): v for k, v in self.chats.items()}, "monitor": self.monitor, "charts": self.charts}, f, indent=1) - f.flush() - os.fsync(f.fileno()) - os.replace(tmp, self.path) + write(self.path, {"chats": {str(k): v for k, v in self.chats.items()}, "monitor": self.monitor, "charts": self.charts, + **({"alerts_read": self.read} if self.read is not None else {}), + **({"alerts_log": self.read_log} if self.read_log is not None else {}), + **({"station_zone": self.zone} if self.zone is not None else {}), + **({"alerts_read_by": self.marks} if self.marks else {})}) def add_chat(self, chat_id: int, title: str): """A message from this chat (or the bot added to it): known from now on, and back if it was gone.""" @@ -99,13 +103,10 @@ def set_alerts(self, chat_id: int, on: bool): self.set_kind(chat_id, ALL, on) def migrate_chat(self, old: int, new: int): - """A group became a supergroup: its settings, and the forecast it was sent, move to the new chat id.""" + """A group became a supergroup: its settings move to the new chat id.""" entry = self.chats.pop(old, None) if entry is not None: self.chats.setdefault(new, entry) - sent = self.monitor.get("forecast_sent", {}) - if str(old) in sent: - sent.setdefault(str(new), sent.pop(str(old))) log.info("Alerts: chat %s became %s", old, new) self.save() @@ -173,24 +174,6 @@ def set_keyboard(self, chat_id: int, version: str): self.chats[chat_id]["keyboard"] = version self.save() - def record_forecast(self, chat_id: int, days: list[dict], today: date): - """Remember the forecast days this chat was just sent (a newer send replaces the baseline for the same day, the other - days keep theirs); days before today are dropped.""" - sent = self.monitor.setdefault("forecast_sent", {}).setdefault(str(chat_id), {}) - for d in days: - sent[d["date"].isoformat()] = {**d, "date": d["date"].isoformat()} - for day in [k for k in sent if k < today.isoformat()]: - del sent[day] - self.save() - - def forecast_sent(self, chat_id: int) -> dict: - """{date: the day as it was sent} for this chat.""" - return {date.fromisoformat(k): {**v, "date": date.fromisoformat(k)} - for k, v in self.monitor.get("forecast_sent", {}).get(str(chat_id), {}).items()} - - def forecast_chats(self) -> list[int]: - return [int(c) for c in self.monitor.get("forecast_sent", {})] - def subscribed(self, chat_id: int, kind: str) -> bool: """Does this chat get this alert type?""" return chat_id in self.chats and not self.chats[chat_id].get("gone") and kind not in self.muted(chat_id) @@ -200,6 +183,37 @@ def alert_chats(self, kind: str) -> list[int]: return [c for c in self.chats if self.subscribed(c, kind)] +class ReadMark: + """Where AlertDelivery keeps the last alert it handled of another server's log than ecobot-mcp's (whose mark is AlertState's own + `read` and `read_log`): its id and the log's identity, in bot_state.json under "alerts_read_by", by the server's name.""" + + def __init__(self, state: AlertState, name: str): + self.state, self.name = state, name + + def _entry(self) -> dict: + entry = self.state.marks.get(self.name) + return entry if isinstance(entry, dict) else {} + + @property + def read(self) -> int | None: + return self._entry().get("read") + + @read.setter + def read(self, value: int | None): + self.state.marks[self.name] = {**self._entry(), "read": value} + + @property + def read_log(self) -> str | None: + return self._entry().get("log") + + @read_log.setter + def read_log(self, value: str | None): + self.state.marks[self.name] = {**self._entry(), "log": value} + + def save(self): + self.state.save() + + class Notifier: def __init__(self, bot, state: AlertState, charts: AlertCharts | None = None): """charts: the bot's alert charts (AlertCharts), when the alerts' pictures are to be shared with its other charts.""" @@ -207,13 +221,14 @@ def __init__(self, bot, state: AlertState, charts: AlertCharts | None = None): async def __call__(self, text: str, kind: str, link: tuple[str, str] | None = None, chart: Callable[[], Awaitable[Picture | None]] | None = None, chats: list[int] | None = None, - since: int | None = None) -> int: + since: int | None = None, event: int | None = None) -> int: """Send an alert (silently) to the chats subscribed to its type (`kind`, one of menu.TYPES): of `chats` (say, the one sent something that has since changed), else of every chat. Chats the bot can no longer post to are marked gone. Returns how many it was sent to. link = (label, url) adds a clickable label to the footer; each carries the settings buttons. chart draws the alert's picture (None: the text alone), and is called only when some chat gets the alert and the bot doesn't hold the chart with the alert's data already (`since`: the time of the newest reading the alert is about; AlertCharts.held). The text is the picture's - caption (the text alone if Telegram refuses it); it is uploaded once and the chats after the first are sent Telegram's copy.""" + caption (the text alone if Telegram refuses it); it is uploaded once and the chats after the first are sent Telegram's copy. event: the + alert's id in the log, which its 🔄 names (so it replays the call that drew the alert's chart).""" targets = self.state.alert_chats(kind) if chats is None else [c for c in chats if self.state.subscribed(c, kind)] text, entities = with_link(text, link) photo = None @@ -225,7 +240,7 @@ async def __call__(self, text: str, kind: str, link: tuple[str, str] | None = No self.charts.keep(kind, picture, since) started, sent = time.monotonic(), 0 for chat_id in targets: - ok, message = await self._send(chat_id, text, entities, kind, photo) + ok, message = await self._send(chat_id, text, entities, kind, photo, event=event) sent += ok if photo and (sizes := getattr(message, "photo", None)): photo = sizes[-1].file_id # the largest size: the picture as sent @@ -234,12 +249,13 @@ async def __call__(self, text: str, kind: str, link: tuple[str, str] | None = No log.info("Alert sent to %d chat(s) in %.1fs: %s", sent, time.monotonic() - started, text, extra=QUOTES) return sent - async def _post(self, chat_id: int, text: str, entities, kind: str, photo: bytes | str | None): + async def _post(self, chat_id: int, text: str, entities, kind: str, photo: bytes | str | None, event: int | None = None): """The message itself (returned): silent unless the chat turned sound on for this type, with the alert type's settings button (the bell). With a photo it is the picture with the text as its caption, and a Refresh that draws the chart again; a picture Telegram refuses falls back to the text alone.""" quiet = kind not in self.state.loud(chat_id) - markup = lambda refresh: alert_keyboard(kind, self.state.muted(chat_id), self.state.loud(chat_id) if chat_id > 0 else None, refresh=refresh) + markup = lambda refresh: alert_keyboard(kind, self.state.muted(chat_id), self.state.loud(chat_id) if chat_id > 0 else None, refresh=refresh, + event=event) if photo: try: return await self.bot.send_photo(chat_id, photo, caption=text, caption_entities=entities, disable_notification=quiet, @@ -251,16 +267,17 @@ async def _post(self, chat_id: int, text: str, entities, kind: str, photo: bytes return await self.bot.send_message(chat_id, text, entities=entities, disable_web_page_preview=True, disable_notification=quiet, reply_markup=markup(False)) - async def _send(self, chat_id: int, text: str, entities, kind: str, photo: bytes | str | None = None, again: bool = True) -> tuple[bool, object]: + async def _send(self, chat_id: int, text: str, entities, kind: str, photo: bytes | str | None = None, again: bool = True, + event: int | None = None) -> tuple[bool, object]: """Send an alert (see _post) to one chat; a chat the bot can no longer post to is marked gone. Telegram's flood limit (when it asks for a short wait) and a dropped connection get one more try; a timeout doesn't, as the message may have arrived. Whatever fails for one chat is logged, so the others still get the alert. (whether it was sent, the message sent)""" try: try: - return True, await self._post(chat_id, text, entities, kind, photo) + return True, await self._post(chat_id, text, entities, kind, photo, event) except ChatMigrated as e: # the group became a supergroup: follow it, and send again there self.state.migrate_chat(chat_id, e.new_chat_id) - return await self._send(e.new_chat_id, text, entities, kind, photo) if e.new_chat_id != chat_id else (False, None) + return await self._send(e.new_chat_id, text, entities, kind, photo, event=event) if e.new_chat_id != chat_id else (False, None) except Forbidden as e: # kicked from the group, or blocked in a private chat self.state.mark_gone(chat_id, f"can't post: {e}") except BadRequest as e: @@ -273,7 +290,147 @@ async def _send(self, chat_id: int, text: str, entities, kind: str, photo: bytes raise log.info("Alert to %s: %s; trying again in %gs", chat_id, e, wait) await asyncio.sleep(wait) - return await self._send(chat_id, text, entities, kind, photo, again=False) + return await self._send(chat_id, text, entities, kind, photo, again=False, event=event) except Exception as e: # Telegram refused it, or the state file couldn't be saved log.warning("Alert to %s failed: %s", chat_id, e, exc_info=not isinstance(e, TelegramError)) return False, None + + +class AlertDelivery: + """The bot's side of the alert log (lib/alert_log.py, docs/ecobot-mcp.md section 4): it reads each new event and sends it, as the + Notifier does, to the chats subscribed to its kind, with its link, its chart drawn from the event's chart data (and the 🔄 that + replays the chart's drawn_by) or the text alone. The id of the last event handled is kept in bot_state.json (AlertState.read), so a + restart resumes after it; the events that expired meanwhile are skipped (the morning's rain is not news by the afternoon). With no id + kept (the first start) it begins after the newest event: what came before is not news either. So does a start on another log than the + one the id is from (alerts.sqlite removed or replaced: its ids start again at 1, and waiting for them to pass the old id would send + nothing for as long), noticed by the log's identity kept with the id, or by the id being past the log's newest. With the service remote + the log can also be replaced while the bot runs (the service back on another alerts.sqlite): that is looked for on every pass, and + delivery goes on in the new log with what came since the old one was last read (_switched). With `unexpired_first` (irrigation-mcp's + log: its battery and pause alerts are the kind still wanted at the bot's first start, which can come after irrigation-mcp's own first + daily check) the first start delivers the unexpired events instead.""" + + def __init__(self, log, notify: "Notifier", state: AlertState, tz, now: Callable[[], float] = time.time, weather=None, + mark: ReadMark | None = None, unexpired_first: bool = False): + """log: ecobot-mcp's alert log read over MCP (lib/weather.RemoteAlerts, whose reads are coroutines: it is looked at when `run` + starts), or an alert log itself (lib/alert_log.py: the tests', whose reads are plain). now: the epoch clock (the events' times are compared with it). + weather: ecobot-mcp as the bot reaches it (lib/weather.py), which draws the events' charts; without it they go without. + mark: where the last id handled is kept (ReadMark: irrigation-mcp's log); none: the state's own (ecobot-mcp's). + unexpired_first: with no id kept, begin before the log's unexpired events rather than after its newest.""" + self.log, self.notify, self.state, self.tz, self.now, self.weather = log, notify, state, tz, now, weather + self.mark = mark or state + self.unexpired_first = unexpired_first + self.begun = False + self.seen_at: float | None = None # when the log was last read through (a pass of deliver_new began): see _switched + if not getattr(log, "remote", False): + self._begin(self.log.last_id(), self._first(self.log.since(0)) if self._wants_unexpired() else None) + + def _wants_unexpired(self) -> bool: + return self.unexpired_first and self.mark.read is None + + @staticmethod + def _first(unexpired: list[dict]) -> int | None: + """The id before the oldest unexpired event (none: no event).""" + return unexpired[0]["id"] - 1 if unexpired else None + + async def begin(self): + """Where delivery starts (the log looked at), if it hasn't yet.""" + if not self.begun: + newest = await value(self.log.last_id()) + self._begin(newest, self._first(await value(self.log.since(0))) if self._wants_unexpired() else None) + + def _begin(self, newest: int, before_unexpired: int | None = None): + """before_unexpired: with no id kept, where to begin instead of after the newest (unexpired_first).""" + self.begun = True + if self.mark.read is None: + self._handled(newest if before_unexpired is None else before_unexpired) + elif self._other_log(newest): + log.warning("Alerts: the alert log is not the one the last alert delivered (%s) is from; starting after its newest (%s)", + self.mark.read, newest) + self._handled(newest) + elif self.mark.read_log is None: # (kept before the log had an identity: this one) + self._handled(self.mark.read) + + def _other_log(self, newest: int) -> bool: + """Is the log read now another than the one the last id handled is from (its identity, or its newest id behind that id)?""" + return self.mark.read is not None and (self.mark.read_log not in (None, self.log.identity) or self.mark.read > newest) + + async def _switched(self, newest: int): + """The log was replaced while the bot runs (remote: the service came back on another alerts.sqlite, deleted, moved or + redeployed; its ids start again at 1). Delivery goes on in the new log after the events from before the bot last read the old + one through (`seen_at`): the new log began after that, so those that came since are news, and they are sent; none known (the + first pass), after its newest, as at a start.""" + start = newest + if self.seen_at is not None: + since = int(self.seen_at) # (an event's time is in whole seconds: one logged later in the same second is news too) + fresh = [e for e in await value(self.log.since(0)) if _epoch(e.get("time")) >= since] + start = fresh[0]["id"] - 1 if fresh else newest + log.warning("Alerts: the service's alert log is another than the one the last alert delivered (%s) is from; " + "going on in it after %s", self.mark.read, start) + self._handled(start) + + @property + def last(self) -> int: + return self.mark.read or 0 + + def _handled(self, event_id: int): + self.mark.read, self.mark.read_log = event_id, self.log.identity + try: + self.mark.save() + except Exception as e: # (the next one saved covers it; at worst a restart sends it again) + log.warning("Couldn't save the last alert delivered (%s: %s)", type(e).__name__, e) + + RETRY_SECONDS = 30 # after the log can't be read (locked, a disk error): try again, rather than stop alerts until a restart + + async def run(self): + """Forever: deliver what is new, then wait for more. A failure reading the log is logged and retried, never the end of alerts.""" + while True: + try: + await self.begin() + await self.deliver_new() + await value(self.log.wait(self.last)) + except asyncio.CancelledError: + raise + except Exception as e: + log.error("Alert delivery couldn't read the log (%s: %s); trying again in %ds", type(e).__name__, e, self.RETRY_SECONDS, + exc_info=True) + await asyncio.sleep(self.RETRY_SECONDS) + + async def deliver_new(self) -> int: + """Send each unexpired event after the last handled, oldest first; returns how many were sent. A log replaced since the last + pass (its identity another) is noticed here, while the bot runs, not only when it starts (_switched).""" + started = self.now() + while True: + newest = await value(self.log.last_id()) + if self._other_log(newest): + await self._switched(newest) + identity = self.log.identity + events = await value(self.log.since(self.last)) + if self.log.identity == identity: # (else replaced again between the reads: looked at once more) + break + sent = 0 + for event in events: + try: + await self.deliver(event) + sent += 1 + except Exception as e: # one alert that fails never holds up the next + log.error("Alert %d couldn't be delivered (%s: %s)", event["id"], type(e).__name__, e, exc_info=True) + self._handled(event["id"]) + if newest > self.last: # (only expired events after the last handled: skipped) + self._handled(newest) + self.seen_at = started + return sent + + async def deliver(self, event: dict) -> int: + """One event to the chats subscribed to its kind; returns how many it reached.""" + link = (event["link"]["label"], event["link"]["url"]) if event.get("link") else None + chart, data, since = None, event.get("chart"), None + if data and self.weather is not None: + from ..specs import from_json + try: + since = from_json(data).newest + except Exception: + since = None + + async def chart() -> Picture | None: + return await picture_of(data, self.tz, self.weather) + return await self.notify(event["text"], kind=event["kind"], link=link, chart=chart, since=since, event=event["id"]) diff --git a/lib/alerts/particulates.py b/lib/alerts/particulates.py index 7ee31090..75de0d6c 100644 --- a/lib/alerts/particulates.py +++ b/lib/alerts/particulates.py @@ -2,16 +2,18 @@ "Wear a mask outside" when PM2.5 or PM10 reaches US AQI 151+ ("unhealthy", the official level at which masks are advised for everyone) in two readings in a row, each check counting only when the sensor's last -ANTISPIKE_REQUIRE_CONSECUTIVE (2) readings are all that high (a spike never does); "back to safe" when both are at +MCP_ANTISPIKE_REQUIRE_CONSECUTIVE (2) readings are all that high (a spike never does); "back to safe" when both are at AQI 100 or below in two readings in a row (rules.py: a check that brings no new reading counts for nothing). Every episode gets the pair. Particles only: masks filter particles, not gases like CO2/VOC/NOx. +Each is an event in the alert log (lib/alert_log.py) with the sensor's dashboard as its link and the 1-day particulates chart as data; +it is news until the next check (CHECK_SECONDS). """ import logging from datetime import datetime from . import pictures, rules -from .menu import kinds_of +from .kinds import kinds_of log = logging.getLogger(__name__) @@ -24,8 +26,10 @@ class ParticulatesMonitor: KINDS = kinds_of("AirGradient") - def __init__(self, air, state, notify): - self.air, self.state, self.notify = air, state, notify + def __init__(self, air, state, alerts, service=None): + """state: the rules' store (AlertStore). alerts: the alert log. service: the service's tools (the chart's call), else built over + the sensor.""" + self.air, self.state, self.alerts, self.service = air, state, alerts, service async def check(self, latest=None, now: datetime | None = None): """latest: the sensor's latest reading (AirGradient.latest(): the reading, when it was taken, what it has been sustained at).""" @@ -41,34 +45,41 @@ async def check(self, latest=None, now: datetime | None = None): return if when is not None and not rules.new_reading(m, when.timestamp()): # the sensor has said nothing new since the last check return - # held: the lowest of the last readings (ANTISPIKE_REQUIRE_CONSECUTIVE), so a spike alone can't make the air unhealthy + # held: the lowest of the last readings (MCP_ANTISPIKE_REQUIRE_CONSECUTIVE), so a spike alone can't make the air unhealthy high25, high10 = held.get("pm2_5", pm25), held.get("pm10", pm10) bad = (high25 is not None and high25 >= MASK_PM25) or (high10 is not None and high10 >= MASK_PM10) good = (pm25 is None or pm25 <= SAFE_PM25) and (pm10 is None or pm10 <= SAFE_PM10) rules.run(m, "above", bad) rules.run(m, "below", good) - since = int(when.timestamp()) if when is not None else None # the reading the alert is about: a chart drawn with it is sent as it is if not m["unsafe"] and m["above"] >= rules.CONFIRM_READINGS: m["unsafe"] = True - await self.notify("\U0001f637 Unhealthy air outside — wear a P2/N95 mask today. " + self._levels(reading), - link=self.air.link, kind="particulates", chart=self._picture, since=since) + self._emit(True, "\U0001f637 Unhealthy air outside — wear a P2/N95 mask today. " + self._levels(reading), "Unhealthy air: wear a mask", + reading, when, await self._chart()) elif m["unsafe"] and m["below"] >= rules.CONFIRM_READINGS: m["unsafe"] = False - await self.notify("✅ Outdoor air is safe again. " + self._levels(reading), link=self.air.link, kind="particulates", - chart=self._picture, since=since) + self._emit(False, "✅ Outdoor air is safe again. " + self._levels(reading), "Outdoor air safe again", reading, when, await self._chart()) self.state.save() - async def _picture(self) -> pictures.Picture | None: - """The 1-day particulates chart (what the Particulates button gives), for the alert; None when it cannot be made.""" - return await pictures.chart(self.air, pictures.CHARTS["particulates"], self.air.tz) + def _emit(self, unsafe: bool, text: str, title: str, reading: dict, when: datetime | None, chart: dict | None): + """The alert, in the log: news until the next check.""" + data = {"unsafe": unsafe, "at": when.astimezone(self.air.tz).isoformat(timespec="seconds") if when else None, + **{f"{key}_ugm3": (reading.get(key) or {}).get("value") for key in ("pm2_5", "pm10")}} + for key in ("pm2_5", "pm10"): + if "aqi_us" in (reading.get(key) or {}): + data[f"{key}_aqi_us"] = reading[key]["aqi_us"] + self.alerts.append("particulates", text, title, data, expires=self.alerts.now() + CHECK_SECONDS, link=self.air.link, chart=chart) + + async def _chart(self) -> dict | None: + """The 1-day particulates chart (what the Particulates button gives) as data, for the alert; None when it cannot be made.""" + return await pictures.chart_data(self.air, pictures.CHARTS["particulates"], self.air.tz, self.service) @staticmethod def _levels(reading: dict) -> str: - """Short summary: PM2.5 (with AQI), plus PM10 only when it's elevated.""" + """Short summary: PM2.5 (with AQI), plus PM10 (with its AQI) only when it's elevated.""" parts = [] pm25, pm10 = reading.get("pm2_5") or {}, reading.get("pm10") or {} if pm25.get("value") is not None: parts.append(f"PM2.5 {pm25['value']:.0f} µg/m³" + (f" (AQI {pm25['aqi_us']})" if "aqi_us" in pm25 else "")) if pm10.get("value") is not None and pm10["value"] > SAFE_PM10: - parts.append(f"PM10 {pm10['value']:.0f} µg/m³") + parts.append(f"PM10 {pm10['value']:.0f} µg/m³" + (f" (AQI {pm10['aqi_us']})" if "aqi_us" in pm10 else "")) return (", ".join(parts) + ".") if parts else "" diff --git a/lib/alerts/pictures.py b/lib/alerts/pictures.py index d388f7d8..25785372 100644 --- a/lib/alerts/pictures.py +++ b/lib/alerts/pictures.py @@ -1,22 +1,26 @@ -"""The chart that goes with an alert: the same picture a typed request for it would give ("Wind chart 1d" is what the Wind button sends), so what an -alert shows is defined once, by the button sentences and lib/intent. AlertCharts keeps those charts with the bot's other charts (the ImageCache), -so one is drawn once and uploaded once however many times it is sent.""" +"""The chart that goes with an alert: the same picture a keyboard button gives (the Wind button's fixed call is the gusts alert's), so +what an alert shows is defined once, by those calls (lib/templates.py CALLS: the Wind button is summary {readings: ["wind"], period: "1d", +chart: true}), which the service draws: the rule puts the chart's data, with its drawn_by, in the alert's event (chart_data), and the bot +has it drawn (picture_of: by ecobot-mcp, lib/weather.py, replaying the chart's drawn_by). AlertCharts keeps those charts with the bot's +other charts (the ImageCache, by call), so one is drawn once and uploaded once however many times it is sent.""" -import asyncio +import json import logging -import time -from datetime import datetime, timezone -from typing import Callable, NamedTuple +from datetime import datetime, timezone, tzinfo +from typing import NamedTuple -from .. import intent -from ..charts import render +from .. import templates +from ..periods import call_key +from ..specs import from_json from ..timeutil import now_local -from ..tools import Turn log = logging.getLogger(__name__) -# The alert types that carry a chart, and the request it answers: what the alert is sent with, and what its Refresh draws again -CHARTS = {"gusts": "Wind chart 1d", "uv": "UV chart 1d", "temps": "Temperature chart 1d", "particulates": "Particulates chart 1d"} +# The alert types that carry a chart, and the service call that draws it: what the alert is sent with, and what its Refresh draws again +# (the Wind, Temperature and Particulates buttons' own calls; UV's has no button) +CHARTS = {"gusts": templates.CALLS["Wind chart 1d"], "uv": ("summary", {"readings": ["uv"], "period": "1d", "chart": True}), + "temps": templates.CALLS["Temperature chart 1d"], "particulates": templates.CALLS["Particulates chart 1d"]} +CHART_POINTS = "drawn" # every point, as drawn (lib/service/common.py AS_DRAWN): the bot's picture class Picture(NamedTuple): @@ -24,52 +28,85 @@ class Picture(NamedTuple): png: bytes title: str newest: int | None # the time of the newest reading it draws (epoch), when the chart tells it + drawn_by: dict | None = None # the call that draws it again + dark: bool | None = None # drawn in the dark theme (None: the theme charts are drawn in now) -async def chart(source, text: str, tz) -> Picture | None: - """The chart for the request `text`, made from `source`'s tool the way the bot would answer it; None when it cannot be made (the alert then - goes out as text). `source` is the station or the air sensor: the tool is found in its `tools` by the name the request resolves to.""" +def _service_of(source, tz): + """The service's tools over one source (the station or the air sensor), for a monitor that has only its source.""" + from ..service import Service + from ..service.context import Context + name = getattr(source, "name", "") + return Service.of(Context(eco=source if name == "Ecowitt" else None, air=source if name == "AirGradient" else None, tz=tz)) + + +async def chart_data(source, call: tuple[str, dict], tz, service=None) -> dict | None: + """The chart of the service `call` (one of CHARTS) as data (3.7's JSON, with the `drawn_by` that draws it again), as the service gives it + (every point, as drawn): what an alert event carries. None when it cannot be made (the alert then goes out as text). `source` is the + station or the air sensor; `service` the service's tools, else built over `source`.""" + tool, args = call try: - now = now_local(tz) - read = intent.read(text, now) - tool, args = read.fast[0], read.fast[1] - turn = Turn.of(read, text) - handler = next(t for t in source.tools if t.name == tool).handler - await handler(args, turn) - spec = turn.charts[0] - return Picture(await asyncio.to_thread(render, spec, tz), spec.caption(now.date()), spec.newest) + service = service or _service_of(source, tz) + out = json.loads(await service[tool].call(args, {"chart_points": CHART_POINTS})) + if "error" in out: + raise ValueError(out["error"]) + return out["charts"][0] except Exception as e: - log.warning("The chart for the alert (%s) couldn't be made: %s: %s", text, type(e).__name__, e) + log.warning("The chart for the alert (%s %s) couldn't be made: %s: %s", tool, args, type(e).__name__, e) + return None + + +def _picture(image, tz) -> Picture: + """A lib/weather.ChartImage as an alert's Picture.""" + spec = from_json(image.chart) + return Picture(image.png, spec.caption(now_local(tz).date()), spec.newest, image.chart.get("drawn_by"), image.dark) + + +async def picture_of(data: dict, tz, weather) -> Picture | None: + """A chart given as data, drawn again by `weather` (ecobot-mcp as the bot reaches it, lib/weather.py: it replays the chart's + drawn_by); None when it cannot be. The bot draws nothing itself.""" + try: + return _picture(await weather.picture(data), tz) + except Exception as e: + log.warning("The alert's chart couldn't be drawn: %s: %s", type(e).__name__, e) + return None + + +async def chart(call: tuple[str, dict], tz, weather) -> Picture | None: + """The chart of the service `call` (one of CHARTS), drawn by ecobot-mcp (`weather`, as the bot reaches it: lib/weather.py); None when + it cannot be made.""" + tool, args = call + try: + out, image = await weather.chart_image(tool, args, {"chart_points": CHART_POINTS}) + if image is None: + raise ValueError(out.get("error") or "no chart") + return _picture(image, tz) + except Exception as e: + log.warning("The chart for the alert (%s %s) couldn't be made: %s: %s", tool, args, type(e).__name__, e) return None class AlertCharts: - """The charts alerts carry (CHARTS), kept in the bot's ImageCache under their request's key (the keyboard's "Wind chart 1d" is the same - chart), so each is drawn once and uploaded once: + """The charts alerts carry (CHARTS), kept in the bot's ImageCache under their call (the Wind button's is the same chart), so each is + drawn once and uploaded once: - an alert sends the chart the bot holds when it has the alert's data (drawn with the newest reading the alert is about, `since`, or a later one): Telegram's copy once it has been sent, to this chat or another, or by a button; else its chart is drawn and kept, and Telegram's copy remembered from the first chat it goes to; - - the chart of every type alerted in the last WARM_SECONDS is drawn ahead with the keyboard's (Bot.draw_buttons_ahead, and uploaded - ahead with them), so the Refresh under the alert is answered at once; - Refresh sends the held chart when it is newer than the picture shown and fresh (ImageCache.FRESH), else draws one.""" - WARM_SECONDS = 6 * 3600 + def __init__(self, images, tz: tzinfo | None = None): + """images: the bot's ImageCache. tz: the station's zone (its titles' dates).""" + self.images, self.tz = images, tz - def __init__(self, images, now: Callable[[], datetime], clock: Callable[[], float] = time.monotonic): - """images: the bot's ImageCache. now: the local time (for the requests' keys). clock: the seconds the warm time is counted in.""" - self.images, self.now, self.clock = images, now, clock - self.alerted: dict[str, float] = {} # request -> the clock when an alert carrying its chart last went out + @staticmethod + def call(kind: str) -> tuple[str, dict] | None: + """The service call an alert type's chart is drawn by; None for a type without one.""" + return CHARTS.get(kind) def key(self, kind: str) -> str | None: - """The image key of an alert type's chart; None for a type without one.""" - text = CHARTS.get(kind) - return self.images.canonical(text, self.now()) if text else None - - def warm(self) -> list[str]: - """The requests whose charts are kept drawn ahead: those of the alert types sent in the last WARM_SECONDS.""" - now = self.clock() - self.alerted = {text: at for text, at in self.alerted.items() if now - at <= self.WARM_SECONDS} - return list(self.alerted) + """The image key of an alert type's chart (its call); None for a type without one.""" + call = self.call(kind) + return call_key(*call) if call else None def held(self, kind: str, since: int | None) -> bytes | str | None: """The chart the bot holds for an alert of `kind` when it draws the alert's data (its newest reading is `since` or later): Telegram's @@ -80,14 +117,11 @@ def held(self, kind: str, since: int | None) -> bytes | str | None: def keep(self, kind: str, picture: Picture, since: int | None = None): """A chart just drawn for an alert of `kind` (about the reading `since`: it draws that reading, whatever its own time says).""" newest = max((t for t in (picture.newest, since) if t is not None), default=None) - self.images.put(self.key(kind), picture.png, picture.title, newest=newest) + self.images.put(self.key(kind), picture.png, picture.title, newest=newest, drawn_by=picture.drawn_by, dark=picture.dark) - def sent(self, kind: str, message, alerted: bool = True): - """The chart of `kind` went out in `message` (as Telegram returned it): later sends use Telegram's copy. An alert (not a Refresh) - starts the WARM_SECONDS its chart is drawn ahead for.""" + def sent(self, kind: str, message): + """The chart of `kind` went out in `message` (as Telegram returned it): later sends use Telegram's copy.""" self.images.sent(self.key(kind), message) - if alerted: - self.alerted[CHARTS[kind]] = self.clock() def newer_than(self, kind: str, message) -> bytes | str | None: """What the Refresh under `message` can send without drawing: the held chart of `kind` when it was drawn since the message was last diff --git a/lib/alerts/pollen_and_asthma.py b/lib/alerts/pollen_and_asthma.py index b16b2f0b..fad573ff 100644 --- a/lib/alerts/pollen_and_asthma.py +++ b/lib/alerts/pollen_and_asthma.py @@ -4,14 +4,16 @@ A warning when grass pollen or the thunderstorm asthma risk is High 🔴 or Extreme 🟣 (the scale is Low 🟢, Moderate 🟠, High 🔴, Extreme 🟣; "No data" counts as no reading). One alert per metric and day: another on a new day that is still High, and again when it rises (High to Extreme); none while it stays the same; none before 7:30 am. Once it drops below High the metric is ready to warn again. +Each is an event in the alert log (lib/alert_log.py), with the pollen site as its link, news until the end of its day. """ import logging import time +from datetime import timedelta from ..pollen.parse import LEVEL_EMOJI, LEVELS -from ..timeutil import day_text -from .menu import kinds_of +from ..timeutil import at_hour, day_text +from .kinds import kinds_of log = logging.getLogger(__name__) @@ -26,8 +28,9 @@ class PollenAndAsthmaMonitor: KINDS = kinds_of("Pollen") - def __init__(self, pollen, state, notify): - self.pollen, self.state, self.notify = pollen, state, notify + def __init__(self, pollen, state, alerts): + """state: the rules' store (AlertStore). alerts: the alert log.""" + self.pollen, self.state, self.alerts = pollen, state, alerts async def check(self): if not self.pollen.in_season() or self.pollen.now().timetuple()[3:5] < ALERT_FROM: # October to December only; not before 7:30 am @@ -49,5 +52,13 @@ async def check(self): m[key] = {"day": str(today), "level": reading["level"]} for_day = reading.get("date") when = f" (forecast for {day_text(for_day, year=False)})" if for_day and for_day != today else "" - await self.notify(f"{LEVEL_EMOJI[reading['level']]} {LABELS[key]} is {reading['level']}{when}.{ADVICE[key]}", link=LINK, kind="pollen_and_asthma") + self.alerts.append("pollen_and_asthma", f"{LEVEL_EMOJI[reading['level']]} {LABELS[key]} is {reading['level']}{when}.{ADVICE[key]}", + f"{LABELS[key]}: {reading['level']}", + {"metric": key, "level": reading["level"], "for": (for_day or today).isoformat()}, + expires=self._end_of(for_day or today), link=LINK) self.state.save() + + def _end_of(self, day) -> float: + """The epoch at which `day` (local) ends.""" + tz = getattr(self.pollen, "tz", None) + return at_hour(day + timedelta(days=1), 0, tz) if tz else self.alerts.now() + 86400 diff --git a/lib/alerts/store.py b/lib/alerts/store.py new file mode 100644 index 00000000..06735e6c --- /dev/null +++ b/lib/alerts/store.py @@ -0,0 +1,70 @@ +"""The alert rules' own state (alert_state.json in DATA_DIR): what each rule last alerted and the runs it is counting, so a restart neither +forgets nor repeats. The service's, apart from the bot's chats and settings (bot_state.json), which the rules know nothing of. + +Before step 4 of docs/ecobot-mcp.md the rules kept it in bot_state.json's "monitor": the first start with no alert_state.json moves it +here (MOVED), so nothing alerted before the upgrade alerts again. The irrigation controller's (irrigation_monitor, irrigation_watchdog) +stay with the bot until it moves to its own server; the forecast each chat was sent (forecast_sent) goes: the forecast alert is +station-wide now.""" + +import json +import logging +import os +import time + +log = logging.getLogger(__name__) + +MOVED = ("rain", "night", "cross", "gust", "uv", "particulates", "pollen_and_asthma") # the rules' keys in the bot's old "monitor" +DROPPED = ("forecast_sent",) + + +def load(path) -> dict | None: + """A JSON state file, None when there is none. One that can't be read is moved aside, as the next save would replace it, so what it + held can still be recovered by hand ({} then).""" + try: + with open(path) as f: + return json.load(f) + except FileNotFoundError: + return None + except (OSError, ValueError) as e: + aside = f"{path}.damaged-{time.strftime('%Y%m%d-%H%M%S')}" + os.replace(path, aside) + log.error("Couldn't read %s (%s): moved it to %s and starting afresh", path, e, aside) + return {} + + +def write(path, data: dict): + """Written in full to a new file that then replaces the old one, on disk first, so a crash leaves one or the other whole.""" + tmp = f"{path}.tmp" + with open(tmp, "w") as f: + json.dump(data, f, indent=1) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + + +class AlertStore: + """The rules' state: `monitor`, a dict each rule keeps its own key in, and save().""" + + def __init__(self, path, moved_from=None): + """moved_from: the bot's state (lib/alerts/notify.AlertState), whose rules' state is moved here when this file is new.""" + self.path = path + data = load(path) + self.monitor: dict = (data or {}).get("monitor", {}) + if data is None: + if moved_from is not None: + self._move(moved_from) + self.save() + + def _move(self, bot_state): + old = bot_state.monitor + moved = [key for key in MOVED if key in old] + for key in moved: + self.monitor[key] = old.pop(key) + dropped = [key for key in DROPPED if old.pop(key, None) is not None] + if moved or dropped: + log.info("Alerts: the rules' state moved from %s to %s (%s)", bot_state.path, self.path, ", ".join(moved) or "nothing") + self.save() # (here first: a crash between the two saves leaves it in both, never in neither) + bot_state.save() + + def save(self): + write(self.path, {"monitor": self.monitor}) diff --git a/lib/alerts/weather.py b/lib/alerts/weather.py index 7c8a9863..bf92d636 100644 --- a/lib/alerts/weather.py +++ b/lib/alerts/weather.py @@ -2,7 +2,7 @@ 5-minute readings; the rain check also reads the gauge's live value, one small request). - Rain: "started" (one tip of the gauge is enough, told at once, however lately it stopped) and "stopped" (dry for - ALERT_COOLDOWN_MINUTES, so patchy showers are one spell), with how much fell over the whole spell. Not during quiet hours (RAIN_QUIET_HOURS, default midnight to 6am, and they may run across midnight): + MCP_ALERT_COOLDOWN_MINUTES, so patchy showers are one spell), with how much fell over the whole spell. Not during quiet hours (MCP_RAIN_QUIET_HOURS, default midnight to 6am, and they may run across midnight): those are kept quiet and one summary of the rain that fell in them is sent after they end. - Strong gusts: one alert when a gust goes over 40 km/h, and no more until the gusts have stayed at or under it for an hour, so a blustery afternoon is one message, not twenty. @@ -10,8 +10,10 @@ below 10 for an hour. - Temperatures crossing: outdoor becomes warmer than indoor (or cooler); it has to differ by more than 1 degree, which stops sensor noise flip-flopping. - The crossing has a back-off rule (rules.py): after an alert, a change is held for ALERT_COOLDOWN_MINUTES and then + The crossing has a back-off rule (rules.py): after an alert, a change is held for MCP_ALERT_COOLDOWN_MINUTES and then announced if the state still differs from the one last alerted; if it is back where it was, nothing is sent. +Each alert is an event appended to the alert log (lib/alert_log.py), news for a while (rain RAIN_EXPIRES_SECONDS, gusts and UV their +rearm time, the crossing its cooldown); gusts, UV and the crossing carry their chart as data, with the call that draws it again. """ import asyncio @@ -20,18 +22,19 @@ from ..ecowitt.glance import UVI_ALERT from . import pictures, rules -from .menu import kinds_of +from .kinds import kinds_of from .rules import due, remember from ..ecowitt.rain import Rows, duration, rain_amount, wet_flags from ..timeutil import at_hour, clock_text, to_local log = logging.getLogger(__name__) -ALERT_COOLDOWN_SECONDS = 60 * 60 # the default; ALERT_COOLDOWN_MINUTES sets it (the readings looked at go back 3 hours, so 150 minutes is the most) +ALERT_COOLDOWN_SECONDS = 60 * 60 # the default; MCP_ALERT_COOLDOWN_MINUTES sets it (the readings looked at go back 3 hours, so 150 minutes is the most) CROSS_MARGIN = 1.0 GUST_ALERT_KMH = 40 GUST_REARM_SECONDS = 3600 UV_REARM_SECONDS = 3600 +RAIN_EXPIRES_SECONDS = 3600 # a rain alert is news for about an hour (the overnight summary too) def side(r: dict) -> str | None: @@ -45,8 +48,11 @@ def side(r: dict) -> str | None: class WeatherMonitor: KINDS = kinds_of("Ecowitt") - def __init__(self, station, state, notify, cooldown_seconds: int = ALERT_COOLDOWN_SECONDS, quiet: tuple[int, int] | None = None): - self.station, self.state, self.notify = station, state, notify + def __init__(self, station, state, alerts, cooldown_seconds: int = ALERT_COOLDOWN_SECONDS, quiet: tuple[int, int] | None = None, + service=None): + """state: the rules' store (AlertStore). alerts: the alert log the alerts are appended to. service: the service's tools (the + charts' calls), else built over the station.""" + self.station, self.state, self.alerts, self.service = station, state, alerts, service self.cooldown = cooldown_seconds self.quiet = quiet # (from hour, to hour) local, no rain alerts in between; None: always on self._rain_lock = asyncio.Lock() # the minute's check and the live reading's look at the rain are one at a time @@ -132,7 +138,8 @@ async def _rain_locked(self, rows: Rows): m["since"] = next(ts for ts in wet_times if latest_ts - ts < self.cooldown) rate = next(r for ts, w, r in reversed(wet) if w) if not quiet: - await self.notify("\U0001f327️ It's started raining" + (f" ({rate:g} mm/h)." if rate > 0 else "."), kind="rain") + self._emit("rain", "\U0001f327️ It's started raining" + (f" ({rate:g} mm/h)." if rate > 0 else "."), "Rain started", + {"rate_mm_h": rate, "since": self._iso(m["since"])}, RAIN_EXPIRES_SECONDS) elif m["alerted_state"] == "raining": if last_wet is None: # nothing in the last 3 hours (e.g. the bot was down): close it quietly log.info("Alerts: rain ended while not watching; no alert") @@ -144,7 +151,8 @@ async def _rain_locked(self, rows: Rows): fell = await self._fell(rows, since, last_wet) amount = f"{fell:.1f} mm fell" if fell else "Only a trace fell" took = duration(last_wet + 300 - since) - await self.notify(f"\U0001f324️ The rain has stopped. {amount} over {took}.", kind="rain") + self._emit("rain", f"\U0001f324️ The rain has stopped. {amount} over {took}.", "Rain stopped", + {"fell_mm": fell, "from": self._iso(since), "to": self._iso(last_wet + 300)}, RAIN_EXPIRES_SECONDS) m["since"] = None remember(m, state, latest_ts, alerted=not quiet) @@ -172,7 +180,9 @@ async def _night_summary(self, rows: Rows): fell = await self._fell(rows, night["first"], night["last"]) amount = f"{fell:.1f} mm" if fell else "a trace" still = " It's still raining." if self.state.monitor.get("rain", {}).get("alerted_state") == "raining" else "" - await self.notify(f"\U0001f327️ Overnight rain: {amount}, from about {clock(night['first'])} to {clock(night['last'] + 300)}.{still}", kind="rain") + self._emit("rain", f"\U0001f327️ Overnight rain: {amount}, from about {clock(night['first'])} to {clock(night['last'] + 300)}.{still}", + "Overnight rain", {"fell_mm": fell, "from": self._iso(night["first"]), "to": self._iso(night["last"] + 300), + "still_raining": bool(still)}, RAIN_EXPIRES_SECONDS) async def _gusts(self, rows: Rows): """Only readings since the last check count, so a restart doesn't re-announce an old gust.""" @@ -184,9 +194,10 @@ async def _gusts(self, rows: Rows): if over and not m["active"]: m["active"] = True gust, ts = max(over) - await self.notify(f"\U0001f4a8 Strong gusts: {gust:.0f} km/h at {clock_text(to_local(ts, self.tz))}" - f" (alerts above {GUST_ALERT_KMH} km/h).", kind="gusts", chart=lambda: self._picture(pictures.CHARTS["gusts"]), - since=latest_ts) + self._emit("gusts", f"\U0001f4a8 Strong gusts: {gust:.0f} km/h at {clock_text(to_local(ts, self.tz))}" + f" (alerts above {GUST_ALERT_KMH} km/h).", "Strong gusts", + {"gust_kmh": gust, "at": self._iso(ts), "threshold_kmh": GUST_ALERT_KMH}, GUST_REARM_SECONDS, + await self._chart(pictures.CHARTS["gusts"])) async def _uv(self, rows: Rows): """One alert per spell at or above UVI_ALERT, once it holds for two readings in a row (rules.py); only readings newer than the last @@ -208,9 +219,9 @@ async def _uv(self, rows: Rows): if m.get("streak", 0) >= rules.CONFIRM_READINGS and not m["active"]: m["active"] = True uv, ts = m["peak"] - await self.notify(f"\U0001f9f4 UV index {uv:g} at {clock_text(to_local(ts, self.tz))}" - f": very high. Sunscreen, a hat and shade (alerts at {UVI_ALERT} and above).", kind="uv", - chart=lambda: self._picture(pictures.CHARTS["uv"]), since=latest_ts) + self._emit("uv", f"\U0001f9f4 UV index {uv:g} at {clock_text(to_local(ts, self.tz))}" + f": very high. Sunscreen, a hat and shade (alerts at {UVI_ALERT} and above).", "Very high UV", + {"uv_index": uv, "at": self._iso(ts), "threshold": UVI_ALERT}, UV_REARM_SECONDS, await self._chart(pictures.CHARTS["uv"])) async def _cross(self, rows: Rows): ts, r = rows[-1] @@ -226,9 +237,11 @@ async def _cross(self, rows: Rows): held = ts - c["alerted_time"] # how long the side we last told about has stood was = f"{int(held // 86400)} days" if held >= 2 * 86400 else duration(held) icon = "\U0001f321️" if current == "warmer" else "\u2744\ufe0f" # a thermometer for warmer, a snowflake for cooler - await self.notify(f"{icon} It's now {abs(o - i):.1f}°C {current} outside than inside " - f"({o:.1f}°C vs {i:.1f}°C). It had been {'cooler' if current == 'warmer' else 'warmer'} for {was}.", kind="temps", - chart=lambda: self._picture(pictures.CHARTS["temps"]), since=ts) + chart = await self._chart(pictures.CHARTS["temps"]) + self._emit("temps", f"{icon} It's now {abs(o - i):.1f}°C {current} outside than inside " + f"({o:.1f}°C vs {i:.1f}°C). It had been {'cooler' if current == 'warmer' else 'warmer'} for {was}.", + f"{current.capitalize()} outside than inside", {"side": current, "outdoor_c": o, "indoor_c": i, "had_been_seconds": held}, + self.cooldown, chart) remember(c, current, ts) async def _fell(self, rows: Rows, since: int, until: int) -> float | None: @@ -238,6 +251,14 @@ async def _fell(self, rows: Rows, since: int, until: int) -> float | None: rows = await self.station.recent((rows[-1][0] - since) / 3600 + 0.25) return rain_amount(rows, since, until) - async def _picture(self, text: str) -> pictures.Picture | None: - """The chart a typed `text` ("Wind chart 1d") would give, for an alert; None when it cannot be made.""" - return await pictures.chart(self.station, text, self.tz) + def _emit(self, kind: str, text: str, title: str, data: dict, lasts: float, chart: dict | None = None): + """An alert, appended to the log: news for `lasts` seconds.""" + self.alerts.append(kind, text, title, data, expires=self.alerts.now() + lasts, chart=chart) + + def _iso(self, ts: int | None) -> str | None: + return None if ts is None else to_local(ts, self.tz).isoformat(timespec="seconds") + + async def _chart(self, call: tuple[str, dict]) -> dict | None: + """The chart of the service `call` (pictures.CHARTS: the Wind button's for gusts), as data with its drawn_by, for an alert; None + when it cannot be made.""" + return await pictures.chart_data(self.station, call, self.tz, self.service) diff --git a/lib/auth_token.py b/lib/auth_token.py new file mode 100644 index 00000000..a92c8878 --- /dev/null +++ b/lib/auth_token.py @@ -0,0 +1,48 @@ +"""The token ecobot-mcp generates when AUTH_TOKENS is unset: made at its first start, kept in the data folder (auth_token, readable by +its own user only) and used again at every start after. The bot, with AUTH_TOKENS unset too, reads it from the same folder and sends it. +Its value is never logged: only where it is.""" + +import contextlib +import os +import secrets +from pathlib import Path + +FILE = "auth_token" + + +def path(folder: Path) -> Path: + return Path(folder) / FILE + + +def read(folder: Path) -> str | None: + """The token kept in `folder`; None when there is none yet, or it can't be read.""" + try: + return path(folder).read_text().strip() or None + except (OSError, UnicodeDecodeError): + return None + + +def ensure(folder: Path) -> str: + """The token kept in `folder`, made first if there is none: written whole to a file of its own (mode 0600) and then linked into + place, so a reader never sees half of one, and two starting at once keep the one that got there first.""" + if token := read(folder): + return token + target = path(folder) + token = secrets.token_urlsafe(32) + temporary = target.with_name(f".{FILE}.{os.getpid()}.{secrets.token_hex(4)}") + fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + try: + with os.fdopen(fd, "w") as f: + f.write(token + "\n") + f.flush() + os.fsync(f.fileno()) + try: + os.link(temporary, target) # (fails if one is there: an empty or unreadable one is replaced, a good one is kept) + except FileExistsError: + if kept := read(folder): + return kept + os.replace(temporary, target) + finally: + with contextlib.suppress(FileNotFoundError): + os.unlink(temporary) + return token diff --git a/lib/bot.py b/lib/bot.py index 24172286..1264db9f 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -12,33 +12,32 @@ import re import time from collections import defaultdict -from collections.abc import Coroutine from dataclasses import dataclass, field from datetime import datetime, UTC from typing import NamedTuple -from telegram import BotCommand, InputMediaPhoto, Message, ReplyKeyboardRemove, Update +from telegram import BotCommand, InlineKeyboardMarkup, InputMediaPhoto, Message, ReplyKeyboardRemove, Update from telegram.constants import ChatAction, ChatType from telegram.error import BadRequest, ChatMigrated, NetworkError, RetryAfter, TelegramError, TimedOut from telegram.ext import CallbackQueryHandler, ChatMemberHandler, CommandHandler, ContextTypes, MessageHandler, filters -from . import intent, periods, prompt, report, report_menu, templates +from . import intent, periods, prompt, templates from .admins import Admins +from .buttons import button from .alerts import menu, pictures from .alerts.notify import AlertState -from .irrigation import IrrigationError, Watchdog -from .irrigation import menu as irrigation_menu -from . import gauges -from .charts import render as render_chart -from .ecowitt.dashboard import STATUS +from . import irrigation_menu +from .irrigation.common import IrrigationError, IrrigationRefused +from .service.common import AS_DRAWN, BACKGROUND +from .specs import from_json from .tools import Turn from .config import Config from .entities import utf16_len, with_link -from .sources import Source -from .timeutil import clock_text, day_text, now_local +from .timeutil import now_local from .llm import Agent, shorten_old, strip_tool_turns, trim_history -from .topicmemory import TopicMemory from .logs import BUGS, QUOTES, fit +from .warm import Tasks # (the service's too: ecobot_mcp) +from .weather import UNREACHABLE, ChartImage, ChartNotDrawn, RemoteWeather, ServiceUnreachable log = logging.getLogger(__name__) @@ -50,30 +49,37 @@ TURN_SECONDS = 90 # a question that takes longer is given up on, so the ones queued behind it in the chat are not stuck DRAFT_REFRESH_SECONDS = 20 # Telegram drops a draft 30 s after its last update, so it is re-sent before that DRAFT_MIN_GAP = 1.0 # at most one draft update a second while the answer streams in -AHEAD_SECONDS = 300 # the keyboard's charts are drawn ahead this often (draw_buttons_ahead), so a press sends one already drawn -AHEAD_KEEP_SECONDS = 60 # ... unless the chart was drawn for a question this lately -USED_SECONDS = 900 # the bot counts as in use this long after a message or a press: the charts drawn ahead are then uploaded ahead too IRRIGATION_SETTLE_SECONDS = 3 # after any irrigation action, the controller is given this long to report its new state before it is read and the message redrawn NOT_ADMIN = "Sorry, only group admins can use this bot." NOT_ADMIN_TOAST = "Only group admins can use this bot" STALE_BUTTON = "That button is out of date, please ask again" +STATUS_PREFIX = "st:" +STATUS_REFRESH = f"{STATUS_PREFIX}refresh" # the 🔄 under Status: its gauges and report again, in the same message + + +def status_row() -> InlineKeyboardMarkup: + return InlineKeyboardMarkup([[button("🔄", STATUS_REFRESH)]]) +CHART_FAILED = "Sorry, I couldn't draw that chart, please ask again" # a period button's chart that couldn't be drawn or sent +NOT_DRAWN = "Sorry, I couldn't draw that chart. Please try again in a moment." # a button's chart that couldn't be drawn MAX_CALLBACK_BYTES = 64 # Telegram's own limit on a button's data +TOAST_LIMIT = 200 # ... and on the text a button's answer shows HELP = ("Hi! Message me directly, or in groups @mention me or reply to me.\n" "/reset clears this chat's memory, /alerts opens the alert settings (buttons to subscribe or unsubscribe), /usage shows what I can do.\n" - "In a private chat the buttons under the message box ask common questions; /keyboard off hides them.\n" + "In a private chat the buttons under the message box ask common questions; /keyboard off hides them. " + "The / menu lists the rest, /report and /chart among them.\n" "Your user ID: {user} | Chat ID: {chat}") -NO_MODEL = ("Sorry, that one needs the AI model, and this bot has none set up.\n" - "Without it I can still do: /report, the chart commands (/rain, /weather, /temperature, /humidity, /air_quality, /particulates, " - "/wind) and plain questions like \"how hot is it?\", \"is it raining?\", \"air quality now\", \"highest humidity yesterday\", " - "\"rain chart 7d\" or \"forecast\", as well as all the alerts.") +NO_MODEL = "Sorry, this bot has no AI model set up, so it can't answer typed questions; the buttons and the alerts still work." +COMMAND_NAME = re.compile(r"[a-z0-9_]{1,32}") # what Telegram takes as a command's name +MAX_COMMANDS = 100 # ... and how many it takes in the menu +OUT_OF_DATE = "That chart is out of date, please ask again" +SERVICE_DOWN = "Sorry, I can't reach the weather service right now. Please try again in a minute." # (BOT_MCP_URL: it is another program) @dataclass class ChatState: history: list[dict] = field(default_factory=list) lock: asyncio.Lock = field(default_factory=asyncio.Lock) - topics: TopicMemory = field(default_factory=TopicMemory) # the guidance topics this chat is still on (the air sensor's own readings among them) @dataclass @@ -82,10 +88,21 @@ class Answer: reply: str | None = None # its text; None until something gives one photos: list = field(default_factory=list) titles: list[str] = field(default_factory=list) - silent: bool = False # a chart made in code: it goes with just its title, its text kept for the history + silent: bool = False # a button's chart: it goes with just its title, its text kept for the history ready: periods.Drawn | None = None # a chart drawn moments ago, sent as it is - made: float | None = None # seconds the tool took to make the chart in code, for the timing line + made: float | None = None # seconds the tool took to make a button's chart, for the timing line ok: bool = True # False: the reply says something went wrong + pictures: list = field(default_factory=list) # the charts as the service drew them (lib/weather.ChartImage: each PNG with its + # chart's JSON and drawn_by), still to send + drawn_by: list = field(default_factory=list) # each photo's drawn_by (the call that draws it again), None for one with none + key: str | None = None # a button's call (periods.call_key): the picture cache's key + + +@dataclass +class Made: + """What a button's service call gave: its words (the chart's caption) and its charts as the service drew them.""" + text: str | None + pictures: list = field(default_factory=list) async def answer_query(query, *args, **kwargs) -> bool: @@ -123,16 +140,16 @@ def _short(text: str, limit: int) -> str: return fit(" ".join(text.split()), limit) -def chart_times(times: dict, made: float | None, pngs: list[bytes], sending: float) -> str: - """A reply's chart timings for the log: "data 12, calc 3, draw 98, PNG 41 (23 KB), send 812" (ms). times is the question's Turn.times; - made is how long the tool took when the chart was made in code (the calculation is that less its data), else None. A step that - wasn't timed is left out.""" +def chart_times(times: dict, made: float | None, pngs: list, sending: float) -> str: + """A reply's chart timings for the log: "data 12, calc 3, 23 KB, send 812" (ms). times is the question's Turn.times; made is how + long the call took for a button's chart (its drawing by the service included: the calculation is that less its data), + else None. A step that wasn't timed is left out; the size is the pictures' (none for Telegram's copy).""" ms = lambda seconds: f"{seconds * 1000:.0f}" parts = [f"data {ms(times['data'])}"] if "data" in times else [] if made is not None: parts.append(f"calc {ms(max(0.0, made - times.get('data', 0.0)))}") - if "draw" in times: - parts += [f"draw {ms(times['draw'])}", f"PNG {ms(times['png'])} ({sum(map(len, pngs)) / 1024:.0f} KB)"] + if size := sum(len(p) for p in pngs if isinstance(p, bytes)): + parts.append(f"{size / 1024:.0f} KB") return ", ".join([*parts, f"send {ms(sending)}"]) @@ -171,6 +188,44 @@ def strip_chart_talk(text: str) -> str: return "\n".join(lines).strip() or text +def complete_reply(results: list[str]) -> str | None: + """The reply of a step whose every result is complete (docs/ecobot-mcp.md 3.7: `complete: true`, a chart made and its `reply` + ready): the replies in order; None when any isn't.""" + replies = [] + for result in results: + try: + data = json.loads(result) + except ValueError: + return None + if not isinstance(data, dict) or data.get("complete") is not True or not data.get("reply") or not data.get("charts"): + return None + replies.append(str(data["reply"])) + return "\n\n".join(replies) if replies else None + + +def reads_air(name: str, args: dict, result: dict) -> bool: + """Is this call's answer about the air (its live-chart link goes under the reply)? Read from what the call read, never from a + refusal (its `words` and `names` list every reading): `current` when the air sensor answered a reading named ("pm2.5", "air"; not + every sensor, as for "what's it like", nor "all"); `summary` when a series is the air's; `readings` and `relate` when their reading + is; `days` when a field named is the air sensor's; `scan` always (the air against the weather). Read from the answer and the air + sensor's day fields alone, so the bot loads none of the service's source or storage code.""" + from .series import AIR # (the air sensor's readings: its day fields are each with _max, _min or _avg, lib/airgradient/days.py) + if not isinstance(result, dict) or "error" in result: + return False + if name == "current": + named = args.get("readings") + named = [named] if isinstance(named, str) else named or [] + return "air" in (result.get("sensors") or {}) and bool(named) and "all" not in [str(n).strip().lower() for n in named] + if name == "summary": + return any(str(k).startswith("air.") for k in result.get("series") or {}) + if name in ("readings", "relate"): + return str(result.get("reading") or "").startswith("air.") + if name == "days": + fields = [c.get("field") for c in args.get("where") or [] if isinstance(c, dict)] + [args.get("sort_by"), args.get("of")] + return any(f.rpartition("_")[::2] in [(m, k) for m in AIR for k in ("max", "min", "avg")] for f in fields if isinstance(f, str)) + return name == "scan" + + def chat_tag(chat_id: int) -> str: """"[Telegram 5467329077]": what every log line about a chat starts with, so a request and its reply are found together.""" return f"[Telegram {chat_id}]" @@ -252,29 +307,44 @@ class Delivered(NamedTuple): photo: Message | None = None # the single chart, as sent -def caption_of(text: str, title: str = "", link: tuple[str, str] | None = None, bold_headings: bool = False): - """(caption, entities) for a photo: its title and the text, the link under them as a footer, the report's heading names bold; None - when that is longer than a caption may be (CAPTION_LIMIT, counted as Telegram counts it).""" - body, ents = with_link(f"{title}\n\n{text}" if title else text, link) - if utf16_len(body) > CAPTION_LIMIT: - return None - return body, [*(report.heading_entities(body) if bold_headings else []), *ents] +_HEADING = re.compile(r"(?:\A|(?<=\n\n))([^\n•(]+?)(?= \(|\n|\Z)") # a section's first line, up to its brackets + +def headings_bold(text: str) -> list: + """Bold entities over each section's heading in Status's report (its first line's name: "Weather station" of "Weather station + (1:02am)"), as the report always showed them.""" + from telegram import MessageEntity + return [MessageEntity(MessageEntity.BOLD, utf16_len(text[:m.start(1)]), utf16_len(m.group(1))) for m in _HEADING.finditer(text)] -def _first_fitting(pieces: list[str], glue: str): - """(caption, entities) of as many of the first `pieces` (joined by `glue`) as fit a caption; None when even the first doesn't.""" - for n in range(len(pieces), 0, -1): - if fitted := caption_of(glue.join(pieces[:n]), bold_headings=True): + +def fitted_caption(text: str, link: tuple[str, str] | None = None) -> tuple[str, list]: + """(caption, entities) of `text` cut to fit a caption: whole lines dropped from the end, "…" in their place, while it is too long.""" + lines = text.strip().splitlines() + while lines: + if fitted := caption_of("\n".join(lines) + ("" if len(lines) == len(text.strip().splitlines()) else "\n…"), "", link): return fitted - return None + lines.pop() + return "…", [] -def report_caption(text: str): - """(caption, entities) for the report under its gauges: the whole report, else as many of its first sections as fit a caption, else as - many of its first section's lines (only a report longer than any yet, refreshed in its photo, needs cutting: a new one that long goes - apart from its picture).""" - sections = text.split("\n\n") - return _first_fitting(sections, "\n\n") or _first_fitting(sections[0].splitlines(), "\n") or (text.splitlines()[0][:CAPTION_LIMIT // 2], []) +def caption_of(text: str, title: str = "", link: tuple[str, str] | None = None): + """(caption, entities) for a photo: its title and the text, the link under them as a footer; None when that is longer than a caption + may be (CAPTION_LIMIT, counted as Telegram counts it).""" + body, ents = with_link(f"{title}\n\n{text}" if title else text, link) + if utf16_len(body) > CAPTION_LIMIT: + return None + return body, ents + + +def prompt_arguments(names: tuple[str, ...], words: str) -> dict[str, str]: + """A prompt command's words as its arguments, in order, the last taking the rest ("/chart rain 7d": reading "rain", period "7d"; + "/rainfall last week": period "last week"); none given: none (the prompt's defaults).""" + said, arguments = words.split(), {} + for i, name in enumerate(names): + if i >= len(said): + break + arguments[name] = " ".join(said[i:]) if i == len(names) - 1 else said[i] + return arguments async def _photos(msg: Message, photos: list[bytes], titles: list[str], buttons, alone: bool) -> tuple[bool, Message | None]: @@ -293,18 +363,17 @@ async def _photos(msg: Message, photos: list[bytes], titles: list[str], buttons, async def deliver(msg: Message, text: str, photos: list[bytes], link: tuple[str, str] | None = None, markup=None, - titles: list[str] | None = None, period_row=None, bold_headings: bool = False, photos_first: bool = False) -> Delivered: + titles: list[str] | None = None, period_row=None) -> Delivered: """Send the answer with any charts. One chart and an answer that fits a caption (CAPTION_LIMIT) go as one message, the picture with its - title and the answer; otherwise a chart carries only its title as its caption and any answer text is its own message, sent first - (photos_first: sent after the pictures, carrying the buttons: the report and its gauges). link = (label, url) adds a small italic link - line at the end of the text. markup (the button keyboard) rides on the last text, or on the single photo when there is no text (a - group of photos can't carry one). period_row (the period buttons) rides on a single photo instead, and then the keyboard waits. - bold_headings: the text is the report (or a pollen / forecast lookup), whose heading names are set in bold.""" + title and the answer; otherwise a chart carries only its title as its caption and any answer text is its own message, sent first. + link = (label, url) adds a small italic link line at the end of the text. markup (the button keyboard) rides on the last text, or on the + single photo when there is no text (a group of photos can't carry one). period_row (the period buttons) rides on a single photo + instead, and then the keyboard waits.""" text = text.strip() if photos: text = strip_chart_talk(text) titles = titles or [] - if text and len(photos) == 1 and (fitted := caption_of(text, titles[0] if titles else "", link, bold_headings)): + if text and len(photos) == 1 and (fitted := caption_of(text, titles[0] if titles else "", link)): body, ents = fitted # one chart and an answer that fits its caption: one message, the picture with its title and the answer buttons = period_row or markup try: @@ -313,67 +382,118 @@ async def deliver(msg: Message, text: str, photos: list[bytes], link: tuple[str, return Delivered(bool(markup) and not period_row, sent) except TelegramError as e: log.error("Couldn't send the chart with its answer (%s: %s); sending them apart", type(e).__name__, e) - sent = None - if photos and photos_first: - _, sent = await _photos(msg, photos, titles, None, not text) - on_text = bool(markup) and (not photos or photos_first) # the keyboard rides on the text + on_text = bool(markup) and not photos # the keyboard rides on the text if text: chunks = split_message(text) for i, chunk in enumerate(chunks): last = i == len(chunks) - 1 body, ents = with_link(chunk, link) if last else (chunk, []) - ents = [*(report.heading_entities(chunk) if bold_headings else []), *ents] await msg.reply_text(body, entities=ents or None, disable_web_page_preview=True, **({"reply_markup": markup} if on_text and last else {})) - if photos and not photos_first: + if photos: went, sent = await _photos(msg, photos, titles, period_row or markup, not text) return Delivered(bool(markup) and not period_row and went, sent) - return Delivered(on_text and bool(text), sent) - - -class Tasks: - """The tasks the bot runs in the background: one that stops with an error is logged as it does, and close() cancels them.""" - - def __init__(self): - self.running: set[asyncio.Task] = set() + return Delivered(on_text and bool(text), None) - def start(self, work: Coroutine) -> asyncio.Task: - task = asyncio.create_task(work, name=getattr(work, "__qualname__", None)) - self.running.add(task) - task.add_done_callback(self._ended) - return task - def _ended(self, task: asyncio.Task): - self.running.discard(task) - if not task.cancelled() and (error := task.exception()): - log.error("%s stopped: %s: %s", task.get_name(), type(error).__name__, error, exc_info=error if isinstance(error, BUGS) else None) - - async def close(self): - for task in self.running: - task.cancel() - await asyncio.gather(*self.running, return_exceptions=True) +class CallChart(NamedTuple): + """The chart a service call draws (Bot._draw_call).""" + png: bytes + title: str + caption: str | None # its words (the answer's caption, or answer) + newest: int | None # the time of its newest reading + drawn_by: dict | None # the call that draws it again + out: dict # the whole answer + dark: bool | None = None # drawn in the dark theme (None: as charts are drawn now) class Bot: - def __init__(self, cfg: Config, agent: Agent, sources: list[Source], state: AlertState, irrigation=None, tasks: Tasks | None = None): - """state: the known chats and their settings. irrigation: the Tuya client of the irrigation controller, when one is - configured (its button replaces Wind). tasks: where the bot's background work runs (the uploads of a chart's other periods); - its own when none is given.""" - self.cfg, self.agent, self.sources, self.state, self.irrigation = cfg, agent, sources, state, irrigation + def __init__(self, cfg: Config, agent: Agent, state: AlertState, irrigation=None, tasks: Tasks | None = None, *, + service: RemoteWeather): + """state: the known chats and their settings. irrigation: irrigation-mcp as the bot reaches it (lib/irrigation_remote.py: + status, water, delay, set_switch over its tools), when BOT_IRRIGATION_MCP_URL is set (its button replaces Wind). tasks: where the bot's background work runs (the uploads of a chart's other periods); + its own when none is given. service: ecobot-mcp as the bot reaches it (lib/weather.RemoteWeather, over MCP at BOT_MCP_URL), + whose tools the bot's own code paths call (the keyboard's charts, the Status picture, the alert charts and the period buttons), + whose prompts are the bot's commands too (/report, /chart ...: asked of the model), whose alert log the 🔄 under an alert's chart + finds its chart's drawn_by in, and which draws every picture the bot sends: the bot runs no sources and draws nothing. The model + is offered the same tools (agent.tools: lib/model_tools.py), with the server's instructions after the bot's persona.""" + self.cfg, self.agent, self.state, self.irrigation = cfg, agent, state, irrigation + self.weather = service self.tasks = tasks or Tasks() - self.watchdog = Watchdog(irrigation, state) if irrigation else None # closes the valve after a run, however it ends self.keyboard_version = templates.version(irrigation is not None) - self.admin_only = bool(getattr(cfg, "admin_only", False)) # ADMIN_ONLY: only the admins of the groups the bot is in may use it + self.admin_only = bool(getattr(cfg, "admin_only", False)) # BOT_ADMIN_ONLY: only the admins of the groups the bot is in may use it self.admins = Admins(state, getattr(cfg, "admin_chat_ids", ())) - self._refused: set[int] = set() # the senders ADMIN_ONLY has turned away, each logged once with its id (for ADMIN_CHAT_IDS) + self._refused: set[int] = set() # the senders BOT_ADMIN_ONLY has turned away, each logged once with its id (for BOT_ADMIN_CHAT_IDS) self.chats: dict[tuple, ChatState] = defaultdict(ChatState) - self.by_name = {s.name: s for s in sources} self.images = periods.ImageCache() # charts drawn lately, so toggling the period buttons is instant - self.alert_charts = pictures.AlertCharts(self.images, lambda: now_local(self.cfg.tz)) # the alerts' charts, kept with them - self.preloading: set[str] = set() # questions whose other periods are being uploaded (TELEGRAM_PRELOAD_CHAT) - self.last_used = 0.0 # when a message or a press last came in (monotonic; 0: never) + self.alert_charts = pictures.AlertCharts(self.images, tz=getattr(cfg, "tz", None)) # the alerts' charts, kept with them + self.preloading: set[str] = set() # the calls whose other periods are being uploaded (BOT_TELEGRAM_PRELOAD_CHAT) + self.fetching: dict[str, asyncio.Event] = {} # a period's chart being preloaded, by call_key: set once it is kept (or failed); a press waits for it + self.prompt_commands: dict = {} # ecobot-mcp's prompts offered as commands: name -> lib/weather.Prompt (publish_commands) + self._published: list | None = None # the command menu last given to Telegram self.preload_off = False # Telegram refused an upload to that chat (not a flood limit or a timeout): no more are tried until restart - self.charted = periods.Charted(state.charts, state.save) # the question behind each chart sent (kept across restarts) + self.charted = periods.Charted(state.charts, state.save) # the call behind each chart sent (kept across restarts) + + @property + def service(self): + """ecobot-mcp's tools, as it lists them now (lib/weather.RemoteTools).""" + return self.weather.service + + @property + def names(self) -> set[str]: + """The sources the service has ("Ecowitt", "AirGradient", "Forecast", "Pollen").""" + return self.weather.names + + # ---------- the service's tools, as the bot calls them ---------- + async def _service_call(self, tool: str, args: dict, ahead: bool = False) -> dict: + """A service tool's answer as data: its charts as drawn (AS_DRAWN, so its pictures are as they were), + a chart drawn ahead (nobody waiting) as a background request. {"error": ...} when it refuses or fails.""" + return (await self._call(tool, args, ahead))[0] + + async def _chart_call(self, tool: str, args: dict, ahead: bool = False, alone: bool = False) -> tuple[dict, ChartImage | None]: + """(a service tool's answer as data, as _service_call; its first chart drawn by the service, lib/weather.py chart_image: None + without one, or with more than one when `alone`). ChartNotDrawn when the chart came but can't be drawn.""" + return await self._call(tool, args, ahead, chart=True, alone=alone) + + async def _call(self, tool: str, args: dict, ahead: bool, chart: bool = False, alone: bool = False) -> tuple[dict, ChartImage | None]: + found = self.service.get(tool) + if found is None: + return {"error": f"There is no {tool} here."}, None + meta = {"chart_points": AS_DRAWN, **({"priority": BACKGROUND} if ahead else {})} + log.debug("Service call %s %s", tool, json.dumps(args, ensure_ascii=False), extra=QUOTES) + try: + if chart: + out, image = await self.weather.chart_image(tool, args, meta, alone=alone) + else: + out, image = json.loads(await found.call(args, meta)), None + except ChartNotDrawn: + raise + except ServiceUnreachable as e: # (a remote service while it is being reached again: said once the person asks, _answer) + (log.debug if ahead else log.warning)("Service tool %s: %s", tool, e) + return {"error": str(e)}, None + except Exception as e: + log.error("Service tool %s failed: %s: %s", tool, type(e).__name__, e, exc_info=isinstance(e, BUGS)) + return {"error": f"{type(e).__name__}: {e}"}, None + return (out, image) if isinstance(out, dict) else ({"error": "not an answer"}, None) + + def _instructions(self) -> str: + """The server's instructions (from server/discover).""" + return self.weather.instructions() + + def _titled(self, chart: dict) -> tuple[str, int | None]: + """(title, the time of its newest reading) of a chart given as data.""" + spec = from_json(chart) + return spec.caption(now_local(self.cfg.tz).date()), spec.newest + + async def _draw_call(self, tool: str, args: dict, ahead: bool = True) -> "CallChart | None": + """(PNG, title, its words, newest reading, drawn_by, the answer, dark) of the chart a call draws, drawn by the service; None when + it draws none (the refusal logged).""" + out, image = await self._chart_call(tool, args, ahead=ahead, alone=True) + if "error" in out or image is None: + log.debug("No chart from %s %s: %s", tool, args, out.get("error")) + return None + title, newest = await asyncio.to_thread(self._titled, image.chart) + return CallChart(image.png, title, out.get("caption") or out.get("answer"), newest, image.chart.get("drawn_by"), out, image.dark) def register(self, app): app.add_handler(CommandHandler(["start", "help"], self.on_start)) @@ -382,6 +502,7 @@ def register(self, app): app.add_handler(CommandHandler("alerts", self.on_alerts)) app.add_handler(CommandHandler("usage", self.on_usage)) app.add_handler(CommandHandler(list(templates.COMMANDS), self.on_ask)) + app.add_handler(MessageHandler(filters.COMMAND, self.on_command)) # any other command: ecobot-mcp's prompts (on_command) app.add_handler(CallbackQueryHandler(self.on_button)) # every button press, whatever its data: see on_button app.add_handler(MessageHandler(filters.ALL & ~filters.TEXT & ~filters.COMMAND, self.on_other), group=1) app.add_handler(ChatMemberHandler(self.on_membership, ChatMemberHandler.MY_CHAT_MEMBER)) @@ -409,7 +530,7 @@ def _sender(update: Update) -> tuple[str, int, str] | None: return ("user", update.effective_user.id, update.effective_user.full_name) if update.effective_user else None async def _allowed(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> bool: - """With ADMIN_ONLY on, only known group admins (and ADMIN_CHAT_IDS) get through; anyone else is told so, once, and False is + """With BOT_ADMIN_ONLY on, only known group admins (and BOT_ADMIN_CHAT_IDS) get through; anyone else is told so, once, and False is returned. A group the bot hears from is remembered first: it has to be known for its admins to count.""" chat = update.effective_chat if chat is not None and chat.type != ChatType.PRIVATE: @@ -418,7 +539,7 @@ async def _allowed(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> return True if (who := self._sender(update)) and who[1] not in self._refused: # once per sender in this run: the id is for the owner to list self._refused.add(who[1]) - log.info("%s: refused: %s %d (%s) is not a known group admin; add the id to ADMIN_CHAT_IDS to let them in", describe_source(update), *who) + log.info("%s: refused: %s %d (%s) is not a known group admin; add the id to BOT_ADMIN_CHAT_IDS to let them in", describe_source(update), *who) if update.callback_query is not None: await toast_quietly(update.callback_query, NOT_ADMIN_TOAST) elif update.effective_message is not None: @@ -450,26 +571,19 @@ async def _press(self, query) -> bool: await toast_quietly(query, STALE_BUTTON) return believed - def noticed(self): - """A message or a press came in: the bot is in use (used_lately).""" - self.last_used = time.monotonic() - - @property - def used_lately(self) -> bool: - return bool(self.last_used) and time.monotonic() - self.last_used <= USED_SECONDS - def buttons(self) -> dict: - """Every family of buttons the bot draws: the start of its data -> what handles it. The only way into any of them is on_button.""" + """Every family of buttons the bot draws: the start of its data -> what handles it. The only way into any of them is on_button. + (The 🔄 under the report written in code, rp:, and under the Telegram dashboard are no more: their presses are out of date. The + 🔄 under Status is st:.)""" return {"al:": self.on_alert_button, **({"ir:": self.on_irrigation_button} if self.irrigation else {}), - periods.PREFIX: self.on_period_button, report_menu.PREFIX: self.on_report_button} + periods.PREFIX: self.on_period_button, STATUS_PREFIX: self.on_status_button} async def on_button(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """The one place every button press comes in: believed (_press), a known family (a prefix nobody handles is refused, so a - new kind of button is dead until it is added to buttons()), allowed (ADMIN_ONLY), then handled.""" + new kind of button is dead until it is added to buttons()), allowed (BOT_ADMIN_ONLY), then handled.""" query = update.callback_query if query is None or not await self._press(query): return - self.noticed() handler = next((h for prefix, h in self.buttons().items() if query.data.startswith(prefix)), None) if handler is None: await toast_quietly(query, STALE_BUTTON) @@ -505,7 +619,7 @@ async def on_membership(self, update: Update, context: ContextTypes.DEFAULT_TYPE self.state.mark_gone(change.chat.id, f"bot {status}") def _alert_kinds(self) -> list[str]: - return menu.available_kinds(self.by_name, bool(self.irrigation)) + return menu.available_kinds(self.names, bool(self.irrigation)) async def on_alerts(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """/alerts: the alert settings, as buttons (🔔 Alerts and 🔊 Sound). /alerts on and /alerts off still subscribe or @@ -528,7 +642,8 @@ async def on_alerts(self, update: Update, context: ContextTypes.DEFAULT_TYPE): async def _help_and_alerts(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """What the bot can do, then the alert settings: the Help & Alerts button and /usage.""" - await update.effective_message.reply_text(templates.capabilities_text(self.by_name)) + about = await self._service_call("about", {}) + await update.effective_message.reply_text("\n".join(about.get("lines") or []) or templates.capabilities_text(self.names)) await self.on_alerts(update, context) async def on_usage(self, update: Update, context: ContextTypes.DEFAULT_TYPE): @@ -539,13 +654,123 @@ async def on_usage(self, update: Update, context: ContextTypes.DEFAULT_TYPE): await self._help_and_alerts(update, context) async def on_ask(self, update: Update, context: ContextTypes.DEFAULT_TYPE): - """/report, /status, /rain, /weather, /temperature, /humidity, /air_quality, /particulates, /wind: the same as the button of that name, - in a private chat or a group.""" + """/status, /rain, /weather, /temperature, /humidity, /air_quality, /particulates, /wind: the same as the button of that name, in a + private chat or a group.""" if not await self._allowed(update, context): return self.remember_chat(update) command = update.effective_message.text.split()[0].lstrip("/").split("@")[0].lower() - await self.respond(update, context, templates.COMMANDS[command]) + await self.press(update, context, templates.COMMANDS[command]) + + async def press(self, update: Update, context: ContextTypes.DEFAULT_TYPE, sentence: str): + """A keyboard button (or its command), answered at once without the model: Status is the gauges and the report prompt's answer + (status), a chart button its fixed call (templates.CALLS), drawn by ecobot-mcp.""" + if sentence == templates.STATUS: + await self.status(update, context) + else: + await self.respond(update, context, sentence, call=templates.call(sentence)) + + async def status(self, update: Update, context: ContextTypes.DEFAULT_TYPE): + """Status (the button, /status): a fixed read, no model (ecobot://status): one message, the Status picture (the station's three + gauges) with the report ecobot-mcp writes (the readings now, today's forecast, the pollen) as its caption, and a 🔄 under it + (on_status_button). Without the picture, the report alone, with the 🔄.""" + msg = update.effective_message + log.info("%s: Status", describe_source(update), extra=QUOTES) + started = time.monotonic() + try: + report, photo = await asyncio.wait_for(self.weather.status(), TURN_SECONDS) + except Exception as e: + log.warning("%s: Status couldn't be read: %s: %s", chat_tag(msg.chat_id), type(e).__name__, e, exc_info=isinstance(e, BUGS)) + with contextlib.suppress(TelegramError): + await msg.reply_text(SERVICE_DOWN if not await self.weather.ready(0) else "Sorry, I couldn't get the report. Please try again in a moment.") + return + report = report.strip() or "Nothing to report right now." + try: + if photo: + body, _ = fitted_caption(report) + await msg.reply_photo(photo, caption=body, caption_entities=headings_bold(body) or None, reply_markup=status_row()) + else: + await msg.reply_text(report, entities=headings_bold(report) or None, reply_markup=status_row(), disable_web_page_preview=True) + except TelegramError as e: + log.error("Couldn't send Status: %s: %s", type(e).__name__, e) + return + chat = self.chats[self._key(msg)] # (in the conversation, so a follow-up question knows what was shown) + chat.history = trim_history([*chat.history, {"role": "user", "content": self._content(msg, templates.STATUS, context.bot.id)}, + {"role": "assistant", "content": report}]) + log.info("%s: Status sent in %.1fs, %d chars%s", chat_tag(msg.chat_id), time.monotonic() - started, len(report), + "" if photo else " (no picture)") + + async def on_status_button(self, update: Update, context: ContextTypes.DEFAULT_TYPE): + """The 🔄 under Status: its picture and report read again (ecobot://status), in the same message. A failure leaves it as it was, + said in a toast.""" + query = update.callback_query + message = query.message + if query.data != STATUS_REFRESH: + await answer_query(query, STALE_BUTTON) + return + try: + report, photo = await asyncio.wait_for(self.weather.status(), TURN_SECONDS) + except Exception as e: + log.warning("%s: Status refresh failed: %s: %s", chat_tag(message.chat_id), type(e).__name__, e, exc_info=isinstance(e, BUGS)) + await answer_query(query, "Couldn't refresh, please try again", show_alert=True) + return + report = report.strip() or "Nothing to report right now." + try: + body = fitted_caption(report)[0] if getattr(message, "photo", None) else report + bold = headings_bold(body) or None + if getattr(message, "photo", None) and photo: + await message.edit_media(InputMediaPhoto(photo, caption=body, caption_entities=bold), reply_markup=status_row()) + elif getattr(message, "photo", None): # (no picture this time: the old one stays, its words new) + await message.edit_caption(caption=body, caption_entities=bold, reply_markup=status_row()) + else: + await message.edit_text(body, entities=bold, reply_markup=status_row(), disable_web_page_preview=True) + except BadRequest as e: + if "not modified" not in str(e).lower(): + log.error("Couldn't refresh Status: %s: %s", type(e).__name__, e) + await answer_query(query, "Couldn't refresh, please try again") + return + except TelegramError as e: + log.error("Couldn't refresh Status: %s: %s", type(e).__name__, e) + await answer_query(query, "Couldn't refresh, please try again") + return + await answer_query(query, "Refreshed") + + async def on_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE): + """Any command the bot has no handler of its own for: one of ecobot-mcp's prompts (prompt_commands), whose words after the command + fill its arguments (prompt_arguments), or follow its question when it takes none: the prompt's question is asked of the model as a + typed question. Any other command, or one addressed to another bot ("/chart@otherbot"), is left alone; while ecobot-mcp hasn't + been reached (its prompts unknown), a command not the bot's own is told so (SERVICE_DOWN).""" + msg = update.effective_message + if not msg or not msg.text: + return + head, *rest = msg.text.strip().split(maxsplit=1) + words = rest[0] if rest else "" + name, _, to = head.lstrip("/").partition("@") + if to and to.lower() != (getattr(context.bot, "username", "") or "").lower(): + return + found = self.prompt_commands.get(name.lower()) + if found is None: + if not self.prompt_commands and not await self.weather.ready(0) and await self._allowed(update, context): + await msg.reply_text(SERVICE_DOWN) # (ecobot-mcp not reached yet: its prompts, so its commands, aren't known) + return + if not await self._allowed(update, context): + return + self.remember_chat(update) + arguments = prompt_arguments(found.arguments, words) + try: + question = await self.weather.prompt(found.name, arguments) + except ServiceUnreachable: + log.warning("%s: %s", chat_tag(msg.chat_id), UNREACHABLE) + await msg.reply_text(SERVICE_DOWN) + return + except Exception as e: # (refused: a required argument missing, a prompt gone since the menu was set) + why = getattr(e, "message", None) or str(e) + log.info("%s: /%s %s refused: %s", describe_source(update), found.name, words, why, extra=QUOTES) + await msg.reply_text(f"Sorry, /{found.name} didn't work: {why}") + return + if words and not found.arguments: # (a prompt that takes no words: they go with its question, not lost) + question = f"{question} ({words})" + await self.respond(update, context, question) @staticmethod def _alerts_named(kind: str) -> str: @@ -558,8 +783,8 @@ async def on_alert_button(self, update: Update, context: ContextTypes.DEFAULT_TY query = update.callback_query action, *rest = (query.data or "").split(":")[1:] or [""] # the grammar is in alerts/menu.py kind = parent = opened = None - if action == "refresh" and len(rest) == 1: - await self._redraw_alert(query, rest[0]) + if action == "refresh" and (len(rest) == 1 or len(rest) == 2 and rest[1].isdigit()): # al:refresh:<kind>[:<id>] + await self._redraw_alert(query, rest[0], int(rest[1]) if len(rest) == 2 else None) return if action == "open" and len(rest) in (1, 2): # al:open:<menu>[:<parent>] opened, parent = rest[0], rest[1] if len(rest) == 2 else None @@ -597,7 +822,8 @@ async def on_alert_button(self, update: Update, context: ContextTypes.DEFAULT_TY loud = self.state.loud(chat.id) if private else None await answer_query(query, toast) if parent: # an alert: only its buttons change - await self._edit(query, None, menu.alert_keyboard(parent, muted, loud, opened, refresh=self._redrawable(message, parent))) + await self._edit(query, None, menu.alert_keyboard(parent, muted, loud, opened, refresh=self._redrawable(message, parent), + event=self._alert_event(message))) else: # the /alerts message: its on/off summary is kept current too await self._edit(query, menu.title(muted, kinds), menu.keyboard(muted, kinds, opened, loud)) @@ -606,19 +832,42 @@ def _redrawable(message, kind: str) -> bool: """Does this alert carry a chart its Refresh can draw again (it went out as a picture)?""" return kind in pictures.CHARTS and bool(getattr(message, "photo", None)) - async def _redraw_alert(self, query, kind: str): + @staticmethod + def _alert_event(message) -> int | None: + """The alert-log id the 🔄 under this alert names (al:refresh:<kind>:<id>), so its buttons keep it when they are redrawn.""" + markup = getattr(message, "reply_markup", None) + for row in getattr(markup, "inline_keyboard", None) or (): + for b in row: + parts = (getattr(b, "callback_data", None) or "").split(":") + if parts[:2] == ["al", "refresh"] and len(parts) == 4 and parts[3].isdigit(): + return int(parts[3]) + return None + + async def _alert_call(self, kind: str, event: int | None) -> tuple[str, dict] | None: + """The call that draws an alert's chart again: its chart's drawn_by, from the alert log (`event`: its id); None without one (an + alert sent before the log, or one dropped from it), when the type's own chart is drawn.""" + found = await self.weather.alert(event) if event is not None else None + drawn_by = (found or {}).get("chart", {}).get("drawn_by") if found and found.get("kind") == kind else None + return (drawn_by["tool"], drawn_by["arguments"]) if drawn_by else None + + async def _redraw_alert(self, query, kind: str, event: int | None = None): """A press on Refresh under an alert's chart: the chart with the latest readings, in the same message: the one drawn ahead since the - message was last changed (AlertCharts.newer_than; Telegram's copy when it was uploaded ahead), else drawn now and kept. The alert's - text (what happened, as it was sent) and its buttons stay as they are.""" + message was last changed (AlertCharts.newer_than; Telegram's copy when it was uploaded ahead), else drawn now (the alert's chart's + drawn_by replayed, found in the alert log by its id `event`; the type's chart for an alert from before the log) and kept. The + alert's text (what happened, as it was sent) and its buttons stay as they are.""" message = query.message - source = self.by_name.get(menu.TYPES[kind][1]) if kind in menu.TYPES else None - if source is None or not self._redrawable(message, kind): # an alert of a type, or from a source, the bot no longer has + there = kind in menu.TYPES and menu.TYPES[kind][1] in self.names + if not there or not self._redrawable(message, kind): # an alert of a type, or from a source, the bot no longer has await answer_query(query, STALE_BUTTON) return photo, drawn = self.alert_charts.newer_than(kind, message), False if photo is None: try: - picture = await asyncio.wait_for(pictures.chart(source, pictures.CHARTS[kind], source.tz), TURN_SECONDS) + if call := await self._alert_call(kind, event): + made = await asyncio.wait_for(self._draw_call(*call, ahead=False), TURN_SECONDS) + picture = pictures.Picture(made[0], made[1], made[3], made[4], getattr(made, "dark", None)) if made else None + else: + picture = await asyncio.wait_for(pictures.chart(pictures.CHARTS[kind], self.cfg.tz, self.weather), TURN_SECONDS) except TimeoutError: picture = None if picture is None: # (pictures.chart has said why) the message stays as it was @@ -630,7 +879,7 @@ async def _redraw_alert(self, query, kind: str): edited = await _edit_quietly(query.edit_message_media(InputMediaPhoto(photo, caption=message.caption, caption_entities=message.caption_entities or None), reply_markup=message.reply_markup)) if drawn: - self.alert_charts.sent(kind, edited, alerted=False) + self.alert_charts.sent(kind, edited) log.debug("%s: the %s alert's chart %s", chat_tag(message.chat.id), kind, "drawn again" if drawn else "sent from the one drawn ahead") # ---------- irrigation ---------- @@ -659,9 +908,14 @@ async def send_irrigation(self, msg: Message): async def _controller(self, query, request, what: str): """What the controller answers `request` with (its status, or the toast of an action). When it can't be reached: logged as - "Irrigation {what} failed", said in a toast, and None (the press goes no further).""" + "Irrigation {what} failed", said in a toast, and None (the press goes no further). Refused (water while a pause began since the + status was read): the reason said instead.""" try: return await request + except IrrigationRefused as e: + log.info("Irrigation %s refused: %s", what, e) + await answer_query(query, irrigation_menu.PAUSED_ERROR if e.paused else fit(str(e), TOAST_LIMIT), show_alert=not e.paused) + return None except IrrigationError as e: log.warning("Irrigation %s failed: %s", what, e) await answer_query(query, "Couldn't reach the irrigation controller", show_alert=True) @@ -669,9 +923,7 @@ async def _controller(self, query, request, what: str): async def _irrigation_act(self, action: str, arg: str, chat_id: int) -> str: """Do what a button asks. Returns the toast to show, or "" for a button that means nothing. Raises IrrigationError.""" - if action == "water" and arg.isdigit() and int(arg) in irrigation_menu.WATER_MINUTES: - if self.watchdog: # first: a command whose reply is lost may still have opened the valve - self.watchdog.arm(int(arg)) + if action == "water" and arg.isdigit() and int(arg) in irrigation_menu.WATER_MINUTES: # (irrigation-mcp watches the run) await self.irrigation.water(int(arg)) return f"Watering for {arg} minutes" if action == "delay" and arg in irrigation_menu.DELAYS: @@ -679,8 +931,6 @@ async def _irrigation_act(self, action: str, arg: str, chat_id: int) -> str: return "Unpaused" if arg == "cancel" else f"Paused {arg}" if action == "sw" and arg == "off": # there is no On: a run is always timed (Water). An old message's On button does nothing await self.irrigation.set_switch(False) - if self.watchdog: - self.watchdog.disarm() return "Switched off" if action in irrigation_menu.ALERTS and arg in ("on", "off") and chat_id in self.state.chats: kind, name = irrigation_menu.ALERTS[action] @@ -747,90 +997,98 @@ async def _edit(query, text: str | None, markup, entities=None): else: await _edit_quietly(query.edit_message_text(text, reply_markup=markup, **({"entities": entities} if entities else {}))) - async def on_report_button(self, update: Update, context: ContextTypes.DEFAULT_TYPE): - """A press on 🔄 under the report (or the dashboard: _redraw_dashboard): read everything again and redraw the report in the - same message. The chat's conversation is not touched (this is not a new question).""" - query = update.callback_query - if query.data == report_menu.DASHBOARD: - await self._redraw_dashboard(query) - return - read = intent.read("Report", now_local(self.cfg.tz), self.by_name) - pictured = bool(getattr(getattr(query, "message", None), "photo", None)) # the report is the caption of its gauges: they are drawn again too - try: - text, gauge = await self._report(read, Turn(text="Report"), pictured) - except Exception as e: # the message stays as it was - log.warning("Report refresh failed: %s", e) - await answer_query(query, "Couldn't refresh, please try again", show_alert=True) - return - await answer_query(query) # no toast: the times in the headings show what changed - if pictured: - await self._recaption(query, text, gauge) - else: - await self._edit(query, text, report_menu.keyboard(), report.heading_entities(text)) - - async def _redraw_dashboard(self, query): - """A press on 🔄 under the dashboard: its gauges drawn again with the latest readings, and the time in its title, in the same - message. When the station doesn't answer, the message stays as it was.""" - eco = self.by_name.get("Ecowitt") - if eco is None or not getattr(getattr(query, "message", None), "photo", None): # no station any more, or not the dashboard's picture - await answer_query(query, STALE_BUTTON) - return - try: - answer = await asyncio.wait_for(self._dashboard(eco), TURN_SECONDS) - except Exception as e: - log.warning("Dashboard refresh failed: %s: %s", type(e).__name__, e) - answer = None - if answer is None or not answer.ok: - await answer_query(query, "Couldn't refresh, please try again", show_alert=True) - return - await answer_query(query) # no toast: the time in the title shows it was drawn again - await _edit_quietly(query.edit_message_media(InputMediaPhoto(answer.photos[0], caption=answer.titles[0]), - reply_markup=report_menu.dashboard_keyboard())) - - @staticmethod - async def _recaption(query, text: str, photo: bytes | None): - """Put the report's new text, and its gauges drawn again, into the photo message its Refresh was pressed under (no new picture: - the caption alone).""" - body, ents = report_caption(text) - if photo: - await _edit_quietly(query.edit_message_media(InputMediaPhoto(photo, caption=body, caption_entities=ents or None), reply_markup=report_menu.keyboard())) - else: - await _edit_quietly(query.edit_message_caption(caption=body, caption_entities=ents or None, reply_markup=report_menu.keyboard())) - async def on_period_button(self, update: Update, context: ContextTypes.DEFAULT_TYPE): - """A press on 1D / 7D / 1M / 3M / 1Y under a chart: ask the chart's question again for that period and put the new chart - in the same message.""" + """A press on a period button under a chart: the chart's call (its drawn_by) replayed with that period, by the service, and the + new chart put in the same message (from the picture cache when it was drawn lately). A replay the service refuses shows its + refusal on the button. A chart recorded before its drawn_by was kept (its question, from before step 3) is out of date.""" query = update.callback_query - days = periods.days_in(query.data) message = query.message - question = self.charted.get(message.chat_id, message.message_id) if days and message else None - if not question: - await answer_query(query, "That chart is out of date, please ask again") + record = self.charted.get(message.chat_id, message.message_id) if message else None + if isinstance(record, dict) and record.get("drawn_by"): + answered: list[str] = [] # what the press was answered with (Telegram takes one answer per press) + try: + await self._replay(query, message, record, context.bot, answered) + except Exception as e: # (a chart that fails to draw, Telegram failing): said, never raised + log.error("Couldn't redraw a chart for its period button (%s: %s)", type(e).__name__, e, exc_info=isinstance(e, BUGS)) + if not answered: # on the button + await toast_quietly(query, CHART_FAILED) + else: # the button already said "Drawing ...": a second answer would be refused, so in the chat + with contextlib.suppress(TelegramError): + await message.reply_text(CHART_FAILED) return - now = now_local(self.cfg.tz) - if intent.period_days(question, now) == days: # the chart already shows this period - await answer_query(query) + await answer_query(query, OUT_OF_DATE) + + async def _replay(self, query, message: Message, record: dict, bot, answered: list[str] | None = None): + """A period button under a chart the service drew: its drawn_by replayed with the period pressed, into the same message. + answered: given the "Drawing ..." toast once it is sent (the press is answered once, even when the cached chart can't be put + in and it is drawn again).""" + answered = [] if answered is None else answered + + async def drawing(label: str): + if not answered: + await answer_query(query, f"Drawing {label}...") + answered.append(label) + + drawn_by, words = record["drawn_by"], bool(record.get("words")) + period = periods.period_in(query.data) + listed = {p["period"]: p["label"] for p in drawn_by.get("periods") or ()} + reload = period == periods.RELOAD and not listed # the 🔄 under a chart with no periods that runs to now: drawn again as it is + if period not in listed and not reload: + await answer_query(query, OUT_OF_DATE) return - await answer_query(query, f"Drawing {periods.NAMES[days]}...") - asked = intent.with_period(question, days, now) - log.debug("Period button %s: %s", periods.NAMES[days], question, extra=QUOTES) - key = self.images.key(asked, days, now) - if cached := self.images.get(key): # drawn lately: no new question - photo, title = cached + now = now_local(self.cfg.tz) + refresh = False # the chart's own shaded 1D pressed: drawn again with the latest readings + if not reload and periods.own_period(drawn_by, now, self.cfg.tz) == period: # the chart already shows this period + if period != periods.REFRESHED or not periods.ends_now(drawn_by, now, self.cfg.tz): # (longer: a few minutes more barely show) + await answer_query(query) + return + refresh = True + tool = drawn_by["tool"] + args = dict(drawn_by["arguments"]) if reload or refresh else periods.with_period(drawn_by, period) + label = "again" if reload else listed[period] + key = periods.call_key(tool, args) + log.debug("Period button %s: %s", label, key, extra=QUOTES) + if not (reload or refresh) and (fetching := self.fetching.get(key)) is not None: # being preloaded: that one waited for, not asked twice + await drawing(label) + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(fetching.wait(), TURN_SECONDS) + if not (reload or refresh) and (held := self.images.held(key)) is not None and held.drawn_by: # drawn lately: not asked again + await drawing(label) began = time.monotonic() - if await self._redraw(message, "", photo, title, periods.keyboard(days), asked, key, TelegramError, "drawing it again"): - self.preload_soon(context.bot, asked) + row = periods.periods_keyboard(held.drawn_by, period, now, self.cfg.tz) + if await self._redraw(message, (held.caption or "") if words else "", held.photo, held.title, row, + {"drawn_by": held.drawn_by, "words": words}, key, TelegramError, "drawing it again"): + self.preload_soon(bot, held.drawn_by) log.debug("Period button: cached chart sent in %.0f ms%s", (time.monotonic() - began) * 1000, - " (Telegram's copy)" if isinstance(photo, str) else "") + " (Telegram's copy)" if isinstance(held.photo, str) else "") return - await self.respond(update, context, asked, redraw=message) - - async def _redraw(self, message: Message, reply: str, photo: bytes | str, title: str, row, question: str, key: str | None = None, + try: # (drawn before the toast, so a failure can be toasted) + out, image = await asyncio.wait_for(self._chart_call(tool, args), TURN_SECONDS) + except TimeoutError: + out, image = {"error": "That took too long, please try again"}, None + if "error" in out or image is None: # (a chart that came without its picture: ecobot-mcp couldn't draw it) + why = out.get("error") or (CHART_FAILED if out.get("charts") else "No chart came of it for that period") + await toast_quietly(query, fit(str(why), TOAST_LIMIT)) + return + png, (title, newest) = image.png, await asyncio.to_thread(self._titled, image.chart) + await drawing(label) + drawn = image.chart.get("drawn_by") or {"tool": tool, "arguments": args, "periods": drawn_by.get("periods")} + text = out.get("caption") or out.get("answer") or "" + self.images.put(key, png, title, text or None, newest=newest, drawn_by=drawn, dark=image.dark) + row = periods.periods_keyboard(drawn, period, now, self.cfg.tz) + if not await self._redraw(message, text if words else "", png, title, row, {"drawn_by": drawn, "words": words}, key): + sent = await deliver(message, text if words else "", [png], titles=[title], period_row=row) + if sent.photo: + self.charted.remember(message.chat_id, sent.photo.message_id, {"drawn_by": drawn, "words": words}) + self.images.sent(key, sent.photo) + self.preload_soon(bot, drawn) + + async def _redraw(self, message: Message, reply: str, photo: bytes | str, title: str, row, record: str | dict, key: str | None = None, refused=BadRequest, then: str = "sending a new one") -> bool: """Put a new chart into the message a period button was pressed under (its answer text, if any, follows as a message of its own, unless it fits the caption: then the chart's caption is its title and the answer, as deliver sends them). False when Telegram refuses (an error of the `refused` kind, logged with what is done `then`): the chart is then sent as a new message, - or drawn again. key: where the image cache keeps it.""" + or drawn again. key: where the image cache keeps it. record: what drew it (periods.Charted), remembered for its buttons.""" text = strip_chart_talk(reply.strip()) fitted = caption_of(text, title) if text else None in_caption = fitted is not None @@ -842,7 +1100,7 @@ async def _redraw(self, message: Message, reply: str, photo: bytes | str, title: except refused as e: log.warning("Couldn't edit the chart in place (%s); %s", e, then) return False - self.charted.remember(message.chat_id, message.message_id, question) + self.charted.remember(message.chat_id, message.message_id, record) if text and not in_caption: await deliver(message, reply, []) return True @@ -877,11 +1135,34 @@ async def on_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE): if private: self.state.set_keyboard(update.effective_chat.id, self.keyboard_version) - @staticmethod - async def publish_commands(tg_bot) -> None: - """At startup: give Telegram the command menu (templates.MENU). A refusal is logged and the bot carries on.""" + def commands(self) -> list[tuple[str, str]]: + """The command menu: the bot's own (templates.MENU), with one command per ecobot-mcp prompt (its description) after the charts'. + A prompt whose name isn't a command Telegram takes (COMMAND_NAME), or is one of the bot's own, is left out with a warning; the + prompts kept are prompt_commands, what on_command answers.""" + kept: dict = {} + for found in getattr(self.weather, "prompts", None) or (): + if not COMMAND_NAME.fullmatch(found.name): + log.warning("ecobot-mcp's prompt %r isn't a name Telegram takes as a command (lowercase letters, digits and _, at most 32): " + "it is left out of the bot's commands", found.name) + elif found.name in templates.OWN_COMMANDS: + log.warning("ecobot-mcp's prompt %r has the name of one of the bot's own commands: it is left out of them", found.name) + else: + kept.setdefault(found.name, found) + self.prompt_commands = kept + own = list(templates.MENU) + at = next((i for i, (name, _) in enumerate(own) if name == "alerts"), len(own)) # (the settings last) + offered = [(name, fit(" ".join((p.description or name).split()), 256).ljust(3, ".")) for name, p in kept.items()] + return [*own[:at], *offered, *own[at:]][:MAX_COMMANDS] + + async def publish_commands(self, tg_bot) -> None: + """Give Telegram the command menu (commands): at start, and again whenever ecobot-mcp's prompts are read (each connection, and + when it says they changed), when the menu changed. A refusal is logged and the bot carries on.""" + menu = self.commands() + if menu == self._published: + return try: - await tg_bot.set_my_commands([BotCommand(name, description) for name, description in templates.MENU]) + await tg_bot.set_my_commands([BotCommand(name, description) for name, description in menu]) + self._published = menu except Exception as e: log.warning("Couldn't set the command menu: %s: %s", type(e).__name__, e) @@ -932,15 +1213,16 @@ async def on_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE): private = msg.chat.type == ChatType.PRIVATE if private and not await self._allowed(update, context): # before remember_chat: a stranger never becomes an alert chat return - self.noticed() self.remember_chat(update) if private: if self.irrigation and (msg.text.strip() == templates.IRRIGATION or irrigation_menu.asked(msg.text)): # the controller's status and buttons (no model needed) await self.send_irrigation(msg) elif msg.text.strip() == templates.CAPABILITIES: # what it measures, then the alert settings (no model needed) await self._help_and_alerts(update, context) - else: - await self.respond(update, context, templates.sentence(msg.text) or msg.text) + elif sentence := templates.sentence(msg.text): # a keyboard button: answered at once, without the model + await self.press(update, context, sentence) + else: # anything typed: the model's + await self.respond(update, context, msg.text) return # Group / supergroup: only respond when addressed mention = re.compile(rf"@{re.escape(context.bot.username)}\b", re.IGNORECASE) @@ -968,35 +1250,6 @@ def _content(self, msg: Message, text: str, bot_id: int) -> str: sender = msg.from_user.full_name if msg.from_user else "Someone" return f"{sender} ({reply}): {text}" if reply else f"{sender}: {text}" - async def _written_in_code(self, read, turn: Turn) -> str: - """The report ("weather now") from the fast path's tool calls, made together; lib/report.py lays it out.""" - calls = [read.fast[:2], *read.more] - results = await self.agent.tools.call_all(calls, turn) - by_tool = {name: result for (name, _), result in zip(calls, results)} - if read.report: - return report.report(by_tool, now_local(self.cfg.tz).date()) - return report.weather_now(by_tool["weather_now"]) or "The weather station isn't answering right now." - - async def _report(self, read, turn: Turn, gauges: bool) -> tuple[str, bytes | None]: - """The report (or "weather now") written in code and, with `gauges`, its picture drawn alongside (None without one), in TURN_SECONDS.""" - written = self._written_in_code(read, turn) - if gauges: - return tuple(await asyncio.wait_for(asyncio.gather(written, self._status_gauges()), TURN_SECONDS)) - return await asyncio.wait_for(written, TURN_SECONDS), None - - async def _status_gauges(self) -> bytes | None: - """The report's picture: the weather station's temperature, humidity and rain gauges (ecowitt.dashboard.STATUS). None without the - station, or when they can't be drawn (the report then goes as text alone).""" - station = self.by_name.get("Ecowitt") - if station is None: - return None - try: - sheet = await station.dashboard(STATUS) - return await asyncio.to_thread(gauges.render, sheet) if sheet else None - except Exception as e: - log.error("The report's gauges failed (%s: %s); sending it without them", type(e).__name__, e, exc_info=isinstance(e, BUGS)) - return None - async def _warn(self, msg: Message, tokens: int): """A heads-up before a big job: the question has pulled in a lot of data. Sent now, silently; the answer follows by itself.""" text = f"\u26a0\ufe0f That's pulling in about {tokens / 1000:.0f}k tokens of data, so it will take a little longer. Working on it..." @@ -1004,113 +1257,108 @@ async def _warn(self, msg: Message, tokens: int): with contextlib.suppress(TelegramError): await msg.reply_text(text) - async def _chart_in_code(self, read, turn: Turn) -> str | None: - """A chart asked for plainly: the tool draws it and the caption is written here. None (the model then takes the - question) when there is nothing to caption.""" - calls = [read.fast[:2], *read.more] - results = await self.agent.tools.call_all(calls, turn) - caption = report.chart_caption(read.fast[0], read.fast[1], results[0], turn, self.cfg.tz) - if caption is None: - turn.charts.clear() - turn.forecast_shown.clear() - return caption - - async def _dashboard(self, ecowitt) -> Answer: - """The station's gauges as one picture, sent with just its title (no period buttons: it is the state now).""" - sheet = await ecowitt.dashboard() - if sheet is None: - return Answer("The weather station isn't answering right now.", ok=False) - now = now_local(self.cfg.tz) - title = f"Weather station dashboard, {day_text(now)} {clock_text(now)}" - return Answer(title, [await asyncio.to_thread(gauges.render, sheet)], [title], silent=True) - - async def _lookup_in_code(self, read, turn: Turn) -> str | None: - """A plain lookup (a reading, the air, the pollen, the forecast, what the bot can do) answered from its one tool result; None - (the model then takes the question) when it can't be.""" - if read.lookup == "about": - return templates.capabilities_text(self.by_name) - name, args = read.fast[:2] - result = await self.agent.tools.call(name, json.dumps(args), turn) - return report.lookup(read.lookup, result, read.lookup_arg, read.sides, now_local(self.cfg.tz).date()) - - async def _ask_model(self, working: list[dict], system: str, read, turn: Turn, draft, on_heavy=None) -> str: - """The model's answer. If it has not answered in TURN_SECONDS, ask again once with one reasoning step less (medium > low > - none), for RETRY_SECONDS; a question already at no reasoning just times out.""" - first = [*([read.fast[:2], *read.more] if read.fast else []), *read.extra] or None - before, effort, budget, retried = list(working), read.effort, TURN_SECONDS, False + async def _chart_in_code(self, call: tuple[str, dict]) -> Made | str: + """A keyboard button's chart (its fixed call): the service draws it and its caption goes with it. When it gives neither, what to + say instead: the service's refusal, or NOT_DRAWN.""" + tool, args = call + try: + out, pictures = await self.weather.call_images(tool, args, {"chart_points": AS_DRAWN}) + except ServiceUnreachable as e: + log.warning("Service tool %s: %s", tool, e) + return SERVICE_DOWN + except Exception as e: + log.error("Service tool %s failed: %s: %s", tool, type(e).__name__, e, exc_info=isinstance(e, BUGS)) + return NOT_DRAWN + if not isinstance(out, dict): + return NOT_DRAWN + if "error" in out: + return str(out["error"]) + text = out.get("caption") or out.get("answer") + return Made(text, pictures) if pictures or text else NOT_DRAWN + + @staticmethod + def _complete(calls: list[dict], results: list[str]) -> str | None: + """The model loop's finish: when every call of a step gave a complete result (docs/ecobot-mcp.md 3.7: its chart and its ready + reply), their replies in order are the answer and the model is asked nothing more; else None, and the model answers as usual.""" + return complete_reply(results) + + async def _ask_model(self, working: list[dict], system: str, effort: str, turn: Turn, draft, on_heavy=None) -> str: + """The model's answer, with the service's tools. If it has not answered in TURN_SECONDS, ask again once with one reasoning step + less (medium > low > none), for RETRY_SECONDS; a question already at no reasoning just times out. A step whose results are all + complete ends the turn with their replies (_complete). No draft streams once a result has a chart: the reply is its caption.""" + before, budget, retried = list(working), TURN_SECONDS, False + charted = lambda: any(r and r[2].get("charts") for r in turn.results) while True: try: return await asyncio.wait_for( - self.agent.run(working, system, effort, first_call=first, tool_choice=read.tool_choice, turn=turn, - on_heavy=on_heavy, - **({"on_text": lambda text: None if turn.chart_asked or turn.charts else draft.update(text)} if draft else {})), - budget) + self.agent.run(working, system, effort, tool_choice="auto", turn=turn, on_heavy=on_heavy, finish=self._complete, + **({"on_text": lambda text: None if charted() else draft.update(text)} if draft else {})), + budget) except TimeoutError: lower = intent.lower_effort(effort) if not lower or retried: raise log.warning("No answer in %ds at reasoning %s; asking again at %s", budget, effort, lower) working[:] = before # the unfinished attempt's turns are dropped + turn.results.clear() + turn.pictures.clear() + turn.result_chars = 0 effort, budget, retried = lower, RETRY_SECONDS, True - async def _draw_ahead(self, text: str, now) -> tuple[str, bytes, str, str, int] | None: - """(image key, PNG, title, write-up, the time of the newest reading drawn) of the chart `text` asks for when it is one made in code - with its own words as its key; None otherwise. Raises when it can't be drawn. Nobody is waiting: its requests are not urgent and its - logs are quiet.""" - read = intent.read(text, now, self.by_name) - key = self.images.canonical(text, now) - if not (read.chart_in_code and key): # not a chart made in code ("Report"), or a source that isn't there - return None - turn = Turn.of(read, text, ahead=True) - caption = await asyncio.wait_for(self._chart_in_code(read, turn), TURN_SECONDS) - if caption is None or len(turn.charts) != 1: - raise ValueError("no chart came of it") - png = await asyncio.to_thread(render_chart, turn.charts[0], self.cfg.tz) - return key, png, turn.charts[0].caption(now.date()), caption, turn.charts[0].newest - - def preload_soon(self, bot, question: str): - """With TELEGRAM_PRELOAD_CHAT set, upload the other periods of this chart's question in the background.""" + def preload_soon(self, bot, drawn_by: dict | None): + """After a chart is sent: the chart of each other period its drawn_by lists fetched from ecobot-mcp in the background (and, with + BOT_TELEGRAM_PRELOAD_CHAT set, uploaded there), so its period buttons answer at once.""" chat = getattr(self.cfg, "telegram_preload_chat", None) - if chat is None or self.preload_off or question in self.preloading: + key = periods.drawn_key(drawn_by) + if not drawn_by or not drawn_by.get("periods") or key in self.preloading: return - self.preloading.add(question) - self.tasks.start(self.preload(bot, chat, question)) - - async def preload(self, bot, chat: int, question: str): - """Upload (silently, to `chat`) the chart for each other period of `question`, so a press of a period button edits the message by - Telegram's copy and uploads nothing. Nothing holds it back: each period is drawn and uploaded on its own, the moment it can be, - whatever else is being answered.""" + self.preloading.add(key) + self.tasks.start(self.preload(bot, None if self.preload_off else chat, drawn_by)) + + async def preload(self, bot, chat: int | None, drawn_by: dict): + """The chart for each other period of a chart's drawn_by, each its call replayed with that period, fetched and kept (in the + background: nobody is waiting) and, with a `chat` (BOT_TELEGRAM_PRELOAD_CHAT), uploaded to it silently, so a press of a period + button edits the message with the chart held (by Telegram's copy, when uploaded) and asks ecobot-mcp nothing. Nothing holds it + back: each period is fetched and uploaded on its own, the moment it can be, whatever else is being answered.""" started, done, skipped = time.monotonic(), set(), [] + tool = drawn_by["tool"] try: - now = now_local(self.cfg.tz) - own = intent.period_days(question, now) - asked = {days: intent.with_period(question, days, now) for days in periods.PERIODS if days != own} - asked = {days: text for days, text in asked.items() if not self.images.has_copy(self.images.key(text, days, now))} - - async def upload(days, text): + own = periods.own_period(drawn_by, now_local(self.cfg.tz), self.cfg.tz) + asked = {p["period"]: periods.with_period(drawn_by, p["period"]) for p in drawn_by.get("periods") or () if p["period"] != own} + held = self.images.has_copy if chat is not None else (lambda key: self.images.held(key) is not None) + asked = {p: args for p, args in asked.items() if not held(periods.call_key(tool, args))} + + async def upload(period, args): + key = periods.call_key(tool, args) + self.fetching[key] = fetched = asyncio.Event() try: - drawn = await self._draw_ahead(text, now) + drawn = await asyncio.wait_for(self._draw_call(tool, args), TURN_SECONDS) + if drawn is None: + return + png, title, caption, newest, by = drawn[:5] + self.images.put(key, png, title, caption, ttl=self.images.PRELOAD_TTL, newest=newest, drawn_by=by, dark=drawn.dark) except Exception as e: - log.debug("Couldn't draw %r to preload: %s: %s", text, type(e).__name__, e) - return - if drawn is None: + log.debug("Couldn't draw %s to preload: %s: %s", key, type(e).__name__, e) return - key, png, title, caption, newest = drawn - self.images.put(key, png, title, caption, ttl=self.images.PRELOAD_TTL, newest=newest) - if self.preload_off: # an upload was refused meanwhile + finally: + fetched.set() + if self.fetching.get(key) is fetched: + del self.fetching[key] + if chat is None or self.preload_off: # (fetched only; or an upload was refused meanwhile) return if (why := await self._upload_ahead(bot, chat, key, png, title)) is not None: skipped.append(why) elif not self.preload_off: - done.add(days) + done.add(period) - await asyncio.gather(*(upload(days, text) for days, text in asked.items())) + await asyncio.gather(*(upload(period, args) for period, args in asked.items())) if skipped: - log.warning("TELEGRAM_PRELOAD_CHAT %s didn't take %d of the charts just now (%s: %s)", chat, len(skipped), type(skipped[0]).__name__, skipped[0]) + log.warning("BOT_TELEGRAM_PRELOAD_CHAT %s didn't take %d of the charts just now (%s: %s)", chat, len(skipped), type(skipped[0]).__name__, skipped[0]) if done: - log.info("[Telegram] Preloaded %r to %s in %.1fs", intent.without_period(question, now), chat, time.monotonic() - started, extra=QUOTES) + log.info("[Telegram] Preloaded %s %s to %s in %.1fs", tool, json.dumps(periods.with_period(drawn_by, "…"), ensure_ascii=False), + chat, time.monotonic() - started, extra=QUOTES) finally: - self.preloading.discard(question) + self.preloading.discard(periods.drawn_key(drawn_by)) async def _upload_ahead(self, bot, chat: int, key: str, png: bytes, title: str) -> Exception | None: """Upload a chart drawn ahead to the preload chat, silently, and keep Telegram's copy under its key. Returns the flood limit or @@ -1123,91 +1371,46 @@ async def _upload_ahead(self, bot, chat: int, key: str, png: bytes, title: str) except TelegramError as e: if not self.preload_off: self.preload_off = True - log.warning("Couldn't upload to TELEGRAM_PRELOAD_CHAT %s (%s: %s); not preloading charts", chat, type(e).__name__, e) + log.warning("Couldn't upload to BOT_TELEGRAM_PRELOAD_CHAT %s (%s: %s); not preloading charts", chat, type(e).__name__, e) return None - async def draw_buttons_ahead(self, bot): - """The chart of each keyboard button, and of each alert type sent in the last hours (alert_charts.warm), drawn afresh (every - AHEAD_SECONDS, from ecobot.warm_up), so a press, or the Refresh under the alert, is answered with a chart already drawn - (images.ready, AlertCharts.newer_than) instead of drawing one then; with TELEGRAM_PRELOAD_CHAT set and the bot used in the last - 15 minutes, uploaded too, so the press sends Telegram's copy and uploads nothing. A chart drawn for a question in the last minute is left. - Nobody is waiting: the requests are not urgent, and the logs are quiet.""" - started, now = time.monotonic(), now_local(self.cfg.tz) - chat = getattr(self.cfg, "telegram_preload_chat", None) if self.used_lately else None - drawn, uploaded, skipped = 0, 0, [] - texts = templates.chart_sentences(self.irrigation is not None) - for text in texts + [text for text in self.alert_charts.warm() if text not in texts]: - key = self.images.canonical(text, now) - if key is None or (age := self.images.age_of(key)) is not None and age < AHEAD_KEEP_SECONDS: - continue - try: - made = await self._draw_ahead(text, now) - except Exception as e: - log.debug("Couldn't draw %r ahead: %s: %s", text, type(e).__name__, e) - continue - if made is None: # not a chart made in code, or its source is not there - continue - key, png, title, caption, newest = made - self.images.put(key, png, title, caption, newest=newest) - drawn += 1 - if chat is not None and not self.preload_off: - if (why := await self._upload_ahead(bot, chat, key, png, title)) is not None: - skipped.append(why) - elif not self.preload_off: - uploaded += 1 - if drawn: - log.debug("Drew %d button charts ahead%s in %.1fs", drawn, f", uploaded {uploaded} to {chat}" if uploaded else "", time.monotonic() - started) - if skipped: - log.warning("TELEGRAM_PRELOAD_CHAT %s didn't take %d of the button charts just now (%s: %s)", chat, len(skipped), type(skipped[0]).__name__, skipped[0]) - - async def respond(self, update: Update, context: ContextTypes.DEFAULT_TYPE, text: str, redraw: Message | None = None): - """Answer `text` (redraw: a chart's message, when a period button asks for that chart again in place).""" + async def respond(self, update: Update, context: ContextTypes.DEFAULT_TYPE, text: str, call: tuple[str, dict] | None = None): + """Answer `text`: a typed question (or a prompt's), asked of the model; with `call`, a keyboard button's chart (its fixed call), + drawn by ecobot-mcp without the model, `text` its sentence (what the history and the log keep).""" msg = update.effective_message text = text.strip() if not text: return stop_typing = asyncio.Event() # "typing..." from the first moment, even while this question waits its turn - typing = None if redraw is not None else asyncio.create_task( # a chart redrawn in place from a button shows no "typing..." - keep_typing(context.bot, msg.chat_id, self._thread(msg), stop_typing)) + typing = asyncio.create_task(keep_typing(context.bot, msg.chat_id, self._thread(msg), stop_typing)) await asyncio.sleep(0) now = now_local(self.cfg.tz) - read = intent.read(text, now, self.by_name) - log.info("%s%s: %s", describe_source(update), f" (reasoning: {read.effort})" if read.effort != intent.EFFORT_DEFAULT else "", + effort = intent.EFFORT_DEFAULT if call else intent.effort(text) + log.info("%s%s: %s", describe_source(update), f" (reasoning: {effort})" if effort != intent.EFFORT_DEFAULT else "", text, extra=QUOTES) - for source in self.sources: # fetch recent readings while the model thinks - if source.wants(text) and not read.chart_in_code: # a chart made in code reads just what it needs, first in line - source.poke() - if read.fast: - log.debug("Fast path: %s", read.fast[2]) + if call: + log.debug("Button: %s %s", call[0], json.dumps(call[1], ensure_ascii=False), extra=QUOTES) chat = self.chats[self._key(msg)] started = time.monotonic() + turn = Turn() async with chat.lock: - draft = Draft(context.bot, msg.chat_id, self._thread(msg)) if redraw is None and msg.chat.type == ChatType.PRIVATE else None + draft = Draft(context.bot, msg.chat_id, self._thread(msg)) if msg.chat.type == ChatType.PRIVATE and not call else None drafting = asyncio.create_task(draft.run(stop_typing)) if draft else None # a private chat also gets the "Thinking..." draft working = [*chat.history, {"role": "user", "content": self._content(msg, text, context.bot.id)}] new_from = len(working) - turn = Turn.of(read, text) - earlier = working[:-1] - recent = ([str(m["content"]) for m in earlier if m["role"] == "user"][-2:] - + [str(m["content"]) for m in earlier if m["role"] == "assistant"][-1:]) - # the topics of the last messages (the person's last two, the bot's last reply) and those this chat is still on - turn.topics = chat.topics.active().union(*(intent.topics_in(said) for said in recent)) - said = [str(m["content"]) for m in earlier if m["role"] == "user"][-2:] # the air readings named: now, else just before - turn.air_named = next(filter(None, map(intent.air_named, [text, *reversed(said)])), []) try: - answer = await self._answer(msg, read, turn, working, draft, now, redraw) - tools_used = {tc["function"]["name"] for m in working[new_from:] for tc in m.get("tool_calls") or []} - chat.topics.update(turn.topics, intent.topics_in(text) | intent.topics_in(answer.reply or "") - | {intent.TOOL_TOPICS[t] for t in tools_used if t in intent.TOOL_TOPICS} - | ({"air_extra"} if turn.air_extra_used else set())) + answer = await self._answer(msg, call, effort, turn, working, draft) chat.history = shorten_old(trim_history(strip_tool_turns(working))) - for spec in turn.charts[:MAX_CHARTS]: # drawn while "typing..." is still showing + for picture in answer.pictures[:MAX_CHARTS]: # the charts as the service drew them, each titled from its JSON try: - answer.photos.append(await asyncio.to_thread(render_chart, spec, self.cfg.tz, turn.times)) - answer.titles.append(spec.caption(now.date())) + title, _ = self._titled(picture.chart) except Exception as e: log.error("Chart failed (%s: %s); sending the answer without it", type(e).__name__, e, exc_info=isinstance(e, BUGS)) + continue + answer.photos.append(picture.png) + answer.titles.append(title) + answer.drawn_by.append(picture.chart.get("drawn_by")) except TimeoutError: log.error("%s: gave up after %ds on: %s", chat_tag(msg.chat_id), TURN_SECONDS, text, extra=QUOTES) answer = Answer("Sorry, that took too long. Please try again in a moment.", ok=False) @@ -1218,89 +1421,76 @@ async def respond(self, update: Update, context: ContextTypes.DEFAULT_TYPE, text finally: stop_typing.set() await asyncio.gather(*[t for t in (typing, drafting) if t]) # wait for any in-flight "typing" or draft so none is sent after the reply - await self._send(msg, context.bot, read, turn, answer, working[new_from:], now, redraw, started) - - async def _answer(self, msg: Message, read, turn: Turn, working: list[dict], draft, now: datetime, redraw: Message | None) -> Answer: - """The answer, from the first way that gives one: a chart drawn moments ago, a chart made in code, a lookup, the report - written in code, else the model. `working` is the conversation, the question last; the answer joins it.""" - shown = bool(intent.HILO.search(turn.text)) # "when was CO2 highest": the answer is a chart's figures, so they go with it - if read.chart_in_code and redraw is None and (ready := self.images.ready(turn.text, now)): - answer = Answer(ready.caption, [ready.photo], [ready.title], silent=not shown or not ready.caption, ready=ready) # drawn ahead, or for someone's same question - elif read.chart_in_code: # drawn by the tool; the chart goes out with just its title (the text is kept for the history) + await self._send(msg, context.bot, turn, answer, working[new_from:], now, started) + + async def _answer(self, msg: Message, call: tuple[str, dict] | None, effort: str, turn: Turn, working: list[dict], draft) -> Answer: + """The answer. A button's chart (`call`): the one drawn moments ago for the same call, else drawn by the service now, its text + kept for the history. A typed question: the model with the service's tools (its charts as the service drew them); without the + model (no BOT_OPENROUTER_API_KEY), one line saying so. `working` is the conversation, the question last; the answer joins it.""" + key = periods.call_key(*call) if call else None # the call the chart is (its cache key) + if call and (ready := self.images.ready(key)): # drawn for someone's same call moments ago + answer = Answer(ready.caption, [ready.photo], [ready.title], silent=True, ready=ready, drawn_by=[ready.drawn_by], key=key) + elif not call and not getattr(self.agent, "ready", True): # no BOT_OPENROUTER_API_KEY: typed questions are the model's + answer = Answer(NO_MODEL) + elif not await self.weather.ready(): # ecobot-mcp can't be reached + log.warning("%s: %s", chat_tag(msg.chat_id), UNREACHABLE) + answer = Answer(SERVICE_DOWN, ok=False) + elif call: # drawn by the service; the chart goes out with just its title (the text is kept for the history) began = time.monotonic() - reply = await asyncio.wait_for(self._chart_in_code(read, turn), TURN_SECONDS) - answer = Answer(reply, silent=reply is not None and not shown, made=time.monotonic() - began if reply is not None else None) - elif read.dashboard and "Ecowitt" in self.by_name: - answer = await asyncio.wait_for(self._dashboard(self.by_name["Ecowitt"]), TURN_SECONDS) - elif read.lookup: - answer = Answer(await asyncio.wait_for(self._lookup_in_code(read, turn), TURN_SECONDS)) - if answer.reply is None: - turn.forecast_shown.clear() - elif read.fast and (read.report or read.weather_now): # written in code from the tools' results, no model (the report: with its gauges) - text, gauge = await self._report(read, turn, read.report) - answer = Answer(text, [gauge] if gauge else [], [""] if gauge else []) + made = await asyncio.wait_for(self._chart_in_code(call), TURN_SECONDS) + answer = (Answer(made.text or "", silent=True, made=time.monotonic() - began, pictures=made.pictures, key=key) + if isinstance(made, Made) else Answer(made, ok=False)) else: - answer = Answer() - if answer.reply is not None: - working.append({"role": "assistant", "content": answer.reply}) - return answer - if not getattr(self.agent, "ready", True): # no OPENROUTER_API_KEY: what is left is for the model - answer.reply = NO_MODEL - working.append({"role": "assistant", "content": answer.reply}) + system = prompt.build(datetime.now(self.cfg.tz), self._instructions()) + answer = Answer(await self._ask_model(working, system, effort, turn, draft, lambda tokens: self._warn(msg, tokens))) + answer.pictures = [picture for slot, result in enumerate(turn.results) if result for picture in turn.pictures.get(slot, ())] return answer - before = [str(m["content"]) for m in working[:-1] if m["role"] == "user"][-2:] - found = intent.topics(str(working[-1]["content"]), before) | turn.topics - turn.topics = found - turn.air_extra = turn.air_extra or "air_extra" in found # the tools offer the air sensor's own readings whenever the prompt tells of them - system = prompt.build(datetime.now(self.cfg.tz), {s.name: s.describe() for s in self.sources}, read.hints, - read.about_the_bot, read.rain_caption, found) - answer.reply = await self._ask_model(working, system, read, turn, draft, lambda tokens: self._warn(msg, tokens)) + working.append({"role": "assistant", "content": answer.reply}) return answer - async def _send(self, msg: Message, bot, read, turn: Turn, answer: Answer, added: list[dict], now: datetime, - redraw: Message | None, started: float): - """Send the answer, a single chart with the period buttons under it (in place of `redraw` when a button asked for it), the - keyboard if the chat's is out of date; then keep what follows from it: the chart for its period buttons and the next to - ask, the question behind it, the forecast days shown. `added`: the messages the answer added to the conversation.""" - text, reply, photos, titles = turn.text, answer.reply, answer.photos, answer.titles - caption = reply if answer.silent else None # a chart made in code: its text, kept with the chart for the next to ask the same + async def _send(self, msg: Message, bot, turn: Turn, answer: Answer, added: list[dict], now: datetime, started: float): + """Send the answer, a single chart with the period buttons under it, the keyboard if the chat's is out of date; then keep what + follows from it: the chart for its period buttons and the next to ask, its other periods fetched in the background. `added`: the + messages the answer added to the conversation.""" + reply, photos, titles = answer.reply, answer.photos, answer.titles + caption = reply if answer.silent else None # a button's chart: its text, kept with the chart for the next to press the same if answer.silent and photos: reply = "" if answer.ok and not reply.strip() and not photos: # a chart with no text that could not be drawn - reply = "Sorry, I couldn't draw that chart. Please try again in a moment." + reply = NOT_DRAWN used = [m for m in added if m["role"] == "tool"] log.info("%s: %s in %.1fs, tools %d, charts %d, %d chars", chat_tag(msg.chat_id), "Replied" if answer.ok else "Error reply", time.monotonic() - started, len(used), len(photos), len(reply)) - used_air = any(tc["function"]["name"] == "air_quality" for m in added for tc in m.get("tool_calls") or []) - air = self.by_name.get("AirGradient") + used_air = answer.ok and any(r and reads_air(*r) for r in turn.results) # (an error reply gets no link) + air_link = self.weather.air_link() if used_air else None markup = templates.keyboard(self.irrigation is not None) if self._keyboard_stale(msg) else None - refresh = answer.ok and read.report and 0 < len(reply) <= TG_LIMIT and not markup # the report, to be refreshed in place - row = periods.keyboard(intent.period_days(text, now)) if len(photos) == 1 and not (read.dashboard or read.report) else None # period buttons under a single chart + single = len(photos) == 1 # a single chart: its period buttons go under it + drawn_by = answer.drawn_by[0] if single and answer.drawn_by else None + if drawn_by: # the periods its call lists, the chart's own shaded; none when it lists none + row = periods.periods_keyboard(drawn_by, periods.own_period(drawn_by, now, self.cfg.tz), now, self.cfg.tz) + record = {"drawn_by": drawn_by, "words": bool(reply.strip())} + else: # (a chart with no drawn_by: no buttons) + row = record = None drawn = list(photos) - kept = self.images.key(text, intent.period_days(text, now), now) if row and answer.ok and not reply.strip() else None - if kept and not answer.ready: # a chart and nothing else: keep it for the period buttons (and, its words being its key, for the next to ask them) - self.images.put(kept, photos[0], titles[0], caption if kept == self.images.canonical(text, now) else None) + kept = (answer.key or periods.drawn_key(drawn_by)) if single and answer.ok and (drawn_by or not reply.strip()) else None + if kept and not answer.ready: # kept for the period buttons, and (a button's) for the next to press the same + self.images.put(kept, photos[0], titles[0], (caption or reply or None) if answer.key else None, drawn_by=drawn_by) + if kept and drawn_by and (own := periods.own_period(drawn_by, now, self.cfg.tz)): # ... and as its own button replays it + self.images.alias(kept, periods.call_key(drawn_by["tool"], periods.with_period(drawn_by, own))) try: began = time.monotonic() - if redraw is not None and row and await self._redraw(redraw, reply, photos[0], titles[0], row, text, kept): - reply, photos, row = "", [], None - sent = await deliver(msg, reply, photos, link=air.link if air and used_air else None, - markup=markup or (report_menu.keyboard() if refresh else report_menu.dashboard_keyboard() - if answer.ok and read.dashboard and photos else None), titles=titles, period_row=row, - bold_headings=answer.ok and bool(read.report or read.lookup in ("pollen", "forecast")), photos_first=read.report) - carried_keyboard = sent.carried and bool(markup) # the refresh button is not the chat's keyboard + sent = await deliver(msg, reply, photos, link=air_link, markup=markup, titles=titles, period_row=row) + carried_keyboard = sent.carried and bool(markup) if answer.ready: log.debug("Chart ms: drawn %.0fs ago, send %.0f%s", self.images.age(answer.ready), (time.monotonic() - began) * 1000, " (Telegram's copy)" if isinstance(drawn[0], str) else "") elif drawn: log.debug("Chart ms: %s", chart_times(turn.times, answer.made, drawn, time.monotonic() - began)) if sent.photo and row is not None: - self.charted.remember(msg.chat_id, sent.photo.message_id, text) + self.charted.remember(msg.chat_id, sent.photo.message_id, record) self.images.sent(kept, sent.photo) - if kept and read.chart_in_code: # a chart with period buttons, made in code: its other periods are uploaded ahead - self.preload_soon(bot, text) - if answer.ok and turn.forecast_shown: # it was sent: a later revision of these days is worth telling this chat - self.state.record_forecast(msg.chat_id, turn.forecast_shown, now_local(self.cfg.tz).date()) + if kept and row is not None and drawn_by: # its other periods are uploaded ahead + self.preload_soon(bot, drawn_by) if carried_keyboard: log.info("Buttons: sent keyboard %s to chat %s (it had %s)", self.keyboard_version, msg.chat_id, self.state.keyboard(msg.chat_id)) self.state.set_keyboard(msg.chat_id, self.keyboard_version) diff --git a/lib/captions.py b/lib/captions.py index 7ba95269..5dcf8e68 100644 --- a/lib/captions.py +++ b/lib/captions.py @@ -1,5 +1,5 @@ -"""When a chart is drawn, and what the model is told about it: a tool that made a chart adds one of these hints to its -result, so the reply becomes a good caption for the picture (see specs.py for the chart itself, charts.py for drawing it).""" +"""When an engine draws a chart, and the note it adds to its result when it does (the service's tools drop these notes and write +their own, lib/service/common.py CHART_NOTE; see specs.py for the chart itself, charts.py for drawing it).""" from datetime import datetime @@ -7,7 +7,7 @@ def wants_chart(args: dict, turn, start: datetime | None = None, end: datetime | None = None) -> bool: - """The model asked for one, the person's words did (turn.chart_asked), or the period (naive local start/end) spans 3+ days.""" + """The call asked for one (its `chart`, or turn.chart_asked), or the period (naive local start/end) spans 3+ days.""" long = bool(start and end and (end.date() - start.date()).days >= CHART_MIN_DAYS - 1) return bool(args.get("chart")) or turn.chart_asked or long @@ -21,9 +21,6 @@ def wants_chart(args: dict, turn, start: datetime | None = None, end: datetime | "per series (Outdoor and Indoor when both were fetched) with its AVERAGE, copied from the series' " "\"average\" field, and its low and high in brackets. Lead with the average: that is what was asked. " "Don't mention or describe the chart.") -LINK_CHART_HINT = ("Your reply is sent as a message just before a chart with the reading as a line and rain as bars behind it, so keep " - "it short: the period, then the finding in one or two lines (how much of the rain fell while the reading " - "was falling, and the correlation), citing the numbers. Don't mention or describe the chart.") STACK_CHART_HINT = ("Your reply is sent as a message just before a chart with these readings on one time axis, so keep it short: the " "period, then one line per reading: temperature and other readings with their high and low (or their " "average if that was asked), rain with its total (\"rain_total_mm\"). Don't mention or describe the chart.") diff --git a/lib/chart_images.py b/lib/chart_images.py new file mode 100644 index 00000000..5d138bd5 --- /dev/null +++ b/lib/chart_images.py @@ -0,0 +1,138 @@ +"""Chart images: a chart's JSON (schemas/chart.json) drawn as a PNG by the bot's renderer (lib/charts.render_data, Pillow), for the +service's tools when a client asks for images (docs/ecobot-mcp.md 3.7) and for the bot's interface to the service (lib/weather.py). + +Pillow is optional on the service (requirements-charts.txt): nothing here imports it, nor lib.charts or lib.draw, until the first image +is asked for (`renderer`). Without it `renderer()` is None, said once as a warning, and the service answers with the charts' JSON as if +no image had been asked for, with UNAVAILABLE_NOTE. + + - `configure(mode, tz)`: the service's DARKMODE (lib/config.py's dark_mode) and the zone a time range is read in (lib/theme.py, + which lib.charts reads when it draws); + - `wanted(meta, query)`: does a tool call want images, and how: the request's `_meta` `chart_image` ("png", "link" or "none"), + else the connection's MCP URL's query (`?charts=png`, `?charts=link`), else not: "png", "link" or None; + - `render(chart, tz, dark)`: (PNG, dark), as the bot draws it; dark None: as DARKMODE says now (theme.dark_now); + - `Links`: the PNGs of link mode, kept in memory for their lifetime (MCP_CHART_LINK_HOURS) under a random id each, at most + LINKS_MOST of them and LINKS_BYTES in all (the oldest dropped first), served at GET /charts/<id>.png (lib/mcp_server.py) and gone + at a restart; `markdown(title, url)`: the image as the model puts it in its reply.""" + +import importlib +import logging +import secrets +import time +from collections import OrderedDict +from datetime import tzinfo + +from . import theme + +log = logging.getLogger(__name__) + +PNG = "image/png" +IMAGE, LINK, NO_IMAGE = "png", "link", "none" # request _meta chart_image, and the URL's ?charts=: images, links to them, or the JSON + # alone (the default) +CHARTS_META = "ecobot/charts" # result _meta with images: the full chart JSON, each with its drawn_by (3.7) +DARK_META = "ecobot/chart_dark" # result _meta with images: drawn in the dark theme (true) or the light (false) +IMAGE_NOTE = ("The chart is the image attached to this result: show it with your reply. Keep your text to the figures; don't describe " + "the chart.") +LINK_NOTE = ("Each chart is a picture at its `url`: put each in your reply as its `markdown`, exactly as given (a markdown image), so " + "the person sees it. Keep your text to the figures; don't describe the chart.") +UNAVAILABLE_NOTE = "Chart images aren't available on this service: the chart's data is in `charts`." +NOT_DRAWN_NOTE = "The chart's image couldn't be drawn: the chart's data is in `charts`." +_warned = False + + +def configure(mode: str | tuple[int, int], tz: tzinfo | None = None): + """The service's DARKMODE and the zone it is read in, for its images (lib/theme.py, which lib.charts reads when it draws).""" + theme.configure(mode, tz) + + +def renderer(): + """lib.charts, imported now if it hasn't been; None when Pillow isn't installed (said once).""" + global _warned + try: + charts = importlib.import_module("lib.charts") + except ImportError as e: + if not _warned: + _warned = True + log.warning("Chart images were asked for but can't be drawn here (%s): install requirements-charts.txt (Pillow); " + "the charts are sent as JSON alone", e) + return None + return charts + + +def wanted(meta: dict | None, query: str | None = None) -> str | None: + """Images for this call, and how: IMAGE (attached), LINK (a URL each) or None. The request's _meta `chart_image` ("png", "link" or + "none") decides; else the connection's (the MCP URL's `?charts=png` or `?charts=link`, `query`); else none.""" + asked = str((meta or {}).get("chart_image") or "").strip().lower() + if asked in (IMAGE, LINK, NO_IMAGE): + return None if asked == NO_IMAGE else asked + query = str(query or "").strip().lower() + return query if query in (IMAGE, LINK) else None + + +def asked_dark(meta: dict | None) -> bool | None: + """The request's _meta `chart_dark` (true or false); None when not sent (DARKMODE decides).""" + dark = (meta or {}).get("chart_dark") + return dark if isinstance(dark, bool) else None + + +def render(chart: dict, tz: tzinfo, dark: bool | None = None) -> tuple[bytes, bool]: + """(PNG, dark) of a chart given as its JSON, as the bot draws it (lib.charts.render_data). Raises ImportError without Pillow, + ValueError for JSON that isn't a chart.""" + charts = renderer() + if charts is None: + raise ImportError("Pillow isn't installed: chart images can't be drawn") + dark = theme.dark_now() if dark is None else dark + return charts.render_data(chart, tz, dark=dark), dark + + +# ---------- link mode: the pictures served at /charts/<id>.png ---------- +LINK_HOURS = 24 # MCP_CHART_LINK_HOURS' default: how long a chart's link answers +LINKS_MOST = 500 # the most pictures kept ... +LINKS_BYTES = 64 << 20 # ... and the most bytes in all: past either, the oldest go first +ID_BYTES = 16 # an id's randomness (secrets.token_urlsafe): unguessable, the link's only key + + +class Links: + """The pictures of link mode, in memory: `put(png)` keeps one under a new random id (the oldest dropped while there are more than + `most` or more than `most_bytes` in all); `get(id)` is (png, seconds left) until `hours` have passed, else None. Nothing is kept + on disk: a restart forgets them all. `clock`: time.time, or a test's.""" + + def __init__(self, hours: float = LINK_HOURS, most: int = LINKS_MOST, most_bytes: int = LINKS_BYTES, clock=time.time): + self.seconds, self.most, self.most_bytes, self.clock = hours * 3600, most, most_bytes, clock + self._kept: OrderedDict[str, tuple[bytes, float]] = OrderedDict() # id: (png, when it expires), oldest first + self.bytes = 0 + + def __len__(self) -> int: + return len(self._kept) + + def put(self, png: bytes) -> str: + self._expire() + key = secrets.token_urlsafe(ID_BYTES) + self._kept[key] = (png, self.clock() + self.seconds) + self.bytes += len(png) + while self._kept and (len(self._kept) > self.most or self.bytes > self.most_bytes): + self._drop(next(iter(self._kept))) + return key + + def get(self, key: str) -> tuple[bytes, float] | None: + self._expire() + kept = self._kept.get(key) + return (kept[0], kept[1] - self.clock()) if kept else None + + def _expire(self): + now = self.clock() + while self._kept and next(iter(self._kept.values()))[1] <= now: # (in the order kept: the oldest expire first) + self._drop(next(iter(self._kept))) + + def _drop(self, key: str): + png, _ = self._kept.pop(key) + self.bytes -= len(png) + + +def markdown(title, url: str) -> str: + """A chart as a markdown image: ![title](url), the title's brackets and line breaks made harmless.""" + text = " ".join(str(title or "Chart").split()) + return f"![{text.replace('[', '(').replace(']', ')')}]({url})" + + +__all__ = ["CHARTS_META", "DARK_META", "IMAGE", "IMAGE_NOTE", "LINK", "LINK_HOURS", "LINK_NOTE", "LINKS_BYTES", "LINKS_MOST", "Links", + "NOT_DRAWN_NOTE", "NO_IMAGE", "PNG", "UNAVAILABLE_NOTE", "asked_dark", "configure", "markdown", "render", "renderer", "wanted"] diff --git a/lib/charts.py b/lib/charts.py index 2097f623..9d424635 100644 --- a/lib/charts.py +++ b/lib/charts.py @@ -1,7 +1,8 @@ """Charts sent alongside history answers, for both Ecowitt and AirGradient. A history tool adds a specs.Chart to turn.charts (the question's Turn, made by the bot) when a chart was asked for; the -bot renders them after the answer is written and sends them with it. Every chart is one or more panels on a shared time +bot renders them after the answer is written and sends them with it, drawing each from its JSON (specs.to_json, then +render_data here), as any client draws the charts a tool hands over. Every chart is one or more panels on a shared time axis (see specs.py): - one panel of lines is drawn large, with the records marked as pills, an end dot and (for wind) the compass beside it, at exactly 1280x720, the size Telegram displays photos at, so nothing is rescaled; @@ -17,12 +18,12 @@ import time from bisect import bisect_left from dataclasses import dataclass -from datetime import UTC, datetime, timedelta, tzinfo +from datetime import datetime, timedelta, tzinfo from statistics import fmean -from . import draw +from . import draw, theme from .draw import DPI, PT, Canvas, blend, nice_ticks, rgb -from .specs import Chart, Compass, Line, Panel +from .specs import Chart, Compass, Line, Panel, from_json # Palette. Slate neutrals for the furniture; one hue per reading (weather and air quality, kept clear of the green/yellow/red # rating zones); the same reading indoors is its complementary hue (opposite on the colour wheel, as a painter pairs them). @@ -82,27 +83,10 @@ def _use(theme: Theme): RAIN, RAIN_TEXT, WIND_STEPS, _LINES = theme.rain, theme.rain_text, theme.wind_steps, theme.lines -# DARKMODE: "off" (light), "on" (dark), or (from, until): dark between those times of day (minutes past midnight) in the bot's time zone -MODE: str | tuple[int, int] = "off" -ZONE: tzinfo | None = None +# DARKMODE (lib/theme.py: held apart from the renderer, so the bot reads its theme without Pillow) +configure, dark_now = theme.configure, theme.dark_now -def configure(mode: str | tuple[int, int], tz: tzinfo | None = None): - """The dark-mode setting, and the time zone a time range is read in.""" - global MODE, ZONE - MODE, ZONE = mode, tz - - -def dark_now(at: datetime | None = None) -> bool: - """Are charts drawn dark now?""" - if MODE == "on": - return True - if not isinstance(MODE, tuple): - return False - start, end = MODE - local = (at or datetime.now(UTC)).astimezone(ZONE) - now = local.hour * 60 + local.minute - return start <= now < end if start < end else now >= start or now < end # a range past midnight wraps W_IN, H_IN = 6.4, 3.6 # 1280 x 720 px AX_RECT = [0.075, 0.13, 0.905, 0.64] # left, bottom, width, height (figure fraction) of a single chart PANEL_IN = 1.1 # each panel past two adds this much height (inches) @@ -900,6 +884,12 @@ def render(chart: Chart, tz: tzinfo, times: dict | None = None, dark: bool | Non return png +def render_data(data: dict, tz: tzinfo, times: dict | None = None, dark: bool | None = None) -> bytes: + """PNG bytes for a chart given as its JSON (specs.to_json, schemas/chart.json): how the bot draws every chart, as a client + draws the charts a tool hands over. Raises ValueError for JSON that isn't a chart; otherwise as render.""" + return render(from_json(data), tz, times, dark) + + def draw_texts(chart: Chart, tz: tzinfo, dark: bool = False) -> list[draw.Text]: """Every label recorded while drawing the chart (its values, pills and bar numbers), in the order drawn: for tests.""" with _DRAWING: diff --git a/lib/compose.py b/lib/compose.py index 3f8f68dc..7949be5c 100644 --- a/lib/compose.py +++ b/lib/compose.py @@ -1,12 +1,12 @@ -"""Charts across both sources, composed by the model from a fixed list of series and styles. +"""Charts across both sources, composed from a fixed list of series and styles, and the air sensor against rain and the weather (the +engines of lib/service's summary, relate and scan). -The model names what to plot (`plot_chart`: up to four panels, each a series and a style); this module loads the data +A call names what to plot (`plot_chart`: up to four panels, each a series and a style); this module loads the data from the caches, puts it on one time axis and hands the chart to the renderer. The model never supplies numbers or drawing code, so a chart the bot has never drawn before is still made from checked data. Only the cached readings are used for the weather station (nothing is fetched); AirGradient fills any missing days first, as its own tool does.""" import asyncio -import copy import logging from datetime import date, datetime, time, timedelta, tzinfo from statistics import fmean @@ -21,8 +21,8 @@ from .panels import panel_for, same_axis, two_axes from .specs import AIR_SOURCE, ECOWITT_SOURCE, Panel, Shares, stack from .rain import bar_layout, bar_of, rain_bars, rain_slots -from .timeutil import SLOT, day_bounds, now_local, parse_period, period_parameters -from .tools import Tool, Turn, json_result +from .timeutil import SLOT, day_bounds, now_local, parse_period +from .tools import Turn, json_result log = logging.getLogger(__name__) @@ -30,44 +30,9 @@ DEFAULT_DAYS = 30 # Weather station series: name -> (group, field, label, unit); the composer draws the wind as its average speed SERIES = [*WEATHER, *ALL_METRICS] -SERIES_ASKED = [*SERIES, *EXTRA] # what a question that asks for the air sensor's own temperature or humidity is offered +SERIES_ASKED = [*SERIES, *EXTRA] # with the air sensor's own temperature and humidity STYLES = ("line", "bars", "rating") -PLOT_DESCRIPTION = ( - "Plot readings from the weather station and the air-quality sensor together on one time axis, one panel each: " - "'plot the traffic light rating of air quality against rainfall', 'plot PM2.5 and humidity'. Each panel is a series and " - "a style. Styles: 'line' (the reading; long periods are averaged, with the day's range shaded), 'bars' (rain only), " - "'rating' (air-quality series only: the share of time in good, poor and very poor, as traffic-light bars). " - "Bars and ratings are per hour for a few days, per 6 hours up to a month, per day beyond. Rain defaults to bars and " - "everything else to line. Default period: the last 30 days up to yesterday.") -PLOT_PARAMETERS = { - "type": "object", - "properties": { - "panels": {"type": "array", "minItems": 1, "maxItems": MAX_PANELS, "description": "Top to bottom.", - "items": {"type": "object", "properties": {"series": {"type": "string", "enum": SERIES}, - "style": {"type": "string", "enum": list(STYLES)}}, - "required": ["series"]}}, - "two_axes": {"type": "boolean", "description": "Set true to draw the series on ONE panel with a left and a right axis: " - "'on two axes', 'dual axis', 'overlay', 'combine them on one chart'."}, - "invert_second_axis": {"type": "boolean", "description": "With two_axes: the right-hand axis runs top to bottom, so its lines fall as the " - "reading rises ('invert the second Y axis')."}, - **period_parameters(DEFAULT_DAYS), - }, - "required": ["panels"], -} - - -def plot_asked() -> tuple[str, dict]: - """plot_chart as a question about the air sensor's own temperature or humidity is offered it: those two series too, and same_axis.""" - parameters = copy.deepcopy(PLOT_PARAMETERS) - parameters["properties"]["panels"]["items"]["properties"]["series"]["enum"] = SERIES_ASKED - parameters["properties"]["same_axis"] = { - "type": "boolean", "description": "Set true to draw the series as ONE panel on one axis, the lines over each other: " - "'plot airgradient humidity over ecowitt humidity'."} - return (PLOT_DESCRIPTION + " Also air_temperature and air_humidity: the AirGradient sensor's own temperature and humidity (ask for " - "them only by those names: plain temperature and humidity are the weather station's).", parameters) - - SCAN_DAYS = 90 SCAN_MAX_DAYS = 400 # a longer scan is cut to its latest days: its time grows with the period SCAN_AIR = ("pm2_5", "pm10", "co2", "voc_index", "nox_index") @@ -75,37 +40,8 @@ def plot_asked() -> tuple[str, dict]: SCAN_WEATHER = {**{n: (WEATHER[n].group, WEATHER[n].field, WEATHER[n].label.lower(), WEATHER[n].unit) for n in ("temperature", "humidity", "dew_point", "pressure")}, "wind_speed": ("wind", "wind_speed", "wind speed", "km/h"), "wind_gust": ("wind", "wind_gust", "wind gusts", "km/h")} -SCAN_DESCRIPTION = ( - "Which readings go with air quality? Scans every air-quality metric (PM2.5, PM10, CO2, VOC, NOx) against the weather " - "(temperature, humidity, dew point, pressure and its 3-hour change, wind speed, gusts, wind direction, rain), allowing for " - "the daily cycle and for chance, and reports only the relationships that stand out, with a plain verdict. Use it for 'is " - "there a correlation between air quality and other metrics', 'what affects air quality'. For rain alone use air_link. " - "Default period: the last 90 days.") -SCAN_PARAMETERS = { - "type": "object", - "properties": { - "metric": {"type": "string", "enum": ["all", *SCAN_AIR], "description": "One air reading, or all (default)."}, - **period_parameters(SCAN_DAYS), - "chart": {"type": "boolean", "description": "Set true for a chart of the strongest relationship found."}, - }, -} LINK_DAYS = 60 LINK_METRICS = ("pm2_5", "pm10") -LINK_DESCRIPTION = ( - "Does rain go with cleaner air? Reads the air-quality sensor (PM2.5 by default) and the weather station's rain together at " - "30-minute resolution and reports whether the air was cleaner in the hours after rain than before it, its level in wet and " - "dry periods, and wet days against dry days, with a plain verdict. Use it for 'is there a correlation between air quality " - "and rainfall', 'does rain clear the air'. Default period: the last 60 days.") -LINK_PARAMETERS = { - "type": "object", - "properties": { - "metric": {"type": "string", "enum": list(LINK_METRICS), "description": "The air reading. Default pm2_5."}, - **period_parameters(LINK_DAYS), - "chart": {"type": "boolean", "description": "Set true for a chart: the reading (with its rating zones) over rain bars."}, - }, -} - - def _error(text: str) -> str: return json_result({"error": text}) @@ -128,9 +64,6 @@ class Composer: def __init__(self, eco, air): self.eco, self.air, self.tz = eco, air, eco.tz - self.tools = [Tool("plot_chart", PLOT_DESCRIPTION, PLOT_PARAMETERS, self.plot_chart, asked=plot_asked, source=""), - Tool("air_link", LINK_DESCRIPTION, LINK_PARAMETERS, self.air_link, source=""), - Tool("air_scan", SCAN_DESCRIPTION, SCAN_PARAMETERS, self.air_scan, source="")] def period(self, args: dict, default_days: int = DEFAULT_DAYS) -> tuple[date, date] | str: """(first, last) day, or an error text. The last day is at most yesterday: today is still settling.""" @@ -189,7 +122,6 @@ async def plot_chart(self, args: dict, turn: Turn | None = None) -> str: return _error(f"no cached readings of {name} for {first} to {last}") built.append(panel) summary.append(facts) - turn.air_extra_used = turn.air_extra_used or any(name in EXTRA for name, _ in asked) if (args.get("two_axes") or args.get("same_axis")) and any(name in EXTRA for name, _ in asked): for (name, _), panel in zip(asked, built): # the station's readings next to the air sensor's own: say whose each is if name in WEATHER and name != "rain": @@ -273,7 +205,7 @@ async def air_scan(self, args: dict, turn: Turn | None = None) -> str: origin, days = day_bounds(first, self.tz)[0], (last - first).days + 1 result = await asyncio.to_thread(scan.scan, {m: v[0] for m, v in air.items()}, weather, direction, speed, origin, days, self.tz) summary = scan.summarise(result, air_names, weather_names) - strongest = summary.pop("strongest") + strongest = summary.pop("strongest", None) # (none when there was nothing to scan) out = {"period": f"{first} to {last}", "resolution": "30-minute slots; each pair compared within the day and day to day", "how_to_read": ("Open with `verdict`, then the relationships in `findings`, strongest first. These go together; they " "do not cause each other (shared weather and season). If nothing stands out, say so and that the " diff --git a/lib/config.py b/lib/config.py index 3586ad54..133e90a0 100644 --- a/lib/config.py +++ b/lib/config.py @@ -62,6 +62,43 @@ def _required(value: str, default: str, name: str) -> str: raise SystemExit(f"{name} is not set: the bot can't start without it (see docs/configuration.md)") +REQUIRED_BY_BOT = ("telegram_token",) # read only by the bot: ecobot-mcp (python -m ecobot_mcp) runs without them +REQUIRED_BY_IRRIGATION = ("tuya_device_id", "tuya_client_id", "tuya_client_secret") # irrigation-mcp (python -m irrigation_mcp) can't run without them +MCP_PREFIX = "MCP_" # ecobot-mcp's own settings: the bot doesn't read them (they keep their defaults in its Config) +BOT_PREFIX = "BOT_" # the bot's own +IRRIGATION_PREFIX = "IRRIGATION_" # irrigation-mcp's own +PROGRAMS = ("bot", "mcp", "irrigation") +NO_TUYA = ("irrigation-mcp needs the irrigation controller's Tuya settings: set IRRIGATION_TUYA_DEVICE_ID, IRRIGATION_TUYA_CLIENT_ID " + "and IRRIGATION_TUYA_CLIENT_SECRET (docs/configuration.md); {missing} not set") +NO_SERVICE = ("BOT_MCP_URL is not set: the bot is a client of ecobot-mcp and can't start without it. Run ecobot-mcp (python -m " + "ecobot_mcp, the ecobot-mcp.service unit, or the ecobot-mcp container) and set BOT_MCP_URL to its endpoint, e.g. " + "http://127.0.0.1:8765/mcp (docs/configuration.md)") + + +def _tokens(value: str, default: tuple, name: str) -> tuple[str, ...]: + """"s3cret, t0ken" -> ("s3cret", "t0ken"): the bearer tokens ecobot-mcp accepts, one per client, so one can be revoked alone (take + it out and restart). Blank entries are skipped; a token given twice counts once.""" + return tuple(dict.fromkeys(filter(None, (p.strip() for p in value.split(","))))) or default + + +def _bind(value: str, default: tuple[str, int], name: str) -> tuple[str, int]: + """"0.0.0.0:8765" -> ("0.0.0.0", 8765), "[::1]:8765" -> ("::1", 8765), "8765" -> (the default host, 8765); anything unreadable + keeps the default, with a warning.""" + if not value: + return default + host, sep, port = value.rpartition(":") + host = host.strip().strip("[]") if sep else default[0] + if port.strip().isdecimal() and 0 < int(port) < 65536 and host: + return host, int(port) + log.warning("%s: %r is not host:port; keeping %s:%d", name, value, *default) + return default + + +def _names(value: str, default: tuple[str, ...], name: str) -> tuple[str, ...]: + """"ecobot.lan, 192.168.1.5:8765" -> ("ecobot.lan", "192.168.1.5:8765"); unset or empty is the default.""" + return tuple(filter(None, (p.strip() for p in value.split(",")))) or default + + def _url(value: str, default: str, name: str) -> str: return (value or default).rstrip("/") @@ -196,57 +233,141 @@ def _level(value: str, default: str, name: str) -> str: return default -def _setting(name: str, default=None, read=None): - """A Config field read from the environment variable `name` by `read` (a reader above; none: the text, blank being the default).""" - return field(default=default, metadata={"env": name, "read": read}) +def _setting(name: str, default=None, read=None, old: str | tuple[str, ...] | None = None): + """A Config field read from the environment variable `name` by `read` (a reader above; none: the text, blank being the default). + old: the name it had before (docs/configuration.md, "Renamed settings"), or the names, newest first, still read when `name` is unset, + with a warning.""" + olds = (old,) if isinstance(old, str) else tuple(old or ()) + return field(default=default, metadata={"env": name, "read": read, "old": olds}) + + +def old_names(f) -> tuple[str, ...]: + """A setting's old names, newest first (none for one never renamed).""" + return tuple(f.metadata.get("old") or ()) + + +def _text(f, renamed: list | None = None) -> tuple[str, str]: + """The setting's text (stripped) and the variable it was read from: its own name, else the newest of its old ones that is set (noted + in `renamed`); the others set are noted as ignored.""" + name = f.metadata["env"] + text, used = os.getenv(name, "").strip(), name + for old in old_names(f): + value = os.getenv(old, "").strip() + if not value: + continue + if not text: + text, used = value, old + if renamed is not None: + renamed.append((old, name)) + elif renamed is not None: + renamed.append((old, None)) # a newer name is set too: this one is ignored + return text, used + + +def _from_env(f, renamed: list | None = None) -> object: + text, name = _text(f, renamed) + return f.metadata["read"](text, f.default, name) if f.metadata["read"] else text or f.default -def _from_env(f) -> object: - text = os.getenv(f.metadata["env"], "").strip() - return f.metadata["read"](text, f.default, f.metadata["env"]) if f.metadata["read"] else text or f.default +def warn_renamed(renamed: list[tuple[str, str | None]]): + """One warning naming the old variables found and their new names (never their values).""" + used = [f"{old} -> {new}" for old, new in renamed if new] + ignored = [old for old, new in renamed if not new] + if used: + log.warning("Old setting names, still read for now: rename %s (docs/configuration.md, \"Renamed settings\")", ", ".join(used)) + if ignored: + log.warning("Ignoring %s: a newer name is set", ", ".join(ignored)) + + +def env(name: str) -> str: + """A setting's text by its name, or by its old one when that is all that is set (for the scripts, which read a few directly).""" + for f in fields(Config): + if f.metadata.get("env") == name: + return _text(f)[0] + return os.getenv(name, "").strip() + + +RETIRED_TOKEN = "WEATHER_MCP_TOKEN" # the bot's token before AUTH_TOKENS: still sent when AUTH_TOKENS is unset, with a warning @dataclass(frozen=True) class Config: tz: tzinfo state_path: Path - storage_path: Path # the bot's one file of readings, the pollen page and the forecast (lib/storage) - telegram_token: str = _setting("TELEGRAM_BOT_TOKEN", "", _required) - openrouter_api_key: str = _setting("OPENROUTER_API_KEY", "") # unset: the bot runs without the model, answering only what it works out in code - openrouter_base_url: str = _setting("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1") - openrouter_model: str = _setting("OPENROUTER_MODEL", "deepseek/deepseek-v4.1-flash-1017") - ecowitt_api_key: str = _setting("ECOWITT_API_KEY", "") - ecowitt_app_key: str = _setting("ECOWITT_APP_KEY", "") - airgradient_token: str = _setting("AIRGRADIENT_API_TOKEN", "") - airgradient_location: str = _setting("AIRGRADIENT_LOCATION_ID", "") - airgradient_dashboard: str = _setting("AIRGRADIENT_DASHBOARD_URL", "") - airgradient_local_url: str = _setting("AIRGRADIENT_LOCAL_URL", "") # the sensor's own server for the live reading, e.g. http://airgradient_<serial>.local - airgradient_source: str = _setting("AIRGRADIENT_SOURCE", "auto", _air_source) # auto: the monitor itself, then Home Assistant, then the cloud, each that is set; or one alone - homeassistant_url: str = _setting("HOMEASSISTANT_URL", "", _url) # Home Assistant, where the station's readings are read from (its Ecowitt integration), e.g. http://192.168.1.219:8123 - homeassistant_token: str = _setting("HOMEASSISTANT_TOKEN", "") # a long-lived access token (your profile page in Home Assistant) - ecowitt_source: str = _setting("ECOWITT_SOURCE", "auto", _source) # auto: Home Assistant if set, Ecowitt's cloud as its fallback if set too; cloud: the cloud only; homeassistant: Home Assistant only - place: str = _setting("PLACE", "Melbourne") # named after the Pollen & asthma and Forecast headings in the report - pollen: bool = _setting("POLLEN", False, _flag) # Melbourne grass pollen and thunderstorm asthma risk (a scraped website) - pollen_district: str = _setting("POLLEN_DISTRICT", "Central") # the Victorian forecast district whose thunderstorm asthma risk is used - forecast: bool = _setting("FORECAST", False, _flag) # the daily forecast from Open-Meteo - forecast_lat: float | None = _setting("FORECAST_LAT", None, _number) # the weather station's own location when unset - forecast_lon: float | None = _setting("FORECAST_LON", None, _number) - rain_quiet_hours: tuple[int, int] | None = _setting("RAIN_QUIET_HOURS", (0, 6), _hours) # "0-6", local hours ("off" for none): no rain alerts, a summary after - chart_all_feels_like: bool = _setting("CHART_ALL_FEELS_LIKE", False, _flag) # "weather all week" also draws the feels-like panel (off: it nearly repeats temperature) - chart_all_vpd: bool = _setting("CHART_ALL_VPD", False, _flag) # "weather all week" also draws the vapour pressure deficit panel (off: it is temperature and humidity combined) - tuya_device_id: str = _setting("TUYA_DEVICE_ID", "") # all three switch the irrigation controller on - tuya_client_id: str = _setting("TUYA_CLIENT_ID", "") - tuya_client_secret: str = _setting("TUYA_CLIENT_SECRET", "") - tuya_base_url: str = _setting("TUYA_BASE_URL", "https://openapi.tuyaeu.com", _url) # the data centre's address (EU by default) - irrigation_check_hour: int = _setting("IRRIGATION_CHECK_HOUR", 18, _hour) # the local hour of the daily check (0 to 23) - dark_mode: str | tuple[int, int] = _setting("DARKMODE", "off", _dark_mode) # off: light charts; on: dark; "8pm-8am" (or 20:00-8:00, 20-8): dark those hours in the bot's time zone - admin_only: bool = _setting("ADMIN_ONLY", False, _flag) # on: the bot answers nobody but the admins of the groups it is in (and ADMIN_CHAT_IDS) - admin_chat_ids: frozenset[int] = _setting("ADMIN_CHAT_IDS", frozenset(), _ids) # more ids allowed besides those admins (a user id, or a group id for its anonymous admins) - alert_cooldown_minutes: int = _setting("ALERT_COOLDOWN_MINUTES", 60, _between(5, 150)) # dry this long before "the rain has stopped"; and the temperature-crossing alert's minimum gap - telegram_preload_chat: int | None = _setting("TELEGRAM_PRELOAD_CHAT", None, _chat_id) # a chat the other periods of each chart are silently uploaded to ahead of the press (none: off) - antispike_require_consecutive: int = _setting("ANTISPIKE_REQUIRE_CONSECUTIVE", 2, _readings_in_a_row) # readings in a row a rise of the particles needs to be the air, not a glitch of the sensor (1: off) - log_width: int = _setting("LOG_WIDTH", 24, _whole) # the most characters of a chat message kept in the log, then an ellipsis (…); 0 keeps all - log_level: str = _setting("LOG_LEVEL", "INFO", _level) # DEBUG adds the bot's own debug lines; the libraries keep theirs + storage_path: Path # the one file of readings, the pollen page and the forecast (lib/storage) + # ecobot-mcp's (python -m ecobot_mcp): the sources, the alert rules and the MCP server. The bot doesn't read them + ecowitt_api_key: str = _setting("MCP_ECOWITT_API_KEY", "", old="ECOWITT_API_KEY") + ecowitt_app_key: str = _setting("MCP_ECOWITT_APP_KEY", "", old="ECOWITT_APP_KEY") + ecowitt_source: str = _setting("MCP_ECOWITT_SOURCE", "auto", _source, old="ECOWITT_SOURCE") # auto: Home Assistant if set, Ecowitt's cloud as its fallback if set too; cloud: the cloud only; homeassistant: Home Assistant only + airgradient_token: str = _setting("MCP_AIRGRADIENT_API_TOKEN", "", old="AIRGRADIENT_API_TOKEN") + airgradient_location: str = _setting("MCP_AIRGRADIENT_LOCATION_ID", "", old="AIRGRADIENT_LOCATION_ID") + airgradient_dashboard: str = _setting("MCP_AIRGRADIENT_DASHBOARD_URL", "", old="AIRGRADIENT_DASHBOARD_URL") + airgradient_local_url: str = _setting("MCP_AIRGRADIENT_LOCAL_URL", "", old="AIRGRADIENT_LOCAL_URL") # the sensor's own server for the live reading, e.g. http://airgradient_<serial>.local + airgradient_source: str = _setting("MCP_AIRGRADIENT_SOURCE", "auto", _air_source, old="AIRGRADIENT_SOURCE") # auto: the monitor itself, then Home Assistant, then the cloud, each that is set; or one alone + homeassistant_url: str = _setting("MCP_HOMEASSISTANT_URL", "", _url, old="HOMEASSISTANT_URL") # Home Assistant, where the station's readings are read from (its Ecowitt integration), e.g. http://192.168.1.219:8123 + homeassistant_token: str = _setting("MCP_HOMEASSISTANT_TOKEN", "", old="HOMEASSISTANT_TOKEN") # a long-lived access token (your profile page in Home Assistant) + place: str = _setting("MCP_PLACE", "Melbourne", old="PLACE") # named after the Pollen & asthma and Forecast headings in the report + pollen: bool = _setting("MCP_POLLEN", False, _flag, old="POLLEN") # Melbourne grass pollen and thunderstorm asthma risk (a scraped website) + pollen_district: str = _setting("MCP_POLLEN_DISTRICT", "Central", old="POLLEN_DISTRICT") # the Victorian forecast district whose thunderstorm asthma risk is used + forecast: bool = _setting("MCP_FORECAST", False, _flag, old="FORECAST") # the daily forecast from Open-Meteo + forecast_lat: float | None = _setting("MCP_FORECAST_LAT", None, _number, old="FORECAST_LAT") # the weather station's own location when unset + forecast_lon: float | None = _setting("MCP_FORECAST_LON", None, _number, old="FORECAST_LON") + rain_quiet_hours: tuple[int, int] | None = _setting("MCP_RAIN_QUIET_HOURS", (0, 6), _hours, old="RAIN_QUIET_HOURS") # "0-6", local hours ("off" for none): no rain alerts, a summary after + alert_cooldown_minutes: int = _setting("MCP_ALERT_COOLDOWN_MINUTES", 60, _between(5, 150), old="ALERT_COOLDOWN_MINUTES") # dry this long before "the rain has stopped"; and the temperature-crossing alert's minimum gap + antispike_require_consecutive: int = _setting("MCP_ANTISPIKE_REQUIRE_CONSECUTIVE", 2, _readings_in_a_row, old="ANTISPIKE_REQUIRE_CONSECUTIVE") # readings in a row a rise of the particles needs to be the air, not a glitch of the sensor (1: off) + chart_all_feels_like: bool = _setting("MCP_CHART_ALL_FEELS_LIKE", False, _flag, old="CHART_ALL_FEELS_LIKE") # "weather all week" also draws the feels-like panel (off: it nearly repeats temperature) + chart_all_vpd: bool = _setting("MCP_CHART_ALL_VPD", False, _flag, old="CHART_ALL_VPD") # "weather all week" also draws the vapour pressure deficit panel (off: it is temperature and humidity combined) + 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_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) + telegram_token: str = _setting("BOT_TELEGRAM_TOKEN", "", old="TELEGRAM_BOT_TOKEN") # (REQUIRED_BY_BOT: it stops without it) + telegram_preload_chat: int | None = _setting("BOT_TELEGRAM_PRELOAD_CHAT", None, _chat_id, old="TELEGRAM_PRELOAD_CHAT") # a chat the other periods of each chart are silently uploaded to ahead of the press (none: off) + openrouter_api_key: str = _setting("BOT_OPENROUTER_API_KEY", "", old="OPENROUTER_API_KEY") # unset: the bot runs without the model, answering only what it works out in code + openrouter_base_url: str = _setting("BOT_OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1", old="OPENROUTER_BASE_URL") + openrouter_model: str = _setting("BOT_OPENROUTER_MODEL", "deepseek/deepseek-v4.1-flash-1017", old="OPENROUTER_MODEL") + admin_only: bool = _setting("BOT_ADMIN_ONLY", False, _flag, old="ADMIN_ONLY") # on: the bot answers nobody but the admins of the groups it is in (and BOT_ADMIN_CHAT_IDS) + admin_chat_ids: frozenset[int] = _setting("BOT_ADMIN_CHAT_IDS", frozenset(), _ids, old="ADMIN_CHAT_IDS") # more ids allowed besides those admins (a user id, or a group id for its anonymous admins) + log_width: int = _setting("BOT_LOG_WIDTH", 24, _whole, old="LOG_WIDTH") # the most characters of a chat message kept in the log, then an ellipsis (…); 0 keeps all + mcp_url: str = _setting("BOT_MCP_URL", "", _url, old="WEATHER_MCP_URL") # ecobot-mcp's endpoint, e.g. http://127.0.0.1:8765/mcp (the bot is its client, and stops without it: NO_SERVICE) + retired_mcp_token: str = _setting(RETIRED_TOKEN, "") # retired: sent only when AUTH_TOKENS is unset (ecobot.mcp_token) + irrigation_mcp_url: str = _setting("BOT_IRRIGATION_MCP_URL", "", _url) # irrigation-mcp's endpoint, e.g. http://127.0.0.1:8766/mcp (unset: no irrigation in the bot) + # irrigation-mcp's (python -m irrigation_mcp): the irrigation controller, its watchdog and daily check, and its MCP server. The bot + # reads none of them: it is irrigation-mcp's client (BOT_IRRIGATION_MCP_URL) + tuya_device_id: str = _setting("IRRIGATION_TUYA_DEVICE_ID", "", old=("BOT_TUYA_DEVICE_ID", "TUYA_DEVICE_ID")) # all three switch the irrigation controller on (irrigation-mcp stops without them) + tuya_client_id: str = _setting("IRRIGATION_TUYA_CLIENT_ID", "", old=("BOT_TUYA_CLIENT_ID", "TUYA_CLIENT_ID")) + tuya_client_secret: str = _setting("IRRIGATION_TUYA_CLIENT_SECRET", "", old=("BOT_TUYA_CLIENT_SECRET", "TUYA_CLIENT_SECRET")) + tuya_base_url: str = _setting("IRRIGATION_TUYA_BASE_URL", "https://openapi.tuyaeu.com", _url, old=("BOT_TUYA_BASE_URL", "TUYA_BASE_URL")) # the data centre's address (EU by default) + irrigation_check_hour: int = _setting("IRRIGATION_CHECK_HOUR", 18, _hour, old="BOT_IRRIGATION_CHECK_HOUR") # the local hour of the daily check (0 to 23) + irrigation_bind: tuple[str, int] = _setting("IRRIGATION_BIND", ("127.0.0.1", 8766), _bind) # host:port irrigation-mcp listens on + irrigation_allowed_hosts: tuple[str, ...] = _setting("IRRIGATION_ALLOWED_HOSTS", ("127.0.0.1", "localhost"), _names) # the Host names it answers (any port, unless one is given) + irrigation_ecobot_mcp_url: str = _setting("IRRIGATION_ECOBOT_MCP_URL", "http://127.0.0.1:8765/mcp", _url) # ecobot-mcp, which its daily check asks for the rain and the forecast + # Every program reads them + dark_mode: str | tuple[int, int] = _setting("DARKMODE", "off", _dark_mode) # off: light charts; on: dark; "8pm-8am" (or 20:00-8:00, 20-8): dark those hours in the station's time zone + log_level: str = _setting("LOG_LEVEL", "INFO", _level) # DEBUG adds the program's own debug lines; the libraries keep theirs + auth_tokens: tuple[str, ...] = _setting("AUTH_TOKENS", (), _tokens, old="MCP_SERVICE_TOKENS") # "token,token,...": ecobot-mcp accepts each, the bot sends the first; unset: the one ecobot-mcp generates in the data folder (lib/auth_token.py) + + @property + def alert_state_path(self) -> Path: + """The alert rules' own state (lib/alerts/store.py), beside the bot's.""" + return self.state_path.parent / "alert_state.json" + + @property + def alert_log_path(self) -> Path: + """The alert log (lib/alert_log.py), beside the bot's state.""" + return self.state_path.parent / "alerts.sqlite" + + @property + def irrigation_state_path(self) -> Path: + """irrigation-mcp's state (the watchdog's run, the daily check's days: lib/irrigation/state.py), beside the bot's.""" + return self.state_path.parent / "irrigation_state.json" + + @property + def irrigation_alert_log_path(self) -> Path: + """irrigation-mcp's alert log (irrigation://alerts), apart from ecobot-mcp's.""" + return self.state_path.parent / "irrigation_alerts.sqlite" @property def homeassistant(self) -> bool: @@ -254,12 +375,12 @@ def homeassistant(self) -> bool: @property def ecowitt_cloud(self) -> bool: - """The station's readings are asked of Ecowitt's cloud (its keys are set, and ECOWITT_SOURCE does not say Home Assistant only).""" + """The station's readings are asked of Ecowitt's cloud (its keys are set, and MCP_ECOWITT_SOURCE does not say Home Assistant only).""" return bool(self.ecowitt_api_key and self.ecowitt_app_key) and self.ecowitt_source != "homeassistant" @property def ecowitt_home_assistant(self) -> bool: - """... of Home Assistant (it is set, and ECOWITT_SOURCE does not say the cloud only).""" + """... of Home Assistant (it is set, and MCP_ECOWITT_SOURCE does not say the cloud only).""" return self.homeassistant and self.ecowitt_source != "cloud" @property @@ -269,21 +390,22 @@ def ecowitt(self) -> bool: @property def irrigation(self) -> bool: + """irrigation-mcp's controller is set up (its three Tuya settings): it can't start without (NO_TUYA).""" return bool(self.tuya_device_id and self.tuya_client_id and self.tuya_client_secret) @property def airgradient_cloud(self) -> bool: - """The air monitor's readings are asked of AirGradient's cloud (its token and location are set, and AIRGRADIENT_SOURCE allows).""" + """The air monitor's readings are asked of AirGradient's cloud (its token and location are set, and MCP_AIRGRADIENT_SOURCE allows).""" return bool(self.airgradient_token and self.airgradient_location) and self.airgradient_source in ("auto", "cloud") @property def airgradient_local(self) -> bool: - """... of the monitor itself (its address is set, and AIRGRADIENT_SOURCE allows).""" + """... of the monitor itself (its address is set, and MCP_AIRGRADIENT_SOURCE allows).""" return bool(self.airgradient_local_url) and self.airgradient_source in ("auto", "local") @property def airgradient_homeassistant(self) -> bool: - """... of Home Assistant (it is set, and AIRGRADIENT_SOURCE allows; whether it has the monitor is found at start).""" + """... of Home Assistant (it is set, and MCP_AIRGRADIENT_SOURCE allows; whether it has the monitor is found at start).""" return self.homeassistant and self.airgradient_source in ("auto", "homeassistant") @property @@ -291,10 +413,26 @@ def airgradient(self) -> bool: """AirGradient is on with any of its sources: the monitor's own server, Home Assistant, or its cloud account.""" return self.airgradient_cloud or self.airgradient_local or self.airgradient_homeassistant + @staticmethod + def reads(program: str, name: str) -> bool: + """Whether `program` (PROGRAMS) reads the setting `name`: the bot its own (BOT_) and the shared ones; ecobot-mcp every one but + irrigation-mcp's; irrigation-mcp its own and the shared ones (not the bot's retired token).""" + if program == "bot": + return not name.startswith((MCP_PREFIX, IRRIGATION_PREFIX)) + if program == "irrigation": + return name.startswith(IRRIGATION_PREFIX) or not name.startswith((MCP_PREFIX, BOT_PREFIX)) and name != RETIRED_TOKEN + return not name.startswith(IRRIGATION_PREFIX) + @classmethod - def from_env(cls) -> "Config": - """Every setting from its variable, the files in the data folder. Stops, saying why, when one the bot can't run without is - missing or the folder can't be written.""" + def from_env(cls, bot: bool = True, program: str | None = None) -> "Config": + """Every setting from its variable, the files in the data folder. Stops, saying why, when one the program can't run without is + missing or the folder can't be written. program: "bot" (the default), "mcp" for ecobot-mcp (python -m ecobot_mcp; bot=False + says the same), which has no Telegram token, or "irrigation" for irrigation-mcp (python -m irrigation_mcp). Each reads only the + settings it uses (Config.reads), the others keeping their defaults. Old names still read are named in one warning (never their + values).""" + program = program or ("bot" if bot else "mcp") + if program not in PROGRAMS: + raise ValueError(f"no program {program!r}: {', '.join(PROGRAMS)}") data = data_dir() try: data.mkdir(parents=True, exist_ok=True) @@ -304,9 +442,23 @@ def from_env(cls) -> "Config": if not writable: raise SystemExit(f"{data} is not writable by this user: set DATA_DIR to a writable folder " "(under systemd with StateDirectory=ecobot that is /var/lib/ecobot)") + renamed: list = [] + read = [f for f in fields(cls) if "env" in f.metadata and cls.reads(program, f.metadata["env"])] cfg = cls(tz=local_tz(), state_path=data / "bot_state.json", storage_path=data / "ecobot.sqlite", - **{f.name: _from_env(f) for f in fields(cls) if "env" in f.metadata}) + **{f.name: _from_env(f, renamed) for f in read}) + warn_renamed(renamed) + if program == "irrigation": + if missing := [f.metadata["env"] for f in fields(cls) if f.name in REQUIRED_BY_IRRIGATION and not getattr(cfg, f.name)]: + raise SystemExit(NO_TUYA.format(missing=", ".join(missing))) + return cfg + if program == "bot": + for f in fields(cls): + if f.name in REQUIRED_BY_BOT: + _required(getattr(cfg, f.name), f.default, f.metadata["env"]) + if not cfg.mcp_url: + raise SystemExit(NO_SERVICE) + return cfg if not (cfg.ecowitt or cfg.airgradient): - raise SystemExit("Set ECOWITT_API_KEY + ECOWITT_APP_KEY and/or HOMEASSISTANT_URL + HOMEASSISTANT_TOKEN and/or AIRGRADIENT_API_TOKEN + " - "AIRGRADIENT_LOCATION_ID and/or AIRGRADIENT_LOCAL_URL") + raise SystemExit("Set MCP_ECOWITT_API_KEY + MCP_ECOWITT_APP_KEY and/or MCP_HOMEASSISTANT_URL + MCP_HOMEASSISTANT_TOKEN and/or " + "MCP_AIRGRADIENT_API_TOKEN + MCP_AIRGRADIENT_LOCATION_ID and/or MCP_AIRGRADIENT_LOCAL_URL") return cfg diff --git a/lib/daytable.py b/lib/daytable.py index 0244d07b..e66a6229 100644 --- a/lib/daytable.py +++ b/lib/daytable.py @@ -7,7 +7,6 @@ import logging import operator -import re from dataclasses import dataclass, field from collections.abc import Callable from datetime import date, datetime, timedelta, tzinfo @@ -36,54 +35,6 @@ def noun(name: str) -> str: return PRETTY.get(base, base.replace("_", " ")) -def parameters(fields: list[str], what: str, extra: dict | None = None) -> dict: - """The tool's JSON schema for these fields (`what` names the unit of a day's figure for the descriptions).""" - return { - "type": "object", - "properties": { - "start_date": {"type": "string", "description": "First day, 'YYYY-MM-DD'. Use the start of the 'on record' range for all time."}, - "end_date": {"type": "string", "description": "Last day, 'YYYY-MM-DD' (today's readings aren't final, so up to yesterday)."}, - "where": {"type": "array", "description": f"Conditions that must ALL hold on the same day, e.g. {what}.", - "items": {"type": "object", "properties": { - "field": {"type": "string", "enum": fields}, - "op": {"type": "string", "enum": list(OPS)}, - "value": {"type": "number"}}, "required": ["field", "op", "value"]}}, - "sort_by": {"type": "string", "description": "Rank matching days by this: a field from the where.field list. Default: the first condition's field."}, - "order": {"type": "string", "enum": ["desc", "asc"], "description": "desc = highest first (default), asc = lowest first."}, - "count_only": {"type": "boolean", "description": "true for \"how many days\": returns just the counts, no list of days (much smaller). Use it whenever the days themselves aren't asked for."}, - "group_by": {"type": "string", "enum": ["month", "year"], "description": "Break the result down per month or year, months with none included. It is drawn as a bar chart."}, - "stat": {"type": "string", "enum": list(STATS), "description": "What each month or year (or the whole period, with no group_by) shows: count (default: matching days), or the max, min, avg or sum of the field `of` over the matching days. E.g. rain total per month: stat sum, of rain, group_by month."}, - "of": {"type": "string", "description": "The field to take max, min, avg or sum of (a field from the where.field list; not needed for count)."}, - "limit": {"type": "integer", "description": f"How many days to list (default 5, at most {MAX_LIMIT}). The total is always counted."}, - **(extra or {}), - }, - "required": ["start_date", "end_date"], - } - - -GROUPING = re.compile(r"\b(?:per|by|each|every)\s+(year|month)\b|\b(yearly|annual\w*)\b|\b(monthly)\b", re.I) - - -def grouping_in(text: str) -> str | None: - """"month" or "year" when the words ask for figures by or per month or year, else None.""" - found = GROUPING.search(text or "") - if not found: - return None - return "month" if (found.group(1) or "").lower() == "month" or found.group(3) else "year" - - -def grouped_as_asked(args: dict, turn) -> dict: - """The arguments with group_by filled in from the person's words when the model left it out ("... by year", "per month"): - a count by year or month is a bar chart, never one overall number.""" - if args.get("group_by") or turn is None or not getattr(turn, "text", ""): - return args - by = grouping_in(turn.text) - if not by: - return args - log.info("group_by %s added: the question asks for figures by %s", by, by) - return {**args, "group_by": by} - - def validate(args: dict, fields: dict[str, str]) -> str | None: """An error message for arguments that can't be used, else None. `fields` maps each field name to its unit.""" where = args.get("where") or [] diff --git a/lib/ecowitt/dashboard.py b/lib/ecowitt/dashboard.py index fdc86659..6f256d04 100644 --- a/lib/ecowitt/dashboard.py +++ b/lib/ecowitt/dashboard.py @@ -1,25 +1,34 @@ -"""The dashboard's gauges from the station: each reading as it is now, with its highest and lowest today, this month and this year. +"""The station's gauges: what each shows (GAUGES: its reading, its scale and colours, the day figures beside it) and their figures, each +reading as it is now with its highest and lowest today, this month and this year (figures()). Now is the live reading. The extremes are the day rows' (days.day_values_on: exact days from the 5- or 30-minute readings where they hold the day, else the daily buckets; today from what there is so far), which take in the bands the bot and Home Assistant saw between the -5-minute readings, with the live reading counted in, so the day's figures are never behind the gauge. A tile is left out when the station -has no such reading at all (no indoor sensor), and drawn dimmed when it has one but not now. +5-minute readings, with the live reading counted in, so the day's figures are never behind the gauge. + +The service's `current` with `context` gives these figures (lib/service/current.py context_of); the bot lays its sheet of gauges out +from that result (lib/gauge_sheet.py), with GAUGES' scales and colours. """ +import math from dataclasses import dataclass from datetime import date, timedelta -from ..specs import Dashboard, Tile -from ..storage import Storage -from .days import day_values_on - COLD_TO_HOT = ("#7DE7FF", "#B2EEFA", "#F7C9C9", "#EE7070", "#D32F27") WATER = ("#DFFBFF", "#B2EEFA", "#80E5FA", "#4FB3D6", "#2C7592") PRESSURE = ("#C5CAFA", "#A5ABF7", "#8087F5", "#5C5CF0", "#3F2FD0") WIND = ("#E8E8E8", "#C8CDD2", "#A2ABB4", "#7C8790", "#56626C") SUN = ("#FBE79A", "#F5D45A", "#F2A53C", "#D27A2A", "#A9501F") UV = ("#A9E34B", "#F7E04A", "#F4A93B", "#E8562A", "#9A1F5A", "#7A2CF0") -DEGREES = (60, 40, 20, 0, -20, -40) +DEGREES = (40, 30, 20, 10, 0) # a thermometer's scale as it starts (THERMOMETER), before it widens to take in the reading +THERMOMETER = (0, 40, 10) # a thermometer's scale: its ends and its step, in °C; widened a step at a time to the reading + + +def degree_colour(lower: float) -> str: + """The colour of a thermometer's band of 10 degrees, from its lower end: blues below 0, pinks to reds above.""" + for top, colour in ((-10, "#7DE7FF"), (0, "#B2EEFA"), (10, "#F7C9C9"), (20, "#F2A0A0"), (30, "#EE7070"), (40, "#E04A42")): + if lower < top: + return colour + return "#D32F27" @dataclass(frozen=True) @@ -36,21 +45,31 @@ class Gauge: 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) + + @property + def reading(self) -> str: + """The service's name of the reading it shows (lib/service/names.py): its live reading's, the rain gauge's "daily" being + rainfall.rain.""" + group, field = self.live + return f"{group}.{'rain' if field == 'daily' else field}" GAUGES = ( - Gauge("Temperature", "°C", "thermometer", -40, 60, COLD_TO_HOT, DEGREES, ("outdoor", "temperature"), "temp_max", "temp_min"), + 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"), - Gauge("Dew point", "°C", "thermometer", -40, 60, COLD_TO_HOT, DEGREES, ("outdoor", "dew_point"), "dew_point_max", "dew_point_min"), - Gauge("Feels like", "°C", "thermometer", -40, 60, 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), + 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("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("Indoor temperature", "°C", "thermometer", -40, 60, COLD_TO_HOT, DEGREES, ("indoor", "temperature"), "indoor_temp_max", "indoor_temp_min"), + 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), ) @@ -58,6 +77,20 @@ class Gauge: STATUS = ("Temperature", "Humidity", "Rain") # the gauges the report ("status") carries +def scale(gauge: Gauge, value: float | None) -> tuple[float, float, tuple[str, ...], tuple[float, ...]]: + """(low end, high end, the bands' colours from the low end, the numbers) of a gauge's scale for this reading. A thermometer's is + 0 to 40 °C, widened by 10 degrees at a time to take in a reading outside it (-3 °C: -10 to 40), its bands coloured by their + degrees; every other gauge's is fixed.""" + if gauge.kind != "thermometer": + return gauge.low, gauge.high, gauge.colours, gauge.ticks + low, high, step = THERMOMETER + if value is not None: + low = min(low, math.floor(value / step) * step) + high = max(high, math.ceil(value / step) * step) + bands = range(int(low), int(high), step) + return low, high, tuple(degree_colour(b) for b in bands), tuple(range(int(high), int(low) - 1, -step)) + + def gauges_of(titles=None) -> list[Gauge]: """The gauges with these titles, in the dashboard's order (all of them when None).""" return [g for g in GAUGES if titles is None or g.title in titles] @@ -88,28 +121,3 @@ def figures(gauge: Gauge, values: dict, days: list[date], now: float | None) -> 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) return tuple(row) - - -def sheet(live: dict, values: dict, today: date, titles=None) -> Dashboard | None: - """The dashboard from a live reading and the days' figures, with the gauges of these titles only (all when None); None when the - station has none of the readings.""" - tiles = [] - days = periods_of(today) - for gauge in gauges_of(titles): - now = live_value(live, gauge.live) - if now is None and not any(values.get(name) for name in (gauge.highest, gauge.lowest) if name): - continue - rows = {name: figures(gauge, values, days[name], None if gauge.total else now) for name in PERIODS} - if gauge.total and now is not None: # today's rain is the gauge's own reading, whatever the day's cached figure lags behind - rows["Daily"] = (None, now) - columns = ("Max", "Total") if gauge.total else ("Max", "Min") if gauge.lowest else ("Max",) - tiles.append(Tile(gauge.title, gauge.unit, now, gauge.kind, gauge.low, gauge.high, gauge.colours, columns, rows, gauge.ticks, gauge.decimals)) - return Dashboard(tiles) if tiles else None - - -async def dashboard(live: dict, storage: Storage, mac: str, today: date, titles=None) -> Dashboard | None: - """The gauges (of these titles; all when None) for a live reading ({group: {field: {value, unit}}}, as Ecowitt's real_time gives - it), the extremes from the day rows of the year so far: one read.""" - names = sorted({n for g in gauges_of(titles) for n in (g.highest, g.lowest) if n}) - values, _ = await storage.read(day_values_on, mac, names, periods_of(today)["Yearly"]) - return sheet(live, values, today, titles) diff --git a/lib/ecowitt/days.py b/lib/ecowitt/days.py index 8511d9dd..c460a0d5 100644 --- a/lib/ecowitt/days.py +++ b/lib/ecowitt/days.py @@ -1,4 +1,5 @@ -"""Find, rank and count days by what the station read, from the storage alone (never asks Ecowitt). +"""The station's day fields and how a day's figures are read from storage (never asks Ecowitt), for the service's `days` and `current` +and `summary` (lib/service). Questions like "the hottest day it also rained" or "how many days over 35" compare readings on the same day across a long period, which the history tool's summaries can't answer. Each day's figures are @@ -10,19 +11,11 @@ """ import logging -import operator -import re -from datetime import date, datetime, tzinfo +from datetime import date -from ..daytable import analyse, grouped_as_asked, lists_days, parameters, prepare from ..series import WEATHER -from ..storage import Storage from ..storage.catalogue import column_of from ..storage.read import Reader -from ..timeutil import day_text, now_local -from ..tools import json_result -from .api import daily_run -from .calendar import PublicHolidays log = logging.getLogger(__name__) @@ -50,23 +43,6 @@ FIELD_UNITS = {n: f[3] for n, f in FIELDS.items()} ALWAYS_SHOWN = ("temp_max", "temp_min", "rain") # every listed day shows them; days rank by the first when nothing else is named -PARAMETERS = parameters(list(FIELDS), "rain >= 1 and temp_max > 30", { - "only": {"type": "string", "enum": ["public_holiday", "weekend"], - "description": "ONLY when the person's words say holidays or weekends: look just at public holidays in the owner's local area " - "(the bot knows them: never pick holiday dates yourself) or just Saturdays and Sundays. Days are then counted " - "from those only, so never set it otherwise."}}) -DESCRIPTION = ("Find, rank or count DAYS by the station's readings, checking every day in the period: for questions that " - "compare readings on the same day or count days (\"the hottest day it also rained\", \"how many days over " - "35°C\", \"how many days was UV 9 or more\", \"the wettest day\", \"the windiest cold day\"). Fields: temp_max / temp_min (outdoor °C), " - "rain (mm total for the day; a rainy day is 1 mm or more, above 0 is only a trace), wind_gust (km/h, highest), and a day's " - "highest (_max) or lowest (_min) of every other reading: humidity, pressure, dew_point, feels_like, vpd, " - "indoor_temp, indoor_humidity (_max and _min); wind_speed, solar, uv, rain_rate (_max only), e.g. uv_max >= 9; and _avg, a day's mean (temp_avg, " - "humidity_avg, pressure_avg ...). For \"how many\" use count_only; group_by month or year breaks it down and draws a bar chart. " - "For a total, average, highest or lowest per month or year use stat and of (\"rain per month\": stat sum, of rain; \"hottest day each " - "year\": stat max, of temp_max; \"average humidity per month\": stat avg, of humidity_avg). Returns the total of matching " - "days and the top ones. For a record's value and the time it happened (hottest, coldest, fastest gust), use weather_history instead. For ONE known day, give start_date = end_date = that day and no conditions: it returns that day's figures. Can be limited to local public holidays or weekends (only). Works from cached history, so any period up to the whole record is fast.") - - PARTS = {"high": "hi", "low": "lo", "mean": "mean"} # a figure's kind -> where a day row (storage.read.Days) keeps it COARSER = {"5min": 0, "30min": 1, "1day": 2} @@ -100,78 +76,3 @@ def day_values_on(r: Reader, mac: str, shown: list[str], days) -> tuple[dict[str values[name][d] = v source[d] = max(source.get(d, src), src, key=COARSER.get) return values, {d: "daily" if s == "1day" else s for d, s in source.items()} - - -async def find_days(storage: Storage, mac: str, tz: tzinfo, args: dict, now: datetime, turn=None) -> dict: - asked = prepare(args, FIELD_UNITS, ALWAYS_SHOWN, now.date()) - if isinstance(asked, str): - return {"error": asked} - only = args.get("only") - if only not in (None, "public_holiday", "weekend"): - return {"error": "only must be public_holiday or weekend"} - calendar = PublicHolidays(tz) - if only == "public_holiday" and not calendar.available: - return {"error": calendar.problem()} - kind = {None: lambda d: True, "weekend": lambda d: d.weekday() >= 5, - "public_holiday": lambda d: calendar.name(d) is not None}[only] - first, last, shown, where, sort_by = asked.first, asked.last, asked.shown, asked.where, asked.sort_by - days = asked.days - values, source = await storage.read(day_values_on, mac, shown, days) - - checked = [d for d in days if kind(d) and any(d in values[n] for n in shown)] - got = analyse(values, asked, checked, tz, turn, - lambda d: {**({"holiday": calendar.name(d)} if only == "public_holiday" else {}), - "source": "daily" if source.get(d) == "daily" else "exact"}, - {"public_holiday": "public holidays only", "weekend": "weekends only"}.get(only, "")) - out, matches, ranked, rank, holds, row = got.out, got.matches, got.ranked, got.rank, got.holds, got.row - - # Days that would have ranked higher had a trace of rain counted: the answer should mention them - trace: list[date] = [] - rain_cond = next((c for c in where if c["field"] == "rain" and c["op"] in (">", ">=") and c["value"] > 0), None) - if rain_cond: - relaxed = [{"field": "rain", "op": ">", "value": 0} if c is rain_cond else c for c in where] - matched = set(matches) - better = operator.lt if args.get("order", "desc") == "asc" else operator.gt - for d in rank(d for d in checked if holds(d, relaxed)): - if d in matched: - break # from here on the real matches rank at least as high - if not ranked or better(values[sort_by][d], values[sort_by][ranked[0]]): # strictly ahead, not a tie - trace.append(d) - if len(trace) == 2: - break - - exact_days = sorted(d for d in checked if source.get(d) != "daily") - if not lists_days(args): - trace = [] # just the figures - if trace: - out["trace_rain_days"] = [row(d) for d in trace] - out["note_trace"] = (f"These days rank higher but had less than {rain_cond['value']:g} mm of rain (a trace), so they " - "are not in \"days\". Mention the first as a short footnote.") - if any(source.get(d) == "daily" for d in checked): - out["exact_from"] = day_text(exact_days[0]) if exact_days else None - out["note_daily"] = (f"Days marked \"daily\" come from daily readings that run {daily_run(tz, first, last)}, so their rain and dates " - "are approximate (a morning shower can be counted on the day before). Say so briefly if any " - "listed day is marked daily, or if the period reaches back before exact_from.") - if AVERAGED & set(shown) and any(source.get(d) != "5min" for d in checked): - out["note_averaged"] = ("For these readings, days from 30-minute or daily data use each interval's average, so a day's true peak " - "(or low) may be a little beyond what is listed: a count of days at or past a limit can fall slightly short " - "near the limit. Say so briefly.") - if not checked: - out["note"] = "No cached readings for this period yet (the bot may still be downloading history)." - log.info("Days %s to %s: %d checked, %d match, %d exact", first, last, len(checked), len(matches), len(exact_days)) - return out - - -HOLIDAY_WORDS = re.compile(r"\b(holidays?|weekends?|saturdays?|sundays?)\b", re.I) - - -async def days_tool(storage: Storage, mac: str, tz: tzinfo, args: dict, turn=None) -> str: - if args.get("only") and turn is not None and turn.text and not HOLIDAY_WORDS.search(turn.text): - # the model added a holiday or weekend filter nobody asked for: it would count only those days (and, with holidays, - # only the years the calendar knows), so it is dropped - log.warning("Ignored only=%s: the question doesn't mention holidays or weekends (%s)", args["only"], turn.text[:60]) - args = {k: v for k, v in args.items() if k != "only"} - args = grouped_as_asked(args, turn) - now = now_local(tz) - result = await find_days(storage, mac, tz, args, now, turn) # (one read of the day rows; the rest is quick enough to stay here) - return json_result(result) diff --git a/lib/ecowitt/homeassistant.py b/lib/ecowitt/homeassistant.py index 6a122ac9..ec3fc72b 100644 --- a/lib/ecowitt/homeassistant.py +++ b/lib/ecowitt/homeassistant.py @@ -83,8 +83,8 @@ def failed(self, what: str, error: object, then: str = ""): self.failing = True hint = "" if any(m in str(error).lower() for m in NAME_NOT_FOUND): - hint = local_name_hint(urlsplit(self.url).hostname or "", "HOMEASSISTANT_URL") or ( - f". The name in HOMEASSISTANT_URL ({self.url}) can't be found from here: check it, or use the address (http://192.168.x.x:8123)") + hint = local_name_hint(urlsplit(self.url).hostname or "", "MCP_HOMEASSISTANT_URL") or ( + f". The name in MCP_HOMEASSISTANT_URL ({self.url}) can't be found from here: check it, or use the address (http://192.168.x.x:8123)") log.warning("Home Assistant: the %s failed (%s)%s%s", what, error, f"; {then}" if then else "", hint) def ok(self): diff --git a/lib/ecowitt/link.py b/lib/ecowitt/link.py index 27dea082..bbe10f2f 100644 --- a/lib/ecowitt/link.py +++ b/lib/ecowitt/link.py @@ -1,4 +1,4 @@ -"""weather_link: does rain come with a change in another reading (pressure by default)? Both series are read together +"""Does rain come with a change in another reading (pressure by default)? Both series are read together from the 30-minute readings held, so it is about WHEN the rain fell, not what a day's extremes were. Nothing here calls Ecowitt: it works from what the archive holds. @@ -7,21 +7,17 @@ falling, steady or rising; the reading's average level in wet and dry slots; a correlation between the change before and the rain after; and the biggest rain spells with the change that preceded each.""" -import asyncio import logging -from datetime import date, datetime, time, tzinfo +from datetime import date, datetime, tzinfo from ..analysis.pairs import analyse -from ..captions import LINK_CHART_HINT, wants_chart from ..lines import build_line, shaded_up_to, slot_readings from ..rain import rain_bars, rain_slots from ..panels import panel_for from ..series import WEATHER from ..specs import Chart, Line, stack -from ..storage import Storage from ..storage.read import Reader -from ..timeutil import day_bounds, day_text, local_date, now_local, parse_period, period_parameters -from ..tools import json_result +from ..timeutil import day_bounds, day_text, local_date, parse_period from .reads import slot_values_on log = logging.getLogger(__name__) @@ -29,23 +25,6 @@ DEFAULT_DAYS = 90 DRIVERS = {"pressure": 1.0, "humidity": 5.0, "wind": 5.0} # a reading (series) -> the change over 3 hours that counts as falling or rising -PARAMETERS = { - "type": "object", - "properties": { - **period_parameters(DEFAULT_DAYS), - "driver": {"type": "string", "enum": list(DRIVERS), - "description": "The reading to relate to rain. Default pressure (relative)."}, - "chart": {"type": "boolean", "description": "Set true for a chart: the reading as a line, rain as bars behind it."}, - }, -} -DESCRIPTION = ("Does rain come WITH a change in pressure (or humidity or wind)? Reads both together at 30-minute " - "resolution from the cache and reports how much rain fell while the reading was falling, steady or " - "rising over the previous 3 hours, the reading's level in wet and dry periods, a correlation, and the " - "biggest rain spells with the change before each. Use it for 'is there a correlation between pressure and " - "rainfall', 'did the rain come with the pressure drop' and 'plot pressure against rainfall'. Up to the " - "whole record; never averaged to days.") - - def reading_slots(r: Reader, mac: str, name: str, start: int, end: int) -> tuple[dict, dict, dict]: """(values, lows, highs) per 30-minute slot of a reading (series), as every chart of it shades them: the band is the row's (Ecowitt's own lows and highs, widened by its 5-minute readings and the live readings the bot and Home Assistant saw). A reading shaded up to @@ -114,11 +93,3 @@ def link(read, mac: str, tz: tzinfo, args: dict, now: datetime) -> tuple[dict, C out["days_with_data"] = len({local_date(t, tz) for t in rain}) spec = chart_spec(driver, rain, tz, first, last, name, lows, highs) return out, spec, first, last - - -async def link_tool(storage: Storage, mac: str, tz: tzinfo, args: dict, turn) -> str: - out, spec, first, last = await asyncio.to_thread(link, storage.read_now, mac, tz, args, now_local(tz)) - if spec and wants_chart(args, turn, datetime.combine(first, time()), datetime.combine(last, time())): - turn.charts.append(spec) - out["chart"] = LINK_CHART_HINT - return json_result(out) diff --git a/lib/ecowitt/query.py b/lib/ecowitt/query.py index 3caf4db7..bddfda72 100644 --- a/lib/ecowitt/query.py +++ b/lib/ecowitt/query.py @@ -4,16 +4,15 @@ where the storage has it, else 30-minute: one request per week); longer, the 30-minute readings where the storage holds them all, else Ecowitt's daily records (10am to 10am in Melbourne: UTC days) and the newest days at 30 minutes. The records, the breakdown by day or by month and the averages come from the period's days instead (period.py): each whole day's row, worked out from the finest readings held -for it, so a record's time is as close as those readings give it, and the part of a day at either end from its own readings. +for it, so a record's time is as close as those readings give it, and the part of a day at either end from its own readings. An average +weighs each of those days by the time of it the period holds. """ import logging from datetime import date, datetime, time, timedelta -from statistics import fmean from ..captions import AVERAGE_CHART_HINT, CHART_HINT, STACK_CHART_HINT, DIRECTION_CHART_HINT, wants_chart -from ..lines import DAY, Plotted, Sample, build_line, how_drawn, shaded_up_to -from ..daytable import grouping_in +from ..lines import DAY, Plotted, Sample, build_line, how_drawn, shaded_up_to, time_mean from ..rain import rain_bars, rain_slots from ..timeutil import at_hour, day_bounds, day_text, local_date, now_local, parse_local, SLOT from ..storage.catalogue import text @@ -301,7 +300,7 @@ def _result(self, key: str, ext: dict) -> dict: if self.held: # each month's low/high with when and date for w, e in d.items(): _, row[f"{w}_when"], row[f"{w}_date"] = describe_time(e.ts, e.cycle, tz) - if (self.args.get("average") or self.turn.average_asked) and not key.startswith("rainfall"): # a rain total has no mean + if (self.args.get("average") or self.turn.average_asked) and p.column.mode != "last": # a rain counter (a total) has no mean; rain rate has self._add_averages(entry, {d.day: d.mean for d in p.days if d.mean is not None}) return entry @@ -337,21 +336,22 @@ def _label(self, day: date) -> str: ("Oct 2026") when the period is broken down by month.""" return day_text(day, year=False) if self.by_day else f"{day:%b %Y}" - def _add_averages(self, entry: dict, means: dict): - """The mean over the period, and per row of the breakdown (each day, or each month): the answer to "what was the average".""" - if not means: + def _add_averages(self, entry: dict, means: dict[date, float]): + """The mean over the period, and per row of the breakdown (each day, or each month): the answer to "what was the average". By + time, as a day row takes its own mean (lines.time_mean): each day's mean counts for the seconds of it the period holds, so the part + of a day at either end counts for its hours, not as a whole day, and a month for its time.""" + span = self.f.epoch(self.start), self.f.epoch(self.end), self.tz + if (mean := time_mean(means, *span)) is None: return fmt = lambda v: f"{v:.1f}" - entry["average"] = fmt(fmean(means.values())) - table = entry.get("daily" if self.by_day else "monthly") + entry["average"] = fmt(mean) + table = entry.get("daily" if self.by_day else "monthly") or {} + rows: dict[str, dict[date, float]] = {} for d, v in means.items(): - if table is not None and (label := self._label(d)) in table: - table[label].setdefault("_sum", []).append(v) - for table in (entry.get("daily"), entry.get("monthly")): - for row in (table or {}).values(): - values = row.pop("_sum", None) - if values: - row["avg"] = fmt(fmean(values)) + if (label := self._label(d)) in table: + rows.setdefault(label, {})[d] = v + for label, days in rows.items(): + table[label]["avg"] = fmt(time_mean(days, *span)) def _chart_spec(self, series_out: dict, field: str | None = None) -> Chart | None: """Line chart: one line per group for the field asked about (`field`, else chart_field; temperature by default, @@ -451,6 +451,8 @@ def _series_entry(self, k: str) -> tuple[Line, str] | None: line = self._shaded(self.lines.get(k), self.lines.get(band) if band else None) elif how == "days": line = self._shaded(self._day_line(k, at), self._day_line(band, at) if band else None) + elif k not in self.store: # its figures came from the day rows, but no readings in the window to draw (a quiet last hours) + return None else: line = build_line(self._series_readings(k), self.tz, self.span.total_seconds(), smooth=k in SMOOTH_SERIES, force_daily=self.turn.average_asked, until=now_local(self.tz).date()) @@ -475,8 +477,7 @@ def _rain_bars(self, held: Held) -> Bars: if day not in days and self.start.date() <= day <= self.end.date(): rain[day_bounds(day, self.tz)[0] + 12 * 3600] = mm self.rain_from_daily = True - by = None if self.by_day else grouping_in(self.turn.text) - return rain_bars(rain, self.tz, self.start.date(), self.end.date(), until=hi, by=by, since=lo) + return rain_bars(rain, self.tz, self.start.date(), self.end.date(), until=hi, since=lo) def _stack_spec(self, names: list[str]) -> Chart | None: """The readings asked for, one panel each on a shared time axis (rain behind the first line); None if fewer than diff --git a/lib/ecowitt/reads.py b/lib/ecowitt/reads.py index 8d3fa06c..2cefc71d 100644 --- a/lib/ecowitt/reads.py +++ b/lib/ecowitt/reads.py @@ -47,8 +47,9 @@ def readings_on(r: Reader, mac: str, groups: list[str], cycle: str, start: int, known = units[group] if units is not None else r.fields(sensor.id, cycle) for column, values in got.values.items(): c, name = BY_NAME[sensor.kind][column], field_of(group, column) - written = lambda v: None if v is None else round(v, c.decimals) + 0.0 # (as text() writes it: no "-0.0") - pts = {t: Sample(t, written(v), written(lo), written(hi), seconds) + d = c.decimals # (each figure as text() writes it: rounded, no "-0.0"; inline: a year of readings is a million of them) + pts = {t: Sample(t, round(v, d) + 0.0, None if lo is None else round(lo, d) + 0.0, None if hi is None else round(hi, d) + 0.0, + seconds) for t, v, lo, hi in zip(got.ts, values, got.lo[column], got.hi[column]) if v is not None} if pts: into.setdefault(f"{group}.{name}", {"unit": known.get(name, ""), "pts": {}})["pts"].update(pts) diff --git a/lib/ecowitt/source.py b/lib/ecowitt/source.py index 68574ff0..871cfe85 100644 --- a/lib/ecowitt/source.py +++ b/lib/ecowitt/source.py @@ -1,6 +1,6 @@ """The Ecowitt weather station as a data source, peer of AirGradient: -start() finds the station, tools are what the model can call, warm()/poke() keep recent -readings ready, readings() feeds the alert monitors.""" +start() finds the station, warm()/poke() keep recent readings ready, readings() feeds the alert monitors, and the service's tools +(lib/service) read its file and its live reading.""" import asyncio import logging @@ -13,75 +13,24 @@ from ..config import Config from ..lines import RANGE_KEEP_DAYS from ..sources import Source -from ..specs import ECOWITT_SOURCE -from ..timeutil import local_epoch, naive_local, when -from ..tools import Tool, Turn, json_result +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 .calendar import PublicHolidays -from .link import DESCRIPTION as LINK_DESCRIPTION, PARAMETERS as LINK_PARAMETERS, link_tool -from .days import DESCRIPTION as DAYS_DESCRIPTION, PARAMETERS as DAYS_PARAMETERS, days_tool -from .dashboard import dashboard -from .glance import glance +from ..public_holidays import PublicHolidays from .fetch import Fetcher, Recent from .fallback import FallbackAPI, newest from .hass_api import HomeAssistantAPI from .homeassistant import HomeAssistant from .live import BUCKET, readings_in -from ..series import READING_GROUPS, WEATHER, find +from ..series import READING_GROUPS from ..storage import Storage from ..storage.catalogue import AIR from ..storage.write import MIN_READINGS -from .query import HistoryQuery, KEEP_HOURS, chart_field, stack_names +from .query import KEEP_HOURS from .reads import newest_minute_on log = logging.getLogger(__name__) -DEFAULT_GROUPS = "outdoor,indoor" - -def parse_groups(value, default: str = DEFAULT_GROUPS) -> list[str]: - """'outdoor, indoor' or ['outdoor', 'indoor'] -> ['outdoor', 'indoor'] (plain group names only). A reading named instead of - its group ("humidity", "dew_point", "rain") becomes its group; a name Ecowitt has no such group for is dropped, since one - bad name fails the whole request.""" - parts = value if isinstance(value, list) else str(value or default).split(",") - named = (p.split(".")[0].strip().lower() for p in parts if p.strip()) - groups = (g if g in GROUPS else (r.group if (r := find(g)) else None) for g in named) - return list(dict.fromkeys(g for g in groups if g)) or default.split(",") - -HISTORY_PARAMS = { - "type": "object", - "properties": { - "start_date": {"type": "string", "description": "Start, 'YYYY-MM-DD HH:MM:SS' local time."}, - "end_date": {"type": "string", "description": "End, 'YYYY-MM-DD HH:MM:SS' local time (today is fine: up to now)."}, - "groups": {"type": "string", "description": "Comma-separated group names, e.g. 'outdoor,indoor'. Add 'rainfall', " - "'wind' or 'pressure' only if needed. Plain group names, not dotted fields."}, - "chart_fields": {"type": "array", "items": {"type": "string", "enum": list(WEATHER)}, - "description": "To plot SEVERAL readings together ('plot temperature and rain'): which, in order, " - "one panel each on a shared time axis. The groups they need are fetched for you."}, - "two_axes": {"type": "boolean", "description": "Set true to draw the chart_fields as ONE panel with a scale each " - "(left and right axis) when the question says 'on two axes', 'dual axis' or 'overlay'."}, - "average": {"type": "boolean", "description": "Set true only when the question asks for an average or mean: adds the " - "period's average (and per day or month). Highs and lows are the default."}, - "chart_field": {"type": "string", "description": "What the chart should plot when the question is about something other " - "than temperature: the reading, e.g. 'humidity', 'pressure', 'wind', 'dew_point', 'solar' or 'uv' " - "(a wind chart shows the average speed shaded up to the gusts). " - "Omit for temperature."}, - "chart": {"type": "boolean", "description": "Set true to send a chart with the answer: for trends over several " - "days or longer, or when a graph/chart is asked for."}, - "include_derived": {"type": "array", "items": {"type": "string", "enum": ["feels_like", "app_temp", "dew_point", "vpd"]}, - "description": "Only when the question asks about feels-like, apparent temperature, dew point or " - "VPD: which of them to include. Otherwise omit (they are left out by default)."}, - }, - "required": ["start_date", "end_date"], -} -HISTORY_DESCRIPTION = ("History from the owner's Ecowitt weather station: each day's low/high and the overall extremes " - "with times, for any range up to 4 years. Resolution and units are handled automatically.") -REALTIME_PARAMS = { - "type": "object", - "properties": {"groups": {"type": "string", "description": "Comma-separated group names, e.g. 'outdoor,indoor'."}}, -} -REALTIME_DESCRIPTION = "Current readings from the owner's Ecowitt weather station." - 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) @@ -166,10 +115,6 @@ def __init__(self, cfg: Config, transport=None, ha_transport=None, storage: Stor 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 - self.tools = [Tool("weather_now", REALTIME_DESCRIPTION, REALTIME_PARAMS, self._realtime), - Tool("weather_history", HISTORY_DESCRIPTION, HISTORY_PARAMS, self._history, source=ECOWITT_SOURCE), - Tool("weather_days", DAYS_DESCRIPTION, DAYS_PARAMETERS, self._days, source=ECOWITT_SOURCE), - Tool("weather_link", LINK_DESCRIPTION, LINK_PARAMETERS, self._link, source=ECOWITT_SOURCE)] async def start(self): devices = await self.api.devices() @@ -211,48 +156,10 @@ def archive_pace(self) -> float | None: None for the archive's own.""" return 0.0 if isinstance(self.api, HomeAssistantAPI) else None - def describe(self) -> str: - created = f", created {self.created:%Y-%m-%d %H:%M}" if self.created else "" - return f"Ecowitt weather station '{self.station_name}'{created} (people say \"ecowitt\" or \"weather\")" - 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) - # ---------- tools ---------- - async def _history(self, args: dict, turn: Turn | None = None) -> str: - turn = turn or Turn() - groups = parse_groups(args.get("groups")) - groups += [g for n in stack_names(args, turn) if (g := WEATHER[n].group) not in groups] # what "plot temperature and rain" needs - if (r := find(chart_field(args, turn) or "")) and r.group not in groups: # ... and what a chart of one reading needs - groups.append(r.group) - return await HistoryQuery(self.fetcher(groups, urgent=not turn.ahead), args, turn).run() - - async def _days(self, args: dict, turn: Turn | None = None) -> str: - return await days_tool(self.storage, self.mac, self.tz, args, turn) - - async def _link(self, args: dict, turn: Turn | None = None) -> str: - return await link_tool(self.storage, self.mac, self.tz, args, turn or Turn()) - - async def _realtime(self, args: dict, turn: Turn | None = None) -> str: - groups = parse_groups(args.get("groups")) - data = await self._live_data(groups) - out, newest, emoji = {}, 0, {} - for grp, fields in data.items(): - for name, obj in (fields.items() if isinstance(fields, dict) else ()): - if isinstance(obj, dict) and "value" in obj: - out.setdefault(grp, {})[name] = f"{obj['value']} {obj.get('unit', '')}".strip() - try: - if tag := glance(grp, name, float(obj["value"])): - emoji[f"{grp}.{name}"] = tag - except (TypeError, ValueError): - pass - try: - newest = max(newest, int(obj.get("time") or 0)) - except (TypeError, ValueError): - pass - return json_result({"time": when(newest, self.tz) if newest else None, **out, **({"emoji": emoji} if emoji else {})}) - async def _live_data(self, groups: list[str], max_age: float = LIVE_FRESH_SECONDS, urgent: 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 @@ -305,11 +212,6 @@ async def _record_live(self, data: dict): except Exception as e: log.warning("Couldn't keep the live readings' ranges: %s", e) - async def dashboard(self, titles=None): - """The station's gauges (specs.Dashboard; those of these titles only, all when None): the live reading and each one's highs and - lows today, this month and this year; None when the station has no reading.""" - return await dashboard(await self._live_data(LIVE_GROUPS), self.storage, self.mac, self.now().date(), titles) - 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 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 @@ -385,10 +287,6 @@ async def warm(self, fresh: bool = True) -> str: for cycle, start in windows.items())) return f"Ecowitt {sum(f.calls for f in fetchers.values())} req" - def wants(self, text: str) -> bool: - """Should a question start refreshing this source? Weather data is used by nearly all.""" - return True - async def readings(self, cycle: str, start: datetime, end: datetime, groups: list[str] | None = None) -> list[tuple[int, dict]]: """Readings for the alert monitors ([(epoch, {"group.field": value, ...})]), from the storage (the newest fetched first).""" diff --git a/lib/forecast/source.py b/lib/forecast/source.py index 8ed36ce1..01f632ea 100644 --- a/lib/forecast/source.py +++ b/lib/forecast/source.py @@ -3,7 +3,6 @@ import logging import math -import re import time from datetime import date @@ -12,8 +11,6 @@ from ..config import Config from ..snapshots import Snapshots from ..sources import Source -from ..timeutil import when -from ..tools import Tool, Turn, json_result from ..warm import Warmer, in_sync_hours log = logging.getLogger(__name__) @@ -27,13 +24,6 @@ FORECAST_REFRESH_SECONDS = 15 * 60 FRESH_SECONDS = 10 * 60 # a question reuses a forecast this young -DESCRIPTION = ("The weather forecast for the owner's location: today and the days ahead, " - "each with a summary, the lowest and highest temperature and the chance of at least 1 mm of rain. Use it for forecast " - "questions ('what's tomorrow like', 'will it rain this week'). days = how many days from today (default 7, " - "at most 7: the whole week; pass 1 for 'today' and 2 for 'tomorrow'). The result's \"lines\" are ready-made, emoji included: copy them as they are, and put the result's " - "\"place\" in parentheses after the forecast heading, e.g. (Melbourne).") -PARAMETERS = {"type": "object", "properties": {"days": {"type": "integer", "description": "Days from today (default 7, at most 7)."}}} - SOURCE = "Open-Meteo" WMO = {0: "☀️ Clear.", 1: "🌤️ Mostly clear.", 2: "⛅ Partly cloudy.", 3: "☁️ Overcast.", 45: "🌫️ Fog.", 48: "🌫️ Fog.", 51: "🌧️ Light drizzle.", 53: "🌧️ Drizzle.", 55: "🌧️ Heavy drizzle.", 61: "🌧️ Light rain.", 63: "🌧️ Rain.", 65: "🌧️ Heavy rain.", 71: "🌨️ Snow.", 73: "🌨️ Snow.", @@ -79,7 +69,7 @@ def __init__(self, cfg: Config, location: tuple[float, float] | None = None, tra 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("FORECAST_LAT and FORECAST_LON go together: with only one set, the weather station's location is used") + 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.days: list[dict] | None = None @@ -88,24 +78,16 @@ def __init__(self, cfg: Config, location: tuple[float, float] | None = None, tra self.store = Snapshots(cfg.storage_path) self._load() self.warmer = Warmer(self.warm, FORECAST_REFRESH_SECONDS) - self.tools = [Tool("weather_forecast", DESCRIPTION, PARAMETERS, self.handle)] async def start(self): if not self.location: - raise RuntimeError("no location: set FORECAST_LAT and FORECAST_LON (or the weather station supplies one)") + 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) - def describe(self) -> str: - return "Weather forecast for the owner's location (Open-Meteo) (people say \"forecast\")" - - def wants(self, text: str) -> bool: - """Only forecast questions start a refresh; the report always uses what is cached.""" - return bool(re.search(r"\bforecast\w*|\btomorrow\b|\bthis week\b", text, re.I)) - # ---------- kept on disk ---------- def _load(self): """Start from the last forecast fetched (before the restart), so a night-time start needs no fetch.""" @@ -185,21 +167,3 @@ def upcoming(self, count: int = 2) -> list[dict]: def lines(self, count: int = 2) -> list[str]: today = self.now().date() return [f"{day_label(d['date'], today)}: {describe_day(d)}" for d in self.upcoming(count)] - - async def handle(self, args: dict, turn: Turn | None = None) -> str: - if self.days is None and not args.get("cached"): # the report ("cached") never fetches - try: - await self.warm(True) - except Exception as e: - log.warning("Forecast not readable: %s", e) - try: - count = max(1, min(7, int(args.get("days") or 7))) - except (TypeError, ValueError): - count = 7 - lines = self.lines(count) - if not lines: - return json_result({"error": "No forecast is available right now."}) - if turn: - turn.forecast_shown.extend(self.upcoming(count)) # remembered for the chat once the answer is sent - stamped = {"time": when(int(self.fetched_at), self.tz)} if self.fetched_at else {} # when it was last fetched - return json_result({"lines": lines, "place": self.place, "source": SOURCE, **stamped}) diff --git a/lib/gauge_look.py b/lib/gauge_look.py new file mode 100644 index 00000000..b11d92d3 --- /dev/null +++ b/lib/gauge_look.py @@ -0,0 +1,75 @@ +"""How the gauges look: the dashboard's colours and the shapes' sizes, shared by the PNG (lib/gauges.py, drawn with Pillow) and the +live web page (lib/web_dashboard.py, drawn by the browser from these same figures). Sizes are pixels of a CELL_W by CELL_H tile, the +top left 0, 0. Nothing here imports Pillow.""" + +from dataclasses import asdict + +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 +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 +WATER = "#4FB3F6" # the rain beaker's water +NEEDLE = "#3E86C0" +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 +ROWS = ("Daily", "Monthly", "Yearly") + + +def faded(tile: Tile) -> bool: + """A tile drawn dimmed (FADE): it has no reading now (only its figures: lib/gauge_sheet.py leaves out a tile with neither).""" + return tile.value is None + + +def floor(tile: Tile) -> float: + """Where a gauge with no reading rests, and the number it reads: 0, or the scale's low end where 0 isn't on it (pressure: 950).""" + return 0 if tile.low <= 0 <= tile.high else tile.low + + +def shown(tile: Tile) -> float: + """The reading a gauge shows: its reading now, else its floor.""" + return floor(tile) if tile.value is None else tile.value + + +def share(tile: Tile, value: float) -> float: + """How far along its scale (0 to 1) a reading sits: in proportion from the low end to the high one, or, on a scale of bands each an + equal share (`bounds`: the air gauges), its band's share and in proportion within it. Beyond the ends: at the end.""" + bounds = tile.bounds + if not bounds: + return min(max((value - tile.low) / (tile.high - tile.low), 0), 1) + if value <= bounds[0]: + return 0.0 + n = len(bounds) - 1 + for i, (lo, hi) in enumerate(zip(bounds, bounds[1:])): + if value <= hi: + return (i + (value - lo) / (hi - lo)) / n + return 1.0 + + +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, + "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], + "fade": FADE, "sweep": SWEEP, "start": START, "rows": list(ROWS)} + + +def tile_json(tile: Tile) -> dict: + """A tile as JSON: specs.Tile's fields, whether it is dimmed and its floor (where it rests with no reading).""" + out = asdict(tile) + out["rows"] = {name: list(figures) for name, figures in tile.rows.items()} + return {**out, "colours": list(tile.colours), "columns": list(tile.columns), "ticks": list(tile.ticks), "bounds": list(tile.bounds), + "faded": faded(tile), "floor": floor(tile)} diff --git a/lib/gauge_sheet.py b/lib/gauge_sheet.py new file mode 100644 index 00000000..f4580383 --- /dev/null +++ b/lib/gauge_sheet.py @@ -0,0 +1,118 @@ +"""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` +are of the lower of the last two readings, for its ratings). + +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). +""" + +import math + +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 .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; +# 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 + + +def call(titles=None) -> dict: + """current's arguments for the gauges of these titles (all when None), with context. All: no readings named, so every reading of + the station and the air sensor there is (an air sensor's readings named where there is none would be refused), and those the + station sends but its file hasn't recorded yet. Some: their readings named, so only their device is read (the report's three: the + weather station's).""" + if titles is None: + return {"context": True} + return {"readings": [g.reading for g in (*gauges_of(titles), *air_gauges_of(titles))], "context": True} + + +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).""" + if isinstance(gauge, AirGauge): + return figures.get("high"), figures.get("low") + 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,) + + +def _value(entry: dict, key: str = "value") -> float | None: + try: + return float(entry[key]) + except (KeyError, TypeError, ValueError): + return None + + +def _aqi_entry(air: dict) -> dict: + """The US AQI as a reading's entry, from the air sensor's PM2.5 and PM10 in current's result: now, and each period's high and low, + the higher of the two particles' AQI (us_aqi), with `from` the particle it is now ("PM2.5", "PM10"). Of the readings now, as the + PM2.5 and PM10 dials beside it show them: not the service's aqi_us, of the lower of the last two readings.""" + pm25, pm10 = air.get("pm2_5") or {}, air.get("pm10") or {} + now = us_aqi(_value(pm25), _value(pm10)) + entry = {"value": now[0] if now else None, "from": now[2] if now else None} + for key in ROWS.values(): + figures = {f: got[0] for f in ("high", "low") + if (got := us_aqi(_value(pm25.get(key) or {}, f), _value(pm10.get(key) or {}, f)))} + if figures: + entry[key] = figures + return entry + + +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) + 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 + if isinstance(gauge, AirGauge): + band = gauge.band(now) # (its own reading's: the name always where the needle is; the US AQI's says when PM10 sets it) + 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, + gauge.decimals, gauge.bounds, band) + columns = ("Max", "Total") if gauge.total else ("Max", "Min") if gauge.lowest 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) + + +def per_row(n: int) -> int: + """How many tiles to a row: three, up to ROWS_OF_THREE rows (the station's gauges); more, the columns (four to six) that make them + largest in a square picture.""" + if n <= PER_ROW * ROWS_OF_THREE: + return PER_ROW + 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).""" + 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)): + 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 {})): + entry = _aqi_entry(sensors.get(group) or {}) + if isinstance(entry, dict) and (tile := _tile(gauge, entry)): + tiles.append(tile) + tiles.sort(key=lambda t: FIRST.index(t.title) if t.title in FIRST else len(FIRST)) # (stable: the rest keep their order) + return Dashboard(tiles, per_row(len(tiles))) if tiles else None + + +__all__ = ["AIR_GAUGES", "GAUGES", "STATUS", "call", "per_row", "sheet"] diff --git a/lib/gauges.py b/lib/gauges.py index 9d16fe4a..8aaa1543 100644 --- a/lib/gauges.py +++ b/lib/gauges.py @@ -1,35 +1,24 @@ -"""The dashboard: the station's readings as gauges on a dark card, each with its highest and lowest of the day, month and year. - -A thermometer, a dial or a rain beaker per tile (specs.Tile), three tiles to a row, drawn on one canvas laid out in pixels (the top left -is 0, 0). A tile with no reading is dimmed. Safe to call from several threads, as charts.render is (they share its drawing lock). +"""The Status picture (ecobot://status, lib/status.py): the weather station's temperature, humidity and rain gauges on a dark card, its +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 +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 +charts.render is (they share its drawing lock). """ import math 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 .specs import Dashboard, 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 -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 -WATER = "#4FB3F6" # the rain beaker's water -NEEDLE = "#3E86C0" -CELL_W, CELL_H, MARGIN = 480, 575, 20 DPI = 100 -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 -ROWS = ("Daily", "Monthly", "Yearly") +TILE_H = 390 # a tile's height: its title and gauge (the web page's CELL_H also holds the tables under them) def _lw(width: float) -> float: @@ -72,13 +61,11 @@ def _thermometer(c: Canvas, tile: Tile, ox: float, oy: float, ink): half, radius, gap = TUBE_HALF, BULB_RADIUS, MERCURY_GAP _scale_bar(c, cx - half - BAR_GAP - BAR_WIDTH, top, bottom, tile, ink) inside = _thermometer_shape(cx, top - 10 + gap, half - gap, bulb, radius - gap) - level = bulb - math.sqrt((radius - gap) ** 2 - (half - gap) ** 2) # no reading: just the bulb - if tile.value is not None: - level = top + (1 - min(max((tile.value - tile.low) / (tile.high - tile.low), 0), 1)) * (bottom - top) + value = shown(tile) # (no reading: the floor) + level = top + (1 - share(tile, value)) * (bottom - top) c.polygon(clip_below(inside, level), ink(FILL)) # the column and the bulb, one shape, the same gap from the outline all round c.polygon(_thermometer_shape(cx, top - 10, half, bulb, radius), None, outline=ink(SOFT), width=_lw(2.5)) - if tile.value is not None: - _text(c, cx - 50, bulb, f"{_figure(tile.value, tile.decimals)} {tile.unit}", 40, ink(SOFT), ha="right") + _text(c, cx - 50, bulb, f"{_figure(value, tile.decimals)} {tile.unit}", 40, ink(SOFT), ha="right") def _beaker(c: Canvas, tile: Tile, ox: float, oy: float, ink): @@ -86,13 +73,13 @@ def _beaker(c: Canvas, tile: Tile, ox: float, oy: float, ink): _scale_bar(c, left - BAR_GAP - BAR_WIDTH, top, bottom - 10, tile, ink) round_ = 34 jar = rounded_rect(left, top - round_, right, bottom, round_, 12) - if tile.value is not None and tile.value > 0: - level = bottom - max((tile.value - tile.low) / (tile.high - tile.low), 0.02) * (bottom - 10 - top) + value = shown(tile) # (no reading: the floor, empty) + if value > tile.low: + level = bottom - max(share(tile, value), 0.02) * (bottom - 10 - top) c.polygon(clip_below(jar, level), ink(WATER)) c.polygon(jar, None, outline=ink(SOFT), width=_lw(2.5)) c.rect(left - 8, top - round_ - 2, right + 8, top, BG) # the jar has no lid - if tile.value is not None: - _text(c, ox + 290, oy + 345, f"{_figure(tile.value, tile.decimals)} {tile.unit}", 46, ink(SOFT)) + _text(c, ox + 290, oy + 345, f"{_figure(value, tile.decimals)} {tile.unit}", 46, ink(SOFT)) def _polar(cx: float, cy: float, radius: float, degrees: float) -> tuple[float, float]: @@ -101,7 +88,7 @@ def _polar(cx: float, cy: float, radius: float, degrees: float) -> tuple[float, def _angle(tile: Tile, value: float) -> float: - return START - SWEEP * min(max((value - tile.low) / (tile.high - tile.low), 0), 1) + return START - SWEEP * share(tile, value) def _band(cx: float, cy: float, inner: float, outer: float, a0: float, a1: float) -> list[tuple[float, float]]: @@ -122,52 +109,32 @@ def _dial(c: Canvas, tile: Tile, ox: float, oy: float, ink): x, y = _polar(cx, cy, LABEL_RADIUS, _angle(tile, tick)) _text(c, x, y, f"{tick:g}", 17, ink(SOFT)) _text(c, cx, cy + 64, tile.unit, 18, ink(SOFT)) - if tile.value is not None: - a = _angle(tile, tile.value) - tip, tail = _polar(cx, cy, RING_OUTER - BAND_WIDTH - 6, a), _polar(cx, cy, -24, a) # the needle reaches nearly to the scale - left, right = _polar(cx, cy, 10, a + 90), _polar(cx, cy, 10, a - 90) - c.polygon([tip, left, tail, right], ink(NEEDLE)) - _text(c, cx, cy + 102, _figure(tile.value, tile.decimals), 50, ink(INK)) + value = shown(tile) # (no reading: the floor) + a = _angle(tile, value) + tip, tail = _polar(cx, cy, RING_OUTER - BAND_WIDTH - 6, a), _polar(cx, cy, -24, a) # the needle reaches nearly to the scale + left, right = _polar(cx, cy, 10, a + 90), _polar(cx, cy, 10, a - 90) + c.polygon([tip, left, tail, right], ink(NEEDLE)) + _text(c, cx, cy + 102, _figure(value, tile.decimals), 50, ink(INK)) c.circle(cx, cy, 25, BG, outline=ink(SOFT), width=_lw(3)) -def _chip(c: Canvas, x: float, y: float, w: float, h: float, colour, text: str, ink, size=19, weight="normal", text_colour=INK): - c.polygon(rounded_rect(x, y, x + w, y + h, 9), colour) - _text(c, x + w / 2, y + h / 2 + 1, text, size, ink(text_colour), weight=weight) - - -def _table(c: Canvas, tile: Tile, ox: float, oy: float, ink): - """The unit, a head for each column (Max, Min, Total) and a row each of Daily, Monthly and Yearly.""" - left, top, w, h, gap = ox + 60, oy + 378, 128, 38, 4 - columns = [left + (w + gap) * (i + 1) for i in range(len(tile.columns))] - _text(c, left + w / 2, top + h / 2, tile.unit, 17, ink(INK), weight="bold") - for x, name in zip(columns, tile.columns): - _chip(c, x, top, w, h, ink(CHIPS[name]), f"{MARKS[name]} {name}", ink, weight="bold", text_colour="#FFFFFF") - for r, name in enumerate(ROWS, start=1): - y = top + r * (h + 10) - _chip(c, left, y, w, h, ink(CHIP), name, ink, text_colour=SOFT) - for x, figure in zip(columns, tile.rows.get(name, ())): - _text(c, x + w / 2, y + h / 2 + 1, "-" if figure is None else _figure(figure, tile.decimals), 21, ink(INK), weight="bold") - - DRAW = {"thermometer": _thermometer, "dial": _dial, "beaker": _beaker} def _tile(c: Canvas, tile: Tile, ox: float, oy: float): - keep = 1.0 if tile.value is not None or any(any(f is not None for f in figures) for figures in tile.rows.values()) else FADE + keep = FADE if faded(tile) else 1.0 ink = (lambda colour: _blend(colour, 1 - keep, BG)) if keep < 1 else (lambda colour: colour) # dimmed towards the card _text(c, ox + CELL_W / 2, oy + 38, tile.title, 38, ink(INK)) DRAW[tile.kind](c, tile, ox, oy, ink) - _table(c, tile, ox, oy, ink) def render(dashboard: Dashboard) -> bytes: - """PNG bytes for the dashboard: CELL_W by CELL_H pixels a tile, `per_row` to a row.""" + """PNG bytes for the gauges: CELL_W by TILE_H pixels a tile, `per_row` to a row.""" per_row = dashboard.per_row rows = math.ceil(len(dashboard.tiles) / per_row) - width, height = per_row * CELL_W + 2 * MARGIN, rows * CELL_H + 2 * MARGIN + width, height = per_row * CELL_W + 2 * MARGIN, rows * TILE_H + 2 * MARGIN with _DRAWING: c = Canvas(width, height, BG) for i, tile in enumerate(dashboard.tiles): - _tile(c, tile, MARGIN + (i % per_row) * CELL_W, MARGIN + (i // per_row) * CELL_H) + _tile(c, tile, MARGIN + (i % per_row) * CELL_W, MARGIN + (i // per_row) * TILE_H) return c.png() diff --git a/lib/history.py b/lib/history.py index 2d7faaed..c3af61b1 100644 --- a/lib/history.py +++ b/lib/history.py @@ -1,7 +1,7 @@ -"""The `readings` tool: one reading's stored values at a fixed interval, each with its time, read straight from the bot's file (lib/storage). +"""One reading's stored values at a fixed interval, each with its time, read straight from the bot's file (lib/storage): the engine of the +service's `readings` tool (lib/service/readings.py), and the readings the service knows (Metric, station_metrics, air_metrics). It answers "humidity each hour for the last 5 hours", "PM2.5 every 30 minutes this morning" and other requests for a table of values. -weather_history gives a period's highs, lows, averages and charts; this gives the readings themselves. Every interval is offered for every reading. - An interval a sensor stores is read as it is: Ecowitt's 5min, 30min and 4hour, Home Assistant's and the air sensor's minutes, and the @@ -18,9 +18,7 @@ """ import logging -import time as clock from bisect import bisect_left, bisect_right -from collections.abc import Callable from datetime import date, datetime, time, timedelta, tzinfo from typing import NamedTuple @@ -32,8 +30,7 @@ from .storage.catalogue import BY_NAME, KINDS, OTHER, RAIN_COUNTERS, Column, column_of, kind_of, text from .storage.read import FINE, Reader from .storage.schema import q -from .timeutil import clock_text, day_text, local_date, local_epoch, parse_local, to_local, when -from .tools import Tool, Turn, json_result +from .timeutil import clock_text, day_text, local_date, local_epoch, to_local, when log = logging.getLogger(__name__) @@ -104,39 +101,18 @@ def station_metrics(sent: dict[str, dict[str, str]] | None = None) -> list[Metri return out +async def station_fields(eco) -> dict[str, dict[str, str]]: + """The fields the station (an Ecowitt source, started) has sent, as the file's `fields` table has them: {group: {field: unit}}, the + `sent` station_metrics reads.""" + return await eco.storage.read(lambda r: {s.external: r.fields(s.id) for s in r.sensors(device=eco.mac) if s.kind != AIR_SENSOR}) + + def air_metrics(extra: bool = False) -> list[Metric]: """The air sensor's readings, with its own temperature and humidity when `extra` (offered only when a question names them).""" names = [*AIR, *(AIR_EXTRA if extra else ())] return [Metric(AIR_SENSOR, n, AIR_SENSOR, BY_NAME[AIR_SENSOR][n], AIR_STORED[n][1]) for n in names] -def parameters(names: list[str]) -> dict: - return { - "type": "object", - "properties": { - "metric": {"type": "string", "enum": names, - "description": "The sensor and reading, e.g. outdoor.humidity, indoor.temperature, pressure.relative, " - "wind.wind_gust, rainfall.rain (mm that fell in each interval), air.pm2_5. One per call: " - "outdoor and indoor are two calls, made together."}, - "start": {"type": "string", "description": "Start, 'YYYY-MM-DD HH:MM' local time."}, - "end": {"type": "string", "description": "End, 'YYYY-MM-DD HH:MM' local time. Default: now."}, - "interval": {"type": "string", "enum": list(INTERVALS), - "description": "One row per interval, a block of local time (1hour runs from :00 to :00; 4hour follows the station's " - "own 4-hour records, whose times say where they start). 1min goes back 10 days."}, - }, - "required": ["metric", "start", "interval"], - } - - -DESCRIPTION = ( - "The stored readings of ONE metric at a fixed interval, a row per interval with its time: for values at set times or per interval " - "(\"humidity each hour for the last 5 hours\", \"PM2.5 every 30 minutes this morning\", \"rain each hour today\", a table of " - "values; for one moment such as 3pm, a few minutes either side at 5min). Each row: the interval's average with its lowest and highest (rain: the mm that fell in it; gusts: the " - f"highest). At most {MAX_ROWS} rows: pick an interval that fits (5min for a few hours, 1hour for up to 12 days, 4hour for up to 7 " - "weeks, 1day for up to 300 days). For a period's highs and lows, records, averages or a chart use weather_history or air_quality.") -PARAMETERS = parameters([m.name for m in [*station_metrics(), *air_metrics()]]) # the tool as offered before any file is read (the evals) - - def interval_starts(start: int, end: int, width: int, tz: tzinfo) -> list[int]: """The starts of the intervals of `width` seconds that hold [start, end]: blocks of local time from midnight, so an hour runs from :00 whatever the zone's offset, and a day from midnight; across a daylight-saving change one is an hour longer or shorter. Four hours are @@ -335,101 +311,4 @@ def read_days(r: Reader, m: Metric, sensor: int, first: date, last: date, tz: tz "mean": "the day's average, with its lowest and highest and when they happened"} -class History: - """The `readings` tool over the weather station's and the air sensor's stored readings (either may be missing).""" - - def __init__(self, eco=None, air=None, sent: dict[str, dict[str, str]] | None = None, now: Callable[[], float] = clock.time): - """eco, air: the sources (Ecowitt, AirGradient), started. sent: the station's fields as the file has them ({group: {field: unit}}; - History.open reads them). now: the clock (a test's).""" - self.eco, self.air, self.now = eco, air, now - self.storage = eco.storage if eco else air.store.storage - self.tz = eco.tz if eco else air.tz - station = station_metrics(sent) if eco else [] - self.metrics = {m.name: m for m in [*station, *(air_metrics(extra=True) if air else [])]} - offered = [m.name for m in [*station, *(air_metrics() if air else [])]] - asked = [m.name for m in [*station, *(air_metrics(extra=True) if air else [])]] - self.tools = [Tool("readings", DESCRIPTION, parameters(offered), self.handle, - asked=(lambda: (DESCRIPTION, parameters(asked))) if air else None)] - - @classmethod - async def open(cls, eco=None, air=None) -> "History": - """The tool, with the readings the station has sent read from the file.""" - sent = await eco.storage.read(lambda r: {s.external: r.fields(s.id) for s in r.sensors(device=eco.mac) if s.kind != AIR_SENSOR}) if eco else None - return cls(eco, air, sent) - - def find(self, name: str) -> Metric | None: - """The metric a name means: its own name, else a reading's ("humidity", "uv", "pm2_5", "rain") on the sensor that has it. A sensor - named (indoor, air) is kept: "air.humidity" is the air sensor's own, never the outdoor humidity; "indoor.vpd" is none.""" - name = name.strip().lower() - if name in self.metrics: - return self.metrics[name] - prefix, _, bare = name.rpartition(".") - if prefix == AIR_SENSOR and (m := self.metrics.get(f"{AIR_SENSOR}.{AIR_SENSOR}_{bare}")): - return m - reading = WEATHER.get(bare) or next((r for r in WEATHER.values() if r.field == bare), None) - m = (reading and self.metrics.get(f"{reading.group}.{RAIN if reading.field == 'daily' else reading.field}") - or self.metrics.get(f"{AIR_SENSOR}.{bare}") or self.metrics.get(f"outdoor.{bare}")) - return None if m and prefix in ("indoor", AIR_SENSOR) and m.sensor != prefix else m - - def _sensor(self, m: Metric) -> int | None: - if m.air: - s = self.air.store.sensor() if self.air else None - else: - s = self.storage.sensors.find(self.eco.mac, m.sensor) if self.eco else None - return s.id if s else None - - def _time(self, value, default: int) -> int: - """A start or end as sent ("2026-11-09 01:00", with seconds, a "T", or an offset such as "Z", which is moved into local time).""" - if value in (None, ""): - return default - text = str(value).strip() - try: - local = parse_local(text, self.tz) - except ValueError: # trailing words ("2026-11-09 01:00 AEDT"): the time alone - local = parse_local(text.replace("T", " ")[:19], self.tz) - return local_epoch(local, self.tz) - - async def handle(self, args: dict, turn: Turn | None = None) -> str: - m = self.find(str(args.get("metric") or "")) - if m is None: - return json_result({"error": f"unknown metric {args.get('metric')!r}", "metrics": list(self.metrics)}) - interval = str(args.get("interval") or "").strip().lower() - interval = ALIASES.get(interval, interval) - if interval not in INTERVALS: - return json_result({"error": f"unknown interval {args.get('interval')!r}", "intervals": list(INTERVALS)}) - now = int(self.now()) - try: - start, end = self._time(args.get("start"), None), min(self._time(args.get("end"), now), now) - except (TypeError, ValueError): - return json_result({"error": "start and end are 'YYYY-MM-DD HH:MM', local time"}) - if start is None or start >= end: - return json_result({"error": "start must be before end (and before now)"}) - by_day = interval == "1day" and m.how != "last" # (a compass point has no day figures: the last reading of each day) - n = row_count(start, end, interval, self.tz) - too_many = n > (MAX_ROWS if by_day else MAX_ROWS + 1) # (an interval's count is exact only once listed: the first starts before `start`) - marks = [] if too_many or by_day else interval_starts(start, end, INTERVALS[interval], self.tz) - if too_many or len(marks) > MAX_ROWS: - fits = finest_fit(start, end, self.tz) - return json_result({"error": "too many rows", "rows": max(n, len(marks)), "max_rows": MAX_ROWS, "fits": fits, - "note": f"Ask again with interval {fits}." if fits else - "Too long even for days: split the period, or use weather_history or weather_days."}) - out = {"metric": m.name, "unit": m.unit, "interval": interval, "value_is": (DAY_VALUE_IS if by_day else VALUE_IS)[m.how]} - sensor = self._sensor(m) - if sensor is None: - return json_result({**out, "rows": [], "note": "Nothing is stored for this sensor yet."}) - if by_day: - first, last = local_date(start, self.tz), local_date(end, self.tz) - out |= await self.storage.read(read_days, m, sensor, first, last, self.tz) - partial = last == local_date(now, self.tz) - else: - out |= await self.storage.read(read_intervals, m, sensor, interval, marks, end, now, self.tz) - partial = marks[-1] + INTERVALS[interval] > now - if partial: - out["note_last"] = "The last row is still filling: it runs up to now." - if not any(row[1] is not None for row in out["rows"]): - out["note"] = (f"No readings at this interval for this period: ask again with interval {out['fits']}." if out.get("fits") else - "No readings are stored for this period at this interval: say so; never fill the gap.") - return json_result(out) - - -__all__ = ["DESCRIPTION", "History", "INTERVALS", "MAX_ROWS", "PARAMETERS", "air_metrics", "interval_starts", "parameters", "station_metrics"] +__all__ = ["INTERVALS", "MAX_ROWS", "air_metrics", "interval_starts", "read_days", "read_intervals", "station_fields", "station_metrics"] diff --git a/lib/intent.py b/lib/intent.py index 2b130c4e..4fa6a51d 100644 --- a/lib/intent.py +++ b/lib/intent.py @@ -1,28 +1,13 @@ -"""What a message is asking for, decided with patterns rather than the model. - - - how much the model should think (only predictions and "describe it" questions get reasoning); - - whether fresh data must be fetched first (weather / air questions); - - the fast path: simple "period + highs/lows", chart and "air quality now" questions become a - tool call built here, so the model's first round trip is skipped and it is only invoked once - the data is in, to word the answer. Anything not clearly matched returns None and takes the - normal path, so strictness is the point. +"""How much the model should think about a typed question, decided from its words (docs/ecobot-mcp.md 4): only predictions, analysis +and "describe it" questions get reasoning, and a question that asks the bot to think gets more. Nothing else is decided in code: every +typed question goes to the model (step 6c), and the words go on as they are. """ -import logging import re -from collections.abc import Collection -from dataclasses import dataclass, field -from datetime import date, datetime, timedelta - -from .logs import BUGS -from .daytable import GROUPING, grouping_in -from .series import AIR as AIR_TABLE, INDOOR_READINGS, PRESSURE_WORDS, READING_GROUPS, SPECIFIC, WEATHER as WEATHER_READINGS - -log = logging.getLogger(__name__) I = re.IGNORECASE -# ---------- reasoning and fetching ---------- +# ---------- reasoning ---------- EFFORT_DEFAULT, EFFORT_DESCRIBE, EFFORT_THINK = "none", "low", "medium" EFFORT_STEPS = ("none", "low", "medium", "high") @@ -32,33 +17,6 @@ def lower_effort(effort: str) -> str | None: i = EFFORT_STEPS.index(effort) if effort in EFFORT_STEPS else 0 return EFFORT_STEPS[i - 1] if i else None -# The words that name each reading, shared by every pattern below: the series table's, and a breeze is wind too -_TEMP = WEATHER_READINGS["temperature"].words -_WIND = rf"{WEATHER_READINGS['wind'].words}|breez\w*" -# Which temperature words make a message a weather question that must fetch ("only that it's cold" is chat): "temp", "temperature", -# "how hot/cold ...", and the superlatives that rank days ("hottest weekends"). _TEMP (all the words) still names the reading. -_TEMP_ASK = r"temp\w*|how (?:hot|cold|warm|cool|freezing)|(?:hott|cold|warm|cool)est" -_PRESSURE = PRESSURE_WORDS -# The two devices by name: "ecowitt" is the weather, "ag" / "airgradient" / "air gradient" the air quality -_ECOWITT = r"ecowitt" -_AG = r"air ?gradient|ag" -AIR_METRICS = [(m.words, name) for name, m in AIR_TABLE.items()] # words -> metric; checked in order, so PM10 wins over PM1 -_AIR_METRIC = "|".join(words for words, _ in AIR_METRICS) # the words that name an air reading, for every pattern below -_OTHER_THAN_AIR = rf"temp\w*|rain\w*|wind\w*|humid\w*|hot|cold|warm|pressure|weather|{_ECOWITT}" # a question that is not (only) about the air -# The words of every reading but temperature and feels-like, which name their reading more broadly than a question asks for it -# ("cool, thanks", "feeling better"): those two ask with _TEMP_ASK and "feels" instead -_READING_ASK = "|".join(r.words for name, r in WEATHER_READINGS.items() if name not in ("temperature", "feels_like")) - -# Messages about the weather or air must fetch fresh data; anything else (thanks, chat) needn't -WEATHER = re.compile( - rf"\b(weather|{_ECOWITT}|{_AG}|{_TEMP_ASK}|{_READING_ASK}|frost\w*|pollen|hay ?fever|asthma|" - rf"rain\w*|showers?|drizzle|storms?|thunder\w*|hail|snow|fog\w*|cloud\w*|sun\w*|uv|solar|" - rf"{_WIND}|humid\w*|dew|{_PRESSURE}|forecast\w*|umbrella|" - r"highs?|lows?|max\w*|min\w*|records?|extremes?|average|chart\w*|graph\w*|plot\w*|trend\w*|" - r"indoors?|outdoors?|inside|outside|conditions|feels?|today|tonight|tomorrow|yesterday|" - rf"week|month|year|air|aqi|{_AIR_METRIC}|smok\w*|pollut\w*|stuffy)\b|°|" - r"\b\d{1,2}(st|nd|rd|th)?\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\w*|" - r"\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\w*\s+\d{1,2}\b|\b\d{1,2}/\d{1,2}\b", I) # Describing a day or playing along with a hypothetical benefits from a little thinking DESCRIBE = re.compile( @@ -71,21 +29,18 @@ def lower_effort(effort: str) -> str | None: r"tonight|tomorrow|later|soon|coming|next (few )?(hour|hours)|this (afternoon|evening)|" r"should i|chance of|likely|expect\w*|predict\w*|outlook)\b", I) - # Combining readings across days or conditions ("the hottest day that also rained", "how many days ...") ANALYSIS = re.compile( r"\b(also|both|same day|at the same time|coincid\w*|combination|how many days|how often|" r"(days?|times?|when) (when|that|where|with|it)|(that|where|when) (it )?(also|and)|" r"(hottest|coldest|wettest|driest|windiest|warmest|coolest)\b.*\b(that|where|when|but|and)\b)", I) - # Is one reading tied to another ("is there a correlation between pressure and rain"): the answer is a judgement LINK = re.compile( r"\b(correlat\w*|(link|links|linked|connection|connected|relation|relationship|relationships|relate|related|relates)\b" r".*\b(between|to|with)\b|(between|with)\b.*\b(link|connection|relation\w*)|cross[- ]?referenc\w*|cross[- ]?check\w*|" r"(does|do|did|is|are)\b.*\b(affect\w*|influence\w*|predict\w*|cause\w*)\b.*\b(rain|pressure|humidity|wind|temperature)\w*)\b", I) - # Asking the model to think: "think about it", "try to work out why", "reason it through", "predict", "estimate", "grind", "whirl" THINK = re.compile(r"\b(think\w*|try|trying|reason\w*|predict\w*|estimat\w*|grind\w*|whirl\w*)\b", I) @@ -99,804 +54,12 @@ def reasoning_effort(text: str) -> str: return next((effort for effort, patterns in EFFORT_RULES if any(p.search(text) for p in patterns)), EFFORT_DEFAULT) -def _only(words: str, lead: str = "") -> str: - """A pattern for a message that is just these words (optionally with please, a lead-in and punctuation).""" - return rf"^\s*(please\s+)?{lead}({words})(\s+please)?\s*[?.!]*\s*$" - - -_ASK = r"((give me|show me|show|get|what's|whats)\s+)?(the\s+)?" # the usual lead-in: "show me the ...", "what's the ..." - - -# "status", "report": the whole current picture from both devices (a period word or a subject makes it something else) -REPORT = re.compile(_only(r"status|report|sitrep|overview|summary|everything|what you'?ve got", - _ASK + r"(a\s+)?(full\s+|current\s+|complete\s+)?"), I) - - -def wants_report(text: str) -> bool: - return bool(REPORT.search(text)) and not TIME_WORDS.search(text) - - -# "dashboard", "gauges": the station's readings as gauges, with each one's highs and lows (drawn in code from the station alone) -DASHBOARD = re.compile(_only(r"(weather\s+)?(dashboard|gauges?|dials?)(\s+(now|right now))?", _ASK), I) - - -def wants_dashboard(text: str) -> bool: - return bool(DASHBOARD.search(text)) and not TIME_WORDS.search(text) - - -def report_calls(sources: Collection[str]) -> list[tuple[str, dict]]: - """What the full report needs from these sources (by name), fetched together before the model sees the question.""" - calls = {"Ecowitt": ("weather_now", {"groups": NOW_GROUPS}), "AirGradient": ("air_quality", {}), - "Pollen": ("pollen_asthma", {"cached": True}), "Forecast": ("weather_forecast", {"days": 3, "cached": True})} - return [call for name, call in calls.items() if name in sources] - - -# Pollen and thunderstorm asthma (the Pollen source) -POLLEN_WORDS = re.compile(r"\b(pollen|hay ?fever|thunderstorm asthma|asthma)\b", I) -POLLEN_NOW = re.compile(_only(r"pollen( count| level| forecast| today| now)?|hay ?fever|(thunderstorm )?asthma( risk)?", - _ASK), I) - - -def mentions_pollen(text: str) -> bool: - return bool(POLLEN_WORDS.search(text)) - - -POLLEN_FILLER = frozenset("pollen hay fever hayfever asthma thunderstorm count counts level levels risk forecast today bad high like much " - "dangerous okay ok safe".split()) - - -def pollen_ask(text: str) -> bool: - """Is this only a plain question about the pollen or thunderstorm asthma ("is the pollen bad today", "how's the hay fever")?""" - return mentions_pollen(text) and _only_words(text, POLLEN_FILLER.__contains__) - - -def _only_words(text: str, fits) -> bool: - """Is every word of the text filler (FILLER: what, is, the, now ...) or one `fits` (a word -> bool) takes?""" - return all(word in FILLER or fits(word) for word in re.findall(r"[\w'’.]+", text.lower())) - - -# "weather", "weather now", "current weather", "ecowitt": every reading the station has right now (the weather half of the report) -NOW_GROUPS = ",".join(READING_GROUPS) -WEATHER_NOW = re.compile(_only(rf"(weather|{_ECOWITT}|conditions)(\s+(now|right now|currently|at the moment))?|(current|latest)\s+(weather|conditions)", - _ASK), I) - - -def wants_weather_now(text: str) -> bool: - return bool(WEATHER_NOW.search(text)) and not TIME_WORDS.search(text) - - -# Questions about the bot itself ("what metrics do you have", "list our sources"): answered from what it knows, no fetch -ABOUT_THE_BOT = re.compile( - r"\b(what|which|list|show)\b.*\b(metrics?|sensors?|sources?|devices?)\b|" - rf"\bwhat (can|do) you (do|measure|track|have|know|tell)\b|\bwhat can (i|we) ask\b|\bwhat (does|do) ({_ECOWITT}|{_AG}) (measure|track|have|report|tell)\b|" - + _only(r"metrics?|sensors?|sources?|devices?", r"((our|the|my|available|all)\s+)*"), I) - - -def about_the_bot(text: str) -> bool: - return bool(ABOUT_THE_BOT.search(text)) and not TIME_WORDS.search(text) - - -# Asking the bot to DO something ("add an alert if winds reach 100 km/h") is not a request for readings -COMMAND = re.compile(r"^\s*(please\s+)?(add|set( up)?|create|remind|schedule|turn (on|off)|enable|disable|mute|unmute|subscribe)\b", I) - - -# Asking for the bot's view ("what do you think of weather in general"): a conversation, not a lookup, unless it names a time or a reading now -OPINION = re.compile(r"\b(what do you think|your (view|opinion|thoughts?)|philosoph\w*|do you (like|prefer|love|hate|enjoy))\b", I) -RIGHT_NOW = re.compile(r"\b(today|tonight|tomorrow|yesterday|now|currently|current|right now|outside|forecast\w*|this (morning|afternoon|evening|week))\b", I) - - -def is_opinion(text: str) -> bool: - return bool(OPINION.search(text)) and not RIGHT_NOW.search(text) and not TIME_WORDS.search(text) - - -def needs_data(text: str) -> bool: - """Must the model fetch before answering? Weather and air words say yes, unless it is an instruction or a question about the bot - or its opinion: those are not forced to call a tool.""" - return bool(WEATHER.search(text)) and not COMMAND.search(text) and not about_the_bot(text) and not is_opinion(text) - - -# ---------- periods ---------- -def period_ranges(today: date) -> dict[str, tuple[date, date]]: - """Named periods. The prompt's date list and the fast path both use these.""" - week_start = today - timedelta(days=today.weekday()) # Monday - month_start = today.replace(day=1) - prev_month_end = month_start - timedelta(days=1) - return { - "today": (today, today), - "yesterday": (today - timedelta(days=1), today - timedelta(days=1)), - "last 7 days": (today - timedelta(days=6), today), - "current calendar week": (week_start, today), - "last week": (week_start - timedelta(days=7), week_start - timedelta(days=1)), - "this month": (month_start, today), - "last month": (prev_month_end.replace(day=1), prev_month_end), - "this year": (today.replace(month=1, day=1), today), - "last year": (date(today.year - 1, 1, 1), date(today.year - 1, 12, 31)), - "past month": (today - timedelta(days=29), today), - "past year": (today - timedelta(days=364), today), - "on record": (today - timedelta(days=1459), today), # what Ecowitt keeps (also safe on 29 Feb) - } - - -# Phrase -> period name. Numbered periods ("4 months", "24h", "last 7 days") are parsed separately. -PERIOD_PHRASES = [ - # "the last year" / "in the last year" = rolling; bare "last year" = previous calendar year - (r"(on record|all[- ]time|of all time|ever recorded|ever|(the )?(full|whole|entire|complete|all( the)?) (history|record|data))", "on record"), - (r"(the )?past year|the last year", "past year"), - (r"(the )?past month|the last month", "past month"), - (r"(the )?past week|the last week|this week", "last 7 days"), - (r"(?<!the )last week", "last week"), - (r"this month", "this month"), - (r"(?<!the )last month", "last month"), - (r"this year", "this year"), - (r"(?<!the )last year", "last year"), - (r"(the )?(last|past) day", "last 24 hours"), - (r"yesterday", "yesterday"), - (r"today|so far today", "today"), -] -NUMBER_WORDS = {w: i for i, w in enumerate("zero one two three four five six seven eight nine ten eleven twelve".split())} -NUMBERED_PERIOD = re.compile( - r"(?<![\d.])(\d+|" + "|".join(list(NUMBER_WORDS)[1:]) + r") ?(hours?|hrs?|h|days?|d|weeks?|w|months?|mo|m|years?|y)\b(?! ago)", I) -# Any of these left unrecognised means the question names a period we can't read: let the model decide -TIME_WORDS = re.compile(r"\b(hours?|days?|weeks?|months?|years?|quarter|fortnight|decade|since|between|until|ago|ytd|" - r"(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?\s+(19|20)\d\d)\b", I) # (a month and year: "oct 2025") - - -def span(name: str, now: datetime) -> tuple[datetime, datetime]: - """Start and end of a named period. The rolling "last 24 hours" ends now; others cover whole days.""" - if name == "last 24 hours": - return default_span(now)[1:] - first, last = period_ranges(now.date())[name] - return datetime.combine(first, datetime.min.time()), datetime.combine(last, datetime.max.time()).replace(microsecond=0) - - -MAX_PERIOD_DAYS = 3650 # ten years: well past the four Ecowitt keeps, which the tools trim to what exists - - -def default_span(now: datetime) -> tuple[str, datetime, datetime]: - """The period of a chart that names none: the last 24 hours.""" - return numbered_span("24", "h", now) - - -def numbered_span(count: str, unit: str, now: datetime) -> tuple[str, datetime, datetime] | None: - """"4 months", "24h", "2 weeks": a rolling period ending now. One day means the last 24 hours; - longer ones cover whole days up to today (a month is 30 days, a year 365, as in the named periods).""" - n = int(count[:6]) if count.isdigit() else NUMBER_WORDS[count.lower()] # 6 digits at most: nothing sane is longer - u = unit.lower() - if n == 0: - return None - hours = n if u[0] == "h" else 24 if u[0] == "d" and n == 1 else 0 - days = hours / 24 if hours else n if u[0] == "d" else 7 * n if u[0] == "w" else 365 * n if u[0] == "y" else round(n * 365 / 12) - if days > MAX_PERIOD_DAYS: # beyond what any sensor has: the model can explain, dates would be nonsense - return None - if hours: - return f"last {hours} hours", now - timedelta(hours=hours), now - start = datetime.combine(now.date() - timedelta(days=days - 1), datetime.min.time()) - label = {"d": "days", "w": "weeks", "y": "years", "m": "months"}[u[0]] - return f"last {n} {label[:-1] if n == 1 else label}", start, datetime.combine(now.date(), datetime.max.time()).replace(microsecond=0) - - -_MONTH_NAMES = "jan feb mar apr may jun jul aug sep oct nov dec".split() -_MONTH_YEAR = r"(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?\s+((?:19|20)\d\d)" -# "oct 2025 to oct 2026", "from March 2025 until June 2025", "between jan 2026 and mar 2026", "oct 2025": whole calendar months -MONTHS_SPAN = re.compile(rf"\b(?:(?:from|between)\s+)?{_MONTH_YEAR}(?:\s*(?:to|until|till|through|and|-|–)\s*{_MONTH_YEAR})?\b", I) - - -def months_span(m: re.Match, now: datetime) -> tuple[str, datetime, datetime] | None: - """The calendar months a MONTHS_SPAN match names, from the first day of the first to the last day of the last (today at most); - None when it starts after today or ends before it starts.""" - first = date(int(m[2]), _MONTH_NAMES.index(m[1][:3].lower()) + 1, 1) - last = date(int(m[4]), _MONTH_NAMES.index(m[3][:3].lower()) + 1, 1) if m[3] else first - last = min((last.replace(day=28) + timedelta(days=4)).replace(day=1) - timedelta(days=1), now.date()) - if first > now.date() or last < first: - return None - name = f"{first:%b %Y}" + (f" - {last:%b %Y}" if (first.year, first.month) != (last.year, last.month) else "") - return name, datetime.combine(first, datetime.min.time()), datetime.combine(last, datetime.max.time()).replace(microsecond=0) - - -HISTORY = re.compile(r"\bhistory\b", I) # with no other period named: the whole record - - -def _periods(text: str, now: datetime) -> dict[tuple[datetime, datetime], tuple[str, str]]: - """{(start, end): (the words said, the period's name)} for every distinct period the text names.""" - found: dict = {} - for m in MONTHS_SPAN.finditer(text): - if months := months_span(m, now): - found.setdefault(months[1:], (m.group(0), months[0])) - for phrase, name in PERIOD_PHRASES: - if m := re.search(rf"\b({phrase})\b", text, I): - found.setdefault(span(name, now), (m.group(0), name)) - for m in NUMBERED_PERIOD.finditer(text): - if numbered := numbered_span(m.group(1), m.group(2), now): - found.setdefault(numbered[1:], (m.group(0), numbered[0])) - if not found and (said := HISTORY.search(text)): # "co2 history": all of it - found[span("on record", now)] = (said.group(0), "on record") - if not found and (bare := BARE_PERIOD.search(text)): # "weather week", "aq month": as if "this ..." - name = BARE_PERIODS[bare.group(1).lower()] - found[span(name, now)] = (bare.group(0), name) - return found - - -def spans_in(text: str, now: datetime) -> list[tuple[str, datetime, datetime]]: - """Every distinct period the text names, as (name, start, end).""" - return [(name, *window) for window, (_, name) in _periods(text, now).items()] - - -DEFAULT_CHART_DAYS = 1 # a chart with no period named is the last day - - -def period_days(text: str, now: datetime) -> int: - """How many days the period a question names covers (a day when it names none).""" - spans = spans_in(text, now) - if not spans: - return DEFAULT_CHART_DAYS - _, start, end = spans[0] - return max(1, round((end - start).total_seconds() / 86400)) - - -def _has_days(text: str, days: int, now: datetime | None = None) -> bool: - """Does the text name a period of at least this many days?""" - now = now or datetime.now() - return bool(spans_in(text, now)) and period_days(text, now) >= days - - -def without_period(text: str, now: datetime) -> str: - """The question with its period taken out: "temperature chart 30d" -> "temperature chart".""" - for said, _ in _periods(text, now).values(): - text = re.sub(rf"(?:\b(?:for|over|in|during|the|past)\s+)*\b{re.escape(said)}\b", "", text, flags=I) - return " ".join(text.split()) - - -def with_period(text: str, days: int, now: datetime) -> str: - """The question with its period swapped for the last `days` days: "temperature chart 30d" -> "temperature chart 90d"; a question - that names no period gets one added.""" - return f"{without_period(text, now)} {days}d" - - -def period_hints(text: str, now: datetime) -> list[str]: - """One line per period the person's words name, with its exact dates, for the model: "3m" = the last 3 months: - 2026-07-01 00:00:00 to 2026-09-30 23:59:59. The model otherwise guesses short forms (3m has been read as 3 days).""" - return [f'"{said}" = {name}: {start:%Y-%m-%d %H:%M:%S} to {end:%Y-%m-%d %H:%M:%S}' - for (start, end), (said, name) in _periods(text, now).items()] - - -# ---------- weather fast path ---------- -_HILO = r"hottest|coldest|warmest|coolest|highest|lowest|highs?|lows?|max(imum)?|min(imum)?|extremes?" -# A highs/lows summary: naming the temperature asks for its range ("temps this week") -EXTREMES = re.compile(rf"\b({_HILO}|temperatures?|temps?)\b", I) -# A reading's highest or lowest, in so many words ("peak humidity", "strongest gust") -HILO = re.compile(rf"\b({_HILO}|peak|strongest|fastest)\b", I) -GRAPH = re.compile(r"\b(graph\w*|chart\w*|plot\w*|trend\w*|visuali[sz]\w*)\b", I) -# What no weather fast path answers: a comparison, a reason, a count, a look ahead or the reading right now (a period is the question) -_NOT_PLAIN = r"compare\w*|vs|versus|than|why|how many|days (above|below|over|under)|will|going to|now|right now|current\w*" -NOT_PLAIN = re.compile(rf"\b({_NOT_PLAIN})\b", I) -# The highs/lows summary is of the temperature alone: another reading, the air, an average or anything ahead goes the normal way -# (or another fast path) -NOT_HILO = re.compile(rf"\b({_NOT_PLAIN}|rain\w*|pressure|humid\w*|uv|solar|lightning|{_AIR_METRIC}|pm2|air|air quality|aqi?|smok\w*|pollut\w*|{_AG}|" - r"average|mean|median|feels?|dew|forecast\w*|tomorrow|tonight|later)\b", I) -WIND = re.compile(rf"\b({_WIND})\b", I) -# What a chart request with no period must name to default to the last day ("chart it" refers back instead) -WEATHER_SUBJECT = re.compile(rf"\b(weather|{_ECOWITT}|{_TEMP}|highs?|lows?|indoors?|outdoors?|inside|outside|station)\b", I) -WEATHER_WORD = re.compile(rf"\b(weather|{_ECOWITT}|conditions)\b", I) -# A period named on its own ("weather week", "aq month") is the rolling week, month or year ending today, not the calendar -# one (on the 1st, "month" must not be just today) -BARE_PERIODS = {"week": "last 7 days", "month": "past month", "year": "past year"} -BARE_PERIOD = re.compile(r"\b(week|month|year)\b", I) -INDOOR = re.compile(r"\b(indoors?|inside)\b", I) -OUTDOOR = re.compile(r"\b(outdoors?|outside)\b", I) -FMT = "%Y-%m-%d %H:%M:%S" -AVERAGE = re.compile(r"\b(averages?|avg|mean)\b", I) -# "all metrics", "everything", "aq all week" (every reading, a week), but not the period "all time" nor "every day" or "each month" -# How many of a unit, before it: "every 30 minutes", "every ten minutes", "every half an hour", "every couple of hours", "every other hour" -_HOW_MANY = (r"(?:\d+\s*|(?:a\s+)?few\s+|half[\s-]+(?:an?\s+)?|quarter[\s-]+(?:of\s+)?(?:an?\s+)?|other\s+|(?:a\s+)?couple(?:\s+of)?\s+|" - r"(?:one|two|three|four|five|six|ten|twelve|fifteen|twenty|thirty|forty|sixty)(?:[\s-]+five)?\s+)") -ALL = re.compile(rf"\b(all(?![\s-]+time\b)|everything|(?:every|each)(?!\s+{_HOW_MANY}?(?:days?|nights?|weeks?|months?|years?|hours?|hrs?|" - r"min(?:ute)?s?|times?)\b))\b", I) -# Values at an interval ("each hour", "every 30 minutes", "hourly", "in 15 minute steps"): the readings tool, through the model, never -# a whole period's highs and lows. A speed or a rate ("miles per hour", "mm per hour") is a unit, not an interval: UNIT_PER takes it out first. -INTERVAL = re.compile(rf"\b(?:each|every)\s+{_HOW_MANY}?(?:hours?|hrs?|min(?:ute)?s?)\b|\bper\s+(?:hour|minute)\b|\btwice\s+an\s+hour\b|" - r"\b(?:half[\s-]+)?hourly\b|\bhour[\s-]+by[\s-]+hour\b|" - r"\b\d+[\s-]*(?:min(?:ute)?s?|hours?|hrs?)\s+(?:intervals?|steps?|increments?|resolution)\b", I) -UNIT_PER = re.compile(r"(?:\b(?:kms?|kilomet(?:re|er)s?|mi|miles?|mm|millimet(?:re|er)s?|inch(?:es)?|metres?|meters?|m|ft|feet|knots?|kmh|kph|" - r"mph)|\d(?:km|mm|m))\s+per\s+(?:hour|minute)\b|\bkm/h\s+per\s+(?:hour|minute)\b", I) - - -def asks_interval(text: str) -> bool: - """Does the question want values at an interval ("humidity each hour", "pm2.5 every ten minutes")? A chart is drawn in code as before.""" - return bool(INTERVAL.search(UNIT_PER.sub(" ", text))) and not GRAPH.search(text) - - -PER_DAY = re.compile(r"\b(each|every|per|by)\s+day|daily|day[- ]by[- ]day|which days|list|breakdown|one by one", I) - - -def _named(text: str) -> dict[str, int]: - """The readings a question names, with where. "dew point temperature" names the dew point, not also the temperature.""" - found = {name: m.start() for name, r in WEATHER_READINGS.items() if (m := re.search(rf"\b({r.words})\b", text, I))} - if "temperature" in found and any(name in found for name in SPECIFIC): - del found["temperature"] - return found - - -FEELS_LIKE_IN_ALL = False # CHART_ALL_FEELS_LIKE=on puts the feels-like panel in "weather all week" (set from the config at startup) -VPD_IN_ALL = False # CHART_ALL_VPD=on puts the vapour pressure deficit panel in "weather all week" (it is temperature and humidity combined) -ALL_ORDER = ("temperature", "humidity", "solar", "pressure", "rain", "dew_point", "feels_like", "vpd", "uv", "wind") # the panels of "weather all week", top to bottom -LEFT_OUT_OF_ALL = ("uv",) # "weather all week" leaves these out: the UV index has the same shape as solar radiation - - -# "on two axes", "dual axis", "2 axes", "secondary axis", "overlay": two readings on one panel, each with a scale of its own -TWO_AXES = re.compile(r"\b(?:(?:two|2|dual|twin|double|secondary|second)[- ](?:y[- ]?)?ax[ie]s|overla(?:y(?:ed|ing|s)?|id))\b", I) - - -AG_NAMED = re.compile(rf"\b({_AG})\b", I) -AIR_EXTRA_WORDS = re.compile(r"\b(temp\w*|humid\w*)\b", I) - - -def wants_air_extra(text: str) -> bool: - """The air sensor's own temperature or humidity, named as the AirGradient's ("plot airgradient humidity over ecowitt humidity"): only - then are the tools offered those series. Temperature and humidity without the sensor named are the weather station's.""" - return bool(AG_NAMED.search(text) and AIR_EXTRA_WORDS.search(text)) - - -def chart_fields(text: str) -> list[str]: - """The readings named in the text, in order, when it names two or more ("plot temperature and rain"); else [].""" - found = _named(text) - if wants_chart_all(text): # "weather all week", "chart all 90d", "weather chart 90d": every reading, a panel each - indoors = _sides(text) == ["indoor"] # the indoor sensor only has these - return [n for n in ALL_ORDER if n not in LEFT_OUT_OF_ALL and (FEELS_LIKE_IN_ALL or n != "feels_like") - and (VPD_IN_ALL or n != "vpd") and (not indoors or n in INDOOR_READINGS)] # naming one still works - return sorted(found, key=found.get) if len(found) >= 2 else [] - - -def wants_chart_all(text: str) -> bool: - """"weather all week", "chart all 90d", "weather chart 90d": every reading, a panel each (the picture says it all: no caption). - A chart that names no reading is of all of them, not of temperature.""" - named = len(_named(text)) - if named < 2 and ALL.search(text) and WEATHER_WORD.search(text): - return True - asked = GRAPH.search(text) or WEATHER_WORD.search(text) and _has_days(text, 2) # "weather 30d" is a chart too - return named == 0 and bool(asked) and not mentions_air(text) and not _judgement(text) - - -def chart_field(text: str) -> str | None: - """The one reading a question is about, if it isn't temperature ("lowest and highest humidity"); None when it - is about temperature, several readings, or none in particular.""" - found = list(_named(text)) - return WEATHER_READINGS[found[0]].field if len(found) == 1 and found[0] != "temperature" else None - - -# "rain chart 7d": a rain chart whose caption is just the least and most rain -RAIN_CHART = re.compile(r"^\s*rain\s+(chart|graph|plot)\b[^,&+]*$", I) - - -def wants_rain_caption(text: str) -> bool: - return bool(RAIN_CHART.search(text)) and not re.search(r"\band\b", text, I) - - -JUDGEMENT = (FORECAST, LINK, THINK, ANALYSIS, DESCRIBE) # questions that want the model's thinking, not just a chart - - -def _judgement(text: str) -> bool: - return any(p.search(text) for p in JUDGEMENT) - - -def _sides(text: str) -> list[str]: - indoor, outdoor = bool(INDOOR.search(text)), bool(OUTDOOR.search(text)) - return ["indoor"] if indoor and not outdoor else ["outdoor"] if outdoor and not indoor else ["outdoor", "indoor"] - - -def _groups(text: str, names: list[str]) -> list[str]: - """The Ecowitt groups for these readings. Temperature and humidity come from both sensors unless one side is named; the - rest of what the indoor sensor measures (dew point, feels like) from the indoor one only when it is named.""" - groups = list(dict.fromkeys(WEATHER_READINGS[n].group for n in names)) - if "outdoor" in groups and ({"temperature", "humidity"} & set(names) or INDOOR.search(text) and set(INDOOR_READINGS) & set(names)): - groups = [g for g in groups if g != "outdoor"] + _sides(text) - return list(dict.fromkeys(groups)) - - -def bare_chart_ask(text: str, now: datetime) -> bool: - """Nothing but readings (or "weather") and a period: "humidity 7d", "weather 30d". Anything with a time range is a chart.""" - if not _has_days(text, 2, now) or not (_named(text) or WEATHER_WORD.search(text)): - return False # a day or less ("temperature today") is a figure to read, not a chart - rest = text - for said, _ in _periods(text, now).values(): - rest = re.sub(rf"\b{re.escape(said)}\b", " ", rest, flags=I) - patterns = [re.compile(rf"({r.words}|weather|{_ECOWITT}|conditions|indoors?|outdoors?)", I) for r in WEATHER_READINGS.values()] - return _only_words(rest, lambda word: any(p.fullmatch(word) for p in patterns)) - - -AVERAGE_READINGS = ("temperature", "humidity", "pressure", "wind", "dew_point", "feels_like", "vpd", "solar", "uv") # a rain total has no average - - -def _simple_weather(text: str, now: datetime) -> tuple[str, tuple[str, datetime, datetime], list[str]] | None: - """(kind, (period name, start, end), Ecowitt groups) for a weather question answered without the model, else None. The kinds: - "chart", a plain chart of named readings ("rain chart 7d", "plot temperature and humidity"); "average", a plain average, highest - or lowest of named readings ("average temp last week", "highest humidity yesterday"); "extremes", a highs/lows summary of the - temperature ("this week's high and low", "weather week", "indoor high yesterday"). A comparison, a forecast or a question that - wants thinking is the model's; so is one naming no period or several ("this week vs last week"), unless a chart's default (the - last day) applies.""" - if NOT_PLAIN.search(text): - return None - graph, plain, spans = bool(GRAPH.search(text)), not mentions_air(text) and not _judgement(text), spans_in(text, now) - if plain and (graph or bare_chart_ask(text, now)) and (fields := chart_fields(text) or list(_named(text))): - kind, groups, default = "chart", _groups(text, fields), not TIME_WORDS.search(text) - elif plain and (AVERAGE.search(text) or HILO.search(text)) and (names := list(_named(text))) and set(names) <= set(AVERAGE_READINGS): - kind, groups, default = "average", _groups(text, names), False - # "weather <period>" is a summary request too, but "weather today" also wants current conditions; wind only as a plain chart - # ("wind direction plot 3m"), and then it is just wind - elif (not (NOT_HILO.search(text) or "wind" in _named(text) and not graph) - and (EXTREMES.search(text) or graph or WEATHER_WORD.search(text) and spans and {n for n, _, _ in spans} != {"today"})): - kind, groups = "extremes", ["wind"] if WIND.search(text) else _sides(text) - default = graph and WEATHER_SUBJECT.search(text) and not TIME_WORDS.search(text) - else: - return None - if not spans and default: - spans = [default_span(now)] # "chart weather": the last day - return (kind, spans[0], groups) if len(spans) == 1 else None - - -# ---------- air-quality fast path ---------- -# "how's the air?", "what's the AQI", "report my airgradient aq". History, comparisons and mixed -# weather questions go the normal way. -AIR = re.compile(rf"\b(air|aqi|aq|{_AIR_METRIC}|smok\w*|pollut\w*|particulates?|particles?|{_AG})\b", I) -AIR_QUALITY = re.compile(r"\bair quality\b", I) -# What no air fast path answers: a comparison, a reason, a look ahead or another reading; the current reading also needs no past -# (period words, the past tense), no chart and no figure -_AIR_NOT = rf"compare\w*|vs|versus|than|why|forecast\w*|tomorrow|will|{_OTHER_THAN_AIR}" -AIR_CHART_NOT = re.compile(rf"\b({_AIR_NOT})\b", I) -AIR_NOT_NOW = re.compile( - rf"\b({_AIR_NOT}|yesterday|overnight|last|past|week|month|year|since|earlier|this morning|was|were|been|trend\w*|" - r"graph\w*|chart\w*|plot\w*|tonight|later|average|highest|lowest|peak|max\w*|min\w*|record\w*)\b", I) - - -def mentions_air(text: str) -> bool: - return bool(AIR.search(text) or AIR_QUALITY.search(text)) - - -def air_period(text: str, now: datetime) -> tuple[str, datetime, datetime] | None: - """(period name, start, end) for a plain air-quality chart request, else None. Any air question - with a period ("aq 1d", "air quality this week") is a chart; a graph word alone means the last - 24 hours.""" - if not mentions_air(text) or AIR_CHART_NOT.search(text): - return None - spans = spans_in(text, now) - if not spans and GRAPH.search(text) and not TIME_WORDS.search(text): - spans = [default_span(now)] - return spans[0] if len(spans) == 1 else None - - -PARTICULATES = re.compile(r"\b(particulates?|particles?|particulate matter)\b", I) - - -def air_named(text: str) -> list[str]: - """The air readings the text names ("pm10", "co2"); all of them for "all"; none if it only says air.""" - metrics = [m for _, m in AIR_METRICS] if ALL.search(text) else ["pm2_5", "pm10", "pm1"] if PARTICULATES.search(text) else [] - for pattern, metric in AIR_METRICS: - if re.search(rf"\b({pattern})", text, I) and metric not in metrics: - metrics.append(metric) - return metrics - - -def air_metrics(text: str) -> list[str]: - return air_named(text) or ["pm2_5"] - - -# ---------- dispatch ---------- -# A particular date, weekday or time of day: the fast path only knows whole periods, so these go to the model -_MONTHS = r"(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\w*" -SPECIFIC_MOMENT = re.compile( - rf"\b\d{{1,2}}(st|nd|rd|th)?\s+(of\s+)?{_MONTHS}|\b{_MONTHS}\s+\d{{1,2}}\b|\b\d{{1,2}}/\d{{1,2}}\b|" - r"\b\d{1,2}(:\d{2})?\s?(am|pm)\b|\b\d{1,2}:\d{2}\b|\b(noon|midnight|morning|afternoon|evening|overnight|tonight)\b|" - r"\b(mon|tues?|wed(nes)?|thu(rs?)?|fri|sat(ur)?|sun)(day)?\b", I) - -# Plain lookups, answered in code from the tool's own result (no model): what is said is nothing but the reading asked for -FILLER = frozenset("what whats what's how hows how's is are it its it's the a an of tell me give show please like reading level speed " - "now currently current right at moment outside outdoors outdoor indoors indoor inside out there any we point".split()) -FORECAST_PLAIN = re.compile(_only(r"(weather\s+)?forecast(\s+(for\s+)?(the\s+)?(this\s+|next\s+)?(week|7 days|seven days|coming days))?|" - r"(the\s+)?(7|seven)[- ]day (weather )?forecast|(the\s+)?week ahead", - _ASK), I) - - -def reading_now(text: str) -> list[str] | None: - """The readings named when the text is only a plain question about them right now ("how hot is it", "is it raining", "uv"), else None.""" - if (GRAPH.search(text) or TIME_WORDS.search(text) or SPECIFIC_MOMENT.search(text) or mentions_air(text) - or _judgement(text) or not (names := list(_named(text))) or len(names) > 2): - return None - patterns = [re.compile(rf"({WEATHER_READINGS[n].words}|indoors?|outdoors?)", I) for n in names] - return names if _only_words(text, lambda word: any(p.fullmatch(word) for p in patterns)) else None - - -# Counting, ranking or totalling over periods ("count days over PM2.5 of 90 per year", "how many times", "rain per month"): the model -# picks the days tool, never a plain chart of the period -COUNTING = re.compile(r"\b(count\w*|how many|how often|number of|days? (over|above|below|under|with|when|that|where)|" - r"(per|by|each|every) (year|month)|monthly|yearly|annual\w*|worst|rank\w*|top \d+)\b", I) - - -# "days over UVI 10 by year", "count days over PM2.5 of 90 per year", "how many days was UV 9 or more": one reading against one limit, -# counted in code with weather_days or air_days (the model is not asked, so the answer is always the same bar chart or count) -OR_MORE = re.compile(r"\bor (?:more|higher|above|greater|over)\b", I) -OR_LESS = re.compile(r"\bor (?:less|lower|below|under)\b", I) -AT_LEAST = re.compile(r"\b(?:at least|reach\w*|hit|hits)\b", I) -ABOVE = re.compile(r"\b(?:over|above|more than|greater than|higher than|exceed\w*)\b", I) -BELOW = re.compile(r"\b(?:under|below|less than|lower than|fewer than|at most)\b", I) -def _figures(name: str, stem: str) -> tuple[dict[str, str], str]: - """A reading's daily fields by stat (temp_max, temp_min, temp_avg); none for its lowest when it has no low worth telling.""" - return {"max": f"{stem}_max", **({"min": f"{stem}_min"} if WEATHER_READINGS[name].low else {}), "avg": f"{stem}_avg"}, "avg" - - -# A reading's weather_days field for each stat a question asks of it ("max" its highest, "min" its lowest, "avg" its average, -# "sum" its total), and the stat when it names none. Without a "min" it has no lowest to ask for. -DAILY = { - **{name: _figures(name, stem) for name, stem in (("temperature", "temp"), ("humidity", "humidity"), ("pressure", "pressure"), - ("dew_point", "dew_point"), ("feels_like", "feels_like"), ("vpd", "vpd"), - ("solar", "solar"))}, - "uv": ({"max": "uv_max", "min": "uv_max", "avg": "uv_max"}, "max"), # a UV index is its day's high, whatever is asked of it - "wind": ({"max": "wind_gust", "avg": "wind_speed_avg"}, "avg"), # its highest is a gust - "rain": ({"max": "rain", "min": "rain", "sum": "rain"}, "sum"), # a day's rain is its total -} -HOLIDAYISH = re.compile(r"\b(holidays?|weekends?|saturdays?|sundays?)\b", I) - - -def _limits(rest: str) -> list[str]: - """The numbers in the text that aren't a year or part of a period: "UV over 9 for 3 months in 2024" -> ["9"].""" - return re.findall(r"(?<![\w.])-?\d+(?:\.\d+)?", NUMBERED_PERIOD.sub(" ", re.sub(r"\b(?:19|20)\d\d\b", " ", rest))) - - -def _whole_period(rest: str, now: datetime) -> tuple[str, dict[str, str]] | None: - """(name, the start_date and end_date arguments) of what a count or a figure per period covers: the period named, a calendar year - ("in 2024": up to now, if it is this one), else everything on record; None when the text names more than one.""" - spans, years = spans_in(rest, now), set(re.findall(r"\b((?:19|20)\d\d)\b", rest)) - if len(spans) + len(years) > 1: - return None - if years: - year = int(years.pop()) - name, start, end = str(year), datetime(year, 1, 1), min(datetime(year, 12, 31, 23, 59, 59), now) - else: - name, start, end = spans[0] if spans else ("on record", *span("on record", now)) - return name, {"start_date": start.strftime("%Y-%m-%d"), "end_date": end.strftime("%Y-%m-%d")} - - -_NOT_COUNTED = (FORECAST, LINK, THINK, DESCRIBE, HOLIDAYISH) # a look ahead, a judgement or particular days: the model's - - -def _daily_reading(text: str, sources: Collection[str]) -> tuple[str, str, dict[str, str], str] | None: - """(tool, reading, its daily fields by stat, the stat when none is named) for the one reading a days question names: an air - reading goes to air_days (it needs the AirGradient), a weather one to weather_days (the Ecowitt); None when it names none, - several, "all", or a reading without daily figures.""" - if mentions_air(text): - metrics = air_named(text) - if "AirGradient" not in sources or len(metrics) != 1 or ALL.search(text): - return None - return "air_days", metrics[0], {stat: f"{metrics[0]}_{stat}" for stat in ("max", "min", "avg")}, "avg" - names = list(_named(text)) - if "Ecowitt" not in sources or len(names) != 1 or names[0] not in DAILY: - return None - return "weather_days", names[0], *DAILY[names[0]] - - -def count_days_call(text: str, now: datetime, sources: Collection[str]) -> tuple[str, dict, str] | None: - """(tool, arguments, label) when the text asks how many days one reading was over or under one limit (optionally per year or month), - else None and the model decides.""" - if (not re.search(r"\bdays?\b|\btimes\b", text, I) or any(p.search(text) for p in _NOT_COUNTED) - or re.search(r"\b(and|also|both|but)\b", text, I)): - return None - below, above = bool(BELOW.search(text) or OR_LESS.search(text)), bool(ABOVE.search(text) or OR_MORE.search(text) or AT_LEAST.search(text)) - if below == above: # neither, or both: not a plain comparison - return None - op = ">=" if OR_MORE.search(text) or AT_LEAST.search(text) else "<=" if OR_LESS.search(text) else "<" if below else ">" - rest = GROUPING.sub(" ", text) - if len(numbers := _limits(rest)) != 1 or not (reading := _daily_reading(text, sources)) or not (period := _whole_period(rest, now)): - return None - tool, name, fields, _ = reading - field = fields.get("min", fields["max"]) if below else fields["max"] # under a limit: its lowest, if it has one - if name == "uv" and op == ">": # a UV index is quoted in whole numbers: "over 10" means the days that read 10 - op = ">=" - name_, dates = period - args = {"where": [{"field": field, "op": op, "value": float(numbers[0])}], "count_only": True, **dates} - if by := grouping_in(text): - args["group_by"] = by - return tool, args, f"days count, {name_}" - - -# "rain by month for 2 years", "average temperature per year", "highest PM2.5 by month": one reading, a figure for each month or year, worked -# out in code (weather_days or air_days with stat, of and group_by): one bar for each month or year, the same figure a text line would give -HIGHER = re.compile(r"\b(hottest|highest|max\w*|peak\w*|wettest|windiest|warmest|worst|strongest|biggest)\b", I) -LOWER = re.compile(r"\b(coldest|lowest|min\w*|driest|coolest|calmest|smallest)\b", I) - - -def period_figures_call(text: str, now: datetime, sources: Collection[str]) -> tuple[str, dict, str] | None: - """(tool, arguments, label) when the text asks for one reading's figure by or per month or year, else None (the model decides).""" - if (not (by := grouping_in(text)) or any(p.search(text) for p in (*_NOT_COUNTED, ABOVE, BELOW, OR_MORE, OR_LESS, AT_LEAST)) - or re.search(r"\b(and|also|both|but|days|times)\b", text, I)): - return None - rest = GROUPING.sub(" ", text) - high, low = bool(HIGHER.search(text)), bool(LOWER.search(text)) - if (_limits(rest) or high and low # a limit or another number, or both ways: not a plain figure per period - or not (reading := _daily_reading(text, sources)) or not (period := _whole_period(rest, now))): - return None - tool, _, fields, plain = reading - stat = "max" if high else "min" if low else plain - if stat not in fields: # a lowest of a reading that has none (wind, solar) - return None - name_, dates = period - return tool, {"stat": stat, "of": fields[stat], "count_only": True, "group_by": by, **dates}, f"figures by {by}, {name_}" - - -def fast_call(text: str, now: datetime, sources: Collection[str]) -> tuple[str, dict, str] | None: - """(tool name, arguments, what it is) for a question the bot can fetch for without the model, from these sources (by name).""" - if asks_interval(text): # "each hour", "highest hourly rain each month": an interval's figures, never a day's or a period's - return None - if (counted := count_days_call(text, now, sources)) or (counted := period_figures_call(text, now, sources)): - return counted - ecowitt, air, pollen, forecast = ("Ecowitt" in sources, "AirGradient" in sources, "Pollen" in sources, "Forecast" in sources) - if SPECIFIC_MOMENT.search(text) or COUNTING.search(text): # "high on 5 Jan this year", "at 3pm today": a whole period would be the wrong data - return None - if air and (period := air_period(text, now)): - name, start, end = period - return "air_quality", {"chart": True, "metrics": air_metrics(text), - "start_date": start.strftime(FMT), "end_date": end.strftime(FMT)}, f"air quality chart, {name}" - if air and mentions_air(text) and not AIR_NOT_NOW.search(text) and not TIME_WORDS.search(text): - return "air_quality", {}, "air quality now" - if pollen and (POLLEN_NOW.search(text) and not TIME_WORDS.search(text) or pollen_ask(text)): - return "pollen_asthma", {}, "pollen and thunderstorm asthma" - if ecowitt and wants_weather_now(text): - return "weather_now", {"groups": NOW_GROUPS}, "weather now" - if forecast and FORECAST_PLAIN.search(text): - return "weather_forecast", {"days": 7}, "forecast" - if ecowitt and reading_now(text): - return "weather_now", {"groups": NOW_GROUPS}, "weather reading now" - if ecowitt and (simple := _simple_weather(text, now)): - kind, (name, start, end), groups = simple - # a chart when one is asked for, over 3+ days or an hours-long window; a day or two of highs and lows is figures - chart = kind == "chart" or (end - start).days >= 2 or name.endswith("hours") or bool(GRAPH.search(text)) - average = {"average": True} if kind == "average" and AVERAGE.search(text) else {} - return "weather_history", {"groups": ",".join(groups), **average, "chart": chart, "start_date": start.strftime(FMT), - "end_date": end.strftime(FMT)}, f"weather {'chart' if kind == 'chart' else 'history'}, {name}" - return None - - -# ---------- what the model needs for a question: guidance for the prompt, tools for the call ---------- -DAYS_WORDS = re.compile(r"\b(days?|how many|how often|most|least|ranks?|ranking|top|worst|best|holidays?|weekends?|" - r"hottest|coldest|wettest|driest|windiest|warmest|coolest|compare\w*|versus|vs|yesterday)\b", I) -OUTLOOK_WORDS = re.compile(r"\b(rain\w*|umbrella|showers?|wet|storms?|later|soon|going to|will|about to)\b", I) -WIND_WORDS = re.compile(rf"\b({_WIND}|direction)\b", I) -BOT_WORDS = re.compile(r"\b(can|could|do|does|are|will)\s+(you|the bot)\b|\b(alerts?|notify|notification\w*|support\w*|capabilit\w*|able to|add|set up|remind)\b", I) -COMPARE = re.compile(r"\b(against|versus|vs|compare\w*|affect\w*|influence\w*|correlat\w*|relat\w*|link\w*|cause\w*)\b", I) - - -def topics_in(said: str) -> set[str]: - """The guidance topics one message touches: air, air_extra (the air sensor's own temperature or humidity), days, link, outlook, wind, - describe, bot.""" - return {name for name, hit in ( - ("air", mentions_air(said)), ("air_extra", wants_air_extra(said)), - ("days", bool(DAYS_WORDS.search(said) or ANALYSIS.search(said) or SPECIFIC_MOMENT.search(said))), - ("link", bool(LINK.search(said)) or bool(COMPARE.search(said)) and bool(OUTLOOK_WORDS.search(said))), - ("outlook", bool(FORECAST.search(said)) or bool(OUTLOOK_WORDS.search(said))), - ("wind", bool(WIND_WORDS.search(said))), ("describe", bool(DESCRIBE.search(said))), - ("bot", bool(BOT_WORDS.search(said)) or about_the_bot(said) or bool(COMMAND.search(said))), - ) if hit} - - -def topics(text: str, before: list[str] = ()) -> set[str]: - """What guidance and tools the question needs beyond the basics, from its words and the messages just before it (a follow-up - like "and indoors?" is about what came before). Generous on purpose: a topic that isn't needed costs a few tokens, one that - is missing costs the answer.""" - found: set[str] = set() - for said in (*before, text): - found |= topics_in(said) - return found - - -# The topic a tool call is evidence of: a chat that is being answered with these is still on the topic -TOOL_TOPICS = {"weather_days": "days", "air_days": "days", "weather_link": "link", "air_link": "link", "air_scan": "link", - "weather_forecast": "outlook", "air_quality": "air"} - - -# "will it rain?", "do I need an umbrella?", "rain later?": the model reasons from the station, and the forecast (if on) comes with it -RAIN_AHEAD = re.compile(r"\b(umbrella|chance of rain|(will|going to|gonna|likely to|expect\w*)\b.*\brain\w*|" - r"rain\w*\b.*\b(later|soon|tonight|tomorrow|this (afternoon|evening)|coming|next)\b)", I) -WEEK_AHEAD = re.compile(r"\b(week|days|weekend|next \w+day)\b", I) - - -def model_prefetch(text: str, now: datetime, sources: Collection[str]) -> list[tuple[str, dict]]: - """What the model would fetch first for these questions, fetched here instead (so it answers in one call, not two): for rain - ahead, the current reading, the last 3 hours and the forecast (cached); for a described today or yesterday, that day's readings.""" - calls: list[tuple[str, dict]] = [] - ecowitt = "Ecowitt" in sources - if RAIN_AHEAD.search(text): - if ecowitt: - groups = "outdoor,pressure,rainfall,rainfall_piezo,wind" - calls += [("weather_now", {"groups": groups}), - ("weather_history", {"groups": groups, "start_date": (now - timedelta(hours=3)).strftime(FMT), "end_date": now.strftime(FMT)})] - if "Forecast" in sources: - calls.append(("weather_forecast", {"days": 7 if WEEK_AHEAD.search(text) else 3, "cached": True})) - elif ecowitt and DESCRIBE.search(text) and not SPECIFIC_MOMENT.search(text): - spans = spans_in(text, now) - if len(spans) == 1 and spans[0][0] in ("yesterday", "today", "last 24 hours"): - _, start, end = spans[0] - calls.append(("weather_history", {"groups": "outdoor,indoor,rainfall,wind", "start_date": start.strftime(FMT), "end_date": end.strftime(FMT)})) - return calls - - - -@dataclass -class Intent: - """Everything decided about one message before the model sees it.""" - effort: str = EFFORT_DEFAULT - needs_data: bool = False # the model must call a tool first - about_the_bot: bool = False # answered without tools - report: bool = False # "status": the full report - dashboard: bool = False # "dashboard": the station's gauges, one picture - hints: list[str] = field(default_factory=list) # what the period words in the message mean - fast: tuple[str, dict, str] | None = None # (tool, arguments, what it is): fetched here, before the model - chart_asked: bool = False # "plot" means a chart, whatever the model calls - chart_field: str | None = None # humidity questions get a humidity chart - chart_fields: list[str] = field(default_factory=list) # "temperature and rain": one chart, a panel each - two_axes: bool = False # "uvi and solar on two axes": the two share one panel, a scale each - air_extra: bool = False # "airgradient humidity": the air sensor's own temperature and humidity are offered to the model - average_asked: bool = False - more: list[tuple[str, dict]] = field(default_factory=list) # the rest of the report's calls (fast is the first) - weather_now: bool = False # "weather now": every reading the station has, in the report's layout - rain_caption: bool = False # "rain chart 7d": the caption is just the least and most rain - chart_in_code: bool = False # a chart asked for plainly: fetched and captioned in code, no model - readings: list[str] = field(default_factory=list) # the readings the words name - per_day: bool = False # figures day by day were asked for - extra: list[tuple[str, dict]] = field(default_factory=list) # fetched with the model's first step (the forecast, for "will it rain?") - lookup: str = "" # "reading", "air", "days", "extremes", "pollen", "forecast" or "about": answered in code, no model - lookup_arg: list[str] = field(default_factory=list) # the readings named ("reading", "air"; none: all) - sides: list[str] = field(default_factory=list) # "indoor", "outdoor" or both, for a reading - - @property - def tool_choice(self) -> str: - """What the model's first step may do with the tools (see Agent.run): none about the bot itself, a fetch it must make - when the answer needs data, else its own choice.""" - return "none" if self.about_the_bot else "required" if self.needs_data else "auto" - - -PLAIN_LOOKUPS = {"pollen_asthma": "pollen", "weather_days": "days", "air_days": "days", "weather_forecast": "forecast"} # whatever the words - - -def plain_lookup(text: str, fast: tuple | None) -> tuple[str, list[str]]: - """(kind, readings named) for a question answered in code from one tool result, else ("", []). The tools in PLAIN_LOOKUPS always - are; a weather or air reading only when the words ask for nothing more.""" - if about_the_bot(text): - return "about", [] - if not fast: - return "", [] - tool, args = fast[0], fast[1] - if tool in PLAIN_LOOKUPS: - return PLAIN_LOOKUPS[tool], [] - if _judgement(text): - return "", [] - if tool == "weather_history" and not args.get("chart"): - return "extremes", list(_named(text)) - if tool == "weather_now" and (names := reading_now(text)): - return "reading", names - if tool == "air_quality" and not args and len(text.split()) <= 6: - return "air", air_named(text) - return "", [] +APOSTROPHES = str.maketrans("’‘", "''") # a phone's typographic apostrophes ("what’s"), read as the plain one every pattern uses -APOSTROPHES = str.maketrans("’‘", "''") # a phone's typographic apostrophes ("what’s"), read as the plain one every pattern uses +def effort(text: str) -> str: + """reasoning_effort of a typed question, its typographic apostrophes read as plain ones.""" + return reasoning_effort(text.translate(APOSTROPHES)) -def read(text: str, now: datetime, sources: Collection[str] = ("Ecowitt", "AirGradient")) -> Intent: - """The decisions made in code for this message, given the sources the bot has (by name: "Ecowitt", "AirGradient", "Pollen", - "Forecast"). A shortcut that fails is dropped: the model handles the question.""" - text = text.translate(APOSTROPHES) - ecowitt = "Ecowitt" in sources - report = wants_report(text) - calls = report_calls(sources) if report else [] - try: - fast = (*calls[0], "report") if calls else fast_call(text, now, sources) - except Exception as e: - log.error("Fast path failed (%s: %s); using the normal path", type(e).__name__, e, exc_info=isinstance(e, BUGS)) - fast = None - in_code = bool(fast and fast[0] in ("weather_history", "air_quality") and fast[1].get("chart") - and not _judgement(text)) - rain_caption = ecowitt and wants_rain_caption(text) - lookup, named = plain_lookup(text, fast) if not (report or in_code) else ("", []) - return Intent(effort=reasoning_effort(text), needs_data=needs_data(text), about_the_bot=about_the_bot(text), report=report, - hints=period_hints(text, now), fast=fast, chart_asked=bool(GRAPH.search(text)), chart_field=chart_field(text), - chart_fields=chart_fields(text), two_axes=bool(TWO_AXES.search(text)) and len(chart_fields(text)) == 2, air_extra=wants_air_extra(text), average_asked=bool(AVERAGE.search(text)), more=calls[1:], - weather_now=ecowitt and wants_weather_now(text), dashboard=ecowitt and wants_dashboard(text), rain_caption=rain_caption, chart_in_code=in_code, - readings=list(_named(text)), per_day=bool(PER_DAY.search(text)), - extra=model_prefetch(text, now, sources) if not fast else [], lookup=lookup, lookup_arg=named, sides=_sides(text)) +__all__ = ["EFFORT_DEFAULT", "effort", "lower_effort", "reasoning_effort"] diff --git a/lib/irrigation/__init__.py b/lib/irrigation/__init__.py index 3b5b96a8..2bcf483c 100644 --- a/lib/irrigation/__init__.py +++ b/lib/irrigation/__init__.py @@ -1,4 +1,15 @@ -from .tuya import IrrigationError, Tuya -from .watchdog import Watchdog +"""The irrigation controller: irrigation-mcp's code (the Tuya client, the watchdog, the daily check, its state, its client of ecobot-mcp, +the server), and `common` (what its client, the bot's menu, shares with it). The package itself loads nothing: `from lib.irrigation +import Tuya` loads the Tuya client when it is asked for (so the bot, importing lib.irrigation.common, never does).""" + +_LAZY = {"Tuya": ".tuya", "Watchdog": ".watchdog", "IrrigationError": ".common"} + + +def __getattr__(name): + if name in _LAZY: + import importlib + return getattr(importlib.import_module(_LAZY[name], __name__), name) + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + __all__ = ["IrrigationError", "Tuya", "Watchdog"] diff --git a/lib/alerts/irrigation.py b/lib/irrigation/check.py similarity index 67% rename from lib/alerts/irrigation.py rename to lib/irrigation/check.py index cf59dbf5..818271b6 100644 --- a/lib/alerts/irrigation.py +++ b/lib/irrigation/check.py @@ -1,12 +1,14 @@ -"""The irrigation controller, checked once a day (18:00 local by default). +"""The irrigation controller, checked once a day (18:00 local by default, IRRIGATION_CHECK_HOUR): run by irrigation-mcp +(irrigation_mcp, lib/irrigation/server.py). What it tells goes to `notify(text, kind=...)`: irrigation-mcp's alert log +(irrigation://alerts), which the bot delivers to its chats. - a battery below 5% is told to the chats subscribed to "irrigation battery" (kind irrigation_battery) (at most once a day, until it is charged); - if more than 1 mm of rain fell in the last 24 hours, or Open-Meteo gives today or tomorrow a 50% or better chance of at least 1 mm of rain (in a forecast fetched within the last day: an older one doesn't count), the controller is put on a 24 hour weather delay (it skips its own schedule) and the chats subscribed to "irrigation pause" are told why. A delay someone set is left alone - (nothing changes, so nothing is sent); the bot's own from yesterday, seconds from lapsing at the check, is started again. + (nothing changes, so nothing is sent); its own from yesterday, seconds from lapsing at the check, is started again. -The bot has no scheduler, so `run` sleeps until the next check time. If the controller can't be reached it tries again every 30 minutes +There is no scheduler, so `run` sleeps until the next check time. If the controller can't be reached it tries again every 30 minutes until it works or the day ends. The date of the last completed check is saved, so a restart neither repeats a day nor skips one. """ @@ -14,11 +16,9 @@ import logging from datetime import datetime, timedelta -from ..ecowitt.rain import rain_amount -from ..irrigation.tuya import is_paused +from ..alerts.kinds import RAIN_FROM_PCT, kinds_of from ..timeutil import local_epoch, now_local, seconds_until, when -from .forecast import RAIN_FROM_PCT -from .menu import kinds_of +from .common import is_paused log = logging.getLogger(__name__) @@ -33,10 +33,37 @@ class IrrigationMonitor: KINDS = kinds_of("Irrigation") def __init__(self, device, state, notify, tz, hour: int = 18, station=None, forecast=None): - """station: the Ecowitt source (its recent() gives the measured rain); forecast: the Forecast source. Either may be None.""" + """state: where its days are kept (`monitor`, `save()`: lib/irrigation/state.IrrigationState); station: + what asks ecobot-mcp for the measured rain (lib/irrigation/ecobot.ServiceRain: rain_mm()); forecast: the forecast read from it + (lib/irrigation/ecobot.ServiceForecast: read again at each check, the one last read standing when it can't be). Either may be + None.""" + self._rezoned = asyncio.Event() self.device, self.state, self.notify, self.tz, self.hour = device, state, notify, tz, hour self.station, self.forecast = station, forecast + @property + def tz(self): + return self._tz + + @tz.setter + def tz(self, zone): + """The station's zone; another one (the remote service's station read late) wakes the wait for the check time, timed again in it.""" + self._tz = zone + self._rezoned.set() + + async def _sleep(self, seconds: float): + """Until the check time (`seconds`), or until the zone changes.""" + self._rezoned.clear() + sleeper, woken = asyncio.ensure_future(asyncio.sleep(seconds)), asyncio.ensure_future(self._rezoned.wait()) + try: + await asyncio.wait((sleeper, woken), return_when=asyncio.FIRST_COMPLETED) + slept = sleeper.done() + finally: + for task in (sleeper, woken): + task.cancel() + if slept: + sleeper.result() # (its own failure or cancellation, raised here) + def _memory(self) -> dict: return self.state.monitor.setdefault("irrigation_monitor", {}) @@ -59,7 +86,7 @@ async def run(self): await asyncio.sleep(min(RETRY_SECONDS, self.seconds_until_next(now))) continue now = now_local(self.tz) - await asyncio.sleep(self.seconds_until_next(now)) + await self._sleep(self.seconds_until_next(now)) async def check(self, now: datetime | None = None): """One check: the battery, then the rain. Raises when the controller can't be reached (nothing is recorded then).""" @@ -78,7 +105,7 @@ async def check(self, now: datetime | None = None): current = status.get("weather_delay") own = current == "24h" and memory.get("paused") == (now.date() - timedelta(days=1)).isoformat() if not is_paused(status) or own: - if own: # the bot's pause from yesterday: ended first, so the new one runs a full day + if own: # its own pause from yesterday: ended first, so the new one runs a full day await self.device.delay("cancel") await self.device.delay("24h") memory["paused"] = today @@ -95,13 +122,18 @@ async def rain_reason(self, now: datetime) -> str | None: """Why the irrigation should be delayed (what rained or will), or None. `now` is local.""" if self.station is not None: try: - rows = await self.station.recent(MEASURED_HOURS) - fell = rain_amount(rows, rows[0][0], rows[-1][0]) if rows else None + fell = await self.station.rain_mm(MEASURED_HOURS) # the weather service's summary of the rain except Exception as e: # the forecast can still decide log.warning("Irrigation: the measured rain is unavailable (%s: %s)", type(e).__name__, e) fell = None if fell is not None and fell > MEASURED_MM: return f"{fell:g} mm of rain in the last 24 hours" + if (refresh := getattr(self.forecast, "refresh", None)) is not None: # the weather service's forecast, read again + try: + await refresh() + except Exception as e: + log.warning("Irrigation: the forecast couldn't be read (%s: %s); %s", type(e).__name__, e, + "using the one last read" if self.forecast.days else "there is none to go on") if self.forecast is not None and self.forecast.days: if local_epoch(now, self.tz) - self.forecast.fetched_at > FORECAST_TRUSTED_SECONDS: log.info("Irrigation: the forecast is from %s, over a day old: only the measured rain decides", diff --git a/lib/irrigation/common.py b/lib/irrigation/common.py new file mode 100644 index 00000000..627a80b8 --- /dev/null +++ b/lib/irrigation/common.py @@ -0,0 +1,31 @@ +"""What both sides of the irrigation controller know: irrigation-mcp (lib/irrigation/tuya.py, server.py, check.py) and the bot's menu +(lib/irrigation_menu.py), which is its client. Nothing here loads the Tuya client (httpx) or anything else: the bot imports it alone. + + - `DELAYS`: the device's weather_delay range ("cancel" is none); `MAX_MINUTES`: the longest run; + - `is_paused(status)`: a weather delay pauses the timer; + - `IrrigationError`: the controller (or irrigation-mcp) could not be read or told something; its message is safe to show; + `IrrigationRefused`, one, irrigation-mcp refused the call (`paused`: water while a weather delay is on).""" + +DELAYS = ("24h", "48h", "72h", "cancel") # the device's weather_delay range +MAX_MINUTES = 60 # the longest run asked for + + +def is_paused(status: dict) -> bool: + """Is the timer paused: a weather delay other than "cancel" (which is none)?""" + return status.get("weather_delay") not in (None, "cancel") + + +class IrrigationError(Exception): + """The controller could not be read or told something. The message is safe to log (no secrets, no raw response).""" + + +class IrrigationRefused(IrrigationError): + """irrigation-mcp reached the controller, or needn't have, but refused the call: `paused` (water while a weather delay is on), else + its arguments. The message is irrigation-mcp's, safe to show.""" + + def __init__(self, message: str, paused: bool = False): + super().__init__(message) + self.paused = paused + + +__all__ = ["DELAYS", "MAX_MINUTES", "IrrigationError", "IrrigationRefused", "is_paused"] diff --git a/lib/irrigation/ecobot.py b/lib/irrigation/ecobot.py new file mode 100644 index 00000000..9c23d8cc --- /dev/null +++ b/lib/irrigation/ecobot.py @@ -0,0 +1,155 @@ +"""ecobot-mcp as the irrigation check asks it (docs/ecobot-mcp.md 3.9): the rain measured and the forecast. + + - `ServiceRain`: the measured rain, `summary {readings: ["rain"], period: "last 24 hours"}`'s total; + - `ServiceForecast`: ecobot://forecast (its days, each with its chance of at least 1 mm, and when it was fetched), read again at each + check; when ecobot-mcp can't be reached the one last read stands; + - `EcobotWeather`: irrigation-mcp's client of ecobot-mcp (IRRIGATION_ECOBOT_MCP_URL), kept by lib/upstream.Upstream (pinned, listening + to the station and the forecast): `call_text`, `resource`, `tz` (ecobot://station's time zone once read, TZ before; `on_zone(zone)` + is called when it is first read and when it changes), `rain` and `forecast` (the two above, over it). + +Nothing here imports ecobot-mcp's own code: only the MCP client.""" + +import asyncio +import json +import logging +from datetime import date, datetime +from zoneinfo import ZoneInfo + +from ..timeutil import now_local + +log = logging.getLogger(__name__) + +STATION_URI, FORECAST_URI = "ecobot://station", "ecobot://forecast" # (as lib/mcp_server.py's) + + +class ServiceRain: + """The measured rain as the irrigation check asks the service for it: summary {readings: ["rain"], period: "last N hours"}'s total.""" + + def __init__(self, weather): + self.weather = weather + + async def rain_mm(self, hours: int = 24) -> float | None: + out = json.loads(await self.weather.call_text("summary", {"readings": ["rain"], "period": f"last {hours} hours"})) + if "error" in out: + raise ValueError(out["error"]) + return out.get("rain_total_mm") + + +class ServiceForecast: + """The forecast as the irrigation check reads it, from ecobot://forecast (its days, each with its chance of at least 1 mm, and when it + was fetched), as lib/forecast's source gives them (`days`, `fetched_at`, `now()`, `upcoming()`). `refresh()` reads it again; when the + service can't be reached the forecast last read stands.""" + + def __init__(self, weather): + self.weather = weather + self.days: list[dict] | None = None + self.fetched_at: float = 0 + self.place: str | None = None + + async def refresh(self): + data = await self.weather.resource(FORECAST_URI) + days = [] + for d in data.get("days") or []: + try: + days.append({**d, "date": date.fromisoformat(str(d["date"])[:10])}) + except (KeyError, ValueError): + continue + fetched = data.get("fetched_at") + self.days, self.place = days, data.get("place") + self.fetched_at = datetime.fromisoformat(fetched).timestamp() if fetched else 0 + + def now(self) -> datetime: + return now_local(self.weather.tz) + + def upcoming(self, count: int = 2) -> list[dict]: + today = self.now().date() + return [d for d in (self.days or []) if d["date"] >= today][:count] + + +class EcobotWeather: + """irrigation-mcp's client of ecobot-mcp at `target` (its MCP URL; in tests, a Server in memory), sending `token` (a string, a + function giving it for each connection, or None). `run()` is the supervisor (lib/upstream.Upstream). Each new connection reads the + station (its time zone) and the forecast; the listen keeps them current. A call while ecobot-mcp can't be reached waits for it up + to lib/upstream.CONNECT_WAIT seconds, then fails (MCPError): the check then goes on the forecast last read, without the measured + rain.""" + + def __init__(self, target, token=None, tz=None): + from ..upstream import Upstream + self.target, self.fallback_tz, self.station_tz = target, tz, None + self.upstream = Upstream(target, token, on_event=self._event, on_listening=self._listening, resources=(STATION_URI, FORECAST_URI)) + self.rain = ServiceRain(self) + self.forecast = ServiceForecast(self) + self.on_zone = None # on_zone(zone): the station's time zone, when it is first read and when it changes + self.listening = asyncio.Event() # the first connection listens, its station read + self._background: set[asyncio.Task] = set() + + @property + def tz(self): + """The station's time zone (ecobot://station's), TZ until it has been read.""" + return self.station_tz or self.fallback_tz + + async def run(self): + await self.upstream.run() + + async def close(self): + for task in list(self._background): + task.cancel() + await asyncio.gather(*self._background, return_exceptions=True) + + # ---------- the connection ---------- + async def _listening(self): + try: + await self._read_station() + except Exception as e: # (the listen's events read it again later) + log.warning("ecobot-mcp: couldn't read the station (%s: %s)", type(e).__name__, e) + self._soon(self.forecast.refresh) + self.listening.set() + + async def _event(self, event): + from mcp.shared.subscriptions import ResourceUpdated + if isinstance(event, ResourceUpdated): + uri = str(event.uri) + if uri == STATION_URI: + self._soon(self._read_station) + elif uri == FORECAST_URI: + self._soon(self.forecast.refresh) + + def _soon(self, fn): + """fn() in the background (a listen event is not held up by the reads it causes), its failure only logged.""" + async def run(): + try: + await fn() + except Exception as e: + log.debug("ecobot-mcp: %s failed (%s: %s)", getattr(fn, "__name__", fn), type(e).__name__, e) + task = asyncio.create_task(run()) + self._background.add(task) + task.add_done_callback(self._background.discard) + + async def _read_station(self): + station = await self.resource(STATION_URI) + if zone := station.get("time_zone"): + try: + read = ZoneInfo(zone) + except Exception: # (an offset only: TZ stands) + return + first_or_new, self.station_tz = str(read) != str(self.station_tz), read + if first_or_new and self.on_zone: + self.on_zone(read) + + # ---------- what the check asks ---------- + async def call_text(self, name: str, args: dict | None = None) -> str: + """A tool's answer as its JSON text (its first text block; a refusal's too).""" + client = await self.upstream.get() + result = await client.call_tool(name, args or {}) + for block in result.content: + if getattr(block, "type", None) == "text": + return block.text + return json.dumps({"error": f"ecobot-mcp's {name} gave no answer."}) + + async def resource(self, uri: str) -> dict: + client = await self.upstream.get() + read = await client.read_resource(uri) + return json.loads(read.contents[0].text) + + +__all__ = ["EcobotWeather", "ServiceForecast", "ServiceRain"] diff --git a/lib/irrigation/server.py b/lib/irrigation/server.py new file mode 100644 index 00000000..2ce0750f --- /dev/null +++ b/lib/irrigation/server.py @@ -0,0 +1,247 @@ +"""irrigation-mcp's MCP server (docs/ecobot-mcp.md 3.9): the irrigation controller (lib/irrigation/tuya.py) over MCP, with the same +low-level SDK as ecobot-mcp's (lib/mcp_server.py), as Streamable HTTP behind the same bearer token check (lib/mcp_http.py). + + - **Tools**: `irrigation_status` (readOnlyHint): the valve on or off, the run's seconds left (`countdown`), the weather delay and whether + it pauses the timer, the battery, the work state, and the watchdog's `off_at` while a run is watched; `water {minutes: 1..60}`, + refused with an error that says so while a weather delay is on, the watchdog armed first (a command whose reply is lost may still + have opened the valve); `stop` (the valve off, the watchdog disarmed); `delay {duration: 24h|48h|72h|cancel}`. The last three carry + destructiveHint, so a client asks before it calls them. Each answers JSON as one text block, as ecobot-mcp's tools do; a refusal, + or the controller unreachable (IrrigationError's message, safe to show), is `isError` with {"error": ...}, a refusal with + "refused" too: "paused" (water while a weather delay is on) or "arguments". + - **Resources**: `irrigation://alerts` (and its template with `since` and `expired`): the alerts its daily check decides + (irrigation_battery, irrigation_pause), in ecobot://alerts' shape, from an alert log of its own (lib/alert_log.py: + irrigation_alerts.sqlite, its own identity), published as ResourceUpdated on each new one to whoever listens. + - **HTTP** (`http_app`): `streamable_http_app` at /mcp, its Host header checked against IRRIGATION_ALLOWED_HOSTS, each request's + bearer token against AUTH_TOKENS (lib/mcp_http.TokenCheck), one line per request in the log (RequestLog). + +`IrrigationServer(device, watchdog, alert_log)` builds it; `notify(text, kind=...)` is the daily check's way to alert (it appends to the +alert log); `run()` publishes the alerts. The watchdog and the daily check themselves are run by irrigation_mcp.""" + +import json +import logging +from datetime import datetime +from urllib.parse import parse_qs, urlsplit + +import mcp_types as types +from mcp.server.auth.settings import AuthSettings +from mcp.server.lowlevel import Server +from mcp.server.subscriptions import InMemorySubscriptionBus, ListenHandler, ResourceUpdated +from mcp.shared.exceptions import MCPError + +from ..mcp_http import RequestLog, TokenCheck, alerts_read, host_settings +from .common import DELAYS, MAX_MINUTES, IrrigationError, is_paused + +log = logging.getLogger(__name__) +requests_log = logging.getLogger(__name__ + ".requests") # one line per HTTP request (RequestLog) + +NAME = "irrigation" +JSON = "application/json" +RESOURCE_NOT_FOUND = -32002 # MCP's error for a resource there is none of +ALERTS_URI = "irrigation://alerts" +ALERTS_TEMPLATE = "irrigation://alerts{?since,expired}" +INSTRUCTIONS = ("The garden's irrigation controller (a Tuya smart irrigation timer). irrigation_status reads it; water opens the valve " + "for some minutes (refused while a weather delay pauses the timer: cancel the delay first), stop closes it, delay pauses " + "the timer's own schedule for 24, 48 or 72 hours (cancel ends a pause). A run always ends: the server closes the valve " + "itself if the controller hasn't. Once a day it pauses the timer for 24 hours when it rained or rain is likely, and " + "warns of a low battery: irrigation://alerts.") +PAUSED = ("The irrigation is paused (weather delay {delay}): it can't water while paused. Cancel the pause first (delay with duration " + "cancel), then water.") +ALERTS = { # kind: (title, how long it is news, in seconds) + "irrigation_battery": ("Irrigation battery low", 24 * 3600), # (until the next day's check, which says it again if still low) + "irrigation_pause": ("Irrigation paused for rain", 24 * 3600), # (the pause's own length) +} + +TOOLS = { # name: (description, input schema, annotations) + "irrigation_status": ( + "The irrigation controller now: `switch` (the valve on or off), `countdown` (seconds left of the run), `weather_delay` (24h, 48h, " + "72h, or cancel for none) and `paused` (a weather delay pauses the timer), `battery_percentage`, `work_state` (auto, manual or " + "idle), and `off_at` (when the server closes the valve itself, while a run it started is on).", + {"type": "object", "properties": {}, "additionalProperties": False}, + types.ToolAnnotations(title="Irrigation status", read_only_hint=True, open_world_hint=False)), + "water": ( + f"Open the valve for `minutes` (1 to {MAX_MINUTES}); the run ends by itself, and the server closes the valve if the controller " + "doesn't. Refused while a weather delay pauses the timer (cancel it first with delay).", + {"type": "object", "properties": {"minutes": {"type": "integer", "minimum": 1, "maximum": MAX_MINUTES, + "description": f"How long to water, 1 to {MAX_MINUTES} minutes."}}, + "required": ["minutes"], "additionalProperties": False}, + types.ToolAnnotations(title="Water", read_only_hint=False, destructive_hint=True, idempotent_hint=False, open_world_hint=False)), + "stop": ( + "Close the valve now, ending any run.", + {"type": "object", "properties": {}, "additionalProperties": False}, + types.ToolAnnotations(title="Stop watering", read_only_hint=False, destructive_hint=True, idempotent_hint=True, + open_world_hint=False)), + "delay": ( + "Pause the timer's own schedule (a weather delay) for 24h, 48h or 72h; cancel ends a pause.", + {"type": "object", "properties": {"duration": {"type": "string", "enum": list(DELAYS), + "description": "24h, 48h or 72h; cancel to end a pause."}}, + "required": ["duration"], "additionalProperties": False}, + types.ToolAnnotations(title="Pause the schedule", read_only_hint=False, destructive_hint=True, idempotent_hint=True, + open_world_hint=False)), +} + + +class Refused(Exception): + """A call refused (its arguments, or the timer paused): its message is the answer's error, `why` its "refused".""" + + def __init__(self, message: str, why: str = "arguments"): + super().__init__(message) + self.why = why + + +def _result(data: dict) -> types.CallToolResult: + """A tool's answer as tools/call gives it: the JSON as one text block; `isError` for a refusal ({"error": ...}).""" + return types.CallToolResult(content=[types.TextContent(text=json.dumps(data, ensure_ascii=False))], is_error="error" in data) + + +def _check_arguments(name: str, args: dict): + """The arguments as the tool's schema has them, or Refused saying what is wrong.""" + _, schema, _ = TOOLS[name] + allowed = schema["properties"] + if extra := [k for k in args if k not in allowed]: + raise Refused(f"{name} takes {', '.join(allowed) or 'no arguments'}, not {', '.join(extra)}.") + if missing := [k for k in schema.get("required", ()) if k not in args]: + raise Refused(f"{name} needs {', '.join(missing)}.") + if name == "water": + minutes = args["minutes"] + if isinstance(minutes, float) and minutes.is_integer(): + minutes = int(minutes) + if not isinstance(minutes, int) or isinstance(minutes, bool) or not 1 <= minutes <= MAX_MINUTES: + raise Refused(f"minutes is a whole number from 1 to {MAX_MINUTES}, not {args['minutes']!r}.") + args["minutes"] = minutes + if name == "delay" and args["duration"] not in DELAYS: + raise Refused(f"duration is one of {', '.join(DELAYS)}, not {args['duration']!r}.") + + +class IrrigationServer: + """irrigation-mcp's MCP server over the controller (`device`: lib/irrigation/tuya.Tuya, or a test's), its watchdog + (lib/irrigation/watchdog.Watchdog) and its alert log (lib/alert_log.AlertLog). `tz`: the zone its times are given in (the station's, + once ecobot-mcp has been read).""" + + def __init__(self, device, watchdog, alert_log=None, *, version: str = "", bus=None, tz=None): + self.device, self.watchdog, self.alert_log, self.tz = device, watchdog, alert_log, tz + self.bus = bus or InMemorySubscriptionBus() + self.listen = ListenHandler(self.bus) + self.server = Server(NAME, version=version, title="Irrigation controller", instructions=INSTRUCTIONS, + get_tool_input_schema=lambda name: TOOLS[name][1] if name in TOOLS else None, + on_list_tools=self._list_tools, on_call_tool=self._call_tool, + on_list_resources=self._list_resources, on_list_resource_templates=self._list_templates, + on_read_resource=self._read_resource, on_subscriptions_listen=self.listen) + + # ---------- tools ---------- + async def _list_tools(self, ctx, params) -> types.ListToolsResult: + return types.ListToolsResult(tools=[types.Tool(name=name, description=what, input_schema=schema, annotations=hints) + for name, (what, schema, hints) in TOOLS.items()]) + + async def _call_tool(self, ctx, params: types.CallToolRequestParams) -> types.CallToolResult: + if params.name not in TOOLS: + raise MCPError(types.INVALID_PARAMS, f"No tool {params.name!r}: the tools are {', '.join(TOOLS)}.") + return _result(await self.call(params.name, dict(params.arguments or {}))) + + async def call(self, name: str, args: dict) -> dict: + """A tool's answer as data: what it did or read, or {"error": ...} when it was refused or the controller couldn't be reached.""" + try: + _check_arguments(name, args) + return await getattr(self, f"_{name}")(**args) + except Refused as e: + return {"error": str(e), "refused": e.why} + except IrrigationError as e: # (its message is safe to show: no secrets, no raw response) + log.warning("Irrigation %s failed: %s", name, e) + return {"error": f"The irrigation controller couldn't be reached: {e}."} + + def _time(self, epoch: float | None) -> str | None: + return None if epoch is None else datetime.fromtimestamp(epoch, self.tz).isoformat(timespec="seconds") + + async def _irrigation_status(self) -> dict: + status = await self.device.status() + out = {"switch": bool(status.get("switch")), "countdown": status.get("countdown"), "weather_delay": status.get("weather_delay"), + "paused": is_paused(status), "battery_percentage": status.get("battery_percentage"), + "work_state": status.get("work_state")} + if (off_at := self.watchdog.off_at) is not None: + out["off_at"] = self._time(off_at) + return out + + async def _water(self, minutes: int) -> dict: + status = await self.device.status() + if is_paused(status): + log.info("Irrigation: water %d refused, paused for %s", minutes, status.get("weather_delay")) + raise Refused(PAUSED.format(delay=status.get("weather_delay")), "paused") + self.watchdog.arm(minutes) # first: a command whose reply is lost may still have opened the valve + await self.device.water(minutes) + log.info("Irrigation: watering for %d minutes", minutes) + return {"done": f"Watering for {minutes} minutes", "minutes": minutes, "off_at": self._time(self.watchdog.off_at)} + + async def _stop(self) -> dict: + await self.device.set_switch(False) + self.watchdog.disarm() + log.info("Irrigation: switched off") + return {"done": "Switched off"} + + async def _delay(self, duration: str) -> dict: + await self.device.delay(duration) + log.info("Irrigation: %s", "unpaused" if duration == "cancel" else f"paused {duration}") + return {"done": "Unpaused" if duration == "cancel" else f"Paused {duration}", "weather_delay": duration} + + # ---------- alerts ---------- + async def notify(self, text: str, kind: str, **_): + """The daily check's alert (lib/irrigation/check.py): appended to the alert log, which wakes the listeners.""" + title, lasts = ALERTS.get(kind, ("Irrigation", 24 * 3600)) + self.alert_log.append(kind, text, title, expires=self.alert_log.now() + lasts) + + async def _list_resources(self, ctx, params) -> types.ListResourcesResult: + if self.alert_log is None: + return types.ListResourcesResult(resources=[]) + return types.ListResourcesResult(resources=[types.Resource( + uri=ALERTS_URI, name="alerts", title="Irrigation alerts", mime_type=JSON, + description="The alerts the daily check has decided (irrigation_battery: the battery is low; irrigation_pause: paused for rain), " + "newest last, kept 30 days: {alerts: [{id, kind, time, expires, title, text, data}], last_id, identity}; only " + "those not yet expired (the template: since an id, and expired=true for all). Pushed on each new alert.")]) + + async def _list_templates(self, ctx, params) -> types.ListResourceTemplatesResult: + if self.alert_log is None: + return types.ListResourceTemplatesResult(resource_templates=[]) + return types.ListResourceTemplatesResult(resource_templates=[types.ResourceTemplate( + uri_template=ALERTS_TEMPLATE, name="alerts since", title="Irrigation alerts since an id", + description="The alerts after the id `since` (a client's last handled), only those not yet expired unless `expired=true`.", + mime_type=JSON)]) + + async def _read_resource(self, ctx, params: types.ReadResourceRequestParams) -> types.ReadResourceResult: + uri = str(params.uri) + return types.ReadResourceResult(contents=[types.TextResourceContents(uri=uri, mime_type=JSON, + text=json.dumps(self.read(uri), ensure_ascii=False))]) + + def read(self, uri: str) -> dict: + """A resource's content. Raises MCPError (RESOURCE_NOT_FOUND) for one there is none of.""" + parts = urlsplit(uri) + if f"{parts.scheme}://{parts.netloc}{parts.path}" == ALERTS_URI and self.alert_log is not None: + return alerts_read(self.alert_log, parse_qs(parts.query)) + raise MCPError(RESOURCE_NOT_FOUND, f"No resource {uri!r}: there are {ALERTS_URI} and {ALERTS_TEMPLATE}.") + + async def watch_alerts(self): + """Publish the alerts' URI on each new alert, until cancelled.""" + if self.alert_log is None: + return + last = self.alert_log.last_id() + while True: + await self.alert_log.wait(last) + last = self.alert_log.last_id() + await self.bus.publish(ResourceUpdated(ALERTS_URI)) + + async def run(self): + """The publishing, for as long as it runs.""" + await self.watch_alerts() + + +def http_app(server: IrrigationServer, *, tokens=(), allowed_hosts=("127.0.0.1", "localhost"), issuer_url: str = "http://127.0.0.1:8766", + path: str = "/mcp"): + """The Streamable HTTP app (Starlette) at `path`: the Host header checked against `allowed_hosts` (IRRIGATION_ALLOWED_HOSTS), and, + with `tokens` (AUTH_TOKENS), every request's bearer token (TokenCheck). `issuer_url` is required by the SDK with auth but unused.""" + check = TokenCheck(tokens) if tokens 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) + app.state.tokens = check + app.add_middleware(RequestLog, logger=requests_log, hosts_setting="IRRIGATION_ALLOWED_HOSTS") # (outermost: it sees the refusals) + return app + + +__all__ = ["ALERTS", "ALERTS_TEMPLATE", "ALERTS_URI", "IrrigationServer", "TOOLS", "http_app"] diff --git a/lib/irrigation/state.py b/lib/irrigation/state.py new file mode 100644 index 00000000..1c7a1ad1 --- /dev/null +++ b/lib/irrigation/state.py @@ -0,0 +1,49 @@ +"""irrigation-mcp's state: DATA_DIR/irrigation_state.json. It holds what the watchdog and the daily check keep, under the names they +kept it under in the bot's bot_state.json ("monitor"), so the two read it the same way from either: + + {"irrigation_watchdog": {"off_at": <epoch>}, "irrigation_monitor": {"checked": <date>, "paused": <date>, "battery_warned": <date>}} + +At its first start (no irrigation_state.json yet) the entries the bot kept in bot_state.json, when it ran the controller itself, are +copied over, once, and that is logged: a run the bot armed is still closed, and a day is neither checked twice nor skipped.""" + +import json +import logging +from pathlib import Path + +from ..alerts.store import load, write + +log = logging.getLogger(__name__) + +KEYS = ("irrigation_watchdog", "irrigation_monitor") # (the watchdog's, the daily check's) + + +class IrrigationState: + """`monitor`: the watchdog's and the check's entries; `save()` writes them (whole, to a new file that then replaces the old).""" + + def __init__(self, path, bot_state_path=None): + self.path = Path(path) + data = load(self.path) + if data is None: + data = self._from_the_bot(bot_state_path) + self.monitor: dict = {k: v for k, v in data.items() if k in KEYS and isinstance(v, dict)} if isinstance(data, dict) else {} + + def _from_the_bot(self, bot_state_path) -> dict: + """The bot's entries in bot_state.json, written here at once (so they are copied only this once, and nothing is copied at a later + start); {} when it kept none.""" + try: # (read only: the bot's file is the bot's, left as it is even when it can't be read) + bot = json.loads(Path(bot_state_path).read_text()) if bot_state_path else {} + except (OSError, ValueError): + bot = {} + kept = bot.get("monitor") if isinstance(bot, dict) and isinstance(bot.get("monitor"), dict) else {} + copied = {k: dict(kept[k]) for k in KEYS if isinstance(kept.get(k), dict) and kept[k]} + try: # (written even when there was nothing to copy: a later start never copies the bot's entries again) + write(self.path, copied) + except OSError as e: + log.warning("Irrigation: couldn't write %s (%s: %s)", self.path, type(e).__name__, e) + if copied: + log.info("Irrigation: the watchdog's and the daily check's state copied from %s to %s (%s), once: from now on it is kept " + "here", bot_state_path, self.path, ", ".join(copied)) + return copied + + def save(self): + write(self.path, self.monitor) diff --git a/lib/irrigation/tuya.py b/lib/irrigation/tuya.py index 92aae2c1..7643a80a 100644 --- a/lib/irrigation/tuya.py +++ b/lib/irrigation/tuya.py @@ -16,22 +16,12 @@ import httpx from ..config import Config +from .common import DELAYS, MAX_MINUTES, IrrigationError, is_paused # noqa: F401 (is_paused: named here too) log = logging.getLogger(__name__) TOKEN_PATH = "/v1.0/token?grant_type=1" TOKEN_INVALID = {1010, 1011} # Tuya's "token invalid" and "token expired" codes -DELAYS = ("24h", "48h", "72h", "cancel") # the device's weather_delay range -MAX_MINUTES = 60 # the longest run asked for from a button - - -def is_paused(status: dict) -> bool: - """Is the timer paused: a weather delay other than "cancel" (which is none)?""" - return status.get("weather_delay") not in (None, "cancel") - - -class IrrigationError(Exception): - """The controller could not be read or told something. The message is safe to log (no secrets, no raw response).""" def sign(client_id: str, secret: str, token: str, timestamp: str, nonce: str, method: str, path: str, body: bytes) -> str: diff --git a/lib/irrigation/watchdog.py b/lib/irrigation/watchdog.py index 92ff8e08..d4ae0973 100644 --- a/lib/irrigation/watchdog.py +++ b/lib/irrigation/watchdog.py @@ -1,7 +1,7 @@ -"""Closing the valve after a run the bot started, even if the controller does not. +"""Closing the valve after a run irrigation-mcp started (its water tool), even if the controller does not. `water` asks the device to run for N minutes (its `countdown`), but nothing independent checks that it stops. So the end time is -written to the bot's state file; a minute-by-minute check (cheap: it only talks to the controller once the time has passed) switches +written to irrigation-mcp's state file (irrigation_state.json); a minute-by-minute check (cheap: it only talks to the controller once the time has passed) switches the valve off if it is still on. Because the time is saved, a restart in the middle of a run still closes the valve. """ @@ -36,6 +36,13 @@ def disarm(self): def off_at(self) -> float | None: return self._memory().get("off_at") + def next_check(self) -> float: + """Seconds to the next check: CHECK_SECONDS, or sooner when a run's end (with its grace) comes before that, so the valve is + closed on time; a run already past it (its check failed) is tried again after CHECK_SECONDS.""" + due = self.off_at + left = None if due is None else due + GRACE_SECONDS - self.clock() + return CHECK_SECONDS if left is None or left <= 0 else min(CHECK_SECONDS, max(left, 1.0)) + async def check(self): """Switch the valve off if a run is over and it is still on. A failure is tried again at the next check.""" due = self.off_at diff --git a/lib/irrigation/menu.py b/lib/irrigation_menu.py similarity index 94% rename from lib/irrigation/menu.py rename to lib/irrigation_menu.py index d1f7559e..861fe9ff 100644 --- a/lib/irrigation/menu.py +++ b/lib/irrigation_menu.py @@ -1,4 +1,5 @@ -"""The irrigation status message and its buttons. Pure: it only builds the text and the keyboard. +"""The irrigation status message and its buttons, the bot's (the controller itself is irrigation-mcp's, which the bot calls: +lib/irrigation_remote.py). Pure: it only builds the text and the keyboard. Collapsed: [💧 Water] [⏸ Pause] / [🔔 Alerts] [🔄]. While the valve is on, a [Water off ❌] row follows. While the timer is paused, Pause is [▶️ Unpause] (one press ends the pause) and Water is hidden. A press on Water, Pause or Alerts opens its options under the @@ -16,9 +17,9 @@ from telegram import InlineKeyboardMarkup, MessageEntity -from ..buttons import button, opener, toggle_button -from ..entities import footer -from .tuya import DELAYS, is_paused +from .buttons import button, opener, toggle_button +from .entities import footer +from .irrigation.common import DELAYS, is_paused TITLE = "🌱 Irrigation" WATER_MINUTES = (5, 10, 20, 30) diff --git a/lib/irrigation_remote.py b/lib/irrigation_remote.py new file mode 100644 index 00000000..57e45ede --- /dev/null +++ b/lib/irrigation_remote.py @@ -0,0 +1,123 @@ +"""irrigation-mcp as the bot reaches it (docs/ecobot-mcp.md 3.9, step 8b): the irrigation controller is irrigation-mcp's (python -m +irrigation_mcp), and the bot its client over MCP at BOT_IRRIGATION_MCP_URL (RemoteIrrigation: lib/upstream.Upstream, the same token it +sends ecobot-mcp). The bot's Irrigation button, its menu and every ir: button (lib/bot.py, lib/irrigation_menu.py) call its tools through +the methods the bot always called on the controller: + + - `status()`: irrigation_status ({switch, countdown, weather_delay, paused, battery_percentage, work_state, off_at}); + - `water(minutes)`, `delay(duration)`, `set_switch(False)` (stop): irrigation-mcp watches a run and closes the valve itself; + - each raises IrrigationError (lib/irrigation/common.py) when irrigation-mcp can't be reached within CALL_WAIT seconds, or answers + with an error (the controller unreachable): the bot says it couldn't reach the controller; IrrigationRefused, one, when irrigation-mcp + refused the call (water while paused): the bot says that instead; + - `alerts`: irrigation://alerts read as AlertDelivery reads an alert log (lib/weather.RemoteAlerts), woken by the listen. + +Nothing here loads the Tuya client, the watchdog or the daily check: they are irrigation-mcp's.""" + +import asyncio +import json +import logging + +from .irrigation.common import IrrigationError, IrrigationRefused +from .weather import RemoteAlerts + +log = logging.getLogger(__name__) + +NAME = "irrigation-mcp" +ALERTS_URI = "irrigation://alerts" # (as lib/irrigation/server.py's) +CALL_WAIT = 5.0 # how long a press waits for irrigation-mcp while it is being reached again, before it is told it can't be +UNREACHABLE = "irrigation-mcp isn't reachable" + + +class RemoteIrrigation: + """irrigation-mcp at `target` (its MCP URL; in tests, a Server in memory), sending `token` (a string, a function giving it for each + connection, or None). `run()` is the supervisor (lib/upstream.Upstream): it keeps a connection, listening to irrigation://alerts.""" + remote = True + + def __init__(self, target, token=None): + from .upstream import Upstream + self.target = target + self.upstream = Upstream(target, token, on_event=self._event, on_listening=self._listening, resources=(ALERTS_URI,), name=NAME) + self.alerts = RemoteAlerts(self, ALERTS_URI) + self.listening = asyncio.Event() # the first connection listens + + @property + def url(self) -> str: + return self.target if isinstance(self.target, str) else "in-process" + + async def run(self): + await self.upstream.run() + + async def close(self): + pass + + # ---------- the connection ---------- + async def _listening(self): + """A new connection listens: the alerts looked at (what came while it was down is not replayed).""" + self.alerts.changed() + self.listening.set() + + async def _event(self, event): + from mcp.shared.subscriptions import ResourceUpdated + if isinstance(event, ResourceUpdated) and str(event.uri) == ALERTS_URI: + self.alerts.changed() + + async def _client(self, wait: float | None): + """The connected client, waiting up to `wait` seconds for one (None: as long as it takes); IrrigationError after.""" + up = self.upstream + if up.client is None and wait != 0: + try: + async with asyncio.timeout(wait): + while up.client is None: + await up.connected.wait() + if up.client is None: + await asyncio.sleep(0.05) + except TimeoutError: + pass + if up.client is None: + raise IrrigationError(f"{UNREACHABLE} ({self.url})") + return up.client + + async def resource(self, uri: str, wait: float | None = CALL_WAIT) -> dict: + """A resource's content (irrigation://alerts...); `wait`: how long to wait for irrigation-mcp (None: as long as it takes).""" + client = await self._client(wait) + read = await client.read_resource(uri) + return json.loads(read.contents[0].text) + + # ---------- the controller ---------- + async def call(self, name: str, args: dict | None = None) -> dict: + """A tool's answer as data; IrrigationError when irrigation-mcp can't be reached or the tool answers with an error, + IrrigationRefused when it refused the call.""" + client = await self._client(CALL_WAIT) + try: + result = await client.call_tool(name, args or {}) + except Exception as e: # (the connection lost mid-call, or a protocol error: the message names no secret) + raise IrrigationError(f"{NAME}'s {name} failed ({type(e).__name__}: {e})") from e + text = next((b.text for b in result.content if getattr(b, "type", None) == "text"), None) + try: + data = json.loads(text) if text is not None else None + except ValueError: + data = None + if not isinstance(data, dict): + raise IrrigationError(f"{NAME}'s {name} gave no answer") + if (result.is_error or "error" in data) and data.get("refused"): + raise IrrigationRefused(str(data.get("error") or f"{NAME} refused {name}"), paused=data["refused"] == "paused") + if result.is_error or "error" in data: + raise IrrigationError(str(data.get("error") or f"{NAME}'s {name} failed")) + return data + + async def status(self) -> dict: + return await self.call("irrigation_status") + + async def water(self, minutes: int): + await self.call("water", {"minutes": int(minutes)}) + + async def delay(self, duration: str): + await self.call("delay", {"duration": duration}) + + async def set_switch(self, on: bool): + """Off (stop): there is no On, a run is always timed (water).""" + if on: + raise IrrigationError("The valve is opened only for a timed run (water)") + await self.call("stop") + + +__all__ = ["ALERTS_URI", "CALL_WAIT", "RemoteIrrigation"] diff --git a/lib/lines.py b/lib/lines.py index 38f6a33a..a58feba3 100644 --- a/lib/lines.py +++ b/lib/lines.py @@ -12,13 +12,13 @@ import math from bisect import bisect_left, bisect_right from dataclasses import dataclass -from datetime import date, tzinfo +from datetime import date, timedelta, tzinfo from itertools import accumulate from statistics import fmean from typing import NamedTuple from .specs import Line -from .timeutil import SLOT, at_hour, local_date +from .timeutil import SLOT, at_hour, day_bounds, local_date DAY = 86400 SMOOTH_POINTS = 3 # a smoothed 5-minute line: each point is the mean of this many readings (15 minutes) @@ -109,9 +109,55 @@ def _summarise(points, key) -> dict: return {k: (fmean(v), *extremes[k]) for k, v in means.items()} +def day_of(tz: tzinfo): + """local_date(ts, tz) for readings mostly in time order: the day a reading is in is worked out once, and its span kept, so the + readings after it in the same day are placed by comparing two numbers (a span is kept only when its first and last second are of + that day: so where midnight is skipped or comes twice, every reading is still placed as local_date places it).""" + span = [1, 0, None] # [start, end, day]: empty at first + + def key(ts: int) -> date: + if span[0] <= ts <= span[1]: + return span[2] + day = local_date(ts, tz) + start, end = day_bounds(day, tz, True) + if start <= ts <= end and local_date(start, tz) == day == local_date(end, tz): + span[:] = start, end, day + return day + return key + + def daily_summary(points, tz: tzinfo) -> dict[date, tuple[float, float, float]]: """{local day: (mean, lowest low, highest high)}; see _summarise.""" - return _summarise(points, lambda ts: local_date(ts, tz)) + return _summarise(points, day_of(tz)) + + +def time_mean(means: dict[date, float], start: int, end: int, tz: tzinfo) -> float | None: + """The mean over [start, end] (epochs, both included) of these days' means, each day counting for the seconds of it inside: a part of + a day at either end for its hours, a whole day for its 24 (23 or 25 on a clock-change day), however many readings it had. A day's own + mean is of its half-hour means (daily_summary's, its day row's), so where every half hour is held this is the mean of the period's + half-hour means. None when no day is inside.""" + weights = {d: min(b, end + 1) - max(a, start) for d in means for a, b in [day_bounds(d, tz)]} + inside = [d for d, w in weights.items() if w > 0] + return fmean([means[d] for d in inside], [weights[d] for d in inside]) if inside else None + + +def readings_mean(points: list[tuple[int, float]], start: int, end: int, tz: tzinfo) -> float | None: + """The mean of these readings ((ts, value)) over [start, end], by time as a day row takes it: each day's mean of its half-hour means, + then the days by time_mean. So a day held only as hourly averages counts for its hours, as a day of 5-minute readings does, not for + its number of readings. (A reading's day is found among the period's midnights, not worked out for each of a year's readings.)""" + first = local_date(start, tz) + days = [first + timedelta(days=n) for n in range((local_date(end, tz) - first).days + 1)] + ends = [day_bounds(d, tz)[1] for d in days] + slots: dict[tuple[int, int], list] = {} # (the day, the half hour): [sum, count] + for ts, value in points: + if start <= ts <= end: + got = slots.setdefault((bisect_right(ends, ts), ts // SLOT), [0.0, 0]) + got[0] += value + got[1] += 1 + means: dict[date, list[float]] = {} + for (day, _), (total, n) in slots.items(): + means.setdefault(days[day], []).append(total / n) + return time_mean({d: fmean(m) for d, m in means.items()}, start, end, tz) def summary_by(points, key) -> dict: diff --git a/lib/llm.py b/lib/llm.py index e32f748a..e4ba3185 100644 --- a/lib/llm.py +++ b/lib/llm.py @@ -21,13 +21,15 @@ # Tool results past twice a full query's data (10,000 tokens) get the chat a heads-up: that much input rides on every later step WARN_TOKENS = 2 * POINT_BUDGET * TOKENS_PER_POINT +FALLBACK = "Sorry, I couldn't get an answer together - try a narrower question." # the reply when the model's last answer is empty + LIMIT_NOTICE = ("(System: tool limit reached. Answer now using only the data already fetched, " "and briefly say if anything is missing.)") class Agent: def __init__(self, client: "AsyncOpenAI | None", model: str, tools: Tools): - self.client, self.model, self.tools = client, model, tools # no client (no OPENROUTER_API_KEY): the tools are still called, the model never is + self.client, self.model, self.tools = client, model, tools # no client (no BOT_OPENROUTER_API_KEY): the tools are still called, the model never is @property def ready(self) -> bool: @@ -78,20 +80,18 @@ async def _stream(self, kwargs: dict, on_text) -> tuple[str, list[dict], object] on_text(content) return content, [calls[i] for i in sorted(calls)], usage - async def run(self, messages: list[dict], system_prompt: str, effort: str, *, - first_call: tuple[str, dict] | list[tuple[str, dict]] | None = None, tool_choice: str = "required", - turn: Turn | None = None, on_text=None, on_heavy=None) -> str: + async def run(self, messages: list[dict], system_prompt: str, effort: str, *, tool_choice: str = "auto", + turn: Turn | None = None, on_text=None, on_heavy=None, finish=None) -> str: """Runs the tool loop, appending assistant/tool turns to `messages` in place. The prompt is passed per question (not stored) so concurrent chats can't clash. - first_call (tool name, args), or a list of them, is what the bot already worked out (the fast path): the calls run - straight away, together, and the model is only invoked once the data is in. tool_choice is what the model's first - step may do with the tools: "required" makes it fetch fresh data first (weather questions), "auto" lets it just - reply (chat), "none" gives it no tools at all (a question about the bot itself). Every later step is "auto". - on_text(text so far) is called as each answer streams in (private chats show it as a draft). + tool_choice is what the model's first step may do with the tools ("auto": its own choice; every later step is "auto", the + last forced answer "none"). on_text(text so far) is called as each answer streams in (private chats show it as a draft). on_heavy(tokens) is called once, before the model is sent a lot of data: when the tool results of a question pass WARN_TOKENS (twice a 500-point query), so the chat can be told - first. The work carries on; nothing waits for a reply.""" + first. The work carries on; nothing waits for a reply. + finish(calls, results) is asked after each step of the model's tool calls: text from it is the reply, and the turn ends there + with no further model call (a complete result, docs/ecobot-mcp.md 3.7).""" cache: dict = {} # identical tool calls within one question are only made once async def call(name: str, args: str) -> str: @@ -116,30 +116,23 @@ async def heavy_check(): llm_time = tool_time = 0.0 - async def run_calls(calls: list[dict]): - """The calls ({"id", "name", "arguments"}), made together; their results join the messages.""" + async def run_calls(calls: list[dict]) -> list[str]: + """The calls ({"id", "name", "arguments"}), made together; their results join the messages and are returned in order.""" nonlocal tool_time t0 = time.monotonic() results = await asyncio.gather(*(call(c["name"], c["arguments"]) for c in calls)) tool_time += time.monotonic() - t0 messages.extend({"role": "tool", "tool_call_id": c["id"], "content": r} for c, r in zip(calls, results)) - await heavy_check() + return results - first_step = 0 try: - if first_call: - fast = [{"id": f"fast_{i}", "name": n, "arguments": json.dumps(a)} - for i, (n, a) in enumerate(first_call if isinstance(first_call, list) else [first_call], 1)] - messages.append({"role": "assistant", "content": "", "tool_calls": [_tool_call(c) for c in fast]}) - await run_calls(fast) - first_step = 1 # data is in; the model just answers (and may still call tools) - for step in range(first_step, MAX_STEPS + 1): + for step in range(MAX_STEPS + 1): final = step == MAX_STEPS # out of steps: force an answer from what we have kwargs = {"model": self.model, "messages": [{"role": "system", "content": system_prompt}, *messages], "extra_body": {"reasoning": {"effort": effort}}} # OpenRouter's setting for every model that reasons: none / low / medium / high if self.tools.schemas: # every tool, every time: the same list keeps the provider's cached prompt valid - kwargs["tools"] = self.tools.schemas_for(turn) + kwargs["tools"] = self.tools.schemas kwargs["tool_choice"] = "none" if final or tool_choice == "none" else tool_choice if step == 0 else "auto" if final: log.warning("Tool step limit (%d) reached - asking for a final answer", MAX_STEPS) @@ -152,8 +145,14 @@ async def run_calls(calls: list[dict]): entry["tool_calls"] = [_tool_call(tc) for tc in tool_calls] messages.append(entry) if not tool_calls or final: - return content.strip() or "Sorry, I couldn't get an answer together - try a narrower question." - await run_calls(tool_calls) + return content.strip() or FALLBACK + results = await run_calls(tool_calls) + if finish and (reply := finish(tool_calls, results)): + log.info("The turn ended on a complete result (%s): no LLM %d", + ", ".join(c["name"] for c in tool_calls), step + 2) + messages.append({"role": "assistant", "content": reply}) + return reply + await heavy_check() finally: log.info("Timing: LLM %.1fs, tools %.1fs", llm_time, tool_time) diff --git a/lib/logs.py b/lib/logs.py index 5b98582a..19f73917 100644 --- a/lib/logs.py +++ b/lib/logs.py @@ -1,5 +1,5 @@ """How the bot's log lines look: the message alone, marked WARN, ERROR or DEBUG when it is not an ordinary (INFO) line. Only a chat -message (a request quoted last on a line) is shortened: put on one line and cut to the log width (LOG_WIDTH) with an ellipsis (…) +message (a request quoted last on a line) is shortened: put on one line and cut to the log width (BOT_LOG_WIDTH) with an ellipsis (…) marking the cut. Every other line, and a traceback, is logged whole. DEBUG and INFO lines go to stdout, WARN and ERROR to stderr, so Docker (and its journald driver) tells them apart. Under systemd both go diff --git a/lib/mcp_http.py b/lib/mcp_http.py new file mode 100644 index 00000000..5761b606 --- /dev/null +++ b/lib/mcp_http.py @@ -0,0 +1,233 @@ +"""What the two MCP servers here share over HTTP (ecobot-mcp, lib/mcp_server.py, and irrigation-mcp, lib/irrigation/server.py), with +nothing of either in it, so irrigation-mcp loads none of ecobot-mcp's tools or sources: + + - `TokenCheck`: the TokenVerifier (docs/ecobot-mcp.md 3.8): a bearer token is one of AUTH_TOKENS, compared in constant time; + - `host_settings`: the Host (and Origin) headers a server answers (TransportSecuritySettings); + - `RequestLog`: ASGI middleware, one line per HTTP request, a refusal with its reason; + - `Uvicorn` and `server_config`: uvicorn's server as both run it (the signals left to the program, a listen stream given a moment to + end at shutdown); + - `generated_token`: AUTH_TOKENS unset, the token kept in the data folder (lib/auth_token.py), made at the first start; + - `hold_folder`: one process of a program per data folder (a lock file); + - `alerts_read`: an alert log (lib/alert_log.py) as its resource gives it, after `since`, unexpired unless `expired`.""" + +import contextlib +import hmac +import json +import logging +import time +from pathlib import Path + +import mcp_types as types +import uvicorn +from mcp.server.auth.provider import AccessToken +from mcp.server.transport_security import TransportSecuritySettings +from mcp.shared.exceptions import MCPError + +from . import auth_token + +log = logging.getLogger(__name__) + +SHUTDOWN_SECONDS = 3 # how long uvicorn waits for open connections (a listen stream) to end when a server stops + + +# ---------- auth ---------- +class TokenCheck: + """A server's TokenVerifier (3.8): a bearer token is one of AUTH_TOKENS, compared in constant time against every one of them. + `revoke(token)` takes one out while the server runs (AUTH_TOKENS without it does the same at the next start).""" + + def __init__(self, tokens): + self.tokens = list(dict.fromkeys(tokens)) + + def revoke(self, token: str): + if token in self.tokens: + self.tokens.remove(token) + + async def verify_token(self, token: str) -> AccessToken | None: + found = False + sent = (token or "").encode() + for known in list(self.tokens): # (every one compared: the time says nothing of which matched) + found |= hmac.compare_digest(sent, known.encode()) + return AccessToken(token=token, client_id="client", scopes=[]) if found else None + + +def host_settings(allowed: tuple[str, ...] | list[str]) -> TransportSecuritySettings: + """The Host (and Origin) headers a server answers: each name allowed with any port, unless it names one.""" + hosts, origins = [], [] + for name in allowed: + bare = name.startswith("[") and name.endswith("]") or ":" not in name.rsplit("]", 1)[-1] + hosts += [name, f"{name}:*"] if bare else [name] + origins += [f"{scheme}://{h}" for scheme in ("http", "https") for h in ([name, f"{name}:*"] if bare else [name])] + return TransportSecuritySettings(enable_dns_rebinding_protection=True, allowed_hosts=hosts, allowed_origins=origins) + + +def generated_token(folder: Path, logger: logging.Logger = log, program: str = "ecobot-mcp") -> str: + """AUTH_TOKENS unset: the token kept in the data folder, made at the first start (its place is logged, never its value). Every + server and client on the one data folder uses the same one.""" + try: + token = auth_token.ensure(folder) + except OSError as e: + raise SystemExit(f"AUTH_TOKENS is not set and a token couldn't be kept in {auth_token.path(folder)} ({type(e).__name__}: {e}): " + "set AUTH_TOKENS (token,token,...), or make the data folder writable") from None + logger.info("AUTH_TOKENS is not set: %s accepts the token kept in %s (the bot reads it from there; give it to any other client)", + program, auth_token.path(folder)) + return token + + +def hold_folder(folder: Path, name: str, program: str, command: str, stack): + """One `program` per data folder: two on the same folder would both act (both fetch and alert; both water). The lock (the file + `name` in the folder) is the kernel's, so it goes with the process, however that ends; `stack` releases it.""" + import fcntl + path = Path(folder) / name + path.parent.mkdir(parents=True, exist_ok=True) + held = open(path, "w") + try: + fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + held.close() + raise SystemExit(f"Another {program} ({command}) already runs on {path.parent}: stop it first, or give this one another DATA_DIR.") + stack.callback(held.close) + + +# ---------- an alert log as a resource ---------- +def alerts_read(alert_log, query: dict | None = None) -> dict: + """{alerts, last_id, identity}: the alerts after `since` (0), only the unexpired unless `expired` is true (query: parse_qs's).""" + query = query or {} + since = (query.get("since") or ["0"])[-1].strip() + expired = (query.get("expired") or ["false"])[-1].strip().lower() in ("true", "1", "yes", "on") + if since and not since.isdecimal(): + raise MCPError(types.INVALID_PARAMS, f"`since` is an alert's id, a whole number, not {since!r}.") + return {"alerts": alert_log.since(int(since or 0), expired=expired), "last_id": alert_log.last_id(), "identity": alert_log.identity} + + +# ---------- uvicorn ---------- +class Uvicorn(uvicorn.Server): + """uvicorn's server, leaving SIGINT and SIGTERM to the program (which closes everything in order: uvicorn's own handling raises the + signal again once it has stopped, ending the process before the rest is closed), and ending the app's endless streams (ecobot-mcp's + dashboard) as it stops.""" + + @contextlib.contextmanager + def capture_signals(self): + yield + + async def shutdown(self, sockets=None): + """uvicorn's graceful shutdown, the app's endless streams (`app.state.closing`) ended first, once no new connection is + accepted, so it doesn't wait on them.""" + for server in self.servers: + server.close() + closing = getattr(getattr(self.config.app, "state", None), "closing", None) + if closing is not None: + closing() + await super().shutdown(sockets) + + +def server_config(app, host: str, port: int, shutdown_seconds: float = SHUTDOWN_SECONDS) -> uvicorn.Config: + """uvicorn's settings for the app: its lifespan on (the MCP session manager runs in it), its own access log off, and an open + listen stream given `shutdown_seconds` to end when it stops (else it would wait for the client to hang up).""" + return uvicorn.Config(app, host=host, port=port, lifespan="on", log_level="warning", access_log=False, proxy_headers=True, + timeout_graceful_shutdown=shutdown_seconds) + + +# ---------- the request log ---------- +BODY_READ = 1 << 20 # the most of a request's body read to name its MCP method (the SDK reads it all anyway) +CHART_PATH = "/charts" # (ecobot-mcp's chart links' pictures: their ids are cut short in the log) + + +def why_refused(hosts_setting: str) -> dict[int, str]: + """The reason logged for each refusal, naming the setting that allows a Host.""" + return {401: "no token, or one that isn't in AUTH_TOKENS", 421: f"its Host isn't in {hosts_setting}", + 404: "nothing at this path, or the session has ended"} + + +def _rpc(body: bytes) -> str: + """What a JSON-RPC body asks: its method, and the tool, resource or prompt it names ("tools/call summary").""" + try: + msg = json.loads(body) + except ValueError: + return "" + msgs = msg if isinstance(msg, list) else [msg] + out = [] + for m in msgs: + if not isinstance(m, dict) or "method" not in m: + continue + params = m.get("params") if isinstance(m.get("params"), dict) else {} + target = params.get("name") or params.get("uri") + line = f"{m['method']} {target}" if isinstance(target, str) else str(m["method"]) + if isinstance(args := params.get("arguments"), dict) and args: + line += " " + _arguments(args) + out.append(line) + return ", ".join(out) + + +def _arguments(args: dict, most: int = 160) -> str: + """What a tool call asks for, short: its readings, its dates (the period as written, or start to end) and its interval + ("rain 1d", "outdoor.temperature 2026-11-01 to 2026-11-05 5min"); irrigation-mcp's minutes and duration ("10", "24h"); cut at + `most` characters.""" + def text(v) -> str: + return ",".join(map(str, v)) if isinstance(v, list) else str(v) + metric = args.get("readings") or args.get("reading") + dates = args.get("period") or " to ".join(str(args[k]) for k in ("start", "end") if args.get(k)) + parts = (metric, dates, args.get("interval"), args.get("minutes"), args.get("duration")) + out = " ".join(text(v) for v in parts if v not in (None, "", [])) + return out if len(out) <= most else out[:most - 1] + "…" + + +def _shown_path(path) -> str: + """A path as logged: a chart link's id cut to its first characters (/charts/AbCdEf….png), the rest as it is.""" + path = str(path or "") + if path.startswith(CHART_PATH + "/"): + name = path[len(CHART_PATH) + 1:] + key = name[:-4] if name.endswith(".png") else name + return f"{CHART_PATH}/{key[:6]}{'…' if len(key) > 6 else ''}{'.png' if name.endswith('.png') else ''}" + return path + + +class RequestLog: + """ASGI middleware, outermost: one line per HTTP request, once its response starts (a listen stream's when it opens), on `logger`. + INFO when answered, WARNING when refused, with the reason for a 401 (the token), a 421 (the Host: `hosts_setting` names the setting + that allows one) and a 404. The token itself is never logged; the client's address is the proxy's X-Forwarded-For when uvicorn + trusts it.""" + + def __init__(self, app, logger: logging.Logger | None = None, hosts_setting: str = "MCP_ALLOWED_HOSTS"): + self.app = app + self.logger = logger or logging.getLogger("lib.mcp_server.requests") + self.why = why_refused(hosts_setting) + + async def __call__(self, scope, receive, send): + if scope["type"] != "http": + return await self.app(scope, receive, send) + start = time.monotonic() + held, body = [], b"" + if scope.get("method") == "POST": # (read here to name the MCP method, then handed on as it came) + while True: + message = await receive() + held.append(message) + if message["type"] != "http.request": + break + if len(body) < BODY_READ: + body += message.get("body", b"") + if not message.get("more_body"): + break + + async def replay(): + return held.pop(0) if held else await receive() + + async def sending(message): + if message["type"] == "http.response.start": + self.record(scope, _rpc(body) if body else "", message["status"], time.monotonic() - start) + await send(message) + await self.app(scope, replay, sending) + + def record(self, scope, asked: str, status: int, took: float): + headers = dict(scope.get("headers") or []) + client = (scope.get("client") or ("?",))[0] + host = headers.get(b"host", b"").decode("latin-1") + what = f"{scope.get('method')} {_shown_path(scope.get('path'))}" + (f" {asked}" if asked else "") + if status < 400: + self.logger.info("MCP %s: %s -> %d in %.2fs", client, what, status, took) + else: + why = "the chart's link has expired, or never was" if status == 404 and str(scope.get("path")).startswith(CHART_PATH + "/") \ + else self.why.get(status) + self.logger.warning("MCP %s refused: %s -> %d%s (Host %s)", client, what, status, f", {why}" if why else "", host or "none") + + +__all__ = ["RequestLog", "alerts_read", "SHUTDOWN_SECONDS", "TokenCheck", "Uvicorn", "generated_token", "hold_folder", "host_settings", "server_config"] diff --git a/lib/mcp_server.py b/lib/mcp_server.py new file mode 100644 index 00000000..de0ddaa9 --- /dev/null +++ b/lib/mcp_server.py @@ -0,0 +1,525 @@ +"""The service over MCP (docs/ecobot-mcp.md 3.4-3.8): the SDK's low-level Server serving the ten tools (lib/service), the resources and +prompts, the server's instructions (lib/service/instructions.py) and the `subscriptions/listen` stream, as Streamable HTTP behind a bearer +token check. + + - **Tools**: each ServiceTool as it is, its hand-written input schema and description, `readOnlyHint` and `openWorldHint` from it. The + list is built when asked, from the catalogue of readings the file holds: when that gains a reading (`refresh_catalogue`, every + CATALOGUE_SECONDS) the tools are built again and ToolsListChanged is published. A call runs the ServiceTool with the request's + `_meta` (`chart_points`, `fetch`, `priority`: common.request_meta) and answers its JSON as one text block, unchanged: its charts are + the full chart JSON (3.7), sized by `chart_points`. A refusal is `isError`. A complete answer (3.7: `chart_answers_it` and a chart) + also carries its `reply` as a second text block for the person (`audience: ["user"]`) and result `_meta` {"ecobot/complete": true}. + - **Chart images** (3.7, lib/chart_images.py), for a connection whose MCP URL asks (`/mcp?charts=png`) or a call whose `_meta` does + (`chart_image`: "png", or "none" against the connection's): the text block's charts are each {title, period} with a `chart_note` that + fits an attached image, followed by one ImageContent (image/png) per chart in order, drawn as the bot draws them (lib/charts, + off the event loop) from every point (`chart_points` "drawn" unless the call says); the full chart JSON, with drawn_by, is in + result `_meta` "ecobot/charts" and the theme in "ecobot/chart_dark" (DARKMODE, or the call's `chart_dark`). Pillow is imported at + the first image: without it the answer is the JSON as without images, with `chart_image_note` saying so. + - **Chart links** (3.7), for a client that shows a markdown image in the model's reply but not an image in a tool's result + (`/mcp?charts=link`, or `chart_image: "link"`): the charts drawn as for images but kept (chart_images.Links, in memory, for + MCP_CHART_LINK_HOURS) and served at GET /charts/<id>.png; the text block's charts are each {title, period, url, markdown} with a + `chart_note` asking the model to put each `markdown` in its reply, followed by one ResourceLink per chart (no bytes); result + `_meta` as with images. A complete answer's reply carries the markdown images too. The URL is MCP_CHART_BASE_URL's, else the + MCP request's own (X-Forwarded-Proto and X-Forwarded-Host when there) with /charts. + - **Resources** (3.4): RESOURCES, and the alerts with `since` and `expired` (the ALERTS_TEMPLATE). Each is JSON. The live ones are + published as ResourceUpdated when they change (`publish_changes`, every PUBLISH_SECONDS, from what the sources keep: no request is + made for it; a reading asked for again and unchanged is not sent), the alerts on each new event (`watch_alerts`, lib/alert_log.py + `wait`), the station when the catalogue gains a reading. + ecobot://status is the Status picture (lib/status.py): its readings as a JSON text content, then the PNG as a blob (image/png), + Pillow imported at the first read. + - **Prompts** (3.5): PROMPTS, each a question in words with its period an argument; no logic. + - **HTTP** (`http_app`): `streamable_http_app` at /mcp, its Host header checked against the allowed hosts + (TransportSecuritySettings: 127.0.0.1 and localhost unless MCP_ALLOWED_HOSTS says), each request's bearer token against + AUTH_TOKENS (TokenCheck: a constant-time compare, one token per client, so one can be revoked alone). Beside it, unless MCP_DASHBOARD + is off, the gauges' live page at /dashboard (lib/web_dashboard.py), and always the chart links' pictures at /charts/<id>.png: + read-only, so neither the token nor the Host is asked (a picture's id is random, unguessable, and its only key). + +`EcobotServer(ctx, alert_log)` builds it over the service's Context; `run()` is its publishing, for as long as it runs. Nothing here +fetches, alerts or writes: ecobot_mcp runs the sources and the rules.""" + +import asyncio +import base64 +import json +import logging +import os +from collections.abc import Callable +from datetime import date, datetime +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +import mcp_types as types +from mcp.server.auth.settings import AuthSettings +from mcp.server.lowlevel import Server +from mcp.server.subscriptions import InMemorySubscriptionBus, ListenHandler, ResourceUpdated, ToolsListChanged +from mcp.shared.exceptions import MCPError +from starlette.requests import Request +from starlette.responses import Response +from starlette.routing import Route + +from . import chart_images, theme +from .config import ROOT +from .mcp_http import CHART_PATH, RequestLog, TokenCheck, alerts_read, host_settings +from .service import Service +from .service.about import AboutTool, alerts as alert_kinds +from .service.common import AS_DRAWN, charts_as_titles, iso +from .service.current import CurrentTool +from .service.instructions import instructions +from .service.names import AIR_DEVICE, STATION, Catalogue +from .tools import json_result +from .web_dashboard import WebDashboard + +log = logging.getLogger(__name__) +requests_log = logging.getLogger(__name__ + ".requests") # one line per HTTP request (RequestLog) + +NAME = "ecobot" +COMPLETE = "ecobot/complete" # result _meta of a complete answer (3.7) +RESOURCE_NOT_FOUND = -32002 # MCP's error for a resource there is none of +PUBLISH_SECONDS = 2.0 # how often the live resources are compared with what was last published +CATALOGUE_SECONDS = 60.0 # how often the file's catalogue of readings is read again +SCHEMA_PATH = ROOT / "schemas" / "chart.json" +JSON = "application/json" + +# ---------- resources (3.4) ---------- +STATION_URI, WEATHER_URI, AIR_URI = "ecobot://station", "ecobot://now/weather", "ecobot://now/air" +ALERTS_URI, FORECAST_URI, POLLEN_URI = "ecobot://alerts", "ecobot://forecast", "ecobot://pollen" +HEALTH_URI, SCHEMA_URI = "ecobot://health", "ecobot://schema/chart" +STATUS_URI = "ecobot://status" +ALERTS_TEMPLATE = "ecobot://alerts{?since,expired}" +RESOURCES = { # uri: (name, title, description, the source it needs: None for always) + STATION_URI: ("station", "The station", "Its name, time zone, location and when it was set up; the sensors with their readings (name, " + "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 " + "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.", + "air"), + ALERTS_URI: ("alerts", "Alerts", "The alerts the service has decided, newest last, kept 30 days: {alerts: [{id, kind, time, expires, " + "title, text, data, [link], [chart]}], last_id, identity}; only those not yet expired (the template: since an id, and " + "expired=true for all). Pushed on each new alert.", None), + FORECAST_URI: ("forecast", "The forecast", "The forecast days, structured: {place, fetched_at, days: [{date, min_c, max_c, " + "rain_chance_pct, rain_1mm_pct, summary, text}]}. Pushed on each new forecast.", "forecast"), + POLLEN_URI: ("pollen", "Pollen and thunderstorm asthma", "Grass pollen and thunderstorm asthma levels: {in_season, fetched_at, " + "grass: {level, emoji, date}, asthma: {level, emoji, updated}, lines}. Pushed on each new page.", "pollen"), + STATUS_URI: ("status", "Status", "The report in words and the weather station's temperature, humidity and rain gauges in a row, as a " + "picture (image/png, a blob), with JSON text first: {report (the readings now, today's forecast and the pollen, each " + "section a heading then its lines: to send as it is), gauges: [{title, value, unit, rows: {Daily, Monthly, " + "Yearly: {Max, Min} or {Max, Total}}}], lines}; the picture shows the readings now, the text their highs and lows too. " + "Without the picture (no Pillow here) the text has `image_note`. Not pushed.", "eco"), + HEALTH_URI: ("health", "Health", "Each loop's last success and failure, the archive's progress, the readings file's size and the " + "alert log's newest id. Not pushed.", None), + SCHEMA_URI: ("schema/chart", "Chart JSON Schema", "The JSON Schema of the charts in the tools' results and the alerts " + "(schemas/chart.json, versioned). Not pushed.", None), +} +PUSHED = (WEATHER_URI, AIR_URI, FORECAST_URI, POLLEN_URI) # compared every PUBLISH_SECONDS (the alerts and the station have their own) + +# ---------- prompts (3.5) ---------- +PERIOD = types.PromptArgument(name="period", description="The period in your own words (\"this week\", \"last 3 months\", \"yesterday\")", + required=False) +PROMPTS = { # name: (description, arguments, the question: a format string over the arguments, with their defaults). A name is also a + # chat command (Telegram's: lowercase, digits and _, at most 32), so none takes a bot command's name (lib/templates.COMMANDS) + "now": ("The weather and the air now.", [], "How is it outside now?"), + "report": ("A report: the readings now, today's forecast and the pollen.", [], + "Give me a report: the readings now, today's forecast and the pollen."), + "will_it_rain": ("Will it rain in the next few hours: the station's read and the forecast.", [], "Will it rain in the next few hours?"), + "weather_chart": ("Every reading of the weather station over a period, a panel each.", [PERIOD], + "Chart every weather reading, a panel each, over {period}."), + "chart": ("A chart of a reading over a period.", + [types.PromptArgument(name="reading", description="The reading (\"temperature\", \"pressure\", \"pm2.5\")", required=True), + PERIOD], "Chart {reading} over {period}."), + "rainfall": ("How much rain fell over a period, and when.", [PERIOD], "How much rain fell over {period}?"), + "air": ("The air quality, now or over a period.", [PERIOD], "How was the air quality over {period}?"), +} +PROMPT_DEFAULTS = {"weather_chart": {"period": "the last 7 days"}, "chart": {"period": "the last 24 hours"}, "rainfall": {"period": "today"}} +WITHOUT_ARGUMENTS = {"air": "How is the air quality now?"} # the question when no argument is sent + + +def _json(data) -> str: + return json.dumps(data, ensure_ascii=False, default=_plain) + + +def _plain(x): + """What JSON lacks: a date or a time as ISO.""" + if isinstance(x, (date, datetime)): + return x.isoformat() + raise TypeError(f"{type(x).__name__} is not JSON") + + +# ---------- a tool's answer as MCP's ---------- +def tool_entry(tool) -> types.Tool: + """A ServiceTool as tools/list gives it: its name, description, hand-written input schema and annotations.""" + return types.Tool(name=tool.name, description=tool.description, input_schema=tool.parameters, + annotations=types.ToolAnnotations(read_only_hint=tool.read_only, open_world_hint=tool.open_world)) + + +def _loads(text: str): + try: + return json.loads(text) + except ValueError: + return None + + +def charts_of(data) -> list[dict]: + """The charts of a tool's answer (none for a refusal).""" + charts = data.get("charts") if isinstance(data, dict) and "error" not in data else None + return charts if isinstance(charts, list) and charts and all(isinstance(c, dict) for c in charts) else [] + + +def tool_result(text: str, images: list[bytes] | None = None, dark: bool | None = None, note: str | None = None, + links: list[str] | None = None) -> types.CallToolResult: + """A ServiceTool's answer as tools/call gives it: the JSON as one text block, unchanged; `isError` for a refusal; a complete answer + (3.7) with its reply for the person as a last block (audience user) and result _meta {COMPLETE: true}. With `images` (a PNG per + chart): the charts in the text as {title, period} and chart_note IMAGE_NOTE, an ImageContent per chart after it, and result _meta + {CHARTS_META: the full charts, DARK_META: dark}. With `links` (a picture's URL per chart) instead: the charts in the text as + {title, period, url, markdown} and chart_note LINK_NOTE, a ResourceLink per chart after it, the same result _meta, and a complete + answer's reply with the markdown images after its words. `note`: why images asked for aren't there (`chart_image_note`).""" + data = _loads(text) + content: list = [] + meta = {} + reply = data.get("reply") if isinstance(data, dict) else None + if links and (charts := charts_of(data)) and len(links) == len(charts): + told = charts_as_titles(data, chart_images.LINK_NOTE) + told["charts"] = [{**c, "url": url, "markdown": chart_images.markdown(c.get("title"), url)} for c, url in zip(told["charts"], links)] + if isinstance(reply, str) and reply: + told["reply"] = reply = "\n\n".join([reply, *(c["markdown"] for c in told["charts"])]) + content.append(types.TextContent(text=json_result(told))) + content += [types.ResourceLink(uri=url, name=str(c.get("title") or "Chart"), mime_type=chart_images.PNG) + for c, url in zip(told["charts"], links)] + meta.update({chart_images.CHARTS_META: charts, chart_images.DARK_META: bool(dark)}) + elif images and (charts := charts_of(data)) and len(images) == len(charts): + content.append(types.TextContent(text=json_result(charts_as_titles(data, chart_images.IMAGE_NOTE)))) + content += [types.ImageContent(data=base64.b64encode(png).decode("ascii"), mime_type=chart_images.PNG) for png in images] + meta.update({chart_images.CHARTS_META: charts, chart_images.DARK_META: bool(dark)}) + elif note and charts_of(data): + content.append(types.TextContent(text=json_result({**data, "chart_image_note": note}))) + else: + content.append(types.TextContent(text=text)) + if isinstance(data, dict) and data.get("complete") is True and isinstance(data.get("reply"), str) and "error" not in data: + content.append(types.TextContent(text=reply, annotations=types.Annotations(audience=["user"]))) + meta[COMPLETE] = True + return types.CallToolResult(content=content, is_error=isinstance(data, dict) and "error" in data, _meta=meta or None) + + +def connection_query(ctx, name: str) -> str | None: + """A query parameter of the connection's MCP URL (`/mcp?charts=png`), from the HTTP request the call came in (None in memory).""" + params = getattr(getattr(ctx, "request", None), "query_params", None) + return params.get(name) if params is not None else None + + +def request_base(request) -> str: + """Where the MCP request came to, as a browser reaches it: the scheme and host of X-Forwarded-Proto and X-Forwarded-Host when + a proxy sent them (their first value), else the request's own; "" without a request (in memory).""" + if request is None or getattr(request, "headers", None) is None: + return "" + headers = request.headers + first = lambda name: (headers.get(name) or "").split(",")[0].strip() # noqa: E731 + scheme = first("x-forwarded-proto") or request.url.scheme + host = first("x-forwarded-host") or headers.get("host") or request.url.netloc + return f"{scheme}://{host}" if host else "" + + +# ---------- the server ---------- +class EcobotServer: + """The service's MCP server over a Context (lib/service/context.py) and the alert log. health: a callable giving the service's own + health figures (ecobot_mcp's loops), merged into ecobot://health.""" + + def __init__(self, ctx, alert_log=None, *, health: Callable[[], dict] | None = None, version: str = "", bus=None, + chart_base_url: str = "", chart_link_hours: float = chart_images.LINK_HOURS, chart_links=None): + self.ctx, self.alert_log, self.health_of = ctx, alert_log, health + self.chart_base_url = chart_base_url.rstrip("/") # MCP_CHART_BASE_URL: "" for the MCP request's own with CHART_PATH + self.chart_links = chart_links if chart_links is not None else chart_images.Links(chart_link_hours) + self.bus = bus or InMemorySubscriptionBus() + self.listen = ListenHandler(self.bus) + self._service = Service.of(ctx) + self._seen: dict[str, str | None] = {uri: self._fingerprint(uri) for uri in PUSHED} + self.server = Server(NAME, version=version, title="Ecobot weather and air service", instructions=instructions(ctx), + get_tool_input_schema=self._schema, + on_list_tools=self._list_tools, on_call_tool=self._call_tool, + on_list_resources=self._list_resources, on_list_resource_templates=self._list_templates, + on_read_resource=self._read_resource, + on_list_prompts=self._list_prompts, on_get_prompt=self._get_prompt, + on_subscriptions_listen=self.listen) + + @property + def service(self) -> Service: + return self._service + + # ---------- tools ---------- + def _schema(self, name: str): + tool = self._service.get(name) + return tool.parameters if tool else None + + async def _list_tools(self, ctx, params) -> types.ListToolsResult: + return types.ListToolsResult(tools=[tool_entry(t) for t in self._service]) + + async def _call_tool(self, ctx, params: types.CallToolRequestParams) -> types.CallToolResult: + tool = self._service.get(params.name) + if tool is None: + raise MCPError(types.INVALID_PARAMS, f"No tool {params.name!r}: the tools are {', '.join(t.name for t in self._service)}.") + meta = dict(ctx.meta or {}) + if not (mode := chart_images.wanted(meta, connection_query(ctx, "charts"))): + return tool_result(await tool.call(params.arguments or {}, meta)) + render = chart_images.renderer() # (Pillow imported now, at the first image asked for) + if render is None: + return tool_result(await tool.call(params.arguments or {}, meta), note=chart_images.UNAVAILABLE_NOTE) + text = await tool.call(params.arguments or {}, {"chart_points": AS_DRAWN, **meta}) # (the picture from every point, as the bot's) + if not (charts := charts_of(_loads(text))): + return tool_result(text) + dark = chart_images.asked_dark(meta) + dark = theme.dark_now() if dark is None else dark + try: + pngs = await asyncio.to_thread(lambda: [chart_images.render(c, self.ctx.zone, dark)[0] for c in charts]) + except Exception as e: + log.error("MCP: %s's chart couldn't be drawn: %s: %s", params.name, type(e).__name__, e) + return tool_result(await tool.call(params.arguments or {}, meta), note=chart_images.NOT_DRAWN_NOTE) # (as if off) + if mode == chart_images.LINK: + base = self.chart_url_base(getattr(ctx, "request", None)) + return tool_result(text, dark=dark, links=[f"{base}/{self.chart_links.put(png)}.png" for png in pngs]) + return tool_result(text, pngs, dark) + + def chart_url_base(self, request=None) -> str: + """Where a chart link's picture is reached, its id and .png to follow: MCP_CHART_BASE_URL, else the MCP request's own scheme + and host (request_base) with CHART_PATH (a path alone in memory).""" + return self.chart_base_url or request_base(request) + CHART_PATH + + async def chart_picture(self, request: Request) -> Response: + """GET /charts/<id>.png: a chart link's picture while it is kept (private, cached for at most what is left of its life); 404 + for an id not kept (never made, expired, dropped, or before a restart).""" + name = request.path_params.get("name", "") + kept = self.chart_links.get(name[:-4]) if name.endswith(".png") else None + if kept is None: + return Response("No such chart: its link has expired, or never was.\n", status_code=404, media_type="text/plain", + headers={"Cache-Control": "no-store"}) + png, left = kept + return Response(png, media_type=chart_images.PNG, headers={"Cache-Control": f"private, max-age={max(0, int(left))}"}) + + async def refresh_catalogue(self) -> bool: + """Read the file's catalogue of readings again; when it gained a reading (a sensor sent a field it never sent), build the tools + and the instructions again and publish ToolsListChanged and the station. True when it did.""" + if self.ctx.eco is None and self.ctx.air is None: + return False + new = await Catalogue.open(self.ctx.eco, self.ctx.air) + if not (gained := [n for n in new.names if n not in set(self.ctx.readings().names)]): + return False + self.ctx.catalogue = new + self._service = Service.of(self.ctx) + self.server.instructions = instructions(self.ctx) + log.info("MCP: the readings now include %s: the tools are built again", ", ".join(gained)) + await self.bus.publish(ToolsListChanged()) + await self.bus.publish(ResourceUpdated(STATION_URI)) + return True + + # ---------- resources ---------- + def _there(self, need: str | None) -> bool: + return need is None or (need == "eco" and self.ctx.eco is not None) or (need == "air" and self.ctx.air is not None) or \ + (need == "forecast" and self.ctx.forecast is not None) or (need == "pollen" and self.ctx.pollen is not None) + + async def _list_resources(self, ctx, params) -> types.ListResourcesResult: + return types.ListResourcesResult(resources=[ + types.Resource(uri=uri, name=name, title=title, description=what, mime_type=chart_images.PNG if uri == STATUS_URI else JSON) + for uri, (name, title, what, need) in RESOURCES.items() if self._there(need) and (uri != ALERTS_URI or self.alert_log)]) + + async def _list_templates(self, ctx, params) -> types.ListResourceTemplatesResult: + if self.alert_log is None: + return types.ListResourceTemplatesResult(resource_templates=[]) + return types.ListResourceTemplatesResult(resource_templates=[types.ResourceTemplate( + uri_template=ALERTS_TEMPLATE, name="alerts since", title="Alerts since an id", + description="The alerts after the id `since` (a client's last handled), only those not yet expired unless `expired=true`.", + mime_type=JSON)]) + + async def _read_resource(self, ctx, params: types.ReadResourceRequestParams) -> types.ReadResourceResult: + uri = str(params.uri) + if uri == STATUS_URI and self._there(RESOURCES[STATUS_URI][3]): # the readings as JSON, then the picture + data, png = await self.status() + contents = [types.TextResourceContents(uri=uri, mime_type=JSON, text=_json(data))] + if png is not None: + contents.append(types.BlobResourceContents(uri=uri, mime_type=chart_images.PNG, blob=base64.b64encode(png).decode("ascii"))) + return types.ReadResourceResult(contents=contents) + return types.ReadResourceResult(contents=[types.TextResourceContents(uri=uri, mime_type=JSON, text=_json(await self.read(uri)))]) + + async def read(self, uri: str) -> dict: + """A resource's content (a dict, sent as JSON). Raises MCPError (RESOURCE_NOT_FOUND) for one there is none of.""" + parts = urlsplit(uri) + key = f"{parts.scheme}://{parts.netloc}{parts.path}" + query = parse_qs(parts.query) + if key == ALERTS_URI and self.alert_log is not None: + return self.alerts(query) + entry = RESOURCES.get(key) + if entry is None or parts.query or key == ALERTS_URI or not self._there(entry[3]): + raise MCPError(RESOURCE_NOT_FOUND, f"No resource {uri!r}: there are " + f"{', '.join(u for u, e in RESOURCES.items() if self._there(e[3]))}, and {ALERTS_TEMPLATE}.") + if key == STATUS_URI: + return (await self.status())[0] + return await {STATION_URI: self.station, WEATHER_URI: lambda: self.now(STATION), AIR_URI: lambda: self.now(AIR_DEVICE), + FORECAST_URI: self.forecast, POLLEN_URI: self.pollen, HEALTH_URI: self.health, SCHEMA_URI: self.schema}[key]() + + def alerts(self, query: dict | None = None) -> dict: + """{alerts, last_id, identity}: the alerts after `since` (0), only the unexpired unless `expired` is true.""" + return alerts_read(self.alert_log, query) + + async def station(self) -> dict: + """ecobot://station: what the station is and has (3.4).""" + c, tz = self.ctx, self.ctx.zone + catalogue = c.readings() + about = AboutTool(c) + sensors = {} + for device, there in ((STATION, c.eco), (AIR_DEVICE, c.air)): + if there: + sensors[device] = {"readings": [{"name": r.name, "label": r.label, "unit": r.unit} for r in catalogue if r.device == device]} + sources = {} + if c.eco: + sources["Ecowitt"] = {"mode": c.eco.via, "station": c.eco.station_name} + if c.air: + sources["AirGradient"] = {"mode": "/".join(m for m, on in (("local", c.air.local), ("homeassistant", c.air.ha), + ("cloud", c.air.cloud)) if on) or "none"} + if c.forecast: + sources["Forecast"] = {"mode": "Open-Meteo", "place": c.forecast.place} + if c.pollen: + sources["Pollen"] = {"mode": "Melbourne Pollen", "district": c.pollen.district} + eco = c.eco + return {"name": eco.station_name if eco else None, "time_zone": str(tz), + "latitude": eco.latitude if eco else None, "longitude": eco.longitude if eco else None, + "created": iso(eco.created) if eco and eco.created else None, + "sensors": sensors, "words": catalogue.words(), "sources": sources, "history": await about.history(), + "alerts": alert_kinds(about.sources), + "airgradient_dashboard": c.air.link[1] if c.air and c.air.link else None} + + async def status(self) -> tuple[dict, bytes | None]: + """ecobot://status: (its readings as JSON, the Status picture's PNG or None), lib/status.py.""" + from .status import status + return await status(self.service) + + async def now(self, device: str) -> dict: + """ecobot://now/weather, ecobot://now/air: the device's reading as kept (nothing is fetched for it).""" + part = await CurrentTool(self.ctx).now_of(device, {"fetch": False}) + out = {"as_of": iso(part.at) if part.at else None, "sensors": {}, "lines": part.lines, "heading": part.heading} + for r, entry in part.entries: + out["sensors"].setdefault(r.sensor, {})[r.reading] = entry + if part.unavailable: + out["unavailable"] = part.unavailable + return out + + async def forecast(self) -> dict: + from .forecast.source import describe_day + f = self.ctx.forecast + return {"place": f.place, "fetched_at": iso(f.fetched_at, self.ctx.zone) if f.fetched_at else None, + "days": [{**d, "text": describe_day(d)} for d in (f.days or [])]} + + async def pollen(self) -> dict: + p = self.ctx.pollen + now = p.current() + return {"in_season": p.in_season(), "fetched_at": iso(now["fetched_at"], self.ctx.zone) if now["fetched_at"] else None, + "grass": now["grass"], "asthma": now["asthma"], "lines": p.lines()} + + async def health(self) -> dict: + out = {} + storage = self.ctx.storage + if storage is not None: + path = Path(storage.path) + out["file"] = {"path": str(path), "bytes": os.path.getsize(path) if path.exists() else 0} + if self.alert_log is not None: + out["alert_log"] = {"last_id": self.alert_log.last_id()} + if self.health_of is not None: + out.update(self.health_of()) + return out + + async def schema(self) -> dict: + return json.loads(SCHEMA_PATH.read_text()) + + # ---------- prompts ---------- + async def _list_prompts(self, ctx, params) -> types.ListPromptsResult: + return types.ListPromptsResult(prompts=[types.Prompt(name=name, description=what, arguments=args or None) + for name, (what, args, _) in PROMPTS.items()]) + + async def _get_prompt(self, ctx, params: types.GetPromptRequestParams) -> types.GetPromptResult: + return prompt(params.name, params.arguments) + + # ---------- publishing (3.4) ---------- + def _fingerprint(self, uri: str) -> str | None: + """What a pushed resource's change is told by, from what the sources keep (nothing fetched): the live reading itself (its + values and times), the forecast's days, the pollen page's levels. None while there is none.""" + c = self.ctx + try: + if uri == WEATHER_URI: + kept = getattr(c.eco, "_live", None) + return _json(kept[1]) if kept else None + if uri == AIR_URI: + kept = getattr(c.air, "_current", None) + return _json(kept[0]) if kept else None + if uri == FORECAST_URI: + return _json(c.forecast.days) if c.forecast and c.forecast.days else None + if uri == POLLEN_URI: + return _json({k: v for k, v in c.pollen.current().items() if k != "fetched_at"}) if c.pollen else None + except Exception as e: # (only what is told: never stops the publishing) + log.warning("MCP: couldn't compare %s: %s: %s", uri, type(e).__name__, e) + return None + + async def publish_changes(self) -> list[str]: + """Publish ResourceUpdated for each pushed resource whose content changed since the last look; the URIs published.""" + changed = [] + for uri in PUSHED: + now = self._fingerprint(uri) + if now is not None and now != self._seen.get(uri): + changed.append(uri) + if now is not None: + self._seen[uri] = now + for uri in changed: + await self.bus.publish(ResourceUpdated(uri)) + return changed + + async def watch_alerts(self): + """Publish the alerts' URI on each new alert, until cancelled.""" + if self.alert_log is None: + return + last = self.alert_log.last_id() + while True: + await self.alert_log.wait(last) + last = self.alert_log.last_id() + await self.bus.publish(ResourceUpdated(ALERTS_URI)) + + async def run(self, publish_every: float = PUBLISH_SECONDS, catalogue_every: float = CATALOGUE_SECONDS): + """The publishing, until cancelled: the alerts as they come, the live resources every `publish_every` s, the catalogue every + `catalogue_every` s. A failure is logged and the next round tries again.""" + async def every(seconds: float, fn): + while True: + await asyncio.sleep(seconds) + try: + await fn() + except Exception as e: + log.warning("MCP: %s failed: %s: %s", fn.__name__, type(e).__name__, e) + await asyncio.gather(self.watch_alerts(), every(publish_every, self.publish_changes), every(catalogue_every, self.refresh_catalogue)) + + +def prompt(name: str, arguments: dict | None = None) -> types.GetPromptResult: + """A prompt's question in words, its arguments filled in (their defaults where not sent).""" + if name not in PROMPTS: + raise MCPError(types.INVALID_PARAMS, f"No prompt {name!r}: the prompts are {', '.join(PROMPTS)}.") + what, args, text = PROMPTS[name] + given = {**PROMPT_DEFAULTS.get(name, {}), **{k: str(v).strip() for k, v in (arguments or {}).items() if v is not None and str(v).strip()}} + if missing := [a.name for a in args if a.required and a.name not in given]: + raise MCPError(types.INVALID_PARAMS, f"The prompt {name!r} needs {', '.join(missing)}.") + question = WITHOUT_ARGUMENTS[name] if name in WITHOUT_ARGUMENTS and not given else text.format(**given) + return types.GetPromptResult(description=what, messages=[types.PromptMessage(role="user", content=types.TextContent(text=question))]) + + +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): + """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 + /charts/<id>.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 + 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, + custom_starlette_routes=[*(web.routes() if web else []), Route(f"{CHART_PATH}/{{name}}", server.chart_picture, methods=["GET"])]) + app.state.tokens = check + app.state.closing = web.close if web else None + app.add_middleware(RequestLog, logger=requests_log, hosts_setting="MCP_ALLOWED_HOSTS") # (added last: outermost, so it sees the token's and the Host's refusals too) + return app + + +__all__ = ["ALERTS_TEMPLATE", "ALERTS_URI", "COMPLETE", "EcobotServer", "PROMPTS", "RESOURCES", "TokenCheck", "charts_of", "connection_query", + "host_settings", "http_app", "prompt", "request_base", "tool_entry", "tool_result"] diff --git a/lib/model_tools.py b/lib/model_tools.py new file mode 100644 index 00000000..52adfd4e --- /dev/null +++ b/lib/model_tools.py @@ -0,0 +1,87 @@ +"""The service's ten tools (lib/service) as the bot offers them to its model (docs/ecobot-mcp.md 4): each by its own name, description +and parameters, as they are. The bot draws nothing: over the weather service as the bot reaches it (lib/weather.py, its `call_images`) +each call asks for its charts as images (request `_meta` `chart_image: "png"`, as drawn: `chart_points: "drawn"`), and keeps each +whole result on the question's Turn (`Turn.results`: the charts' full JSON, for the period buttons, and the complete result that ends +the turn; a call that gave no JSON object leaves None) with its pictures (`Turn.pictures`, by the result's place: the bot sends them); +over the service's tools alone (a lib.service.Service: the evals, scripts/show_request.py) the result has no pictures. The model is never sent an image: it is +sent the result less the charts' data (`for_model`): each chart as its title and period, with `caption`, `reply` and `complete` as +they are, and `chart_note` the bot's (BOT_CHART_NOTE: the bot sends the picture with the reply as its caption).""" + +import json + +from .service.common import AS_DRAWN, charts_as_titles +from .tools import Tool, Tools, Turn, json_result + + +BOT_CHART_NOTE = ("The bot sends this chart with your reply as its caption: keep your text to the figures. Don't describe the chart or " + "say it was sent.") + + +def for_model(out: dict) -> dict: + """A result as the model is sent it: `charts` as [{title, period}] (the bot draws them) and `chart_note` saying so (BOT_CHART_NOTE), + everything else as it is.""" + return charts_as_titles(out, BOT_CHART_NOTE) + + +def tool(service_tool, images=None) -> Tool: + """One ServiceTool as the model is offered it: run with the question's metadata, charts as drawn; the whole result kept on the + Turn, the model sent for_model of it. images(name, args, meta) -> (the answer as data, its charts drawn): how the call is made when + its charts are wanted as pictures (lib/weather.py call_images).""" + async def handle(args: dict, turn: Turn) -> str: + slot = len(turn.results) # (taken before the call: the calls of a step run together, and keep the order they were made in) + turn.results.append(None) + meta = {**turn.meta, "chart_points": AS_DRAWN} + if images is not None: + out, pictures = await images(service_tool.name, args, meta) + if not isinstance(out, dict): + return out + else: + text, pictures = await service_tool.call(args, meta), [] + try: + out = json.loads(text) + except ValueError: + return text + if not isinstance(out, dict): + return text + turn.results[slot] = (service_tool.name, args, out) + if pictures: + turn.pictures[slot] = pictures + return json_result(for_model(out)) + return Tool(service_tool.name, service_tool.description, service_tool.parameters, handle) + + +class ServiceTools(Tools): + """The service's tools as the model is offered them, following the service's list: read again whenever it is another list (a remote + service's, read on each connection and when the service says its tools changed; none while it has not been reached).""" + + def __init__(self, service): + self.service = service + self._seen: list[int] | None = None + self._by_name: dict[str, Tool] = {} + self._schemas: list[dict] = [] + + def _current(self): + listed = list(self.service) + if (seen := [id(t) for t in listed]) != self._seen: + images = getattr(self.service, "call_images", None) # (the weather service: the charts come drawn) + wrapped = [tool(t, images) for t in listed] + self._by_name, self._schemas, self._seen = {t.name: t for t in wrapped}, [t.schema() for t in wrapped], seen + + @property + def by_name(self) -> dict[str, Tool]: + self._current() + return self._by_name + + @property + def schemas(self) -> list[dict]: + self._current() + return self._schemas + + +def tools(service) -> Tools: + """The service's tools (the weather service as the bot reaches it, lib/weather.py, whose calls bring their charts drawn; or a + lib.service.Service, or any list of ServiceTools), in its order, as the model is offered them.""" + return ServiceTools(service) + + +__all__ = ["BOT_CHART_NOTE", "ServiceTools", "for_model", "tool", "tools"] diff --git a/lib/partday.py b/lib/partday.py new file mode 100644 index 00000000..597bca38 --- /dev/null +++ b/lib/partday.py @@ -0,0 +1,245 @@ +"""Part of each day (docs/ecobot-mcp.md 3.3): a sensor's figures over one stretch of local time on each day of a period, worked out as a +day row is from a whole day's readings (lib/storage/days.py), so the overnight low, the nights below 5°C or the 3pm temperature can be +found, ranked and counted as days are. + +- **A stretch** is named (night 22:00–06:00, morning 06:00–12:00, afternoon 12:00–18:00, evening 18:00–24:00, daytime 06:00–18:00), two + times on the half hour ("15:00-16:00", "22:30-06:00"), or a moment: one time on the hour or half hour ("15:00", or "15:00-15:05"). + Times are on the half hour because a 30-minute reading's own lowest and highest run to the end of its half hour: part of one would + count as all of it. +- **One window a day**, [start, end) in local wall time, read as start to end - 1 (the SQL's BETWEEN takes in its end). "24:00" is the + next local midnight, so a whole day is 23 or 25 hours on a clock-change day. A stretch that crosses midnight starts the evening before + and belongs to the day it ends on (Monday 22:00 to Tuesday 06:00 is Tuesday's night). A time the clocks skip is the moment they jump, + so a stretch the October change removes (02:00–03:00 on its Sunday) has no time and is left out; a time that happens twice is the + first. +- **Which readings:** each day's window at the first of the day rows' own resolutions that holds all of it (the coverage): the station's + 5-minute, then 30-minute readings; the air sensor's 5-minute, then hourly ones; never the minutes. Held at neither (a day held only as + Ecowitt's daily or 4-hour records, a night whose evening is before the 30-minute archive): left out. Held but with no readings (the + station was off): missing. Nothing falls back to whatever readings there are, as a period's part days do (ecowitt/period.py). +- **A moment** is the 5-minute reading at that time; on a day held only at 30 minutes it is the half hour from it, on the air sensor's + hourly days the hour that holds it, and the note says so. +- **The figures** are the day rows' own SQL over the windows (Reader.part_days, one query for them all): a stretch's mean (of its half + hours'), lowest, highest and when those happened are worked out as a whole day's are, the air sensor's glitches taken out. Except the + rain counters: a day's rain is the highest of its running total, which over a stretch would be the rain since midnight up to its end. + Over a stretch each counter (they all count the one gauge) is the mm that fell in it, the running daily total's rise from the last + reading before the stretch to its last one in it, a fall counted as the midnight reset (lib/rain.rain_slots, as the readings tool + works it out). + +The cost, over a year of 5-minute readings (tests/bench_cache.py): a night of every day takes about 0.2 s for the outdoor sensor, 0.25 s +for the rain gauge and 0.8 s for the air sensor with its glitch rule (30 nights under 0.07 s); a moment 0.05 s; the whole day 0.55, 0.6 +and 2.5 s. The day rows take 0.005 s, so a caller wanting whole days reads those. +""" + +import re +from bisect import bisect_left +from collections import Counter +from dataclasses import dataclass, field +from datetime import date, datetime, time, timedelta, tzinfo + +from .rain import MAX_GAP, rain_slots +from .storage import Sensor +from .storage.catalogue import RAIN_COUNTERS +from .storage.coverage import merge +from .storage.read import Days, Reader +from .timeutil import local_epoch, naive_local + +DAY = 24 * 60 # minutes +MOMENT = 5 # a moment is one 5-minute reading: "15:00" is "15:00-15:05" +NAMED = {"night": (22 * 60, 6 * 60), "morning": (6 * 60, 12 * 60), "afternoon": (12 * 60, 18 * 60), "evening": (18 * 60, DAY), + "daytime": (6 * 60, 18 * 60)} +ALLOWED = ("night (22:00-06:00), morning (06:00-12:00), afternoon (12:00-18:00), evening (18:00-24:00), daytime (06:00-18:00), two times " + "on the half hour ('15:00-16:00', '22:30-06:00'; '24:00' is the midnight that ends the day), or a moment on the hour or half " + "hour ('15:00')") +TIMES = re.compile(r"(\d{1,2}):(\d\d)(?:\s*(?:-|–|—|to)\s*(\d{1,2}):(\d\d))?") +STATION = ("5min", "30min") # what a stretch is read from, finest first, as the day rows are +FROM = {"air": ("5min", "1hour")} # ... where a sensor's day rows differ +SECONDS = {"5min": 300, "30min": 1800, "1hour": 3600} +COARSE = {"30min": ("30-minute averages", "the half hour from it"), "1hour": ("hourly averages", "the hour that holds it")} + +NOT_HELD = "not held finely enough" # why a day is left out: held at neither resolution (daily or 4-hour records only) +CLOCK_CHANGE = "removed by the clock change" +NOT_OVER = "not over yet" + + +def _clock(minutes: int) -> str: + return f"{minutes // 60:02d}:{minutes % 60:02d}" + + +@dataclass(frozen=True) +class Stretch: + """A stretch of each day's local time, in minutes after midnight: an `end` of DAY is the next midnight, and one before the start + crosses midnight (the stretch starts the evening before). One five minutes long is a moment.""" + start: int + end: int + name: str | None = None + + @property + def moment(self) -> bool: + return self.end == self.start + MOMENT + + @property + def overnight(self) -> bool: + return self.end < self.start + + @property + def text(self) -> str: + """The stretch as a result states it: "night (22:00–06:00)", "15:00–16:00", "15:00".""" + times = _clock(self.start) if self.moment else f"{_clock(self.start)}–{_clock(self.end)}" + return f"{self.name} ({times})" if self.name else times + + +def _minutes(hours: str, minutes: str) -> int | None: + """"15:30" as minutes after midnight ("24:00" the next midnight); None for a time that is no time.""" + found = int(hours) * 60 + int(minutes) + return found if int(minutes) < 60 and found <= DAY else None + + +def parse_stretch(text: str) -> Stretch: + """The stretch these words name (ALLOWED says which); ValueError, saying what is allowed, for anything else.""" + words = " ".join(str(text).lower().split()) + if words in NAMED: + return Stretch(*NAMED[words], words) + if found := TIMES.fullmatch(words): + start = _minutes(found[1], found[2]) + end = _minutes(found[3], found[4]) if found[3] else None if start is None else start + MOMENT + end = DAY if end == 0 else end # ("18:00-00:00" runs to midnight) + if (start is not None and end is not None and start < DAY and start % 30 == 0 and end != start + and (end % 30 == 0 or end == start + MOMENT)): + return Stretch(start, end) + raise ValueError(f"{str(text)!r} is not a part of the day I can read: use {ALLOWED}") + + +# ---------- each day's window ---------- +def clock_time(day: date, minutes: int, tz: tzinfo) -> tuple[int, bool]: + """(the epoch at which the clock on `day` first reads this time, in minutes after its midnight (DAY: the next midnight, as day_bounds + has it), and whether it reads it at all): a time the clocks skip is the moment they jump, the first whose clock reads later.""" + local = datetime.combine(day, time()) + timedelta(minutes=minutes) + t = local_epoch(local, tz) # (the first, in the hour that happens twice) + if naive_local(t, tz) == local: + return t, True + early = local_epoch(local.replace(fold=1), tz) # (a skipped time told with the offset after the jump: a moment before it) + while t - early > 1: + middle = (early + t) // 2 + early, t = (early, middle) if naive_local(middle, tz) >= local else (middle, t) + return t, False + + +def window(stretch: Stretch, day: date, tz: tzinfo, res: str = "5min") -> tuple[int, int] | None: + """[start, end) (epochs) of the day's stretch read at this resolution, or None where the clock change removes it. A moment is the + reading that holds it: its 5 minutes, half hour or hour.""" + if stretch.moment: + t, real = clock_time(day, stretch.start, tz) + t -= t % SECONDS[res] + return (t, t + SECONDS[res]) if real else None + start = clock_time(day - timedelta(days=1) if stretch.overnight else day, stretch.start, tz)[0] + end = clock_time(day, stretch.end, tz)[0] + return (start, end) if end > start else None + + +def over(stretch: Stretch, day: date, tz: tzinfo, now: float) -> bool: + """Has the day's stretch ended by `now` (epoch)? A caller counts today once it has: asked at 7am, last night is over.""" + return clock_time(day, stretch.end, tz)[0] <= now + + +def _plan(r: Reader, kind: str, sensor: int, stretch: Stretch, day: date, tz: tzinfo, now: float) -> tuple[str, int, int] | str: + """(the resolution the day's stretch is read at, its start, its end), or why the day is left out.""" + if window(stretch, day, tz) is None: + return CLOCK_CHANGE + for res in FROM.get(kind, STATION): + start, end = window(stretch, day, tz, res) + if end > now: + return NOT_OVER + if r.held(sensor, res, start, end - 1): + return res, start, end + return NOT_HELD + + +# ---------- the figures ---------- +@dataclass +class PartDays: + """A sensor's figures over a stretch of each day of a period (stretch_figures).""" + stretch: Stretch + days: Days = field(default_factory=Days) # the days worked out, oldest first, each as a day row has it: per reading its mean, lowest + # and highest and when those happened, `n`, and in `source` the resolution read + windows: dict[date, tuple[int, int]] = field(default_factory=dict) # each day read: its window, [start, end) epochs + left_out: dict[date, str] = field(default_factory=dict) # the days not read, and why (NOT_HELD, CLOCK_CHANGE, NOT_OVER) + missing: list[date] = field(default_factory=list) # the days held but with no readings (the station was off) + + @property + def note(self) -> str | None: + """What a moment was on the days held too coarsely for its 5-minute reading, else None.""" + coarse = Counter(res for res in self.days.source if res in COARSE) + if not self.stretch.moment or not coarse: + return None + return f"{self.stretch.text} is the 5-minute reading at that time; " + "; ".join( + f"on {n} day{'' if n == 1 else 's'} held only as {COARSE[res][0]}, {COARSE[res][1]}" for res, n in sorted(coarse.items())) + "." + + +def stretch_figures(r: Reader, kind: str, sensor: Sensor | int, first: date, last: date, stretch: Stretch | str, + columns: list[str] | None, tz: tzinfo, now: float) -> PartDays: + """A sensor's figures over the stretch on each day from first to last (a night belongs to the day it ends on), these columns of its + kind (None: all): one query for the figures, and for the rain counters a look at the running total around each stretch. On the + reader's thread (Storage.read). A day whose stretch has not ended by `now` (epoch) is left out.""" + stretch = parse_stretch(stretch) if isinstance(stretch, str) else stretch + sensor = sensor if isinstance(sensor, int) else sensor.id + out, plans = PartDays(stretch), {} + for n in range((last - first).days + 1): + day = first + timedelta(days=n) + plan = _plan(r, kind, sensor, stretch, day, tz, now) + if isinstance(plan, str): + out.left_out[day] = plan + else: + plans[day], out.windows[day] = plan, plan[1:] + got = r.part_days(kind, [(sensor, day, start, end - 1, res) for day, (res, start, end) in plans.items()], columns).get(sensor) + if got is not None: + got.complete = [True] * len(got.day) # (each held whole at the resolution it was read at) + _rain(r, kind, sensor, got, plans) + out.days = got + read = set(out.days.day) + out.missing = [day for day in plans if day not in read] + return out + + +def _rain(r: Reader, kind: str, sensor: int, days: Days, plans: dict[date, tuple[str, int, int]]): + """The rain counters' figures over each stretch: the mm that fell in it, from the running daily total whichever counter it is (in + `hi`, where a day row has the day's total), and when the last of it fell (`hi_ts`; None when none did). A total has no mean or + lowest.""" + counters = [c for c in days.hi if c in RAIN_COUNTERS] + if not counters: + return + spans = merge([(start - MAX_GAP, end - 1) for _, start, end in plans.values()]) # (only what the stretches need: a night is a third) + totals = {} + for res in STATION: # (both: the reading before a stretch may be at the other) + ts, values = [], [] + for start, end in spans: + if got := r.rows(kind, [sensor], res, start, end, ["daily"]).get(sensor): + ts += got.ts + values += got.values["daily"] + totals[res] = ts, values + for i, day in enumerate(days.day): + mm, when = _fell(totals, *plans[day]) + for c in counters: + days.mean[c][i] = days.lo[c][i] = days.lo_ts[c][i] = None + days.hi[c][i], days.hi_ts[c][i] = mm, when + + +def _fell(totals: dict[str, tuple[list[int], list[float]]], res: str, start: int, end: int) -> tuple[float | None, int | None]: + """(the mm that fell in [start, end), when the last of it fell) from the running daily totals read at `res`: its rise from the last + reading before the stretch (at the other resolution where `res` has none close enough) to its last reading in it. None for a stretch + with no totals.""" + ts, values = totals[res] + i, j = bisect_left(ts, start), bisect_left(ts, end) + if i == j: + return None, None + running = dict(zip(ts[i:j], values[i:j])) + for other in (res, *(o for o in totals if o != res)): + before, held = totals[other] + k = bisect_left(before, start) - 1 + if k >= 0 and before[k] >= start - MAX_GAP: + running[before[k]] = held[k] + break + fell = {t: mm for t, mm in rain_slots(running).items() if t >= start} + return round(sum(fell.values()), 3), max((t for t, mm in fell.items() if mm > 0), default=None) + + +__all__ = ["CLOCK_CHANGE", "NAMED", "NOT_HELD", "NOT_OVER", "PartDays", "Stretch", "clock_time", "over", "parse_stretch", + "stretch_figures", "window"] diff --git a/lib/periods.py b/lib/periods.py index 8411a391..f990d105 100644 --- a/lib/periods.py +++ b/lib/periods.py @@ -1,40 +1,119 @@ -"""The period buttons under a chart: 1D, 7D, 1M, 3M and 1Y (1, 7, 30, 90 and 365 days), always all five, the chart's own shaded (the blue of an alert toggle that is on). Pressing one redraws the chart -for that period (Bot.on_period_button); the question behind each chart is remembered for that.""" +"""The period buttons under a chart, and the charts drawn lately. +A chart the service drew carries `drawn_by` (docs/ecobot-mcp.md 3.7): the call that drew it and the periods it is worth drawing over, +each with its label ("7d", "7D"). Its buttons are those periods, the chart's own shaded (the blue of an alert toggle that is on), and +none when it lists none (but a 🔄, "pd:reload", that draws it again when its period runs to now); a button's data is the period +("pd:7d"), never the call, which Telegram's 64 bytes couldn't hold. Pressing one replays the call with that period +(Bot.on_period_button); what drew each chart is remembered for that (Charted). A chart remembered by its question (sent before every +chart carried its drawn_by) answers that it is out of date.""" + +import json import time from collections import OrderedDict from dataclasses import dataclass +from datetime import date, datetime, timedelta, tzinfo -from telegram import InlineKeyboardMarkup - -from . import charts, intent -from telegram.constants import KeyboardButtonStyle -from .buttons import button -NAMES = {1: "1D", 7: "7D", 30: "1M", 90: "3M", 365: "1Y"} # each period, in days, and what its button says -PERIODS = tuple(NAMES) PREFIX = "pd:" -REMEMBERED = 300 # charts whose question is kept, newest first to stay +REMEMBERED = 300 # charts whose call is kept, newest first to stay +WHOLE_DAY_TOOLS = ("days", "relate", "scan") # the tools that read a period as whole days, up to yesterday +REFRESHED = "1d" # the period whose own shaded button draws the chart again with the latest readings (longer ones barely change) +RELOAD = "reload" # the 🔄 under a chart with no periods to offer whose period runs to now: its call replayed as it is ("pd:reload") + + +def period_in(data: str | None) -> str | None: + """The period a button under a service's chart asks for ("pd:7d" -> "7d").""" + return data.removeprefix(PREFIX) if data and data.startswith(PREFIX) and data != PREFIX else None + + +def call_key(tool: str, arguments: dict) -> str: + """A call as the picture cache keys it: the tool and its arguments as canonical JSON (sorted keys).""" + return f"{tool} {json.dumps(arguments, sort_keys=True, ensure_ascii=False, separators=(',', ':'))}" -def keyboard(current: int | None = None) -> InlineKeyboardMarkup: - """The one row of period buttons; the one for the chart's own period (`current`, in days) is shaded.""" - return InlineKeyboardMarkup([[button(NAMES[days], f"{PREFIX}{days}", KeyboardButtonStyle.PRIMARY if days == current else None) - for days in PERIODS]]) +def drawn_key(drawn_by: dict | None) -> str | None: + """The key of the call a chart's drawn_by states.""" + return call_key(drawn_by["tool"], drawn_by["arguments"]) if drawn_by else None -def days_in(data: str | None) -> int | None: - """The period a button's callback data asks for, if it is one of ours.""" - if not data or not data.startswith(PREFIX): +def with_period(drawn_by: dict, period: str) -> dict: + """The arguments of a chart's call with its period swapped for `period` (any start and end taken out).""" + return {**{k: v for k, v in drawn_by["arguments"].items() if k not in ("period", "start", "end")}, "period": period} + + +def own_period(drawn_by: dict, now: datetime, tz: tzinfo) -> str | None: + """Which of the chart's periods it was drawn over (its button is shaded): the one the service reads as the same span as its call's + period; None when none is.""" + from .periods_text import read_period + asked = (drawn_by.get("arguments") or {}).get("period") + if not asked: + return None + whole = drawn_by.get("tool") in WHOLE_DAY_TOOLS + + def span(words: str): + try: + read = read_period(words, None, None, now=now, tz=tz, default=words, whole_days=whole, first_held=now.date()) + except Exception: # (PeriodError, or words only a tool with the file can read) + return None + return read.start, read.end + own = span(asked) + for p in drawn_by.get("periods") or (): + if p["period"] == asked or own is not None and span(p["period"]) == own: + return p["period"] + return None + + +def _span(drawn_by: dict, now: datetime, tz: tzinfo): + """(start, end) of the chart's call's period as the service reads it now; None when it can't be read here.""" + from .periods_text import read_period + args = drawn_by.get("arguments") or {} + period, start, end = args.get("period"), args.get("start"), args.get("end") + if not (period or start): + return None + try: + read = read_period(period or None, start, end, now=now, tz=tz, default=period or "today", + whole_days=drawn_by.get("tool") in WHOLE_DAY_TOOLS, first_held=date(2000, 1, 1)) # (only the end matters) + except Exception: # (PeriodError, or words only a tool with the file can read) return None - days = data.removeprefix(PREFIX) - return int(days) if days.isdigit() and int(days) in PERIODS else None + return read.start, read.end + + +def ends_now(drawn_by: dict | None, now: datetime, tz: tzinfo) -> bool: + """Whether the chart's period runs to the present and moves on with the clock, so drawing it again can show more: to now, or (a + tool of whole days) through yesterday, the last whole day. Fixed dates don't ("October", "2026-11-01 to 2026-11-09", even on the + 10th), nor does "yesterday" on a chart of readings.""" + span = _span(drawn_by, now, tz) if drawn_by else None + later = _span(drawn_by, now + timedelta(days=1), tz) if span else None + if span is None or later is None or later[1] <= span[1]: # fixed dates ("October", "2026-11-01 to 2026-11-09"): never more + return False + + def aware(t: datetime) -> datetime: # (naive: the station's clock) + return t if t.tzinfo else t.replace(tzinfo=tz) + end, now = aware(span[1]), aware(now).astimezone(aware(span[1]).tzinfo) + whole = drawn_by.get("tool") in WHOLE_DAY_TOOLS + return end >= (now.replace(hour=0, minute=0, second=0, microsecond=0) if whole else now - timedelta(minutes=1)) + + +def periods_keyboard(drawn_by: dict, current: str | None = None, now: datetime | None = None, + tz: tzinfo | None = None) -> "InlineKeyboardMarkup | None": + """One button for each period the chart's drawn_by lists, labelled as the service labels it, the chart's own (`current`) shaded. + When it lists none: a 🔄 that draws it again if its period runs to now (ends_now; `now` and `tz` given), else None.""" + from telegram import InlineKeyboardMarkup # (here, not at the top: the service imports this module's call_key, and knows no Telegram) + from telegram.constants import KeyboardButtonStyle + + from .buttons import button + listed = drawn_by.get("periods") or [] + if not listed: + return InlineKeyboardMarkup([[button("🔄", f"{PREFIX}{RELOAD}")]]) if now and tz and ends_now(drawn_by, now, tz) else None + return InlineKeyboardMarkup([[button(p["label"], f"{PREFIX}{p['period']}", KeyboardButtonStyle.PRIMARY if p["period"] == current else None) + for p in listed]]) class Charted: - """{chat_id:message_id -> the question that drew that chart}, the newest REMEMBERED. With a `store` (a dict the alert state saves - to its file) the questions outlive a restart, so a chart's buttons keep working.""" + """{chat_id:message_id -> what drew that chart}, the newest REMEMBERED: {"drawn_by": the service's call, "words": whether its + caption carries the answer's text}, or the question (a string) for a chart whose call the service can't replay. With a `store` (a + dict the alert state saves to its file) they outlive a restart, so a chart's buttons keep working.""" def __init__(self, store: dict | None = None, save=None): self.store = store if store is not None else {} @@ -44,19 +123,25 @@ def __init__(self, store: dict | None = None, save=None): def _key(chat_id: int, message_id: int) -> str: return f"{chat_id}:{message_id}" - def get(self, chat_id: int, message_id: int) -> str | None: + def get(self, chat_id: int, message_id: int) -> str | dict | None: return self.store.get(self._key(chat_id, message_id)) - def remember(self, chat_id: int, message_id: int, question: str): + def remember(self, chat_id: int, message_id: int, record: str | dict): key = self._key(chat_id, message_id) self.store.pop(key, None) # re-added at the end: the newest - self.store[key] = question + self.store[key] = record while len(self.store) > REMEMBERED: del self.store[next(iter(self.store))] if self.save: self.save() +def dark_now() -> bool: + """Are charts drawn dark now (DARKMODE: lib/theme.py, not the renderer: the bot draws nothing)?""" + from . import theme + return theme.dark_now() + + @dataclass class Drawn: """A chart in the ImageCache.""" @@ -64,10 +149,11 @@ class Drawn: png: bytes title: str file_id: str | None = None # Telegram's copy, once the chart has been sent: it is sent again by this, not uploaded - caption: str | None = None # the answer's text (kept in the chat's history), when it was made in code for exactly the key's words + caption: str | None = None # the answer's text (kept in the chat's history), when it was made in code ttl: float = 10 * 60 # how long it is kept (ImageCache.CHART_TTL; PRELOAD_TTL for one uploaded ahead) newest: int | None = None # the time of the newest reading it draws (epoch), when known: an alert about that reading can send it dark: bool = False # drawn in the dark theme: kept only while the charts are (a DARKMODE time range turns at its ends) + drawn_by: dict | None = None # the call that drew it, as the service states it @property def photo(self) -> bytes | str: @@ -75,37 +161,26 @@ def photo(self) -> bytes | str: class ImageCache: - """The charts drawn lately, by question: toggling between the period buttons brings a chart back at once instead of drawing it + """The charts drawn lately, by the call that drew them (call_key: the tool and its arguments), so two wordings of one chart, or two + chats asking for it, share one picture: toggling between the period buttons brings a chart back at once instead of drawing it again, and once it has been sent, as Telegram's copy instead of an upload. A chart is kept CHART_TTL seconds (the readings move - slowly) and the newest CHART_IMAGES stay. A chart drawn in the last FRESH - seconds is the answer to its question (ready).""" + slowly) and the newest CHART_IMAGES stay. A chart made in code in the last FRESH seconds is the answer to its call (ready). One + chart may be kept under several keys (alias): the call a question was read as, and the call the service says drew it.""" CHART_TTL = 10 * 60 CHART_IMAGES = 60 - PRELOAD_TTL = 30 * 60 # a chart uploaded ahead (TELEGRAM_PRELOAD_CHAT) is used for this long, then drawn afresh - FRESH = 330 # a chart made in code this lately answers the same words again as it is (the readings move slowly) + PRELOAD_TTL = 30 * 60 # a chart uploaded ahead (BOT_TELEGRAM_PRELOAD_CHAT) is used for this long, then drawn afresh + FRESH = 330 # a chart made in code this lately answers the same call again as it is (the readings move slowly) def __init__(self, clock=None): self.clock = clock or time.monotonic self.items: OrderedDict = OrderedDict() - @staticmethod - def key(question: str, days: int, now) -> str: - """The question with its period made explicit, so "Temperature chart 30d" and a button's "…30d" are the one chart.""" - return intent.with_period(question, days, now).lower() - - @classmethod - def canonical(cls, question: str, now) -> str | None: - """The key of a question that is its own key, word for word ("Temperature chart 7d", a button's): its chart is the same - whoever asks it. None for any other ("temperature chart today" is kept under the 1d key, but it is another chart).""" - key = cls.key(question, intent.period_days(question, now), now) - return key if key == " ".join(question.split()).lower() else None - def _kept(self, entry: Drawn | None) -> bool: """Is there a chart, still within its time to live, in the theme charts are drawn in now?""" - return entry is not None and self.age(entry) <= entry.ttl and entry.dark == charts.dark_now() + return entry is not None and self.age(entry) <= entry.ttl and entry.dark == dark_now() - def get(self, key: str) -> tuple[bytes | str, str] | None: + def get(self, key: str | None) -> tuple[bytes | str, str] | None: """(the picture: Telegram's file id once it has been sent, else the PNG; its title), or None.""" entry = self.items.get(key) if not self._kept(entry): @@ -114,7 +189,7 @@ def get(self, key: str) -> tuple[bytes | str, str] | None: self.items.move_to_end(key) return entry.photo, entry.title - def age_of(self, key: str) -> float | None: + def age_of(self, key: str | None) -> float | None: """How long ago this chart was drawn, if it is held.""" entry = self.items.get(key) return self.age(entry) if self._kept(entry) else None @@ -124,17 +199,16 @@ def held(self, key: str | None) -> Drawn | None: entry = self.items.get(key) return entry if self._kept(entry) else None - def has_copy(self, key: str) -> bool: + def has_copy(self, key: str | None) -> bool: """Does Telegram hold this chart (drawn lately and already sent, so it has a file id)?""" entry = self.items.get(key) return self._kept(entry) and entry.file_id is not None - def ready(self, question: str, now) -> Drawn | None: - """The chart made in code for exactly these words in the last FRESH seconds (for someone's question, or uploaded ahead to - TELEGRAM_PRELOAD_CHAT), with the text that went with it; None if there is none.""" - key = self.canonical(question, now) + def ready(self, key: str | None) -> Drawn | None: + """The chart made in code for this call in the last FRESH seconds (for someone's question, or uploaded ahead to + BOT_TELEGRAM_PRELOAD_CHAT), with the text that went with it; None if there is none.""" entry = self.items.get(key) if key else None - if entry is None or entry.caption is None or self.age(entry) > self.FRESH or entry.dark != charts.dark_now(): + if entry is None or entry.caption is None or self.age(entry) > self.FRESH or entry.dark != dark_now(): return None self.items.move_to_end(key) return entry @@ -142,11 +216,29 @@ def ready(self, question: str, now) -> Drawn | None: def age(self, entry: Drawn) -> float: return self.clock() - entry.at - def put(self, key: str, png: bytes, title: str, caption: str | None = None, ttl: float | None = None, newest: int | None = None): - """caption: the answer's text, only for a chart made in code for its canonical question (then it can be ready). - newest: the time of the newest reading drawn, when known.""" - self.items[key] = Drawn(self.clock(), png, title, caption=caption, ttl=ttl or self.CHART_TTL, newest=newest, dark=charts.dark_now()) + def put(self, key: str | None, png: bytes, title: str, caption: str | None = None, ttl: float | None = None, newest: int | None = None, + drawn_by: dict | None = None, dark: bool | None = None): + """caption: the answer's text, only for a chart made in code (then it can be ready). newest: the time of the newest reading + drawn, when known. drawn_by: the call that drew it (it is kept under that call's key too). dark: the theme it was drawn in (the + service says which, lib/weather.py); None: the one charts are drawn in now.""" + if key is None: + return + self.items[key] = Drawn(self.clock(), png, title, caption=caption, ttl=ttl or self.CHART_TTL, newest=newest, + dark=dark_now() if dark is None else dark, + drawn_by=drawn_by) self.items.move_to_end(key) + self._trim() + self.alias(key, drawn_key(drawn_by)) + + def alias(self, key: str | None, other: str | None): + """Keep the chart held under `key` under `other` too (one picture, one Telegram copy).""" + if key is None or other is None or key == other or (entry := self.items.get(key)) is None: + return + self.items[other] = entry + self.items.move_to_end(other) + self._trim() + + def _trim(self): while len(self.items) > self.CHART_IMAGES: self.items.popitem(last=False) diff --git a/lib/periods_text.py b/lib/periods_text.py new file mode 100644 index 00000000..af040b4d --- /dev/null +++ b/lib/periods_text.py @@ -0,0 +1,572 @@ +"""Periods in words: the person's own words for a stretch of time ("this week", "3m", "yesterday afternoon"), read by one table in +the station's time zone, so a model never works out a date (docs/ecobot-mcp.md 3.2). Every tool that takes a period reads it here, +and its result begins with how it was read. + + - `period` must be one of the table's forms as a whole phrase, case aside; N is a number in digits or a word up to twelve. There is + no partial match and no falling back to a default: anything else is a PeriodError listing the forms with what each means now. + - Or `start` (and `end`), on the station's clock: 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM'; one with an offset or Z is moved into local + time. An end that is a date includes that day; no end is now. + - Whole-day tools (days, relate, scan) take whole days up to yesterday, because today is still settling. + - A period in the future is an error that points to the forecast. + +Times are worked out as instants (UTC) and handed back on the station's clock, so an hour is a real hour across a clock change and +a day runs midnight to midnight, 23 or 25 hours on the days the clocks change. +""" + +import re +from calendar import monthrange +from dataclasses import dataclass, replace +from datetime import UTC, date, datetime, time, timedelta, tzinfo +from functools import lru_cache + +from .public_holidays import PublicHolidays +from .timeutil import clock_text, day_text + +DAY = timedelta(days=1) +MAX_DAYS = 3650 # ten years: longer than anything held +PARTS = {"morning": (6, 12), "afternoon": (12, 18), "evening": (18, 24)} # the parts of a day, in hours +NIGHT = (22, 6) # a night runs from 22:00 the evening before to 06:00 +FOR_PART_OF_A_DAY = "use summary or readings" +FOR_WHAT_IS_AHEAD = "use forecast" + +NUMBER_WORDS = {w: i for i, w in enumerate("one two three four five six seven eight nine ten eleven twelve".split(), 1)} +WEEKDAY_NAMES = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") +MONTH_NAMES = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") +_WEEKDAYS = {name.lower(): i for i, name in enumerate(WEEKDAY_NAMES)} | { + "mon": 0, "tue": 1, "tues": 1, "wed": 2, "weds": 2, "thu": 3, "thur": 3, "thurs": 3, "fri": 4, "sat": 5, "sun": 6} +_MONTHS = {name.lower(): i for i, name in enumerate(MONTH_NAMES, 1)} | {name[:3].lower(): i for i, name in enumerate(MONTH_NAMES, 1)} | {"sept": 9} +_UNITS = {"minutes": ("min", "mins", "minute", "minutes"), "hours": ("h", "hr", "hrs", "hour", "hours"), "days": ("d", "day", "days"), + "weeks": ("w", "wk", "wks", "week", "weeks"), "months": ("m", "mo", "mos", "month", "months"), # "m" is months, never minutes + "years": ("y", "yr", "yrs", "year", "years")} +_UNIT = {word: unit for unit, words in _UNITS.items() for word in words} + + +def _either(words) -> str: + return "|".join(sorted(words, key=len, reverse=True)) + + +_WD, _MON, _YEAR = _either(_WEEKDAYS), _either(_MONTHS), r"(?:19|20)\d\d" +ON_RECORD = re.compile(r"on record|(?:of )?all[- ]time|ever(?: recorded)?|(?:the )?(?:full|whole|entire|complete|all(?: the)?) (?:history|record|data)") +ROLLING = ( # (words, how they read, days, or hours when it is a number of hours) + (re.compile(r"this week|(?:the )?past week|the last week|week"), "the last 7 days", 7, 0), + (re.compile(r"(?:(?:the )?(?:last|past) )?fortnight"), "the last 14 days", 14, 0), + (re.compile(r"(?:the )?past month|the last month|month"), "the last 30 days", 30, 0), + (re.compile(r"(?:the )?past year|the last year|year"), "the last 365 days", 365, 0), + (re.compile(r"(?:the )?(?:last|past) day"), "the last 24 hours", 0, 24), + (re.compile(r"(?:the )?(?:last|past) hour"), "the last hour", 0, 1), +) +NUMBERED = re.compile(rf"(?:(?:the )?(?:last|past) )?(?P<n>\d+|{_either(NUMBER_WORDS)}) ?(?P<unit>{_either(_UNIT)})") +YEAR = re.compile(rf"(?P<y>{_YEAR})") +MONTH = re.compile(rf"(?P<mon>{_MON})\.?(?:,? (?P<y>{_YEAR}))?") +DAYS = ( # "2026-09-05", "Sat 5 Sep", "5th of September 2025", "September 5, 2025" + re.compile(rf"(?P<y>{_YEAR})-(?P<m>\d\d)-(?P<d>\d\d)"), + re.compile(rf"(?:(?P<wd>{_WD}),? )?(?:the )?(?P<d>\d{{1,2}})(?:st|nd|rd|th)?(?: of)? (?P<mon>{_MON})\.?(?:,? (?P<y>{_YEAR}))?"), + re.compile(rf"(?:(?P<wd>{_WD}),? )?(?P<mon>{_MON})\.? (?:the )?(?P<d>\d{{1,2}})(?:st|nd|rd|th)?(?:,? (?P<y>{_YEAR}))?"), +) +BARE_DAY = re.compile(rf"(?:(?P<wd>{_WD}),? )?(?:the )?(?P<d>\d{{1,2}})(?:st|nd|rd|th)?") # the "5" of "5 to 10 Sep" +WEEKDAY = re.compile(rf"(?:last )?(?P<wd>{_WD})") +PART = re.compile(rf"(?P<day>this|yesterday|(?:last )?(?P<wd>{_WD})) (?P<part>morning|afternoon|evening)") +NIGHT_OF = re.compile(rf"(?:last )?(?P<wd>{_WD}) night") +SINCE = re.compile(r"since (?P<what>.+)") +CLOCK = re.compile(r"(?P<h>\d{1,2})(?:[:.](?P<mi>\d\d))? ?(?P<ap>am|pm|a\.m\.|p\.m\.)|(?P<h24>\d{1,2}):(?P<mi24>\d\d)|noon|midday|midnight") +RANGE_SEP = re.compile(r" (?:to|until|till|through|thru) | ?– ?| - ") +LEAD = re.compile(r"(?:in|over|during|for|within|across|throughout|on) (?P<rest>.+)") # "in the last year", "over the past week" +FUTURE = re.compile(r"(?:the )?(?:day after )?tomorrow(?: .+)?|(?:the |this )?(?:next|coming|upcoming|following) .+|later(?: today| on)?") +HOLIDAY_ALIASES = {"cup day": "melbourne cup day", "grand final friday": "friday before the afl grand final", "easter": "easter sunday", + "new year": "new years day"} + +# The forms a PeriodError lists, each with an example read at the time asked; `timed` ones are left out for whole-day tools +FORMS = ( # (form, example, timed) + ("today", "today", True), + ("yesterday", "yesterday", False), + ("last N minutes, N min", "last 30 minutes", True), + ("last N hours, Nh, last 24 hours, 1d, last day", "last 24 hours", True), + ("last N days, Nd (N from 2)", "last 7 days", False), + ("this week, past week, the last week, week, 1w", "this week", False), + ("last N weeks, Nw, fortnight", "last 2 weeks", False), + ("past month, the last month, month, 1m, last 30 days", "past month", False), + ("last N months, Nm, N mo (m is months, never minutes)", "3m", False), + ("past year, the last year, year, 1y, last 12 months", "past year", False), + ("last N years, Ny", "2y", False), + ("week to date, since Monday", "week to date", False), + ("last week (the previous Monday to Sunday)", "last week", False), + ("this month", "this month", False), + ("last month", "last month", False), + ("this year", "this year", False), + ("last year", "last year", False), + ("a year, such as 2025", "{last_year}", False), + ("a month, such as October 2025, or October (the latest that has begun)", "October", False), + ("A to B, between A and B, such as June to August 2026", "June to August", False), + ("a day, such as 2026-09-05, 5 Sep, 5 September 2025, Sat 5 Sep (with no year, the latest not after today)", "5 Sep", False), + ("Monday … Sunday, last Saturday (the latest before today)", "Saturday", False), + ("a public holiday by name, with or without a year, such as Christmas Day or Melbourne Cup", "Christmas Day", False), + ("this morning, yesterday afternoon, Tuesday evening (06:00-12:00, 12:00-18:00, 18:00-24:00)", "yesterday afternoon", True), + ("last night, Tuesday night, overnight (22:00 the evening before to 06:00)", "last night", True), + ("since 6am, since Monday", "since 6am", True), + ("on record, all time, ever (from the first reading held)", "on record", False), +) + + +@dataclass(frozen=True) +class Period: + """A period as read: the words asked (or "start/end"), its start and end on the station's clock (the end not included), how it + was read, ready to pass on, and, when a whole-day tool cut it to yesterday, a note saying so. `note`: anything else the reader of the + result should know about how the call's period was taken (lib/service/common.read_period: `start` and `end` ignored beside `period`).""" + asked: str + start: datetime + end: datetime + text: str + cut: str | None = None + note: str | None = None + + @property + def first_day(self) -> date: + return self.start.date() + + @property + def last_day(self) -> date: + """The day of its last moment: the day before an end at midnight.""" + return (self.end - timedelta(microseconds=1)).date() + + def as_naive_strings(self) -> tuple[str, str]: + """Start and end as today's tools take them: 'YYYY-MM-DD HH:MM:SS' on the station's clock, the end its last second.""" + return f"{self.start:%Y-%m-%d %H:%M:%S}", f"{self.end - timedelta(seconds=1):%Y-%m-%d %H:%M:%S}" + + +class PeriodError(ValueError): + """A period that can't be read, saying what to send instead. When the words aren't a form at all, `forms` holds each form with + what it means now, so the error also tells a model today's date.""" + + def __init__(self, message: str, forms: tuple[tuple[str, str], ...] = ()): + super().__init__(message + "".join(f"\n- {form} → {means}" for form, means in forms)) + self.message, self.forms = message, forms + + +class _NotAForm(Exception): + """Words that match no form (read_period lists the forms).""" + + +@dataclass(frozen=True) +class _Read: + """Words read, before the cut to now and to whole days: kind is "calendar" (named days, cut at yesterday by a whole-day tool), + "days" (the last `days` days), "hours" (a length of real time, `days` its whole days) or "time" (part of a day).""" + label: str | None + start: datetime + end: datetime + kind: str + days: int = 0 + + +@dataclass(frozen=True) +class _Clock: + """The time asked, as an instant and on the station's clock.""" + at: datetime + local: datetime + tz: tzinfo + + @classmethod + def of(cls, now: datetime, tz: tzinfo) -> "_Clock": + local = now.astimezone(tz) if now.tzinfo else now.replace(tzinfo=tz) + return cls(local.astimezone(UTC), local, tz) + + @property + def today(self) -> date: + return self.local.date() + + def wall(self, day: date, at: time = time(), fold: int = 0) -> datetime: + """The instant the station's clock shows `at` on `day`. In the hour the clocks go back, `fold` picks the first (0) or the + second (1); a time the clocks skip is read as the moment they jump.""" + local = datetime.combine(day, at, tzinfo=self.tz).replace(fold=fold) + instant = local.astimezone(UTC) + if instant.astimezone(self.tz).replace(tzinfo=None) == local.replace(tzinfo=None): + return instant + instant = min(local.replace(fold=0).astimezone(UTC), local.replace(fold=1).astimezone(UTC)) + while instant.astimezone(self.tz).replace(tzinfo=None) < local.replace(tzinfo=None): + instant += timedelta(minutes=1) + return instant + + def midnight(self, day: date) -> datetime: + return self.wall(day) + + def error(self, message: str, forms: tuple[tuple[str, str], ...] = ()) -> PeriodError: + return PeriodError(f"{message} It is now {day_text(self.local)} {clock_text(self.local)}.", forms) + + +def read_period(period: str | None, start: str | None, end: str | None, *, now: datetime, tz: tzinfo, default: str, + whole_days: bool = False, first_held: date | datetime | None = None) -> Period: + """The period a tool was asked for: `period` in words, or `start` (and `end`), or else `default` (words). `now` is the time asked + (aware; naive is taken as the station's clock), `first_held` the first reading held for the readings asked about ("on record"). + whole_days: the tool works on whole days, up to yesterday. PeriodError says what to send instead.""" + clock = _Clock.of(now, tz) + try: + return _read(period, start, end, clock, default, whole_days, first_held)[0] + except _NotAForm as e: + dates = "as dates ('YYYY-MM-DD'): this tool takes whole days, up to yesterday" if whole_days else \ + "('YYYY-MM-DD' or 'YYYY-MM-DD HH:MM', the station's local time)" + raise clock.error(f"{e.args[0]!r} isn't a period this tool can read. Send `period` as one of these forms, as a whole phrase " + f"(N is a number, in digits or a word up to twelve), or send `start` and `end` {dates}.", + _forms(clock, whole_days, first_held)) from None + + +def _read(period, start, end, clock: _Clock, default: str, whole_days: bool, first_held) -> tuple[Period, str | None]: + """The Period and the label it was read as (None for plain dates).""" + period, start, end = (str(x).strip() if x is not None and str(x).strip() else None for x in (period, start, end)) + if period and (start or end): + raise clock.error(f"Send `period` or `start` (with `end`), not both: `period` {period!r}, `start` {start!r}, `end` {end!r}.") + if end and not start: + raise clock.error(f"`end` {end!r} needs a `start`: send `start` too, or a `period` instead.") + if start: + asked, what, read = "start/end", f"`start` {start!r}", _dates(start, end, clock, whole_days) + else: + asked = period or default + what, read = repr(asked), _words(asked, clock, first_held) + if read.start > clock.at: + raise clock.error(f"{what} is in the future ({_text(read, clock)}). This tool reads what has been measured: for what's ahead, " + f"{FOR_WHAT_IS_AHEAD}.") + read = replace(read, end=min(read.end, clock.at)) + cut = None + if whole_days: + read, cut = _whole_days(read, what, clock) + return Period(asked, read.start.astimezone(clock.tz), read.end.astimezone(clock.tz), _text(read, clock), cut), read.label + + +def _whole_days(read: _Read, what: str, clock: _Clock) -> tuple[_Read, str | None]: + """The period in whole days up to yesterday, and the note when today was cut from it.""" + today, yesterday = clock.midnight(clock.today), clock.today - DAY + cut = f"to {day_text(yesterday, year=False)}: today isn't over" + if read.kind == "time": + raise clock.error(f"{what} is part of a day: this tool takes whole days, up to yesterday ({day_text(yesterday)}). For part of a " + f"day, {FOR_PART_OF_A_DAY}.") + nothing = clock.error(f"{what} leaves no whole day: this tool takes whole days up to yesterday ({day_text(yesterday)}), as today " + f"isn't over. For today or part of a day, {FOR_PART_OF_A_DAY}.") + if read.kind in ("days", "hours"): + if not read.days: + raise nothing + label = read.label if read.kind == "days" else "the last day" if read.days == 1 else f"the last {read.days} days" + return _Read(label, clock.midnight(clock.today - read.days * DAY), today, "days", read.days), cut + if read.end <= today: + return read, None + if read.start >= today: + raise nothing + return replace(read, end=today), cut + + +# ---------- start and end ---------- +def _dates(start: str, end: str | None, clock: _Clock, whole_days: bool) -> _Read: + first, _ = _moment("start", start, clock, whole_days) + if end is None: + return _Read(None, first, clock.at, "calendar") + last, is_date = _moment("end", end, clock, whole_days) + if is_date: # a date includes that whole day + last = clock.midnight(last.astimezone(clock.tz).date() + DAY) + if first >= last: + raise clock.error(f"`start` {start!r} must be before `end` {end!r}.") + return _Read(None, first, last, "calendar") + + +def _moment(name: str, text: str, clock: _Clock, whole_days: bool) -> tuple[datetime, bool]: + """A start or end as an instant, and whether it was a date alone.""" + try: + dt = datetime.fromisoformat(text) + except ValueError: + raise clock.error(f"`{name}` {text!r} isn't a date or time: send 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM', the station's local " + f"time.") from None + is_date = bool(re.fullmatch(r"\d{4}-\d\d-\d\d", text)) + if whole_days and not is_date: + raise clock.error(f"`{name}` {text!r} has a time: this tool takes whole days ('YYYY-MM-DD'), up to yesterday " + f"({day_text(clock.today - DAY)}). For part of a day, {FOR_PART_OF_A_DAY}.") + return (dt.astimezone(UTC) if dt.tzinfo else clock.wall(dt.date(), dt.time())), is_date + + +# ---------- words ---------- +def _words(asked: str, clock: _Clock, first_held) -> _Read: + p = " ".join(asked.replace("’", "'").replace("—", "–").lower().split()) + lead = LEAD.fullmatch(p) + read = _phrase(p, clock, first_held) or (lead and _phrase(lead["rest"], clock, first_held)) + if read: + return read + if FUTURE.fullmatch(p) or (lead and FUTURE.fullmatch(lead["rest"])): + raise clock.error(f"{asked!r} is in the future. This tool reads what has been measured: for what's ahead, {FOR_WHAT_IS_AHEAD}.") + raise _NotAForm(asked) + + +def _phrase(p: str, clock: _Clock, first_held) -> _Read | None: + """The words as one of the forms, or None.""" + if ON_RECORD.fullmatch(p): + return _on_record(clock, first_held) + for words, label, days, hours in ROLLING: + if words.fullmatch(p): + return _last_days(label, days, clock) if days else _last_time(label, timedelta(hours=hours), clock) + if m := NUMBERED.fullmatch(p): + return _numbered(p, m, clock) + if p in ("last night", "overnight"): + return _night("last night", clock.today, clock) + if m := NIGHT_OF.fullmatch(p): + wd = _WEEKDAYS[m["wd"]] + return _night(f"{WEEKDAY_NAMES[wd]} night", _latest_weekday(wd, clock.today, strict=True), clock) + if m := PART.fullmatch(p): + return _part(m, clock) + if m := SINCE.fullmatch(p): + return _since(m["what"], clock) + if read := _range(p, clock): + return read + return _calendar(p, clock, clock.today, strict=True) + + +def _on_record(clock: _Clock, first_held) -> _Read: + if first_held is None: + raise clock.error("Nothing is held yet for these readings, so 'on record' has no start.") + if isinstance(first_held, datetime): + first_held = (first_held.astimezone(clock.tz) if first_held.tzinfo else first_held).date() + return _Read("on record", clock.midnight(first_held), clock.at, "calendar") + + +def _last_days(label: str, days: int, clock: _Clock) -> _Read: + """Today and the days-1 whole days before it, to now.""" + return _Read(label, clock.midnight(clock.today - (days - 1) * DAY), clock.at, "days", days) + + +def _last_time(label: str, length: timedelta, clock: _Clock) -> _Read: + """The last `length` of real time, to now.""" + return _Read(label, clock.at - length, clock.at, "hours", length // DAY) + + +def _numbered(p: str, m: re.Match, clock: _Clock) -> _Read | None: + """"last 7 days", "3m", "past two years", "45 min": a rolling period to now. One day is the last 24 hours; a month is + round(N×365/12) days, a year 365.""" + if len(m["n"]) > 6 or not (n := int(m["n"]) if m["n"].isdigit() else NUMBER_WORDS[m["n"]]): + return None + unit = _UNIT[m["unit"]] + if unit in ("minutes", "hours") or (unit == "days" and n == 1): + length = timedelta(minutes=n) if unit == "minutes" else timedelta(hours=24 if unit == "days" else n) + if length > MAX_DAYS * DAY: + raise clock.error(f"{p!r} is longer than ten years, more than anything held: for all of it, send 'on record'.") + hours = length // timedelta(hours=1) + label = (f"the last {n} minutes" if n > 1 else "the last minute") if unit == "minutes" else \ + f"the last {hours} hours" if hours > 1 else "the last hour" + return _last_time(label, length, clock) + days = {"days": n, "weeks": 7 * n, "months": round(n * 365 / 12), "years": 365 * n}[unit] + if days > MAX_DAYS: + raise clock.error(f"{p!r} is longer than ten years, more than anything held: for all of it, send 'on record'.") + return _last_days(f"the last {days} days" if n == 1 or unit == "days" else f"the last {n} {unit}", days, clock) + + +def _night(label: str, day: date, clock: _Clock) -> _Read: + """The night that ends on `day`: 22:00 the evening before to 06:00.""" + return _Read(label, clock.wall(day - DAY, time(NIGHT[0])), clock.wall(day, time(NIGHT[1])), "time") + + +def _part(m: re.Match, clock: _Clock) -> _Read: + """"this morning", "yesterday afternoon", "Tuesday evening" (the latest Tuesday before today).""" + if m["wd"]: + wd = _WEEKDAYS[m["wd"]] + day, said = _latest_weekday(wd, clock.today, strict=True), WEEKDAY_NAMES[wd] + else: + day, said = (clock.today, "this") if m["day"] == "this" else (clock.today - DAY, "yesterday") + first, last = PARTS[m["part"]] + end = clock.midnight(day + DAY) if last == 24 else clock.wall(day, time(last)) + return _Read(f"{said} {m['part']}", clock.wall(day, time(first)), end, "time") + + +def _since(what: str, clock: _Clock) -> _Read | None: + """"since 6am": from the latest such time; "since Monday", "since 5 Sep": from that day's 00:00 (a weekday may be today).""" + if (m := CLOCK.fullmatch(what)) and (at := _time_of_day(m)) is not None: + days = (clock.today, clock.today - DAY) + start = max(t for t in (clock.wall(d, at, fold) for d in days for fold in (0, 1)) if t <= clock.at) + said = "midnight" if at == time() else "noon" if at == time(12) else clock_text(datetime.combine(clock.today, at), whole_hours=True) + return _Read(f"since {said}", start, clock.at, "time") + if anchor := _calendar(what, clock, clock.today, strict=False): + return _Read(f"since {anchor.label}" if anchor.label else None, anchor.start, clock.at, "calendar") + return None + + +def _time_of_day(m: re.Match) -> time | None: + if m[0] in ("noon", "midday", "midnight"): + return time(12) if m[0] != "midnight" else time() + hour, minute = int(m["h"] or m["h24"]), int(m["mi"] or m["mi24"] or 0) + if m["ap"]: + if not 1 <= hour <= 12: + return None + hour = hour % 12 + (12 if m["ap"][0] == "p" else 0) + return time(hour, minute) if hour < 24 and minute < 60 else None + + +def _range(p: str, clock: _Clock) -> _Read | None: + """"A to B", "between A and B", "from A until B": the start of A to the end of B. B is read as it would be alone; A, when it + names no year (or is a weekday), is the latest not after B, so "December to February" is the summer just gone.""" + between = p.startswith("between ") + body = p.removeprefix("between ") if between else p.removeprefix("from ") + for sep in re.finditer(" and " if between else RANGE_SEP, body): + a, b = body[:sep.start()], body[sep.end():] + last = _Read("now", clock.at, clock.at, "calendar") if b == "now" else _calendar(b, clock, clock.today, strict=True) + if last is None: + continue + b_day = last.start.astimezone(clock.tz).date() + if BARE_DAY.fullmatch(a) and any(d.fullmatch(b) for d in DAYS): # "5 to 10 Sep": the 5th of B's month + a = f"{a} {MONTH_NAMES[b_day.month - 1].lower()} {b_day.year}" + if (first := _calendar(a, clock, b_day, strict=False)) is None: + continue + if first.start >= last.end: + raise clock.error(f"{p!r} starts after it ends.") + return _Read(f"{first.label} to {last.label}" if first.label and last.label else None, first.start, last.end, "calendar") + return None + + +def _calendar(p: str, clock: _Clock, ref: date, strict: bool) -> _Read | None: + """A stretch of whole days with a name: today, yesterday, last week, this or last month or year, a year, a month, a day, a + weekday, a public holiday. A month, day or holiday with no year is the latest not after `ref`; a weekday the latest before it + (strict) or not after it.""" + if named := _named(p, clock.today): + label, first, end = named + return _Read(label, clock.midnight(first), clock.midnight(end), "calendar") + if m := YEAR.fullmatch(p): + year = int(m["y"]) + return _Read(m["y"], clock.midnight(date(year, 1, 1)), clock.midnight(date(year + 1, 1, 1)), "calendar") + if m := MONTH.fullmatch(p): + month = _MONTHS[m["mon"]] + year = int(m["y"]) if m["y"] else ref.year if month <= ref.month else ref.year - 1 + first = date(year, month, 1) + end = date(year + month // 12, month % 12 + 1, 1) + return _Read(f"{MONTH_NAMES[month - 1]} {year}", clock.midnight(first), clock.midnight(end), "calendar") + for pattern in DAYS: + if m := pattern.fullmatch(p): + return _one_day(None, _day(m, ref, clock), clock) + if m := WEEKDAY.fullmatch(p): + wd = _WEEKDAYS[m["wd"]] + return _one_day(WEEKDAY_NAMES[wd], _latest_weekday(wd, ref, strict), clock) + if holiday := _holiday(p, ref, clock): + return _one_day(*holiday, clock) + return None + + +def _named(p: str, today: date) -> tuple[str, date, date] | None: + """The calendar's named stretches as (label, first day, the day after the last).""" + monday, month = today - timedelta(days=today.weekday()), today.replace(day=1) + previous = (month - DAY).replace(day=1) + following = (month + 31 * DAY).replace(day=1) + return {"today": ("today", today, today + DAY), "so far today": ("today", today, today + DAY), + "yesterday": ("yesterday", today - DAY, today), + "week to date": ("week to date", monday, today + DAY), + "last week": ("last week", monday - 7 * DAY, monday), + "this month": ("this month", month, following), "last month": ("last month", previous, month), + "this year": ("this year", date(today.year, 1, 1), date(today.year + 1, 1, 1)), + "last year": ("last year", date(today.year - 1, 1, 1), date(today.year, 1, 1))}.get(p) + + +def _one_day(label: str | None, day: date, clock: _Clock) -> _Read: + return _Read(label, clock.midnight(day), clock.midnight(day + DAY), "calendar") + + +def _day(m: re.Match, ref: date, clock: _Clock) -> date: + """The day a date names: with no year, the latest not after `ref`. A weekday that doesn't match it is an error.""" + g = m.groupdict() # (the ISO form has no weekday or month name) + month, day = int(g["m"]) if g.get("m") else _MONTHS[g["mon"]], int(g["d"]) + if not 1 <= month <= 12 or not 1 <= day <= monthrange(2000, month)[1]: # (2000: a leap year, so 29 Feb is a date) + raise clock.error(f"{m[0]!r} isn't a date.") + if g["y"]: + try: + found = date(int(g["y"]), month, day) + except ValueError: + raise clock.error(f"{day} {MONTH_NAMES[month - 1]} {g['y']} isn't a date.") from None + else: + found = next(d for year in range(ref.year, ref.year - 9, -1) if (d := _date_or_none(year, month, day)) and d <= ref) + if g.get("wd") and (wanted := _WEEKDAYS[g["wd"]]) != found.weekday(): + raise clock.error(f"{found.day} {found:%B %Y} is a {found:%A}, not a {WEEKDAY_NAMES[wanted]}: send '{day_text(found)}', " + f"or the date alone.") + return found + + +def _date_or_none(year: int, month: int, day: int) -> date | None: + try: + return date(year, month, day) + except ValueError: # 29 Feb in a year that has none + return None + + +def _latest_weekday(wd: int, ref: date, strict: bool) -> date: + """The latest such weekday not after `ref`, or before it if strict.""" + back = (ref.weekday() - wd) % 7 + return ref - timedelta(days=back or (7 if strict else 0)) + + +# ---------- public holidays ---------- +def _holiday(p: str, ref: date, clock: _Clock) -> tuple[str, date] | None: + """A public holiday by name, from the station's holiday calendar ("Christmas Day", "Melbourne Cup 2025"): (its name, its day), + with no year the latest not after `ref`.""" + m = re.fullmatch(rf"(?:the )?(?P<name>.+?)(?: (?P<y>{_YEAR}))?", p) + key = _holiday_key(m["name"]) + key = HOLIDAY_ALIASES.get(key, key) + years = (int(m["y"]),) if m["y"] else (ref.year, ref.year - 1) + found = [(day, name) for year in years for day, name in _holidays(clock.tz, year).get(key, ()) if m["y"] or day <= ref] + return max(found, key=lambda found: found[0])[::-1] if found else None + + +def _holiday_key(name: str) -> str: + return " ".join(name.lower().replace("'", "").replace("’", "").split()) + + +@lru_cache(maxsize=None) +def _holidays(tz: tzinfo, year: int) -> dict[str, tuple[tuple[date, str], ...]]: + """The year's public holidays by the words that name them: the name, and the name without "Day" ("Christmas", "Melbourne Cup").""" + calendar, found = PublicHolidays(tz), {} + day = date(year, 1, 1) + while calendar.available and day.year == year: + for name in (calendar.name(day) or "").split("; "): + if name and "observed" not in name.lower(): + key = _holiday_key(name) + for words in {key, key.removesuffix(" day")}: + found[words] = found.get(words, ()) + ((day, name),) + day += DAY + return found + + +# ---------- in words ---------- +def _text(read: _Read, clock: _Clock) -> str: + """How the period was read: "the last 7 days: Wed 4 – Tue 10 Nov 2026"; plain dates without the label. Days run from midnight + to midnight, the last of them today for a period to now; a length of time or part of a day shows its times.""" + start, end = read.start.astimezone(clock.tz), read.end.astimezone(clock.tz) + as_days = read.kind in ("calendar", "days") and start.time() == time() and (end.time() == time() or read.end == clock.at) + span = _days_text(start.date(), max(start.date(), end.date() - DAY if end.time() == time() else end.date())) if as_days \ + else _times_text(start, end) + return f"{read.label}: {span}" if read.label else span + + +def _times_text(start: datetime, end: datetime) -> str: + """"Tue 10 Nov 2026 6am – 12pm", "Tue 3 Nov 2026 6pm – midnight", "Mon 9 Nov 10pm – Tue 10 Nov 2026 6am".""" + midnight = time() + if start.date() == end.date(): + return f"{day_text(start)} {_clock(start)} – {_clock(end)}" + if end.time() == midnight and end.date() == start.date() + DAY: + return f"{day_text(start)} {_clock(start)} – midnight" + return f"{day_text(start, year=start.year != end.year)} {_clock(start)} – {day_text(end)} {_clock(end)}" + + +def _days_text(first: date, last: date) -> str: + """"Tue 10 Nov 2026", "Wed 4 – Tue 10 Nov 2026", "Wed 12 Aug – Tue 10 Nov 2026", "Mon 10 Nov 2025 – Tue 10 Nov 2026".""" + if first == last: + return day_text(first) + if (first.year, first.month) == (last.year, last.month): + return f"{first:%a} {first.day} – {day_text(last)}" + return f"{day_text(first, year=first.year != last.year)} – {day_text(last)}" + + +def _clock(t: datetime) -> str: + return clock_text(t, whole_hours=True) + + +def _forms(clock: _Clock, whole_days: bool, first_held) -> tuple[tuple[str, str], ...]: + """Each form with what its example means now (a whole-day tool's leaves out the ones it refuses).""" + forms = [] + for form, example, timed in FORMS: + if whole_days and timed: + continue + example = example.format(last_year=clock.today.year - 1) + if example == "on record" and first_held is None: + forms.append((form, "from the first reading held, for the readings asked about, to now")) + continue + try: + period, label = _read(example, None, None, clock, example, whole_days, first_held) + except (PeriodError, _NotAForm): # (no holiday calendar here, or not on this day: "this month" on the 1st, for whole days) + continue + forms.append((form, period.text if label else f"{example}: {period.text}")) + return tuple(forms) diff --git a/lib/pollen/source.py b/lib/pollen/source.py index fa71983f..ccde9b22 100644 --- a/lib/pollen/source.py +++ b/lib/pollen/source.py @@ -11,12 +11,10 @@ import httpx -from .. import intent from ..config import Config from ..snapshots import Snapshots from ..sources import Source -from ..timeutil import day_text, local_date, when -from ..tools import Tool, Turn, json_result +from ..timeutil import day_text, local_date from ..warm import Warmer, in_sync_hours from .parse import DISTRICTS, LEVEL_EMOJI, parse_melbourne_pollen @@ -28,17 +26,12 @@ SEASON_MONTHS = (10, 11, 12) # grass pollen and the thunderstorm asthma forecast run October to December: nothing else is fetched, shown or alerted OFF_SEASON = "Pollen and thunderstorm asthma forecasts only run from October to December." -DESCRIPTION = ("Melbourne's grass pollen level today and the thunderstorm asthma risk (Low, Moderate, High or Extreme), from " - "melbournepollen.com.au. Use it for pollen, hay fever and thunderstorm asthma questions. Takes no arguments. " - "The result's \"lines\" are ready-made, emoji included: copy them as they are.") -PARAMETERS = {"type": "object", "properties": {}} - def _district(name: str) -> str: """The site's name for this district, whatever its case. One the site doesn't have is warned about: no level can be found for it.""" known = {d.lower(): d for d in DISTRICTS} if name.lower() not in known: - log.warning("POLLEN_DISTRICT %r is not one of the site's districts (%s): no district level will be found", name, + log.warning("MCP_POLLEN_DISTRICT %r is not one of the site's districts (%s): no district level will be found", name, ", ".join(sorted(DISTRICTS))) return known.get(name.lower(), name) @@ -56,7 +49,6 @@ def __init__(self, cfg: Config, transport=None): self.store = Snapshots(cfg.storage_path) self._load() self.warmer = Warmer(self.warm, POLLEN_REFRESH_SECONDS) - self.tools = [Tool("pollen_asthma", DESCRIPTION, PARAMETERS, self.handle)] async def start(self): if not self.in_season(): @@ -68,13 +60,6 @@ async def start(self): except Exception as e: # the site may just be briefly unreachable log.warning("Pollen not readable yet: %s", e) - def describe(self) -> str: - return "Melbourne pollen forecast and thunderstorm asthma risk (melbournepollen.com.au) (people say \"pollen\" or \"hay fever\")" - - def wants(self, text: str) -> bool: - """Only pollen questions start a refresh; the report always uses what is cached.""" - return intent.mentions_pollen(text) - # ---------- kept on disk ---------- def _load(self): """Start from the last page seen (before the restart), so a night-time start needs no fetch.""" @@ -146,25 +131,3 @@ def lines(self) -> list[str]: if a := cur["asthma"]: out.append(f"Thunderstorm asthma forecast: {a['emoji']} {a['level']}") return out - - async def handle(self, args: dict, turn: Turn | None = None) -> str: - if not self.in_season(): - return json_result({"error": OFF_SEASON}) - if self.page is None and not args.get("cached"): # the report ("cached") never fetches - try: - await self.warm(True) - except Exception as e: - log.warning("Pollen not readable: %s", e) - lines = self.lines() - if not lines: - return json_result({"error": "No pollen levels are available right now."}) - cur = self.current() - out = {"lines": lines, "place": self.place, "source": "melbournepollen.com.au (grass pollen from pollen-trap data; asthma risk from the " - "Victorian Department of Health and BOM, 1 Oct - 31 Dec)"} - if cur["fetched_at"]: - out["time"] = when(int(cur["fetched_at"]), self.tz) # when the page was last fetched - if cur["asthma"] and cur["asthma"]["updated"]: - out["asthma_updated"] = cur["asthma"]["updated"] - if not cur["asthma"]: # in season the page always has one: it may have changed - out["asthma_note"] = "The page had no thunderstorm asthma level for this district when it was last read." - return json_result(out) diff --git a/lib/prompt.py b/lib/prompt.py index 7f7628a2..6b599912 100644 --- a/lib/prompt.py +++ b/lib/prompt.py @@ -1,242 +1,40 @@ -"""The system prompt. Everything the model would otherwise have to work out (dates, devices, -units, wording of times) is decided in code and handed over ready-made.""" +"""The bot's system prompt (docs/ecobot-mcp.md 4): its persona, a friendly Telegram bot, then the server's instructions +(lib/service/instructions.py) and the date and time now. Everything about the tools and the data is in their descriptions and results +(3.2): nothing here is about which tool to call or how to read what comes back.""" -from collections.abc import Collection from datetime import datetime -from .airgradient.metrics import ALL_METRICS, CHART_UNITS, LABELS -from .alerts.forecast import TEMP_CHANGE_C -from .alerts.menu import TYPES -from .alerts.weather import GUST_ALERT_KMH -from .ecowitt.glance import UVI_ALERT -from .intent import period_ranges -from .series import WEATHER -from .timeutil import day_text - -WEATHER_NAMES = list(WEATHER) -NEVER_AVAILABLE = ["lightning", "soil or extra sensor channels", "indoor air quality", "other stations or places"] -WITHOUT = {"Pollen": "pollen and thunderstorm asthma", "Forecast": "forecasts (only a short read of the pressure trend)"} # what a source that is off leaves out -# Each alert type as the prompt describes it, with its own threshold; told only when the source that sends it is on (alerts.menu.TYPES) -ALERT_WORDS = {"rain": "rain starting or stopping", "gusts": f"wind gusts over {GUST_ALERT_KMH} km/h", - "uv": f"UV index of {UVI_ALERT} or more", "temps": "indoor/outdoor temperature crossing", - "particulates": "air-quality mask alerts", "pollen_and_asthma": "pollen or thunderstorm asthma risk reaching High", - "forecast": f"a forecast it sent being revised (rain, or max temperature over {TEMP_CHANGE_C:g} degrees)"} - -PROMPT = """\ -You are a friendly weather bot on Telegram. -People ask about the owner's personal weather station and air-quality sensor: current conditions and historical data. Always fetch data with your tools; never guess or invent readings. If data is missing, say so briefly. - -DATA SOURCES (already discovered - no lookup needed) -{sources} -People name the devices too: "ecowitt" means the weather station, exactly like "weather" (the weather_* tools); "ag", "airgradient" and "air gradient" mean the air-quality sensor, exactly like "aq" and "air quality" (the air_quality tool). -{capabilities} -TIME PERIODS -- A day runs from midnight to midnight local time. Weeks start on Monday. -- "This week" (especially in past tense) means the last 7 days: today plus the previous 6 days. -- "This month"/"this year" are month-to-date/year-to-date. -- Short forms: 24h or 1d = the last 24 hours, 1w = the last 7 days, 1m = one month, 3m = three months, 6m = six months, 1y = one year (a number then h, d, w, m or y is a length of time, never a date). Rolling periods end now. -- With "the" ("the last year", "in the last year", "over the last month", "the last week") or "past" ("past year"), or a number ("last 12 months", "last 30 days"), it's a rolling period ending today: past year / past month / last 7 days. -- Bare "last week/month/year" ("hottest last year") is the previous full calendar week (Monday to Sunday), month or year. -- The exact ranges, and the time now, are listed under RIGHT NOW at the end (use them, don't recalculate). -- A period that includes today runs up to now; include today's data. -- "On record", "ever" or "all time" means all available data: the "on record" range under RIGHT NOW, or from the station's creation time above if that is later. Never shorten it to this year. -- State the date range you used in a few words, e.g. "Sun 20 - Sat 26 Sep". - -HOW TO FETCH WEATHER DATA (be fast: ONE round of tool calls, in parallel if more than one, then answer) -- If a tool returns an error, a note saying it can't do something, or no data, read it and correct the call once (the note usually says how) rather than answering from nothing. Never invent readings to fill a gap. -- Always fetch fresh data for every question, even if the same or a similar question was answered earlier in this conversation. Never reuse numbers, times or dates from earlier messages or earlier tool results. A follow-up about what was just answered ("give me the timestamp", "in ISO format", "and the lowest?") is fetched again at once, for the same reading and period: never ask whether to. -- For any past period (highs/lows, records, daily summaries, "this week" etc.): make ONE weather_history call covering the whole period, start_date = first day 00:00:00, end_date = last day 23:59:59 (today is included up to now). Any length up to 4 years is fine: the bot handles resolution, request limits and units. Don't split it yourself and don't add weather_now calls. -- For a reading's values at set times or per interval ("each hour", "every 30 minutes", "hourly", a table of values, or what it was at one time such as 3pm: a few minutes either side at 5min), use readings, not weather_history (unless a chart or graph is asked for: that is weather_history or air_quality with chart=true): one call per metric, made together (outdoor and indoor humidity are two), with the interval asked for (each hour = 1hour) and start and end in local time. Give a "•" line per row with its time, and say which rows are missing; never fill a gap. If it answers "too many rows", call it again with the interval in "fits". -- Prefer one or two calls. Never split a period into many weather_history calls when weather_days or one weather_history call can answer it; the bot warns the chat by itself when a question pulls in a lot of data. -- To plot several readings together ("plot temperature and rain", "humidity and wind"), set chart_fields to them, in order (temperature, humidity, pressure, wind, rain, dew_point, feels_like, vpd, solar, uv): one chart, a panel each, on one time axis. Never say it can't combine them. When the person says "on two axes", "dual axis" or "overlay", also set two_axes true: one panel, each reading with a scale of its own, left and right (plot_chart takes two_axes too, for readings from both sensors). -- A chart plots temperature unless told otherwise: for a question about humidity, pressure, wind or another reading, set chart_field to it (a reading name such as "humidity", "dew_point", "solar" or "uv" is fine). -- Set chart=true on the history call whenever the period is 3 days or longer (the bot draws one anyway), or a graph or chart is asked for. Your reply then becomes the chart's caption: keep it short: the period, then one line each for Outdoor and Indoor with its high and low (or its average, if that is what was asked), with times and dated days as usual, no other lists. For a chart of several readings, one short line per reading. The whole reply must stay under 900 characters (Telegram's limit for a chart's caption is 1024; a longer one is cut). Never write about the chart itself (e.g. "Chart sent..."). -- With any chart, set the tool's source argument to where its data came from: the site, tool or URL ("Ecowitt weather station", "AirGradient sensor", "ecowitt.net"). It is written small under the chart; never repeat it in your reply. -- Feels-like, apparent temperature, dew point and VPD are left out of history results unless you ask for them with include_derived (only when the question is about them; a chart of one of them brings it in by itself). -- groups takes plain group names, comma-separated, e.g. "outdoor,indoor" (add "rainfall" or "wind" only if needed). Never use dotted names like "outdoor.temp". -- The result has, per series (e.g. "outdoor.temperature"): low and high for the whole period, each with ready-made "_when" wording and a "_date" (plus the raw "_time"), and a "daily" (up to 31 days) or "monthly" breakdown. For periods of up to about a year, each month in "monthly" also has its own low/high "_when" and "_date" (when the bot has the detailed data cached; otherwise, and for longer periods, monthly figures are values only - see "monthly_note"). Read the answer straight from those fields. -- If the question names several months ("June, July, August") or asks about "each month", answer each month separately (its low and/or high, with when and date) rather than one figure for the whole period. -- If the result has a "warning" or "missing", say briefly that some data couldn't be fetched. -- State only what the result shows. weather_history has no day-by-day figures over about a month, and each series is separate, so it can't say what one reading (e.g. rain) was on a day picked by another. Never guess or say "no rain was recorded" without seeing it. -- Use weather_now only for current conditions. Its "emoji" holds ready-made emojis, only for readings that are notable right now: put each right before that reading's own value, copied exactly. a reading with no entry gets NO emoji, and never add one of your own to current readings. -- Never repeat an identical call. Timestamps in results are already local time. - -HIGHS AND LOWS -- Say when each high or low happened by copying its "_when" text exactly as given ("at 7:05am", "around 3:30pm", or a window), then "on", the day's emoji and its "_date": "28.3°C around 3:30pm on ☀️ Fri 9 Jan 2026". Never change "at" to "around" or the reverse. -- If "_date" is empty, the "_when" text is a window spanning two days: give it as is, with no emoji and no single date. -- If a high or low has a note saying it came from averaged data, add a short caveat that the real value may have been more extreme (not needed for averages). -- Default to highs and lows. Give averages only when asked ("average", "mean"): set average=true on the history call, then use the series' "average" for the period (and "avg" per day or month), the mean of the daily means. Never work an average out from lows and highs. - -LABELS -- For temperature and humidity, give both Indoor and Outdoor (fetch groups "outdoor,indoor"), unless the question asks about only one of them. Wind, rain, pressure, solar radiation and UV exist only outdoors: just give those. -- Call readings simply "Indoor" and "Outdoor". Don't mention sensor models, console names or the station name. - -UNITS -- Always Celsius for temperature (convert if a sensor reports Fahrenheit). Never show Fahrenheit, not even in brackets. Metric for everything else: mm rain, km/h wind, hPa pressure, kPa vapour pressure deficit, W/m² solar radiation. - -WEATHER EMOJIS (required) -- Whenever you name a specific day, including today, put an emoji for that day's outdoor weather immediately before it (day-by-day lists and single mentions such as the day of a high or low). Infer it from that day's figures ("daily", or temp_max, temp_min, rain and wind_gust): ☀️ sunny, 🌤️ mostly sunny, ⛅ partly cloudy, ☁️ overcast, 🌦️ light showers, 🌧️ rain, ⛈️ storms, 💨 windy, 🥵 very hot, 🥶 very cold, 🌫️ foggy. Use only these. With no figures for the day, leave the emoji out rather than guess. +PERSONA = """\ +You are a friendly weather bot on Telegram, for the owner's home weather station and air-quality sensor. TONE - Friendly and a little playful. Match the person's tone: if they're joking, play along briefly while still answering. -- Imagination is for the description, never the data: every number, time and date must come from tool results. +- Imagination is for the description, never the data: every number, time and date comes from the tools' results. Never guess or invent a reading, and never say something was or wasn't recorded without seeing it. If data is missing, say so briefly. STYLE -- A message that replies to an earlier one, or follows on from your last answer ("the lowest day", "that day", "and indoors?"), is about that answer: keep its subject (e.g. pressure, not temperature) and use the dates it gave. Never switch to a different reading because the words fit it too. -- Only talk about the weather when the message asks about it. Compliments, thanks, jokes and chat get a short, natural reply, with no weather data and no tool calls. +- A message that replies to an earlier one, or follows on from your last answer ("the lowest day", "that day", "and indoors?"), is about that answer: keep its subject (e.g. pressure, not temperature) and the dates it gave. Never switch to a different reading because the words fit it too. +- Only talk about the weather when the message asks about it. Compliments, thanks, jokes and chat get a short, natural reply, with no weather data. - In group chats, messages are prefixed with the sender's name. Never start your reply with a name or "Name:" prefix. -- Be concise. Plain text only: no markdown headers, tables or bold. Use "•" bullet lists for data answers (highs and lows, lists of days); descriptive and chatty answers are prose. - -EXAMPLE -Q: what was this week's high and low for indoor and outdoor? -A: Mon 3 - Sun 9 Aug (including today so far): -Outdoor -• High: 19.4°C at 2:35pm on 🌤️ Thu 6 Aug -• Low: -1.2°C at 6:10am on 🥶 Mon 3 Aug -Indoor -• High: 22.1°C at 3:55pm on 🌤️ Thu 6 Aug -• Low: 11.5°C at 7:20am on 🥶 Mon 3 Aug -(Example values are made up. Always use real tool data.) +- Be concise. Plain text only: no markdown headers, tables or bold. Use "•" bullet lists for data answers (highs and lows, lists of days, rows of readings); descriptive and chatty answers are prose. +- "What was it like", "describe" or "imagine" questions get a short, vivid picture of the day in 2-4 sentences of plain prose, built only from the real readings, then the key numbers in one short line. +- Emoji: put the ones the results give (a day's look, a reading's, a rating's) beside what they belong to, copied as given. Never add your own to a day or a reading. +- Call the sides simply "Indoor" and "Outdoor". Don't mention sensor models, console names or the station's name. +- When a result has a chart, the bot sends the chart with your reply as its caption: keep it short (the period, then one short line per reading), under 900 characters (Telegram cuts a caption at 1024), and never write about the chart itself ("Chart sent...", "see the chart above"). +- Don't mention a dashboard or chart link: the bot adds a small live-chart link under air-quality answers itself. +- About the bot itself: alerts are sent to chats by themselves, each with buttons to subscribe or unsubscribe by type, and /alerts opens the same settings; /usage lists what it can do; in a private chat the buttons under the message box ask the common questions. """ -# What the model is told only when the question needs it. Everything above is the same on every call, so the model provider -# can cache it; these follow it, then the date and time. -BLOCKS = { - "air_extra": """AIRGRADIENT'S OWN TEMPERATURE AND HUMIDITY -- The person named the AirGradient sensor's own temperature or humidity. They are the series air_temperature and air_humidity (plot_chart series, or metrics of air_quality), not the weather station's temperature and humidity. -- To put them against the station's ("plot airgradient humidity over ecowitt outdoor humidity"): plot_chart with series air_humidity and humidity and same_axis true (the same unit: one axis, the lines over each other). For readings in different units use two_axes true; for two pairs (humidity from each sensor, and temperature from each) list all four and set two_axes true: each unit gets an axis. Keep the caption short: the period, then one line per series with its low, high and average. -""", - "air": """AIR QUALITY -- For air quality (AQI, PM2.5, PM10, CO2, VOC, smoke, "is the air OK"), use the air_quality tool (the owner's AirGradient outdoor sensor): no dates for now, start_date/end_date for how it was over a period (up to about a year). -- Use the weather station for temperature and humidity; use the air-quality sensor only for air quality. -- Don't mention a dashboard or chart link: the bot adds a small "live chart" link itself. -- For air-quality graphs ("graph PM2.5 this week", "chart the air quality"), call air_quality with chart=true, the period's start_date/end_date (none for the last 24 hours) and the metrics asked about (default PM2.5; "all" means all six). Keep the caption short: the period, then one line per metric with its peak and rating (a practical tip only when something isn't good). -- VOC and NOx are relative indexes, not health measurements: 100 (VOC) and 1 (NOx) are the sensor's recent average and baseline. Well above that means something changed nearby (e.g. smoke, solvents, traffic); say so plainly, without calling it healthy or unhealthy. -- Put each metric's ready-made rating ("\U0001f7e2 good", "\U0001f7e1 poor" or "\U0001f534 very poor") next to it, copied exactly: e.g. "• PM2.5: 0.0 µg/m³ \U0001f7e2 good (AQI 0)". For history, use high_rating and average_rating. A current rating is held at the better level until two readings in a row agree (a "rating_note" says so): use the ready-made rating and never add a warning of your own about a single high value. Add a short practical tip when anything isn't good. -""", - "days": """DAYS (ranking, comparing and counting days) -- For questions that rank, compare or count DAYS ("the hottest day it also rained", "how many days over 35°C", "the wettest day", "the windiest cold day", "days below 5°C with wind"), use weather_days instead of weather_history, in ONE call. It checks every day in the period. weather_days has a day's highest or lowest of every reading the station has (temp_max, humidity_max, pressure_min, uv_max, solar_max, wind_gust, rain ...), so "how many days was UV 9 or more" is one call: where uv_max >= 9, count_only true (group_by month or year adds a count for each and the bot draws them as a bar chart: your reply is then its one-line caption, the matching days out of those checked and the period, never a list of the bars). A total, average, highest or lowest of a reading per month or year ("rain per month", "hottest day each year", "average humidity per year") is also one call: stat (sum, avg, max, min) and of (a field such as rain, temp_max, humidity_avg) with group_by, drawn as a bar chart the same way. With no period named ("per year", "how many times"), use the whole record (the "on record" range). Set only (public_holiday, weekend) only when the person's words say holidays or weekends; it limits the count to those days. For air quality use air_days, which has the same arguments over pm1, pm2_5, pm10, co2, voc_index and nox_index (pm2_5_max, co2_avg ...). - - A RECORD (the highest, lowest, hottest, coldest or fastest reading over a period or ever) with when it happened is weather_history, not weather_days: it gives the value and its exact time. - - Put each requirement in "where" and say what to rank by: sort_by (e.g. temp_max for "hottest") and order. Ask for a few days (limit 3-5). Use the "on record" range for all time. - - For public holidays ("hottest public holidays"), set only="public_holiday": the bot knows the local ones and names each in "holiday". Never pick holiday dates yourself; give each day's holiday name with its figures. - - For the figures of one known day ("did it rain on Sat 5 Sep"), set start_date = end_date = that day and no "where". To describe a day ("what was it like", "what kind of weather was June 11"), use weather_history for that day. Never search a wider period and infer from a day's absence. - - A rainy or wet day means rain of 1 mm or more (rain >= 1), unless the person says "any rain" or "a trace" (then rain > 0). - - Answer with the top day: its date (with the weather emoji) and figures (temp_max, temp_min, rain, wind_gust), the rain amount if it is small. - - Give the count in plain words, e.g. "It rained on 507 of 1,454 days" (matching_days of days_checked), never "507 such days". - - If the result has "trace_rain_days", add the first as a short footnote, e.g. "(A hotter day, 41.6°C on Sun 4 Feb 2024, had only 0.3 mm of rain.)". - - If a day you name is marked "daily", or the period reaches back before "exact_from", add the short caveat from "note_daily". -""", - "link": """CORRELATION -- To ask whether rain comes WITH a change in pressure (or humidity or wind) - "is there a correlation between pressure and rainfall", "did the rain come with the pressure drop", "plot pressure against rainfall" - use weather_link in ONE call (default period: the last 90 days). It reads both together at 30 minutes; open with its `verdict` (a plain yes, no or weak), then give the evidence from its `findings` - the ratios for moving vs steady, the level in rain, and the rain events with the biggest one (the most checkable evidence) - and say it used 30-minute readings, never monthly figures. Never conclude 'no link' from the correlation alone; it is weak by design. -""", - "outlook": """RAIN AND SHORT-TERM OUTLOOK ("will it rain?", "do I need an umbrella?", "what's it doing later?") -- The current reading (weather_now) and the last 3 hours (weather_history), groups "outdoor,pressure,rainfall,rainfall_piezo,wind", are normally - already in the conversation: use them. Fetch them in ONE step, in parallel, only if they are missing. -- Pressure tendency (relative pressure, last 3 hours): falling if the high came before the low, rising if the low came first. Change = high minus low. - Falling more than 3 hPa: unsettled, rain likely soon. Falling 1-3 hPa: rain possible. Steady (under 1 hPa) or rising: rain unlikely. -- Pressure level: under 1005 hPa is unsettled; over 1020 hPa is settled. -- Moisture: humidity 90% or more, or temperature within 2°C of dew point, makes rain more likely. -- Recent rain: a rain rate above 0 now, or rain in the last hour, means showers are likely to continue for a while. -- Wind picking up alongside falling pressure strengthens a rain call. -- Answer with one of: unlikely / possible / likely, then a short reason citing one or two readings (e.g. "pressure down 2.4 hPa in 3 hours, humidity 91%"). Only look a few hours ahead. -- When a weather_forecast result is in the conversation (or the tool is available), give it too: its ready-made lines for the days asked about (copied as they are, emoji included), after your own read of the station. If it disagrees with the station read, say so plainly. Keep the station read short and say it is a read of the station data; the forecast is Open-Meteo's. Don't list every reading. -""", - "wind": """WIND DIRECTION -- Wind direction has no low or high (it is circular: 350° and 10° are 20° apart). For "wind.wind_direction" the result gives "most_common" (with its share of the time), "then", "average_direction", "steadiness" and, for up to 31 days, a "daily" dominant direction. Answer from those with compass names, e.g. "mostly NE (34% of the time), then E; fairly steady". Never give degrees as a range, or say the wind swung "from 2° to 349°". Add any "note", "note_period" or "calm" briefly. -""", - "describe": """DESCRIBING A DAY -For today or yesterday the day's readings are normally already in the conversation; fetch only if missing. -- For "what was it like", "what would it have been like", "describe" or "imagine" questions, paint a short, vivid picture of the day in 2-4 sentences of plain prose, built only from the real readings (e.g. when the rain came, how cold it got, how windy), then give the key numbers in one short line. No bullet list for these. -""", -} - - -DATE_LABELS = [ # period name -> label in the prompt - ("yesterday", "Yesterday"), - ("last 7 days", 'Last 7 days / the last week / "this week"'), ("current calendar week", "Current calendar week"), - ("last week", "Last week"), ("this month", "This month"), ("last month", "Last month"), - ("this year", "This year"), ("last year", "Last year"), ("past month", "Past month / the last month / last 30 days"), - ("past year", "Past year / the last year / last 12 months"), ("on record", "On record (Ecowitt keeps 4 years)"), -] - +def now_line(now: datetime, zone: str | None = None) -> str: + """"Now: Tuesday 10 November 2026, 14:05 (Australia/Melbourne time).": the date, time and zone the model is told.""" + zone = zone or getattr(now.tzinfo, "key", None) or (now.tzname() if now.tzinfo else None) + return f"Now: {now:%A} {now.day} {now:%B %Y}, {now:%H:%M}" + (f" ({zone} time)." if zone else ".") -def date_ranges(now: datetime) -> str: - """Pre-computed date ranges so the model never does calendar maths (same definitions as - the fast path).""" - fmt = day_text - periods = period_ranges(now.date()) - lines = [f" Today: {fmt(now)} (00:00 to now)"] - for name, label in DATE_LABELS: - first, last = periods[name] - lines.append(f" {label}: {fmt(first)}" if first == last else f" {label}: {fmt(first)} to {fmt(last)}") - return "\n".join(lines) - -def capabilities(have: Collection[str], brief: bool = False) -> str: - """What the bot can and can't do with the sources it has (by name), for questions about the bot itself ("what metrics do you - have?") and so the model knows what is possible before it says something can't be done. Built from the code's own lists.""" - missing = ", ".join([*NEVER_AVAILABLE, *(what for name, what in WITHOUT.items() if name not in have)]) - if brief: # most questions: only the limits, so it never promises what it can't do - return (f"\nLIMITS: not available: {missing}. Custom alerts (\"tell me when winds reach 100\") can't be added: say so. " - "A chart series or style the tools don't offer can't be drawn: say so.\n") - lines = ["\nWHAT THIS BOT CAN AND CAN'T DO (answer questions about the bot from this, with no tool call)"] - if "Ecowitt" in have: - lines.append("- Weather station: outdoor and indoor temperature and humidity, dew point, feels-like, vapour pressure deficit, " - "pressure, wind speed, gust and direction, rain (daily total and rate), solar radiation and UV index. History " - "back to when it was installed: 5-minute detail for the last 90 days, 30-minute for a year, then daily.") - if "AirGradient" in have: - lines.append("- Air quality (outdoor AirGradient): " + ", ".join(f"{LABELS[m]} ({CHART_UNITS[m] or 'index'})" for m in ALL_METRICS) - + ", each with a traffic-light rating. History about a year.") - lines.append("- Tools: weather_now (current), weather_history (highs, lows, averages, charts), weather_days (find, rank and " - "count days, holidays, weekends), weather_link (does rain come with a pressure, humidity or wind change), " - "air_quality, readings (any reading's values at an interval, from a minute to a day, each with its time).") - if "Ecowitt" in have and "AirGradient" in have: - lines.append("- Across both devices: plot_chart draws readings from both on one chart, up to 4 panels (series: " - + ", ".join([*WEATHER, *ALL_METRICS]) + "; styles: line, bars for rain, " - "rating = the traffic-light share of time, air series only), air_link answers whether rain goes with " - "cleaner air, and air_scan scans every air metric against every weather reading for what goes with what. " - "Use them for \"plot X against Y\", \"does rain affect air quality\" and \"is there a correlation between air " - "quality and other metrics\"; a series or style not listed can't be plotted: say so.") - if "Pollen" in have: - lines.append("- Pollen: Melbourne's grass pollen level and the thunderstorm asthma risk (Low, Moderate, High, Extreme), tool pollen_asthma. " - "Both forecasts only run from October to December: outside those months the tool says so.") - if "Forecast" in have: - lines.append("- Forecast: today and the days ahead from Open-Meteo (summary, temperatures, chance of at least 1 mm of rain), tool weather_forecast.") - lines.append("- Charts: any one reading, or several readings together on one time axis, one panel each (" + ", ".join(WEATHER_NAMES) - + "; \"weather all week\" draws every reading); wind as average speed with gusts beside a compass rose of directions; " - "air quality with ratings.") - if alerts := ", ".join(words for kind, words in ALERT_WORDS.items() if TYPES[kind][1] in have): - lines.append(f"- Alerts, sent to chats automatically: {alerts}. Each alert has buttons to subscribe or unsubscribe by type, and " - "/alerts opens the same settings. Custom alerts (\"tell me when winds reach 100\", another limit) can't be added: say so.") - lines.append(f"- Not available: {missing}.") - return "\n".join(lines) + "\n" - - -RAIN_CAPTION_SECTION = """ -THIS IS A RAIN CHART: its caption is ONLY the least and the most rain in the period (daily totals, mm, with the dated days). -Nothing else: no averages, no other readings, no outlook. -""" +def build(now: datetime, instructions: str = "") -> str: + """The system prompt: the persona, the server's instructions (instructions.instructions(ctx)), then the date and time now (last: the + model provider caches a prompt's start).""" + return "\n\n".join(part for part in (PERSONA.rstrip(), instructions.strip(), now_line(now)) if part) + "\n" -def build(now: datetime, sources: dict[str, str], hints: list[str] = (), about_bot: bool = False, rain_caption: bool = False, - topics: set[str] | None = None) -> str: - """The system prompt for the bot's sources ({name: its line for the prompt, Source.describe()}). `topics` (see intent.topics) - picks the guidance the question needs; None puts all of it in.""" - # Most stable first: the model provider caches a prompt's start, so what changes (the topics, the date, then the time) goes last - everything = topics is None - text = PROMPT.format(sources="\n".join(f"- {s}" for s in sources.values()) or "(none)", - capabilities=capabilities(sources, brief=not (everything or about_bot or "bot" in topics))) - text += "".join(f"\n{block}" for name, block in BLOCKS.items() if everything or name in topics) - text += f"\nRIGHT NOW (exact ranges, then the time)\n{date_ranges(now)}\nIt is now {now.strftime('%A %d %B %Y, %H:%M %Z')}.\n" - if rain_caption: - text += RAIN_CAPTION_SECTION - if about_bot: - text += ("\nTHIS QUESTION IS ABOUT THE BOT ITSELF: answer from WHAT THIS BOT CAN AND CAN'T DO above, with no tool call. Keep it " - "to the METRICS, as a few simple bullet points (\u2022, one short line each, 7 at most, no intro or closing sentence, no " - "sub-bullets), grouped: indoor and outdoor together, PM1, PM2.5 and PM10 together. No dates, and don't say \"available " - "now\"; mention history only if asked. Leave out tools, charts and alerts unless the question asks about them.\n") - if hints: # decided in code, for this question only - text += ("\nTHE PERSON'S WORDS NAME THESE PERIODS (use exactly these start_date/end_date values; do not " - "reinterpret them):\n" + "\n".join(f"- {h}" for h in hints) + "\n") - return text +__all__ = ["PERSONA", "build", "now_line"] diff --git a/lib/ecowitt/calendar.py b/lib/public_holidays.py similarity index 100% rename from lib/ecowitt/calendar.py rename to lib/public_holidays.py diff --git a/lib/report.py b/lib/report.py deleted file mode 100644 index effeb37b..00000000 --- a/lib/report.py +++ /dev/null @@ -1,323 +0,0 @@ -"""The report (and "weather now") written in code from the tools' own results, with no model: the layout, units and emoji are all -decided here, so it is instant and always the same. Each tool result is JSON; one that failed or is missing is left out.""" - -import json -import re -from datetime import date, datetime - -from telegram import MessageEntity - -from .ecowitt.api import unit_text -from .ecowitt.glance import solar_band -from .entities import utf16_len -from .series import AIR, INDOOR_READINGS, WEATHER, find -from .timeutil import clock_text, day_text, to_local - - -def _load(result: str | None) -> dict | None: - """The tool's JSON, or None when it is missing, an error message or says it has nothing.""" - try: - data = json.loads(result or "") - except ValueError: - return None - return data if isinstance(data, dict) and "error" not in data else None - - -def _zero(text: str | None) -> bool: - """Is this reading missing or zero ("0.0 W/m²", "0")?""" - try: - return not text or float(text.split()[0]) == 0 - except ValueError: - return False - - -def _band(solar: str | None) -> str: - """" (medium)" for a solar reading like "40.2 W/m²"; nothing when it can't be read.""" - try: - return f" ({solar_band(float(solar.split()[0]))})" - except (AttributeError, IndexError, ValueError): - return "" - - -def _join(parts: list[str | None], sep: str = ", ") -> str: - return sep.join(p for p in parts if p) - - -def _stamp(result: dict, today: date) -> str | None: - """The time of the data, "11:45pm", with its day when that isn't today ("Sat 10 Oct 11:45pm"), from the result's "time" (as - timeutil.when writes it, "Sun 11 Oct 2026 11:45pm"); None when it is missing or unreadable.""" - try: - at = datetime.strptime(result.get("time") or "", "%a %d %b %Y %I:%M%p") - except ValueError: - return None - return clock_text(at) if at.date() == today else f"{day_text(at, year=False)} {clock_text(at)}" - - -def _heading(name: str, result: dict, today: date) -> str: - """"Forecast (Melbourne, 6:00pm)": the place the result names and the time of its data, whichever it has.""" - note = ", ".join(x for x in (result.get("place"), _stamp(result, today)) if x) - return f"{name} ({note})" if note else name - - -def _getters(now: dict): - """(get, tag) for a weather_now result: a reading's text, and the same with its emoji (if it has one) before it.""" - emoji = now.get("emoji") or {} - - def get(group: str, field: str) -> str | None: - return unit_text((now.get(group) or {}).get(field)) - - def tag(group: str, field: str, text: str | None = None) -> str | None: - text = text or get(group, field) - return f"{emoji[f'{group}.{field}']} {text}" if text and f"{group}.{field}" in emoji else text - return get, tag - - -def _rain(now: dict) -> str: - """Today's rain, the month's and, while it rains, the rate: "☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)".""" - get, tag = _getters(now) - rate, month = get("rainfall", "rain_rate"), get("rainfall", "monthly") - return _join([_join([tag("rainfall", "daily"), f"(month total {month})" if month else None], " "), - None if _zero(rate) else tag("rainfall", "rain_rate", f"raining ({rate})")], "; ") - - -def _wind(now: dict) -> str | None: - """The wind, where it comes from and its gusts: "14.0 km/h from 131°, gust 31.0 km/h"; None when it is calm.""" - get, tag = _getters(now) - if _zero(get("wind", "wind_speed")) and _zero(get("wind", "wind_gust")): - return None - direction, gust = get("wind", "wind_direction"), tag("wind", "wind_gust") - return _join([_join([tag("wind", "wind_speed"), f"from {direction}" if direction else None], " "), f"gust {gust}" if gust else None]) - - -def weather_lines(now: dict) -> list[str]: - """The weather station's bullets from a weather_now result: an emoji sits right before the reading it is keyed to.""" - get, tag = _getters(now) - solar, uvi = get("solar_and_uvi", "solar"), get("solar_and_uvi", "uvi") - sun = _join([None if _zero(solar) else tag("solar_and_uvi", "solar", f"solar radiation {solar}{_band(solar)}"), # night: no sun line - None if _zero(uvi) else tag("solar_and_uvi", "uvi", f"UV index {uvi}")]) - bullets = [("Outdoor", _join([tag("outdoor", "temperature"), tag("outdoor", "humidity")])), # (dew point and VPD are there to ask for) - ("Indoor", _join([tag("indoor", "temperature"), tag("indoor", "humidity")])), - ("Pressure", tag("pressure", "relative")), - ("Rain today", _rain(now)), - ("Sun", sun), - ("Wind", _wind(now))] # calm: no line - return [f"• {name}: {text}" for name, text in bullets if text] - - -def air_lines(air: dict, only: list[str] | None = None) -> list[str]: - out = [] - for key, label in ((name, m.label) for name, m in AIR.items()): - entry = air.get(key) if only is None or key in only else None - if not isinstance(entry, dict) or entry.get("value") is None: - continue - unit = entry.get("unit", "") - shown = (f"{entry['value']:.1f} {unit}" if unit.startswith("µg") else f"{entry['value']:.0f} {unit}" if unit == "ppm" - else f"{entry['value']:.1f}" if key == "nox_index" else f"{entry['value']:.0f}") - aqi = f" (AQI {entry['aqi_us']})" if key == "pm2_5" and "aqi_us" in entry else "" - out.append(f"• {label}: {_join([shown, entry.get('rating')], ' ')}{aqi}") - return out - - -def reading_lines(now: dict, names: list[str], sides: list[str]) -> list[str]: - """Just the readings asked about from a weather_now result ("how hot is it": the temperature, indoors and out).""" - get, tag = _getters(now) - lines = [] - for name in names: - reading = WEATHER[name] - if name in ("temperature", "humidity"): # a line for each side asked about; the temperature with what it feels like - for side in sides: - feels = get(side, "feels_like") if name == "temperature" else None - if text := _join([tag(side, reading.field), f"feels like {feels}" if feels else None]): - lines.append(f"• {side.capitalize()}: {text}") - elif name == "wind": - lines.append(f"• Wind: {_wind(now) or 'calm'}") - elif name == "rain": - lines.append(f"• Rain today: {_rain(now) or 'none'}") - else: - group = sides[0] if name in INDOOR_READINGS and len(sides) == 1 else reading.group # "indoor dew point": that sensor's - if text := tag(group, reading.field): - lines.append(f"• {reading.label}{' (indoor)' if group == 'indoor' else ''}: {text}") - return lines - - -def _own_lines(result: dict) -> list[str]: - """The bullets of a result that brings its own lines (pollen and asthma, the forecast).""" - return [f"• {line}" for line in result.get("lines", [])] - - -# The report's sections in order: the tool, the section's heading, its bullets from the tool's result, and whether it is still -# shown when that result failed ("• not available right now") rather than left out -SECTIONS = (("weather_now", "Weather station", weather_lines, True), - ("air_quality", "Air quality", air_lines, True), - ("pollen_asthma", "Pollen & asthma", _own_lines, False), - ("weather_forecast", "Forecast", _own_lines, False)) -HEADINGS = {tool: heading for tool, heading, _, _ in SECTIONS} # the pollen and forecast lookups start with theirs too -HEADING_LINE = re.compile(rf"^({'|'.join(map(re.escape, HEADINGS.values()))})(?= \(|$)", re.M) - - -def heading_entities(text: str) -> list[MessageEntity]: - """Bold entities over the name of each heading line in `text` (not over its brackets).""" - return [MessageEntity(MessageEntity.BOLD, utf16_len(text[:m.start()]), utf16_len(m.group(1))) for m in HEADING_LINE.finditer(text)] - - -def report(results: dict[str, str], today: date) -> str: - """The full report from the tool results by tool name (weather_now, air_quality, pollen_asthma, weather_forecast), on `today` (local).""" - sections = [] - for tool, heading, bullets, always in SECTIONS: - data = _load(results.get(tool)) - if data or (always and tool in results): - sections.append("\n".join([_heading(heading, data or {}, today), *(bullets(data) if data else ["• not available right now"])])) - return "\n\n".join(sections) or "No readings are available right now." - - -def weather_now(result: str | None) -> str | None: - """"Weather now": the weather station's bullets alone (None if the reading isn't available).""" - now = _load(result) - return "\n".join(weather_lines(now)) if now else None - - -# ---------- plain lookups ---------- -def _alone(tool: str, result: dict, today: date) -> str | None: - """A pollen or forecast result on its own: its section of the report, or None when it has no lines.""" - lines = _own_lines(result) - return "\n".join([_heading(HEADINGS[tool], result, today), *lines]) if lines else None - - -def _days(data: dict) -> str | None: - """"137 of 1,454 days with UV index ≥ 10 (period)", or a total, average, highest or lowest over the period: the chart (if any) - carries the breakdown.""" - if "matching_days" not in data: - return None - if data.get("stat") and data.get("value") is not None: - unit = unit_text(data["stat"].get("unit")) or "" - return f"{data['stat']['what']}: {data['value']:g} {unit}".rstrip() + f" over {data['days_checked']:,} days ({_period(data)})." - what = f" with {data['condition']}" if data.get("condition") else "" - note = " Older days use averages, so a count near the limit may fall slightly short." if data.get("note_averaged") else "" - return f"{data['matching_days']:,} of {data['days_checked']:,} days{what} ({_period(data)}).{note}" - - -def _series_label(field: str) -> str: - """A series' name: its reading's label ("Temperature"), the gusts their own ("Wind gust").""" - if field == "wind_gust": - return "Wind gust" - return reading.label if (reading := find(field)) else field.replace("_", " ").capitalize() - - -def _extremes(data: dict, names: list[str]) -> str | None: - """The period, then the low and high (or the average) of each reading named, each with its day and time: wind, its speed and - its gusts; nothing named, the temperature. A reading on both sides (indoor, outdoor) has a line for each.""" - series = data.get("series") or {} - wanted = [f for r in filter(None, map(find, names)) for f in (r.field, r.band_field) if f] or ["temperature"] - keys = [k for k in series if k.split(".", 1)[1] in wanted and "low" in series[k]] - fields = [k.split(".", 1)[1] for k in keys] - lines = [] - for key in keys: - group, field = key.split(".", 1) - label = _series_label(field) + (f" ({group})" if fields.count(field) > 1 else "") - lines.append(f"• {_range(label, series[key], 'average' in series[key])}") - return "\n".join([_period(data), *lines]) if lines else None - - -def lookup(kind: str, result: str | None, names: list[str], sides: list[str], today: date) -> str | None: - """A plain lookup written from its one tool result: `kind` is "reading", "air", "days", "extremes", "pollen" or "forecast", - `names` the readings asked about and `sides` where (indoor, outdoor), on `today` (local). None when the result can't be used - (the model then takes the question).""" - data = _load(result) - answers = {"reading": lambda: "\n".join(reading_lines(data, names, sides)), - "air": lambda: "\n".join(air_lines(data, names or None)), - "days": lambda: _days(data), - "extremes": lambda: _extremes(data, names), - "pollen": lambda: _alone("pollen_asthma", data, today), - "forecast": lambda: _alone("weather_forecast", data, today)} - return (answers[kind]() or None) if data and kind in answers else None - - -# ---------- chart captions ---------- -def _year(text: str | None) -> str: - """"Tue 29 Sep 2026" -> "Tue 29 Sep".""" - return re.sub(r" 20\d\d\b", "", text or "") - - -def _period(data: dict) -> str: - """"Tue 29 Sep 2026 - Tue 06 Oct 2026" -> "Tue 29 Sep – Tue 06 Oct 2026" (the first year is dropped only when it is the same year).""" - text = data.get("period", "") - years = re.findall(r" (20\d\d)\b", text) - if len(years) == 2 and years[0] == years[1]: - text = re.sub(r" 20\d\d\b(?= - )", "", text) - return text.replace(" - ", " – ") - - -def _at(entry: dict, which: str) -> str: - """"high 24.3 °C, Tue 29 Sep around 3pm" for one record of a series.""" - when = _year(f"{entry.get(f'{which}_date', '')} {entry.get(f'{which}_when', '')}".strip()) - return f"{entry[which]} {unit_text(entry.get('unit')) or ''}".strip() + (f", {when}" if when else "") - - -def _range(label: str, entry: dict, average: bool) -> str: - unit = unit_text(entry.get("unit")) or "" - if average and entry.get("average"): - return f"{label}: average {entry['average']} {unit} (low {entry['low']}, high {entry['high']})".replace(" )", ")") - return f"{label}: low {_at(entry, 'low')} · high {_at(entry, 'high')}" - - -def _rain_line(turn, tz) -> list[str]: - """Least and most rain in a period (the chart's own bars).""" - bars = next((p.bars for c in turn.charts for p in c.panels if p.bars and p.bars.x), None) - if not bars: - return [] - def day(i: int) -> str: - start = to_local(bars.x[i], tz) - return day_text(start, year=False) + (f" {clock_text(start, whole_hours=True)}" if bars.width < 86400 else "") - lo, hi = min(range(len(bars.y)), key=bars.y.__getitem__), max(range(len(bars.y)), key=bars.y.__getitem__) - per = f" per {bars.per}" if bars.per else "" - return [f"☔ Rain{per}: least {bars.y[lo]:g} mm ({day(lo)}) · most {bars.y[hi]:g} mm ({day(hi)}) · {sum(bars.y):.1f} mm in all"] - - -def _weather_caption(result: dict, turn, tz) -> list[str]: - series = result.get("series") or {} - names = [n for n in dict.fromkeys(turn.chart_fields or [turn.chart_field or "temperature"]) if find(n)] - lines: list[str] = [] - for name in names: - reading = find(name) - keys = [k for k in series if k.split(".", 1)[1] == reading.field] - if reading.field == "daily": # rain: the amounts the chart draws - lines += _rain_line(turn, tz) - continue - for key in keys: - group = key.split(".", 1)[0] - label = reading.label + (f" ({group})" if len(keys) > 1 and group in ("outdoor", "indoor") else "") - if reading.field == "wind_speed": - gust = series.get(f"{group}.wind_gust") or series.get("wind.wind_gust") - lines.append(f"🌬️ Wind: strongest gust {_at(gust, 'high')}" if gust else _range(label, series[key], bool(turn.average_asked))) - else: - lines.append(_range(label, series[key], bool(turn.average_asked))) - if reading.field == "wind_speed" and (d := series.get("wind.wind_direction")): - lines.append(f"🧭 Mostly from the {d['most_common']}" + (f", {d['steadiness']}" if d.get("steadiness") else "")) - return lines - - -def _air_caption(result: dict, args: dict) -> list[str]: - lines = [] - for key, label in ((name, m.label) for name, m in AIR.items()): - entry = result.get(key) - if key not in (args.get("metrics") or ["pm2_5"]) or not isinstance(entry, dict): - continue - unit = unit_text(entry.get("unit")) or "" - rating = entry.get("high_rating") - lines.append(f"• {label}: peak {entry['high']} {unit} ({_year(entry.get('high_time'))})".replace(" )", ")") - + (f" · {rating}" if rating else "") + f" · average {entry['average']}") - return lines - - -def chart_caption(tool: str, args: dict, result: str | None, turn, tz) -> str | None: - """The caption for a chart, from the tool's result: the period, then a line per reading. None when there is nothing to say (the - model then takes the question).""" - data = _load(result) - if not data or not turn.charts: - return None - lines = _air_caption(data, args) if tool == "air_quality" else _weather_caption(data, turn, tz) - if not lines: - return None - notes = (["(Older days are still downloading, so they are left out.)"] if data.get("note_missing") else - ["(Some data couldn't be fetched, so this may be incomplete.)"] if data.get("warning") else []) - return "\n".join([_period(data), *lines, *notes]).strip() diff --git a/lib/report_menu.py b/lib/report_menu.py deleted file mode 100644 index febf8bc6..00000000 --- a/lib/report_menu.py +++ /dev/null @@ -1,18 +0,0 @@ -"""The 🔄 under the full report ("status") and under the dashboard: it reads everything again and redraws the message in place -(Bot.on_report_button).""" - -from telegram import InlineKeyboardMarkup - -from .buttons import button - -PREFIX = "rp:" -REFRESH = f"{PREFIX}refresh" -DASHBOARD = f"{PREFIX}dashboard" - - -def keyboard() -> InlineKeyboardMarkup: - return InlineKeyboardMarkup([[button("🔄", REFRESH)]]) - - -def dashboard_keyboard() -> InlineKeyboardMarkup: - return InlineKeyboardMarkup([[button("🔄", DASHBOARD)]]) diff --git a/lib/service/__init__.py b/lib/service/__init__.py new file mode 100644 index 00000000..a70b7e9d --- /dev/null +++ b/lib/service/__init__.py @@ -0,0 +1,57 @@ +"""The service's tools (docs/ecobot-mcp.md 3.2 and 3.3): the ten that will replace the bot's twelve, each in a module of its own, on +what every one of them shares: + + - common.py: how a tool is made, what it is sent (its arguments and the request's metadata, nothing else), and the shape of what it + answers: the period it read, the time of its figures, its charts, and its refusals; + - names.py: the readings the service has, one name each (`outdoor.temperature`, `air.pm2_5`), and the words people use for them; + - daylook.py: a day's look ("wet", 🌧️) from its figures; + - instructions.py: the server's instructions, a short summary for a client to pass to its model. + +`build(ctx)` makes the ten, in 3.3's order, each module's `tools(ctx)` (a tool whose source isn't there is left out), and `Service` +holds them by name. The bot offers them to its model (lib/model_tools.py) and its own code paths call them; nothing here knows of +Telegram, of the bot's buttons or of who draws a chart. +""" + +from .common import ServiceTool + +ORDER = ("current", "summary", "readings", "days", "relate", "scan", "outlook", "forecast", "pollen", "about") # 3.3's + + +def build(ctx) -> list["ServiceTool"]: + """The service's tools over this Context, in 3.3's order: each module's tools(ctx).""" + from importlib import import_module + return [t for name in ORDER for t in import_module(f"{__name__}.{name}").tools(ctx)] + + +class Service: + """The service's tools by name: `service["summary"]`, `service.get(name)`, `name in service`; iterated in 3.3's order.""" + + def __init__(self, tools: list["ServiceTool"] = (), ctx=None): + self.tools, self.ctx = list(tools), ctx # ctx: the Context they were built over, when known + self.by_name = {t.name: t for t in self.tools} + + @classmethod + def of(cls, ctx) -> "Service": + return cls(build(ctx), ctx) + + def held(self, names: list[str]) -> list[str]: + """These readings' names, less those the service's catalogue doesn't hold (all of them when it isn't known).""" + if self.ctx is None: + return list(names) + known = set(self.ctx.readings().names) + return [n for n in names if n in known] + + def get(self, name: str) -> "ServiceTool | None": + return self.by_name.get(name) + + def __getitem__(self, name: str) -> "ServiceTool": + return self.by_name[name] + + def __contains__(self, name: str) -> bool: + return name in self.by_name + + def __iter__(self): + return iter(self.tools) + + +__all__ = ["ORDER", "Service", "build"] diff --git a/lib/service/about.py b/lib/service/about.py new file mode 100644 index 00000000..1586c33d --- /dev/null +++ b/lib/service/about.py @@ -0,0 +1,278 @@ +"""The `about` tool (docs/ecobot-mcp.md 3.3): what the service measures and what it doesn't, how far back each kind of history goes, +the alerts there are with their thresholds, and that alerts can't be added or changed by asking. It replaces what the bot's prompt told +its model outside the tools (lib/prompt.py: NEVER_AVAILABLE, the capabilities, ALERT_WORDS), whose lists are copied here (the prompt +goes with the bot), and the bot's Help list (lib/templates.py MEASURES: `lines`, the same words). + + - measures: each device and service there is (the sources in the Context), in words and, for the sensors, the readings the catalogue + holds, each with its name, label and unit; + - history: for each sensor, from when to when each resolution is held, and on how many days, from the coverage of the file (the + minutes, which have none, from the readings themselves): what "on record" reaches, and how fine a record is in each stretch of it; + - alerts: each kind there is for the sources there are (lib/alerts/menu.py TYPES, copied), with what it is, its rule in words and its + thresholds as figures, from the alert rules' own constants and the settings (MCP_RAIN_QUIET_HOURS, MCP_ALERT_COOLDOWN_MINUTES). + +It takes no arguments and reads only what is held, so `fetch` and `priority` change nothing. +""" + +from datetime import datetime, tzinfo + +from ..alerts.forecast import BASELINE_HOUR, DRY_BELOW_PCT, RAIN_FROM_PCT, TEMP_CHANGE_C +from ..alerts.particulates import CHECK_SECONDS, MASK_PM10, MASK_PM25, SAFE_PM10, SAFE_PM25 +from ..alerts.pollen_and_asthma import ALERT_FROM, WARN_FROM +from ..alerts.rules import CONFIRM_READINGS +from ..alerts.weather import CROSS_MARGIN, GUST_ALERT_KMH, GUST_REARM_SECONDS, UV_REARM_SECONDS +from ..airgradient.metrics import ALL_METRICS, CHART_UNITS, LABELS as AIR_LABELS +from ..ecowitt.api import daily_run +from ..ecowitt.glance import UVI_ALERT +from ..pollen.parse import LEVELS +from ..storage.catalogue import KINDS +from ..storage.coverage import merge +from ..storage.read import Reader +from ..storage.write import MINUTES_KEPT +from ..timeutil import clock_text, day_text, local_date +from .common import Refusal, ServiceTool, answer +from .context import Context +from .names import AIR_DEVICE, STATION + +NAME = "about" + +# ---------- the settings the alerts follow ---------- +# The rain alert's quiet hours and the alerts' cooldown are the service's config (MCP_RAIN_QUIET_HOURS, MCP_ALERT_COOLDOWN_MINUTES): set from it at +# startup, as names.FEELS_LIKE_IN_ALL is. These are the config's defaults. +RAIN_QUIET_HOURS: tuple[int, int] | None = (0, 6) # local hours with no rain alerts, a summary after; None: none +ALERT_COOLDOWN_MINUTES = 60 # dry this long before "the rain has stopped"; the temperature crossing's least gap + +# ---------- what the bot's prompt said (lib/prompt.py), copied: the prompt goes with the bot ---------- +NEVER_AVAILABLE = ["lightning", "soil or extra sensor channels", "indoor air quality", "other stations or places"] +WITHOUT = {"Pollen": "pollen and thunderstorm asthma", "Forecast": "forecasts (only a short read of the pressure trend)"} # a source that is off +ALERT_WORDS = {"rain": "rain starting or stopping", "gusts": f"wind gusts over {GUST_ALERT_KMH} km/h", + "uv": f"UV index of {UVI_ALERT} or more", "temps": "indoor/outdoor temperature crossing", + "particulates": "air-quality mask alerts", "pollen_and_asthma": "pollen or thunderstorm asthma risk reaching High", + "forecast": f"today's or tomorrow's forecast changing (rain becoming likely or unlikely, or the high moving over {TEMP_CHANGE_C:g} degrees)"} +# The alert kinds (lib/alerts/menu.py TYPES, copied, without the irrigation controller's: that is a server of its own): kind -> (its name, +# the source that sends it) +TYPES = {"rain": ("rain", "Ecowitt"), "gusts": ("gusts", "Ecowitt"), "uv": ("UV", "Ecowitt"), "temps": ("temperature crossing", "Ecowitt"), + "particulates": ("particulates", "AirGradient"), "pollen_and_asthma": ("pollen & asthma", "Pollen"), + "forecast": ("forecast changes", "Forecast")} +# What each source measures, as the bot's Help lists it (lib/templates.py MEASURES) +MEASURES = {"Ecowitt": ["Temperature, humidity (indoor, outdoor)", "Dew point, vapour pressure deficit, pressure, wind speed", + "Rain, solar radiation, UV index"], + "AirGradient": ["PM1, PM2.5, PM10, CO₂, VOC, NOx"], + "Pollen": ["Pollen and thunderstorm asthma risk (October to December)"], + "Forecast": ["Forecast"]} +STATION_TEXT = ("Weather station (Ecowitt): outdoor and indoor temperature and humidity, dew point, feels-like, vapour pressure deficit, " + "pressure, wind speed, gust and direction, rain (daily total and rate), solar radiation and UV index.") +AIR_TEXT = ("Air quality (outdoor AirGradient): " + ", ".join(f"{AIR_LABELS[m]} ({CHART_UNITS[m] or 'index'})" for m in ALL_METRICS) + + ", each with a traffic-light rating, and PM2.5 and PM10 each with its US AQI (the US AQI is the higher); also the sensor's own temperature and humidity " + "(air.temperature, air.humidity).") +FORECAST_TEXT = "Forecast: today and the days ahead from Open-Meteo (summary, temperatures, chance of at least 1 mm of rain)." +POLLEN_TEXT = ("Pollen: Melbourne's grass pollen level and the thunderstorm asthma risk (Low, Moderate, High, Extreme). Both forecasts " + "only run from October to December.") +ALERTS_NOTE = ("Alerts can't be added or changed by asking (\"tell me when the wind reaches 100\", another threshold, another reading): " + "there are only these, at these thresholds. The service sends them to the apps that listen for them; which of them a " + "person gets is set where they receive them.") +NOT_NOTE = "A reading, a place or a chart style not listed here can't be had by asking: say so." + +# What each tool answers, for "what can you do": (tool, what, the sources it needs) +TOOLS = (("current", "the readings now, with today's, this month's and this year's highs and lows", ("Ecowitt", "AirGradient")), + ("summary", "a period's highs and lows with when, averages, rain totals, air ratings, and charts of any readings", + ("Ecowitt", "AirGradient")), + ("readings", "any reading's values at an interval, from a minute to a day, each with its time", ("Ecowitt", "AirGradient")), + ("days", "days found, ranked or counted by their figures (the wettest day, days over 35°C, rain per month), or over part of " + "each day (the overnight low)", ("Ecowitt", "AirGradient")), + ("relate", "whether rain comes with a change in pressure, humidity or wind, and whether the air is cleaner after rain", + ("Ecowitt",)), + ("scan", "which air readings go with which weather readings", ("Ecowitt+AirGradient",)), + ("outlook", "whether it will rain in the next few hours", ("Ecowitt",)), + ("forecast", "today and the days ahead", ("Forecast",)), + ("pollen", "grass pollen and thunderstorm asthma (October to December)", ("Pollen",))) + +# The resolutions each sensor's history is held at, finest first, and what each is called +STATION_HELD = (("1min", "minute readings"), ("5min", "5-minute readings"), ("30min", "30-minute readings"), ("4hour", "4-hour records"), + ("1day", "daily records")) +AIR_HELD = (("1min", "minute readings"), ("5min", "5-minute readings"), ("1hour", "hourly averages")) +MINUTE = "1min" # held as readings only, for MINUTES_KEPT, with no coverage of their own + +# ---------- the description ---------- +DESCRIPTION = ( + "What this service is: what it measures and what it doesn't (no lightning, soil sensors, indoor air quality or other places), how " + "far back each kind of history goes and how fine it is, which alerts there are with their thresholds, and what each tool answers. " + "For \"what can you do\", \"what do you measure\", \"can you measure lightning\", \"how far back does the history go\", \"what " + "alerts are there\", \"alert me when the wind reaches 100\": {} (no arguments). Alerts can't be added or changed by asking: there " + "are only those listed, at their thresholds; say so. Not for any reading or figure: current (now), summary (a period), days, " + "readings. Result: measures (each device in words, and its readings: each name with its label and unit); not_available and " + "not_note; history (each sensor's text, ready to pass on, and each resolution held: from, to, days); alerts (each with what it is, " + "its rule in words and its thresholds as figures) and alerts_note; tools (what each answers); lines (a short list of what is " + "measured, to pass on as it is).") +PARAMETERS = {"type": "object", "properties": {}} + + +# ---------- what is held ---------- +def _minutes(r: Reader, sensors: list) -> tuple[int, int] | None: + """(the first, the last) minute held of these sensors (epochs), None for none: one query per kind.""" + found = [] + for kind in dict.fromkeys(s.kind for s in sensors): + ids = [s.id for s in sensors if s.kind == kind] + found.append(r.db.execute(f"SELECT MIN(ts), MAX(ts) FROM {kind} WHERE sensor IN ({', '.join('?' * len(ids))}) AND res = ?", + (*ids, MINUTE)).fetchone()) + firsts, lasts = [a for a, _ in found if a is not None], [b for _, b in found if b is not None] + return (min(firsts), max(lasts)) if firsts else None + + +def held_on(r: Reader, sensors: list, resolutions: tuple) -> dict[str, tuple[int, int, int]]: + """{resolution: (first, last, whole days held)} of these sensors (epochs; merged over them), for the resolutions held.""" + out = {} + for res, _ in resolutions: + if res == MINUTE: + if span := _minutes(r, sensors): + out[res] = (*span, round((span[1] - span[0]) / 86400)) + continue + spans = merge([span for s in sensors for span in r.storage.coverage.of(s.id, res)]) + if spans: + out[res] = (spans[0][0], spans[-1][1], sum(e - s + 1 for s, e in spans) // 86400) + return out + + +def history_of(held: dict[str, tuple[int, int, int]], resolutions: tuple, device: str, tz: tzinfo) -> dict: + """{text, held: {resolution: {from, to, days}}} of one sensor: its text ready to pass on ("Weather station: 5-minute readings from + Mon 12 May 2025, ..."), and each resolution's first and last day held (ISO dates) and its days held.""" + if not held: + return {"text": f"{'Weather station' if device == STATION else 'Air sensor'}: nothing held yet.", "held": {}} + parts, out = [], {} + for res, what in resolutions: + if res not in held: + continue + first, last, days = held[res] + a, b = local_date(first, tz), local_date(last, tz) + out[res] = {"from": a.isoformat(), "to": b.isoformat(), "days": days} + if res == MINUTE: + parts.append(f"{what} from {day_text(a)} (kept {MINUTES_KEPT // 86400} days)") + elif res == "1day": + parts.append(f"{what} from {day_text(a)}, each {daily_run(tz, a, b)}") + else: + parts.append(f"{what} from {day_text(a)}") + name = "Weather station" if device == STATION else "Air sensor" + return {"text": f"{name}: {', '.join(parts)}. The tools use the finest held for each part of a period.", "held": out} + + +# ---------- the alerts ---------- +def _clock(hour: int, minute: int = 0) -> str: + """"12am", "7:30am": a time of day as the service writes one.""" + return clock_text(datetime(2000, 1, 1, hour % 24, minute), whole_hours=True) + + +def alert_rules() -> dict[str, tuple[str, dict]]: + """{kind: (its rule in words, its thresholds as figures)}, from the rules' constants and the settings.""" + cooldown, quiet = ALERT_COOLDOWN_MINUTES, RAIN_QUIET_HOURS + rain = (f"Started: the first tip of the gauge, told at once. Stopped: dry for {cooldown} minutes, with how much fell." + + (f" None from {_clock(quiet[0])} to {_clock(quiet[1])}: one summary of the rain in those hours after them." if quiet else "")) + return { + "rain": (rain, {"dry_minutes": cooldown, "quiet_hours": f"{quiet[0]:02d}:00-{quiet[1]:02d}:00" if quiet else None}), + "gusts": (f"A gust over {GUST_ALERT_KMH} km/h; then none until the gusts have stayed at or under it for " + f"{GUST_REARM_SECONDS // 60} minutes.", {"gust_kmh": GUST_ALERT_KMH, "rearm_minutes": GUST_REARM_SECONDS // 60}), + "uv": (f"A UV index of {UVI_ALERT} or more in {CONFIRM_READINGS} readings in a row; then none until it has stayed below {UVI_ALERT} " + f"for {UV_REARM_SECONDS // 60} minutes.", + {"uv_index": UVI_ALERT, "readings_in_a_row": CONFIRM_READINGS, "rearm_minutes": UV_REARM_SECONDS // 60}), + "temps": (f"Outdoor becoming warmer than indoor, or cooler, by more than {CROSS_MARGIN:g}°C; at most one every {cooldown} minutes.", + {"margin_c": CROSS_MARGIN, "cooldown_minutes": cooldown}), + "particulates": (f"Wear a mask: PM2.5 at {MASK_PM25:g} µg/m³ or more, or PM10 at {MASK_PM10:g} µg/m³ or more (US AQI 151 and up: " + f"unhealthy), in {CONFIRM_READINGS} readings in a row. Safe again: PM2.5 at {SAFE_PM25:g} or less and PM10 at " + f"{SAFE_PM10:g} or less (AQI 100 or better), in {CONFIRM_READINGS} readings in a row. Checked every " + f"{CHECK_SECONDS // 60} minutes.", + {"mask_pm2_5": MASK_PM25, "mask_pm10": MASK_PM10, "safe_pm2_5": SAFE_PM25, "safe_pm10": SAFE_PM10, + "readings_in_a_row": CONFIRM_READINGS, "check_minutes": CHECK_SECONDS // 60}), + "pollen_and_asthma": (f"Grass pollen or the thunderstorm asthma risk forecast {' or '.join(LEVELS[WARN_FROM:])}: once a day from " + f"{_clock(*ALERT_FROM)} while it stays there, and again when it rises. October to December only.", + {"from_level": LEVELS[WARN_FROM]}), + "forecast": (f"Today's or tomorrow's forecast revised from the first one fetched after {_clock(BASELINE_HOUR)} that day: its highest " + f"temperature by more than {TEMP_CHANGE_C:g}°C, or the chance of at least 1 mm of rain rising from under {RAIN_FROM_PCT}% " + f"to {RAIN_FROM_PCT}% or more (rain likely), or falling from {RAIN_FROM_PCT}% or more to {DRY_BELOW_PCT}% or less (rain " + "unlikely). The forecast alerted on is the one later forecasts are compared with.", + {"max_change_c": TEMP_CHANGE_C, "rain_likely_from_pct": RAIN_FROM_PCT, "rain_unlikely_at_pct": DRY_BELOW_PCT, + "baseline_from": f"{BASELINE_HOUR:02d}:00"}), + } + + +# ---------- the tool ---------- +class AboutTool: + """The about tool over a Context.""" + + def __init__(self, ctx: Context): + self.ctx = ctx + + @property + def sources(self) -> list[str]: + """The sources there are, by the names the bot's lists use.""" + c = self.ctx + return [name for name, there in (("Ecowitt", c.eco), ("AirGradient", c.air), ("Pollen", c.pollen), ("Forecast", c.forecast)) if there] + + def tool(self) -> ServiceTool: + return ServiceTool(NAME, DESCRIPTION, PARAMETERS, self.handle) + + async def handle(self, args: dict, meta: dict) -> str: + if args: + raise Refusal(f"about takes no arguments, not {', '.join(map(repr, args))}: call it with {{}}.", arguments=[]) + sources = self.sources + return answer(period=None, as_of=None, measures=self.measures(), not_available=not_available(sources), not_note=NOT_NOTE, + history=await self.history(), alerts=alerts(sources), alerts_note=ALERTS_NOTE, + tools={name: what for name, what, needs in TOOLS if any(_has(sources, n) for n in needs)}, + lines=measure_lines(sources)) + + def measures(self) -> dict: + """Each device and service there is, in words; the sensors with their readings (name, label, unit).""" + catalogue = self.ctx.readings() + out = {} + for device, there, text in ((STATION, self.ctx.eco, STATION_TEXT), (AIR_DEVICE, self.ctx.air, AIR_TEXT)): + if there: + out[device] = {"text": text, "readings": {r.name: f"{r.label} ({r.unit})" if r.unit else r.label + for r in catalogue if r.device == device}} + if self.ctx.forecast: + out["forecast"] = {"text": FORECAST_TEXT} + if self.ctx.pollen: + out["pollen"] = {"text": POLLEN_TEXT} + return out + + async def history(self) -> dict: + """Each sensor's history: from when to when each resolution is held (history_of).""" + storage, tz, out = self.ctx.storage, self.ctx.zone, {} + if storage is None: + return out + if self.ctx.eco: + sensors = [s for s in storage.station(self.ctx.eco.mac).values() if s.kind in KINDS] + out[STATION] = history_of(await storage.read(held_on, sensors, STATION_HELD), STATION_HELD, STATION, tz) + if self.ctx.air: + sensor = self.ctx.air.store.sensor + held = await storage.read(held_on, [sensor], AIR_HELD) if sensor is not None else {} + out[AIR_DEVICE] = history_of(held, AIR_HELD, AIR_DEVICE, tz) + return out + + +def _has(sources: list[str], need: str) -> bool: + return all(n in sources for n in need.split("+")) + + +def not_available(sources: list[str]) -> list[str]: + """What the service can't give: never (NEVER_AVAILABLE), and what a source that is off leaves out (WITHOUT).""" + return [*NEVER_AVAILABLE, *(what for name, what in WITHOUT.items() if name not in sources), + *(["weather station readings"] if "Ecowitt" not in sources else []), *(["air quality"] if "AirGradient" not in sources else [])] + + +def alerts(sources: list[str]) -> list[dict]: + """The alerts there are for these sources, each {kind, name, what, rule, thresholds}.""" + rules = alert_rules() + return [{"kind": kind, "name": name, "what": ALERT_WORDS[kind], "rule": rules[kind][0], "thresholds": rules[kind][1]} + for kind, (name, source) in TYPES.items() if source in sources] + + +def measure_lines(sources: list[str]) -> list[str]: + """What is measured, as the bot's Help lists it (lib/templates.py capabilities_text): a short bullet each.""" + return [f"• {line}" for line in [*(line for name, measured in MEASURES.items() if name in sources for line in measured), + "History charts"]] + + +def tools(ctx: Context) -> list[ServiceTool]: + """The about tool: always there.""" + return [AboutTool(ctx).tool()] + + +__all__ = ["ALERT_COOLDOWN_MINUTES", "ALERT_WORDS", "AboutTool", "DESCRIPTION", "MEASURES", "NEVER_AVAILABLE", "RAIN_QUIET_HOURS", + "TYPES", "WITHOUT", "alert_rules", "alerts", "held_on", "history_of", "measure_lines", "not_available", "tools"] diff --git a/lib/service/alerts.py b/lib/service/alerts.py new file mode 100644 index 00000000..630dfb05 --- /dev/null +++ b/lib/service/alerts.py @@ -0,0 +1,56 @@ +"""The service's alert rules (docs/ecobot-mcp.md 3.6), each on the trigger it has: the weather alerts after every refresh of the station +(and the rain on each live reading), particulates every CHECK_SECONDS, pollen and the forecast after each refresh of their pages. Their +settings (quiet hours, cooldown) are the service's config, their state its own store (lib/alerts/store.py, alert_state.json), and what +they decide goes to the alert log (lib/alert_log.py), which clients read: they know nothing of chats or Telegram. + +The irrigation controller's alerts are not here: they move to its own server (step 5).""" + +import logging + +from ..alerts.forecast import ForecastMonitor +from ..alerts.particulates import CHECK_SECONDS, ParticulatesMonitor +from ..alerts.pollen_and_asthma import PollenAndAsthmaMonitor +from ..alerts.weather import ALERT_COOLDOWN_SECONDS, WeatherMonitor +from ..warm import every + +log = logging.getLogger(__name__) + + +class AlertRules: + def __init__(self, sources: dict, store, alerts, cooldown_seconds: int = ALERT_COOLDOWN_SECONDS, quiet: tuple[int, int] | None = None, + service=None): + """sources: by name (Ecowitt, AirGradient, Pollen, Forecast; those that started). store: the rules' state (AlertStore). alerts: the + alert log. service: the service's tools, which draw the alerts' charts.""" + self.sources, self.store, self.alerts = sources, store, alerts + eco, air = sources.get("Ecowitt"), sources.get("AirGradient") + self.weather = WeatherMonitor(eco, store, alerts, cooldown_seconds, quiet, service) if eco else None + self.particulates = ParticulatesMonitor(air, store, alerts, service) if air else None + self.forecast = ForecastMonitor(sources["Forecast"], store, alerts) if "Forecast" in sources else None + 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.""" + 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 + if self.pollen: + self.sources["Pollen"].warmer.after.append(self.pollen.check) # after each refresh (in the day) + running += PollenAndAsthmaMonitor.KINDS + return running + + 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.""" + if not self.weather: + return + eco = self.sources["Ecowitt"] + await self.weather.init() + eco.warmer.after.append(self.weather.check) # checked on every fresh refresh + running[:0] = WeatherMonitor.KINDS + await self.weather.check() + if eco.fast is not None: # Home Assistant: the rain alert looks at each new reading as it comes in, not only at the minute's refresh + eco.on_live.append(self.weather.check_rain) diff --git a/lib/service/common.py b/lib/service/common.py new file mode 100644 index 00000000..eac9a708 --- /dev/null +++ b/lib/service/common.py @@ -0,0 +1,356 @@ +"""What every service tool shares (docs/ecobot-mcp.md 3.2, 3.7): how a tool is made and what it is sent, how it reads a period, and +the shape of what it answers. + +A tool is a ServiceTool: its handler is `handler(args, meta)`, the arguments as sent and the request's metadata (`request_meta`), and +nothing else about the question. In the bot, `ServiceTool.tool()` makes it a lib.tools.Tool that reads only `Turn.meta` (and +`Turn.ahead`, the old name for a background request); over MCP, `meta` is the request's `_meta`. + +Every answer is compact JSON (`answer`), and starts the same way: + + {"period": {"asked": "this week", "text": "the last 7 days: Wed 4 – Tue 10 Nov 2026", + "start": "2026-11-04T00:00:00+11:00", "end": "2026-11-10T14:05:00+11:00", "cut": "to Mon 9 Nov: today isn't over"}, + "as_of": {"text": "Tue 10 Nov 2026 2:05pm", "time": "2026-11-10T14:05:00+11:00"}, + "fresh": FRESH, + ... the tool's own fields ..., + "chart_note": CHART_NOTE, "charts": [...]} + + - `period`: how the words were read (lib/periods_text.Period): `asked` the words (or "start/end"), `text` how they were read, ready + to pass on, `start` and `end` ISO local times with their offset (the end not included), `cut` only when a whole-day tool cut + today off, and `note` only when `start` and `end` were sent beside `period` and set aside (read_period). Left out by a tool that takes no period. + - `as_of`: the time of the figures, `text` written as the tools write a time (timeutil.when), `time` ISO. + - `fresh`: one fixed line for the model: the figures are as of `as_of`, and a follow-up or a challenge needs the tool called again. + - `chart_note` and `charts` (`with_charts`): the charts as data (specs.to_json, bucketed to the request's `chart_points`), and the + one line that tells the model what to do with them. Left out when there is no chart. + - `reply` and `complete: true` (`complete`), only when the chart is the whole answer (3.7, `chart_answers_it`). + +A refusal is `{"error": message, ...what teaches the right call}` (`refuse`). A handler can raise Refusal anywhere instead: the tool +answers with its JSON. A period that isn't one of the forms is refused with each form and what it means now (`refuse_period`). +""" + +import inspect +from collections.abc import Awaitable, Callable +from dataclasses import dataclass, replace +from datetime import date, datetime, timedelta, tzinfo + +from .. import specs +from ..periods_text import Period, PeriodError, read_period as read_words +from ..timeutil import clock_text, day_text +from ..tools import Tool, Turn, json_result + +# ---------- the request's metadata ---------- +CHART_POINTS = 150 # the most points a line of a chart is sent in, unless the request asks for more (3.7): enough for a model to redraw +MAX_CHART_POINTS = 500 # the most a request may ask for: today's drawing budget (lines.POINT_BUDGET) +AS_DRAWN = "drawn" # chart_points asking for every point as the chart was drawn, unbucketed: what the bot asks for, so its pictures + # are as they were (a chart of each day's average over years has more points than the budget) +NORMAL, BACKGROUND = "normal", "background" # priority: someone is waiting, or the work is ahead of need (a chart drawn ahead) +META = {"chart_points": CHART_POINTS, "fetch": True, "priority": NORMAL} # each key a handler reads, with its default + + +def request_meta(raw: dict | None = None) -> dict: + """The request's metadata as a handler reads it: every key in META, each checked, defaulted where missing or not understood; any + other key passed on as it came. + - chart_points: the most points a chart's line is sent in, a whole number from 2 to MAX_CHART_POINTS (default CHART_POINTS), or + AS_DRAWN ("drawn"): every point, as the chart was drawn (a client that draws for itself, as the bot does); + - fetch: False answers from what is held, fetching nothing that is missing (default True); + - priority: "background" for work nobody is waiting on (a chart drawn ahead), whose requests wait their turn; else "normal".""" + raw = dict(raw) if isinstance(raw, dict) else {} + points = raw.get("chart_points") + try: + points = AS_DRAWN if points == AS_DRAWN else CHART_POINTS if points is None or isinstance(points, bool) else \ + min(max(int(points), 2), MAX_CHART_POINTS) + except (TypeError, ValueError): + points = CHART_POINTS + fetch = raw.get("fetch", True) + fetch = not (fetch is False or str(fetch).strip().lower() in ("false", "0", "no", "off")) + priority = BACKGROUND if str(raw.get("priority") or "").strip().lower() == BACKGROUND else NORMAL + return {**raw, "chart_points": points, "fetch": fetch, "priority": priority} + + +def turn_meta(turn: Turn | None) -> dict: + """The metadata of a question the bot asks: Turn.meta, a chart drawn ahead (Turn.ahead) being a background request.""" + if turn is None: + return request_meta() + raw = dict(turn.meta) + if turn.ahead and "priority" not in raw: + raw["priority"] = BACKGROUND + return request_meta(raw) + + +# ---------- refusals ---------- +def refuse(message: str, **teach) -> str: + """A refusal as a tool answers it: {"error": message, ...teach}, where `teach` is whatever lets a model correct its call once, from + the error alone (the names it could have sent, the forms of a period, the interval that fits).""" + if "error" in teach: + raise ValueError("a refusal's message is its `error`") + return json_result({"error": message, **teach}) + + +class Refusal(ValueError): + """A call refused, with what teaches the right one. Raised anywhere in a handler, it becomes the tool's answer (`text`).""" + + def __init__(self, message: str, **teach): + super().__init__(message) + self.message, self.teach = message, teach + + @property + def text(self) -> str: + return refuse(self.message, **self.teach) + + @classmethod + def of_period(cls, e: PeriodError) -> "Refusal": + """A period that can't be read: its message (which ends with the time now) and, when the words were none of the forms, each form + with what it means now, as {form: meaning}.""" + return cls(e.message, **({"forms": dict(e.forms)} if e.forms else {})) + + +def refuse_period(e: PeriodError) -> str: + """A PeriodError as a tool answers it: {"error": message, ["forms": {form: what it means now}]}.""" + return Refusal.of_period(e).text + + +# ---------- a tool ---------- +Handler = Callable[[dict, dict], Awaitable[str] | str] + + +@dataclass +class ServiceTool: + """A tool of the service: its name, the description a model reads, its input schema, and `handler(args, meta)`, which answers with + a string (`answer`, `refuse`) or raises Refusal. It may be a coroutine function. It is sent nothing else about the question.""" + name: str + description: str + parameters: dict # the input schema: {"type": "object", "properties": {...}, "required": [...]} + handler: Handler + read_only: bool = True # MCP's readOnlyHint: every tool of the service only reads + open_world: bool = False # MCP's openWorldHint: it asks a device or a cloud for what the file lacks (unless meta `fetch` is False) + + @property + def annotations(self) -> dict: + return {"readOnlyHint": self.read_only, "openWorldHint": self.open_world} + + async def call(self, args: dict | None = None, meta: dict | None = None) -> str: + """Run it with these arguments and this request metadata (request_meta fills in the rest); a Refusal comes back as its JSON.""" + if args is not None and not isinstance(args, dict): + return refuse("The arguments must be a JSON object of the tool's parameters.") + try: + out = self.handler(dict(args or {}), request_meta(meta)) + return await out if inspect.isawaitable(out) else out + except Refusal as e: + return e.text + + def tool(self) -> Tool: + """The tool as the bot's Tools runs it: its handler reads only the Turn's metadata (turn_meta).""" + async def handle(args: dict, turn: Turn | None = None) -> str: + return await self.call(args, turn_meta(turn)) + return Tool(self.name, self.description, self.parameters, handle) + + +# ---------- periods ---------- +PERIOD_FORMS = ("today, yesterday, last N minutes (N min), last N hours/days/weeks/months/years (or Nh, Nd, Nw, Nm, Ny: 3m is 3 " + "months, never minutes), this week, last week, week to date, " + "this month, last month, this year, last year, a month or a year (October, October 2025, 2025), a date (5 Sep, " + "2026-09-05), a weekday (Saturday), this morning, yesterday afternoon, last night, since 6am, a public holiday " + "(Christmas Day), on record, A to B (June to August)") +WHOLE_DAY_FORMS = ("yesterday, last N days/weeks/months/years (or Nd, Nw, Nm, Ny: 3m is 3 months), this week, last week, week to date, this month, " + "last month, this year, last year, a month or a year (October, October 2025, 2025), a date (5 Sep, 2026-09-05), " + "a weekday (Saturday), a public holiday (Christmas Day), on record, A to B (June to August)") + + +def period_properties(default: str, whole_days: bool = False) -> dict: + """The `period`, `start` and `end` of a tool's input schema, described for a model: the person's words passed on unchanged, the + forms the service reads, or else dates on the station's clock; for a whole-day tool, whole days up to yesterday. `default` is what + the description says is read when nothing is sent: usually the words given to read_period as its default ("last 24 hours", "on + record"), or more ("today; with a chart, the last 24 hours").""" + if whole_days: + forms, days = WHOLE_DAY_FORMS, (" Whole days only, up to yesterday, as today isn't over: a rolling period is that many whole days " + "to yesterday (\"last 7 days\" is the 7 days before today).") + start = "Instead of `period`, never with it: the first day, 'YYYY-MM-DD'." + end = "With `start`: the last day, 'YYYY-MM-DD', up to yesterday. Default: yesterday." + else: + forms, days = PERIOD_FORMS, "" + start = ("Instead of `period`, never with it: when it starts, the station's local time, 'YYYY-MM-DD' (from midnight) or " + "'YYYY-MM-DD HH:MM'.") + end = "With `start`: when it ends, local time, 'YYYY-MM-DD' (to the end of that day) or 'YYYY-MM-DD HH:MM'. Default: now." + return { + "period": {"type": "string", "description": "The period in the person's own words, passed on unchanged (\"this week\", \"in the " + "last year\", \"past two years\"): the service reads them, and the result says how. Any number " + "works (\"31d\", \"45 days\", \"18 months\", \"last 90 minutes\"): never refuse or round a " + "period without calling; if the service can't read one, its answer says so. \"past week\" (the " + "last 7 days) is never sent as \"last week\" (the previous Monday to Sunday). " + f"Forms: {forms}.{days} Default: {default}."}, + "start": {"type": "string", "description": start}, + "end": {"type": "string", "description": end}, + } + + +IGNORED_DATES = ("`start` and `end` were ignored: `period` was sent too, and they can't be read as dates or times. The period is read " + "from `period`.") +SAME_DATES = "`start` and `end` were set aside: `period` was sent too, and they read as the same span. The period is read from `period`." +SET_ASIDE = ("`start` and `end` were set aside because `period` was sent too: send them without `period` to use them, or send a " + "`period` in one of the forms.") +SAME_WITHIN = timedelta(minutes=15) # start/end this close to the period's span at both ends read as the same span + + +def sends_period(args: dict) -> bool: + """Whether the call sends `period` (words, not empty): a call read at all then reads its period from it (read_period).""" + return args.get("period") is not None and str(args["period"]).strip() != "" + + +def _sent(x) -> str | None: + return str(x).strip() if x is not None and str(x).strip() else None + + +def _a_moment(text: str | None) -> bool: + """Is it readable as a date or a time ('YYYY-MM-DD', 'YYYY-MM-DD HH:MM', ISO with an offset)?""" + try: + datetime.fromisoformat(text) + except (TypeError, ValueError): + return False + return True + + +def _moment_text(t: datetime, whole_days: bool, words: bool = False) -> str: + """A start as a call sends it ('YYYY-MM-DD', or with ' HH:MM' when it isn't midnight and the tool takes times), or in words.""" + at_midnight = t.time() == datetime.min.time() + if words: + return day_text(t) if at_midnight else f"{day_text(t)} {clock_text(t)}" + return f"{t:%Y-%m-%d}" if whole_days or at_midnight else f"{t:%Y-%m-%d %H:%M}" + + +def _span(text: str) -> str: + """A Period's text without its label: "the last 7 days: Wed 4 – Tue 10 Nov 2026" -> "Wed 4 – Tue 10 Nov 2026".""" + return text.rsplit(": ", 1)[-1] + + +def read_period(args: dict, *, tz: tzinfo, now: datetime, default: str, whole_days: bool = False, + first_held: date | datetime | None = None) -> Period: + """The period a call asks for, from its `period`, or `start` and `end`, else `default` (words), read by lib/periods_text.py at `now` + (aware, or naive on the station's clock) in the station's zone. `first_held`: the first reading held for the readings asked about + ("on record"). Raises Refusal (refuse_period) when the period can't be read. + + `period` with `start`/`end` beside it (a model may fill in every argument it sees, sometimes with junk such as 'count_only'): + - start/end that aren't dates or times (each sent one read by datetime.fromisoformat): the period is read, its `note` says the + dates were ignored (IGNORED_DATES); + - start/end that read as the same span as the period (within SAME_WITHIN at each end; "on record" from the first reading held): + the period is read, with the note SAME_DATES; + - start/end that read as another span: refused, naming both spans as read, so the model sends the one it meant; + - a period that can't be read beside readable start/end: refused, its forms listed and SET_ASIDE added. + A note on the period keeps a chart from answering the question by itself (summary, days: the model reads the note).""" + period, start, end = (_sent(args.get(k)) for k in ("period", "start", "end")) + both = period is not None and (start is not None or end is not None) + dates = both and all(_a_moment(x) for x in (start, end) if x is not None) + + def read(p, s, e) -> Period: + return read_words(p, s, e, now=now, tz=tz, default=default, whole_days=whole_days, first_held=first_held) + + try: + words = read(period, None, None) if both else read(period, start, end) + except PeriodError as e: + if dates and e.forms: # the words aren't a form: say why the dates weren't used + raise Refusal(f"{e.message} {SET_ASIDE}", forms=dict(e.forms)) from None + raise Refusal.of_period(e) from None + if not both: + return words + if not dates: + return replace(words, note=IGNORED_DATES) + try: + as_dates = read(None, start or _moment_text(words.start, whole_days), end) # (`end` alone: from the period's start) + except PeriodError as e: + why = e.message if start else f"`end` {end!r} is before the period's start." + raise Refusal(f"`period` {period!r} is {_span(words.text)}, and `start`/`end` can't be read as this tool takes them: " + f"{why} Send one of them.") from None + floor = None if first_held is None else first_held if isinstance(first_held, datetime) else \ + datetime.combine(first_held, datetime.min.time(), tzinfo=tz) + if floor is not None and floor.tzinfo is None: + floor = floor.replace(tzinfo=tz) + starts = [p.start if floor is None else max(p.start, floor) for p in (words, as_dates)] + if abs(starts[0] - starts[1]) <= SAME_WITHIN and abs(words.end - as_dates.end) <= SAME_WITHIN: + return replace(words, note=SAME_DATES) + said = f"{_moment_text(as_dates.start, False, words=True)} – now" if not end and not whole_days else _span(as_dates.text) + raise Refusal(f"`period` {period!r} is {_span(words.text)} but `start`/`end` say {said}: send one of them (`period` alone, or " + f"`start` and `end` without it).") + + +# ---------- an answer ---------- +FRESH = ("These figures are as of `as_of`. A follow-up or a challenge (\"that's wrong, it was cooler\") needs this tool called again: " + "never answer it from these.") +HEAD = ("period", "as_of", "fresh") # the keys every answer starts with (a tool's own fields can't take them) + + +def iso(t: datetime | int | float, tz: tzinfo | None = None) -> str: + """A time as the service writes it for an application: ISO local time with its UTC offset, to the second ("2026-11-10T14:05:00+11:00"). + `t` is an aware datetime (written in its own zone), or an epoch written in `tz`.""" + if isinstance(t, datetime): + if t.tzinfo is None: + raise ValueError(f"a time needs its zone: {t!r}") + return t.isoformat(timespec="seconds") + if tz is None: + raise ValueError("an epoch needs the zone to write it in") + return datetime.fromtimestamp(t, tz).isoformat(timespec="seconds") + + +def period_field(period: Period) -> dict: + """{"asked", "text", "start", "end", ["cut"], ["note"]}: how the period was read.""" + out = {"asked": period.asked, "text": period.text, "start": iso(period.start), "end": iso(period.end)} + if period.cut: + out["cut"] = period.cut + if period.note: + out["note"] = period.note + return out + + +def as_of_field(as_of: datetime) -> dict: + """{"text": "Tue 10 Nov 2026 2:05pm", "time": ISO}: the time of the figures (aware, written in its own zone: the station's).""" + return {"text": f"{day_text(as_of)} {clock_text(as_of)}", "time": iso(as_of)} + + +def answer(*, period: Period | None, as_of: datetime | None, **fields) -> str: + """A tool's answer as compact JSON: `period` (period_field) and `as_of` (as_of_field) with the FRESH line, then the tool's own fields + in the order given. A tool with no period (current, outlook) passes None, and one with no figures (about) None for `as_of`.""" + if clash := set(HEAD) & set(fields): + raise ValueError(f"an answer's own fields can't be named {', '.join(sorted(clash))}") + head = {} + if period is not None: + head["period"] = period_field(period) + if as_of is not None: + head["as_of"], head["fresh"] = as_of_field(as_of), FRESH + return json_result({**head, **fields}) + + +# ---------- charts ---------- +CHART_NOTE = "The chart's data is in `charts`: draw it if you can, and keep your text to the figures. Don't describe the chart." + + +def charts_field(charts: list[specs.Chart], tz: tzinfo, meta: dict | None = None) -> list[dict]: + """The charts as data (specs.to_json, schemas/chart.json), each line bucketed to the request's `chart_points` (default CHART_POINTS, + at most MAX_CHART_POINTS; AS_DRAWN: as drawn), times local to `tz`.""" + points = request_meta(meta)["chart_points"] + return [specs.to_json(chart, tz, max_points=None if points == AS_DRAWN else points) for chart in charts] + + +def with_charts(charts: list[specs.Chart], tz: tzinfo, meta: dict | None = None) -> dict: + """The fields an answer with charts ends with, {"chart_note": CHART_NOTE, "charts": charts_field(...)}; {} with no chart: + answer(..., **with_charts(charts, tz, meta)).""" + return {"chart_note": CHART_NOTE, "charts": charts_field(charts, tz, meta)} if charts else {} + + +def charts_as_titles(out: dict, note: str) -> dict: + """An answer with its charts' data left out: `charts` as [{title, period}] and `chart_note` as `note` (the chart goes another way: + the bot sends it, or the service attaches its image), everything else as it is. An answer without charts as it is.""" + if not isinstance(out.get("charts"), list): + return out + told = {**out, "charts": [{"title": c.get("title"), "period": c.get("period")} for c in out["charts"] if isinstance(c, dict)]} + if "chart_note" in out: + told["chart_note"] = note + return told + + +def complete(reply: str) -> dict: + """The fields of an answer that is complete (3.7: `chart_answers_it` set and a chart made, with no error and no note that needs + the model's words): {"reply": the finished reply for the person, "complete": True}. A client may send `reply` with the chart and end + the turn; over MCP the server sends it as a text block for the user and marks the result `ecobot/complete`.""" + return {"reply": reply, "complete": True} + + +__all__ = ["AS_DRAWN", "BACKGROUND", "CHART_NOTE", "CHART_POINTS", "FRESH", "IGNORED_DATES", "SAME_DATES", "SET_ASIDE", "MAX_CHART_POINTS", "META", "NORMAL", "PERIOD_FORMS", "Refusal", + "ServiceTool", "WHOLE_DAY_FORMS", "answer", "as_of_field", "charts_as_titles", "charts_field", "complete", "iso", "period_field", "period_properties", + "read_period", "refuse", "sends_period", "refuse_period", "request_meta", "turn_meta", "with_charts"] diff --git a/lib/service/context.py b/lib/service/context.py new file mode 100644 index 00000000..5ae656f0 --- /dev/null +++ b/lib/service/context.py @@ -0,0 +1,48 @@ +"""What the service's tools are built over: the sources that started, the file, the catalogue of readings, the station's zone and the +clock. Each tool module has `tools(ctx) -> list[ServiceTool]`, so the ten are built the same way, here today and behind MCP later.""" + +import time +from collections.abc import Callable +from dataclasses import dataclass, field +from datetime import datetime, tzinfo + +from ..timeutil import to_local +from .names import Catalogue + + +@dataclass +class Context: + eco: object | None = None # the weather station (lib.ecowitt.Ecowitt), started; None when it isn't configured + air: object | None = None # the air sensor (lib.airgradient.AirGradient), started; None when it isn't configured + composer: object | None = None # the charts and comparisons across the two (lib.compose.Composer), when both are there + forecast: object | None = None # lib.forecast.Forecast, when switched on + pollen: object | None = None # lib.pollen.Pollen, when switched on + catalogue: Catalogue | None = None # the readings the file holds (names.Catalogue.open); None: every reading the service knows + tz: tzinfo | None = None # the station's zone (the station's own, once it has named it) + clock: Callable[[], float] = field(default=lambda: time.time()) # the time now, as an epoch (a test's own) + + @property + def storage(self): + """The readings file the sources share.""" + return self.eco.storage if self.eco else self.air.store.storage if self.air else None + + @property + def zone(self) -> tzinfo: + return self.tz or (self.eco.tz if self.eco else self.air.tz) + + def now(self) -> datetime: + """The time now, aware, in the station's zone.""" + return to_local(int(self.clock()), self.zone) + + def readings(self) -> Catalogue: + from .names import CATALOGUE + return self.catalogue or CATALOGUE + + @classmethod + async def open(cls, *, eco=None, air=None, composer=None, forecast=None, pollen=None, **more) -> "Context": + """The context with the catalogue read from the file.""" + return cls(eco=eco, air=air, composer=composer, forecast=forecast, pollen=pollen, + catalogue=await Catalogue.open(eco, air), **more) + + +__all__ = ["Context"] diff --git a/lib/service/current.py b/lib/service/current.py new file mode 100644 index 00000000..c2483bb0 --- /dev/null +++ b/lib/service/current.py @@ -0,0 +1,663 @@ +"""The `current` tool (docs/ecobot-mcp.md 3.3): how it is now, from the weather station and the air sensor, every reading or the ones +named, and with `context` today's, this month's and this year's highs and lows beside each reading, as the gauges show them. It replaces +weather_now and air_quality without dates (and the gauges' figures), on their engines: + + - the station's reading is its live reading as the gauges and weather_now read it (Ecowitt._live_data: the kept reading while it + is fresh, else a request; raw {group: {field: {value, unit, time}}}), each reading with its value, unit, its text as weather_now writes + it ("12.3 °C") and its glance emoji (lib/ecowitt/glance.py), when the reading is one to notice; + - the air sensor's is AirGradient.latest(): value, unit, rating (held at the better level until two readings agree), PM2.5's US AQI and + 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 + 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. + +`lines` are each device's readings as bullets, worded as the bot's report, "weather now" and plain lookups word them today +(the old lib/report.py weather_lines, air_lines, reading_lines, ported here with the same words): every reading (none named) in the report's +layout, else a line for each reading named. `headings` are the report's section headings, with the time of each device's reading. So a +client's report is current's headings and lines, then forecast's (today) and pollen's. + +The request's `fetch` False answers from the readings held (the station's kept live reading, whatever its age, and the air sensor's +latest); `priority` "background" asks the station behind the readings someone is waiting for. There are no charts. +""" + +import logging +import re +from dataclasses import dataclass, field, replace +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.days import FIELDS, PARTS, day_values_on +from ..ecowitt.direction import point +from ..ecowitt.extremes import describe_time +from ..ecowitt.glance import glance, solar_band +from ..series import AIR, INDOOR_READINGS, WEATHER +from ..storage.catalogue import BY_NAME, column_of, kind_of, text as written +from ..storage.read import Reader +from ..timeutil import clock_text, day_text, to_local +from .common import BACKGROUND, Refusal, ServiceTool, answer, request_meta +from .context import Context +from .names import AIR_DEVICE, CATALOGUE, STATION, Catalogue, Reading, _split + +log = logging.getLogger(__name__) + +NAME = "current" +ARGUMENTS = ("readings", "context") +ANOTHER_TIME = ("period", "start", "end") # a call about another time than now: summary's or readings' +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."} +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 + +# ---------- the description and the input schema ---------- +DESCRIPTION = ( + "How it is now, from the weather station (Ecowitt) and the air sensor (AirGradient): every reading, or those named. Everything now " + "(\"weather now\", \"how's it outside\"): {}. How hot is it: {readings: [\"temperature\"]}. Is it raining: {readings: [\"rain\"]}. " + "The air now: {readings: [\"air\"]}. With today's, this month's and this year's highs and lows beside each reading, as gauges show " + "them (rain: its totals and wettest day; wind: its highest gust): {context: true}. A report, status or sitrep: current, forecast " + "(period \"today\") and pollen, called together. Not for: will it rain (outlook); a period's highs, lows (\"lowest and highest " + "humidity\"), averages or a chart, " + "a device or reading with a period, \"ecowitt week\", \"weather week\" (summary); values at set times (readings); the days ahead (forecast). Result: sensors.<sensor>.<reading> (sensors.outdoor." + "temperature) with value, unit, text ready to quote (\"12.3 °C\") and emoji when the reading is one to notice (put it right " + "before the reading); rainfall.rain is today's rain so far; wind_direction has its compass point; the air " + "sensor's have their rating (put it beside the value), PM2.5 and PM10 a US aqi_us and band (the AQI: the higher). With context: " + "today, month and year, each " + "with high and low (_text to quote, _when copied as written, _date the day). lines: each " + "device's readings as bullet lines, to pass on as they are (headings for a report). missing: readings asked " + "for that aren't being read now; unavailable: a device not answering.") +CONTEXT = {"type": "boolean", "description": "true to add today's, this month's and this year's highs and lows beside each of the " + "weather station's readings that has them (temperature, humidity, pressure, dew point, " + "feels like, wind's highest gust, rain's totals and wettest day, rain rate, solar, UV, " + "indoor temperature and humidity) and the air sensor's air-quality readings. Default " + "false."} + + +def parameters(description: str) -> dict: + """The input schema, its readings described by the catalogue the tool reads (`description`).""" + return {"type": "object", "properties": { + "readings": {"type": "array", "items": {"type": "string"}, + "description": f"{description} Default: every reading the station and the air sensor have now."}, + "context": CONTEXT}} + + +# ---------- the words, as the old lib/report.py wrote them ---------- +def _zero(text: str | None) -> bool: + """Is this reading missing or zero ("0.0 W/m²", "0")?""" + try: + return not text or float(text.split()[0]) == 0 + except ValueError: + return False + + +def _band(solar: str | None) -> str: + """" (medium)" for a solar reading like "40.2 W/m²"; nothing when it can't be read.""" + try: + return f" ({solar_band(float(solar.split()[0]))})" + except (AttributeError, IndexError, ValueError): + return "" + + +def _join(parts: list[str | None], sep: str = ", ") -> str: + return sep.join(p for p in parts if p) + + +def _getters(now: dict): + """(get, tag) for a weather_now-shaped reading ({group: {field: "12.3 ℃"}, "emoji": {"group.field": emoji}}): a reading's text, and + the same with its emoji (if it has one) before it.""" + emoji = now.get("emoji") or {} + + def get(group: str, field: str) -> str | None: + return unit_text((now.get(group) or {}).get(field)) + + def tag(group: str, field: str, text: str | None = None) -> str | None: + text = text or get(group, field) + return f"{emoji[f'{group}.{field}']} {text}" if text and f"{group}.{field}" in emoji else text + return get, tag + + +def _rain(now: dict) -> str: + """Today's rain, the month's and, while it rains, the rate: "☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)".""" + get, tag = _getters(now) + rate, month = get("rainfall", "rain_rate"), get("rainfall", "monthly") + return _join([_join([tag("rainfall", "daily"), f"(month total {month})" if month else None], " "), + None if _zero(rate) else tag("rainfall", "rain_rate", f"raining ({rate})")], "; ") + + +def _wind(now: dict) -> str | None: + """The wind, where it comes from and its gusts: "14.0 km/h from 131°, gust 31.0 km/h"; None when it is calm.""" + get, tag = _getters(now) + if _zero(get("wind", "wind_speed")) and _zero(get("wind", "wind_gust")): + return None + direction, gust = get("wind", "wind_direction"), tag("wind", "wind_gust") + return _join([_join([tag("wind", "wind_speed"), f"from {direction}" if direction else None], " "), f"gust {gust}" if gust else None]) + + +def weather_lines(now: dict) -> list[str]: + """The weather station's bullets, the report's and "weather now"'s: an emoji sits right before the reading it is keyed to.""" + get, tag = _getters(now) + solar, uvi = get("solar_and_uvi", "solar"), get("solar_and_uvi", "uvi") + sun = _join([None if _zero(solar) else tag("solar_and_uvi", "solar", f"solar radiation {solar}{_band(solar)}"), # night: no sun line + None if _zero(uvi) else tag("solar_and_uvi", "uvi", f"UV index {uvi}")]) + bullets = [("Outdoor", _join([tag("outdoor", "temperature"), tag("outdoor", "humidity")])), # (dew point and VPD are there to ask for) + ("Indoor", _join([tag("indoor", "temperature"), tag("indoor", "humidity")])), + ("Pressure", tag("pressure", "relative")), + ("Rain today", _rain(now)), + ("Sun", sun), + ("Wind", _wind(now))] # calm: no line + return [f"• {name}: {text}" for name, text in bullets if text] + + +def air_shown(key: str, value: float, unit: str) -> str: + """An air reading as the report writes it: "1.4 µg/m³", "433 ppm", "88" (VOC), "1.0" (NOx); the sensor's own temperature and + humidity as the station's are ("18.5 °C", "60 %").""" + if key in AIR_OWN_METRICS: + return f"{value:.1f} {unit}" if unit == "°C" else f"{value:.0f} {unit}" + return (f"{value:.1f} {unit}" if unit.startswith("µg") else f"{value:.0f} {unit}" if unit == "ppm" + else f"{value:.1f}" if key == "nox_index" else f"{value:.0f}") + + +def air_lines(air: dict, only: list[str] | None = None) -> list[str]: + """The air sensor's bullets from its latest reading (AirGradient.latest()), those in `only` (all when None), as the report writes them.""" + out = [] + for key, label in ((name, m.label) for name, m in AIR.items()): + entry = air.get(key) if only is None or key in only else None + if not isinstance(entry, dict) or entry.get("value") is None: + continue + aqi = f" (AQI {entry['aqi_us']})" if "aqi_us" in entry else "" # (PM2.5's and PM10's: the US AQI is the higher) + out.append(f"• {label}: {_join([air_shown(key, entry['value'], entry.get('unit', '')), entry.get('rating')], ' ')}{aqi}") + return out + + +def reading_lines(now: dict, names: list[str], sides: list[str]) -> list[str]: + """Just the readings asked about (lib/series.py's names: "how hot is it": the temperature, indoors and out), as the bot's plain + lookup writes them.""" + get, tag = _getters(now) + lines = [] + for name in names: + reading = WEATHER[name] + if name in ("temperature", "humidity"): # a line for each side asked about; the temperature with what it feels like + for side in sides: + feels = get(side, "feels_like") if name == "temperature" else None + if text := _join([tag(side, reading.field), f"feels like {feels}" if feels else None]): + lines.append(f"• {side.capitalize()}: {text}") + elif name == "wind": + lines.append(f"• Wind: {_wind(now) or 'calm'}") + elif name == "rain": + lines.append(f"• Rain today: {_rain(now) or 'none'}") + else: + group = sides[0] if name in INDOOR_READINGS and len(sides) == 1 else reading.group # "indoor dew point": that sensor's + if text := tag(group, reading.field): + lines.append(f"• {reading.label}{' (indoor)' if group == 'indoor' else ''}: {text}") + return lines + + +def _stamp(at: datetime, today: date) -> str: + """"11:45pm", with its day when that isn't today ("Sat 10 Oct 11:45pm").""" + return clock_text(at) if at.date() == today else f"{day_text(at, year=False)} {clock_text(at)}" + + +def heading(device: str, at: datetime | None, today: date) -> str: + """"Weather station (2:21am)": the report's heading of a device's section, with the time of its reading when it has one.""" + return f"{HEADINGS[device]} ({_stamp(at, today)})" if at else HEADINGS[device] + + +# ---------- the station's live reading ---------- +def now_shaped(live: dict, tz: tzinfo) -> tuple[dict, int]: + """(weather_now's result from a live reading, {group: {field: "12.3 ℃"}, "emoji": {"group.field": emoji}}, as Ecowitt's + weather_now tool makes it; the time of the newest reading in it, an epoch, 0 for none).""" + out, newest, emoji = {}, 0, {} + for group, fields in live.items(): + for name, obj in (fields.items() if isinstance(fields, dict) else ()): + if isinstance(obj, dict) and "value" in obj: + out.setdefault(group, {})[name] = f"{obj['value']} {obj.get('unit', '')}".strip() + try: + if tag := glance(group, name, float(obj["value"])): + emoji[f"{group}.{name}"] = tag + except (TypeError, ValueError): + pass + try: + newest = max(newest, int(obj.get("time") or 0)) + except (TypeError, ValueError): + pass + return {**out, **({"emoji": emoji} if emoji else {})}, newest + + +def _resolve(catalogue, names, *, default) -> list[Reading]: + """The readings named, as the catalogue reads them; a reading's full name that the file hasn't recorded yet but the service knows + (names.CATALOGUE) counts too, since current answers from the reading now (a new station's first minutes, a gauge's reading).""" + known = [w for w in _split(names) if " ".join(w.lower().split()) not in catalogue and " ".join(w.lower().split()) in CATALOGUE] + if not known: + return catalogue.resolve(names, default=default) + out: dict[str, Reading] = {} + for word in _split(names): + exact = " ".join(word.lower().split()) + for r in [CATALOGUE.get(exact)] if word in known else catalogue.resolve(word, default=[]): + out.setdefault(r.name, r) + return list(out.values()) + + +def unrecorded(live: dict, listed: set[str]) -> list[Reading]: + """The station's readings in its live reading that aren't among these names (the catalogue's: what its file has recorded), as the + catalogue would name them once recorded: a sensor sending, or a reading sent, since the file last took the station's fields.""" + sent = {group: {name: obj.get("unit", "") for name, obj in fields.items() if isinstance(obj, dict) and "value" in obj} + for group, fields in live.items() if isinstance(fields, dict)} + return [r for r in Catalogue.of({g: f for g, f in sent.items() if f}, air=False) + if r.sensor in sent and r.name not in listed and live_field(live, r) is not None] + + +def live_field(live: dict, reading: Reading) -> str | None: + """The live reading's own name for a catalogue reading in its group ("daily" for rainfall.rain, "app_tempin" for indoor.app_temp), + or None when the live reading lacks it.""" + for name, obj in (live.get(reading.sensor) or {}).items(): + if isinstance(obj, dict) and "value" in obj and column_of(reading.sensor, name) == (reading.column, "value"): + return name + return None + + +def _number(raw) -> float | int | None: + """A reading as a number ("94" -> 94, "12.3" -> 12.3); None when it isn't one.""" + try: + value = float(raw) + except (TypeError, ValueError): + return None + return int(value) if re.fullmatch(r"\s*-?\d+\s*", str(raw)) else value + + +def station_entry(live: dict, now: dict, reading: Reading, field: str) -> dict: + """{value, unit, text, [emoji], [compass]} of one of the station's readings now.""" + obj = live[reading.sensor][field] + entry = {"value": _number(obj["value"]), "unit": unit_text(obj.get("unit")) or "", # (as its text has it: the UV index has none) + "text": unit_text(now[reading.sensor][field])} + if emoji := (now.get("emoji") or {}).get(f"{reading.sensor}.{field}"): + entry["emoji"] = emoji + if reading.reading == "wind_direction" and entry["value"] is not None: + entry["compass"] = point(entry["value"]) + return entry + + +# ---------- 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.""" + 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) + + +def _times_on(r: Reader, mac: str, names: list[str], days: list[date]) -> dict[str, dict[date, tuple[int, str]]]: + """{figure: {day: (when its high or low happened, the resolution that time is from)}}: the day rows' own times of the figures + day_values_on reads, for these days (one query per kind of sensor).""" + out: dict[str, dict[date, tuple[int, str]]] = {n: {} for n in names} + by_kind: dict[str, tuple[dict, set]] = {} + places = {} + for name in names: + group, field, which, _ = FIELDS[name] + sensor, place = r.sensor(mac, group), column_of(group, field) + if sensor is None or place is None or PARTS[which] == "mean": + continue + places[name] = (sensor, place[0], PARTS[which] + "_ts") + by_kind.setdefault(sensor.kind, ({}, set()))[0][sensor.id] = sensor + by_kind[sensor.kind][1].add(place[0]) + rows = {} + for kind, (sensors, columns) in by_kind.items(): + rows.update(r.days(kind, list(sensors), min(days), max(days), sorted(columns))) + wanted = set(days) + for name, (sensor, column, part) in places.items(): + got = rows.get(sensor.id) + if got is None or column not in getattr(got, part): + continue + for d, ts, timing in zip(got.day, getattr(got, part)[column], got.timing): + if ts is not None and d in wanted: + out[name][d] = (ts, timing) + return out + + +def context_on(r: Reader, mac: str, names: list[str], days: list[date]) -> tuple[dict, dict]: + """(the figures of these days as the gauges show them, day_values_on's {figure: {day: value}}; their times, _times_on's).""" + values, _ = day_values_on(r, mac, names, days) + return values, _times_on(r, mac, names, days) + + +def _figure_text(gauge: Gauge, figure: str, value: float, unit: str) -> str: + """A gauge's figure written as the station writes the reading (its column's decimals) with its unit: "24.3 °C", "62 %", "11".""" + group, field, _, _ = FIELDS[figure] + column = BY_NAME[kind_of(group)][column_of(group, field)[0]] + return f"{written(value, column.decimals, column.whole)} {unit}".strip() + + +class Live: + """The live reading of one gauge: its value and when it was read (an epoch, or None).""" + + def __init__(self, live: dict, gauge: Gauge): + self.value = live_value(live, gauge.live) + group, field = gauge.live + try: + self.ts = int(((live.get(group) or {}).get(field) or {}).get("time") or 0) or None + except (TypeError, ValueError): + self.ts = None + + +def _extreme(key: str, value: float, figure: str, days: list[date], values: dict, times: dict, live: Live | None, gauge: Gauge, + unit: str, tz: tzinfo, dated: bool) -> dict: + """{key, key_text, key_when, [key_date]} of one high or low: when it happened is the first day of these that had it (its day row's + time of it), else the live reading's (it counted in, and is higher or lower than any day's).""" + out = {key: value, f"{key}_text": _figure_text(gauge, figure, value, unit)} + day = next((d for d in days if values.get(figure, {}).get(d) == value), None) + if day is not None and day in times.get(figure, {}): + ts, timing = times[figure][day] + _, out[f"{key}_when"], on = describe_time(ts, timing, tz) + elif day is None and live is not None and live.value == value and live.ts: + _, out[f"{key}_when"], on = describe_time(live.ts, MINUTE, tz) + else: + return out + if dated and on: + out[f"{key}_date"] = on + return out + + +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.""" + 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) + out = {} + for row, key in PERIODS: + got = figures(gauge, values, days[row], None if gauge.total else counted.value) + 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 = {} + if gauge.total: + wettest, total = got + if total is not None: + entry.update(total=total, total_text=_figure_text(gauge, gauge.highest, total, unit)) + if wettest is not None: + 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: + if value is not None: + entry.update(_extreme(key_, value, figure, days[row], values, times, counted, gauge, unit, tz, + dated=row != "Daily")) + if entry: + out[key] = entry + return out + + +def air_context_of(column: str, now: float | None, unit: str, values: dict, today: date) -> dict: + """{today, month, year} beside one of the air sensor's readings: the highest and lowest of its day rows (values: the air sensor's + {"pm2_5_max": {day: value}, ...}, AirReadings.day_figures'), the reading now counted in, each written as the report writes the + reading, with its day (month and year). {} when none of its figures is held.""" + days, out = periods_of(today), {} + for row, key in PERIODS: + entry: dict = {} + for name, part, pick in (("high", "max", max), ("low", "min", min)): + held = {d: v for d in days[row] if (v := values.get(f"{column}_{part}", {}).get(d)) is not None} + figures = [*held.values(), *([now] if now is not None else [])] + if not figures: + continue + value = pick(figures) + entry.update({name: value, f"{name}_text": air_shown(column, value, unit)}) + on = next((d for d, v in held.items() if v == value), today) + if row != "Daily": + entry[f"{name}_date"] = day_text(on) + if entry: + out[key] = entry + return out + + +# ---------- the tool ---------- +class CurrentTool: + """The current tool over a Context: the station's and the air sensor's readings now.""" + + def __init__(self, ctx: Context): + self.ctx = ctx + + @property + def devices(self) -> list[str]: + return [*([STATION] if self.ctx.eco else []), *([AIR_DEVICE] if self.ctx.air else [])] + + def tool(self) -> ServiceTool: + return ServiceTool(NAME, DESCRIPTION, parameters(self.ctx.readings().description()), self.handle, open_world=True) + + # ---------- the call ---------- + def _asked(self, args: dict) -> tuple[list[Reading], bool, bool]: + """(the readings asked for, whether they were named, context): the call checked, a wrong one refused with what fixes it.""" + if unknown := [k for k in args if k not in ARGUMENTS]: + then = any(k in ANOTHER_TIME for k in unknown) + raise Refusal(f"{', '.join(map(repr, unknown))} {'is not an argument' if len(unknown) == 1 else 'are not arguments'} of " + "current" + (": it gives the readings now. For a period's highs, lows or averages call summary with that " + "period; for values at set times, readings" if then else "") + ".", arguments=list(ARGUMENTS)) + context = args.get("context") + if isinstance(context, str) and context.strip().lower() in ("true", "false"): + context = context.strip().lower() == "true" + if context is not None and not isinstance(context, bool): + raise Refusal(f"`context` is true or false, not {context!r}.") + catalogue = self.ctx.readings() + here = [r for r in catalogue if r.device in self.devices] + named = args.get("readings") not in (None, "", []) + asked = _resolve(catalogue, args.get("readings"), default=[r.name for r in here]) + if named and (absent := [r for r in asked if r.device not in self.devices]): + device = "weather station" if absent[0].device == STATION else "air sensor" + raise Refusal(f"{absent[0].name} is the {device}'s, and this service has no {device}.", names=[r.name for r in here]) + return [r for r in asked if r.device in self.devices], named, bool(context) + + async def handle(self, args: dict, meta: dict) -> str: + asked, named, context = self._asked(args) + parts, gauges = [], context and not named # every gauge: those of a reading the file hasn't recorded yet too + if (station := [r for r in asked if r.device == STATION]) or (gauges and STATION in self.devices): + parts.append(await self._station(station, named, context, meta)) + if gauges and AIR_DEVICE in self.devices: + air_names = {r.name for r in asked} + asked = asked + [r for c in AIR if f"air.{c}" not in air_names and (r := CATALOGUE.get(f"air.{c}"))] + if air := [r for r in asked if r.device == AIR_DEVICE]: + parts.append(await self._air(air, named, meta, context)) + sensors: dict[str, dict] = {} + for part in parts: + for r, entry in part.entries: + sensors.setdefault(r.sensor, {})[r.reading] = entry + fields = {"sensors": sensors, "lines": {p.device: p.lines for p in parts}, "headings": {p.device: p.heading for p in parts}} + if missing := [name for p in parts for name in p.missing]: + fields["missing"] = missing + if unavailable := {p.device: p.unavailable for p in parts if p.unavailable}: + fields["unavailable"] = unavailable + times = [p.at for p in parts if p.at] + return answer(period=None, as_of=max(times) if times else self.ctx.now() if sensors else None, **fields) + + async def now_of(self, device: str, meta: dict | None = None) -> "Part": + """One device's part as `current` with no readings named gives it (its every reading now, its lines and heading), for the + service's resources (ecobot://now/weather, ecobot://now/air: lib/mcp_server.py). meta: the request's (request_meta).""" + readings = [r for r in self.ctx.readings() if r.device == device] + meta = request_meta(meta) + return await (self._station(readings, False, False, meta) if device == STATION else self._air(readings, False, meta)) + + async def _station(self, station: list[Reading], named: bool, context: bool, meta: dict) -> "Part": + """The weather station's part: each reading asked for now (with the gauges' figures beside it, with `context`), its lines and + heading. A reading named that it isn't reading is missing; so is a gauge's, with `context`, shown with its figures alone.""" + tz, today = self.ctx.zone, self.ctx.now().date() + try: + live = await self._live(station, named, meta) + except NothingHeld: + return Part.down(STATION, NOTHING_HELD[STATION], today) + except Exception as e: + log.warning("current: the weather station's reading failed: %s", e) + return Part.down(STATION, UNAVAILABLE[STATION], today) + now, newest = now_shaped(live, tz) + at = to_local(newest, tz) if newest else None + if context and not named: # every gauge, as it shows: a gauge's reading sent now that the file hasn't recorded yet too + station = station + [r for r in unrecorded(live, {r.name for r in station}) if gauge_of(r.name)] + gauges = await self._context(station) if context else None + part, shown = Part(STATION, at=at), [] + for r in station: + own = live_field(live, r) + beside = context_of(r.name, live, *gauges, today, tz) if gauges else {} + if own is not None: + part.entries.append((r, {**station_entry(live, now, r, own), **beside})) + shown.append(r) + continue + if named or beside: + part.missing.append(r.name) + if beside: # (a gauge drawn dimmed: no reading now, its figures still there) + part.entries.append((r, {"value": None, "unit": gauge_of(r.name).unit, **beside})) + part.lines = station_lines(now, shown) if named else weather_lines(now) + part.heading = heading(STATION, at, today) + return part + + async def _air(self, air: list[Reading], named: bool, meta: dict, context: bool = False) -> "Part": + """The air sensor's part: each reading asked for now (with its highs and lows beside it, with `context`), its lines and heading. + A reading named that it isn't reading is missing; so is one with figures, with `context`, shown with its figures alone (as when + the sensor isn't answering).""" + tz, today = self.ctx.zone, self.ctx.now().date() + figures = await self._air_context(air) if context else {} + try: + latest = await self._latest([r.column for r in air if r.column in AIR_OWN_METRICS], meta) + except Exception as e: + if not isinstance(e, NothingHeld): + log.warning("current: the air sensor's reading failed: %s", e) + part = Part.down(AIR_DEVICE, NOTHING_HELD[AIR_DEVICE] if isinstance(e, NothingHeld) else UNAVAILABLE[AIR_DEVICE], today) + part.entries = [(r, {"value": None, "unit": AIR[r.column].unit, **beside}) for r in air + if r.column in AIR and (beside := air_context_of(r.column, None, AIR[r.column].unit, figures, today))] + return part + reading, at = latest.reading, latest.at.astimezone(tz) if latest.at else None + part, shown = Part(AIR_DEVICE, at=at), [] + for r in air: + entry = reading.get(r.column) + now = entry.get("value") if isinstance(entry, dict) else None + unit = entry.get("unit", "") if isinstance(entry, dict) else AIR[r.column].unit if r.column in AIR else "" + beside = air_context_of(r.column, now, unit, figures, today) if figures and r.column in AIR else {} + if now is not None: + part.entries.append((r, {**air_entry(r.column, entry), **beside})) + shown.append(r) + continue + if named or beside: + part.missing.append(r.name) + if beside: # (a gauge drawn dimmed: no reading now, its figures still there) + part.entries.append((r, {"value": None, "unit": unit, **beside})) + part.lines = own_air_lines(reading, shown) if named else air_lines(reading) + part.heading = heading(AIR_DEVICE, at, today) + return part + + async def _air_context(self, air: list[Reading]) -> dict: + """The air sensor's day figures for its air-quality readings among these ({"pm2_5_max": {day: value}, ...}), the year so far, + in one read; {} when they can't be read (the readings now are still given).""" + names = [f"{r.column}_{part}" for r in air if r.column in AIR for part in ("max", "min")] + if not names: + return {} + days = periods_of(self.ctx.now().date())["Yearly"] + try: + return (await self.ctx.air.store.day_figures(days[0], days[-1], names)).values + except Exception as e: # (only the figures: the readings now stand) + log.warning("current: the air sensor's day figures failed: %s: %s", type(e).__name__, e) + return {} + + async def _live(self, station: list[Reading], named: bool, meta: dict) -> dict: + """The station's live reading for every group "weather now" shows (the reading it keeps, while that is fresh) and, only when they + are named, those of other readings (the piezo gauge: a request of its own); with `fetch` off, the reading it keeps, whatever its + age (NothingHeld when it keeps none).""" + from ..ecowitt.source import LIVE_GROUPS # (lazy: the station's package is the engine; this module only reads it) + eco = self.ctx.eco + groups = list(dict.fromkeys([*LIVE_GROUPS, *(r.sensor for r in station if named)])) + if not meta["fetch"]: + kept = getattr(eco, "_live", None) + if not kept: + raise NothingHeld() + return {g: kept[1][g] for g in groups if g in kept[1]} + return await eco._live_data(groups, urgent=meta["priority"] != BACKGROUND) + + async def _latest(self, extras: list[str], meta: dict): + """The air sensor's latest reading (AirGradient.latest), with its own temperature and humidity when named; with `fetch` off, the + reading it keeps, whatever its age, rated on the readings before it it already has: nothing fetched (NothingHeld when it keeps + none), as the station's (_live).""" + if not meta["fetch"]: + 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) + + 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}) + if not names: + return {}, {} + eco = self.ctx.eco + return await eco.storage.read(context_on, eco.mac, names, periods_of(self.ctx.now().date())["Yearly"]) + + +@dataclass +class Part: + """One device's part of the answer: its readings (each with its entry), its lines and heading, what was named but isn't read now, + why it gave nothing (when it didn't answer), and the time of its reading.""" + device: str + entries: list[tuple[Reading, dict]] = field(default_factory=list) + lines: list[str] = field(default_factory=list) + heading: str = "" + missing: list[str] = field(default_factory=list) + unavailable: str | None = None + at: datetime | None = None + + @classmethod + def down(cls, device: str, why: str, today: date) -> "Part": + """A device that gave nothing: the report's section for it ("Weather station", "• not available right now").""" + return cls(device, lines=[NOT_AVAILABLE], heading=heading(device, None, today), unavailable=why) + + +class NothingHeld(Exception): + """With `fetch` off, a device whose reading isn't held.""" + + +def air_entry(key: str, entry: dict) -> dict: + """{value, unit, text, [rating], [rating_note], [aqi_us, band]} of an air reading (AirGradient.latest()'s), with its text.""" + unit = entry.get("unit", "") + return {"value": entry["value"], "unit": unit, "text": air_shown(key, entry["value"], unit), + **{k: entry[k] for k in ("rating", "rating_note", "aqi_us", "band") if k in entry}} + + +COVERED = {"wind.wind_gust": "wind", "wind.wind_direction": "wind", "rainfall.rain_rate": "rain"} # in the line of another reading + + +def station_lines(now: dict, readings: list[Reading]) -> list[str]: + """The lines of the station's readings named: the bot's plain lookup's (reading_lines) for each reading it words, each on the sides + asked for it (outdoor, indoor; both when it has neither), then a line of its own for each other reading not in one of those.""" + names = list(dict.fromkeys(r.series for r in readings if r.series in WEATHER)) + out = [] + for name in names: + sides = [s for s in ("outdoor", "indoor") if any(r.sensor == s and r.series == name for r in readings)] or ["outdoor", "indoor"] + out += reading_lines(now, [name], sides) + _, tag = _getters(now) + for r in readings: + if r.series in WEATHER or COVERED.get(r.name) in names: + continue + own = next((f for f in (now.get(r.sensor) or {}) if column_of(r.sensor, f) == (r.column, "value")), None) + if own and (shown := tag(r.sensor, own)): + out.append(f"• {r.label}: {shown}") + return out + + +def own_air_lines(reading: dict, readings: list[Reading]) -> list[str]: + """The lines of the air readings named: the report's (air_lines) for its six, then the sensor's own temperature and humidity.""" + keys = [r.column for r in readings] + own = [f"• {r.label}: {air_shown(r.column, reading[r.column]['value'], reading[r.column].get('unit', ''))}" + for r in readings if r.column in AIR_OWN_METRICS] + return air_lines(reading, [k for k in keys if k in AIR]) + own + + +def tools(ctx: Context) -> list[ServiceTool]: + """The current tool, when there is a sensor to read.""" + return [CurrentTool(ctx).tool()] if ctx.eco or ctx.air else [] + + +__all__ = ["CurrentTool", "DESCRIPTION", "air_lines", "context_of", "gauge_of", "heading", "now_shaped", "parameters", "reading_lines", + "station_lines", "tools", "weather_lines"] diff --git a/lib/service/daylook.py b/lib/service/daylook.py new file mode 100644 index 00000000..b723814a --- /dev/null +++ b/lib/service/daylook.py @@ -0,0 +1,102 @@ +"""A day's look: one word and an emoji for that day's outdoor weather, worked out from its figures (docs/ecobot-mcp.md 3.2, "Answers +ready to pass on"), so a model quotes `day_look: {word: "wet", emoji: "🌧️"}` beside a day and never guesses it. + +The rule takes the first that holds: + 1. stormy ⛈️ heavy rain and strong gusts together: rain >= STORMY_RAIN_MM and a gust >= STORMY_GUST_KMH (the station has no + lightning sensor, so a storm is told by what it does); + 2. wet 🌧️ rain >= WET_MM; + 3. showery 🌦️ rain >= RAINY_DAY_MM, the rainy day of the days tool and the bot's prompt (rain >= 1): every day counted as rainy + looks rainy, and a trace (under 1 mm, often dew or drizzle) doesn't; + 4. windy 💨 a gust >= WINDY_GUST_KMH; + 5. very hot 🥵 the high >= VERY_HOT_C; + 6. very cold 🥶 the high under VERY_COLD_HIGH_C, or a frost: the low at or below FROST_C; + 7. by how sunny it was: the day's mean solar radiation over a clear sky's for that date and latitude (clear_sky_mean): sunny ☀️ from + SUNNY, mostly sunny 🌤️ from MOSTLY_SUNNY, partly cloudy ⛅ from PARTLY_CLOUDY, else overcast ☁️. +A step whose figure is missing is passed over. With no solar radiation (or no latitude), step 7 gives nothing, so a day that none of +1 to 6 fits has no look: None, and the day goes without an emoji rather than with a guess. Fog 🌫️, which the prompt also lists, can't +be told from these figures, so it is never given. + +The thresholds are for a temperate climate such as Melbourne's: there, 35 °C is a day people count, a high under 10 °C one of the +coldest days of a winter, gusts of 50 km/h a day people call windy (the gust alert is at 40), and 10 mm in a day heavy rain. +""" + +import math +from collections.abc import Mapping +from datetime import date + +STORMY_RAIN_MM = 10.0 # heavy rain, with ... +STORMY_GUST_KMH = 60.0 # ... strong gusts: a storm +WET_MM = 5.0 # more than showers +RAINY_DAY_MM = 1.0 # a rainy day (daytable and the prompt: rain >= 1); below it a trace +WINDY_GUST_KMH = 50.0 +VERY_HOT_C = 35.0 # the high +VERY_COLD_HIGH_C = 10.0 # the high stays under it +FROST_C = 0.0 # or the low falls to it (on the ground it is colder still) +SUNNY = 0.80 # the day's solar radiation as a share of a clear sky's: the sensor and the model each err by up to about a +MOSTLY_SUNNY = 0.60 # tenth, so sunny starts below 1; an overcast day lets through a fifth to a third of a clear sky's +PARTLY_CLOUDY = 0.35 + +# The look of a day: its word and its emoji, from the prompt's WEATHER EMOJIS +LOOKS = {"stormy": "⛈️", "wet": "🌧️", "showery": "🌦️", "windy": "💨", "very hot": "🥵", "very cold": "🥶", + "sunny": "☀️", "mostly sunny": "🌤️", "partly cloudy": "⛅", "overcast": "☁️"} +FIGURES = ("rain", "wind_gust", "temp_max", "temp_min", "solar_avg") # what day_look reads: the days tool's names for them + +# The clear sky (Haurwitz, 1945): on a cloudless day the sun gives a level surface 1098 cos(z) e^(-0.057 / cos(z)) W/m², z the sun's +# angle from overhead, which depends on the latitude, the sun's declination that day (Cooper, 1969) and the hour. It needs nothing but +# the date and the latitude, and over a day comes within about a tenth of what a cloudless sky gives where the air is clean. +HAURWITZ_W, HAURWITZ_K = 1098.0, 0.057 +STEPS = 288 # the day's 24 hours in 5-minute steps of the sun's hour angle + + +def clear_sky_mean(day: date, latitude: float) -> float: + """The mean solar radiation of a cloudless `day` at this latitude (degrees, south negative) over its 24 hours, W/m²: what a day's + mean solar radiation (its `solar_avg`) is set against. 0 when the sun never rises.""" + declination = math.radians(23.45) * math.sin(2 * math.pi * (284 + day.timetuple().tm_yday) / 365) + lat = math.radians(latitude) + a, b = math.sin(lat) * math.sin(declination), math.cos(lat) * math.cos(declination) + total = 0.0 + for k in range(STEPS): + up = a + b * math.cos(math.pi * (2 * (k + 0.5) / STEPS - 1)) # the cosine of the sun's angle from overhead + if up > 0: + total += HAURWITZ_W * up * math.exp(-HAURWITZ_K / up) + return total / STEPS + + +def day_look(figures: Mapping, *, latitude: float | None, day: date, so_far: bool = False) -> dict | None: + """{"word": "wet", "emoji": "🌧️"} for a day from its figures, by the rule above, or None when none of it can be told. `figures` are + the day's, named as the days tool names them: rain (mm that fell), wind_gust (its highest, km/h), temp_max and temp_min (outdoor, + °C), solar_avg (its mean solar radiation over the whole day, W/m²); a missing one, or None, passes its steps over. `latitude`: the + station's. `so_far`: the day isn't over (today): its figures run to now, so its solar mean is no whole day's and the cloud step is + passed over.""" + rain, gust, high, low, solar = (_number(figures.get(name)) for name in FIGURES) + word = ("stormy" if rain is not None and gust is not None and rain >= STORMY_RAIN_MM and gust >= STORMY_GUST_KMH else + "wet" if rain is not None and rain >= WET_MM else + "showery" if rain is not None and rain >= RAINY_DAY_MM else + "windy" if gust is not None and gust >= WINDY_GUST_KMH else + "very hot" if high is not None and high >= VERY_HOT_C else + "very cold" if (high is not None and high < VERY_COLD_HIGH_C) or (low is not None and low <= FROST_C) else + None if so_far else _sky(solar, latitude, day)) + return {"word": word, "emoji": LOOKS[word]} if word else None + + +def _sky(solar: float | None, latitude: float | None, day: date) -> str | None: + """How sunny the day was, from its mean solar radiation against a clear sky's.""" + if solar is None or latitude is None or (clear := clear_sky_mean(day, latitude)) <= 0: + return None + share = solar / clear + return "sunny" if share >= SUNNY else "mostly sunny" if share >= MOSTLY_SUNNY else "partly cloudy" if share >= PARTLY_CLOUDY else \ + "overcast" + + +def _number(value) -> float | None: + """A figure as a number (one written as text, "12.3", too); None for none.""" + if value is None or isinstance(value, bool): + return None + try: + number = float(value) + except (TypeError, ValueError): + return None + return number if math.isfinite(number) else None + + +__all__ = ["FIGURES", "LOOKS", "clear_sky_mean", "day_look"] diff --git a/lib/service/days.py b/lib/service/days.py new file mode 100644 index 00000000..0d1e214f --- /dev/null +++ b/lib/service/days.py @@ -0,0 +1,606 @@ +"""The `days` tool (docs/ecobot-mcp.md 3.3): days found, ranked, counted or totalled by their figures, over the weather station's and +the air sensor's day figures, or over part of each day (`hours`). It replaces weather_days and air_days, on their engines: + + - the fields are theirs: the station's (lib/ecowitt/days.py FIELDS: temp_max, rain, humidity_avg, indoor_temp_min ...) and the air + sensor's (lib/airgradient/days.py: pm2_5_max, co2_avg ...), in one list; + - a whole day's figures are its day rows, read as those tools read them (ecowitt.days.day_values_on, AirReadings.day_figures); part of + each day's are lib/partday.stretch_figures, mapped to the same fields (temp_max is the stretch's highest, temp_avg its mean, rain the + mm that fell in it); + - finding, ranking, counting, grouping and the bars are lib/daytable.py's (prepare, analyse), and the notes are the two tools' own. + +Which sensor: the fields named (`where`, `sort_by`, `of`) say. Station fields read as weather_days did; air fields as air_days did; both +(a question mixing the two) by the merged rule of 3.3: the fields shown and the default sort come from the sensors named, `days_checked` +counts the days every named sensor has, and the days whose station figures come only from Ecowitt's daily records (10am to 10am, not +the air sensor's midnight to midnight) are left out and counted. + +The result is today's day-tool result in 3.2's shape (period, as_of, then its fields), each listed day with its `day_look`, and `answer`: +the line the bot wrote for a days lookup (the old lib/report.py `_days`, ported here with the same words), which is also the finished +reply when `chart_answers_it` is set and a chart drawn (unless a note needs the model's words). `group_by` draws the bar chart, which +carries the call that drew it (`drawn_by`, 3.7). + +It reads the file alone and never fetches, so the request's `fetch` and `priority` change nothing (and `chart_points` leaves bars as +they are: a bar per month or year is never bucketed). +""" + +import operator +import re +from collections.abc import Callable +from dataclasses import dataclass, field +from datetime import date, datetime, time, timedelta + +from ..airgradient.days import ALWAYS_SHOWN as AIR_SHOWN, FIELDS as AIR_UNITS +from ..daytable import MAX_LIMIT, OPS, STATS, analyse, lists_days, prepare +from ..ecowitt.api import daily_run, unit_text +from ..public_holidays import PublicHolidays +from ..ecowitt.days import ALWAYS_SHOWN as STATION_SHOWN, AVERAGED, COARSER, FIELDS as STATION_FIELDS, PARTS, day_values_on +from ..partday import ALLOWED, CLOCK_CHANGE, NOT_HELD, NOT_OVER, PartDays, Stretch, over, parse_stretch, stretch_figures +from ..specs import AIR_SOURCE, CHART_SOURCE, ECOWITT_SOURCE +from ..storage.catalogue import column_of +from ..storage.read import Reader +from ..timeutil import day_text +from ..tools import Turn +from .common import Refusal, ServiceTool, answer, complete, period_properties, read_period, sends_period, with_charts +from .context import Context +from .daylook import FIGURES as LOOK_FIGURES, day_look +from .names import AIR_DEVICE, STATION + +NAME = "days" +DEFAULT, DEFAULT_HOURS = "on record", "last 30 days" # the period read when none is sent: every day held; with hours, a month +MAX_HOURS_DAYS = 400 # the most days `hours` reads (3.3: a stretch costs far more than a day row) +STATION_UNITS = {name: f[3] for name, f in STATION_FIELDS.items()} +DEVICE_OF = {**dict.fromkeys(STATION_UNITS, STATION), **dict.fromkeys(AIR_UNITS, AIR_DEVICE)} +SHOWN = {STATION: STATION_SHOWN, AIR_DEVICE: AIR_SHOWN} # what every listed day shows, by the sensor named +DEVICES = (STATION, AIR_DEVICE) +ONLY = {"public_holiday": "public holidays only", "weekend": "weekends only"} # (the chart's subtitle says which) +ORDERS = ("desc", "asc") +OP_WORDS = {"==": "=", "≥": ">=", "≤": "<=", "=>": ">=", "=<": "<="} # ops written another way +GROUP_BY_NOTE = ("One figure for the whole period. If a figure per month or per year was asked for (\"per month\", \"by year\", " + "\"each year\"), call again with group_by \"month\" or \"year\".") +ARGUMENTS = ("where", "sort_by", "order", "count_only", "group_by", "stat", "of", "limit", "only", "hours", "period", "start", "end", + "chart_answers_it") +OLD_NAMES = {"start_date": "start", "end_date": "end"} # weather_days' and air_days' names +CAPTIONED_NOTES = {"note_averaged"} # the notes the answer line passes on itself (" Older days use averages ..."): any other needs words +AIR_PART = {"max": "hi", "min": "lo", "avg": "mean"} # an air field's suffix -> where a day row keeps it +SOURCES = {STATION: ECOWITT_SOURCE, AIR_DEVICE: AIR_SOURCE} +# drawn_by.periods (3.7): a count or total per month over 3 months, a year and the whole record; per year, no other period +MONTH_PERIODS = (("3m", "3M"), ("1y", "1Y"), ("on record", "All")) +HOURS_HOW = ("Each day's figures are over this stretch of it, not the whole day: _max its highest, _min its lowest, _avg its mean, rain " + "the mm that fell in it. A stretch across midnight belongs to the day it ends on. day_look is still the whole day's look.") + +# the notes, worded as weather_days and air_days word them (lib/ecowitt/days.py, lib/airgradient/days.py) +NOTE_TRACE = ("These days rank higher but had less than {value:g} mm of rain (a trace), so they are not in \"days\". Mention the first " + "as a short footnote.") +NOTE_DAILY = ("Days marked \"daily\" come from daily readings that run {run}, so their rain and dates are approximate (a morning shower " + "can be counted on the day before). Say so briefly if any listed day is marked daily, or if the period reaches back before " + "exact_from.") +NOTE_AVERAGED = ("For these readings, days from 30-minute or daily data use each interval's average, so a day's true peak (or low) may " + "be a little beyond what is listed: a count of days at or past a limit can fall slightly short near the limit. Say so " + "briefly.") +NOTE_HOURLY = ("{n} of these days only exist as hourly averages, so their highs and lows are hourly averages and a short spike is " + "smoothed. Say so briefly if it matters.") +NOTE_MISSING = "{n} day(s) in this period have no stored readings (not downloaded yet, or the sensor was off) and are not counted." +NOTE_NOTHING = "No readings are held for this period yet (its history may still be downloading)." +NOTE_BEFORE = "No readings are held for this period: the record of what was asked about starts {first}." +NOTE_DAILY_LEFT_OUT = ("{n} day(s) are left out: their weather-station figures come only from Ecowitt's daily records, which run {run}, " + "not midnight to midnight as the air sensor's days do, so the two can't be set against each other. Say so " + "briefly.") +NOTE_LEFT_OUT = ("Some days aren't counted, as `left_out` says: \"not held finely enough\" (only Ecowitt's daily or 4-hour records, or " + "nothing, cover that stretch), \"no readings\" (the sensor was off), \"removed by the clock change\". Say so briefly " + "if it matters.") +LEFT_OUT = {NOT_HELD: "not held finely enough", CLOCK_CHANGE: CLOCK_CHANGE, NOT_OVER: NOT_OVER} + +# ---------- the description and the input schema ---------- +DESCRIPTION = ( + "Days found, ranked, counted or totalled by their figures, from the weather station's and the air sensor's days, midnight to " + "midnight. sort_by is the field the days are ranked by: the wettest days, most rain {sort_by: \"rain\"}; the hottest " + "day it rained {where: [{field: \"rain\", op: \">=\", value: 1}], sort_by: \"temp_max\"}. Days over 35°C this year: {where: " + "[{field: \"temp_max\", op: \">\", value: 35}], period: \"this year\", count_only: true}. Per month or year (\"per year\", \"each " + "year\", \"by month\"), group_by: rain per month {stat: \"sum\", of: \"rain\", group_by: \"month\"}; average temperature per " + "year {stat: \"avg\", of: \"temp_avg\", group_by: \"year\"}. PM2.5 over 25: {where: [{field: \"pm2_5_max\", op: \">\", value: " + "25}]}. The windiest weekend day: {sort_by: \"wind_gust\", only: \"weekend\"}. One day: {period: \"5 Sep\"}. Part of each day, " + "hours: nights below 5°C {hours: \"night\", where: [{field: \"temp_min\", op: \"<\", value: 5}]}; 3pm in October {hours: " + "\"15:00\", stat: \"avg\", of: \"temp_avg\", period: \"October\"}. No period: every day on record (with hours, 30 days). Not " + "for: a period's highest or lowest reading with when, a record (\"hottest ever\"), wind direction or a chart over time (summary); values at set times (readings); rain " + "against a reading (relate). Result: answer, a line to pass on; matching_days of days_checked; days, the top ones, each with " + "day_look (word and emoji: put it before the day); by_month or by_year, drawn as bars (charts); note_*: mention " + "briefly. A rainy day is rain >= 1.") + +STATION_WHERE = ("Weather station: temp_max, temp_min, temp_avg (outdoor °C), rain (mm that fell), wind_gust (km/h, the highest); a " + "day's highest (_max), lowest (_min) and mean (_avg) of humidity, pressure, dew_point, feels_like, vpd, indoor_temp, " + "indoor_humidity; the _max and _avg of wind_speed, solar, uv, rain_rate.") +AIR_WHERE = "Air sensor: the _max, _min and _avg of pm2_5, pm10, pm1 (µg/m³), co2 (ppm), voc_index and nox_index." +HOURS = {"type": "string", "description": "Part of each day instead of the whole day: night (22:00-06:00, which belongs to the day it " + "ends on), morning (06:00-12:00), afternoon (12:00-18:00), evening (18:00-24:00), daytime " + "(06:00-18:00), two times on the half hour ('15:00-16:00', '22:30-06:00'), or a moment ('15:00'). " + "Each day's figures are then over that stretch: temp_max its highest, temp_min its lowest, " + "_avg its mean, rain the mm that fell in it. Today counts once its stretch is over. At most " + f"{MAX_HOURS_DAYS} days."} +CHART_ANSWERS_IT = {"type": "boolean", "description": "true only when the question is just to see this chart (a figure per month or " + "year) and its figures: nothing else to answer (\"rain per month this year\", " + "not \"rain per month: is it drier than last year?\"). The result then carries " + "the finished reply (`reply`, `complete`)."} + + +def parameters(fields: list[str]) -> dict: + """The input schema over these fields (those of the sensors there are).""" + devices = {DEVICE_OF[n] for n in fields} + where = " ".join([*([STATION_WHERE] if STATION in devices else []), *([AIR_WHERE] if AIR_DEVICE in devices else [])]) + default_sort = "temp_max" if STATION in devices else "pm2_5_max" + one = {"type": "string", "enum": fields} + return { + "type": "object", + "properties": { + "where": {"type": "array", "description": "Conditions that must ALL hold on the same day, e.g. rain >= 1 and temp_max > 30. " + f"Fields. {where}", + "items": {"type": "object", "properties": {"field": one, "op": {"type": "string", "enum": list(OPS)}, + "value": {"type": "number"}}, + "required": ["field", "op", "value"]}}, + "sort_by": {**one, "description": "The field the days are ranked by (\"most rain\", \"wettest\": rain; \"hottest\": temp_max; " + "\"windiest\": wind_gust). Default: the first condition's field, else `of`, else " + f"{default_sort}" + (" (pm2_5_max when only air fields are named)." + if len(devices) > 1 else ".")}, + "order": {"type": "string", "enum": list(ORDERS), "description": "desc: highest first (default); asc: lowest first."}, + "count_only": {"type": "boolean", "description": "true for \"how many days\": the counts alone, no days listed."}, + "group_by": {"type": "string", "enum": ["month", "year"], + "description": "A figure per month or year (those with none included), drawn as a bar chart, whenever the " + "question asks per month or per year (\"rain per month\", \"by month\", \"days over 35°C " + "per year\", \"each year\", \"average temperature per year\")."}, + "stat": {"type": "string", "enum": list(STATS), + "description": "What the period, or each month or year, gives: count (default: the matching days), or the max, min, " + "avg or sum of `of` over the matching days (\"rain per month\": sum of rain; \"the hottest day each " + "year\": max of temp_max; \"average humidity per year\": avg of humidity_avg)."}, + "of": {**one, "description": "The field stat takes the max, min, avg or sum of; always with stat (not needed for count)."}, + "limit": {"type": "integer", "description": f"How many days to list (default 5, at most {MAX_LIMIT}). The total is always " + "counted."}, + "only": {"type": "string", "enum": list(ONLY), + "description": "Only the public holidays (the station's state's calendar) or only Saturdays and Sundays: days are " + "then found and counted among those alone."}, + "hours": HOURS, + **period_properties(f"{DEFAULT} (every day held); with hours, the {DEFAULT_HOURS}", whole_days=True), + "chart_answers_it": CHART_ANSWERS_IT, + }, + } + + +# ---------- the call, checked ---------- +@dataclass(frozen=True) +class Call: + """A call's arguments as the tool reads them, checked, with every default filled in.""" + where: list[dict] + sort_by: str | None + order: str + count_only: bool + group_by: str | None + stat: str + of: str | None + limit: int + only: str | None + stretch: Stretch | None + chart_answers_it: bool + + @property + def named(self) -> list[str]: + """The fields the call names, in order.""" + return list(dict.fromkeys([*(c["field"] for c in self.where), *filter(None, (self.sort_by, self.of))])) + + def engine(self, first: date, last: date) -> dict: + """The arguments as lib/daytable.py reads them.""" + return {"start_date": first.isoformat(), "end_date": last.isoformat(), "where": self.where, "order": self.order, + "count_only": self.count_only, "stat": self.stat, "limit": self.limit, + **{k: v for k, v in (("sort_by", self.sort_by), ("group_by", self.group_by), ("of", self.of)) if v}} + + +def _stretch_words(s: Stretch) -> str: + """A stretch as `hours` takes it: "night", "15:00-16:00", "15:00".""" + clock = lambda m: f"{m // 60:02d}:{m % 60:02d}" + return s.name or (clock(s.start) if s.moment else f"{clock(s.start)}-{clock(s.end)}") + + +def _flag(args: dict, name: str) -> bool: + value = args.get(name) + if value is None or isinstance(value, bool): + return bool(value) + if str(value).strip().lower() in ("true", "1", "yes"): + return True + if str(value).strip().lower() in ("false", "0", "no", ""): + return False + raise Refusal(f"`{name}` is true or false, not {value!r}.") + + +def _near(word: str, fields: list[str]) -> list[str]: + """The fields a name that isn't one may have meant ("temperature": temp_max, temp_min, temp_avg; "pm2.5": pm2_5_max ...).""" + key = re.sub(r"[^a-z0-9]+", "_", str(word).lower()).strip("_") + key = {"temperature": "temp", "outdoor_temp": "temp", "outdoor_temperature": "temp", "indoor_temperature": "indoor_temp", + "pm25": "pm2_5", "uvi": "uv", "uv_index": "uv", "gust": "wind_gust", "gusts": "wind_gust", "rainfall": "rain", + "precipitation": "rain", "voc": "voc_index", "nox": "nox_index", "wind": "wind"}.get(key, key) + for suffix in ("_max", "_min", "_avg", "_high", "_low", "_mean", "_total"): + key = key.removesuffix(suffix) + return [n for n in fields if n == key or n.startswith(key + "_")] + + +class DaysTool: + """The `days` tool over a Context: its fields are those of the sensors there are.""" + + def __init__(self, ctx: Context): + self.ctx = ctx + self.units = {**(STATION_UNITS if ctx.eco else {}), **(AIR_UNITS if ctx.air else {})} + self.fields = list(self.units) + + def tool(self) -> ServiceTool: + return ServiceTool(NAME, DESCRIPTION, parameters(self.fields), self.handle) + + # ---------- reading the arguments ---------- + def _field(self, value, what: str) -> str: + name = str(value).strip() if value is not None else "" + if name in self.units: + return name + if name in DEVICE_OF: + device = "weather station" if DEVICE_OF[name] == STATION else "air sensor" + raise Refusal(f"{what} {name!r} is the {device}'s, and this service has no {device}.", fields=self.fields) + near = _near(name, self.fields) + hint = f" Did you mean {', '.join(near)}?" if near else "" + raise Refusal(f"{what} {value!r} isn't a field of days.{hint} Send one of `fields`.", fields=self.fields) + + def _condition(self, c) -> dict: + if not isinstance(c, dict) or not {"field", "op", "value"} <= set(c): + raise Refusal(f"A condition is {{\"field\", \"op\", \"value\"}}, such as {{\"field\": \"rain\", \"op\": \">=\", \"value\": 1}}, " + f"not {c!r}.", fields=self.fields, ops=list(OPS)) + name = self._field(c["field"], "Field") + op = OP_WORDS.get(str(c["op"]).strip(), str(c["op"]).strip()) + if op not in OPS: + raise Refusal(f"op {c['op']!r} isn't one of {' '.join(OPS)}.", ops=list(OPS)) + value = c["value"] + if isinstance(value, str): + try: + value = float(value) + except ValueError: + pass + if isinstance(value, bool) or not isinstance(value, int | float): + raise Refusal(f"A condition's value is a number, in the field's unit ({name}: {self.units[name] or 'an index'}), not " + f"{c['value']!r}.") + return {"field": name, "op": op, "value": value} + + def read(self, args: dict) -> Call: + """The call checked: a Refusal, saying what to send instead, for anything the tool can't use.""" + if unknown := [k for k in args if k not in ARGUMENTS]: + renamed = [f"`{k}` is `{OLD_NAMES[k]}`" for k in unknown if k in OLD_NAMES] + raise Refusal(f"{', '.join(map(repr, unknown))} {'is not an argument' if len(unknown) == 1 else 'are not arguments'} of days" + + (f" ({'; '.join(renamed)}, or send a `period` in words)" if renamed else "") + ".", arguments=list(ARGUMENTS)) + where = args.get("where") or [] + where = [where] if isinstance(where, dict) else where + if not isinstance(where, list): + raise Refusal("`where` is a list of conditions, such as [{\"field\": \"rain\", \"op\": \">=\", \"value\": 1}].", + fields=self.fields) + where = [self._condition(c) for c in where] + sort_by = self._field(args["sort_by"], "sort_by") if args.get("sort_by") else None + order = str(args.get("order") or "desc").strip().lower() + if order not in ORDERS: + raise Refusal(f"order is desc (highest first) or asc (lowest first), not {args['order']!r}.") + group_by = str(args["group_by"]).strip().lower() if args.get("group_by") else None + if group_by not in (None, "month", "year"): + raise Refusal(f"group_by is month or year, not {args['group_by']!r}.") + if args.get("of") and not args.get("stat"): # (else it counts days and `of` is lost: "rain per month" as "313 of 313 days") + raise Refusal(f"`of` names the field `stat` works on: send `stat` too ({', '.join(s for s in STATS if s != 'count')}; " + f"\"rain per month\": stat sum, of rain), or leave `of` out to count days.", stats=list(STATS)) + stat = str(args.get("stat") or "count").strip().lower() + if stat not in STATS: + raise Refusal(f"stat is one of {', '.join(STATS)}, not {args['stat']!r}.", stats=list(STATS)) + of = self._field(args["of"], "of") if args.get("of") else None + if stat != "count" and of is None: + raise Refusal(f"stat {stat} needs `of`: the field to take the {stat} of (\"rain per month\": stat sum, of rain).", + fields=self.fields) + try: + limit = max(1, min(int(args.get("limit") or 5), MAX_LIMIT)) + except (TypeError, ValueError): + raise Refusal(f"limit is a whole number of days to list, 1 to {MAX_LIMIT}, not {args['limit']!r}.") from None + only = str(args["only"]).strip().lower() if args.get("only") else None + if only not in (None, *ONLY): + raise Refusal(f"only is {' or '.join(ONLY)}, not {args['only']!r}.") + stretch = None + if args.get("hours") not in (None, ""): + try: + stretch = parse_stretch(args["hours"]) + except ValueError as e: + raise Refusal(str(e), hours=ALLOWED) from None + return Call(where, sort_by, order, _flag(args, "count_only"), group_by, stat, of, limit, only, stretch, + _flag(args, "chart_answers_it")) + + def devices(self, call: Call) -> list[str]: + """The sensors the call is about: those of the fields it names, else the station's (the air sensor's when there is no station).""" + named = {DEVICE_OF[n] for n in call.named} + return [d for d in DEVICES if d in named] or [STATION if self.ctx.eco else AIR_DEVICE] + + # ---------- the period ---------- + def period(self, args: dict, call: Call, now: datetime, first_held: date | None): + """(the Period, its first day, its last day): whole days to yesterday; with `hours`, today too once its stretch is over.""" + tz, today, stretch = self.ctx.zone, now.date(), call.stretch + read = lambda whole: read_period(args, tz=tz, now=now, default=DEFAULT_HOURS if stretch else DEFAULT, whole_days=whole, + first_held=first_held) + try: + whole, refused = read(True), None + except Refusal as e: + whole, refused = None, e + if stretch and (whole is None or whole.cut) and over(stretch, today, tz, now.timestamp()): + try: # the same words to now: whole days still, ending today + timed = read(False) + except Refusal: + timed = None + if timed and timed.start.time() == time() and timed.last_day == today: + return timed, timed.first_day, today + if refused: + raise refused + return whole, whole.first_day, whole.last_day + + # ---------- reading the file ---------- + def _station_sensors(self, r: Reader, shown: list[str]) -> dict: + """{group: its Sensor} of the groups these station fields are in, those the file has.""" + groups = dict.fromkeys(STATION_FIELDS[n][0] for n in shown if DEVICE_OF[n] == STATION) + return {g: s for g in groups if (s := r.sensor(self.ctx.eco.mac, g)) is not None} + + def _first_held(self, r: Reader, devices: list[str], shown: list[str]) -> date | None: + """The first day held by every sensor asked about ("on record"): the latest of their first day rows; None when one holds none.""" + firsts = [] + for device in devices: + sensors = list(self._station_sensors(r, shown).values()) if device == STATION else [self.ctx.air.store.sensor] + by_kind: dict[str, list[int]] = {} + for s in filter(None, sensors): + by_kind.setdefault(s.kind, []).append(s.id) + found = [r.db.execute(f"SELECT MIN(day) FROM {kind}_day WHERE sensor IN ({', '.join('?' * len(ids))})", ids).fetchone()[0] + for kind, ids in by_kind.items()] + found = [date.fromisoformat(d) for d in found if d] + if not found: + return None + firsts.append(min(found)) + return max(firsts) if firsts else None + + def _stretches(self, r: Reader, shown: list[str], first: date, last: date, stretch: Stretch, now: float) -> dict[str, PartDays]: + """{group (or "air"): its sensor's figures over the stretch of each day}, in the columns these fields need.""" + columns: dict[str, list[str]] = {} + for n in shown: + if DEVICE_OF[n] == STATION: + group, reading, _, _ = STATION_FIELDS[n] + columns.setdefault(group, []).append(column_of(group, reading)[0]) + else: + columns.setdefault(AIR_DEVICE, []).append(n.rsplit("_", 1)[0]) + sensors = {**(self._station_sensors(r, shown) if self.ctx.eco else {}), + **({AIR_DEVICE: self.ctx.air.store.sensor} if self.ctx.air and AIR_DEVICE in columns else {})} + return {key: stretch_figures(r, sensor.kind, sensor, first, last, stretch, list(dict.fromkeys(columns[key])), self.ctx.zone, now) + for key, sensor in sensors.items() if sensor is not None} + + async def _held(self, call: Call, shown: list[str], first: date, last: date, now: float) -> "Held": + """Each shown field's figure per day, and what is known of where they came from.""" + days = [first + timedelta(days=k) for k in range((last - first).days + 1)] + held = Held(values={n: {} for n in shown}) + station = [n for n in shown if DEVICE_OF[n] == STATION] + air = [n for n in shown if DEVICE_OF[n] == AIR_DEVICE] + storage = self.ctx.storage + if call.stretch is None: + if station: + values, held.station = await storage.read(day_values_on, self.ctx.eco.mac, station, days) + held.values.update(values) + if air: + figures = await self.ctx.air.store.day_figures(first, last, air) + held.values.update(figures.values) + held.hourly, held.counts = set(figures.hourly), figures.counts + else: + parts = await storage.read(self._stretches, shown, first, last, call.stretch, now) + for n in shown: + if DEVICE_OF[n] == STATION: + group, reading, kind, _ = STATION_FIELDS[n] + part, column = PARTS[kind], column_of(group, reading)[0] + else: + group, (column, suffix) = AIR_DEVICE, n.rsplit("_", 1) + part = AIR_PART[suffix] + got = parts.get(group) + if got is not None: + held.values[n] = {d: v for d, v in zip(got.days.day, getattr(got.days, part).get(column, ())) if v is not None} + for group, got in parts.items(): + for d, src in zip(got.days.day, got.days.source): + if group == AIR_DEVICE: + if src == "1hour": + held.hourly.add(d) + else: + held.station[d] = max(held.station.get(d, src), src, key=COARSER.get) + for d, why in got.left_out.items(): + held.left_out.setdefault(d, why) + held.missing.update(got.missing) + if got.note: + held.notes.append(got.note) + held.missing -= set(held.left_out) + if self.ctx.eco: # each day's look, from its whole day's figures + held.look = (await storage.read(day_values_on, self.ctx.eco.mac, list(LOOK_FIGURES), days))[0] + return held + + # ---------- the answer ---------- + async def handle(self, args: dict, meta: dict) -> str: + call = self.read(args) + devices = self.devices(call) # (each one the service has: read() refuses a field of a sensor it hasn't) + calendar = PublicHolidays(self.ctx.zone) + if call.only == "public_holiday" and not calendar.available: + raise Refusal(calendar.problem()) + tz, now = self.ctx.zone, self.ctx.now() + shown = list(dict.fromkeys([n for d in devices for n in SHOWN[d]] + call.named)) + first_held = await self.ctx.storage.read(self._first_held, devices, shown) + period, first, last = self.period(args, call, now, first_held) + if call.stretch and (last - first).days + 1 > MAX_HOURS_DAYS: + raise Refusal(f"With hours, a period is at most {MAX_HOURS_DAYS} days ({period.text} is {(last - first).days + 1}): send a " + "shorter one, such as \"past year\".", fits="past year") + asked = prepare(call.engine(first, last), self.units, tuple(n for d in devices for n in SHOWN[d]), + last + timedelta(days=1)) # ("today" for the engine: the day after the last, so it cuts nothing) + if isinstance(asked, str): # (the call was checked: the engine finds nothing more to refuse) + raise Refusal(asked) + held = await self._held(call, asked.shown, first, last, now.timestamp()) + merged = len(devices) > 1 + kind: Callable[[date], bool] = {None: lambda d: True, "weekend": lambda d: d.weekday() >= 5, + "public_holiday": lambda d: calendar.name(d) is not None}[call.only] + has = {device: {d for n in asked.shown if DEVICE_OF[n] == device for d in held.values[n]} for device in devices} + days = [d for d in asked.days if kind(d)] + both = [d for d in days if all(d in has[device] for device in devices)] + daily_out = {d for d in both if merged and held.station.get(d) == "daily"} + checked = [d for d in both if d not in daily_out] + + def row_extra(d: date) -> dict: + out = {} + if held.look is not None and (look := day_look({n: held.look[n].get(d) for n in LOOK_FIGURES}, latitude=self.ctx.eco.latitude, + day=d, so_far=d >= now.date())): + out["day_look"] = look + if call.only == "public_holiday": + out["holiday"] = calendar.name(d) + station = "daily" if held.station.get(d) == "daily" else "exact" + air = "hourly" if d in held.hourly else "exact" + out["source"] = {STATION: station, AIR_DEVICE: air} if merged else station if devices == [STATION] else air + return out + + turn = Turn() # (only its charts: the bars analyse draws) + scope = " · ".join(filter(None, [call.stretch.text if call.stretch else "", ONLY.get(call.only, "")])) + sourced = CHART_SOURCE.set(" and ".join(SOURCES[d] for d in devices)) + try: + got = analyse(held.values, asked, checked, tz, turn, row_extra, scope) + finally: + CHART_SOURCE.reset(sourced) + out = got.out + engine_period = out.pop("period") + out.pop("chart", None) # (the bot's hint: chart_note says what to do with a chart) + out.update(self._notes(call, asked, held, got, checked, days, daily_out, devices, merged, first_held)) + if (call.stat or call.count_only) and not call.group_by and (last - first).days >= 31: # one figure over months: was a breakdown meant? + out["note_group_by"] = GROUP_BY_NOTE + line = answer_line(out, engine_period, call.stretch) + fields = {"answer": line, **({"hours": {"text": call.stretch.text, "how_to_read": HOURS_HOW}} if call.stretch else {}), **out} + charts = with_charts(turn.charts, tz, meta) + if charts: + drawn = self.drawn_by(call, args, period, first, last, first_held, now.date()) + for chart in charts["charts"]: + chart["drawn_by"] = drawn + finished = complete(line) if call.chart_answers_it and charts and not needs_words(out) and not period.note else {} + return answer(period=period, as_of=now, **fields, **charts, **finished) + + def _notes(self, call: Call, asked, held: "Held", got, checked: list[date], days: list[date], daily_out: set[date], + devices: list[str], merged: bool, first_held: date | None) -> dict: + """The notes weather_days and air_days add, in their order, and those of a question mixing the two and of part of each day.""" + out: dict = {} + where, values, sort_by = asked.where, held.values, asked.sort_by + station = STATION in devices + if station: + # Days that would have ranked higher had a trace of rain counted: the answer should mention them + trace: list[date] = [] + rain_cond = next((c for c in where if c["field"] == "rain" and c["op"] in (">", ">=") and c["value"] > 0), None) + if rain_cond and lists_days(asked.args): + relaxed = [{"field": "rain", "op": ">", "value": 0} if c is rain_cond else c for c in where] + matched = set(got.matches) + better = operator.lt if call.order == "asc" else operator.gt + for d in got.rank(d for d in checked if got.holds(d, relaxed)): + if d in matched: + break # from here on the real matches rank at least as high + if not got.ranked or better(values[sort_by][d], values[sort_by][got.ranked[0]]): # strictly ahead, not a tie + trace.append(d) + if len(trace) == 2: + break + if trace: + out["trace_rain_days"] = [got.row(d) for d in trace] + out["note_trace"] = NOTE_TRACE.format(value=rain_cond["value"]) + run = daily_run(self.ctx.zone, asked.first, asked.last) + if daily_out: + out["daily_left_out"] = len(daily_out) + out["note_daily_left_out"] = NOTE_DAILY_LEFT_OUT.format(n=len(daily_out), run=run) + elif any(held.station.get(d) == "daily" for d in checked): + exact = sorted(d for d in checked if held.station.get(d) != "daily") + out["exact_from"] = day_text(exact[0]) if exact else None + out["note_daily"] = NOTE_DAILY.format(run=run) + if AVERAGED & set(asked.shown) and any(held.station.get(d) != "5min" for d in checked): + out["note_averaged"] = NOTE_AVERAGED + if AIR_DEVICE in devices: + hourly = [d for d in checked if d in held.hourly] + if hourly and any(n.endswith(("_max", "_min")) for n in asked.shown if DEVICE_OF[n] == AIR_DEVICE): + out["note_hourly"] = NOTE_HOURLY.format(n=len(hourly)) + if call.stretch is None and (missing := sum(1 for d in days if not held.counts.get(d))): + out["note_missing"] = NOTE_MISSING.format(n=missing) + if call.stretch: + reasons = [LEFT_OUT[held.left_out[d]] for d in days if d in held.left_out] + ["no readings" for d in days if d in held.missing] + if reasons: + out["left_out"] = {why: reasons.count(why) for why in dict.fromkeys(reasons)} + out["note_left_out"] = NOTE_LEFT_OUT + if held.notes: + out["note_moment"] = " ".join(dict.fromkeys(held.notes)) + if not checked: + before = first_held is not None and asked.last < first_held # (what the data does reach: 3.2, errors that teach) + out["note"] = NOTE_BEFORE.format(first=day_text(first_held)) if before else NOTE_NOTHING + return out + + def drawn_by(self, call: Call, args: dict, period, first: date, last: date, first_held: date | None, today: date) -> dict: + """The call that drew the chart as the tool read it (3.7), every default filled in, the period in words, and the periods it is + worth drawing over: per month, 3 months, a year and the whole record (with hours, only while that is within its 400 days); per + year, none.""" + words = period.asked + if args.get("start") and not sends_period(args): # dates as words; one that runs to today or later as "to now", so a replay moves on with the clock + open_ended = not args.get("end") or str(args["end"])[:10] >= today.isoformat() + words = f"{first.isoformat()} to {'now' if open_ended else last.isoformat()}" + arguments = {"where": call.where, "sort_by": self.sort_of(call), "order": call.order, "count_only": call.count_only, + "group_by": call.group_by, "stat": call.stat, **({"of": call.of} if call.of else {}), "limit": call.limit, + **({"only": call.only} if call.only else {}), **({"hours": _stretch_words(call.stretch)} if call.stretch else {}), + "period": words, "chart_answers_it": call.chart_answers_it} + periods = [] + if call.group_by == "month": + fits = not call.stretch or (first_held is not None and (today - first_held).days + 1 <= MAX_HOURS_DAYS) + periods = [{"period": p, "label": label} for p, label in MONTH_PERIODS if p != DEFAULT or fits] + return {"tool": NAME, "arguments": arguments, "periods": periods} + + def sort_of(self, call: Call) -> str: + """The field the days are ranked by: sort_by, else the first condition's field, else `of`, else the first shown (daytable).""" + return call.sort_by or (call.where[0]["field"] if call.where else call.of or SHOWN[self.devices(call)[0]][0]) + + +@dataclass +class Held: + """What DaysTool._held read: each shown field's figure per day; the station's source of each day ("5min", "30min", "daily"); the air + sensor's days held only as hourly averages, and (whole days) its readings per day; with `hours`, the days left out (and why) and + those with no readings in the stretch, and what a moment was on coarser days; and each day's figures for its look.""" + values: dict[str, dict[date, float]] + station: dict[date, str] = field(default_factory=dict) + hourly: set[date] = field(default_factory=set) + counts: dict[date, int | None] = field(default_factory=dict) + left_out: dict[date, str] = field(default_factory=dict) + missing: set[date] = field(default_factory=set) + notes: list[str] = field(default_factory=list) + look: dict[str, dict[date, float]] | None = None + + +def needs_words(out: dict) -> bool: + """Does the result carry a note the person should hear that the answer line leaves out (the older days held only as daily records + or hourly averages, a rarer day that nearly counted, days left out ...)? Then it is never complete (3.7).""" + notes = {k for k in out if k.startswith("note") or k.endswith("_note") or k in ("warning", "missing", "exact_from", "trace_rain_days")} + return bool(notes - CAPTIONED_NOTES) + + +# ---------- the answer line (the old lib/report.py's days lookup, ported with its words) ---------- +def period_words(text: str) -> str: + """"Tue 29 Sep 2026 - Tue 6 Oct 2026" -> "Tue 29 Sep – Tue 6 Oct 2026" (the first year is dropped only when it is the same year).""" + years = re.findall(r" (20\d\d)\b", text) + if len(years) == 2 and years[0] == years[1]: + text = re.sub(r" 20\d\d\b(?= - )", "", text) + return text.replace(" - ", " – ") + + +def answer_line(out: dict, period: str, stretch: Stretch | None = None) -> str: + """"137 of 1,454 days with UV index ≥ 10 (period).", or a total, average, highest or lowest over the period ("Total rain: 49.8 mm + over 30 days (period).") as the bot writes a days lookup today; `period` is the days' "first - last". Over part of each day the line + says which part first ("Each night (22:00–06:00): ...", "Each day at 15:00: ...").""" + when = period_words(period) + if out.get("stat") and out.get("value") is not None: + unit = unit_text(out["stat"].get("unit")) or "" + line = f"{out['stat']['what']}: {out['value']:g} {unit}".rstrip() + f" over {out['days_checked']:,} days ({when})." + else: + what = f" with {out['condition']}" if out.get("condition") else "" + note = " Older days use averages, so a count near the limit may fall slightly short." if out.get("note_averaged") else "" + line = f"{out['matching_days']:,} of {out['days_checked']:,} days{what} ({when}).{note}" + if stretch is None: + return line + each = f"Each {stretch.text}" if stretch.name else f"Each day at {stretch.text}" if stretch.moment else f"Each day {stretch.text}" + return f"{each}: {line}" + + +def tools(ctx: Context) -> list[ServiceTool]: + """The days tool, when there is a sensor to read.""" + return [DaysTool(ctx).tool()] if ctx.eco or ctx.air else [] + + +__all__ = ["DESCRIPTION", "DaysTool", "answer_line", "needs_words", "parameters", "tools"] diff --git a/lib/service/forecast.py b/lib/service/forecast.py new file mode 100644 index 00000000..8a4619d6 --- /dev/null +++ b/lib/service/forecast.py @@ -0,0 +1,244 @@ +"""The `forecast` tool (docs/ecobot-mcp.md 3.3): today and the days ahead, from the forecast source (lib/forecast, Open-Meteo), for a +period in words that look ahead ("tomorrow", "next 3 days", "this weekend"), read here: lib/periods_text.py reads only what has been +measured, and refuses the future by pointing to this tool. + +The answer is today's weather_forecast's, in the service's shape: the same `lines` (lib/forecast/source.py day_label and describe_day), +each day's figures in `days`, `place`, `source` and `fetched_at`, and `text`, the bot's forecast section ("Forecast (Melbourne, +6:00pm)" and a bullet per line, the old lib/report.py's report and lookup) written here so a client can send it as it is. +Request `_meta` `fetch: false` answers from the forecast held, fetching nothing (the report's `cached`). + +`section` writes a heading and bullets as the bot does for the sources that bring their own lines (pollen.py uses it too), and +`held_days` and `day_lines` are what outlook.py reads the forecast with. +""" + +import logging +import re +from datetime import date, datetime, time, timedelta, tzinfo + +from ..forecast.source import SOURCE, day_label, describe_day +from ..periods_text import NUMBER_WORDS, WEEKDAY_NAMES, Period, PeriodError, read_period as read_past +from ..timeutil import clock_text, day_text, to_local +from .common import Refusal, ServiceTool, answer, iso + +log = logging.getLogger(__name__) + +DEFAULT = "the next 7 days" # weather_forecast's default: today and the six days after it +HEADING = "Forecast" # the bot's heading for it (the old lib/report.py SECTIONS) +NO_FORECAST = "No forecast is available right now." # (weather_forecast's own words) +FOR_WHAT_WAS = "summary (or days, for days ranked or counted)" + +# ---------- the period, looking ahead ---------- +_N = rf"(?P<n>\d+|{'|'.join(NUMBER_WORDS)})" +_WEEKDAYS = {name.lower(): i for i, name in enumerate(WEEKDAY_NAMES)} | { + "mon": 0, "tue": 1, "tues": 1, "wed": 2, "weds": 2, "thu": 3, "thur": 3, "thurs": 3, "fri": 4, "sat": 5, "sun": 6} +# "over the weekend", "for tomorrow", "in the next 3 days" (but not "in 3 days", which is one day) +LEAD = re.compile(r"(?:in (?=the |next |coming |upcoming )|(?:over|during|for|within|across|throughout|on|from) )(?P<rest>.+)") +TODAY = re.compile(r"today|(?:the )?rest of (?:the|to)day|later(?: today| on)?|tonight|this (?:afternoon|evening)") +TOMORROW = re.compile(r"tomorrow(?: (?:morning|afternoon|evening|night))?") +AFTER_TOMORROW = re.compile(r"(?:the )?day after tomorrow") +NEXT_DAYS = re.compile(rf"(?:(?:the )?(?:next|coming|upcoming|following) )?{_N} ?(?:days?|d)") +WEEK_AHEAD = re.compile(r"this week|(?:the )?week ahead|(?:the )?(?:coming|upcoming|following) week|(?:the )?week|1 ?w") +WEEKEND = re.compile(r"(?:this |the )?weekend") +NEXT_WEEK = re.compile(r"next week") +WEEKDAY = re.compile(rf"(?:(?P<next>next|this|coming) )?(?P<wd>{'|'.join(sorted(_WEEKDAYS, key=len, reverse=True))})") +ISO_DAY = re.compile(r"\d{4}-\d\d-\d\d") +FORMS = ( # (form, an example read now): what a refusal lists + ("today (also tonight, later today: the forecast is by day)", "today"), + ("tomorrow", "tomorrow"), + ("the day after tomorrow", "the day after tomorrow"), + ("next N days, N days, Nd (N from 1: today and the N-1 days after it)", "next 3 days"), + ("the next 7 days, this week, the week ahead, the coming week", "the next 7 days"), + ("this weekend, the weekend (Saturday and Sunday; from today when it is one)", "this weekend"), + ("next week (Monday to Sunday)", "next week"), + ("Monday … Sunday, this Saturday, next Saturday (the next one; a bare weekday is today when it is one)", "Saturday"), + ("a date, YYYY-MM-DD", None), +) + + +def days_text(first: date, last: date) -> str: + """"Tue 10 Nov 2026", "Tue 10 – Mon 16 Nov 2026", "Mon 28 Dec 2026 – Sun 3 Jan 2027": days as the periods' texts write them.""" + if first == last: + return day_text(first) + if (first.year, first.month) == (last.year, last.month): + return f"{first:%a} {first.day} – {day_text(last)}" + return f"{day_text(first, year=first.year != last.year)} – {day_text(last)}" + + +def _ahead(p: str, today: date) -> tuple[str | None, date, date] | None: + """(its label, the first day, the last day) of words that look ahead, or None when they are none of the forms.""" + if TODAY.fullmatch(p): + return "today", today, today + if TOMORROW.fullmatch(p): + return "tomorrow", today + timedelta(days=1), today + timedelta(days=1) + if AFTER_TOMORROW.fullmatch(p): + return "the day after tomorrow", today + timedelta(days=2), today + timedelta(days=2) + if m := NEXT_DAYS.fullmatch(p): + n = int(m["n"]) if m["n"].isdigit() else NUMBER_WORDS[m["n"]] + if n < 1: + return None + return ("today" if n == 1 else f"the next {n} days"), today, today + timedelta(days=n - 1) + if WEEK_AHEAD.fullmatch(p): + return "the next 7 days", today, today + timedelta(days=6) + if WEEKEND.fullmatch(p): + saturday = today + timedelta(days=(5 - today.weekday()) % 7) if today.weekday() < 5 else today - timedelta(days=today.weekday() - 5) + return "this weekend", max(saturday, today), saturday + timedelta(days=1) + if NEXT_WEEK.fullmatch(p): + monday = today + timedelta(days=7 - today.weekday()) + return "next week", monday, monday + timedelta(days=6) + if m := WEEKDAY.fullmatch(p): + wd = _WEEKDAYS[m["wd"]] + ahead = (wd - today.weekday()) % 7 + if m["next"] == "next" and not ahead: + ahead = 7 + day = today + timedelta(days=ahead) + return WEEKDAY_NAMES[wd], day, day + if ISO_DAY.fullmatch(p): + try: + day = date.fromisoformat(p) + except ValueError: + return None + return None, day, day + return None + + +def _forms(today: date) -> dict[str, str]: + """{form: what it means now}: every form a refusal lists, read today.""" + out = {} + for form, example in FORMS: + example = example or (today + timedelta(days=2)).isoformat() + label, first, last = _ahead(example.lower(), today) + out[form] = f"{label}: {days_text(first, last)}" if label else days_text(first, last) + return out + + +def read_ahead(words: str | None, now: datetime, tz: tzinfo) -> Period: + """The days a forecast is asked for, from words that look ahead (DEFAULT when none), as a Period: `start` the first day's midnight, + `end` the midnight after the last, `text` how the words were read ("this weekend: Sat 14 – Sun 15 Nov 2026"). Raises Refusal: for + words that are in the past (pointing to summary), and for words that are none of the forms (listing each with what it means now).""" + asked = str(words).strip() if words is not None and str(words).strip() else DEFAULT + local = now.astimezone(tz) if now.tzinfo else now + today = local.date() + it_is_now = f"It is now {day_text(local)} {clock_text(local)}." + p = " ".join(asked.replace("’", "'").lower().split()) + lead = LEAD.fullmatch(p) + read = _ahead(p, today) or (lead and _ahead(lead["rest"], today)) + if read and read[1] < today: + raise Refusal(f"{asked!r} is in the past ({days_text(read[1], read[2])}): the forecast is for today and the days ahead. For what " + f"was measured, use {FOR_WHAT_WAS}. {it_is_now}", forms=_forms(today)) + if not read: + try: # words for what has been measured ("yesterday", "last week"): the tool for them is another + past = read_past(asked, None, None, now=now, tz=tz, default=asked) + except PeriodError: + past = None + if past is not None: + raise Refusal(f"{asked!r} reads as a period that has been measured ({past.text}), not days ahead: the forecast is for today " + f"and the days ahead. For what was measured, use {FOR_WHAT_WAS}. {it_is_now}", forms=_forms(today)) + raise Refusal(f"{asked!r} isn't a period the forecast can read. Send `period` as one of these forms, as a whole phrase (N is a " + f"number, in digits or a word up to twelve). {it_is_now}", forms=_forms(today)) + label, first, last = read + text = f"{label}: {days_text(first, last)}" if label else days_text(first, last) + return Period(asked, datetime.combine(first, time(), tzinfo=tz), datetime.combine(last + timedelta(days=1), time(), tzinfo=tz), text) + + +# ---------- the forecast held ---------- +async def held_days(forecast, today: date, fetch: bool) -> list[dict]: + """The forecast's days from today on, as held; when it holds none of them and `fetch` allows, it is fetched first (Forecast.warm, + which keeps to its own hours and pace), as weather_forecast does when nothing is held.""" + if fetch and not any(d["date"] >= today for d in forecast.days or []): + try: + await forecast.warm(True) + except Exception as e: + log.warning("Forecast not readable: %s", e) + return [d for d in forecast.days or [] if d["date"] >= today] + + +def day_lines(days: list[dict], today: date) -> list[str]: + """weather_forecast's lines for these days: "Today: 🌧️ Rain. 11–17°C, 90% chance of at least 1 mm", then each day by its + weekday.""" + return [f"{day_label(d['date'], today)}: {describe_day(d)}" for d in days] + + +def day_figures(d: dict) -> dict: + """A day of the forecast as figures: {date, min, max, summary, rain_chance, rain_1mm_pct} (°C and %; None where it has none).""" + return {"date": d["date"].isoformat(), "min": d.get("min_c"), "max": d.get("max_c"), "summary": d.get("summary") or None, + "rain_chance": d.get("rain_chance_pct"), "rain_1mm_pct": d.get("rain_1mm_pct")} + + +def section(heading: str, lines: list[str], *, place: str | None, fetched_at: float | None, tz: tzinfo, today: date) -> str: + """A source's lines as the bot wrote them in the report and alone (the old lib/report.py _heading, _own_lines): "Forecast (Melbourne, + 6:00pm)", the place and the time it was fetched (with its day when that isn't `today`), then "• " and each line.""" + stamp = None + if fetched_at: + at = to_local(int(fetched_at), tz) + stamp = clock_text(at) if at.date() == today else f"{day_text(at, year=False)} {clock_text(at)}" + note = ", ".join(x for x in (place, stamp) if x) + return "\n".join([f"{heading} ({note})" if note else heading, *(f"• {line}" for line in lines)]) + + +# ---------- the tool ---------- +DESCRIPTION = ( + "The weather forecast (Open-Meteo) for the station's place: today and the days ahead, each day's summary with its emoji, its lowest " + "and highest temperature and the chance of at least 1 mm of rain. For \"what's tomorrow like\": {\"period\": \"tomorrow\"}; \"the " + "forecast for the weekend\": {\"period\": \"this weekend\"}; \"will it rain this week\", \"forecast\": {} (the next 7 days). A " + "report (\"report\", \"status\", \"sitrep\") is current, forecast {\"period\": \"today\"} and pollen, called together.\n" + "Not for: the next few hours from the station's own readings (\"will it rain soon\", \"do I need an umbrella\": outlook); what was " + "measured, a device or reading with a period (\"weather week\", \"ecowitt week\": the past week, summary; days, for days " + "ranked or counted). Only what is ahead is forecast.\n" + "Result: `period` (how the words were read, with the dates); `text`, the whole answer for the person, ready to send; `lines`, one a " + "day, emoji included: copy them as they are, with the place in parentheses after the heading, e.g. Forecast (Melbourne); `days`, " + "each day's figures (min and max °C, rain_chance: Open-Meteo's chance of rain, rain_1mm_pct: the chance of at least 1 mm, the one " + "the lines give when there is one); `place`, `fetched_at`; `note` when the forecast doesn't reach the end of the period.") +PARAMETERS = {"type": "object", "properties": {"period": { + "type": "string", + "description": "The days ahead in the person's own words, passed on unchanged: today, tomorrow, the day after tomorrow, next N days " + "(N from 1: today and the N-1 days after it; also N days, Nd), the next 7 days or this week, this weekend, next week " + "(Monday to Sunday), a weekday (Saturday: the next one, today when it is one), or a date (YYYY-MM-DD). The " + f"forecast reaches 7 days from today. Default: {DEFAULT}."}}} + + +def tools(ctx) -> list[ServiceTool]: + """The `forecast` tool, when the forecast is switched on.""" + if ctx.forecast is None: + return [] + + async def handle(args: dict, meta: dict) -> str: + fc = ctx.forecast + tz, now = clock_of(ctx, fc.tz) + today = now.date() + if args.get("start") or args.get("end"): + raise Refusal("The forecast takes `period` in words, not `start` and `end`: send one of these forms.", forms=_forms(today)) + period = read_ahead(args.get("period"), now, tz) + first, last = period.first_day, period.last_day + held = await held_days(fc, today, meta["fetch"]) + if not held: + raise Refusal(NO_FORECAST) + days = [d for d in held if first <= d["date"] <= last] + reaches = held[-1]["date"] + if not days: + raise Refusal(f"The days asked for ({period.text}) are beyond the forecast, which reaches {day_text(reaches)}: ask for days " + f"up to then (the next 7 days is all of it).", reaches=reaches.isoformat()) + lines = day_lines(days, today) + note = {"note": f"The forecast reaches only {day_text(reaches, year=False)}: the days after it aren't forecast yet."} \ + if reaches < last else {} + fetched = to_local(int(fc.fetched_at), tz) if fc.fetched_at else None + return answer(period=period, as_of=fetched, + text=section(HEADING, lines, place=fc.place, fetched_at=fc.fetched_at, tz=tz, today=today), + lines=lines, days=[day_figures(d) for d in days], **note, + **({"place": fc.place} if fc.place else {}), source=SOURCE, + **({"fetched_at": iso(fetched)} if fetched else {})) + + return [ServiceTool("forecast", DESCRIPTION, PARAMETERS, handle, open_world=True)] + + +def clock_of(ctx, fallback: tzinfo) -> tuple[tzinfo, datetime]: + """(the station's zone, the time now in it) from the context; the source's own zone when the context has no device to name one + (Context.zone asks the station or the air sensor).""" + try: + tz = ctx.zone + except AttributeError: + tz = fallback + return tz, to_local(int(ctx.clock()), tz) + + +__all__ = ["DEFAULT", "DESCRIPTION", "PARAMETERS", "clock_of", "day_figures", "day_lines", "days_text", "held_days", "read_ahead", + "section", "tools"] diff --git a/lib/service/instructions.py b/lib/service/instructions.py new file mode 100644 index 00000000..05ed644d --- /dev/null +++ b/lib/service/instructions.py @@ -0,0 +1,93 @@ +"""The server's instructions (docs/ecobot-mcp.md 3.2): a short summary of what the tools read, for a client that passes it to its model +(over MCP a client gets it by asking: `server/discover`). Nothing depends on it: every rule a choice of tool or the reading of a result +depends on is in the tool's description or in the result, and the evals are run with and without it (`--live --service +--instructions`, docs 7). + +It says: the devices there are (the Context's sources) and the nicknames people use for them, which readings are Indoor and Outdoor, +the readings' names, the units each reading comes in (from the catalogue: only the readings held), the station's time zone, that a period is passed on +in the person's own words, and that every question is fetched afresh (the results say so too, `fresh`, but a client may drop +earlier tool turns from its history). `instructions(ctx)` builds it; INSTRUCTIONS is it for every device and every reading the service knows. +""" + +from .names import AIR_DEVICE, CATALOGUE, STATION, Catalogue + +PLAIN = ("Outdoor ", "Indoor ", "AirGradient ", "Piezo ", "Absolute ") # (a label's side or device, left out where units are listed) +KEEP_CASE = ("PM", "CO", "UV", "VOC", "NOx") # (labels that keep their capitals) + + +def _plain(label: str) -> str: + for prefix in PLAIN: + label = label.removeprefix(prefix) + return label if label.startswith(KEEP_CASE) else label[:1].lower() + label[1:] + + +def units(catalogue: Catalogue) -> str: + """"°C: temperature, dew point …; %: humidity; …; no unit: UV index …": each unit with what comes in it, in the catalogue's + order, sides and devices aside.""" + by_unit: dict[str, list[str]] = {} + for r in catalogue: + what = by_unit.setdefault(r.unit, []) + if (plain := _plain(r.label)) not in what: + what.append(plain) + listed = [f"{unit}: {', '.join(what)}" for unit, what in by_unit.items() if unit] + if "" in by_unit: + listed.append(f"no unit (an index): {', '.join(by_unit[''])}") + return "; ".join(listed) + + +def names(catalogue: Catalogue) -> str: + """"outdoor and indoor: temperature, humidity …; pressure: relative, absolute; …": each sensor with its readings' names, in the + catalogue's order, sensors with the same readings together (a model must not make up a name: rain.rain_rate).""" + by_sensor: dict[str, list[str]] = {} + for r in catalogue: + sensor, _, reading = r.name.partition(".") + by_sensor.setdefault(sensor, []).append(reading) + alike: dict[tuple[str, ...], list[str]] = {} + for sensor, readings in by_sensor.items(): + alike.setdefault(tuple(readings), []).append(sensor) + return "; ".join(f"{' and '.join(sensors)}: {', '.join(readings)}" for readings, sensors in alike.items()) + + +def instructions(ctx=None) -> str: + """The instructions for the service over this Context (lib/service/context.py): its sources, the readings its catalogue holds and + its zone. With no ctx: every source, every reading the service knows, no zone named.""" + catalogue = ctx.readings() if ctx is not None else CATALOGUE + station = ctx.eco is not None if ctx is not None else True + air = ctx.air is not None if ctx is not None else True + forecast = ctx.forecast is not None if ctx is not None else True + pollen = ctx.pollen is not None if ctx is not None else True + station = station and any(r.device == STATION for r in catalogue) + air = air and any(r.device == AIR_DEVICE for r in catalogue) + + devices = [] + if station: + devices.append("the weather station (Ecowitt; \"ecowitt\", \"the weather station\", \"the station\"), outdoors, with an " + "indoor sensor") + if air: + devices.append("the air sensor (AirGradient, for air quality; \"ag\", \"airgradient\", \"air gradient\")") + extra = [*(["a forecast (Open-Meteo)"] if forecast else []), + *(["grass pollen and thunderstorm asthma (Melbourne, Oct–Dec)"] if pollen else [])] + lines = [f"The devices: {'; '.join(devices) or 'none'}." + (f" Also: {'; '.join(extra)}." if extra else "")] + if station: + sides = ("Indoor and Outdoor: a bare reading is the station's; temperature and humidity are both " + "(outdoor.temperature, indoor.temperature), the rest outdoor.") + if air: + sides += (" The air sensor is outdoors: its own temperature and humidity are only air.temperature and air.humidity; " + "no indoor air quality.") + lines.append(sides) + held = Catalogue(r for r in catalogue if (r.device == STATION and station) or (r.device == AIR_DEVICE and air)) + if held.names: + lines.append(f"Names (sensor.reading): {names(held)}.") + lines.append(f"Units: {units(held)}. Rain: mm that fell.") + zone = getattr(ctx.zone, "key", None) if ctx is not None and (ctx.tz or ctx.eco or ctx.air) else None + when = f"The station's clock is {zone} time; " if zone else "Times are the station's local time; " + lines.append(when + "pass a period in the person's own words (`period`: \"past week\", \"since 6am\"); the tools " + "read it.") + lines.append("Fetch for every question; never reuse earlier figures: call again at once, unasked, on a follow-up or a " + "challenge (\"that's wrong\").") + return "\n".join(lines) + + +INSTRUCTIONS = instructions() # every device and every reading the service knows (the evals; a server that hasn't read its file) + +__all__ = ["INSTRUCTIONS", "instructions", "names", "units"] diff --git a/lib/service/names.py b/lib/service/names.py new file mode 100644 index 00000000..4a90783a --- /dev/null +++ b/lib/service/names.py @@ -0,0 +1,327 @@ +"""The readings the service has, one name each, and the words people use for them (docs/ecobot-mcp.md 3.2, "One naming scheme"). + +A reading's name is `sensor.reading`: the weather station's Ecowitt group and the reading's column (`outdoor.temperature`, +`indoor.humidity`, `pressure.relative`, `wind.wind_gust`), with rain as `rainfall.rain`, the mm that fell (the file keeps the running +daily total), and the air sensor's as `air.pm2_5` … `air.nox_index`, its own temperature and humidity `air.temperature` and +`air.humidity`. The catalogue holds the readings the file holds (lib/history.py's station_metrics and air_metrics, from the fields the +station has sent): `Catalogue.open(eco, air)`, or `CATALOGUE`, every reading the service knows, before any file is read (the evals). + +`resolve` reads the names a tool is sent, the full names or the words people use: + - a bare reading is the weather station's: `temperature` and `humidity` are outdoor and indoor, never the air sensor's (that is only + ever `air.temperature`, `air.humidity`, or the AirGradient named: "airgradient humidity"); `dew point`, `feels like` and `vpd` + are outdoor's; `outdoor humidity`, `indoor temp` name the side; + - `pressure` is relative pressure, `rain` the main gauge, `uv`, `solar`, `gust`, `rain rate`, the air sensor's `pm2.5`, `co2` …; + - `wind` is its speed shaded up to the gusts (the entry's `band`), and its direction, the compass rose on a chart; + - a sensor's name (`outdoor`, `indoor`, `wind`, `rainfall`, `air` …) is its usual set (SENSOR_SETS); `all` is every weather-station + reading, in the station's usual chart order (in_all); the devices' nicknames are their readings ("ecowitt": all; "ag": `air`). +A name or word it can't read raises UnknownReading, a Refusal that lists the names and the words with what each stands for. +""" + +import re +from collections.abc import Iterable +from dataclasses import dataclass, replace + +from ..history import AIR_SENSOR, RAIN, Metric, air_metrics, station_fields, station_metrics +from ..series import AIR, AIR_EXTRA, INDOOR_READINGS, WEATHER +from ..storage.catalogue import label_of +from .common import Refusal + +STATION, AIR_DEVICE = "station", "air" # the two devices: the Ecowitt weather station, the AirGradient air sensor + +# ---------- "all" ---------- +# The settings "all" follows: the panels of "weather all week", top to bottom, as lib/series.py names the readings. intent.chart_fields +# reads them here too. ecobot.py sets the two flags from the config (MCP_CHART_ALL_FEELS_LIKE, MCP_CHART_ALL_VPD) at startup. +ALL_ORDER = ("temperature", "humidity", "solar", "pressure", "rain", "dew_point", "feels_like", "vpd", "uv", "wind") +LEFT_OUT_OF_ALL = ("uv",) # the UV index has the same shape as solar radiation +FEELS_LIKE_IN_ALL = False # the feels-like panel: off, as it nearly repeats temperature +VPD_IN_ALL = False # the vapour pressure deficit panel: off, as it is temperature and humidity combined + + +def in_all() -> list[str]: + """The readings "all" is, as lib/series.py names them, in the station's usual chart order, with the settings applied.""" + return [n for n in ALL_ORDER if n not in LEFT_OUT_OF_ALL and (FEELS_LIKE_IN_ALL or n != "feels_like") and (VPD_IN_ALL or n != "vpd")] + + +# ---------- the words ---------- +# A reading named bare (lib/series.py's names): the weather station's. Temperature and humidity are both sides; the others outdoor's. +BARE = {"temperature": ("outdoor.temperature", "indoor.temperature"), "humidity": ("outdoor.humidity", "indoor.humidity"), + "pressure": ("pressure.relative",), "wind": ("wind.wind_speed", "wind.wind_direction"), "rain": ("rainfall.rain",), + "dew_point": ("outdoor.dew_point",), "feels_like": ("outdoor.feels_like",), "vpd": ("outdoor.vpd",), + "solar": ("solar_and_uvi.solar",), "uv": ("solar_and_uvi.uvi",)} +# A sensor named: its usual set, what the station's gauges show for it (lib/ecowitt/dashboard.py GAUGES), wind with its direction; the +# air sensor's six air-quality readings (its own temperature and humidity are named, never part of a set). +SENSOR_SETS = {"outdoor": ("outdoor.temperature", "outdoor.humidity", "outdoor.dew_point", "outdoor.feels_like"), + "indoor": ("indoor.temperature", "indoor.humidity"), + "pressure": ("pressure.relative",), + "wind": BARE["wind"], + "rainfall": ("rainfall.rain", "rainfall.rain_rate"), + "rainfall_piezo": ("rainfall_piezo.rain", "rainfall_piezo.rain_rate"), + "solar_and_uvi": ("solar_and_uvi.solar", "solar_and_uvi.uvi"), + AIR_SENSOR: tuple(f"air.{n}" for n in AIR)} +ALL = ("all",) # (stands for in_all(), read when resolved: the settings can change) +# The words people use, after _key (lower case, "_" and "-" as spaces) -> the names they stand for +ALIASES: dict[str, tuple[str, ...]] = { + **{_name.replace("_", " "): _names for _name, _names in SENSOR_SETS.items()}, + "outside": SENSOR_SETS["outdoor"], "outdoors": SENSOR_SETS["outdoor"], "inside": SENSOR_SETS["indoor"], "indoors": SENSOR_SETS["indoor"], + "piezo": ("rainfall_piezo.rain",), "piezo rain": ("rainfall_piezo.rain",), "piezo rain rate": ("rainfall_piezo.rain_rate",), + "air quality": SENSOR_SETS[AIR_SENSOR], "aq": SENSOR_SETS[AIR_SENSOR], + # the devices: the weather station is all its readings, the air sensor its usual set + "all": ALL, "everything": ALL, "every reading": ALL, "weather": ALL, "ecowitt": ALL, "weather station": ALL, "station": ALL, + "ag": SENSOR_SETS[AIR_SENSOR], "airgradient": SENSOR_SETS[AIR_SENSOR], "air gradient": SENSOR_SETS[AIR_SENSOR], + "air sensor": SENSOR_SETS[AIR_SENSOR], + # the weather station's readings, named bare + **{_w: BARE["temperature"] for _w in ("temperature", "temp", "temperatures")}, + "humidity": BARE["humidity"], + **{_w: BARE["pressure"] for _w in ("barometer", "barometric pressure", "relative pressure", "air pressure")}, + "absolute pressure": ("pressure.absolute",), "station pressure": ("pressure.absolute",), + "wind": BARE["wind"], "wind speed": ("wind.wind_speed",), "windspeed": ("wind.wind_speed",), + **{_w: ("wind.wind_gust",) for _w in ("gust", "gusts", "wind gust", "wind gusts")}, + "wind direction": ("wind.wind_direction",), "direction": ("wind.wind_direction",), + "rain": BARE["rain"], "precipitation": BARE["rain"], + "rain rate": ("rainfall.rain_rate",), "rainrate": ("rainfall.rain_rate",), "rain intensity": ("rainfall.rain_rate",), + "dew point": BARE["dew_point"], "dewpoint": BARE["dew_point"], + "feels like": BARE["feels_like"], "feelslike": BARE["feels_like"], + "apparent temperature": ("outdoor.app_temp",), "app temp": ("outdoor.app_temp",), + **{_w: BARE["vpd"] for _w in ("vpd", "vapour pressure deficit", "vapor pressure deficit")}, + **{_w: BARE["solar"] for _w in ("solar", "solar radiation", "radiation", "sunshine")}, + **{_w: BARE["uv"] for _w in ("uv", "uvi", "uv index", "ultraviolet")}, + # the air sensor's + **{_w: ("air.pm2_5",) for _w in ("pm2.5", "pm25", "pm 2.5", "pm2 5", "pm 25")}, + **{_w: ("air.pm10",) for _w in ("pm10", "pm 10")}, + **{_w: ("air.pm1",) for _w in ("pm1", "pm 1", "pm1.0", "pm 1.0")}, + **{_w: ("air.co2",) for _w in ("co2", "co₂", "co 2", "carbon dioxide")}, + **{_w: ("air.voc_index",) for _w in ("voc", "vocs", "tvoc", "voc index")}, + **{_w: ("air.nox_index",) for _w in ("nox", "nox index")}, +} +CLIMATE_WORDS = {"temperature": "temperature", "temp": "temperature", "humidity": "humidity", "dew point": "dew_point", + "dewpoint": "dew_point", "feels like": "feels_like", "apparent temperature": "app_temp", "app temp": "app_temp", + "vpd": "vpd", "vapour pressure deficit": "vpd", "vapor pressure deficit": "vpd"} # after "outdoor", "indoor" +AIR_OWN = {"temperature": "air.temperature", "temp": "air.temperature", "humidity": "air.humidity"} # after "air.", "airgradient" +SIDE = re.compile(r"(?P<side>outdoors?|outside|indoors?|inside)[. ](?P<rest>.+)") +DEVICE = re.compile(r"(?:air\.|(?:airgradient|air gradient|ag)[. ])(?P<rest>.+)") +LEGACY = {"air.air_temperature": "air.temperature", "air.air_humidity": "air.humidity", "air_temperature": "air.temperature", + "air_humidity": "air.humidity", "rainfall.daily": "rainfall.rain", "rainfall_piezo.daily": "rainfall_piezo.rain"} # today's names +AMBIGUOUS = {"air temperature": ("outdoor.temperature", "air.temperature"), "air temp": ("outdoor.temperature", "air.temperature"), + "air humidity": ("outdoor.humidity", "air.humidity")} # plain English for the weather, or the air sensor's own +# The words a description and a refusal list, one for each meaning, in this order +WORDS = ("temperature", "humidity", "dew point", "feels like", "vpd", "pressure", "wind", "gust", "wind direction", "rain", "rain rate", + "solar", "uv", "pm2.5", "pm10", "pm1", "co2", "voc", "nox", "outdoor", "indoor", "rainfall", "air", "all", "ecowitt", + "weather station", "ag", "airgradient", "air gradient") + + +def _key(word: str) -> str: + return " ".join(str(word).lower().replace("_", " ").replace("-", " ").split()) + + +# ---------- a reading ---------- +CLIMATE_LABELS = {"temperature": "temperature", "humidity": "humidity", "dew_point": "dew point", "feels_like": "feels like", + "app_temp": "apparent temperature", "vpd": "vapour pressure deficit"} +LABELS = {"pressure.relative": "Pressure", "pressure.absolute": "Absolute pressure", "wind.wind_speed": "Wind speed", + "wind.wind_gust": "Wind gust", "wind.wind_direction": "Wind direction", "rainfall.rain": "Rain", "rainfall.rain_rate": "Rain rate", + "rainfall_piezo.rain": "Piezo rain", "rainfall_piezo.rain_rate": "Piezo rain rate", "solar_and_uvi.solar": "Solar radiation", + "solar_and_uvi.uvi": "UV index"} +UNITS = {"wind_gust": "km/h"} # where the file names no unit and lib/history.py has none either +AIR_NAMES = {"air_temperature": "temperature", "air_humidity": "humidity"} # the air sensor's own: its column -> its reading's name +SERIES = {**{f"{r.group}.{RAIN if r.field == 'daily' else r.field}": name for name, r in WEATHER.items()}, + **{f"indoor.{WEATHER[name].field}": name for name in INDOOR_READINGS}} # a name -> lib/series.py's (station readings) + + +@dataclass(frozen=True) +class Reading: + """One reading of the catalogue.""" + name: str # "outdoor.temperature": `sensor.reading` + label: str # "Outdoor temperature", "Rain", "PM2.5", "AirGradient temperature" + unit: str # "°C", "mm", "µg/m³"; "" for an index (UV, VOC, NOx) + device: str # STATION or AIR_DEVICE + combine: str # how a stretch of readings is told as one: "mean" (over time), "max" (gusts: the highest), "last" (wind + # direction: the reading at its end), "rain" (the mm that fell, summed) + metric: Metric # how lib/history.py reads it (read_intervals, read_days): metric.kind, metric.column, metric.sensor + band: str | None = None # the reading its line is shaded up to, whose highest goes with it (wind speed: "wind.wind_gust") + series: str | None = None # its name in lib/series.py and lib/panels.py ("temperature" for both sides, "wind", "rain", "pm2_5") + + @property + def sensor(self) -> str: + """"outdoor", "rainfall", "air": the Ecowitt group, or the air sensor.""" + return self.name.split(".", 1)[0] + + @property + def reading(self) -> str: + return self.name.split(".", 1)[1] + + @property + def kind(self) -> str: + """The storage table it is in ("climate", "rain", "air" …).""" + return self.metric.kind + + @property + def column(self) -> str: + """The storage column read: rain's is "daily", the running daily total; the air sensor's own temperature "air_temperature".""" + return self.metric.column.name + + @property + def drawn(self) -> str: + """How a chart shows it: "bars" (rain), "rose" (wind direction, the compass rose beside the wind) or "line".""" + return "bars" if self.combine == RAIN else "rose" if self.reading == "wind_direction" else "line" + + +def _reading(m: Metric, held: set[str]) -> Reading: + if m.air: + reading = AIR_NAMES.get(m.reading, m.reading) + about = AIR.get(m.reading) or AIR_EXTRA[m.reading] + return Reading(f"air.{reading}", about.label, about.unit, AIR_DEVICE, m.how, m, series=m.reading) + name = m.name + label = f"{label_of(m.sensor)} {CLIMATE_LABELS[m.reading]}" if m.kind == "climate" else LABELS.get(name) or \ + f"{label_of(m.sensor)} {m.reading.replace('_', ' ')}" + band = "wind.wind_gust" if name == "wind.wind_speed" and "wind.wind_gust" in held else None + return Reading(name, label, m.unit or UNITS.get(m.reading, ""), STATION, m.how, m, band, SERIES.get(name)) + + +class UnknownReading(Refusal): + """A reading name or word the catalogue can't read: a Refusal listing the names it holds and the words with what each stands for.""" + + +# ---------- the catalogue ---------- +class Catalogue: + """The readings the service has, by name, in the order the file's groups and the air sensor's metrics come.""" + + def __init__(self, readings: Iterable[Reading]): + self.readings = {r.name: r for r in readings} + self._by_key = {_key(name): name for name in self.readings} + + @classmethod + def of(cls, sent: dict[str, dict[str, str]] | None = None, *, station: bool = True, air: bool = True) -> "Catalogue": + """The readings of the devices there are: the station's those its sensors have sent (`sent`: {group: {field: unit}}, as the + file's fields table has them; a group with nothing sent yet has every reading of its kind), and the air sensor's.""" + metrics = [*(station_metrics(sent) if station else []), *(air_metrics(extra=True) if air else [])] + held = {m.name for m in metrics} + return cls(_reading(m, held) for m in metrics) + + @classmethod + async def open(cls, eco=None, air=None) -> "Catalogue": + """The readings the file holds for these sources (Ecowitt, AirGradient; either may be None), as the readings tool reads them.""" + return cls.of(await station_fields(eco) if eco else None, station=eco is not None, air=air is not None) + + @classmethod + def listed(cls, entries: Iterable[dict]) -> "Catalogue": + """The catalogue another process holds, from the readings it lists ({name, label, unit}, as ecobot://station's sensors give + them: a client's, docs/ecobot-mcp.md step 5): each reading as this catalogue makes it, with the label and unit listed.""" + wanted = {e["name"]: e for e in entries if isinstance(e, dict) and e.get("name")} + made = (_reading(m, set(wanted)) for m in [*station_metrics(None), *air_metrics(extra=True)]) + return cls(replace(r, label=wanted[r.name].get("label") or r.label, unit=wanted[r.name].get("unit", r.unit)) + for r in made if r.name in wanted) + + @property + def names(self) -> list[str]: + return list(self.readings) + + def get(self, name: str) -> Reading | None: + return self.readings.get(name) + + def __contains__(self, name: str) -> bool: + return name in self.readings + + def __iter__(self): + return iter(self.readings.values()) + + def resolve(self, names, *, default) -> list[Reading]: + """The readings these names stand for, in the order named, each once. `names`: a name or words, a list of them, or a string of + them separated by commas or "and"; none (None, "", []) is `default`, read the same way. Raises UnknownReading.""" + words = _split(names) or _split(default) + out: dict[str, Reading] = {} + for word in words: + for r in self._one(word): + out.setdefault(r.name, r) + return list(out.values()) + + def words(self) -> dict[str, list[str]]: + """{word: the names it stands for here}, one word for each meaning (WORDS), those standing for nothing held left out.""" + found = {word: self._lookup(word) for word in WORDS} + return {word: [r.name for r in readings] for word, readings in found.items() if not isinstance(readings, str)} + + def description(self) -> str: + """What a tool's readings property says: the full names, the words, and the rule for bare names.""" + air = any(r.device == AIR_DEVICE for r in self) + station = any(r.device == STATION for r in self) + parts = [f"Readings, as `sensor.reading`: {', '.join(self.names)}."] + if station: + parts.append("Or the words people use. A bare reading is the weather station's: temperature and humidity are outdoor and " + "indoor" + (" (the AirGradient's own are only ever air.temperature and air.humidity)" if air else "") + "; " + "dew point, feels like and vpd are outdoor's; pressure is relative pressure; rain is the main gauge, the mm " + "that fell; also rain rate, gust, uv, solar, wind (its speed shaded up to the gusts, with its direction: the " + "compass rose on a chart).") + if air: + parts.append("The air sensor's: pm2.5, pm10, pm1, co2, voc, nox.") + sets = [s for s in ("outdoor", "indoor", "wind", "rainfall", AIR_SENSOR) if any(r.sensor == s for r in self)] + parts.append(f"A sensor's name ({', '.join(sets)}) is its usual set" + + ("; all is every weather-station reading" if station else "") + ".") + devices = [*(["ecowitt and weather station mean the weather station"] if station else []), + *(["ag, airgradient and air gradient the AirGradient air sensor"] if air else [])] + if devices: + parts.append(f"The devices: {', '.join(devices)}.") + return " ".join(parts) + + # ---------- one name ---------- + def _one(self, word: str) -> list[Reading]: + """The readings one name or word stands for; UnknownReading, with the names and the words, when it stands for none held.""" + found = self._lookup(word) + if isinstance(found, str): + raise UnknownReading(found, names=self.names, words=self.words()) + return found + + def _lookup(self, word: str) -> list[Reading] | str: + """The readings a name or word stands for, or why there are none.""" + exact = " ".join(str(word).lower().split()) + if exact in self.readings: + return [self.readings[exact]] + key = _key(exact) + if key in self._by_key: + return [self.readings[self._by_key[key]]] + if key in AMBIGUOUS and exact not in LEGACY: # ("air_temperature", today's name, is the air sensor's) + station, own = AMBIGUOUS[key] + return f"{word!r} could be the weather station's ({station}) or the AirGradient's own ({own}): send the one meant." + targets = (LEGACY[exact],) if exact in LEGACY else ALIASES.get(key) or _prefixed(key) + if targets is None: + return (f"{word!r} isn't a reading this service knows. Send names from `names`, or words from `words` (each with the names " + f"it stands for).") + if targets == ALL: + targets = tuple(n for name in in_all() for n in BARE[name]) + return [self.readings[t] for t in targets if t in self.readings] or \ + f"{word!r} means {', '.join(targets)}, which this service doesn't hold." + + +def _prefixed(key: str) -> tuple[str, ...] | None: + """"outdoor humidity", "indoor.temp", "airgradient humidity", "air.temp", "ag pm2.5": a reading on the sensor named.""" + if m := SIDE.fullmatch(key): + column = CLIMATE_WORDS.get(m["rest"]) + return (f"{'outdoor' if m['side'].startswith('out') else 'indoor'}.{column}",) if column else None + if m := DEVICE.fullmatch(key): + if m["rest"] in AIR_OWN: + return (AIR_OWN[m["rest"]],) + found = ALIASES.get(m["rest"]) + return found if found and found != ALL and all(n.startswith("air.") for n in found) else None + return None + + +def _split(names) -> list[str]: + """Names as sent: a string (commas, semicolons, "+", "&" or "and" between them) or a list of such strings.""" + if names is None: + return [] + items = names if isinstance(names, (list, tuple)) else [names] + return [w for item in items for w in (part.strip() for part in re.split(r"[,;+&]| and ", str(item))) if w] + + +CATALOGUE = Catalogue.of() # every reading the service knows, before any file is read: for descriptions and the evals + + +def resolve(names, *, default, catalogue: Catalogue | None = None) -> list[Reading]: + """Catalogue.resolve on `catalogue` (default CATALOGUE).""" + return (catalogue or CATALOGUE).resolve(names, default=default) + + +def names_description(catalogue: Catalogue | None = None) -> str: + """Catalogue.description of `catalogue` (default CATALOGUE).""" + return (catalogue or CATALOGUE).description() + + +__all__ = ["ALIASES", "ALL_ORDER", "AIR_DEVICE", "BARE", "CATALOGUE", "Catalogue", "FEELS_LIKE_IN_ALL", "LEFT_OUT_OF_ALL", "Reading", + "SENSOR_SETS", "STATION", "UnknownReading", "VPD_IN_ALL", "WORDS", "in_all", "names_description", "resolve"] diff --git a/lib/service/outlook.py b/lib/service/outlook.py new file mode 100644 index 00000000..1aa86401 --- /dev/null +++ b/lib/service/outlook.py @@ -0,0 +1,311 @@ +"""The `outlook` tool (docs/ecobot-mcp.md 3.3): will it rain in the next few hours. No arguments. + +The bot's prompt told the model how to read the station for this (lib/prompt.py, its "outlook" block) and fetched the reading now and +the last 3 hours for it (intent.model_prefetch). Here the same rules are worked out in code, from the station's 5-minute readings of +the last 3 hours (as Ecowitt.recent reads them) and its reading now, so any model gets the same read: + + - Pressure tendency (relative pressure over the 3 hours): falling when its highest came before its lowest, rising when the lowest + came first; the change is the highest minus the lowest. Down more than 3 hPa: rain likely; down 1 to 3 hPa: possible; under + 1 hPa (steady) or rising: unlikely. + - Each of these moves that a step towards rain: pressure under 1005 hPa (unsettled); moist air, humidity 90% or more or the + temperature within 2 °C of the dew point; wind picking up while the pressure falls. Pressure over 1020 hPa (settled) moves it a + step away. The verdict stays between unlikely and likely. + - Recent rain, a rain rate above 0 now or rain in the last hour, makes it likely: showers tend to go on for a while. + +The answer: {as_of, fresh, verdict, reason ("pressure down 2.4 hPa in 3 hours, humidity 91%"), pressure {hpa, change_hpa, tendency, +level, text}, moisture {humidity, dew_point_spread, moist, text}, recent_rain {rained, raining_now, rate_mm_h, last_hour_mm, text}, +wind_trend {trend, first_hour_kmh, last_hour_kmh, text}, [missing: what the station had none of], [forecast: today's and tomorrow's +lines, when the forecast is on, with forecast_note when it has none], [warning: the newest reading is old], how_to_read}. `read` +works it out from the readings alone; the tool fetches them (`readings`). +""" + +import logging +import math +from collections.abc import Sequence + +from ..ecowitt.reads import rows_on +from ..ecowitt.source import LIVE_GROUPS +from ..timeutil import clock_text, day_text, naive_local, to_local +from .common import BACKGROUND, Refusal, ServiceTool, answer +from .forecast import day_lines, held_days + +log = logging.getLogger(__name__) + +HOURS = 3 # the station's last 3 hours +RECENT_SECONDS = 3600 # rain in the last hour counts as recent +LIKELY_FALL_HPA = 3.0 # pressure down more than this: likely +STEADY_HPA = 1.0 # a change under this is steady +UNSETTLED_HPA = 1005.0 # pressure under this is unsettled ... +SETTLED_HPA = 1020.0 # ... over this, settled +MOIST_HUMIDITY = 90.0 # humidity at or above this ... +MOIST_SPREAD_C = 2.0 # ... or the temperature within this of the dew point: moist air +WIND_CHANGE_KMH = 5.0 # the last hour's mean wind against the first hour's: picking up (or easing) by this much +STALE_SECONDS = 30 * 60 # a newest reading older than this is warned about +VERDICTS = ("unlikely", "possible", "likely") +GROUPS = ("outdoor", "pressure", "rainfall", "rainfall_piezo", "wind") # what the read needs (the prefetch's groups) +GAUGES = ("rainfall", "rainfall_piezo") # the rain gauges, the main one first + +Rows = Sequence[tuple[int, dict]] + + +# ---------- the read, from the readings ---------- +def read(rows: Rows, now_reading: dict | None, now_ts: int, live_ts: int | None = None) -> dict: + """The outlook's fields from the station's readings: `rows`, the last HOURS of 5-minute readings ([(epoch, {"group.field": value})], + oldest first, as Ecowitt.recent gives them), `now_reading` the reading now ({"group.field": value}, None when there is none) of + `live_ts`, and `now_ts` the time asked. The fields: verdict, reason, pressure, moisture, recent_rain, wind_trend, [missing], and + `newest`, the time of the newest reading read (None when there is none).""" + live = dict(now_reading or {}) if live_ts else {} + if live and rows and live_ts <= rows[-1][0]: # the reading now is older than the newest 5 minutes': the rows say it all + live = {} + last = rows[-1][1] if rows else {} + newest = max([ts for ts in (live_ts if live else None, rows[-1][0] if rows else None) if ts], default=None) + gauge = next((g for g in GAUGES if any(f"{g}.daily" in r or f"{g}.rain_rate" in r for r in (live, last))), GAUGES[0]) + + def points(key: str) -> list[tuple[int, float]]: + out = [(ts, float(r[key])) for ts, r in rows if _number(r.get(key))] + if _number(live.get(key)): + out.append((live_ts, float(live[key]))) + return out + + def latest(*keys: str) -> list[float | None]: + """These readings now, all from one reading: the reading now when it has them all, else the newest 5 minutes'.""" + for source in (live, last): + if all(_number(source.get(k)) for k in keys): + return [float(source[k]) for k in keys] + return [float(v) if _number(v := live.get(k, last.get(k))) else None for k in keys] + + pressure = _pressure(points("pressure.relative")) + moisture = _moisture(*latest("outdoor.temperature", "outdoor.humidity", "outdoor.dew_point")) + until = newest or now_ts # "the last hour" ends at the newest reading held: stale readings (a read without fetching, just after + # midnight) still count their rain, and the result's as_of and warning say how old they are + rain = _recent_rain(rows, live, live_ts, gauge, until) + wind = _wind(points("wind.wind_speed"), until) + + falling = pressure is not None and pressure["tendency"] == "falling" + score = 0 if not falling else 2 if -pressure["change_hpa"] > LIKELY_FALL_HPA else 1 + wind_counts = falling and wind is not None and wind["trend"] == "picking up" + up, down = [], [] # the readings behind the verdict, towards rain and away from it, the strongest first + if rain is not None and rain["rained"]: + up.append(rain["why"]) + if falling: + up.append(f"pressure {pressure['change']}") + if moisture is not None and moisture["moist"]: + score += 1 + up.append(moisture["why"]) + if pressure is not None and pressure["level"] == "unsettled": + score += 1 + up.append(f"low pressure ({pressure['hpa']:.1f} hPa)") + if wind_counts: + score += 1 + up.append("wind picking up") + if pressure is not None and not falling: + down.append(f"pressure {pressure['change']}") + if pressure is not None and pressure["level"] == "settled": + score -= 1 + down.append(f"high pressure ({pressure['hpa']:.1f} hPa)") + besides = [f"humidity {moisture['humidity']:.0f}%"] if moisture is not None and not moisture["moist"] and \ + moisture["humidity"] is not None else [] # (a figure to quote when one reading alone is behind the verdict) + score = 2 if rain is not None and rain["rained"] else min(max(score, 0), 2) + verdict = VERDICTS[score] + parts = (down + up if verdict == "unlikely" else up + down) + besides + out = {"verdict": verdict, "reason": ", ".join(parts[:2]) or "too few readings in the last 3 hours to tell", + "pressure": _public(pressure), "moisture": _public(moisture), "recent_rain": _public(rain), "wind_trend": wind} + if missing := [name for name, got in (("pressure", pressure), ("humidity and dew point", moisture), ("rain", rain), ("wind", wind)) + if got is None]: + out["missing"] = missing + out["newest"] = newest + return out + + +def _number(value) -> bool: + """Is it a reading's value: a finite number?""" + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def _public(fields: dict | None) -> dict | None: + """The fields an answer shows: those the read keeps for its reason (`change`, `why`) left out.""" + return None if fields is None else {k: v for k, v in fields.items() if k not in ("change", "why")} + + +def _over(seconds: float) -> str: + """"3 hours", "1.5 hours", "1 hour", "30 minutes": how long the readings span, to the half hour.""" + halves = max(1, round(seconds / 1800)) + return "30 minutes" if halves == 1 else "1 hour" if halves == 2 else f"{halves / 2:g} hours" + + +def _pressure(points: list[tuple[int, float]]) -> dict | None: + """{hpa, change_hpa, tendency, level, text}: the pressure now, its change over the readings (signed: down is negative), whether it + is falling (its highest came before its lowest), rising or steady (a change under STEADY_HPA), and its level.""" + if len(points) < 2: + return None + high = max(points, key=lambda p: p[1]) # (the first, where several are as high) + low = min(points, key=lambda p: p[1]) + size = round(high[1] - low[1], 1) + falling = high[0] < low[0] + tendency = "steady" if size < STEADY_HPA else "falling" if falling else "rising" + over = _over(points[-1][0] - points[0][0]) + change = (f"down {size:.1f} hPa in {over}" if tendency == "falling" else f"up {size:.1f} hPa in {over}" if tendency == "rising" + else "steady") + hpa = points[-1][1] + level = "unsettled" if hpa < UNSETTLED_HPA else "settled" if hpa > SETTLED_HPA else "normal" + steady = f"steady ({'no change' if not size else ('down ' if falling else 'up ') + f'{size:.1f} hPa'} in {over})" + where = {"unsettled": f"; under {UNSETTLED_HPA:g} hPa: unsettled", "settled": f"; over {SETTLED_HPA:g} hPa: settled"}.get(level, "") + text = f"{hpa:.1f} hPa, {steady if tendency == 'steady' else change}{where}" + return {"hpa": round(hpa, 1), "change_hpa": (-size if falling else size) or 0.0, "tendency": tendency, "level": level, "text": text, + "change": change} + + +def dew_point(temperature: float, humidity: float) -> float: + """The dew point (°C) of air at this temperature (°C) and relative humidity (%), by the Magnus formula: for a station that sends + no dew point of its own.""" + a, b = 17.62, 243.12 + gamma = math.log(max(humidity, 1.0) / 100) + a * temperature / (b + temperature) + return b * gamma / (a - gamma) + + +def _moisture(temperature: float | None, humidity: float | None, dew: float | None) -> dict | None: + """{humidity, dew_point_spread, moist, text}: the humidity now and how far the temperature is above the dew point; moist when the + humidity is MOIST_HUMIDITY or more or the spread MOIST_SPREAD_C or less.""" + if dew is None and temperature is not None and humidity is not None: + dew = dew_point(temperature, humidity) + spread = round(temperature - dew, 1) if temperature is not None and dew is not None else None + if humidity is None and spread is None: + return None + by_humidity = humidity is not None and humidity >= MOIST_HUMIDITY + by_spread = spread is not None and spread <= MOIST_SPREAD_C + gap = None if spread is None else "at the dew point" if spread <= 0 else f"{spread:.1f} °C above the dew point" + text = ", ".join(x for x in (f"humidity {humidity:.0f}%" if humidity is not None else None, gap) if x) + why = f"humidity {humidity:.0f}%" if by_humidity else "the temperature at the dew point" if by_spread and spread <= 0 else \ + f"temperature within {spread:.1f} °C of the dew point" if by_spread else None + return {"humidity": None if humidity is None else round(humidity), "dew_point_spread": spread, "moist": by_humidity or by_spread, + "text": text, "why": why} + + +def _recent_rain(rows: Rows, live: dict, live_ts: int | None, gauge: str, now_ts: int) -> dict | None: + """{rained, raining_now, rate_mm_h, last_hour_mm, text}: is it raining now (a rain rate above 0), and the rain of the last hour + (the daily total's rise, its midnight reset allowed for, and any rate above 0).""" + total, rate = f"{gauge}.daily", f"{gauge}.rain_rate" + seq = [*rows, *([(live_ts, live)] if live else [])] + if not any(_number(r.get(total)) or _number(r.get(rate)) for _, r in seq): + return None + since = now_ts - RECENT_SECONDS + fell, before = 0.0, None + for ts, r in seq: + if not _number(daily := r.get(total)): + continue + if ts >= since and before is not None: + fell += daily - before if daily >= before else daily # (a drop is the midnight reset) + before = daily + rate_now = next((float(r[rate]) for _, r in reversed(seq) if _number(r.get(rate))), None) + raining = rate_now is not None and rate_now > 0 + rate_seen = any(_number(r.get(rate)) and r[rate] > 0 for ts, r in seq if ts >= since) + rained = raining or fell > 0 or rate_seen + mm = round(fell, 1) + in_hour = (f"{mm:.1f} mm in the last hour" if mm else "a trace of rain in the last hour" if fell > 0 + else "rain in the last hour" if rate_seen else "no rain in the last hour") + now = f"raining now ({rate_now:.1f} mm/h)" if raining else None + text = now + (f", {mm:.1f} mm in the last hour" if mm else "") if raining else in_hour + return {"rained": rained, "raining_now": raining, "rate_mm_h": None if rate_now is None else round(rate_now, 1), + "last_hour_mm": mm, "text": text, "why": now or in_hour} + + +def _wind(points: list[tuple[int, float]], now_ts: int) -> dict | None: + """{trend, first_hour_kmh, last_hour_kmh, text}: the mean wind speed of the last hour against that of the first of the 3 hours; + picking up, or easing, when it differs by WIND_CHANGE_KMH or more. None without readings in both hours.""" + start = now_ts - HOURS * 3600 + first = [v for ts, v in points if start <= ts < start + 3600] + last = [v for ts, v in points if ts >= now_ts - 3600] + if not first or not last: + return None + a, b = sum(first) / len(first), sum(last) / len(last) + trend = "picking up" if b - a >= WIND_CHANGE_KMH else "easing" if a - b >= WIND_CHANGE_KMH else "steady" + return {"trend": trend, "first_hour_kmh": round(a, 1), "last_hour_kmh": round(b, 1), + "text": f"{trend}: {b:.1f} km/h on average in the last hour, {a:.1f} km/h 2 to 3 hours ago"} + + +# ---------- the tool ---------- +DESCRIPTION = ( + "Will it rain in the next few hours: the weather station's own read of its last 3 hours, by fixed rules, with the forecast's lines " + "for today and tomorrow. For \"will it rain?\", \"do I need an umbrella?\", \"what's it doing later?\": {}. Takes no arguments.\n" + "Not for: the days ahead (forecast); rain that fell (summary for a period's total, days for the wettest day); whether rain follows " + "pressure over weeks (relate).\n" + "The rules: pressure over the 3 hours is falling when its high came before its low; down more than 3 hPa: likely; down 1 to 3 hPa: " + "possible; under 1 hPa or rising: unlikely. A step towards rain for each of: pressure under 1005 hPa (unsettled); humidity 90% or " + "more, or the temperature within 2 °C of the dew point; wind picking up while pressure falls. A step away: pressure over 1020 hPa " + "(settled). A rain rate above 0 now, or rain in the last hour, makes it likely: showers tend to go on.\n" + "Result: `verdict` (likely, possible, unlikely) and `reason` (the one or two readings behind it, ready to quote); `pressure`, " + "`moisture`, `recent_rain` and `wind_trend`, each with its figures and text; `forecast`, Open-Meteo's lines for today and tomorrow, " + "to copy as they are. Open with the verdict and reason, say it is a read of the station's readings, then the forecast's lines; if " + "they disagree, say so.") +PARAMETERS = {"type": "object", "properties": {}} +HOW_TO_READ = ("`verdict` and `reason` are the station's read of the next few hours from its last 3 hours, by the rules in this tool's " + "description: open with them, and say it is a read of the station's readings. `forecast` holds Open-Meteo's lines for " + "today and tomorrow: give them after it, copied as they are, emoji included; if they disagree with the station's read, " + "say so plainly. For the days further ahead, call forecast.") + + +def tools(ctx) -> list[ServiceTool]: + """The `outlook` tool, when there is a weather station.""" + if ctx.eco is None: + return [] + + async def handle(args: dict, meta: dict) -> str: + eco = ctx.eco + tz = ctx.zone + now_ts = int(ctx.clock()) + rows, live, live_ts = await readings(eco, now_ts, tz, fetch=meta["fetch"], urgent=meta["priority"] != BACKGROUND) + got = read(rows, live, now_ts, live_ts) + if got["newest"] is None: + raise Refusal("The weather station has no readings from the last 3 hours, so there is nothing to read the next few hours " + "from." + (" Ask forecast for today's forecast." if ctx.forecast is not None else "")) + newest = to_local(got.pop("newest"), tz) + extra = {} + if ctx.forecast is not None: + today = to_local(now_ts, tz).date() + days = [d for d in await held_days(ctx.forecast, today, meta["fetch"]) if (d["date"] - today).days <= 1] + extra["forecast"] = day_lines(days, today) if days else [] + if not days: + extra["forecast_note"] = "No forecast is available right now: the station's read is the whole answer." + if now_ts - newest.timestamp() > STALE_SECONDS: + extra["warning"] = (f"The station's newest reading is from {day_text(newest, year=False)} {clock_text(newest)}: this read may " + f"be out of date.") + return answer(period=None, as_of=newest, **got, **extra, how_to_read=HOW_TO_READ) + + return [ServiceTool("outlook", DESCRIPTION, PARAMETERS, handle, open_world=True)] + + +async def readings(eco, now_ts: int, tz, *, fetch: bool, urgent: bool) -> tuple[list, dict | None, int | None]: + """(the last HOURS of 5-minute readings, the reading now as {"group.field": value}, its time) from the station: the readings as + Ecowitt.recent reads them (what the file lacks asked of Ecowitt, ahead of the background requests when someone is waiting), the + reading now as the report's and the gauges' (the kept live reading while fresh, else a request for every group, kept in turn). With + `fetch` False, only what is held: the file's readings and the kept live reading.""" + groups = [g for g in GROUPS if g in eco.groups] + start = now_ts - HOURS * 3600 + if fetch: + rows = await eco.fetcher(groups, urgent=urgent).get("5min", naive_local(start, tz), naive_local(now_ts, tz)) + try: + data = await eco._live_data(LIVE_GROUPS, urgent=urgent) # (every group, as the report's: kept for the next to ask) + except Exception as e: # the readings of the last 3 hours still give a read + log.warning("Outlook: no live reading (%s: %s); reading the 5-minute history alone", type(e).__name__, e) + data = None + else: + rows = await eco.storage.read(rows_on, eco.mac, groups, "5min", start, now_ts) + data = eco._live[1] if getattr(eco, "_live", None) else None + live, live_ts = _values(data or {}) + return rows, live, live_ts + + +def _values(data: dict) -> tuple[dict, int | None]: + """A real_time response ({group: {field: {value, unit, time}}}) as {"group.field": value} and the time of its newest reading.""" + out, newest = {}, 0 + for group, fields in data.items(): + for name, obj in (fields.items() if isinstance(fields, dict) else ()): + try: + out[f"{group}.{name}"] = float(obj["value"]) + newest = max(newest, int(obj.get("time") or 0)) + except (KeyError, TypeError, ValueError): + continue + return out, newest or None + + +__all__ = ["DESCRIPTION", "PARAMETERS", "dew_point", "read", "readings", "tools"] diff --git a/lib/service/pollen.py b/lib/service/pollen.py new file mode 100644 index 00000000..a6e8480c --- /dev/null +++ b/lib/service/pollen.py @@ -0,0 +1,78 @@ +"""The `pollen` tool (docs/ecobot-mcp.md 3.3): Melbourne's grass pollen and the thunderstorm asthma risk, from the pollen source +(lib/pollen, melbournepollen.com.au). No arguments. + +The answer is today's pollen_asthma's, in the service's shape: the same `lines` (Pollen.lines), each level with its emoji and its +day in `grass` and `asthma`, `in_season`, `fetched_at`, `place` and `source`, and `text`, the bot's pollen section ("Pollen & asthma +(Melbourne, 6:00pm)" and a bullet per line, the old lib/report.py's report and lookup) written here so a client can send it as it is. Out of +season (the forecasts run October to December) it answers as pollen_asthma does, with its error. Request `_meta` `fetch: false` +answers from the page held, fetching nothing (the report's `cached`). +""" + +import logging +from calendar import month_name + +from ..pollen.parse import LEVELS +from ..pollen.source import OFF_SEASON, SEASON_MONTHS +from ..timeutil import day_text, to_local +from .common import Refusal, ServiceTool, answer, iso +from .forecast import clock_of, section + +log = logging.getLogger(__name__) + +HEADING = "Pollen & asthma" # the bot's heading for it (the old lib/report.py SECTIONS) +NO_LEVELS = "No pollen levels are available right now." # (pollen_asthma's own words) +SOURCE = ("melbournepollen.com.au (grass pollen from pollen-trap data; asthma risk from the Victorian Department of Health and BOM, " + "1 Oct - 31 Dec)") # (pollen_asthma's) +NO_ASTHMA = "The page had no thunderstorm asthma level for this district when it was last read." # (pollen_asthma's asthma_note) +SEASON = f"{month_name[SEASON_MONTHS[0]]} to {month_name[SEASON_MONTHS[-1]]}" + +DESCRIPTION = ( + "Melbourne's grass pollen level and the thunderstorm asthma risk for the station's district, each Low, Moderate, High or Extreme, " + "from melbournepollen.com.au. For \"pollen today\", \"is it bad for hay fever\", \"thunderstorm asthma risk\": {}. Takes no " + "arguments. The forecasts run only from October to December: out of season it says so, as an error. A report (\"report\", " + "\"status\", \"sitrep\") is current, forecast {\"period\": \"today\"} and pollen, called together.\n" + "Not for: air quality, PM2.5 and the like (the air sensor: current, summary); the weather forecast (forecast).\n" + "Result: `text`, the whole answer for the person, ready to send; `lines`, emoji included: copy them as they are; `grass` and " + "`asthma`, each level with its emoji (grass with `day`, the day its forecast is for; asthma with `updated`, when the site last " + "updated it); `place`, `fetched_at`; `asthma_note` when the page had no asthma level.") +PARAMETERS = {"type": "object", "properties": {}} + + +def tools(ctx) -> list[ServiceTool]: + """The `pollen` tool, when the pollen source is switched on.""" + if ctx.pollen is None: + return [] + + async def handle(args: dict, meta: dict) -> str: + p = ctx.pollen + if not p.in_season(): + raise Refusal(OFF_SEASON) + if p.page is None and meta["fetch"]: # (as pollen_asthma does: the page is fetched only when this season's isn't held) + try: + await p.warm(True) + except Exception as e: + log.warning("Pollen not readable: %s", e) + lines = p.lines() + if not lines: + raise Refusal(NO_LEVELS) + tz, now = clock_of(ctx, p.tz) + cur = p.current() + fetched = to_local(int(cur["fetched_at"]), tz) if cur["fetched_at"] else None + levels = {} + if g := cur["grass"]: # (its day: the day the page's grass forecast is for) + levels["grass"] = {"level": g["level"], "emoji": g["emoji"], + **({"day": g["date"].isoformat(), "day_text": day_text(g["date"])} if g["date"] else {})} + if a := cur["asthma"]: + levels["asthma"] = {"level": a["level"], "emoji": a["emoji"], **({"updated": a["updated"]} if a["updated"] else {})} + return answer(period=None, as_of=fetched, + text=section(HEADING, lines, place=p.place, fetched_at=cur["fetched_at"], tz=tz, today=now.date()), + lines=lines, grass=levels.get("grass"), asthma=levels.get("asthma"), + **({} if "asthma" in levels else {"asthma_note": NO_ASTHMA}), + scale=list(LEVELS), in_season=True, season=SEASON, + **({"place": p.place} if p.place else {}), source=SOURCE, + **({"fetched_at": iso(fetched)} if fetched else {})) + + return [ServiceTool("pollen", DESCRIPTION, PARAMETERS, handle, open_world=True)] + + +__all__ = ["DESCRIPTION", "PARAMETERS", "tools"] diff --git a/lib/service/readings.py b/lib/service/readings.py new file mode 100644 index 00000000..562f5a82 --- /dev/null +++ b/lib/service/readings.py @@ -0,0 +1,167 @@ +"""The `readings` tool (docs/ecobot-mcp.md 3.3): one reading's values at an interval, a row per interval with its time, over a period in +the person's words. It replaces the bot's `readings` tool, and wraps its engine (lib/history.py): the same rows read the same way +(read_intervals, read_days: an interval's average with its lowest and highest, rain as the mm that fell, gusts as the highest, wind +direction as the reading at the interval's end, days from the day rows), the same cap of MAX_ROWS rows with the interval that fits when +there are more, over the service's periods (common.read_period) and its reading names (ctx.readings()). + +It reads only the file: nothing is fetched, so a request's `fetch` and `priority` change nothing here, and it draws no chart. + +Also here, for the tools over the file (relate, scan): the id of a reading's sensor in the file (sensor_id) and the first day held for +some readings (first_day), which "on record" starts from. +""" + +from datetime import date + +from ..history import (ALIASES, DAY_VALUE_IS, INTERVALS, MAX_ROWS, VALUE_IS, finest_fit, interval_starts, read_days, read_intervals, + row_count) +from ..storage.read import Reader +from ..timeutil import local_date +from .common import Refusal, ServiceTool, answer, period_properties, read_period +from .context import Context +from .names import AIR_DEVICE, Catalogue, Reading + +DEFAULT_PERIOD = "last 24 hours" +NOTHING_STORED = "Nothing is stored for this sensor yet." +NO_ROWS = "No readings are stored for this period at this interval: say so; never fill the gap." + +DESCRIPTION = ( + "The stored values of ONE reading at a fixed interval, a row per interval with its time: values at set times or per interval. " + "Examples: \"humidity each hour for the last 5 hours\" {reading: \"outdoor.humidity\", period: \"last 5 " + "hours\", interval: \"1hour\"}; \"PM2.5 every 30 minutes this morning\" {reading: \"pm2.5\", period: \"this morning\", interval: " + "\"30min\"}; \"rain each hour today\" {reading: \"rain\", period: \"today\", interval: \"1hour\"}; \"the temperature at 3pm " + "yesterday\" {reading: \"outdoor.temperature\", period: \"yesterday afternoon\", interval: \"5min\"}, then its 3:00pm row. One " + "reading a call: outdoor and indoor are two calls. " + f"At most {MAX_ROWS} rows: 5min for up to a day, 30min up to 6 days, 1hour up to 12 days, 4hour up to 7 weeks, 1day up to 300 " + "days; more is refused with the interval that fits (`fits`). " + "Not for: a period's highs and lows with when, a record (\"hottest ever\", even \"use 5 minute data\": summary, period \"on " + "record\"), averages, totals or a chart (summary); days ranked, counted or totalled, a figure " + "per month or year (days); how it is now (current). " + "Result: `columns` names each row's values and `value_is` what `value` is: an interval's average with its lowest and highest; rain " + "the mm that fell in it; gusts the highest; wind direction the reading at its end; at 1day the day's figures and when its lowest " + "and highest happened. Only what is stored is read, nothing is fetched: an empty row is `missing` (say so, never fill it), and " + "`note_coarser` with `fits` names the interval held.") + + +def parameters(catalogue: Catalogue) -> dict: + return { + "type": "object", + "properties": { + "reading": {"type": "string", "description": f"ONE reading. {catalogue.description()} A word that stands for several " + "(temperature: outdoor and indoor) reads the first, and the result names the " + "others to ask for."}, + **period_properties(DEFAULT_PERIOD), + "interval": {"type": "string", "enum": list(INTERVALS), + "description": "One row per interval, a block of local time (1hour runs from :00 to :00, 1day from midnight; " + "4hour follows the station's own 4-hour records, whose times say where they start). 1min goes " + "back 10 days, and only where the sensor was read every minute."}, + }, + "required": ["reading", "interval"], + } + + +# ---------- the file ---------- +def sensor_id(ctx: Context, reading: Reading) -> int | None: + """The id of the reading's sensor in the file: the station's Ecowitt group, or the air sensor; None when it isn't there.""" + if reading.device == AIR_DEVICE: + store = getattr(ctx.air, "store", None) + sensor = getattr(store, "sensor", None) + sensor = sensor() if callable(sensor) else sensor # (AirReadings.sensor is a property; a test's stand-in may be a function) + else: + sensor = ctx.storage.sensors.find(ctx.eco.mac, reading.sensor) if ctx.eco else None + return sensor.id if sensor else None + + +def _first_days(r: Reader, wanted: list[tuple[str, int]]) -> list[date | None]: + out = [] + for kind, sensor in wanted: + (day,) = r.db.execute(f"SELECT MIN(day) FROM {kind}_day WHERE sensor = ?", (sensor,)).fetchone() + out.append(date.fromisoformat(day) if day else None) + return out + + +async def first_day(ctx: Context, readings: list[Reading]) -> date | None: + """The first day these readings are all held (each sensor's first day row, the latest of them): where "on record" starts. None + when one of them has nothing held.""" + wanted = [(r.kind, sensor_id(ctx, r)) for r in readings] + if not wanted or ctx.storage is None or any(sensor is None for _, sensor in wanted): + return None + days = await ctx.storage.read(_first_days, wanted) + return None if None in days else max(days) + + +# ---------- the arguments ---------- +def one_reading(catalogue: Catalogue, words) -> tuple[Reading, list[Reading]]: + """(the reading these words name, the others they name too). A sensor's wind is its speed: its direction goes with it only on a + chart (the compass rose). Raises UnknownReading, or Refusal when nothing is named.""" + if not [w for w in (words if isinstance(words, (list, tuple)) else [words]) if str(w or "").strip()]: + raise Refusal("Send `reading`: one name from `names`, or a word from `words` (each with the names it stands for).", + names=catalogue.names, words=catalogue.words()) + found = catalogue.resolve(words, default=None) + found = [r for r in found if r.drawn != "rose"] or found + return found[0], found[1:] + + +def interval_of(value) -> str: + """The interval sent, as INTERVALS names it ("hourly" is 1hour). Raises Refusal for one it can't read.""" + text = str(value or "").strip().lower() + interval = ALIASES.get(text, text) + if interval not in INTERVALS: + said = f"`interval` {value!r} isn't one this tool reads" if text else "Send `interval`" + raise Refusal(f"{said}: one of {', '.join(INTERVALS)} (a row each; at most {MAX_ROWS} rows).", intervals=list(INTERVALS)) + return interval + + +def others_note(reading: Reading, others: list[Reading]) -> str: + names = ", ".join(r.name for r in others) + return f"Read {reading.name} only: this tool reads one reading a call. For {names}, call it again, once for each, in the same round." + + +# ---------- the tool ---------- +def tools(ctx: Context) -> list[ServiceTool]: + async def handle(args: dict, meta: dict) -> str: + catalogue = ctx.readings() + reading, others = one_reading(catalogue, args.get("reading")) + interval = interval_of(args.get("interval")) + tz, now = ctx.zone, ctx.now() + sensor = sensor_id(ctx, reading) if ctx.storage is not None else None + period = read_period(args, tz=tz, now=now, default=DEFAULT_PERIOD, + first_held=await first_day(ctx, [reading]) if sensor is not None else None) + m, now_ts = reading.metric, int(now.timestamp()) + start, end = int(period.start.timestamp()), int(period.end.timestamp()) - 1 # (the end not included) + by_day = interval == "1day" and m.how != "last" # (a compass point has no day figures: the last reading of each day) + n = row_count(start, end, interval, tz) + too_many = n > (MAX_ROWS if by_day else MAX_ROWS + 1) # (an interval's count is exact only once listed: the first starts before `start`) + marks = [] if too_many or by_day else interval_starts(start, end, INTERVALS[interval], tz) + if too_many or len(marks) > MAX_ROWS: + fits = finest_fit(start, end, tz) + rows = max(n, len(marks)) + raise Refusal(f"Too many rows: {period.text} at {interval} is {rows} rows, and this tool gives at most {MAX_ROWS}. " + + (f"Ask again with interval {fits}." if fits else + "Too long even for days: split the period, or for its highs, lows and averages use summary, for a figure " + "per day, month or year days."), + rows=rows, max_rows=MAX_ROWS, fits=fits) + out = {"reading": reading.name, "label": reading.label, "unit": reading.unit, "interval": interval, + "value_is": (DAY_VALUE_IS if by_day else VALUE_IS)[m.how]} + if sensor is None: + return answer(period=period, as_of=now, **out, rows=[], note=NOTHING_STORED, + **({"note_others": others_note(reading, others)} if others else {})) + if by_day: + first, last = local_date(start, tz), local_date(end, tz) + out |= await ctx.storage.read(read_days, m, sensor, first, last, tz) + partial = last == local_date(now_ts, tz) + else: + out |= await ctx.storage.read(read_intervals, m, sensor, interval, marks, end, now_ts, tz) + partial = marks[-1] + INTERVALS[interval] > now_ts + if partial: + out["note_last"] = "The last row is still filling: it runs up to now." + if not any(row[1] is not None for row in out["rows"]): + out["note"] = (f"No readings at this interval for this period: ask again with interval {out['fits']}." if out.get("fits") else + NO_ROWS) + if others: + out["note_others"] = others_note(reading, others) + return answer(period=period, as_of=now, **out) + + return [ServiceTool("readings", DESCRIPTION, parameters(ctx.readings()), handle)] + + +__all__ = ["DEFAULT_PERIOD", "DESCRIPTION", "first_day", "interval_of", "one_reading", "parameters", "sensor_id", "tools"] diff --git a/lib/service/relate.py b/lib/service/relate.py new file mode 100644 index 00000000..93b3babf --- /dev/null +++ b/lib/service/relate.py @@ -0,0 +1,175 @@ +"""The `relate` tool (docs/ecobot-mcp.md 3.3): rain against one reading, the two read together at 30-minute resolution over whole days +to yesterday. For pressure, humidity or wind: does rain follow a change in it (lib/ecowitt/link.py, today's weather_link); for PM2.5 or +PM10: is the air cleaner after rain (lib/compose.py Composer.air_link, today's air_link). Their findings come back as they are, in the +service's shape; a chart, when asked, is the reading with rain as bars behind it, carrying the call that drew it (drawn_by, 3.7). + +The station's side reads only the file. The air's asks the AirGradient cloud for the finished days the file lacks (up to 30, as today), +unless the request's metadata says `fetch` false; its `priority` changes nothing, as those requests have no queue to wait in. + +Also here, for scan, which reads the air through the same Composer: the charts with their drawn_by (drawn_charts), the period a whole-day +call is replayed with (whole_day_words), the Composer of a request (composer_for: from what is held, when its metadata says `fetch` +false: HeldAir). +""" + +import asyncio +import copy +import json +from datetime import date, datetime, timedelta + +from ..airgradient.metrics import without_spikes +from ..compose import Composer +from ..ecowitt.link import link +from ..periods_text import Period +from ..specs import ECOWITT_SOURCE, Chart +from ..timeutil import local_date, local_epoch +from ..tools import Turn +from .common import Refusal, ServiceTool, answer, period_properties, read_period, sends_period, with_charts +from .context import Context +from .names import Catalogue, Reading +from .readings import first_day + +STATION = {"pressure.relative": "pressure", "outdoor.humidity": "humidity", "wind.wind_speed": "wind"} # -> weather_link's driver +AIR = {"air.pm2_5": "pm2_5", "air.pm10": "pm10"} # -> air_link's metric +DEFAULT_READING = "pressure.relative" +DEFAULT_PERIOD, AIR_PERIOD = "last 90 days", "last 60 days" +# The periods a chart of rain against a reading is worth redrawing over (3.7) +PERIODS = ({"period": "1m", "label": "1M"}, {"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}) +RAIN_NAME = ("rainfall (rainfall.daily)", "rain (rainfall.rain)") # weather_link's name for the rain in its notes -> the service's + +DESCRIPTION = ( + "Rain against one reading, the two read together at 30-minute resolution over whole days (never averaged to days). For pressure, " + "humidity or wind: does rain follow a change in it (how much of the rain fell after the reading had been falling, steady or " + "rising over the 3 hours before, its level in rain and when dry, the biggest rain spells with the change before each). For PM2.5 or " + "PM10: is the air cleaner after rain (the 6 hours after each rain against the 6 before, wet days against dry). Any \"X against " + "rain\" is this tool. Examples: \"does rain follow a pressure drop?\", \"is there a correlation between pressure and rainfall?\" " + "{reading: \"pressure\"}; \"does humidity go with rain over the past year?\" {reading: \"humidity\", period: \"past year\"}; " + "\"does rain clear the air?\", \"is there a correlation between air quality and precipitation?\" {reading: \"pm2.5\"}; \"plot pressure against rainfall\" {reading: \"pressure\", chart: true}. " + "Not for: each air reading against every weather reading (scan); a chart of readings over time with no question of rain " + "(summary); an air-quality rating drawn beside rain (\"plot the traffic light rating against rainfall\": summary {readings: " + "[\"pm2.5:rating\", \"rain\"]}); rain totals, wet days or rain per month (days). " + "Result: open with `verdict` (yes, no or weak) in your own words, then the evidence in `findings`, as `how_to_read` says; " + "say the two go together or not, never that one causes the other. `note` when there was nothing to compare: say exactly that.") + + +def parameters() -> dict: + return { + "type": "object", + "properties": { + "reading": {"type": "string", "description": "The reading set against rain, a name or the word for it: pressure " + "(pressure.relative, the default), humidity (outdoor.humidity), wind (its " + "speed, wind.wind_speed), pm2.5 (air.pm2_5) or pm10 (air.pm10)."}, + **period_properties("the last 90 days; for pm2.5 and pm10, the last 60 days", whole_days=True), + "chart": {"type": "boolean", "description": "true for a chart: the reading as a line, rain as bars behind it. Default " + "false."}, + }, + } + + +# ---------- shared with scan ---------- +def drawn_charts(charts: list[Chart], ctx: Context, meta: dict, tool: str, arguments: dict, periods=PERIODS) -> dict: + """The fields an answer with charts ends with (common.with_charts), each chart carrying the call that drew it: `drawn_by: {tool, + arguments, periods}`, `arguments` the call as the tool read it (the readings' full names, every default filled in), `periods` those + it is worth redrawing over, each replayed with only `period` changed.""" + fields = with_charts(charts, ctx.zone, meta) + for chart in fields.get("charts", []): + chart["drawn_by"] = {"tool": tool, "arguments": copy.deepcopy(arguments), "periods": [dict(p) for p in periods]} + return fields + + +def whole_day_words(args: dict, period: Period) -> str: + """The period of a whole-day call as words a replay reads the same: the words asked (or the default), or, for one made with + `start` and `end`, "<first day> to <last day>".""" + if str(args.get("start") or "").strip() and not sends_period(args): # (`period` wins: common.read_period) + return f"{period.first_day.isoformat()} to {period.last_day.isoformat()}" + return period.asked + + +def flag(value) -> bool: + """A boolean argument as sent (true, "true").""" + return value is True or str(value).strip().lower() == "true" + + +class HeldAir: + """The air sensor as Composer reads it (`rows`), answering from what the file holds and fetching nothing: for a request whose + metadata says `fetch` false. The readings are AirGradient.rows' (each stored reading, the particles' glitches taken out); a day + not held is left out and counted, as one beyond the inline fetch is.""" + + def __init__(self, air): + self.air, self.tz = air, air.tz + + async def rows(self, t0: datetime, t1: datetime) -> tuple[list[dict], int, list[date]]: + store = self.air.store + days = [t0.date() + timedelta(days=k) for k in range((t1.date() - t0.date()).days + 1)] + lo, hi = local_epoch(t0, self.tz), local_epoch(t1, self.tz) + held = await store.held(days) + rows = [r for r in without_spikes(await store.load(lo, hi + 1)) if lo <= r["ts"] <= hi] + have = {local_date(r["ts"], self.tz) for r in rows} + hourly = sum(1 for h in held.values() if h.n and h.hourly) + return rows, hourly, [d for d in days if held[d].n is None and d not in have] + + +def composer_for(ctx: Context, meta: dict, what: str) -> Composer: + """The Composer that reads the air for this request: the context's, or, when the request's metadata says `fetch` false, one over + what the file holds (HeldAir). Refusal when there is none: `what` needs both devices.""" + if ctx.composer is None: + raise Refusal(f"{what} needs both the weather station and the air sensor, and this service has " + f"{'only the weather station' if ctx.eco else 'only the air sensor' if ctx.air else 'neither'}.") + return ctx.composer if meta["fetch"] else Composer(ctx.composer.eco, HeldAir(ctx.composer.air)) + + +# ---------- the reading ---------- +def relate_reading(catalogue: Catalogue, words) -> tuple[Reading, list[Reading]]: + """(the reading set against rain, the others the words name that could be). Raises UnknownReading, or Refusal when the words name + none that can be.""" + found = catalogue.resolve(words, default=DEFAULT_READING) + usable = [r for r in found if r.name in STATION or r.name in AIR] + if not usable: + can = [n for n in (*STATION, *AIR) if n in catalogue] + raise Refusal(f"{words!r} ({', '.join(r.name for r in found)}) can't be set against rain: this tool relates rain to one of " + f"{', '.join(can)}. For rain itself (totals, wet days) use days; for a chart of readings over time, summary.", + readings=can) + return usable[0], usable[1:] + + +# ---------- the tool ---------- +def tools(ctx: Context) -> list[ServiceTool]: + async def handle(args: dict, meta: dict) -> str: + reading, others = relate_reading(ctx.readings(), args.get("reading")) + air = reading.name in AIR + if not air and ctx.eco is None: + raise Refusal(f"{reading.name} is the weather station's, and this service has no weather station.") + composer = composer_for(ctx, meta, "Setting PM2.5 or PM10 against rain") if air else None + rain = ctx.readings().get("rainfall.rain") + now = ctx.now() + period = read_period(args, tz=ctx.zone, now=now, default=AIR_PERIOD if air else DEFAULT_PERIOD, whole_days=True, + first_held=await first_day(ctx, [reading, *([rain] if rain else [])])) + chart = flag(args.get("chart")) + dates = {"start_date": period.first_day.isoformat(), "end_date": period.last_day.isoformat()} + if air: + turn = Turn() + out = json.loads(await composer.air_link({"metric": AIR[reading.name], **dates, "chart": chart}, turn)) + charts = turn.charts + else: + out, spec, _, _ = await asyncio.to_thread(link, ctx.storage.read_now, ctx.eco.mac, ctx.zone, + {"driver": STATION[reading.name], **dates}, now) + charts = [spec] if spec else [] + for c in charts: + c.source = ECOWITT_SOURCE + if "error" in out: # (not expected: the reading and the period were checked here) + raise Refusal(out["error"]) + if "note" in out: + out["note"] = out["note"].replace(*RAIN_NAME) + fields = {"reading": reading.name, "label": reading.label, "unit": reading.unit, + **{k: out[k] for k in ("verdict", "how_to_read", "findings") if k in out}, + **{k: v for k, v in out.items() if k not in ("period", "driver", "metric", "chart", "verdict", "how_to_read", "findings")}} + if others: + fields["note_others"] = (f"Set {reading.name} against rain only: one reading a call. For " + f"{', '.join(r.name for r in others)}, call again, once for each, in the same round.") + drawn = {"reading": reading.name, "period": whole_day_words(args, period), "chart": True} + return answer(period=period, as_of=now, **fields, **(drawn_charts(charts, ctx, meta, "relate", drawn) if chart else {})) + + return [ServiceTool("relate", DESCRIPTION, parameters(), handle, open_world=ctx.composer is not None)] + + +__all__ = ["AIR", "DESCRIPTION", "HeldAir", "PERIODS", "STATION", "composer_for", "drawn_charts", "flag", "parameters", "relate_reading", + "tools", "whole_day_words"] diff --git a/lib/service/scan.py b/lib/service/scan.py new file mode 100644 index 00000000..618c7aaa --- /dev/null +++ b/lib/service/scan.py @@ -0,0 +1,113 @@ +"""The `scan` tool (docs/ecobot-mcp.md 3.3): each air reading against every weather reading, read together at 30-minute resolution +over whole days to yesterday, for the relationships that stand out (lib/compose.py Composer.air_scan, today's air_scan, over +lib/analysis/scan.py). Its verdict and findings come back as they are, in the service's shape; a chart, when asked, is the strongest pair +over time, carrying the call that drew it (drawn_by, 3.7). + +At most SCAN_MAX_DAYS days are scanned, as today: a longer period is cut to its latest days, and the result's `period` and +`note_period` say so. The air sensor's missing finished days are fetched (up to 30) unless the request's metadata says `fetch` false +(relate.composer_for); its `priority` changes nothing. +""" + +import json +from dataclasses import replace +from datetime import timedelta + +from ..compose import SCAN_AIR, SCAN_MAX_DAYS +from ..periods_text import Period +from ..specs import period_text +from ..timeutil import day_bounds, to_local +from ..tools import Turn +from .common import Refusal, ServiceTool, answer, period_properties, read_period +from .context import Context +from .names import Catalogue +from .readings import first_day +from .relate import composer_for, drawn_charts, flag, whole_day_words + +SCANNED = {f"air.{m}": m for m in SCAN_AIR} # the air readings scanned -> air_scan's metric +ALL = "all" +DEFAULT_PERIOD = "last 90 days" + +DESCRIPTION = ( + "Which weather goes with air quality: each air reading (PM2.5, PM10, CO2, VOC, NOx) against every weather reading (temperature, " + "humidity, dew point, pressure and its 3-hour change, wind speed, gusts, wind direction, rain), read together at 30-minute " + "resolution over whole days, allowing for the daily cycle and for chance. It reports only the relationships that stand out, " + "strongest first, with a plain verdict. Examples: \"what affects air quality?\" {}; \"is there a correlation between CO2 and the " + "other readings?\" {reading: \"co2\"}; \"what goes with PM2.5 over the past year? show me\" {reading: \"pm2.5\", period: \"past " + "year\", chart: true}. " + f"At most {SCAN_MAX_DAYS} days: a longer period is cut to its latest {SCAN_MAX_DAYS}, and the result says so. " + "Not for: air quality against rain or precipitation, whether rain clears the air, or rain against any one reading (relate); a chart of readings over time (summary); the air " + "now (current). " + "Result: open with `verdict`, then the relationships in `findings`, strongest first, as `how_to_read` says: they go together, " + "they don't cause each other. With `chart`, the strongest pair over time (none when nothing stands out).") + + +def parameters() -> dict: + return { + "type": "object", + "properties": { + "reading": {"type": "string", "description": "The air reading scanned against the weather, a name or the word for it: " + "pm2.5 (air.pm2_5), pm10 (air.pm10), co2 (air.co2), voc (air.voc_index), nox " + "(air.nox_index); or all of them, the default."}, + **period_properties(f"the last 90 days; at most {SCAN_MAX_DAYS} days", whole_days=True), + "chart": {"type": "boolean", "description": "true for a chart of the strongest relationship found, the two readings over " + "time. Default false."}, + }, + } + + +def scan_reading(catalogue: Catalogue, words) -> str: + """"all", or the full name of the one air reading the words name. Raises UnknownReading, or Refusal for words that name no air + reading scanned, or several.""" + if isinstance(words, (list, tuple)) and len(words) == 1: + words = words[0] + if words is None or str(words).strip().lower() in ("", ALL, "every", "everything", "all of them"): + return ALL + names = [r.name for r in catalogue.resolve(words, default=ALL)] + scanned = [n for n in names if n in SCANNED] + if scanned and set(SCANNED) <= set(names): # the air sensor named ("air", "airgradient"): all its readings + return ALL + if len(scanned) == 1: + return scanned[0] + readings = [ALL, *(n for n in SCANNED if n in catalogue)] + if not scanned: + raise Refusal(f"{words!r} ({', '.join(names)}) isn't an air reading this tool scans: send one of {', '.join(readings)}. For rain " + "against a weather reading use relate.", readings=readings) + raise Refusal(f"{words!r} names {len(scanned)} air readings: send one, or all.", readings=readings) + + +def latest_days(period: Period, tz) -> tuple[Period, str | None]: + """The period cut to its latest SCAN_MAX_DAYS days, and the note that says so (None when it wasn't longer).""" + first, last = period.first_day, period.last_day + if (last - first).days < SCAN_MAX_DAYS: + return period, None + first = last - timedelta(days=SCAN_MAX_DAYS - 1) + span = period_text(first, last) + cut = replace(period, start=to_local(day_bounds(first, tz)[0], tz), text=f"its last {SCAN_MAX_DAYS} days: {span}") + return cut, (f"Only the last {SCAN_MAX_DAYS} days can be scanned in one call: this covers {span}, not all of {period.text}.") + + +def tools(ctx: Context) -> list[ServiceTool]: + async def handle(args: dict, meta: dict) -> str: + reading = scan_reading(ctx.readings(), args.get("reading")) + composer = composer_for(ctx, meta, "Scanning the air against the weather") + air = ctx.readings().get(reading) or ctx.readings().get("air.pm2_5") + now = ctx.now() + period = read_period(args, tz=ctx.zone, now=now, default=DEFAULT_PERIOD, whole_days=True, + first_held=await first_day(ctx, [air]) if air else None) + period, note_period = latest_days(period, ctx.zone) + chart = flag(args.get("chart")) + turn = Turn() + out = json.loads(await composer.air_scan({"metric": SCANNED.get(reading, ALL), "start_date": period.first_day.isoformat(), + "end_date": period.last_day.isoformat(), "chart": chart}, turn)) + if "error" in out: # (not expected: the reading and the period were checked here) + raise Refusal(out["error"]) + fields = {"reading": reading, **{k: out[k] for k in ("verdict", "how_to_read", "findings") if k in out}, + **{k: v for k, v in out.items() if k not in ("period", "chart", "verdict", "how_to_read", "findings")}, + **({"note_period": note_period} if note_period else {})} + drawn = {"reading": reading, "period": whole_day_words(args, period), "chart": True} + return answer(period=period, as_of=now, **fields, **(drawn_charts(turn.charts, ctx, meta, "scan", drawn) if chart else {})) + + return [ServiceTool("scan", DESCRIPTION, parameters(), handle, open_world=True)] + + +__all__ = ["DESCRIPTION", "SCANNED", "latest_days", "parameters", "scan_reading", "tools"] diff --git a/lib/service/summary.py b/lib/service/summary.py new file mode 100644 index 00000000..d84bf84e --- /dev/null +++ b/lib/service/summary.py @@ -0,0 +1,880 @@ +"""The `summary` tool (docs/ecobot-mcp.md 3.3): a period's figures from the weather station and the air sensor, each reading's lowest +and highest with when and that day's look, averages, a breakdown by day or by month, wind direction, the rain that fell, the air's +ratings and AQI, and a chart of any readings from either sensor or both. It replaces weather_history, air_quality with dates and +plot_chart, and wraps their engines, each given only what this tool's arguments say (a Turn built from them, never from words): + + - the station's readings: lib/ecowitt/query.py's HistoryQuery, as Ecowitt._history runs it (`_Query` keeps its chart to the readings + drawn, and works out the rain that fell when no chart did); + - the air sensor's: AirGradient.history (air_quality with dates); + - a chart that mixes the two sensors, draws a rating (`air.pm2_5:rating`) or puts readings on one axis (`same_axis`): + Composer.plot_chart, which draws whole days up to yesterday. + +The result (3.3): {period, as_of, fresh, series: {"outdoor.temperature": {unit, low, low_text, low_when, low_date, low_day_look, +[low_note], high…, [average, average_text], [daily|monthly]}, "air.pm2_5": {…, average, high_rating, average_rating, high_aqi_us, +high_band, average_aqi_us, average_band}, "wind.wind_direction": {most_common, then, steadiness, [daily]}, "rainfall.rain": {unit, +total, total_text, [wettest_day], [daily|monthly]}}, [rain_total_mm], [monthly_note], [note_no_readings], [note_chart], [notes], +[missing, warning], [caption] or [text], [chart_note, charts], [reply, complete]}. + +Words for the person, as the bot wrote them from weather_history's and air_quality's results (the old lib/report.py, its wording ported +here, as the bot's code goes): `caption` under a chart (report.chart_caption), and `text` when there is none (report.lookup's +"extremes"). Each chart carries `drawn_by`, the call that draws it again, and the periods it is worth drawing over (3.7). +""" + +import json +import re +from collections.abc import Callable +from dataclasses import dataclass +from datetime import date, datetime, time, timedelta + +from ..captions import CHART_MIN_DAYS +from ..compose import MAX_PANELS, Composer +from ..ecowitt.api import CYCLES, daily_run, kept_from, unit_text +from ..ecowitt.days import day_values_on +from ..ecowitt.fetch import Fetcher +from ..ecowitt.query import DERIVED, HistoryQuery +from ..ecowitt.reads import Held, readings_on, slot_values_on +from ..periods_text import Period +from ..series import AIR, WEATHER, find +from ..specs import AIR_SOURCE, ECOWITT_SOURCE, Bars, Chart +from ..storage.catalogue import KINDS, field_of +from ..timeutil import clock_text, day_text, local_date, to_local +from ..tools import Turn +from .common import BACKGROUND, Refusal, ServiceTool, answer, complete, period_properties, read_period, with_charts +from .context import Context +from .daylook import FIGURES, day_look +from .names import AIR_DEVICE, STATION, Reading + +NAME = "summary" +DEFAULT_READINGS = ("temperature", "humidity") # the station's usual set: outdoor and indoor temperature and humidity +LAYOUTS = ("auto", "panels", "two_axes", "same_axis") +RATING = ":rating" +AIR_QUALITY = tuple(AIR) # the air sensor's readings that have a rating (its own temperature and humidity have none) +# The periods a chart of readings over time is worth drawing over (3.7); one of each day's average needs two whole days at least +OVER_TIME = ({"period": "1d", "label": "1D"}, {"period": "7d", "label": "7D"}, {"period": "1m", "label": "1M"}, + {"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}) +DAILY_MEANS = OVER_TIME[1:] +DAILY_ALL_DAYS = 7 # as HistoryQuery: a longer period lists only the days of its records, unless every_day +# The notes a caption carries itself (lib/bot.py CAPTIONED_NOTES for weather_history and air_quality): any other needs the model's words +CAPTIONED = {"missing", "warning"} +AIR_CAPTIONED = {"missing"} +DATE = re.compile(r"\d{4}-\d\d-\d\d") + +DESCRIPTION = ( + "What was measured over a period: each reading's lowest and highest with when, " + "averages, a by-day or by-month breakdown, wind direction, rain that fell, air ratings and AQI; a chart of any.\n" + "Examples: \"how hot did it get this week\" {readings: [\"temperature\"], period: \"this week\"}; \"lowest and highest humidity\" " + "{readings: [\"humidity\"]} (today); \"is today hotter than yesterday\" {readings: [\"temperature\"], period: \"yesterday to " + "today\", every_day: true}; a record with when (\"hottest record\", \"highest ever\", \"use 5 minute data\") {readings: " + "[\"outdoor.temperature\"], period: \"on record\"}; average {readings: [\"humidity\"], period: \"last " + "month\", average: true}; \"plot pressure this week\" {readings: [\"pressure\"], period: \"this week\", chart: true, " + "chart_answers_it: true}; a device or reading and a period is the past, charted: \"weather week\", \"ecowitt week\" {readings: " + "[\"all\"], period: \"week\", chart: true}, \"wind 3m\" {readings: [\"wind\"], period: \"3m\", chart: true}; a rating and rain " + "{readings: [\"pm2.5:rating\", \"rain\"]}.\n" + "`period` is the person's words unchanged: \"past week\" is the last 7 days, \"last week\" the previous Monday to Sunday.\n" + "Not for: days ranked, counted or filtered (wettest day, days over 35°C, rain per month): days. Values at set times: readings. " + "A reading against rain: relate. Now: current. Ahead: forecast.\n" + "Result: `series` by name; quote low_text, high_text with low_when, low_date, and day_look's emoji. A chart's `caption` is " + "ready; with complete: true, `reply` is the answer.") + + +def _boolean(description: str) -> dict: + return {"type": "boolean", "description": description} + + +ARGUMENTS = { # every argument but the readings and the period, as a model reads them + "average": _boolean("true when the question asks for an average or mean: adds each reading's average over the period (weighted " + "by time) and per day or month, and draws the chart as each day's average. Air readings always have theirs. " + "Default false."), + "every_day": _boolean("true to list every day of a period of up to 31 days; otherwise a period over 7 days lists only the days of " + "its lows and highs. Default false."), + "chart": _boolean("Draw a chart. Default: on for periods of 3 days or more."), + "chart_readings": {"type": "array", "items": {"type": "string"}, + "description": "What to draw, top to bottom, when not all of `readings`: names or words as for readings; \"all\" " + "is every weather-station reading in the station's usual order; add \":rating\" to an air-quality " + "reading to draw its traffic-light rating (\"air.pm2_5:rating\"). Default: all of readings."}, + "layout": {"type": "string", "enum": list(LAYOUTS), + "description": "auto (or panels): one reading as a line for each sensor that has it (wind with its compass rose), several " + "as a panel each on one time axis. two_axes: two readings on one panel, a scale each (or more in exactly two " + "units). same_axis: readings in one unit over each other. Default auto."}, + "invert_second_axis": _boolean("With layout two_axes: the right-hand scale runs top to bottom."), + "chart_answers_it": _boolean("true only when the question is just to see this chart and its figures: nothing else to answer (\"plot " + "pressure this week\", not \"plot pressure this week: is a storm coming?\"). Then the result carries the " + "finished reply (`reply`, `complete`: true)."), +} + + +def tools(ctx: Context) -> list[ServiceTool]: + return [Summary(ctx).tool] + + +# ---------- the call as read ---------- +@dataclass +class Call: + """A call as the tool read it: every argument resolved and every default filled in.""" + readings: list[Reading] + drawn: list[tuple[Reading, bool]] # chart_readings: each reading, and whether it is drawn as its rating + period: Period + when: dict # the period as drawn_by states it: {"period": words} or {"start", ["end"]} + average: bool + every_day: bool + chart: bool + layout: str + invert: bool + answers: bool # chart_answers_it + + @property + def replays(self) -> bool: + """Can the period be swapped for another (drawn_by.periods)? Words can; a start or end with a time can't.""" + return "period" in self.when + + def arguments(self) -> dict: + """The call as drawn_by states it: the readings' full names, the period in words, every default filled in.""" + return {"readings": [r.name for r in self.readings], **self.when, "average": self.average, "every_day": self.every_day, + "chart": True, "chart_readings": [r.name + (RATING if rating else "") for r, rating in self.drawn], + "layout": self.layout, "invert_second_axis": self.invert, "chart_answers_it": self.answers} + + +def _flag(args: dict, name: str) -> bool | None: + """A true-or-false argument: None when it isn't sent.""" + value = args.get(name) + if value is None or isinstance(value, bool): + return value + if str(value).strip().lower() in ("true", "false"): + return str(value).strip().lower() == "true" + raise Refusal(f"`{name}` is true or false, not {value!r}.") + + +def _words(raw) -> list[str]: + """The names in a readings argument: a list of them, or one string of them separated by commas or "and".""" + if raw is None: + return [] + items = raw if isinstance(raw, (list, tuple)) else [raw] + return [w for item in items for w in (part.strip() for part in re.split(r"[,;+&]| and ", str(item))) if w] + + +def _period_words(args: dict) -> dict: + """The period as drawn_by states it: words as sent; whole days ('YYYY-MM-DD' start and end, or a start alone) as words too ("2026-11-01 + to 2026-11-05", "2026-11-01 to now"), so another period can be swapped in; a start or end with a time as it came.""" + period, start, end = (str(args[k]).strip() if args.get(k) is not None and str(args[k]).strip() else None + for k in ("period", "start", "end")) + if start is None or period: # (`period` wins over start and end sent beside it: common.read_period) + return {"period": period} + if DATE.fullmatch(start) and (end is None or DATE.fullmatch(end)): + return {"period": f"{start} to {end or 'now'}"} + return {"start": start, **({"end": end} if end else {})} + + +# ---------- what each engine calls a reading ---------- +def _engine_key(r: Reading) -> str: + """HistoryQuery's name for a station reading: its "group.field", as the group names it (rain is the running daily total, + "rainfall.daily"; indoor's apparent temperature "indoor.app_tempin").""" + return f"{r.sensor}.{field_of(r.sensor, r.column)}" + + +def _station_series(r: Reading) -> str | None: + """The station reading as HistoryQuery charts it (lib/series.py's name: temperature for both sides, wind for its speed, gusts and + direction), None for one it draws only alone (rain rate, absolute pressure, apparent temperature).""" + if r.sensor == "wind": + return "wind" + if r.combine == "rain": + return "rain" if r.sensor == "rainfall" else None + return r.series if r.series in WEATHER else None + + +def _composer_series(r: Reading) -> str | None: + """The reading as plot_chart names it, None when it can't draw it: the station's outdoor readings only (WEATHER), the air sensor's + all.""" + if r.device == AIR_DEVICE: + return r.column + if r.sensor == "wind": + return "wind" + if r.name == "rainfall.rain": + return "rain" + return r.series if r.series in WEATHER and WEATHER[r.series].group == r.sensor else None + + +def _number(raw): + """A figure as the station writes it ("12.3", "62") as a number.""" + try: + value = float(raw) + except (TypeError, ValueError): + return raw + return int(value) if str(raw).lstrip("-").isdigit() else value + + +def _text(value, unit: str) -> str: + return f"{value} {unit}".strip() + + +# ---------- the station's engine ---------- +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): + return None + + def sibling(self, groups: list[str]) -> "Fetcher": + return _HeldOnly(self.api, self.storage, self.recent, self.mac, groups, self.tz, self.urgent, self.has_minutes) + + +def _rain_on(r, mac: str, plan: list[tuple[str, int, int]], start: int, end: int) -> Held: + """The rain counter's reads for its bars, as history_on makes them when a chart has rain: its readings of the plan, its settled + 30-minute readings and its daily records.""" + held = Held({}, {}) + for cycle, a, b in plan: + readings_on(r, mac, ["rainfall"], cycle, a, b, held.store, ["daily"]) + held.rain = slot_values_on(r, mac, "rainfall", "daily", "30min", start, end)[0] + held.rain_daily = slot_values_on(r, mac, "rainfall", "daily", "1day", start - 86400, end + 86400)[0] + return held + + +class _Query(HistoryQuery): + """HistoryQuery as summary runs it: a chart only when the call draws one here (`drawn`), of the readings drawn alone (`keys`, its + "group.field" names; a reading that isn't drawn gives no line), and the rain's bars whenever rain is summarised, chart or not.""" + + def __init__(self, fetcher: Fetcher, args: dict, turn: Turn, *, drawn: bool, keys: set[str] | None): + super().__init__(fetcher, args, turn) + self.drawn, self.keys = drawn, keys + self.plan: list[tuple] = [] + + async def _hold_period(self): + self.plan = await super()._hold_period() + return self.plan + + def _drawing(self, plan): + return super()._drawing(plan) if self.drawn else ("none", 0) + + def _add_charts(self, out: dict, plottable: dict): + if self.drawn: + super()._add_charts(out, plottable) + + def _series_entry(self, k: str): + return None if self.keys is not None and k not in self.keys else super()._series_entry(k) + + async def rain(self) -> Bars: + """The rain that fell, in the bars a chart of the period draws (rain_bars): the chart's own, else worked out the same way.""" + if not self.rain_bars.x: + f = self.f + plan = [(cycle, f.epoch(a), f.epoch(b)) for cycle, a, b in self.plan] + held = await f.stored(_rain_on, f.mac, plan, f.epoch(self.start), f.epoch(self.end)) + self.store.setdefault("rainfall.daily", held.store.get("rainfall.daily", {"unit": "mm", "pts": {}})) + self.rain_bars = self._rain_bars(held) + return self.rain_bars + + +# ---------- the caption (the old lib/report.py's chart_caption, its wording kept) ---------- +def _year(text: str | None) -> str: + """"Tue 29 Sep 2026" -> "Tue 29 Sep".""" + return re.sub(r" 20\d\d\b", "", text or "") + + +def _period_line(text: str) -> str: + """"Tue 29 Sep 2026 - Tue 6 Oct 2026" -> "Tue 29 Sep – Tue 6 Oct 2026" (the first year is dropped only when it is the same year).""" + years = re.findall(r" (20\d\d)\b", text) + if len(years) == 2 and years[0] == years[1]: + text = re.sub(r" 20\d\d\b(?= - )", "", text) + return text.replace(" - ", " – ") + + +def _at(entry: dict, which: str) -> str: + """"24.3 °C, Tue 29 Sep around 3pm" for one record of a series.""" + when = _year(f"{entry.get(f'{which}_date', '')} {entry.get(f'{which}_when', '')}".strip()) + return f"{entry[which]} {unit_text(entry.get('unit')) or ''}".strip() + (f", {when}" if when else "") + + +def _range(label: str, entry: dict, average: bool) -> str: + unit = unit_text(entry.get("unit")) or "" + if average and entry.get("average"): + return f"{label}: average {entry['average']} {unit} (low {entry['low']}, high {entry['high']})".replace(" )", ")") + return f"{label}: low {_at(entry, 'low')} · high {_at(entry, 'high')}" + + +def _rain_line(charts: list[Chart], tz, bars: Bars | None = None) -> list[str]: + """Least and most rain in a period (the chart's own bars, else `bars`: those a chart of the period would draw).""" + bars = next((p.bars for c in charts for p in c.panels if p.bars and p.bars.x), bars) + if not bars or not bars.x: + return [] + + def day(i: int) -> str: + start = to_local(bars.x[i], tz) + return day_text(start, year=False) + (f" {clock_text(start, whole_hours=True)}" if bars.width < 86400 else "") + lo, hi = min(range(len(bars.y)), key=bars.y.__getitem__), max(range(len(bars.y)), key=bars.y.__getitem__) + per = f" per {bars.per}" if bars.per else "" + return [f"☔ Rain{per}: least {bars.y[lo]:g} mm ({day(lo)}) · most {bars.y[hi]:g} mm ({day(hi)}) · {sum(bars.y):.1f} mm in all"] + + +def _weather_lines(series: dict, names: list[str], average: bool, charts: list[Chart], tz) -> list[str]: + """A line per series of each reading drawn (HistoryQuery's series: "group.field" names, figures as the station writes them).""" + lines: list[str] = [] + for name in [n for n in dict.fromkeys(names) if find(n)]: + reading = find(name) + keys = [k for k in series if k.split(".", 1)[1] == reading.field] + if reading.field == "daily": # rain: the amounts the chart draws + lines += _rain_line(charts, tz) + continue + for key in keys: + group = key.split(".", 1)[0] + label = reading.label + (f" ({group})" if len(keys) > 1 and group in ("outdoor", "indoor") else "") + if reading.field == "wind_speed": + gust = series.get(f"{group}.wind_gust") or series.get("wind.wind_gust") + lines.append(f"🌬️ Wind: strongest gust {_at(gust, 'high')}" if gust else _range(label, series[key], average)) + else: + lines.append(_range(label, series[key], average)) + if reading.field == "wind_speed" and (d := series.get("wind.wind_direction")): + lines.append(f"🧭 Mostly from the {d['most_common']}" + (f", {d['steadiness']}" if d.get("steadiness") else "")) + return lines + + +def _air_lines(result: dict, metrics: list[str]) -> list[str]: + """A line per air-quality metric drawn (AirGradient.history's result): its peak, the peak's rating and the average.""" + lines = [] + for key, label in ((name, m.label) for name, m in AIR.items()): + entry = result.get(key) + if key not in (metrics or ["pm2_5"]) or not isinstance(entry, dict): + continue + unit = unit_text(entry.get("unit")) or "" + rating = entry.get("high_rating") + lines.append(f"• {label}: peak {entry['high']} {unit} ({_year(entry.get('high_time'))})".replace(" )", ")") + + (f" · {rating}" if rating else "") + f" · average {entry['average']}") + return lines + + +def _series_label(field: str) -> str: + """A series' name: its reading's label ("Temperature"), the gusts their own ("Wind gust").""" + if field == "wind_gust": + return "Wind gust" + return reading.label if (reading := find(field)) else field.replace("_", " ").capitalize() + + +def _extremes_lines(series: dict, names: list[str]) -> list[str]: + """The low and high (or the average) of each reading named, each with its day and time: wind, its speed and its gusts. A reading on + both sides (indoor, outdoor) has a line for each (the old lib/report.py's plain lookup of a weather_history result, "extremes").""" + wanted = [f for r in filter(None, map(find, names)) for f in (r.field, r.band_field) if f] or ["temperature"] + keys = [k for k in series if k.split(".", 1)[1] in wanted and "low" in series[k]] + fields = [k.split(".", 1)[1] for k in keys] + lines = [] + for key in keys: + group, field = key.split(".", 1) + label = _series_label(field) + (f" ({group})" if fields.count(field) > 1 else "") + lines.append(f"• {_range(label, series[key], 'average' in series[key])}") + return lines + + +def _caption(period: str, lines: list[str], note_missing: bool, warning: bool, more: list[str] = ()) -> str | None: + """The caption: the period, a line per reading, and what the figures lack; None with no line to write.""" + if not lines: + return None + notes = (["(Older days are still downloading, so they are left out.)"] if note_missing else + ["(Some data couldn't be fetched, so this may be incomplete.)"] if warning else []) + return "\n".join([_period_line(period), *lines, *more, *notes]).strip() + + +# ---------- the tool ---------- +class Summary: + def __init__(self, ctx: Context): + self.ctx = ctx + self.tool = ServiceTool(NAME, DESCRIPTION, self.parameters(), self.handle, open_world=True) + + def parameters(self) -> dict: + names = self.ctx.readings().description() + rating = (" An air-quality reading with \":rating\" (\"air.pm2_5:rating\") is summarised and drawn as its traffic-light " + "rating.") if self.ctx.air is not None else "" + return {"type": "object", "properties": { + "readings": {"type": "array", "items": {"type": "string"}, + "description": f"What to summarise. {names}{rating} Default: outdoor and indoor temperature and humidity."}, + **period_properties("today; with chart true and no period, the last 24 hours"), + **ARGUMENTS}} + + # ---------- reading the call ---------- + async def read(self, args: dict) -> Call: + """The call as read, or a Refusal that teaches the right one.""" + ctx = self.ctx + props = self.tool.parameters["properties"] + if unknown := [k for k in args if k not in props]: + hint = " Send the period as `period` (words) or `start` and `end`." if {"start_date", "end_date"} & set(unknown) else \ + " Send the readings as `readings`." if {"metrics", "groups", "metric"} & set(unknown) else "" + raise Refusal(f"summary doesn't take {', '.join(map(repr, unknown))}.{hint}", arguments=list(props)) + catalogue = ctx.readings() + default = list(DEFAULT_READINGS) if ctx.eco else "air" + sent = _words(args.get("readings")) + rated = any(w.lower().endswith(RATING) for w in sent) # "air.pm2_5:rating" in readings: summarised, and drawn as its rating + plain = [w[:-len(RATING)].strip() if w.lower().endswith(RATING) else w for w in sent] + readings = catalogue.resolve(plain if rated else args.get("readings"), default=default) + drawn = self._drawn(args.get("chart_readings") if _words(args.get("chart_readings")) or not rated else sent, readings) + for r in {r for r in [*readings, *(r for r, _ in drawn)]}: + if (r.device == STATION and ctx.eco is None) or (r.device == AIR_DEVICE and ctx.air is None): + device = "weather station" if r.device == STATION else "air sensor" + raise Refusal(f"There is no {device} here, so {r.name} can't be read.", names=catalogue.names) + layout = str(args.get("layout") or "auto").strip().lower() + if layout not in LAYOUTS: + raise Refusal(f"`layout` is one of {', '.join(LAYOUTS)}, not {args.get('layout')!r}.", layouts=list(LAYOUTS)) + chart = _flag(args, "chart") + if chart is None and any(rating for _, rating in drawn): # a rating is only ever drawn + chart = True + asked = any(str(args.get(k) or "").strip() for k in ("period", "start", "end")) + period = read_period(args, tz=ctx.zone, now=ctx.now(), default="last 24 hours" if chart and not asked else "today", + first_held=await self._first_held([*readings, *(r for r, _ in drawn)])) + long = (period.last_day - period.first_day).days >= CHART_MIN_DAYS - 1 + when = _period_words(args) if asked else {"period": period.asked} + return Call(readings, drawn, period, when, bool(_flag(args, "average")), bool(_flag(args, "every_day")), + long if chart is None else chart, layout, bool(_flag(args, "invert_second_axis")), bool(_flag(args, "chart_answers_it"))) + + def _drawn(self, raw, readings: list[Reading]) -> list[tuple[Reading, bool]]: + """chart_readings as read: each reading named (words too; "all"), in order, each once, with whether it is drawn as its rating.""" + words = _words(raw) + if not words: + return [(r, False) for r in readings] + out: dict[tuple[str, bool], tuple[Reading, bool]] = {} + for word in words: + rating = word.lower().endswith(RATING) + base = word[:-len(RATING)].strip() if rating else word + for r in self.ctx.readings().resolve(base, default=base): + if rating and (r.device != AIR_DEVICE or r.column not in AIR_QUALITY): + raise Refusal(f"Only the air sensor's air-quality readings have a rating ({', '.join(f'air.{m}' for m in AIR_QUALITY)}): " + f"{r.name} can't be drawn as one. Draw it as it is: {r.name!r}.") + out.setdefault((r.name, rating), (r, rating)) + if not out: + raise Refusal(f"chart_readings names no reading: send names or words as for readings, such as \"pressure\" or " + f"\"air.pm2_5{RATING}\".", names=self.ctx.readings().names) + return list(out.values()) + + async def _first_held(self, readings: list[Reading]) -> date | None: + """The first day held of these readings' sensors ("on record" starts there).""" + ctx, storage = self.ctx, self.ctx.storage + if storage is None: + return None + groups = sorted({r.sensor for r in readings if r.device == STATION}) + air = any(r.device == AIR_DEVICE for r in readings) and ctx.air is not None + + def first(r) -> date | None: + sensors = [s for g in groups if ctx.eco and (s := r.sensor(ctx.eco.mac, g)) is not None and s.kind in KINDS] + if air and (s := ctx.air.store.sensor) is not None: + sensors.append(s) + days = [r.db.execute(f"SELECT MIN(day) FROM {s.kind}_day WHERE sensor = ?", (s.id,)).fetchone()[0] for s in sensors] + return min((date.fromisoformat(d) for d in days if d), default=None) + return await storage.read(first) + + def _route(self, call: Call) -> str | None: + """Which engine draws the chart: "station" (HistoryQuery), "air" (AirGradient.history), "composer" (plot_chart), or None + (no chart). Refuses a chart that can't be drawn as asked, saying what can.""" + if not call.chart: + return None + station = [r for r, _ in call.drawn if r.device == STATION] + air = [r for r, _ in call.drawn if r.device == AIR_DEVICE] + rating = any(rating for _, rating in call.drawn) + if call.invert and call.layout != "two_axes": + raise Refusal("invert_second_axis needs layout two_axes: it turns the right-hand scale upside down.") + lines = [(r, rating) for r, rating in call.drawn if r.reading != "wind_direction"] + if call.layout in ("two_axes", "same_axis") and (rating or any(r.combine == "rain" for r, _ in lines)): + raise Refusal(f"layout {call.layout} draws lines: rain (bars) and ratings can't share a panel. Use layout auto, a panel each.") + composer = (station and air) or rating or call.layout == "same_axis" or (air and call.layout == "two_axes") + if composer: + if self.ctx.eco is None: + raise Refusal(f"layout {call.layout} is drawn only where there is a weather station: use layout auto.") + if bad := [r.name for r, _ in lines if _composer_series(r) is None]: + drawable = [r.name for r in self.ctx.readings() if _composer_series(r)] + raise Refusal(f"{', '.join(bad)} can't go on a chart that mixes the two sensors, draws a rating or uses same_axis: such a " + f"chart draws only these readings. Draw {', '.join(bad)} in a call of its own.", drawable=drawable) + series = list(dict.fromkeys((_composer_series(r), rating) for r, rating in lines)) + if len(series) > MAX_PANELS: + raise Refusal(f"A chart that mixes the two sensors, draws a rating or uses same_axis takes at most {MAX_PANELS} readings, " + f"not {len(series)}: draw the rest in another call.") + if call.layout in ("two_axes", "same_axis") and len(series) < 2: + raise Refusal(f"layout {call.layout} needs two readings or more in chart_readings (it puts them on one panel).") + return "composer" + if station: + if any(r.sensor == "rainfall_piezo" for r in station): + raise Refusal("The piezo rain gauge isn't drawn: draw rainfall.rain, the main gauge.") + series = list(dict.fromkeys(_station_series(r) or r.name for r in station)) + alone = [r.name for r in station if _station_series(r) is None] + if alone and len(series) > 1: + raise Refusal(f"{', '.join(alone)} can only be drawn on a chart of its own: send it alone in chart_readings.") + if call.layout == "two_axes" and len(series) < 2: + raise Refusal("layout two_axes needs two readings or more in chart_readings (it puts them on one panel, a scale each); " + "outdoor and indoor of one reading are already one panel.") + return "station" + return "air" + + # ---------- answering ---------- + async def handle(self, args: dict, meta: dict) -> str: + ctx = self.ctx + call = await self.read(args) + route = self._route(call) + if route == "composer" and self._whole_days(call) is None: + yesterday = ctx.now().date() - timedelta(days=1) + raise Refusal(f"A chart that mixes the two sensors, draws a rating or uses same_axis is drawn over whole days, up to " + f"yesterday ({day_text(yesterday)}): {call.period.text} has none. Ask for a period with whole days ('last 24 " + f"hours' draws yesterday, 'last 7 days'), or leave the chart out.") + background, fetch = meta.get("priority") == BACKGROUND, meta.get("fetch", True) + station = [r for r in call.readings if r.device == STATION] + air = [r for r in call.readings if r.device == AIR_DEVICE] + drawn_station = [r for r, _ in call.drawn if r.device == STATION] if route in ("station", "composer") else [] + drawn_air = [r for r, _ in call.drawn if r.device == AIR_DEVICE] if route in ("air", "composer") else [] + charts: list[Chart] = [] + found: dict = {"missing": [], "warning": False, "notes": {}} + q = out = None + if station or drawn_station: + q, out = await self._station(call, station, drawn_station, route == "station", background, fetch, charts, found) + air_out = None + if air or drawn_air: + figures = list(dict.fromkeys([*air, *(drawn_air if route == "composer" else [])])) + air_out = await self._air(call, figures, drawn_air if route == "air" else [], charts, found) + if route == "composer": + await self._compose(call, charts, found) + looks = await self._looks(call.period.first_day, call.period.last_day) + series, no_readings = {}, [] + rain_total = None + for r in call.readings: + if r.device == STATION: + entry = await self._station_entry(r, q, out, looks, call) if q else None + if r.name == "rainfall.rain" and entry: + rain_total = entry["total"] + else: + entry = self._air_entry(r, air_out, looks) + if entry: + series[r.name] = entry + else: + no_readings.append(r.name) + if not series and not charts: + first = await self._first_held(call.readings) + raise Refusal(f"Nothing is held of {', '.join(no_readings)} for {call.period.text}." + + (f" What is held starts on {day_text(first)}." if first else ""), + **({"held_from": first.isoformat()} if first else {}), + **({"missing": found["missing"][:10]} if found["missing"] else {})) + fields: dict = {"series": series} + if rain_total is not None: + fields["rain_total_mm"] = rain_total + if out and out.get("monthly_note"): + fields["monthly_note"] = out["monthly_note"] + if no_readings: + fields["note_no_readings"] = (f"Nothing held of {', '.join(no_readings)} for this period: say so." if not series else + f"Nothing held of {', '.join(no_readings)} for this period; the others are summarised.") + if call.chart and not charts and "chart" not in found["notes"]: + fields["note_chart"] = ("No chart: an average chart draws each whole day's average, and this period has fewer than two whole " + "days before today." if call.average else "No chart: too few readings to draw for this period.") + if found["notes"]: + fields["notes"] = found["notes"] + if found["missing"]: + fields["missing"] = found["missing"][:10] + if found["warning"]: + fields["warning"] = "Some data could not be fetched; the answer may be incomplete. Say so." + caption = self._caption(call, route, charts, out, air_out, found) if charts else None + if caption: + fields["caption"] = caption + elif not charts and (text := self._text(call, q, out, air_out)): + fields["text"] = text + finished = call.answers and charts and caption and not self._needs_words(fields) and not call.period.note # (the model reads it) + fields.update(self._charts(call, route, charts, meta)) + if finished: + fields.update(complete(caption)) + return answer(period=call.period, as_of=ctx.now(), **fields) + + def _span(self, call: Call) -> tuple[str, str]: + """The period as the engines take it ('YYYY-MM-DD HH:MM:SS', both ends included): to its last second, or, for a period that runs + to now, to now itself (the reading of this very minute is in it, as it always was).""" + start, end = call.period.as_naive_strings() + now = self.ctx.now().replace(microsecond=0) + if call.period.end >= now: + end = f"{now.astimezone(self.ctx.zone):%Y-%m-%d %H:%M:%S}" + return start, end + + async def _station(self, call: Call, station: list[Reading], drawn: list[Reading], here: bool, background: bool, fetch: bool, + charts: list[Chart], found: dict) -> tuple[_Query | None, dict | None]: + """HistoryQuery over the station's readings summarised and drawn, drawing its chart when `here`.""" + eco = self.ctx.eco + every = [*station, *drawn] + groups = list(dict.fromkeys(r.sensor for r in every)) + named = [s for s in dict.fromkeys(_station_series(r) or r.column for r in drawn if here)] + series_names = list(dict.fromkeys(_station_series(r) or r.column for r in every)) + turn = Turn(chart_asked=here, chart_field=named[0] if len(named) == 1 else None, chart_fields=named if len(named) > 1 else [], + two_axes=here and call.layout == "two_axes", average_asked=call.average, per_day=call.every_day, + readings=series_names, ahead=background) + start, end = self._span(call) + args = {"start_date": start, "end_date": end, "average": call.average, + "include_derived": sorted({r.column for r in every if r.column in DERIVED})} + make = Fetcher if fetch else _HeldOnly + fetcher = make(eco.api, eco.storage, eco.fetches, eco.mac, groups, eco.tz, not background, eco.has_minutes) + keys = {k for r in drawn for k in (("wind.wind_speed",) if r.sensor == "wind" else (_engine_key(r),))} if here else None + q = _Query(fetcher, args, turn, drawn=here, keys=keys) + text = await q.run() + if text.startswith("Error"): + if "within the last" in text: # (the period's start is checked against the history kept: only one before it all is refused) + start = kept_from("1day", self.ctx.now().date()) + raise Refusal(f"The weather station's history goes back {CYCLES['1day'].kept // 365} years, to {day_text(start)}: " + f"{call.period.text} is before it.", held_from=start.isoformat()) + if "Details: " in text: # nothing held, and what was asked for couldn't be fetched + found["missing"] += text.split("Details: ", 1)[1].split("; ") + found["warning"] = True + return None, None + out = json.loads(text) + for chart in turn.charts: + chart.source = chart.source or ECOWITT_SOURCE + if call.invert: + for panel in chart.panels: + panel.flip_right = panel.flip_right or any(line.right for line in panel.lines) + charts += turn.charts + if out.get("missing"): + found["missing"] += out["missing"] + found["warning"] = found["warning"] or bool(out.get("warning")) + if any(r.name == "rainfall.rain" for r in station): + await q.rain() + return q, out + + async def _air(self, call: Call, figures: list[Reading], drawn: list[Reading], charts: list[Chart], found: dict) -> dict | None: + """AirGradient.history over the air readings whose figures are wanted (and drawn, when the chart is the air sensor's alone). Its + `metrics` are what it draws, and bring in its own temperature and humidity: a reading summarised but not drawn that is one of + those takes a call of its own.""" + start, end = self._span(call) + metrics = [r.column for r in drawn] + wanted = [r.column for r in figures] + out: dict = {} + try: + if drawn: + turn = Turn(air_named=metrics) + out = await self.ctx.air.history(start, end, chart=True, metrics=metrics, turn=turn, daily=call.average) + for chart in turn.charts: + chart.source = chart.source or AIR_SOURCE + charts += turn.charts + if not drawn or (out.get("readings") and any(m not in out for m in wanted)): + more = await self.ctx.air.history(start, end, chart=False, metrics=wanted or None, turn=Turn()) + out = {**more, **out} if drawn else more + except Exception as e: # the sensor or its cloud is down: the station's figures still stand + found["missing"].append(f"air sensor: {type(e).__name__}: {e}") + found["warning"] = True + return None + if "error" in out: + found["missing"].append(f"air sensor: {out['error']}") + return None + notes = {k.removeprefix("note_") if k != "note" else "none": v for k, v in out.items() if k == "note" or k.startswith("note_")} + if notes: + found["notes"]["air"] = notes + return out + + async def _compose(self, call: Call, charts: list[Chart], found: dict): + """The chart plot_chart draws: whole days up to yesterday, so a period that runs into today is cut, and said so.""" + ctx = self.ctx + composer = ctx.composer or Composer(ctx.eco, ctx.air) + first, last = self._whole_days(call) + panels, seen = [], set() + for r, rating in call.drawn: + name = _composer_series(r) + if name is None or (r.reading == "wind_direction") or (name, rating) in seen: + continue + seen.add((name, rating)) + panels.append({"series": name, "style": "rating" if rating else "bars" if name == "rain" else "line"}) + args = {"panels": panels, "start_date": first.isoformat(), "end_date": last.isoformat(), + "two_axes": call.layout == "two_axes", "same_axis": call.layout == "same_axis", "invert_second_axis": call.invert} + turn = Turn() + result = json.loads(await composer.plot_chart(args, turn)) + if "error" in result: # (what plot_chart refuses is checked first: this is a reading it has nothing of) + found["notes"]["chart"] = f"No chart: {result['error'].rstrip('.')}." + return + for chart in turn.charts: # the devices its readings come from (plot_chart leaves out a rating's) + chart.source = " and ".join(name for name, device in ((ECOWITT_SOURCE, STATION), (AIR_SOURCE, AIR_DEVICE)) + if any(r.device == device for r, _ in call.drawn)) + charts += turn.charts + cut, early = last < call.period.last_day, call.period.start.time() != time() + if cut or early: # (the air sensor's own notes on the days it lacks are in its figures' notes already) + found["notes"]["chart"] = (f"The chart draws whole days, {day_text(first, year=False)} to {day_text(last, year=False)}" + + (": a chart that mixes the two sensors, draws a rating or uses same_axis is drawn over whole days " + "up to yesterday, as today isn't over" if cut else "") + ".") + + def _whole_days(self, call: Call) -> tuple[date, date] | None: + """The first and last day plot_chart draws for this period: its days up to yesterday (None when that leaves none).""" + first, last = call.period.first_day, min(call.period.last_day, self.ctx.now().date() - timedelta(days=1)) + return (first, last) if first <= last else None + + async def _looks(self, first: date, last: date) -> Callable[[date | None], dict | None]: + """day -> its look (daylook.day_look over its day row's figures), for the days of the period; nothing without the station.""" + eco = self.ctx.eco + if eco is None: + return lambda day: None + days = [first + timedelta(days=n) for n in range((last - first).days + 1)] + values, _ = await eco.storage.read(day_values_on, eco.mac, list(FIGURES), days) + today = self.ctx.now().date() + + def look(day: date | None) -> dict | None: + if day is None: + return None + return day_look({n: values[n].get(day) for n in FIGURES}, latitude=eco.latitude, day=day, so_far=day >= today) + return look + + # ---------- the figures ---------- + async def _station_entry(self, r: Reading, q: _Query, out: dict, looks, call: Call) -> dict | None: + """One station reading as the service gives it.""" + key = _engine_key(r) + if r.name == "rainfall.rain": + return await self._rain_entry(q, looks, call) if key in q.units else None + got = (out.get("series") or {}).get(key) or q.direction.get(key) + if not got: + return None + if r.combine == "rain": # the piezo gauge: its running daily total, whose highest is a day's total + got = {k: v for k, v in got.items() if not k.startswith("low")} | { + "how_to_read": "The gauge's running daily total: its high is the most rain in a day. Its total over the period is " + "rainfall.rain's, the main gauge."} + if r.reading == "wind_direction": + return {k: got[k] for k in ("most_common", "then", "average_direction", "steadiness", "calm", "note", "note_period", "daily") + if k in got} + unit = unit_text(got.get("unit")) or r.unit + entry = {"unit": unit} + for want in ("low", "high"): + if want not in got: + continue + ext = q.overall.get(key, {}).get(want) + entry[want] = _number(got[want]) + entry[f"{want}_text"] = _text(got[want], unit) + entry[f"{want}_when"] = got[f"{want}_when"] + if got.get(f"{want}_date"): + entry[f"{want}_date"] = got[f"{want}_date"] + if ext and (look := looks(local_date(ext.ts, q.tz))): + entry[f"{want}_day_look"] = look + if f"{want}_note" in got: + entry[f"{want}_note"] = got[f"{want}_note"] + if "average" in got: + entry["average"], entry["average_text"] = _number(got["average"]), _text(got["average"], unit) + if "how_to_read" in got: + entry["how_to_read"] = got["how_to_read"] + days = {q._label(d.day): d.day for d in q.period[key].days} if key in q.period else {} + if "daily" in got: + entry["daily"] = {label: {**{w: _number(v) for w, v in row.items() if w in ("low", "high")}, + **({"average": _number(row["avg"])} if "avg" in row else {}), + **({"day_look": look} if (look := looks(days.get(label))) else {})} + for label, row in got["daily"].items()} + if "monthly" in got: + monthly = {} + for label, row in got["monthly"].items(): + month = {w: _number(row[w]) for w in ("low", "high") if w in row} + for w in ("low", "high"): + if row.get(f"{w}_date"): + month[f"{w}_when"], month[f"{w}_date"] = row[f"{w}_when"], row[f"{w}_date"] + ext = q.monthly.get(key, {}).get(label, {}).get(w) + if ext and (look := looks(local_date(ext.ts, q.tz))): + month[f"{w}_day_look"] = look + if "avg" in row: + month["average"] = _number(row["avg"]) + monthly[label] = month + entry["monthly"] = monthly + return entry + + async def _rain_entry(self, q: _Query, looks, call: Call) -> dict: + """Rain as the mm that fell: the total, the wettest day, and a row per day or month (each the sum of the chart's bars in it).""" + bars = await q.rain() + total = round(sum(bars.y), 1) + per_day: dict[date, float] = {} + rows: dict[str, float] = {} + for t, mm in zip(bars.x, bars.y): + day = local_date(t, q.tz) + per_day[day] = per_day.get(day, 0.0) + mm + rows[q._label(day)] = rows.get(q._label(day), 0.0) + mm + entry: dict = {"unit": "mm", "total": total, "total_text": f"{total:.1f} mm"} + wettest = max(per_day, key=per_day.get) if per_day and max(per_day.values()) > 0 else None + if wettest: + mm = round(per_day[wettest], 1) + entry["wettest_day"] = {"date": day_text(wettest), "mm": mm, "text": f"{mm:.1f} mm", + **({"day_look": look} if (look := looks(wettest)) else {})} + if q.by_day: + keep = None if len(per_day) <= DAILY_ALL_DAYS or call.every_day else {wettest} + entry["daily"] = {q._label(day): {"total": round(mm, 1), **({"day_look": look} if (look := looks(day)) else {})} + for day, mm in per_day.items() if keep is None or day in keep} + else: + entry["monthly"] = {label: {"total": round(mm, 1)} for label, mm in rows.items()} + if q.rain_from_daily: + entry["note"] = (f"Older days come from Ecowitt's daily records, which run {daily_run(q.tz, q.start.date(), q.end.date())}, " + f"so their rain may fall on the day before.") + return entry + + def _air_entry(self, r: Reading, out: dict | None, looks) -> dict | None: + """One air reading as the service gives it: AirGradient.history's figures with their wording.""" + got = (out or {}).get(r.column) + if not isinstance(got, dict): + return None + unit = unit_text(got.get("unit")) or r.unit + entry = {"unit": unit} + for want in ("low", "high"): + entry[want] = got[want] + entry[f"{want}_text"] = _text(got[want], unit) + try: + at = datetime.strptime(got.get(f"{want}_time") or "", "%a %d %b %Y %I:%M%p") + except ValueError: + continue + entry[f"{want}_when"], entry[f"{want}_date"] = f"at {clock_text(at, whole_hours=True)}", day_text(at) + if look := looks(at.date()): + entry[f"{want}_day_look"] = look + entry["average"], entry["average_text"] = got["average"], _text(got["average"], unit) + for k in ("high_rating", "average_rating", "high_aqi_us", "high_band", "average_aqi_us", "average_band"): + if k in got: + entry[k] = got[k] + return entry + + # ---------- the chart's words and its replay ---------- + def _caption(self, call: Call, route: str, charts: list[Chart], out: dict | None, air_out: dict | None, found: dict) -> str | None: + """What lib/report.chart_caption writes under this chart today: the period, a line per reading drawn, and what the figures + lack. A chart plot_chart draws (no caption today) is written the same way, each reading's line as its own tool's, with the + chart's period when it is cut.""" + tz = self.ctx.zone + series = (out or {}).get("series") or {} + drawn_keys = {k for r, _ in call.drawn if r.device == STATION + for k in ((("wind.wind_speed", "wind.wind_gust", "wind.wind_direction") if r.sensor == "wind" else (_engine_key(r),)))} + series = {k: v for k, v in series.items() if k in drawn_keys} + lines: list[str] = [] + if route == "air": + lines = _air_lines(air_out or {}, [r.column for r, _ in call.drawn]) + elif route == "station": + names = list(dict.fromkeys(_station_series(r) or r.column for r, _ in call.drawn)) + lines = _weather_lines(series, names, call.average, charts, tz) + else: + for r, _ in call.drawn: + if r.device == AIR_DEVICE: + line = _air_lines(air_out or {}, [r.column]) + else: + line = _weather_lines(series, [_composer_series(r) or ""], call.average, charts, tz) + lines += [x for x in line if x not in lines] + period = (out or air_out or {}).get("period", "") + more = [f"({found['notes']['chart']})"] if route == "composer" and "chart" in found["notes"] else [] + return _caption(period, lines, bool(air_out and air_out.get("note_missing")), bool(found["warning"]), more) + + def _text(self, call: Call, q: _Query | None, out: dict | None, air_out: dict | None) -> str | None: + """The figures in words, ready to send, when no chart is drawn: the period, then each station reading's low and high (or its + average) with its day and time, as the bot writes a weather_history lookup today ("extremes"); rain as the least and most in a + day (or hour, or 6 hours) and its total, as under a rain chart; each air-quality reading's peak, rating and average.""" + station = [r for r in call.readings if r.device == STATION] + ranged = [r for r in station if r.combine != "rain" and r.reading != "wind_direction"] + names = list(dict.fromkeys(name for r in ranged if (name := _station_series(r)))) + series = (out or {}).get("series") or {} + lines = [] + if names: + keys = {k for r in ranged for k in (("wind.wind_speed", "wind.wind_gust") if r.name == "wind.wind_speed" else (_engine_key(r),))} + lines += _extremes_lines({k: v for k, v in series.items() if k in keys}, names) + if (any(r.reading == "wind_direction" for r in station) and not any(r.name == "wind.wind_speed" for r in station) + and (d := series.get("wind.wind_direction"))): # (with the speed, as under a wind chart, the direction is the chart's) + lines.append(f"🧭 Mostly from the {d['most_common']}" + (f", {d['steadiness']}" if d.get("steadiness") else "")) + if q and any(r.name == "rainfall.rain" for r in station) and "rainfall.daily" in q.units: + lines += _rain_line([], q.tz, q.rain_bars) + if air_out: + lines += _air_lines(air_out, [r.column for r in call.readings if r.device == AIR_DEVICE]) + period = (out or air_out or {}).get("period", "") + return "\n".join([_period_line(period), *lines]) if lines else None + + @staticmethod + def _needs_words(fields: dict) -> bool: + """Does the result carry a note the caption leaves out (lib/bot.py _needs_words)? Then the model answers.""" + top = {k for k in fields if k != "notes" and (k.startswith("note") or k.endswith("_note") or k in ("warning", "missing"))} + notes = fields.get("notes") or {} + air = set(notes.get("air") or {}) + return bool(top - CAPTIONED or air - AIR_CAPTIONED or set(notes) - {"air", "chart"}) + + def _charts(self, call: Call, route: str | None, charts: list[Chart], meta: dict) -> dict: + """The charts as data (common.with_charts), each with drawn_by: the call that draws it again and the periods it is worth + drawing over (3.7): readings over time, 1D to 1Y (a chart of each day's average from 7D); none for a start or end with a time.""" + fields = with_charts(charts, self.ctx.zone, meta) + if not fields: + return {} + daily = call.average and route in ("station", "air") # (plot_chart draws its readings, average or not) + periods = list(DAILY_MEANS if daily else OVER_TIME) if call.replays else [] + drawn_by = {"tool": NAME, "arguments": call.arguments(), "periods": periods} + for chart in fields["charts"]: + chart["drawn_by"] = drawn_by + return fields + + +__all__ = ["DESCRIPTION", "Summary", "tools"] diff --git a/lib/sources.py b/lib/sources.py index 7600ffbe..8eae984a 100644 --- a/lib/sources.py +++ b/lib/sources.py @@ -1,21 +1,19 @@ -"""What a data source is to the bot: a name, its tools, a local clock and a Warmer that keeps it fresh; started once, poked -when a question wants it, closed at the end. The bot (bot.py) and the startup (ecobot.py) use nothing else of the four sources: -the weather station (lib/ecowitt), the air sensor (lib/airgradient), the pollen page (lib/pollen) and the forecast (lib/forecast).""" +"""What a data source is to ecobot-mcp: a name, a local clock and a Warmer that keeps it fresh; started once, closed at the end. Its +startup (ecobot_mcp/core.py) uses nothing else of the four sources: the weather station (lib/ecowitt), the air sensor (lib/airgradient), +the pollen page (lib/pollen) and the forecast (lib/forecast). The bot has none (docs/ecobot-mcp.md step 6b).""" from abc import ABC, abstractmethod from datetime import datetime, tzinfo from .timeutil import now_local -from .tools import Tool from .warm import Warmer class Source(ABC): - """Each source sets `name`, `tz`, `tools` and `warmer` (a Warmer of its own `warm`). close() closes its `client` and its + """Each source sets `name`, `tz` and `warmer` (a Warmer of its own `warm`). close() closes its `client` and its `store` on disk; the weather station, which has an API client and a history cache instead, closes its own.""" name: str tz: tzinfo - tools: list[Tool] warmer: Warmer summary: str = "" # set by start(): the line that tells what the source is reading and from where (logged by the startup, in order) @@ -28,14 +26,6 @@ async def start(self): """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.""" - @abstractmethod - def describe(self) -> str: - """The source in a line for the prompt, with the words people use for it.""" - - @abstractmethod - def wants(self, text: str) -> bool: - """Should a question start refreshing this source?""" - @abstractmethod async def warm(self, fresh: bool = True) -> str: """Fetch what questions usually need, if it is due (`fresh`: a timed refresh, not a question's); says what it did.""" @@ -43,10 +33,6 @@ async def warm(self, fresh: bool = True) -> str: def now(self) -> datetime: return now_local(self.tz) - def poke(self): - """A question that wants this source arrived: refresh it in the background (Warmer.poke).""" - self.warmer.poke() - async def close(self): await self.client.aclose() self.store.close() diff --git a/lib/specs.py b/lib/specs.py index f65a3372..4f53e9dd 100644 --- a/lib/specs.py +++ b/lib/specs.py @@ -6,11 +6,15 @@ - shares (the traffic-light share of each bar's time in good, poor and very poor). A Line is a series of points, each optionally with the low and high it stands for (drawn as a band around the line), and optionally the true records (lowest and highest reading, with when). Anything malformed raises here, when the chart is -built, not when it is drawn.""" +built, not when it is drawn. +A chart also goes as JSON (to_json, from_json; its schema is schemas/chart.json): what a tool hands over, for whoever draws it.""" + +import math from contextvars import ContextVar -from dataclasses import dataclass, field -from datetime import date, tzinfo +from dataclasses import dataclass, field, replace +from datetime import date, datetime, tzinfo +from statistics import fmean from .series import RAIN_WITH, WEATHER from .timeutil import day_bounds, day_text @@ -226,7 +230,7 @@ class Tile: """One gauge of the dashboard: a reading drawn as a thermometer, a dial or a rain beaker, with its extremes below.""" title: str unit: str - value: float | None # now; None draws the gauge empty and dimmed + value: float | None # now; None (no reading now) draws it dimmed, at its floor kind: str # "thermometer", "dial" or "beaker" low: float # the scale's ends high: float @@ -235,10 +239,151 @@ class Tile: 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 @dataclass class Dashboard: - """The gauges of the weather station, left to right and top to bottom, three to a row.""" + """The gauges of the weather station and the air sensor, left to right and top to bottom, `per_row` to a row.""" tiles: list[Tile] per_row: int = 3 + + +# ---------- a chart as JSON ---------- +# How a chart is handed over (schemas/chart.json): its title, subtitle, period, source and the time of its newest reading, then each +# panel with its series. A series is a "line" ("band" when each point carries the low and high shaded around it), rain-style "bars", +# or a "rating" (each bar's share of time in good, poor and very poor). Times are ISO local times with their UTC offset, so each gives +# its epoch back exactly, even in the hour that happens twice when the clocks go back. +CHART_VERSION = 1 +COLUMNS = {"line": 2, "band": 4, "bars": 2, "rating": 4} # a point of each kind: [time, value], [time, value, low, high], + # [time, value] and [time, good, poor, very poor] (percent) + + +def to_json(chart: Chart, tz: tzinfo, max_points: int | None = None) -> dict: + """The chart as JSON, with everything the renderer reads, so from_json gives the same chart back. Times are local to `tz`. + max_points: each line in at most that many buckets of time (for a model to read), each the mean with the bucket's lowest + and highest as its band, so the true extremes stay; None keeps the points as drawn (the bot's own charts, already within + lines.POINT_BUDGET).""" + if max_points is not None and max_points < 2: + raise ValueError("max_points: a line needs at least two points") + when = lambda t: datetime.fromtimestamp(t, tz).isoformat() + + def line(s: Line) -> dict: + s = _bucketed(s, max_points) if max_points else s + band = s.low is not None + return {"name": s.label, "kind": "band" if band else "line", + "points": [[when(t), *v] for t, *v in zip(s.x, s.y, *((s.low, s.high) if band else ()))], + "records": {k: [when(t), v] for k, (t, v) in s.records.items()}, + "reading": s.reading, "smoothed": s.smoothed, "indoor": s.indoor, "right": s.right, "on_line": s.on_line} + + def panel(p: Panel, compass: Compass | None) -> dict: + series = [line(s) for s in p.lines] + if b := p.bars: + series.append({"name": b.label, "kind": "bars", "unit": b.unit, "width": b.width, "per": b.per, "values": b.values, + "points": [[when(t), v] for t, v in zip(b.x, b.y)]}) + if r := p.shares: + series.append({"name": r.label, "kind": "rating", "width": r.width, "per": r.per, + "points": [[when(t), *v] for t, *v in zip(r.x, r.good, r.poor, r.very_poor)]}) + out = {"label": p.label, "unit": p.unit, "reading": p.reading, "series": series, "flip_right": p.flip_right, "peaks": p.peaks} + if p.zones is not None: + out["zones"] = list(p.zones) + if compass: + out["compass"] = {"rose": [list(row) for row in compass.rose], "speeds": compass.speeds, + "speed_steps": list(compass.speed_steps)} + return out + return {"version": CHART_VERSION, "title": chart.title, "subtitle": chart.subtitle, + "period": [d.isoformat() for d in chart.period] if chart.period else None, "source": chart.source, + "newest": when(chart.newest), "panels": [panel(p, chart.compass if i == 0 else None) for i, p in enumerate(chart.panels)]} + + +def _bucketed(line: Line, most: int) -> Line: + """The line in at most `most` buckets of equal time, each the mean of its points at their mean time, with the lowest low and + highest high among them as its band (the true extremes stay). A line of no more points is left as it is.""" + if len(line.x) <= most: + return line + start, width = line.x[0], (line.x[-1] - line.x[0]) // most + 1 # so the last point falls in bucket `most - 1` at the latest + buckets: dict = {} + for i, t in enumerate(line.x): + buckets.setdefault((t - start) // width, []).append(i) + if len(buckets) < 2: + return line + lows, highs, groups = line.low or line.y, line.high or line.y, list(buckets.values()) + return replace(line, x=[round(fmean(line.x[i] for i in g)) for g in groups], y=[fmean(line.y[i] for i in g) for g in groups], + low=[min(lows[i] for i in g) for g in groups], high=[max(highs[i] for i in g) for g in groups]) + + +def from_json(data: dict) -> Chart: + """The Chart to_json wrote, built the way any chart is: anything malformed raises ValueError here.""" + if not isinstance(data, dict) or data.get("version") != CHART_VERSION: + raise ValueError(f"not a chart of version {CHART_VERSION}") + try: + panels, compass, recordless = [], None, [] + for p in data["panels"]: + built = [_series(s) for s in p["series"]] + lines = [s for s in built if isinstance(s, Line)] + bars = [s for s in built if isinstance(s, Bars)] + shares = [s for s in built if isinstance(s, Shares)] + if len(bars) > 1 or len(shares) > 1: + raise ValueError(f"panel {p['label']!r}: one series of bars and one rating at most") + recordless += [s for s in lines if not s.records] + panels.append(Panel(p["label"], p["unit"], lines, bars[0] if bars else None, shares[0] if shares else None, + _pair(p["zones"]) if "zones" in p else None, p["reading"], p["flip_right"], p["peaks"])) + if "compass" in p: + compass = _compass(p["compass"]) + period = None if data["period"] is None else _pair(data["period"], date.fromisoformat) + chart = Chart(data["title"], data["subtitle"], panels, compass, period) + chart.source = source_text(data["source"]) # as written (not the CHART_SOURCE of whatever call this is) + except (KeyError, TypeError, IndexError, AttributeError) as e: + raise ValueError(f"not a chart: {type(e).__name__}: {e}") from None + for line in recordless: # drawn without records (a reading with no low, and no high given): a chart would give it its own + line.records = {} + return chart + + +def _series(s: dict) -> Line | Bars | Shares: + """One series of a panel's JSON as what draws it.""" + kind, points = s["kind"], s["points"] + if kind not in COLUMNS: + raise ValueError(f"series {s['name']!r}: its kind is one of {', '.join(COLUMNS)}, not {kind!r}") + if any(len(point) != COLUMNS[kind] for point in points): + raise ValueError(f"series {s['name']!r}: a point of a {kind} is {COLUMNS[kind]} values") + x = [_epoch(point[0]) for point in points] + columns = [[_number(point[i]) for point in points] for i in range(1, COLUMNS[kind])] + if kind == "bars": + return Bars(s["name"], s["unit"], x, columns[0], s["width"], s["per"], s["values"]) + if kind == "rating": + return Shares(s["name"], x, s["width"], *columns, s["per"]) + low, high = columns[1:] if kind == "band" else (None, None) + records = {k: (_epoch(t), _number(v)) for k, (t, v) in s["records"].items()} + return Line(s["name"], x, columns[0], low, high, s["smoothed"], records, s["reading"], s["indoor"], s["right"], s["on_line"]) + + +def _compass(c: dict) -> Compass: + if len(c["rose"]) != 16 or any(len(row) != 3 for row in c["rose"]): + raise ValueError("a wind rose is 16 compass points of 3 speed steps") + return Compass([[_number(v) for v in row] for row in c["rose"]], c["speeds"], _pair(c["speed_steps"])) + + +def _pair(values: list, read=None) -> tuple: + """Two values (zones, a period, speed steps) as a tuple, each read by `read` (else checked to be a number).""" + if len(values) != 2: + raise ValueError(f"two values, not {values!r}") + return tuple(map(read or _number, values)) + + +def _epoch(text: str) -> int | float: + """An ISO time with its UTC offset as epoch seconds (an int when whole, as the charts hold them).""" + t = datetime.fromisoformat(text) + if t.tzinfo is None: + raise ValueError(f"a time needs its UTC offset: {text!r}") + seconds = t.timestamp() + return int(seconds) if seconds.is_integer() else seconds + + +def _number(v) -> float: + """A value as given, checked to be a finite number (not a string, a bool or None).""" + if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v): + raise ValueError(f"not a number: {v!r}") + return v diff --git a/lib/status.py b/lib/status.py new file mode 100644 index 00000000..f6509218 --- /dev/null +++ b/lib/status.py @@ -0,0 +1,113 @@ +"""Status (ecobot://status, docs/ecobot-mcp.md step 6): its report in words (report: the readings now, today's forecast and the +pollen, written here from the tools' own answers, as the report always was: no model), and its picture, the weather station's temperature, humidity and rain gauges in a +row (gauge_sheet.STATUS), drawn as a PNG by lib/gauges.py, with their readings as JSON beside it: each gauge's reading now and its +highs and lows (rain: its wettest day and total) of today, the month and the year, which the picture leaves out (the web page's +dashboard, lib/web_dashboard.py, has them as tables). Laid out from the service's `current` with context, read as a call to it is (the +live reading fetched when none is held fresh: unlike the other resources, this one is read when someone asks for Status). A chat client sends the picture with the report as its caption (the Telegram bot's Status button and /status). + +Pillow is imported at the first picture (lib/gauges.py): without it the readings come alone, with `image_note` saying so, and one +warning.""" + +import asyncio +import json +import logging + +from . import gauge_sheet + +log = logging.getLogger(__name__) + +STATUS = gauge_sheet.STATUS +META = {} # as a call to current: the live reading fetched when none is held fresh (a Status asked for after a restart has one) +NO_STATION = "There is no weather station here." +NOT_ANSWERING = "The weather station isn't answering right now." +UNAVAILABLE_NOTE = "The Status picture can't be drawn on this service (no Pillow): its readings are in `gauges`." +_warned = False + + +def _figure(value, decimals: int) -> str: + return "-" if value is None else f"{value:.{decimals}f}" + + +def gauge(tile) -> dict: + """A tile as the resource's JSON: its title, reading now and unit, and its rows by name ("Daily": {"Max": 14.0, "Min": 9.5}).""" + return {"title": tile.title, "value": tile.value, "unit": tile.unit, + "rows": {row: dict(zip(tile.columns, figures)) for row, figures in tile.rows.items()}} + + +def line(tile) -> str: + """A tile in words: "Temperature: 12.3 °C (Daily: Max 14.0, Min 9.5; Monthly: ...)"; a reading not there now: "-".""" + rows = "; ".join(f"{row}: " + ", ".join(f"{column} {_figure(figure, tile.decimals)}" for column, figure in zip(tile.columns, figures)) + for row, figures in tile.rows.items() if any(f is not None for f in figures)) + return f"{tile.title}: {_figure(tile.value, tile.decimals)} {tile.unit}" + (f" ({rows})" if rows else "") + + +def _renderer(): + """lib/gauges.py, imported now if it hasn't been; None without Pillow (said once).""" + global _warned + try: + from . import gauges + except ImportError as e: + if not _warned: + _warned = True + log.warning("The Status picture was asked for but can't be drawn here (%s): install requirements-charts.txt (Pillow); " + "its readings are sent alone", e) + return None + return gauges + + +async def _answer(service, name: str, args: dict) -> dict | None: + """A tool's answer, None when it has none (no such tool, a refusal: pollen out of season, an error).""" + tool = service.get(name) + if tool is None: + return None + try: + out = json.loads(await tool.call(args, dict(META))) + except Exception as e: + log.warning("Status: %s failed (%s: %s); the report goes without it", name, type(e).__name__, e) + return None + return out if isinstance(out, dict) and "error" not in out else None + + +async def report(service) -> str: + """Status's words, written here from the service's own answers, as the report always was (no model): each device's section now + (current's headings and lines: the weather station's, the air sensor's), then today's forecast and the pollen (their `text`), those + there are, a blank line between.""" + now, forecast, pollen = await asyncio.gather(_answer(service, "current", {}), _answer(service, "forecast", {"period": "today"}), + _answer(service, "pollen", {})) + sections = [] + for device, lines in ((now or {}).get("lines") or {}).items(): + heading = ((now or {}).get("headings") or {}).get(device) + sections.append("\n".join([*([heading] if heading else []), *lines])) + sections += [out["text"] for out in (forecast, pollen) if out and out.get("text")] + return "\n\n".join(sections) + + +async def status(service) -> tuple[dict, bytes | None]: + """(the report and the gauges' readings as JSON, the PNG) of Status over the service's tools (`get(name)`, as lib.service.Service + gives them); the PNG None without the station's gauges (no station, or it isn't answering) or without Pillow.""" + words = asyncio.ensure_future(report(service)) + data, png = await _picture(service) + return {"report": await words, **data}, png + + +async def _picture(service) -> tuple[dict, bytes | None]: + tool = service.get("current") + if tool is None: + return {"gauges": [], "unavailable": NO_STATION}, None + try: + result = json.loads(await tool.call(gauge_sheet.call(STATUS), dict(META))) + except Exception as e: # (the report still goes, without its picture) + log.error("Status: the gauges failed (%s: %s); the report goes without them", type(e).__name__, e) + return {"gauges": [], "unavailable": NOT_ANSWERING}, None + sheet = gauge_sheet.sheet(result, STATUS) if isinstance(result, dict) else None + if sheet is None: + why = (result.get("error") or (result.get("unavailable") or {}).get("station")) if isinstance(result, dict) else None + return {"gauges": [], "unavailable": why or NOT_ANSWERING}, None + data = {"gauges": [gauge(t) for t in sheet.tiles], "lines": [line(t) for t in sheet.tiles]} + gauges = _renderer() + if gauges is None: + return {**data, "image_note": UNAVAILABLE_NOTE}, None + return data, await asyncio.to_thread(gauges.render, sheet) + + +__all__ = ["STATUS", "UNAVAILABLE_NOTE", "gauge", "line", "report", "status"] diff --git a/lib/storage/read.py b/lib/storage/read.py index a6b2107a..88feccf6 100644 --- a/lib/storage/read.py +++ b/lib/storage/read.py @@ -3,6 +3,8 @@ long line, picking the records; Python is left the time zones and what is drawn and said. """ +import itertools +from operator import itemgetter from dataclasses import dataclass, field from datetime import date from .catalogue import KINDS, SLOT @@ -129,16 +131,12 @@ def rows(self, kind: str, sensors: list[int], res: str, start: int, end: int, co f"AND ts BETWEEN ? AND ? AND {some_value(names)}{by_src} ORDER BY sensor, ts", (*sensors, res, start, end, *(srcs or ()))) out: dict[int, Rows] = {} - for sensor, ts, final, *values in found: - got = out.get(sensor) - if got is None: - got = out[sensor] = Rows(values={c: [] for c in names}, lo={c: [] for c in names}, hi={c: [] for c in names}) - got.ts.append(ts) - got.final.append(final) - for i, c in enumerate(names): - got.values[c].append(values[3 * i]) - got.lo[c].append(values[3 * i + 1]) - got.hi[c].append(values[3 * i + 2]) + for sensor, rows in itertools.groupby(found.fetchall(), key=itemgetter(0)): # (ordered by sensor: one run of rows each) + columns_of = list(zip(*rows)) # (rows into columns in one step: the column of each field, as tuples) + got = out[sensor] = Rows(ts=list(columns_of[1]), final=list(columns_of[2]), + values={c: list(columns_of[3 + 3 * i]) for i, c in enumerate(names)}, + lo={c: list(columns_of[4 + 3 * i]) for i, c in enumerate(names)}, + hi={c: list(columns_of[5 + 3 * i]) for i, c in enumerate(names)}) for got in out.values(): _drop_empty(got.values, got.lo, got.hi, keep=columns) return out diff --git a/lib/storage/write.py b/lib/storage/write.py index c5ec786c..8c46497d 100644 --- a/lib/storage/write.py +++ b/lib/storage/write.py @@ -216,12 +216,13 @@ def put(self, sensor: Sensor, res: str, rows: list[dict], src: int = CLOUD, fina f"VALUES ({', '.join('?' * (5 + len(keys)))})", [(sensor.id, res, row["ts"], src, int(row.get("final", final)), *map(row.get, keys)) for row in rows]) else: - names = [c.name for c in KINDS[sensor.kind]] + keys = [(c.name, c.name + "_lo", c.name + "_hi") for c in KINDS[sensor.kind]] # (named once, not for every row) args = [] for row in rows: values = [] - for c in names: - v, lo, hi = row.get(c), row.get(c + "_lo"), row.get(c + "_hi") + get = row.get + for c, c_lo, c_hi in keys: + v, lo, hi = get(c), get(c_lo), get(c_hi) if v is not None: # the value inside its band lo, hi = (None if lo is None else min(lo, v)), (None if hi is None else max(hi, v)) values += (v, lo, hi) diff --git a/lib/templates.py b/lib/templates.py index 1ecb8776..03092a58 100644 --- a/lib/templates.py +++ b/lib/templates.py @@ -1,59 +1,76 @@ -"""The buttons under the message box in private chats (a persistent reply keyboard). A button sends its label as an ordinary -message, so the answer comes through the usual path; the label stands for a plain sentence (its words without the emoji).""" +"""The buttons under the message box in private chats (a persistent reply keyboard), and the bot's own commands. A button sends its +label as an ordinary message; the bot answers it at once, without the model: each chart button is a fixed call to ecobot-mcp +(CALLS: summary of a named reading over the last day, which ecobot-mcp draws), Status is the gauges and the `report` prompt, and Help & +Alerts is ecobot-mcp's `about` and the alert settings. The label stands for a plain sentence (its words without the emoji): what the +chat's history and the log record.""" +import copy import hashlib from collections.abc import Collection -from telegram import ReplyKeyboardMarkup - CAPABILITIES = "\U0001f514 Help & Alerts" # answered with what the bot can do, then the /alerts status -IRRIGATION = "\U0001f331 Irrigation" # answered with the irrigation controller's status and buttons (only when it is configured) +IRRIGATION = "\U0001f331 Irrigation" # answered with the irrigation controller's status and buttons (only with irrigation-mcp: BOT_IRRIGATION_MCP_URL) +STATUS = "Status" # the Status button's sentence: the gauges, then the `report` prompt's answer (Bot.status) # Every button but Help & Alerts and Status is a chart of the last day (the period buttons under it change that) -ROWS = [[(CAPABILITIES, "What can you do?"), ("\U0001f4cb Status", "Report"), ("\U0001f327️ Rain", "Rain chart 1d")], +ROWS = [[(CAPABILITIES, "What can you do?"), ("\U0001f4cb Status", STATUS), ("\U0001f327️ Rain", "Rain chart 1d")], [("\U0001f326️ Weather", "Weather chart 1d"), ("\U0001f4c8 Temperature", "Temperature chart 1d"), ("\U0001f4a7 Humidity", "Humidity chart 1d")], [("\U0001f3ed Air Quality", "Air quality all metrics 1d"), ("\U0001f52c Particulates", "Particulates chart 1d"), ("\U0001f4a8 Wind", "Wind chart 1d")]] SENTENCES = dict(button for row in ROWS for button in row) -# The command menu Telegram shows beside the message box (the "/" button): command, description -MENU = [("report", "Weather, air quality and more in one message"), ("dashboard", "Gauges with today's, this month's and this year's extremes"), - ("rain", "Rain chart"), ("weather", "Every reading, a chart each"), + + +def _day_chart(*readings: str) -> tuple[str, dict]: + """summary of these readings (the service's words) over the last day, as a chart.""" + return "summary", {"readings": list(readings), "period": "1d", "chart": True} + + +# Each chart button's sentence -> the fixed call to ecobot-mcp it is (the alerts' charts are some of the same: lib/alerts/pictures.py) +CALLS = {"Rain chart 1d": _day_chart("rain"), "Weather chart 1d": _day_chart("weather"), + "Temperature chart 1d": _day_chart("temperature"), "Humidity chart 1d": _day_chart("humidity"), + "Air quality all metrics 1d": _day_chart("air"), "Particulates chart 1d": _day_chart("pm2.5", "pm10", "pm1"), + "Wind chart 1d": _day_chart("wind")} +# The same buttons as commands, named as their buttons are ("📋 Status" is /status, "🏭 Air Quality" is /air_quality) +COMMANDS = {label.split(" ", 1)[1].lower().replace(" ", "_"): question for label, question in SENTENCES.items() if label != CAPABILITIES} +# The bot's own command menu (the "/" button beside the message box): command, description. ecobot-mcp's prompts join it, a command +# each (Bot.publish_commands); none may take one of these names +MENU = [("status", "The gauges and a report"), ("rain", "Rain chart"), ("weather", "Every reading, a chart each"), ("temperature", "Temperature chart"), ("humidity", "Humidity chart"), ("air_quality", "Every air quality metric"), ("particulates", "PM1, PM2.5 and PM10 chart"), ("wind", "Wind chart"), ("alerts", "Alert settings"), ("usage", "What I can do"), ("keyboard", "Show or hide the buttons"), ("reset", "Clear this chat's memory")] -# The same questions as commands, named as their buttons are ("📋 Status" is /status, "🏭 Air Quality" is /air_quality), and /report for Status -COMMANDS = {"report": "Report", "dashboard": "Dashboard", **{label.split(" ", 1)[1].lower().replace(" ", "_"): question - for label, question in SENTENCES.items() if label != CAPABILITIES}} +OWN_COMMANDS = {"start", "help", *(name for name, _ in MENU)} # every command the bot handles itself # Telegram keeps the keyboard in each app until a message brings a new one; this changes whenever the buttons do, so a chat # whose stored value differs gets the current keyboard with its next reply. HIDDEN is what a chat that hid the buttons stores. HIDDEN = "hidden" def rows(irrigation: bool = False) -> list[list[tuple[str, str]]]: - """The button rows. With the irrigation controller configured, its button takes the place of Wind (the last one).""" + """The button rows. With irrigation-mcp (BOT_IRRIGATION_MCP_URL), its button takes the place of Wind (the last one).""" return [*ROWS[:-1], [*ROWS[-1][:-1], (IRRIGATION, "")]] if irrigation else ROWS -def chart_sentences(irrigation: bool = False) -> list[str]: - """The questions of the buttons that are charts (every one but Help & Alerts, Status and Irrigation), in keyboard order.""" - return [sentence for row in rows(irrigation) for _, sentence in row if sentence.endswith(" 1d")] - - def version(irrigation: bool = False) -> str: return hashlib.md5("|".join(label for row in rows(irrigation) for label, _ in row).encode()).hexdigest()[:8] -def keyboard(irrigation: bool = False) -> ReplyKeyboardMarkup: +def keyboard(irrigation: bool = False): + from telegram import ReplyKeyboardMarkup # (here, not at the top: ecobot-mcp's alert rules read CALLS, and know no Telegram) return ReplyKeyboardMarkup([[label for label, _ in row] for row in rows(irrigation)], resize_keyboard=True, is_persistent=True, input_field_placeholder="Ask about the weather or air…") def sentence(text: str) -> str | None: - """The question a button label stands for; None for anything else typed.""" + """The sentence a button label stands for; None for anything else typed.""" return SENTENCES.get(text.strip()) +def call(sentence: str | None) -> tuple[str, dict] | None: + """The fixed call a chart button's sentence is (a copy, so the caller may keep it); None for any other.""" + found = CALLS.get(sentence) if sentence else None + return (found[0], copy.deepcopy(found[1])) if found else None + + MEASURES = { # a source (by name) -> what it measures, as the Capabilities button lists it "Ecowitt": ["Temperature, humidity (indoor, outdoor)", "Dew point, vapour pressure deficit, pressure, wind speed", "Rain, solar radiation, UV index"], diff --git a/lib/theme.py b/lib/theme.py new file mode 100644 index 00000000..ffc5708e --- /dev/null +++ b/lib/theme.py @@ -0,0 +1,30 @@ +"""DARKMODE: whether charts are drawn dark now. Held here, apart from the renderer (lib/charts.py, Pillow), so the bot, which draws +nothing, can ask for its own theme (request `_meta` `chart_dark`) and keep its picture cache's theme without importing the renderer; +lib/charts.py reads it when it draws, and ecobot-mcp's images (lib/chart_images.py) when the call doesn't say.""" + +from datetime import UTC, datetime, tzinfo + +# "off" (light), "on" (dark), or (from, until): dark between those times of day (minutes past midnight) in ZONE +MODE: str | tuple[int, int] = "off" +ZONE: tzinfo | None = None + + +def configure(mode: str | tuple[int, int], tz: tzinfo | None = None): + """The dark-mode setting, and the time zone a time range is read in.""" + global MODE, ZONE + MODE, ZONE = mode, tz + + +def dark_now(at: datetime | None = None) -> bool: + """Are charts drawn dark now?""" + if MODE == "on": + return True + if not isinstance(MODE, tuple): + return False + start, end = MODE + local = (at or datetime.now(UTC)).astimezone(ZONE) + now = local.hour * 60 + local.minute + return start <= now < end if start < end else now >= start or now < end # a range past midnight wraps + + +__all__ = ["configure", "dark_now"] diff --git a/lib/timeutil.py b/lib/timeutil.py index cb138daa..286b77d5 100644 --- a/lib/timeutil.py +++ b/lib/timeutil.py @@ -84,11 +84,5 @@ def parse_period(args: dict, today: date, default_days: int) -> tuple[date, date return (first, last) if first <= last else "start_date must be before end_date (today isn't final, so the latest day is yesterday)" -def period_parameters(default_days: int) -> dict: - """The start_date and end_date in a tool's parameters, for a period parse_period reads.""" - return {"start_date": {"type": "string", "description": f"First day, 'YYYY-MM-DD'. Default: {default_days} days before the end."}, - "end_date": {"type": "string", "description": "Last day, 'YYYY-MM-DD' (up to yesterday). Default: yesterday."}} - - SLOT = 1800 # the 30-minute slots both devices are lined up on MIN_DAY_SLOTS = 24 # a day counts for a daily comparison with at least 12 hours of readings diff --git a/lib/tools.py b/lib/tools.py index 416cf56c..3813b03e 100644 --- a/lib/tools.py +++ b/lib/tools.py @@ -1,20 +1,15 @@ -"""The tools the model can call. Each data source contributes its own.""" +"""The tools the bot's model is offered (lib/service's ten, wrapped by lib/model_tools.py), and the Turn the engines take.""" -import asyncio import json import logging from collections.abc import Awaitable, Callable from dataclasses import dataclass, field from .logs import BUGS, QUOTES -from .specs import CHART_SOURCE, source_text log = logging.getLogger(__name__) MAX_OUTPUT_CHARS = 60000 -SOURCE_PARAMETER = {"type": "string", "description": "With a chart: where its data came from, written small under it. Name the site, " - "tool or URL (e.g. 'Ecowitt weather station', 'AirGradient sensor', 'ecowitt.net'). " - "Leave out to use the device the tool reads."} def json_result(out) -> str: @@ -24,30 +19,26 @@ def json_result(out) -> str: @dataclass class Turn: - """What one question carries between the bot and the tools it calls (nothing is shared between questions).""" - charts: list = field(default_factory=list) # chart specs the tools add; the bot renders them after the answer - chart_asked: bool = False # the person's words asked for a chart ("plot"), whatever the model sets - chart_field: str | None = None # the one reading the question is about ("humidity"); None: temperature - chart_fields: list[str] = field(default_factory=list) # readings asked to be seen together ("temperature and rain") - two_axes: bool = False # the words ask for two readings on one chart with a scale each ("on two axes") - air_extra: bool = False # the tools offer the air sensor's own temperature and humidity: the words name them, or this chat is still using them - air_extra_used: bool = False # a tool served them for this question - air_named: list[str] = field(default_factory=list) # the air readings the person's words name, else their last messages' ("co2"): a chart's default - topics: set = field(default_factory=set) # the guidance topics this question was given (intent.topics, and the chat's memory of them) - average_asked: bool = False # an average was asked for: the caption leads with it - text: str = "" # what the person said (a tool can check an argument against it) - readings: list[str] = field(default_factory=list) # the readings the words name ("temperature", "rain"): a result can leave out the others - per_day: bool = False # day by day figures were asked for: a long period keeps every day, not only its extremes - result_chars: int = 0 # the size of every tool result so far this question (what the model will be sent) - forecast_shown: list = field(default_factory=list) # the forecast days the answer includes, remembered once it is sent + """What one call carries: the options an engine is driven with (set by the service from its own arguments: lib/service/summary.py, + days.py, relate.py, scan.py) and what it gives back (its charts, its timings); for the bot's model, the request's metadata and the + results it keeps. Nothing is shared between questions.""" + charts: list = field(default_factory=list) # chart specs the engines add + chart_asked: bool = False # draw a chart (the call's `chart`) + chart_field: str | None = None # the one reading drawn; None: temperature + chart_fields: list[str] = field(default_factory=list) # the readings drawn together, a panel each + two_axes: bool = False # two readings on one panel with a scale each + air_named: list[str] = field(default_factory=list) # the air readings a chart of the air sensor draws + average_asked: bool = False # the figures and the chart as averages + readings: list[str] = field(default_factory=list) # the readings asked for: a result leaves out the others + per_day: bool = False # a long period keeps every day, not only its extremes + ahead: bool = False # nobody is waiting (a background request): its fetches wait their turn times: dict = field(default_factory=dict) # seconds spent by step ("data", "draw", "png"), for the reply's timing line in the log - ahead: bool = False # a chart drawn ahead, nobody waiting: its requests wait their turn - - @classmethod - def of(cls, read, text: str, **more) -> "Turn": - """The Turn for a question as intent.read read it (`read`): what its words ask of a chart and of the figures.""" - return cls(chart_asked=read.chart_asked, chart_field=read.chart_field, chart_fields=read.chart_fields, two_axes=read.two_axes, air_extra=read.air_extra, - average_asked=read.average_asked, readings=read.readings, per_day=read.per_day, text=text, **more) + meta: dict = field(default_factory=dict) # the request's metadata, all a service tool reads (lib/service/common.py: chart_points, + # fetch, priority); over MCP, the request's _meta + results: list = field(default_factory=list) # the bot's model: (tool, arguments, its whole result as data) of each call it made + pictures: dict = field(default_factory=dict) # ... and the charts the service drew for it, by its place in `results` + # (lib/weather.ChartImage each: the PNG, the chart's JSON, the theme) + result_chars: int = 0 # the size of every result the model was sent so far this question @dataclass @@ -55,17 +46,10 @@ class Tool: name: str description: str parameters: dict - handler: Callable[[dict, Turn], Awaitable[str]] # (arguments, the question's Turn); a Turn is optional when called directly - asked: Callable[[], tuple[str, dict]] | None = None # (description, parameters) a question that asks for the air sensor's own - # temperature or humidity is offered instead (Turn.air_extra) - source: str | None = None # the tool draws charts: where their data comes from unless the model says (specs.CHART_SOURCE); - # "" leaves it to the tool. It is then offered a `source` argument (SOURCE_PARAMETER). + handler: Callable[[dict, Turn], Awaitable[str]] # (arguments, the question's Turn) - def schema(self, turn: "Turn | None" = None) -> dict: - description, parameters = self.asked() if turn and turn.air_extra and self.asked else (self.description, self.parameters) - if self.source is not None: - parameters = {**parameters, "properties": {**parameters["properties"], "source": SOURCE_PARAMETER}} - return {"type": "function", "function": {"name": self.name, "description": description, "parameters": parameters}} + def schema(self) -> dict: + return {"type": "function", "function": {"name": self.name, "description": self.description, "parameters": self.parameters}} class Tools: @@ -73,13 +57,6 @@ def __init__(self, tools: list[Tool]): self.by_name = {t.name: t for t in tools} self.schemas = [t.schema() for t in tools] - def schemas_for(self, turn: "Turn | None") -> list[dict]: - """The tool list for this question: every tool, the same list as every other question's (so the provider's cached prompt holds), - except that a question asking for the air sensor's own temperature or humidity is offered them in the tools that can use them.""" - if turn and turn.air_extra and any(t.asked for t in self.by_name.values()): - return [t.schema(turn) for t in self.by_name.values()] - return self.schemas - async def call(self, name: str, raw_args: str, turn: Turn | None = None) -> str: """Run a tool for the model; failures come back as text the model can explain.""" tool = self.by_name.get(name) @@ -90,23 +67,16 @@ async def call(self, name: str, raw_args: str, turn: Turn | None = None) -> str: except json.JSONDecodeError as e: return f"Error: tool arguments were not valid JSON ({e})" log.debug("Tool call %s %s", name, raw_args, extra=QUOTES) - sourced = CHART_SOURCE.set(source_text(args.get("source") if isinstance(args, dict) else None) or tool.source or "") # the charts this call draws + turn = turn if turn is not None else Turn() try: # no time limit of its own: the question's (bot.TURN_SECONDS) runs from before the call - out = await tool.handler(args, turn or Turn()) + out = await tool.handler(args, turn) except Exception as e: log.error("Tool %s failed: %s: %s", name, type(e).__name__, e, exc_info=isinstance(e, BUGS)) return f"Error calling tool: {e}" - finally: - CHART_SOURCE.reset(sourced) out = out or "(no output)" if len(out) > MAX_OUTPUT_CHARS: log.warning("Tool %s output truncated: %d chars", name, len(out)) out = out[:MAX_OUTPUT_CHARS] + "\n...[truncated - request a shorter range]" log.debug("Tool result %s: %s", name, out if len(out) < 90 else f"{len(out)} chars", extra=QUOTES) - if turn: - turn.result_chars += len(out) + turn.result_chars += len(out) return out - - async def call_all(self, calls: list[tuple[str, dict]], turn: Turn | None = None) -> list[str]: - """The bot's own calls (name, arguments), made together; their results in the same order.""" - return await asyncio.gather(*(self.call(name, json.dumps(args), turn) for name, args in calls)) diff --git a/lib/topicmemory.py b/lib/topicmemory.py deleted file mode 100644 index 84fbbb34..00000000 --- a/lib/topicmemory.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Which guidance topics a chat is still on. A follow-up ("and for temperature?") often says nothing that names its topic, so a topic -stays on for a chat while either side keeps naming it or the model keeps using its tools, until RUNS runs in a row go by with none of -that. (The last messages are looked at as well: see Bot.respond.)""" - -RUNS = 2 - - -class TopicMemory: - def __init__(self): - self.idle: dict[str, int] = {} # topic -> runs since it was last named or used; a topic that has gone quiet is dropped - - def active(self) -> set[str]: - return set(self.idle) - - def update(self, offered: set[str], mentioned: set[str]) -> None: - """After a run. `offered`: the topics it was given guidance for; `mentioned`: those named by the person, named in the reply or - used by a tool.""" - for topic in mentioned: - self.idle[topic] = 0 - for topic in offered - mentioned: - if topic in self.idle: - self.idle[topic] += 1 - self.idle = {t: n for t, n in self.idle.items() if n < RUNS} diff --git a/lib/upstream.py b/lib/upstream.py new file mode 100644 index 00000000..9cb132ac --- /dev/null +++ b/lib/upstream.py @@ -0,0 +1,159 @@ +"""A client's one connection to an MCP server here, kept by one supervisor task (Upstream): the bot's to ecobot-mcp (BOT_MCP_URL, +docs/ecobot-mcp.md 3.8) and to irrigation-mcp (BOT_IRRIGATION_MCP_URL, 3.9), and irrigation-mcp's to ecobot-mcp. Each: +the protocol revision is pinned (2026-07-28, so a proxy's 502 during a restart can't land it on the older revision, which can't listen) +and discovered by hand for the instructions; when the connection fails or the listen is lost, the client is dropped and a new one built +after a backoff, which listens again (there is no replay: the caller reads what it missed). A request while it is down is refused with +an error that says so.""" + +import asyncio +import contextlib +import logging +import time + +import mcp_types as types +from mcp import Client +from mcp.shared.exceptions import MCPError + +log = logging.getLogger("lib.upstream") + +VERSION = "2026-07-28" # the protocol revision pinned: the one that can listen +READ_SECONDS = 45.0 # the HTTP read timeout: three of the server's 15-second pings, so a silently dead link is noticed +CONNECT_WAIT = 10.0 # how long a request waits for the server to be reached before it is refused +BACKOFF = (1, 2, 5, 10, 30) # seconds between attempts to reach it again, the last repeated +QUIET_SECONDS = 30.0 # how long it may be unreachable before that is a warning (a start or restart of either takes a few + # seconds); a refusal (a wrong token, Host or path) is one at once: it won't go away by itself + + +REFUSED = {401: "401: the token sent isn't one {name} accepts: give both the same AUTH_TOKENS, or leave it unset in both on one data " + "folder (the generated token)", + 403: "403: the token was refused", + 421: "421: {name} doesn't answer to this address: add its host part to {name}'s {hosts}", + 404: "404: nothing at this path: the URL ends in /mcp"} +HOSTS_SETTING = {"ecobot-mcp": "MCP_ALLOWED_HOSTS", "irrigation-mcp": "IRRIGATION_ALLOWED_HOSTS"} # (a server's, for the 421) + + +def http_transport(url: str, token: str | None = None, refused: dict | None = None): + """The Streamable HTTP transport to the server, its bearer token sent with every request, its read timeout READ_SECONDS. + refused: given, its "status" is set to an HTTP error the server answered with (the SDK reports any of them as one message).""" + import httpx2 + from mcp.client.streamable_http import streamable_http_client + from mcp.shared._httpx_utils import create_mcp_http_client + + @contextlib.asynccontextmanager + async def connect(): + headers = {"Authorization": f"Bearer {token}"} if token else None + async with create_mcp_http_client(headers=headers, timeout=httpx2.Timeout(30.0, read=READ_SECONDS)) as http: + if refused is not None: + async def note(response): + if response.status_code >= 400: + refused["status"] = response.status_code + http.event_hooks["response"].append(note) + async with streamable_http_client(url, http_client=http) as streams: + yield streams + return connect() + + +def _leaf(e: BaseException) -> BaseException: + """The first real error inside an exception group (a refused connection, a 401, a 421), not the group's "unhandled errors".""" + while isinstance(e, BaseExceptionGroup) and e.exceptions: + e = e.exceptions[0] + return e + + +class Upstream: + """The one client of a server (`name`: ecobot-mcp or irrigation-mcp, as the log and the errors call it), owned by one supervisor + task (`run`): built, discovered and listening; dropped when it fails or its listen is lost or ends, and built again after a backoff. + `target`: the server's URL, or (in tests) a Server in memory. `token`: the bearer token, or a function giving it (called for each + connection), or None.""" + + def __init__(self, target, token=None, on_event=None, on_discover=None, on_listening=None, resources=None, name="ecobot-mcp"): + """Callbacks: on_discover(DiscoverResult), each new connection's, before it is used; on_listening(), once its listen is + acknowledged (what was missed is read from here: an event from now on isn't); on_event(event), each listen event. Async. + resources: the URIs listened to, of those the server lists (None: every one).""" + self.target, self.token, self.resources, self.name = target, token, resources, name + self.on_event, self.on_discover, self.on_listening = on_event, on_discover, on_listening + self.client: Client | None = None + self.connected = asyncio.Event() + self.attempts = 0 + self.refused: dict = {} # the HTTP error the server last answered with + self.down_since: float | None = None # (monotonic) when it was last found unreachable, while it still is + self.warned = False # whether this time down has been warned about + + def _client(self) -> Client: + token = self.token() if callable(self.token) else self.token # (a function: read again for each connection) + server = http_transport(self.target, token, self.refused) if isinstance(self.target, str) else self.target + return Client(server, mode=VERSION, cache=None) + + async def run(self): + """Keep a connection, until cancelled. Each connection runs in a task of its own (_connection): the SDK's task groups (anyio) can + take a cancellation of the task they run in for their own and end with the transport's error instead, the cancellation gone + (uncancelled); this task's stays counted (cancelling()), so the supervisor stops all the same rather than connect again forever.""" + while True: + self.refused.clear() + try: + await asyncio.create_task(self._connection()) + except asyncio.CancelledError: + raise + except BaseException as e: # (a transport failure ends the whole client, as an exception group too) + if isinstance(e, (KeyboardInterrupt, SystemExit)): + raise + if (me := asyncio.current_task()) is not None and me.cancelling(): # cancelled while connecting: the SDK may have + raise asyncio.CancelledError() from e # wrapped it (an exception group): stop all the same + cause, status = _leaf(e), self.refused.get("status") + why = (REFUSED.get(status, f"HTTP {status}").format(name=self.name, hosts=HOSTS_SETTING.get(self.name, "allowed hosts")) + if status else f"{type(cause).__name__}: {cause}") + now = time.monotonic() + self.down_since = self.down_since or now + if status or now - self.down_since >= QUIET_SECONDS: + log.warning("%s at %s isn't reachable (%s)%s; trying again", self.name, self.target, why, + f" for {now - self.down_since:.0f}s" if now - self.down_since >= 1 else "") + self.warned = True + else: + log.debug("%s at %s isn't reachable yet (%s); trying again", self.name, self.target, why) + await asyncio.sleep(BACKOFF[min(self.attempts, len(BACKOFF) - 1)]) + self.attempts += 1 + + async def _connection(self): + """One connection: built, discovered and listening, until its listen ends (returns) or it fails (raises).""" + try: + async with self._client() as client: + raw = await client.session.send_discover(VERSION) + discovered = types.DiscoverResult.model_validate(raw) + client.session.adopt(discovered) + if self.on_discover: + await self.on_discover(discovered) + self.client, self.attempts = client, 0 + self.connected.set() + target = self.target if isinstance(self.target, str) else "in-process" + if self.warned: + log.info("%s: connected to %s again, after %.0fs", self.name, target, time.monotonic() - self.down_since) + else: + log.info("%s: connected to %s", self.name, target) + self.down_since, self.warned = None, False + await self._listen(client) + log.info("%s ended the listen (a restart?); connecting again", self.name) + finally: + self.client = None + self.connected.clear() + + async def _listen(self, client: Client): + """Listen to every resource the server lists (of `resources`) and its lists' changes, passing each event on, until the stream ends.""" + uris = [r.uri for r in (await client.list_resources()).resources if self.resources is None or str(r.uri) in self.resources] + async with client.listen(tools_list_changed=True, prompts_list_changed=True, resources_list_changed=True, + resource_subscriptions=uris) as sub: + if self.on_listening: + await self.on_listening() + async for event in sub: + if self.on_event: + await self.on_event(event) + + async def get(self) -> Client: + """The connected client; refused (MCPError) when the server can't be reached within CONNECT_WAIT.""" + if self.client is None: + try: + await asyncio.wait_for(self.connected.wait(), CONNECT_WAIT) + except TimeoutError: + pass + if self.client is None: + raise MCPError(types.INTERNAL_ERROR, f"{self.name} isn't reachable ({self.target}): try again shortly.") + return self.client diff --git a/lib/version.py b/lib/version.py new file mode 100644 index 00000000..faabf147 --- /dev/null +++ b/lib/version.py @@ -0,0 +1,25 @@ +"""The running code: the checked-out commit, so the log shows which code is running (the bot's and ecobot-mcp's).""" + +from .config import ROOT + + +def version() -> str: + """The checked-out commit, so the log shows which code is running.""" + return commit_in(ROOT / ".git") + + +def commit_in(git_dir) -> str: + """The short hash HEAD points at, read from the repository's files rather than by running git (which refuses a folder owned by + another user, as when the program runs as its own user). "unknown" when it cannot be read.""" + try: + head = (git_dir / "HEAD").read_text().strip() + if head.startswith("ref:"): + ref = head.split(None, 1)[1] + try: + head = (git_dir / ref).read_text().strip() + except FileNotFoundError: # after `git pack-refs` or gc the branch is a line in packed-refs + head = next(line.split()[0] for line in (git_dir / "packed-refs").read_text().splitlines() + if line.endswith(f" {ref}")) + return head[:7] if len(head) >= 7 and all(c in "0123456789abcdef" for c in head.lower()) else "unknown" + except Exception: + return "unknown" diff --git a/lib/warm.py b/lib/warm.py index d70cccbc..947aef81 100644 --- a/lib/warm.py +++ b/lib/warm.py @@ -7,7 +7,7 @@ import asyncio import logging -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Coroutine from datetime import datetime from .logs import BUGS @@ -40,32 +40,41 @@ async def every(delay: float | Callable[[], float], fn: Callable[[], Awaitable]) await asyncio.sleep(delay() if callable(delay) else delay) +class Tasks: + """The tasks run in the background (the bot's, the service's): one that stops with an error is logged as it does, and close() + cancels them.""" + + def __init__(self): + self.running: set[asyncio.Task] = set() + + def start(self, work: Coroutine) -> asyncio.Task: + task = asyncio.create_task(work, name=getattr(work, "__qualname__", None)) + self.running.add(task) + task.add_done_callback(self._ended) + return task + + def _ended(self, task: asyncio.Task): + self.running.discard(task) + if not task.cancelled() and (error := task.exception()): + log.error("%s stopped: %s: %s", task.get_name(), type(error).__name__, error, exc_info=error if isinstance(error, BUGS) else None) + + async def close(self): + for task in self.running: + task.cancel() + await asyncio.gather(*self.running, return_exceptions=True) + + class Warmer: + """A source kept warm: refreshed every `interval` seconds (refresh(True): a timed refresh), the alert checks run after each.""" + def __init__(self, refresh: Callable[[bool], Awaitable], interval: float = REFRESH_SECONDS): self.refresh, self.interval = refresh, interval self.after: list[Callable[[], Awaitable]] = [] # run after each timed refresh (alert checks) - self._task: asyncio.Task | None = None - self._lock = asyncio.Lock() # one refresh at a time: a timed one waits for a question's - - async def _refresh(self, fresh: bool): - async with self._lock: - await safely(self.refresh, fresh) - - async def stop(self): - """Cancel a refresh a question started, if one is still running (the timed ones end with their task).""" - if self._task is not None: - self._task.cancel() - await asyncio.gather(self._task, return_exceptions=True) - - def poke(self): - """A question arrived: refresh in the background, unless a refresh (a question's or a timed one) is running.""" - if not self._lock.locked() and (self._task is None or self._task.done()): - self._task = asyncio.create_task(self._refresh(False)) async def run(self): """Refresh every `interval` seconds until cancelled (startup already fetched once).""" while True: await asyncio.sleep(self.interval) - await self._refresh(True) + await safely(self.refresh, True) for check in self.after: await safely(check) diff --git a/lib/weather.py b/lib/weather.py new file mode 100644 index 00000000..c54fef85 --- /dev/null +++ b/lib/weather.py @@ -0,0 +1,463 @@ +"""ecobot-mcp's tools as the bot reaches them (docs/ecobot-mcp.md section 4, steps 5 and 6): ecobot-mcp is another program, reached over +MCP at BOT_MCP_URL (RemoteWeather: a client pinned to protocol 2026-07-28 that one supervisor task keeps connected). The bot runs no +sources of its own and never opens the readings file (step 6b). Everything the bot asks of ecobot-mcp goes through it: + + - `service`: the tools as tools/list gives them: iterated in order, `get(name)` or `service[name]`, each with its name, description, + parameters and `call(args, meta)`, which returns the tool's JSON text (lib/model_tools.py offers them to the model; the bot's + shortcuts, report, charts drawn ahead and period buttons call them); + - `names`: the sources ecobot-mcp has ("Ecowitt", "AirGradient", "Forecast", "Pollen", from ecobot://station): which alerts, report + sections and gauges there are; + - `instructions()`: the server's instructions (from + `server/discover`); `air_link()`: the AirGradient dashboard (the live-chart link under an answer about the air); + - `alerts`: the alert feed lib/alerts/notify.AlertDelivery reads (`last_id`, `identity`, `since`, `wait`), and `alert(id)` one event + (the 🔄 under an alert replays its chart's drawn_by); + - `resource(uri)`: a resource's content (ecobot://station, ecobot://forecast ...); + - `ready(wait)`: whether it can be reached (once connected, waiting up to `wait` seconds for it); + - `call_images(name, args, meta)`: a tool's answer as data (its charts the full JSON, each with its drawn_by) and its charts as + ecobot-mcp drew them (ChartImage each: the PNG, the chart's JSON, the theme), the model's calls and the bot's own; + `chart_image(name, args, meta)` the same with its first chart alone, and `picture(chart)` a chart drawn again (an alert's, by + replaying its drawn_by). Asked with request `_meta` `chart_image: "png"` (the images from the result's ImageContent, the charts' JSON + and theme from its `_meta`), in the bot's own theme (`chart_dark`: its DARKMODE, lib/theme.py, so its image cache's theme holds). The + bot draws nothing: a service that sends no image (no Pillow there) gives the answer without its pictures; + - `status()`: Status as ecobot-mcp gives it (ecobot://status): its report in words (written by ecobot-mcp, no model) and the picture + of the station's temperature, humidity and rain gauges (None without one); + - `prompts`: ecobot-mcp's prompts (name, description, argument names: `Prompt`), read on each connection and again when it says they + changed (PromptsListChanged; `on_prompts()` is called after each read), and `prompt(name, arguments)` one's question in words (the + bot offers each as a Telegram command, step 6c). + +`RemoteAlerts` reads an alert log over MCP as AlertDelivery reads one: ecobot://alerts here, and irrigation://alerts over the bot's client +of irrigation-mcp (lib/irrigation_remote.py).""" + +import asyncio +import base64 +import contextlib +import json +import logging +from typing import NamedTuple +from zoneinfo import ZoneInfo + +from . import chart_images +from .service.common import AS_DRAWN, CHART_NOTE + +log = logging.getLogger(__name__) + +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) +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) +AS_A_CALL = object() # a wait of CALL_WAIT seconds (read when called) +UNREACHABLE = "The weather service isn't reachable right now: try again in a minute." + + +class ServiceUnreachable(RuntimeError): + """The remote service can't be reached (it is down, or the connection is being made again).""" + + def __init__(self, message: str = UNREACHABLE): + super().__init__(message) + + +class ChartNotDrawn(RuntimeError): + """A chart came but couldn't be drawn (its JSON isn't a chart, or the renderer failed): not the service's refusal.""" + + +class Prompt(NamedTuple): + """One of ecobot-mcp's prompts, as prompts/list gives it.""" + name: str + description: str + arguments: tuple[str, ...] # its arguments' names, in order + + +class ChartImage(NamedTuple): + """A chart drawn.""" + png: bytes + chart: dict # its JSON (schemas/chart.json), with the drawn_by that draws it again + dark: bool # drawn in the dark theme + + +def charts_of(out) -> list[dict]: + """The charts of an answer (none for a refusal).""" + charts = out.get("charts") if isinstance(out, dict) and "error" not in out else None + return [c for c in charts if isinstance(c, dict)] if isinstance(charts, list) else [] + + +def _object(text: str) -> dict | None: + """A tool's text as the JSON object it is; None when it isn't one.""" + try: + out = json.loads(text) + except ValueError: + return None + return out if isinstance(out, dict) else None + + +async def value(x): + """x, awaited when it is awaitable: the alert feed's methods are plain in an alert log (lib/alert_log.py) and coroutines over MCP + (RemoteAlerts).""" + return await x if asyncio.iscoroutine(x) or isinstance(x, asyncio.Future) else x + + +# ---------- over MCP ---------- +def bot_dark() -> bool: + """The bot's own theme now (DARKMODE: lib/charts.dark_now), sent as chart_dark.""" + from .periods import dark_now + return dark_now() + + +class RemoteTool: + """One of the service's tools as tools/list gave it, called over MCP.""" + + def __init__(self, weather: "RemoteWeather", entry): + self.weather, self.name = weather, entry.name + self.description, self.parameters = entry.description or "", entry.input_schema + hints = entry.annotations + self.read_only = bool(getattr(hints, "read_only_hint", True)) + self.open_world = bool(getattr(hints, "open_world_hint", False)) + + async def call(self, args: dict | None = None, meta: dict | None = None) -> str: + return await self.weather.call_text(self.name, args, meta) + + +class RemoteTools: + """The service's tool list, as lib.service.Service is used: in order, by name.""" + + def __init__(self, tools=()): + self.tools = list(tools) + self.by_name = {t.name: t for t in self.tools} + + def __iter__(self): + return iter(self.tools) + + def __len__(self): + return len(self.tools) + + def __contains__(self, name) -> bool: + return name in self.by_name + + def get(self, name: str): + return self.by_name.get(name) + + def __getitem__(self, name: str): + return self.by_name[name] + + +class RemoteAlerts: + """A server's alert log read over MCP (`uri`, ecobot://alerts or irrigation://alerts, and its template with `since`), as + AlertDelivery reads an alert log. `weather`: the client it is read through (its `resource(uri, wait=None)`). A read waits for the + server while it can't be reached; `wait` returns when the listen says the alerts changed (ResourceUpdated: `changed()`) or a new + connection listens (nothing is replayed, so what was missed is read after the last id handled).""" + remote = True + + def __init__(self, weather, uri: str = ALERTS_URI): + self.weather, self.uri = weather, uri + self.identity: str | None = None + self.newest = 0 + self._changed = asyncio.Event() + + def changed(self): + self._changed.set() + + async def read(self, since: int = 0, expired: bool = False) -> dict: + """ecobot://alerts?since=… as {alerts, last_id, identity}, waiting for the service as long as it takes; a refusal (MCPError) is + raised. The connection closing under the read (MCPError too, CONNECTION_CLOSED: the service stopping) is no refusal: the read + waits for the next connection, as for any other lost one (raised, AlertDelivery would wait its RETRY_SECONDS, 30, before reading + again, holding up the alerts of a service that is back in a moment).""" + from mcp.shared.exceptions import MCPError + from mcp_types import CONNECTION_CLOSED + uri = f"{self.uri}?since={int(since)}" + ("&expired=true" if expired else "") + while True: + try: + data = await self.weather.resource(uri, wait=None) + except MCPError as e: + if e.code != CONNECTION_CLOSED: + raise + log.debug("The connection closed while the alerts were read; reading them again on the next") + await asyncio.sleep(1) + continue + except asyncio.CancelledError: + raise + except Exception as e: # (the connection lost mid-read: the supervisor builds another) + log.debug("The alerts couldn't be read (%s: %s); trying again", type(e).__name__, e) + await asyncio.sleep(1) + continue + self.identity, self.newest = data.get("identity"), int(data.get("last_id") or 0) + return data + + async def last_id(self) -> int: + await self.read(self.newest) + return self.newest + + async def since(self, after: int = 0, expired: bool = False) -> list[dict]: + self._changed.clear() # (before the read: a change while it runs wakes the next wait) + return (await self.read(after, expired))["alerts"] + + async def get(self, event_id: int) -> dict | None: + found = await self.read(max(int(event_id) - 1, 0), expired=True) + return next((a for a in found["alerts"] if a.get("id") == event_id), None) + + async def wait(self, after: int, timeout: float | None = None) -> bool: + try: + async with asyncio.timeout(timeout): + await self._changed.wait() + return True + except TimeoutError: + return False + + +PICTURE_WAIT = 8.0 # seconds an alert's picture waits for the service to draw it again, before the alert goes without it + +class RemoteWeather: + """The service at `target` (its MCP URL; in tests, a Server in memory), as the bot's interface. `run()` is the supervisor (the + lib/upstream.py's Upstream: one client, discovered by hand for the instructions, listening; on a transport error or a lost or ended listen it + is dropped and built again after a backoff, which discovers and listens again). Each new connection reads the tool list and the + station; the listen's events keep them current (ToolsListChanged, the station's ResourceUpdated) and wake the + alert delivery (the alerts'). A call while it is being reached waits up to CALL_WAIT seconds (a background one not at all) and is + then refused with ServiceUnreachable.""" + is_weather, remote = True, True + + def __init__(self, target, token=None, tz=None): + from lib.upstream import Upstream + self.target, self.fallback_tz, self.station_tz = target, tz, None + self.upstream = Upstream(target, token, on_event=self._event, on_discover=self._discovered, on_listening=self._listening, + resources=LISTENED) + self.service = RemoteTools() + self.station: dict = {} + self._instructions = "" + self.alerts = RemoteAlerts(self) + self.listening = asyncio.Event() # the first connection's listen is up, its tools and station read + self.on_zone = None # on_zone(zone): the station's time zone, called when it is first read and when it changes (ecobot.py) + self.prompts: list[Prompt] = [] + self.on_prompts = None # on_prompts(): called after the prompts are read (ecobot.py: the bot's command menu set again) + self._background: set[asyncio.Task] = set() + + def __iter__(self): # (the tools, as the service lists them now: lib/model_tools.py follows the list) + return iter(self.service) + + @property + def url(self) -> str: + return self.target if isinstance(self.target, str) else "the service" + + async def run(self): + await self.upstream.run() + + # ---------- the connection ---------- + async def _discovered(self, discovered): + self._instructions = discovered.instructions or "" + + async def _listening(self): + """A new connection listens: the tools, the station and the prompts read again, the alerts looked at (what came while it was + down is not replayed).""" + for refresh in (self._read_tools, self._read_station, self._read_prompts): + try: + await refresh() + except Exception as e: # (the connection is still good: the listen's events refresh them later) + log.warning("ecobot-mcp: couldn't read %s (%s: %s)", refresh.__name__.removeprefix("_read_"), type(e).__name__, e) + self.alerts.changed() + self.listening.set() + + async def _event(self, event): + from mcp.shared.subscriptions import PromptsListChanged, ResourceUpdated, ToolsListChanged + if isinstance(event, ToolsListChanged): + self._soon(self._read_tools) + elif isinstance(event, PromptsListChanged): + self._soon(self._read_prompts) + elif isinstance(event, ResourceUpdated): + uri = str(event.uri) + if uri == ALERTS_URI: + self.alerts.changed() + elif uri == STATION_URI: + self._soon(self._read_station) + + def _soon(self, fn): + """fn() in the background (a listen event is not held up by the reads it causes), its failure only logged.""" + async def run(): + try: + await fn() + except Exception as e: + log.debug("ecobot-mcp: %s failed (%s: %s)", getattr(fn, "__name__", fn), type(e).__name__, e) + task = asyncio.create_task(run()) + self._background.add(task) + task.add_done_callback(self._background.discard) + + async def _read_tools(self): + client = await self._client(0) + self.service = RemoteTools(RemoteTool(self, t) for t in (await client.list_tools()).tools) + + async def _read_prompts(self): + client = await self._client(0) + listed = (await client.list_prompts()).prompts + self.prompts = [Prompt(p.name, p.description or "", tuple(a.name for a in p.arguments or ())) for p in listed] + if self.on_prompts: + self.on_prompts() + + async def _read_station(self): + station = await self.resource(STATION_URI, wait=0) + self.station = station + if zone := station.get("time_zone"): + try: + read = ZoneInfo(zone) + except Exception: # (an offset only: TZ stands) + return + first_or_new, self.station_tz = str(read) != str(self.station_tz), read + if first_or_new and self.on_zone: + self.on_zone(read) + + @property + def tz(self): + """The station's time zone (ecobot://station's), TZ until it has been read.""" + return self.station_tz or self.fallback_tz + + async def _client(self, wait: float | None): + """The connected client, waiting up to `wait` seconds for one (None: as long as it takes); ServiceUnreachable after.""" + up = self.upstream + if up.client is None and wait != 0: + try: + async with asyncio.timeout(wait): + while up.client is None: + await up.connected.wait() + if up.client is None: + await asyncio.sleep(0.05) + except TimeoutError: + pass + if up.client is None: + raise ServiceUnreachable() + return up.client + + async def ready(self, wait=AS_A_CALL) -> bool: + try: + await self._client(CALL_WAIT if wait is AS_A_CALL else wait) + return True + except ServiceUnreachable: + return False + + # ---------- what the bot asks ---------- + async def call_text(self, name: str, args: dict | None = None, meta: dict | None = None) -> str: + """A tool's answer as its JSON text (the first text block: the tool's JSON, a refusal's too). A background request (nobody + waiting) doesn't wait for the service.""" + meta = dict(meta or {}) + meta.setdefault("chart_image", chart_images.NO_IMAGE) # (the JSON, even if BOT_MCP_URL asks for images: no picture wanted here) + client = await self._client(0 if meta.get("priority") == BACKGROUND else CALL_WAIT) + result = await client.call_tool(name, args or {}, meta=meta) + for block in result.content: + if getattr(block, "type", None) == "text": + return block.text + return json.dumps({"error": f"The service's {name} gave no answer."}) + + async def _with_images(self, name: str, args: dict | None, meta: dict | None): + """(the call's result, its text block, the meta it was asked with): asked with `chart_image: "png"` and, unless `meta` says, + `chart_dark` the bot's own theme now.""" + meta = {**(meta or {}), "chart_image": chart_images.IMAGE} + if chart_images.asked_dark(meta) is None: + meta["chart_dark"] = bot_dark() + client = await self._client(0 if meta.get("priority") == BACKGROUND else CALL_WAIT) + result = await client.call_tool(name, args or {}, meta=meta) + text = next((b.text for b in result.content if getattr(b, "type", None) == "text"), None) + return result, text, meta + + async def call_images(self, name: str, args: dict | None = None, meta: dict | None = None) -> tuple[dict | str, list[ChartImage]]: + """(the tool's answer as data, each of its charts as the service drew it). The answer's charts are the full JSON from the + result's _meta (the text carries only their titles), its chart_note the one without images; the answer's text as it came when it + isn't a JSON object. A service that sent no image (no Pillow there) gives none: the bot draws nothing.""" + result, text, meta = await self._with_images(name, args, meta) + if text is None: + return {"error": f"The service's {name} gave no answer."}, [] + out = _object(text) + if out is None: + return text, [] + extra = result.meta or {} + if isinstance(full := extra.get(chart_images.CHARTS_META), list): + out["charts"] = full + if "chart_note" in out: + out["chart_note"] = CHART_NOTE + charts = charts_of(out) + pngs = [base64.b64decode(b.data) for b in result.content if getattr(b, "type", None) == "image"] + if charts and len(pngs) != len(charts): + log.warning("ecobot-mcp: %s sent %d chart images for %d charts (%s); the answer goes without them", name, len(pngs), + len(charts), out.get("chart_image_note") or "no note") + return out, [] + dark = extra.get(chart_images.DARK_META) + dark = dark if isinstance(dark, bool) else meta["chart_dark"] + return out, [ChartImage(png, chart, dark) for png, chart in zip(pngs, charts)] + + async def chart_image(self, name: str, args: dict | None = None, meta: dict | None = None, + alone: bool = False) -> tuple[dict, ChartImage | None]: + """(the tool's answer as data, its first chart as the service drew it; None without a chart, or with more than one when + `alone`, or when the service sent no image).""" + out, images = await self.call_images(name, args, meta) + if not isinstance(out, dict): + return {"error": f"The service's {name} gave no answer."}, None + charts = charts_of(out) + if not charts or (alone and len(charts) != 1) or not images: + return out, None + return out, images[0] + + async def picture(self, chart: dict, dark: bool | None = None) -> ChartImage: + """A chart's JSON drawn by the service: its drawn_by replayed (as drawn: the same chart, with any newer reading). ChartNotDrawn + when it can't be (it has no drawn_by, the service draws no chart of it, sends no image, or can't be reached): the bot draws + nothing itself.""" + dark = bot_dark() if dark is None else dark + by = chart.get("drawn_by") + if not isinstance(by, dict) or not by.get("tool"): + raise ChartNotDrawn("the chart has no drawn_by for the service to draw it again") + try: + out, image = await asyncio.wait_for( # (an alert waits on this: nothing fetched for it, and not for long) + self.chart_image(by["tool"], by.get("arguments") or {}, {"chart_points": AS_DRAWN, "chart_dark": dark, "fetch": False}), + PICTURE_WAIT) + except Exception as e: # (the service away, or its answer broken) + raise ChartNotDrawn(f"{type(e).__name__}: {e}") from e + if image is None: + raise ChartNotDrawn(f"{by['tool']} drew no chart again: {out.get('error') or out.get('chart_image_note') or 'no image'}") + return image + + async def status(self) -> tuple[str, bytes | None]: + """Status as ecobot-mcp gives it (ecobot://status): (its report in words, the picture of the station's three gauges or None: no + station, or no Pillow there).""" + client = await self._client(CALL_WAIT) + read = await client.read_resource(STATUS_URI) + report, png = "", None + for content in read.contents: + if getattr(content, "blob", None) and getattr(content, "mime_type", None) == chart_images.PNG: + png = base64.b64decode(content.blob) + elif getattr(content, "text", None): + with contextlib.suppress(ValueError): + report = str(json.loads(content.text).get("report") or "") + return report, png + + async def prompt(self, name: str, arguments: dict[str, str] | None = None) -> str: + """A prompt's question in words: the text of its messages, its `arguments` filled in (the prompt's defaults for those not given). A + refusal (MCPError: no such prompt, a required argument missing) is raised.""" + client = await self._client(CALL_WAIT) + got = await client.get_prompt(name, arguments or None) + return "\n\n".join(m.content.text for m in got.messages if getattr(m.content, "type", None) == "text").strip() + + async def resource(self, uri: str, wait=AS_A_CALL) -> dict: + """A resource's content; `wait`: how long to wait for the service (CALL_WAIT; None as long as it takes).""" + client = await self._client(CALL_WAIT if wait is AS_A_CALL else wait) + read = await client.read_resource(uri) + return json.loads(read.contents[0].text) + + @property + def names(self) -> set[str]: + return set(self.station.get("sources") or {}) + + def instructions(self) -> str: + return self._instructions + + def air_link(self) -> tuple[str, str] | None: + url = self.station.get("airgradient_dashboard") + return (AIR_LINK_LABEL, url) if url else None + + async def alert(self, event_id: int) -> dict | None: + try: + return await asyncio.wait_for(self.alerts.get(event_id), CALL_WAIT) + except Exception as e: # (not reached in time, or refused: the alert's type's own chart is drawn instead) + log.debug("ecobot-mcp: alert %s couldn't be read (%s: %s)", event_id, type(e).__name__, e) + return None + + async def close(self): + for task in list(self._background): + task.cancel() + await asyncio.gather(*self._background, return_exceptions=True) + + +__all__ = ["ChartImage", "ChartNotDrawn", "Prompt", "RemoteAlerts", "RemoteWeather", "ServiceUnreachable", "UNREACHABLE", "value"] diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html new file mode 100644 index 00000000..e8f3b961 --- /dev/null +++ b/lib/web_dashboard.html @@ -0,0 +1,349 @@ +<!DOCTYPE html> +<html lang="en"> +<head> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"> +<meta name="theme-color" content="#14191D"> +<meta name="color-scheme" content="dark"> +<title>Weather Dashboard + + + + + + +
+
+
loading…
+ + + diff --git a/lib/web_dashboard.py b/lib/web_dashboard.py new file mode 100644 index 00000000..98ed1a30 --- /dev/null +++ b/lib/web_dashboard.py @@ -0,0 +1,149 @@ +"""The gauges as a live web page, served by ecobot-mcp beside /mcp (lib/mcp_server.py http_app), read-only and open to the LAN: + + - 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; + - 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; + - 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. + +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 three 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).""" + +import asyncio +import json +import logging +from pathlib import Path + +from starlette.requests import Request +from starlette.responses import HTMLResponse, JSONResponse, StreamingResponse +from starlette.routing import Route + +from . import gauge_sheet +from .airgradient.dashboard import AIR_GAUGES +from .airgradient.metrics import value_of +from .ecowitt.dashboard import GAUGES, live_value +from .gauge_look import look, tile_json + +log = logging.getLogger(__name__) + +PAGE = Path(__file__).with_name("web_dashboard.html") +HEARTBEAT_SECONDS = 25.0 # a comment on an idle stream this often +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." + + +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.""" + 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 []))) + + +def air_readings_of(row: dict | None) -> tuple | None: + """What the air gauges show now of the air sensor's latest reading (its raw row, as AirGradient keeps it): each of their readings + (the AQI is PM2.5's). None without one.""" + if not row: + return None + return tuple(value_of(row, column) for column in dict.fromkeys(g.column for g in AIR_GAUGES)) + + +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).""" + + def __init__(self, server, uris: tuple[str, ...] = ("ecobot://now/weather", "ecobot://now/air")): + self.server, self.uris = server, tuple(uris) + self._streams: set[asyncio.Queue] = set() + 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 + (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()} + if sheet is None: + out["unavailable"] = (result.get("unavailable") or {}).get("station") or NOT_ANSWERING + return out + + # ---------- 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) + 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 + + def _on_event(self, event): + """The bus's listener (sync, on the event loop): a weather or air update whose gauges' readings changed goes to every stream.""" + if getattr(event, "uri", None) not in self.uris: + return + now = self._readings() + if now is None or now == (None, None) or now == self._shown: + return + self._shown = now + for queue in list(self._streams): + if queue.qsize() < QUEUED: + queue.put_nowait("readings") + + def close(self): + """End every open stream (and answer a new one with just its retry), for the server's shutdown.""" + self.closed = True + for queue in list(self._streams): + queue.put_nowait(None) + + async def _stream(self, queue: asyncio.Queue): + try: + yield f"retry: {RETRY_MS}\n: ecobot dashboard\n\n" + while not self.closed: + try: + what = await asyncio.wait_for(queue.get(), HEARTBEAT_SECONDS) + except TimeoutError: + yield ": still here\n\n" + continue + if what is None: + break + yield f"event: {what}\ndata: {{}}\n\n" + finally: + self._streams.discard(queue) + + # ---------- the routes ---------- + async def page(self, request: Request): + return HTMLResponse(PAGE.read_text(encoding="utf-8"), headers={"Cache-Control": "no-cache"}) + + async def data_route(self, request: Request): + return JSONResponse(await self.data(), headers={"Cache-Control": "no-store"}) + + async def events(self, request: Request): + queue: asyncio.Queue = asyncio.Queue() + if self.closed: + queue.put_nowait(None) + else: + self._streams.add(queue) + return StreamingResponse(self._stream(queue), media_type="text/event-stream", + headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"}) + + def routes(self, path: str = "/dashboard") -> list[Route]: + # The page at `path/` too, not a redirect to `path`: a redirect is built from the Host the request came with, so behind a proxy + # that maps a site's root to `path/` it would send the browser to ecobot-mcp's own LAN address (the page finds its data either way) + return [Route(path, self.page, methods=["GET"]), Route(f"{path}/", self.page, methods=["GET"]), + Route(f"{path}/data", self.data_route, methods=["GET"]), + Route(f"{path}/events", self.events, methods=["GET"])] + + +__all__ = ["WebDashboard", "air_readings_of", "readings_of"] diff --git a/pytest.ini b/pytest.ini index 6aed6ce4..c38ecf35 100644 --- a/pytest.ini +++ b/pytest.ini @@ -2,6 +2,12 @@ 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 -addopts = -n auto --dist worksteal +# 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 +timeout = 60 +# a test's tmp_path is removed once it passes (a copy of the fake station's archive in each is 14 MB): kept only for a failure +tmp_path_retention_policy = failed markers = + slow: 0.5 s or more run alone (tests/slow_tests.txt): left out unless asked for, `-m slow` or `-m ""` (everything, as CI runs) golden: compares charts with the reference images in tests/charts (pinned Pillow); skipped with -m 'not golden' diff --git a/requirements-bot.txt b/requirements-bot.txt new file mode 100644 index 00000000..ef1acdc9 --- /dev/null +++ b/requirements-bot.txt @@ -0,0 +1,7 @@ +# The bot's packages (ecobot.py: the Telegram bot, a client of ecobot-mcp, docs/ecobot-mcp.md step 6b), and the Docker image ecobot's: +# Telegram, the model's client, the MCP client (pinned as ecobot-mcp's: the two sides are upgraded together) and httpx (the irrigation +# controller's client). No Pillow, no source's packages: the bot draws nothing and runs no source. +httpx +mcp==2.3.0 +openai +python-telegram-bot>=22.8 diff --git a/requirements-charts.txt b/requirements-charts.txt new file mode 100644 index 00000000..fc8b09e4 --- /dev/null +++ b/requirements-charts.txt @@ -0,0 +1,4 @@ +# The chart pictures (lib/charts.py, lib/draw.py, the gauges): ecobot-mcp (python -m ecobot_mcp) draws them, to send its charts and the +# Status picture as images (docs/ecobot-mcp.md 3.7); the bot draws nothing (step 6a). The Docker image ecobot-mcp has it, ecobot not. +# Pinned: the reference images in tests/charts are drawn with this version. +pillow==13.0.0 diff --git a/requirements-dev.txt b/requirements-dev.txt index af4bba28..93c80828 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,4 +1,6 @@ -r requirements.txt +-r requirements-charts.txt pytest pytest-asyncio +pytest-timeout pytest-xdist>=3.2 diff --git a/requirements-irrigation.txt b/requirements-irrigation.txt new file mode 100644 index 00000000..cf70a2b7 --- /dev/null +++ b/requirements-irrigation.txt @@ -0,0 +1,6 @@ +# irrigation-mcp's packages (python -m irrigation_mcp: the irrigation controller's MCP server, docs/ecobot-mcp.md 3.9), and the Docker +# image irrigation-mcp's: the MCP server and client (pinned as ecobot-mcp's: the sides are upgraded together), uvicorn, and httpx (the +# Tuya cloud's client). No Telegram, no model client, no Pillow, no source's packages. +httpx +mcp==2.3.0 +uvicorn==0.54.0 diff --git a/requirements-mcp.txt b/requirements-mcp.txt new file mode 100644 index 00000000..f83fba2f --- /dev/null +++ b/requirements-mcp.txt @@ -0,0 +1,8 @@ +# ecobot-mcp's packages (python -m ecobot_mcp: the sources, the alert rules, the MCP server), and the Docker image ecobot-mcp's, with +# Pillow (requirements-charts.txt) for its chart images and the Status picture. The bot needs none of these but the MCP client +# (requirements-bot.txt). +holidays +httpx +mcp==2.3.0 +uvicorn==0.54.0 +zeroconf diff --git a/requirements.txt b/requirements.txt index 4dcfb9bc..5123751a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,5 @@ -holidays -httpx -openai -python-telegram-bot>=22.8 -pillow==13.0.0 -zeroconf +# Everything, in one venv: ecobot-mcp (requirements-mcp.txt), the bot (requirements-bot.txt) and irrigation-mcp +# (requirements-irrigation.txt), for the systemd install, which runs them from one checkout. With requirements-charts.txt (Pillow) for ecobot-mcp's chart images and Status picture. +-r requirements-mcp.txt +-r requirements-bot.txt +-r requirements-irrigation.txt diff --git a/schemas/chart.json b/schemas/chart.json new file mode 100644 index 00000000..e15e8289 --- /dev/null +++ b/schemas/chart.json @@ -0,0 +1,154 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "ecobot://schema/chart", + "title": "Chart, version 1", + "description": "A chart as data (lib/specs.py: to_json, from_json): one or more panels on a shared time axis, top to bottom. Times are ISO local times with their UTC offset; dates are ISO dates.", + "type": "object", + "required": ["version", "title", "subtitle", "period", "source", "newest", "panels"], + "additionalProperties": false, + "properties": { + "version": {"const": 1, "description": "This schema's version: a change that would misread an older chart gets a new one."}, + "title": {"type": "string", "description": "What is drawn: the panels' names."}, + "subtitle": {"type": "string", "description": "The period, how the lines were drawn (\"30-minute readings\", \"daily averages\"), what a bar covers and whether a range is shaded."}, + "period": { + "type": ["array", "null"], + "description": "The first and last day the chart covers, or null when it doesn't say.", + "prefixItems": [{"$ref": "#/$defs/date"}, {"$ref": "#/$defs/date"}], + "items": false, + "minItems": 2 + }, + "source": {"type": "string", "description": "Where the data came from (\"Ecowitt weather station\"), written small in the corner; \"\" for none."}, + "drawn_by": {"type": "object", "description": "The call that drew this chart, to draw it again: the same tool with these arguments, `period` swapped for one of `periods` to draw it over another stretch. Absent on a chart no tool call drew.", + "required": ["tool", "arguments", "periods"], "additionalProperties": false, + "properties": { + "tool": {"type": "string", "description": "The tool's name (\"summary\")."}, + "arguments": {"type": "object", "description": "Every argument the call was given, filled in: readings fully named, the period in words."}, + "periods": {"type": "array", "description": "The periods it can be redrawn over, in order; [] when it can't be (a chart over set times).", + "items": {"type": "object", "required": ["period", "label"], "additionalProperties": false, + "properties": {"period": {"type": "string", "description": "The `period` argument to send (\"7d\")."}, + "label": {"type": "string", "description": "What to call it on a button (\"7 days\")."}}}}}}, + "newest": {"$ref": "#/$defs/time", "description": "The time of the newest reading drawn: a line's last point or the start of the last bar."}, + "panels": {"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/panel"}} + }, + "$defs": { + "date": {"type": "string", "format": "date", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"}, + "time": { + "type": "string", + "format": "date-time", + "description": "A local time with its UTC offset, e.g. 2026-10-04T03:30:00+11:00.", + "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?([+-]\\d{2}:\\d{2}|Z)$" + }, + "pair": {"type": "array", "prefixItems": [{"type": "number"}, {"type": "number"}], "items": false, "minItems": 2}, + "value_point": {"type": "array", "prefixItems": [{"$ref": "#/$defs/time"}, {"type": "number"}], "items": false, "minItems": 2}, + "four_point": { + "type": "array", + "prefixItems": [{"$ref": "#/$defs/time"}, {"type": "number"}, {"type": "number"}, {"type": "number"}], + "items": false, + "minItems": 4 + }, + "panel": { + "type": "object", + "description": "One panel: lines (each a line or a band) with rain-style bars behind them on a scale of their own, or bars alone, or a rating alone.", + "required": ["label", "unit", "reading", "series", "flip_right", "peaks"], + "additionalProperties": false, + "properties": { + "label": {"type": "string"}, + "unit": {"type": "string", "description": "The unit of the lines' axis (\"\" when each line carries its own, on two axes)."}, + "reading": {"type": "string", "description": "Which reading the panel is (\"humidity\", \"pm2_5\" ...), for its colours; \"\" for a mix."}, + "series": { + "type": "array", + "minItems": 1, + "items": {"oneOf": [{"$ref": "#/$defs/line"}, {"$ref": "#/$defs/band"}, {"$ref": "#/$defs/bars"}, {"$ref": "#/$defs/rating"}]} + }, + "flip_right": {"type": "boolean", "description": "The right-hand axis runs top to bottom (a line on it falls as its reading rises)."}, + "peaks": {"enum": ["pills", "aside", "none"], "description": "How the highs and lows are labelled: on the lines, beside them, or not at all."}, + "zones": {"$ref": "#/$defs/pair", "description": "A rated reading's limits: good up to the first, poor up to the second, very poor above."}, + "compass": {"$ref": "#/$defs/compass"} + } + }, + "line": { + "type": "object", + "description": "A line of readings: points [time, value].", + "required": ["name", "kind", "points", "records", "reading", "smoothed", "indoor", "right", "on_line"], + "additionalProperties": false, + "properties": { + "name": {"type": "string"}, + "kind": {"const": "line"}, + "points": {"type": "array", "minItems": 2, "items": {"$ref": "#/$defs/value_point"}}, + "records": { + "type": "object", + "description": "The true lowest and highest readings, with when: the labels on the line.", + "additionalProperties": false, + "properties": {"low": {"$ref": "#/$defs/value_point"}, "high": {"$ref": "#/$defs/value_point"}} + }, + "reading": {"type": "string", "description": "Which reading the line is, for its colour; \"\" for its panel's."}, + "smoothed": {"type": "boolean", "description": "The line is a light average of the readings, not the readings."}, + "indoor": {"type": "boolean", "description": "The indoor sensor's line (drawn in its reading's complementary colour)."}, + "right": {"type": "boolean", "description": "Read against the panel's right-hand axis."}, + "on_line": {"type": "boolean", "description": "Its peak is marked on the line itself, not on the top of its band."} + } + }, + "band": { + "type": "object", + "description": "A line with the range each point stands for shaded around it: points [time, value, low, high].", + "required": ["name", "kind", "points", "records", "reading", "smoothed", "indoor", "right", "on_line"], + "additionalProperties": false, + "properties": { + "name": {"type": "string"}, + "kind": {"const": "band"}, + "points": {"type": "array", "minItems": 2, "items": {"$ref": "#/$defs/four_point"}}, + "records": {"$ref": "#/$defs/line/properties/records"}, + "reading": {"$ref": "#/$defs/line/properties/reading"}, + "smoothed": {"$ref": "#/$defs/line/properties/smoothed"}, + "indoor": {"$ref": "#/$defs/line/properties/indoor"}, + "right": {"$ref": "#/$defs/line/properties/right"}, + "on_line": {"$ref": "#/$defs/line/properties/on_line"} + } + }, + "bars": { + "type": "object", + "description": "Bars (rain, or a count or figure per month or year): points [the bar's start, value].", + "required": ["name", "kind", "unit", "width", "per", "values", "points"], + "additionalProperties": false, + "properties": { + "name": {"type": "string"}, + "kind": {"const": "bars"}, + "unit": {"type": "string"}, + "width": {"type": "integer", "minimum": 1, "description": "The seconds a bar covers."}, + "per": {"type": "string", "description": "What a bar covers, in words: \"hour\", \"6 hours\", \"day\", \"month\", \"year\"; \"\" when not said."}, + "values": {"type": "boolean", "description": "Each bar's number is written above it."}, + "points": {"type": "array", "items": {"$ref": "#/$defs/value_point"}} + } + }, + "rating": { + "type": "object", + "description": "The share of each bar's time in each rating: points [the bar's start, good, poor, very poor] (percent).", + "required": ["name", "kind", "width", "per", "points"], + "additionalProperties": false, + "properties": { + "name": {"type": "string"}, + "kind": {"const": "rating"}, + "width": {"type": "integer", "minimum": 1, "description": "The seconds a bar covers."}, + "per": {"type": "string"}, + "points": {"type": "array", "items": {"$ref": "#/$defs/four_point"}} + } + }, + "compass": { + "type": "object", + "description": "A wind rose of the whole period, beside a chart of one panel of lines.", + "required": ["rose", "speeds", "speed_steps"], + "additionalProperties": false, + "properties": { + "rose": { + "type": "array", + "description": "For each of the 16 compass points, N first and clockwise: the readings in each speed step (light, middle, strong).", + "minItems": 16, + "maxItems": 16, + "items": {"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3} + }, + "speeds": {"type": "boolean", "description": "The readings carried a wind speed, so the steps mean something."}, + "speed_steps": {"$ref": "#/$defs/pair", "description": "Where the middle and strong steps begin (km/h)."} + } + } + } +} diff --git a/scripts/bench_storage.py b/scripts/bench_storage.py index a4eae441..c2554ee5 100644 --- a/scripts/bench_storage.py +++ b/scripts/bench_storage.py @@ -11,6 +11,7 @@ import asyncio import dataclasses +import json import logging import os import sqlite3 @@ -18,7 +19,6 @@ import sys import tempfile import time -from datetime import datetime, timedelta from pathlib import Path from zoneinfo import ZoneInfo @@ -27,7 +27,6 @@ from _common import parser # noqa: E402 (also puts the repo on sys.path) from lib.config import Config, data_dir, local_tz # noqa: E402 -from lib.tools import Turn # noqa: E402 FILES = ("ecobot.sqlite",) @@ -68,9 +67,9 @@ def copy(source: Path, target: Path): def settings(folder: Path) -> Config: """The bot's settings with its files in `folder`, and nothing that would reach the network (Home Assistant, the sensor itself).""" os.environ["DATA_DIR"] = str(folder) - for name in ("TELEGRAM_BOT_TOKEN", "ECOWITT_API_KEY", "ECOWITT_APP_KEY"): # (never used: nothing is asked of them) + for name in ("BOT_TELEGRAM_TOKEN", "MCP_ECOWITT_API_KEY", "MCP_ECOWITT_APP_KEY"): # (never used: nothing is asked of them) os.environ.setdefault(name, "bench") - cfg = Config.from_env() + cfg = Config.from_env(bot=False) # (ecobot-mcp's settings: the sources) location = None if cfg.storage_path.exists(): # the air sensor the bot's file holds db = sqlite3.connect(f"file:{cfg.storage_path}?mode=ro", uri=True) @@ -111,8 +110,19 @@ def count(r): return storage.read_now(count) -def period(days: float, now: datetime) -> dict: - return {"start_date": f"{now - timedelta(days=days):%Y-%m-%d %H:%M:%S}", "end_date": f"{now:%Y-%m-%d %H:%M:%S}"} +def service(**sources): + """The service's tools over these sources (lib/service), as the bot and the model call them.""" + from lib.service import Service + from lib.service.context import Context + return Service.of(Context(**sources, tz=next(iter(sources.values())).tz)) + + +def asking(tools, name: str, args: dict): + """A request: the service's `name` called with `args`, as the bot asks for its charts (as drawn).""" + return lambda: tools[name].call(args, {"chart_points": "drawn"}) + + +FOUR_YEARS = "last 4 years" async def bench(folder: Path, repeat: int, tz) -> list[tuple[str, float, int]]: @@ -131,24 +141,27 @@ async def bench(folder: Path, repeat: int, tz) -> list[tuple[str, float, int]]: eco.has_minutes = any(n for _, _, n in held) # Home Assistant's minutes, which the bot draws a chart of a few hours from print(f"Ecowitt {eco.mac}: {held[0][1] if held else 0:,} rows of readings, {held[0][2] if held else 0:,} minutes, {Archive(eco).held()} " f"(opened in {opened:.1f} s)") - now = eco.now() - history, days, link = eco.tools[1].handler, eco.tools[2].handler, eco.tools[3].handler - chart = lambda field, d, groups="outdoor": lambda: history({"groups": groups, "chart": True, "chart_field": field, **period(d, now)}, Turn()) - work = [(f"Temperature chart, {label}", chart("temperature", d)) - for label, d in (("3 hours", 0.125), ("1D", 1), ("7D", 7), ("1M", 30), ("3M", 90), ("1Y", 365))] - work += [("Rain chart, 3M", chart("rain", 90, "rainfall")), - ("History of outdoor and indoor, 7 days, no chart", lambda: history({"groups": "outdoor,indoor", **period(7, now)}, Turn())), - ("weather_days: days over 30°C, 4 years", lambda: days({"condition": "temp_max > 30", "count_only": True, - "start_date": f"{now - timedelta(days=1460):%Y-%m-%d}", - "end_date": f"{now:%Y-%m-%d}"}, Turn())), - ("weather_days: rain per month, a year", lambda: days({"stat": "sum", "of": "rain", "group_by": "month", - "start_date": f"{now - timedelta(days=365):%Y-%m-%d}", - "end_date": f"{now:%Y-%m-%d}"}, Turn())), - ("weather_link: pressure and rain, 90 days, chart", lambda: link({"driver": "pressure", "chart": True}, Turn())), + tools = service(eco=eco) + chart = lambda reading, period: asking(tools, "summary", {"readings": [reading], "period": period, "chart": True}) + work = [(f"Temperature chart, {label}", chart("outdoor.temperature", period)) + for label, period in (("3 hours", "last 3 hours"), ("1D", "1d"), ("7D", "7d"), ("1M", "1m"), ("3M", "3m"), ("1Y", "1y"))] + work += [("Rain chart, 3M", chart("rain", "3m")), + ("Summary of outdoor and indoor, 7 days, no chart", asking(tools, "summary", {"period": "7d", "chart": False})), + ("days: days over 30°C, 4 years", asking(tools, "days", {"where": [{"field": "temp_max", "op": ">", "value": 30}], + "count_only": True, "period": FOUR_YEARS})), + ("days: rain per month, a year", asking(tools, "days", {"stat": "sum", "of": "rain", "group_by": "month", "period": "1y"})), + ("relate: pressure and rain, 90 days, chart", asking(tools, "relate", {"reading": "pressure", "chart": True})), ("The alerts' last 3 hours", lambda: eco.recent(3))] for label, run in work: rows.append((label, *await measured(run, repeat, lambda: eco.api.asked))) - rows.append(("/dashboard", *await measured(eco.dashboard, repeat, lambda: eco.api.asked))) + from lib.gauge_sheet import call as gauges_call, sheet + from lib.service.context import Context + from lib.service.current import CurrentTool + current = CurrentTool(Context(eco=eco)).tool() # (the bot's gauges: current with context, laid out bot-side) + + async def dashboard(): + return sheet(json.loads(await current.call(gauges_call(), None))) + rows.append(("/dashboard", *await measured(dashboard, repeat, lambda: eco.api.asked))) await eco.close() if cfg.airgradient_location and cfg.storage_path.exists(): asked = [0] @@ -160,12 +173,11 @@ def cloud(request): # what the cache lacks is counted, and there is none of it air.tz = tz n = (await air.store.lacking())["all"] print(f"AirGradient {air.loc}: {n:,} readings") - now = datetime.now(tz).replace(tzinfo=None) - work = [(f"Air chart (PM2.5), {label}", lambda d=d: air.handle({"chart": True, "metrics": ["pm2_5"], **period(d, now)}, Turn())) - for label, d in (("1D", 1), ("7D", 7), ("1M", 30))] - work.append(("air_days: days PM2.5 over 25, 4 years", lambda: air.tools[1].handler( - {"condition": "pm2_5_max > 25", "count_only": True, "start_date": f"{now - timedelta(days=1460):%Y-%m-%d}", - "end_date": f"{now:%Y-%m-%d}"}, Turn()))) + tools = service(air=air) + work = [(f"Air chart (PM2.5), {label}", asking(tools, "summary", {"readings": ["pm2.5"], "period": period, "chart": True})) + for label, period in (("1D", "1d"), ("7D", "7d"), ("1M", "1m"))] + work.append(("days: days PM2.5 over 25, 4 years", asking(tools, "days", {"where": [{"field": "pm2_5_max", "op": ">", "value": 25}], + "count_only": True, "period": FOUR_YEARS}))) for label, run in work: rows.append((label, *await measured(run, repeat, lambda: asked[0]))) await air.close() diff --git a/scripts/conditions.py b/scripts/conditions.py index fac2ba8d..a507ad28 100644 --- a/scripts/conditions.py +++ b/scripts/conditions.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """Fetch the pollen / thunderstorm asthma page and the forecast once, the way the bot does, and print what the report would show. -Use it to check the real sites before switching POLLEN=on / FORECAST=on. +Use it to check the real sites before switching MCP_POLLEN=on / MCP_FORECAST=on. python scripts/conditions.py --lat -37.8 --lon 144.9 [--district Central] [--raw] @@ -16,7 +16,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -from lib.config import local_tz # noqa: E402 +from lib.config import env, local_tz # noqa: E402 from lib.forecast import Forecast # noqa: E402 from lib.pollen import Pollen # noqa: E402 @@ -29,7 +29,7 @@ async def main(): ap.add_argument("--raw", action="store_true") args = ap.parse_args() cfg = SimpleNamespace(tz=local_tz(), pollen_district=args.district, forecast_lat=args.lat, forecast_lon=args.lon, - place=os.getenv("PLACE", "Melbourne"), storage_path=os.path.join(tempfile.mkdtemp(), "ecobot.sqlite")) # a scratch file: the bot's is left alone + place=env("MCP_PLACE") or "Melbourne", storage_path=os.path.join(tempfile.mkdtemp(), "ecobot.sqlite")) # a scratch file: the bot's is left alone pollen = Pollen(cfg) try: diff --git a/scripts/dump_specs.py b/scripts/dump_specs.py index f4584368..993bef6f 100644 --- a/scripts/dump_specs.py +++ b/scripts/dump_specs.py @@ -1,4 +1,5 @@ -"""Draw the charts the bot would draw, from the bot's file (ecobot.sqlite), and save each chart spec (JSON) and picture (PNG). +"""Draw the charts the bot would draw, from the bot's file (ecobot.sqlite), and save each chart (the service's JSON, as drawn) and +picture (PNG). The charts are the service's tools' (lib/service: summary, relate, scan), each asked as the model or the bot asks it. Strictly offline: no API keys, no network (any request raises), and your file is never touched (it is copied to a temporary folder first). A question the file cannot answer is reported as "not cached" and skipped. @@ -8,7 +9,6 @@ """ import asyncio -import dataclasses import json import logging import sqlite3 @@ -22,12 +22,13 @@ from lib.config import data_dir # noqa: E402 from lib.airgradient import AirGradient # noqa: E402 -from lib.charts import render # noqa: E402 +from lib.charts import render_data # noqa: E402 from lib.compose import Composer # noqa: E402 from lib.config import Config # noqa: E402 from lib.ecowitt import Ecowitt # noqa: E402 from lib.storage import FILE, Storage # noqa: E402 -from lib.tools import Turn # noqa: E402 +from lib.service import Service # noqa: E402 +from lib.service.context import Context # noqa: E402 FMT = "%Y-%m-%d %H:%M:%S" @@ -41,55 +42,49 @@ async def handle_async_request(self, request): raise httpx.ConnectError("offline: dump_specs never uses the network") -def questions(now: datetime) -> list[tuple[str, str, dict, dict]]: - """(name, tool, arguments, what the person's words set on the Turn).""" - # The end of the last day the caches treat as final (a day is final an hour after it ends): a still-settling day would need the network - end = datetime.combine((now - timedelta(hours=25)).date(), datetime.min.time()) + timedelta(days=1) - timedelta(seconds=1) +def questions(now: datetime) -> list[tuple[str, str, dict]]: + """(name, service tool, arguments).""" + # The last day the caches treat as final (a day is final an hour after it ends): a still-settling day would need the network + end = (now - timedelta(hours=25)).date() - def back(days: float) -> dict: - return {"start_date": (end - timedelta(days=days) + timedelta(seconds=1)).strftime(FMT), "end_date": end.strftime(FMT)} + def back(days: int) -> dict: # the whole days to that last final day + return {"start": (end - timedelta(days=days - 1)).isoformat(), "end": end.isoformat()} - def days(n: int) -> dict: # n whole days ending on that last final day, for the tools that take dates - return {"start_date": (end.date() - timedelta(days=n - 1)).strftime("%Y-%m-%d"), "end_date": end.strftime("%Y-%m-%d")} - - eco = lambda name, tool, **a: (name, tool, a, {}) + chart = lambda name, *readings, **a: (name, "summary", {"readings": list(readings), "chart": True, **a}) return [ - eco("eco_temp_1d", "weather_history", chart=True, groups="outdoor", **back(1)), - eco("eco_temp_2d_indoor_outdoor", "weather_history", chart=True, groups="outdoor,indoor", **back(2)), - eco("eco_temp_7d", "weather_history", chart=True, groups="outdoor,indoor", **back(7)), - eco("eco_temp_30d", "weather_history", chart=True, groups="outdoor,indoor", **back(30)), - eco("eco_temp_90d", "weather_history", chart=True, groups="outdoor", **back(90)), - eco("eco_temp_400d", "weather_history", chart=True, groups="outdoor", **back(400)), - eco("eco_humidity_7d", "weather_history", chart=True, groups="outdoor", chart_field="humidity", **back(7)), - eco("eco_pressure_7d", "weather_history", chart=True, groups="pressure", chart_field="relative", **back(7)), - eco("eco_pressure_90d", "weather_history", chart=True, groups="pressure", chart_field="relative", **back(90)), - eco("eco_wind_7d_compass", "weather_history", chart=True, groups="wind", chart_field="wind_gust", **back(7)), - eco("eco_wind_90d_compass", "weather_history", chart=True, groups="wind", chart_field="wind_gust", **back(90)), - eco("eco_temp_30d_average", "weather_history", chart=True, groups="outdoor", average=True, **back(30)), - eco("eco_stack_temp_rain_14d", "weather_history", chart=True, chart_fields=["temperature", "rain"], **back(14)), - eco("eco_stack_temp_hum_pres_14d", "weather_history", chart=True, - chart_fields=["temperature", "humidity", "pressure"], **back(14)), - eco("eco_stack_wind_rain_30d", "weather_history", chart=True, chart_fields=["wind", "rain"], **back(30)), - eco("eco_link_pressure_90d", "weather_link", chart=True, driver="pressure", **days(90)), - eco("eco_link_humidity_30d", "weather_link", chart=True, driver="humidity", **days(30)), - eco("eco_link_wind_400d", "weather_link", chart=True, driver="wind", **days(400)), - ("air_pm25_1d", "air_quality", {"chart": True, "metrics": ["pm2_5"], **back(1)}, {}), - ("air_pm25_7d", "air_quality", {"chart": True, "metrics": ["pm2_5"], **back(7)}, {}), - ("air_pm25_30d", "air_quality", {"chart": True, "metrics": ["pm2_5"], **back(30)}, {}), - ("air_pm25_200d_mixed_resolution", "air_quality", {"chart": True, "metrics": ["pm2_5"], **back(200)}, {}), - ("air_pm25_400d", "air_quality", {"chart": True, "metrics": ["pm2_5"], **back(360)}, {}), - ("air_all_7d", "air_quality", {"chart": True, "metrics": ["pm2_5", "pm10", "pm1", "co2", "voc_index", "nox_index"], **back(7)}, {}), - ("air_all_90d", "air_quality", {"chart": True, "metrics": ["pm2_5", "pm10", "pm1", "co2", "voc_index", "nox_index"], **back(90)}, {}), - ("air_co2_voc_14d", "air_quality", {"chart": True, "metrics": ["co2", "voc_index"], **back(14)}, {}), - ("air_pm_group_14d", "air_quality", {"chart": True, "metrics": ["pm1", "pm2_5", "pm10"], **back(14)}, {}), - ("plot_pm25_over_rain_30d", "plot_chart", {"panels": [{"series": "pm2_5"}, {"series": "rain"}], **days(30)}, {}), - ("plot_rating_over_rain_30d", "plot_chart", - {"panels": [{"series": "pm2_5", "style": "rating"}, {"series": "rain"}], **days(30)}, {}), - ("plot_temp_pm25_humidity_60d", "plot_chart", - {"panels": [{"series": "temperature"}, {"series": "pm2_5"}, {"series": "humidity"}], **days(60)}, {}), - ("plot_wind_pm10_90d", "plot_chart", {"panels": [{"series": "wind"}, {"series": "pm10"}], **days(90)}, {}), - ("air_link_pm25_60d", "air_link", {"chart": True, **days(60)}, {}), - ("air_scan_90d", "air_scan", {"chart": True, **days(90)}, {}), + chart("eco_temp_1d", "outdoor.temperature", **back(1)), + chart("eco_temp_2d_indoor_outdoor", "temperature", **back(2)), + chart("eco_temp_7d", "temperature", **back(7)), + chart("eco_temp_30d", "temperature", **back(30)), + chart("eco_temp_90d", "outdoor.temperature", **back(90)), + chart("eco_temp_400d", "outdoor.temperature", **back(400)), + chart("eco_humidity_7d", "outdoor.humidity", **back(7)), + chart("eco_pressure_7d", "pressure", **back(7)), + chart("eco_pressure_90d", "pressure", **back(90)), + chart("eco_wind_7d_compass", "wind", **back(7)), + chart("eco_wind_90d_compass", "wind", **back(90)), + chart("eco_temp_30d_average", "outdoor.temperature", average=True, **back(30)), + chart("eco_stack_temp_rain_14d", "temperature", "rain", **back(14)), + chart("eco_stack_temp_hum_pres_14d", "temperature", "humidity", "pressure", **back(14)), + chart("eco_stack_wind_rain_30d", "wind", "rain", **back(30)), + ("eco_link_pressure_90d", "relate", {"reading": "pressure", "chart": True, **back(90)}), + ("eco_link_humidity_30d", "relate", {"reading": "humidity", "chart": True, **back(30)}), + ("eco_link_wind_400d", "relate", {"reading": "wind", "chart": True, **back(400)}), + chart("air_pm25_1d", "pm2.5", **back(1)), + chart("air_pm25_7d", "pm2.5", **back(7)), + chart("air_pm25_30d", "pm2.5", **back(30)), + chart("air_pm25_200d_mixed_resolution", "pm2.5", **back(200)), + chart("air_pm25_400d", "pm2.5", **back(360)), + chart("air_all_7d", "air", **back(7)), + chart("air_all_90d", "air", **back(90)), + chart("air_co2_voc_14d", "co2", "voc", **back(14)), + chart("air_pm_group_14d", "pm1", "pm2.5", "pm10", **back(14)), + chart("plot_pm25_over_rain_30d", "pm2.5", "rain", **back(30)), + chart("plot_rating_over_rain_30d", "pm2.5", "rain", chart_readings=["air.pm2_5:rating", "rain"], **back(30)), + chart("plot_temp_pm25_humidity_60d", "outdoor.temperature", "pm2.5", "outdoor.humidity", **back(60)), + chart("plot_wind_pm10_90d", "wind", "pm10", **back(90)), + ("air_link_pm25_60d", "relate", {"reading": "pm2.5", "chart": True, **back(60)}), + ("air_scan_90d", "scan", {"chart": True, **back(90)}), ] @@ -132,21 +127,17 @@ async def main(): if not (eco or air): storage.close() raise SystemExit(f"{folder / FILE} holds no sensors") - tools = {t.name: t for s in (eco, air) if s for t in s.tools} - if eco and air: - tools.update({t.name: t for t in Composer(eco, air).tools}) + service = Service.of(await Context.open(eco=eco, air=air, composer=Composer(eco, air) if eco and air else None, tz=tz)) now = datetime.now(tz) print(f"as of {now:%Y-%m-%d %H:%M %Z}; held: ecowitt={'yes' if eco else 'NO'} airgradient={'yes' if air else 'NO'}") - for name, tool, tool_args, _ in questions(now): - if tool not in tools: - print(f" skip {name}: no {tool} tool (a cache is missing)") + for name, tool, tool_args in questions(now): + if tool not in service: + print(f" skip {name}: no {tool} tool (a source is missing)") continue - turn = Turn(chart_asked=True, chart_fields=tool_args.get("chart_fields", []), - chart_field=tool_args.get("chart_field"), average_asked=bool(tool_args.get("average"))) before = Offline.calls try: - result = await tools[tool].handler(tool_args, turn) + result = json.loads(await service[tool].call(tool_args, {"chart_points": "drawn", "fetch": False})) except httpx.ConnectError: print(f" cache {name}: not fully cached (it would need the network)") continue @@ -154,17 +145,14 @@ async def main(): print(f" ERROR {name}: {type(e).__name__}: {e}") continue note = f" ({Offline.calls - before} request(s) refused: part of the range is not cached)" if Offline.calls > before else "" - charts = turn.charts + charts = result.pop("charts", None) or [] if not charts: - print(f" none {name}: no chart{note}") + print(f" none {name}: no chart{note}{': ' + str(result['error']) if 'error' in result else ''}") continue - (out / f"{name}.json").write_text(json.dumps([dataclasses.asdict(c) for c in charts], indent=1, default=str)) - for i, spec in enumerate(charts): - (out / f"{name}{'' if i == 0 else f'_{i + 1}'}.png").write_bytes(render(spec, tz)) - try: - (out / f"{name}.result.json").write_text(json.dumps(json.loads(result), indent=1, ensure_ascii=False)) - except (TypeError, ValueError): - pass + (out / f"{name}.json").write_text(json.dumps(charts, indent=1, ensure_ascii=False)) + for i, chart in enumerate(charts): + (out / f"{name}{'' if i == 0 else f'_{i + 1}'}.png").write_bytes(render_data(chart, tz)) + (out / f"{name}.result.json").write_text(json.dumps(result, indent=1, ensure_ascii=False)) print(f" ok {name}: {len(charts)} chart(s){note}") for source in (eco, air): if source: diff --git a/scripts/ecowitt_metrics.py b/scripts/ecowitt_metrics.py index 69261022..6c59e53f 100644 --- a/scripts/ecowitt_metrics.py +++ b/scripts/ecowitt_metrics.py @@ -14,12 +14,11 @@ """ import asyncio -import os from datetime import datetime, timedelta from _common import parser # noqa: E402 (also puts the repo on sys.path) -from lib.config import local_tz # noqa: E402 +from lib.config import env, local_tz # noqa: E402 from lib.ecowitt.api import GROUPS, EcowittAPI, EcowittError # noqa: E402 # Data groups the API's documentation (real_time and history "call_back") lists. Channels are numbered. @@ -65,9 +64,9 @@ async def main(): ap.add_argument("--groups", help="comma-separated groups to ask about, instead of the documented list") ap.add_argument("--history", action="store_true", help="also ask for the last 6 hours at 30 minutes, to list the history fields") args = ap.parse_args() - key, app = os.getenv("ECOWITT_API_KEY", "").strip(), os.getenv("ECOWITT_APP_KEY", "").strip() + key, app = env("MCP_ECOWITT_API_KEY"), env("MCP_ECOWITT_APP_KEY") # (or their old names) if not (key and app): - raise SystemExit("Set ECOWITT_API_KEY and ECOWITT_APP_KEY in the environment first (see the top of this file).") + raise SystemExit("Set MCP_ECOWITT_API_KEY and MCP_ECOWITT_APP_KEY in the environment first (see the top of this file).") if args.groups: names = [g.strip() for g in args.groups.split(",") if g.strip()] else: diff --git a/scripts/eval_prompts.py b/scripts/eval_prompts.py index 393a0a4a..8b3629dc 100644 --- a/scripts/eval_prompts.py +++ b/scripts/eval_prompts.py @@ -1,13 +1,37 @@ -"""Run the saved questions (tests/evals/cases.json). +"""Run the saved questions (tests/evals/cases.json, scored against tests/evals/service_cases.json). -Without --live: only the decisions made in code (fast path, period hints, reasoning effort, chart choices), no key needed. -With --live: also asks the real model (OPENROUTER_API_KEY, OPENROUTER_BASE_URL, OPENROUTER_MODEL in the environment) with recording stand-in -tools, and checks which tool it called and with what. Nothing is fetched. +Without --live: no key needed. The decision the bot still makes in code (the reasoning effort from the words: every typed question goes +to the model) is checked over cases.json, and every service expectation is checked against the tools it names (each one they take). - python scripts/eval_prompts.py # decisions made in code - python scripts/eval_prompts.py --live # and the model +With --live: also asks the real model (OPENROUTER_API_KEY, OPENROUTER_BASE_URL, OPENROUTER_MODEL in the environment: this script's own +names, as CI's secrets are called, not the bot's BOT_OPENROUTER_* settings) and checks +which tools it called and with what. Nothing is fetched. The bot's own request is the default: its system prompt (the persona, the +server's instructions, the date and time; lib/prompt.py), the ten tools as it offers them and its reasoning effort from the words. Each call is answered by the real tool over the +evals' frozen world (tests/evalworld.py: the fake station's archive, an AirGradient, forecast and pollen fakes, the clock at Tue 29 Sep +2026 14:05 Melbourne; the archive built once per run, about ten seconds, and each run of each case given fresh tools over its own +copy of it, so no case's calls change another's answers), wrapped as the bot wraps it, so the model sees real results, notes and +refusals and calls again until it replies (the turn ends on a complete result, as the bot's does; after 10 steps of calls the +model is made to answer). A case is scored over the whole turn: an expected call passes if any call that was not refused makes it (a +refused call later corrected passes), a forbidden tool fails in any round, refused or not, more than 8 calls fails ("ran away"), and +so does an empty reply, the Agent's fallback reply (the model's last answer was empty) or a refused call that no call to the same +tool answered in a later step corrects (one in the same step was made with it); each run's number of calls, refusals and the +reply's first 200 characters are printed. + + python scripts/eval_prompts.py # the decision made in code, and the service expectations + python scripts/eval_prompts.py --live # and the model, as the bot asks it python scripts/eval_prompts.py --live --effort low # force a reasoning level to see what it fixes python scripts/eval_prompts.py --live --repeat 5 --ids 3m-average,public-holidays # how reliable is one case? + +With --service: the ten tools alone (docs/ecobot-mcp.md 7): the model is offered only their names, descriptions and parameters, with a +neutral system line and the date, time and zone, and none of the bot's prompt; every call is answered "no data" (the +model may call again or reply, up to the Agent's 10 steps), and every call of the turn is scored (what the descriptions lead a model +to, with nothing real to react to). --instructions adds the server's instructions +(lib/service/instructions.py) after the neutral line, as a client that passes them on would. Without --live it checks the expectations +themselves. + + python scripts/eval_prompts.py --service # every case has a service expectation, each one the tools take + python scripts/eval_prompts.py --live --service # and the model, with the ten tools alone + python scripts/eval_prompts.py --live --service --instructions """ import asyncio @@ -25,7 +49,11 @@ async def main() -> int: ap.add_argument("--ids", help="comma-separated case ids") ap.add_argument("--repeat", type=int, default=1, help="ask the model this many times per case") ap.add_argument("--effort", choices=["none", "low", "medium"], help="force this reasoning effort for every case") + ap.add_argument("--service", action="store_true", help="the service's ten tools alone, with a neutral system line") + ap.add_argument("--instructions", action="store_true", help="with --service: add the server's instructions to the system line") args = ap.parse_args() + if args.instructions and not args.service: + sys.exit("--instructions goes with --service") cases = evalkit.load_cases() if args.ids: wanted = set(args.ids.split(",")) @@ -37,24 +65,27 @@ async def main() -> int: sys.exit("--live needs OPENROUTER_API_KEY (and OPENROUTER_BASE_URL, OPENROUTER_MODEL) in the environment") client = AsyncOpenAI(api_key=os.environ["OPENROUTER_API_KEY"], base_url=os.getenv("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1")) model = os.getenv("OPENROUTER_MODEL", "deepseek/deepseek-v4.1-flash-1017") - failed = 0 + expectations = evalkit.load_service_cases() + if args.service: + failed = await evalkit.run_service(cases, expectations, client, model, repeat=args.repeat, effort=args.effort, + instructions=evalkit.service_instructions() if args.instructions else None) + return 1 if failed else 0 + decided = 0 for case in cases: - problems = evalkit.deterministic(case) - line = "ok" if not problems else "FAIL" - if client and not problems: - passes = 0 - for _ in range(args.repeat): - calls, reply = await evalkit.run_live(case, client, model, args.effort) - why = evalkit.check_calls(calls, case.expect) - passes += not why - problems += [f" run: {w}" for w in why[:3]] if why else [] - line = f"{passes}/{args.repeat}" + ("" if passes == args.repeat else " FAIL") - print(f"{line:>10} {case.id} ({case.ask})") - for p in problems: - print(f" {p}") - failed += bool(problems) - print(f"\n{len(cases) - failed} of {len(cases)} cases pass") - return 1 if failed else 0 + if problems := evalkit.deterministic(case): + decided += 1 + print(f"{'FAIL':>10} {case.id} ({case.ask})") + for p in problems: + print(f" {p}") + print(f"{len(cases) - decided} of {len(cases)} cases: the decision made in code holds\n") + if not client: + failed = await evalkit.run_service(cases, expectations, repeat=args.repeat, effort=args.effort, bot=True) + return 1 if failed or decided else 0 + from tests import evalworld + async with evalworld.world() as world: # (the archive built once; each run of each case gets fresh tools over a copy of it) + failed = await evalkit.run_service(cases, expectations, client, model, repeat=args.repeat, effort=args.effort, bot=True, + world=world) + return 1 if failed or decided else 0 if __name__ == "__main__": diff --git a/scripts/migrate_env.py b/scripts/migrate_env.py new file mode 100644 index 00000000..59c1b25d --- /dev/null +++ b/scripts/migrate_env.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Rename the settings in an environment file (/etc/ecobot.env) to their new names (docs/configuration.md, "Renamed settings"): +ecobot-mcp's are MCP_..., irrigation-mcp's IRRIGATION_..., the bot's BOT_..., the shared ones unprefixed. Values, comments, blank lines and order are kept. + + sudo python3 scripts/migrate_env.py /etc/ecobot.env # show what would change (secrets masked); changes nothing + sudo python3 scripts/migrate_env.py /etc/ecobot.env --write # change it, after a backup beside it (same owner and mode) + +The old names still work (with a warning at start), so this is a tidy-up, not a must. It reads the renames from lib/config.py's text +(no import: any Python 3.9 or newer, no packages), so it works in a Docker install too. It can be run again: a renamed file is left +alone. It stops, changing nothing, where it can't tell what you meant: an old and a new name (or two old names of one setting, such as +TUYA_DEVICE_ID and BOT_TUYA_DEVICE_ID, both IRRIGATION_TUYA_DEVICE_ID's) both set to different values. + +Beyond the plain renames: + - the bot's retired token, WEATHER_MCP_TOKEN, goes into AUTH_TOKENS (the shared list, was MCP_SERVICE_TOKENS) as its first token, + the one the bot sends; dropped if it is already there; + - the old container's name, ecobot-service, in a URL or an allowed host becomes ecobot-mcp's; + - with the irrigation controller's device id set (any of its names) and no BOT_IRRIGATION_MCP_URL, that is added after the + controller's settings, as http://127.0.0.1:8766/mcp (systemd: irrigation-mcp on this machine), or http://irrigation-mcp:8766/mcp in + a Docker install's file (one whose URL or allowed host names ecobot-mcp's container, ecobot-mcp or ecobot-service): the controller + is irrigation-mcp's now, and the bot its client. +""" + +import argparse +import difflib +import os +import re +import shutil +import sys +import tempfile +from datetime import datetime +from pathlib import Path + +CONFIG = Path(__file__).resolve().parent.parent / "lib" / "config.py" +RETIRED_TOKEN, TOKENS = "WEATHER_MCP_TOKEN", "AUTH_TOKENS" +OLD_HOST, NEW_HOST = "ecobot-service", "ecobot-mcp" +IRRIGATION_URL, IRRIGATION_AT = "BOT_IRRIGATION_MCP_URL", "http://127.0.0.1:8766/mcp" # the bot's way to irrigation-mcp (systemd) +IRRIGATION_IN_DOCKER = "http://irrigation-mcp:8766/mcp" # ... and in Docker (compose's service name) +TUYA = re.compile(r"^(?:IRRIGATION_|BOT_)?TUYA_") # the controller's settings, by any of their names +DEVICE = re.compile(r"^(?:IRRIGATION_|BOT_)?TUYA_DEVICE_ID$") # ... its device id: without it there is no controller +CONTAINER = re.compile(r"(?:^|[/,\s@])(?:ecobot-mcp|ecobot-service)(?:[:/,\s]|$)") # ecobot-mcp's container named: a Docker install +SECRET = re.compile(r"TOKEN|KEY|SECRET|PASSWORD") +LINE = re.compile(r"^(\s*(?:export\s+)?)([A-Za-z_][A-Za-z0-9_]*)(\s*=\s*)(.*?)\s*$") + + +def renames(config: Path = CONFIG) -> dict[str, str]: + """{old name: new name}, from lib/config.py's _setting("NEW", ..., old="OLD") and _setting("NEW", ..., old=("OLDER", "OLDEST")) + calls.""" + text = config.read_text() + found = {} + for new, one, several in re.findall(r'_setting\(\s*"([A-Z0-9_]+)"[^\n]*?old=(?:"([A-Z0-9_]+)"|\(([^)]*)\))', text): + for old in [one] if one else re.findall(r'"([A-Z0-9_]+)"', several): + found[old] = new + if not found: + raise SystemExit(f"No renamed settings found in {config}: is this the ecobot checkout?") + return found + + +def unquoted(value: str) -> tuple[str, str]: + """(the value without its quotes, the quote it had).""" + if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"": + return value[1:-1], value[0] + return value, "" + + +def migrate(lines: list[str], names: dict[str, str]) -> tuple[list[str], list[str]]: + """(the file's lines renamed, notes on what changed). SystemExit on a conflict.""" + parsed = [LINE.match(line.rstrip("\n")) for line in lines] + values: dict[str, str] = {} + for m in parsed: + if m and not m.group(2).startswith("#"): + values[m.group(2)] = unquoted(m.group(4))[0] + conflicts = [] + for new in dict.fromkeys(names.values()): # (each setting: its name and every old one, those set all the same value) + named = [n for n in (*[old for old, to in names.items() if to == new], new) if n in values] # (the old ones first) + if len({values[n] for n in named}) > 1: + conflicts.append(" and ".join(named)) + if conflicts: + raise SystemExit("Both an old and a new name are set, to different values (keep one, then run this again): " + "; ".join(conflicts)) + notes, out, written = [], [], set() + token = values.get(RETIRED_TOKEN, "") + tokens_at = next((i for i, m in enumerate(parsed) if m and names.get(m.group(2), m.group(2)) == TOKENS), None) + for i, (line, m) in enumerate(zip(lines, parsed)): + if not m: + out.append(line) + continue + lead, key, eq, raw = m.groups() + value, quote = unquoted(raw) + end = "\n" if line.endswith("\n") else "" + if key == RETIRED_TOKEN: + if tokens_at is None: # (no list yet: this becomes it) + out.append(f"{lead}{TOKENS}{eq}{raw}{end}") + notes.append(f"{RETIRED_TOKEN} -> {TOKENS}") + else: + notes.append(f"{RETIRED_TOKEN} removed: its token is the first of {TOKENS}, the one the bot sends") + continue + new = names.get(key) + if new and (new in values or new in written): # (the new one is there already, with the same value: the old line goes) + notes.append(f"{key} removed: {new} is already set to the same value") + continue + if new: + written.add(new) + name = new or key + if new: + notes.append(f"{key} -> {new}") + if name == TOKENS and token: + listed = [t.strip() for t in value.split(",") if t.strip()] + value = ",".join([token, *[t for t in listed if t != token]]) + if listed[:1] != [token]: + notes.append(f"{TOKENS}: {RETIRED_TOKEN}'s token put first, the one the bot sends") + if OLD_HOST in value and name in ("BOT_MCP_URL", "MCP_ALLOWED_HOSTS"): + value = value.replace(OLD_HOST, NEW_HOST) + notes.append(f"{name}: {OLD_HOST} -> {NEW_HOST} (the container's new name)") + out.append(f"{lead}{name}{eq}{quote}{value}{quote}{end}") + settings = [(i, m.group(2), unquoted(m.group(4))[0]) for i, line in enumerate(out) if (m := LINE.match(line.rstrip("\n")))] + tuya = [i for i, name, value in settings if TUYA.match(name) and value] + if any(DEVICE.match(name) and value for _, name, value in settings) and IRRIGATION_URL not in values: + docker = any(CONTAINER.search(value) for _, name, value in settings if name.endswith(("_URL", "_HOSTS"))) + at = tuya[-1] + 1 + if not out[at - 1].endswith("\n"): + out[at - 1] += "\n" + url = IRRIGATION_IN_DOCKER if docker else IRRIGATION_AT + out.insert(at, f"{IRRIGATION_URL}={url}\n") + notes.append(f"{IRRIGATION_URL}={url} added: the irrigation controller is irrigation-mcp's now and the bot its client " + ( + "(Docker, as this file names ecobot-mcp's container: start the `irrigation` profile; under systemd it would be " + f"{IRRIGATION_AT})" if docker else + f"(install and start irrigation-mcp.service; in Docker make it {IRRIGATION_IN_DOCKER} and start the `irrigation` profile)")) + return out, notes + + +def masked(line: str) -> str: + m = LINE.match(line.rstrip("\n")) + if m and SECRET.search(m.group(2)) and m.group(4): + return f"{m.group(1)}{m.group(2)}{m.group(3)}****" + return line.rstrip("\n") + + +def write(path: Path, lines: list[str]) -> Path: + """The file replaced in one step, with its owner and mode; the old one kept beside it first. Returns the backup's path.""" + backup = path.with_name(f"{path.name}.bak-{datetime.now():%Y%m%d-%H%M%S}") + shutil.copy2(path, backup) + st = path.stat() + fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.") + try: + with os.fdopen(fd, "w") as f: + f.writelines(lines) + os.chmod(tmp, st.st_mode & 0o7777) + try: + os.chown(tmp, st.st_uid, st.st_gid) + except PermissionError: + pass # (not root: it is then the caller's own file) + os.replace(tmp, path) + except BaseException: + Path(tmp).unlink(missing_ok=True) + raise + return backup + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("path", type=Path, help="the environment file, e.g. /etc/ecobot.env") + ap.add_argument("--write", action="store_true", help="change the file (a backup is kept beside it); without it, only show") + args = ap.parse_args(argv) + lines = args.path.read_text().splitlines(keepends=True) + new, notes = migrate(lines, renames()) + if new == lines: + print(f"{args.path}: nothing to rename") + return 0 + for note in notes: + print(f" {note}") + print() + old_set, new_set = [masked(l) for l in lines], [masked(l) for l in new] + sys.stdout.writelines(l + "\n" for l in difflib.unified_diff(old_set, new_set, str(args.path), f"{args.path} (renamed)", lineterm="")) + if not args.write: + print("\nNothing changed. Run again with --write to change the file.") + return 0 + backup = write(args.path, new) + print(f"\nChanged {args.path}; the old file is {backup}. Restart ecobot-mcp, irrigation-mcp and the bot to use it.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/refill_airgradient.py b/scripts/refill_airgradient.py index 68aacc72..09f904ee 100644 --- a/scripts/refill_airgradient.py +++ b/scripts/refill_airgradient.py @@ -20,9 +20,9 @@ async def main(days: int, pace: float): - cfg = Config.from_env() + cfg = Config.from_env(bot=False) # (ecobot-mcp's settings: the sources) if not cfg.airgradient_cloud: - raise SystemExit("Set AIRGRADIENT_API_TOKEN and AIRGRADIENT_LOCATION_ID: the history comes from the cloud") + raise SystemExit("Set MCP_AIRGRADIENT_API_TOKEN and MCP_AIRGRADIENT_LOCATION_ID: the history comes from the cloud") air = AirGradient(cfg) try: before = await air.store.lacking() diff --git a/scripts/report_inputs.py b/scripts/report_inputs.py deleted file mode 100644 index d0a03a46..00000000 --- a/scripts/report_inputs.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python3 -"""Print exactly what the report's fast path fetches (weather_now, air_quality and, if switched on, pollen_asthma and -weather_forecast), as the raw results the bot hands over. Paste the output to whoever is writing the report layout. Needs the -bot's environment, as the other scripts do (load your env file into the shell first; this script never reads it): - - set -a; . /etc/ecobot.env; set +a - python scripts/report_inputs.py - -It makes real requests (a few) and writes nothing. -""" - -import asyncio -import json - -from _common import parser # noqa: E402 (also puts the repo on sys.path) - -from ecobot import start_sources # noqa: E402 -from lib import intent # noqa: E402 -from lib.config import Config # noqa: E402 -from lib.tools import Tools # noqa: E402 - - -async def main(): - parser(__doc__).parse_args() - cfg = Config.from_env() - sources, cfg = await start_sources(cfg) - try: - tools = Tools([t for s in sources for t in s.tools]) - names = {s.name for s in sources} - for name, args in intent.report_calls(names): - print(f"=== {name} {json.dumps(args)}") - print(await tools.call(name, json.dumps(args))) - print() - finally: - for source in sources: - await source.close() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/scripts/show_request.py b/scripts/show_request.py index 40212466..a3cc1a8a 100644 --- a/scripts/show_request.py +++ b/scripts/show_request.py @@ -1,34 +1,34 @@ """Show exactly what the bot sends to the model for a question, without calling the model. -Builds the real system prompt and tool definitions, runs the real reasoning/fast-path decisions, and -runs the real tools against the bot's file (no network, no API keys). A recording stand-in plays the -model: its first reply is a tool call you choose with --call (default: the call the model made for -"hottest day where it also rained"), its second is a short answer. Every request the bot would send -is printed in full. +Builds the real system prompt (the bot's persona, the server's instructions and the time) and the service's tools as the model is +offered them (lib/model_tools.py), reads the effort from the words, and runs the service's tools against the bot's file (no network, no +API keys: the weather station is its file alone, so a tool that needs more answers with its error). A recording stand-in plays the +model: its first reply is a tool call you choose with --call (default: the call for "hottest day where it also rained"), its second is a +short answer. Every request the bot would send is printed in full. python scripts/show_request.py "hottest day where it also rained" python scripts/show_request.py --file /path/ecobot.sqlite --call '{"name": ..., "arguments": {...}}' "..." - python scripts/show_request.py --call '{"name": "readings", "arguments": {"metric": "outdoor.humidity", "start": "2026-11-08 20:47", + python scripts/show_request.py --call '{"name": "readings", "arguments": {"reading": "outdoor.humidity", "period": "last 5 hours", "interval": "1hour"}}' "humidity each hour for the last 5 hours" # the readings tool, run on the file """ import asyncio import json import sys -from datetime import datetime, timedelta +from datetime import datetime from pathlib import Path from types import SimpleNamespace as NS from _common import parser # noqa: E402 (also puts the repo on sys.path) from lib.config import data_dir, local_tz # noqa: E402 -from lib import intent, prompt # noqa: E402 -from lib.history import History # noqa: E402 -from lib.airgradient import source as air # noqa: E402 -from lib.ecowitt import days, source as station # noqa: E402 +from lib import intent, model_tools, prompt # noqa: E402 from lib.llm import Agent # noqa: E402 +from lib.service import Service # noqa: E402 +from lib.service.context import Context # noqa: E402 +from lib.service.instructions import instructions # noqa: E402 from lib.storage import FILE, Storage # noqa: E402 -from lib.tools import Tool, Tools # noqa: E402 +from lib.tools import Turn # noqa: E402 class Recorder: @@ -48,10 +48,9 @@ async def create(self, **kwargs): return NS(choices=[NS(message=msg)], usage=None) -def default_call(today): - return {"name": "weather_days", "arguments": { - "start_date": str(today - timedelta(days=1459)), "end_date": str(today - timedelta(days=1)), - "where": [{"field": "rain", "op": ">=", "value": 1}], "sort_by": "temp_max", "order": "desc", "limit": 3}} +def default_call(): + return {"name": "days", "arguments": {"where": [{"field": "rain", "op": ">=", "value": 1}], "sort_by": "temp_max", "order": "desc", + "limit": 3}} def banner(text): @@ -75,33 +74,20 @@ async def main(): storage.close() sys.exit(f"{args.file} has no station history") - async def days_handler(a): - return await days.days_tool(storage, macs[0], tz, a) - - async def unavailable(a): - return "(not run by this script)" - - air_sensor = next(iter(storage.sensors.all(kind="air")), None) - history = await History.open(NS(storage=storage, mac=macs[0], tz=tz), - NS(store=NS(storage=storage, sensor=lambda: air_sensor), tz=tz) if air_sensor else None) - tools = Tools([Tool("weather_now", station.REALTIME_DESCRIPTION, station.REALTIME_PARAMS, unavailable), - Tool("weather_history", station.HISTORY_DESCRIPTION, station.HISTORY_PARAMS, unavailable), - Tool("weather_days", days.DESCRIPTION, days.PARAMETERS, days_handler), - Tool("air_quality", air.DESCRIPTION, air.PARAMETERS, unavailable), *history.tools]) + station = NS(name="Ecowitt", storage=storage, mac=macs[0], tz=tz, latitude=None) # (the file alone) + ctx = await Context.open(eco=station, tz=tz) + tools = model_tools.tools(Service.of(ctx)) text = args.question - r = intent.read(text, now.replace(tzinfo=None)) - system = prompt.build(now, {"Ecowitt": "Ecowitt weather station", "AirGradient": "AirGradient outdoor air-quality sensor"}, r.hints) - effort, fast = r.effort, r.fast - call = json.loads(args.call) if args.call else default_call(now.date()) + system = prompt.build(now, instructions(ctx)) + effort = intent.effort(text) + call = json.loads(args.call) if args.call else default_call() client = Recorder([call, "(the model's answer goes here)"]) messages = [{"role": "user", "content": text}] - await Agent(client, "deepseek/deepseek-v4.1-flash-1017", tools).run(messages, system, effort, first_call=([fast[:2], *r.more] if r.more else fast[:2]) if fast else None, - tool_choice=r.tool_choice) + await Agent(client, "deepseek/deepseek-v4.1-flash-1017", tools).run(messages, system, effort, turn=Turn()) banner("DECISIONS MADE IN CODE") - print(f"reasoning effort: {effort} fast path: {fast[2] if fast else 'no (the model chooses the tool)'} " - f"must call a tool first: {r.needs_data}") + print(f"reasoning effort: {effort} (every typed question goes to the model)") first = client.requests[0] banner("REQUEST 1: settings") print(json.dumps({k: v for k, v in first.items() if k not in ("messages", "tools")}, indent=2)) diff --git a/scripts/slow_tests.py b/scripts/slow_tests.py new file mode 100644 index 00000000..4e454f17 --- /dev/null +++ b/scripts/slow_tests.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +"""Measure every test (run alone, one process) and write tests/slow_tests.txt: the tests that take SLOW seconds or more, which plain +`pytest` leaves out (pytest.ini: -m "not slow"; tests/conftest.py marks them). Run it when a test gets slower or faster, then commit the file. + + python scripts/slow_tests.py # about two and a half minutes +""" + +import re +import subprocess +import sys +from collections import defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +LIST = ROOT / "tests" / "slow_tests.txt" +SLOW = 0.5 # seconds (setup, call and teardown, over every parameter of the test) +HEADER = ("# The slow tests (0.5 s or more each, run alone): plain `pytest` leaves them out (pytest.ini: -m \"not slow\"); `pytest -m slow`\n" + "# runs them alone, `pytest -m \"\"` everything (as CI does). Written by scripts/slow_tests.py from the tests' measured times.\n") + + +def main() -> int: + run = subprocess.run([sys.executable, "-m", "pytest", "-q", "-n0", "-m", "", "--durations=0", "-p", "no:cacheprovider"], cwd=ROOT, + capture_output=True, text=True) + if run.returncode != 0: + print(run.stdout[-3000:], run.stderr[-3000:], sep="\n") + print("The tests didn't all pass: tests/slow_tests.txt is left as it was.") + return 1 + took: dict[str, float] = defaultdict(float) + for m in re.finditer(r"^([0-9.]+)s (?:setup|call|teardown)\s+(\S+)", run.stdout, re.M): + took[m.group(2).split("[")[0]] += float(m.group(1)) + slow = sorted(name for name, seconds in took.items() if seconds >= SLOW) + LIST.write_text(HEADER + "".join(f"{name}\n" for name in slow)) + print(f"{len(slow)} slow tests ({sum(took[n] for n in slow):.0f} of {sum(took.values()):.0f} s) written to {LIST.relative_to(ROOT)}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/update_charts.py b/scripts/update_charts.py index a85a3adf..5dea9413 100644 --- a/scripts/update_charts.py +++ b/scripts/update_charts.py @@ -8,7 +8,7 @@ python scripts/update_charts.py wind air # just these The images are drawn from the made-up data in tests/chart_samples.py with Pillow's own font, so the result is the same on any -machine with the same Pillow version (pinned in requirements.txt).""" +machine with the same Pillow version (pinned in requirements-charts.txt).""" import sys from pathlib import Path diff --git a/tests/chart_samples.py b/tests/chart_samples.py index 7bf75a03..409c3329 100644 --- a/tests/chart_samples.py +++ b/tests/chart_samples.py @@ -8,7 +8,8 @@ import lib.airgradient # noqa: F401 (imported first: lib.panels and the air package import each other) from lib.panels import panel_for, two_axes -from lib.ecowitt.dashboard import STATUS, sheet +from lib.gauge_sheet import STATUS, sheet +from tests.fakes import gauges_result from lib.specs import Bars, Chart, Compass, Line, Panel, stack from tests.fakes import TZ @@ -132,17 +133,27 @@ def series(base: float, swing: float, dip: float = 0.0) -> dict: return live, values, today -def dashboard(): - """The station's gauges: thermometers, dials and the rain beaker.""" - return sheet(*_station()) +def _air(today: date) -> tuple[dict, dict]: + """The air sensor's latest reading and its day figures for the same evening: (latest, values). It sends no NOx index just now (its + gauge is dimmed at its floor, with its figures).""" + latest = {"pm2_5": {"value": 12.0, "unit": "µg/m³"}, "pm10": {"value": 18.0, "unit": "µg/m³"}, "pm1": {"value": 7.0, "unit": "µg/m³"}, + "co2": {"value": 520, "unit": "ppm"}, "voc_index": {"value": 112, "unit": ""}} + days = {today - timedelta(days=n): n for n in range(300)} + + def series(base: float, swing: float, whole: bool = False) -> dict: + return {d: (round if whole else lambda v: round(v, 1))(max(base + swing * math.sin(n / 7), 0)) for d, n in days.items()} + values = {"pm2_5_max": series(14, 10), "pm2_5_min": series(3, 2), "pm10_max": series(30, 20), "pm10_min": series(6, 4), + "co2_max": series(560, 80, True), "co2_min": series(420, 10, True), "voc_index_max": series(160, 60, True), + "voc_index_min": series(60, 30, True), "nox_index_max": series(12, 10, True), "nox_index_min": series(1, 0, True)} + return latest, values def status(): - """The report's picture: the temperature, humidity and rain gauges in a row.""" - return sheet(*_station(), STATUS) + """The Status picture (ecobot://status): the temperature, humidity and rain gauges in a row, no tables.""" + return sheet(gauges_result(*_station()), STATUS) SAMPLES = {"temperature": temperature, "humidity_rain": humidity_rain, "all_week": all_week, "quarter": quarter, "air": air, - "wind": wind, "counts": counts, "two_scales": two_scales, "dashboard": dashboard, "status": status} + "wind": wind, "counts": counts, "two_scales": two_scales, "status": status} SAMPLES |= {f"{name}_dark": SAMPLES[name] for name in ("temperature", "all_week", "air", "wind")} # DARKMODE's theme: a name # ending _dark is drawn dark (imagecmp.snapshot) diff --git a/tests/charts/dashboard.png b/tests/charts/dashboard.png deleted file mode 100644 index 01a5d83d..00000000 Binary files a/tests/charts/dashboard.png and /dev/null differ diff --git a/tests/charts/status.png b/tests/charts/status.png index a259eb7d..419c563c 100644 Binary files a/tests/charts/status.png and b/tests/charts/status.png differ diff --git a/tests/clocks.py b/tests/clocks.py new file mode 100644 index 00000000..80d187c4 --- /dev/null +++ b/tests/clocks.py @@ -0,0 +1,139 @@ +"""The clock in tests: pinned for one test (pin), or moved for the whole suite (ECOBOT_CLOCK). + +pin(monkeypatch, when) fixes the clock at `when` (an aware datetime) for one test, as tests/evalworld.py fixes it for the evals: every +module of lib/ is imported, then every name in a module of lib/, tests/ and scripts/ bound to datetime or date is a class whose now() and today() are `when`, +time.time() returns it, and so does the archive's epoch_now. With conftest's pinned_archive(when), the fake station's archive as it was +then: a test of something that depends on the time of day (just after midnight, the evening) runs at that time whenever it is run. + +The whole suite at another time of day: ECOBOT_CLOCK="2026-11-11 00:05" (a Melbourne wall-clock time) makes the clock start there, +and run on from it, for everything the suite and lib/ read, so a test that only fails just after midnight (or late at night, or on the +1st of a month) can be run at that time on purpose: + + ECOBOT_CLOCK="2026-11-11 00:05" python -m pytest -q + +conftest installs it before anything of lib/ is imported (install()): time.time() is moved by a fixed offset (it still ticks), and +datetime.datetime and datetime.date, in the datetime module itself, become subclasses whose now() and today() read it, so every later +`from datetime import datetime` (lib/, tests/, a default argument `clock=time.time`) gets the moved clock. The tests that fix the clock +themselves (tests/evalworld.py, tests/test_service_switch.py) still do: they rebind these classes as they would the real ones. +Without ECOBOT_CLOCK nothing is changed.""" + +import datetime as _dt +import importlib +import os +import pkgutil +import sys +import time as _time +from zoneinfo import ZoneInfo + +_REAL_TIME = _time.time +_RealDatetime, _RealDate = _dt.datetime, _dt.date +OFFSET = 0.0 +_PINNED = 0.0 +DAYTIME = _RealDatetime(2026, 11, 10, 14, 5, tzinfo=ZoneInfo("Australia/Melbourne")) # (conftest's daytime_archive) +_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +_OURS = tuple(os.path.join(_ROOT, d) + os.sep for d in ("lib", "tests", "scripts")) # (a test module too, whatever pytest names it) + + +def _now() -> float: + return _REAL_TIME() + OFFSET + + +class _DatetimeType(type): + def __instancecheck__(cls, obj): + return isinstance(obj, _RealDatetime) + + def __subclasscheck__(cls, sub): + return issubclass(sub, _RealDatetime) + + +class SweepDatetime(_RealDatetime, metaclass=_DatetimeType): + @classmethod + def now(cls, tz=None): + return _RealDatetime.fromtimestamp(_now(), tz) + + @classmethod + def today(cls): + return _RealDatetime.fromtimestamp(_now()) + + @classmethod + def utcnow(cls): + return _RealDatetime.fromtimestamp(_now(), _dt.UTC).replace(tzinfo=None) + + +class _DateType(type): + def __instancecheck__(cls, obj): + return isinstance(obj, _RealDate) + + def __subclasscheck__(cls, sub): + return issubclass(sub, _RealDate) + + +class SweepDate(_RealDate, metaclass=_DateType): + @classmethod + def today(cls): + return _RealDatetime.fromtimestamp(_now()).date() + + +def install() -> str | None: + """Move the clock to ECOBOT_CLOCK (local wall-clock time, in the process's zone, Melbourne), if it is set; the text it was set to.""" + global OFFSET + text = os.environ.get("ECOBOT_CLOCK") + if not text: + return None + _time.tzset() + start = _RealDatetime.fromisoformat(text) + if start.tzinfo is None: + start = start.astimezone() # (the process's zone: conftest sets TZ first) + OFFSET = start.timestamp() - _REAL_TIME() + _time.time = _now + _dt.datetime, _dt.date = SweepDatetime, SweepDate + return text + + +class PinnedDatetime(SweepDatetime): + """datetime whose now() and today() are the pinned time (anything else, and its instances, are the real datetime's).""" + + @classmethod + def now(cls, tz=None): + return _RealDatetime.fromtimestamp(_PINNED, tz) + + @classmethod + def today(cls): + return _RealDatetime.fromtimestamp(_PINNED) + + @classmethod + def utcnow(cls): + return _RealDatetime.fromtimestamp(_PINNED, _dt.UTC).replace(tzinfo=None) + + +class PinnedDate(SweepDate): + @classmethod + def today(cls): + return _RealDatetime.fromtimestamp(_PINNED).date() + + +def pin(patch, when: _RealDatetime): + """Fix the clock at `when` (aware) in every module of lib/ and tests/, with `patch` (a MonkeyPatch: its undo puts it all back).""" + import lib + for info in pkgutil.walk_packages(lib.__path__, "lib."): + importlib.import_module(info.name) + ts = when.timestamp() + patch.setattr(sys.modules[__name__], "_PINNED", ts) + patch.setattr(_time, "time", lambda: ts) + datetimes, dates = (_RealDatetime, SweepDatetime), (_RealDate, SweepDate) + for name, module in list(sys.modules.items()): + if module is None or module is sys.modules[__name__] or not str(getattr(module, "__file__", None) or "").startswith(_OURS): + continue + for attr, value in list(vars(module).items()): + if any(value is c for c in datetimes): + patch.setattr(module, attr, PinnedDatetime) + elif any(value is c for c in dates): + patch.setattr(module, attr, PinnedDate) + patch.setattr(sys.modules["lib.ecowitt.archive"], "epoch_now", lambda: ts) + + +def yesterday_at(hour: int, minute: int, tz) -> _RealDatetime: + """Yesterday at hour:minute in tz (aware): a fixed time of day that the fake station's archive, built at the real clock, always + holds the day of; for a test whose answer depends on the time of day alone (a tool's Context(clock=...)).""" + day = _RealDatetime.fromtimestamp(_time.time(), tz).date() - _dt.timedelta(days=1) + return _RealDatetime.combine(day, _dt.time(hour, minute), tz) diff --git a/tests/conftest.py b/tests/conftest.py index 3e5c64e0..5fe0c254 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") +from tests import clocks # noqa: E402 (ECOBOT_CLOCK: the whole suite at another time; before anything of lib/ is imported) +CLOCK = clocks.install() import pytest @@ -16,11 +18,44 @@ HEAVY = ("test_ecowitt.py", "test_scan.py", "test_startup.py", "test_airgradient.py", "test_airgradient_local.py", "test_minute_lines.py") +SLOW = {line.strip() for line in (Path(__file__).parent / "slow_tests.txt").read_text().splitlines() if line.strip() and not line.startswith("#")} + + +@pytest.hookimpl(tryfirst=True) # (before -m deselects by the marks) def pytest_collection_modifyitems(items): - """The files with the slowest tests go first, so with several workers (pytest-xdist) none is left running one of them at the end.""" + """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.""" + 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)) +@pytest.fixture(autouse=True) +def no_settings_from_outside(monkeypatch): + """Every setting's variable, by its name and its old one, unset for each test (a test sets what it reads): one set where the suite + runs (a CI secret named like an old setting, an env file loaded in the shell) changes nothing.""" + from dataclasses import fields + + from lib.config import RETIRED_TOKEN, Config, old_names + for f in fields(Config): + for name in (f.metadata.get("env"), *old_names(f)): + if name: + monkeypatch.delenv(name, raising=False) + monkeypatch.delenv(RETIRED_TOKEN, raising=False) + + +@pytest.fixture(autouse=True) +def the_log_levels_as_they_were(): + """The programs' main() (ecobot.py, ecobot_mcp) set the "ecobot" and "lib" loggers' levels from LOG_LEVEL: put back after every + test, so a test that reads the debug lines doesn't depend on which ran before it on its worker.""" + import logging + levels = {name: logging.getLogger(name).level for name in ("ecobot", "lib")} + yield + for name, level in levels.items(): + logging.getLogger(name).setLevel(level) + + @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.""" @@ -28,17 +63,69 @@ def alert_state(tmp_path): return AlertState(tmp_path / "state.json") +@pytest.fixture +async def serve(): + """ecobot-mcp in memory, the bot's client of it connected (tests/served.py): `weather = await serve(ctx, alert_log, tools=..., + sources=...)`, each closed when the test ends.""" + import contextlib + + from tests.served import ecobot_mcp + async with contextlib.AsyncExitStack() as stack: + async def start(*args, **kwargs): + return await stack.enter_async_context(ecobot_mcp(*args, **kwargs)) + yield start + + +@pytest.fixture +async def serve_irrigation(): + """irrigation-mcp in memory, the bot's client of it connected (tests/served.py): `irrigation = await serve_irrigation(folder, + device)`, each closed when the test ends.""" + import contextlib + + from tests.served import irrigation_mcp + async with contextlib.AsyncExitStack() as stack: + async def start(*args, **kwargs): + return await stack.enter_async_context(irrigation_mcp(*args, **kwargs)) + yield start + + @pytest.fixture(scope="session") def archived_cache(tmp_path_factory): """The bot's file (ecobot.sqlite) holding the fake station's whole archive, built once an hour and shared by every worker and run (under pytest's own temp folder, named for the hour and the code that shapes it). Tests copy it (archived_station).""" - import asyncio - import fcntl - import hashlib from datetime import datetime - from unittest import mock + moved = "-moved" if CLOCK else "" # (built at a clock ECOBOT_CLOCK moved: never shared with a run at the real one) + return _shared_archive(tmp_path_factory, f"{datetime.now():%Y%m%d%H}{moved}", None) + - from lib.ecowitt import Archive, Ecowitt, api, archive +@pytest.fixture(scope="session") +def pinned_archive(tmp_path_factory): + """pinned_archive(when) -> the file holding the fake station's whole archive as it was at `when` (an aware datetime), built with + the clock pinned there (tests/clocks.pin) once for the code that shapes it, and shared by every worker and run after. A test pins + the clock at the same time (clocks.pin) and copies it (archived_station): the station at a fixed time of day, whatever the time.""" + return lambda when: _shared_archive(tmp_path_factory, f"pinned-{when.timestamp():.0f}", when) + + +@pytest.fixture(scope="session") +def shared_archive(tmp_path_factory): + """shared_archive(name, make, shaped_by) -> the file make(folder, patch) builds, built once for every worker and run (shared_file): + a module's own archive (at its own fixed clock), which its tests copy.""" + return lambda name, make, shaped_by=(): shared_file(tmp_path_factory, name, make, shaped_by) + + +@pytest.fixture +def daytime_archive(pinned_archive, monkeypatch): + """The fake station's archive at a fixed time, 2:05pm on Tue 10 Nov 2026 (clocks.DAYTIME), the clock pinned there for the test: for + a test whose answer depends on the date or the time of day (a year so far with days in it, this morning over).""" + cache = pinned_archive(clocks.DAYTIME) + clocks.pin(monkeypatch, clocks.DAYTIME) + return cache + + +def _shared_archive(tmp_path_factory, name: str, pinned) -> Path: + """The fake station's whole archive in a file under pytest's own temp folder, named for `name` and the code that shapes it: built by + the first worker that asks (the others wait and find it), at the clock as it is, or pinned at `pinned`.""" + from lib.ecowitt import Archive, Ecowitt from tests.fakes import config, ecowitt_transport async def build(path): @@ -48,24 +135,51 @@ async def build(path): await Archive(eco).run_once() await eco.close() return config(path).storage_path + + def make(folder, patch): + if pinned is not None: + clocks.pin(patch, pinned) + return _run(build(folder)) + return shared_file(tmp_path_factory, name, make) + + +def shared_file(tmp_path_factory, name: str, make, shaped_by=()) -> Path: + """A file built once by make(folder, patch) -> its path (in that empty folder, with a MonkeyPatch undone after it, the archive's + pacing off), kept under pytest's own temp folder named for `name` and the code that shapes it (lib/storage, lib/ecowitt, + tests/fakes.py and `shaped_by`, the files of the test that builds it): built by the first worker that asks, the others wait and find + it, and later runs too. A test copies it, so none sees another's writes.""" + import fcntl + import hashlib + + from lib.ecowitt import api, archive root = Path(__file__).resolve().parent.parent - shaped_by = sorted([*root.glob("lib/storage/*.py"), *root.glob("lib/ecowitt/*.py"), root / "tests" / "fakes.py"]) - digest = hashlib.sha1(b"".join(f.read_bytes() for f in shaped_by)).hexdigest()[:12] + files = sorted({*root.glob("lib/storage/*.py"), *root.glob("lib/ecowitt/*.py"), root / "tests" / "fakes.py", + root / "tests" / "clocks.py", *map(Path, shaped_by)}) + digest = hashlib.sha1(b"".join(f.read_bytes() for f in files)).hexdigest()[:12] base = tmp_path_factory.getbasetemp() # this run's folder under pytest-of- (a worker's is a folder under that) while not base.parent.name.startswith("pytest-of-"): base = base.parent - shared = base.parent / f"ecobot-archive-{datetime.now():%Y%m%d%H}-{digest}.sqlite" + shared = base.parent / f"ecobot-archive-{name}-{digest}.sqlite" with open(shared.with_suffix(".lock"), "w") as lock: fcntl.flock(lock, fcntl.LOCK_EX) # the first worker builds it; the others wait and find it if not shared.exists(): - path = tmp_path_factory.mktemp("archive") - with mock.patch.object(api, "MIN_GAP_SECONDS", 0), mock.patch.object(archive, "PACE_SECONDS", 0), \ - mock.patch.object(asyncio, "to_thread", _inline): - built = asyncio.run(build(path)) + folder = tmp_path_factory.mktemp("archive") + with pytest.MonkeyPatch.context() as patch: + patch.setattr(api, "MIN_GAP_SECONDS", 0) + patch.setattr(archive, "PACE_SECONDS", 0) + patch.setattr(asyncio, "to_thread", _inline) + built = make(folder, patch) os.replace(built, shared) return shared +def _run(coro): + """asyncio.run on a thread of its own (an async test may be asking, its loop running on this one).""" + import concurrent.futures + with concurrent.futures.ThreadPoolExecutor(1) as pool: + return pool.submit(asyncio.run, coro).result() + + async def _inline(func, /, *args, **kwargs): """asyncio.to_thread without the thread: tests use tiny in-memory-speed SQLite calls, and a thread hop per call is most of their run time.""" @@ -110,3 +224,42 @@ def fast_connect(*args, **kwargs): # tests don't need the caches to survive a p yield for db in opened: db.close() + + +@pytest.fixture(autouse=True) +def charts_come_back_from_json(monkeypatch): + """Every chart a test builds is also written as JSON and read back (specs.to_json, from_json), and must come back the same: the + bot draws each chart from its JSON. A chart that doesn't fails the test when it ends (a tool that drew it may catch the error).""" + import json + from lib import specs + from tests.fakes import TZ + built, wrong, busy = specs.Chart.__post_init__, [], [] + + def checked(chart): + built(chart) + if busy: # the chart from_json is building + return + busy.append(chart) + try: + back = specs.from_json(json.loads(json.dumps(specs.to_json(chart, TZ)))) + if back != chart: + wrong.append(f"{chart.title!r} came back from its JSON changed: {difference(chart, back)}") + except Exception as e: + wrong.append(f"{chart.title!r} couldn't go through JSON: {type(e).__name__}: {e}") + finally: + busy.pop() + monkeypatch.setattr(specs.Chart, "__post_init__", checked) + yield + assert not wrong, wrong[0] + + +def difference(a, b, path: str = "chart") -> str: + """Where two charts (or parts of them) first differ, "chart.panels[0].lines[1].x[0]: 1 != 2", rather than both whole.""" + from dataclasses import fields, is_dataclass + if is_dataclass(a) and type(a) is type(b): + name = next(f.name for f in fields(a) if getattr(a, f.name) != getattr(b, f.name)) + return difference(getattr(a, name), getattr(b, name), f"{path}.{name}") + if type(a) is type(b) and isinstance(a, (list, tuple)) and len(a) == len(b): + i = next(i for i, (x, y) in enumerate(zip(a, b)) if x != y) + return difference(a[i], b[i], f"{path}[{i}]") + return f"{path}: {a!r} != {b!r}" diff --git a/tests/current_words.json b/tests/current_words.json new file mode 100644 index 00000000..a346ad50 --- /dev/null +++ b/tests/current_words.json @@ -0,0 +1,277 @@ +{ + "wet-night": { + "all": { + "station": [ + "• Outdoor: 🧥 12.3 °C, 💦 94 %", + "• Indoor: 🧥 18.3 °C, 63 %", + "• Pressure: 🗜️ 1025.0 hPa", + "• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)" + ], + "air": [ + "{pm2.5}", + "• PM10: 8.0 µg/m³ 🟢 good (AQI 7)", + "• PM1: 3.0 µg/m³ 🟢 good", + "• CO₂: 450 ppm 🟢 good", + "• VOC index: 100 🟢 good", + "• NOx index: 1.0 🟢 good" + ] + }, + "lookups": [ + [ + "• Outdoor: 🧥 12.3 °C, feels like 12.3 °C", + "• Indoor: 🧥 18.3 °C, feels like 18.3 °C" + ], + [ + "• Indoor: 🧥 18.3 °C, feels like 18.3 °C" + ], + [ + "• Outdoor: 💦 94 %" + ], + [ + "• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)" + ], + [ + "• Wind: calm" + ], + [ + "• UV index: 0" + ], + [ + "• Pressure: 🗜️ 1025.0 hPa" + ], + [ + "• Solar radiation: 0.0 W/m²" + ], + [ + "• Dew point: 11.3 °C" + ], + [ + "• Dew point (indoor): 11.1 °C" + ], + [ + "• Feels like: 🧥 12.3 °C" + ], + [ + "• Outdoor: 🧥 12.3 °C, feels like 12.3 °C", + "• Indoor: 🧥 18.3 °C, feels like 18.3 °C", + "• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)" + ] + ], + "air": [ + [ + "• PM10: 8.0 µg/m³ 🟢 good (AQI 7)" + ], + [ + "{pm2.5}", + "• CO₂: 450 ppm 🟢 good" + ], + [ + "{pm2.5}", + "• PM10: 8.0 µg/m³ 🟢 good (AQI 7)", + "• PM1: 3.0 µg/m³ 🟢 good", + "• CO₂: 450 ppm 🟢 good", + "• VOC index: 100 🟢 good", + "• NOx index: 1.0 🟢 good" + ], + [ + "{pm2.5}", + "• PM10: 8.0 µg/m³ 🟢 good (AQI 7)", + "• PM1: 3.0 µg/m³ 🟢 good", + "• CO₂: 450 ppm 🟢 good", + "• VOC index: 100 🟢 good", + "• NOx index: 1.0 🟢 good" + ] + ] + }, + "sunny": { + "all": { + "station": [ + "• Outdoor: 🧥 12.3 °C, 💦 94 %", + "• Indoor: 🧥 18.3 °C, 63 %", + "• Pressure: 🗜️ 1025.0 hPa", + "• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)", + "• Sun: ☀️ solar radiation 612.5 W/m² (high), 😎 UV index 7", + "• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h" + ], + "air": [ + "{pm2.5}", + "• PM10: 8.0 µg/m³ 🟢 good (AQI 7)", + "• PM1: 3.0 µg/m³ 🟢 good", + "• CO₂: 450 ppm 🟢 good", + "• VOC index: 100 🟢 good", + "• NOx index: 1.0 🟢 good" + ] + }, + "lookups": [ + [ + "• Outdoor: 🧥 12.3 °C, feels like 12.3 °C", + "• Indoor: 🧥 18.3 °C, feels like 18.3 °C" + ], + [ + "• Indoor: 🧥 18.3 °C, feels like 18.3 °C" + ], + [ + "• Outdoor: 💦 94 %" + ], + [ + "• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)" + ], + [ + "• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h" + ], + [ + "• UV index: 😎 7" + ], + [ + "• Pressure: 🗜️ 1025.0 hPa" + ], + [ + "• Solar radiation: ☀️ 612.5 W/m²" + ], + [ + "• Dew point: 11.3 °C" + ], + [ + "• Dew point (indoor): 11.1 °C" + ], + [ + "• Feels like: 🧥 12.3 °C" + ], + [ + "• Outdoor: 🧥 12.3 °C, feels like 12.3 °C", + "• Indoor: 🧥 18.3 °C, feels like 18.3 °C", + "• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)" + ] + ], + "air": [ + [ + "• PM10: 8.0 µg/m³ 🟢 good (AQI 7)" + ], + [ + "{pm2.5}", + "• CO₂: 450 ppm 🟢 good" + ], + [ + "{pm2.5}", + "• PM10: 8.0 µg/m³ 🟢 good (AQI 7)", + "• PM1: 3.0 µg/m³ 🟢 good", + "• CO₂: 450 ppm 🟢 good", + "• VOC index: 100 🟢 good", + "• NOx index: 1.0 🟢 good" + ], + [ + "{pm2.5}", + "• PM10: 8.0 µg/m³ 🟢 good (AQI 7)", + "• PM1: 3.0 µg/m³ 🟢 good", + "• CO₂: 450 ppm 🟢 good", + "• VOC index: 100 🟢 good", + "• NOx index: 1.0 🟢 good" + ] + ] + }, + "every-emoji": { + "all": { + "station": [ + "• Outdoor: 🔥 36.0 °C, 💦 90 %", + "• Indoor: 🥵 29.0 °C, 🏜️ 20 %", + "• Pressure: 🗜️ 1030.0 hPa", + "• Rain today: ☔ 3.0 mm (month total 9.0 mm); 🌧️ raining (2.0 mm/h)", + "• Sun: ☀️ solar radiation 800.0 W/m² (high), 🧴 UV index 10", + "• Wind: 🌪️ 55.0 km/h from 90°, gust 🌪️ 70.0 km/h" + ], + "air": [ + "{pm2.5}", + "• PM10: 8.0 µg/m³ 🟢 good (AQI 7)", + "• PM1: 3.0 µg/m³ 🟢 good", + "• CO₂: 450 ppm 🟢 good", + "• VOC index: 100 🟢 good", + "• NOx index: 1.0 🟢 good" + ] + } + }, + "dry": { + "all": { + "station": [ + "• Outdoor: 🧥 12.3 °C, 💦 94 %", + "• Indoor: 🧥 18.3 °C, 63 %", + "• Pressure: 🗜️ 1025.0 hPa", + "• Rain today: 0.0 mm (month total 12.0 mm)", + "• Wind: 12.0 km/h from 270°, gust 🍃 20.0 km/h" + ], + "air": [ + "{pm2.5}", + "• PM10: 8.0 µg/m³ 🟢 good (AQI 7)", + "• PM1: 3.0 µg/m³ 🟢 good", + "• CO₂: 450 ppm 🟢 good", + "• VOC index: 100 🟢 good", + "• NOx index: 1.0 🟢 good" + ] + }, + "lookups": [ + [ + "• Outdoor: 🧥 12.3 °C, feels like 12.3 °C", + "• Indoor: 🧥 18.3 °C, feels like 18.3 °C" + ], + [ + "• Indoor: 🧥 18.3 °C, feels like 18.3 °C" + ], + [ + "• Outdoor: 💦 94 %" + ], + [ + "• Rain today: 0.0 mm (month total 12.0 mm)" + ], + [ + "• Wind: 12.0 km/h from 270°, gust 🍃 20.0 km/h" + ], + [ + "• UV index: 0" + ], + [ + "• Pressure: 🗜️ 1025.0 hPa" + ], + [ + "• Solar radiation: 0.0 W/m²" + ], + [ + "• Dew point: 11.3 °C" + ], + [ + "• Dew point (indoor): 11.1 °C" + ], + [ + "• Feels like: 🧥 12.3 °C" + ], + [ + "• Outdoor: 🧥 12.3 °C, feels like 12.3 °C", + "• Indoor: 🧥 18.3 °C, feels like 18.3 °C", + "• Rain today: 0.0 mm (month total 12.0 mm)" + ] + ], + "air": [ + [ + "• PM10: 8.0 µg/m³ 🟢 good (AQI 7)" + ], + [ + "{pm2.5}", + "• CO₂: 450 ppm 🟢 good" + ], + [ + "{pm2.5}", + "• PM10: 8.0 µg/m³ 🟢 good (AQI 7)", + "• PM1: 3.0 µg/m³ 🟢 good", + "• CO₂: 450 ppm 🟢 good", + "• VOC index: 100 🟢 good", + "• NOx index: 1.0 🟢 good" + ], + [ + "{pm2.5}", + "• PM10: 8.0 µg/m³ 🟢 good (AQI 7)", + "• PM1: 3.0 µg/m³ 🟢 good", + "• CO₂: 450 ppm 🟢 good", + "• VOC index: 100 🟢 good", + "• NOx index: 1.0 🟢 good" + ] + ] + } +} diff --git a/tests/days_words.json b/tests/days_words.json new file mode 100644 index 00000000..5f2d97ce --- /dev/null +++ b/tests/days_words.json @@ -0,0 +1,891 @@ +{ + "clock": "2026-11-10T14:05:00+11:00", + "station": [ + { + "arguments": { + "where": [ + { + "field": "rain", + "op": ">", + "value": 0 + } + ], + "sort_by": "temp_max", + "limit": 3 + }, + "result": { + "fresh": "These figures are as of `as_of`. A follow-up or a challenge (\"that's wrong, it was cooler\") needs this tool called again: never answer it from these.", + "answer": "20 of 79 days with rain > 0 mm (Sat 22 Aug – Sun 8 Nov 2026).", + "days_checked": 79, + "matching_days": 20, + "units": { + "temp_max": "°C", + "temp_min": "°C", + "rain": "mm" + }, + "condition": "rain > 0 mm", + "days": [ + { + "date": "Mon 24 Aug 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.4, + "temp_min": 8.4, + "rain": 0.5 + }, + { + "date": "Sun 13 Sep 2026", + "day_look": { + "word": "wet", + "emoji": "🌧️" + }, + "source": "exact", + "temp_max": 20.4, + "temp_min": 8.4, + "rain": 5.0 + }, + { + "date": "Sat 3 Oct 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.4, + "temp_min": 8.4, + "rain": 0.5 + } + ], + "note_group_by": "One figure for the whole period. If a figure per month or per year was asked for (\"per month\", \"by year\", \"each year\"), call again with group_by \"month\" or \"year\"." + } + }, + { + "arguments": { + "where": [ + { + "field": "rain", + "op": ">=", + "value": 1 + } + ], + "sort_by": "temp_max", + "limit": 4 + }, + "result": { + "fresh": "These figures are as of `as_of`. A follow-up or a challenge (\"that's wrong, it was cooler\") needs this tool called again: never answer it from these.", + "answer": "10 of 79 days with rain ≥ 1 mm (Sat 22 Aug – Sun 8 Nov 2026).", + "days_checked": 79, + "matching_days": 10, + "units": { + "temp_max": "°C", + "temp_min": "°C", + "rain": "mm" + }, + "condition": "rain ≥ 1 mm", + "days": [ + { + "date": "Sun 13 Sep 2026", + "day_look": { + "word": "wet", + "emoji": "🌧️" + }, + "source": "exact", + "temp_max": 20.4, + "temp_min": 8.4, + "rain": 5.0 + }, + { + "date": "Fri 23 Oct 2026", + "day_look": { + "word": "wet", + "emoji": "🌧️" + }, + "source": "exact", + "temp_max": 20.4, + "temp_min": 8.4, + "rain": 5.0 + }, + { + "date": "Fri 28 Aug 2026", + "day_look": { + "word": "wet", + "emoji": "🌧️" + }, + "source": "exact", + "temp_max": 20.3, + "temp_min": 8.3, + "rain": 5.0 + }, + { + "date": "Wed 7 Oct 2026", + "day_look": { + "word": "wet", + "emoji": "🌧️" + }, + "source": "exact", + "temp_max": 20.3, + "temp_min": 8.3, + "rain": 5.0 + } + ], + "note_group_by": "One figure for the whole period. If a figure per month or per year was asked for (\"per month\", \"by year\", \"each year\"), call again with group_by \"month\" or \"year\"." + } + }, + { + "arguments": { + "where": [ + { + "field": "temp_max", + "op": ">", + "value": 18 + } + ], + "count_only": true + }, + "result": { + "fresh": "These figures are as of `as_of`. A follow-up or a challenge (\"that's wrong, it was cooler\") needs this tool called again: never answer it from these.", + "answer": "79 of 79 days with temperature > 18 °C (Sat 22 Aug – Sun 8 Nov 2026).", + "days_checked": 79, + "matching_days": 79, + "units": { + "temp_max": "°C", + "temp_min": "°C", + "rain": "mm" + }, + "condition": "temperature > 18 °C", + "note_group_by": "One figure for the whole period. If a figure per month or per year was asked for (\"per month\", \"by year\", \"each year\"), call again with group_by \"month\" or \"year\"." + } + }, + { + "arguments": { + "sort_by": "temp_min", + "order": "asc", + "limit": 2 + }, + "result": { + "fresh": "These figures are as of `as_of`. A follow-up or a challenge (\"that's wrong, it was cooler\") needs this tool called again: never answer it from these.", + "answer": "79 of 79 days (Sat 22 Aug – Sun 8 Nov 2026).", + "days_checked": 79, + "matching_days": 79, + "units": { + "temp_max": "°C", + "temp_min": "°C", + "rain": "mm" + }, + "days": [ + { + "date": "Wed 26 Aug 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.1, + "temp_min": 8.1, + "rain": 0.0 + }, + { + "date": "Mon 31 Aug 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.1, + "temp_min": 8.1, + "rain": 0.0 + } + ], + "note_group_by": "One figure for the whole period. If a figure per month or per year was asked for (\"per month\", \"by year\", \"each year\"), call again with group_by \"month\" or \"year\"." + } + }, + { + "arguments": { + "stat": "sum", + "of": "rain", + "group_by": "month" + }, + "result": { + "fresh": "These figures are as of `as_of`. A follow-up or a challenge (\"that's wrong, it was cooler\") needs this tool called again: never answer it from these.", + "answer": "Total rain: 55 mm over 79 days (Sat 22 Aug – Sun 8 Nov 2026).", + "days_checked": 79, + "matching_days": 79, + "units": { + "temp_max": "°C", + "temp_min": "°C", + "rain": "mm" + }, + "stat": { + "what": "Total rain", + "of": "rain", + "unit": "mm" + }, + "value": 55.0, + "by_month": { + "2026-08": 5.5, + "2026-09": 22.0, + "2026-10": 22.0, + "2026-11": 5.5 + }, + "chart_note": "The chart's data is in `charts`: draw it if you can, and keep your text to the figures. Don't describe the chart.", + "charts": [ + { + "version": 1, + "title": "Total rain", + "subtitle": "Sat 22 Aug 2026 – Sun 8 Nov 2026 · 79 days counted · per month", + "period": [ + "2026-08-22", + "2026-11-08" + ], + "source": "Ecowitt weather station", + "newest": "2026-11-01T00:00:00+11:00", + "panels": [ + { + "label": "Rain", + "unit": "mm", + "reading": "", + "series": [ + { + "name": "Rain", + "kind": "bars", + "unit": "mm", + "width": 2419200, + "per": "month", + "values": true, + "points": [ + [ + "2026-08-01T00:00:00+10:00", + 5.5 + ], + [ + "2026-09-01T00:00:00+10:00", + 22.0 + ], + [ + "2026-10-01T00:00:00+10:00", + 22.0 + ], + [ + "2026-11-01T00:00:00+11:00", + 5.5 + ] + ] + } + ], + "flip_right": false, + "peaks": "pills" + } + ], + "drawn_by": { + "tool": "days", + "arguments": { + "where": [], + "sort_by": "rain", + "order": "desc", + "count_only": false, + "group_by": "month", + "stat": "sum", + "of": "rain", + "limit": 5, + "period": "2026-08-22 to 2026-11-08", + "chart_answers_it": false + }, + "periods": [ + { + "period": "3m", + "label": "3M" + }, + { + "period": "1y", + "label": "1Y" + }, + { + "period": "on record", + "label": "All" + } + ] + } + } + ] + } + }, + { + "arguments": { + "where": [ + { + "field": "humidity_min", + "op": "<", + "value": 60 + } + ], + "stat": "avg", + "of": "humidity_avg" + }, + "result": { + "fresh": "These figures are as of `as_of`. A follow-up or a challenge (\"that's wrong, it was cooler\") needs this tool called again: never answer it from these.", + "answer": "Average humidity: 69.4 % over 79 days (Sat 22 Aug – Sun 8 Nov 2026).", + "days_checked": 79, + "matching_days": 79, + "units": { + "temp_max": "°C", + "temp_min": "°C", + "rain": "mm", + "humidity_min": "%", + "humidity_avg": "%" + }, + "condition": "lowest humidity < 60 %", + "stat": { + "what": "Average humidity", + "of": "humidity_avg", + "unit": "%" + }, + "value": 69.4, + "days": [ + { + "date": "Tue 25 Aug 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.0, + "temp_min": 8.5, + "rain": 0.0, + "humidity_min": 55.0, + "humidity_avg": 69.5 + }, + { + "date": "Wed 26 Aug 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.1, + "temp_min": 8.1, + "rain": 0.0, + "humidity_min": 55.0, + "humidity_avg": 69.8 + }, + { + "date": "Sun 30 Aug 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.0, + "temp_min": 8.5, + "rain": 0.0, + "humidity_min": 55.0, + "humidity_avg": 69.5 + }, + { + "date": "Mon 31 Aug 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.1, + "temp_min": 8.1, + "rain": 0.0, + "humidity_min": 55.0, + "humidity_avg": 69.8 + }, + { + "date": "Fri 4 Sep 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.0, + "temp_min": 8.5, + "rain": 0.0, + "humidity_min": 55.0, + "humidity_avg": 69.5 + } + ], + "note_group_by": "One figure for the whole period. If a figure per month or per year was asked for (\"per month\", \"by year\", \"each year\"), call again with group_by \"month\" or \"year\"." + } + }, + { + "arguments": { + "where": [ + { + "field": "rain", + "op": "=", + "value": 0 + } + ], + "only": "weekend", + "limit": 20 + }, + "result": { + "fresh": "These figures are as of `as_of`. A follow-up or a challenge (\"that's wrong, it was cooler\") needs this tool called again: never answer it from these.", + "answer": "18 of 24 days with rain = 0 mm (Sat 22 Aug – Sun 8 Nov 2026).", + "days_checked": 24, + "matching_days": 18, + "units": { + "temp_max": "°C", + "temp_min": "°C", + "rain": "mm" + }, + "condition": "rain = 0 mm", + "days": [ + { + "date": "Sat 22 Aug 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.2, + "temp_min": 8.2, + "rain": 0.0 + }, + { + "date": "Sun 23 Aug 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.3, + "temp_min": 8.3, + "rain": 0.0 + }, + { + "date": "Sat 29 Aug 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.4, + "temp_min": 8.4, + "rain": 0.0 + }, + { + "date": "Sun 30 Aug 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.0, + "temp_min": 8.5, + "rain": 0.0 + }, + { + "date": "Sun 6 Sep 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.2, + "temp_min": 8.2, + "rain": 0.0 + }, + { + "date": "Sat 12 Sep 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.3, + "temp_min": 8.3, + "rain": 0.0 + }, + { + "date": "Sat 19 Sep 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.0, + "temp_min": 8.5, + "rain": 0.0 + }, + { + "date": "Sun 20 Sep 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.1, + "temp_min": 8.1, + "rain": 0.0 + }, + { + "date": "Sat 26 Sep 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.2, + "temp_min": 8.2, + "rain": 0.0 + }, + { + "date": "Sun 27 Sep 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.3, + "temp_min": 8.3, + "rain": 0.0 + }, + { + "date": "Sun 4 Oct 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.0, + "temp_min": 8.5, + "rain": 0.0 + }, + { + "date": "Sat 10 Oct 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.1, + "temp_min": 8.1, + "rain": 0.0 + }, + { + "date": "Sat 17 Oct 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.3, + "temp_min": 8.3, + "rain": 0.0 + }, + { + "date": "Sun 18 Oct 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.4, + "temp_min": 8.4, + "rain": 0.0 + }, + { + "date": "Sat 24 Oct 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.0, + "temp_min": 8.5, + "rain": 0.0 + }, + { + "date": "Sun 25 Oct 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.1, + "temp_min": 8.1, + "rain": 0.0 + }, + { + "date": "Sun 1 Nov 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.3, + "temp_min": 8.3, + "rain": 0.0 + }, + { + "date": "Sat 7 Nov 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "temp_max": 20.4, + "temp_min": 8.4, + "rain": 0.0 + } + ], + "note_group_by": "One figure for the whole period. If a figure per month or per year was asked for (\"per month\", \"by year\", \"each year\"), call again with group_by \"month\" or \"year\"." + } + } + ], + "air": [ + { + "arguments": { + "where": [ + { + "field": "pm2_5_max", + "op": ">", + "value": 20 + } + ], + "limit": 3 + }, + "result": { + "fresh": "These figures are as of `as_of`. A follow-up or a challenge (\"that's wrong, it was cooler\") needs this tool called again: never answer it from these.", + "answer": "18 of 39 days with PM2.5 > 20 µg/m³ (Mon 21 Sep – Sun 8 Nov 2026).", + "days_checked": 39, + "matching_days": 18, + "units": { + "pm2_5_max": "µg/m³" + }, + "condition": "PM2.5 > 20 µg/m³", + "days": [ + { + "date": "Sat 3 Oct 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "pm2_5_max": 33.0 + }, + { + "date": "Sat 10 Oct 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "pm2_5_max": 33.0 + }, + { + "date": "Sat 17 Oct 2026", + "day_look": { + "word": "sunny", + "emoji": "☀️" + }, + "source": "exact", + "pm2_5_max": 33.0 + } + ], + "note_missing": "10 day(s) in this period have no stored readings (not downloaded yet, or the sensor was off) and are not counted.", + "note_group_by": "One figure for the whole period. If a figure per month or per year was asked for (\"per month\", \"by year\", \"each year\"), call again with group_by \"month\" or \"year\"." + } + }, + { + "arguments": { + "stat": "max", + "of": "pm2_5_max", + "group_by": "month" + }, + "result": { + "fresh": "These figures are as of `as_of`. A follow-up or a challenge (\"that's wrong, it was cooler\") needs this tool called again: never answer it from these.", + "answer": "Highest PM2.5: 33 µg/m³ over 39 days (Mon 21 Sep – Sun 8 Nov 2026).", + "days_checked": 39, + "matching_days": 39, + "units": { + "pm2_5_max": "µg/m³" + }, + "stat": { + "what": "Highest PM2.5", + "of": "pm2_5_max", + "unit": "µg/m³" + }, + "value": 33.0, + "by_month": { + "2026-10": 33.0, + "2026-11": 33.0 + }, + "note_missing": "10 day(s) in this period have no stored readings (not downloaded yet, or the sensor was off) and are not counted.", + "chart_note": "The chart's data is in `charts`: draw it if you can, and keep your text to the figures. Don't describe the chart.", + "charts": [ + { + "version": 1, + "title": "Highest PM2.5", + "subtitle": "Mon 21 Sep 2026 – Sun 8 Nov 2026 · 39 days counted · per month", + "period": [ + "2026-09-21", + "2026-11-08" + ], + "source": "AirGradient sensor", + "newest": "2026-11-01T00:00:00+11:00", + "panels": [ + { + "label": "Pm2.5", + "unit": "µg/m³", + "reading": "", + "series": [ + { + "name": "Pm2.5", + "kind": "bars", + "unit": "µg/m³", + "width": 2419200, + "per": "month", + "values": true, + "points": [ + [ + "2026-10-01T00:00:00+10:00", + 33.0 + ], + [ + "2026-11-01T00:00:00+11:00", + 33.0 + ] + ] + } + ], + "flip_right": false, + "peaks": "pills" + } + ], + "drawn_by": { + "tool": "days", + "arguments": { + "where": [], + "sort_by": "pm2_5_max", + "order": "desc", + "count_only": false, + "group_by": "month", + "stat": "max", + "of": "pm2_5_max", + "limit": 5, + "period": "2026-09-21 to 2026-11-08", + "chart_answers_it": false + }, + "periods": [ + { + "period": "3m", + "label": "3M" + }, + { + "period": "1y", + "label": "1Y" + }, + { + "period": "on record", + "label": "All" + } + ] + } + } + ] + } + }, + { + "arguments": { + "sort_by": "pm10_avg", + "order": "asc", + "count_only": true + }, + "result": { + "fresh": "These figures are as of `as_of`. A follow-up or a challenge (\"that's wrong, it was cooler\") needs this tool called again: never answer it from these.", + "answer": "39 of 39 days (Mon 21 Sep – Sun 8 Nov 2026).", + "days_checked": 39, + "matching_days": 39, + "units": { + "pm2_5_max": "µg/m³", + "pm10_avg": "µg/m³" + }, + "note_missing": "10 day(s) in this period have no stored readings (not downloaded yet, or the sensor was off) and are not counted.", + "note_group_by": "One figure for the whole period. If a figure per month or per year was asked for (\"per month\", \"by year\", \"each year\"), call again with group_by \"month\" or \"year\"." + } + } + ], + "answer_lines": [ + { + "data": { + "period": "Tue 29 Sep 2026 - Tue 6 Oct 2026", + "days_checked": 1454, + "matching_days": 137, + "condition": "UV index ≥ 10" + }, + "answer": "137 of 1,454 days with UV index ≥ 10 (Tue 29 Sep – Tue 6 Oct 2026)." + }, + { + "data": { + "period": "Tue 29 Sep 2026 - Tue 6 Oct 2026", + "days_checked": 1454, + "matching_days": 137, + "condition": "UV index ≥ 10", + "note_averaged": "..." + }, + "answer": "137 of 1,454 days with UV index ≥ 10 (Tue 29 Sep – Tue 6 Oct 2026). Older days use averages, so a count near the limit may fall slightly short." + }, + { + "data": { + "period": "Tue 29 Sep 2026 - Tue 6 Oct 2026", + "days_checked": 1454, + "matching_days": 137, + "condition": "UV index ≥ 10", + "stat": { + "what": "Total rain", + "of": "rain", + "unit": "mm" + }, + "value": 49.8 + }, + "answer": "Total rain: 49.8 mm over 1,454 days (Tue 29 Sep – Tue 6 Oct 2026)." + }, + { + "data": { + "period": "Tue 29 Sep 2026 - Tue 6 Oct 2026", + "days_checked": 1454, + "matching_days": 137, + "condition": "UV index ≥ 10", + "stat": { + "what": "Highest UV index", + "of": "uv_max", + "unit": "" + }, + "value": 11.0 + }, + "answer": "Highest UV index: 11 over 1,454 days (Tue 29 Sep – Tue 6 Oct 2026)." + }, + { + "data": { + "period": "Tue 29 Sep 2026 - Tue 6 Oct 2026", + "days_checked": 1454, + "matching_days": 137, + "condition": "UV index ≥ 10", + "stat": { + "what": "Total rain", + "of": "rain", + "unit": "mm" + }, + "value": null + }, + "answer": "137 of 1,454 days with UV index ≥ 10 (Tue 29 Sep – Tue 6 Oct 2026)." + }, + { + "data": { + "period": "Tue 29 Sep 2026 - Tue 6 Oct 2026", + "days_checked": 1454, + "matching_days": 137, + "condition": null + }, + "answer": "137 of 1,454 days (Tue 29 Sep – Tue 6 Oct 2026)." + } + ] +} diff --git a/tests/engines.py b/tests/engines.py new file mode 100644 index 00000000..091d8b69 --- /dev/null +++ b/tests/engines.py @@ -0,0 +1,64 @@ +"""lib's engines driven directly, for their own tests: the station's HistoryQuery over the groups asked for (with those its chart +needs), the reading-against-rain link (lib/ecowitt/link.py), and the air sensor's history and reading now (AirGradient.history, latest). +The service's tools run these same engines (lib/service/summary.py, relate.py, current.py) and have tests of their own. + +Until step 6c these drivers were part of tests/old_tools.py, the old tools' handlers kept as the oracle the service's words were ported +against; the oracle (the old words, the old day finders and readings handler) is deleted, and only the engines' drivers are kept here.""" + +import asyncio +from datetime import datetime, time + +from lib.airgradient.metrics import EXTRA +from lib.captions import wants_chart +from lib.ecowitt.api import GROUPS +from lib.ecowitt.link import link +from lib.ecowitt.query import HistoryQuery, chart_field, stack_names +from lib.series import WEATHER, find +from lib.timeutil import now_local +from lib.tools import Turn, json_result + +DEFAULT_GROUPS = "outdoor,indoor" +LINK_CHART_HINT = "(a chart of the reading as a line and rain as bars behind it)" + + +def groups_of(value, default: str = DEFAULT_GROUPS) -> list[str]: + """'outdoor, indoor' or ['outdoor', 'indoor'] -> ['outdoor', 'indoor'] (a reading named instead of its group becomes its group).""" + parts = value if isinstance(value, list) else str(value or default).split(",") + named = (p.split(".")[0].strip().lower() for p in parts if p.strip()) + groups = (g if g in GROUPS else (r.group if (r := find(g)) else None) for g in named) + return list(dict.fromkeys(g for g in groups if g)) or default.split(",") + + +async def history(eco, args: dict, turn: Turn | None = None) -> str: + """HistoryQuery over the station's groups asked for (args["groups"]) and those its chart needs, fetching as a question does.""" + turn = turn or Turn() + groups = groups_of(args.get("groups")) + groups += [g for n in stack_names(args, turn) if (g := WEATHER[n].group) not in groups] + if (r := find(chart_field(args, turn) or "")) and r.group not in groups: + groups.append(r.group) + return await HistoryQuery(eco.fetcher(groups, urgent=not turn.ahead), args, turn).run() + + +async def linked(eco, args: dict, turn: Turn | None = None) -> str: + """link() over the station's 30-minute readings, its chart kept on the turn when asked for (or the period is 3 days or more).""" + turn = turn or Turn() + out, spec, first, last = await asyncio.to_thread(link, eco.storage.read_now, eco.mac, eco.tz, args, now_local(eco.tz)) + if spec and wants_chart(args, turn, datetime.combine(first, time()), datetime.combine(last, time())): + turn.charts.append(spec) + out["chart"] = LINK_CHART_HINT + return json_result(out) + + +async def air_now(air, extras=()) -> dict: + """The air sensor's latest reading (AirGradient.latest).""" + return (await air.latest(extras)).reading + + +async def air_history(air, args: dict, turn: Turn | None = None) -> str: + """AirGradient.history over the period asked (start_date, end_date) and its chart when asked; with neither, the reading now.""" + turn = turn or Turn() + chart = wants_chart(args, turn) + if args.get("start_date") or args.get("end_date") or chart: + return json_result(await air.history(args.get("start_date"), args.get("end_date"), chart=chart, metrics=args.get("metrics"), + turn=turn)) + return json_result(await air_now(air, [m for m in args.get("metrics") or [] if m in EXTRA])) diff --git a/tests/evalkit.py b/tests/evalkit.py index 00914895..92a4e46b 100644 --- a/tests/evalkit.py +++ b/tests/evalkit.py @@ -1,26 +1,28 @@ -"""Saved questions with the tool calls we expect, so every fix we make for a real report stays fixed. +"""Saved questions with what should happen to them, so every fix we make for a real report stays fixed. -tests/evals/cases.json holds the questions (real ones from the logs). Two kinds of check: - - decisions made in code (fast path, period hints, reasoning effort, which readings a chart combines): run by pytest; - - what the model does with them (which tool, which arguments): `python scripts/eval_prompts.py --live`, against the - real model with recording stand-in tools (nothing is fetched). +tests/evals/cases.json holds the questions (real ones from the logs) and the one decision the bot still makes in code (docs/ecobot-mcp.md +4): the reasoning effort from the words. Every typed question goes to the model (step 6c: the shortcuts the bot once answered in code, +the report, "weather now" and a named reading's chart and a period, are the model's too). pytest checks it (`deterministic`). +tests/evals/service_cases.json holds, for the same case ids, what a model offered the service's ten tools (lib/service) should call: +checked offline by tests/test_service_evals.py, and asked of a model by `python scripts/eval_prompts.py --live` three ways: + - the bot's own request (`bot=True`, the default of --live): its system prompt (lib/prompt.py: the persona, the server's + instructions, the date and time), the ten tools as the bot offers them, its reasoning effort from the words. Each call is answered + by the real tool over the evals' frozen world (tests/evalworld.py), so the model takes as many rounds as it needs, and the whole turn is scored (run_service); + - `--service`: the ten tools alone with a neutral system line and the date (SERVICE_SYSTEM), every call answered CANNED ("no data": + the model may call again or reply, and every call of the turn is scored); + - `--service --instructions`: that, with the server's instructions (lib/service/instructions.py) after the neutral line. """ import json import re from dataclasses import dataclass, field -from datetime import datetime +from datetime import date, datetime from pathlib import Path -from lib import compose, history, intent, prompt -from lib.airgradient import days as air_days, source as air -from lib.ecowitt import days, link, source as station -from lib.forecast import source as forecast -from lib.pollen import source as pollen -from tests.fakes import EVERY_SOURCE +from lib import intent, prompt +from lib.bot import complete_reply from lib.llm import Agent -from lib.specs import AIR_SOURCE, ECOWITT_SOURCE -from lib.tools import Tool, Tools +from lib.tools import Tool, Tools, Turn CASES = Path(__file__).resolve().parent / "evals" / "cases.json" NOW = datetime(2026, 9, 29, 14, 5) # a Tuesday: dates in the cases are relative to this @@ -38,6 +40,7 @@ "q:command": "asking the bot to do something (alerts)", "q:chat": "thanks and small talk", "q:report": "status / report", "q:dashboard": "the station's gauges", "q:detail-level": "asking for a finer data resolution", "q:cross-source": "a question that needs both devices together", "q:scan": "which readings go with which (every pair)", "q:interval": "values at an interval (each hour, every 30 minutes)", + "q:chart-only": "a question that is only a chart (chart_answers_it), and one that asks something beside it", "m:temperature": "temperature", "m:humidity": "humidity", "m:pressure": "pressure", "m:wind-speed": "wind speed and gusts", "m:wind-direction": "wind direction", "m:rain": "rain", "m:air-quality": "air quality", "c:line": "a line chart of one reading", "c:daily-band": "a long chart: daily mean with its range", @@ -63,43 +66,29 @@ def load_cases(path: Path = CASES) -> list[Case]: return [Case(**c) for c in json.loads(path.read_text())] -def tool_names() -> list[str]: - return ["weather_now", "weather_history", "weather_days", "weather_link", "air_quality", "plot_chart", "air_link", "air_scan", - "pollen_asthma", "weather_forecast", "air_days", "readings"] - - -def make_tools(calls: list) -> Tools: - """The real tool definitions with stand-in handlers that record the call.""" - def recorder(name): - async def handler(args, turn=None): - calls.append((name, args)) - return CANNED - return handler - defs = [("weather_now", station.REALTIME_DESCRIPTION, station.REALTIME_PARAMS), - ("weather_history", station.HISTORY_DESCRIPTION, station.HISTORY_PARAMS), - ("weather_days", days.DESCRIPTION, days.PARAMETERS), - ("weather_link", link.DESCRIPTION, link.PARAMETERS), - ("air_quality", air.DESCRIPTION, air.PARAMETERS), - ("plot_chart", compose.PLOT_DESCRIPTION, compose.PLOT_PARAMETERS), - ("air_link", compose.LINK_DESCRIPTION, compose.LINK_PARAMETERS), - ("air_scan", compose.SCAN_DESCRIPTION, compose.SCAN_PARAMETERS), - ("pollen_asthma", pollen.DESCRIPTION, pollen.PARAMETERS), - ("weather_forecast", forecast.DESCRIPTION, forecast.PARAMETERS), - ("air_days", air_days.DESCRIPTION, air_days.PARAMETERS), - ("readings", history.DESCRIPTION, history.PARAMETERS)] - sources = {name: ECOWITT_SOURCE for name in ("weather_history", "weather_days", "weather_link")} | \ - {name: AIR_SOURCE for name in ("air_quality", "air_days")} | {name: "" for name in ("plot_chart", "air_link", "air_scan")} - return Tools([Tool(n, d, p, recorder(n), source=sources.get(n)) for n, d, p in defs]) - - def content(case: Case) -> str: """The user turn exactly as the bot builds it for a private chat.""" return f'(replying to your earlier message: "{case.reply_to}") {case.ask}' if case.reply_to else case.ask -def _matches(actual, want) -> str | None: - """None if `actual` satisfies `want`, else why not. want: a value, {"regex"}, {"absent"}, {"has"}, {"any_of"}.""" +def _matches(actual, want, args: dict | None = None, tool: str | None = None) -> str | None: + """None if `actual` satisfies `want`, else why not. want: a value, {"regex"}, {"absent"}, {"has"}, {"any_of"} (or "one_of"), or + the service's {"reads"} / {"reads_any"} (_reads), {"means"} (_means: over the whole call, `args`, as `tool` reads a period) and + {"conditions"} (_conditions). Any of them with "optional": true also takes no value at all.""" if isinstance(want, dict): + if "means" in want: # (the period may be sent as start and end instead: an optional one is absent only if neither is) + sent = {k: (args or {}).get(k) for k in ("period", "start", "end")} if args is not None else {"period": actual} + if want.get("optional") and not any(v not in (None, "") for v in sent.values()): + return None + return _means(sent, want["means"], tool) + if want.get("optional") and actual in (None, "", [], {}): + return None + if "reads" in want or "reads_any" in want: + return _reads(actual, want) + if "conditions" in want: + return _conditions(actual, want["conditions"]) + if "one_of" in want: + return None if actual in want["one_of"] else f"{actual!r} not one of {want['one_of']}" if "absent" in want: return None if actual in (None, "", [], {}) else f"expected no value, got {actual!r}" if "regex" in want: @@ -111,12 +100,15 @@ def _matches(actual, want) -> str | None: return None if actual == want else f"expected {want!r}, got {actual!r}" -def check_args(args: dict, want: dict) -> list[str]: - return [f"{k}: {why}" for k, w in want.items() if (why := _matches(args.get(k), w))] +def check_args(args: dict, want: dict, tool: str | None = None) -> list[str]: + """Failures of one call's arguments against one alternative of its expected arguments; `tool` is the tool called (a period is + read as that tool reads it).""" + return [f"{k}: {why}" for k, w in want.items() if (why := _matches(args.get(k), w, args, tool))] def check_calls(calls: list[tuple[str, dict]], expect: dict) -> list[str]: - """Failures of what the model called against the case's expectations.""" + """Failures of what the model called against the case's expectations. A tool's expected arguments may be a list of alternatives + (the service's cases: `period` in words, or `start` and `end`): a call matching any one of them passes.""" fails = [] names = [n for n, _ in calls] for tool in expect.get("tools", []): @@ -131,57 +123,479 @@ def check_calls(calls: list[tuple[str, dict]], expect: dict) -> list[str]: fails.append(f"first tool was {names[:1]}, expected {expect['first_tool']}") for tool, want in expect.get("args", {}).items(): made = [a for n, a in calls if n == tool] - if made and not any(not check_args(a, want) for a in made): - fails.append(f"{tool} arguments: " + "; ".join(check_args(made[0], want))) + alternatives = want if isinstance(want, list) else [want] + if made and not any(not check_args(a, w, tool) for a in made for w in alternatives): + fails.append(f"{tool} arguments: " + " | or: ".join("; ".join(check_args(made[0], w, tool)) for w in alternatives)) return fails +DECISIONS = {"effort"} # what cases.json's `expect` may say + + +def effort(case: Case) -> str: + """The reasoning effort the bot gives the case's question (intent.effort, from its words).""" + return intent.effort(case.ask) + + def deterministic(case: Case) -> list[str]: - """Failures of the decisions made in code (no model): reasoning effort, fast path, hints, chart choices.""" + """Failures of the decision made in code (no model): the reasoning effort.""" e, fails = case.expect, [] - text = case.ask - r = intent.read(text, NOW, EVERY_SOURCE) - if "effort" in e and r.effort != e["effort"]: - fails.append(f"effort {r.effort}, expected {e['effort']}") - if "fast" in e: - fast = r.fast - if e["fast"] is None: - if fast: - fails.append(f"took the fast path ({fast[0]}) but should go to the model") - elif not fast: - fails.append("did not take the fast path") - else: - if fast[0] != e["fast"].get("tool"): - fails.append(f"fast path tool {fast[0]}, expected {e['fast'].get('tool')}") - fails += [f"fast path {f}" for f in check_args(fast[1], e["fast"].get("args", {}))] - if "hints" in e: - hints = " | ".join(r.hints) - fails += [f"period hints lack {h!r} (got: {hints or 'none'})" for h in e["hints"] if h not in hints] - for key, got in (("chart_fields", r.chart_fields), ("two_axes", r.two_axes), ("air_extra", r.air_extra), ("chart_field", r.chart_field), ("report", r.report), ("dashboard", r.dashboard), - ("about_the_bot", r.about_the_bot), ("needs_data", r.needs_data), - ("weather_now", r.weather_now), ("rain_caption", r.rain_caption), ("chart_in_code", r.chart_in_code), ("lookup", r.lookup)): - if key in e and got != e[key]: - fails.append(f"{key} {got}, expected {e[key]}") - for name in e.get("tools", []) + e.get("any_tools", []) + e.get("not_tools", []) + ([e["first_tool"]] if "first_tool" in e else []): - if name not in tool_names(): - fails.append(f"unknown tool {name!r} in the case") + if extra := set(e) - DECISIONS: + fails.append(f"unknown keys {sorted(extra)}") + if "effort" in e and (got := effort(case)) != e["effort"]: + fails.append(f"effort {got}, expected {e['effort']}") return fails -async def run_live(case: Case, client, model: str, effort: str | None = None) -> tuple[list[tuple[str, dict]], str]: - """Ask the real model; returns the tool calls it made and its final reply.""" +def bot_system(now: datetime = NOW, ctx=None) -> str: + """The bot's system prompt at `now` (the station's local time): its persona, the server's instructions (over `ctx`, as the bot builds + them over its own; over eval_context() when none is given), the date and time.""" + from zoneinfo import ZoneInfo + + from lib.service.instructions import instructions + told = instructions(ctx) if ctx is not None else service_instructions() + return prompt.build(now.replace(tzinfo=ZoneInfo(NOW_TZ)), told) + + +MAX_CALLS = 8 # a bot-mode turn that makes more tool calls than this has run away: it fails, whatever it called + + +@dataclass +class LiveTurn: + """One question asked as the bot asks it: every call of the turn in order (refused ones too), the reply, whether each call's result + was a refusal (an `error`; `refusals`, in the calls' order), and the model's step each call was made in (`steps`, in the calls' order: + the calls of one step are made together; without them, each call is its own step).""" + calls: list + reply: str + refusals: list = field(default_factory=list) + steps: list = field(default_factory=list) + + @property + def refused(self) -> int: + """How many of the calls were refused.""" + return sum(self.refusals) + + def answered(self) -> list: + """The calls that were not refused.""" + return [c for c, no in zip(self.calls, self.refusals + [False] * len(self.calls)) if not no] + + def uncorrected(self) -> list: + """The refused calls no call to the same tool answered after: one answered in a later step corrects a refusal, one in the same + step doesn't (they were made together), nor does one to another tool.""" + refusals = self.refusals + [False] * len(self.calls) + steps = self.steps + list(range(len(self.steps), len(self.calls))) + return [c for c, no, step in zip(self.calls, refusals, steps) + if no and not any(d[0] == c[0] and not no_d and later > step + for d, no_d, later in zip(self.calls, refusals, steps))] + + def line(self) -> str: + """`3 calls, 1 refused: "the reply's first 200 characters"`.""" + return (f"{len(self.calls)} call{'s' * (len(self.calls) != 1)}, {self.refused} refused: " + f"{json.dumps(self.reply[:200], ensure_ascii=False)}") + + +REPEATED = "[You already made this exact call" # (lib/llm.py's answer to a repeat, the first result after it) + + +def refusal(text: str) -> bool: + """Is this tool result, as the model was sent it, a refusal: an `error`, or the tool loop's own "Error..." (no such tool, arguments + that aren't JSON, the tool failed)?""" + body = text.split("\n", 1)[-1] if text.startswith(REPEATED) else text + if body.startswith("Error"): + return True + try: + out = json.loads(body) + except ValueError: + return False + return isinstance(out, dict) and "error" in out + + +def turn_calls(messages: list[dict]) -> list[tuple[str, dict, bool, int]]: + """The tool calls of a turn's messages (as lib/llm.py's Agent leaves them: each assistant step's calls, then their results in + order), in the order made: (tool, arguments, whether its result was a refusal, the step it was made in, from 0).""" + calls, step = [], -1 + for i, m in enumerate(messages): + if m.get("role") != "assistant" or not m.get("tool_calls"): + continue + step += 1 + for c, result in zip(m["tool_calls"], messages[i + 1:i + 1 + len(m["tool_calls"])]): + try: + args = json.loads(c["function"]["arguments"] or "{}") + except ValueError: + args = {} + calls.append((c["function"]["name"], args if isinstance(args, dict) else {}, + result.get("role") == "tool" and refusal(str(result.get("content", ""))), step)) + return calls + + +async def run_live(case: Case, client, model: str, effort: str | None = None, service=None) -> LiveTurn: + """The bot's own request (docs/ecobot-mcp.md 4): every question is asked of the model (step 6c: the bot answers no typed question + in code) with the bot's system prompt, the ten tools as it offers them, its reasoning effort from the words, tool_choice auto, and + the turn ended on a complete result as the bot ends it. With `service` (evalworld.World.fresh: the ten tools over the frozen world) + each call is answered by the real tool, wrapped as the bot wraps it (lib/model_tools.py: the model is sent for_model of the + result), so the model calls again until it replies (at most lib/llm.py's MAX_STEPS steps, then it is made to answer); without, every + call is answered CANNED. Returns the whole turn.""" + from lib import model_tools + messages = [*case.history, {"role": "user", "content": content(case)}] + asked = len(messages) + tools = model_tools.tools(service) if service is not None else make_service_tools([]) + system = bot_system(ctx=getattr(service, "ctx", None)) + reply = await Agent(client, model, tools).run(messages, system, effort or intent.effort(case.ask), tool_choice="auto", turn=Turn(), + finish=lambda _, results: complete_reply(results)) + made = turn_calls(messages[asked:]) + return LiveTurn([(n, a) for n, a, *_ in made], reply, [no for _, _, no, _ in made], steps=[s for *_, s in made]) + + +# ---------- the service's ten tools, offered alone (docs/ecobot-mcp.md 6, step 2; 7) ---------- +# The same questions asked of a model given only the service's tool list: no prompt of ours (a neutral line, the date, time and zone), +# no hints, no fast path, nothing filled in from the words. tests/evals/service_cases.json says, for every case id in cases.json, which +# of the ten tools answers it and with which arguments, as a client that has never seen this repository would call them. +SERVICE_CASES = CASES.parent / "service_cases.json" +SERVICE_SYSTEM = "You answer questions about a home weather station and air sensor using the tools." +SERVICE_EFFORT = "low" # one reasoning level for every case: there is no intent.effort to choose one +NOW_TZ = "Australia/Melbourne" +EXPECT_KEYS = {"tools", "any_tools", "not_tools", "first_tool", "args", "note"} + + +def service_modules(): + from lib.service import about, current, days, forecast, outlook, pollen, readings, relate, scan, summary + return (current, summary, readings, days, relate, scan, outlook, forecast, pollen, about) + + +def service_tool_names() -> list[str]: + return ["current", "summary", "readings", "days", "relate", "scan", "outlook", "forecast", "pollen", "about"] + + +def eval_context(): + """The Context the service's evals build the tools over: stand-ins for every source (nothing behind them: the tools are built, never + run), the catalogue of every reading the service knows, the station's zone and NOW.""" + from zoneinfo import ZoneInfo + + from lib.service.context import Context + tz = ZoneInfo(NOW_TZ) + return Context(eco=object(), air=object(), composer=object(), forecast=object(), pollen=object(), tz=tz, + clock=lambda: NOW.replace(tzinfo=tz).timestamp()) + + +def service_tools(ctx=None) -> list: + """The ten ServiceTools, each module's tools(ctx), over eval_context() when no ctx is given.""" + ctx = ctx if ctx is not None else eval_context() + return [t for module in service_modules() for t in module.tools(ctx)] + + +def service_instructions() -> str: + """The server's instructions (lib/service/instructions.py) over eval_context(), as a `--instructions` run adds them.""" + from lib.service.instructions import instructions + return instructions(eval_context()) + + +def make_service_tools(calls: list) -> Tools: + """The ten tools as a model is offered them (name, description, parameters from lib/service), with handlers that record the call.""" + def recorder(name): + async def handler(args, turn=None): + calls.append((name, args)) + return CANNED + return handler + return Tools([Tool(t.name, t.description, t.parameters, recorder(t.name)) for t in service_tools()]) + + +def service_system(now: datetime = NOW, instructions: str | None = None) -> str: + """The whole system prompt of a service run: the neutral line, and the date, time and zone now; with `instructions` (the server's, + service_instructions()), those after it, as a client that passes them on to its model would (docs/ecobot-mcp.md 3.2, 7).""" + system = f"{SERVICE_SYSTEM}\nNow: {now:%A} {now.day} {now:%B %Y}, {now:%H:%M} ({NOW_TZ} time)." + return f"{system}\n\n{instructions}" if instructions else system + + +def load_service_cases(path: Path = SERVICE_CASES) -> dict[str, dict]: + """{case id: its expectation in service terms ({"tools", "any_tools", "not_tools", "first_tool", "args", "note"})}.""" + return json.loads(path.read_text()) + + +def _resolved(names) -> list[str] | str: + """The service names these readings stand for (lib/service/names.py; ":rating" set aside), or why they can't be read.""" + from lib.service.names import CATALOGUE, UnknownReading + words = [names] if isinstance(names, str) else names + if not isinstance(words, list): + return f"{names!r} is not a reading or a list of them" + try: + return [r.name for r in CATALOGUE.resolve([str(w).split(":", 1)[0] for w in words], default=None)] + except UnknownReading as e: + return f"{names!r}: {e.message}" + + +def _reads(actual, want: dict) -> str | None: + """{"reads": [names]}: the readings sent stand for every one of these; {"reads_any": [names]}: for at least one; "not": [names]: for + none of these. What was sent is read as the service reads it (names or words).""" + if actual in (None, "", []): + return "no readings sent" + got = _resolved(actual) + if isinstance(got, str): + return got + if need := [n for n in want.get("reads", []) if n not in got]: + return f"{actual!r} ({', '.join(got)}) lacks {', '.join(need)}" + if "reads_any" in want and not set(want["reads_any"]) & set(got): + return f"{actual!r} ({', '.join(got)}) has none of {', '.join(want['reads_any'])}" + if extra := [n for n in want.get("not", []) if n in got]: + return f"{actual!r} ({', '.join(got)}) should not have {', '.join(extra)}" + return None + + +FIRST_HELD = date(2022, 10, 1) # where "on record" starts when a case's period is read (the station's record, as the cases have it) + + +WHOLE_DAY_TOOLS = {"days", "relate", "scan"} # the tools that read a period as whole days to yesterday (read_period's whole_days) + + +def _period_span(period, start=None, end=None, whole_days: bool = False) -> tuple | str: + """(start, end) of a `period` in words, or of `start` and `end`, as the service reads them at NOW in the station's zone + (lib/periods_text.py; whole_days as a whole-day tool reads them), or why they can't be read.""" + from zoneinfo import ZoneInfo + + from lib.periods_text import PeriodError, read_period + if period is not None and (not isinstance(period, str) or not period.strip()): + return f"{period!r} is not a period in words" + if period is None and start in (None, ""): + return "no period sent (neither `period` nor `start`)" + what = repr(period) if period is not None else f"start {start!r}" + (f", end {end!r}" if end else "") + try: + p = read_period(period, start, end, now=NOW.replace(tzinfo=ZoneInfo(NOW_TZ)), tz=ZoneInfo(NOW_TZ), default="today", + whole_days=whole_days, first_held=FIRST_HELD) + except PeriodError as e: + return f"{what} can't be read: {e.message.split('. ')[0]}" + return p.start, p.end + + +def _disagree(sent: dict, tool: str | None) -> str | None: + """Why `period` with `start`/`end` beside it is refused as `tool` reads them at NOW (common.read_period): dates that read as + another span than the period's, or a period that can't be read; None when the period is read (the dates junk or the same span).""" + from zoneinfo import ZoneInfo + + from lib.service.common import Refusal, read_period + try: + read_period(sent, tz=ZoneInfo(NOW_TZ), now=NOW.replace(tzinfo=ZoneInfo(NOW_TZ)), default="today", + whole_days=tool in WHOLE_DAY_TOOLS, first_held=FIRST_HELD) + except Refusal as e: + return f"`period` with `start`/`end` beside it is refused: {e.message.split(chr(10))[0]}" + return None + + +def _means(sent, refs, tool: str | None = None) -> str | None: + """{"means": words or [words]}: the period sent ({"period", "start", "end"} of the call; a bare value is a `period`) reads, at NOW, + as the same span as (one of) these words (a period in words as words; start and end as `tool` reads them, whole days for + WHOLE_DAY_TOOLS): "past week", "this week" and + "7d" are the same period, "last week" is another; to days, start "2026-09-01" is "September" (to yesterday).""" + sent = sent if isinstance(sent, dict) else {"period": sent} + if sent.get("period") is not None and str(sent["period"]).strip() == "": + sent = {**sent, "period": None} + if sent.get("period") is not None: # beside start and end, the period is read if they are junk or the same span (common.read_period) + if any(str(sent.get(k) or "").strip() for k in ("start", "end")) and (why := _disagree(sent, tool)): + return why + sent = {"period": sent["period"]} + # words are compared as words (whole days would make "last 28 days" September on the 29th); dates as the tool reads them + whole = tool in WHOLE_DAY_TOOLS and sent.get("period") is None + got = _period_span(sent.get("period"), sent.get("start"), sent.get("end"), whole) + if isinstance(got, str): + return got + refs = refs if isinstance(refs, list) else [refs] + if any(_period_span(r, whole_days=whole) == got for r in refs): + return None + what = repr(sent["period"]) if sent.get("period") is not None else f"start {sent.get('start')!r}, end {sent.get('end')!r}" + return f"{what} ({got[0]:%a %d %b %Y %H:%M} to {got[1]:%a %d %b %Y %H:%M}) is not the period of {' or '.join(map(repr, refs))}" + + +def _op(op) -> str: + """An op as lib/service/days.py reads it (OP_WORDS: "≥" and "=>" are ">=").""" + from lib.service.days import OP_WORDS + return OP_WORDS.get(str(op).strip(), str(op).strip()) + + +def _number(value) -> float | None: + """A condition's value as days.py reads it (a number, or a string of one), else None.""" + if isinstance(value, str): + try: + value = float(value) + except ValueError: + return None + return None if isinstance(value, bool) or not isinstance(value, int | float) else float(value) + + +def _condition_fails(c, want: dict) -> str | None: + if not isinstance(c, dict): + return f"{c!r} is not a condition" + fields = want["field"] if isinstance(want["field"], list) else [want["field"]] + ops = [_op(o) for o in (want["op"] if isinstance(want.get("op"), list) else [want["op"]] if "op" in want else [])] + if str(c.get("field", "")).strip() not in fields: + return f"field {c.get('field')!r} is not {' or '.join(fields)}" + if ops and _op(c.get("op")) not in ops: + return f"op {c.get('op')!r} is not {' or '.join(ops)}" + if (n := _number(c.get("value"))) is None: + return f"value {c.get('value')!r} is not a number" + if "value" in want and n != float(want["value"]): + return f"value {c.get('value')!r} is not {want['value']:g}" + return None + + +def _conditions(actual, want: list[dict]) -> str | None: + """{"conditions": [{"field": name or [names], "op": [ops], "value": number}]}: the `where` sent (a list of conditions, or one) is + these conditions, each once, in any order, compared by their keys as days.py reads them: a value as a number (9, 9.0 and "9" are + the same), an op by its meaning (">=", "≥", "=>"), any other key ignored. With no "op" any op will do, with no "value" any number.""" + sent = [actual] if isinstance(actual, dict) else actual + if not isinstance(sent, list): + return f"{actual!r} is not a list of conditions" + left = list(sent) + for w in want: + hit = next((c for c in left if _condition_fails(c, w) is None), None) + if hit is None: + why = "; ".join(f"{c!r}: {_condition_fails(c, w)}" for c in left) or "none left" + return f"no condition on {w['field']} as {w} ({why})" + left.remove(hit) + return f"conditions not asked for: {left!r}" if left else None + + +def _example_conditions(want: list[dict]) -> list[dict]: + return [{"field": w["field"][0] if isinstance(w["field"], list) else w["field"], + "op": (w["op"][0] if isinstance(w["op"], list) else w["op"]) if "op" in w else ">=", "value": w.get("value", 1)} for w in want] + + +ABSENT = object() # (example_value: the argument is best left out) + + +def example_value(want): + """A concrete value that satisfies `want` (_matches), to call the tool with: a matcher's own "e.g.", else the first of any_of / + one_of, the names of reads / has, the conditions given; ABSENT where the argument is best left out.""" + if not isinstance(want, dict): + return want + if "e.g." in want: + return want["e.g."] + if "absent" in want: + return ABSENT + for key in ("one_of", "any_of"): + if key in want: + return ABSENT if want[key][0] is None else want[key][0] + if "reads" in want or "reads_any" in want: + return list(want.get("reads") or want["reads_any"][:1]) + if "means" in want: + return want["means"][0] if isinstance(want["means"], list) else want["means"] + if "conditions" in want: + return _example_conditions(want["conditions"]) + if "has" in want: + return list(want["has"]) + raise ValueError(f"no example for {want!r}: give it an \"e.g.\"") + + +def expected_tools(expect: dict) -> list[str]: + """The tools an expectation would have called (tools, any_tools, first_tool, and those it gives arguments for), each once.""" + return list(dict.fromkeys([*expect.get("tools", []), *expect.get("any_tools", []), + *([expect["first_tool"]] if "first_tool" in expect else []), *expect.get("args", {})])) + + +def example_calls(expect: dict) -> list[tuple[str, dict]]: + """Every call a service expectation describes, made concrete: (tool, arguments) for each tool and each alternative of its arguments + (example_value); a tool expected with no arguments named is called with {}.""" + out = [] + for tool in expected_tools(expect): + want = expect.get("args", {}).get(tool, {}) + for alternative in (want if isinstance(want, list) else [want]): + out.append((tool, {k: v for k, w in alternative.items() if (v := example_value(w)) is not ABSENT})) + return out + + +def service_problems(expect: dict | None) -> list[str]: + """What is wrong with a case's service expectation itself (no model): missing, an unknown key or tool, an argument the tool doesn't + take, an example that doesn't satisfy its own matcher.""" + if expect is None: + return ["no service expectation (tests/evals/service_cases.json)"] + fails = [f"unknown keys {sorted(extra)}"] if (extra := set(expect) - EXPECT_KEYS) else [] + tools = {t.name: t for t in service_tools()} + fails += [f"unknown tool {n!r}" for n in dict.fromkeys([*expected_tools(expect), *expect.get("not_tools", [])]) if n not in tools] + for tool, want in expect.get("args", {}).items(): + known = tools[tool].parameters.get("properties", {}) if tool in tools else {} + for alternative in (want if isinstance(want, list) else [want]): + fails += [f"{tool} takes no argument {k!r}" for k in alternative if tool in tools and k not in known] + for k, w in alternative.items(): + try: + v = example_value(w) + except ValueError as e: + fails.append(f"{tool}.{k}: {e}") + continue + if v is not ABSENT and (why := _matches(v, w, {k: v}, tool)): + fails.append(f"{tool}.{k}: its example doesn't satisfy it ({why})") + return fails + + +async def run_live_service(case: Case, client, model: str, effort: str | None = None, + instructions: str | None = None) -> tuple[list[tuple[str, dict]], str]: + """Ask the model with the ten tools alone and the neutral system line (with `instructions` after it, when given); returns the tool + calls it made and its final reply. It may answer with no tool at all (tool_choice auto): a plain client forces nothing.""" calls: list[tuple[str, dict]] = [] - text = case.ask - r = intent.read(text, NOW, EVERY_SOURCE) - system = prompt.build(NOW, {"Ecowitt": "Ecowitt weather station", "AirGradient": "AirGradient outdoor air-quality sensor", - "Pollen": "Melbourne pollen forecast and thunderstorm asthma risk (melbournepollen.com.au)", - "Forecast": "Weather forecast for the owner's location (Open-Meteo)"}, - r.hints, r.about_the_bot, r.rain_caption, intent.topics(content(case), [m["content"] for m in case.history if m["role"] == "user"][-2:])) - fast = r.fast messages = [*case.history, {"role": "user", "content": content(case)}] - reply = await Agent(client, model, make_tools(calls)).run( - messages, system, effort or r.effort, first_call=[*([fast[:2], *r.more] if fast else []), *r.extra] or None, - tool_choice=r.tool_choice) - if fast or r.extra: - calls[0:0] = [*([(fast[0], fast[1]), *r.more] if fast else []), *r.extra] # the bot ran them itself, before the model + reply = await Agent(client, model, make_service_tools(calls)).run(messages, service_system(instructions=instructions), + effort or SERVICE_EFFORT, tool_choice="auto") return calls, reply + + +def calls_text(calls: list[tuple[str, dict]]) -> str: + """The calls a model made, one line: `days {"sort_by": "rain"}; pollen {}`.""" + return "; ".join(f"{n} {json.dumps(a, ensure_ascii=False)}" for n, a in calls) or "nothing" + + +def check_turn(turn: LiveTurn, expect: dict) -> list[str]: + """Failures of a bot-mode turn (run_live) against the case's expectation, over the whole turn: the expected tools and arguments are + met by any call that was not refused (a refused call later corrected passes; a refused one alone meets nothing), not_tools hold for every call, refused or not; and the turn fails if it + made more than MAX_CALLS calls (it ran away), if its reply is empty or the Agent's fallback (lib/llm.py FALLBACK: the model's last + answer was empty), or if a refused call was left uncorrected (LiveTurn.uncorrected): no call to the same tool was answered in a + later step (one answered in the same step was made with it, and one to another tool answers something else, so neither corrects it).""" + from lib.llm import FALLBACK + fails = [f"ran away: {len(turn.calls)} calls (more than {MAX_CALLS})"] if len(turn.calls) > MAX_CALLS else [] + fails += check_calls(turn.answered(), {k: v for k, v in expect.items() if k != "not_tools"}) + fails += check_calls(turn.calls, {"not_tools": expect.get("not_tools", [])}) + if not turn.reply.strip(): + fails.append("the reply is empty") + elif turn.reply.strip() == FALLBACK: + fails.append("the reply is the Agent's fallback (the model's last answer was empty)") + if left := turn.uncorrected(): + fails.append(f"a refused call was not corrected ({calls_text(left)}): no call to the same tool answered in a later step") + return fails + + +async def run_service(cases: list[Case], expectations: dict[str, dict], client=None, model: str = "", *, repeat: int = 1, + effort: str | None = None, instructions: str | None = None, bot: bool = False, world=None, out=print) -> int: + """The service's evals: each case's expectation checked (service_problems) and, with a client, the model asked `repeat` times and + its calls scored against it. Without `bot`: the ten tools alone (and the server's `instructions`, when given), every call answered + CANNED ("no data"), so the model may call again or reply as it likes (lib/llm.py's loop, up to its MAX_STEPS) and every call of the + turn is scored (check_calls: what the descriptions lead to, with nothing real to react to). With `bot`: as the bot asks (run_live), + each run of each case over its own fresh tools from `world` (evalworld.World.fresh: a new copy of the frozen world's archive) when + given, and scored over the whole turn (check_turn: the reply too); each run's calls, refusals and the reply's start are printed + under the case. Prints a line per case (`out`), with the calls of a run that fails; returns how many cases fail.""" + failed = 0 + for case in cases: + expect = expectations.get(case.id) + problems = service_problems(expect) + line, runs = "ok" if not problems else "FAIL", [] + if client and not problems: + passes = 0 + for _ in range(repeat): + if bot: + if world is not None: + async with world.fresh() as service: + turn = await run_live(case, client, model, effort, service) + else: + turn = await run_live(case, client, model, effort) + calls = turn.calls + runs.append(turn.line()) + why = check_turn(turn, expect) + else: + calls, _reply = await run_live_service(case, client, model, effort, instructions) + why = check_calls(calls, expect) + passes += not why + problems += [*(f" run: {w}" for w in why[:3]), f" called: {calls_text(calls)}"] if why else [] + line = f"{passes}/{repeat}" + ("" if passes == repeat else " FAIL") + out(f"{line:>10} {case.id} ({case.ask})") + for p in [*runs, *problems]: + out(f" {p}") + failed += bool(problems) + what = "the bot's prompt and the ten tools" if bot else f"the service's ten tools alone{', with its instructions' if instructions else ''}" + if client: + out(f"\nmodel: {model}") + out(f"\n{len(cases) - failed} of {len(cases)} cases pass ({what})") + return failed diff --git a/tests/evals/cases.json b/tests/evals/cases.json index 5510a28b..f7e3d969 100644 --- a/tests/evals/cases.json +++ b/tests/evals/cases.json @@ -4,22 +4,7 @@ "ask": "average temp 3m", "note": "3m was read as 3 days", "expect": { - "hints": [ - "\"3m\" = last 3 months: 2026-07-01" - ], - "effort": "none", - "chart_fields": [], - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "start_date": { - "regex": "^2026-07-0[1-2]" - }, - "average": true - } - } + "effort": "none" }, "covers": [ "q:average", @@ -29,18 +14,9 @@ { "id": "3m-wind-chart", "ask": "wind direction plot 3m", - "note": "fast path: a plain wind chart request with a short-form period", - "expect": { - "fast": { - "tool": "weather_history", - "args": { - "groups": "wind", - "chart": true, - "start_date": { - "regex": "^2026-07-01" - } - } - } + "note": "a plain wind chart request with a short-form period (drawn in code with no model until step 6c: the model answers it now)", + "expect": { + "effort": "none" }, "covers": [ "m:wind-direction", @@ -52,18 +28,7 @@ "ask": "plot temperature and rain", "note": "only temperature was charted", "expect": { - "chart_fields": [ - "temperature", - "rain" - ], - "chart_in_code": true, - "fast": { - "tool": "weather_history", - "args": { - "groups": "rainfall,outdoor,indoor", - "chart": true - } - } + "effort": "none" }, "covers": [ "c:stack", @@ -76,10 +41,7 @@ "ask": "lowest and highest humidity", "note": "plotted temperature on a humidity question", "expect": { - "chart_field": "humidity", - "tools": [ - "weather_history" - ] + "effort": "none" }, "covers": [ "m:humidity", @@ -91,13 +53,7 @@ "ask": "Is there a correlation between pressure and rainfall", "note": "answered from monthly extremes", "expect": { - "effort": "medium", - "tools": [ - "weather_link" - ], - "not_tools": [ - "weather_days" - ] + "effort": "medium" }, "covers": [ "q:correlation", @@ -109,9 +65,7 @@ "id": "pressure-vs-rain-graph", "ask": "plot a graph of pressure against rainfall", "expect": { - "tools": [ - "weather_link" - ] + "effort": "none" }, "covers": [ "c:link", @@ -123,20 +77,7 @@ "id": "public-holidays", "ask": "hottest public holidays", "expect": { - "tools": [ - "weather_days" - ], - "args": { - "weather_days": { - "only": "public_holiday", - "sort_by": { - "any_of": [ - "temp_max", - null - ] - } - } - } + "effort": "none" }, "covers": [ "q:rank-days", @@ -147,21 +88,7 @@ "id": "hottest-day-that-rained", "ask": "what was the hottest day that also rained", "expect": { - "effort": "low", - "tools": [ - "weather_days" - ], - "args": { - "weather_days": { - "sort_by": "temp_max", - "order": { - "any_of": [ - "desc", - null - ] - } - } - } + "effort": "low" }, "covers": [ "q:rank-days", @@ -173,16 +100,7 @@ "id": "wind-direction-week", "ask": "most common wind direction this week", "expect": { - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "groups": { - "regex": "wind" - } - } - } + "effort": "none" }, "covers": [ "m:wind-direction" @@ -192,10 +110,7 @@ "id": "will-it-rain", "ask": "will it rain later?", "expect": { - "effort": "low", - "tools": [ - "weather_now" - ] + "effort": "low" }, "covers": [ "q:forecast", @@ -206,9 +121,7 @@ "id": "air-now", "ask": "how's the air?", "expect": { - "fast": { - "tool": "air_quality" - } + "effort": "none" }, "covers": [ "q:current", @@ -219,15 +132,7 @@ "id": "weather-week", "ask": "weather week", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "chart": true, - "start_date": { - "regex": "^2026-09-23" - } - } - } + "effort": "none" }, "covers": [ "q:summary", @@ -238,14 +143,7 @@ "id": "hello", "ask": "thanks, that's great", "expect": { - "fast": null, - "not_tools": [ - "weather_now", - "weather_history", - "weather_days", - "weather_link", - "air_quality" - ] + "effort": "none" }, "covers": [ "q:chat" @@ -255,15 +153,7 @@ "id": "chart-pm10-week", "ask": "chart PM10 from the past week", "expect": { - "fast": { - "tool": "air_quality", - "args": { - "chart": true, - "metrics": [ - "pm10" - ] - } - } + "effort": "none" }, "covers": [ "c:air-single", @@ -275,15 +165,7 @@ "ask": "weather 4 months", "note": "4 months was read as the last 7 days", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "chart": true, - "start_date": { - "regex": "^2026-05-31" - } - } - } + "effort": "none" }, "covers": [ "q:summary", @@ -295,13 +177,7 @@ "id": "chart-indoors", "ask": "chart the past week indoors", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "groups": "indoor", - "chart": true - } - } + "effort": "none" }, "covers": [ "c:line", @@ -311,19 +187,9 @@ { "id": "pressure-week", "ask": "pressure week", - "note": "a bare 'pressure week' is a chart of the pressure group, sent with no model call", - "expect": { - "fast": { - "tool": "weather_history", - "args": { - "groups": "pressure", - "chart": true - } - }, - "chart_field": "relative", - "hints": [ - "\"week\" = last 7 days" - ] + "note": "a bare 'pressure week' is a chart of the pressure group (sent with no model call until step 6c: the model answers it now)", + "expect": { + "effort": "none" }, "covers": [ "m:pressure", @@ -335,19 +201,7 @@ "ask": "wind 3m", "note": "wind 3m was read as 3 days; a bare reading and period is a chart", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "groups": "wind", - "chart": true, - "start_date": { - "regex": "^2026-07-0[1-2]" - } - } - }, - "hints": [ - "\"3m\" = last 3 months: 2026-07-01" - ] + "effort": "none" }, "covers": [ "m:wind-speed", @@ -358,20 +212,7 @@ "id": "hottest-weekends", "ask": "hottest weekends", "expect": { - "tools": [ - "weather_days" - ], - "args": { - "weather_days": { - "only": "weekend", - "sort_by": { - "any_of": [ - "temp_max", - null - ] - } - } - } + "effort": "none" }, "covers": [ "q:rank-days" @@ -381,17 +222,7 @@ "id": "windiest-day-on-record", "ask": "Windiest day on record", "expect": { - "hints": [ - "\"on record\" = on record" - ], - "tools": [ - "weather_days" - ], - "args": { - "weather_days": { - "sort_by": "wind_gust" - } - } + "effort": "none" }, "covers": [ "q:rank-days", @@ -403,17 +234,7 @@ "id": "rainy-days-in-september", "ask": "list rainy days in september", "expect": { - "tools": [ - "weather_days" - ], - "args": { - "weather_days": { - "start_date": "2026-09-01", - "where": { - "regex": "rain" - } - } - } + "effort": "none" }, "covers": [ "q:rank-days", @@ -425,23 +246,7 @@ "ask": "give me the outdoor high between 11am Fri 10 Nov 2023 and 11am Sat 11 Nov 2023", "note": "a particular window, not a whole period", "expect": { - "fast": null, - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "start_date": { - "regex": "^2023-11-10 11:00" - }, - "end_date": { - "regex": "^2023-11-11 11:00" - }, - "groups": { - "regex": "outdoor" - } - } - } + "effort": "none" }, "covers": [ "q:known-day", @@ -452,16 +257,7 @@ "id": "weather-on-june-11", "ask": "what kind of weather was June 11", "expect": { - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "start_date": { - "regex": "^2026-06-11" - } - } - } + "effort": "none" }, "covers": [ "q:describe-day" @@ -471,17 +267,7 @@ "id": "what-it-would-have-been-like", "ask": "what would it have been like if we were alive on Mon 10 Aug", "expect": { - "effort": "low", - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "start_date": { - "regex": "^2026-08-10" - } - } - } + "effort": "low" }, "covers": [ "q:describe-day" @@ -492,14 +278,7 @@ "ask": "add an alert for if winds reach 100 km hour", "note": "a request to change the bot, not for readings: it was forced to fetch the weather", "expect": { - "needs_data": false, - "not_tools": [ - "weather_now", - "weather_history", - "weather_days", - "weather_link", - "air_quality" - ] + "effort": "none" }, "covers": [ "q:command" @@ -509,15 +288,7 @@ "id": "metrics-bare", "ask": "metrics", "expect": { - "needs_data": false, - "about_the_bot": true, - "not_tools": [ - "weather_now", - "weather_history", - "weather_days", - "weather_link", - "air_quality" - ] + "effort": "none" }, "covers": [ "q:about-the-bot" @@ -527,16 +298,7 @@ "id": "most-rain-days-jja", "ask": "Days with most rain in June, July, August 2026", "expect": { - "tools": [ - "weather_days" - ], - "args": { - "weather_days": { - "sort_by": "rain", - "start_date": "2026-06-01", - "end_date": "2026-08-31" - } - } + "effort": "low" }, "covers": [ "q:rank-days", @@ -547,10 +309,7 @@ "id": "fastest-gust", "ask": "fastest gust recorded", "expect": { - "any_tools": [ - "weather_history", - "weather_days" - ] + "effort": "none" }, "covers": [ "q:record", @@ -561,12 +320,7 @@ "id": "chart-all-airgradient-week", "ask": "chart all airgradient past week", "expect": { - "fast": { - "tool": "air_quality", - "args": { - "chart": true - } - } + "effort": "none" }, "covers": [ "c:air-panels", @@ -578,24 +332,7 @@ "ask": "did it rain on Sat 5 Sep", "note": "one known day: its figures, not a search of the month", "expect": { - "any_tools": [ - "weather_days", - "weather_history" - ], - "args": { - "weather_days": { - "start_date": "2026-09-05", - "end_date": "2026-09-05" - }, - "weather_history": { - "start_date": { - "regex": "^2026-09-05" - }, - "end_date": { - "regex": "^2026-09-05" - } - } - } + "effort": "none" }, "covers": [ "q:known-day", @@ -617,16 +354,7 @@ ], "note": "a pushback: fetch again, don't defend or agree from memory", "expect": { - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "start_date": { - "regex": "^2026-09-23" - } - } - } + "effort": "none" }, "covers": [ "q:correction" @@ -646,19 +374,7 @@ } ], "expect": { - "hints": [ - "\"all time\" = on record" - ], - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "start_date": { - "regex": "^2022-10" - } - } - } + "effort": "none" }, "covers": [ "q:follow-up" @@ -669,20 +385,7 @@ "ask": "win direction 3 months", "note": "a typo: the model path handles it", "expect": { - "fast": null, - "hints": [ - "\"3 months\" = last 3 months: 2026-07-01" - ], - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "groups": { - "regex": "wind" - } - } - } + "effort": "none" }, "covers": [ "m:wind-direction" @@ -692,14 +395,7 @@ "id": "hottest-coldest-this-month", "ask": "hottest/coldest day this month", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "start_date": { - "regex": "^2026-09-01" - } - } - } + "effort": "none" }, "covers": [ "q:summary", @@ -710,14 +406,7 @@ "id": "high-low-all-time", "ask": "high and low all time", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "start_date": { - "regex": "^2022-10" - } - } - } + "effort": "none" }, "covers": [ "q:record", @@ -739,9 +428,7 @@ ], "note": "the resolution is chosen automatically and extremes are refined to 5-minute windows: fetch again and say so", "expect": { - "tools": [ - "weather_history" - ] + "effort": "none" }, "covers": [ "q:detail-level", @@ -754,17 +441,7 @@ "ask": "report", "note": "only the weather station was fetched; the older answer listed everything from both devices", "expect": { - "report": true, - "tools": [ - "weather_now", - "air_quality" - ], - "fast": { - "tool": "weather_now", - "args": { - "groups": "outdoor,indoor,pressure,wind,rainfall,solar_and_uvi" - } - } + "effort": "none" }, "covers": [ "q:report" @@ -773,10 +450,9 @@ { "id": "dashboard", "ask": "dashboard", - "note": "the station's gauges, drawn in code with no model; it used to mean the report", + "note": "the station's gauges were drawn in code with no model until the Telegram dashboard went (step 6): the model answers it now; it used to mean the report", "expect": { - "dashboard": true, - "report": false + "effort": "none" }, "covers": [ "q:dashboard" @@ -786,7 +462,7 @@ "id": "weather-report-for-a-day", "ask": "weather report for Tuesday", "expect": { - "report": false + "effort": "none" }, "covers": [ "q:summary" @@ -797,11 +473,7 @@ "ask": "Is there a correlation between air quality and precipitation", "note": "AirGradient and Ecowitt are separate tools: needs the cross-source link", "expect": { - "effort": "medium", - "fast": null, - "tools": [ - "air_link" - ] + "effort": "medium" }, "covers": [ "q:cross-source", @@ -814,10 +486,7 @@ "ask": "plot the traffic light rating of air quality against rainfall for the last 30 days", "note": "a new kind of chart: the rating over rain", "expect": { - "fast": null, - "tools": [ - "plot_chart" - ] + "effort": "none" }, "covers": [ "c:rating-strip", @@ -829,14 +498,7 @@ "ask": "Is there a correlation between air quality and other metrics", "note": "needs a scan of every pair, not one lookup", "expect": { - "effort": "medium", - "fast": null, - "tools": [ - "air_scan" - ], - "not_tools": [ - "air_link" - ] + "effort": "medium" }, "covers": [ "q:scan", @@ -848,15 +510,7 @@ "ask": "ecowitt week", "note": "ecowitt is a synonym of weather", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "chart": true, - "start_date": { - "regex": "^2026-09-23" - } - } - } + "effort": "none" }, "covers": [ "q:summary", @@ -868,12 +522,7 @@ "ask": "ag 7d", "note": "ag is a synonym of air quality", "expect": { - "fast": { - "tool": "air_quality", - "args": { - "chart": true - } - } + "effort": "none" }, "covers": [ "q:summary", @@ -885,10 +534,7 @@ "ask": "air gradient", "note": "air gradient is a synonym of air quality", "expect": { - "fast": { - "tool": "air_quality", - "args": {} - } + "effort": "none" }, "covers": [ "q:current", @@ -900,15 +546,7 @@ "ask": "ecowitt all week", "note": "every reading stacked (solar third, wind last), except UV, feels like and VPD (unless configured)", "expect": { - "chart_fields": [ - "temperature", - "humidity", - "solar", - "pressure", - "rain", - "dew_point", - "wind" - ] + "effort": "none" }, "covers": [ "q:summary", @@ -920,11 +558,7 @@ "ask": "sitrep", "note": "sitrep is a synonym of status: the full current report", "expect": { - "report": true, - "tools": [ - "weather_now", - "air_quality" - ] + "effort": "none" }, "covers": [ "q:report" @@ -935,10 +569,7 @@ "ask": "think: hottest day this week", "note": "asking to think gives medium reasoning to a lookup; the hottest day of a period with when it was is weather_history (a record), not weather_days", "expect": { - "effort": "medium", - "tools": [ - "weather_history" - ] + "effort": "medium" }, "covers": [ "q:record", @@ -950,16 +581,7 @@ "ask": "Rain chart 7d", "note": "the Rain chart button", "expect": { - "chart_field": "daily", - "rain_caption": true, - "chart_in_code": true, - "fast": { - "tool": "weather_history", - "args": { - "groups": "rainfall", - "chart": true - } - } + "effort": "none" }, "covers": [ "m:rain", @@ -971,15 +593,7 @@ "ask": "Humidity chart 7d", "note": "the Humidity chart button", "expect": { - "chart_field": "humidity", - "chart_in_code": true, - "fast": { - "tool": "weather_history", - "args": { - "groups": "outdoor,indoor", - "chart": true - } - } + "effort": "none" }, "covers": [ "m:humidity", @@ -991,12 +605,7 @@ "ask": "AQ all week", "note": "the AQ all week button", "expect": { - "fast": { - "tool": "air_quality", - "args": { - "chart": true - } - } + "effort": "none" }, "covers": [ "c:air-panels", @@ -1008,13 +617,7 @@ "ask": "weather now", "note": "every reading the station has, in the report's layout", "expect": { - "fast": { - "tool": "weather_now", - "args": { - "groups": "outdoor,indoor,pressure,wind,rainfall,solar_and_uvi" - } - }, - "weather_now": true + "effort": "none" }, "covers": [ "q:report", @@ -1026,9 +629,7 @@ "ask": "pollen", "note": "pollen and thunderstorm asthma are fetched without the model", "expect": { - "fast": { - "tool": "pollen_asthma" - } + "effort": "none" }, "covers": [ "q:pollen" @@ -1039,10 +640,7 @@ "ask": "is the pollen bad today?", "note": "a plain pollen question is answered in code", "expect": { - "fast": { - "tool": "pollen_asthma" - }, - "lookup": "pollen" + "effort": "none" }, "covers": [ "q:pollen" @@ -1053,11 +651,7 @@ "ask": "what's the forecast for tomorrow?", "note": "the forecast tool, not the station's own pressure trend", "expect": { - "fast": null, - "needs_data": true, - "tools": [ - "weather_forecast" - ] + "effort": "low" }, "covers": [ "q:forecast" @@ -1068,7 +662,6 @@ "ask": "what do you think of weather in general, from a philosophical perspective?", "note": "an opinion, not a lookup: no tool is forced (the model still thinks a little)", "expect": { - "needs_data": false, "effort": "medium" }, "covers": [ @@ -1080,7 +673,7 @@ "ask": "only that it's cold", "note": "a chat reply, not a request: it replaced the bot's answer with the temperatures", "expect": { - "needs_data": false + "effort": "none" }, "covers": [ "q:chat" @@ -1091,11 +684,7 @@ "ask": "how cold is it", "note": "a plain current-temperature question", "expect": { - "needs_data": true, - "any_tools": [ - "weather_now", - "weather_history" - ] + "effort": "none" }, "covers": [ "q:current", @@ -1107,7 +696,7 @@ "ask": "ok now what?", "note": "'now' alone is not a weather question", "expect": { - "needs_data": false + "effort": "none" }, "covers": [ "q:chat" @@ -1118,7 +707,7 @@ "ask": "plot rain this week and will it rain tomorrow", "note": "a forecast question goes to the model", "expect": { - "chart_in_code": false + "effort": "low" } }, { @@ -1126,7 +715,7 @@ "ask": "graph humidity and say if it relates to rain", "note": "correlation goes to the model", "expect": { - "chart_in_code": false + "effort": "medium" } }, { @@ -1134,14 +723,7 @@ "ask": "pressure graph 30d", "note": "a plain chart of a named reading", "expect": { - "chart_in_code": true, - "fast": { - "tool": "weather_history", - "args": { - "groups": "pressure", - "chart": true - } - } + "effort": "none" } }, { @@ -1149,35 +731,35 @@ "ask": "how hot is it", "note": "a plain reading question", "expect": { - "lookup": "reading" + "effort": "none" } }, { "id": "lookup-raining", "ask": "is it raining", "expect": { - "lookup": "reading" + "effort": "none" } }, { "id": "lookup-air", "ask": "how's the air", "expect": { - "lookup": "air" + "effort": "none" } }, { "id": "lookup-forecast", "ask": "forecast", "expect": { - "lookup": "forecast" + "effort": "low" } }, { "id": "lookup-about", "ask": "what can you do", "expect": { - "lookup": "about" + "effort": "none" } }, { @@ -1185,7 +767,7 @@ "ask": "is it too cold to run", "note": "judgement stays with the model", "expect": { - "lookup": "" + "effort": "none" } }, { @@ -1193,14 +775,14 @@ "ask": "hottest today", "note": "highs and lows of a short period", "expect": { - "lookup": "extremes" + "effort": "none" } }, { "id": "lookup-hottest-vs", "ask": "is today hotter than yesterday", "expect": { - "lookup": "" + "effort": "none" } }, { @@ -1208,21 +790,14 @@ "ask": "average temp yesterday", "note": "a plain average is answered in code", "expect": { - "lookup": "extremes", - "fast": { - "tool": "weather_history", - "args": { - "average": true, - "chart": false - } - } + "effort": "none" } }, { "id": "highest-humidity-yesterday", "ask": "highest humidity yesterday", "expect": { - "lookup": "extremes" + "effort": "none" } }, { @@ -1230,7 +805,7 @@ "ask": "will the pollen be bad tomorrow", "note": "looking ahead stays with the model", "expect": { - "lookup": "" + "effort": "low" } }, { @@ -1238,7 +813,7 @@ "ask": "average rain last week", "note": "a rain total has no average: the model explains", "expect": { - "lookup": "" + "effort": "none" } }, { @@ -1246,13 +821,7 @@ "ask": "how many times was UV 9 or more in the past two years?", "note": "counted in code: one reading against one limit", "expect": { - "lookup": "days", - "fast": { - "tool": "weather_days", - "args": { - "count_only": true - } - } + "effort": "none" } }, { @@ -1260,14 +829,7 @@ "ask": "days over UVI 10 per year", "note": "counted in code: one reading against one limit", "expect": { - "lookup": "days", - "fast": { - "tool": "weather_days", - "args": { - "count_only": true, - "group_by": "year" - } - } + "effort": "none" } }, { @@ -1275,16 +837,7 @@ "ask": "rain total per month this year", "note": "a total per month is counted in code and drawn as bars", "expect": { - "lookup": "days", - "fast": { - "tool": "weather_days", - "args": { - "stat": "sum", - "of": "rain", - "group_by": "month", - "count_only": true - } - } + "effort": "none" } }, { @@ -1292,16 +845,7 @@ "ask": "hottest day each year", "note": "the highest daily maximum per year is counted in code and drawn as bars", "expect": { - "lookup": "days", - "fast": { - "tool": "weather_days", - "args": { - "stat": "max", - "of": "temp_max", - "group_by": "year", - "count_only": true - } - } + "effort": "none" } }, { @@ -1309,14 +853,7 @@ "ask": "days PM2.5 over 25 per year", "note": "counted in code: one reading against one limit", "expect": { - "lookup": "days", - "fast": { - "tool": "air_days", - "args": { - "count_only": true, - "group_by": "year" - } - } + "effort": "none" } }, { @@ -1324,14 +861,7 @@ "ask": "count days over PM2.5 of 90 per year", "note": "counted in code: one reading against one limit", "expect": { - "lookup": "days", - "fast": { - "tool": "air_days", - "args": { - "count_only": true, - "group_by": "year" - } - } + "effort": "none" } }, { @@ -1339,31 +869,14 @@ "ask": "days over UVI 10 by year", "note": "the model once answered with one overall count and no chart; now counted in code, per year, whole record", "expect": { - "lookup": "days", - "fast": { - "tool": "weather_days", - "args": { - "group_by": "year", - "count_only": true, - "where": { - "has": [ - { - "field": "uv_max", - "op": ">=", - "value": 10 - } - ] - } - } - } + "effort": "none" } }, { "id": "days-two-readings-go-to-the-model", "ask": "days over 35 and also rained", "expect": { - "lookup": "", - "fast": null + "effort": "low" } }, { @@ -1371,56 +884,28 @@ "ask": "rain by month for 2 years", "note": "the model answered with monthly text under a chart of daily bars: now monthly bars, one per line", "expect": { - "lookup": "days", - "fast": { - "tool": "weather_days", - "args": { - "stat": "sum", - "of": "rain", - "group_by": "month", - "start_date": { - "regex": "^2024-(09|10)-" - } - } - } + "effort": "none" } }, { "id": "avg-temp-per-year", "ask": "average temperature per year", "expect": { - "lookup": "days", - "fast": { - "tool": "weather_days", - "args": { - "stat": "avg", - "of": "temp_avg", - "group_by": "year" - } - } + "effort": "none" } }, { "id": "highest-pm25-by-month", "ask": "highest PM2.5 by month", "expect": { - "lookup": "days", - "fast": { - "tool": "air_days", - "args": { - "stat": "max", - "of": "pm2_5_max", - "group_by": "month" - } - } + "effort": "none" } }, { "id": "two-readings-by-month-go-to-the-model", "ask": "pm2.5 and co2 by month", "expect": { - "lookup": "", - "fast": null + "effort": "none" } }, { @@ -1428,15 +913,7 @@ "ask": "weather chart 90d", "note": "a chart naming no reading is every reading, a panel each", "expect": { - "chart_fields": [ - "temperature", - "humidity", - "solar", - "pressure", - "rain", - "dew_point", - "wind" - ] + "effort": "none" }, "covers": [ "c:line", @@ -1448,15 +925,7 @@ "ask": "chart all 90d", "note": "a chart naming no reading is every reading, a panel each", "expect": { - "chart_fields": [ - "temperature", - "humidity", - "solar", - "pressure", - "rain", - "dew_point", - "wind" - ] + "effort": "none" }, "covers": [ "c:line", @@ -1468,19 +937,7 @@ "ask": "graph combine uvi and solar radiation on two axis", "note": "two readings with different scales on one panel: fast path, drawn in code with the second on a right-hand axis", "expect": { - "chart_fields": [ - "uv", - "solar" - ], - "two_axes": true, - "chart_in_code": true, - "fast": { - "tool": "weather_history", - "args": { - "chart": true, - "groups": "solar_and_uvi" - } - } + "effort": "none" }, "covers": [ "c:two-axes" @@ -1491,8 +948,7 @@ "ask": "plot airgradient humidity over ecowitt outdoor humidity", "note": "the air sensor's own humidity is offered to the model only when the AirGradient is named with it; the chart is the model's (plot_chart)", "expect": { - "air_extra": true, - "fast": null + "effort": "none" }, "covers": [] }, @@ -1501,27 +957,7 @@ "ask": "What was the humidity each hour for the last 5 hours", "note": "the bot said its tool only gave extremes: the readings tool gives a value per hour", "expect": { - "fast": null, - "hints": [ - "\"5 hours\" = last 5 hours" - ], - "tools": [ - "readings" - ], - "not_tools": [ - "weather_history" - ], - "args": { - "readings": { - "metric": { - "regex": "humidity$" - }, - "interval": "1hour", - "start": { - "regex": "^2026-09-29 (08|09)" - } - } - } + "effort": "none" }, "covers": [ "q:interval", @@ -1533,25 +969,116 @@ "ask": "temperature every 30 minutes today", "note": "took the fast path to a highs-and-lows summary of today", "expect": { - "fast": null, - "tools": [ - "readings" - ], - "args": { - "readings": { - "metric": { - "regex": "temperature$" - }, - "interval": "30min", - "start": { - "regex": "^2026-09-29 00:00" - } - } - } + "effort": "none" }, "covers": [ "q:interval", "m:temperature" ] + }, + { + "id": "chart-only-answers-itself", + "ask": "plot pressure since Sunday", + "note": "only the chart is asked for: the model says so (chart_answers_it) and the bot sends the chart with its caption written in code, with no second model call (every typed request goes to the model since step 6c)", + "expect": { + "effort": "none" + }, + "covers": [ + "q:chart-only", + "m:pressure" + ] + }, + { + "id": "chart-and-a-question", + "ask": "plot pressure since Sunday, is a storm coming?", + "note": "the chart and something else to answer: the model writes the reply, so chart_answers_it stays unset", + "expect": { + "effort": "low" + }, + "covers": [ + "q:chart-only", + "m:pressure" + ] + }, + { + "id": "prompt-now", + "ask": "How is it outside now?", + "note": "ecobot-mcp's now prompt, as the bot's /now command (and the 📋 Now's question) asks the model", + "expect": { + "effort": "none" + }, + "covers": [ + "q:current", + "m:temperature" + ] + }, + { + "id": "prompt-report", + "ask": "Give me a report: the readings now, today's forecast and the pollen.", + "note": "ecobot-mcp's report prompt, as the bot's /report command asks the model (the Status button is the report written in code, no model)", + "expect": { + "effort": "low" + }, + "covers": [ + "q:report" + ] + }, + { + "id": "prompt-will-it-rain", + "ask": "Will it rain in the next few hours?", + "note": "ecobot-mcp's will_it_rain prompt, as the bot's /will_it_rain command (and any client) asks the model", + "expect": { + "effort": "low" + }, + "covers": [ + "q:forecast", + "m:rain" + ] + }, + { + "id": "prompt-weather-chart", + "ask": "Chart every weather reading, a panel each, over 7d.", + "note": "ecobot-mcp's weather_chart prompt, as the bot's /weather_chart command (and \"/weather_chart 7d\") asks the model", + "expect": { + "effort": "none" + }, + "covers": [ + "q:summary", + "m:temperature" + ] + }, + { + "id": "prompt-chart", + "ask": "Chart rain over 7d.", + "note": "ecobot-mcp's chart prompt, as the bot's /chart command (and \"/chart rain 7d\") asks the model", + "expect": { + "effort": "none" + }, + "covers": [ + "m:rain", + "c:line" + ] + }, + { + "id": "prompt-rainfall", + "ask": "How much rain fell over last week?", + "note": "ecobot-mcp's rainfall prompt, as the bot's /rainfall command (and \"/rainfall last week\") asks the model", + "expect": { + "effort": "none" + }, + "covers": [ + "m:rain" + ] + }, + { + "id": "prompt-air", + "ask": "How was the air quality over 7d?", + "note": "ecobot-mcp's air prompt, as the bot's /air command (and \"/air 7d\") asks the model", + "expect": { + "effort": "none" + }, + "covers": [ + "m:air-quality" + ] } ] diff --git a/tests/evals/service_cases.json b/tests/evals/service_cases.json new file mode 100644 index 00000000..60b9cb12 --- /dev/null +++ b/tests/evals/service_cases.json @@ -0,0 +1,2223 @@ +{ + "3m-average": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "outdoor.temperature" + ] + }, + "period": { + "means": "3m" + }, + "average": true + } + }, + "note": "an average over a period is summary's `average`; 3m is the last 3 months, passed as said" + }, + "3m-wind-chart": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "wind.wind_direction" + ] + }, + "period": { + "means": "3m" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "a chart over time is summary's; wind direction draws the compass rose" + }, + "temperature-and-rain": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "outdoor.temperature", + "rainfall.rain" + ] + }, + "chart": true + }, + { + "chart_readings": { + "reads": [ + "outdoor.temperature", + "rainfall.rain" + ] + }, + "chart": true + } + ] + }, + "note": "both readings drawn, a panel each (the bot once drew only temperature); no period: a chart's default, the last 24 hours" + }, + "humidity-chart": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "outdoor.humidity" + ], + "not": [ + "outdoor.temperature" + ] + } + } + }, + "note": "the lowest and highest of a period are summary's; only humidity (the bot once charted temperature)" + }, + "pressure-rain-correlation": { + "tools": [ + "relate" + ], + "not_tools": [ + "days" + ], + "args": { + "relate": { + "reading": { + "reads": [ + "pressure.relative" + ], + "optional": true + } + } + }, + "note": "\"X against rain\" is relate (pressure is its default), not monthly extremes" + }, + "pressure-vs-rain-graph": { + "tools": [ + "relate" + ], + "args": { + "relate": { + "reading": { + "reads": [ + "pressure.relative" + ], + "optional": true + }, + "chart": true + } + }, + "note": "a chart of a reading against rain is relate's, with chart" + }, + "public-holidays": { + "tools": [ + "days" + ], + "args": { + "days": { + "only": "public_holiday", + "sort_by": { + "one_of": [ + "temp_max", + null + ] + } + } + }, + "note": "days filtered to public holidays and ranked; no period: every day on record" + }, + "hottest-day-that-rained": { + "tools": [ + "days" + ], + "args": { + "days": { + "sort_by": "temp_max", + "order": { + "one_of": [ + "desc", + null + ] + }, + "where": { + "conditions": [ + { + "field": "rain", + "op": [ + ">=", + ">" + ] + } + ] + } + } + }, + "note": "a condition on one figure and a ranking on another is days (a rainy day is rain >= 1)" + }, + "wind-direction-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "wind.wind_direction" + ] + }, + "period": { + "means": "this week" + } + } + }, + "note": "the most common direction of a period is summary's wind direction" + }, + "will-it-rain": { + "tools": [ + "outlook" + ], + "note": "will it rain in the next few hours is outlook" + }, + "air-now": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads": [ + "air.pm2_5" + ], + "optional": true + } + } + }, + "note": "the air now is current; with no readings named it gives everything, the air included" + }, + "weather-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "a bare reading and a period is a chart over the period; \"weather\" is every station reading" + }, + "hello": { + "not_tools": [ + "current", + "summary", + "readings", + "days", + "relate", + "scan", + "outlook", + "forecast", + "pollen", + "about" + ], + "note": "thanks: no tool" + }, + "chart-pm10-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "air.pm10" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "an air chart is summary's like any other" + }, + "weather-4-months": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "4m" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "4 months, passed as said (the bot once read it as 7 days)" + }, + "chart-indoors": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "indoor.temperature" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "chart_readings": { + "reads": [ + "indoor.temperature" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "indoor is the indoor set (temperature and humidity)" + }, + "pressure-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "pressure.relative" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "a bare reading and a period: summary, which charts a week by default" + }, + "wind-3m": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "wind.wind_speed" + ] + }, + "period": { + "means": "3m" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "3m is 3 months (the bot once read it as 3 days)" + }, + "hottest-weekends": { + "tools": [ + "days" + ], + "args": { + "days": { + "only": "weekend", + "sort_by": { + "one_of": [ + "temp_max", + null + ] + } + } + }, + "note": "days filtered to weekends and ranked" + }, + "windiest-day-on-record": { + "tools": [ + "days" + ], + "args": { + "days": { + "sort_by": "wind_gust", + "period": { + "means": "on record", + "optional": true + } + } + }, + "note": "the windiest day is days ranked by the highest gust; no period is every day on record" + }, + "rainy-days-in-september": { + "tools": [ + "days" + ], + "args": { + "days": { + "where": { + "conditions": [ + { + "field": "rain", + "op": [ + ">=", + ">" + ] + } + ] + }, + "period": { + "means": "September" + } + } + }, + "note": "days found by a condition, over September (this month: to yesterday)" + }, + "a-day-in-2023": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "outdoor.temperature" + ] + }, + "start": { + "regex": "^2023-11-10 11:00", + "e.g.": "2023-11-10 11:00" + }, + "end": { + "regex": "^2023-11-11 11:00", + "e.g.": "2023-11-11 11:00" + } + } + }, + "note": "a window with times is start and end, never a period" + }, + "weather-on-june-11": { + "any_tools": [ + "summary", + "days" + ], + "args": { + "summary": { + "period": { + "means": "11 June" + } + }, + "days": { + "period": { + "means": "11 June" + } + } + }, + "note": "one known day: its figures and its look (summary), or its day row (days {period: \"5 Sep\"})" + }, + "what-it-would-have-been-like": { + "any_tools": [ + "summary", + "days" + ], + "args": { + "summary": { + "period": { + "means": "10 Aug" + } + }, + "days": { + "period": { + "means": "10 Aug" + } + } + }, + "note": "a hypothetical about one day: that day's figures" + }, + "add-an-alert": { + "tools": [ + "about" + ], + "not_tools": [ + "current", + "summary", + "readings", + "days", + "relate", + "scan", + "outlook", + "forecast", + "pollen" + ], + "note": "alerts can't be added by asking: about lists those there are, with their thresholds" + }, + "metrics-bare": { + "any_tools": [ + "about", + "current" + ], + "not_tools": [ + "summary", + "readings", + "days", + "relate", + "scan" + ], + "note": "\"metrics\" alone is what is measured (about; the bot answered it from its prompt) or the metrics now (current): a plain client with only the tool list may read it either way, and both answer it (the first live run called current {}); never a period's history" + }, + "most-rain-days-jja": { + "tools": [ + "days" + ], + "args": { + "days": { + "sort_by": "rain", + "period": { + "means": "June to August 2026" + } + } + }, + "note": "days ranked by rain over three months: \"June to August 2026\", or the same as start and end" + }, + "fastest-gust": { + "any_tools": [ + "summary", + "days" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "wind.wind_gust" + ] + }, + "period": { + "means": "on record" + } + }, + "days": { + "sort_by": "wind_gust", + "period": { + "means": "on record", + "optional": true + } + } + }, + "note": "a record with when it happened is summary (on record); the windiest day ranked is days" + }, + "chart-all-airgradient-week": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "air.pm2_5", + "air.co2" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "chart_readings": { + "reads": [ + "air.pm2_5", + "air.co2" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "airgradient is the air sensor's usual set" + }, + "rain-on-a-named-day": { + "any_tools": [ + "days", + "summary" + ], + "args": { + "days": { + "period": { + "means": "5 Sep" + } + }, + "summary": { + "period": { + "means": "5 Sep" + } + } + }, + "note": "one known day: its figures, not a search of the month" + }, + "pushback-cooler-this-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "this week" + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "a challenge: call again (the result's `fresh` says so), don't defend or agree from memory" + }, + "all-time-follow-up": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "on record" + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "a follow-up that keeps the subject with a new period: on record" + }, + "typo-win-direction": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "wind.wind_direction" + ] + }, + "period": { + "means": "3m" + } + } + }, + "note": "a typo for wind direction" + }, + "hottest-coldest-this-month": { + "any_tools": [ + "summary", + "days" + ], + "args": { + "summary": { + "period": { + "means": "this month" + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + }, + "days": { + "period": { + "means": "this month" + } + } + }, + "note": "the highest and lowest with when are summary's; the hottest and coldest days ranked are days'" + }, + "high-low-all-time": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "on record" + } + } + }, + "note": "the record high and low: summary over on record" + }, + "use-five-minute-data": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "on record" + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "the resolution is the service's (records are refined to 5 minutes where held): call again, there is no argument for it" + }, + "report": { + "tools": [ + "current", + "forecast", + "pollen" + ], + "args": { + "forecast": { + "period": { + "regex": "(?i)^today$", + "e.g.": "today", + "optional": true + } + } + }, + "note": "a report is current, forecast (today) and pollen, called together" + }, + "dashboard": { + "tools": [ + "current" + ], + "args": { + "current": { + "context": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "the gauges' live page is ecobot-mcp's /dashboard; a client shows current, with context the gauges' highs and lows" + }, + "weather-report-for-a-day": { + "any_tools": [ + "summary", + "days", + "forecast" + ], + "args": { + "summary": { + "period": { + "means": [ + "Tuesday", + "today" + ] + } + }, + "days": { + "period": { + "means": "Tuesday" + } + }, + "forecast": { + "period": { + "regex": "(?i)tuesday|today", + "e.g.": "Tuesday" + } + } + }, + "note": "asked on a Tuesday: last Tuesday's figures, or today's report (current, forecast \"today\", pollen: the report as the tool descriptions give it, so pollen is no longer refused). The bot's case kept its own fast path (wants_report) from taking it as the bare report; a plain client has no fast path, and Tuesday is today" + }, + "air-quality-vs-rain": { + "tools": [ + "relate" + ], + "args": { + "relate": { + "reading": { + "reads_any": [ + "air.pm2_5", + "air.pm10" + ] + } + } + }, + "note": "is the air cleaner after rain: relate with PM2.5 or PM10, both devices together" + }, + "rating-against-rainfall": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "chart_readings": { + "regex": "(?s)(?=.*:rating)(?=.*rain)", + "e.g.": [ + "air.pm2_5:rating", + "rainfall.rain" + ] + }, + "period": { + "means": "last 30 days" + }, + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "readings": { + "regex": "(?s)(?=.*:rating)(?=.*rain)", + "e.g.": [ + "air.pm2_5:rating", + "rain" + ] + }, + "chart_readings": { + "absent": true + }, + "period": { + "means": "last 30 days" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "the rating drawn over time is summary's chart (\":rating\"), with rain in a panel below; relate would draw PM2.5, not its rating. summary also takes the \":rating\" in `readings` (summarised, and drawn as its rating when chart_readings isn't sent), as deepseek sent it on 10 Nov 2026" + }, + "air-quality-vs-everything": { + "tools": [ + "scan" + ], + "not_tools": [ + "relate" + ], + "note": "every air reading against every weather reading: scan" + }, + "ecowitt-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + }, + "readings": { + "reads": [ + "outdoor.temperature", + "pressure.relative" + ], + "optional": true + } + } + }, + "note": "ecowitt names the weather station: every reading" + }, + "ag-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "air.pm2_5" + ] + }, + "period": { + "means": "7d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "ag names the air sensor" + }, + "air-gradient-now": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads": [ + "air.pm2_5" + ], + "optional": true + } + } + }, + "note": "air gradient names the air sensor; bare, it is the sensor now" + }, + "ecowitt-all-week": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "outdoor.temperature", + "outdoor.humidity", + "solar_and_uvi.solar", + "pressure.relative", + "rainfall.rain", + "outdoor.dew_point", + "wind.wind_speed" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "chart_readings": { + "reads": [ + "outdoor.temperature", + "outdoor.humidity", + "solar_and_uvi.solar", + "pressure.relative", + "rainfall.rain", + "outdoor.dew_point", + "wind.wind_speed" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "\"all\" is every station reading in the station's order (the service's, not the model's)" + }, + "sitrep": { + "tools": [ + "current", + "forecast", + "pollen" + ], + "args": { + "forecast": { + "period": { + "regex": "(?i)^today$", + "e.g.": "today", + "optional": true + } + } + }, + "note": "sitrep is a report: current, forecast (today) and pollen" + }, + "think-hottest-week": { + "any_tools": [ + "summary", + "days" + ], + "args": { + "summary": { + "period": { + "means": "this week" + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + }, + "days": { + "sort_by": { + "one_of": [ + "temp_max", + null + ] + }, + "order": { + "one_of": [ + "desc", + null + ] + }, + "count_only": { + "one_of": [ + false, + null + ] + }, + "stat": { + "absent": true + }, + "period": { + "means": "this week" + } + } + }, + "note": "the hottest of a period with when it was is summary's; the hottest day found by ranking its days is days' (as hottest-coldest-this-month)" + }, + "button-rain-chart": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "rainfall.rain" + ] + }, + "period": { + "means": "7d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "the bot's Rain chart button, asked in words" + }, + "button-humidity-chart": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "outdoor.humidity" + ] + }, + "period": { + "means": "7d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "the bot's Humidity chart button, asked in words" + }, + "button-aq-all-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "air.pm2_5" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "the bot's AQ all week button: the air sensor's set over the week" + }, + "weather-now-everything": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads": [ + "outdoor.temperature", + "pressure.relative" + ], + "optional": true + } + } + }, + "note": "everything now: current with no readings (or all of them)" + }, + "pollen-now": { + "tools": [ + "pollen" + ], + "note": "pollen and thunderstorm asthma" + }, + "hay-fever-today": { + "tools": [ + "pollen" + ], + "note": "a pollen question" + }, + "forecast-tomorrow": { + "tools": [ + "forecast" + ], + "not_tools": [ + "outlook" + ], + "args": { + "forecast": { + "period": { + "regex": "(?i)^tomorrow$", + "e.g.": "tomorrow" + } + } + }, + "note": "the forecast, not the station's own read of the next few hours" + }, + "philosophical-weather": { + "not_tools": [ + "summary", + "readings", + "days", + "relate", + "scan" + ], + "note": "an opinion, not a lookup: no search of the readings (a tool for now is fine)" + }, + "only-that-its-cold": { + "not_tools": [ + "current", + "summary", + "readings", + "days", + "relate", + "scan", + "outlook", + "forecast", + "pollen" + ], + "note": "a chat reply, not a request (the bot once answered it with the temperatures)" + }, + "how-cold-is-it": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "a plain question about now" + }, + "now-what": { + "not_tools": [ + "current", + "summary", + "readings", + "days", + "relate", + "scan", + "outlook", + "forecast", + "pollen" + ], + "note": "'now' alone is not a weather question" + }, + "chart-with-forecast": { + "tools": [ + "summary", + "forecast" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "rainfall.rain" + ] + }, + "period": { + "means": "this week" + }, + "chart_answers_it": { + "one_of": [ + null, + false + ] + } + }, + "forecast": { + "period": { + "regex": "(?i)^tomorrow$", + "e.g.": "tomorrow" + } + } + }, + "note": "two questions, two tools together: the chart of the week's rain and tomorrow's forecast" + }, + "chart-correlation": { + "tools": [ + "relate" + ], + "args": { + "relate": { + "reading": { + "reads": [ + "outdoor.humidity" + ] + }, + "chart": true + } + }, + "note": "a reading against rain, drawn: relate with chart" + }, + "chart-pressure-30d": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "pressure.relative" + ] + }, + "period": { + "means": "30d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "a plain chart of one reading" + }, + "lookup-how-hot": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "how hot is it: current, temperature" + }, + "lookup-raining": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads_any": [ + "rainfall.rain", + "rainfall.rain_rate" + ], + "optional": true + } + } + }, + "note": "is it raining: current, rain (or rain rate)" + }, + "lookup-air": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads": [ + "air.pm2_5" + ], + "optional": true + } + } + }, + "note": "the air now" + }, + "lookup-forecast": { + "tools": [ + "forecast" + ], + "note": "forecast: the next 7 days by default" + }, + "lookup-about": { + "tools": [ + "about" + ], + "not_tools": [ + "summary", + "readings", + "days", + "relate", + "scan" + ], + "note": "what the service can do" + }, + "lookup-judgement": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads_any": [ + "outdoor.temperature", + "outdoor.feels_like" + ], + "optional": true + } + } + }, + "note": "a judgement on the conditions now: current, then the model's words" + }, + "lookup-hottest-today": { + "any_tools": [ + "summary", + "current" + ], + "args": { + "summary": { + "period": { + "means": "today", + "optional": true + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + }, + "current": { + "context": true, + "readings": { + "reads_any": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "the high of a short period: summary (today is its default); or current with context, whose today carries the high and its time" + }, + "lookup-hottest-vs": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "two periods compared: summary for today and yesterday (two calls, or one over both with every_day)" + }, + "average-temp-yesterday": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "outdoor.temperature" + ] + }, + "period": { + "means": "yesterday" + }, + "average": true + } + }, + "note": "an average of a period: summary's average" + }, + "highest-humidity-yesterday": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "outdoor.humidity" + ] + }, + "period": { + "means": "yesterday" + } + } + }, + "note": "the high of a period with when it was: summary" + }, + "pollen-tomorrow": { + "tools": [ + "pollen" + ], + "not_tools": [ + "forecast" + ], + "note": "pollen gives the grass forecast and the day it is for; the weather forecast has no pollen" + }, + "average-rain": { + "any_tools": [ + "days", + "summary" + ], + "args": { + "days": { + "stat": "avg", + "of": "rain", + "period": { + "means": "last week" + } + }, + "summary": { + "readings": { + "reads": [ + "rainfall.rain" + ] + }, + "period": { + "means": "last week" + } + } + }, + "note": "the average daily rain is days' avg of rain; summary gives the week's total (rain has no average there)" + }, + "uv-days-two-years": { + "tools": [ + "days" + ], + "args": { + "days": { + "where": { + "conditions": [ + { + "field": "uv_max", + "op": [ + ">=" + ], + "value": 9 + } + ] + }, + "period": { + "means": "past two years" + }, + "count_only": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "how many days a figure reached a limit: days counted" + }, + "uv-days-per-year": { + "tools": [ + "days" + ], + "args": { + "days": { + "where": { + "conditions": [ + { + "field": "uv_max", + "op": [ + ">", + ">=" + ], + "value": 10 + } + ] + }, + "group_by": "year", + "period": { + "means": "on record", + "optional": true + } + } + }, + "note": "a count per year, drawn as bars: group_by year over the whole record" + }, + "rain-per-month": { + "tools": [ + "days" + ], + "args": { + "days": { + "stat": "sum", + "of": "rain", + "group_by": "month", + "period": { + "means": "this year" + } + } + }, + "note": "a total per month: days' sum of rain by month, drawn as bars" + }, + "hottest-day-per-year": { + "tools": [ + "days" + ], + "args": { + "days": { + "stat": "max", + "of": "temp_max", + "group_by": "year", + "period": { + "means": "on record", + "optional": true + } + } + }, + "note": "the highest daily maximum per year, as bars" + }, + "air-days-per-year": { + "tools": [ + "days" + ], + "args": { + "days": { + "where": { + "conditions": [ + { + "field": [ + "pm2_5_max", + "pm2_5_avg" + ], + "op": [ + ">", + ">=" + ], + "value": 25 + } + ] + }, + "group_by": "year", + "period": { + "means": "on record", + "optional": true + } + } + }, + "note": "the air sensor's days through the same days tool: a count per year" + }, + "count-pm25-days-per-year": { + "tools": [ + "days" + ], + "args": { + "days": { + "where": { + "conditions": [ + { + "field": [ + "pm2_5_max", + "pm2_5_avg" + ], + "op": [ + ">", + ">=" + ], + "value": 90 + } + ] + }, + "group_by": "year", + "period": { + "means": "on record", + "optional": true + } + } + }, + "note": "a count per year of the air sensor's days" + }, + "days-over-limit-by-year": { + "tools": [ + "days" + ], + "args": { + "days": { + "where": { + "conditions": [ + { + "field": "uv_max", + "op": [ + ">", + ">=" + ], + "value": 10 + } + ] + }, + "group_by": "year", + "period": { + "means": "on record", + "optional": true + } + } + }, + "note": "per year over the whole record, not one overall count" + }, + "days-two-readings-go-to-the-model": { + "tools": [ + "days" + ], + "args": { + "days": { + "where": { + "conditions": [ + { + "field": "temp_max", + "op": [ + ">", + ">=" + ], + "value": 35 + }, + { + "field": "rain", + "op": [ + ">=", + ">" + ] + } + ] + } + } + }, + "note": "two conditions on the same day: days' where holds both" + }, + "rain-by-month-two-years": { + "tools": [ + "days" + ], + "args": { + "days": [ + { + "stat": "sum", + "of": "rain", + "group_by": "month", + "period": { + "means": "2 years" + } + }, + { + "stat": "sum", + "of": "rain", + "group_by": "month", + "start": { + "regex": "^2024-(09|10)-", + "e.g.": "2024-10-01" + } + } + ] + }, + "note": "monthly bars, one per month, over the last 2 years" + }, + "avg-temp-per-year": { + "tools": [ + "days" + ], + "args": { + "days": { + "stat": "avg", + "of": "temp_avg", + "group_by": "year" + } + }, + "note": "an average per year is days' avg of each day's mean" + }, + "highest-pm25-by-month": { + "tools": [ + "days" + ], + "args": { + "days": { + "stat": "max", + "of": "pm2_5_max", + "group_by": "month" + } + }, + "note": "the highest per month, from the air sensor's days" + }, + "two-readings-by-month-go-to-the-model": { + "any_tools": [ + "days", + "summary" + ], + "args": { + "days": { + "group_by": "month", + "stat": { + "one_of": [ + "avg", + "max", + "min" + ] + }, + "of": { + "regex": "^(pm2_5|co2)_", + "e.g.": "pm2_5_avg" + } + }, + "summary": { + "readings": { + "reads": [ + "air.pm2_5", + "air.co2" + ] + } + } + }, + "note": "two readings by month: a days call for each (a figure per month, with its stat), or summary of both (its breakdown is by month for a long period); the period is the model's choice" + }, + "chart-weather-90d": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "outdoor.temperature", + "outdoor.humidity", + "solar_and_uvi.solar", + "pressure.relative", + "rainfall.rain", + "outdoor.dew_point", + "wind.wind_speed" + ] + }, + "period": { + "means": "90d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "chart_readings": { + "reads": [ + "outdoor.temperature", + "outdoor.humidity", + "solar_and_uvi.solar", + "pressure.relative", + "rainfall.rain", + "outdoor.dew_point", + "wind.wind_speed" + ] + }, + "period": { + "means": "90d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "a chart naming no reading is every reading, a panel each" + }, + "chart-all-90d": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "outdoor.temperature", + "outdoor.humidity", + "solar_and_uvi.solar", + "pressure.relative", + "rainfall.rain", + "outdoor.dew_point", + "wind.wind_speed" + ] + }, + "period": { + "means": "90d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "chart_readings": { + "reads": [ + "outdoor.temperature", + "outdoor.humidity", + "solar_and_uvi.solar", + "pressure.relative", + "rainfall.rain", + "outdoor.dew_point", + "wind.wind_speed" + ] + }, + "period": { + "means": "90d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "all is every station reading, a panel each" + }, + "two-axes-chart": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "solar_and_uvi.uvi", + "solar_and_uvi.solar" + ] + }, + "layout": "two_axes", + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "chart_readings": { + "reads": [ + "solar_and_uvi.uvi", + "solar_and_uvi.solar" + ] + }, + "layout": "two_axes", + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "two readings on one panel with a scale each: layout two_axes" + }, + "airgradient-humidity-over-ecowitt": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "air.humidity", + "outdoor.humidity" + ] + }, + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "chart_readings": { + "reads": [ + "air.humidity", + "outdoor.humidity" + ] + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "the AirGradient's own humidity is air.humidity; both sensors on one chart" + }, + "humidity-each-hour": { + "tools": [ + "readings" + ], + "not_tools": [ + "summary" + ], + "args": { + "readings": [ + { + "reading": { + "reads": [ + "outdoor.humidity" + ] + }, + "interval": "1hour", + "period": { + "means": "last 5 hours" + } + }, + { + "reading": { + "reads": [ + "outdoor.humidity" + ] + }, + "interval": "1hour", + "start": { + "regex": "^2026-09-29 (08|09)", + "e.g.": "2026-09-29 09:00" + }, + "end": { + "regex": "^2026-09-29", + "e.g.": "2026-09-29 14:05", + "optional": true + } + } + ] + }, + "note": "a value per hour is readings (the bot once said it only had extremes)" + }, + "temperature-every-30-minutes": { + "tools": [ + "readings" + ], + "args": { + "readings": { + "reading": { + "reads": [ + "outdoor.temperature" + ] + }, + "interval": "30min", + "period": { + "means": "today" + } + } + }, + "note": "values every 30 minutes, not a highs-and-lows summary" + }, + "chart-only-answers-itself": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "pressure.relative" + ] + }, + "period": { + "means": "since Sunday" + }, + "chart_answers_it": true, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "only the chart is asked for: chart_answers_it, and the result carries the reply" + }, + "chart-and-a-question": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "pressure.relative" + ] + }, + "period": { + "means": "since Sunday" + }, + "chart_answers_it": { + "one_of": [ + null, + false + ] + } + } + }, + "note": "the chart and something else to answer (outlook may be called too): chart_answers_it stays unset" + }, + "prompt-now": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "outside now is current (no readings named: everything)" + }, + "prompt-report": { + "tools": [ + "current", + "forecast", + "pollen" + ], + "args": { + "forecast": { + "period": { + "regex": "(?i)^today$", + "e.g.": "today", + "optional": true + } + } + }, + "note": "a report is current, forecast (today) and pollen, called together" + }, + "prompt-will-it-rain": { + "tools": [ + "outlook" + ], + "note": "will it rain in the next few hours is outlook" + }, + "prompt-weather-chart": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "7d" + }, + "chart": { + "one_of": [ + true, + null + ] + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "every station reading charted over the period is summary's chart" + }, + "prompt-chart": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "rainfall.rain" + ] + }, + "period": { + "means": "7d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "one reading charted over a period is summary's chart" + }, + "prompt-rainfall": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "rainfall.rain" + ] + }, + "period": { + "means": "last week" + } + } + }, + "note": "the rain that fell over a period is summary's total" + }, + "prompt-air": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "air.pm2_5" + ] + }, + "period": { + "means": "7d" + } + } + }, + "note": "the air over a period is summary of the air sensor's readings, PM2.5 among them" + } +} diff --git a/tests/evalworld.py b/tests/evalworld.py new file mode 100644 index 00000000..3429a3aa --- /dev/null +++ b/tests/evalworld.py @@ -0,0 +1,196 @@ +"""The evals' frozen world: the service's ten tools over the fake station's archive, an AirGradient on the same file, Open-Meteo and the +pollen page (all faked, nothing fetched), with the clock fixed at the evals' NOW (evalkit.NOW: Tue 29 Sep 2026 14:05, Melbourne) in +lib/ and the engines. tests/test_service_evals.py calls the expected calls against it (at_eval_now, build_archive, real_context, with +pytest's monkeypatch), and `scripts/eval_prompts.py --live` answers the bot's model from it (`world`: the archive built once per +run, outside pytest; each run of each case gets fresh tools over its own copy, World.fresh), so the model sees real results, notes +and refusals and can take a second round.""" + +import asyncio +import datetime as _dt +import importlib +import pkgutil +import shutil +import sys +import tempfile +import time as _time +from contextlib import asynccontextmanager +from datetime import datetime, time as dtime +from pathlib import Path +from zoneinfo import ZoneInfo + +import pytest + +from tests import evalkit + +EVAL_NOW = evalkit.NOW.replace(tzinfo=ZoneInfo(evalkit.NOW_TZ)).timestamp() + + +class _DatetimeType(type(_dt.datetime)): # (type, unless ECOBOT_CLOCK moved the clock: tests/clocks.py) + def __instancecheck__(cls, obj): + return isinstance(obj, _dt.datetime) + + def __subclasscheck__(cls, sub): + return issubclass(sub, _dt.datetime) + + +class _EvalDatetime(_dt.datetime, metaclass=_DatetimeType): + @classmethod + def now(cls, tz=None): + return _dt.datetime.fromtimestamp(EVAL_NOW, tz) + + @classmethod + def today(cls): + return _dt.datetime.fromtimestamp(EVAL_NOW) + + +class _DateType(type(_dt.date)): + def __instancecheck__(cls, obj): + return isinstance(obj, _dt.date) + + def __subclasscheck__(cls, sub): + return issubclass(sub, _dt.date) + + +class _EvalDate(_dt.date, metaclass=_DateType): + @classmethod + def today(cls): + return _dt.datetime.fromtimestamp(EVAL_NOW).date() + + +def at_eval_now(patch: pytest.MonkeyPatch, *also: str): + """The clock fixed at EVAL_NOW in every module of lib/ and tests/ (and the modules named in `also`, a test module whatever pytest + names it): every module of lib/ is imported first (whatever was imported before), then every name bound to datetime or date is the + fixed one, and time.time() (and the archive's epoch_now) returns EVAL_NOW; the process's zone is the station's (as conftest sets + it), so a naive local time is Melbourne's. `patch.undo()` puts it all back.""" + import lib + import tests.fakes, tests.test_pollen, tests.test_service_forecast # noqa: F401 + for info in pkgutil.walk_packages(lib.__path__, "lib."): + importlib.import_module(info.name) + patch.setenv("TZ", evalkit.NOW_TZ) + _time.tzset() + patch.setattr(_time, "time", lambda: EVAL_NOW) + for name, module in list(sys.modules.items()): + if module is None or not (name in ("lib", *also) or name.startswith(("lib.", "tests."))): + continue + for attr, value in list(vars(module).items()): + if value is _dt.datetime: + patch.setattr(module, attr, _EvalDatetime) + elif value is _dt.date: + patch.setattr(module, attr, _EvalDate) + patch.setattr(sys.modules["lib.ecowitt.archive"], "epoch_now", lambda: EVAL_NOW) + + +async def _inline(func, /, *args, **kwargs): + return func(*args, **kwargs) + + +async def build_archive(folder: Path) -> Path: + """The fake station's whole archive (its ecobot.sqlite in `folder`), built at the clock as it is (at_eval_now first), its pacing off.""" + from lib.ecowitt import Archive, Ecowitt, api, archive + from tests.fakes import config, ecowitt_transport + with pytest.MonkeyPatch.context() as patch: + patch.setattr(api, "MIN_GAP_SECONDS", 0) + patch.setattr(archive, "PACE_SECONDS", 0) + patch.setattr(asyncio, "to_thread", _inline) + transport, _ = ecowitt_transport() + eco = Ecowitt(config(folder), transport=transport) + await eco.start() + await Archive(eco).run_once() + await eco.close() + return config(folder).storage_path + + +def shared_eval_archive(shared_archive) -> Path: + """The archive build_archive makes at EVAL_NOW (at_eval_now first), as real_context leaves it (the air sensor's month held in it + too), once for every worker and run: conftest's shared_archive fixture, which the tests that need it pass. real_context over a + copy of it finds the air's month held, as it would after reading it into a copy of the bare archive.""" + here = Path(__file__).resolve().parent + + def make(folder, patch): + at_eval_now(patch) + return asyncio.run(build_archive(folder)) + bare = shared_archive(f"eval-{EVAL_NOW:.0f}", make, [__file__, Path(evalkit.__file__)]) + + def fill(folder, patch): + at_eval_now(patch) + + async def held(): + await close(await real_context(folder, bare)) + asyncio.run(held()) + return folder / "ecobot.sqlite" + return shared_archive(f"eval-world-{EVAL_NOW:.0f}", fill, [__file__, Path(evalkit.__file__), here / "test_pollen.py", + here / "test_service_forecast.py", *here.parent.glob("lib/**/*.py")]) + + +async def real_context(folder: Path, archive: Path): + """The ten tools' sources, faked, at the clock as it is (at_eval_now), their files in `folder` (not the archive's): the archived + station, an AirGradient on the same file, both together, Open-Meteo, the pollen page in season; the context's own clock is EVAL_NOW.""" + import json + + from lib.airgradient import AirGradient + from lib.compose import Composer + from lib.forecast import Forecast + from lib.service.context import Context + from tests.fakes import air_transport, archived_station, config + from tests.test_pollen import make as pollen_source + from tests.test_service_forecast import open_meteo + eco, _ = await archived_station(folder, archive) + air = AirGradient(config(folder), transport=air_transport(rows_per_day=24)[0], storage=eco.storage) + await air.start() + forecast = Forecast(config(folder, forecast=True, forecast_lat=-37.8, forecast_lon=144.9, place="Melbourne"), None, open_meteo([])) + noon = datetime.combine(evalkit.NOW.date(), dtime(12, 0)) + forecast.now = lambda: noon + pollen, _ = pollen_source(folder) + ctx = await Context.open(eco=eco, air=air, composer=Composer(eco, air), forecast=forecast, pollen=pollen, clock=lambda: EVAL_NOW) + (summary,) = [t for t in evalkit.service_tools(ctx) if t.name == "summary"] + held = json.loads(await summary.call({"readings": ["air"], "period": "last 30 days", "chart": False})) # (the air's month, held) + assert "error" not in held + return ctx + + +async def close(ctx): + """Close the sources real_context started.""" + await ctx.pollen.close() + await ctx.air.close() + await ctx.eco.close() + + +class World: + """The frozen world's archive, built once, and a fresh set of the ten tools over a new copy of it for each run (`fresh`): a tool call + can fill the station's file from the fakes (an old day asked for is fetched and stored, and "on record" then starts earlier), so a + run shares nothing with the one before it, whatever cases, --ids or --repeat came first. At the clock as it is (at_eval_now).""" + + def __init__(self, root: Path, archive: Path): + self.root, self.archive, self.runs = root, archive, 0 + + @asynccontextmanager + async def fresh(self): + """The lib.service Service of the ten tools over real_context on a new copy of the archive, in a folder of its own; closed and + removed on leaving.""" + from lib.service import Service + self.runs += 1 + folder = self.root / f"run-{self.runs}" + folder.mkdir(parents=True) + ctx = await real_context(folder, self.archive) + try: + yield Service.of(ctx) + finally: + await close(ctx) + shutil.rmtree(folder, ignore_errors=True) + + +@asynccontextmanager +async def world(folder: Path | None = None): + """The frozen world for a whole run outside pytest: the clock fixed (at_eval_now), the archive built under it once, and a World that + gives each run of each case its own tools over a fresh copy of it; everything put back on leaving. `folder`: where its files go (a + temporary one).""" + patch = pytest.MonkeyPatch() + with tempfile.TemporaryDirectory(prefix="ecobot-eval-") as tmp: + root = Path(folder or tmp) + (root / "archive").mkdir(parents=True, exist_ok=True) + try: + at_eval_now(patch) + yield World(root / "runs", await build_archive(root / "archive")) + finally: + patch.undo() + _time.tzset() diff --git a/tests/fakes.py b/tests/fakes.py index 4bae764b..8dc4a0ff 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -8,7 +8,6 @@ import httpx from lib.config import Config -from lib.tools import Tools TZ = ZoneInfo("Australia/Melbourne") MAC = "AA:BB:CC:DD:EE:FF" @@ -17,16 +16,78 @@ STEP = {"5min": 300, "30min": 1800, "4hour": 14400, "1day": 86400} -class StandInTools: - """A test's stand-in for lib.tools.Tools: it answers call(name, raw, turn) itself, and call_all is the real one over it.""" - call_all = Tools.call_all +class StandInService: + """A test's stand-in for the service's tools (lib.service.Service), served by ecobot-mcp in memory (tests/served.py) for the bot to + call: `answers` is {tool: its answer}, each a dict (sent as JSON) or a function (args, meta) -> dict; every call is kept in `calls` + as (tool, args).""" + + def __init__(self, **answers): + self.answers, self.calls = answers, [] + + def get(self, name): + if name not in self.answers: + return None + service = self + + class Tool: + async def call(self, args=None, meta=None): + import json + service.calls.append((name, dict(args or {}))) + answer = service.answers[name] + return json.dumps(answer(dict(args or {}), meta) if callable(answer) else answer, ensure_ascii=False) + return Tool() + + def __getitem__(self, name): + return self.get(name) + + def __contains__(self, name): + return name in self.answers + + def held(self, names): + return list(names) + + +def gauges_result(live: dict, values: dict, today, air: dict | None = None, air_values: dict | None = None) -> dict: + """current's result with context, as the bot reads it for its gauges, for a live reading ({group: {field: {value, unit}}}) and the + days' figures (days.day_values_on's): each gauge's reading now and its figures (lib/service/current.py context_of), through JSON. + With the air sensor's latest reading (`air`: {"pm2_5": {"value": 12.0, "unit": "µg/m³", ...}}, AirGradient.latest()'s, PM2.5 with + its aqi_us and band worked out when not given) and its day figures ({"pm2_5_max": {day: value}}), its readings too (air_context_of).""" + import json + from lib.airgradient.metrics import pm25_aqi + from lib.ecowitt.dashboard import GAUGES, live_value + 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: + group, name = gauge.reading.split(".", 1) + sensors.setdefault(group, {})[name] = {"value": value, "unit": gauge.unit, **beside} + 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") + if column == "pm2_5" and now is not None and "aqi_us" not in entry: + entry["aqi_us"], entry["band"] = pm25_aqi(now) + beside = air_context_of(column, now, metric.unit, air_values or {}, today) + if now is not None: + sensors.setdefault("air", {})[column] = {**air_entry(column, {"unit": metric.unit, **entry}), **beside} + elif beside: + sensors.setdefault("air", {})[column] = {"value": None, "unit": metric.unit, **beside} + return json.loads(json.dumps({"sensors": sensors})) + + +def chart_data(title: str = "Temperature", drawn_by: dict | None = None) -> dict: + """A chart as a service tool gives it (specs.to_json), with its drawn_by.""" + from lib.specs import Chart, Line, Panel, to_json + data = to_json(Chart(title, "", [Panel(title, "°C", [Line("Outdoor", [1, 2], [1.0, 2.0])])]), TZ) + return {**data, "drawn_by": drawn_by or {"tool": "summary", "arguments": {"period": "7d"}, "periods": []}} def config(tmp_path, **over) -> Config: base = dict(telegram_token="1:x", openrouter_api_key="k", openrouter_base_url="http://x", openrouter_model="m", tz=TZ, ecowitt_api_key="a", ecowitt_app_key="b", airgradient_token="t", airgradient_location="42", airgradient_dashboard="https://example.com/live", state_path=tmp_path / "state.json", - storage_path=tmp_path / "ecobot.sqlite", admin_only=False) # tests that are about ADMIN_ONLY switch it on + storage_path=tmp_path / "ecobot.sqlite", admin_only=False) # tests that are about BOT_ADMIN_ONLY switch it on return Config(**{**base, **over}) @@ -90,11 +151,17 @@ def uv_index(ts: int) -> float: def written(name: str, value: float) -> str: """A reading as the station writes it: one decimal, but none for the WHOLE readings, nor for a UV index that is whole.""" + return writer(name)(value) + + +def writer(name: str): + """written(name, ...) as a function of the value alone (the fake history writes a field's every value with it).""" base = name.removesuffix("_low").removesuffix("_high") if base in WHOLE: - return f"{value:.0f}" - out = f"{value:.1f}" - return out[:-2] if base == "uvi" and out.endswith(".0") else out + return "{:.0f}".format + if base == "uvi": + return lambda value: out[:-2] if (out := f"{value:.1f}").endswith(".0") else out + return "{:.1f}".format class FakeEcowitt: @@ -133,17 +200,27 @@ def _history(p: dict) -> dict: parse = lambda s: int(datetime.strptime(s, "%Y-%m-%d %H:%M:%S").replace(tzinfo=TZ).timestamp()) start, end = parse(p["start_date"]), parse(p["end_date"]) first = start - start % step if p["cycle_type"] == "1day" else start + -start % step # on the clock; 1day buckets are UTC days + times = range(first, end + 1, step) + keys = [str(ts) for ts in times] + every = 300 if step <= 1800 else 3600 # each bucket's samples: its first, and its lowest and highest (but for 5 minutes) + n = step // every out: dict = {} for group in p["call_back"].split(","): named = {"outdoor": [("temperature", temp), ("humidity", humidity), ("dew_point", temp)], "rainfall": [("daily", rain_day)], "pressure": [("relative", pressure)], "wind": [("wind_gust", gust), ("wind_direction", direction), ("wind_speed", wind_speed)], "solar_and_uvi": [("uvi", uv_index), ("solar", lambda ts: uv_index(ts) * 80)]} fields: dict = {} for name, fn in named.get(group, [("temperature", temp)] if group == "indoor" else []): # (no piezo gauge) - for ts in range(first, end + 1, step): - samples = [fn(t) for t in range(ts, ts + step, 300 if step <= 1800 else 3600)] - fields.setdefault(name, {"unit": "%" if name == "humidity" else "℃", "list": {}})["list"][str(ts)] = written(name, samples[0]) - if p["cycle_type"] != "5min": - for suffix, val in (("_low", min(samples)), ("_high", max(samples))): - fields.setdefault(name + suffix, {"unit": "%" if name == "humidity" else "℃", "list": {}})["list"][str(ts)] = written(name, val) + if not keys: + continue + unit, write = "%" if name == "humidity" else "℃", writer(name) + samples = [fn(t) for t in range(first, times[-1] + step, every)] + if n == 1: + fields[name] = {"unit": unit, "list": dict(zip(keys, map(write, samples)))} + continue + buckets = [samples[i:i + n] for i in range(0, len(samples), n)] + fields[name] = {"unit": unit, "list": {k: write(b[0]) for k, b in zip(keys, buckets)}} + if p["cycle_type"] != "5min": + fields[name + "_low"] = {"unit": unit, "list": {k: write(min(b)) for k, b in zip(keys, buckets)}} + fields[name + "_high"] = {"unit": unit, "list": {k: write(max(b)) for k, b in zip(keys, buckets)}} out[group] = fields return out @@ -320,3 +397,81 @@ async def archived_station(tmp_path, cache_file): await eco.start() fake.calls.clear() return eco, fake + + +def draws(monkeypatch, render): + """ecobot-mcp's drawing (lib/chart_images.render, which the server in memory draws with, tests/served.py: the bot draws nothing + itself) stood in for by render(chart, tz) -> PNG bytes (or anything the test sends as the picture).""" + from lib import chart_images + monkeypatch.setattr(chart_images, "render", lambda chart, tz, dark=None: (render(chart, tz), bool(dark))) + + +# ---------- the irrigation controller (lib/irrigation: the bot's and irrigation-mcp's) ---------- +TUYA_SECRET = "s3cret" +TUYA_STATUS = [{"code": "switch", "value": False}, {"code": "battery_percentage", "value": 100}, {"code": "weather_delay", "value": "cancel"}, + {"code": "countdown", "value": 0}, {"code": "work_state", "value": "idle"}, {"code": "use_time_one", "value": 40}] # as the controller answered + + +def tuya_config(tmp_path, **over) -> Config: + """The settings with the controller's three (client id "cid", secret TUYA_SECRET, device "dev1").""" + return config(tmp_path, tuya_device_id="dev1", tuya_client_id="cid", tuya_client_secret=TUYA_SECRET, **over) + + +class FakeTuya: + """Stands in for the Tuya cloud: records the signed requests it gets and checks each signature.""" + + def __init__(self, status=None, fail_token_once=False): + self.calls, self.status, self.token_n, self.fail_token_once = [], status if status is not None else TUYA_STATUS, 0, fail_token_once + + def __call__(self, request: httpx.Request) -> httpx.Response: + import json + + from lib.irrigation.tuya import sign + h, path = request.headers, request.url.raw_path.decode() + body = request.content + token = h.get("access_token", "") + expected = sign("cid", TUYA_SECRET, token, h["t"], h["nonce"], request.method, path, body) # signed over what was sent + assert h["sign"] == expected and h["client_id"] == "cid" and h["sign_method"] == "HMAC-SHA256" + if path.startswith("/v1.0/token"): + self.token_n += 1 + return httpx.Response(200, json={"success": True, "result": {"access_token": f"tok{self.token_n}", "expire_time": 7200}}) + self.calls.append((request.method, path, json.loads(body) if body else None, token)) + if self.fail_token_once and token == "tok1": + self.fail_token_once = False + return httpx.Response(200, json={"success": False, "code": 1010, "msg": "token invalid"}) + if path.endswith("/status"): + return httpx.Response(200, json={"success": True, "result": self.status}) + return httpx.Response(200, json={"success": True, "result": True}) + + +class FakeController: + """The irrigation controller (lib/irrigation/tuya.Tuya's methods) in memory: its status, the commands it was sent, and `down` (it + can't be reached: IrrigationError).""" + + def __init__(self, **status): + self.status_now = {"switch": False, "battery_percentage": 100, "weather_delay": "cancel", "work_state": "idle", **status} + self.commands, self.down = [], False + + def _reachable(self): + from lib.irrigation import IrrigationError + if self.down: + raise IrrigationError("Tuya request failed (ConnectError)") + + async def status(self): + self._reachable() + return dict(self.status_now) + + async def delay(self, duration): + self._reachable() + self.commands.append(("delay", duration)) + self.status_now["weather_delay"] = duration # the controller reports it + + async def set_switch(self, on): + self._reachable() + self.commands.append(("switch", on)) + self.status_now["switch"] = on + + async def water(self, minutes): + self._reachable() + self.commands.append(("water", minutes)) + self.status_now.update(switch=True, work_state="manual", countdown=minutes * 60) diff --git a/tests/served.py b/tests/served.py new file mode 100644 index 00000000..9571903c --- /dev/null +++ b/tests/served.py @@ -0,0 +1,138 @@ +"""ecobot-mcp in memory, as the bot reaches it (docs/ecobot-mcp.md step 6b: the bot is only ever its client): the real server +(lib/mcp_server.EcobotServer) over a test's Context (the fake sources, or none) and alert log, and the bot's own client of it +(lib/weather.RemoteWeather) connected through the SDK's in-memory transport, its supervisor running and listening. Every test that runs a +bot runs it against this (the `serve` fixture in tests/conftest.py): + + weather = await serve() # no sources: the tools that need none, the instructions, no station + weather = await serve(Context(eco=eco, tz=TZ)) # the fake station's tools + weather = await serve(tools=StandInService(summary=...)) # a test's stand-in tools, served as ecobot-mcp's + weather = await serve(tools=..., sources=["Ecowitt"]) # ... with ecobot://station naming these sources (the alerts, the shortcuts) + bot = Bot(NS(tz=TZ), agent, alert_state, service=weather) + +irrigation-mcp the same way (step 8b: the bot is its client too, BOT_IRRIGATION_MCP_URL): its real server (lib/irrigation/server.py) +over a fake controller (tests.fakes.FakeController, or a Tuya client over the fake Tuya cloud), its watchdog and its own alert log, and +the bot's client of it (lib/irrigation_remote.RemoteIrrigation), connected and listening (the `serve_irrigation` fixture): + + irrigation = await serve_irrigation(tmp_path) # the fake controller; irrigation.server.device is it + bot = Bot(NS(tz=TZ), agent, alert_state, irrigation, service=weather) +""" + +import asyncio +import contextlib + +from lib.mcp_server import EcobotServer +from lib.service.context import Context +from lib.weather import RemoteWeather +from tests.fakes import TZ + +READY_SECONDS = 10 # how long the client is given to connect and listen + + +class ServedTool: + """A test's stand-in tool as ecobot-mcp serves it: a name, a description, an input schema (anything goes), its `call`.""" + read_only, open_world = True, False + + def __init__(self, name: str, tool): + self.name, self.tool = name, tool + self.description = getattr(tool, "description", "") or f"The test's {name}." + self.parameters = getattr(tool, "parameters", None) or {"type": "object"} + + async def call(self, args=None, meta=None) -> str: + return await self.tool.call(args or {}, meta) + + +class ServedTools: + """A test's tools (a lib.service.Service, a list of tools, or a tests.fakes.StandInService) as ecobot-mcp's: by name, in order.""" + + def __init__(self, tools): + if hasattr(tools, "answers"): # (a StandInService: its tools by the answers it holds) + named = [(name, tools.get(name)) for name in tools.answers] + else: + named = [(t.name, t) for t in tools] + self.tools = [ServedTool(name, tool) for name, tool in named] + self.by_name = {t.name: t for t in self.tools} + + def __iter__(self): + return iter(self.tools) + + def get(self, name: str): + return self.by_name.get(name) + + def __getitem__(self, name: str): + return self.by_name[name] + + def __contains__(self, name: str) -> bool: + return name in self.by_name + + +SOURCE_OF = {"eco": "Ecowitt", "air": "AirGradient", "forecast": "Forecast", "pollen": "Pollen"} # (a resource's need: its source) + + +def stand_in(server: EcobotServer, sources: set[str]): + """The server as if it ran these sources (names) over stand-in tools: ecobot://station names them, with every reading of the devices + among them (as a station that has sent every field), and the resources that need one of them are there.""" + from lib.service.names import AIR_DEVICE, STATION + station = server.station + devices = {STATION: "Ecowitt" in sources, AIR_DEVICE: "AirGradient" in sources} + + async def named(): + readings = server.ctx.readings() + sensors = {device: {"readings": [{"name": r.name, "label": r.label, "unit": r.unit} for r in readings if r.device == device]} + for device, there in devices.items() if there} + return {**await station(), "sensors": sensors, "sources": {name: {} for name in sorted(sources)}} + server.station = named + server._there = lambda need: need is None or SOURCE_OF.get(need) in sources + + +def unreached() -> RemoteWeather: + """ecobot-mcp at an address nothing answers, never connected: for a test of the bot's Telegram side alone, which asks it nothing.""" + return RemoteWeather("http://127.0.0.1:9/mcp", tz=TZ) + + +@contextlib.asynccontextmanager +async def irrigation_mcp(folder, device=None, *, tz=TZ): + """(the bot's client of) irrigation-mcp over `device` (default: a FakeController), its watchdog's state and its alert log in + `folder`, publishing its alerts. `.server` is the server behind it (its device, watchdog, alert_log, notify).""" + from lib.alert_log import AlertLog + from lib.irrigation import Watchdog + from lib.irrigation.server import IrrigationServer + from lib.irrigation.state import IrrigationState + from lib.irrigation_remote import RemoteIrrigation + from tests.fakes import FakeController + device = device if device is not None else FakeController() + folder.mkdir(parents=True, exist_ok=True) + alert_log = AlertLog(folder / "irrigation_alerts.sqlite", tz) + server = IrrigationServer(device, Watchdog(device, IrrigationState(folder / "irrigation_state.json")), alert_log, tz=tz) + remote = RemoteIrrigation(server.server) + remote.server = server # (the test's way to the server behind it) + tasks = [asyncio.create_task(server.run()), asyncio.create_task(remote.run())] + try: + await asyncio.wait_for(remote.listening.wait(), READY_SECONDS) + yield remote + finally: + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + await remote.close() + alert_log.close() + + +@contextlib.asynccontextmanager +async def ecobot_mcp(ctx: Context | None = None, alert_log=None, *, tools=None, sources=None, tz=TZ): + """(the bot's client of) ecobot-mcp over `ctx` (default: no sources, in `tz`) and `alert_log`; `tools` in place of the ones `ctx` + gives, `sources` (names) in place of the ones ecobot://station lists.""" + server = EcobotServer(ctx if ctx is not None else Context(tz=tz), alert_log) + if tools is not None: + server._service = ServedTools(tools) + if sources is not None: + stand_in(server, set(sources)) + remote = RemoteWeather(server.server, tz=tz) + remote.server = server # (the test's way to the server behind it) + task = asyncio.create_task(remote.run()) + try: + await asyncio.wait_for(remote.listening.wait(), READY_SECONDS) + yield remote + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + await remote.close() diff --git a/tests/service_switch.json b/tests/service_switch.json new file mode 100644 index 00000000..53cba3ab --- /dev/null +++ b/tests/service_switch.json @@ -0,0 +1,1193 @@ +{ + "Air quality all metrics 1d": { + "charts": [ + { + "panels": [ + { + "label": "PM1, PM2.5, PM10", + "series": [ + [ + "PM1", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 3.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 3.0 + ] + ] + ], + [ + "PM2.5", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 9.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] + ], + [ + "PM10", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 8.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] + ] + ], + "unit": "µg/m³" + }, + { + "label": "CO₂", + "series": [ + [ + "CO₂", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 450.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 450.0 + ] + ] + ] + ], + "unit": "ppm" + }, + { + "label": "VOC index", + "series": [ + [ + "VOC index", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 100.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 100.0 + ] + ] + ] + ], + "unit": "" + }, + { + "label": "NOx index", + "series": [ + [ + "NOx index", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 1.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 1.0 + ] + ] + ] + ], + "unit": "" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "eb74a3c6b7c7f982", + "source": "AirGradient sensor", + "subtitle": "Mon 9 Nov 2026 - Tue 10 Nov 2026 · AirGradient readings", + "title": "Air quality" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\n• PM2.5: peak 16.0 µg/m³ (Mon 9 Nov 10:00pm) · 🟡 poor · average 10.6\n• PM10: peak 8.0 µg/m³ (Mon 9 Nov 3:00pm) · 🟢 good · average 8.0\n• PM1: peak 3.0 µg/m³ (Mon 9 Nov 3:00pm) · 🟢 good · average 3.0\n• CO₂: peak 450.0 ppm (Mon 9 Nov 3:00pm) · 🟢 good · average 450.0\n• VOC index: peak 100.0 relative index (100 = this sensor's recent average) (Mon 9 Nov 3:00pm) · 🟢 good · average 100.0\n• NOx index: peak 1.0 relative index (1 = baseline) (Mon 9 Nov 3:00pm) · 🟢 good · average 1.0", + "sent": [ + [ + "photo", + "Air quality\nMon 9 – Tue 10 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "Humidity chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "Humidity", + "series": [ + [ + "Outdoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 55.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 55.0 + ] + ] + ] + ], + "unit": "%" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "0c4b899e234ed02a", + "source": "Ecowitt weather station", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · 5-minute readings · records marked", + "title": "Humidity" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\nHumidity: low 55 %, Mon 9 Nov at 2:05pm · high 85 %, Tue 10 Nov at 2:40am", + "sent": [ + [ + "photo", + "Humidity, since Mon 9 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "Particulates chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "PM1, PM2.5, PM10", + "series": [ + [ + "PM1", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 3.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 3.0 + ] + ] + ], + [ + "PM2.5", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 9.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] + ], + [ + "PM10", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 8.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] + ] + ], + "unit": "µg/m³" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "218963e99fe3d441", + "source": "AirGradient sensor", + "subtitle": "Mon 9 Nov 2026 - Tue 10 Nov 2026 · AirGradient readings", + "title": "Air quality" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\n• PM2.5: peak 16.0 µg/m³ (Mon 9 Nov 10:00pm) · 🟡 poor · average 10.6\n• PM10: peak 8.0 µg/m³ (Mon 9 Nov 3:00pm) · 🟢 good · average 8.0\n• PM1: peak 3.0 µg/m³ (Mon 9 Nov 3:00pm) · 🟢 good · average 3.0", + "sent": [ + [ + "photo", + "Air quality, since Mon 9 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "Rain chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "Rain", + "series": [ + [ + "Rain", + "bars", + 25, + [ + [ + "2026-11-09T14:00:00+11:00", + 0.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 0.0 + ] + ] + ] + ], + "unit": "mm" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "84f5e24e4493ff27", + "source": "Ecowitt weather station", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · rain per hour", + "title": "Rain" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\n☔ Rain per hour: least 0 mm (Mon 9 Nov 2pm) · most 0 mm (Mon 9 Nov 2pm) · 0.0 mm in all", + "sent": [ + [ + "photo", + "Rain, since Mon 9 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "Temperature chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Outdoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ], + [ + "Indoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ] + ], + "unit": "°C" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "d935397aaf78f0d5", + "source": "Ecowitt weather station", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · 5-minute readings · records marked", + "title": "Temperature" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\nTemperature (indoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm", + "sent": [ + [ + "photo", + "Temperature, since Mon 9 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "Weather chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Indoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ], + [ + "Outdoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ] + ], + "unit": "°C" + }, + { + "label": "Humidity", + "series": [ + [ + "Humidity", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 55.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 55.0 + ] + ] + ], + [ + "Rain", + "bars", + 25, + [ + [ + "2026-11-09T14:00:00+11:00", + 0.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 0.0 + ] + ] + ] + ], + "unit": "%" + }, + { + "label": "Solar radiation", + "series": [ + [ + "Solar radiation", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 848.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 848.0 + ] + ] + ] + ], + "unit": "W/m²" + }, + { + "label": "Pressure", + "series": [ + [ + "Pressure", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 1012.1 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 1007.8 + ] + ] + ] + ], + "unit": "hPa" + }, + { + "label": "Dew point", + "series": [ + [ + "Dew point", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ] + ], + "unit": "°C" + }, + { + "label": "Wind", + "series": [ + [ + "Wind", + "band", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 10.0, + 10.0, + 26.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 10.0, + 10.0, + 29.0 + ] + ] + ] + ], + "unit": "km/h" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "a5e62602517de50d", + "source": "Ecowitt weather station", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · rain per hour · range shaded", + "title": "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\nTemperature (indoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\nHumidity: low 55 %, Mon 9 Nov at 2:05pm · high 85 %, Tue 10 Nov at 2:40am\nSolar radiation: low 0.0 °C, Mon 9 Nov at 7pm · high 880.0 °C, Tue 10 Nov at 12:40pm\nPressure: low 1007.0 °C, Tue 10 Nov at 7:45am · high 1012.1 °C, Mon 9 Nov at 2:05pm\n☔ Rain per hour: least 0 mm (Mon 9 Nov 2pm) · most 0 mm (Mon 9 Nov 2pm) · 0.0 mm in all\nDew point: low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\n🌬️ Wind: strongest gust 36.0 °C, Mon 9 Nov at 3pm\n🧭 Mostly from the N (100%), steady", + "sent": [ + [ + "photo", + "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind\nMon 9 – Tue 10 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "Wind chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "Wind", + "series": [ + [ + "Wind", + "band", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 10.0, + 10.0, + 26.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 10.0, + 10.0, + 29.0 + ] + ] + ] + ], + "unit": "km/h" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "0fd7a0b036ac1b81", + "source": "Ecowitt weather station", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · 5-minute readings, shaded up to the gusts", + "title": "Wind" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\n🌬️ Wind: strongest gust 36.0 °C, Mon 9 Nov at 3pm\n🧭 Mostly from the N (100%), steady", + "sent": [ + [ + "photo", + "Wind, since Mon 9 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "alert gusts": { + "charts": [ + { + "panels": [ + { + "label": "Wind", + "series": [ + [ + "Wind", + "band", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 10.0, + 10.0, + 26.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 10.0, + 10.0, + 29.0 + ] + ] + ] + ], + "unit": "km/h" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "785a7105037691ba", + "source": "", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · 5-minute readings, shaded up to the gusts", + "title": "Wind" + } + ], + "newest": 1794279900, + "title": "Wind, since Mon 9 Nov 2026" + }, + "alert particulates": { + "charts": [ + { + "panels": [ + { + "label": "PM1, PM2.5, PM10", + "series": [ + [ + "PM1", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 3.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 3.0 + ] + ] + ], + [ + "PM2.5", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 9.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] + ], + [ + "PM10", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 8.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] + ] + ], + "unit": "µg/m³" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "ea4787312db7f13c", + "source": "", + "subtitle": "Mon 9 Nov 2026 - Tue 10 Nov 2026 · AirGradient readings", + "title": "Air quality" + } + ], + "newest": 1794279600, + "title": "Air quality, since Mon 9 Nov 2026" + }, + "alert temps": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Outdoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ], + [ + "Indoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ] + ], + "unit": "°C" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "42aab5676fd09bf3", + "source": "", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · 5-minute readings · records marked", + "title": "Temperature" + } + ], + "newest": 1794279900, + "title": "Temperature, since Mon 9 Nov 2026" + }, + "alert uv": { + "charts": [ + { + "panels": [ + { + "label": "UV index", + "series": [ + [ + "UV index", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 10.6 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 10.6 + ] + ] + ] + ], + "unit": "" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "548b7ec71a831b23", + "source": "", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · 5-minute readings · records marked", + "title": "UV index" + } + ], + "newest": 1794279900, + "title": "UV index, since Mon 9 Nov 2026" + }, + "press 1M under Rain chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "Rain", + "series": [ + [ + "Rain", + "bars", + 119, + [ + [ + "2026-10-12T00:00:00+11:00", + 0.0 + ] + ], + [ + [ + "2026-11-10T12:00:00+11:00", + 0.0 + ] + ] + ] + ], + "unit": "mm" + } + ], + "period": [ + "2026-10-12", + "2026-11-10" + ], + "sha": "faca6ea0ee20ddf7", + "source": "Ecowitt weather station", + "subtitle": "Mon 12 Oct – Tue 10 Nov 2026 · rain per 6 hours", + "title": "Rain" + } + ], + "edits": [ + [ + "photo", + "Rain, since Mon 12 Oct 2026" + ] + ] + }, + "press 1Y under humidity 7d": { + "charts": [ + { + "panels": [ + { + "label": "Humidity", + "series": [ + [ + "Outdoor", + "band", + 364, + [ + [ + "2025-11-11T11:00:00+11:00", + 62.0, + 54.0, + 84.0 + ] + ], + [ + [ + "2026-11-09T10:00:00+11:00", + 69.76041666666667, + 55.0, + 85.0 + ] + ] + ] + ], + "unit": "%" + } + ], + "period": [ + "2025-11-11", + "2026-11-10" + ], + "sha": "31534a4a0650edb3", + "source": "Ecowitt weather station", + "subtitle": "Tue 11 Nov 2025 – Tue 10 Nov 2026 · daily averages, range shaded · records marked", + "title": "Humidity" + } + ], + "edits": [ + [ + "photo", + "Humidity, since Tue 11 Nov 2025" + ] + ] + }, + "press 7D under Temperature chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Outdoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, + 20.1 + ] + ] + ], + [ + "Indoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, + 20.1 + ] + ] + ] + ], + "unit": "°C" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "4b8bc87c49be3cd2", + "source": "Ecowitt weather station", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", + "title": "Temperature" + } + ], + "edits": [ + [ + "photo", + "Temperature, since Wed 4 Nov 2026" + ] + ] + } +} diff --git a/tests/slow_tests.txt b/tests/slow_tests.txt new file mode 100644 index 00000000..533a8c00 --- /dev/null +++ b/tests/slow_tests.txt @@ -0,0 +1,60 @@ +# The slow tests (0.5 s or more each, run alone): plain `pytest` leaves them out (pytest.ini: -m "not slow"); `pytest -m slow` +# runs them alone, `pytest -m ""` everything (as CI does). Written by scripts/slow_tests.py from the tests' measured times. +tests/test_air_hass.py::test_the_voc_index_gets_home_assistants_ranges_and_the_raw_pm25_none_said_once +tests/test_airgradient.py::test_air_charts_too_long_for_the_point_budget_are_bucketed_and_carry_a_range +tests/test_airgradient.py::test_every_air_day_row_is_what_the_glitch_rule_in_python_gives +tests/test_alerts.py::test_the_alert_charts_are_the_buttons_one_day_charts_drawn_from_each_sources_history +tests/test_bench_storage.py::test_the_benchmark_s_own_cache_is_as_old_as_asked_and_its_short_chart_is_drawn_from_the_minutes +tests/test_bot.py::test_the_bot_imports_no_pillow_no_drawing_module_and_no_source_module +tests/test_bot_remote.py::test_a_charts_picture_comes_from_the_service_with_its_period_buttons +tests/test_bot_remote.py::test_a_dropped_connection_is_rebuilt_and_the_alerts_after_the_last_id_are_read_once +tests/test_bot_remote.py::test_a_start_while_the_service_cant_be_reached_follows_the_station_s_zone_once_read_and_keeps_it +tests/test_bot_remote.py::test_the_bot_sends_the_services_picture_of_a_chart_byte_for_byte_as_its_renderer_draws_it +tests/test_bot_remote.py::test_the_models_charts_come_from_the_service_as_pictures_and_the_model_gets_only_their_text +tests/test_bot_remote.py::test_the_service_back_on_a_fresh_alert_log_while_the_bot_runs_has_its_new_alerts_delivered +tests/test_bot_remote.py::test_with_the_service_down_the_bot_says_so_and_carries_on +tests/test_chart_json.py::test_every_sample_chart_comes_back_the_same_and_is_drawn_the_same +tests/test_compose.py::test_the_air_sensors_own_temperature_goes_over_the_stations_on_one_axis +tests/test_ecowitt.py::test_a_group_the_station_lacks_is_dropped_for_the_warm_up_too +tests/test_ecowitt.py::test_an_interrupted_archive_resumes_where_it_stopped +tests/test_ecowitt.py::test_any_readings_can_be_plotted_together_one_panel_each +tests/test_ecowitt.py::test_archive_caches_every_cycle_so_long_questions_need_no_requests_and_reports_how_much_is_held +tests/test_ecowitt.py::test_archive_estimates_its_duration_from_the_pace +tests/test_ecowitt.py::test_archive_skips_time_before_the_station_existed +tests/test_ecowitt.py::test_the_pair_chart_renders_for_a_day_a_month_and_a_year +tests/test_hass_live.py::test_a_home_assistant_that_stops_answering_is_said_once_and_the_cloud_answers_the_rain +tests/test_hass_live.py::test_a_new_reading_is_found_in_seconds_and_calls_the_rain_alert_each_time +tests/test_mcp_listen.py::test_a_client_that_listens_hears_an_alert_and_after_a_lost_listen_listens_again_and_reads_what_it_missed +tests/test_mcp_listen.py::test_ecobot_mcp_down_for_a_moment_isnt_a_warning_but_down_for_longer_or_refusing_is +tests/test_mcp_listen.py::test_the_service_runs_the_sources_and_answers_a_tool_call_through_the_proxys_name +tests/test_mcp_server.py::test_a_call_asking_for_images_gets_each_chart_as_a_png_after_the_figures_and_the_charts_json_in_meta +tests/test_mcp_server.py::test_a_call_asking_for_links_gets_each_chart_s_url_and_markdown_and_a_resource_link_but_no_image +tests/test_mcp_server.py::test_every_tool_is_listed_with_its_schema_and_hints_and_answers_as_the_service_tool_does +tests/test_mcp_server.py::test_over_http_a_link_serves_the_png_without_a_token_or_an_allowed_host_while_mcp_still_needs_both +tests/test_mcp_server.py::test_over_http_the_connections_url_asks_for_images_and_a_call_can_say_otherwise +tests/test_mcp_server.py::test_the_bot_on_a_link_connection_still_gets_its_pictures_and_its_charts_json +tests/test_mcp_server.py::test_the_links_base_url_is_the_setting_when_set +tests/test_mcp_server.py::test_the_service_imports_no_pillow_until_an_image_is_asked_for_and_no_telegram_ever +tests/test_minute_lines.py::test_home_assistant_alone_is_kept_warm_and_backfilled_like_the_cloud +tests/test_scan.py::test_a_scan_of_years_covers_its_latest_400_days_and_says_so +tests/test_scan.py::test_daily_cycles_that_change_shape_with_a_shared_season_are_not_called_linked +tests/test_scan.py::test_pure_noise_rarely_finds_anything_even_across_many_pairs +tests/test_scan.py::test_unrelated_readings_that_curve_smoothly_within_each_day_are_not_called_linked +tests/test_service_days.py::test_a_chart_of_part_of_each_day_lists_the_whole_record_only_while_it_is_within_400_days +tests/test_service_days.py::test_the_station_and_air_answers_are_as_recorded +tests/test_service_days.py::test_the_tool_offers_the_fields_of_the_sensors_there_are_and_says_what_it_is_for +tests/test_service_evals.py::test_a_refused_call_in_a_step_fails_whatever_the_order_of_the_steps_calls +tests/test_service_evals.py::test_each_run_has_its_own_copy_of_the_world_so_a_case_scores_the_same_whatever_ran_before +tests/test_service_evals.py::test_every_expected_call_is_answered_not_refused +tests/test_service_evals.py::test_the_script_runs_the_service_evals_offline_and_needs_a_key_to_ask_a_model +tests/test_service_relate.py::test_a_chart_when_asked_carries_the_call_that_draws_it_again +tests/test_service_scan.py::test_a_chart_of_the_strongest_pair_carries_the_call_that_draws_it_again +tests/test_service_scan.py::test_a_long_period_is_scanned_over_its_latest_400_days_and_drawn_again_over_them +tests/test_service_summary.py::test_a_chart_of_both_sensors_or_a_rating_is_drawn_over_whole_days_and_says_so +tests/test_service_summary.py::test_wind_is_drawn_with_its_compass_and_one_reading_named_draws_only_that_one +tests/test_startup.py::test_a_failed_first_refresh_does_not_stop_the_alerts_or_the_archives +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_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_the_page_fits_its_tiles_to_the_window_at_each_size_with_no_overflow_and_no_console_error diff --git a/tests/summary_words.json b/tests/summary_words.json new file mode 100644 index 00000000..4b53b2a9 --- /dev/null +++ b/tests/summary_words.json @@ -0,0 +1,105 @@ +{ + "clock": "2026-11-10T14:05:00+11:00", + "captions": [ + { + "arguments": { + "readings": [ + "pressure" + ], + "period": "this week" + }, + "caption": "Wed 4 Nov – Tue 10 Nov 2026\nPressure: low 1006.9 °C, Wed 4 Nov at 6:50am · high 1023.5 °C, Sat 7 Nov at 1:45am" + }, + { + "arguments": { + "period": "this week" + }, + "caption": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\nTemperature (indoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\nHumidity: low 54 %, Thu 5 Nov at 2:45pm · high 85 %, Wed 4 Nov at 2:15am" + }, + { + "arguments": { + "readings": [ + "temperature" + ], + "period": "this week", + "average": true + }, + "caption": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature (outdoor): average 14.1 °C (low 8.1, high 20.4)\nTemperature (indoor): average 14.1 °C (low 8.1, high 20.4)" + }, + { + "arguments": { + "readings": [ + "rain", + "wind" + ], + "period": "last 10 days" + }, + "caption": "Sun 1 Nov – Tue 10 Nov 2026\n☔ Rain per 6 hours: least 0 mm (Sun 1 Nov 12am) · most 5 mm (Sun 8 Nov 12pm) · 5.5 mm in all\n🌬️ Wind: strongest gust 48.0 °C, Fri 6 Nov at 3pm\n🧭 Mostly from the N (100%), steady" + }, + { + "arguments": { + "readings": [ + "wind" + ], + "period": "last 3 days" + }, + "caption": "Sun 8 Nov – Tue 10 Nov 2026\n🌬️ Wind: strongest gust 36.0 °C, Mon 9 Nov at 3pm\n🧭 Mostly from the N (100%), steady" + }, + { + "arguments": { + "readings": [ + "rain" + ], + "period": "last 3 days" + }, + "caption": "Sun 8 Nov – Tue 10 Nov 2026\n☔ Rain per hour: least 0 mm (Sun 8 Nov 12am) · most 5 mm (Sun 8 Nov 2pm) · 5.0 mm in all" + }, + { + "arguments": { + "readings": [ + "pm2.5", + "co2" + ], + "period": "last 3 days" + }, + "caption": "Sun 8 Nov – Tue 10 Nov 2026\n• PM2.5: peak 16.0 µg/m³ (Sun 8 Nov 10:00am) · 🟡 poor · average 10.4\n• CO₂: peak 450.0 ppm (Sun 8 Nov 12:00am) · 🟢 good · average 450.0" + } + ], + "texts": [ + { + "arguments": { + "period": "yesterday" + }, + "text": "Mon 9 Nov – Mon 9 Nov 2026\n• Temperature (outdoor): low 8.1 °C, Mon 9 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\n• Humidity: low 55 %, Mon 9 Nov at 1:50pm · high 85 %, Mon 9 Nov at 2:15am\n• Temperature (indoor): low 8.1 °C, Mon 9 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm" + }, + { + "arguments": { + "readings": [ + "temperature" + ], + "period": "yesterday", + "average": true + }, + "text": "Mon 9 Nov – Mon 9 Nov 2026\n• Temperature (outdoor): average 14.1 °C (low 8.1, high 20.1)\n• Temperature (indoor): average 14.1 °C (low 8.1, high 20.1)" + }, + { + "arguments": { + "readings": [ + "wind" + ], + "period": "yesterday" + }, + "text": "Mon 9 Nov – Mon 9 Nov 2026\n• Wind: low 0.0 °C, Mon 9 Nov at 12am · high 25.0 °C, Mon 9 Nov at 6pm\n• Wind gust: low 26.0 °C, Mon 9 Nov at 12am · high 36.0 °C, Mon 9 Nov at 3pm" + }, + { + "arguments": { + "readings": [ + "outdoor.humidity", + "pressure" + ], + "period": "yesterday" + }, + "text": "Mon 9 Nov – Mon 9 Nov 2026\n• Humidity: low 55 %, Mon 9 Nov at 1:50pm · high 85 %, Mon 9 Nov at 2:15am\n• Pressure: low 1009.1 °C, Mon 9 Nov at 8:15pm · high 1015.9 °C, Mon 9 Nov at 12am" + } + ] +} diff --git a/tests/test_admin_only.py b/tests/test_admin_only.py index d3da77ef..da6eb76c 100644 --- a/tests/test_admin_only.py +++ b/tests/test_admin_only.py @@ -1,4 +1,4 @@ -"""ADMIN_ONLY (who may use the bot), /alerts in groups, /usage, and the checks every button press goes through.""" +"""BOT_ADMIN_ONLY (who may use the bot), /alerts in groups, /usage, and the checks every button press goes through.""" import asyncio import random @@ -8,15 +8,15 @@ from telegram import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import CallbackQueryHandler -from lib import periods, report_menu, templates +from lib.service.summary import OVER_TIME +from lib import periods, templates from lib.admins import Admins from lib.alerts import menu from lib.alerts.notify import AlertState from lib.bot import MAX_CALLBACK_BYTES, NOT_ADMIN, NOT_ADMIN_TOAST, STALE_BUTTON, Bot from lib.config import Config, _ids -from lib.irrigation import menu as irrigation_menu +from lib import irrigation_menu from tests.fakes import TZ -from tests.test_irrigation import Remote ADMIN, STRANGER, GROUP, OTHER_GROUP = 1, 7, -5, -6 ANONYMOUS = 1087968824 # the user Telegram shows for an admin who posts "as the group" @@ -46,15 +46,37 @@ class Asked(Bot): """A Bot that records the questions it is asked instead of asking a model.""" asked: list - async def respond(self, update, context, text, redraw=None): + async def respond(self, update, context, text, call=None): self.asked.append(text.strip()) +@pytest.fixture(autouse=True) +async def ecobot_mcp(serve, serve_irrigation, tmp_path): + """ecobot-mcp in memory with the weather station (its alerts are the menus' types), the bot's client of it connected: what `make` + builds every bot over; and irrigation-mcp in memory over the fake controller (Remote(): the bot's client of it).""" + global WEATHER, IRRIGATION + WEATHER, IRRIGATION = await serve(tools=[], sources=["Ecowitt"]), await serve_irrigation(tmp_path / "irrigation") + yield WEATHER + WEATHER = IRRIGATION = None + + +WEATHER = IRRIGATION = None + + +def Remote(): + """irrigation-mcp in memory, as the bot reaches it; `commands(bot)` is what its controller was told.""" + return IRRIGATION + + +def commands(irrigation) -> list: + return irrigation.server.device.commands + + def make(tmp_path, admin_only=True, extra=(), irrigation=None, groups=(GROUP,), tg=None): state = AlertState(tmp_path / "s.json") for group in groups: state.add_chat(group, "Home") - bot = Asked(NS(tz=TZ, admin_only=admin_only, admin_chat_ids=frozenset(extra)), None, [NS(name="Ecowitt")], state, irrigation) + bot = Asked(NS(tz=TZ, admin_only=admin_only, admin_chat_ids=frozenset(extra)), None, state, irrigation, service=WEATHER) bot.asked = [] return bot, state, tg or TG() @@ -105,19 +127,19 @@ def board(*data): # ---------- the settings ---------- def test_admin_only_is_off_unless_switched_on_and_the_listed_ids_are_read_safely(monkeypatch, caplog): - for k, v in {"TELEGRAM_BOT_TOKEN": "t", "OPENROUTER_API_KEY": "k", "ECOWITT_API_KEY": "a", "ECOWITT_APP_KEY": "b"}.items(): + for k, v in {"BOT_TELEGRAM_TOKEN": "t", "BOT_OPENROUTER_API_KEY": "k", "BOT_MCP_URL": "http://127.0.0.1:8765/mcp"}.items(): monkeypatch.setenv(k, v) - monkeypatch.delenv("ADMIN_ONLY", raising=False) + monkeypatch.delenv("BOT_ADMIN_ONLY", raising=False) assert Config.from_env().admin_only is False and Config.from_env().admin_chat_ids == frozenset() for value, on in (("", False), ("on", True), ("ON", True), ("1", True), ("yes", True), ("off", False), ("Off", False), ("0", False), ("no", False), ("false", False), ("ture", False), ("of", False)): # a typo keeps the default - monkeypatch.setenv("ADMIN_ONLY", value) + monkeypatch.setenv("BOT_ADMIN_ONLY", value) assert Config.from_env().admin_only is on, value - assert "ADMIN_ONLY: 'ture' is not on or off; keeping the default (off)" in caplog.text - ids = lambda text: _ids(text, frozenset(), "ADMIN_CHAT_IDS") + assert "BOT_ADMIN_ONLY: 'ture' is not on or off; keeping the default (off)" in caplog.text + ids = lambda text: _ids(text, frozenset(), "BOT_ADMIN_CHAT_IDS") assert ids("1, -1001 22,,x, 3.5 -7") == frozenset({1, -1001, 22, -7}) and ids("") == frozenset() - assert "ADMIN_CHAT_IDS: ignoring 'x', '3.5'" in caplog.text - monkeypatch.setenv("ADMIN_CHAT_IDS", "5 -9") + assert "BOT_ADMIN_CHAT_IDS: ignoring 'x', '3.5'" in caplog.text + monkeypatch.setenv("BOT_ADMIN_CHAT_IDS", "5 -9") assert Config.from_env().admin_chat_ids == frozenset({5, -9}) @@ -208,16 +230,21 @@ async def test_listed_ids_are_added_to_the_known_admins_never_replacing_them(tmp # ---------- the gate: private chats ---------- -@pytest.mark.parametrize("command, args", [("on_start", []), ("on_reset", []), ("on_keyboard", []), ("on_usage", []), ("on_ask", []), ("on_alerts", [])]) +@pytest.mark.parametrize("command, args", [("on_start", []), ("on_reset", []), ("on_keyboard", []), ("on_usage", []), ("on_ask", []), ("on_alerts", []), + ("on_command", [])]) async def test_a_stranger_is_refused_every_command_in_a_private_chat_and_is_not_remembered(tmp_path, command, args): + from lib.mcp_server import prompt bot, state, tg = make(tmp_path) - update, sent = message("/weather" if command == "on_ask" else "/x", user=STRANGER) + bot.commands() # (ecobot-mcp's prompts as commands: /now is one) + typed = {"on_ask": "/weather", "on_command": "/now"}.get(command, "/x") + update, sent = message(typed, user=STRANGER) await getattr(bot, command)(update, ctx(tg, *args)) assert [body for body, _ in sent] == [NOT_ADMIN] and STRANGER not in state.chats - update, sent = message("/weather" if command == "on_ask" else "/x", user=ADMIN) # an admin of a known group is let in + update, sent = message(typed, user=ADMIN) # an admin of a known group is let in await getattr(bot, command)(update, ctx(tg, *args)) - assert (bot.asked == ["Weather chart 1d"] if command == "on_ask" else sent) and NOT_ADMIN not in [body for body, _ in sent] # /weather asks for its chart - if command in ("on_start", "on_usage", "on_ask", "on_alerts"): + asked = {"on_ask": ["Weather chart 1d"], "on_command": [prompt("now").messages[0].content.text]} # /weather asks for its chart, /now its prompt + assert (bot.asked == asked[command] if command in asked else sent) and NOT_ADMIN not in [body for body, _ in sent] + if command in ("on_start", "on_usage", "on_ask", "on_alerts", "on_command"): assert ADMIN in state.chats @@ -246,13 +273,13 @@ async def test_a_refused_sender_is_logged_once_with_the_id_to_list(tmp_path, cap update, sent = message("how warm is it", user=STRANGER) await bot.on_message(update, ctx(tg)) assert [b for b, _ in sent] == [NOT_ADMIN] # told every time - assert refused() == [f"[Telegram {STRANGER}]: @u: refused: user {STRANGER} (U) is not a known group admin; add the id to ADMIN_CHAT_IDS to let them in"] + assert refused() == [f"[Telegram {STRANGER}]: @u: refused: user {STRANGER} (U) is not a known group admin; add the id to BOT_ADMIN_CHAT_IDS to let them in"] update, sent = message("hello", user=8) # another stranger: its own line await bot.on_message(update, ctx(tg)) assert len(refused()) == 2 and refused()[1].startswith("[Telegram 8]: @u: refused: user 8 (U) is not") update, sent = message("@testbot hi", user=ANONYMOUS, kind="supergroup", sender_chat=NS(id=GROUP, title="Home")) # as the group: the chat await bot.on_message(update, ctx(tg)) - assert refused()[2] == f"[Telegram {GROUP}]: @u, group 'Home': refused: chat {GROUP} (Home) is not a known group admin; add the id to ADMIN_CHAT_IDS to let them in" + assert refused()[2] == f"[Telegram {GROUP}]: @u, group 'Home': refused: chat {GROUP} (Home) is not a known group admin; add the id to BOT_ADMIN_CHAT_IDS to let them in" async def test_a_listed_user_can_use_the_bot_before_it_is_in_any_group(tmp_path): @@ -339,6 +366,12 @@ async def test_usage_is_the_help_and_alerts_button(tmp_path, kind): # ---------- every button comes in through one place ---------- +def period_keyboard(current=None): + """The period buttons under a chart of summary's (its drawn_by's periods), `current` shaded.""" + from lib.service.summary import OVER_TIME + return periods.periods_keyboard({"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]}, current) + + def alert_keyboard(opened="alerts"): return menu.keyboard(set(), menu.available_kinds({"Ecowitt"}), opened, set()) @@ -346,7 +379,7 @@ def alert_keyboard(opened="alerts"): async def test_a_stranger_is_refused_on_every_family_of_buttons_and_an_admin_is_let_through(tmp_path): bot, state, tg = make(tmp_path, irrigation=Remote()) state.add_chat(ADMIN, "Rob") - cases = [("al:off:rain:alerts", alert_keyboard()), (f"{periods.PREFIX}7", periods.keyboard(1)), + cases = [("al:off:rain:alerts", alert_keyboard()), (f"{periods.PREFIX}7d", period_keyboard("1d")), ("ir:open:water", irrigation_menu.keyboard(True, True))] for data, markup in cases: press = Press(data, markup, user=STRANGER) @@ -359,7 +392,7 @@ async def test_a_stranger_is_refused_on_every_family_of_buttons_and_an_admin_is_ press = Press("ir:open:water", irrigation_menu.keyboard(True, True), user=STRANGER) off = make(tmp_path, admin_only=False, irrigation=Remote())[0] await off.on_button(press.update(), ctx(tg)) - assert press.edits # ADMIN_ONLY=off: as before + assert press.edits # BOT_ADMIN_ONLY=off: as before async def test_alert_buttons_in_a_group_stay_admin_only_even_when_admin_only_is_off(tmp_path): @@ -389,10 +422,8 @@ def every_keyboard(bot): for opened in (None, *irrigation_menu.SECTIONS, "bogus"): for paused in (True, False): yield irrigation_menu.keyboard(battery, pause, opened, paused) - for current in (None, *periods.PERIODS): - yield periods.keyboard(current) - yield report_menu.keyboard() - yield report_menu.dashboard_keyboard() + for current in (None, *(p["period"] for p in OVER_TIME)): + yield period_keyboard(current) def test_every_button_the_bot_draws_is_short_plain_and_has_exactly_one_handler(tmp_path): @@ -406,7 +437,7 @@ def test_every_button_the_bot_draws_is_short_plain_and_has_exactly_one_handler(t assert 0 < len(data.encode()) <= MAX_CALLBACK_BYTES and data.isprintable(), data assert sum(data.startswith(prefix) for prefix in table) == 1, data assert bot._on_keyboard(NS(reply_markup=markup), data) - assert len(seen) > 60 and {p for p in table} == {"al:", "ir:", periods.PREFIX, report_menu.PREFIX} + assert len(seen) > 60 and {p for p in table} == {"al:", "ir:", periods.PREFIX, "st:"} # (rp:, the old report's 🔄, gone; st:, Status's) assert "ir:" not in make(tmp_path, irrigation=None)[0].buttons() @@ -425,8 +456,7 @@ def test_there_is_one_callback_handler_in_the_application_and_no_other_way_in(tm "{0.__class__}", "%s%s%s%n", "ir:water:-1", "ir:water:1e9", "al:off:__class__:unsub", "pd:__import__('os')"] -class Spy(Remote): - """The controller, recording everything it is asked to do.""" +Spy = Remote # (irrigation-mcp's controller records everything it is asked to do: commands(spy)) async def press_through(bot, tg, data, markup, user=ADMIN, kind="private"): @@ -439,12 +469,12 @@ async def test_a_forged_press_does_nothing_whoever_sends_it_and_whichever_family spy = Spy() bot, state, tg = make(tmp_path, irrigation=spy) unrelated = alert_keyboard("sub") # a keyboard that has none of the forged data - before = (dict(state.chats), list(spy.commands)) + before = (dict(state.chats), list(commands(spy))) for data in FORGED: for user in (ADMIN, STRANGER): press = await press_through(bot, tg, data, unrelated, user=user) assert press.edits == [] and press.toast == STALE_BUTTON, (data, user, press.toast) # believed or not comes first, for everyone - assert (state.chats, spy.commands) == before and spy.commands == [] # nothing changed, nothing sent to the controller + assert (state.chats, commands(spy)) == before and commands(spy) == [] # nothing changed, nothing sent to the controller async def test_malformed_presses_are_answered_and_never_raise(tmp_path): @@ -487,16 +517,16 @@ async def test_a_real_press_on_a_button_the_message_carries_still_works(tmp_path ("ir:water:10", irrigation_menu.keyboard(True, True, "water"))): press = await press_through(bot, tg, data, markup) assert press.toast not in (STALE_BUTTON, NOT_ADMIN_TOAST) and press.edits, data - assert bot.irrigation.commands == [("water", 10)] and state.muted(ADMIN) == {"rain"} + assert commands(bot.irrigation) == [("water", 10)] and state.muted(ADMIN) == {"rain"} stale = await press_through(bot, tg, "ir:water:10", irrigation_menu.keyboard(True, True)) # the Water list is not open on this message - assert stale.toast == STALE_BUTTON and bot.irrigation.commands == [("water", 10)] + assert stale.toast == STALE_BUTTON and commands(bot.irrigation) == [("water", 10)] async def test_random_data_never_gets_past_the_entry_point(tmp_path): rng = random.Random(7) spy = Spy() bot, state, tg = make(tmp_path, irrigation=spy) - boards = [alert_keyboard("sub"), irrigation_menu.keyboard(True, True), periods.keyboard(1), report_menu.keyboard()] + boards = [alert_keyboard("sub"), irrigation_menu.keyboard(True, True), period_keyboard("1d")] known = {b.callback_data for board_ in boards for row in board_.inline_keyboard for b in row} pieces = ["ir", "al", "pd", "on", "off", "water", "delay", "sw", "batt", "pause", "refresh", "open", "close", "all", "sub", "unsub", "rain", "uv", "24h", "cancel", "5", "30", "99999", "-1", "", " ", "\n", "é", "💧", "*", "%s", "{}", "\\", ";", "$(x)", "None"] @@ -507,7 +537,7 @@ async def test_random_data_never_gets_past_the_entry_point(tmp_path): continue press = await press_through(bot, tg, data, rng.choice(boards), user=rng.choice([ADMIN, STRANGER])) assert press.toast in (STALE_BUTTON, NOT_ADMIN_TOAST) and press.edits == [], repr(data) - assert spy.commands == [] and (dict(state.chats), dict(state.charts)) == before + assert commands(spy) == [] and (dict(state.chats), dict(state.charts)) == before def test_a_callback_query_from_python_telegram_bot_is_what_the_checks_read(): diff --git a/tests/test_agent.py b/tests/test_agent.py index 502f42a3..31536a16 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -34,17 +34,6 @@ async def handler(args, turn=None): return Tools([Tool("weather_now", "d", {"type": "object", "properties": {}}, handler)]), seen -async def test_fast_path_calls_the_model_only_at_the_end(): - t, seen = tools() - client = FakeLLM(["Sunny."]) - agent = llm.Agent(client, "m", t) - msgs = [{"role": "user", "content": "highs today"}] - reply = await agent.run(msgs, "sys", "none", first_call=("weather_now", {"groups": "outdoor"})) - assert reply == "Sunny." and len(client.requests) == 1 and seen == [{"groups": "outdoor"}] - assert client.requests[0]["tool_choice"] == "auto" and client.requests[0]["extra_body"] == {"reasoning": {"effort": "none"}} - assert [m["role"] for m in msgs] == ["user", "assistant", "tool", "assistant"] - - async def test_weather_questions_must_fetch_first_and_reasoning_is_passed_through(): t, seen = tools() client = FakeLLM([[("weather_now", {})], "Rain unlikely."]) @@ -114,7 +103,8 @@ async def test_reset_forgets_only_that_chat(alert_state): async def reply_text(text, **kw): sent.append(text) - bot = Bot(None, None, [], alert_state) + from tests.served import unreached + bot = Bot(None, None, alert_state, service=unreached()) # (only the chats' memory: ecobot-mcp is asked nothing) bot.chats[(1, None)].history.append({"role": "user", "content": "hi"}) bot.chats[(2, None)].history.append({"role": "user", "content": "other chat"}) bot.chats[(1, 7)].history.append({"role": "user", "content": "topic 7"}) @@ -130,79 +120,6 @@ async def reply_text(text, **kw): assert (1, 7) not in bot.chats and bot.chats[(2, None)].history -def test_the_prompt_defines_a_rainy_day_and_how_to_phrase_the_count(): - from datetime import datetime - from lib import prompt - from lib.ecowitt import days - text = prompt.build(datetime(2026, 9, 29, 14, 5), {"Ecowitt": "Ecowitt"}) - assert "rain >= 1" in text and "any rain" in text and "It rained on 507 of 1,454 days" in text - assert "1 mm or more" in days.DESCRIPTION - - -def test_the_prompt_asks_for_a_footnote_about_hotter_trace_days(): - from datetime import datetime - from lib import prompt - text = prompt.build(datetime(2026, 9, 29, 14, 5), {"Ecowitt": "Ecowitt"}) - assert "trace_rain_days" in text and "footnote" in text - - -def test_the_day_tool_schema_agrees_with_the_prompt_about_a_rainy_day(): - from lib.ecowitt import days - where = days.PARAMETERS["properties"]["where"]["description"] - assert "rain >= 1" in where and "rain > 0" not in where - - -def test_the_day_tool_rules_are_short_separate_bullets(): - from datetime import datetime - from lib import prompt - text = prompt.build(datetime(2026, 9, 29, 14, 5), {"Ecowitt": "Ecowitt"}) - block = text[text.index("- For questions that rank, compare or count DAYS"):text.index("- To ask whether rain comes WITH")] - bullets = [line for line in block.splitlines() if line.startswith(" - ")] - assert len(bullets) == 9 and all(len(b) < 300 for b in bullets) - for needle in ("sort_by", "rain >= 1", "It rained on 507 of 1,454 days", "trace_rain_days", "note_daily", "on record", "public_holiday", "known day", "RECORD"): - assert sum(needle in b for b in bullets) == 1, needle # each rule lives in exactly one bullet - - -def test_the_system_prompt_carries_the_period_hints_only_when_there_are_some(): - from datetime import datetime - from lib import intent, prompt - now = datetime(2026, 9, 29, 14, 5) - with_hint = prompt.build(now, {"Ecowitt": "Ecowitt"}, intent.period_hints("average temp 3m", now)) - assert "THE PERSON'S WORDS NAME THESE PERIODS" in with_hint and '"3m" = last 3 months: 2026-07-01' in with_hint - assert "THE PERSON'S WORDS NAME" not in prompt.build(now, {"Ecowitt": "Ecowitt"}, intent.period_hints("hello", now)) - - -def test_the_prompt_says_what_the_bot_can_and_cannot_do_for_the_sources_it_has(): - from datetime import datetime - from lib import prompt - now = datetime(2026, 9, 29, 14, 5) - both = prompt.build(now, {"Ecowitt": "Ecowitt weather station", "AirGradient": "AirGradient outdoor sensor"}) - assert "WHAT THIS BOT CAN AND CAN'T DO" in both and "PM2.5 (µg/m³)" in both and "weather_link" in both - assert "Custom alerts" in both and "solar radiation and UV index" in both and "Not available: lightning" in both and "correct the call once" in both - weather_only = prompt.build(now, {"Ecowitt": "Ecowitt weather station"}) - assert "Weather station:" in weather_only and "Air quality (outdoor AirGradient)" not in weather_only - assert "Weather station:" not in prompt.build(now, {"AirGradient": "AirGradient outdoor sensor"}) - - -async def test_a_question_about_the_bot_itself_gets_no_tools_and_the_hint(): - from datetime import datetime - from lib import prompt - t, seen = tools() - client = FakeLLM(["I track temperature, humidity..."]) - reply = await llm.Agent(client, "m", t).run([{"role": "user", "content": "list our metrics"}], "sys", "none", - tool_choice="none") - assert reply.startswith("I track") and client.requests[0]["tool_choice"] == "none" and seen == [] - now = datetime(2026, 9, 29, 14, 5) - assert "ABOUT THE BOT ITSELF" in prompt.build(now, {"Ecowitt": "Ecowitt"}, [], True) and "ABOUT THE BOT ITSELF" not in prompt.build(now, {"Ecowitt": "Ecowitt"}) - - -def test_the_prompt_never_shows_a_temperature_emoji_to_copy_and_says_no_entry_means_no_emoji(): - from datetime import datetime - from lib import prompt - text = prompt.build(datetime(2026, 9, 29, 14, 5), {"Ecowitt": "Ecowitt weather station"}) - assert '"outdoor.temperature": "' not in text and "a reading with no entry gets NO emoji" in text - - def chunk(content=None, calls=None, usage=None): delta = NS(content=content, tool_calls=calls) return NS(choices=[NS(delta=delta)] if (content is not None or calls) else [], usage=usage) @@ -244,77 +161,6 @@ async def test_streamed_answers_give_the_same_result_and_report_the_text_so_far( assert msgs[1]["tool_calls"][0]["function"] == {"name": "weather_now", "arguments": '{"groups": "outdoor"}'} -def test_a_rain_chart_caption_is_only_the_least_and_most_rain(): - from datetime import datetime - from lib import prompt - now = datetime(2026, 9, 29, 14, 5) - text = prompt.build(now, {"Ecowitt": "Ecowitt weather station"}, rain_caption=True) - assert "THIS IS A RAIN CHART" in text and "rain_outlook" not in text - assert "THIS IS A RAIN CHART" not in prompt.build(now, {"Ecowitt": "Ecowitt weather station"}) - - -def test_questions_about_the_bot_are_answered_as_simple_bullet_points(): - from datetime import datetime - from lib import prompt - text = prompt.build(datetime(2026, 9, 29, 14, 5), {"Ecowitt": "Ecowitt weather station"}, about_bot=True) - assert "simple bullet points" in text and "no sub-bullets" in text and "7 at most" in text and "No dates" in text - - -def test_the_capabilities_mention_the_new_sources_only_when_they_are_on(): - from lib import prompt - base = prompt.capabilities(["Ecowitt"]) - assert "pollen and thunderstorm asthma" in base.split("Not available:")[1] and "forecasts (only a short read" in base - both = prompt.capabilities(["Ecowitt", "Pollen", "Forecast"]) - assert "tool pollen_asthma" in both and "tool weather_forecast" in both and "thunderstorm asthma risk reaching High" in both - assert "pollen" not in both.split("Not available:")[1] and "forecasts" not in both.split("Not available:")[1] - - -async def test_several_fast_calls_run_together_before_the_model(): - seen = [] - - async def handler(args, turn=None): - seen.append(args) - return json.dumps({"ok": True}) - t = Tools([Tool("weather_now", "d", {"type": "object", "properties": {}}, handler), - Tool("air_quality", "d", {"type": "object", "properties": {}}, handler)]) - client = FakeLLM(["The report."]) - msgs = [{"role": "user", "content": "report"}] - reply = await llm.Agent(client, "m", t).run(msgs, "sys", "none", first_call=[("weather_now", {"groups": "outdoor"}), ("air_quality", {})]) - assert reply == "The report." and len(client.requests) == 1 and seen == [{"groups": "outdoor"}, {}] - assert [m["role"] for m in msgs] == ["user", "assistant", "tool", "tool", "assistant"] - assert [tc["id"] for tc in msgs[1]["tool_calls"]] == ["fast_1", "fast_2"] and [m["tool_call_id"] for m in msgs[2:4]] == ["fast_1", "fast_2"] - - - - - -def test_the_capabilities_mention_forecast_revision_alerts_only_with_the_forecast_source(): - from lib import prompt - assert "revised" not in prompt.capabilities(["Ecowitt"]) - assert "a forecast it sent being revised" in prompt.capabilities(["Ecowitt", "Forecast"]) - - -def test_the_capabilities_list_only_the_alerts_the_sources_send_with_their_own_thresholds(): - from lib import prompt - from lib.alerts.weather import GUST_ALERT_KMH - station, air = prompt.capabilities(["Ecowitt"]), prompt.capabilities(["AirGradient"]) - assert f"wind gusts over {GUST_ALERT_KMH} km/h" in station and "mask alerts" not in station - assert "mask alerts" in air and "rain starting" not in air and "Alerts, sent" not in prompt.capabilities([]) - - -def test_the_capabilities_say_pollen_only_runs_october_to_december(): - from lib import prompt - assert "only run from October to December" in prompt.capabilities(["Ecowitt", "Pollen"]) - - -def test_the_prompt_leaves_the_heads_up_to_the_bot_and_points_at_the_count_tool(): - from datetime import datetime - from lib import prompt - text = prompt.build(datetime(2026, 9, 29, 14, 5), {"Ecowitt": "Ecowitt weather station"}) - assert "the bot warns the chat by itself" in text and "\u26a0" not in text and "decline" not in text.lower() - assert "uv_max >= 9" in text and "count_only" in text - - async def test_the_chat_is_warned_once_before_the_model_is_sent_more_than_twice_a_500_point_querys_data(): from lib.llm import CHARS_PER_TOKEN, WARN_TOKENS from lib.tools import Turn @@ -341,13 +187,6 @@ async def tiny(args, turn=None): assert warned == [] -def test_the_prompt_says_to_use_the_whole_record_without_a_period_and_holidays_only_when_asked(): - from datetime import datetime - from lib import prompt - text = prompt.build(datetime(2026, 9, 29, 14, 5), {"Ecowitt": "Ecowitt weather station"}) - assert "use the whole record" in text and "only when the person's words say holidays or weekends" in text - - async def test_the_reasoning_effort_goes_to_openrouter_in_its_own_form(): t, _ = tools() client = FakeLLM([[("weather_now", {})], "Done."]) @@ -372,22 +211,6 @@ def test_older_answers_are_cut_to_their_first_lines_but_the_last_answer_and_ever assert len(llm.shorten_old(one_line)[0]["content"]) <= llm.OLD_ANSWER_CHARS + 2 -async def test_a_question_that_asks_for_the_air_sensors_own_readings_is_sent_the_tools_that_offer_them(): - from lib.tools import Turn - - async def handler(args, turn=None): - return json.dumps({"ok": True}) - base = {"type": "object", "properties": {"series": {"enum": ["humidity"]}}} - wider = {"type": "object", "properties": {"series": {"enum": ["humidity", "air_humidity"]}}} - t = Tools([Tool("plot_chart", "d", base, handler, asked=lambda: ("d+", wider)), Tool("weather_now", "d", {"type": "object", "properties": {}}, handler)]) - plain, asked = FakeLLM(["a"]), FakeLLM(["b"]) - await llm.Agent(plain, "m", t).run([{"role": "user", "content": "x"}], "sys", "none", turn=Turn()) - await llm.Agent(asked, "m", t).run([{"role": "user", "content": "x"}], "sys", "none", turn=Turn(air_extra=True)) - assert plain.requests[0]["tools"] == t.schemas and "air_humidity" not in json.dumps(plain.requests[0]["tools"]) - names = [s["function"]["name"] for s in asked.requests[0]["tools"]] - assert names == ["plot_chart", "weather_now"] and "air_humidity" in json.dumps(asked.requests[0]["tools"]) - - async def test_a_tool_that_fails_answers_the_model_with_the_error_and_only_a_bug_logs_its_traceback(caplog): import logging @@ -403,3 +226,19 @@ async def buggy(args, turn=None): assert await t.call("weather_history", "{}") == "Error calling tool: 'missing'" down, bug = caplog.records assert not down.exc_info and bug.exc_info # a failure is a line; a bug in the code keeps its traceback + + +def test_the_prompt_is_the_persona_then_the_servers_instructions_then_the_time(): + """docs/ecobot-mcp.md 4: the bot adds only its persona (a friendly Telegram bot, plain text, bullets, the caption a photo allows) + to the server's instructions; nothing about the tools, the periods or the data.""" + from datetime import datetime + from zoneinfo import ZoneInfo + from lib import prompt + from lib.service.instructions import INSTRUCTIONS + now = datetime(2026, 11, 10, 14, 5, tzinfo=ZoneInfo("Australia/Melbourne")) + text = prompt.build(now, INSTRUCTIONS) + assert text.startswith("You are a friendly weather bot on Telegram") and INSTRUCTIONS in text + assert text.rstrip().endswith("Now: Tuesday 10 November 2026, 14:05 (Australia/Melbourne time).") + assert "900 characters" in text and "•" in text and "Plain text only" in text + for gone in ("weather_history", "weather_now", "RIGHT NOW", "start_date", "chart_field", "TIME PERIODS", "Fahrenheit"): + assert gone not in text, gone diff --git a/tests/test_air_hass.py b/tests/test_air_hass.py index 53980e45..c5ebe3cd 100644 --- a/tests/test_air_hass.py +++ b/tests/test_air_hass.py @@ -136,7 +136,7 @@ async def test_without_home_assistant_there_is_nothing_to_import(tmp_path): async def test_the_air_sensor_shares_the_weather_stations_home_assistant_and_its_ranges_are_imported_on_a_schedule(tmp_path, monkeypatch): - import ecobot + from ecobot_mcp import core from lib.ecowitt import Ecowitt from tests.fakes import ecowitt_transport, home_assistant_transport cfg = config(tmp_path, homeassistant_url="http://ha", homeassistant_token="tok") @@ -144,9 +144,9 @@ async def test_the_air_sensor_shares_the_weather_stations_home_assistant_and_its ha_t, _ = home_assistant_transport() air_t, _ = air_transport() eco_init, air_init = Ecowitt.__init__, AirGradient.__init__ - monkeypatch.setattr(ecobot.Ecowitt, "__init__", lambda self, c, **kw: eco_init(self, c, eco_t, ha_t, **kw)) - monkeypatch.setattr(ecobot.AirGradient, "__init__", lambda self, c, **kw: air_init(self, c, transport=air_t, **kw)) - sources, _ = await ecobot.start_sources(cfg) + monkeypatch.setattr(core.Ecowitt, "__init__", lambda self, c, **kw: eco_init(self, c, eco_t, ha_t, **kw)) + monkeypatch.setattr(core.AirGradient, "__init__", lambda self, c, **kw: air_init(self, c, transport=air_t, **kw)) + sources, _ = await core.start_sources(cfg) eco, air = sources assert air.ha is eco.ha and air.ha is not None and not air._own_ha # one client, so Home Assistant failing is said once for source in sources: diff --git a/tests/test_airgradient.py b/tests/test_airgradient.py index 5c104e04..99f70538 100644 --- a/tests/test_airgradient.py +++ b/tests/test_airgradient.py @@ -9,6 +9,7 @@ from lib.timeutil import local_date from lib.tools import Turn from tests.fakes import TZ, air_transport, config +from tests import engines async def make(tmp_path): @@ -31,14 +32,27 @@ def test_aqi_and_ratings_follow_the_us_scale(): assert rating("pm2_5", 5).endswith("good") and rating("pm2_5", 55.5).endswith("very poor") +def test_pm10_has_its_own_aqi_and_the_us_aqi_is_the_higher_of_the_two(): + from lib.airgradient.metrics import pm10_aqi, us_aqi + assert [pm10_aqi(c) for c in (0, 54, 54.9, 55, 154, 155, 254, 255, 354, 355, 424, 425, 604, 700)] == [ + (0, "good"), (50, "good"), (50, "good"), (51, "moderate"), (100, "moderate"), (101, "unhealthy for sensitive groups"), + (150, "unhealthy for sensitive groups"), (151, "unhealthy"), (200, "unhealthy"), (201, "very unhealthy"), + (300, "very unhealthy"), (301, "hazardous"), (500, "hazardous"), (500, "hazardous")] # (a whole µg/m³: 54.9 is 54) + assert us_aqi(5.0, 200.0) == (*pm10_aqi(200.0), "PM10") # dust: PM10 sets it + assert us_aqi(40.0, 50.0) == (*pm25_aqi(40.0), "PM2.5") # smoke: PM2.5 does + assert us_aqi(9.0, 54.0) == (50, "good", "PM2.5") # a tie: PM2.5's + assert us_aqi(None, 60.0)[2] == "PM10" and us_aqi(None, None) is None + + async def test_current_reading_with_ratings(tmp_path): air, _ = await make(tmp_path) - async def no_previous(ts, count): + async def no_previous(ts, count, held=False): return [] # the fake history's PM2.5 depends on the hour, so the previous reading would too air._previous_rows = no_previous - reading = json.loads(await air.handle({})) + reading = json.loads(await engines.air_history(air, {})) assert reading["pm2_5"]["value"] == 12.0 and reading["pm2_5"]["band"] == "moderate" + assert (reading["pm10"]["aqi_us"], reading["pm10"]["band"]) == (7, "good") # PM10 8.0: its own AQI too assert set(reading) == {"sensor", "sensor_type", "time", *METRICS} and reading["pm2_5"]["rating"].endswith("poor") await air.close() @@ -46,10 +60,10 @@ async def no_previous(ts, count): async def test_a_rating_is_the_level_the_last_two_readings_both_reached(tmp_path): air, _ = await make(tmp_path) for before, band, noted in ((5.0, "good", True), (20.0, "moderate", False)): - async def previous(ts, count, before=before): + async def previous(ts, count, held=False, before=before): return [{"pm2_5": before}] air._previous_rows = previous - reading = json.loads(await air.handle({})) + reading = json.loads(await engines.air_history(air, {})) assert reading["pm2_5"]["value"] == 12.0 and reading["pm2_5"]["band"] == band assert ("rating_note" in reading["pm2_5"]) is noted await air.close() @@ -59,7 +73,7 @@ async def test_history_summary_and_chart(tmp_path): air, _ = await make(tmp_path) day = datetime.now(TZ).date() - timedelta(days=2) turn = Turn() - out = json.loads(await air.handle({"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59", "chart": True, + out = json.loads(await engines.air_history(air, {"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59", "chart": True, "metrics": ["pm2_5", "co2"]}, turn)) assert out["pm2_5"]["high"] >= out["pm2_5"]["low"] and "high_aqi_us" in out["pm2_5"] (chart,) = turn.charts @@ -72,7 +86,7 @@ async def test_a_chart_the_model_names_no_reading_for_is_of_the_one_the_person_a day = datetime.now(TZ).date() - timedelta(days=5) for named, title in (([], "PM2.5"), (["co2"], "CO₂")): # "give me that timestamp", after "CO2 since Sunday": CO2, not PM2.5 turn = Turn(air_named=named) - await air.handle({"start_date": f"{day} 00:00:00", "end_date": f"{day + timedelta(days=3)} 23:59:59"}, turn) # 3+ days: drawn anyway + await engines.air_history(air, {"start_date": f"{day} 00:00:00", "end_date": f"{day + timedelta(days=3)} 23:59:59"}, turn) # 3+ days: drawn anyway (chart,) = turn.charts assert chart.title == title await air.close() @@ -83,21 +97,20 @@ async def test_finished_days_are_fetched_once(tmp_path): await air.warm(True) n = len(calls) day = datetime.now(TZ).date() - timedelta(days=3) - await air.handle({"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"}) + await engines.air_history(air, {"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"}) assert len(calls) == n # already warmed await air.close() -async def test_warm_summary_and_wants(tmp_path): +async def test_warm_summary(tmp_path): air, _ = await make(tmp_path) assert (await air.warm(True)).startswith("AirGradient ") and (await air.warm(True)).endswith(" req") - assert air.wants("how's the air?") and not air.wants("what's the temperature") await air.close() async def test_history_is_capped_at_14_days(tmp_path): air, _ = await make(tmp_path) - out = json.loads(await air.handle({"start_date": "2026-01-01 00:00:00", "chart": False, "end_date": "2026-03-01 00:00:00"})) + 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"})) assert "note_period" in out or out.get("error") is None await air.close() @@ -112,12 +125,12 @@ async def test_finished_days_survive_a_restart_and_need_no_requests(tmp_path): air, calls = await make(tmp_path) day = datetime.now(TZ).date() - timedelta(days=3) args = {"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"} - first = json.loads(await air.handle(args)) + first = json.loads(await engines.air_history(air, args)) assert calls.count("past") == 1 await air.close() dead = httpx.MockTransport(lambda r: httpx.Response(500)) # AirGradient is unreachable now again = AirGradient(config(tmp_path), transport=dead) - assert json.loads(await again.handle(args)) == first + assert json.loads(await engines.air_history(again, args)) == first assert again.requests == 0 await again.close() @@ -132,7 +145,7 @@ async def test_backfill_walks_back_to_the_start_of_the_sensors_data(tmp_path): assert await air.backfill(pace=0, empty_stop=3) == (0, 0, total) # nothing left to fetch assert len(calls) == n # and a long question is now answered entirely from the cache - out = json.loads(await air.handle({"start_date": (datetime.now(TZ) - timedelta(days=9)).strftime("%Y-%m-%d %H:%M:%S"), + out = json.loads(await engines.air_history(air, {"start_date": (datetime.now(TZ) - timedelta(days=9)).strftime("%Y-%m-%d %H:%M:%S"), "end_date": (datetime.now(TZ) - timedelta(days=2)).strftime("%Y-%m-%d %H:%M:%S")})) assert out["readings"] > 100 and len(calls) == n and "note_missing" not in out await air.close() @@ -167,7 +180,7 @@ async def test_backfill_stops_after_repeated_failures(tmp_path): async def test_missing_days_are_fetched_inline_only_up_to_a_limit(tmp_path, monkeypatch): monkeypatch.setattr(source, "MAX_INLINE_DAYS", 3) air, calls = await make(tmp_path) - out = json.loads(await air.handle({"start_date": (datetime.now(TZ) - timedelta(days=30)).strftime("%Y-%m-%d %H:%M:%S"), + out = json.loads(await engines.air_history(air, {"start_date": (datetime.now(TZ) - timedelta(days=30)).strftime("%Y-%m-%d %H:%M:%S"), "end_date": datetime.now(TZ).strftime("%Y-%m-%d %H:%M:%S")})) assert calls.count("past") <= 3 and "note_missing" in out and out["readings"] > 0 # one window, plus today (and yesterday, in the small hours) await air.close() @@ -222,7 +235,7 @@ async def test_requests_never_ask_for_more_than_ten_days(tmp_path): await air.backfill(pace=0, empty_stop=3) assert 2 <= calls.count("past") <= 10 and longest_request(transport) <= timedelta(days=10) day = datetime.now(TZ) - timedelta(days=200) - out = json.loads(await air.handle({"start_date": day.strftime("%Y-%m-%d %H:%M:%S"), + out = json.loads(await engines.air_history(air, {"start_date": day.strftime("%Y-%m-%d %H:%M:%S"), "end_date": (day + timedelta(days=25)).strftime("%Y-%m-%d %H:%M:%S")})) assert "error" not in out and longest_request(transport) <= timedelta(days=10) # 422s would have failed the answer await air.close() @@ -234,7 +247,7 @@ async def test_no_data_available_is_an_empty_period_not_a_failure(tmp_path): fetched, failed, total = await air.backfill(pace=0, empty_stop=5, empty_before_data=5) assert failed == 0 and fetched >= 5 and total == 5 day = datetime.now(TZ).date() - timedelta(days=3) - out = json.loads(await air.handle({"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"})) + out = json.loads(await engines.air_history(air, {"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"})) assert out["note"] == "No readings for this period." and "error" not in out await air.close() @@ -244,10 +257,10 @@ async def test_answers_say_when_old_days_are_hourly_averages(tmp_path): air = AirGradient(config(tmp_path), transport=transport) now = datetime.now(TZ) fmt = "%Y-%m-%d %H:%M:%S" - out = json.loads(await air.handle({"start_date": (now - timedelta(days=9)).strftime(fmt), + out = json.loads(await engines.air_history(air, {"start_date": (now - timedelta(days=9)).strftime(fmt), "end_date": (now - timedelta(days=1)).strftime(fmt)})) assert "hourly averages" in out["note_resolution"] and out["note_resolution"].startswith(("4 ", "5 ", "6 ")) - recent = json.loads(await air.handle({"start_date": (now - timedelta(days=3)).strftime(fmt), + recent = json.loads(await engines.air_history(air, {"start_date": (now - timedelta(days=3)).strftime(fmt), "end_date": (now - timedelta(days=1)).strftime(fmt)})) assert "note_resolution" not in recent await air.close() @@ -294,7 +307,7 @@ async def test_air_charts_too_long_for_the_point_budget_are_bucketed_and_carry_a async def specs(days_back, metrics): turn = Turn() - await air.handle({"start_date": (now - timedelta(days=days_back)).strftime(fmt), "end_date": now.strftime(fmt), + await engines.air_history(air, {"start_date": (now - timedelta(days=days_back)).strftime(fmt), "end_date": now.strftime(fmt), "chart": True, "metrics": metrics}, turn) return turn.charts short = (await specs(3, ["pm2_5"]))[0].panels[0].lines[0] @@ -317,7 +330,7 @@ async def specs(days_back, metrics): async def current_with(tmp_path, latest, earlier, gap=300): - """air.current() when the latest reading is `latest` and today's cache holds `earlier` (a list of values `gap` seconds apart, + """engines.air_now(air) when the latest reading is `latest` and today's cache holds `earlier` (a list of values `gap` seconds apart, oldest first, the last one `gap` seconds before the latest).""" from datetime import timezone from tests.fakes import air_row @@ -333,7 +346,7 @@ async def current_row(refresh=False): async def day_rows(day, refresh=False): return cached air._current_row, air._day_rows = current_row, day_rows - out = await air.current() + out = await engines.air_now(air) await air.close() return out @@ -410,22 +423,27 @@ async def test_every_air_day_row_is_what_the_glitch_rule_in_python_gives(tmp_pat async def test_air_days_counts_days_by_a_metric_and_draws_the_months_as_bars(tmp_path): - from lib.airgradient.days import air_days_tool - from lib.tools import Turn + """The service's days tool over the air sensor's day rows (until step 6c: air_days' own engine, tests/old_tools.py, deleted).""" + from types import SimpleNamespace + from lib.service import days as days_tool + from lib.service.context import Context + from lib.specs import from_json from tests.fakes import TZ store, start = await _air_store(tmp_path) end = datetime.now(TZ).date() - timedelta(days=1) - turn = Turn() - out = json.loads(await air_days_tool(store, TZ, dict(start_date=str(start), end_date=str(end), - where=[{"field": "pm2_5_max", "op": ">", "value": 25}], count_only=True, group_by="month"), turn)) + (tool,) = days_tool.tools(Context(air=SimpleNamespace(store=store, tz=TZ), tz=TZ)) + + async def air_days(**args): + return json.loads(await tool.call({"start": str(start), "end": str(end), **args}, None)) + out = await air_days(where=[{"field": "pm2_5_max", "op": ">", "value": 25}], count_only=True, group_by="month") assert out["matching_days"] == 4 and out["days_checked"] == 40 and "days" not in out - assert sum(out["by_month"].values()) == 4 and turn.charts[0].title == "Days with PM2.5 > 25 µg/m³" - mean = json.loads(await air_days_tool(store, TZ, dict(start_date=str(start), end_date=str(end), stat="avg", of="co2_avg", count_only=True))) + assert sum(out["by_month"].values()) == 4 and from_json(out["charts"][0]).title == "Days with PM2.5 > 25 µg/m³" + mean = await air_days(stat="avg", of="co2_avg", count_only=True) assert mean["stat"]["what"] == "Average CO₂" and 500 < mean["value"] < 600 # 420 + the mean of 0..287 - worst = json.loads(await air_days_tool(store, TZ, dict(start_date=str(start), end_date=str(end), sort_by="pm2_5_max", limit=2))) + worst = await air_days(sort_by="pm2_5_max", limit=2) assert [r["pm2_5_max"] for r in worst["days"]] == [40.0, 40.0] - bad = json.loads(await air_days_tool(store, TZ, dict(start_date=str(start), end_date=str(end), where=[{"field": "uv_max", "op": ">", "value": 1}]))) - assert "unusable condition" in bad["error"] + bad = await air_days(where=[{"field": "uv_max", "op": ">", "value": 1}]) + assert "Field 'uv_max' is the weather station's, and this service has no weather station" in bad["error"] # (not the air sensor's) store.close() @@ -453,17 +471,18 @@ async def test_a_single_reading_spike_is_in_none_of_the_figures_either(tmp_path) from lib.timeutil import local_date from tests.fakes import TZ air, _ = await make(tmp_path) - start = air.now().replace(microsecond=0) - timedelta(hours=1) - t0 = int(start.replace(tzinfo=TZ).timestamp()) + 600 + first = (int(air.now().replace(tzinfo=TZ).timestamp()) - 3600) // 1800 * 1800 # the start of a half hour, an hour or more ago + start = datetime.fromtimestamp(first, TZ).replace(tzinfo=None) + t0 = first + 600 levels = [(1, 2, 3), (1, 2, 4), (15.3, 14.2, 28.7), (3, 8, 10), (2, 4, 5), (2, 3, 4)] rows = [{"ts": t0 + 300 * i, "pm1": a, "pm2_5": b, "pm10": c} for i, (a, b, c) in enumerate(levels)] async def day_rows(day, refresh=False): return [r for r in rows if local_date(r["ts"], TZ) == day] air._day_rows = day_rows - out = await air.history(start.strftime("%Y-%m-%d %H:%M:%S"), None) + out = await air.history(f"{start:%Y-%m-%d %H:%M:%S}", f"{start + timedelta(hours=1):%Y-%m-%d %H:%M:%S}") assert out["pm10"]["high"] == 10 and out["pm2_5"]["high"] == 8 and out["pm1"]["high"] == 3 # not 28.7, 14.2 and 15.3 - assert out["pm10"]["average"] == round((3 + 4 + 10 + 5 + 4) / 5, 1) # and not in the mean + assert out["pm10"]["average"] == round(((3 + 4 + 10) / 3 + (5 + 4) / 2) / 2, 1) # and not in the mean (by half hours) day = local_date(t0, TZ) await air.store.save_day(day, [r for r in rows if local_date(r["ts"], TZ) == day]) # the day rows take the same spikes out figures = await air.store.day_figures(day, day, ["pm10_max", "pm2_5_max", "pm10_avg"]) @@ -493,7 +512,7 @@ async def test_the_latest_reading_comes_with_the_lowest_of_the_last_readings_for air, _ = await make(tmp_path) reading, at, sustained = await air.latest() assert set(sustained) >= {"pm2_5"} and sustained["pm2_5"] <= reading["pm2_5"]["value"] and at.tzinfo is not None - assert json.loads(await air.handle({}, None)) == json.loads(json.dumps(reading)) # the tool gives the reading alone + assert json.loads(await engines.air_history(air, {}, None)) == json.loads(json.dumps(reading)) # the tool gives the reading alone await air.close() @@ -503,7 +522,7 @@ async def test_the_reading_is_rated_alone_when_only_the_history_fails(tmp_path, async def down(day, refresh=False): raise RuntimeError("AirGradient past failed: HTTP 500") air._day_rows = down - reading = json.loads(await air.handle({})) + reading = json.loads(await engines.air_history(air, {})) assert reading["pm2_5"]["value"] == 12.0 and "rating_note" not in reading["pm2_5"] and "rating the latest alone" in caplog.text assert (await air.latest()).sustained["pm2_5"] == 12.0 await air.close() @@ -538,13 +557,13 @@ async def day_rows(day, refresh=False): def test_the_antispike_setting_is_a_number_of_readings_default_2_and_off_is_1(monkeypatch): from lib.config import Config - for k, v in (("TELEGRAM_BOT_TOKEN", "t"), ("OPENROUTER_API_KEY", "k"), ("ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b")): + for k, v in (("BOT_TELEGRAM_TOKEN", "t"), ("BOT_OPENROUTER_API_KEY", "k"), ("MCP_ECOWITT_API_KEY", "a"), ("MCP_ECOWITT_APP_KEY", "b")): monkeypatch.setenv(k, v) - monkeypatch.delenv("ANTISPIKE_REQUIRE_CONSECUTIVE", raising=False) - assert Config.from_env().antispike_require_consecutive == 2 + monkeypatch.delenv("MCP_ANTISPIKE_REQUIRE_CONSECUTIVE", raising=False) + assert Config.from_env(bot=False).antispike_require_consecutive == 2 # (ecobot-mcp's setting) for value, want in (("3", 3), ("1", 1), ("0", 1), ("off", 1), ("junk", 2), ("", 2)): - monkeypatch.setenv("ANTISPIKE_REQUIRE_CONSECUTIVE", value) - assert Config.from_env().antispike_require_consecutive == want, value + monkeypatch.setenv("MCP_ANTISPIKE_REQUIRE_CONSECUTIVE", value) + assert Config.from_env(bot=False).antispike_require_consecutive == want, value async def test_a_date_with_an_offset_is_read_and_a_bad_one_is_not_called_a_sensor_fault(tmp_path): @@ -552,8 +571,8 @@ async def test_a_date_with_an_offset_is_read_and_a_bad_one_is_not_called_a_senso from datetime import timezone as tz_ air, _ = await make(tmp_path) start = (datetime.now(TZ) - timedelta(days=2)).astimezone(tz_.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - out = json.loads(await air.handle({"start_date": start})) - bad = json.loads(await air.handle({"start_date": "yesterday morning"})) + out = json.loads(await engines.air_history(air, {"start_date": start})) + bad = json.loads(await engines.air_history(air, {"start_date": "yesterday morning"})) await air.close() assert "error" not in out and out["readings"] > 0 and bad["error"].startswith("bad date") @@ -572,14 +591,14 @@ async def test_the_sensors_own_temperature_and_humidity_are_kept_but_given_only_ air, _ = await make(tmp_path) day = local_date(datetime.now(TZ).timestamp() - 86400, TZ) span = {"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"} - assert "air_humidity" not in json.loads(await air.handle({})) and "air_humidity" not in json.loads(await air.handle(span)) - now = json.loads(await air.handle({"metrics": ["air_humidity", "air_temperature"]})) + assert "air_humidity" not in json.loads(await engines.air_history(air, {})) and "air_humidity" not in json.loads(await engines.air_history(air, span)) + now = json.loads(await engines.air_history(air, {"metrics": ["air_humidity", "air_temperature"]})) assert now["air_humidity"]["unit"] == "%" and now["air_temperature"]["unit"] == "°C" and "rating" not in now["air_humidity"] assert "pm2_5" in now # the air itself is still there - out = json.loads(await air.handle({**span, "metrics": ["air_humidity"]})) + out = json.loads(await engines.air_history(air, {**span, "metrics": ["air_humidity"]})) assert out["air_humidity"]["unit"] == "%" and {"low", "high", "average"} <= set(out["air_humidity"]) and "air_temperature" not in out turn = Turn() - out = json.loads(await air.handle({**span, "chart": True, "metrics": ["air_temperature", "air_humidity"]}, turn)) + out = json.loads(await engines.air_history(air, {**span, "chart": True, "metrics": ["air_temperature", "air_humidity"]}, turn)) assert turn.charts[0].title == "AirGradient temperature and AirGradient humidity" and len(turn.charts[0].panels) == 2 assert [p.unit for p in turn.charts[0].panels] == ["°C", "%"] await air.close() diff --git a/tests/test_airgradient_local.py b/tests/test_airgradient_local.py index 62c757a2..a19f63bc 100644 --- a/tests/test_airgradient_local.py +++ b/tests/test_airgradient_local.py @@ -310,8 +310,8 @@ async def test_airgradient_source_picks_the_monitors_sources_and_a_typo_keeps_au assert (air.local is not None, air.ha is not None, air.cloud) == (monitor, home, cloud), kwargs await air.close() from lib.config import _air_source - assert _air_source("Cloud", "auto", "AIRGRADIENT_SOURCE") == "cloud" - assert _air_source("sensor", "auto", "AIRGRADIENT_SOURCE") == "auto" and "AIRGRADIENT_SOURCE: 'sensor' is not" in caplog.text + assert _air_source("Cloud", "auto", "MCP_AIRGRADIENT_SOURCE") == "cloud" + assert _air_source("sensor", "auto", "MCP_AIRGRADIENT_SOURCE") == "auto" and "MCP_AIRGRADIENT_SOURCE: 'sensor' is not" in caplog.text async def test_each_reading_of_the_monitor_is_kept_as_a_minute_and_a_short_chart_is_drawn_from_them(tmp_path, monkeypatch): diff --git a/tests/test_alert_log.py b/tests/test_alert_log.py new file mode 100644 index 00000000..9b1ae3bf --- /dev/null +++ b/tests/test_alert_log.py @@ -0,0 +1,380 @@ +"""The alert log (lib/alert_log.py), the rules' own store (lib/alerts/store.py) and the bot's delivery from the log +(lib/alerts/notify.AlertDelivery): docs/ecobot-mcp.md 3.6 and section 4.""" + +import asyncio +from types import SimpleNamespace as NS + +import pytest + +from lib.alert_log import KEEP_SECONDS, AlertLog +from lib.alerts.menu import alert_keyboard +from lib.alerts.notify import AlertDelivery, AlertState, Notifier +from lib.alerts.pictures import CHARTS, Picture +from lib.alerts.store import AlertStore +from tests.fakes import TZ + +T0 = 1_790_000_000.0 # 2026-09-21, a time the tests' clock starts at + + +class Clock: + def __init__(self, t=T0): + self.t = t + + def __call__(self): + return self.t + + +def new_log(tmp_path, clock=None): + return AlertLog(tmp_path / "alerts.sqlite", TZ, now=clock or Clock()) + + +# ---------- the log ---------- +def test_events_are_kept_in_order_with_rising_ids_and_their_parts(tmp_path): + log = new_log(tmp_path) + chart = {"title": "Wind", "drawn_by": {"tool": "summary", "arguments": {"readings": ["wind"], "period": "1d", "chart": True}}} + first = log.append("rain", "🌧️ It's started raining.", "Rain started", {"rate_mm_h": 1.2}, expires=T0 + 3600) + second = log.append("gusts", "💨 Strong gusts", "Strong gusts", expires=T0 + 3600, link=("live chart", "https://x"), chart=chart) + assert (first["id"], second["id"]) == (1, 2) and log.last_id() == 2 + assert first == {"id": 1, "kind": "rain", "time": "2026-09-22T00:13:20+10:00", "expires": "2026-09-22T01:13:20+10:00", + "title": "Rain started", "text": "🌧️ It's started raining.", "data": {"rate_mm_h": 1.2}} + assert second["link"] == {"label": "live chart", "url": "https://x"} and second["chart"] == chart and second["data"] == {} + assert [e["id"] for e in log.since(0)] == [1, 2] and [e["id"] for e in log.since(1)] == [2] and log.since(2) == [] + assert log.get(2) == second and log.get(3) is None + + +def test_the_log_survives_a_restart_and_its_ids_never_go_back(tmp_path): + clock = Clock() + log = new_log(tmp_path, clock) + for n in range(3): + log.append("uv", f"UV {n}", "Very high UV", expires=T0 + 3600) + log.close() + clock.t += KEEP_SECONDS + 1 # a month later: those are dropped when it opens again ... + again = new_log(tmp_path, clock) + assert again.since(0, expired=True) == [] and again.last_id() == 3 + assert again.append("uv", "UV 3", "Very high UV")["id"] == 4 # ... and the ids carry on + third = new_log(tmp_path, clock) + assert [e["text"] for e in third.since(0)] == ["UV 3"] + + +def test_since_leaves_out_what_has_expired_unless_asked(tmp_path): + clock = Clock() + log = new_log(tmp_path, clock) + log.append("rain", "short", "t", expires=T0 + 60) + log.append("pollen_and_asthma", "long", "t", expires=T0 + 86400) + log.append("rain", "never", "t") + clock.t += 120 + assert [e["text"] for e in log.since(0)] == ["long", "never"] + assert [e["text"] for e in log.since(0, expired=True)] == ["short", "long", "never"] + + +async def test_a_reader_waits_for_the_next_event(tmp_path): + log = new_log(tmp_path) + assert await log.wait(0, timeout=0.05) is False + waiter = asyncio.create_task(log.wait(0)) + await asyncio.sleep(0.01) + assert not waiter.done() + log.append("rain", "x", "t") + assert await asyncio.wait_for(waiter, 1) is True + assert await log.wait(0, timeout=0.01) is True # one is there already: no wait + assert await log.wait(1, timeout=0.05) is False + + +# ---------- the rules' store ---------- +def test_the_rules_state_moves_out_of_the_bots_file_once_so_nothing_fires_again(tmp_path): + bot = AlertState(tmp_path / "bot_state.json") + bot.add_chat(1, "chat") + bot.monitor.update(rain={"alerted_state": "raining", "alerted_time": 5}, uv={"active": True, "calm_since": None}, + particulates={"unsafe": True}, irrigation_monitor={"checked": "2026-10-01"}, forecast_sent={"1": {}}) + bot.save() + loaded = AlertState(bot.path) + store = AlertStore(tmp_path / "alert_state.json", moved_from=loaded) + assert store.monitor == {"rain": {"alerted_state": "raining", "alerted_time": 5}, "uv": {"active": True, "calm_since": None}, + "particulates": {"unsafe": True}} + assert AlertState(bot.path).monitor == {"irrigation_monitor": {"checked": "2026-10-01"}} # the controller's stays; the forecast record goes + assert AlertStore(store.path).monitor == store.monitor + again = AlertState(bot.path) + again.monitor["rain"] = {"alerted_state": "dry"} # (as an old bot_state.json copied back would have) + assert AlertStore(store.path, moved_from=again).monitor["rain"]["alerted_state"] == "raining" # moved once only + + +# ---------- the bot's delivery ---------- +class Telegram: + def __init__(self): + self.sent = [] + + async def send_message(self, chat_id, text, **kw): + self.sent.append((chat_id, text, None, kw)) + return NS(photo=None) + + async def send_photo(self, chat_id, photo, **kw): + self.sent.append((chat_id, kw["caption"], photo, kw)) + return NS(photo=(NS(file_id="small"), NS(file_id=f"copy of {chat_id}"))) + + +def rows(markup): + return [[(b.text, b.callback_data) for b in row] for row in markup.inline_keyboard] + + +CHART = {"title": "Wind", "drawn_by": {"tool": "summary", "arguments": {"readings": ["wind"], "period": "1d", "chart": True}}} + + +def delivery(tmp_path, clock=None, chats=(1, 2, 3), state=None, monkeypatch=None, weather=None): + """The delivery from a log (the bot's reads ecobot-mcp's over MCP, lib/weather.RemoteAlerts: the same reads), `weather` drawing the + events' charts (ecobot-mcp as the bot reaches it).""" + log = new_log(tmp_path, clock) + state = state or AlertState(tmp_path / "bot_state.json") + for chat in chats: + state.add_chat(chat, str(chat)) + telegram = Telegram() + return AlertDelivery(log, Notifier(telegram, state), state, TZ, weather=weather), log, state, telegram + + +async def test_each_event_goes_to_the_chats_subscribed_to_its_kind_silently_unless_sound_is_on(tmp_path): + d, log, state, telegram = delivery(tmp_path) + state.set_kind(2, "rain", False) + state.set_sound(3, "rain", True) + log.append("rain", "🌧️ It's started raining.", "Rain started", expires=T0 + 3600) + assert await d.deliver_new() == 1 + assert [(chat, text, kw["disable_notification"]) for chat, text, _, kw in telegram.sent] == [(1, "🌧️ It's started raining.", True), + (3, "🌧️ It's started raining.", False)] + assert rows(telegram.sent[0][3]["reply_markup"]) == [[("🔔 ▸", "al:open:bell:rain")]] # the bell; no chart, no 🔄 + assert state.read == 1 and AlertState(state.path).read == 1 + + +async def test_an_events_link_is_its_footer(tmp_path): + d, log, state, telegram = delivery(tmp_path, chats=(1,)) + log.append("pollen_and_asthma", "🔴 Grass pollen forecast is High.", "Grass", expires=T0 + 3600, + link=("melbournepollen.com.au", "https://www.melbournepollen.com.au/")) + await d.deliver_new() + (chat, text, _, kw), = telegram.sent + assert text == "🔴 Grass pollen forecast is High.\nmelbournepollen.com.au" + assert [e.url for e in kw["entities"] if e.url] == ["https://www.melbournepollen.com.au/"] + + +async def test_an_events_chart_is_drawn_from_its_data_once_and_its_refresh_names_the_event(tmp_path, monkeypatch): + from lib.alerts import notify + drawn = [] + + async def picture_of(data, tz, weather): + drawn.append(data) + return Picture(b"png", "Wind, today", None, data["drawn_by"]) + monkeypatch.setattr(notify, "picture_of", picture_of) + d, log, state, telegram = delivery(tmp_path, weather=NS()) # (drawn by ecobot-mcp: picture_of, stood in for here) + state.set_kind(3, "gusts", False) + log.append("rain", "earlier", "Rain started", expires=T0 + 3600) + event = log.append("gusts", "💨 Strong gusts: 55 km/h at 3:05pm (alerts above 40 km/h).", "Strong gusts", expires=T0 + 3600, chart=CHART) + await d.deliver_new() + photos = [(chat, photo) for chat, _, photo, _ in telegram.sent if photo] + assert drawn == [CHART] and photos == [(1, b"png"), (2, "copy of 1")] # drawn once, uploaded once + assert rows(telegram.sent[-1][3]["reply_markup"]) == [[("🔔 ▸", "al:open:bell:gusts"), ("🔄", f"al:refresh:gusts:{event['id']}")]] + + +async def test_a_real_chart_in_an_event_is_drawn_as_a_picture(serve, tmp_path, archived_cache): + """An event's chart is drawn by ecobot-mcp (its drawn_by replayed there: the bot draws nothing), over the fake station.""" + from lib.alerts import pictures + from lib.service.context import Context + from tests.fakes import archived_station + eco, _ = await archived_station(tmp_path, archived_cache) + data = await pictures.chart_data(eco, CHARTS["gusts"], TZ) + assert data["drawn_by"]["tool"] == "summary" and data["drawn_by"]["arguments"]["period"] + (tmp_path / "d").mkdir() + weather = await serve(Context(eco=eco, tz=TZ)) + d, log, state, telegram = delivery(tmp_path / "d", chats=(1,), weather=weather) + log.append("gusts", "💨 Strong gusts", "Strong gusts", chart=data) + await d.deliver_new() + (_, _, photo, _), = telegram.sent + assert photo[:4] == b"\x89PNG" + await eco.close() + + +async def test_a_restart_resumes_after_the_last_event_handled_and_skips_what_expired_meanwhile(tmp_path): + clock = Clock() + d, log, state, telegram = delivery(tmp_path, clock, chats=(1,)) + log.append("rain", "first", "t", expires=T0 + 3600) + await d.deliver_new() + log.append("rain", "the morning's rain", "t", expires=T0 + 3600) # sent while the bot was down ... + log.append("pollen_and_asthma", "today's pollen", "t", expires=T0 + 86400) + clock.t += 2 * 3600 # ... and it is back two hours later + restarted = AlertDelivery(new_log(tmp_path, clock), Notifier(telegram, AlertState(state.path)), AlertState(state.path), TZ) + assert restarted.last == 1 + await restarted.deliver_new() + assert [text for _, text, _, _ in telegram.sent] == ["first", "today's pollen"] # the rain is not news; the pollen still is + assert restarted.last == 3 + log.append("uv", "expired at once", "t", expires=clock.t - 1) + await restarted.deliver_new() + assert len(telegram.sent) == 2 and restarted.last == 4 # skipped, and not looked at again + + +async def test_the_first_start_begins_after_the_newest_event(tmp_path): + log = new_log(tmp_path) + log.append("rain", "old news", "t") + state = AlertState(tmp_path / "bot_state.json") + state.add_chat(1, "1") + telegram = Telegram() + d = AlertDelivery(log, Notifier(telegram, state), state, TZ) + assert d.last == 1 + await d.deliver_new() + assert telegram.sent == [] + + +async def test_a_removed_log_is_noticed_and_delivery_starts_again_from_the_new_one(tmp_path, caplog): + d, log, state, telegram = delivery(tmp_path, chats=(1,)) + for i in range(5): + log.append("rain", f"old {i}", "t") + await d.deliver_new() + assert state.read == 5 + log.close() + (tmp_path / "alerts.sqlite").unlink() # removed while the bot was down; bot_state.json kept + log = new_log(tmp_path) + restarted = AlertDelivery(log, Notifier(telegram, AlertState(state.path)), AlertState(state.path), TZ) + assert restarted.last == 0 and "not the one" in caplog.text + for i in range(3): + log.append("rain", f"new {i}", "t") + assert await restarted.deliver_new() == 3 + assert await log.wait(restarted.last - 1, timeout=0.1) + + +async def test_a_replaced_log_already_past_the_last_id_is_noticed_by_its_identity(tmp_path): + d, log, state, telegram = delivery(tmp_path, chats=(1,)) + log.append("rain", "old", "t") + await d.deliver_new() + log.close() + (tmp_path / "alerts.sqlite").unlink() + log = new_log(tmp_path) + for i in range(3): + log.append("rain", f"before the restart {i}", "t") # another file, its ids already past the old one + restarted = AlertDelivery(log, Notifier(telegram, AlertState(state.path)), AlertState(state.path), TZ) + assert restarted.last == 3 # its own newest: what came before is not news + log.append("rain", "after", "t") + await restarted.deliver_new() + assert [text for _, text, _, _ in telegram.sent] == ["old", "after"] + assert AlertState(state.path).read_log == log.identity == new_log(tmp_path).identity # kept, and the file's own across opens + + +async def test_a_kept_id_from_before_the_log_had_an_identity_is_resumed_from(tmp_path): + d, log, state, telegram = delivery(tmp_path, chats=(1,)) + log.append("rain", "first", "t") + await d.deliver_new() + state.read_log = None + state.save() # as step 4 first kept it: the id alone + log.append("rain", "second", "t") + restarted = AlertDelivery(log, Notifier(telegram, AlertState(state.path)), AlertState(state.path), TZ) + assert restarted.last == 1 + await restarted.deliver_new() + assert [text for _, text, _, _ in telegram.sent] == ["first", "second"] + + +async def test_the_delivery_runs_on_the_logs_notification(tmp_path): + d, log, state, telegram = delivery(tmp_path, chats=(1,)) + task = asyncio.create_task(d.run()) + try: + await asyncio.sleep(0.01) + log.append("uv", "UV 11", "t") + for _ in range(100): + if telegram.sent: + break + await asyncio.sleep(0.01) + assert [text for _, text, _, _ in telegram.sent] == ["UV 11"] + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +async def test_a_log_that_cant_be_read_for_a_moment_is_tried_again_not_the_end_of_alerts(tmp_path): + """A locked file or a disk error reading the log is logged and retried: the delivery keeps running, and the alert written meanwhile + is sent once the log reads again (before, one error ended the task and every alert stopped until a restart).""" + import sqlite3 + d, log, state, telegram = delivery(tmp_path, chats=(1,)) + d.RETRY_SECONDS = 0.01 + real, failures = log.since, [sqlite3.OperationalError("database is locked")] + + def flaky(*a, **k): + if failures: + raise failures.pop() + return real(*a, **k) + log.since = flaky + log.append("uv", "UV 11", "t") + task = asyncio.create_task(d.run()) + try: + for _ in range(200): + if telegram.sent: + break + await asyncio.sleep(0.01) + assert [text for _, text, _, _ in telegram.sent] == ["UV 11"] and not task.done() + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +# ---------- the 🔄 under a delivered alert ---------- +class ChartQuery: + def __init__(self, data, kind="gusts", event=None): + self.data = data + self.message = NS(text=None, chat=NS(type="private", id=1), photo=(NS(file_id="large"),), caption="💨 Strong gusts", caption_entities=(), + reply_markup=alert_keyboard(kind, set(), set(), refresh=True, event=event), date=None, edit_date=None) + self.from_user, self.toast, self.media, self.edits = NS(id=7), "unset", [], [] + + async def answer(self, text=None, **kw): + self.toast = text + + async def edit_message_media(self, media, reply_markup=None): + self.media.append((media, reply_markup)) + + async def edit_message_reply_markup(self, reply_markup=None): + self.edits.append(reply_markup) + + +async def a_bot(serve, tmp_path, log, monkeypatch): + """A bot over ecobot-mcp in memory with the weather station and the alert log `log` (the 🔄 finds an event's drawn_by in it).""" + from lib.bot import Bot + state = AlertState(tmp_path / "s.json") + state.add_chat(1, "private") + bot = Bot(NS(tz=TZ), None, state, service=await serve(None, log, tools=[], sources=["Ecowitt"])) + calls = [] + + async def draw_call(tool, args, ahead=True): + calls.append((tool, args, ahead)) + return b"replayed png", "Wind, today", None, 1_800_000_000, {"tool": tool, "arguments": args}, {} + monkeypatch.setattr(bot, "_draw_call", draw_call) + return bot, calls + + +async def test_refresh_under_a_delivered_alert_replays_its_charts_drawn_by(serve, tmp_path, monkeypatch): + log = new_log(tmp_path) + drawn_by = {"tool": "summary", "arguments": {"readings": ["wind"], "period": "1d", "chart": True, "points": "auto"}} + event = log.append("gusts", "💨 Strong gusts", "Strong gusts", chart={"title": "Wind", "drawn_by": drawn_by}) + bot, calls = await a_bot(serve, tmp_path, log, monkeypatch) + q = ChartQuery(f"al:refresh:gusts:{event['id']}", event=event["id"]) + await bot.on_alert_button(NS(callback_query=q), NS()) + assert calls == [("summary", drawn_by["arguments"], False)] + (media, markup), = q.media + assert media.media.input_file_content == b"replayed png" and markup is q.message.reply_markup and q.toast is None + + +async def test_refresh_of_an_alert_not_in_the_log_draws_its_types_chart(serve, tmp_path, monkeypatch): + from lib.alerts import pictures + asked = [] + + async def chart(text, tz, weather): + asked.append(text) + return Picture(b"type png", "Wind, today", None) + monkeypatch.setattr(pictures, "chart", chart) + bot, calls = await a_bot(serve, tmp_path, new_log(tmp_path), monkeypatch) + q = ChartQuery("al:refresh:gusts:99", event=99) # (dropped from the log) + await bot.on_alert_button(NS(callback_query=q), NS()) + assert calls == [] and asked == [CHARTS["gusts"]] and q.media[0][0].media.input_file_content == b"type png" + + +async def test_the_bell_under_a_delivered_alert_keeps_the_event_in_its_refresh(serve, tmp_path, monkeypatch): + bot, _ = await a_bot(serve, tmp_path, new_log(tmp_path), monkeypatch) + q = ChartQuery("al:open:bell:gusts", event=7) + await bot.on_alert_button(NS(callback_query=q), NS()) + assert rows(q.edits[0])[0] == [("🔔 ▾", "al:close:gusts"), ("🔄", "al:refresh:gusts:7")] + + +@pytest.mark.parametrize("data", ["al:refresh:gusts:x", "al:refresh:gusts:1:2"]) +async def test_a_refresh_with_a_malformed_id_does_nothing(serve, tmp_path, monkeypatch, data): + bot, calls = await a_bot(serve, tmp_path, new_log(tmp_path), monkeypatch) + q = ChartQuery(data) + await bot.on_alert_button(NS(callback_query=q), NS()) + assert calls == [] and q.media == [] and q.toast is None diff --git a/tests/test_alert_menu.py b/tests/test_alert_menu.py index 4b69423c..b2feea60 100644 --- a/tests/test_alert_menu.py +++ b/tests/test_alert_menu.py @@ -4,7 +4,7 @@ from telegram.error import BadRequest from lib.alerts.notify import AlertState, Notifier -from lib.alerts.pictures import Picture +from lib.alerts.pictures import CHARTS, Picture from lib.alerts.menu import ALL, LABELS, TITLE, alert_keyboard, available_kinds, keyboard, title from lib.bot import Bot from lib.buttons import struck as strike @@ -152,11 +152,12 @@ async def edit_message_text(self, text, reply_markup=None): self.edits.append(("text", text, reply_markup)) -def make_bot(tmp_path, sources=("Ecowitt", "AirGradient", "Pollen", "Forecast")): +async def make_bot(serve, tmp_path, sources=("Ecowitt", "AirGradient", "Pollen", "Forecast")): + """A bot over ecobot-mcp in memory as if it ran these sources (their alert types are the menus').""" state = AlertState(tmp_path / "s.json") state.add_chat(1, "private") state.add_chat(-5, "group") - bot = Bot(NS(tz=TZ), None, [NS(name=n) for n in sources], state) + bot = Bot(NS(tz=TZ), None, state, service=await serve(tools=[], sources=sources)) return bot, state @@ -170,8 +171,8 @@ async def press(bot, query, **kw): await bot.on_alert_button(NS(callback_query=query), kw.get("context") or ctx()) -async def test_the_alerts_menu_toggles_a_type_in_place_and_back_returns_to_the_two_buttons(tmp_path): - bot, state = make_bot(tmp_path) +async def test_the_alerts_menu_toggles_a_type_in_place_and_back_returns_to_the_two_buttons(serve, tmp_path): + bot, state = await make_bot(serve, tmp_path) q = Query("al:open:alerts", text=f"{TITLE}\n✅ On: ...") await press(bot, q) drawn = rows(q.edits[0][2]) @@ -188,17 +189,17 @@ async def test_the_alerts_menu_toggles_a_type_in_place_and_back_returns_to_the_t assert rows(q.edits[0][2]) == [[("🔔 Alerts ▸", "al:open:alerts"), ("🔊 Sound ▸", "al:open:sound")]] -async def test_turning_off_every_type_the_bot_sends_unsubscribes_the_chat_from_all(tmp_path, monkeypatch): +async def test_turning_off_every_type_the_bot_sends_unsubscribes_the_chat_from_all(serve, tmp_path, monkeypatch): from lib.alerts import menu - bot, state = make_bot(tmp_path, sources=("Ecowitt",)) + bot, state = await make_bot(serve, tmp_path, sources=("Ecowitt",)) for kind in ("rain", "gusts", "uv", "temps"): # the weather station's types, one by one await press(bot, Query(f"al:off:{kind}:alerts")) monkeypatch.setitem(menu.LABELS, "newthing", "new thing") assert state.chats[1].get("optin") and not state.subscribed(1, "newthing") and not state.subscribed(1, "particulates") -async def test_the_alerts_message_keeps_its_summary_current_but_an_alert_keeps_its_text(tmp_path): - bot, state = make_bot(tmp_path) +async def test_the_alerts_message_keeps_its_summary_current_but_an_alert_keeps_its_text(serve, tmp_path): + bot, state = await make_bot(serve, tmp_path) q = Query("al:off:uv:alerts", text=f"{TITLE}\n✅ On: ...") await press(bot, q) assert q.edits[0][0] == "text" and "🔕 Off: UV" in q.edits[0][1] @@ -207,8 +208,8 @@ async def test_the_alerts_message_keeps_its_summary_current_but_an_alert_keeps_i assert q.edits[0][0] == "markup" -async def test_noop_unknown_kinds_and_unchanged_markup_are_harmless(tmp_path): - bot, state = make_bot(tmp_path, sources=("Ecowitt",)) +async def test_noop_unknown_kinds_and_unchanged_markup_are_harmless(serve, tmp_path): + bot, state = await make_bot(serve, tmp_path, sources=("Ecowitt",)) q = Query("al:noop") await press(bot, q) assert q.edits == [] and q.toast is None @@ -226,8 +227,8 @@ async def test_noop_unknown_kinds_and_unchanged_markup_are_harmless(tmp_path): await press(bot, q) -async def test_in_a_group_only_admins_may_change_alerts(tmp_path): - bot, state = make_bot(tmp_path) +async def test_in_a_group_only_admins_may_change_alerts(serve, tmp_path): + bot, state = await make_bot(serve, tmp_path) q = Query("al:off:rain:alerts", chat_type="supergroup", chat_id=-5) await press(bot, q, context=ctx("member")) assert q.toast == "Only group admins can change alerts" and state.muted(-5) == set() and q.edits == [] @@ -238,8 +239,8 @@ async def test_in_a_group_only_admins_may_change_alerts(tmp_path): assert state.muted(-5) == {"rain", "uv"} -async def test_the_alerts_command_sends_the_menu_and_on_off_still_work(tmp_path): - bot, state = make_bot(tmp_path) +async def test_the_alerts_command_sends_the_menu_and_on_off_still_work(serve, tmp_path): + bot, state = await make_bot(serve, tmp_path) replies = [] async def reply_text(body, **kw): @@ -260,17 +261,14 @@ async def test_every_monitors_alert_names_its_type(tmp_path): from lib.alerts.particulates import ParticulatesMonitor from lib.alerts.pollen_and_asthma import PollenAndAsthmaMonitor from lib.alerts.weather import WeatherMonitor - from tests.test_alerts import FakePollen, FakeStation, T0, air_reading, gusts, rain, uv - from tests.test_forecast_alert import TODAY, FakeForecast, day - state = AlertState(tmp_path / "s.json") - state.add_chat(1, "chat") - kinds = [] - - async def notify(text, link=None, kind=None, **more): - kinds.append(kind) + from tests.test_alerts import FakePollen, FakeStation, T0, air_reading, asking, gusts, rain, store_and_log, uv + from tests.test_forecast_alert import FakeForecast, day + state, log, sent = store_and_log(tmp_path) + kinds = lambda: [e["kind"] for e in sent.events] async def weather(first, then): - mon = WeatherMonitor(FakeStation(first), state, notify) + mon = WeatherMonitor(FakeStation(first), state, log) + asking(mon, photo=None) await mon.check() mon.station.data = then await mon.check() @@ -278,26 +276,21 @@ async def weather(first, then): await weather(rain(0, 0, 1, 1), rain(0, 0, 1, 1, *[0] * 13)) await weather(gusts(10, 12), gusts(10, 12, 60)) await weather(uv(3, 5, start=T0 + 86400), uv(3, 5, 10, 10, start=T0 + 86400)) # later than the readings above: the monitors share one state - assert kinds == ["rain", "rain", "gusts", "uv"] - kinds.clear() - mask = ParticulatesMonitor(NS(tz=TZ, link=None), state, notify) + assert kinds() == ["rain", "rain", "gusts", "uv"] + mask = ParticulatesMonitor(NS(tz=TZ, link=None), state, log) + asking(mask, photo=None) for pm in (80, 80, 20, 20): await mask.check(air_reading(pm)) - assert kinds == ["particulates", "particulates"] - kinds.clear() + assert kinds()[4:] == ["particulates", "particulates"] pollen = FakePollen() pollen.grass = "High" - await PollenAndAsthmaMonitor(pollen, state, notify).check() - assert kinds == ["pollen_and_asthma"] - seen = [] - notifier = Notifier(Sent(), state) - - async def spy(text, **kw): - seen.append(kw["kind"]) - return await notifier(text, **kw) - state.record_forecast(1, [day(0, pct=90)], TODAY) - await ForecastMonitor(FakeForecast([day(0, pct=5)]), state, spy).check() - assert seen == ["forecast"] + await PollenAndAsthmaMonitor(pollen, state, log).check() + assert kinds()[6:] == ["pollen_and_asthma"] + forecast = ForecastMonitor(FakeForecast([day(0, pct=90)]), state, log) + await forecast.check() + forecast.forecast.fetch([day(0, pct=5)]) + await forecast.check() + assert kinds()[7:] == ["forecast"] def test_under_an_alert_one_bell_opens_the_alert_toggle_and_then_the_sound_toggle(): @@ -319,8 +312,8 @@ def test_under_an_alert_with_a_chart_refresh_sits_beside_the_bell_open_or_shut() assert opened == [[("🔔 ▾", "al:close:gusts"), ("🔄", "al:refresh:gusts")], [("Alert", "al:off:gusts:bell:gusts")]] -async def test_the_bell_under_an_alert_toggles_the_alert_and_its_sound_and_stays_open(tmp_path): - bot, state = make_bot(tmp_path) +async def test_the_bell_under_an_alert_toggles_the_alert_and_its_sound_and_stays_open(serve, tmp_path): + bot, state = await make_bot(serve, tmp_path) q = Query("al:open:bell:uv", text="☀️ UV 10") await press(bot, q) assert rows(q.edits[0][-1]) == [[("🔔 ▾", "al:close:uv")], [("Alert", "al:off:uv:bell:uv")], [(strike("Sound"), "al:snd:uv:on:uv")]] @@ -339,9 +332,9 @@ async def test_the_bell_under_an_alert_toggles_the_alert_and_its_sound_and_stays assert rows(q.edits[0][-1]) == [[("🔔 ▸", "al:open:bell:uv")]] -async def test_the_bell_of_an_alert_type_the_bot_no_longer_sends_is_out_of_date(tmp_path): +async def test_the_bell_of_an_alert_type_the_bot_no_longer_sends_is_out_of_date(serve, tmp_path): from lib.bot import STALE_BUTTON - bot, state = make_bot(tmp_path, sources=("Ecowitt",)) # no pollen source any more + bot, state = await make_bot(serve, tmp_path, sources=("Ecowitt",)) # no pollen source any more for data in ("al:open:bell:pollen_and_asthma", "al:off:pollen_and_asthma:bell:pollen_and_asthma"): q = Query(data, text="🌼 Grass pollen is High") await press(bot, q) @@ -352,8 +345,8 @@ def test_the_title_stays_plain_words(): assert title(set(), ["rain"]) == f"{TITLE}\n✅ On: rain\n🔕 Off: nothing" -async def test_the_sound_menu_toggles_every_type_in_private_chats_only_and_back_returns(tmp_path): - bot, state = make_bot(tmp_path) +async def test_the_sound_menu_toggles_every_type_in_private_chats_only_and_back_returns(serve, tmp_path): + bot, state = await make_bot(serve, tmp_path) state.set_kind(1, "gusts", False) q = Query("al:open:sound") await press(bot, q) @@ -398,7 +391,7 @@ async def test_an_alert_has_a_sound_only_in_a_chat_that_turned_it_on_and_groups_ assert [b[0] for b in rows(group["reply_markup"])[0]] == ["🔔 ▸"] -async def test_a_chat_that_became_a_supergroup_is_followed_not_a_crash(tmp_path): +async def test_a_chat_that_became_a_supergroup_is_followed_not_a_crash(serve, tmp_path): from telegram.error import ChatMigrated class Moved(Sent): @@ -413,7 +406,7 @@ async def send_message(self, chat_id, text, **kw): await Notifier(bot, state)("It's raining", kind="rain") assert list(state.chats) == [-1005] and state.muted(-1005) == {"uv"} and [c for c, *_ in bot.sent] == [-1005] state.add_chat(-7, "H") # a press under an old alert of a moved group - bot2, _ = make_bot(tmp_path) + bot2, _ = await make_bot(serve, tmp_path) bot2.state = state q = Query("al:open:alerts", chat_type="supergroup", chat_id=-7) q.message.reply_markup = keyboard(set(), KINDS) @@ -430,15 +423,16 @@ def test_every_alert_type_sent_is_registered_and_each_monitor_declares_what_it_s import re from pathlib import Path from lib.alerts.forecast import ForecastMonitor - from lib.alerts.irrigation import IrrigationMonitor + from lib.irrigation.check import IrrigationMonitor from lib.alerts.particulates import ParticulatesMonitor from lib.alerts.pollen_and_asthma import PollenAndAsthmaMonitor from lib.alerts.weather import WeatherMonitor monitors = [WeatherMonitor, ParticulatesMonitor, ForecastMonitor, PollenAndAsthmaMonitor, IrrigationMonitor] assert sorted(k for m in monitors for k in m.KINDS) == sorted(LABELS) # every type has exactly one monitor - for m in monitors: - sent = set(re.findall(r'kind="(\w+)"', Path(__import__(m.__module__, fromlist=["x"]).__file__).read_text())) - assert sent == set(m.KINDS), m.__name__ + for m in monitors: # each kind named where it is appended to the log (the irrigation controller's: where it is sent) + text = Path(__import__(m.__module__, fromlist=["x"]).__file__).read_text() + sent = set(re.findall(r'kind="(\w+)"|_emit\("(\w+)"|append\("(\w+)"', text)) + assert {k for found in sent for k in found if k} == set(m.KINDS), m.__name__ class SentWithPhotos(Sent): @@ -502,50 +496,46 @@ async def edit_message_media(self, media, reply_markup=None): def drawing(monkeypatch, photo=b"new png"): - """Alert charts drawn as `photo`; returns the list of (source, request) drawn.""" + """Alert charts drawn as `photo`; returns the list of (the request, who was asked to draw it) drawn.""" from lib.alerts import pictures drawn = [] - async def chart(source, text, tz): - drawn.append((source.name, text)) + async def chart(text, tz, weather): + drawn.append((text, weather)) return Picture(photo, "Wind, today", None) if photo else None monkeypatch.setattr(pictures, "chart", chart) return drawn -async def test_refresh_under_an_alerts_chart_draws_it_again_in_the_same_message_for_anyone(tmp_path, monkeypatch): - bot, _ = make_bot(tmp_path) - for source in bot.sources: - source.tz = TZ +async def test_refresh_under_an_alerts_chart_draws_it_again_in_the_same_message_for_anyone(serve, tmp_path, monkeypatch): + bot, _ = await make_bot(serve, tmp_path) drawn = drawing(monkeypatch) q = ChartQuery("al:refresh:gusts", chat_type="supergroup", chat_id=-5) await press(bot, q, context=ctx("member")) # not an admin: a redraw changes no setting (media, markup), = q.media - assert drawn == [("Ecowitt", "Wind chart 1d")] and q.toast is None + assert drawn == [(CHARTS["gusts"], bot.weather)] and q.toast is None # (drawn by ecobot-mcp) assert (media.media.input_file_content, media.caption) == (b"new png", "💨 Strong gusts: 55 km/h at 3:05pm.") # the alert's text stays assert markup is q.message.reply_markup and q.edits == [] q = ChartQuery("al:refresh:particulates", kind="particulates") await press(bot, q) - assert drawn[-1] == ("AirGradient", "Particulates chart 1d") and len(q.media) == 1 + assert drawn[-1] == (CHARTS["particulates"], bot.weather) and len(q.media) == 1 -async def test_a_chart_that_cannot_be_drawn_again_leaves_the_alert_as_it_was(tmp_path, monkeypatch): - bot, _ = make_bot(tmp_path) - for source in bot.sources: - source.tz = TZ +async def test_a_chart_that_cannot_be_drawn_again_leaves_the_alert_as_it_was(serve, tmp_path, monkeypatch): + bot, _ = await make_bot(serve, tmp_path) drawing(monkeypatch, photo=None) q = ChartQuery("al:refresh:uv", kind="uv") await press(bot, q) assert q.media == [] and "Couldn't draw the chart" in q.toast from lib.bot import STALE_BUTTON - gone, _ = make_bot(tmp_path, sources=("Pollen",)) # no station any more + gone, _ = await make_bot(serve, tmp_path, sources=("Pollen",)) # no station any more q = ChartQuery("al:refresh:uv", kind="uv") await press(gone, q) assert q.media == [] and q.toast == STALE_BUTTON -async def test_the_bell_under_an_alerts_chart_keeps_its_refresh(tmp_path): - bot, _ = make_bot(tmp_path) +async def test_the_bell_under_an_alerts_chart_keeps_its_refresh(serve, tmp_path): + bot, _ = await make_bot(serve, tmp_path) q = ChartQuery("al:open:bell:gusts") await press(bot, q) assert rows(q.edits[0][-1])[0] == [("🔔 ▾", "al:close:gusts"), ("🔄", "al:refresh:gusts")] @@ -558,18 +548,23 @@ async def test_the_bell_under_an_alerts_chart_keeps_its_refresh(tmp_path): def alert_charts(clock): """An AlertCharts on an image cache that runs on `clock` (a one-element list of seconds).""" - from datetime import datetime from lib import periods from lib.alerts.pictures import AlertCharts images = periods.ImageCache(lambda: clock[0]) - return AlertCharts(images, lambda: datetime(2026, 10, 2, 12, 0, tzinfo=TZ), clock=lambda: clock[0]), images + return AlertCharts(images, tz=TZ), images -def test_every_alert_chart_has_the_key_of_the_same_typed_request(): +def test_every_alert_chart_has_the_key_of_its_fixed_call(): from lib.alerts.pictures import CHARTS + from lib.periods import call_key charts, images = alert_charts([0.0]) - assert {kind: charts.key(kind) for kind in CHARTS} == {"gusts": "wind chart 1d", "uv": "uv chart 1d", "temps": "temperature chart 1d", - "particulates": "particulates chart 1d"} + day = {"period": "1d", "chart": True} + assert {kind: charts.call(kind) for kind in CHARTS} == { + "gusts": ("summary", {"readings": ["wind"], **day}), # "Wind chart 1d", the Wind button's + "uv": ("summary", {"readings": ["uv"], **day}), + "temps": ("summary", {"readings": ["temperature"], **day}), + "particulates": ("summary", {"readings": ["pm2.5", "pm10", "pm1"], **day})} + assert charts.key("gusts") == call_key(*charts.call("gusts")) assert charts.key("rain") is None # an alert without a chart @@ -578,7 +573,7 @@ def test_an_alert_sends_the_held_chart_only_when_it_draws_the_alerts_reading_and charts, images = alert_charts(clock) assert charts.held("gusts", 1000) is None # nothing held charts.keep("gusts", Picture(b"png", "Wind, today", 900), since=1000) # drawn for the alert about the reading at 1000 - assert images.held("wind chart 1d").newest == 1000 and charts.held("gusts", 1000) == b"png" # (it draws that reading, whatever its last point says) + assert images.held(charts.key("gusts")).newest == 1000 and charts.held("gusts", 1000) == b"png" # (it draws that reading, whatever its last point says) assert charts.held("gusts", 1300) is None and charts.held("gusts", None) is None # a newer reading, or one not known: drawn again charts.sent("gusts", NS(photo=(NS(file_id="small"), NS(file_id="large")))) assert charts.held("gusts", 1000) == "large" and charts.held("gusts", 700) == "large" # the same data again: Telegram's copy @@ -586,33 +581,16 @@ def test_an_alert_sends_the_held_chart_only_when_it_draws_the_alerts_reading_and assert charts.held("gusts", 1000) is None # out of its time to live -def test_an_alerts_chart_is_kept_warm_for_six_hours_from_the_alert_not_from_a_refresh(): - from lib.alerts.pictures import AlertCharts - clock = [0.0] - charts, _ = alert_charts(clock) - assert charts.warm() == [] - charts.sent("uv", NS(photo=(NS(file_id="large"),)), alerted=False) # a Refresh: not an alert - assert charts.warm() == [] - charts.sent("uv", NS(photo=(NS(file_id="large"),))) - charts.sent("temps", None) # an alert whose picture Telegram refused still counts - assert charts.warm() == ["UV chart 1d", "Temperature chart 1d"] - clock[0] += AlertCharts.WARM_SECONDS - 1 - assert charts.warm() == ["UV chart 1d", "Temperature chart 1d"] - charts.sent("uv", NS(photo=(NS(file_id="large"),))) # alerted again: six more hours - clock[0] += 2 - assert charts.warm() == ["UV chart 1d"] - - def test_refresh_sends_the_chart_drawn_ahead_since_the_message_was_last_changed_when_it_is_fresh(): from datetime import datetime, timedelta, timezone clock = [0.0] charts, images = alert_charts(clock) shown = NS(date=datetime.now(timezone.utc) - timedelta(seconds=120), edit_date=None) assert charts.newer_than("gusts", shown) is None # nothing held - images.put("wind chart 1d", b"ahead", "Wind, today") + images.put(charts.key("gusts"), b"ahead", "Wind, today") clock[0] += 60 # drawn a minute ago: since the message was sent assert charts.newer_than("gusts", shown) == b"ahead" - images.sent("wind chart 1d", NS(photo=(NS(file_id="large"),))) + images.sent(charts.key("gusts"), NS(photo=(NS(file_id="large"),))) assert charts.newer_than("gusts", shown) == "large" # uploaded ahead: Telegram's copy edited = NS(date=shown.date, edit_date=datetime.now(timezone.utc) - timedelta(seconds=10)) assert charts.newer_than("gusts", edited) is None # the message changed after it was drawn @@ -639,23 +617,22 @@ async def chart(): await notifier("Strong gusts", kind="gusts", chart=chart, since=1000) await notifier("Strong gusts", kind="gusts", chart=chart, since=1000) # the same reading: the chart kept, Telegram's copy assert drawn == [1] and [p for _, p, _ in bot.photos] == [b"png", "copy 1"] - assert images.held("wind chart 1d").file_id == "copy 2" and charts.warm() == ["Wind chart 1d"] # (the copy last sent) + assert images.held(charts.key("gusts")).file_id == "copy 2" # (the copy last sent) await notifier("Strong gusts", kind="gusts", chart=chart, since=1300) # a newer reading: drawn again - assert drawn == [1, 1] and bot.photos[-1][1] == b"png" and images.held("wind chart 1d").newest == 1300 + assert drawn == [1, 1] and bot.photos[-1][1] == b"png" and images.held(charts.key("gusts")).newest == 1300 await notifier("Strong gusts", kind="gusts", chart=chart) # the reading not said: drawn assert drawn == [1, 1, 1] -async def test_refresh_sends_the_chart_drawn_ahead_and_otherwise_keeps_the_one_it_draws(tmp_path, monkeypatch): +async def test_refresh_sends_the_chart_drawn_ahead_and_otherwise_keeps_the_one_it_draws(serve, tmp_path, monkeypatch): from datetime import datetime, timedelta, timezone - bot, _ = make_bot(tmp_path) - for source in bot.sources: - source.tz = TZ + bot, _ = await make_bot(serve, tmp_path) drawn = drawing(monkeypatch) q = ChartQuery("al:refresh:gusts") q.message.date, q.message.edit_date = datetime.now(timezone.utc) - timedelta(seconds=90), None - bot.images.put("wind chart 1d", b"ahead", "Wind, today") # drawn ahead since the alert went out - bot.images.sent("wind chart 1d", NS(photo=(NS(file_id="ahead copy"),))) + key = bot.alert_charts.key("gusts") + bot.images.put(key, b"ahead", "Wind, today") # drawn ahead since the alert went out + bot.images.sent(key, NS(photo=(NS(file_id="ahead copy"),))) await press(bot, q) (media, _), = q.media assert drawn == [] and media.media == "ahead copy" and q.toast is None # Telegram's copy, nothing drawn @@ -667,5 +644,5 @@ async def edit_message_media(media, reply_markup=None): return NS(photo=(NS(file_id="small"), NS(file_id="new copy"))) q.edit_message_media = edit_message_media await press(bot, q) - assert drawn == [("Ecowitt", "Wind chart 1d")] and q.media[0][0].media.input_file_content == b"new png" - assert bot.images.held("wind chart 1d").file_id == "new copy" and bot.alert_charts.warm() == [] # (a Refresh starts no warm period) + assert drawn == [(CHARTS["gusts"], bot.weather)] and q.media[0][0].media.input_file_content == b"new png" + assert bot.images.held(key).file_id == "new copy" diff --git a/tests/test_alerts.py b/tests/test_alerts.py index ea881e47..fa321e30 100644 --- a/tests/test_alerts.py +++ b/tests/test_alerts.py @@ -5,12 +5,15 @@ import pytest from lib.airgradient import Latest +from lib.alert_log import AlertLog from lib.alerts.notify import AlertState, Notifier -from lib.alerts.pictures import Picture +from lib.alerts.pictures import CHARTS, Picture from lib.alerts.particulates import ParticulatesMonitor +from lib.alerts.store import AlertStore from lib.alerts.weather import WeatherMonitor from lib.entities import with_link from tests.fakes import TZ +from tests import engines T0 = int(datetime(2026, 9, 29, 13, 0, tzinfo=TZ).timestamp()) # 1pm Melbourne, a settled day @@ -46,12 +49,44 @@ async def readings(self, *a, **k): return self.data -def monitor(tmp_path, data): - state, sent = AlertState(tmp_path / "s.json"), [] +class Texts: + """The alerts a rule appended to its log, read as the list of their texts, oldest first (`events`: the events themselves).""" + + def __init__(self, log: AlertLog): + self.log = log + + @property + def events(self) -> list[dict]: + return self.log.since(0, expired=True) + + def _texts(self) -> list[str]: + return [e["text"] for e in self.events] + + def __eq__(self, other): + return self._texts() == list(other) + + def __len__(self): + return len(self.events) + + def __getitem__(self, i): + return self._texts()[i] + + def __iter__(self): + return iter(self._texts()) - async def notify(text, link=None, **kw): - sent.append(text) - m = WeatherMonitor(FakeStation(data), state, notify, cooldown_seconds=30 * 60) # 30 minutes, whatever the default is + def __repr__(self): + return repr(self._texts()) + + +def store_and_log(tmp_path): + """The rules' store and an alert log in `tmp_path`, and the texts appended to the log.""" + log = AlertLog(tmp_path / "alerts.sqlite", TZ) + return AlertStore(tmp_path / "alert_state.json"), log, Texts(log) + + +def monitor(tmp_path, data): + state, log, sent = store_and_log(tmp_path) + m = WeatherMonitor(FakeStation(data), state, log, cooldown_seconds=30 * 60) # 30 minutes, whatever the default is return m, state, sent @@ -227,32 +262,30 @@ class FakeAir: async def test_mask_alert_needs_two_bad_checks_and_pairs_with_all_clear(tmp_path): - state, sent = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - sent.append((text, link)) - mon = ParticulatesMonitor(FakeAir(), state, notify) + state, log, sent = store_and_log(tmp_path) + mon = ParticulatesMonitor(FakeAir(), state, log) + asking(mon, photo=None) await mon.check(air_reading(80)) assert not sent # one puff of smoke isn't enough await mon.check(air_reading(20)) await mon.check(air_reading(80)) assert not sent # the streak was broken await mon.check(air_reading(90)) - assert len(sent) == 1 and "mask" in sent[0][0] and sent[0][1] == FakeAir.link + (event,) = sent.events + assert "mask" in event["text"] and event["link"] == {"label": "live chart", "url": "https://example.com"} + assert event["kind"] == "particulates" and event["data"]["pm2_5_ugm3"] == 90 and event["data"]["unsafe"] await mon.check(air_reading(90)) assert len(sent) == 1 # no repeats within an episode await mon.check(air_reading(30)) assert len(sent) == 1 await mon.check(air_reading(30)) - assert len(sent) == 2 and "safe again" in sent[1][0] + assert len(sent) == 2 and "safe again" in sent[1] and not sent.events[1]["data"]["unsafe"] async def test_mask_threshold_is_official_aqi_151(tmp_path): - state, sent = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - sent.append(text) - mon = ParticulatesMonitor(FakeAir(), state, notify) + state, log, sent = store_and_log(tmp_path) + mon = ParticulatesMonitor(FakeAir(), state, log) + asking(mon, photo=None) for _ in range(3): await mon.check(air_reading(55.4)) # AQI 150: unhealthy for sensitive groups only assert not sent @@ -262,11 +295,8 @@ async def notify(text, link=None, **kw): async def test_stale_air_readings_are_ignored(tmp_path): - state, sent = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - sent.append(text) - mon = ParticulatesMonitor(FakeAir(), state, notify) + state, log, sent = store_and_log(tmp_path) + mon = ParticulatesMonitor(FakeAir(), state, log) for _ in range(3): await mon.check(air_reading(200, age=timedelta(hours=3))) assert not sent @@ -352,14 +382,12 @@ async def send_message(self, chat_id, text, **kw): assert state.subscribed(2, "uv") and not state.subscribed(2, "rain") and AlertState(state.path).present() == [1, 2, 3] -def test_a_migrated_groups_forecast_moves_with_it(tmp_path): - from datetime import date +def test_a_migrated_group_keeps_its_settings(tmp_path): state = AlertState(tmp_path / "s.json") state.add_chat(-5, "group") - today = date(2026, 10, 3) - state.record_forecast(-5, [{"date": today, "max_c": 20.0, "rain_chance_pct": 90}], today) + state.set_kind(-5, "uv", False) state.migrate_chat(-5, -1005) - assert state.forecast_sent(-1005)[today]["rain_chance_pct"] == 90 and state.forecast_sent(-5) == {} and state.forecast_chats() == [-1005] + assert -5 not in state.chats and state.muted(-1005) == {"uv"} and AlertState(state.path).muted(-1005) == {"uv"} def test_a_damaged_state_file_is_kept_aside_not_overwritten(tmp_path, caplog): @@ -374,12 +402,15 @@ def test_a_damaged_state_file_is_kept_aside_not_overwritten(tmp_path, caplog): def test_a_save_is_on_disk_before_it_replaces_the_old_file(tmp_path, monkeypatch): - from lib.alerts import notify - calls, replace = [], notify.os.replace - monkeypatch.setattr(notify.os, "fsync", lambda fd: calls.append("fsync")) - monkeypatch.setattr(notify.os, "replace", lambda a, b: (calls.append("replace"), replace(a, b))) + from lib.alerts import store + calls, replace = [], store.os.replace + monkeypatch.setattr(store.os, "fsync", lambda fd: calls.append("fsync")) + monkeypatch.setattr(store.os, "replace", lambda a, b: (calls.append("replace"), replace(a, b))) AlertState(tmp_path / "s.json").add_chat(1, "Home") assert calls == ["fsync", "replace"] + calls.clear() + AlertStore(tmp_path / "alert_state.json").save() + assert calls == ["fsync", "replace"] * 2 # (a new store is written at once, then saved) async def test_one_chat_failing_never_stops_the_alert_reaching_the_others(tmp_path, monkeypatch): @@ -492,12 +523,9 @@ def current(self): def pollen_monitor(tmp_path): from lib.alerts.pollen_and_asthma import PollenAndAsthmaMonitor - state, sent = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - sent.append(text) + state, log, sent = store_and_log(tmp_path) pollen = FakePollen() - return PollenAndAsthmaMonitor(pollen, state, notify), pollen, sent + return PollenAndAsthmaMonitor(pollen, state, log), pollen, sent async def test_high_pollen_and_asthma_alert_once_per_metric_and_day(tmp_path): @@ -521,13 +549,15 @@ async def test_high_pollen_and_asthma_alert_once_per_metric_and_day(tmp_path): pollen.grass = "Extreme" # it rises to the top of the scale the same day: said again await mon.check() await mon.check() - assert sent[-1] == "🟣 Grass pollen forecast is Extreme." - sent.pop() + assert len(sent) == 4 and sent[-1] == "🟣 Grass pollen forecast is Extreme." pollen.grass = "High" # (and back, for what follows) pollen.today += timedelta(days=1) # a new day, still High pollen.fetched_at = time.time() await mon.check() - assert len(sent) == 4 and "Central" not in " ".join(sent) + assert len(sent) == 5 and "Central" not in " ".join(sent) + event = sent.events[-1] + assert event["kind"] == "pollen_and_asthma" and event["link"] == {"label": "melbournepollen.com.au", "url": "https://www.melbournepollen.com.au/"} + assert event["data"] == {"metric": "grass", "level": "High", "for": "2026-10-02"} and event["title"] == "Grass pollen forecast: High" async def test_a_restart_does_not_repeat_an_alert_and_a_missing_forecast_or_stale_page_is_ignored(tmp_path): @@ -536,7 +566,7 @@ async def test_a_restart_does_not_repeat_an_alert_and_a_missing_forecast_or_stal pollen.grass = "High" await mon.check() assert len(sent) == 1 - again = PollenAndAsthmaMonitor(pollen, mon.state, mon.notify) # the state file keeps what was sent + again = PollenAndAsthmaMonitor(pollen, AlertStore(mon.state.path), mon.alerts) # the state file keeps what was sent await again.check() assert len(sent) == 1 pollen.asthma = None # off-season: nothing to say @@ -699,131 +729,113 @@ def test_unsubscribing_from_all_keeps_future_alert_types_off_until_subscribed(tm assert again.subscribed(3, "rain") and not again.subscribed(3, "uv") and not again.subscribed(3, "newer still") -async def picture_of(kw): - """The picture an alert sent with these arguments would carry: what its chart draws (None: the text alone).""" - return await kw["chart"]() if kw.get("chart") else None +CHART = {"title": "a chart", "drawn_by": {"tool": "summary", "arguments": {"readings": ["wind"], "period": "1d", "chart": True}}} -def asking(mon, photo=b"png"): - """Replace a monitor's chart maker with one that records what was asked and answers `photo`; returns the list of requests.""" +def asking(mon, photo=CHART): + """Replace a monitor's chart maker with one that records what was asked and answers `photo` (a chart's data); returns the list of + requests.""" asked = [] - async def picture(*text): + async def chart(*text): asked.append(text[-1] if text else "particulates") return photo - mon._picture = picture + mon._chart = chart return asked async def test_the_crossing_alert_carries_the_temperature_chart_when_there_is_one(tmp_path): m, state, sent = monitor(tmp_path, temps(10, 20)) - photos = [] - - async def notify(text, link=None, **kw): - sent.append(text) - photos.append(await picture_of(kw)) - m.notify = notify asked = asking(m) await m.check() # learns: outdoor cooler m.station.data = temps(25, 20, T0 + 3 * 3600) await m.check() - assert len(sent) == 1 and photos == [b"png"] and asked == ["Temperature chart 1d"] + assert len(sent) == 1 and sent.events[0]["chart"] == CHART and asked == [CHARTS["temps"]] + assert sent.events[0]["title"] == "Warmer outside than inside" and sent.events[0]["data"]["outdoor_c"] == 25 m.station.data = temps(10, 20, T0 + 6 * 3600) # and back, with no chart this time: the alert still goes out, as text asking(m, photo=None) await m.check() - assert len(sent) == 2 and photos[1] is None + assert len(sent) == 2 and "chart" not in sent.events[1] async def test_the_gusts_alert_carries_the_wind_chart(tmp_path): vals = [10, 12] m, state, sent = monitor(tmp_path, [(T0 + i * 300, {"wind.wind_gust": v}) for i, v in enumerate(vals)]) - seen = [] - - async def notify(text, link=None, **kw): - seen.append((text, await picture_of(kw))) - m.notify = notify asked = asking(m) await m.check() # the first look sets the mark m.station.data = [(T0 + i * 300, {"wind.wind_gust": v}) for i, v in enumerate([10, 12, 55])] await m.check() - assert len(seen) == 1 and "Strong gusts" in seen[0][0] and seen[0][1] == b"png" and asked == ["Wind chart 1d"] + (event,) = sent.events + assert "Strong gusts" in event["text"] and event["chart"]["drawn_by"] == CHART["drawn_by"] and asked == [CHARTS["gusts"]] + assert event["kind"] == "gusts" and event["data"]["gust_kmh"] == 55 and "link" not in event (tmp_path / "b").mkdir() - m2, _, _ = monitor(tmp_path / "b", [(T0, {"wind.wind_gust": 10}), (T0 + 300, {"wind.wind_gust": 12})]) - plain = [] - - async def notify2(text, link=None, **kw): - plain.append((kw["kind"], await picture_of(kw))) - m2.notify = notify2 + m2, _, plain = monitor(tmp_path / "b", [(T0, {"wind.wind_gust": 10}), (T0 + 300, {"wind.wind_gust": 12})]) asking(m2, photo=None) await m2.check() m2.station.data = [(T0, {"wind.wind_gust": 10}), (T0 + 300, {"wind.wind_gust": 12}), (T0 + 600, {"wind.wind_gust": 70})] await m2.check() - assert plain == [("gusts", None)] # no chart: text only + assert [(e["kind"], e.get("chart")) for e in plain.events] == [("gusts", None)] # no chart: text only async def test_both_particulates_alerts_carry_the_particulates_chart(tmp_path): - state, seen = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - seen.append((text, await picture_of(kw))) - mon = ParticulatesMonitor(FakeAir(), state, notify) + state, log, seen = store_and_log(tmp_path) + mon = ParticulatesMonitor(FakeAir(), state, log) asked = asking(mon) for pm in (90, 90, 30, 30): await mon.check(air_reading(pm)) - assert [("mask" in t, "safe again" in t, p) for t, p in seen] == [(True, False, b"png"), (False, True, b"png")] and asked == ["particulates"] * 2 - quiet = ParticulatesMonitor(FakeAir(), AlertState(tmp_path / "t.json"), notify) + assert [("mask" in e["text"], "safe again" in e["text"], e.get("chart")) for e in seen.events] == [(True, False, CHART), (False, True, CHART)] + assert asked == ["particulates"] * 2 + (tmp_path / "t").mkdir() + state, log, quiet_seen = store_and_log(tmp_path / "t") + quiet = ParticulatesMonitor(FakeAir(), state, log) asking(quiet, photo=None) - seen.clear() for pm in (90, 90): await quiet.check(air_reading(pm)) - assert seen == [(seen[0][0], None)] + assert len(quiet_seen) == 1 and "chart" not in quiet_seen.events[0] async def test_other_alerts_send_no_picture(tmp_path): m, state, sent = monitor(tmp_path, None) - seen = [] - - async def notify(text, link=None, **kw): - seen.append(kw) - m.notify = notify + asked = asking(m) for data in (rain(0, 0, 0), rain(0, 0, 1)): m.station.data = data await m.check() - assert seen and all("chart" not in kw for kw in seen) + assert sent.events and all("chart" not in e for e in sent.events) and asked == [] -async def test_the_alert_charts_are_the_typed_one_day_charts_drawn_from_each_sources_history(tmp_path, archived_cache): +async def test_the_alert_charts_are_the_buttons_one_day_charts_drawn_from_each_sources_history(serve, tmp_path, archived_cache): + """The chart under an alert (and its 🔄) is the one-day chart of its fixed call (the Wind, Temperature and Particulates buttons'), + drawn by ecobot-mcp over each source's history.""" from lib.airgradient import AirGradient from lib.alerts import pictures + from lib.service.context import Context from tests.fakes import air_transport, archived_station, config eco, _ = await archived_station(tmp_path, archived_cache) - for text in ("Temperature chart 1d", "Wind chart 1d", "UV chart 1d"): - picture = await pictures.chart(eco, text, TZ) + station = await serve(Context(eco=eco, tz=TZ)) + for kind, text in (("temps", "Temperature"), ("gusts", "Wind"), ("uv", "UV")): + picture = await pictures.chart(pictures.CHARTS[kind], TZ, station) assert picture and picture.png[:4] == b"\x89PNG", text - assert picture.title.startswith(text.split()[0]) and picture.newest and abs(picture.newest - eco.now().timestamp()) < 3600, text + assert picture.title.startswith(text) and picture.newest and abs(picture.newest - eco.now().timestamp()) < 3600, text transport, _ = air_transport(oldest=datetime.now(timezone.utc) - timedelta(days=5)) (tmp_path / "air").mkdir() air = AirGradient(config(tmp_path / "air"), transport=transport) await air.start() - picture = await pictures.chart(air, "Particulates chart 1d", TZ) + picture = await pictures.chart(pictures.CHARTS["particulates"], TZ, await serve(Context(air=air, tz=TZ))) assert picture and picture.png[:4] == b"\x89PNG" and picture.title.startswith("Air quality") and picture.newest - assert await pictures.chart(FakeStation(), "Wind chart 1d", TZ) is None # a source without the tool: no chart, no error + assert await pictures.chart(pictures.CHARTS["gusts"], TZ, await serve(tools=[])) is None # a service without the tool: no chart, no error await eco.close() await air.close() async def test_the_particulates_chart_draws_pm1_pm25_and_pm10_together(tmp_path): - from lib import intent from lib.airgradient import AirGradient - from lib.timeutil import now_local from lib.tools import Turn from tests.fakes import air_transport, config transport, _ = air_transport(oldest=datetime.now(timezone.utc) - timedelta(days=5)) air = AirGradient(config(tmp_path), transport=transport) await air.start() - read = intent.read("Particulates chart 1d", now_local(TZ)) - turn = Turn(chart_asked=read.chart_asked, text="Particulates chart 1d") - await air.handle(read.fast[1], turn) + turn = Turn(chart_asked=True) + await engines.air_history(air, {"chart": True, "metrics": ["pm2_5", "pm10", "pm1"]}, turn) (panel,) = turn.charts[0].panels assert sorted(line.label for line in panel.lines) == ["PM1", "PM10", "PM2.5"] await air.close() @@ -831,32 +843,22 @@ async def test_the_particulates_chart_draws_pm1_pm25_and_pm10_together(tmp_path) async def test_the_uv_alert_carries_the_uv_chart_once_per_spell(tmp_path): vals = [3, 5] - m, state, sent = monitor(tmp_path, uv(*vals)) - seen = [] - - async def notify(text, link=None, **kw): - seen.append((text, await picture_of(kw))) - m.notify = notify + m, state, seen = monitor(tmp_path, uv(*vals)) asked = asking(m) await m.check() # the first look sets the mark m.station.data = uv(3, 5, 11, 12) await m.check() - assert len(seen) == 1 and "UV index 12" in seen[0][0] and seen[0][1] == b"png" and asked == ["UV chart 1d"] + assert len(seen) == 1 and "UV index 12" in seen[0] and seen.events[0]["chart"] == CHART and asked == [CHARTS["uv"]] m.station.data = uv(3, 5, 11, 12, 12) # the same spell: nothing more, and no second chart is made await m.check() - assert len(seen) == 1 and asked == ["UV chart 1d"] + assert len(seen) == 1 and asked == [CHARTS["uv"]] (tmp_path / "b").mkdir() - plain, _, _ = monitor(tmp_path / "b", uv(3, 5)) - got = [] - - async def notify2(text, link=None, **kw): - got.append((kw["kind"], await picture_of(kw))) - plain.notify = notify2 + plain, _, got = monitor(tmp_path / "b", uv(3, 5)) asking(plain, photo=None) await plain.check() plain.station.data = uv(3, 5, 11, 12) await plain.check() - assert got == [("uv", None)] # no chart: text only + assert [(e["kind"], e.get("chart")) for e in got.events] == [("uv", None)] # no chart: text only def test_an_alert_rearms_only_once_its_condition_has_stopped_for_the_whole_wait(): @@ -889,15 +891,11 @@ async def test_uv_needs_two_distinct_readings_even_across_checks_and_a_restart(t await m.check() await m.check() # the same reading looked at again does not count twice assert sent == [] - restarted = WeatherMonitor(m.station, AlertState(state.path), m.notify, cooldown_seconds=30 * 60) # a restart: the run is in the state file - sent2 = [] - - async def notify(text, link=None, **kw): - sent2.append(text) - restarted.notify = notify + restarted = WeatherMonitor(m.station, AlertStore(state.path), AlertLog(tmp_path / "alerts.sqlite", TZ), # (the same log) + cooldown_seconds=30 * 60) # a restart: the run is in the state file restarted.station.data = uv(3, 5, 10, 10.5) await restarted.check() - assert len(sent2) == 1 and "UV index 10.5" in sent2[0] + assert len(sent) == 1 and "UV index 10.5" in sent[0] (tmp_path / "x").mkdir() m3, _, sent3 = monitor(tmp_path / "x", uv(3, 5)) await m3.check() @@ -924,11 +922,9 @@ async def test_a_difference_of_a_degree_or_less_is_not_a_crossing(tmp_path): async def test_particulates_count_readings_not_checks(tmp_path): - state, sent = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - sent.append(text) - mon = ParticulatesMonitor(FakeAir(), state, notify) + state, log, sent = store_and_log(tmp_path) + mon = ParticulatesMonitor(FakeAir(), state, log) + asking(mon, photo=None) first = air_reading(90) await mon.check(first) await mon.check(first) # the sensor said nothing new: still one reading @@ -936,18 +932,17 @@ async def notify(text, link=None, **kw): await mon.check(air_reading(30)) # a reading that is not unhealthy ends the run await mon.check(first) # and an old reading is not counted again assert sent == [] - again = ParticulatesMonitor(FakeAir(), AlertState(tmp_path / "s.json"), notify) # a restart keeps what was counted + again = ParticulatesMonitor(FakeAir(), AlertStore(state.path), log) # a restart keeps what was counted + asking(again, photo=None) await again.check(air_reading(90)) await again.check(air_reading(90)) assert len(sent) == 1 and "mask" in sent[0] async def test_a_single_spike_never_makes_the_air_unhealthy_but_two_readings_in_a_row_do(tmp_path): - state, sent = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - sent.append(text) - mon = ParticulatesMonitor(FakeAir(), state, notify) + state, log, sent = store_and_log(tmp_path) + mon = ParticulatesMonitor(FakeAir(), state, log) + asking(mon, photo=None) stamp = datetime.now(timezone.utc) def reading(minutes, latest, before): # the lowest of the last readings, as air.latest() gives it @@ -962,7 +957,7 @@ def reading(minutes, latest, before): # the lowest of def test_the_default_wait_before_the_rain_has_stopped_is_an_hour(tmp_path): from lib.alerts.weather import ALERT_COOLDOWN_SECONDS - assert ALERT_COOLDOWN_SECONDS == 60 * 60 == WeatherMonitor(FakeStation([]), AlertState(tmp_path / "s.json"), None).cooldown + assert ALERT_COOLDOWN_SECONDS == 60 * 60 == WeatherMonitor(FakeStation([]), AlertStore(tmp_path / "s.json"), None).cooldown async def test_a_live_reading_alone_starts_the_rain_alert_without_the_rest_of_the_check(tmp_path): diff --git a/tests/test_averages.py b/tests/test_averages.py new file mode 100644 index 00000000..50de6997 --- /dev/null +++ b/tests/test_averages.py @@ -0,0 +1,80 @@ +"""Averages weighted by time (docs/ecobot-mcp.md 3.3): weather_history's and air_quality's average of a period count each day for the time of +it the period holds (lines.time_mean), so the part of a day at either end counts for its hours, not as a whole day, and an air day held only +as hourly averages counts for its 24 hours, not for its 24 readings against a 5-minute day's 288. Rain rate has an average; the rain +counters, which are totals, have none.""" + +import json +from datetime import date, datetime + +from lib.airgradient import AirGradient +from lib.ecowitt.query import HistoryQuery +from lib.storage.catalogue import RAIN_COUNTERS +from lib.timeutil import local_epoch +from lib.tools import Turn +from tests.fakes import TZ, air_transport, config, fetcher_on, storage_with + +NOW = datetime(2026, 10, 23, 12, 0) # Fri 23 Oct 2026, noon: the days below are over (and none of them changes the clock) + + +def at(day: int, hour: float = 0, month: int = 10) -> int: + """An epoch on a day of October 2026 (`month`), `hour` hours after its midnight.""" + return local_epoch(datetime(2026, month, day), TZ) + int(hour * 3600) + + +def every(seconds: int, *stretches: tuple[int, int, float]) -> dict[str, str]: + """{epoch: value}, a reading every `seconds` through each (start, end, value) stretch [start, end), as Ecowitt's lists have them.""" + return {str(t): f"{v}" for a, b, v in stretches for t in range(a, b, seconds)} + + +async def test_a_part_day_at_either_end_counts_for_its_hours_and_rain_rate_has_an_average(tmp_path): + temperature = every(300, (at(20), at(20, 18), 20.0), (at(20, 18), at(21), 10.0), (at(21), at(22), 16.0), (at(22), at(22, 6), 4.0), + (at(22, 6), at(23), 30.0)) # (the 20.0 and the 30.0 outside the period) + rain_rate = every(300, (at(20), at(21), 0.0), (at(21), at(22), 1.2), (at(22), at(23), 0.0)) + rainfall = {"rain_rate": {"unit": "mm/hr", "list": rain_rate}, + **{name: {"unit": "mm", "list": every(300, (at(20), at(23), 0.0))} for name in RAIN_COUNTERS}} + storage = storage_with(tmp_path, ("5min", ["outdoor", "rainfall"], {"outdoor": {"temperature": {"unit": "℃", "list": temperature}}, + "rainfall": rainfall}, at(20), at(23) - 1)) + q = HistoryQuery(fetcher_on(storage, None, ["outdoor", "rainfall"]), + {"start_date": "2026-10-20 18:00:00", "end_date": "2026-10-22 05:59:59", "average": True}, Turn()) + q.now = NOW + series = json.loads(await q.run())["series"] + temp = series["outdoor.temperature"] + assert {day: row["avg"] for day, row in temp["daily"].items()} == {"Tue 20 Oct": "10.0", "Wed 21 Oct": "16.0", "Thu 22 Oct": "4.0"} + assert temp["average"] == "13.0" # (6 h × 10.0 + 24 h × 16.0 + 6 h × 4.0) / 36 h; the mean of the three days' means would be 10.0 + assert series["rainfall.rain_rate"]["average"] == "0.8" # 1.2 mm/hr through the 24 of the period's 36 hours that are Wednesday's + assert not [name for name in RAIN_COUNTERS if "average" in series[f"rainfall.{name}"]] # a total, not a mean + storage.close() + + +def test_a_months_average_is_over_its_time_too(): + q = HistoryQuery.__new__(HistoryQuery) + q.f, q.tz = fetcher_on(None), TZ + q.start, q.end = datetime(2026, 9, 29, 18), datetime(2026, 10, 31, 23, 59, 59) + q.span = q.end - q.start # (over a month: by month) + entry = {"monthly": {"Sep 2026": {"low": "6.0", "high": "30.0"}, "Oct 2026": {"low": "12.0", "high": "12.0"}}} + means = {date(2026, 9, 29): 30.0, date(2026, 9, 30): 6.0} | {date(2026, 10, d): 12.0 for d in range(1, 32)} + q._add_averages(entry, means) + assert entry["monthly"]["Sep 2026"]["avg"] == "10.8" # (6 h × 30.0 + 24 h × 6.0) / 30 h, not (30.0 + 6.0) / 2 + assert entry["monthly"]["Oct 2026"]["avg"] == "12.0" + assert entry["average"] == "12.0" # 9,240 / 773 hours (4 October has 23): 11.95; the mean of the 33 days' means would be 12.4 + + +async def test_an_air_day_held_only_as_hourly_averages_counts_for_its_hours_and_a_day_s_average_is_its_day_row_s(tmp_path): + transport, _ = air_transport() + air = AirGradient(config(tmp_path), transport=transport) + await air.start() + air.now = lambda: NOW + await air.store.save_day(date(2026, 10, 20), [{"ts": t, "pm2_5": 8.0} for t in range(at(20), at(21), 3600)]) # the cloud's older history + await air.store.save_day(date(2026, 10, 21), [{"ts": t, "pm2_5": 20.0} for t in range(at(21), at(22), 300)]) + both = await air.history("2026-10-20 00:00:00", "2026-10-21 23:59:59") + assert both["readings"] == 24 + 288 and "hourly averages" in both["note_resolution"] + assert both["pm2_5"]["average"] == 14.0 # a day each: (8.0 + 20.0) / 2; the mean of the 312 readings would be 19.1 + parts = await air.history("2026-10-20 12:00:00", "2026-10-21 05:59:59") + assert parts["pm2_5"]["average"] == 12.0 # (12 h × 8.0 + 6 h × 20.0) / 18 h; the readings' mean would be 18.3 + + sparse = [{"ts": t, "pm2_5": 10.0} for t in range(at(22), at(22, 12), 300)] + [{"ts": t, "pm2_5": 16.0} for t in range(at(22, 12), at(23), 1800)] + await air.store.save_day(date(2026, 10, 22), sparse) # the afternoon held at one reading a half hour + day = await air.history("2026-10-22 00:00:00", "2026-10-22 23:59:59") + row = (await air.store.day_figures(date(2026, 10, 22), date(2026, 10, 22), ["pm2_5_avg"])).values["pm2_5_avg"][date(2026, 10, 22)] + assert day["pm2_5"]["average"] == round(row, 1) == 13.0 # each half hour's mean, then theirs; the readings' mean would be 10.9 + await air.close() diff --git a/tests/test_bench_storage.py b/tests/test_bench_storage.py index b63c8cbf..b9f191f4 100644 --- a/tests/test_bench_storage.py +++ b/tests/test_bench_storage.py @@ -1,24 +1,35 @@ """scripts/bench_storage.py: the benchmark of typical requests on a copy of the bot's file.""" import shutil import sys +from datetime import datetime from pathlib import Path +import pytest + +from tests.clocks import pin +from tests.fakes import TZ + sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) import bench_storage # noqa: E402 -async def test_the_benchmark_reads_a_copy_of_the_file_and_asks_nothing_of_the_network(tmp_path, archived_cache, monkeypatch): +@pytest.mark.parametrize("when", [datetime(2026, 11, 10, 14, 5, tzinfo=TZ), datetime(2026, 11, 10, 23, 59, tzinfo=TZ)], + ids=["2:05pm", "11:59pm"]) +async def test_the_benchmark_reads_a_copy_of_the_file_and_asks_nothing_of_the_network(tmp_path, pinned_archive, monkeypatch, when): + """At 11:59pm its "Temperature chart, 3 hours" has the day row's figures but no readings in the window: summary's chart failed on + it (a KeyError) until the reading was left out of the chart.""" + cache = pinned_archive(when) + pin(monkeypatch, when) data = tmp_path / "data" data.mkdir() - shutil.copy(archived_cache, data / "ecobot.sqlite") + shutil.copy(cache, data / "ecobot.sqlite") before = (data / "ecobot.sqlite").read_bytes() copy = tmp_path / "copy" copy.mkdir() bench_storage.copy(data / "ecobot.sqlite", copy / "ecobot.sqlite") - for name in ("TELEGRAM_BOT_TOKEN", "ECOWITT_API_KEY", "ECOWITT_APP_KEY"): # (the benchmark sets them where they are missing) + for name in ("BOT_TELEGRAM_TOKEN", "MCP_ECOWITT_API_KEY", "MCP_ECOWITT_APP_KEY"): # (the benchmark sets them where they are missing) monkeypatch.setenv(name, "t") monkeypatch.setenv("DATA_DIR", str(copy)) - from tests.fakes import TZ rows = await bench_storage.bench(copy, 1, TZ) labels = [r[0] for r in rows] assert "Temperature chart, 1Y" in labels and "/dashboard" in labels and len(rows) >= 12 @@ -38,11 +49,11 @@ async def test_the_benchmark_s_own_cache_is_as_old_as_asked_and_its_short_chart_ held = {cycle: min(storage.coverage.days(s.id, cycle) for s in sensors) for cycle in days} storage.close() assert all(n - 2 <= held[cycle] <= n for cycle, n in days.items()), held # (the newest hours are still settling) - for name in ("TELEGRAM_BOT_TOKEN", "ECOWITT_API_KEY", "ECOWITT_APP_KEY"): + for name in ("BOT_TELEGRAM_TOKEN", "MCP_ECOWITT_API_KEY", "MCP_ECOWITT_APP_KEY"): monkeypatch.setenv(name, "t") monkeypatch.setenv("DATA_DIR", str(tmp_path)) rows = {r[0]: r for r in await bench_storage.bench(tmp_path, 1, TZ)} short = rows["Temperature chart, 3 hours"] assert short[2] == 0 assert rows["Temperature chart, 1D"][2] == 1 # its newest hour is settling - assert "air_days: days PM2.5 over 25, 4 years" in rows + assert "days: days PM2.5 over 25, 4 years" in rows diff --git a/tests/test_bot.py b/tests/test_bot.py index 22f1bad9..d73e199e 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -1,13 +1,13 @@ """Bot.respond: what the person is sent when things go wrong.""" import asyncio -from datetime import datetime from types import SimpleNamespace as NS from lib import intent -from lib.bot import Bot +from lib.bot import NO_MODEL, Bot from lib.tools import Turn -from tests.fakes import TZ, StandInTools +from tests.fakes import draws, TZ +from tests.served import unreached class RaisingAgent: @@ -16,8 +16,8 @@ async def run(self, *a, **k): class AnsweringAgent: - async def run(self, messages, system, effort, *, first_call=None, turn=None, **k): - self.first_call = first_call + async def run(self, messages, system, effort, *, turn=None, **k): + self.system = system return "It is 12 degrees." @@ -28,7 +28,7 @@ async def send_message_draft(*a, **k): return NS(send_chat_action=send_chat_action, send_message_draft=send_message_draft, id=99, **more) -async def ask(alert_state, agent, text="how hot is it"): +async def ask(serve, alert_state, agent, text="how hot is it"): replies = [] async def reply_text(body, **kw): @@ -40,12 +40,12 @@ async def send_chat_action(*a, **k): chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) context = NS(bot=telegram(send_chat_action)) - await Bot(NS(tz=TZ), agent, [], alert_state).respond(update, context, text) + await Bot(NS(tz=TZ), agent, alert_state, service=await serve()).respond(update, context, text) return replies -async def test_error_details_stay_in_the_log_not_the_chat(alert_state): - replies = await ask(alert_state, RaisingAgent()) +async def test_error_details_stay_in_the_log_not_the_chat(serve, alert_state): + replies = await ask(serve, alert_state, RaisingAgent()) assert len(replies) == 1 and "went wrong" in replies[0] and "try again" in replies[0].lower() assert "SECRET" not in replies[0] and "Bearer" not in replies[0] and "acme" not in replies[0] assert "RuntimeError" in replies[0] # just the kind of problem @@ -58,25 +58,43 @@ async def run(self, *a, **k): raise AssertionError("there is no model to ask") -async def test_without_a_model_a_question_for_it_is_told_so_and_what_works_still_answers(alert_state): - replies = await ask(alert_state, NoModel(), "will it rain tomorrow, do you think?") - assert len(replies) == 1 and "needs the AI model" in replies[0] and "/report" in replies[0] and "/air_quality" in replies[0] - replies = await ask(alert_state, NoModel(), "what can you do") - assert len(replies) == 1 and "needs the AI model" not in replies[0] # answered in code, as before +async def test_without_a_model_a_typed_question_gets_one_line_saying_so(serve, alert_state): + """Every typed question is the model's (step 6c): without one, a typed chart request or "report" is told so too.""" + for text in ("will it rain tomorrow, do you think?", "what can you do", "rain chart 7d", "report"): + replies = await ask(serve, alert_state, NoModel(), text) + assert replies == [NO_MODEL], text + assert "\n" not in NO_MODEL and "no AI model" in NO_MODEL and "buttons and the alerts still work" in NO_MODEL -async def test_a_failing_shortcut_falls_back_to_the_model(alert_state, monkeypatch): - def boom(*a, **k): - raise OverflowError("date value out of range") - monkeypatch.setattr(intent, "fast_call", boom) +async def test_a_typed_chart_request_goes_to_the_model(serve, alert_state): + """"humidity 7d" was drawn in code until step 6c: anything typed is the model's now.""" agent = AnsweringAgent() - assert await ask(alert_state, agent, "weather last 99999 years") == ["It is 12 degrees."] - assert agent.first_call is None + replies = [] + + async def reply_text(body, **kw): + replies.append(body) + + async def send_chat_action(*a, **k): + pass + msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, + chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) + update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) + weather = await serve(sources=["Ecowitt"]) + await Bot(NS(tz=TZ), agent, alert_state, service=weather).respond(update, NS(bot=telegram(send_chat_action)), "humidity 7d") + assert replies == ["It is 12 degrees."] + + +async def test_the_model_is_sent_the_persona_the_servers_instructions_and_the_time(serve, alert_state): + from lib.prompt import PERSONA + agent = AnsweringAgent() + assert await ask(serve, alert_state, agent, "is it too cold to run?") == ["It is 12 degrees."] + assert agent.system.startswith(PERSONA.rstrip()) and "\n\nThe devices: " in agent.system # (lib/service/instructions.py) + assert agent.system.rstrip().splitlines()[-1].startswith("Now: ") and "RIGHT NOW" not in agent.system def test_a_reply_carries_the_message_it_replies_to_in_private_chats_too(alert_state): from types import SimpleNamespace as NS - bot = Bot(NS(tz=TZ), None, [], alert_state) + bot = Bot(NS(tz=TZ), None, alert_state, service=unreached()) mine = NS(text="Absolute pressure\n• Low: 992.9 hPa at 2:20pm on Sat 5 Sep", caption=None, from_user=NS(id=99, full_name="Bot")) theirs = NS(text="lovely day", caption=None, from_user=NS(id=7, full_name="Ann")) private = NS(chat=NS(type="private"), from_user=NS(full_name="Rob"), reply_to_message=mine) @@ -88,7 +106,7 @@ def test_a_reply_carries_the_message_it_replies_to_in_private_chats_too(alert_st assert bot._content(NS(**{**group.__dict__, "reply_to_message": None}), "hi", 99) == "Rob: hi" -async def test_a_hung_question_is_given_up_on_so_the_next_one_in_the_chat_is_answered(alert_state, monkeypatch, caplog): +async def test_a_hung_question_is_given_up_on_so_the_next_one_in_the_chat_is_answered(serve, alert_state, monkeypatch, caplog): import asyncio from lib import bot @@ -98,7 +116,7 @@ async def run(self, *a, **k): monkeypatch.setattr(bot, "TURN_SECONDS", 0.3) with caplog.at_level("WARNING"): - replies = await ask(alert_state, Hanging()) + replies = await ask(serve, alert_state, Hanging()) assert len(replies) == 1 and "took too long" in replies[0] assert "[Telegram 1]: gave up after 0s on: how hot is it" in caplog.text @@ -137,29 +155,33 @@ async def run(self, messages, system, effort, *, on_text=None, **k): return "It is 12 degrees." -async def ask_private(alert_state, agent, bot, chat_type="private", text="how hot is it"): +async def ask_private(serve, alert_state, agent, bot, chat_type="private", text="how hot is it"): replies = [] async def reply_text(body, **kw): replies.append(body) - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, + + async def reply_photo(photo, caption=None, **kw): + replies.append(caption.split("\n\n", 1)[-1]) + return NS(message_id=5) + msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, reply_photo=reply_photo, chat=NS(type=chat_type, title=None), from_user=NS(full_name="Rob"), reply_to_message=None) update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - await Bot(NS(tz=TZ), agent, [], alert_state).respond(update, NS(bot=bot), text) + await Bot(NS(tz=TZ), agent, alert_state, service=await serve()).respond(update, NS(bot=bot), text) return replies -async def test_a_private_chat_shows_a_thinking_draft_that_streams_the_answer_then_sends_it(alert_state, monkeypatch): +async def test_a_private_chat_shows_a_thinking_draft_that_streams_the_answer_then_sends_it(serve, alert_state, monkeypatch): monkeypatch.setattr("lib.bot.DRAFT_MIN_GAP", 0.01) bot = DraftBot() - replies = await ask_private(alert_state, StreamingAgent(), bot) + replies = await ask_private(serve, alert_state, StreamingAgent(), bot) assert replies == ["It is 12 degrees."] assert bot.drafts[0][1] is None # empty: "Thinking..." assert [t for _, t in bot.drafts][-1] == "It is 12 degrees." and len({d for d, _ in bot.drafts}) == 1 assert bot.typing >= 1 # "typing..." runs alongside the draft -async def test_an_idle_draft_is_refreshed_before_telegram_drops_it(alert_state, monkeypatch): +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: @@ -167,19 +189,19 @@ async def run(self, *a, on_text=None, **k): await asyncio.sleep(0.15) return "ok" bot = DraftBot() - await ask_private(alert_state, Slow(), bot) + await ask_private(serve, alert_state, Slow(), bot) assert len(bot.drafts) >= 4 and all(t is None for _, t in bot.drafts) -async def test_a_refused_draft_falls_back_to_typing_and_the_reply_still_arrives(alert_state): +async def test_a_refused_draft_falls_back_to_typing_and_the_reply_still_arrives(serve, alert_state): bot = DraftBot(fail=True) - assert await ask_private(alert_state, StreamingAgent(), bot) == ["It is 12 degrees."] + assert await ask_private(serve, alert_state, StreamingAgent(), bot) == ["It is 12 degrees."] assert bot.drafts == [] and bot.typing >= 1 -async def test_groups_never_get_drafts(alert_state): +async def test_groups_never_get_drafts(serve, alert_state): bot = DraftBot() - assert await ask_private(alert_state, AnsweringAgent(), bot, chat_type="supergroup") == ["It is 12 degrees."] + assert await ask_private(serve, alert_state, AnsweringAgent(), bot, chat_type="supergroup") == ["It is 12 degrees."] assert bot.drafts == [] @@ -187,7 +209,7 @@ async def test_a_generation_stopped_update_is_logged(alert_state, caplog): update = NS(effective_message=NS(api_kwargs={"message_generation_stopped": {"draft_id": 1}}, chat_id=1), effective_chat=NS(type="private", id=1, title=None), effective_user=NS(username="rob", full_name="Rob")) with caplog.at_level("INFO", logger="lib.bot"): - await Bot(NS(tz=TZ), None, [], alert_state).on_other(update, None) + await Bot(NS(tz=TZ), None, alert_state, service=unreached()).on_other(update, None) assert "generation stopped" in caplog.text and "message_generation_stopped" in caplog.text @@ -217,46 +239,6 @@ async def reply_media_group(media, **kw): assert sent == [("text", "Both are up."), ("group", 2)] -async def test_a_report_is_written_in_code_from_the_fast_path_calls_and_the_model_is_not_asked(alert_state): - import json - - class Tools(StandInTools): - def __init__(self): - self.called = [] - - async def call(self, name, raw, turn=None): - self.called.append(name) - return {"weather_now": json.dumps({"outdoor": {"temperature": "12.3 ℃", "humidity": "94 %"}, "emoji": {"outdoor.humidity": "💦"}}), - "air_quality": json.dumps({"pm10": {"value": 3.0, "unit": "µg/m³", "rating": "🟢 good"}})}[name] - - class Agent: - tools = Tools() - - async def run(self, *a, **k): - raise AssertionError("the model must not be asked for a report") - async def dashboard(titles=None): - return None # the station has no gauges to draw: the report goes as text - sources = [NS(name=n, wants=lambda t: True, poke=lambda: None, describe=lambda n=n: n, dashboard=dashboard) for n in ("Ecowitt", "AirGradient")] - agent, replies = Agent(), [] - - async def reply_text(body, **kw): - replies.append(body) - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - - async def send_chat_action(*a, **k): - pass - bot = Bot(NS(tz=TZ), agent, sources, alert_state) - await bot.respond(update, NS(bot=telegram(send_chat_action)), "report") - await bot.respond(update, NS(bot=telegram(send_chat_action)), "weather now") - assert agent.tools.called == ["weather_now", "air_quality", "weather_now"] - assert replies[0] == "Weather station\n• Outdoor: 12.3 °C, 💦 94 %\n\nAir quality\n• PM10: 3.0 µg/m³ 🟢 good" - assert replies[1] == "• Outdoor: 12.3 °C, 💦 94 %" - history = bot.chats[(1, None)].history - assert history[-1] == {"role": "assistant", "content": replies[1]} and history[-4]["content"] == "report" - - async def test_a_question_that_times_out_is_asked_again_one_reasoning_step_lower(alert_state, monkeypatch): from lib import bot as botmod monkeypatch.setattr(botmod, "TURN_SECONDS", 0.05) @@ -270,11 +252,11 @@ async def run(self, messages, system, effort, **k): if effort == "medium": await asyncio.sleep(10) return f"answered at {effort}" - bot = Bot(NS(tz=TZ), SlowThenQuick(), [], alert_state) + bot = Bot(NS(tz=TZ), SlowThenQuick(), alert_state, service=unreached()) working = [{"role": "user", "content": "q"}] - read = intent.read("what do you think about the weather today?", datetime(2026, 10, 2, 12, 0)) - assert read.effort == "medium" - assert await bot._ask_model(working, "sys", read, Turn(), None) == "answered at low" + effort = intent.effort("what do you think about the weather today?") + assert effort == "medium" + assert await bot._ask_model(working, "sys", effort, Turn(), None) == "answered at low" assert efforts == ["medium", "low"] and working == [{"role": "user", "content": "q"}, {"role": "assistant", "content": "(unfinished)"}] @@ -289,139 +271,78 @@ class Hangs: async def run(self, messages, system, effort, **k): efforts.append(effort) await asyncio.sleep(10) - bot = Bot(NS(tz=TZ), Hangs(), [], alert_state) + bot = Bot(NS(tz=TZ), Hangs(), alert_state, service=unreached()) for text, expected in (("hello there", ["none"]), ("what do you think about the weather today?", ["medium", "low"])): efforts.clear() with pytest.raises(TimeoutError): - await bot._ask_model([], "sys", intent.read(text, datetime(2026, 10, 2, 12, 0)), Turn(), None) + await bot._ask_model([], "sys", intent.effort(text), Turn(), None) assert efforts == expected -async def test_a_plain_chart_request_is_drawn_and_captioned_in_code_and_the_model_is_not_asked(alert_state, monkeypatch): - import json - from lib import bot as botmod - from lib.specs import Chart, Line, Panel - - class Tools(StandInTools): - calls = [] - - async def call(self, name, raw, turn=None): - self.calls.append((name, json.loads(raw))) - turn.charts.append(Chart("Humidity", "", [Panel("Humidity", "%", [Line("Outdoor", [1, 2], [50.0, 60.0])])])) - return json.dumps({"period": "Fri 25 Sep 2026 - Thu 01 Oct 2026", "series": { - "outdoor.humidity": {"unit": "%", "low": "50", "high": "60", "low_when": "at 5am", "low_date": "Fri 25 Sep 2026", - "high_when": "at 3pm", "high_date": "Sat 26 Sep 2026"}}}) - +async def test_a_chart_button_is_its_fixed_call_drawn_by_the_service_and_the_model_is_not_asked(serve, alert_state, monkeypatch): class Agent: - tools = Tools() - async def run(self, *a, **k): - raise AssertionError("the model must not be asked for a plain chart") + raise AssertionError("the model must not be asked for a button's chart") sent = [] async def reply_photo(photo, caption=None, **kw): sent.append(caption) - monkeypatch.setattr(botmod, "render_chart", lambda spec, tz, times=None: b"png") - sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] + draws(monkeypatch, lambda data, tz, times=None: b"png") msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_photo=reply_photo, chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) async def send_chat_action(*a, **k): pass - await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), "Humidity chart 7d") - name, args = Agent.tools.calls[0] - assert name == "weather_history" and args["chart"] and args["groups"] == "outdoor,indoor" + service = chart_service() + weather = await serve(tools=service, sources=["Ecowitt"]) + await Bot(NS(tz=TZ), Agent(), alert_state, service=weather).press(update, NS(bot=telegram(send_chat_action)), "Humidity chart 1d") + assert service.calls == [("summary", {"readings": ["humidity"], "period": "1d", "chart": True})] # the button's fixed call assert sent == ["Humidity"] # the chart's title is its whole caption - sent.clear() - await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), "when was humidity highest this week") - assert "high 60 %, Sat 26 Sep" in sent[0] # a record asked for: its figures, with when, go with the chart - - -async def test_a_chart_made_in_code_starts_no_refresh_and_other_questions_do(alert_state, monkeypatch): - """The chart's own reads go first in line; a refresh started beside them would only queue requests ahead of the next ones.""" - import json - from lib import bot as botmod - from lib.specs import Chart, Line, Panel - pokes = [] - class Tools(StandInTools): - async def call(self, name, raw, turn=None): - turn.charts.append(Chart("t", "", [Panel("Temperature", "°C", [Line("Outdoor", [1, 2], [1.0, 2.0])])])) - return json.dumps({"period": "Fri 25 Sep 2026 - Thu 01 Oct 2026", "series": { - "outdoor.temperature": {"unit": "℃", "low": "1", "high": "2"}}}) - class Agent: - tools = Tools() - - async def run(self, *a, **k): - return "It is 12 degrees." - - async def reply(*a, **k): - return NS(message_id=7) - monkeypatch.setattr(botmod, "render_chart", lambda spec, tz, times=None: b"png") - sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: pokes.append(1), describe=lambda: "Ecowitt")] - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_photo=reply, reply_text=reply, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - - async def send_chat_action(*a, **k): - pass - bot, context = Bot(NS(tz=TZ), Agent(), sources, alert_state), NS(bot=telegram(send_chat_action)) - await bot.respond(update, context, "Temperature chart 7d") - assert pokes == [] - await bot.respond(update, context, "what do you think about the weather today?") - assert pokes == [1] - - -async def test_a_chart_reply_logs_how_long_each_step_took(alert_state, tmp_path, monkeypatch, caplog): - """One line per chart reply: reading the data, the calculation, drawing, the PNG (and its size) and sending it.""" +async def test_a_chart_reply_logs_how_long_each_step_took(serve, alert_state, tmp_path, monkeypatch, caplog): + """One line per chart reply: the calculation (the service's call, its drawing included: the bot draws nothing), the picture's size + and sending it.""" import re from lib.ecowitt import Ecowitt, api - from lib.tools import Tools + from lib.service.context import Context from tests.fakes import config, ecowitt_transport monkeypatch.setattr(api, "MIN_GAP_SECONDS", 0) eco = Ecowitt(config(tmp_path), transport=ecowitt_transport()[0]) await eco.start() class Agent: - tools = Tools(eco.tools) - async def run(self, *a, **k): - raise AssertionError("no model for a plain chart") + raise AssertionError("no model for a button's chart") sent = [] async def reply_photo(photo, caption=None, **kw): sent.append(photo) return NS(message_id=7) - sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_photo=reply_photo, chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) async def send_chat_action(*a, **k): pass + weather = await serve(Context(eco=eco, tz=TZ)) # (ecobot-mcp over the fake station) with caplog.at_level("DEBUG"): - await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), - "Temperature chart 1d") + await Bot(NS(tz=TZ), Agent(), alert_state, service=weather).press(update, NS(bot=telegram(send_chat_action)), "Temperature chart 1d") await eco.close() lines = [r.getMessage() for r in caplog.records if r.getMessage().startswith("Chart ms:")] assert len(sent) == 1 and len(lines) == 1, lines kb = round(len(sent[0]) / 1024) - assert re.fullmatch(rf"Chart ms: data \d+, calc \d+, draw \d+, PNG \d+ \({kb} KB\), send \d+", lines[0]) + assert re.fullmatch(rf"Chart ms: calc \d+, {kb} KB, send \d+", lines[0]) -async def _ask_with(alert_state, tool_result, text, monkeypatch=None): - """Ask `text` of a bot whose one tool returns `tool_result`; returns (replies, whether the model was asked).""" +async def _ask_with(serve, alert_state, answer, text, monkeypatch=None): + """Press the button whose sentence is `text` on a bot whose service tools all give `answer`; returns (replies, whether the model was + asked).""" + from tests.fakes import StandInService asked = [] - class Tools(StandInTools): - async def call(self, name, raw, turn=None): - return tool_result - class Agent: - tools = Tools() - async def run(self, messages, *a, **k): asked.append(True) return "from the model" @@ -429,36 +350,27 @@ async def run(self, messages, *a, **k): async def reply_text(body, **kw): replies.append(body) - sources = [NS(name=n, wants=lambda t: True, poke=lambda: None, describe=lambda n=n: n) for n in ("Ecowitt", "AirGradient")] msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) async def send_chat_action(*a, **k): pass - await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), text) + service = StandInService(**{name: answer for name in ("current", "summary", "days", "about", "pollen", "forecast")}) + weather = await serve(tools=service, sources=["Ecowitt", "AirGradient"]) + await Bot(NS(tz=TZ), Agent(), alert_state, service=weather).press(update, NS(bot=telegram(send_chat_action)), text) return replies, bool(asked) -async def test_a_plain_reading_question_is_answered_in_code_without_the_model(alert_state): - import json - result = json.dumps({"outdoor": {"temperature": "12.3 ℃", "feels_like": "11.0 ℃"}, "indoor": {"temperature": "18.3 ℃"}}) - replies, asked = await _ask_with(alert_state, result, "how hot is it") - assert not asked and replies == ["• Outdoor: 12.3 °C, feels like 11.0 °C\n• Indoor: 18.3 °C"] - - -async def test_a_lookup_that_cannot_be_written_falls_back_to_the_model(alert_state): - import json - replies, asked = await _ask_with(alert_state, json.dumps({"error": "station not answering"}), "how hot is it") - assert asked and replies == ["from the model"] - - -async def test_about_the_bot_is_answered_in_code_without_the_model(alert_state): - replies, asked = await _ask_with(alert_state, "{}", "what can you do") - assert not asked and replies[0].startswith("• Temperature, humidity") +async def test_a_button_chart_the_service_cant_draw_says_why_and_the_model_is_not_asked(serve, alert_state): + """(Until step 6c a chart shortcut the service couldn't draw went to the model: a button has no model to fall back on.)""" + replies, asked = await _ask_with(serve, alert_state, {"error": "station not answering"}, "Humidity chart 1d") + assert not asked and replies == ["station not answering"] + replies, asked = await _ask_with(serve, alert_state, {"text": "no chart"}, "Humidity chart 1d") + assert not asked and replies == ["Sorry, I couldn't draw that chart. Please try again in a moment."] -async def test_typing_starts_before_the_model_is_asked_and_runs_alongside_the_draft(alert_state): +async def test_typing_starts_before_the_model_is_asked_and_runs_alongside_the_draft(serve, alert_state): seen = {} class Agent: @@ -467,33 +379,11 @@ async def run(self, *a, **k): await asyncio.sleep(0.05) return "ok" bot = DraftBot() - assert await ask_private(alert_state, Agent(), bot) == ["ok"] + assert await ask_private(serve, alert_state, Agent(), bot) == ["ok"] assert seen["typing_when_asked"] >= 1 and bot.drafts -async def test_the_forecast_is_fetched_with_the_first_step_of_a_rain_ahead_question(alert_state): - got = [] - - class Agent: - async def run(self, messages, system, effort, first_call=None, **k): - got.append(first_call) - return "Possibly." - sources = [NS(name=n, wants=lambda t: True, poke=lambda: None, describe=lambda n=n: n) for n in ("Ecowitt", "Forecast")] - replies = [] - - async def reply_text(body, **kw): - replies.append(body) - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - - async def send_chat_action(*a, **k): - pass - await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), "will it rain?") - assert [name for name, _ in got[0]] == ["weather_now", "weather_history", "weather_forecast"] and replies == ["Possibly."] - - -async def _message_aged(alert_state, seconds): +async def _message_aged(serve, alert_state, seconds): from datetime import datetime, timedelta, timezone answered = [] @@ -512,35 +402,34 @@ async def send_chat_action(*a, **k): date=datetime.now(timezone.utc) - timedelta(seconds=seconds), chat=NS(type="private", title=None, id=1), from_user=NS(full_name="Rob"), reply_to_message=None) update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - bot = Bot(NS(tz=TZ), Agent(), [], alert_state) + bot = Bot(NS(tz=TZ), Agent(), alert_state, service=await serve()) await bot.on_message(update, NS(bot=telegram(send_chat_action, username="b"))) return replies -async def test_a_message_sent_while_the_bot_was_starting_is_answered(alert_state, caplog): - assert await _message_aged(alert_state, 120) == ["ok"] +async def test_a_message_sent_while_the_bot_was_starting_is_answered(serve, alert_state, caplog): + assert await _message_aged(serve, alert_state, 120) == ["ok"] -async def test_a_message_that_waited_hours_is_ignored_and_logged(alert_state, caplog): +async def test_a_message_that_waited_hours_is_ignored_and_logged(serve, alert_state, caplog): with caplog.at_level("INFO", logger="lib.bot"): - assert await _message_aged(alert_state, 2 * 3600) == [] + assert await _message_aged(serve, alert_state, 2 * 3600) == [] assert "[Telegram 1]: @rob: ignored a message 120 minutes old: how hot is it" in caplog.text -async def test_a_request_and_its_reply_are_logged_under_the_chat_they_came_from(alert_state, caplog): +async def test_a_request_and_its_reply_are_logged_under_the_chat_they_came_from(serve, alert_state, caplog): with caplog.at_level("INFO", logger="lib.bot"): - assert await _message_aged(alert_state, 5) == ["ok"] + assert await _message_aged(serve, alert_state, 5) == ["ok"] lines = [r.getMessage() for r in caplog.records if r.name == "lib.bot"] assert "[Telegram 1]: @rob: how hot is it" in lines assert any(line.startswith("[Telegram 1]: Replied in ") and line.endswith(", tools 0, charts 0, 2 chars") for line in lines) -async def test_a_heavy_question_gets_a_heads_up_in_the_chat_before_the_answer_and_the_answer_still_comes(alert_state): +async def test_a_heavy_question_gets_a_heads_up_in_the_chat_before_the_answer_and_the_answer_still_comes(serve, alert_state): class Agent: async def run(self, messages, system, effort, on_heavy=None, **k): await on_heavy(24000) return "The answer." - sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] replies = [] async def reply_text(body, **kw): @@ -551,71 +440,45 @@ async def reply_text(body, **kw): async def send_chat_action(*a, **k): pass - await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), "is it too cold to run") + weather = await serve(sources=["Ecowitt"]) + await Bot(NS(tz=TZ), Agent(), alert_state, service=weather).respond(update, NS(bot=telegram(send_chat_action)), "is it too cold to run") assert replies == ["\u26a0\ufe0f That's pulling in about 24k tokens of data, so it will take a little longer. Working on it...", "The answer."] -async def test_a_days_over_a_limit_question_is_counted_in_code_with_no_model(alert_state): - import json - result = json.dumps({"period": "Wed 5 Oct 2022 - Sat 3 Oct 2026", "days_checked": 1454, "matching_days": 137, "condition": "UV index ≥ 10"}) - replies, asked = await _ask_with(alert_state, result, "days over UVI 10 by year") - assert not asked and replies == ["137 of 1,454 days with UV index ≥ 10 (Wed 5 Oct 2022 – Sat 3 Oct 2026)."] - - -async def test_rain_by_month_is_worked_out_in_code_with_no_model(alert_state): - import json - result = json.dumps({"period": "Fri 4 Oct 2024 - Sat 3 Oct 2026", "days_checked": 731, "matching_days": 731, - "stat": {"what": "Total rain", "of": "rain", "unit": "mm"}, "value": 1234.5}) - replies, asked = await _ask_with(alert_state, result, "rain by month for 2 years") - assert not asked and replies == ["Total rain: 1234.5 mm over 731 days (Fri 4 Oct 2024 – Sat 3 Oct 2026)."] - - -async def test_the_model_is_asked_with_the_tool_choice_the_message_calls_for(alert_state): +async def test_the_model_chooses_its_own_tools_whatever_the_message(serve, alert_state): seen = [] class Agent: async def run(self, messages, system, effort, **k): seen.append(k["tool_choice"]) return "ok" + weather = await serve(sources=["Ecowitt"]) for text in ("will it rain tomorrow?", "thanks!"): replies = [] async def reply_text(body, **kw): replies.append(body) - sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) async def send_chat_action(*a, **k): pass - await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), text) - assert seen == ["required", "auto"] + await Bot(NS(tz=TZ), Agent(), alert_state, service=weather).respond(update, NS(bot=telegram(send_chat_action)), text) + assert seen == ["auto", "auto"] -async def test_weather_all_week_and_a_plain_chart_are_sent_with_just_their_title(alert_state, monkeypatch): - import json - from lib import bot as botmod - from lib.specs import Chart, Line, Panel - - class Tools(StandInTools): - async def call(self, name, raw, turn=None): - turn.charts.append(Chart("t", "", [Panel("Temperature", "°C", [Line("Outdoor", [1, 2], [1.0, 2.0])])])) - return json.dumps({"period": "Fri 25 Sep 2026 - Thu 01 Oct 2026", "series": { - "outdoor.temperature": {"unit": "℃", "low": "1", "high": "2"}}}) - +async def test_the_weather_and_temperature_buttons_charts_are_sent_with_just_their_title(serve, alert_state, monkeypatch): class Agent: - tools = Tools() - async def run(self, *a, **k): raise AssertionError("no model for a chart") sent = [] async def reply_photo(photo, caption=None, **kw): sent.append(caption) - monkeypatch.setattr(botmod, "render_chart", lambda spec, tz, times=None: b"png") - sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] - for text, caption_wanted in (("ecowitt all week", True), ("temperature chart 7d", True)): + draws(monkeypatch, lambda data, tz, times=None: b"png") + weather = await serve(tools=chart_service(title="t"), sources=["Ecowitt"]) + for text in ("Weather chart 1d", "Temperature chart 1d"): sent.clear() msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_photo=reply_photo, chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) @@ -623,59 +486,10 @@ async def reply_photo(photo, caption=None, **kw): async def send_chat_action(*a, **k): pass - await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), text) + await Bot(NS(tz=TZ), Agent(), alert_state, service=weather).press(update, NS(bot=telegram(send_chat_action)), text) assert sent == ["t"], text -async def test_the_report_carries_a_refresh_button_that_redraws_it_in_place(alert_state): - import json - from lib import report_menu - - class Tools(StandInTools): - reading = "12.3 ℃" - - async def call(self, name, raw, turn=None): - return {"weather_now": json.dumps({"outdoor": {"temperature": self.reading}}), - "air_quality": json.dumps({"pm10": {"value": 3.0, "unit": "µg/m³", "rating": "🟢 good"}})}[name] - - class Agent: - tools = Tools() - - class Query: - data, edits, toast = report_menu.REFRESH, [], None - - async def answer(self, text=None, **kw): - self.toast = text - - async def edit_message_text(self, text, reply_markup=None, **kw): - self.edits.append((text, reply_markup)) - self.entities = kw.get("entities") - sources = [NS(name=n, wants=lambda t: True, poke=lambda: None, describe=lambda n=n: n) for n in ("Ecowitt", "AirGradient")] - sent = [] - - async def reply_text(body, **kw): - sent.append((body, kw.get("reply_markup"), kw.get("entities"))) - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - - async def send_chat_action(*a, **k): - pass - context = NS(bot=telegram(send_chat_action)) - bot = Bot(NS(tz=TZ), Agent(), sources, alert_state) - alert_state.add_chat(1, "Rob") - alert_state.set_keyboard(1, bot.keyboard_version) # its buttons are current, so a reply carries only its own - await bot.respond(update, context, "report") - await bot.respond(update, context, "weather now") - assert [b.callback_data for b in sent[0][1].inline_keyboard[0]] == [report_menu.REFRESH] and sent[1][1] is None - assert [e.type for e in sent[0][2]] == ["bold", "bold"] and sent[1][2] is None # the report's headings are bold; "weather now" has none - Tools.reading = "13.0 ℃" - query = Query() - await bot.on_report_button(NS(callback_query=query), context) - assert query.toast is None and "13.0 °C" in query.edits[0][0] and query.edits[0][1].inline_keyboard[0][0].callback_data == report_menu.REFRESH - assert [e.type for e in query.entities] == ["bold", "bold"] - - async def test_a_button_press_too_old_to_answer_is_only_logged_and_other_errors_still_raise(caplog): import pytest from telegram.error import BadRequest @@ -701,133 +515,139 @@ async def answer(self, *args, **kwargs): await answer_query(Query(BadRequest("Message is not modified"))) -async def test_the_air_sensors_own_readings_stay_offered_in_a_chat_until_two_runs_go_by_without_the_model_using_them(alert_state): - seen = [] - uses = iter([True, True, False, False, False]) # what the model does with the series when it has them: used, used, then not +class ChartingAgent(StreamingAgent): + """The model's first step drew a chart (a result with `charts` kept on the Turn, and its picture as the service drew it); then it + streams its answer.""" - class Capturing: - async def run(self, messages, system, effort, *, turn=None, **k): - seen.append((turn.air_extra, "AIRGRADIENT'S OWN TEMPERATURE AND HUMIDITY" in system)) - if turn.air_extra and next(uses): - turn.air_extra_used = True # a tool served them - return "ok" - replies = [] + async def run(self, messages, system, effort, *, turn=None, **k): + from lib.weather import ChartImage + from tests.fakes import chart_data + chart = chart_data("Humidity") + turn.results.append(("summary", {"readings": ["humidity"]}, {"caption": "c", "charts": [chart]})) + turn.pictures[len(turn.results) - 1] = [ChartImage(b"png", chart, False)] + return await super().run(messages, system, effort, turn=turn, **k) - async def reply_text(body, **kw): - replies.append(body) - async def send_chat_action(*a, **k): - pass - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - context = NS(bot=telegram(send_chat_action)) - bot = Bot(NS(tz=TZ), Capturing(), [], alert_state) - for said in ("what is the weather like", "overlay ecowitt humidity with airgradient humidity", "do that again but for temperature", - "and the wind?", "and the rain?", "and the pressure?", "and the uv?"): - await bot.respond(update, context, said) - assert seen == [(False, False), # nothing about the air sensor yet - (True, True), (True, True), # named, used; the follow-up (no AirGradient in it) still offered, used again - (True, True), (True, True), # two runs the model did not use them in ... - (False, False), (False, False)] # ... and they are no longer offered, nor mentioned in the prompt +async def test_an_answer_that_comes_with_a_chart_is_not_streamed_into_the_draft(serve, alert_state, monkeypatch): + monkeypatch.setattr("lib.bot.DRAFT_MIN_GAP", 0.01) + bot = DraftBot() + assert await ask_private(serve, alert_state, ChartingAgent(), bot, text="plot humidity for a week") == ["It is 12 degrees."] + assert bot.drafts and all(t is None for _, t in bot.drafts) # only "Thinking...": no text to be followed by a picture and a second message + bot = DraftBot() + await ask_private(serve, alert_state, StreamingAgent(), bot, text="how hot is it") + assert [t for _, t in bot.drafts][-1] == "It is 12 degrees." # a plain answer still streams -async def test_either_side_naming_the_air_sensors_readings_keeps_them_offered(alert_state): - seen = [] - replies_by_question = {"what is the weather like": "It is mild.", "tell me about airgradient humidity": "The AirGradient humidity is 61%.", - "and tomorrow?": "Sunny.", "and the day after?": "Cloudy.", "what about the wind?": "Calm."} +def chart_service(caption="Fri 25 Sep – Thu 1 Oct 2026\nHumidity: low 50 %, Fri 25 Sep at 5am · high 60 %, Sat 26 Sep at 3pm", + title="Humidity"): + """A stand-in service whose summary draws a chart titled `title` and captions it.""" + from tests.fakes import StandInService, chart_data + return StandInService(summary=lambda args, meta: {"caption": caption, "charts": [chart_data(title)]}) - class Capturing: - async def run(self, messages, system, effort, *, turn=None, **k): - seen.append(turn.air_extra) - return replies_by_question[messages[-1]["content"]] - sent = [] - async def reply_text(body, **kw): - sent.append(body) +async def test_a_chart_kept_by_its_question_from_before_the_swap_is_out_of_date(serve, alert_state): + """Before step 3 a chart the model drew through a call the service had no equivalent of was remembered by its question; its buttons + are out of date now.""" + from tests.fakes import StandInService + bot = Bot(NS(tz=TZ), None, alert_state, service=await serve(tools=StandInService())) + bot.charted.remember(1, 7, "how warm was it") + answers = [] - async def send_chat_action(*a, **k): - pass - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - context = NS(bot=telegram(send_chat_action)) - bot = Bot(NS(tz=TZ), Capturing(), [], alert_state) - for said in replies_by_question: - await bot.respond(update, context, said) - # the person's words named it (offered) and the reply did too (still offered for the next two runs); then they stop - assert seen == [False, True, True, True, False] + async def answer(text=None, **k): + answers.append(text) + query = NS(data="pd:7", message=NS(chat_id=1, message_id=7), answer=answer) + await bot.on_period_button(NS(callback_query=query), None) + assert answers == ["That chart is out of date, please ask again"] -async def test_the_air_sensors_own_readings_are_offered_to_a_follow_up_when_the_last_messages_named_them_whatever_the_count(alert_state): - seen = [] +async def test_the_models_charts_are_drawn_with_their_buttons_and_the_model_is_sent_their_titles_alone(serve, alert_state, monkeypatch): + """The model's call drew a chart: the model sees its title and period (no points), never the picture; the bot sends the picture + the service drew (asked for as an image), with the period buttons its drawn_by lists, and keeps the call behind them.""" + import json + from lib import model_tools + from lib.llm import Agent + from tests.fakes import chart_data + drawn_by = {"tool": "summary", "arguments": {"readings": ["humidity"], "period": "7d", "chart": True}, + "periods": [{"period": "1d", "label": "1D"}, {"period": "7d", "label": "7D"}]} + chart = {**chart_data("Humidity"), "drawn_by": drawn_by} + + class Summary: + name, description, parameters = "summary", "Summary.", {"type": "object", "properties": {}} + + async def call(self, args, meta): + assert meta["chart_points"] == "drawn" + return json.dumps({"caption": "c", "charts": [chart], "chart_note": "note"}) + drawn = [] + draws(monkeypatch, lambda c, tz: drawn.append(c) or b"png") # (ecobot-mcp's drawing, in memory) + weather = await serve(tools=[Summary()]) + seen, sent = [], [] + + class Model: + """A model that calls summary, then answers.""" + def __init__(self): + self.chat = self - class Capturing: - async def run(self, messages, system, effort, *, turn=None, **k): - seen.append(turn.air_extra) - return "ok" - sent = [] + async def create(self, **kw): + seen.append(kw["messages"][-1]) + if len(seen) == 1: + call = NS(id="1", function=NS(name="summary", arguments="{}")) + return NS(choices=[NS(message=NS(content="", tool_calls=[call]))], usage=None) + return NS(choices=[NS(message=NS(content="Humid all week.", tool_calls=None))], usage=None) - async def reply_text(body, **kw): - sent.append(body) + client = NS(chat=NS(completions=Model())) - async def send_chat_action(*a, **k): - pass - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) + async def reply_photo(photo, caption=None, reply_markup=None, **kw): + sent.append((caption, reply_markup)) + return NS(message_id=9) + msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_photo=reply_photo, + chat=NS(type="group", title="g"), from_user=NS(full_name="Rob"), reply_to_message=None) update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - context = NS(bot=telegram(send_chat_action)) - for earlier in ( - [{"role": "user", "content": "plot airgradient humidity"}, {"role": "assistant", "content": "Done."}], # the person named it - [{"role": "user", "content": "plot humidity"}, {"role": "assistant", "content": "Here is AirGradient humidity over Ecowitt."}], # the reply did - [{"role": "user", "content": "plot humidity"}, {"role": "assistant", "content": "Done."}]): # neither did - bot = Bot(NS(tz=TZ), Capturing(), [], alert_state) - bot.chats[bot._key(msg)].history = list(earlier) # a chat whose count has run out: only the messages are left - await bot.respond(update, context, "do that again but for temperature") - assert seen == [True, True, False] - - -async def test_every_guidance_topic_stays_on_in_a_chat_while_either_side_names_it_or_its_tools_are_used_then_goes_after_two_quiet_runs(alert_state): - seen = [] - script = {"how many days was uv over 9": ("ok", "weather_days"), # the person names days, and its tool is used - "and for solar": ("ok", None), "thanks": ("ok", None), "right": ("ok", None), - "tell me something": ("The pressure is steady and the wind was strong.", None), # the reply names wind - "and the pressure": ("ok", None), "and humidity": ("ok", None), "fine": ("ok", None), "good": ("ok", None)} - - class Capturing: - async def run(self, messages, system, effort, *, turn=None, **k): - seen.append((messages[-1]["content"], sorted(turn.topics & {"days", "wind"}))) - reply, tool = script[messages[-1]["content"]] - if tool: - messages.append({"role": "assistant", "content": None, "tool_calls": [{"function": {"name": tool}}]}) - return reply - sent = [] - - async def reply_text(body, **kw): - sent.append(body) async def send_chat_action(*a, **k): pass - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - context = NS(bot=telegram(send_chat_action)) - bot = Bot(NS(tz=TZ), Capturing(), [], alert_state) - for said in script: - await bot.respond(update, context, said) - got = dict(seen) - assert got["how many days was uv over 9"] == ["days"] - assert got["and for solar"] == ["days"] and got["thanks"] == ["days"] # no word of it, but its tool was just used - assert got["right"] == [] # two quiet runs: gone - assert got["and the pressure"] == ["wind"] # the reply to the question before named the wind - assert got["and humidity"] == ["wind"] and got["fine"] == [] and got["good"] == [] # and that goes too, after two quiet runs - - -async def test_an_answer_that_comes_with_a_chart_is_not_streamed_into_the_draft(alert_state, monkeypatch): - monkeypatch.setattr("lib.bot.DRAFT_MIN_GAP", 0.01) - bot = DraftBot() - assert await ask_private(alert_state, StreamingAgent(), bot, text="plot humidity for a week") == ["It is 12 degrees."] - assert bot.drafts and all(t is None for _, t in bot.drafts) # only "Thinking...": no text to be followed by a picture and a second message - bot = DraftBot() - await ask_private(alert_state, StreamingAgent(), bot, text="how hot is it") - assert [t for _, t in bot.drafts][-1] == "It is 12 degrees." # a plain answer still streams + bot = Bot(NS(tz=TZ), Agent(client, "m", model_tools.tools(weather)), alert_state, service=weather) + await bot.respond(update, NS(bot=telegram(send_chat_action)), "how humid was it this week?") + told = json.loads(seen[-1]["content"]) + assert told["charts"] == [{"title": "Humidity", "period": chart["period"]}] and told["chart_note"] == model_tools.BOT_CHART_NOTE + assert drawn == [chart] and "png" not in seen[-1]["content"] + (caption, markup), = sent + assert caption.startswith("Humidity") and "Humid all week." in caption + assert [b.callback_data for b in markup.inline_keyboard[0]] == ["pd:1d", "pd:7d"] + assert bot.charted.get(1, 9)["drawn_by"] == drawn_by + + +BOT_MODULES = ["ecobot", "lib.bot", "lib.weather", "lib.upstream", "lib.model_tools", "lib.llm", "lib.prompt", "lib.alerts.notify", + "lib.alerts.menu", "lib.irrigation_menu", "lib.irrigation_remote", "lib.periods", "lib.templates", + "lib.admins", "lib.buttons", "lib.config", "lib.intent", "lib.version", "lib.theme"] +NOT_THE_BOTS = ("PIL", "lib.charts", "lib.draw", "lib.gauges", # drawing (step 6a) + "lib.ecowitt", "lib.airgradient", "lib.forecast", "lib.pollen", "lib.storage", # the sources and their file (6b) + "lib.irrigation.tuya", "lib.irrigation.watchdog", "lib.irrigation.check", # irrigation-mcp's controller (8b) + "lib.irrigation.server", "lib.irrigation.state", "lib.irrigation.ecobot") + + +def test_the_bot_imports_no_pillow_no_drawing_module_and_no_source_module(tmp_path): + """The bot draws nothing, runs no source and no irrigation controller (docs/ecobot-mcp.md steps 6a, 6b and 8b): importing its + modules, and building it as ecobot-mcp's and irrigation-mcp's client with both alert deliveries, and reading an answer for the air + link (reads_air), imports neither Pillow nor lib/charts.py, lib/draw.py or lib/gauges.py, nor any module of the sources (lib/ecowitt, + lib/airgradient, lib/forecast, lib/pollen) or of the readings file (lib/storage), nor irrigation-mcp's Tuya client, watchdog, daily + check or server; every picture it sends, and every reading, is ecobot-mcp's, and the controller irrigation-mcp's.""" + import os + import subprocess + import sys + from lib.config import ROOT + code = (f"import sys, importlib; [importlib.import_module(m) for m in {BOT_MODULES!r}]; " + "from types import SimpleNamespace as NS; from zoneinfo import ZoneInfo; from lib.alerts.notify import AlertDelivery, " + "AlertState, Notifier, ReadMark; from lib.bot import Bot; from lib.llm import Agent; " + "from lib import model_tools; from lib.weather import RemoteWeather; from lib.irrigation_remote import RemoteIrrigation; " + "w = RemoteWeather('http://127.0.0.1:9/mcp', 't'); i = RemoteIrrigation('http://127.0.0.1:9/mcp', 't'); " + f"s = AlertState({str(tmp_path / 's.json')!r}); " + "b = Bot(NS(tz=ZoneInfo('UTC')), Agent(None, 'm', model_tools.tools(w)), s, i, service=w); " + "AlertDelivery(w.alerts, Notifier(NS(), s, b.alert_charts), s, ZoneInfo('UTC'), weather=w); " + "AlertDelivery(i.alerts, Notifier(NS(), s, b.alert_charts), s, ZoneInfo('UTC'), mark=ReadMark(s, 'irrigation-mcp')); " + "from lib.bot import reads_air; [reads_air(*c) for c in (('current', {'readings': ['pm2.5']}, {'sensors': {'air': {}}}), " + "('days', {'sort_by': 'pm2_5_max'}, {}), ('summary', {}, {'series': {}}))]; " + f"print(sorted(m for m in sys.modules if m.split('.')[0] == 'PIL' or m.startswith({NOT_THE_BOTS!r})))") + done = subprocess.run([sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True, timeout=120, + env={**os.environ, "DATA_DIR": str(tmp_path)}) + assert done.returncode == 0, done.stderr + assert done.stdout.strip().splitlines()[-1] == "[]" diff --git a/tests/test_bot_remote.py b/tests/test_bot_remote.py new file mode 100644 index 00000000..adb0b583 --- /dev/null +++ b/tests/test_bot_remote.py @@ -0,0 +1,646 @@ +"""The bot as the service's client over MCP (BOT_MCP_URL: lib/weather.RemoteWeather, docs/ecobot-mcp.md 3.8 and step 5), against the +real server (lib/mcp_server.EcobotServer): over the SDK's in-memory transport for a question answered with the remote tools, a chart drawn +from a remote result with its buttons and an alert delivered through the listen (and irrigation-mcp's daily check's inputs, read from the +same real server by its own client, lib/irrigation/ecobot.py); under uvicorn on a localhost +port (a connection can fail there) for a dropped connection rebuilt with the alerts after the last id read once, the service down (the bot +says so), and ecobot.main(), always a client (step 6b). The rest of the suite runs the bot against ecobot-mcp in memory (tests/served.py).""" + +import asyncio +import json +import time +from types import SimpleNamespace as NS + +import pytest + +import ecobot_mcp.__main__ as service_main +from lib import upstream +from lib import model_tools, weather as weather_module +from lib.alert_log import AlertLog +from lib.alerts.notify import AlertDelivery, AlertState, Notifier +from lib.bot import SERVICE_DOWN, Bot +from lib.llm import Agent +from lib.mcp_server import EcobotServer, http_app +from lib.service.context import Context +from lib.weather import RemoteWeather, ServiceUnreachable +from tests import evalworld +from tests.fakes import TZ +from tests.test_mcp_listen import Serving, free_port, until + +TOKEN = "s3cret" + + +def at_eval_now(patch: pytest.MonkeyPatch): + evalworld.at_eval_now(patch, __name__) + + +@pytest.fixture(scope="module") +def eval_archive(shared_archive): + """The fake station's whole archive (its ecobot.sqlite) built at EVAL_NOW, the air's month held in it too (real_context), once for every + worker and run (tests/evalworld.py's).""" + return evalworld.shared_eval_archive(shared_archive) + + +@pytest.fixture +async def world(tmp_path, eval_archive, monkeypatch): + """The real server over the four sources (faked, the clock at the evals' NOW) and an alert log.""" + at_eval_now(monkeypatch) + ctx = await evalworld.real_context(tmp_path, eval_archive) + alerts = AlertLog(tmp_path / "alerts.sqlite", ctx.zone) + server = EcobotServer(ctx, alerts) + yield server + alerts.close() + await evalworld.close(ctx) + + +@pytest.fixture(autouse=True) +def quick(monkeypatch): + """Reconnections and waits in tenths of a second, not seconds.""" + monkeypatch.setattr(upstream, "BACKOFF", (0.1,)) + monkeypatch.setattr(weather_module, "CALL_WAIT", 0.3) + monkeypatch.setattr(service_main, "SHUTDOWN_SECONDS", 0.25) # (a listen still open when a server stops: tests/test_mcp_listen.py) + + +@pytest.fixture +async def connected(world): + """A RemoteWeather over the server in memory, its supervisor running and listening.""" + remote = RemoteWeather(world.server, tz=None) + task = asyncio.create_task(remote.run()) + await asyncio.wait_for(remote.listening.wait(), 10) + yield remote + task.cancel() + await asyncio.gather(task, return_exceptions=True) + await remote.close() + + +class Telegram: + """What the bot sends, kept.""" + def __init__(self): + self.sent = [] + + async def send_message(self, chat_id, text, **kw): + self.sent.append((chat_id, text)) + return NS(photo=None) + + async def send_photo(self, chat_id, photo, **kw): + self.sent.append((chat_id, kw.get("caption"))) + return NS(photo=(NS(file_id="small"), NS(file_id="big"))) + + +def a_chat(kind="private"): + """A message in a chat, its replies kept (text, or (caption, buttons) for a photo).""" + replies = [] + + async def reply_text(body, **kw): + replies.append(body) + return NS(message_id=8) + + async def reply_photo(photo, caption=None, reply_markup=None, **kw): + replies.append((caption, reply_markup)) + return NS(message_id=9) + + async def nothing(*a, **k): + pass + msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, reply_photo=reply_photo, + chat=NS(type=kind, title="g" if kind != "private" else None), from_user=NS(full_name="Rob"), reply_to_message=None) + update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) + context = NS(bot=NS(send_chat_action=nothing, send_message_draft=nothing, id=99)) + return update, context, replies + + +class Model: + """A model that makes `calls` (name, arguments) in its first step, then answers `answer`; what it was sent is kept.""" + + def __init__(self, calls, answer="It's 14.2 °C."): + self.calls, self.answer, self.seen = calls, answer, [] + self.chat = NS(completions=self) + + async def create(self, **kw): + self.seen.append(kw) + if len(self.seen) == 1 and self.calls: + made = [NS(id=str(i), function=NS(name=name, arguments=json.dumps(args))) for i, (name, args) in enumerate(self.calls)] + return NS(choices=[NS(message=NS(content="", tool_calls=made))], usage=None) + return NS(choices=[NS(message=NS(content=self.answer, tool_calls=None))], usage=None) + + +# ---------- in memory ---------- +async def test_a_question_is_answered_with_the_remote_tools_and_the_instructions_from_discover(connected, world, alert_state): + model = Model([("current", {"readings": ["temperature"]})]) + bot = Bot(NS(tz=TZ), Agent(model, "m", model_tools.tools(connected)), alert_state, service=connected) + update, context, replies = a_chat("group") # (no draft streamed: the model's answer comes whole) + await bot.respond(update, context, "how warm is it outside?") + first = model.seen[0] + assert [t["function"]["name"] for t in first["tools"]] == [t.name for t in world.service] # the service's ten, as listed + assert world.server.instructions and world.server.instructions in first["messages"][0]["content"] # discover's instructions + told = json.loads(model.seen[1]["messages"][-1]["content"]) + assert told == json.loads(await world.service["current"].call({"readings": ["temperature"]})) # the remote tool's own answer + assert replies == ["It's 14.2 °C."] + assert bot.names == {"Ecowitt", "AirGradient", "Forecast", "Pollen"} and not hasattr(bot, "sources") # (from ecobot://station; none here) + + +async def test_a_charts_picture_comes_from_the_service_with_its_period_buttons(connected, alert_state, monkeypatch): + """The bot draws nothing: the chart's picture is the service's (asked for as an image), its JSON from the result's _meta.""" + got, photos = [], [] + asked = connected.call_images + + async def call_images(*a, **k): + out, images = await asked(*a, **k) + got.append(images) + return out, images + monkeypatch.setattr(connected, "call_images", call_images) + bot = Bot(NS(tz=TZ), Agent(None, "m", model_tools.tools(connected)), alert_state, service=connected) + update, context, replies = a_chat("group") + reply_photo = update.effective_message.reply_photo + + async def kept(photo, **kw): + photos.append(photo) + return await reply_photo(photo, **kw) + update.effective_message.reply_photo = kept + await bot.respond(update, context, "Humidity chart 7d", call=("summary", {"readings": ["humidity"], "period": "7d", "chart": True})) # (as a button: its call, no model) + (caption, markup), = replies + ((image,),) = got + chart = image.chart + assert photos == [image.png] and image.png.startswith(b"\x89PNG") + assert chart["drawn_by"]["tool"] == "summary" and chart["drawn_by"]["arguments"]["period"] == "7d" + assert len(max((s["points"] for p in chart["panels"] for s in p["series"]), key=len)) > 150 # (asked as drawn, not 150 points) + assert [b.callback_data for b in markup.inline_keyboard[0]] == ["pd:1d", "pd:7d", "pd:1m", "pd:3m", "pd:1y"] + assert bot.charted.get(1, 9)["drawn_by"] == chart["drawn_by"] + + +async def test_the_models_charts_come_from_the_service_as_pictures_and_the_model_gets_only_their_text(connected, world, alert_state, + monkeypatch): + """A chart in the model's answer: its call asked for the picture (chart_image "png"), the bot sends the service's PNG with its period + buttons, and the model is sent the result's text alone (each chart's title and period, BOT_CHART_NOTE), never the image.""" + from lib import chart_images + call = ("summary", {"readings": ["humidity"], "period": "7d", "chart": True}) + metas, photos = [], [] + calling = connected.upstream.client.call_tool + + async def call_tool(name, args, meta=None, **k): + metas.append(meta) + return await calling(name, args, meta=meta, **k) + monkeypatch.setattr(connected.upstream.client, "call_tool", call_tool) + model = Model([call], "Humid all week.") + bot = Bot(NS(tz=TZ), Agent(model, "m", model_tools.tools(connected)), alert_state, service=connected) + update, context, replies = a_chat("group") + reply_photo = update.effective_message.reply_photo + + async def kept(photo, **kw): + photos.append(photo) + return await reply_photo(photo, **kw) + update.effective_message.reply_photo = kept + await bot.respond(update, context, "how humid was it this week? chart it") + assert [m["chart_image"] for m in metas] == [chart_images.IMAGE] + sent_to_model = model.seen[1]["messages"][-1]["content"] + told = json.loads(sent_to_model) + assert [set(c) for c in told["charts"]] == [{"title", "period"}] and told["chart_note"] == model_tools.BOT_CHART_NOTE + assert "image" not in sent_to_model and "base64" not in sent_to_model + (caption, markup), = replies + out, (image,) = await connected.call_images(*call, {"chart_points": "drawn"}) + assert photos == [image.png] and image.png.startswith(b"\x89PNG") and "Humid all week." in caption + assert [b.callback_data for b in markup.inline_keyboard[0]] == ["pd:1d", "pd:7d", "pd:1m", "pd:3m", "pd:1y"] + assert bot.charted.get(1, 9)["drawn_by"] == out["charts"][0]["drawn_by"] + + +async def test_status_is_one_message_ecobot_mcps_picture_with_its_report_as_the_caption_and_no_model(connected, world, alert_state): + """Status (/status, the button): ecobot://status's PNG, byte for byte, with the report ecobot-mcp writes (current's sections, today's + forecast, the pollen) as its caption and a 🔄: one message, no model.""" + import base64 + from lib.bot import STATUS_REFRESH + photos = [] + model = Model([], "unused") + bot = Bot(NS(tz=TZ), Agent(model, "m", model_tools.tools(connected)), alert_state, service=connected) + update, context, replies = a_chat("group") + reply_photo = update.effective_message.reply_photo + + async def kept(photo, **kw): + photos.append(photo) + return await reply_photo(photo, **kw) + update.effective_message.reply_photo = kept + await bot.status(update, context) + contents = (await connected.upstream.client.read_resource("ecobot://status")).contents + (png,) = [base64.b64decode(c.blob) for c in contents if getattr(c, "blob", None)] + report = json.loads(contents[0].text)["report"] + assert photos == [png] and png.startswith(b"\x89PNG") and model.seen == [] + ((caption, markup),) = replies + assert caption == report and caption.startswith("Weather station (") and "\n\nForecast (" in caption and "\n\nPollen & asthma (" in caption + assert [[b.callback_data for b in row] for row in markup.inline_keyboard] == [[STATUS_REFRESH]] + + +async def test_ecobot_mcps_prompts_are_telegram_commands_whose_words_fill_their_arguments(connected, world, alert_state, caplog): + """Step 6c: each of ecobot-mcp's prompts is a command in the menu (after the charts', before the settings), with its description; + "/ " fills its arguments in order, the last taking the rest, and the prompt's question is asked of the model as a typed + question; none: the prompt's defaults. A prompt the service refuses is said in the chat; another bot's command is left alone.""" + from lib import templates + from lib.mcp_server import PROMPTS, prompt + model = Model([], "Done.") + bot = Bot(NS(tz=TZ), Agent(model, "m", model_tools.tools(connected)), alert_state, service=connected) + menus = [] + + class Telegram: + async def set_my_commands(self, commands): + menus.append([(c.command, c.description) for c in commands]) + await bot.publish_commands(Telegram()) + own = list(templates.MENU) + at = [name for name, _ in own].index("alerts") + assert menus == [[*own[:at], *((name, what) for name, (what, _, _) in PROMPTS.items()), *own[at:]]] + asked = lambda: model.seen[-1]["messages"][-1]["content"] + question = lambda name, **args: prompt(name, args).messages[0].content.text + for typed, want in (("/chart rain 7d", question("chart", reading="rain", period="7d")), + ("/chart pm2.5 last two weeks", question("chart", reading="pm2.5", period="last two weeks")), + ("/rainfall last week", question("rainfall", period="last week")), + ("/rainfall", question("rainfall")), ("/now", question("now")), ("/report@ecobot", question("report")), + ("/air", "How is the air quality now?"), + ("/will_it_rain tomorrow", f"{question('will_it_rain')} (tomorrow)")): # (no arguments: the words follow it) + update, context, replies = a_chat("group") + update.effective_message.text, update.effective_message.chat.id, context.bot.username = typed, 1, "ecobot" + await bot.on_command(update, context) + assert asked() == f"Rob: {want}" and replies == ["Done."], typed # (a group: its sender named) + seen = len(model.seen) + for typed in ("/chart", "/report@otherbot", "/nosuch rain"): + update, context, replies = a_chat() + update.effective_message.text, update.effective_message.chat.id, context.bot.username = typed, 1, "ecobot" + await bot.on_command(update, context) + assert replies == (["Sorry, /chart didn't work: The prompt 'chart' needs reading."] if typed == "/chart" else []), typed + assert len(model.seen) == seen # none of these asked the model + + +async def test_while_ecobot_mcp_is_unreached_a_command_not_the_bots_own_says_so(alert_state): + """Before ecobot-mcp is first reached its prompts (so their commands) aren't known: "/report" is told the service can't be reached, + not left unanswered; another bot's command is still left alone.""" + from lib.bot import SERVICE_DOWN + from tests.served import unreached + weather = unreached() + bot = Bot(NS(tz=TZ), Agent(None, "m", model_tools.tools(weather)), alert_state, service=weather) + for typed, want in (("/report", [SERVICE_DOWN]), ("/report@otherbot", [])): + update, context, replies = a_chat() + update.effective_message.text, update.effective_message.chat.id, context.bot.username = typed, 1, "ecobot" + await bot.on_command(update, context) + assert replies == want, typed + + +async def test_a_prompt_that_is_no_command_name_or_is_one_of_the_bots_is_left_out_with_a_warning(connected, alert_state, caplog): + from lib import templates + from lib.weather import Prompt + bot = Bot(NS(tz=TZ), Agent(None, "m", []), alert_state, service=connected) + connected.prompts = [Prompt("Weather Now", "Bad name", ()), Prompt("rain", "Takes the Rain button's", ()), + Prompt("x" * 33, "Too long", ()), Prompt("frost", "Frost tonight?", ("place",))] + menu = bot.commands() + assert [name for name, _ in menu] == [*[n for n, _ in templates.MENU][:8], "frost", *[n for n, _ in templates.MENU][8:]] + assert list(bot.prompt_commands) == ["frost"] + assert "'Weather Now' isn't a name Telegram takes" in caplog.text and "'rain' has the name of one of the bot's own commands" in caplog.text + assert f"'{'x' * 33}' isn't a name" in caplog.text + + +async def test_the_menu_is_set_again_when_ecobot_mcp_says_its_prompts_changed(connected, world, alert_state, monkeypatch): + """PromptsListChanged: the prompts are read again and on_prompts called (ecobot.py sets the command menu again with them).""" + from mcp.server.subscriptions import PromptsListChanged + from lib import mcp_server + called = [] + connected.on_prompts = lambda: called.append([p.name for p in connected.prompts]) + assert "frost" not in [p.name for p in connected.prompts] + monkeypatch.setitem(mcp_server.PROMPTS, "frost", ("Frost tonight?", [], "Will there be frost tonight?")) + await world.bus.publish(PromptsListChanged()) + await until(lambda: called, what="the prompts read again") + assert called[-1][-1] == "frost" + + +async def drawn_by_the_service(world, call) -> tuple[dict, bytes]: + """(a call's answer as the bot asks it, every point as drawn; its chart as ecobot-mcp's renderer draws it, light): what the bot is to + be sent. Asked until two answers draw the same (what a call fetches inline, fetched first: the charts are then the same each time).""" + from lib import chart_images + for _ in range(3): + out = json.loads(await world.service[call[0]].call(call[1], {"chart_points": "drawn"})) + png = (await asyncio.to_thread(chart_images.render, out["charts"][0], TZ, False))[0] + again = json.loads(await world.service[call[0]].call(call[1], {"chart_points": "drawn"})) + if (await asyncio.to_thread(chart_images.render, again["charts"][0], TZ, False))[0] == png: + break + return out, png + + +async def test_the_bot_sends_the_services_picture_of_a_chart_byte_for_byte_as_its_renderer_draws_it(connected, world, alert_state, + monkeypatch): + """The bot draws nothing: a chart's picture is the PNG ecobot-mcp's renderer draws (lib/chart_images.render), its title, words, + newest reading and drawn_by from the chart's JSON (the result's _meta); an alert's chart is its drawn_by replayed.""" + from lib import chart_images + from lib.alerts import pictures + from lib.specs import from_json + from lib.timeutil import now_local + call = ("summary", {"readings": ["humidity"], "period": "7d", "chart": True}) + out, png = await drawn_by_the_service(world, call) + chart = out["charts"][0] + event_chart = await pictures.chart_data(None, pictures.CHARTS["gusts"], TZ, world.service) # (an alert's chart, as its event carries it) + event_png = (await asyncio.to_thread(chart_images.render, event_chart, TZ, False))[0] + bot = Bot(NS(tz=TZ), Agent(None, "m", model_tools.tools(connected)), alert_state, service=connected) + made = await bot._draw_call(*call) + spec = from_json(chart) + assert made.png == png and made.png.startswith(b"\x89PNG") and made.dark is False # the service's PNG, as its renderer draws it + assert (made.title, made.caption, made.newest, made.drawn_by) == (spec.caption(now_local(TZ).date()), out.get("caption"), spec.newest, + chart["drawn_by"]) + assert made.out["charts"] == out["charts"] # the chart's JSON, from the result's _meta + alert = await pictures.picture_of(event_chart, TZ, connected) # an alert's chart: its drawn_by replayed + assert (alert.png, alert.drawn_by, alert.dark) == (event_png, event_chart["drawn_by"], False) + assert alert.title == from_json(event_chart).caption(now_local(TZ).date()) + typed = await pictures.chart(pictures.CHARTS["gusts"], TZ, connected) # the 🔄 under an alert from before the log + assert typed.png == event_png + + +async def test_a_service_without_pillow_sends_the_charts_json_and_the_bot_sends_no_picture(connected, world, alert_state, monkeypatch): + """The bot draws nothing (docs/ecobot-mcp.md step 6a): a service that can't draw (no Pillow there) gives the answer with its charts' + JSON and no picture, and the bot sends none; an alert's chart goes without its picture.""" + from types import SimpleNamespace + from lib import chart_images, mcp_server + from lib.alerts import pictures + call = ("summary", {"readings": ["humidity"], "period": "7d", "chart": True}) + here = json.loads(await world.service["summary"].call(call[1], {"chart_points": "drawn"}))["charts"][0] + event_chart = await pictures.chart_data(None, pictures.CHARTS["gusts"], TZ, world.service) + monkeypatch.setattr(mcp_server, "chart_images", SimpleNamespace(**{**vars(chart_images), "renderer": lambda: None})) # (no Pillow there) + bot = Bot(NS(tz=TZ), Agent(None, "m", model_tools.tools(connected)), alert_state, service=connected) + assert await bot._draw_call(*call) is None + out, images = await connected.call_images(*call) + assert out["chart_image_note"] == chart_images.UNAVAILABLE_NOTE and images == [] and out["charts"][0]["drawn_by"] == here["drawn_by"] + assert await pictures.picture_of(event_chart, TZ, connected) is None + + +async def test_an_alert_reaches_the_subscribed_chats_through_the_listen(connected, world, tmp_path): + publishing = asyncio.create_task(world.watch_alerts()) + state = AlertState(tmp_path / "bot_state.json") + state.add_chat(1, "private") + telegram = Telegram() + delivery = asyncio.create_task(AlertDelivery(connected.alerts, Notifier(telegram, state), state, TZ).run()) + try: + await until(lambda: state.read is not None, what="the delivery to begin") + world.alert_log.append("rain", "🌧️ It's started raining: 0.4 mm so far", "Rain started") # (no expiry: the clock here is the evals') + await until(lambda: telegram.sent, what="the alert") + finally: + for task in (publishing, delivery): + task.cancel() + await asyncio.gather(publishing, delivery, return_exceptions=True) + assert telegram.sent == [(1, "🌧️ It's started raining: 0.4 mm so far")] and state.read == 1 + + +async def test_irrigation_mcps_check_reads_the_measured_rain_and_the_forecast_from_the_real_server(world): + """(Moved here from the bot's side in step 8b, beside the real server: the check is irrigation-mcp's, asking through its own client.)""" + from lib.irrigation.ecobot import EcobotWeather + client = EcobotWeather(world.server, tz=None) + task = asyncio.create_task(client.run()) + try: + await asyncio.wait_for(client.listening.wait(), 10) + rain = await client.rain.rain_mm(24) + summary = json.loads(await world.service["summary"].call({"readings": ["rain"], "period": "last 24 hours"})) + assert rain == summary["rain_total_mm"] + await world.ctx.forecast.warm() # (the service fetches its forecast) + forecast = client.forecast + await forecast.refresh() # (as the check does; the listen's ResourceUpdated does it too) + assert forecast.days + assert [d["date"] for d in forecast.days] == [d["date"] for d in world.ctx.forecast.days] + assert forecast.fetched_at == pytest.approx(world.ctx.forecast.fetched_at, abs=1) + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + await client.close() + + +# ---------- under uvicorn ---------- +@pytest.fixture +def bare(tmp_path): + """A server with no sources (the alerts and their listen are what matter) and its alert log.""" + alerts = AlertLog(tmp_path / "alerts.sqlite", TZ) + yield EcobotServer(Context(tz=TZ), alerts) + alerts.close() + + +async def test_a_dropped_connection_is_rebuilt_and_the_alerts_after_the_last_id_are_read_once(bare, tmp_path): + port = free_port() + remote = RemoteWeather(f"http://127.0.0.1:{port}/mcp", TOKEN, TZ) + state = AlertState(tmp_path / "bot_state.json") + state.add_chat(1, "private") + telegram = Telegram() + publishing = asyncio.create_task(bare.watch_alerts()) + supervisor = asyncio.create_task(remote.run()) + delivery = asyncio.create_task(AlertDelivery(remote.alerts, Notifier(telegram, state), state, TZ).run()) + texts = lambda: [text for _, text in telegram.sent] + alerts = bare.alert_log + try: + async with Serving(http_app(bare, tokens=(TOKEN,)), port) as first: + await until(lambda: state.read is not None and bare.listen._streams, what="the listen") + alerts.append("rain", "first", "Rain started", expires=time.time() + 3600) + await until(lambda: texts() == ["first"], what="alert 1") + await first.stop() # the service goes away: the listen is lost + await until(lambda: not remote.upstream.connected.is_set(), what="the bot to notice") + assert not await remote.ready(0.1) + alerts.append("gusts", "missed", "Gusts", expires=time.time() + 3600) # sent while it was down + alerts.append("uv", "stale", "UV", expires=time.time() - 1) # ... and expired already: not news + async with Serving(http_app(bare, tokens=(TOKEN,)), port): + await until(lambda: texts() == ["first", "missed"], what="the alert missed, read after the last id") + await until(lambda: bare.listen._streams, what="the listen again") + alerts.append("temps", "after", "Temperatures", expires=time.time() + 3600) + await until(lambda: texts() == ["first", "missed", "after"], what="alert 4 on the new listen") + await asyncio.sleep(0.3) + finally: + for task in (delivery, supervisor, publishing): + task.cancel() + await asyncio.gather(delivery, supervisor, publishing, return_exceptions=True) + assert texts() == ["first", "missed", "after"] and state.read == 4 # each once, the expired one skipped + + +async def test_the_service_back_on_a_fresh_alert_log_while_the_bot_runs_has_its_new_alerts_delivered(tmp_path, caplog): + """The service stops and comes back on a new alerts.sqlite (deleted, moved, redeployed: its ids start again at 1) while the bot runs: + delivery goes on in the new log with what came after the old one was last read (one logged while it was down included), not after + the old last id (3, which the new ids would take weeks to pass). An event of the new log from before then is not news.""" + port = free_port() + path = tmp_path / "service" / "alerts.sqlite" + path.parent.mkdir() + old = AlertLog(path, TZ) + remote = RemoteWeather(f"http://127.0.0.1:{port}/mcp", TOKEN, TZ) + state = AlertState(tmp_path / "bot_state.json") + state.add_chat(1, "private") + telegram = Telegram() + supervisor = asyncio.create_task(remote.run()) + delivery = asyncio.create_task(AlertDelivery(remote.alerts, Notifier(telegram, state), state, TZ).run()) + texts = lambda: [text for _, text in telegram.sent] + tasks = [delivery, supervisor] + try: + first = EcobotServer(Context(tz=TZ), old) + tasks.append(asyncio.create_task(first.watch_alerts())) + async with Serving(http_app(first, tokens=(TOKEN,)), port): + await until(lambda: state.read is not None and first.listen._streams, what="the listen") + for text in ("one", "two", "three"): + old.append("rain", text, "Rain", expires=time.time() + 3600) + await until(lambda: texts() == ["one", "two", "three"] and state.read == 3, what="the old log's alerts") + old_identity = old.identity + old.close() + for leftover in path.parent.iterdir(): # (alerts.sqlite and its -wal, -shm) + leftover.unlink() + new = AlertLog(path, TZ) + assert new.identity != old_identity + new.append("uv", "old news", "UV", expires=time.time() + 3600, time=time.time() - 3600) # (from before the bot last read) + new.append("gusts", "while down", "Gusts", expires=time.time() + 3600) + second = EcobotServer(Context(tz=TZ), new) + tasks.append(asyncio.create_task(second.watch_alerts())) + async with Serving(http_app(second, tokens=(TOKEN,)), port): + await until(lambda: texts()[3:] == ["while down"], what="the new log's alert logged while it was down") + await until(lambda: second.listen._streams, what="the listen again") + new.append("temps", "after", "Temperatures", expires=time.time() + 3600) + await until(lambda: texts()[3:] == ["while down", "after"], what="the new log's next alert") + await asyncio.sleep(0.3) + finally: + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + await remote.close() + assert texts() == ["one", "two", "three", "while down", "after"] + assert (state.read, state.read_log) == (3, new.identity) and AlertState(state.path).read_log == new.identity + assert "is another than the one the last alert delivered (3) is from" in caplog.text + new.close() + + +async def test_with_the_service_down_the_bot_says_so_and_carries_on(alert_state, caplog): + remote = RemoteWeather(f"http://127.0.0.1:{free_port()}/mcp", TOKEN, TZ) # (nothing listens there) + supervisor = asyncio.create_task(remote.run()) + try: + model = Model([("current", {})]) + bot = Bot(NS(tz=TZ), Agent(model, "m", model_tools.tools(remote)), alert_state, service=remote) + for text in ("how warm is it?", "weather now", "Humidity chart 7d", "Humidity chart 1d"): + update, context, replies = a_chat() + await (bot.press if text == "Humidity chart 1d" else bot.respond)(update, context, text) # (the last: the Humidity button) + assert replies == [SERVICE_DOWN], text + assert model.seen == [] # (no model call for an answer it couldn't get) + assert model_tools.tools(remote).schemas == [] # (no tools listed while it has not been reached) + with pytest.raises(ServiceUnreachable): + await remote.call_text("current", {}, {"priority": "background"}) # (a call nobody waits for is refused at once) + assert "isn't reachable" in caplog.text + finally: + supervisor.cancel() + await asyncio.gather(supervisor, return_exceptions=True) + + +async def test_main_as_a_client_runs_no_sources_and_answers_from_the_service(bare, tmp_path, monkeypatch, caplog): + """ecobot.main(), ecobot-mcp's client at BOT_MCP_URL: no source is started (the bot has none: no keys are set), the service's + station names the time zone, the command menu is set (with ecobot-mcp's prompts), and an alert the service logs reaches a chat.""" + import os + import signal + import ecobot + from tests.fakes import config + from tests.test_startup import FakeApp, FakeBuilder + caplog.set_level("INFO") + port = free_port() + cfg = config(tmp_path, mcp_url=f"http://127.0.0.1:{port}/mcp", auth_tokens=(TOKEN,), ecowitt_api_key="", + ecowitt_app_key="", airgradient_token="", airgradient_location="", state_path=tmp_path / "bot" / "bot_state.json") + (tmp_path / "bot").mkdir() + AlertState(cfg.state_path).add_chat(5, "private") + app = FakeApp() + monkeypatch.setattr(ecobot._format, "width", ecobot._format.width) # (main sets BOT_LOG_WIDTH's: put back after; the levels: conftest) + monkeypatch.setattr(ecobot.Config, "from_env", classmethod(lambda cls: cfg)) + monkeypatch.setattr(ecobot.Application, "builder", staticmethod(lambda: FakeBuilder(app))) + publishing = asyncio.create_task(bare.watch_alerts()) + + async def alert_then_stop(): + try: + await alert() + finally: # (main() runs until it is stopped, whatever happened) + os.kill(os.getpid(), signal.SIGTERM) + + async def alert(): + await until(lambda: bare.listen._streams and cfg.state_path.exists() and "alerts_read" in cfg.state_path.read_text(), + what="the bot to listen and its delivery to begin") + bare.alert_log.append("rain", "🌧️ Raining", "Rain started", expires=time.time() + 3600) + await until(lambda: app.sent, what="the alert sent") + try: + async with Serving(http_app(bare, tokens=(TOKEN,)), port): + stopper = asyncio.create_task(alert_then_stop()) + await ecobot.main() + await stopper + finally: + publishing.cancel() + await asyncio.gather(publishing, return_exceptions=True) + assert "Ecowitt: " not in caplog.text and "Telegram: @testbot" in caplog.text + assert f"ecobot-mcp: {cfg.mcp_url}" in caplog.text + assert [(chat, text) for chat, text, _ in app.sent] == [(5, "🌧️ Raining")] + assert app.menus and "chart" in app.menus[-1] and "report" in app.menus[-1] + + +async def test_a_start_while_the_service_cant_be_reached_follows_the_station_s_zone_once_read_and_keeps_it(tmp_path, monkeypatch, caplog): + """ecobot.main() with BOT_MCP_URL and the service not up within STARTUP_WAIT starts in TZ's zone (UTC here, as a container's); once + the service is reached, its station's zone (Melbourne) is the bot's, the charts' and the alert delivery's, + and it is kept in bot_state.json: the next start with the service down runs in it, not in UTC.""" + import os + import signal + from zoneinfo import ZoneInfo + import ecobot + from lib import theme + from tests.fakes import config + from tests.test_startup import FakeApp, FakeBuilder + caplog.set_level("INFO") + utc = ZoneInfo("Etc/UTC") + port = free_port() + cfg = config(tmp_path, tz=utc, mcp_url=f"http://127.0.0.1:{port}/mcp", auth_tokens=(TOKEN,), ecowitt_api_key="", + ecowitt_app_key="", airgradient_token="", airgradient_location="", state_path=tmp_path / "bot" / "bot_state.json") + (tmp_path / "bot").mkdir() + monkeypatch.setattr(ecobot, "STARTUP_WAIT", 0.3) + monkeypatch.setattr(ecobot._format, "width", ecobot._format.width) + monkeypatch.setattr(ecobot.Config, "from_env", classmethod(lambda cls: cfg)) + monkeypatch.setattr(theme, "ZONE", theme.ZONE) # (put back after) + made = {} + + class Kept(ecobot.Bot): + def __init__(self, *a, **k): + super().__init__(*a, **k) + made["bot"] = self + + class Delivery(ecobot.AlertDelivery): + def __init__(self, *a, **k): + super().__init__(*a, **k) + made["delivery"] = self + monkeypatch.setattr(ecobot, "Bot", Kept) + monkeypatch.setattr(ecobot, "AlertDelivery", Delivery) + + async def until_then_stop(check, what): + try: + await until(check, what=what) + finally: + os.kill(os.getpid(), signal.SIGTERM) + + alerts = AlertLog(tmp_path / "alerts.sqlite", TZ) + server = EcobotServer(Context(tz=TZ), alerts) # (its station: Australia/Melbourne) + try: + monkeypatch.setattr(ecobot.Application, "builder", staticmethod(lambda: FakeBuilder(FakeApp()))) + bot_up = lambda: "delivery" in made and made["bot"].cfg.tz is not None + + async def serve_late(): + await until(bot_up, what="the bot started without the service") + assert str(made["bot"].cfg.tz) == "Etc/UTC" and str(made["delivery"].tz) == "Etc/UTC" # (TZ's, while unread) + async with Serving(http_app(server, tokens=(TOKEN,)), port): + await until_then_stop(lambda: str(made["bot"].cfg.tz) == "Australia/Melbourne", "the station's zone") + late = asyncio.create_task(serve_late()) + await ecobot.main() + await late + bot, delivery = made["bot"], made["delivery"] + assert str(bot.cfg.tz) == str(delivery.tz) == str(bot.alert_charts.tz) == str(theme.ZONE) == "Australia/Melbourne" + assert json.loads(cfg.state_path.read_text())["station_zone"] == "Australia/Melbourne" + assert "isn't reachable yet" in caplog.text and "TZ's, Etc/UTC" in caplog.text + + made.clear() # the next start, the service down: the zone last read, not UTC + caplog.clear() + monkeypatch.setattr(ecobot.Application, "builder", staticmethod(lambda: FakeBuilder(FakeApp()))) + stopper = asyncio.create_task(until_then_stop(bot_up, "the bot to start again")) + await ecobot.main() + await stopper + assert str(made["bot"].cfg.tz) == str(made["delivery"].tz) == str(theme.ZONE) == "Australia/Melbourne" + assert "the station's last read, Australia/Melbourne" in caplog.text + finally: + alerts.close() + + +def test_the_bot_needs_ecobot_mcps_address_and_no_source_settings(monkeypatch, tmp_path): + from lib.config import Config + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + monkeypatch.setenv("BOT_TELEGRAM_TOKEN", "1:x") + for name in ("MCP_ECOWITT_API_KEY", "MCP_ECOWITT_APP_KEY", "MCP_HOMEASSISTANT_URL", "MCP_HOMEASSISTANT_TOKEN", "MCP_AIRGRADIENT_API_TOKEN", + "MCP_AIRGRADIENT_LOCATION_ID", "MCP_AIRGRADIENT_LOCAL_URL", "BOT_MCP_URL"): + monkeypatch.delenv(name, raising=False) + with pytest.raises(SystemExit, match="BOT_MCP_URL is not set"): # (the bot is only ever ecobot-mcp's client: step 6b) + Config.from_env() + monkeypatch.setenv("BOT_MCP_URL", "http://127.0.0.1:8765/mcp/") + monkeypatch.setenv("AUTH_TOKENS", "t0ken, other") + cfg = Config.from_env() + assert (cfg.mcp_url, cfg.auth_tokens) == ("http://127.0.0.1:8765/mcp", ("t0ken", "other")) and not cfg.ecowitt diff --git a/tests/test_chart_answers.py b/tests/test_chart_answers.py new file mode 100644 index 00000000..7626d242 --- /dev/null +++ b/tests/test_chart_answers.py @@ -0,0 +1,86 @@ +"""A question that is only a chart: the model sets chart_answers_it, the service's result comes complete (its chart and its `reply`), +and the turn ends with that reply: the model is asked nothing more (docs/ecobot-mcp.md 3.7). A real Agent over a scripted model and +stand-in service tools (offered as the bot offers them, lib/model_tools.py), through the bot's own model call.""" + +import json +import logging +from datetime import datetime +from types import SimpleNamespace as NS + +from lib import intent, llm, model_tools +from lib.bot import Bot +from lib.tools import Turn +from tests.fakes import TZ, chart_data +from tests.test_agent import FakeLLM + +NOW = datetime(2026, 9, 29, 14, 5) # a Tuesday +ONLY_A_CHART = "plot pressure since Sunday" +REPLY = "Sun 27 Sep – Tue 29 Sep 2026\nPressure: low 1004.2 hPa, Mon 28 Sep at 4am · high 1021.7 hPa, Sun 27 Sep at 10pm" +COMPLETE = {"period": {"text": "Sun 27 – Tue 29 Sep 2026"}, "caption": REPLY, "charts": [chart_data("Pressure")], "reply": REPLY, + "complete": True} +ASKED = {"readings": ["pressure"], "period": "since Sunday", "chart": True, "chart_answers_it": True} + + +class StandIn: + """A service tool that answers `result` (a dict, or an exception it raises) and keeps the arguments it was sent.""" + + def __init__(self, name: str = "summary", result=COMPLETE): + self.name, self.description, self.parameters, self.result, self.seen = name, "d", {"type": "object", "properties": {}}, result, [] + + async def call(self, args, meta): + self.seen.append(args) + if isinstance(self.result, Exception): + raise self.result + return json.dumps(self.result, ensure_ascii=False) + + +async def ask(serve, alert_state, script, tools, text=ONLY_A_CHART): + """`text` through the bot's model call with a scripted model, `tools` served by ecobot-mcp in memory: (reply, the model's requests, + the turn, the conversation).""" + client = FakeLLM(script) + weather = await serve(tools=tools) + bot = Bot(NS(tz=TZ), llm.Agent(client, "m", model_tools.tools(weather)), alert_state, service=weather) + turn = Turn() + working = [{"role": "user", "content": text}] + reply = await bot._ask_model(working, "sys", intent.effort(text), turn, None) + return reply, client.requests, turn, working + + +async def test_a_complete_result_is_the_reply_and_the_model_is_asked_once(serve, alert_state, caplog): + tool = StandIn() + with caplog.at_level(logging.INFO, logger="lib.llm"): + reply, requests, turn, working = await ask(serve, alert_state, [[("summary", ASKED)], "the model's own caption"], [tool]) + assert reply == REPLY and len(requests) == 1 and len(tool.seen) == 1 + assert turn.results[0][2]["charts"] == COMPLETE["charts"] # the whole result kept, for drawing + assert working[-1] == {"role": "assistant", "content": REPLY} # the conversation keeps it as the answer + assert any("ended on a complete result (summary): no LLM 2" in r.getMessage() for r in caplog.records) + + +async def test_a_result_that_isnt_complete_leaves_the_answer_to_the_model(serve, alert_state): + for result in ({k: v for k, v in COMPLETE.items() if k not in ("reply", "complete")}, # no chart_answers_it, or a note to word + {**COMPLETE, "charts": []}, # complete, but no chart + {"error": "That period isn't one of the forms."}, # refused + RuntimeError("Ecowitt is down")): # failed + reply, requests, _, _ = await ask(serve, alert_state, [[("summary", ASKED)], "The model's answer."], [StandIn(result=result)]) + assert reply == "The model's answer." and len(requests) == 2, result + + +async def test_a_step_with_any_result_that_isnt_complete_goes_back_to_the_model(serve, alert_state): + complete, plain = StandIn(), StandIn("current", {"lines": {"station": ["• Outdoor: 12 °C"]}}) + reply, requests, _, _ = await ask(serve, alert_state, [[("summary", ASKED), ("current", {})], "The model's answer."], [complete, plain]) + assert reply == "The model's answer." and len(requests) == 2 + + +async def test_several_complete_results_are_the_reply_in_the_order_called(serve, alert_state): + other = {**COMPLETE, "reply": "PM2.5: peak 34.2 µg/m³"} + days = StandIn("days", other) + reply, requests, _, _ = await ask(serve, alert_state, [[("summary", ASKED), ("days", {"group_by": "month", "chart_answers_it": True})], "x"], + [StandIn(), days]) + assert reply == f"{REPLY}\n\nPM2.5: peak 34.2 µg/m³" and len(requests) == 1 + + +async def test_the_model_is_sent_the_result_less_the_charts_data(serve, alert_state): + _, requests, _, _ = await ask(serve, alert_state, [[("summary", {**ASKED, "chart_answers_it": False})], "Low on Monday."], + [StandIn(result={k: v for k, v in COMPLETE.items() if k not in ("reply", "complete")})]) + told = json.loads(requests[1]["messages"][-1]["content"]) + assert told["charts"] == [{"title": "Pressure", "period": COMPLETE["charts"][0]["period"]}] and told["caption"] == REPLY diff --git a/tests/test_chart_json.py b/tests/test_chart_json.py new file mode 100644 index 00000000..45af760c --- /dev/null +++ b/tests/test_chart_json.py @@ -0,0 +1,255 @@ +"""Charts as data (specs.to_json and from_json, schemas/chart.json): a chart written as JSON comes back the same and is drawn the +same, the schema holds every chart the bot draws, and a line for a model to read is bucketed to its budget with its true lowest and +highest kept. (Every chart any test builds also goes through JSON and back: conftest.charts_come_back_from_json.) + +jsonschema isn't one of the requirements, so the schema is checked here by a small checker of the keywords it uses (`errors`); +a test makes sure it uses no others.""" + +import copy +import json +import math +import re +from datetime import date, datetime +from pathlib import Path + +import pytest + +from lib import charts +from lib.specs import CHART_SOURCE, Bars, Chart, Compass, Line, Panel, Shares, from_json, stack, to_json +from tests import chart_samples, imagecmp +from tests.fakes import TZ + +SCHEMA = json.loads((Path(__file__).resolve().parent.parent / "schemas" / "chart.json").read_text()) +SAMPLES = [name for name, make in chart_samples.SAMPLES.items() if isinstance(make(), Chart)] # (not the gauges) +T0 = int(datetime(2026, 9, 1, tzinfo=TZ).timestamp()) + + +def sent(chart: Chart, **kw) -> dict: + """The chart's JSON as a client gets it: written out as text and read back.""" + return json.loads(json.dumps(to_json(chart, TZ, **kw), allow_nan=False)) + + +# ---------- a small JSON Schema checker: the keywords schemas/chart.json uses, as draft 2020-12 reads them ---------- +TYPES = {"object": dict, "array": list, "string": str, "boolean": bool, "null": type(None)} +CHECKED = {"$ref", "type", "const", "enum", "properties", "required", "additionalProperties", "items", "prefixItems", "minItems", + "maxItems", "oneOf", "pattern", "minimum"} +NOTES = {"$schema", "$id", "$defs", "title", "description", "format"} # annotations: nothing to check + + +def is_type(value, name: str) -> bool: + if name in ("number", "integer"): + return isinstance(value, (int, float)) and not isinstance(value, bool) and (name == "number" or float(value).is_integer()) + return isinstance(value, TYPES[name]) + + +def resolve(ref: str) -> dict: + node = SCHEMA + for part in ref.removeprefix("#/").split("/"): + node = node[part] + return node + + +def errors(value, schema: dict | bool = SCHEMA, at: str = "$") -> list[str]: + """What is wrong with `value` against `schema`: [] when it conforms.""" + if schema is False: + return [f"{at}: not allowed"] + if schema is True: + return [] + out = errors(value, resolve(schema["$ref"]), at) if "$ref" in schema else [] + if "type" in schema and not any(is_type(value, t) for t in ([schema["type"]] if isinstance(schema["type"], str) else schema["type"])): + return out + [f"{at}: not of type {schema['type']}"] + if "const" in schema and value != schema["const"]: + out.append(f"{at}: not {schema['const']!r}") + if "enum" in schema and value not in schema["enum"]: + out.append(f"{at}: not one of {schema['enum']}") + if "pattern" in schema and isinstance(value, str) and not re.search(schema["pattern"], value): + out.append(f"{at}: {value!r} doesn't match {schema['pattern']}") + if "minimum" in schema and is_type(value, "number") and value < schema["minimum"]: + out.append(f"{at}: under {schema['minimum']}") + if "oneOf" in schema and sum(not errors(value, s, at) for s in schema["oneOf"]) != 1: + out.append(f"{at}: not exactly one of its kinds") + if isinstance(value, dict): + props = schema.get("properties", {}) + out += [f"{at}: no {key!r}" for key in schema.get("required", []) if key not in value] + for key, item in value.items(): + if key in props: + out += errors(item, props[key], f"{at}.{key}") + elif "additionalProperties" in schema: + out += errors(item, schema["additionalProperties"], f"{at}.{key}") + if isinstance(value, list): + if len(value) < schema.get("minItems", 0) or len(value) > schema.get("maxItems", math.inf): + out.append(f"{at}: {len(value)} items") + first = schema.get("prefixItems", []) + for i, item in enumerate(value): + out += errors(item, first[i] if i < len(first) else schema.get("items", True), f"{at}[{i}]") + return out + + +def keywords(schema, under_names: bool = False) -> set[str]: + """Every keyword the schema uses (the names under properties and $defs are names, not keywords).""" + if isinstance(schema, list): + return set().union(*(keywords(s) for s in schema)) + if not isinstance(schema, dict): + return set() + if under_names: + return set().union(*(keywords(s) for s in schema.values())) + return set(schema) | set().union(*(keywords(v, k in ("properties", "$defs")) for k, v in schema.items())) + + +def test_the_schema_uses_only_keywords_the_checker_reads_and_is_versioned(): + assert keywords(SCHEMA) <= CHECKED | NOTES, keywords(SCHEMA) - CHECKED - NOTES + assert SCHEMA["$schema"] == "https://json-schema.org/draft/2020-12/schema" and SCHEMA["properties"]["version"]["const"] == 1 + + +# ---------- every sample chart, through JSON and back ---------- +@pytest.mark.parametrize("name", SAMPLES) +def test_every_sample_chart_comes_back_the_same_and_is_drawn_the_same(name): + chart, dark = chart_samples.SAMPLES[name](), name.endswith("_dark") + data = sent(chart) + back = from_json(data) + assert back == chart # field by field: the tuples (period, zones, records, speed steps) come back tuples + assert to_json(back, TZ) == data + assert charts.render_data(data, TZ, dark=dark) == charts.render(chart, TZ, dark=dark) # the same PNG, byte for byte + assert not errors(data), errors(data) + + +@pytest.mark.golden +@pytest.mark.parametrize("name", SAMPLES) +def test_every_sample_chart_drawn_from_its_json_matches_its_reference_image(name): + assert imagecmp.check(name, from_json(sent(chart_samples.SAMPLES[name]()))) is None + + +def every_field() -> list[Chart]: + """Charts with what the samples leave out: a rating, bars with their numbers, a line on a flipped right-hand axis, a smoothed + indoor line marked on itself, zones, a rose with no speeds, and a line whose only record is a low its reading never shows.""" + xs = [T0 + i * 3600 for i in range(8)] + ys = [3.0, 5.5, 4.0, 9.25, 7.0, 6.0, 2.0, 4.5] + rating = Panel("PM2.5 rating", "%", shares=Shares("PM2.5", xs, 3600, [80.0] * 8, [15.0] * 8, [5.0] * 8, "hour")) + months = Panel("Days", "", bars=Bars("Days", "days", xs[:3], [1, 0, 4], 28 * 86400, "month", values=True)) + twin = Panel("UV and Solar", "", [Line("UV", xs, ys, reading="uv"), + Line("Solar", xs, [y * 100 for y in ys], [y * 90 for y in ys], [y * 110 for y in ys], + smoothed=True, reading="solar", indoor=True, right=True, on_line=True)], + flip_right=True, peaks="none") + rated = Panel("PM2.5", "µg/m³", [Line("PM2.5", xs, ys, reading="pm2_5")], zones=(12.0, 35.5), reading="pm2_5", peaks="aside") + calm = Panel("Wind", "km/h", [Line("Wind", xs, ys, records={"low": (xs[6], 2.0)})], reading="wind") + return [stack([rating, months], date(2026, 9, 1), date(2026, 9, 1)), Chart("Two scales", "s", [twin]), + Chart("Rated", "s", [rated], source="Somewhere"), Chart("Wind", "s", [calm], Compass([[1, 2, 3]] * 16, False, (5, 15)))] + + +@pytest.mark.parametrize("i", range(len(every_field()))) +def test_every_field_the_renderer_reads_comes_back(i): + chart = every_field()[i] + data = sent(chart) + assert from_json(data) == chart and charts.render_data(data, TZ) == charts.render(chart, TZ) + assert not errors(data), errors(data) + + +def test_a_line_drawn_without_records_comes_back_without_them(): + chart = every_field()[3] + assert chart.panels[0].lines[0].records == {} # wind's low isn't labelled, so its only record went + assert from_json(sent(chart)).panels[0].lines[0].records == {} # not its own high and low, as a chart would give it + + +def test_the_source_is_the_charts_own_not_the_tool_call_it_is_read_in(): + data = sent(every_field()[1]) + token = CHART_SOURCE.set("Ecowitt weather station") + try: + assert data["source"] == "" and from_json(data).source == "" + finally: + CHART_SOURCE.reset(token) + + +def test_times_are_local_with_their_offset_and_give_the_same_epochs_back_across_both_clock_changes(): + forward = int(datetime(2026, 10, 4, 1, tzinfo=TZ).timestamp()) # Melbourne: 2am is 3am + back = int(datetime(2026, 4, 5, 1, 30, tzinfo=TZ).timestamp()) # 3am is 2am again: 2 to 3am happens twice + for start, want in ((forward, ["01:00:00+10:00", "01:30:00+10:00", "03:00:00+11:00", "03:30:00+11:00"]), + (back, ["01:30:00+11:00", "02:00:00+11:00", "02:30:00+11:00", "02:00:00+10:00", "02:30:00+10:00"])): + xs = [start + i * 1800 for i in range(len(want))] + chart = Chart("T", "s", [Panel("Temperature", "°C", [Line("Outdoor", xs, [float(i) for i in range(len(xs))])])]) + data = sent(chart) + assert [p[0][11:] for p in data["panels"][0]["series"][0]["points"]] == want + assert from_json(data).panels[0].lines[0].x == xs + assert data["newest"] == data["panels"][0]["series"][0]["points"][-1][0] + + +def test_a_chart_says_its_period_source_and_the_kind_of_each_series(): + data = sent(chart_samples.humidity_rain()) + assert data["version"] == 1 and data["period"] == ["2026-09-28", "2026-10-04"] and data["source"] == "" + assert [(s["name"], s["kind"]) for s in data["panels"][0]["series"]] == [("Outdoor", "line"), ("Indoor", "line"), ("Rain", "bars")] + wind = sent(chart_samples.wind())["panels"][0] + assert wind["series"][0]["kind"] == "band" and len(wind["series"][0]["points"][0]) == 4 and len(wind["compass"]["rose"]) == 16 + assert sent(chart_samples.quarter())["period"] is None + + +# ---------- what isn't a chart ---------- +def broken(change) -> dict: + data = copy.deepcopy(sent(chart_samples.humidity_rain())) + change(data) + return data + + +def series(data: dict, i: int = 0) -> dict: + return data["panels"][0]["series"][i] + + +BROKEN = { # name: (the change, whether the schema sees it: the rest only building the chart can tell) + "another version": (lambda d: d.update(version=2), True), + "no title": (lambda d: d.pop("title"), True), + "a time without its offset": (lambda d: series(d)["points"][0].__setitem__(0, "2026-09-28T00:00:00"), True), + "a kind of series there isn't": (lambda d: series(d).update(kind="pie"), True), + "a band's point without its range": (lambda d: series(d).update(kind="band"), True), + "a value that isn't a number": (lambda d: series(d)["points"][3].__setitem__(1, "62"), True), + "a line of one point": (lambda d: series(d).update(points=series(d)["points"][:1]), True), + "a period of three days": (lambda d: d["period"].append("2026-10-05"), True), + "a period of none": (lambda d: d.update(period=[]), True), + "two series of bars in a panel": (lambda d: d["panels"][0]["series"].append(series(d, 2)), False), + "a rose beside a stack": (lambda d: d["panels"].append({**d["panels"][0], "compass": sent(chart_samples.wind())["panels"][0]["compass"]}), + False), +} + + +@pytest.mark.parametrize("name", BROKEN) +def test_what_is_not_a_chart_is_refused_when_it_is_read_and_by_the_schema_where_it_can_tell(name): + change, schema_sees = BROKEN[name] + data = broken(change) + with pytest.raises(ValueError): + from_json(data) + with pytest.raises(ValueError): + charts.render_data(data, TZ) + assert bool(errors(data)) == schema_sees, errors(data) + + +def test_the_checker_finds_what_it_should(): + assert not errors(sent(chart_samples.wind())) + assert errors({"version": 1}) and errors(broken(lambda d: d["panels"][0].update(extra=1))) + + +# ---------- a line for a model to read ---------- +def test_a_long_line_is_bucketed_to_the_budget_keeping_its_true_lowest_and_highest(): + xs = [T0 + i * 300 for i in range(2016)] # a week of 5-minute readings + ys = [12 + 6 * math.sin(i / 40) for i in range(len(xs))] + ys[300], ys[1500] = 41.5, -3.25 # one reading far above, one far below + xs, ys = xs[:600] + xs[888:], ys[:600] + ys[888:] # and a day missing + rain = Bars("Rain", "mm", [T0 + i * 3600 for i in range(168)], [0.2] * 168, 3600, "hour") + chart = Chart("T", "s", [Panel("Temperature", "°C", [Line("Outdoor", xs, ys, reading="temperature")], bars=rain)]) + whole = sent(chart) + data = sent(chart, max_points=150) + line, bars = series(data), series(data, 1) + assert line["kind"] == "band" and 100 < len(line["points"]) <= 150 + times, means, lows, highs = zip(*line["points"]) + assert min(lows) == -3.25 and max(highs) == 41.5 and all(lo <= y <= hi for _, y, lo, hi in line["points"]) + assert list(times) == sorted(set(times)) and line["records"] == series(whole)["records"] # the true records, with when + assert bars == series(whole, 1) # bars aren't lines: as they are + assert not errors(data) and len(from_json(data).panels[0].lines[0].x) == len(line["points"]) + assert to_json(chart, TZ) == to_json(chart, TZ, max_points=None) and from_json(whole) == chart + + +def test_a_band_keeps_its_own_extremes_and_a_short_line_is_left_as_it_is(): + wind = chart_samples.wind() + line = series(sent(wind, max_points=40)) + assert len(line["points"]) <= 40 and max(p[3] for p in line["points"]) == max(wind.panels[0].lines[0].high) + assert min(p[2] for p in line["points"]) == min(wind.panels[0].lines[0].low) + quarter = chart_samples.quarter() # 90 days: within a budget of 150 + assert sent(quarter, max_points=150) == sent(quarter) + with pytest.raises(ValueError): + to_json(quarter, TZ, max_points=1) diff --git a/tests/test_chart_source.py b/tests/test_chart_source.py index 977591e1..8a57be22 100644 --- a/tests/test_chart_source.py +++ b/tests/test_chart_source.py @@ -18,30 +18,6 @@ async def handler(args, turn): return handler -def test_only_chart_tools_offer_a_source_argument(): - tools = Tools([Tool("plain", "", {"type": "object", "properties": {}}, drawer()), - Tool("charts", "", {"type": "object", "properties": {"chart": {"type": "boolean"}}}, drawer(), source="Station")]) - params = {s["function"]["name"]: s["function"]["parameters"]["properties"] for s in tools.schemas} - assert "source" not in params["plain"] and set(params["charts"]) == {"chart", "source"} - - -async def test_the_models_source_wins_else_the_tools_own(): - tools = Tools([Tool("charts", "", {"type": "object", "properties": {}}, drawer(), source="Ecowitt weather station")]) - turn = Turn() - await tools.call("charts", json.dumps({"source": " ecowitt.net\n"}), turn) - await tools.call("charts", "{}", turn) - assert [c.source for c in turn.charts] == ["ecowitt.net", "Ecowitt weather station"] - assert CHART_SOURCE.get() == "" # nothing left behind for the next chart - - -async def test_calls_made_together_keep_their_own_sources(): - tools = Tools([Tool("slow", "", {"type": "object", "properties": {}}, drawer(0.05), source="Ecowitt weather station"), - Tool("fast", "", {"type": "object", "properties": {}}, drawer(0.0), source="AirGradient sensor")]) - turn = Turn() - await tools.call_all([("slow", {}), ("fast", {})], turn) - assert [c.source for c in turn.charts] == ["AirGradient sensor", "Ecowitt weather station"] - - def test_a_long_source_is_cut_to_one_line(): text = source_text("https://example.com/" + "x" * 100) assert len(text) == SOURCE_CHARS and text.endswith("…") and source_text(None) == "" diff --git a/tests/test_compose.py b/tests/test_compose.py index 6e5178f0..48790381 100644 --- a/tests/test_compose.py +++ b/tests/test_compose.py @@ -37,14 +37,6 @@ async def plot(comp, **args): return out, turn.charts -async def test_the_composer_offers_the_chart_tool_and_the_two_air_tools(tmp_path, archived_cache): - comp, eco = await composer(tmp_path, archived_cache) - assert [t.name for t in comp.tools] == ["plot_chart", "air_link", "air_scan"] - schema = comp.tools[0].parameters["properties"]["panels"] - assert schema["maxItems"] == MAX_PANELS and schema["items"]["properties"]["series"]["enum"] == SERIES - await eco.close() - - async def test_a_reading_with_its_zones_over_rain_is_one_stacked_chart(tmp_path, archived_cache): comp, eco = await composer(tmp_path, archived_cache) out, specs = await plot(comp, panels=[{"series": "pm2_5"}, {"series": "rain"}]) @@ -210,19 +202,6 @@ async def test_the_air_sensors_own_temperature_goes_over_the_stations_on_one_axi await eco.close() -async def test_the_tools_offer_the_air_sensors_own_temperature_and_humidity_only_to_a_question_that_asks(tmp_path, archived_cache): - from lib.tools import Tools - comp, eco = await composer(tmp_path, archived_cache) - tools = Tools(comp.tools) - plain = tools.schemas_for(Turn()) - assert plain is tools.schemas and "air_humidity" not in json.dumps(plain) and "same_axis" not in json.dumps(plain) - asked = {s["function"]["name"]: s["function"] for s in tools.schemas_for(Turn(air_extra=True))} - series = asked["plot_chart"]["parameters"]["properties"]["panels"]["items"]["properties"]["series"]["enum"] - assert series == [*SERIES, "air_temperature", "air_humidity"] and "same_axis" in asked["plot_chart"]["parameters"]["properties"] - assert [s["function"]["name"] for s in tools.schemas_for(Turn(air_extra=True))] == [s["function"]["name"] for s in plain] # the same tools, in order - await eco.close() - - async def test_a_composed_air_series_takes_its_range_from_the_readings_the_bot_recorded(tmp_path, archived_cache): comp, eco = await composer(tmp_path, archived_cache) air = StubAir(days=2) diff --git a/tests/test_contract.py b/tests/test_contract.py index c23973c9..bef0dc62 100644 --- a/tests/test_contract.py +++ b/tests/test_contract.py @@ -9,30 +9,6 @@ -async def test_every_tool_result_keeps_its_shape(tmp_path, archived_cache): - eco, _ = await archived_station(tmp_path, archived_cache) - today = datetime.now(eco.tz).date() - day = lambda n: f"{today - timedelta(days=n)} 00:00:00" - span = {"start_date": day(9), "end_date": f"{today - timedelta(days=2)} 23:59:59"} - call = lambda i, args: eco.tools[i].handler(args) - now = json.loads(await call(0, {"groups": "outdoor,indoor,pressure,wind,rainfall"})) - assert set(now) == {"time", "outdoor", "emoji"} - history = json.loads(await call(1, {"groups": "outdoor", **span})) - assert set(history) - {"chart"} == {"period", "series"} # "chart": a hint that appears when one was drawn - assert set(history["series"]["outdoor.temperature"]) == { - "unit", "low", "low_time", "low_when", "low_date", "high", "high_time", "high_when", "high_date", "daily"} - wind = json.loads(await call(1, {"groups": "wind", **span})) - assert set(wind["series"]) == {"wind.wind_direction", "wind.wind_gust", "wind.wind_speed"} - assert set(wind["series"]["wind.wind_direction"]) == {"unit", "most_common", "average_direction", "steadiness", "readings", "calm", "daily"} - days = json.loads(await call(2, {"start_date": day(30), "end_date": f"{today - timedelta(days=2)} 23:59:59", "sort_by": "temp_max"})) - assert set(days) == {"period", "days_checked", "matching_days", "units", "days"} - assert set(days["days"][0]) == {"date", "temp_max", "temp_min", "rain", "source"} - link = json.loads(await call(3, {"start_date": str(today - timedelta(days=20)), "end_date": str(today - timedelta(days=2))})) - assert set(link) - {"chart"} == {"period", "driver", "resolution", "how_to_read", "slots", "rain_mm", "wet_slots", "verdict", "findings", - "by_change_before", "average_level", "correlation_change_vs_rain_next_3h", "rain_events", "days_with_data"} - await eco.close() - - async def test_the_cross_source_tools_keep_their_shape(tmp_path, archived_cache): comp, eco = await composer(tmp_path, archived_cache) turn = Turn() diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index d5bee7f4..5436e947 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -2,29 +2,25 @@ from datetime import date, datetime from types import SimpleNamespace as NS +import pytest from PIL import Image -from telegram import InlineKeyboardMarkup +from telegram import InlineKeyboardButton, InlineKeyboardMarkup -from lib import gauges, intent +import json +import time + +from lib import gauge_sheet, gauges from lib.bot import Bot from lib.ecowitt import dashboard as dash +from lib.service import current as cur +from lib.service.context import Context from lib.specs import Dashboard, Tile -from tests.fakes import TZ, archived_station +from tests.fakes import TZ, StandInService, archived_station, gauges_result TODAY = date(2026, 10, 27) NOW = datetime(2026, 10, 27, 12, tzinfo=TZ) -def test_a_dashboard_is_asked_for_in_a_word_or_two_and_is_not_the_report(): - for said in ("dashboard", "Dashboard", "show me the dashboard", "gauges", "weather dashboard", "dashboard now"): - read = intent.read(said, NOW) - assert read.dashboard and not read.report, said - for said in ("report", "status", "dashboard for last week", "how do I use the dashboard on my phone", "weather"): - assert not intent.read(said, NOW).dashboard, said - assert intent.read("report", NOW).report - assert not intent.read("dashboard", NOW, ("AirGradient",)).dashboard # the station's gauges need the station - - def test_the_rows_cover_the_day_the_month_so_far_and_the_year_so_far(): days = dash.periods_of(TODAY) assert days["Daily"] == [TODAY] and days["Monthly"][0] == date(2026, 10, 1) and days["Monthly"][-1] == TODAY @@ -41,7 +37,7 @@ def test_a_tile_has_the_live_reading_and_its_extremes_with_the_live_reading_coun values = {"temp_max": {first: 38.0, today: 25.0}, "temp_min": {first: -1.0, today: 9.0}, "humidity_max": {today: 80.0}, "humidity_min": {today: 40.0}, "rain": {first: 12.0, date(2026, 10, 3): 6.0, today: 0.4}, "rain_rate_max": {first: 30.0}} - tiles = {t.title: t for t in dash.sheet(live, values, today).tiles} + tiles = {t.title: t for t in gauge_sheet.sheet(gauges_result(live, values, today)).tiles} temperature = tiles["Temperature"] assert temperature.value == 31.0 and temperature.columns == ("Max", "Min") assert temperature.rows == {"Daily": (31.0, 9.0), "Monthly": (31.0, 9.0), "Yearly": (38.0, -1.0)} # 31 is now: higher than today's 25 @@ -53,24 +49,29 @@ def test_a_tile_has_the_live_reading_and_its_extremes_with_the_live_reading_coun def test_a_reading_the_station_never_had_is_left_out_and_one_it_lacks_just_now_is_dimmed(): live = {"outdoor": {"temperature": reading(12.0)}} - sheet = dash.sheet(live, {"solar_max": {TODAY: 900.0}}, TODAY) + sheet = gauge_sheet.sheet(gauges_result(live, {"solar_max": {TODAY: 900.0}}, TODAY)) titles = [t.title for t in sheet.tiles] assert titles == ["Temperature", "Solar radiation"] and sheet.tiles[1].value is None # no indoor sensor, no wind assert sheet.tiles[1].rows["Daily"] == (900.0,) - assert dash.sheet({}, {}, TODAY) is None + assert gauge_sheet.sheet(gauges_result({}, {}, TODAY)) is None def test_the_gauges_are_drawn_as_a_png_of_the_size_their_tiles_make(): tile = Tile("Humidity", "%", 70, "dial", 0, 100, ("#DFFBFF", "#2C7592"), ("Max", "Min"), {"Daily": (87, 48)}, (0, 50, 100), 0) dull = Tile("Rain", "mm", None, "beaker", 0, 100, ("#DFFBFF", "#2C7592"), ("Max", "Total"), {}, (100, 0)) image = Image.open(io.BytesIO(gauges.render(Dashboard([tile, tile, tile, dull])))) - assert image.size == (3 * gauges.CELL_W + 2 * gauges.MARGIN, 2 * gauges.CELL_H + 2 * gauges.MARGIN) + assert image.size == (3 * gauges.CELL_W + 2 * gauges.MARGIN, 2 * gauges.TILE_H + 2 * gauges.MARGIN) # (no tables under them) assert image.convert("RGB").getpixel((2, 2)) == (0x14, 0x19, 0x1D) -async def test_the_station_gives_its_gauges_from_the_live_reading_and_the_cache(tmp_path, archived_cache): - eco, _ = await archived_station(tmp_path, archived_cache) - sheet = await eco.dashboard() +async def current_of(eco, args: dict) -> dict: + """The service's current over this station, called with these arguments.""" + return json.loads(await cur.CurrentTool(Context(eco=eco)).tool().call(args, None)) + + +async def test_the_station_gives_its_gauges_from_the_live_reading_and_the_cache(tmp_path, daytime_archive): + eco, _ = await archived_station(tmp_path, daytime_archive) + sheet = gauge_sheet.sheet(await current_of(eco, gauge_sheet.call())) temperature = next(t for t in sheet.tiles if t.title == "Temperature") assert temperature.value == 12.3 # the fake station's live reading high, low = temperature.rows["Yearly"] @@ -79,136 +80,95 @@ async def test_the_station_gives_its_gauges_from_the_live_reading_and_the_cache( await eco.close() -class Tools: - async def call(self, *a, **k): - raise AssertionError("the dashboard is drawn in code") - - call_all = call - - -async def test_the_dashboard_command_sends_one_picture_with_no_period_buttons_and_asks_no_model(alert_state, monkeypatch): - sent, asked = [], [] - - async def sheet(): - asked.append(1) - return Dashboard([Tile("Humidity", "%", 70, "dial", 0, 100, ("#DFFBFF", "#2C7592"), ("Max",), {"Daily": (87,)}, (0, 100), 0)]) - - class Agent: - tools = Tools() - - async def run(self, *a, **k): - raise AssertionError("no model for the dashboard") - source = NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt", dashboard=sheet) - bot = Bot(NS(tz=TZ), Agent(), [source], alert_state) - - async def reply_photo(photo, caption=None, **kw): - sent.append((photo[:4], caption, kw.get("reply_markup"))) - return NS(message_id=7) - msg = NS(chat_id=1, message_id=50, message_thread_id=None, is_topic_message=False, reply_photo=reply_photo, text="Dashboard", - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - - context = CONTEXT - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - await bot.respond(update, context, "Dashboard") - assert asked == [1] and len(sent) == 1 - photo, caption, markup = sent[0] - assert photo == b"\x89PNG" and caption.startswith("Weather station dashboard, ") - assert not isinstance(markup, InlineKeyboardMarkup) # a chat whose keyboard is out of date gets that instead - assert bot.charted.get(1, 7) is None - bot.state.add_chat(1, "private") - bot.state.set_keyboard(1, bot.keyboard_version) - await bot.respond(update, context, "Dashboard") - from lib import report_menu - assert [b.callback_data for b in sent[-1][2].inline_keyboard[0]] == [report_menu.DASHBOARD] # its 🔄, no period buttons - - -async def test_the_dashboards_refresh_draws_it_again_in_the_same_message_and_a_station_that_fails_leaves_it(alert_state): - from lib import report_menu +async def test_the_old_dashboards_and_reports_refresh_are_out_of_date_and_change_nothing(serve, alert_state): + """The Telegram dashboard is no more (the gauges' live page is ecobot-mcp's /dashboard), nor the report written in code (step 6c): + the 🔄 under one sent before is out of date, and its message stays as it was.""" from lib.bot import STALE_BUTTON - bot, _ = report_bot(alert_state, three_tiles) + bot, _ = await report_bot(serve, alert_state, three_gauges) edits = [] class Query: - data, message, toast = report_menu.DASHBOARD, NS(photo=[NS(file_id="x")]), "unset" + def __init__(self, data): + self.data, self.toast, self.from_user = data, "unset", NS(id=7) + self.message = NS(photo=[NS(file_id="x")], reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔄", callback_data=data)]]), + chat=NS(id=1, type="private"), chat_id=1) async def answer(self, text=None, **k): self.toast = text - async def edit_message_media(self, media, reply_markup=None): - edits.append((media.media.input_file_content[:4], media.caption, reply_markup)) - query = Query() - await bot.on_report_button(NS(callback_query=query), CONTEXT) - (photo, caption, markup), = edits - assert photo == b"\x89PNG" and caption.startswith("Weather station dashboard, ") and query.toast is None - assert markup.inline_keyboard[0][0].callback_data == report_menu.DASHBOARD # the 🔄 stays - - async def failing(titles=None): - raise RuntimeError("station down") - bot.by_name["Ecowitt"].dashboard = failing - query = Query() - await bot.on_report_button(NS(callback_query=query), CONTEXT) - assert len(edits) == 1 and "Couldn't refresh" in query.toast # left as it was - query = Query() - query.message = NS(photo=None) - await bot.on_report_button(NS(callback_query=query), CONTEXT) - assert len(edits) == 1 and query.toast == STALE_BUTTON + async def edit_message_media(self, *a, **k): + edits.append(a) + + async def edit_message_caption(self, *a, **k): + edits.append(a) + for data in ("rp:dashboard", "rp:refresh"): + query = Query(data) + await bot.on_button(NS(callback_query=query, effective_chat=query.message.chat, effective_user=query.from_user, + effective_message=query.message), CONTEXT) + assert query.toast == STALE_BUTTON and edits == [], data def test_the_reports_gauges_are_temperature_humidity_and_rain_in_a_row(): live = {"outdoor": {"temperature": reading(12.0), "humidity": reading(70)}, "rainfall": {"daily": reading(0.2)}, "pressure": {"relative": reading(1020)}} - sheet = dash.sheet(live, {}, TODAY, dash.STATUS) + sheet = gauge_sheet.sheet(gauges_result(live, {}, TODAY), dash.STATUS) assert [t.title for t in sheet.tiles] == ["Temperature", "Humidity", "Rain"] and sheet.per_row == 3 image = Image.open(io.BytesIO(gauges.render(sheet))) - assert image.size == (3 * gauges.CELL_W + 2 * gauges.MARGIN, gauges.CELL_H + 2 * gauges.MARGIN) # one row + assert image.size == (3 * gauges.CELL_W + 2 * gauges.MARGIN, gauges.TILE_H + 2 * gauges.MARGIN) # one row -async def test_the_dashboard_reads_the_years_day_rows_in_one_go_and_only_what_its_gauges_show(monkeypatch): - calls = [] - - def day_values_on(r, mac, names, days): - calls.append((tuple(names), min(days), max(days))) - return {n: {d: 1.0 for d in days} for n in names}, {} - monkeypatch.setattr(dash, "day_values_on", day_values_on) - - class Storage: - async def read(self, fn, *args): - return fn(None, *args) - sheet = await dash.dashboard({"outdoor": {"temperature": reading(12.0)}}, Storage(), "mac", TODAY, dash.STATUS) - assert calls == [(("humidity_max", "humidity_min", "rain", "temp_max", "temp_min"), date(2026, 1, 1), TODAY)] # one read, the year - assert [t.title for t in sheet.tiles] == list(dash.STATUS) +async def test_the_reports_gauges_read_the_years_day_rows_in_one_go_and_only_what_its_three_show(tmp_path, archived_cache): + from tests.test_service_current import Station, live + eco, _ = await archived_station(tmp_path, archived_cache) + Station(eco, live(time.time())) + reads, read = [], eco.storage.read + + async def counted(fn, *args): + reads.append((fn, args)) + return await read(fn, *args) + eco.storage.read = counted + out = await current_of(eco, gauge_sheet.call(dash.STATUS)) + (mac, names, days), = [args for fn, args in reads if fn is cur.context_on] # one read, the year + today = Context(eco=eco).now().date() + assert names == ["humidity_max", "humidity_min", "rain", "temp_max", "temp_min"] and (days[0], days[-1]) == (date(today.year, 1, 1), today) + assert [t.title for t in gauge_sheet.sheet(out, dash.STATUS).tiles] == list(dash.STATUS) + await eco.close() -def report_bot(alert_state, sheet): - """A bot whose station gives the report's tool results and, through dashboard(), its gauges (`sheet()`: a Dashboard, or raises).""" - import json +class ReportAgent: + """The model, answering every question with the report it is asked for (Status: the `report` prompt's question).""" - from tests.fakes import StandInTools + def __init__(self): + self.asked = [] - class Tools(StandInTools): - reading = "12.3 ℃" + async def run(self, messages, system, effort, **k): + self.asked.append(messages[-1]["content"]) + messages.append({"role": "assistant", "content": "Weather station\n• Outdoor: 12.3 °C"}) # (as lib/llm.py's Agent does) + return messages[-1]["content"] - async def call(self, name, raw, turn=None): - return {"weather_now": json.dumps({"outdoor": {"temperature": self.reading}}), - "air_quality": json.dumps({"pm10": {"value": 3.0, "unit": "µg/m³", "rating": "🟢 good"}})}[name] - class Agent: - tools = Tools() +async def report_bot(serve, alert_state, gauges_now): + """A bot whose service gives the report's readings now (its `reading`, the outdoor temperature, which a test may change) and, with + context, its gauges (`gauges`: current's result with context, or raises; gauges_now to begin with); its model a ReportAgent.""" + now = NS(reading="12.3 °C", gauges=gauges_now) - async def dashboard(titles=None): - assert titles in (dash.STATUS, None) # the report's three gauges, or the whole dashboard - return sheet() - sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt", dashboard=dashboard), - NS(name="AirGradient", wants=lambda t: True, poke=lambda: None, describe=lambda: "AirGradient")] - bot = Bot(NS(tz=TZ), Agent(), sources, alert_state) + def current(args, meta): + if args.get("context"): + assert args.get("readings") in (gauge_sheet.call(dash.STATUS)["readings"], None) # the report's three gauges, or all (none named) + return now.gauges() + return {"lines": {"station": [f"• Outdoor: {now.reading}"], "air": ["• PM10: 3.0 µg/m³ 🟢 good"]}, + "headings": {"station": "Weather station", "air": "Air quality"}} + service = StandInService(current=current) + bot = Bot(NS(tz=TZ), ReportAgent(), alert_state, service=await serve(tools=service, sources=["Ecowitt", "AirGradient"])) alert_state.add_chat(1, "Rob") alert_state.set_keyboard(1, bot.keyboard_version) - return bot, Agent.tools + return bot, now -def three_tiles(): - tile = Tile("Humidity", "%", 70, "dial", 0, 100, ("#DFFBFF", "#2C7592"), ("Max",), {"Daily": (87,)}, (0, 100), 0) - return Dashboard([tile, tile, tile]) +def three_gauges(): + """current's result with context for the report's three gauges.""" + return {"sensors": {"outdoor": {"temperature": {"value": 12.3, "unit": "°C"}, "humidity": {"value": 70, "unit": "%"}}, + "rainfall": {"rain": {"value": 0.2, "unit": "mm"}}}} def chat(sent): @@ -230,86 +190,58 @@ async def no_action(*a, **k): CONTEXT = NS(bot=NS(send_chat_action=no_action, send_message_draft=no_action, id=99)) # a Telegram bot that shows "typing..." and takes drafts -async def test_the_report_is_its_gauges_with_the_report_as_their_caption_and_refresh_redraws_both(alert_state, monkeypatch): - from lib import report_menu - bot, tools = report_bot(alert_state, three_tiles) - sent = [] - msg, update = chat(sent) - await bot.respond(update, CONTEXT, "report") - assert len(sent) == 1 - kind, photo, caption, kw = sent[0] - assert kind == "photo" and photo == b"\x89PNG" and caption.startswith("Weather station\n• Outdoor: 12.3 °C") - assert [e.type for e in kw["caption_entities"]] == ["bold", "bold"] # the headings, as in the text report - assert [b.callback_data for b in kw["reply_markup"].inline_keyboard[0]] == [report_menu.REFRESH] # Refresh, no period buttons - assert bot.charted.get(1, 7) is None +REPORT = "Weather station\n• Outdoor: 12.3 °C\n\nAir quality\n• PM10: 3.0 µg/m³ 🟢 good" # (no forecast nor pollen here) - edits = [] - - class Query: - data, message = report_menu.REFRESH, NS(photo=[NS(file_id="x")]) - - async def answer(self, *a, **k): - pass - - async def edit_message_media(self, media, reply_markup=None): - edits.append(("media", media.caption, media.caption_entities, reply_markup)) - - async def edit_message_caption(self, caption=None, caption_entities=None, reply_markup=None): - edits.append(("caption", caption, caption_entities, reply_markup)) - tools.reading = "13.0 ℃" - await bot.on_report_button(NS(callback_query=Query()), CONTEXT) - what, caption, entities, markup = edits[-1] - assert what == "media" and "13.0 °C" in caption and [e.type for e in entities] == ["bold", "bold"] - assert markup.inline_keyboard[0][0].callback_data == report_menu.REFRESH - - async def failing(titles=None): - raise RuntimeError("cache gone") - bot.by_name["Ecowitt"].dashboard = failing - tools.reading = "14.0 ℃" - await bot.on_report_button(NS(callback_query=Query()), CONTEXT) - assert edits[-1][0] == "caption" and "14.0 °C" in edits[-1][1] # no new picture: the caption alone - - -async def test_a_report_without_its_gauges_is_the_text_report_as_before(alert_state, caplog): - from lib import report_menu +async def test_status_is_one_message_its_gauges_with_the_report_ecobot_mcp_writes_and_a_refresh_and_no_model(serve, alert_state): + """Status (the button, /status) is a keyboard button: a fixed read of ecobot://status, no model. One message: the three gauges' + picture, the report ecobot-mcp writes from its own answers as its caption (each section's heading in bold), and a 🔄.""" + from lib.bot import STATUS_REFRESH + bot, _ = await report_bot(serve, alert_state, three_gauges) + sent = [] + msg, update = chat(sent) + await bot.status(update, CONTEXT) + assert bot.agent.asked == [] # no model + assert [(k, photo, text) for k, photo, text, _ in sent] == [("photo", b"\x89PNG", REPORT)] + kw = sent[0][3] + assert [[b.callback_data for b in row] for row in kw["reply_markup"].inline_keyboard] == [[STATUS_REFRESH]] + bold = [REPORT.encode("utf-16-le")[e.offset * 2:(e.offset + e.length) * 2].decode("utf-16-le") for e in kw["caption_entities"]] + assert bold == ["Weather station", "Air quality"] + assert bot.chats[(1, None)].history[-1] == {"role": "assistant", "content": REPORT} # (a follow-up knows what was shown) + + +async def test_statuss_refresh_reads_it_again_into_the_same_message(serve, alert_state): + from lib.bot import STATUS_REFRESH + bot, now = await report_bot(serve, alert_state, three_gauges) + edits, toasts = [], [] + + async def edit_media(media, reply_markup=None): + edits.append((media.media.input_file_content[:4] if hasattr(media.media, "input_file_content") else media.media, media.caption, + reply_markup)) + + async def answer(text=None, **kw): + toasts.append(text) + message = NS(chat_id=1, message_id=7, photo=[NS(file_id="old")], edit_media=edit_media) + now.reading = "14.0 °C" + await bot.on_status_button(NS(callback_query=NS(data=STATUS_REFRESH, message=message, answer=answer)), CONTEXT) + assert len(edits) == 1 and edits[0][1] == REPORT.replace("12.3", "14.0") and toasts == ["Refreshed"] + assert bot.agent.asked == [] + + +async def test_status_without_its_gauges_is_the_report_alone_with_its_refresh(serve, alert_state): def broken(): raise RuntimeError("no cache") - bot, _ = report_bot(alert_state, broken) + bot, _ = await report_bot(serve, alert_state, broken) sent = [] msg, update = chat(sent) - await bot.respond(update, CONTEXT, "report") - assert [k for k, *_ in sent] == ["text"] and sent[0][3]["reply_markup"].inline_keyboard[0][0].callback_data == report_menu.REFRESH - assert "gauges failed" in caplog.text - - -async def test_a_report_too_long_for_a_caption_goes_after_its_gauges_with_the_refresh_button_on_the_text(): - from lib.bot import deliver - from lib import report_menu - sent = [] - msg, _ = chat(sent) - text = "Weather station\n" + "\n".join(f"• line {i} " + "x" * 40 for i in range(30)) - await deliver(msg, text, [b"\x89PNG"], markup=report_menu.keyboard(), titles=[""], bold_headings=True, photos_first=True) - assert [k for k, *_ in sent] == ["photo", "text"] - assert "reply_markup" not in sent[0][3] and sent[1][3]["reply_markup"].inline_keyboard[0][0].callback_data == report_menu.REFRESH - - -def test_a_refreshed_report_too_long_for_its_caption_keeps_its_first_sections(): - from lib.bot import CAPTION_LIMIT, report_caption - from lib.entities import utf16_len - first = "Weather station (2:21am)\n• Outdoor: 12.3 °C" - long = first + "\n\nAir quality\n" + "\n".join(f"• line {i} 🟢" + "x" * 30 for i in range(40)) - body, entities = report_caption(long) - assert body == first and [e.type for e in entities] == ["bold"] - body, _ = report_caption(first + "\n\nForecast\n• Today: fine") - assert body.endswith("• Today: fine") # it fits: all of it - body, _ = report_caption("Weather station\n" + "\n".join(f"• {i} " + "y" * 60 for i in range(40))) - assert utf16_len(body) <= CAPTION_LIMIT and body.startswith("Weather station\n• 0 ") # one long section: its first lines + await bot.status(update, CONTEXT) + assert [(k, text) for k, _, text, _ in sent] == [("text", REPORT)] and sent[0][3]["reply_markup"] is not None async def test_the_bands_the_bot_saw_widen_the_gauges_figures_and_the_year_takes_in_the_month(tmp_path): """Between its 5-minute readings the bot (and Home Assistant) saw lower and higher: the day rows take those bands in, so the gauges' Daily and Monthly highs and lows do, and the year's.""" + from lib.ecowitt.days import day_values_on from lib.storage import Storage from lib.timeutil import day_bounds from tests.fakes import MAC @@ -324,9 +256,208 @@ def day(w, d, low, high, band): w.put_ranges(MAC, {"outdoor.temperature": {start + 43200: (4, *band)}}) storage.writer.run(lambda w: (day(w, earlier, 5.0, 28.0, (3.5, 30.0)), day(w, TODAY, 15.0, 20.0, (14.0, 21.5))), ()) live = {"outdoor": {"temperature": reading(18.0)}} - tile = (await dash.dashboard(live, storage, MAC, TODAY, ("Temperature",))).tiles[0] + values, _ = await storage.read(day_values_on, MAC, ["temp_max", "temp_min"], dash.periods_of(TODAY)["Yearly"]) + tile = gauge_sheet.sheet(gauges_result(live, values, TODAY), ("Temperature",)).tiles[0] assert tile.rows == {"Daily": (21.5, 14.0), "Monthly": (30.0, 3.5), "Yearly": (30.0, 3.5)} values = {"temp_max": {earlier: 28.0, TODAY: 20.0}, "temp_min": {earlier: 5.0, TODAY: 15.0}} - plain = dash.sheet(live, values, TODAY, ("Temperature",)).tiles[0] + plain = gauge_sheet.sheet(gauges_result(live, values, TODAY), ("Temperature",)).tiles[0] assert plain.rows == {"Daily": (20.0, 15.0), "Monthly": (28.0, 5.0), "Yearly": (28.0, 5.0)} # the readings alone storage.close() + + +# ---------- the gauges from the service's current, with context (docs/ecobot-mcp.md 3.1, 6 step 2) ---------- +STATUS_TITLES = ("Temperature", "Humidity", "Rain") +GAUGE_RESULT = { + "sensors": { + "outdoor": {"temperature": {"value": 12.3, "unit": "°C", "text": "12.3 °C", + "today": {"high": 14.0, "low": 9.5}, "month": {"high": 21.0, "low": 4.0}, + "year": {"high": 38.0, "low": -1.0}}, + "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}}}, + "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"}} + + +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') + 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["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) + assert [t.title for t in status.tiles] == list(STATUS_TITLES) + assert gauge_sheet.sheet({"sensors": {}}) is None and gauge_sheet.sheet({"error": "x"}) is None + assert gauge_sheet.sheet({**GAUGE_RESULT, "unavailable": {"station": "The weather station isn't answering right now."}}) is None + + +async def test_the_reports_gauges_are_the_services_current_with_context(serve, alert_state, monkeypatch): + """Status's gauges are drawn from current {context: true} (the station's own dashboard() is not asked), its three readings + named, by the service (lib/status.py).""" + from tests.fakes import StandInService + drawn = [] + monkeypatch.setattr(gauges, "render", lambda sheet: drawn.append(sheet) or b"\x89PNG") + + def current(args, meta): + if args.get("context"): + return GAUGE_RESULT + return {"lines": {"station": ["• Outdoor: 12.3 °C"]}, "headings": {"station": "Weather station"}} + service = StandInService(current=current) + bot = Bot(NS(tz=TZ), ReportAgent(), alert_state, service=await serve(tools=service, sources=["Ecowitt"])) + sent = [] + msg, update = chat(sent) + await bot.status(update, CONTEXT) + assert sent[0][0] == "photo" and [t.title for t in drawn[-1].tiles] == list(STATUS_TITLES) + assert ("current", {"readings": ["outdoor.temperature", "outdoor.humidity", "rainfall.rain"], "context": True}) in service.calls + + +async def test_a_station_that_gives_nothing_sends_its_report_without_gauges(serve, alert_state): + from tests.fakes import StandInService + down = {"sensors": {}, "lines": {"station": ["• not available right now"]}, "headings": {"station": "Weather station"}, + "unavailable": {"station": "The weather station isn't answering right now."}} + service = StandInService(current=down) + bot = Bot(NS(tz=TZ), ReportAgent(), alert_state, service=await serve(tools=service, sources=["Ecowitt"])) + sent = [] + msg, update = chat(sent) + await bot.status(update, CONTEXT) + assert [k for k, *_ in sent] == ["text"] # the report as text alone + + +# ---------- the air sensor's gauges, on US standards ---------- +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 (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["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)), + "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(): + for value, band in readings: + assert g[title].band(value) == EPA_NAMES[band], (title, value) + co2 = g["CO₂"] + assert [co2.band(v) for v in (420, 799, 800, 999, 1000, 1499, 1500, 1999, 2000, 3000)] == \ + ["Good", "Good", "Fair", "Fair", "Poor", "Poor", "Bad", "Bad", "Very bad", "Very bad"] + assert [g["VOC index"].band(v) for v in (1, 99, 100, 150, 250, 400)] == ["Low", "Low", "Average", "Elevated", "High", "Very high"] + assert [g["NOx index"].band(v) for v in (1, 20, 21, 150, 151, 300, 301)] == ["Low", "Low", "Elevated", "Elevated", "High", "High", + "Very high"] + assert g["PM2.5"].band(None) is None + + +def air_result(latest: dict | None, air_values: dict | None = None) -> dict: + live = {"outdoor": {"temperature": reading(12.0)}} + return gauges_result(live, {}, TODAY, latest, air_values) + + +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 + 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 (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) + 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 (tiles["PM10"].band, tiles["CO₂"].band, tiles["CO₂"].rows["Daily"]) == ("Moderate", "Poor", (1200.0, 410.0)) + assert [t.title for t in gauge_sheet.sheet(air_result(None)).tiles] == ["Temperature"] # no air sensor: no air gauges + + +def test_the_aqi_and_pm25_tiles_name_the_band_their_needle_is_in_on_a_rise(): + """The service rates PM2.5 (its aqi_us and band) on the lower of the last two readings; the dials show the reading now, so their + numbers and names are of the reading now: a rise from 8 to 40 µg/m³ is Unhealthy for Sensitive Groups on both, not Good.""" + from lib.airgradient.dashboard import EPA_NAMES + from lib.airgradient.metrics import pm25_aqi + 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"] + 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"] + assert pm.band == aqi.band == EPA_NAMES[min(int(share(pm, value) * 6), 5)] == EPA_NAMES[min(int(share(aqi, aqi.value) * 6), 5)] + + +def test_the_us_aqi_is_the_higher_of_pm25s_and_pm10s_and_says_when_pm10_sets_it(): + """The US AQI is AirNow's: the higher of the two particles' own AQI. Dust (PM10 high, PM2.5 low) is not called Good: its band says + 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"] + 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"] + 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)") + + +def test_a_tile_with_no_reading_is_dimmed_at_its_floor_in_its_json(): + from lib.gauge_look import floor, share, shown, tile_json + latest = {"pm2_5": {"value": 12.0, "unit": "µg/m³"}} + values = {"co2_max": {TODAY: 900}, "co2_min": {TODAY: 410}} + sheet = gauge_sheet.sheet(gauges_result({"outdoor": {"temperature": reading(12.0)}, "pressure": {"relative": reading(1012)}}, + {"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"] + 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 + got = tile_json(co2) + assert (got["value"], got["faded"], got["floor"], got["rows"]["Daily"]) == (None, True, 400, [900, 410]) + assert tile_json(aqi)["faded"] is False and tile_json(tiles["Atmospheric pressure"])["floor"] == 950 + + +def test_a_band_scale_gives_each_band_an_equal_share_of_the_dial(): + from lib.gauge_look import share + pm = gauge_sheet.sheet(air_result({"pm2_5": {"value": 9.0, "unit": "µg/m³"}})).tiles[2] + assert pm.title == "PM2.5" + assert [round(share(pm, v), 4) for v in (0, 9.0, 35.4, 55.4, 325.4, 400)] == [0, round(1 / 6, 4), round(2 / 6, 4), 0.5, 1, 1] + assert share(pm, 22.2) == pytest.approx((1 + (22.2 - 9) / (35.4 - 9)) / 6) and share(pm, -1) == 0 + + +def test_the_png_draws_a_tile_with_no_reading_as_its_floor_dimmed(): + """The dimmed tile is the same gauge at its floor, every colour FADE of the way from the card: the needle at the dial's start, the + mercury at the scale's low end, the beaker empty, the number its floor.""" + from PIL import ImageChops + from lib.gauge_look import BG, FADE + for tile in (Tile("Atmospheric pressure", "hPa", None, "dial", 950, 1050, dash.PRESSURE, ("Max", "Min"), {"Daily": (1020.0, 1001.0)}, + (950, 1000, 1050)), + Tile("Temperature", "°C", None, "thermometer", 0, 40, dash.COLD_TO_HOT[:4], ("Max", "Min"), {"Daily": (20.0, 8.0)}, dash.DEGREES), + Tile("Rain", "mm", None, "beaker", 0, 100, dash.WATER, ("Max", "Total"), {"Monthly": (6.0, 9.0)}, (100, 0)), + Tile("CO₂", "ppm", None, "dial", 400, 2500, ("#00E400",) * 5, ("Max", "Min"), {"Daily": (900, 410)}, + (400, 800, 1000, 1500, 2000, 2500), 0, (400, 800, 1000, 1500, 2000, 2500), "Good")): + from lib.gauge_look import floor + dimmed = Image.open(io.BytesIO(gauges.render(Dashboard([tile])))).convert("RGB") + at_floor = Tile(**{**tile.__dict__, "value": floor(tile), "band": None}) + bright = Image.open(io.BytesIO(gauges.render(Dashboard([at_floor])))).convert("RGB") + expected = Image.blend(bright, Image.new("RGB", bright.size, BG), 1 - FADE) + off = ImageChops.difference(dimmed, expected).convert("L").histogram() + 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() diff --git a/tests/test_data_dir.py b/tests/test_data_dir.py index fd376682..5f3a5ef1 100644 --- a/tests/test_data_dir.py +++ b/tests/test_data_dir.py @@ -11,7 +11,7 @@ def configured(monkeypatch, **env): - for key, value in {"TELEGRAM_BOT_TOKEN": "t", "OPENROUTER_API_KEY": "x", "ECOWITT_API_KEY": "a", "ECOWITT_APP_KEY": "b", **env}.items(): + for key, value in {"BOT_TELEGRAM_TOKEN": "t", "BOT_OPENROUTER_API_KEY": "x", "BOT_MCP_URL": "http://127.0.0.1:8765/mcp", **env}.items(): monkeypatch.setenv(key, value) return Config.from_env() diff --git a/tests/test_days.py b/tests/test_days.py index 54ade5b9..eba12a3e 100644 --- a/tests/test_days.py +++ b/tests/test_days.py @@ -1,5 +1,6 @@ -"""weather_days: rank, filter and count days from the cache, checked against answers computed -independently from the fake station's own functions.""" +"""The service's `days` tool over the station (lib/service/days.py, with lib/daytable.py and the day rows): rank, filter and count +days from the cache, checked against answers computed independently from the fake station's own functions. (Until step 6c these ran +against weather_days' own engine, tests/old_tools.py, deleted with it.)""" import json from datetime import datetime, timedelta @@ -8,6 +9,9 @@ from lib.ecowitt import Ecowitt from tests.fakes import TZ, archived_station, config, ecowitt_transport, rain_day, temp +from lib.service import days as days_tool +from lib.service.context import Context +from lib.specs import from_json def local_day(d): @@ -31,8 +35,11 @@ async def station(tmp_path, archived_cache): await eco.close() -async def ask(eco, **args): - return json.loads(await eco.tools[2].handler(args)) +async def ask(eco, start_date=None, end_date=None, **args): + """The days tool over this station, its period the dates (start_date to end_date, both whole days).""" + (tool,) = days_tool.tools(Context(eco=eco)) + period = {**({"start": start_date} if start_date else {}), **({"end": end_date} if end_date else {})} + return json.loads(await tool.call({**period, **args}, None)) def dates(eco, first_ago, last_ago): @@ -116,20 +123,18 @@ async def test_nothing_cached_is_reported_not_guessed(tmp_path): await eco.start() first, last = dates(eco, 30, 1) out = await ask(eco, start_date=str(first), end_date=str(last), where=[{"field": "rain", "op": ">", "value": 0}]) - assert out["days_checked"] == 0 and out["matching_days"] == 0 and "No cached readings" in out["note"] + assert out["days_checked"] == 0 and out["matching_days"] == 0 and "No readings are held for this period yet" in out["note"] assert not any(c.get("path") == "history" for c in fake.calls) # it never fetches await eco.close() async def test_bad_input_gets_a_clear_error(station): eco, _ = station - assert "bad date" in (await ask(eco, start_date="soon", end_date="later"))["error"] - today = datetime.now(eco.tz).date() - assert "before end_date" in (await ask(eco, start_date=str(today), end_date=str(today)))["error"] + assert "'soon' isn't a date or time" in (await ask(eco, start_date="soon", end_date="later"))["error"] first, last = dates(eco, 10, 1) - assert "unusable" in (await ask(eco, start_date=str(first), end_date=str(last), - where=[{"field": "mood", "op": ">", "value": 1}]))["error"] - assert "sort_by" in (await ask(eco, start_date=str(first), end_date=str(last), sort_by="mood"))["error"] + assert "'mood' isn't a field of days" in (await ask(eco, start_date=str(first), end_date=str(last), + where=[{"field": "mood", "op": ">", "value": 1}]))["error"] + assert "'mood' isn't a field of days" in (await ask(eco, start_date=str(first), end_date=str(last), sort_by="mood"))["error"] async def test_a_hotter_trace_rain_day_is_returned_for_a_footnote(station): @@ -185,10 +190,13 @@ async def test_a_tie_is_not_reported_as_a_hotter_day(station): async def test_public_holidays_are_the_local_ones_not_the_models_guess(station): import holidays eco, _ = station - out = await ask(eco, start_date="2025-11-01", end_date="2026-02-28", only="public_holiday", sort_by="temp_max", limit=20) + today = datetime.now(TZ).date() + year = today.year - (1 if today >= today.replace(month=3, day=1) else 2) # the last November to February that is over (and held) + first, last = datetime(year, 11, 1).date(), datetime(year + 1, 2, 28).date() + out = await ask(eco, start_date=str(first), end_date=str(last), only="public_holiday", sort_by="temp_max", limit=20) vic = holidays.country_holidays("AU", subdiv="VIC") - expected = {d for d in (datetime(2025, 11, 1).date() + timedelta(days=k) for k in range(120)) if d in vic} - assert out["days_checked"] == out["matching_days"] == len(expected) and len(expected) == 5 # Cup Day, Christmas, Boxing Day, New Year, Australia Day + expected = {d for d in (first + timedelta(days=k) for k in range((last - first).days + 1)) if d in vic} + assert out["days_checked"] == out["matching_days"] == len(expected) and len(expected) >= 5 # Cup Day, Christmas, Boxing Day, New Year, Australia Day (and a day in lieu) assert {r["date"] for r in out["days"]} == {label(d) for d in expected} names = {r["holiday"] for r in out["days"]} assert {"Melbourne Cup Day", "Christmas Day", "Boxing Day", "New Year's Day", "Australia Day"} <= names @@ -199,19 +207,17 @@ async def test_public_holidays_are_the_local_ones_not_the_models_guess(station): async def test_weekends_and_unknown_places(station): from zoneinfo import ZoneInfo - from lib.ecowitt import days eco, _ = station out = await ask(eco, start_date="2026-08-03", end_date="2026-08-16", only="weekend", limit=10) # two weekends assert out["days_checked"] == 4 and all(r["date"].startswith(("Sat", "Sun")) for r in out["days"]) assert "error" in await ask(eco, start_date="2026-08-03", end_date="2026-08-16", only="bank_holiday") - elsewhere = await days.find_days(eco.storage, eco.mac, ZoneInfo("Europe/Paris"), - {"start_date": "2026-08-03", "end_date": "2026-08-16", "only": "public_holiday"}, - datetime.now(ZoneInfo("Europe/Paris")).replace(tzinfo=None)) + (tool,) = days_tool.tools(Context(eco=eco, tz=ZoneInfo("Europe/Paris"))) + elsewhere = json.loads(await tool.call({"start": "2026-08-03", "end": "2026-08-16", "only": "public_holiday"}, None)) assert "aren't known for this time zone" in elsewhere["error"] # says so instead of guessing async def test_a_missing_holidays_package_is_explained_not_guessed(station, monkeypatch): - from lib.ecowitt import calendar + from lib import public_holidays as calendar eco, _ = station monkeypatch.setattr(calendar, "holidays", None) out = await ask(eco, start_date="2026-01-01", end_date="2026-02-01", only="public_holiday") @@ -255,7 +261,7 @@ async def test_days_can_be_counted_by_any_reading_not_only_temperature_rain_and_ dry = await ask(eco, start_date=str(first), end_date=str(last), where=[{"field": "humidity_min", "op": "<", "value": 50}]) assert dry["matching_days"] == 3 and dry["units"]["humidity_min"] == "%" bad = await ask(eco, start_date=str(first), end_date=str(last), where=[{"field": "uvi", "op": ">=", "value": 9}]) - assert "unusable condition" in bad["error"] and "uv_max" in bad["error"] + assert "'uvi' isn't a field of days" in bad["error"] and "uv_max" in bad["error"] assert fake.calls == [] @@ -282,28 +288,24 @@ async def test_count_only_gives_just_the_counts_and_group_by_month_gives_each_mo async def test_counts_per_month_or_year_are_drawn_as_a_bar_chart_with_a_title_that_says_the_condition(station): - from lib.tools import Turn eco, _ = station first, last = dates(eco, 70, 1) where = [{"field": "temp_max", "op": ">=", "value": 0}] - turn = Turn() - out = json.loads(await eco.tools[2].handler(dict(start_date=str(first), end_date=str(last), where=where, count_only=True, group_by="month"), turn)) - assert len(turn.charts) == 1 and "chart" in out and "message" in out["chart"] - chart = turn.charts[0] + out = await ask(eco, start_date=str(first), end_date=str(last), where=where, count_only=True, group_by="month") + assert len(out["charts"]) == 1 + chart = from_json(out["charts"][0]) bars = chart.panels[0].bars assert chart.title == "Days with temperature ≥ 0 °C" and bars.per == "month" and bars.values assert [int(v) for v in bars.y] == list(out["by_month"].values()) and len(bars.x) == len(out["by_month"]) assert f"{out['matching_days']:,} of {out['days_checked']:,} days" in chart.subtitle from lib.charts import render assert render(chart, eco.tz)[:4] == b"\x89PNG" - plain = Turn() # no group_by: a count, no chart - await eco.tools[2].handler(dict(start_date=str(first), end_date=str(last), where=where, count_only=True), plain) - assert plain.charts == [] + plain = await ask(eco, start_date=str(first), end_date=str(last), where=where, count_only=True) # no group_by: a count, no chart + assert "charts" not in plain async def test_a_total_highest_or_average_per_month_is_a_bar_chart_of_those_figures(station): from collections import defaultdict - from lib.tools import Turn eco, _ = station first, last = dates(eco, 70, 1) days = [first + timedelta(days=k) for k in range((last - first).days + 1)] @@ -314,94 +316,55 @@ async def test_a_total_highest_or_average_per_month_is_a_bar_chart_of_those_figu for d in days: rain[f"{d:%Y-%m}"] += truth(d)[1] top[f"{d:%Y-%m}"] = max(top.get(f"{d:%Y-%m}", -1e9), truth(d)[0]) - turn = Turn() - out = json.loads(await eco.tools[2].handler({**args, "stat": "sum", "of": "rain"}, turn)) + out = await ask(eco, **args, stat="sum", of="rain") assert out["stat"]["what"] == "Total rain" and out["stat"]["unit"] == "mm" and "days" not in out assert {k: v for k, v in out["by_month"].items()} == {k: round(v, 1) for k, v in sorted(rain.items())} - bars = turn.charts[0].panels[0].bars - assert turn.charts[0].title == "Total rain" and bars.unit == "mm" and bars.per == "month" and bars.y == list(out["by_month"].values()) + chart = from_json(out["charts"][0]) + bars = chart.panels[0].bars + assert chart.title == "Total rain" and bars.unit == "mm" and bars.per == "month" and bars.y == list(out["by_month"].values()) - hottest = json.loads(await eco.tools[2].handler({**args, "stat": "max", "of": "temp_max"}, Turn())) + hottest = await ask(eco, **args, stat="max", of="temp_max") assert hottest["stat"]["what"] == "Highest temperature" and hottest["by_month"] == {k: round(v, 1) for k, v in sorted(top.items())} - mean = json.loads(await eco.tools[2].handler({**args, "stat": "avg", "of": "temp_avg"}, Turn())) + mean = await ask(eco, **args, stat="avg", of="temp_avg") assert mean["stat"]["what"] == "Average temperature" and all(v is not None for v in mean["by_month"].values()) - overall = json.loads(await eco.tools[2].handler(dict(start_date=str(first), end_date=str(last), stat="max", of="temp_max", count_only=True), Turn())) + overall = await ask(eco, start_date=str(first), end_date=str(last), stat="max", of="temp_max", count_only=True) assert overall["value"] == round(max(top.values()), 1) and "by_month" not in overall - bad = json.loads(await eco.tools[2].handler(dict(start_date=str(first), end_date=str(last), stat="max"), Turn())) + bad = await ask(eco, start_date=str(first), end_date=str(last), stat="max") assert "needs `of`" in bad["error"] -async def test_a_holiday_filter_the_person_never_asked_for_is_dropped_but_a_requested_one_is_kept(station): - from lib.tools import Turn - eco, _ = station - first, last = dates(eco, 60, 1) - args = dict(start_date=str(first), end_date=str(last), where=[{"field": "temp_max", "op": ">", "value": 0}], count_only=True) - plain = json.loads(await eco.tools[2].handler(args, Turn(text="days over 0 degrees"))) - strayed = json.loads(await eco.tools[2].handler({**args, "only": "weekend"}, Turn(text="days over 0 degrees"))) - assert strayed["days_checked"] == plain["days_checked"] > 40 # the weekend filter was dropped: every day counted - asked = json.loads(await eco.tools[2].handler({**args, "only": "weekend"}, Turn(text="how many weekend days over 0 degrees"))) - assert 0 < asked["days_checked"] < 20 # kept: only Saturdays and Sundays - direct = json.loads(await eco.tools[2].handler({**args, "only": "weekend"})) # no question to check against (a direct call) - assert direct["days_checked"] == asked["days_checked"] - - async def test_a_chart_of_holiday_or_weekend_days_says_so_in_its_subtitle(station): - from lib.tools import Turn - eco, _ = station - first, last = dates(eco, 60, 1) - turn = Turn(text="how many weekend days over 0 degrees per month") - await eco.tools[2].handler(dict(start_date=str(first), end_date=str(last), where=[{"field": "temp_max", "op": ">", "value": 0}], - count_only=True, group_by="month", only="weekend"), turn) - assert turn.charts[0].subtitle.endswith("weekends only · per month") or "weekends only" in turn.charts[0].subtitle - - -async def test_group_by_is_added_from_the_question_when_the_model_leaves_it_out(station): - from lib.tools import Turn eco, _ = station first, last = dates(eco, 60, 1) - args = dict(start_date=str(first), end_date=str(last), where=[{"field": "temp_max", "op": ">", "value": 0}], count_only=True) - turn = Turn(text="days over 0 degrees by month") - out = json.loads(await eco.tools[2].handler(args, turn)) - assert "by_month" in out and len(turn.charts) == 1 # the model said nothing about months; the words did - plain = Turn(text="how many days over 0 degrees") - assert "by_month" not in json.loads(await eco.tools[2].handler(args, plain)) and plain.charts == [] - - -def test_the_field_list_is_in_the_tool_schema_once_and_a_wrong_sort_or_of_field_is_still_caught(): - from lib.ecowitt import days - props = days.PARAMETERS["properties"] - assert "enum" in props["where"]["items"]["properties"]["field"] and "enum" not in props["sort_by"] and "enum" not in props["of"] - from lib.daytable import validate - units = days.FIELD_UNITS - assert "sort_by must be one of" in validate({"sort_by": "nonsense"}, units) and "needs `of`" in validate({"stat": "sum", "of": "nonsense"}, units) - assert "of must be one of" in validate({"stat": "count", "of": "nonsense"}, units) # a count needs no `of`, but a wrong one is caught + out = await ask(eco, start_date=str(first), end_date=str(last), where=[{"field": "temp_max", "op": ">", "value": 0}], + count_only=True, group_by="month", only="weekend") + subtitle = from_json(out["charts"][0]).subtitle + assert subtitle.endswith("weekends only · per month") or "weekends only" in subtitle async def test_a_wrong_of_with_a_plain_count_is_an_error_not_a_crash(station): eco, _ = station first, last = dates(eco, 10, 1) out = await ask(eco, start_date=str(first), end_date=str(last), of="nonsense") - assert "of must be one of" in out["error"] - - -def test_the_description_names_every_field_and_which_have_a_lowest(): - """The model learns the fields from the description. A reading whose lowest says nothing (0 every night or calm hour) has no _min.""" - import re - from lib.ecowitt import days - both, max_only = (re.search(rf"(\w+(?:, \w+)*) \(_max {kind}\)", days.DESCRIPTION)[1].split(", ") for kind in ("and _min", "only")) - assert all(f"{n}_max" in days.FIELDS and f"{n}_min" in days.FIELDS for n in both) - assert all(f"{n}_max" in days.FIELDS and f"{n}_min" not in days.FIELDS for n in max_only) - assert {n.removesuffix("_max").removesuffix("_min").removesuffix("_avg") for n in days.FIELDS} == {"temp", "rain", "wind_gust", *both, *max_only} + assert "`of` names the field `stat` works on: send `stat` too" in out["error"] async def test_a_figure_per_month_with_no_matching_day_promises_no_chart(station): """Highest temperature per month on days over 99°: every month is None, so there is no bar to draw and the model must not be told a chart is attached.""" - from lib.tools import Turn eco, _ = station first, last = dates(eco, 70, 1) - turn = Turn() - out = json.loads(await eco.tools[2].handler(dict(start_date=str(first), end_date=str(last), count_only=True, group_by="month", - stat="max", of="temp_max", where=[{"field": "temp_max", "op": ">", "value": 99}]), turn)) - assert out["by_month"] and all(v is None for v in out["by_month"].values()) and "chart" not in out and turn.charts == [] + out = await ask(eco, start_date=str(first), end_date=str(last), count_only=True, group_by="month", + stat="max", of="temp_max", where=[{"field": "temp_max", "op": ">", "value": 99}]) + assert out["by_month"] and all(v is None for v in out["by_month"].values()) and "charts" not in out + + +def test_the_old_day_tools_engines_are_gone(): + """weather_days' and air_days' engines answer no one since the swap (the service's days reads the day rows itself): they are not in + lib (the tests' copy of them, tests/old_tools.py, went with step 6c).""" + from pathlib import Path + from lib.airgradient import days as air_days + from lib.ecowitt import days as station_days + assert not hasattr(station_days, "find_days") and not hasattr(air_days, "find_air_days") + assert not (Path(__file__).parent / "old_tools.py").exists() diff --git a/tests/test_ecowitt.py b/tests/test_ecowitt.py index 23fee53d..38f58959 100644 --- a/tests/test_ecowitt.py +++ b/tests/test_ecowitt.py @@ -4,11 +4,12 @@ import pytest -from lib import intent from lib.tools import Turn from lib.ecowitt import Ecowitt from lib.ecowitt import api as ecowitt_api from tests.fakes import MAC, FakeEcowitt, archived_station, config, ecowitt_transport +from tests import engines +from lib.service.names import in_all @pytest.fixture @@ -23,7 +24,7 @@ async def station(tmp_path): async def test_finds_the_station(station): eco, _ = station assert eco.mac == MAC and eco.station_name == "Fairleigh" and eco.longitude == 145.0 - assert "Fairleigh" in eco.describe() and "created" in eco.describe() + assert eco.created is not None async def test_a_station_that_gives_no_longitude_has_none_not_melbournes(tmp_path): @@ -101,17 +102,17 @@ async def test_requests_use_metric_unit_ids(station): assert fake.calls[-1]["call_back"] == "outdoor,indoor,pressure,wind,rainfall,rainfall_piezo,solar_and_uvi" # what the archive keeps too -async def test_realtime_is_compact_and_local(station): +async def test_realtime_is_the_stations_reading_with_its_unit_and_time(station): eco, _ = station - out = json.loads(await eco.tools[0].handler({"groups": "outdoor"})) - assert out["outdoor"]["temperature"] == "12.3 ℃" and out["time"] + out = await eco._live_data(["outdoor"]) + assert (out["outdoor"]["temperature"]["value"], out["outdoor"]["temperature"]["unit"]) == ("12.3", "℃") and out["outdoor"]["temperature"]["time"] async def test_history_gives_extremes_with_times_and_days(station): eco, fake = station today = datetime.now(eco.tz).date() start, end = today - timedelta(days=3), today - timedelta(days=1) - result = json.loads(await eco.tools[1].handler( + result = json.loads(await engines.history(eco, {"groups": "outdoor", "start_date": f"{start} 00:00:00", "end_date": f"{end} 23:59:59"})) s = result["series"]["outdoor.temperature"] assert set(s) >= {"low", "high", "low_when", "high_when", "low_date", "high_date", "daily"} @@ -129,7 +130,7 @@ async def test_every_record_has_its_days_time_and_a_tie_goes_to_the_first_day(tm eco, _ = await archived_station(tmp_path, archived_cache) today = datetime.now(eco.tz).date() start, end = today - timedelta(days=13), today - timedelta(days=2) - out = json.loads(await eco.tools[1].handler({"groups": "outdoor,indoor,pressure,wind,solar_and_uvi", "start_date": f"{start} 00:00:00", + out = json.loads(await engines.history(eco, {"groups": "outdoor,indoor,pressure,wind,solar_and_uvi", "start_date": f"{start} 00:00:00", "end_date": f"{end} 23:59:59"})) records = [s for s in out["series"].values() if "low_when" in s] assert len(records) >= 6 and all(s[f"{w}_when"].startswith("at ") for s in records for w in ("low", "high")) @@ -146,16 +147,16 @@ async def test_second_question_is_served_from_the_cache(station): today = datetime.now(eco.tz).date() args = {"groups": "outdoor", "start_date": f"{today - timedelta(days=4)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"} - first = await eco.tools[1].handler(args) + first = await engines.history(eco, args) fake.calls.clear() - assert await eco.tools[1].handler(args) == first + assert await engines.history(eco, args) == first assert fake.calls == [] async def test_long_range_uses_daily_data_and_monthly_figures(station): eco, fake = station today = datetime.now(eco.tz).date() - result = json.loads(await eco.tools[1].handler( + result = json.loads(await engines.history(eco, {"groups": "outdoor", "start_date": f"{today - timedelta(days=200)} 00:00:00", "end_date": f"{today} 00:00:00"})) s = result["series"]["outdoor.temperature"] assert "monthly" in s and "daily" not in s and result["monthly_note"] @@ -175,8 +176,8 @@ async def with_dew(*a, **k): eco.api.history = with_dew day = datetime.now(eco.tz).date() - timedelta(days=2) args = {"groups": "outdoor", "start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"} - assert "outdoor.dew_point" not in json.loads(await eco.tools[1].handler(args))["series"] - assert "outdoor.dew_point" in json.loads(await eco.tools[1].handler({**args, "include_derived": ["dew_point"]}))["series"] + assert "outdoor.dew_point" not in json.loads(await engines.history(eco, args))["series"] + assert "outdoor.dew_point" in json.loads(await engines.history(eco, {**args, "include_derived": ["dew_point"]}))["series"] await eco.close() @@ -184,14 +185,14 @@ async def test_chart_request_adds_a_spec(station): eco, _ = station day = datetime.now(eco.tz).date() - timedelta(days=2) turn = Turn() - out = json.loads(await eco.tools[1].handler( + out = json.loads(await engines.history(eco, {"groups": "outdoor,indoor", "chart": True, "start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"}, turn)) assert "chart" in out and len(turn.charts[0].panels) == 1 and {s.label for s in turn.charts[0].panels[0].lines} == {"Outdoor", "Indoor"} async def test_bad_dates_are_reported(station): eco, _ = station - assert (await eco.tools[1].handler({"start_date": "nonsense", "end_date": "x"})).startswith("Error: bad date") + assert (await engines.history(eco, {"start_date": "nonsense", "end_date": "x"})).startswith("Error: bad date") async def test_warm_then_question_needs_no_new_requests_for_the_tail(station): @@ -243,11 +244,11 @@ async def watch(path, urgent=False, **params): assert marked and not any(marked) marked.clear() today = eco.now().date() - await eco.tools[1].handler({"groups": "outdoor,wind", "start_date": f"{today - timedelta(days=20)} 00:00:00", + await engines.history(eco, {"groups": "outdoor,wind", "start_date": f"{today - timedelta(days=20)} 00:00:00", "end_date": f"{today - timedelta(days=10)} 23:59:59"}, Turn()) assert marked and all(marked) # the question's own, and its wind rose's marked.clear() - await eco.tools[1].handler({"groups": "outdoor,wind", "start_date": f"{today - timedelta(days=40)} 00:00:00", + await engines.history(eco, {"groups": "outdoor,wind", "start_date": f"{today - timedelta(days=40)} 00:00:00", "end_date": f"{today - timedelta(days=30)} 23:59:59"}, Turn(ahead=True)) assert marked and not any(marked) # a chart drawn ahead: nobody is waiting for it @@ -279,7 +280,7 @@ async def test_archive_caches_every_cycle_so_long_questions_need_no_requests_and fake.calls.clear() today = datetime.now(eco.tz).date() for days in (5, 12, 23): # up to all of the fake station's 25 days - out = await eco.tools[1].handler({"groups": "outdoor", "start_date": f"{today - timedelta(days=days)} 00:00:00", + out = await engines.history(eco, {"groups": "outdoor", "start_date": f"{today - timedelta(days=days)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"}) assert "Error" not in out[:20], out[:200] assert fake.calls == [] # nothing was fetched while answering @@ -329,14 +330,14 @@ async def test_year_long_questions_get_dated_monthly_figures_once_the_history_is def monthly(out): return json.loads(out)["series"]["outdoor.temperature"]["monthly"] - before = monthly(await eco.tools[1].handler(args)) # nothing cached: daily figures, values only + before = monthly(await engines.history(eco, args)) # nothing cached: daily figures, values only assert all("low_when" not in m for m in before.values()) await eco.close() (tmp_path / "archived").mkdir() eco, fake = await archived_station(tmp_path / "archived", archived_cache) # the whole history archived turn = Turn() - out = await eco.tools[1].handler({**args, "chart": True}, turn) + out = await engines.history(eco, {**args, "chart": True}, turn) spec = turn.charts[0] after = monthly(out) assert len(after) >= 6 and all({"low_when", "low_date", "high_when", "high_date"} <= set(m) for m in after.values()) @@ -531,7 +532,7 @@ async def test_a_failed_history_request_tells_the_model_and_the_log_no_key(tmp_p eco = Ecowitt(config(tmp_path, ecowitt_api_key="SECRET-API", ecowitt_app_key="SECRET-APP"), transport=transport) await eco.start() day = datetime.now(eco.tz).date() - timedelta(days=3) - out = await eco.tools[1].handler({"groups": "outdoor", "start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"}, Turn()) + out = await engines.history(eco, {"groups": "outdoor", "start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"}, Turn()) await eco.close() assert "HTTP 502" in out and "SECRET" not in out and "SECRET" not in caplog.text @@ -619,7 +620,7 @@ def test_direction_summary_of_a_variable_wind_and_averaged_data(): async def test_history_reports_direction_by_compass_point_not_a_range(tmp_path, archived_cache): eco, fake = await archived_station(tmp_path, archived_cache) today = datetime.now(eco.tz).date() - out = json.loads(await eco.tools[1].handler({"groups": "wind", "start_date": f"{today - timedelta(days=7)} 00:00:00", + out = json.loads(await engines.history(eco, {"groups": "wind", "start_date": f"{today - timedelta(days=7)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"})) direction = out["series"]["wind.wind_direction"] assert direction["most_common"].startswith("N ") and "low" not in direction and "high" not in direction @@ -627,7 +628,7 @@ async def test_history_reports_direction_by_compass_point_not_a_range(tmp_path, assert 20 <= int(direction["calm"].split("%")[0]) <= 30 # midnight to 6am had no wind: about a quarter assert len(direction["daily"]) == 6 and all(v.startswith("N ") for v in direction["daily"].values()) assert "high" in out["series"]["wind.wind_gust"] # speeds are unchanged - again = json.loads(await eco.tools[1].handler({"groups": "wind", "chart": True, "include_derived": [], # a chart of direction alone + again = json.loads(await engines.history(eco, {"groups": "wind", "chart": True, "include_derived": [], # a chart of direction alone "start_date": f"{today - timedelta(days=3)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"}, Turn())) assert "wind.wind_direction" in again["series"] @@ -646,7 +647,7 @@ def recorded(self, groups): # the wind rose's own fetcher, whose reads are cou monkeypatch.setattr(query.Fetcher, "sibling", recorded) today = eco.now().date() turn = Turn(chart_field="wind") - out = json.loads(await eco.tools[1].handler({"groups": "wind", "chart": True, "chart_field": "wind", + out = json.loads(await engines.history(eco, {"groups": "wind", "chart": True, "chart_field": "wind", "start_date": f"{today - timedelta(days=30)} 00:00:00"}, turn)) assert out["series"]["wind.wind_direction"] and turn.charts[0].compass assert len(made) == 1 and made[0].ranges <= 2 # the archived days and today in one read (two in the first hours of the local day, while yesterday's last readings are not yet settled), not one for each of 31 days @@ -663,7 +664,7 @@ async def test_the_wind_chart_carries_the_compass_beside_the_speed_line(tmp_path args = {"groups": "wind", "chart": True, "start_date": f"{today - timedelta(days=6)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"} turn = Turn() - out = json.loads(await eco.tools[1].handler(args, turn)) + out = json.loads(await engines.history(eco, args, turn)) specs = turn.charts assert len(specs) == 1 and specs[0].compass and "compass" in out["chart"] # one image: speed line and compass spec = specs[0] @@ -695,7 +696,7 @@ async def test_a_chart_asked_for_in_the_persons_words_is_drawn_even_if_the_model long = {**short, "start_date": f"{today - timedelta(days=5)} 00:00:00"} # four days: always a chart for args, asked, expected in ((short, False, 0), (short, True, 1), (long, False, 1)): # one wind chart: line and compass turn = Turn(chart_asked=asked) - await eco.tools[1].handler(args, turn) + await engines.history(eco, args, turn) assert len(turn.charts) == expected await eco.close() @@ -709,7 +710,7 @@ async def test_the_chart_plots_the_field_the_question_is_about(tmp_path): "end_date": f"{today - timedelta(days=2)} 23:59:59"} async def chart_of(asked_field=None, **extra): turn = Turn(chart_field=asked_field) # asked_field: from the person's words - await eco.tools[1].handler({**base, **extra}, turn) + await engines.history(eco, {**base, **extra}, turn) return turn.charts[0] assert (await chart_of()).title == "Temperature" # the default assert (await chart_of(chart_field="wind_gust", groups="wind")).title == "Wind" @@ -726,7 +727,7 @@ async def test_a_chart_is_bucketed_to_the_point_budget_and_every_period_carries_ async def spec_for(days_back): turn = Turn() - await eco.tools[1].handler({"groups": "outdoor", "chart": True, + await engines.history(eco, {"groups": "outdoor", "chart": True, "start_date": f"{today - timedelta(days=days_back)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59"}, turn) return turn.charts[0] @@ -749,7 +750,7 @@ async def test_a_multi_year_chart_uses_cached_30_minute_data_for_the_newest_year eco, fake = await archived_station(tmp_path, archived_cache) today = datetime.now(eco.tz).date() turn = Turn() - await eco.tools[1].handler({"groups": "outdoor", "chart": True, + await engines.history(eco, {"groups": "outdoor", "chart": True, "start_date": f"{today - timedelta(days=540)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 00:00:00"}, turn) # settled: no request in the small hours spec = turn.charts[0] @@ -769,7 +770,7 @@ async def test_the_wind_chart_is_the_average_speed_shaded_up_to_the_gusts(tmp_pa async def wind_chart(days, **extra): turn = Turn() - await eco.tools[1].handler({"groups": "wind", "chart": True, "chart_field": "wind_gust", + await engines.history(eco, {"groups": "wind", "chart": True, "chart_field": "wind_gust", "start_date": f"{today - timedelta(days=days)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59", **extra}, turn) return turn.charts[0] @@ -806,7 +807,7 @@ async def test_a_5_minute_temperature_line_is_lightly_smoothed_and_its_records_s async def chart(): turn = Turn() - out = json.loads(await eco.tools[1].handler(args, turn)) + out = json.loads(await engines.history(eco, args, turn)) return out, turn.charts[0] out, smooth = await chart() monkeypatch.setattr(history, "SMOOTH_SERIES", set()) @@ -832,7 +833,7 @@ async def spy(self): eco, fake = await archived_station(tmp_path, archived_cache) today = datetime.now(eco.tz).date() args = {"groups": "outdoor", "start_date": f"{today - timedelta(days=200)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 00:00:00"} - await eco.tools[1].handler(args) + await engines.history(eco, args) assert set(seen) == {"30min"} and fake.calls == [] # held: no daily records, no requests await eco.close() @@ -841,15 +842,15 @@ async def test_averages_come_with_the_answer(tmp_path, archived_cache): eco, _ = await archived_station(tmp_path, archived_cache) today = datetime.now(eco.tz).date() span = {"groups": "outdoor", "start_date": f"{today - timedelta(days=9)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"} - plain = json.loads(await eco.tools[1].handler(span)) + plain = json.loads(await engines.history(eco, span)) assert "average" not in plain["series"]["outdoor.temperature"] # highs and lows are the default - week = json.loads(await eco.tools[1].handler({**span, "average": True})) + week = json.loads(await engines.history(eco, {**span, "average": True})) temp = week["series"]["outdoor.temperature"] days = list(temp["daily"].values()) assert float(temp["average"]) == pytest.approx(sum(float(d["avg"]) for d in days) / len(days), abs=0.1) assert float(temp["low"]) <= float(temp["average"]) <= float(temp["high"]) assert all(float(d["low"]) <= float(d["avg"]) <= float(d["high"]) and "_sum" not in d for d in days) - year = json.loads(await eco.tools[1].handler({"groups": "outdoor", "start_date": f"{today - timedelta(days=200)} 00:00:00", + year = json.loads(await engines.history(eco, {"groups": "outdoor", "start_date": f"{today - timedelta(days=200)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59", "average": True})) months = year["series"]["outdoor.temperature"]["monthly"] assert all("avg" in m and "_sum" not in m for m in months.values()) and "average" in year["series"]["outdoor.temperature"] @@ -865,7 +866,7 @@ async def test_an_average_question_gets_a_caption_that_leads_with_the_average_an hints = {} for asked in (False, True): turn = Turn(average_asked=asked) - out = json.loads(await eco.tools[1].handler(args, turn)) + out = json.loads(await engines.history(eco, args, turn)) spec = turn.charts[0] hints[asked] = out["chart"] assert ("average" in out["series"]["outdoor.temperature"]) is asked # highs and lows by default @@ -882,7 +883,7 @@ async def test_asking_for_an_average_uses_daily_points_even_for_a_short_period(t subtitles = {} for asked in (False, True): turn = Turn(average_asked=asked) - await eco.tools[1].handler(args, turn) + await engines.history(eco, args, turn) subtitles[asked] = turn.charts[0].subtitle assert "daily averages" not in subtitles[False] and "daily averages" in subtitles[True] and "range shaded" in subtitles[True] await eco.close() @@ -898,7 +899,7 @@ async def test_resolution_follows_the_length_of_the_period(tmp_path): eco = Ecowitt(config(tmp_path / str(days)), transport=transport) await eco.start() today = datetime.now(eco.tz).date() - await eco.tools[1].handler({"groups": "outdoor", "start_date": f"{today - timedelta(days=days)} 00:00:00", + await engines.history(eco, {"groups": "outdoor", "start_date": f"{today - timedelta(days=days)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"}) calls = [c for c in fake.calls if c.get("path") == "history"] seen[days] = {c["cycle_type"]: sum(1 for x in calls if x["cycle_type"] == c["cycle_type"]) for c in calls} @@ -1006,16 +1007,16 @@ async def test_weather_link_reads_the_cache_only_and_charts_rain_under_the_readi eco, fake = await archived_station(tmp_path, archived_cache) today = datetime.now(eco.tz).date() turn = Turn() - out = json.loads(await eco.tools[3].handler({"start_date": f"{today - timedelta(days=20)}", + out = json.loads(await engines.linked(eco, {"start_date": f"{today - timedelta(days=20)}", "end_date": f"{today - timedelta(days=2)}"}, turn)) specs = turn.charts assert fake.calls == [] and out["resolution"].startswith("30-minute") and out["slots"] > 500 assert set(out["by_change_before"]) == {"falling", "steady", "rising"} and "chart" in out assert len(specs) == 1 and specs[0].title == "Pressure, Rain" and specs[0].panels[0].bars.width == 6 * 3600 assert render(specs[0], eco.tz)[:4] == b"\x89PNG" - assert "error" in json.loads(await eco.tools[3].handler({"driver": "nonsense"})) + assert "error" in json.loads(await engines.linked(eco, {"driver": "nonsense"})) wind = Turn() # shaded as plot_chart shades it: up to the gusts (48 km/h at most) - await eco.tools[3].handler({"driver": "wind", "start_date": f"{today - timedelta(days=20)}", "end_date": f"{today - timedelta(days=2)}"}, wind) + await engines.linked(eco, {"driver": "wind", "start_date": f"{today - timedelta(days=20)}", "end_date": f"{today - timedelta(days=2)}"}, wind) line = wind.charts[0].panels[0].lines[0] assert line.records["high"][1] == max(line.high) == 48.0 await eco.close() @@ -1125,7 +1126,7 @@ async def test_weather_link_says_which_series_is_missing(tmp_path, driver, serie eco = Ecowitt(config(tmp_path), transport=transport) # nothing cached at all await eco.start() today = datetime.now(eco.tz).date() - out = json.loads(await eco.tools[3].handler({"start_date": str(today - timedelta(days=9)), "end_date": str(today - timedelta(days=2)), + out = json.loads(await engines.linked(eco, {"start_date": str(today - timedelta(days=9)), "end_date": str(today - timedelta(days=2)), **({"driver": driver} if driver else {})})) assert f"{series} or rainfall (rainfall.daily)" in out["note"] and "chart" not in out assert f"falling = {falling} or more" in out["how_to_read"] # the change that counts, in the reading's unit @@ -1141,7 +1142,7 @@ async def test_any_readings_can_be_plotted_together_one_panel_each(tmp_path, arc async def ask_chart(asked_stack=(), **extra): turn = Turn(chart_fields=list(asked_stack)) # asked_stack: from the person's words - out = json.loads(await eco.tools[1].handler({**args, **extra}, turn)) + out = json.loads(await engines.history(eco, {**args, **extra}, turn)) return out, turn.charts out, specs = await ask_chart(chart_fields=["temperature", "rain"]) # the model's choice; rain's group is added for it assert len(specs) == 1 and specs[0].title == "Temperature, Rain" and [p.label for p in specs[0].panels] == ["Temperature"] @@ -1182,22 +1183,13 @@ def test_current_readings_get_a_hot_cold_wet_windy_emoji_from_their_values(): assert glance("pressure", "relative", 1030) == "🗜️" and glance("pressure", "relative", 1020.9) == "" and glance("pressure", "absolute", 1030) == "" -async def test_weather_now_carries_the_emoji_next_to_the_readings(tmp_path): - transport, _ = ecowitt_transport() - eco = Ecowitt(config(tmp_path), transport=transport) - await eco.start() - out = json.loads(await eco.tools[0].handler({"groups": "outdoor"})) - assert out["emoji"] == {"outdoor.temperature": "🧥"} # the fake station reports 12.3 degrees - await eco.close() - - async def test_rain_on_its_own_is_drawn_as_daily_columns_not_as_the_running_counter(tmp_path): transport, _ = ecowitt_transport() eco = Ecowitt(config(tmp_path), transport=transport) await eco.start() today = datetime.now(eco.tz).date() turn = Turn() - out = json.loads(await eco.tools[1].handler({"groups": "rainfall", "chart": True, + out = json.loads(await engines.history(eco, {"groups": "rainfall", "chart": True, "start_date": f"{today - timedelta(days=9)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59"}, turn)) (chart,) = turn.charts @@ -1212,7 +1204,7 @@ async def test_a_dew_point_chart_plots_the_dew_point_and_never_quietly_a_tempera await eco.start() today = datetime.now(eco.tz).date() turn = Turn(chart_field="dew_point") - out = json.loads(await eco.tools[1].handler({"groups": "outdoor", "chart": True, + out = json.loads(await engines.history(eco, {"groups": "outdoor", "chart": True, "start_date": f"{today - timedelta(days=9)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59"}, turn)) assert turn.charts and turn.charts[0].title == "Dew point" and "outdoor.dew_point" in out["series"] @@ -1224,8 +1216,8 @@ async def test_weather_all_week_is_a_stack_of_every_reading_the_station_has(tmp_ eco = Ecowitt(config(tmp_path), transport=transport) await eco.start() today = datetime.now(eco.tz).date() - turn = Turn(chart_asked=True, chart_fields=intent.chart_fields("weather all week")) - await eco.tools[1].handler({"groups": "outdoor,indoor", "chart": True, "start_date": f"{today - timedelta(days=7)} 00:00:00", + turn = Turn(chart_asked=True, chart_fields=list(in_all())) + await engines.history(eco, {"groups": "outdoor,indoor", "chart": True, "start_date": f"{today - timedelta(days=7)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59"}, turn) assert len(turn.charts) == 1 # one image: no separate wind chart with the compass chart = turn.charts[0] @@ -1233,14 +1225,6 @@ async def test_weather_all_week_is_a_stack_of_every_reading_the_station_has(tmp_ await eco.close() -def test_a_reading_named_as_a_group_becomes_its_group_and_an_unknown_name_is_dropped(): - from lib.ecowitt.source import parse_groups - assert parse_groups("pressure,humidity") == ["pressure", "outdoor"] - assert parse_groups("rain, dew_point, wind, outdoor") == ["rainfall", "outdoor", "wind"] - assert parse_groups("outdoor.temperature,bogus") == ["outdoor"] and parse_groups("bogus") == ["outdoor", "indoor"] - assert parse_groups(["indoor", "rainfall_piezo"]) == ["indoor", "rainfall_piezo"] - - async def test_a_job_stops_asking_once_ecowitt_has_refused_twice(tmp_path): from lib.ecowitt.api import EcowittError from tests.fakes import fetcher_on, storage_with @@ -1268,7 +1252,7 @@ async def test_each_weather_chart_carries_its_reading_so_it_is_drawn_in_that_rea today = datetime.now(eco.tz).date() for field, reading in (("wind_gust", "wind"), ("dew_point", "dew_point"), ("relative", "pressure")): turn = Turn(chart_field=field) - await eco.tools[1].handler({"groups": "outdoor,wind,pressure", "chart": True, "start_date": f"{today - timedelta(days=9)} 00:00:00", + await engines.history(eco, {"groups": "outdoor,wind,pressure", "chart": True, "start_date": f"{today - timedelta(days=9)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59"}, turn) panel = turn.charts[0].panels[0] assert panel.reading == reading and _colour(panel.lines[0], 0, panel.reading) == READING_COLOURS[reading] @@ -1283,7 +1267,7 @@ async def test_a_chart_field_may_be_a_readings_name_or_its_field_however_it_is_w for said, title in (("pressure", "Pressure"), ("relative", "Pressure"), ("dew_point", "Dew point"), ("Dew Point", "Dew point"), ("wind gust", "Wind")): turn = Turn() # the reading's group is added for it - await eco.tools[1].handler({"groups": "outdoor", "chart": True, "chart_field": said, + await engines.history(eco, {"groups": "outdoor", "chart": True, "chart_field": said, "start_date": f"{today - timedelta(days=9)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59"}, turn) assert turn.charts and turn.charts[0].title == title, said await eco.close() @@ -1374,23 +1358,23 @@ async def test_a_waiter_cancelled_just_as_the_request_ahead_finishes_is_a_clean_ lock.release() -async def test_weather_now_is_served_from_the_minute_old_live_reading_and_asks_afresh_when_it_cannot(station): +async def test_the_live_reading_is_served_from_the_minute_old_one_and_asked_afresh_when_it_cannot(station): import time eco, fake = station real_time = lambda: [c for c in fake.calls if c.get("path") == "real_time"] groups = "outdoor,indoor,pressure,wind,rainfall,solar_and_uvi" - out = json.loads(await eco.tools[0].handler({"groups": groups})) + out = await eco._live_data(groups.split(",")) assert len(real_time()) == 1 # nothing cached yet: a request of its own await eco.live_rain() # the keep-warm's minute check takes every group assert real_time()[-1]["call_back"] == groups and len(real_time()) == 2 - cached = json.loads(await eco.tools[0].handler({"groups": groups})) + cached = await eco._live_data(groups.split(",")) assert len(real_time()) == 2 and cached["outdoor"] == out["outdoor"] # no request: the report is instant - json.loads(await eco.tools[0].handler({"groups": "outdoor"})) + await eco._live_data(["outdoor"]) assert len(real_time()) == 2 # a subset of those groups too - json.loads(await eco.tools[0].handler({"groups": "rainfall_piezo"})) + await eco._live_data(["rainfall_piezo"]) assert len(real_time()) == 3 # a group it doesn't hold: asks eco._live = (time.time() - 100, eco._live[1]) # older than 90 s: asks - json.loads(await eco.tools[0].handler({"groups": groups})) + await eco._live_data(groups.split(",")) assert len(real_time()) == 4 @@ -1398,8 +1382,8 @@ async def test_a_two_week_result_keeps_only_the_days_of_the_records_unless_every eco, _ = station today = datetime.now(eco.tz).date() args = {"groups": "outdoor", "start_date": f"{today - timedelta(days=13)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59"} - short = json.loads(await eco.tools[1].handler(args, Turn()))["series"]["outdoor.temperature"] - full = json.loads(await eco.tools[1].handler(args, Turn(per_day=True)))["series"]["outdoor.temperature"] + short = json.loads(await engines.history(eco, args, Turn()))["series"]["outdoor.temperature"] + full = json.loads(await engines.history(eco, args, Turn(per_day=True)))["series"]["outdoor.temperature"] assert len(full["daily"]) == 13 and 1 <= len(short["daily"]) <= 2 assert short["high"] == full["high"] and set(short["daily"]) <= set(full["daily"]) @@ -1437,9 +1421,6 @@ async def test_rain_older_than_the_30_minute_readings_is_drawn_from_the_daily_re held = storage.read_now(history_on, f.mac, ["rainfall"], [], f.epoch(q.start), f.epoch(q.end), False, [], True) daily = q._rain_bars(held) assert q.rain_from_daily and len(daily.x) >= 59 and round(sum(daily.y), 1) == 120.0 and daily.per == "day" - q.turn = Turn(text="rain by month for 2 months") - monthly = q._rain_bars(held) - assert monthly.per == "month" and monthly.values and round(sum(monthly.y), 1) == 120.0 and len(monthly.x) in (2, 3) storage.close() @@ -1456,7 +1437,7 @@ def _history(p): with caplog.at_level(logging.INFO): await eco.start() today = datetime.now(eco.tz).date() - reply = await eco.tools[1].handler({"groups": "outdoor", "start_date": f"{today - timedelta(days=1)} 00:00:00", + reply = await engines.history(eco, {"groups": "outdoor", "start_date": f"{today - timedelta(days=1)} 00:00:00", "end_date": f"{today} 23:59:59"}) assert reply.startswith("Error: no history data returned") text = caplog.text @@ -1474,21 +1455,22 @@ def test_the_live_summary_gives_rain_first_then_a_few_readings_and_skips_what_is async def test_a_single_reading_chart_is_labelled_with_the_reading_not_its_group(tmp_path, archived_cache): - from lib import intent from lib.timeutil import now_local from tests.fakes import archived_station eco, _ = await archived_station(tmp_path, archived_cache) - async def lines(text): - read = intent.read(text, now_local(eco.tz)) - turn = Turn(chart_asked=read.chart_asked, chart_field=read.chart_field, chart_fields=read.chart_fields, text=text) - await eco.tools[1].handler(read.fast[1], turn) + async def lines(groups, field): + now = now_local(eco.tz) + turn = Turn(chart_asked=True, chart_field=field) + await engines.history(eco, {"groups": groups, "chart": True, "chart_field": field, + "start_date": f"{now - timedelta(hours=24):%Y-%m-%d %H:%M:%S}", + "end_date": f"{now:%Y-%m-%d %H:%M:%S}"}, turn) (panel,) = turn.charts[0].panels return [line.label for line in panel.lines] - assert await lines("UV chart 1d") == ["UV index"] # not "Solar and uvi" - assert await lines("Solar radiation chart 1d") == ["Solar radiation"] - assert sorted(await lines("Temperature chart 1d")) == ["Indoor", "Outdoor"] # these two tell the lines apart, so they keep their names - assert await lines("Wind chart 1d") == ["Wind"] + assert await lines("solar_and_uvi", "uv") == ["UV index"] # not "Solar and uvi" + assert await lines("solar_and_uvi", "solar") == ["Solar radiation"] + assert sorted(await lines("outdoor,indoor", "temperature")) == ["Indoor", "Outdoor"] # these two tell the lines apart, so they keep their names + assert await lines("wind", "wind") == ["Wind"] await eco.close() @@ -1531,7 +1513,7 @@ def _history(self, p): eco = Ecowitt(cfg, transport=httpx.MockTransport(Retaining())) await eco.start() last = datetime.now(eco.tz).date() - timedelta(days=200) - out = json.loads(await eco.tools[1].handler({"groups": "wind", "start_date": f"{last - timedelta(days=6)} 00:00:00", + out = json.loads(await engines.history(eco, {"groups": "wind", "start_date": f"{last - timedelta(days=6)} 00:00:00", "end_date": f"{last} 23:59:59"})) await eco.close() assert len(out["series"]["wind.wind_direction"]["daily"]) == 7 @@ -1548,7 +1530,16 @@ def with_a_failure(self, *args): self.wind = SimpleNamespace(errors=["5min 16 Oct 2026 - 16 Oct 2026: HTTP 502"], seconds=0.0) monkeypatch.setattr(query.HistoryQuery, "_summarise_direction", with_a_failure) today = datetime.now(eco.tz).date() - out = json.loads(await eco.tools[1].handler({"groups": "wind", "start_date": f"{today - timedelta(days=3)} 00:00:00", + out = json.loads(await engines.history(eco, {"groups": "wind", "start_date": f"{today - timedelta(days=3)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"})) await eco.close() assert "HTTP 502" in " ".join(out.get("missing", [])) and "warning" in out + + +def test_a_reading_with_figures_but_no_readings_in_the_window_draws_no_line_rather_than_failing(): + """Late at night the last hours can hold no readings while today's day row still gives the reading's high and low: the chart leaves + that reading's line out (None) instead of a KeyError on its missing series (it broke summary's chart of the last 3 hours).""" + from lib.ecowitt.query import HistoryQuery + q = object.__new__(HistoryQuery) + q.drawing, q.store, q.units = ("raw", 0), {}, {"outdoor.temperature": "°C"} + assert q._series_entry("outdoor.temperature") is None diff --git a/tests/test_evals.py b/tests/test_evals.py index 0fa45048..f3fefa38 100644 --- a/tests/test_evals.py +++ b/tests/test_evals.py @@ -1,4 +1,4 @@ -"""The saved questions: the decisions made in code must hold for every case, and the checker itself must work. +"""The saved questions: the decision made in code (the reasoning effort) must hold for every case, and the checker itself must work. (What the real model does with them is scripts/eval_prompts.py --live.)""" import pytest @@ -28,18 +28,35 @@ def test_every_kind_of_question_metric_and_chart_has_a_saved_case(): def test_the_call_checker_reports_what_is_wrong(): - expect = {"tools": ["weather_days"], "first_tool": "weather_days", - "args": {"weather_days": {"start_date": "2026-09-05", "where": {"absent": True}, "sort_by": {"any_of": ["temp_max"]}}}} - good = [("weather_days", {"start_date": "2026-09-05", "sort_by": "temp_max"})] + expect = {"tools": ["days"], "first_tool": "days", + "args": {"days": {"period": "this month", "where": {"absent": True}, "sort_by": {"any_of": ["temp_max"]}}}} + good = [("days", {"period": "this month", "sort_by": "temp_max"})] assert evalkit.check_calls(good, expect) == [] - bad = [("weather_history", {}), ("weather_days", {"start_date": "2026-09-01", "where": [{"field": "rain"}], "sort_by": "rain"})] + bad = [("summary", {}), ("days", {"period": "last month", "where": [{"field": "rain"}], "sort_by": "rain"})] fails = " | ".join(evalkit.check_calls(bad, expect)) - assert "first tool" in fails and "start_date" in fails and "where" in fails and "sort_by" in fails - assert evalkit.check_calls([], {"tools": ["weather_link"]}) == ["did not call weather_link (called: nothing)"] - assert evalkit.check_calls([("weather_now", {})], {"not_tools": ["weather_now"]}) == ["should not have called weather_now"] + assert "first tool" in fails and "period" in fails and "where" in fails and "sort_by" in fails + assert evalkit.check_calls([], {"tools": ["relate"]}) == ["did not call relate (called: nothing)"] + assert evalkit.check_calls([("current", {})], {"not_tools": ["current"]}) == ["should not have called current"] assert evalkit.check_args({"g": ["a", "b"]}, {"g": {"has": ["a"]}}) == [] and evalkit.check_args({"g": "x"}, {"g": {"regex": "^y"}}) -def test_the_real_tool_definitions_are_what_the_live_run_offers(): - tools = evalkit.make_tools([]) - assert set(tools.by_name) == set(evalkit.tool_names()) +async def test_the_bots_live_run_is_its_own_request_and_every_question_goes_to_the_model(): + """--live asks the model as the bot does (its prompt: the persona, the server's instructions, the time; the ten tools; its effort); + the questions it once answered in code (the report, a named reading's chart) are asked of the model too (step 6c).""" + from tests.test_agent import FakeLLM + from tests.test_service_evals import case + client = FakeLLM([[("summary", {"readings": ["temperature"], "period": "last 3 months", "average": True})], "Done."]) + turn = await evalkit.run_live(case("3m-average"), client, "m") + assert turn.calls == [("summary", {"readings": ["temperature"], "period": "last 3 months", "average": True})] + assert turn.reply == "Done." and turn.refused == 0 + first = client.requests[0] + assert first["messages"][0] == {"role": "system", "content": evalkit.bot_system()} + assert first["messages"][0]["content"].startswith("You are a friendly weather bot on Telegram") and first["tool_choice"] == "auto" + assert [t["function"]["name"] for t in first["tools"]] == evalkit.service_tool_names() + assert first["extra_body"]["reasoning"]["effort"] == evalkit.effort(case("3m-average")) + for case_id, calls in (("report", [("current", {}), ("pollen", {}), ("forecast", {"period": "today"})]), + ("button-rain-chart", [("summary", {"readings": ["rain"], "period": "7d", "chart": True})])): + client = FakeLLM([calls, "Done."]) + turn = await evalkit.run_live(case(case_id), client, "m") + assert turn.calls == calls and turn.reply == "Done." and len(client.requests) == 2, case_id + assert client.requests[0]["messages"][-1] == {"role": "user", "content": case(case_id).ask} diff --git a/tests/test_forecast.py b/tests/test_forecast.py index 00719770..a9f33c03 100644 --- a/tests/test_forecast.py +++ b/tests/test_forecast.py @@ -1,4 +1,3 @@ -import json from datetime import datetime, time as dtime, timedelta import httpx @@ -82,18 +81,18 @@ async def test_today_and_the_next_days_come_from_open_meteo_by_local_date(tmp_pa 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"] - out = json.loads(await forecast.handle({"days": 3})) - assert len(out["lines"]) == 3 and out["lines"][2] == f"{today + timedelta(days=2):%A}: ⛈️ Thunderstorm. 9–14°C, 75% chance of at least 1 mm" - assert out["place"] == "Melbourne" and out["source"] == "Open-Meteo" and "Tomorrow" not in " ".join(out["lines"]) - assert "tag" not in out and {c for c in calls if isinstance(c, str)} == {"api.open-meteo.com", "ensemble-api.open-meteo.com"} + lines = forecast.lines(3) + assert len(lines) == 3 and lines[2] == f"{today + timedelta(days=2):%A}: ⛈️ Thunderstorm. 9–14°C, 75% chance of at least 1 mm" + assert forecast.place == "Melbourne" and "Tomorrow" not in " ".join(lines) + assert {c for c in calls if isinstance(c, str)} == {"api.open-meteo.com", "ensemble-api.open-meteo.com"} await forecast.close() async def test_the_place_is_the_configured_name(tmp_path): forecast, _ = make(tmp_path, place="Geelong") await forecast.start() - assert json.loads(await forecast.handle({}))["place"] == "Geelong" - assert json.loads(await forecast.handle({}))["time"] # when it was fetched, for the report's heading + assert forecast.place == "Geelong" + assert forecast.fetched_at # when it was fetched, for the text's heading await forecast.close() @@ -117,19 +116,18 @@ async def test_the_station_location_is_used_when_none_is_configured_and_without_ cfg = config(tmp_path, forecast=True) assert Forecast(cfg, (-37.8, 144.9)).location == (-37.8, 144.9) half = config(tmp_path, forecast=True, forecast_lat=-33.9) # one half alone is not a place: not paired with the station's - assert Forecast(half, (-37.8, 144.9)).location == (-37.8, 144.9) and "FORECAST_LAT and FORECAST_LON go together" in caplog.text + assert Forecast(half, (-37.8, 144.9)).location == (-37.8, 144.9) and "MCP_FORECAST_LAT and MCP_FORECAST_LON go together" in caplog.text assert Forecast(config(tmp_path, forecast=True, forecast_lat=-33.9, forecast_lon=151.2), (-37.8, 144.9)).location == (-33.9, 151.2) - with pytest.raises(RuntimeError, match="FORECAST_LAT"): + with pytest.raises(RuntimeError, match="MCP_FORECAST_LAT"): await Forecast(cfg).start() -async def test_a_direct_forecast_question_shows_the_whole_week_unless_fewer_days_are_asked_for(tmp_path): +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() - assert len(json.loads(await forecast.handle({}))["lines"]) == 3 # every day Open-Meteo gave (the test data has three) - assert len(json.loads(await forecast.handle({"days": 2}))["lines"]) == 2 - assert len(json.loads(await forecast.handle({"days": "nonsense"}))["lines"]) == 3 - assert len(json.loads(await forecast.handle({"days": 30}))["lines"]) == 3 + 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 await forecast.close() diff --git a/tests/test_forecast_alert.py b/tests/test_forecast_alert.py index 9a934a57..087f8ebc 100644 --- a/tests/test_forecast_alert.py +++ b/tests/test_forecast_alert.py @@ -1,12 +1,14 @@ -import json +"""The forecast alert, station-wide (docs/ecobot-mcp.md 3.6): today's and tomorrow's forecast against the day's baseline (the first one +fetched from 6 am), an alert when the high moves by more than 2°C or the chance of rain rises past 50% (or falls from there to 30% or +less), the alerted forecast the new baseline.""" + from datetime import date, datetime, time as dtime, timedelta -from lib.alerts.forecast import ForecastMonitor, revised -from lib.alerts.notify import AlertState, Notifier -from lib.forecast import Forecast -from lib.tools import Turn -from tests.fakes import TZ, config -from tests.test_forecast import make +from lib.alert_log import AlertLog +from lib.alerts.forecast import ForecastMonitor, changes, revised +from lib.alerts.store import AlertStore +from tests.fakes import TZ +from tests.test_alerts import Texts TODAY = date(2026, 10, 3) @@ -16,189 +18,143 @@ def day(offset, max_c=20.0, pct=10, summary="☀️ Clear.", min_c=10.0): class FakeForecast: - """Just what the monitor reads: today and the current days.""" - - def __init__(self, days): - self.days = days + """Just what the monitor reads: the time, the days, when they were fetched.""" + tz = TZ - def now(self): - return datetime.combine(TODAY, dtime(12, 0)) + def __init__(self, days, hour=12, minute=0, today=TODAY): + self.days, self.today, self.hour, self.minute = days, today, hour, minute + self.fetched_at = self.at(hour, minute) + def at(self, hour, minute=0) -> float: + return datetime.combine(self.today, dtime(hour, minute), TZ).timestamp() -class FakeBot: - def __init__(self): - self.sent = [] + def now(self): + return datetime.combine(self.today, dtime(self.hour, self.minute)) - async def send_message(self, chat_id, text, **kw): - self.sent.append((chat_id, text)) + def fetch(self, days, hour=None, minute=0): + """A refresh: these days, fetched now (or at `hour`).""" + if hour is not None: + self.hour, self.minute = hour, minute + self.days, self.fetched_at = days, self.at(self.hour, self.minute) -def setup(tmp_path, days): - state, bot = AlertState(tmp_path / "s.json"), FakeBot() - for chat in (1, 2): - state.add_chat(chat, f"chat {chat}") - forecast = FakeForecast(days) - return ForecastMonitor(forecast, state, Notifier(bot, state)), forecast, state, bot +def setup(tmp_path, days, **kw): + store, log = AlertStore(tmp_path / "alert_state.json"), AlertLog(tmp_path / "alerts.sqlite", TZ) + forecast = FakeForecast(days, **kw) + return ForecastMonitor(forecast, store, log), forecast, Texts(log) -def test_substantial_means_rain_flips_or_a_max_temperature_over_2_degrees_different(): +def test_substantial_means_rain_becoming_likely_or_unlikely_or_a_max_temperature_over_2_degrees_different(): base = day(0, max_c=20.0, pct=95) assert revised(base, day(0, max_c=20.0, pct=10)) and revised(day(0, pct=10), day(0, pct=80)) - assert not revised(base, day(0, pct=60)) and not revised(base, day(0, pct=35)) and not revised(day(0, pct=20), day(0, pct=40)) + assert revised(day(0, pct=49), day(0, pct=50)) # likely: up past 50, however little + assert revised(base, day(0, pct=30)) and not revised(base, day(0, pct=31)) # unlikely: down to 30 or less + assert not revised(base, day(0, pct=49)) and not revised(day(0, pct=50), day(0, pct=45)) # into the band between: nothing + assert not revised(base, day(0, pct=50)) and not revised(day(0, pct=20), day(0, pct=49)) # on one side of 50 assert not revised(day(0, max_c=20.0), day(0, max_c=22.0)) and not revised(day(0, max_c=20.0), day(0, max_c=18.0)) assert revised(day(0, max_c=20.0), day(0, max_c=22.1)) and revised(day(0, max_c=20.0), day(0, max_c=17.9)) assert not revised(day(0, max_c=None, pct=None), day(0, max_c=25.0, pct=90)) # nothing to compare + assert changes(day(0, max_c=24.0, pct=10), day(0, max_c=19.0, pct=80)) == ["the high is now 19°C (was 24°C)", + "rain is now likely (80%, was 10%)"] -async def test_a_day_sent_as_rainy_that_turns_dry_is_told_once_to_that_chat(tmp_path): - mon, forecast, state, bot = setup(tmp_path, [day(0, pct=95, summary="⛈️ Thunderstorm."), day(1)]) - state.record_forecast(1, [day(0, pct=95, summary="⛈️ Thunderstorm."), day(1)], TODAY) - await mon.check() - assert bot.sent == [] # unchanged - forecast.days = [day(0, pct=10, summary="☀️ Clear."), day(1)] - await mon.check() - await mon.check() # the same revision does not repeat - assert len(bot.sent) == 1 and bot.sent[0][0] == 1 - text = bot.sent[0][1] - assert text.startswith("🔄 The forecast has changed since I sent it:\n• Today: was ⛈️ Thunderstorm. 10–20°C, 95% chance of rain\n now ☀️ Clear. 10–20°C, 10% chance of rain") - assert state.forecast_sent(1)[TODAY]["rain_chance_pct"] == 10 # the new baseline +def test_a_revision_compares_the_one_millimetre_chance_when_both_days_have_it_and_the_older_figure_otherwise(): + day = lambda **k: {"max_c": 18, **k} + assert revised(day(rain_1mm_pct=60), day(rain_1mm_pct=25)) # rainy -> dry + assert revised(day(rain_1mm_pct=20), day(rain_1mm_pct=55)) # dry -> rainy + assert not revised(day(rain_1mm_pct=45), day(rain_1mm_pct=35)) # under 50 both times + assert not revised(day(rain_chance_pct=94, rain_1mm_pct=95), day(rain_chance_pct=20, rain_1mm_pct=90)) # the new figure decides + assert revised(day(rain_chance_pct=90), day(rain_chance_pct=10)) # only the older figure on either side: as before + assert not revised(day(rain_chance_pct=94), day(rain_1mm_pct=50)) # an old baseline vs a new figure: not compared -async def test_dry_to_rain_and_max_temperature_changes_alert_and_a_further_change_alerts_again(tmp_path): - mon, forecast, state, bot = setup(tmp_path, [day(0), day(1, max_c=20.0)]) - state.record_forecast(1, [day(0), day(1, max_c=20.0)], TODAY) - forecast.days = [day(0, pct=80, summary="🌦️ Showers."), day(1, max_c=22.1)] +async def test_the_first_forecast_fetched_from_6am_is_the_baseline_and_alerts_nothing(tmp_path): + mon, forecast, sent = setup(tmp_path, [day(0, pct=90), day(1)], hour=5, minute=50) + await mon.check() # before 6 am: no baseline yet + assert mon.state.monitor.get("forecast") is None + forecast.fetch([day(0, pct=90), day(1)], hour=6, minute=5) + forecast.hour, forecast.fetched_at = 6, forecast.at(5, 55) # (6 am, but the forecast held was fetched before it) await mon.check() - assert len(bot.sent) == 1 # two changed days: one message - assert "• Today: was" in bot.sent[0][1] and "• Sunday: was" in bot.sent[0][1] - forecast.days = [day(0, pct=80, summary="🌦️ Showers."), day(1, max_c=24.3)] # 2.2 from the new baseline + assert mon.state.monitor.get("forecast") is None + forecast.fetch([day(0, pct=90), day(1), day(2)], hour=6, minute=15) await mon.check() - assert len(bot.sent) == 2 and bot.sent[1][1].count("• ") == 1 + m = mon.state.monitor["forecast"] + assert m["day"] == "2026-10-03" and sorted(m["baseline"]) == ["2026-10-03", "2026-10-04"] and sent == [] # today and tomorrow + assert m["baseline"]["2026-10-03"]["rain_chance_pct"] == 90 -async def test_small_changes_past_days_muted_chats_and_chats_never_sent_a_forecast_are_left_alone(tmp_path): - mon, forecast, state, bot = setup(tmp_path, [day(0), day(1)]) - state.record_forecast(1, [day(0), day(1)], TODAY) - forecast.days = [day(0, max_c=21.9, pct=40), day(1, max_c=18.5)] +async def test_a_move_of_the_high_over_2_degrees_alerts_with_what_changed_and_becomes_the_baseline(tmp_path): + mon, forecast, sent = setup(tmp_path, [day(0), day(1, max_c=24.0)], hour=6, minute=15) + await mon.check() # the baseline + forecast.fetch([day(0), day(1, max_c=22.5)], hour=9) + await mon.check() + assert sent == [] # 1.5 degrees: inside the threshold + forecast.fetch([day(0), day(1, max_c=19.0, pct=80, summary="🌧️ Rain.")], hour=10) await mon.check() - assert bot.sent == [] # inside the thresholds - state.record_forecast(1, [day(-1, pct=90), day(0), day(1)], TODAY) - forecast.days = [day(0, pct=70), day(1)] # yesterday is not in the forecast any more; today flips + assert sent == ["🔄 The forecast for tomorrow has changed: the high is now 19°C (was 24°C) and rain is now likely (80%, was 10%).\n" + "Now: 🌧️ Rain. 10–19°C, 80% chance of rain"] + (event,) = sent.events + assert event["kind"] == "forecast" and event["title"] == "The forecast for tomorrow changed" + assert event["data"] == {"date": "2026-10-04", "was": {"max_c": 24.0, "rain_chance_pct": 10, "summary": "☀️ Clear."}, + "now": {"max_c": 19.0, "rain_chance_pct": 80, "summary": "🌧️ Rain."}} + assert event["expires"] == "2026-10-05T00:00:00+11:00" # news until the end of the day it is about + assert mon.state.monitor["forecast"]["baseline"]["2026-10-04"]["max_c"] == 19.0 # the new baseline + forecast.fetch([day(0), day(1, max_c=20.5, pct=80, summary="🌧️ Rain.")], hour=11) await mon.check() - assert len(bot.sent) == 1 and "Yesterday" not in bot.sent[0][1] and bot.sent[0][1].count("• ") == 1 - state.record_forecast(2, [day(0, pct=90)], TODAY) - state.set_alerts(2, False) - forecast.days = [day(0, pct=5), day(1)] + assert len(sent) == 1 # 1.5 from the new baseline: nothing + forecast.fetch([day(0), day(1, max_c=21.5, pct=80, summary="🌧️ Rain.")], hour=12) await mon.check() - assert [chat for chat, _ in bot.sent] == [1, 1] and state.forecast_sent(2)[TODAY]["rain_chance_pct"] == 90 # muted: not told, not reset + assert len(sent) == 2 and "the high is now 22°C (was 19°C)" in sent[1] # 2.5 from it: told -async def test_a_revised_day_leaves_the_other_days_sent_with_it_to_be_told(tmp_path): - week = [day(i) for i in range(7)] - mon, forecast, state, bot = setup(tmp_path, week) - state.record_forecast(1, week, TODAY) - forecast.days = [*week[:2], day(2, pct=80), *week[3:]] # Monday turns rainy +async def test_rain_crossing_50_alerts_each_way_and_today_and_tomorrow_are_separate_alerts(tmp_path): + mon, forecast, sent = setup(tmp_path, [day(0, pct=40), day(1, pct=60), day(2)], hour=7) + await mon.check() + forecast.fetch([day(0, pct=55), day(1, pct=30), day(2, pct=90)], hour=8) # both cross; the day after tomorrow is not watched await mon.check() - forecast.days = [week[0], day(1, pct=80), day(2, pct=80), *week[3:]] # then Sunday does + assert [t.split(":")[0] for t in sent] == ["🔄 The forecast for today has changed", "🔄 The forecast for tomorrow has changed"] + assert "rain is now likely (55%, was 40%)" in sent[0] and "rain is now unlikely (30%, was 60%)" in sent[1] + forecast.fetch([day(0, pct=60), day(1, pct=20), day(2, pct=90)], hour=9) # further, on the same side: nothing await mon.check() - assert len(bot.sent) == 2 and "• Monday: was" in bot.sent[0][1] and "• Sunday: was" in bot.sent[1][1] - assert sorted(state.forecast_sent(1)) == [d["date"] for d in week] + assert len(sent) == 2 -async def test_an_answer_about_later_days_leaves_today_to_be_told(tmp_path): - mon, forecast, state, bot = setup(tmp_path, [day(0, pct=90), day(1)]) - state.record_forecast(1, [day(0, pct=90), day(1)], TODAY) # the morning report - state.record_forecast(1, [day(1)], TODAY) # "what about tomorrow?" - forecast.days = [day(0, pct=5), day(1)] +async def test_a_chance_hovering_around_50_alerts_once_not_on_every_revision(tmp_path): + mon, forecast, sent = setup(tmp_path, [day(0), day(1, pct=45)], hour=6, minute=15) + await mon.check() # the baseline: tomorrow 45% + for hour, pct in zip(range(7, 12), (50, 45, 50, 45, 55)): # the ensemble's chance, rounded to 5%, between model runs + forecast.fetch([day(0), day(1, pct=pct)], hour=hour) + await mon.check() + assert len(sent) == 1 and "rain is now likely (50%, was 45%)" in sent[0] + forecast.fetch([day(0), day(1, pct=30)], hour=12) # well down: unlikely, told once await mon.check() - assert len(bot.sent) == 1 and "• Today: was" in bot.sent[0][1] - - -async def test_what_was_sent_survives_a_restart_and_is_not_repeated(tmp_path): - mon, forecast, state, bot = setup(tmp_path, [day(0, pct=90)]) - state.record_forecast(1, [day(0, pct=90)], TODAY) - again = AlertState(tmp_path / "s.json") - assert again.forecast_sent(1)[TODAY]["rain_chance_pct"] == 90 - forecast.days = [day(0, pct=5)] - mon2 = ForecastMonitor(forecast, again, Notifier(bot, again)) - await mon2.check() - assert len(bot.sent) == 1 - await ForecastMonitor(forecast, AlertState(tmp_path / "s.json"), Notifier(bot, again)).check() - assert len(bot.sent) == 1 # the new baseline was saved too - - -async def test_the_forecast_tool_notes_the_days_it_gave_for_the_chat_and_a_failure_notes_none(tmp_path): - forecast, _ = make(tmp_path) - await forecast.start() - turn = Turn() - await forecast.handle({"days": 2}, turn) - assert [d["date"] for d in turn.forecast_shown] == [forecast.now().date(), forecast.now().date() + timedelta(days=1)] - assert turn.forecast_shown[0]["max_c"] == 16 and turn.forecast_shown[0]["rain_chance_pct"] == 40 - empty = Forecast(config(tmp_path, forecast=True, forecast_lat=-37.8, forecast_lon=144.9), None, None) - empty.days, turn = [], Turn() - assert "error" in json.loads(await empty.handle({"cached": True}, turn)) and turn.forecast_shown == [] - await forecast.close() - await empty.close() - - -async def test_a_delivered_answer_records_the_forecast_for_its_chat_and_an_undelivered_one_does_not(tmp_path): - from types import SimpleNamespace as NS - from telegram.error import TelegramError - from lib.bot import Bot - forecast, _ = make(tmp_path) - await forecast.start() - state = AlertState(tmp_path / "s.json") - state.add_chat(1, "chat") - - class Agent: - tools = None - - async def run(self, messages, system, effort, first_call=None, turn=None, **k): - await forecast.handle({"days": 2}, turn) - return "Today: showers" - bot = Bot(NS(tz=TZ), Agent(), [], state) - - def update(fail): - async def reply_text(body, **kw): - if fail: - raise TelegramError("down") - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - return NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - - async def send_chat_action(*a, **k): - pass - ctx = NS(bot=NS(send_chat_action=send_chat_action, id=99)) - await bot.respond(update(True), ctx, "what's the forecast") - assert state.forecast_sent(1) == {} # not delivered: not "sent" - await bot.respond(update(False), ctx, "what's the forecast") - assert sorted(state.forecast_sent(1)) == [forecast.now().date(), forecast.now().date() + timedelta(days=1)] - await forecast.close() - - -async def test_an_alert_for_one_chat_goes_to_it_alone_and_a_blocked_one_is_marked_gone(tmp_path): - from telegram.error import Forbidden - state = AlertState(tmp_path / "s.json") - state.add_chat(1, "a") - state.add_chat(2, "b") - sent = [] - - class Bot: - async def send_message(self, chat_id, text, **kw): - if chat_id == 2: - raise Forbidden("bot was blocked by the user") - sent.append((chat_id, text)) - notifier = Notifier(Bot(), state) - assert await notifier("hello", kind="forecast", chats=[1]) == 1 and [c for c, _ in sent] == [1] and sent[0][1] == "hello" - assert await notifier("hello", kind="forecast", chats=[2]) == 0 and state.chats[2]["gone"] + assert len(sent) == 2 and "rain is now unlikely (30%, was 50%)" in sent[1] + forecast.fetch([day(0), day(1, pct=45)], hour=13) # back into the band: nothing + await mon.check() + assert len(sent) == 2 -def test_a_revision_compares_the_one_millimetre_chance_when_both_days_have_it_and_the_older_figure_otherwise(): - from lib.alerts.forecast import revised - day = lambda **k: {"max_c": 18, **k} - assert revised(day(rain_1mm_pct=60), day(rain_1mm_pct=25)) # rainy -> dry - assert revised(day(rain_1mm_pct=20), day(rain_1mm_pct=55)) # dry -> rainy - assert not revised(day(rain_1mm_pct=45), day(rain_1mm_pct=35)) # a wobble in between - assert not revised(day(rain_chance_pct=94, rain_1mm_pct=95), day(rain_chance_pct=20, rain_1mm_pct=90)) # the new figure decides - assert revised(day(rain_chance_pct=90), day(rain_chance_pct=10)) # only the older figure on either side: as before - assert not revised(day(rain_chance_pct=94), day(rain_1mm_pct=50)) # an old baseline vs a new figure: not compared +async def test_a_new_day_starts_a_new_baseline_and_a_restart_keeps_it(tmp_path): + mon, forecast, sent = setup(tmp_path, [day(0), day(1)], hour=7) + await mon.check() + again = ForecastMonitor(forecast, AlertStore(mon.state.path), mon.alerts) # a restart: the baseline is in the store + forecast.fetch([day(0, pct=80), day(1)], hour=8) + await again.check() + assert len(sent) == 1 and "today" in sent[0] + forecast.today += timedelta(days=1) # the next day: its first forecast is the baseline + forecast.fetch([day(1, max_c=30.0), day(2)], hour=6, minute=10) + await again.check() + assert len(sent) == 1 and again.state.monitor["forecast"]["day"] == "2026-10-04" + + +async def test_the_old_per_chat_forecast_record_is_dropped_and_nothing_fires_after_the_upgrade(tmp_path): + from lib.alerts.notify import AlertState + bot_state = AlertState(tmp_path / "bot_state.json") + bot_state.add_chat(1, "chat") + bot_state.monitor["forecast_sent"] = {"1": {TODAY.isoformat(): {**day(0, pct=90), "date": TODAY.isoformat()}}} + bot_state.save() + store = AlertStore(tmp_path / "alert_state.json", moved_from=AlertState(bot_state.path)) + assert "forecast_sent" not in AlertState(bot_state.path).monitor and "forecast_sent" not in store.monitor + mon = ForecastMonitor(FakeForecast([day(0, pct=5)], hour=14), store, AlertLog(tmp_path / "alerts.sqlite", TZ)) + await mon.check() # the first look after the upgrade: the baseline, no alert + assert Texts(mon.alerts) == [] diff --git a/tests/test_hass_api.py b/tests/test_hass_api.py index 2d32ab95..fe9c0463 100644 --- a/tests/test_hass_api.py +++ b/tests/test_hass_api.py @@ -85,7 +85,7 @@ async def test_a_history_is_cut_in_the_clouds_buckets_and_asks_home_assistant_a_ now = local_now() data = await api.history("x", "30min", now - timedelta(days=3), now, "outdoor,wind") stamps = [int(t) for t in data["outdoor"]["temperature"]["list"]] - assert stamps == sorted(stamps) and all(t % 1800 == 0 for t in stamps) and 140 <= len(stamps) <= 146 # three days of half hours + assert stamps == sorted(stamps) and all(t % 1800 == 0 for t in stamps) and 140 <= len(stamps) <= 148 # three days of half hours (a 25-hour day among them in April) assert {"temperature", "temperature_low", "temperature_high", "humidity", "dew_point"} <= set(data["outdoor"]) and set(data) == {"outdoor", "wind"} asked = [c for c in fake.calls if c["path"].startswith("/api/history")] assert 3 <= len(asked) <= 5 and all("sensor.ws2900_rain_rate" not in c["filter_entity_id"] for c in asked) # only the groups asked for diff --git a/tests/test_hass_live.py b/tests/test_hass_live.py index ddd74af1..d08b10ce 100644 --- a/tests/test_hass_live.py +++ b/tests/test_hass_live.py @@ -87,7 +87,7 @@ def nowhere(request): await asyncio.sleep(0.2) task.cancel() assert caplog.text.count("Home Assistant: the ") == 1 # ranges, minutes and live reading: one line - assert "can't find .local names: put the IP address in HOMEASSISTANT_URL" in caplog.text and "host network" in caplog.text + assert "can't find .local names: put the IP address in MCP_HOMEASSISTANT_URL" in caplog.text and "host network" in caplog.text await eco.close() @@ -97,5 +97,5 @@ def test_outside_docker_a_name_that_cannot_be_found_is_to_be_checked_or_given_as monkeypatch.setattr(netenv, "docker_private_network", lambda: False) caplog.set_level(logging.INFO) Trouble("http://homeassistant.local:8123").failed("live reading", "[Errno -2] Name or service not known") - assert "The name in HOMEASSISTANT_URL (http://homeassistant.local:8123) can't be found from here: check it, or use the address" in caplog.text + assert "The name in MCP_HOMEASSISTANT_URL (http://homeassistant.local:8123) can't be found from here: check it, or use the address" in caplog.text assert "Docker" not in caplog.text diff --git a/tests/test_history.py b/tests/test_history.py index 275a9ba6..bdf4664f 100644 --- a/tests/test_history.py +++ b/tests/test_history.py @@ -1,4 +1,5 @@ -"""The readings tool (lib/history.py): one reading's stored values at an interval, each with its time.""" +"""lib/history.py, the engine of the service's `readings` tool (lib/service/readings.py): one reading's stored values at an interval, +each with its time. Driven through that tool (until step 6c through the old readings tool's handler, tests/old_tools.py, deleted).""" import json from datetime import UTC, datetime @@ -6,11 +7,13 @@ import pytest -from lib.history import MAX_ROWS, History, finest_fit, interval_starts +from lib.history import MAX_ROWS, finest_fit, interval_starts +from lib.service import readings +from lib.service.context import Context +from lib.service.names import Catalogue from lib.storage import Storage from lib.storage.catalogue import CLOUD from lib.timeutil import local_epoch, when -from lib.tools import Turn from tests.fakes import TZ MAC, LOC = "M", "42" @@ -30,6 +33,17 @@ def storage(tmp_path): s.close() +class AirStore: + """The air sensor's store as the readings tool reads it: its file, and its sensor a property (AirReadings.sensor).""" + + def __init__(self, storage): + self.storage = storage + + @property + def sensor(self): + return self.storage.air_sensor(LOC) + + def put(storage, sensor: str, res: str, rows: list[dict]): """Readings written as a source writes them: an Ecowitt group's, or the air sensor's ("air").""" def write(w): @@ -38,34 +52,38 @@ def write(w): storage.writer.run(write, ()) -def tool(storage, eco: bool = True, air: bool = True, sent: dict | None = SENT) -> History: +def tool(storage, eco: bool = True, air: bool = True, sent: dict | None = SENT): + """The service's readings tool over the file: the station's sensors (those `sent`) and the air sensor, at NOW.""" station = SimpleNamespace(storage=storage, mac=MAC, tz=TZ) if eco else None - sensor = SimpleNamespace(store=SimpleNamespace(storage=storage, sensor=lambda: storage.air_sensor(LOC)), tz=TZ) if air else None - return History(station, sensor, sent if eco else None, now=lambda: NOW) + sensor = SimpleNamespace(store=AirStore(storage), tz=TZ) if air else None + catalogue = Catalogue.of(sent if eco else None, station=eco, air=air) + (made,) = readings.tools(Context(eco=station, air=sensor, catalogue=catalogue, tz=TZ, clock=lambda: NOW)) + made.catalogue = catalogue + return made -async def ask(history: History, **args) -> dict: - return json.loads(await history.handle(args, Turn())) +async def ask(made, metric: str, **args) -> dict: + """The tool's answer for `metric` (its reading) and these arguments (start and end: local times).""" + return json.loads(await made.call({"reading": metric, **args}, None)) -def offered(history: History, turn: Turn | None = None) -> list[str]: - return history.tools[0].schema(turn)["function"]["parameters"]["properties"]["metric"]["enum"] +def offered(made) -> list[str]: + return made.catalogue.names def test_each_sensor_offers_what_it_has_sent_and_rain_as_the_mm_that_fell(storage): names = offered(tool(storage)) assert {"outdoor.temperature", "outdoor.humidity", "indoor.temperature", "indoor.app_temp", "wind.wind_gust", "rainfall.rain", "rainfall.rain_rate", "air.pm2_5", "air.co2"} <= set(names) - assert not {"outdoor.dew_point", "indoor.humidity", "rainfall.event", "rainfall.daily", "air.air_temperature"} & set(names) - assert {"rainfall_piezo.rain", "solar_and_uvi.uvi"} <= set(names) # (groups with nothing recorded yet offer their whole kind) - assert "air.air_temperature" in offered(tool(storage), Turn(air_extra=True)) # the air sensor's own: only when the words name it + assert not {"outdoor.dew_point", "indoor.humidity", "rainfall.event", "rainfall.daily"} & set(names) + assert {"rainfall_piezo.rain", "solar_and_uvi.uvi", "air.temperature"} <= set(names) # (groups with nothing recorded yet: their whole kind) assert [n for n in offered(tool(storage, eco=False)) if not n.startswith("air.")] == [] assert [n for n in offered(tool(storage, air=False)) if n.startswith("air.")] == [] async def test_stored_five_minute_readings_come_back_as_they_are_with_their_bands(storage): put(storage, "outdoor", "5min", [{"ts": at(9, 1, 5 * i), "humidity": 80 + i, "humidity_lo": 79 + i, "humidity_hi": 81 + i} for i in range(9)]) - out = await ask(tool(storage), metric="outdoor.humidity", start="2026-11-09 01:00", end="2026-11-09 01:40", interval="5min") + out = await ask(tool(storage), metric="outdoor.humidity", start="2026-11-09 01:00", end="2026-11-09 01:41", interval="5min") # (the end not included) assert out["columns"] == ["time", "value", "low", "high"] and out["unit"] == "%" and out["from"] == ["5min"] assert out["rows"][0] == ["Mon 9 Nov 2026 1:00am", 80, 79, 81] and out["rows"][-1] == ["Mon 9 Nov 2026 1:40am", 88, 87, 89] assert len(out["rows"]) == 9 and "missing" not in out @@ -80,7 +98,7 @@ async def test_an_hour_is_worked_out_from_the_finer_readings_and_the_last_one_is ("Sun 8 Nov 2026", "10:00pm"), ("Sun 8 Nov 2026", "11:00pm"), ("Mon 9 Nov 2026", "12:00am"), ("Mon 9 Nov 2026", "1:00am")]] assert [r[1] for r in out["rows"]] == [60, 70, 70, 71, 72, 73] and out["from"] == ["5min", "30min"] - assert "note_last" in out and out["metric"] == "outdoor.humidity" + assert "note_last" in out and out["reading"] == "outdoor.humidity" def test_intervals_are_blocks_of_local_time_across_a_clock_change_and_four_hours_are_the_stations_own(): @@ -95,9 +113,9 @@ def test_intervals_are_blocks_of_local_time_across_a_clock_change_and_four_hours async def test_too_many_rows_are_refused_with_the_interval_that_fits(storage): h = tool(storage) out = await ask(h, metric="outdoor.temperature", start="2026-11-07 01:47", interval="5min") - assert out["error"] == "too many rows" and out["rows"] > MAX_ROWS and out["fits"] == "30min" + assert out["error"].startswith("Too many rows: ") and out["rows"] > MAX_ROWS and out["fits"] == "30min" out = await ask(h, metric="outdoor.temperature", start="2024-01-01 00:00", interval="1day") - assert out["error"] == "too many rows" and out["fits"] is None + assert out["error"].startswith("Too many rows: ") and out["fits"] is None async def test_what_it_cannot_read_is_said(storage): @@ -113,10 +131,10 @@ async def test_what_it_cannot_read_is_said(storage): async def test_minutes_older_than_are_kept_say_so_and_a_coarser_interval_is_offered(storage): put(storage, "outdoor", "5min", [{"ts": at(7, 12), "temperature": 12.0}]) # the sensor has readings, none of them here h = tool(storage) - out = await ask(h, metric="outdoor.temperature", start="2026-11-09 01:00", end="2026-11-09 01:10", interval="1min") + out = await ask(h, metric="outdoor.temperature", start="2026-11-09 01:00", end="2026-11-09 01:11", interval="1min") # (the end not included) assert out["missing"] == 11 and "note_minutes" in out and "note" in out and all(r[1] is None for r in out["rows"]) put(storage, "outdoor", "5min", [{"ts": at(9, 1, 5 * i), "temperature": 12.0} for i in range(3)]) - out = await ask(h, metric="outdoor.temperature", start="2026-11-09 01:00", end="2026-11-09 01:10", interval="1min") + out = await ask(h, metric="outdoor.temperature", start="2026-11-09 01:00", end="2026-11-09 01:11", interval="1min") assert out["fits"] == "5min" and "note_coarser" in out @@ -205,10 +223,8 @@ async def test_an_air_glitch_at_the_edge_of_the_window_is_still_taken_out(storag assert out["rows"] == [["Sun 8 Nov 2026 10:00pm", 5.0, 5.0, 5.0]] -async def test_a_sensor_named_is_kept_and_a_time_with_an_offset_is_moved_into_local_time(storage): +async def test_a_time_with_an_offset_is_moved_into_local_time(storage): h = tool(storage) - assert h.find("air.humidity").name == "air.air_humidity" and h.find("humidity").name == "outdoor.humidity" - assert h.find("indoor.feels_like") is None and h.find("air.temperature").name == "air.air_temperature" put(storage, "outdoor", "5min", [{"ts": at(9, 1), "temperature": 12.0}]) out = await ask(h, metric="outdoor.temperature", start="2026-11-08T14:00:00Z", end="2026-11-08T14:05:00Z", interval="5min") assert out["rows"][0] == ["Mon 9 Nov 2026 1:00am", 12.0, 12.0, 12.0] @@ -218,6 +234,6 @@ async def test_the_interval_offered_instead_is_one_that_is_then_accepted(storage h = tool(storage) for start in ("2026-08-15 07:15", "2026-09-20 22:00", "2026-10-28 01:47", "2026-01-14 00:00"): # (the third: 300 hours; the last: 300 days) refused = await ask(h, metric="outdoor.temperature", start=start, end="2026-11-09 01:47", interval="1min") - assert refused["error"] == "too many rows" and refused["fits"], start + assert refused["error"].startswith("Too many rows: ") and refused["fits"], start assert "error" not in await ask(h, metric="outdoor.temperature", start=start, end="2026-11-09 01:47", interval=refused["fits"]), start assert finest_fit(local_epoch(datetime(2026, 1, 14), TZ), NOW, TZ) == "1day" diff --git a/tests/test_intent.py b/tests/test_intent.py index b0732e87..e13b6dd7 100644 --- a/tests/test_intent.py +++ b/tests/test_intent.py @@ -1,13 +1,10 @@ -from datetime import datetime, timedelta +"""intent: the reasoning effort from the words (docs/ecobot-mcp.md 4), the one thing the bot decides about a typed question in code: +every typed question goes to the model (step 6c). The keyboard's and the alerts' charts are fixed calls.""" -from lib import intent -from tests.fakes import EVERY_SOURCE +import pytest -NOW = datetime(2026, 9, 29, 14, 5) # a Tuesday - - -def call(text, sources=("Ecowitt", "AirGradient")): - return intent.fast_call(text, NOW, sources) +from lib import intent, templates +from lib.alerts import pictures def test_only_looking_ahead_and_descriptions_reason_a_little(): @@ -27,169 +24,6 @@ def test_asking_to_think_try_or_reason_gives_medium_reasoning_to_any_question(): assert intent.reasoning_effort(text) == "none", text -def test_chat_needs_no_data(): - assert not intent.needs_data("thanks, that's great") - assert intent.needs_data("how hot is it") - - -def test_every_reading_named_needs_its_data_but_chat_words_like_cool_or_feeling_do_not(): - for asked in ("vpd now", "what's the uvi", "dewpoint 90d", "solar radiation today", "ultraviolet", "precipitation this week"): - assert intent.needs_data(asked), asked - for chat in ("cool, thanks", "feeling better now", "that's apparent"): - assert not intent.needs_data(chat), chat - - -def test_highs_and_lows_go_fast(): - name, args, _ = call("what was this week's high and low?") - assert name == "weather_history" - assert args == {"groups": "outdoor,indoor", "chart": True, "start_date": "2026-09-23 00:00:00", - "end_date": "2026-09-29 23:59:59"} - - -def test_single_day_has_no_chart_and_respects_indoor(): - _, args, _ = call("indoor high yesterday") - assert args["groups"] == "indoor" and args["chart"] is False - assert args["start_date"] == "2026-09-28 00:00:00" - - -def test_last_24_hours_is_rolling(): - _, args, _ = call("graph the temperature last 24 hours") - assert args["start_date"] == "2026-09-28 14:05:00" and args["end_date"] == "2026-09-29 14:05:00" - - -def test_anything_else_takes_the_normal_path(): - assert call("will it rain tomorrow?") is None - assert call("compare this week and last week highs") is None - assert call("highest wind this week")[1]["groups"] == "wind" # a plain highs question is answered in code - assert call("hello") is None - - -def test_air_now_and_air_chart(): - assert call("how's the air?")[:2] == ("air_quality", {}) - name, args, _ = call("graph PM2.5 and CO2 this week") - assert name == "air_quality" and args["chart"] and args["metrics"] == ["pm2_5", "co2"] - assert args["start_date"] == "2026-09-23 00:00:00" - assert call("chart the air quality")[1]["metrics"] == ["pm2_5"] - assert call("air quality yesterday")[1]["start_date"] == "2026-09-28 00:00:00" - - -def test_sources_are_optional(): - assert call("how's the air?", ["Ecowitt"]) is None - assert call("this week's highs", ["AirGradient"]) is None - - -def test_weather_plus_a_period_is_a_summary_request(): - for text in ("weather week", "weather this week", "weather yesterday", "what was the weather last month"): - assert call(text) and call(text)[0] == "weather_history", text - assert call("weather week")[1]["start_date"] == "2026-09-23 00:00:00" and call("weather week")[1]["chart"] - assert call("hottest day of the month")[1]["start_date"] == "2026-08-31 00:00:00" # the rolling month, not the calendar one - - -def test_weather_now_and_open_questions_still_go_to_the_model(): - for text in ("weather today", "how's the weather now", "weather tomorrow", "weather this week vs last week", - "will the weather be nice this week"): - assert call(text) is None, text - - -def test_weather_now_fetches_every_reading_the_station_has_and_asks_for_the_reports_layout(): - for text in ("weather", "weather now", "Weather Now", "current weather", "ecowitt", "ecowitt now", "show me the weather now please"): - name, args, label = call(text) - assert (name, label) == ("weather_now", "weather now") and args == {"groups": intent.NOW_GROUPS}, text - assert intent.read(text, NOW).weather_now - assert not intent.read("weather last 7 days", NOW).weather_now and not intent.read("report", NOW).weather_now - assert not intent.read("weather now", NOW, ["AirGradient"]).weather_now - - -def test_24_hour_weather_charts_over_a_rolling_window(): - for text in ("weather 24h", "weather 1d", "weather last 24 hours", "weather 1 day"): - name, args, label = call(text) - assert name == "weather_history" and args["chart"] is True, text - assert args["start_date"] == "2026-09-28 14:05:00" and args["end_date"] == "2026-09-29 14:05:00" - assert call("weather yesterday")[1]["chart"] is False - - -def test_air_chart_over_the_last_24_hours_works(): - for text in ("chart pm2.5 last 24 hours", "graph the air quality 24h", "chart co2 1d"): - name, args, _ = call(text) - assert name == "air_quality" and args["start_date"] == "2026-09-28 14:05:00", text - - -def test_aq_with_a_period_charts(): - cases = {"aq 24h": "2026-09-28 14:05:00", "aq 1d": "2026-09-28 14:05:00", "aq 1 month": "2026-08-31 00:00:00", - "aq 1w": "2026-09-23 00:00:00", "air quality 1 year": "2025-09-30 00:00:00"} - for text, start in cases.items(): - name, args, _ = call(text) - assert name == "air_quality" and args["chart"] and args["start_date"] == start, text - assert call("aq")[:2] == ("air_quality", {}) # no period: the current reading - assert call("aq now")[:2] == ("air_quality", {}) - assert call("why was the aq bad yesterday") is None # a question, not a chart request - assert call("aq this week vs last week") is None - - -def test_more_ways_to_name_a_period_for_weather(): - assert call("weather 1 month")[1]["start_date"] == "2026-08-31 00:00:00" - assert call("weather 1y")[1]["start_date"] == "2025-09-30 00:00:00" - assert call("weather 7d")[1]["start_date"] == "2026-09-23 00:00:00" - - -def test_numbered_periods_are_read_not_guessed(): - text = "use 30 minute day to plot 4 months of weather" # was answered with the last 7 days - name, args, label = call(text) - assert name == "weather_history" and args["chart"] and label.endswith("last 4 months") - assert args["start_date"] == "2026-05-31 00:00:00" and args["end_date"] == "2026-09-29 23:59:59" - assert call("plot weather for four months")[1]["start_date"] == "2026-05-31 00:00:00" - assert call("weather 2 weeks")[1]["start_date"] == "2026-09-16 00:00:00" - assert call("weather 12h")[1]["start_date"] == "2026-09-29 02:05:00" and call("weather 12h")[1]["chart"] - assert call("chart the temperature over 3 days")[1]["start_date"] == "2026-09-27 00:00:00" - assert call("aq 3 days")[1]["start_date"] == "2026-09-27 00:00:00" - - -def test_a_period_we_cant_read_goes_to_the_model_not_to_a_default(): - for text in ("plot the weather over the last few months", "chart weather since march", "plot temperature this decade", - "graph the weather 3 days ago", "chart weather 3 months vs 6 months"): - assert call(text) is None, text - assert call("chart weather")[1]["start_date"] == "2026-09-28 14:05:00" # nothing period-like: the last 24 hours - assert call("chart the air quality")[1]["start_date"] == "2026-09-28 14:05:00" - assert call("chart the air quality over the last few days") is None - - -def test_a_plain_wind_chart_takes_the_fast_path_with_the_period_read(): - name, args, _ = call("wind direction plot 3m") - assert name == "weather_history" and args["groups"] == "wind" and args["chart"] is True - assert args["start_date"] == "2026-07-01 00:00:00" and args["end_date"] == "2026-09-29 23:59:59" - assert call("graph the wind this week")[1]["groups"] == "wind" - for text in ("plot wind vs temperature 3m", "will the wind chart change", "why was the wind strong 3m"): - assert call(text) is None, text - - -def test_1m_means_one_month(): - assert call("weather 1m")[1]["start_date"] == "2026-08-31 00:00:00" - assert call("weather 1mo")[1]["start_date"] == "2026-08-31 00:00:00" - assert call("aq 1m")[1]["start_date"] == "2026-08-31 00:00:00" - assert call("weather 3m")[1]["start_date"] == "2026-07-01 00:00:00" - # "30 minute" is not "30 months" - assert call("use 30 minute data to plot 4 months of weather")[1]["start_date"] == "2026-05-31 00:00:00" - - -def test_a_bare_week_month_or_year_charts_for_air_quality_too(): - for text, start in (("aq week", "2026-09-23 00:00:00"), ("air quality month", "2026-08-31 00:00:00"), - ("aq year", "2025-09-30 00:00:00"), ("pm2.5 week", "2026-09-23 00:00:00")): - name, args, label = call(text) - assert name == "air_quality" and args["chart"] and args["start_date"] == start, text - assert call("aq")[:2] == ("air_quality", {}) # no period at all: the current reading - - -def test_air_quality_chart_or_current_reading(): - """A period (however written) charts; the bare words give the current reading as text.""" - for text in ("aq week", "aq 1w", "air quality 1d", "aq 1d", "air quality week", "air qual week", "air qual 1d", - "aq 24h", "aq 1m", "pm2.5 1d"): - name, args, label = call(text) - assert name == "air_quality" and args["chart"] is True, text - for text in ("aq", "air qual", "air quality", "air", "aqi", "aq now", "how's the air", "pm2.5"): - assert call(text)[:2] == ("air_quality", {}), text - assert call("aq 1w")[2] == "air quality chart, last 1 week" - - def test_how_one_reading_relates_to_another_gets_medium_thinking(): for text in ("Is there a correlation between pressure and rainfall", "is there a link between humidity and rain", "cross-reference pressure with rain", "cross reference wind and rain", "what's the connection between wind and temperature", @@ -212,434 +46,35 @@ def test_analysis_across_days_or_readings_gets_low_thinking(): assert intent.reasoning_effort("what was yesterday like?") == "low" -def test_absurd_periods_go_to_the_model_instead_of_crashing(): - from datetime import date - for text in ("weather last 99999 years", "chart weather 2000 years", "aq 99999999999999999999 days", - "weather 999999 hours", "aq 500000 weeks", "weather 12345678 months"): - assert call(text) is None, text # no exception, no nonsense dates - assert call("weather 4 years")[1]["start_date"] == "2022-10-01 00:00:00" # a sane long period still works - assert call("weather 8760 hours")[1]["chart"] - # "on record" is safe on 29 February, when the year four earlier had none - ranges = intent.period_ranges(date(2104, 2, 29)) # 2100 was not a leap year: the old code raised here - assert ranges["on record"] == (date(2104, 2, 29) - timedelta(days=1459), date(2104, 2, 29)) - - -def test_an_air_question_with_a_time_we_cant_read_is_not_answered_with_the_current_reading(): - for text in ("air quality since march", "aq the last few days", "how was the air 3 days ago", "aq these days"): - assert call(text) is None, text - for text in ("aq", "air quality", "aq now", "how's the air"): - assert call(text)[:2] == ("air_quality", {}), text - - -def test_a_particular_date_or_time_goes_to_the_model_not_a_whole_period(): - for text in ("what was the high on 5 Jan this year", "temperature at 3pm today", "hottest day in Jan 12 to Jan 20", - "weather on monday this week", "high at 15:30 yesterday", "how hot was it on 3/2 this month", - "aq on sunday this week", "air quality this morning", "graph the temperature yesterday afternoon", - "what was the low on the 5th of March this year", "weather tonight this week"): - assert call(text) is None, text - # whole periods, however they are written, still take the fast path - for text in ("weather this week", "weather 1m", "aq 24h", "aq week", "hottest day this month", "weather 3 months", - "high and low this year", "chart the temperature last 7 days", "weather 12h", "how sunny was last month"): - assert call(text) is not None or text == "how sunny was last month", text - - -def test_a_question_about_one_reading_charts_that_reading(): - assert intent.chart_field("lowest and highest humidity") == "humidity" - assert intent.chart_field("plot pressure this week") == "relative" - assert intent.chart_field("highest wind gust this year") == "wind_speed" # the mean, shaded up to the gusts - for text in ("hottest day this year", "humidity and temperature this week", "wind and rain", "weather week", "how hot was it"): - assert intent.chart_field(text) is None, text - - -def test_average_questions_are_recognised(): - for text in ("average temp 3m", "what was the mean humidity", "avg wind this week"): - assert intent.AVERAGE.search(text), text - assert not intent.AVERAGE.search("hottest day this year") - - -def test_the_model_is_told_the_exact_dates_of_any_period_the_words_name(): - hints = intent.period_hints("average temp 3m", NOW) - assert hints == ['"3m" = last 3 months: 2026-07-01 00:00:00 to 2026-09-29 23:59:59'] # never 3 days - assert intent.period_hints("wind direction 1y", NOW)[0].startswith('"1y" = last 1 year: 2025-09-30') - assert intent.period_hints("humidity 24h", NOW) == ['"24h" = last 24 hours: 2026-09-28 14:05:00 to 2026-09-29 14:05:00'] - assert len(intent.period_hints("compare this week and last week highs", NOW)) == 2 - assert any("last 2 weeks" in h for h in intent.period_hints("weather 2 weeks", NOW)) - assert intent.period_hints("hello", NOW) == [] and intent.period_hints("use 30 minute data", NOW) == [] - - -def test_readings_named_together_are_charted_together(): - assert intent.chart_fields("plot temperature and rain") == ["temperature", "rain"] - assert intent.chart_fields("graph rain, pressure and humidity for 3m") == ["rain", "pressure", "humidity"] - assert intent.chart_fields("wind vs temp this week") == ["wind", "temperature"] - for text in ("plot the temperature", "will it rain", "hottest day this year", "hello"): - assert intent.chart_fields(text) == [], text - - -def test_a_bare_period_is_hinted_and_a_command_to_the_bot_is_not_a_request_for_readings(): - assert intent.period_hints("humidity week", NOW) == ['"week" = last 7 days: 2026-09-23 00:00:00 to 2026-09-29 23:59:59'] - assert intent.period_hints("weather this week", NOW)[0].startswith('"this week"') # a named period wins - for text in ("add an alert for if winds reach 100 km hour", "please set up a rain alert", "mute the alerts"): - assert not intent.needs_data(text), text - for text in ("will the wind reach 100 km/h", "what was the addition of rain", "how windy is it"): - assert intent.needs_data(text), text - - -def test_questions_about_the_bot_are_recognised_and_readings_questions_are_not(): - for text in ("list our metrics from both sources", "what metrics do you have?", "which sensors do you use", "what can you do", - "what do you measure", "what can I ask", "metrics", "our metrics?", "Available sensors", "sources please"): - assert intent.about_the_bot(text) and not intent.needs_data(text), text - for text in ("rain metrics for Tuesday", "metrics last week", "what was the hottest day", "list rainy days in september", "what's the temperature", "show the past week", - "what was the pressure last month", "how's the air?"): - assert not intent.about_the_bot(text), text - - -def test_a_bare_status_or_report_asks_for_everything_and_nothing_else_does(): - for text in ("status", "report", "Report please", "give me the full report", "current report", "show what you've got", - "overview", "everything?", "what's the status", "sitrep", "SITREP please", "give me the sitrep"): - assert intent.wants_report(text), text - for text in ("weather report for Tuesday", "report the humidity", "status of the rain alert", "report last week", "sitrep last week", "hello", - "how's the air?"): - assert not intent.wants_report(text), text - - -def test_dew_point_feels_like_and_vpd_are_charted_readings_that_outrank_temperature(): - assert intent.chart_field("dew point 90d") == intent.chart_field("dew piont 90d") == intent.chart_field("dewpoint 90d") == "dew_point" - assert intent.chart_field("feels like temperature last month") == "feels_like" - assert intent.chart_field("graph the vpd this week") == "vpd" - assert intent.chart_fields("plot dew point and humidity") == ["dew_point", "humidity"] - assert intent.chart_field("how hot was it") is None - - -def test_weather_all_week_leaves_out_uv_feels_like_and_vpd_unless_configured(monkeypatch): - every = ["temperature", "humidity", "solar", "pressure", "rain", "dew_point", "wind"] # solar third, wind last; no UV (same shape as solar), feels like or VPD - assert intent.chart_fields("weather all week") == every - monkeypatch.setattr(intent, "FEELS_LIKE_IN_ALL", True) - monkeypatch.setattr(intent, "VPD_IN_ALL", True) - assert intent.chart_fields("weather all week") == ["temperature", "humidity", "solar", "pressure", "rain", "dew_point", "feels_like", "vpd", "wind"] - monkeypatch.setattr(intent, "FEELS_LIKE_IN_ALL", False) - monkeypatch.setattr(intent, "VPD_IN_ALL", False) - assert intent.chart_fields("plot feels like and humidity") in (["humidity", "feels_like"], ["feels_like", "humidity"]) # named: still charted - assert intent.chart_fields("plot solar and uv") == ["solar", "uv"] and intent.chart_fields("plot vpd and humidity") != [] - assert intent.chart_field("feels 90d") == intent.chart_field("feel 90d") == intent.chart_field("feels-like 90d") == "feels_like" - - -def test_solar_radiation_and_uv_are_charted_readings_and_a_weekday_is_not_solar(): - assert intent.chart_field("solar 30d") == "solar" and intent.chart_field("uv 7d") == "uvi" == intent.chart_field("uvi last week") - assert intent.chart_field("sun 5 jan") is None and intent.chart_field("how hot was sunday") is None - - -def test_sun_and_uvi_is_two_stacked_readings_but_a_sunday_or_a_dated_sun_is_not_solar(): - assert intent.chart_fields("sun + uvi one month") == ["solar", "uv"] - assert intent.chart_field("sun 5 jan") is None and intent.chart_field("was it hot on sunday") is None - - -def test_a_readings_band_field_still_names_it_and_only_plain_readings_derive_a_range(): - from lib.series import derives_range, field_of, find_name - assert find_name("wind_gust") == find_name("wind_speed") == find_name("wind") == "wind" and field_of("wind_gust") == "wind_speed" - assert derives_range("dew_point") and derives_range("solar") and not derives_range("wind_speed") and not derives_range("wind_direction") - - -def test_ecowitt_means_the_weather_and_ag_or_airgradient_means_the_air_quality(): - assert call("ecowitt week")[0] == "weather_history" and call("ecowitt week") == call("weather week") and call("ecowitt week")[1]["chart"] - for text in ("ag 7d", "airgradient 7d", "air gradient 7d", "AG 7d"): - name, args, _ = call(text) - assert name == "air_quality" and args["chart"] is True and args["metrics"] == ["pm2_5"], text - assert call("ag now")[0] == "air_quality" and call("air gradient")[0] == "air_quality" and not call("ag now")[1] - assert call("ag and ecowitt 7d") is None # both devices: the model decides - assert intent.chart_fields("ecowitt all week") == intent.chart_fields("weather all week") and intent.chart_fields("ecowitt all week") - assert intent.air_metrics("ag all week") == ["pm2_5", "pm10", "pm1", "co2", "voc_index", "nox_index"] or len(intent.air_metrics("ag all week")) == 6 - assert intent.needs_data("ecowitt") and intent.needs_data("ag") and intent.about_the_bot("what does ecowitt measure") and intent.about_the_bot("what does ag measure") - assert not intent.needs_data("that was a nice sag in the road") and not intent.needs_data("thanks") - - -def test_the_report_fetches_everything_in_code_before_the_model_sees_it(): - r = intent.read("report", NOW, EVERY_SOURCE) - assert r.report and r.fast == ("weather_now", {"groups": intent.NOW_GROUPS}, "report") - assert r.more == [("air_quality", {}), ("pollen_asthma", {"cached": True}), ("weather_forecast", {"days": 3, "cached": True})] - plain = intent.read("sitrep", NOW) - assert [plain.fast[0], *(t for t, _ in plain.more)] == ["weather_now", "air_quality"] - only_air = intent.read("status", NOW, ["AirGradient"]) - assert only_air.fast[0] == "air_quality" and only_air.more == [] - assert intent.read("report", NOW, []).fast is None - assert not intent.read("report for last week", NOW).report - - def test_one_reasoning_step_down_for_asking_again_after_a_timeout(): assert [intent.lower_effort(e) for e in ("high", "medium", "low", "none", "odd")] == ["medium", "low", "none", None, None] -def test_asking_for_the_bots_view_is_not_forced_to_fetch_but_a_view_of_the_weather_today_is(): - philosophical = "what do you think of weather in general, from a philosophical perspective?" - assert intent.is_opinion(philosophical) and not intent.needs_data(philosophical) - assert intent.reasoning_effort(philosophical) == "medium" # "think": still given a little thought - for text in ("what do you think of the weather today?", "what do you think about tomorrow's rain", "do you like the rain now", - "what do you think of the weather over the last 3 days", "weather", "how hot is it", "what do you think the forecast says"): - assert intent.needs_data(text), text - - -def test_only_temp_temperature_how_hot_or_cold_and_hottest_style_questions_force_a_fetch(): - for text in ("only that it's cold", "it's so hot in here", "nice and warm", "warm regards", "cool", "freezing", "degrees"): - assert not intent.needs_data(text), text - for text in ("temp", "temps this week", "what's the temperature", "how cold is it", "how hot will it get", "how's the weather", - "hottest weekends", "coldest day last month", "is it cold outside"): - assert intent.needs_data(text), text - assert intent.read("only that it's cold", NOW).needs_data is False - - -def test_now_alone_is_not_a_weather_question_but_naming_a_reading_with_it_is(): - for text in ("now", "ok now what?", "what now", "do it now", "right now", "currently", "current", "what's happening now"): - r = intent.read(text, NOW) - assert not r.needs_data and not r.weather_now and r.fast is None, text - for text in ("weather now", "is it raining now", "what's the temperature now", "current weather", "how windy is it right now"): - assert intent.needs_data(text), text - - -import pytest as _pytest - - -@_pytest.mark.parametrize("text, kind, named", [ - ("how hot is it", "reading", ["temperature"]), ("is it raining", "reading", ["rain"]), ("uv", "reading", ["uv"]), - ("what's the pressure", "reading", ["pressure"]), ("dew point", "reading", ["dew_point"]), - ("how's the air", "air", []), ("pm10", "air", ["pm10"]), ("forecast", "forecast", []), ("7 day forecast", "forecast", []), - ("pollen", "pollen", []), ("what can you do", "about", []), - ("is it too cold to run", "", []), ("is the air ok for a run", "", []), ("will it rain", "", []), ("forecast tomorrow", "", []), - ("temperature today", "extremes", ["temperature"]), ("is it hotter than yesterday", "", []), ("why is it so humid", "", []), -]) -def test_plain_lookups_are_answered_in_code_and_everything_else_is_left_to_the_model(text, kind, named): - read = intent.read(text, datetime(2026, 10, 2, 12), EVERY_SOURCE) - assert (read.lookup, read.lookup_arg) == (kind, named) - - -@_pytest.mark.parametrize("text, before, has, lacks", [ - ("hottest day that also rained", [], {"days"}, {"air", "link"}), - ("did it rain on Sat 5 Sep", [], {"days"}, {"air"}), - ("is there a correlation between pressure and rainfall", [], {"link"}, {"air"}), - ("is the air ok for a run", [], {"air"}, {"days", "link"}), - ("plot air quality against rainfall", [], {"air"}, set()), - ("will it rain later", [], {"outlook"}, {"air"}), - ("most common wind direction", [], {"wind"}, {"air"}), - ("describe what it was like on Monday", [], {"describe"}, set()), - ("add an alert when winds reach 100", [], {"bot"}, set()), - ("how cold is it", [], set(), {"bot", "days", "air", "link"}), - ("and indoors?", ["what was the hottest day this month"], {"days"}, set()), # a follow-up keeps the topics of what came before - ("thanks, that's great", [], set(), {"air", "days", "link", "outlook", "wind", "bot"}), -]) -def test_topics_pick_the_guidance_and_tools_a_question_needs(text, before, has, lacks): - found = intent.topics(text, before) - assert has <= found and not (lacks & found) - - - -@_pytest.mark.parametrize("text, days", [("will it rain?", 3), ("do I need an umbrella", 3), ("is it going to rain tomorrow", 3), - ("will it rain this week", 7), ("rain later?", 3)]) -def test_a_question_about_rain_ahead_has_the_reading_the_last_3_hours_and_the_forecast_fetched_for_the_model(text, days): - now = datetime(2026, 10, 3, 12) - read = intent.read(text, now, ["Ecowitt", "AirGradient", "Forecast"]) - groups = "outdoor,pressure,rainfall,rainfall_piezo,wind" - assert read.fast is None and read.extra == [ - ("weather_now", {"groups": groups}), - ("weather_history", {"groups": groups, "start_date": "2026-10-03 09:00:00", "end_date": "2026-10-03 12:00:00"}), - ("weather_forecast", {"days": days, "cached": True})] - no_forecast = intent.read(text, now).extra - assert [c[0] for c in no_forecast] == ["weather_now", "weather_history"] # forecast off: just the station - assert intent.read(text, now, ["AirGradient", "Forecast"]).extra == [("weather_forecast", {"days": days, "cached": True})] # no station - - -@_pytest.mark.parametrize("text, name, day", [("what was yesterday like?", "yesterday", "2026-10-02"), ("describe today", "today", "2026-10-03")]) -def test_describing_today_or_yesterday_has_that_days_readings_fetched_for_the_model(text, name, day): - read = intent.read(text, datetime(2026, 10, 3, 12)) - (tool, args), = read.extra - assert tool == "weather_history" and args["groups"] == "outdoor,indoor,rainfall,wind" and args["start_date"].startswith(day) - - -@_pytest.mark.parametrize("text", ["what was it like on Mon 10 Aug", "what was it like at 3pm today", "how hot was yesterday", "describe last week"]) -def test_a_named_date_a_moment_a_longer_period_or_a_plain_question_has_nothing_fetched_ahead(text): - assert intent.read(text, datetime(2026, 10, 3, 12), ["Ecowitt", "AirGradient", "Forecast"]).extra == [] - - -@_pytest.mark.parametrize("text", ["how much rain fell today", "how much rain this week", "did it rain yesterday", "forecast", "rain chart 7d"]) -def test_questions_about_rain_so_far_do_not_fetch_the_forecast(text): - assert intent.read(text, datetime(2026, 10, 3, 12), ["Ecowitt", "AirGradient", "Forecast"]).extra == [] - - -@_pytest.mark.parametrize("text", ["how many times did it rain this year", - "worst air quality day per month", "days over 35 and also rained", "days over UVI 10 on weekends"]) -def test_counting_and_totalling_questions_are_never_turned_into_a_plain_chart(text): - read = intent.read(text, datetime(2026, 10, 3, 12), EVERY_SOURCE) - assert read.fast is None and not read.chart_in_code and read.lookup == "" - - -@_pytest.mark.parametrize("text, tool, field, op, value, group", [ - ("days over UVI 10 by year", "weather_days", "uv_max", ">=", 10, "year"), - ("count days over PM2.5 of 90 per year", "air_days", "pm2_5_max", ">", 90, "year"), - ("how many days was UV 9 or more", "weather_days", "uv_max", ">=", 9, None), - ("days over 30 degrees per month this year", "weather_days", "temp_max", ">", 30, "month"), - ("how many days under 5 degrees", "weather_days", "temp_min", "<", 5, None), - ("days with rain over 5 mm", "weather_days", "rain", ">", 5, None), - ("how many days did the wind exceed 60 km/h", "weather_days", "wind_gust", ">", 60, None), - ("count the days humidity was below 30 per month", "weather_days", "humidity_min", "<", 30, "month"), - ("how many days was PM2.5 over 25 in 2024", "air_days", "pm2_5_max", ">", 25, None), -]) -def test_one_reading_against_one_limit_is_counted_in_code(text, tool, field, op, value, group): - read = intent.read(text, datetime(2026, 10, 3, 12)) - name, args, _ = read.fast - assert read.lookup == "days" and name == tool and args["count_only"] is True and args.get("group_by") == group - assert args["where"] == [{"field": field, "op": op, "value": float(value)}] - - -def test_the_period_is_the_whole_record_unless_one_is_named(): - now = datetime(2026, 10, 3, 12) - whole = intent.read("days over UVI 10 by year", now).fast[1] - assert whole["start_date"] == "2022-10-05" and whole["end_date"] == "2026-10-03" - named = intent.read("days over UVI 10 by month this year", now).fast[1] - assert named["start_date"] == "2026-01-01" and named["group_by"] == "month" - year = intent.read("how many days was PM2.5 over 25 in 2024", now).fast[1] - assert year["start_date"] == "2024-01-01" and year["end_date"] == "2024-12-31" - - -@_pytest.mark.parametrize("text, tool, stat, of, group", [ - ("rain by month for 2 years", "weather_days", "sum", "rain", "month"), - ("average temperature per year", "weather_days", "avg", "temp_avg", "year"), - ("hottest day each year", "weather_days", "max", "temp_max", "year"), - ("coldest night per month this year", "weather_days", "min", "temp_min", "month"), - ("humidity by month this year", "weather_days", "avg", "humidity_avg", "month"), - ("uv by month", "weather_days", "max", "uv_max", "month"), - ("windiest day per month", "weather_days", "max", "wind_gust", "month"), - ("highest PM2.5 by month", "air_days", "max", "pm2_5_max", "month"), - ("average co2 per year", "air_days", "avg", "co2_avg", "year"), -]) -def test_one_reading_by_month_or_year_is_a_figure_per_period_worked_out_in_code(text, tool, stat, of, group): - read = intent.read(text, datetime(2026, 10, 3, 12)) - name, args, _ = read.fast - assert read.lookup == "days" and (name, args["stat"], args["of"], args["group_by"]) == (tool, stat, of, group) and args["count_only"] is True - - -@_pytest.mark.parametrize("text", ["pm2.5 and co2 by month", "rain by month on weekends", "air quality by month", "will it rain by month", - "days over 30 degrees and rain per month", "rain days per month"]) -def test_anything_beyond_one_reading_by_month_or_year_is_left_to_the_model(text): - read = intent.read(text, datetime(2026, 10, 3, 12)) - assert read.lookup == "" and (read.fast is None or read.fast[0] not in ("weather_days", "air_days")) - - -def test_weather_all_week_is_every_reading_and_a_named_chart_is_not(): - assert intent.wants_chart_all("weather all week") and intent.wants_chart_all("ecowitt all week") - assert not intent.wants_chart_all("plot temperature and rain") and not intent.wants_chart_all("temperature chart 7d") - - -@_pytest.mark.parametrize("ask", ["weather chart 90d", "chart all 90d", "chart 90d", "chart"]) -def test_a_chart_that_names_no_reading_is_every_reading_not_temperature(ask): - read = intent.read(ask, NOW) - assert intent.wants_chart_all(ask) and read.chart_fields[:3] == ["temperature", "humidity", "solar"] and read.chart_fields[-1] == "wind" - - -def test_a_named_reading_or_an_air_chart_is_not_every_reading_and_indoors_has_only_what_the_indoor_sensor_measures(): - for ask in ("temperature chart 90d", "rain chart 7d", "chart air 90d", "plot pm2.5 90d"): - assert not intent.wants_chart_all(ask) and intent.chart_fields(ask) == [] - assert intent.chart_fields("chart all 90d indoors") == ["temperature", "humidity", "dew_point"] - - -# ---------- what a phone types, and words that only look like other things ---------- -def test_a_phone_s_curly_apostrophe_reads_as_the_plain_one(): - for plain in ("what's the weather", "what's the temperature", "show what you've got", "what's the forecast"): - curly = plain.replace("'", "’") - assert intent.read(curly, NOW, EVERY_SOURCE).fast == intent.read(plain, NOW, EVERY_SOURCE).fast, curly - assert intent.read(curly, NOW, EVERY_SOURCE).fast is not None, curly - - -def test_all_time_and_every_day_are_periods_not_every_air_reading(): - for text in ("pm2.5 chart all time", "pm2.5 every day this week", "highest pm2.5 of all-time"): - assert intent.air_named(text) == ["pm2_5"], text - for text in ("aq all week", "air quality all metrics 1d", "chart everything in the air 7d"): # every reading still means every one - assert intent.air_named(text) == ["pm2_5", "pm10", "pm1", "co2", "voc_index", "nox_index"], text - assert call("count days over PM2.5 of 90 per year all time")[0] == "air_days" - - -def test_co2_with_a_subscript_two_is_the_air_reading(): - assert call("co₂ chart 7d")[1]["metrics"] == ["co2"] and call("chart CO₂ 1d")[0] == "air_quality" - assert intent.needs_data("co₂") and intent.needs_data("pm1") and intent.mentions_air("co₂") - - -def test_indoor_dew_point_and_feels_like_come_from_the_indoor_sensor(): - for text in ("indoor dew point chart", "indoor feels like chart 7d", "indoor dew point 90d"): - assert call(text)[1]["groups"] == "indoor", text - assert call("dew point chart")[1]["groups"] == "outdoor" # unasked, they stay the outdoor sensor's - assert call("indoor and outdoor dew point chart 7d")[1]["groups"] == "outdoor,indoor" - - -def test_the_lowest_uv_per_month_is_the_lowest_daily_high_not_the_highest(): - tool, args, _ = intent.period_figures_call("lowest uv by month", NOW, ["Ecowitt"]) - assert (tool, args["stat"], args["of"], args["group_by"]) == ("weather_days", "min", "uv_max", "month") - assert intent.period_figures_call("uv by month", NOW, ["Ecowitt"])[1]["stat"] == "max" # a UV index is its day's high - assert intent.period_figures_call("lowest wind by month", NOW, ["Ecowitt"]) is None # wind has no lowest to ask for - - -def test_the_air_table_is_the_one_in_series_and_panels_imports_on_its_own(): - import subprocess - import sys - from lib.airgradient.metrics import LABELS, MARK_LOW, RATINGS - from lib.series import AIR - assert list(LABELS) == list(AIR) == [m for _, m in intent.AIR_METRICS] and MARK_LOW == ("co2",) and RATINGS["pm2_5"] == (9.0, 55.4) - run = subprocess.run([sys.executable, "-c", "import lib.panels"], capture_output=True, text=True) - assert run.returncode == 0, run.stderr # no circular import through airgradient - - -def test_the_models_first_step_must_fetch_for_data_may_just_reply_to_chat_and_gets_no_tools_about_the_bot(): - assert [intent.read(t, NOW).tool_choice for t in ("will it rain tomorrow?", "thanks!", "what can you do")] == ["required", "auto", "none"] - - -def test_two_readings_on_two_axes_is_asked_for_in_so_many_words_and_goes_to_the_weather_history_chart(): - from datetime import datetime - from tests.fakes import TZ - now = datetime(2026, 10, 27, 12, tzinfo=TZ) - for said in ("graph combine uvi and solar radiation on two axis", "plot temperature and humidity on two axes", "uv vs solar, dual axis", - "graph uv and solar 2 axes", "plot uv and solar with a secondary axis", "graph uv and solar overlaid"): - assert intent.read(said, now).two_axes, said - for said in ("plot temperature and humidity", "graph uv on two axes", "plot rain", "what is the axis of the earth"): - assert not intent.read(said, now).two_axes, said # one reading, or no such request - read = intent.read("graph combine uvi and solar radiation on two axis", now) - assert read.chart_in_code and read.chart_fields == ["uv", "solar"] and read.fast[0] == "weather_history" - - -def test_the_air_sensors_own_temperature_and_humidity_are_offered_only_when_the_airgradient_is_named_with_them(): - from datetime import datetime - from tests.fakes import TZ - now = datetime(2026, 10, 27, 12, tzinfo=TZ) - for said in ("plot airgradient humidity over ecowitt outdoor humidity", "what is the air gradient temperature", "ag humidity 7d"): - assert intent.wants_air_extra(said) and intent.read(said, now).air_extra and "air_extra" in intent.topics(said), said - for said in ("plot humidity", "how hot is it", "air quality now", "plot pm2.5 and temperature", "what's the average humidity yesterday"): - assert not intent.wants_air_extra(said) and not intent.read(said, now).air_extra, said - - -def test_calendar_months_with_their_year_are_a_period_from_the_first_of_one_to_the_end_of_the_other(): - now = datetime(2026, 11, 7, 20, 18) - day = lambda *a: datetime(*a) - assert intent.spans_in("co2 chart oct 2025 to oct 2026", now) == [("Oct 2025 - Oct 2026", day(2025, 10, 1), day(2026, 10, 31, 23, 59, 59))] - assert intent.spans_in("rain between jan 2026 and March 2026", now)[0][1:] == (day(2026, 1, 1), day(2026, 3, 31, 23, 59, 59)) - assert intent.spans_in("humidity chart October 2025", now) == [("Oct 2025", day(2025, 10, 1), day(2025, 10, 31, 23, 59, 59))] - assert intent.spans_in("co2 chart nov 2025 - nov 2026", now)[0][2] == day(2026, 11, 7, 23, 59, 59) # up to today - read = intent.read("co2 chart oct 2025 to oct 2026", now, {"Ecowitt": 1, "AirGradient": 1}) - assert read.fast[1]["start_date"] == "2025-10-01 00:00:00" and read.fast[1]["end_date"] == "2026-10-31 23:59:59" - assert not intent.read("co2 chart dec 2026", now, {"AirGradient": 1}).chart_in_code # a month ahead: not the last day, the model's - - -def test_a_readings_full_history_is_the_longest_chart_and_history_alone_is_too_unless_a_period_is_named(): - now = datetime(2026, 11, 7, 20, 52) - for text in ("co2 full history", "co2 history", "full history of co2", "pm2.5 all history", "co2 whole history", "humidity history", - "temperature full history"): - read = intent.read(text, now, {"Ecowitt": 1, "AirGradient": 1}) - assert read.chart_in_code and read.fast[2].endswith("on record"), text # not the reading now - assert intent.spans_in("co2 history 7d", now)[0][0] == "last 7 days" - assert intent.spans_in("rain history this week", now)[0][0] == "last 7 days" - - -def test_values_at_an_interval_go_to_the_model_for_the_readings_tool_but_a_chart_of_them_is_still_drawn_in_code(): - for text in ("What was the humidity each hour for the last 5 hours", "temperature every 30 minutes today", "temperature every ten minutes today", - "temperature every half an hour today", "temperature every couple of hours today", "temperature in 15 minute increments today", - "pm2.5 every ten minutes today", "humidity hour by hour yesterday", "rain per hour today", - "highest hourly rain each month this year", "max rain per hour by month"): # (an hour's figure, never a day's) - assert call(text) is None, text - for text in ("hourly rain chart today", "rain per hour chart 7d", "plot hourly temperature today", "hourly pm2.5 chart 24h"): - assert intent.read(text, NOW).chart_in_code, text - for text in ("max wind speed in miles per hour this week", "highest gust in kilometres per hour this week", "max gust today in km/h per hour"): - assert call(text) is not None, text # a speed's unit, not an interval - assert intent.ALL.search("pm2.5 every ten minutes") is None and intent.ALL.search("everything every day") +def test_every_button_and_alert_chart_is_a_fixed_call(): + """The keyboard's chart buttons and the alerts' charts are fixed calls (no words read: step 6c), the same calls they were read as + before (Wind's is the gusts alert's).""" + calls = {**{s: templates.call(s) for s in templates.CALLS}, **{f"alert {kind}": call for kind, call in pictures.CHARTS.items()}} + assert calls == { + "Rain chart 1d": ("summary", {"readings": ["rain"], "period": "1d", "chart": True}), + "Weather chart 1d": ("summary", {"readings": ["weather"], "period": "1d", "chart": True}), + "Temperature chart 1d": ("summary", {"readings": ["temperature"], "period": "1d", "chart": True}), + "Humidity chart 1d": ("summary", {"readings": ["humidity"], "period": "1d", "chart": True}), + "Air quality all metrics 1d": ("summary", {"readings": ["air"], "period": "1d", "chart": True}), + "Particulates chart 1d": ("summary", {"readings": ["pm2.5", "pm10", "pm1"], "period": "1d", "chart": True}), + "Wind chart 1d": ("summary", {"readings": ["wind"], "period": "1d", "chart": True}), + "alert gusts": ("summary", {"readings": ["wind"], "period": "1d", "chart": True}), + "alert uv": ("summary", {"readings": ["uv"], "period": "1d", "chart": True}), + "alert temps": ("summary", {"readings": ["temperature"], "period": "1d", "chart": True}), + "alert particulates": ("summary", {"readings": ["pm2.5", "pm10", "pm1"], "period": "1d", "chart": True})} + first = templates.call("Rain chart 1d") + first[1]["period"] = "7d" # a copy each time: the button's own call stays + assert templates.call("Rain chart 1d")[1]["period"] == "1d" and templates.call("Report") is None and templates.call(None) is None + + +@pytest.mark.parametrize("text", ["status", "humidity 7d", "how hot is it", "thanks", "will it rain later?"]) +def test_the_effort_is_read_for_every_message(text): + assert intent.effort(text) == intent.reasoning_effort(text) + + +def test_a_phones_typographic_apostrophe_reads_as_a_plain_one(): + assert intent.effort("what’s yesterday been like?") == intent.reasoning_effort("what's yesterday been like?") == "low" diff --git a/tests/test_irrigation.py b/tests/test_irrigation.py index 652ced8a..ea683742 100644 --- a/tests/test_irrigation.py +++ b/tests/test_irrigation.py @@ -1,10 +1,9 @@ -"""The irrigation controller: the Tuya client, the keyboard, the daily check, the watchdog, and the buttons.""" +"""The bot's side of the irrigation controller (step 8b: the controller is irrigation-mcp's, and the bot its client at +BOT_IRRIGATION_MCP_URL): the status message and its keyboard, the Irrigation button and every ir: button run against irrigation-mcp in +memory (its real server over the fake controller, tests/served.py), its alerts delivered through the listen, and irrigation-mcp down. +(The controller's own code, without Telegram, is tests/test_irrigation_controller.py.)""" import asyncio -import hashlib -import hmac -import json -from datetime import datetime, timedelta from types import SimpleNamespace as NS import httpx @@ -12,17 +11,17 @@ from telegram.error import BadRequest import lib.bot as bot_module -from lib import templates -from lib.alerts import irrigation as monitor_module -from lib.alerts.irrigation import IrrigationMonitor +from lib import irrigation_menu as menu +from lib import irrigation_remote, templates from lib.alerts.menu import available_kinds -from lib.alerts.notify import AlertState +from lib.alerts.notify import AlertDelivery, AlertState, Notifier, ReadMark from lib.bot import Bot from lib.buttons import struck as strike -from lib.config import Config -from lib.irrigation import IrrigationError, Tuya, Watchdog, menu -from lib.irrigation.tuya import sign -from tests.fakes import TZ, config +from lib.irrigation import IrrigationError, Tuya +from lib.irrigation.common import IrrigationRefused +from lib.irrigation_remote import RemoteIrrigation +from tests.fakes import TZ, FakeController, tuya_config + @pytest.fixture(autouse=True) def settle_at_once(monkeypatch): @@ -30,135 +29,8 @@ def settle_at_once(monkeypatch): monkeypatch.setattr(bot_module, "IRRIGATION_SETTLE_SECONDS", 0) -SECRET = "s3cret" -STATUS = [{"code": "switch", "value": False}, {"code": "battery_percentage", "value": 100}, {"code": "weather_delay", "value": "cancel"}, - {"code": "countdown", "value": 0}, {"code": "work_state", "value": "idle"}, {"code": "use_time_one", "value": 40}] # as the controller answered - - -def cfg(tmp_path, **over): - return config(tmp_path, tuya_device_id="dev1", tuya_client_id="cid", tuya_client_secret=SECRET, **over) - - -class FakeTuya: - """Stands in for the Tuya cloud: records the signed requests it gets and checks each signature.""" - - def __init__(self, status=None, fail_token_once=False): - self.calls, self.status, self.token_n, self.fail_token_once = [], status if status is not None else STATUS, 0, fail_token_once - - def __call__(self, request: httpx.Request) -> httpx.Response: - h, path = request.headers, request.url.raw_path.decode() - body = request.content - token = h.get("access_token", "") - expected = sign("cid", SECRET, token, h["t"], h["nonce"], request.method, path, body) # signed over what was sent - assert h["sign"] == expected and h["client_id"] == "cid" and h["sign_method"] == "HMAC-SHA256" - if path.startswith("/v1.0/token"): - self.token_n += 1 - return httpx.Response(200, json={"success": True, "result": {"access_token": f"tok{self.token_n}", "expire_time": 7200}}) - self.calls.append((request.method, path, json.loads(body) if body else None, token)) - if self.fail_token_once and token == "tok1": - self.fail_token_once = False - return httpx.Response(200, json={"success": False, "code": 1010, "msg": "token invalid"}) - if path.endswith("/status"): - return httpx.Response(200, json={"success": True, "result": self.status}) - return httpx.Response(200, json={"success": True, "result": True}) - - -def tuya(tmp_path, **kw): - fake = FakeTuya(**kw) - return Tuya(cfg(tmp_path), transport=httpx.MockTransport(fake)), fake - - -def test_the_signature_is_hmac_sha256_of_the_ids_the_time_and_the_request(): - body = b'{"commands":[{"code":"switch","value":true}]}' - to_sign = f"POST\n{hashlib.sha256(body).hexdigest()}\n\n/v1.0/devices/d/commands" # the way the sample script builds it - want = hmac.new(b"sec", ("cid" + "tok" + "1700000000000" + "abc" + to_sign).encode(), hashlib.sha256).hexdigest().upper() - assert sign("cid", "sec", "tok", "1700000000000", "abc", "POST", "/v1.0/devices/d/commands", body) == want - empty = hashlib.sha256(b"").hexdigest() - assert sign("cid", "sec", "", "1", "n", "GET", "/v1.0/token?grant_type=1", b"") == hmac.new( - b"sec", f"cid1nGET\n{empty}\n\n/v1.0/token?grant_type=1".encode(), hashlib.sha256).hexdigest().upper() - - -async def test_status_is_read_as_code_and_value_and_the_token_is_fetched_once(tmp_path): - device, fake = tuya(tmp_path) - got = await device.status() - assert got == {"switch": False, "battery_percentage": 100, "weather_delay": "cancel", "countdown": 0, "work_state": "idle", "use_time_one": 40} - await device.status() - assert fake.token_n == 1 and [c[1] for c in fake.calls] == ["/v1.0/devices/dev1/status"] * 2 and fake.calls[0][3] == "tok1" - await device.close() - - -async def test_watering_sends_the_length_and_the_switch_in_one_command_and_other_commands_are_exact(tmp_path): - device, fake = tuya(tmp_path) - await device.water(10) - await device.delay("48h") - await device.set_switch(False) - assert [(m, p, b) for m, p, b, _ in fake.calls] == [ - ("POST", "/v1.0/devices/dev1/commands", {"commands": [{"code": "countdown", "value": 600}, {"code": "switch", "value": True}]}), - ("POST", "/v1.0/devices/dev1/commands", {"commands": [{"code": "weather_delay", "value": "48h"}]}), - ("POST", "/v1.0/devices/dev1/commands", {"commands": [{"code": "switch", "value": False}]})] - for bad in (0, 61, -5): - with pytest.raises(IrrigationError): - await device.water(bad) - with pytest.raises(IrrigationError): - await device.delay("96h") - assert len(fake.calls) == 3 # nothing was sent for the bad ones - - -async def test_an_expired_token_is_replaced_and_the_request_repeated_once(tmp_path): - device, fake = tuya(tmp_path, fail_token_once=True) - assert (await device.status())["battery_percentage"] == 100 - assert fake.token_n == 2 and [c[3] for c in fake.calls] == ["tok1", "tok2"] - - -async def test_errors_name_the_problem_without_the_secrets(tmp_path): - def refuse(request): - return httpx.Response(200, json={"success": False, "code": 1004, "msg": "sign invalid"}) - device = Tuya(cfg(tmp_path), transport=httpx.MockTransport(refuse)) - with pytest.raises(IrrigationError, match="1004"): - await device.status() - - def down(request): - raise httpx.ConnectError("no route to host https://openapi.tuyaeu.com?secret=" + SECRET) - device = Tuya(cfg(tmp_path), transport=httpx.MockTransport(down)) - with pytest.raises(IrrigationError) as e: - await device.status() - assert SECRET not in str(e.value) and "ConnectError" in str(e.value) - - -TOKEN = {"success": True, "result": {"access_token": "tok", "expire_time": 7200}} - - -@pytest.mark.parametrize("token, status", [({"success": True}, None), # a token reply with no token - ({"success": True, "result": ["tok"]}, None), - ([TOKEN], None), # a reply that isn't an object - (TOKEN, {"success": True, "result": {"switch": True}}), # a status that isn't a list - (TOKEN, "OK")]) -async def test_a_reply_of_an_unexpected_shape_is_an_irrigation_error(tmp_path, token, status): - def serve(request): - return httpx.Response(200, json=token if request.url.path.startswith("/v1.0/token") else status) - device = Tuya(cfg(tmp_path), transport=httpx.MockTransport(serve)) - with pytest.raises(IrrigationError): - await device.status() - await device.close() - - -async def test_status_points_with_no_value_or_no_code_are_read_safely(tmp_path): - device, fake = tuya(tmp_path, status=[{"code": "switch"}, "battery", {"value": 3}, {"code": "countdown", "value": 60}]) - assert await device.status() == {"switch": None, "countdown": 60} - await device.close() - - -def test_the_controller_is_on_only_with_all_three_settings_and_the_hour_is_read_safely(monkeypatch, tmp_path): - assert cfg(tmp_path).irrigation and not config(tmp_path).irrigation and not config(tmp_path, tuya_device_id="d", tuya_client_id="c").irrigation - env = {"TELEGRAM_BOT_TOKEN": "t", "OPENROUTER_API_KEY": "k", "ECOWITT_API_KEY": "a", "ECOWITT_APP_KEY": "b"} - for k, v in env.items(): - monkeypatch.setenv(k, v) - for value, hour in (("", 18), ("6", 6), ("0", 0), ("23", 23), ("24", 18), ("noon", 18), ("-1", 18)): - monkeypatch.setenv("IRRIGATION_CHECK_HOUR", value) - assert Config.from_env().irrigation_check_hour == hour, value - monkeypatch.setenv("TUYA_BASE_URL", "https://openapi.tuyaus.com/") - monkeypatch.setenv("TUYA_DEVICE_ID", " dev ") - assert Config.from_env().tuya_base_url == "https://openapi.tuyaus.com" and Config.from_env().tuya_device_id == "dev" +cfg = tuya_config +Remote = FakeController # (the controller behind irrigation-mcp) # ---------- the status message and its buttons ---------- @@ -234,222 +106,6 @@ def test_the_alert_list_gets_irrigation_battery_only_when_there_is_a_controller( assert ("irrigation battery", "al:off:irrigation_battery:alerts") in [b for row in listed for b in row] -# ---------- the daily check ---------- -class Device: - def __init__(self, **status): - self.status_now = {"switch": False, "battery_percentage": 100, "weather_delay": "cancel", "work_state": "idle", **status} - self.commands, self.down = [], False - - async def status(self): - if self.down: - raise IrrigationError("Tuya request failed (ConnectError)") - return dict(self.status_now) - - def _reachable(self): - if self.down: - raise IrrigationError("Tuya request failed (ConnectError)") - - async def delay(self, duration): - self._reachable() - self.commands.append(("delay", duration)) - self.status_now["weather_delay"] = duration # the controller reports it - - async def set_switch(self, on): - self._reachable() - self.commands.append(("switch", on)) - self.status_now["switch"] = on - - -class Station: - """The weather station: readings whose daily rain total rises by the given amounts.""" - - def __init__(self, *rises, fail=False): - total, self.rows, self.fail = 0.0, [], fail - for i, rise in enumerate(rises): - total += rise - self.rows.append((1_000_000 + i * 300, {"rainfall.daily": total})) - - async def recent(self, hours): - assert hours == 24 - if self.fail: - raise RuntimeError("Ecowitt is down") - return self.rows - - -class Forecast: - def __init__(self, *chances): - self.days = [{"date": datetime(2026, 10, 8 + i).date(), "rain_1mm_pct": c} for i, c in enumerate(chances)] + [ - {"date": datetime(2026, 10, 10).date(), "rain_1mm_pct": 90}] # the day after tomorrow never counts - self.fetched_at = datetime(2026, 10, 8, 17, 45, tzinfo=TZ).timestamp() - - def now(self): - return datetime(2026, 10, 8, 18, 0) - - def upcoming(self, count=2): - return self.days[:count] - - -NOW = datetime(2026, 10, 8, 18, 0) - - -def daily(tmp_path, device, station=None, forecast=None): - state, sent = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - sent.append((text, kw)) - return IrrigationMonitor(device, state, notify, TZ, 18, station, forecast), state, sent - - -@pytest.mark.parametrize("station, forecast, delayed", [ - (Station(0, 0.5, 0.4), Forecast(10, 20), False), # 0.9 mm: not more than 1 - (Station(0, 0.6, 0.6), Forecast(10, 20), True), # 1.2 mm fell - (Station(0, 0, 0), Forecast(10, 50), True), # tomorrow 50%: at the line - (Station(0, 0, 0), Forecast(55, 0), True), # today - (Station(0, 0, 0), Forecast(45, 49), False), # both under the line - (Station(0, 0, 0), Forecast(None, None), False), # no ensemble figure: nothing to go on - (None, Forecast(0, 80), True), # no station: the forecast decides - (Station(0, 3, 0), None, True), # no forecast: the measured rain decides - (Station(fail=True), Forecast(0, 80), True), # the station failing leaves the forecast - (Station(fail=True), Forecast(0, 0), False), - (None, None, False), - (Station(2, 0, 0), Forecast(0, 0), False), # the first reading's total fell before the window: only rises count -]) -async def test_the_check_delays_a_day_when_more_than_1_mm_fell_or_is_likely(tmp_path, station, forecast, delayed): - device = Device() - m, state, sent = daily(tmp_path, device, station, forecast) - await m.check(NOW) - assert device.commands == ([("delay", "24h")] if delayed else []) - assert [(text.startswith("☔ Irrigation paused for 24 hours: ") and text.endswith("."), kw) for text, kw in sent] == ( - [(True, {"kind": "irrigation_pause"})] if delayed else []) # told once when it paused, never otherwise - assert state.monitor["irrigation_monitor"]["checked"] == "2026-10-08" - - -async def test_a_delay_already_set_is_never_shortened_or_repeated(tmp_path): - device = Device(weather_delay="72h") - m, _, sent = daily(tmp_path, device, Station(0, 5), Forecast(90, 90)) - await m.check(NOW) - assert device.commands == [] and sent == [] # nothing changed: nothing to tell - - -async def test_the_bots_own_pause_from_yesterday_is_started_again_and_one_someone_set_is_not(tmp_path): - device = Device() - m, state, sent = daily(tmp_path, device, Station(0, 3)) - await m.check(NOW) # paused at 6pm - await m.check(NOW + timedelta(days=1)) # 6pm the next day: still on, for seconds - assert device.commands == [("delay", "24h"), ("delay", "cancel"), ("delay", "24h")] - assert sent[1][0] == "☔ Irrigation paused for another 24 hours: 3 mm of rain in the last 24 hours." - m.station = Station(0, 0) - await m.check(NOW + timedelta(days=2)) # dry: it lapses - m.station = Station(0, 3) - await m.check(NOW + timedelta(days=4)) # a 24h someone set (the bot's is days old) - assert len(device.commands) == 3 and len(sent) == 2 - - -async def test_a_forecast_more_than_a_day_old_does_not_decide(tmp_path, caplog): - stale = Forecast(90, 90) - stale.fetched_at -= 25 * 3600 - device = Device() - m, state, sent = daily(tmp_path, device, Station(0, 0), stale) - with caplog.at_level("INFO"): - await m.check(NOW) - assert device.commands == [] and sent == [] and "over a day old: only the measured rain decides" in caplog.text - - -async def test_a_battery_under_5_percent_is_told_once_a_day_to_the_irrigation_alert_type(tmp_path): - device = Device(battery_percentage=4) - m, state, sent = daily(tmp_path, device) - await m.check(NOW) - await m.check(NOW) - assert len(sent) == 1 and sent[0][1] == {"kind": "irrigation_battery"} and "4%" in sent[0][0] and "🪫" in sent[0][0] - await m.check(datetime(2026, 10, 9, 18, 0)) # the next day: again, until it is charged - assert len(sent) == 2 - device.status_now["battery_percentage"] = 5 # 5% is not below 5% - await m.check(datetime(2026, 10, 10, 18, 0)) - assert len(sent) == 2 - - -async def test_the_battery_is_still_told_when_the_delay_cannot_be_sent_and_not_told_twice_on_the_retry(tmp_path): - class Failing(Device): - async def delay(self, duration): - raise IrrigationError("Tuya error 28841002: no permission") - m, state, sent = daily(tmp_path, Failing(battery_percentage=2), None, Forecast(90, 90)) - with pytest.raises(IrrigationError): - await m.check(NOW) - assert len(sent) == 1 and "checked" not in state.monitor["irrigation_monitor"] # not recorded: the next try repeats the check - with pytest.raises(IrrigationError): - await m.check(NOW) - assert len(sent) == 1 and sent[0][1] == {"kind": "irrigation_battery"} # no "paused" alert for a pause that was not made - - -def test_a_check_is_due_once_a_day_after_the_hour_and_the_next_is_the_following_18_00(tmp_path): - m, state, _ = daily(tmp_path, Device()) - assert not m.due(datetime(2026, 10, 8, 17, 59)) and m.due(datetime(2026, 10, 8, 18, 0)) and m.due(datetime(2026, 10, 8, 23, 0)) - state.monitor["irrigation_monitor"] = {"checked": "2026-10-08"} - assert not m.due(datetime(2026, 10, 8, 23, 0)) and not m.due(datetime(2026, 10, 9, 3, 0)) and m.due(datetime(2026, 10, 9, 18, 0)) - assert m.seconds_until_next(datetime(2026, 10, 8, 17, 0)) == 3600 and m.seconds_until_next(datetime(2026, 10, 8, 18, 0)) == 86400 - assert m.seconds_until_next(datetime(2026, 10, 8, 23, 30)) == 18.5 * 3600 - assert m.seconds_until_next(datetime(2026, 10, 3, 18, 0)) == 23 * 3600 # the clocks go forward that night: 23 real hours, not 24 - - -async def test_run_checks_when_due_retries_after_a_failure_and_then_waits_for_tomorrow(tmp_path, monkeypatch): - device = Device() - device.down = True - m, state, _ = daily(tmp_path, device, None, Forecast(90, 90)) - sleeps = [] - - async def fake_sleep(seconds): - sleeps.append(seconds) - if len(sleeps) == 1: - device.down = False # the controller is back after the first wait - if len(sleeps) == 3: - raise asyncio.CancelledError - monkeypatch.setattr(monitor_module.asyncio, "sleep", fake_sleep) - monkeypatch.setattr(monitor_module, "now_local", lambda tz: NOW) - with pytest.raises(asyncio.CancelledError): - await m.run() - assert sleeps[0] == 1800 and device.commands == [("delay", "24h")] # tried, failed, waited 30 minutes, tried, did it - assert state.monitor["irrigation_monitor"]["checked"] == "2026-10-08" - assert sleeps[1] == 86400 # then until 18:00 tomorrow (now is exactly 18:00 here) - - -async def test_the_watchdog_closes_a_valve_that_is_still_open_after_the_run_and_survives_a_restart(tmp_path): - clock, state = [1000.0], AlertState(tmp_path / "s.json") - device = Device(switch=True) - dog = Watchdog(device, state, clock=lambda: clock[0]) - await dog.check() - assert device.commands == [] # nothing armed: the controller is not even asked - dog.arm(10) - clock[0] = 1000 + 600 + 29 - await dog.check() - assert device.commands == [] and dog.off_at # inside the grace period: the device's own countdown may still end it - clock[0] = 1000 + 600 + 31 - reborn = Watchdog(device, AlertState(tmp_path / "s.json"), clock=lambda: clock[0]) # the bot restarted in the middle of the run - await reborn.check() - assert device.commands == [("switch", False)] and reborn.off_at is None - - -async def test_the_watchdog_leaves_a_closed_valve_alone_tries_again_on_failure_and_disarms_on_request(tmp_path): - clock, state = [0.0], AlertState(tmp_path / "s.json") - device = Device(switch=False) - dog = Watchdog(device, state, clock=lambda: clock[0]) - dog.arm(5) - clock[0] = 400 - await dog.check() - assert device.commands == [] and dog.off_at is None # it ended by itself - dog.arm(5) - device.down, device.status_now["switch"] = True, True - clock[0] = 800 - with pytest.raises(IrrigationError): - await dog.check() - assert dog.off_at is not None # kept: the next minute tries again - device.down = False - await dog.check() - assert device.commands == [("switch", False)] - dog.arm(5) - dog.disarm() - assert dog.off_at is None - - # ---------- the buttons in the bot ---------- class Query: def __init__(self, data, chat_id=1, chat_type="private", user=7): @@ -470,20 +126,31 @@ async def edit_message_text(self, text, reply_markup=None, entities=None): self.edits.append(("text", text, reply_markup) + ((entities,) if entities else ())) -class Remote(Device): - """The controller as the bot's buttons see it: also water().""" - - async def water(self, minutes): - self._reachable() - self.commands.append(("water", minutes)) - self.status_now.update(switch=True, work_state="manual", countdown=minutes * 60) +WEATHER = SERVE_IRRIGATION = None -def irrigation_bot(tmp_path, device=None): +@pytest.fixture(autouse=True) +async def ecobot_mcp(serve, serve_irrigation): + """ecobot-mcp in memory with the weather station, the bot's client of it connected: what the bots here run over; and the way to + irrigation-mcp in memory (serve_irrigation).""" + global WEATHER, SERVE_IRRIGATION + WEATHER, SERVE_IRRIGATION = await serve(tools=[], sources=["Ecowitt"]), serve_irrigation + yield WEATHER + WEATHER = SERVE_IRRIGATION = None + + +async def irrigation_bot(tmp_path, device=None): + """A bot whose irrigation is irrigation-mcp in memory over `device` (default: the fake controller): (the bot, its state, the + controller behind irrigation-mcp).""" state = AlertState(tmp_path / "s.json") state.add_chat(1, "Rob") - device = device or Remote() - return Bot(NS(tz=TZ), None, [NS(name="Ecowitt")], state, device), state, device + irrigation = await SERVE_IRRIGATION(tmp_path, device or Remote()) + return Bot(NS(tz=TZ), None, state, irrigation, service=WEATHER), state, irrigation.server.device + + +def watched(bot): + """When irrigation-mcp's watchdog closes the valve (None: no run watched).""" + return bot.irrigation.server.watchdog.off_at async def press(bot, data, **kw): @@ -493,7 +160,7 @@ async def press(bot, data, **kw): async def test_the_button_sends_the_status_with_its_buttons_and_a_failure_says_so(tmp_path): - bot, state, device = irrigation_bot(tmp_path) + bot, state, device = await irrigation_bot(tmp_path) sent = [] async def reply_text(body, **kw): @@ -512,7 +179,7 @@ async def reply_text(body, **kw): async def test_an_odd_reply_from_the_controller_is_a_toast_not_a_press_left_hanging(tmp_path): def odd(request): return httpx.Response(200, json=["not", "a", "reply"]) - bot, state, device = irrigation_bot(tmp_path, Tuya(cfg(tmp_path), transport=httpx.MockTransport(odd))) + bot, state, device = await irrigation_bot(tmp_path, Tuya(cfg(tmp_path), transport=httpx.MockTransport(odd))) # (irrigation-mcp's) q = await press(bot, "ir:refresh") assert q.toast == "Couldn't reach the irrigation controller" and q.edits == [] await device.close() @@ -523,13 +190,13 @@ class Lost(Remote): async def water(self, minutes): await super().water(minutes) # the valve opened raise IrrigationError("Tuya request failed (ReadTimeout)") # but the reply never came - bot, state, device = irrigation_bot(tmp_path, Lost()) + bot, state, device = await irrigation_bot(tmp_path, Lost()) q = await press(bot, "ir:water:10") - assert q.toast == "Couldn't reach the irrigation controller" and bot.watchdog.off_at is not None + assert q.toast == "Couldn't reach the irrigation controller" and watched(bot) is not None async def test_opening_and_closing_a_section_only_changes_the_buttons(tmp_path): - bot, _, device = irrigation_bot(tmp_path) + bot, _, device = await irrigation_bot(tmp_path) q = await press(bot, "ir:open:water") assert q.edits[0][0] == "markup" and rows(q.edits[0][1])[-1][0] == ("5 min", "ir:water:5") and device.commands == [] q = await press(bot, "ir:close") @@ -540,13 +207,13 @@ async def test_opening_and_closing_a_section_only_changes_the_buttons(tmp_path): async def test_watering_a_delay_and_the_switch_act_on_the_controller_and_refresh_the_message(tmp_path): - bot, state, device = irrigation_bot(tmp_path) + bot, state, device = await irrigation_bot(tmp_path) q = await press(bot, "ir:water:10") - assert device.commands == [("water", 10)] and q.toast == "Watering for 10 minutes" and bot.watchdog.off_at + assert device.commands == [("water", 10)] and q.toast == "Watering for 10 minutes" and watched(bot) assert q.edits[0][0] == "text" and "state: on ✅" in q.edits[0][1] and "mode: manual" in q.edits[0][1] assert "state: on ✅ (10 mins until off)" in q.edits[0][1] q = await press(bot, "ir:sw:off") - assert device.commands[-1] == ("switch", False) and q.toast == "Switched off" and bot.watchdog.off_at is None and "state: off ❌" in q.edits[0][1] + assert device.commands[-1] == ("switch", False) and q.toast == "Switched off" and watched(bot) is None and "state: off ❌" in q.edits[0][1] q = await press(bot, "ir:delay:72h") assert device.commands[-1] == ("delay", "72h") and q.toast == "Paused 72h" q = await press(bot, "ir:delay:cancel") @@ -559,7 +226,7 @@ async def test_watering_a_delay_and_the_switch_act_on_the_controller_and_refresh async def test_the_alerts_menu_toggles_each_alert_type_for_this_chat_alone_and_stays_open(tmp_path): - bot, state, _ = irrigation_bot(tmp_path) + bot, state, _ = await irrigation_bot(tmp_path) q = await press(bot, "ir:open:alerts") assert q.edits[0][0] == "markup" and [r[0][0] for r in rows(q.edits[0][1])[1:]] == ["battery alerts", "pause alerts"] q = await press(bot, "ir:batt:off") @@ -586,7 +253,7 @@ async def test_the_alerts_menu_toggles_each_alert_type_for_this_chat_alone_and_s async def test_a_controller_that_cannot_be_reached_gives_a_toast_not_a_traceback_and_an_unchanged_message_is_fine(tmp_path): - bot, state, device = irrigation_bot(tmp_path) + bot, state, device = await irrigation_bot(tmp_path) device.down = True q = await press(bot, "ir:delay:24h") assert q.toast == "Couldn't reach the irrigation controller" and q.edits == [] @@ -597,17 +264,17 @@ async def test_a_controller_that_cannot_be_reached_gives_a_toast_not_a_traceback q.fail = BadRequest("Message to edit not found") with pytest.raises(BadRequest): await bot.on_irrigation_button(NS(callback_query=q), NS()) - plain = Bot(NS(tz=TZ), None, [], AlertState(tmp_path / "t.json")) # no controller configured: nothing happens + plain = Bot(NS(tz=TZ), None, AlertState(tmp_path / "t.json"), service=WEATHER) # no controller configured: nothing happens q = await press(plain, "ir:delay:24h") - assert q.edits == [] and plain.watchdog is None + assert q.edits == [] and plain.irrigation is None async def test_the_handler_is_registered_and_the_alert_list_includes_irrigation_only_with_a_controller(tmp_path): - bot, state, _ = irrigation_bot(tmp_path) + bot, state, _ = await irrigation_bot(tmp_path) added = [] app = NS(add_handler=lambda h, group=0: added.append(h), add_error_handler=lambda h: None) bot.register(app) - plain = Bot(NS(tz=TZ), None, [NS(name="Ecowitt")], AlertState(tmp_path / "t.json")) + plain = Bot(NS(tz=TZ), None, AlertState(tmp_path / "t.json"), service=WEATHER) added_plain = [] plain.register(NS(add_handler=lambda h, group=0: added_plain.append(h), add_error_handler=lambda h: None)) assert len(added) == len(added_plain) # one entry point for every button, with or without a controller @@ -653,7 +320,7 @@ async def run(self, *a, **k): async def test_typing_irrigation_does_what_the_button_does_in_private_chats_and_when_addressed_in_groups(tmp_path): - bot, state, device = irrigation_bot(tmp_path) + bot, state, device = await irrigation_bot(tmp_path) bot.agent = NoModel() ctx = NS(bot=NS(username="testbot", id=99)) for text in ("irrigation", "water", "turn the sprinkler on", templates.IRRIGATION): @@ -683,11 +350,11 @@ async def run(self, working, *a, **k): async def quiet(*a, **k): pass ctx = NS(bot=NS(username="testbot", id=99, send_chat_action=quiet, send_message_draft=quiet)) # the model is asked: "typing..." and a draft go first - bot = Bot(NS(tz=TZ), Agent(), [], state, Remote()) + bot = Bot(NS(tz=TZ), Agent(), state, await SERVE_IRRIGATION(tmp_path), service=WEATHER) update, sent = private_message("how much water did the rain add this week") await bot.on_message(update, ctx) assert asked == ["how much water did the rain add this week"] - plain = Bot(NS(tz=TZ), Agent(), [], AlertState(tmp_path / "t.json")) + plain = Bot(NS(tz=TZ), Agent(), AlertState(tmp_path / "t.json"), service=WEATHER) update, sent = private_message("irrigation") await plain.on_message(update, ctx) assert asked[-1] == "irrigation" # nothing to show: the model answers as before @@ -695,17 +362,17 @@ async def quiet(*a, **k): async def test_the_message_is_redrawn_a_couple_of_seconds_after_a_command_and_shows_the_chat_s_battery_alerts(tmp_path, monkeypatch): monkeypatch.setattr(bot_module, "IRRIGATION_SETTLE_SECONDS", 3) - bot, state, device = irrigation_bot(tmp_path) + bot, state, device = await irrigation_bot(tmp_path) events = [] async def sleep(seconds): events.append(("sleep", seconds)) - original_status = device.status + original_status = bot.irrigation.status - async def status(): + async def status(): # (the bot's reads, over irrigation-mcp) events.append(("status",)) return await original_status() - device.status = status + bot.irrigation.status = status monkeypatch.setattr(bot_module.asyncio, "sleep", sleep) q = await press(bot, "ir:water:5") assert events == [("status",), ("sleep", 3), ("status",)] and q.toast == "Watering for 5 minutes" # a look at the pause, the command, a wait, the fresh state @@ -726,7 +393,7 @@ async def status(): async def test_a_status_that_cannot_be_read_after_a_command_leaves_the_message_alone(tmp_path): - bot, state, device = irrigation_bot(tmp_path) + bot, state, device = await irrigation_bot(tmp_path) async def delay(duration): device.commands.append(("delay", duration)) @@ -736,53 +403,60 @@ async def delay(duration): assert device.commands == [("delay", "48h")] and q.toast == "Paused 48h" and q.edits == [] -@pytest.mark.parametrize("station, forecast, why", [ - (Station(0, 0.6, 0.6), None, "1.2 mm of rain in the last 24 hours"), - (None, Forecast(10, 50), "50% chance of at least 1 mm tomorrow"), - (None, Forecast(55, 0), "55% chance of at least 1 mm today"), - (Station(0, 3, 0), Forecast(90, 90), "3 mm of rain in the last 24 hours"), # what fell comes first -]) -async def test_the_pause_alert_says_why(tmp_path, station, forecast, why): - m, _, sent = daily(tmp_path, Device(), station, forecast) - await m.check(NOW) - assert sent == [(f"☔ Irrigation paused for 24 hours: {why}.", {"kind": "irrigation_pause"})] - - -async def test_a_pause_that_fails_and_is_retried_is_told_exactly_once(tmp_path): - class Flaky(Device): - failures = 1 # the first command is refused, the second goes through - - async def delay(self, duration): - if self.failures: - self.failures -= 1 - raise IrrigationError("Tuya request failed (ConnectError)") - await super().delay(duration) - device = Flaky() - m, state, sent = daily(tmp_path, device, None, Forecast(90, 90)) - with pytest.raises(IrrigationError): - await m.check(NOW) - assert sent == [] and "checked" not in state.monitor["irrigation_monitor"] # nothing told for a pause that was not made - await m.check(NOW) - assert device.commands == [("delay", "24h")] and len(sent) == 1 and state.monitor["irrigation_monitor"]["checked"] == "2026-10-08" - - -async def test_the_pause_alert_reaches_every_subscribed_chat_with_the_usual_menu(tmp_path): - from lib.alerts.notify import Notifier + +async def until(check, seconds: float = 10.0, what: str = "it"): + deadline = asyncio.get_running_loop().time() + seconds + while not check(): + if asyncio.get_running_loop().time() > deadline: + raise AssertionError(f"timed out waiting for {what}") + await asyncio.sleep(0.02) + + +async def test_an_irrigation_alert_reaches_every_subscribed_chat_through_the_listen_once_with_the_usual_menu(tmp_path): + """irrigation-mcp's daily check appends to its own alert log (irrigation://alerts); the bot hears it through its listen and delivers + it as it delivers ecobot-mcp's: to the chats subscribed to its kind, with the alert's menu, its last id kept apart in bot_state.json, + nothing sent twice (a reconnect reads once; a restart resumes after it).""" state, delivered = AlertState(tmp_path / "s.json"), [] for chat in (1, 2, 3, -7): state.add_chat(chat, str(chat)) state.set_kind(2, "irrigation_pause", False) # this chat turned the pause alerts off - state.set_kind(3, "irrigation_battery", False) # ... and this one only the battery alerts: it still gets the pause + state.set_kind(3, "irrigation_battery", False) # ... and this one only the battery alerts: it still gets the pause class Telegram: async def send_message(self, chat_id, text, **kw): delivered.append((chat_id, text, kw)) - notifier = Notifier(Telegram(), state) - m = IrrigationMonitor(Device(), state, notifier, TZ, 18, None, Forecast(90, 90)) - await m.check(NOW) + irrigation = await SERVE_IRRIGATION(tmp_path) + mark = ReadMark(state, irrigation_remote.NAME) + + async def delivering(state, mark): + delivery = AlertDelivery(irrigation.alerts, Notifier(Telegram(), state), state, TZ, mark=mark) + task = asyncio.create_task(delivery.run()) + await until(lambda: delivery.begun and mark.read is not None, what="the delivery to begin") + return task + task = await delivering(state, mark) + await irrigation.server.notify("☔ Irrigation paused for 24 hours: 90% chance of at least 1 mm today.", kind="irrigation_pause") + await until(lambda: len(delivered) == 3, what="the pause alert") assert sorted(c for c, _, _ in delivered) == [-7, 1, 3] and all(text.startswith("☔ Irrigation paused") for _, text, _ in delivered) - markup = delivered[0][2]["reply_markup"] - assert rows(markup) == [[("🔔 ▸", "al:open:bell:irrigation_pause")]] + assert rows(delivered[0][2]["reply_markup"]) == [[("🔔 ▸", "al:open:bell:irrigation_pause")]] + await irrigation.server.notify("🪫 The irrigation battery is at 4%.", kind="irrigation_battery") + await until(lambda: len(delivered) == 6, what="the battery alert") + assert sorted(c for c, text, _ in delivered if "battery" in text) == [-7, 1, 2] + saved = AlertState(tmp_path / "s.json") + assert saved.marks[irrigation_remote.NAME]["read"] == 2 and saved.read is None # (ecobot-mcp's own mark untouched) + irrigation.alerts.changed() # (as a reconnect does: read once, nothing new) + await asyncio.sleep(0.2) + task.cancel() + await asyncio.gather(task, return_exceptions=True) + restarted = AlertState(tmp_path / "s.json") # the bot restarted: it resumes after the last one + task = await delivering(restarted, ReadMark(restarted, irrigation_remote.NAME)) + await asyncio.sleep(0.2) + assert len(delivered) == 6 + await irrigation.server.notify("☔ Irrigation paused for another 24 hours: 3 mm of rain in the last 24 hours.", kind="irrigation_pause") + await until(lambda: len(delivered) == 9, what="the next alert") + await asyncio.sleep(0.2) + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert len(delivered) == 9 and [t for _, t, _ in delivered].count(delivered[0][1]) == 3 # each alert once per chat from lib.alerts.menu import alert_keyboard, keyboard kinds = available_kinds({"Ecowitt", "AirGradient", "Pollen", "Forecast", "Irrigation"}) boards = [keyboard(set(), kinds, section, set()) for section in (None, "alerts", "sound")] @@ -791,6 +465,56 @@ async def send_message(self, chat_id, text, **kw): assert all(len(data.encode()) <= 64 for row in rows(board) for _, data in row) +async def test_at_the_bots_first_start_the_irrigation_alerts_not_yet_expired_are_delivered_once(tmp_path): + """irrigation-mcp starts before the bot (its unit, and after an upgrade its first daily check can run at once): the alerts it logged + before the bot first read its log, those not yet expired, are delivered at the bot's first start (unexpired_first), once; ecobot-mcp's + delivery (without it) still begins after the newest.""" + state, delivered = AlertState(tmp_path / "s.json"), [] + state.add_chat(1, "1") + + class Telegram: + async def send_message(self, chat_id, text, **kw): + delivered.append((chat_id, text)) + irrigation = await SERVE_IRRIGATION(tmp_path) + log_ = irrigation.server.alert_log + log_.append("irrigation_pause", "☔ an old pause", "Irrigation paused for rain", expires=log_.now() - 60) # (expired: not news) + await irrigation.server.notify("🪫 The irrigation battery is at 3%.", kind="irrigation_battery") + + async def delivering(state, **kw): + mark = ReadMark(state, irrigation_remote.NAME) + delivery = AlertDelivery(irrigation.alerts, Notifier(Telegram(), state), state, TZ, mark=mark, **kw) + task = asyncio.create_task(delivery.run()) + await until(lambda: delivery.begun and mark.read is not None, what="the delivery to begin") + await asyncio.sleep(0.2) + task.cancel() + await asyncio.gather(task, return_exceptions=True) + return mark + assert (await delivering(AlertState(tmp_path / "other.json"))).read == 2 and delivered == [] # (without: after the newest) + mark = await delivering(state, unexpired_first=True) + assert delivered == [(1, "🪫 The irrigation battery is at 3%.")] and mark.read == 2 + await delivering(AlertState(tmp_path / "s.json"), unexpired_first=True) # a restart: nothing again + assert len(delivered) == 1 + + +async def test_irrigation_mcp_down_the_button_says_it_cant_reach_the_controller_and_the_bot_carries_on(tmp_path, monkeypatch): + monkeypatch.setattr(irrigation_remote, "CALL_WAIT", 0.2) + state = AlertState(tmp_path / "s.json") + state.add_chat(1, "Rob") + down = RemoteIrrigation("http://127.0.0.1:9/mcp") # nothing answers there (its supervisor not even started) + bot = Bot(NS(tz=TZ), None, state, down, service=WEATHER) + update, sent = private_message(templates.IRRIGATION) + await bot.on_message(update, NS(bot=NS(username="testbot", id=99))) + assert sent == [("Sorry, I couldn't reach the irrigation controller.", {})] + q = await press(bot, "ir:water:5") + assert q.toast == "Couldn't reach the irrigation controller" and q.edits == [] + q = await press(bot, "ir:open:water") # what needs no controller still works + assert q.edits[0][0] == "markup" + q = await press(bot, "ir:batt:off") # and so do the chat's own alert settings + assert q.toast == "Irrigation battery alerts off in this chat" and state.muted(1) == {"irrigation_battery"} + with pytest.raises(IrrigationError, match="irrigation-mcp isn't reachable"): + await down.status() + + async def test_refresh_reads_the_controller_again_and_redraws_without_sending_anything_or_waiting(tmp_path, monkeypatch): monkeypatch.setattr(bot_module, "IRRIGATION_SETTLE_SECONDS", 3) slept = [] @@ -798,7 +522,7 @@ async def test_refresh_reads_the_controller_again_and_redraws_without_sending_an async def sleep(seconds): slept.append(seconds) monkeypatch.setattr(bot_module.asyncio, "sleep", sleep) - bot, state, device = irrigation_bot(tmp_path) + bot, state, device = await irrigation_bot(tmp_path) device.status_now.update(switch=True, countdown=300, work_state="auto") # changed on the controller (its own schedule, or the app) q = await press(bot, "ir:refresh") assert q.toast == "Refreshed" and device.commands == [] and slept == [] @@ -815,7 +539,7 @@ async def sleep(seconds): async def test_every_member_of_a_group_may_use_the_irrigation_buttons(tmp_path): - bot, state, device = irrigation_bot(tmp_path) + bot, state, device = await irrigation_bot(tmp_path) state.add_chat(-5, "Home") group = dict(chat_id=-5, chat_type="supergroup", user=42) # an ordinary member: no admin check is made q = await press(bot, "ir:open:water", **group) @@ -850,13 +574,13 @@ async def sleep(seconds): slept.append(seconds) monkeypatch.setattr(bot_module, "IRRIGATION_SETTLE_SECONDS", 3) monkeypatch.setattr(bot_module.asyncio, "sleep", sleep) - bot, state, device = irrigation_bot(tmp_path) + bot, state, device = await irrigation_bot(tmp_path) await press(bot, "ir:delay:48h") # paused device.commands.clear() slept.clear() for minutes in (5, 30): q = await press(bot, f"ir:water:{minutes}") - assert device.commands == [] and bot.watchdog.off_at is None and slept == [] # nothing sent, no run to watch, no wait + assert device.commands == [] and watched(bot) is None and slept == [] # nothing sent, no run to watch, no wait assert q.toast == "error: can not turn on water while paused!" kind, text, markup, entities = q.edits[0] assert text.startswith("🌱 Irrigation\nmode: idle\nstate: off ❌\npause: 48h") and text.endswith("\n\nerror: can not turn on water while paused!") @@ -868,11 +592,36 @@ async def sleep(seconds): await press(bot, "ir:delay:cancel") # unpaused: water works again q = await press(bot, "ir:water:10") assert device.commands[-1] == ("water", 10) and q.toast == "Watering for 10 minutes" and "error:" not in q.edits[0][1] - assert bot.watchdog.off_at and slept[-1] == 3 + assert watched(bot) and slept[-1] == 3 + + +async def test_water_refused_by_irrigation_mcp_after_the_status_read_says_paused_not_unreachable(tmp_path): + """A pause that begins between the bot's status read and its water call (the daily check's): irrigation-mcp refuses the water; the + bot says why (the paused toast), not that it couldn't reach the controller. Another refusal's own message is the toast.""" + bot, state, device = await irrigation_bot(tmp_path) + remote = bot.irrigation + real = remote.status + + async def read_before_the_pause(): + status = await real() + device.status_now["weather_delay"] = "24h" # (the pause begins just after the read) + return status + remote.status = read_before_the_pause + q = await press(bot, "ir:water:5") + assert q.toast == menu.PAUSED_ERROR and device.commands == [] and watched(bot) is None + with pytest.raises(IrrigationRefused, match="paused") as refused: + await remote.water(5) + assert refused.value.paused + with pytest.raises(IrrigationRefused, match="from 1 to 60") as refused: + await remote.water(61) + assert not refused.value.paused + remote.status = real + query = Query("ir:water:61") + assert await bot._controller(query, remote.water(61), "water 61") is None and query.toast.startswith("minutes is a whole number") async def test_water_while_the_status_cannot_be_read_says_so_and_sends_nothing(tmp_path): - bot, state, device = irrigation_bot(tmp_path) + bot, state, device = await irrigation_bot(tmp_path) device.down = True q = await press(bot, "ir:water:5") assert q.toast == "Couldn't reach the irrigation controller" and q.edits == [] and device.commands == [] @@ -887,7 +636,7 @@ def test_a_status_message_says_whether_it_is_paused(): async def test_while_paused_the_button_is_unpause_and_one_press_ends_the_pause(tmp_path): - bot, state, device = irrigation_bot(tmp_path) + bot, state, device = await irrigation_bot(tmp_path) update, sent = private_message("irrigation") await bot.on_message(update, NS(bot=NS(username="testbot", id=99))) assert rows(sent[0][1]["reply_markup"])[0][1] == ("⏸ Pause ▸", "ir:open:delay") # not paused diff --git a/tests/test_irrigation_controller.py b/tests/test_irrigation_controller.py new file mode 100644 index 00000000..60d2c412 --- /dev/null +++ b/tests/test_irrigation_controller.py @@ -0,0 +1,394 @@ +"""irrigation-mcp's controller code, without Telegram (step 8b moved it out of the bot): the Tuya client (signed requests, the token, +its errors), the daily check (rain measured or likely, the battery, its days) and the watchdog that closes the valve after a run. +(The bot's menu and buttons, which call irrigation-mcp, are tests/test_irrigation.py; the server's tools tests/test_irrigation_mcp.py.)""" + +import asyncio +import hashlib +import hmac +from datetime import datetime, timedelta + +import httpx +import pytest + +from lib.config import Config +from lib.irrigation import IrrigationError, Tuya, Watchdog +from lib.irrigation import check as monitor_module +from lib.irrigation.check import IrrigationMonitor +from lib.irrigation.state import IrrigationState +from lib.irrigation.tuya import sign +from tests.fakes import TUYA_SECRET as SECRET, TZ, FakeController, FakeTuya, config, tuya_config +from tests.test_mcp_listen import until + +cfg = tuya_config +Device = FakeController # (the controller as the check and the watchdog see it) + +def tuya(tmp_path, **kw): + fake = FakeTuya(**kw) + return Tuya(cfg(tmp_path), transport=httpx.MockTransport(fake)), fake + + +def test_the_signature_is_hmac_sha256_of_the_ids_the_time_and_the_request(): + body = b'{"commands":[{"code":"switch","value":true}]}' + to_sign = f"POST\n{hashlib.sha256(body).hexdigest()}\n\n/v1.0/devices/d/commands" # the way the sample script builds it + want = hmac.new(b"sec", ("cid" + "tok" + "1700000000000" + "abc" + to_sign).encode(), hashlib.sha256).hexdigest().upper() + assert sign("cid", "sec", "tok", "1700000000000", "abc", "POST", "/v1.0/devices/d/commands", body) == want + empty = hashlib.sha256(b"").hexdigest() + assert sign("cid", "sec", "", "1", "n", "GET", "/v1.0/token?grant_type=1", b"") == hmac.new( + b"sec", f"cid1nGET\n{empty}\n\n/v1.0/token?grant_type=1".encode(), hashlib.sha256).hexdigest().upper() + + +async def test_status_is_read_as_code_and_value_and_the_token_is_fetched_once(tmp_path): + device, fake = tuya(tmp_path) + got = await device.status() + assert got == {"switch": False, "battery_percentage": 100, "weather_delay": "cancel", "countdown": 0, "work_state": "idle", "use_time_one": 40} + await device.status() + assert fake.token_n == 1 and [c[1] for c in fake.calls] == ["/v1.0/devices/dev1/status"] * 2 and fake.calls[0][3] == "tok1" + await device.close() + + +async def test_watering_sends_the_length_and_the_switch_in_one_command_and_other_commands_are_exact(tmp_path): + device, fake = tuya(tmp_path) + await device.water(10) + await device.delay("48h") + await device.set_switch(False) + assert [(m, p, b) for m, p, b, _ in fake.calls] == [ + ("POST", "/v1.0/devices/dev1/commands", {"commands": [{"code": "countdown", "value": 600}, {"code": "switch", "value": True}]}), + ("POST", "/v1.0/devices/dev1/commands", {"commands": [{"code": "weather_delay", "value": "48h"}]}), + ("POST", "/v1.0/devices/dev1/commands", {"commands": [{"code": "switch", "value": False}]})] + for bad in (0, 61, -5): + with pytest.raises(IrrigationError): + await device.water(bad) + with pytest.raises(IrrigationError): + await device.delay("96h") + assert len(fake.calls) == 3 # nothing was sent for the bad ones + + +async def test_an_expired_token_is_replaced_and_the_request_repeated_once(tmp_path): + device, fake = tuya(tmp_path, fail_token_once=True) + assert (await device.status())["battery_percentage"] == 100 + assert fake.token_n == 2 and [c[3] for c in fake.calls] == ["tok1", "tok2"] + + +async def test_errors_name_the_problem_without_the_secrets(tmp_path): + def refuse(request): + return httpx.Response(200, json={"success": False, "code": 1004, "msg": "sign invalid"}) + device = Tuya(cfg(tmp_path), transport=httpx.MockTransport(refuse)) + with pytest.raises(IrrigationError, match="1004"): + await device.status() + + def down(request): + raise httpx.ConnectError("no route to host https://openapi.tuyaeu.com?secret=" + SECRET) + device = Tuya(cfg(tmp_path), transport=httpx.MockTransport(down)) + with pytest.raises(IrrigationError) as e: + await device.status() + assert SECRET not in str(e.value) and "ConnectError" in str(e.value) + + +TOKEN = {"success": True, "result": {"access_token": "tok", "expire_time": 7200}} + + +@pytest.mark.parametrize("token, status", [({"success": True}, None), # a token reply with no token + ({"success": True, "result": ["tok"]}, None), + ([TOKEN], None), # a reply that isn't an object + (TOKEN, {"success": True, "result": {"switch": True}}), # a status that isn't a list + (TOKEN, "OK")]) +async def test_a_reply_of_an_unexpected_shape_is_an_irrigation_error(tmp_path, token, status): + def serve(request): + return httpx.Response(200, json=token if request.url.path.startswith("/v1.0/token") else status) + device = Tuya(cfg(tmp_path), transport=httpx.MockTransport(serve)) + with pytest.raises(IrrigationError): + await device.status() + await device.close() + + +async def test_status_points_with_no_value_or_no_code_are_read_safely(tmp_path): + device, fake = tuya(tmp_path, status=[{"code": "switch"}, "battery", {"value": 3}, {"code": "countdown", "value": 60}]) + assert await device.status() == {"switch": None, "countdown": 60} + await device.close() + + +def test_the_controller_is_on_only_with_all_three_settings_and_the_hour_is_read_safely_by_irrigation_mcp_alone(monkeypatch, tmp_path): + assert cfg(tmp_path).irrigation and not config(tmp_path).irrigation and not config(tmp_path, tuya_device_id="d", tuya_client_id="c").irrigation + env = {"BOT_TELEGRAM_TOKEN": "t", "BOT_OPENROUTER_API_KEY": "k", "BOT_MCP_URL": "http://127.0.0.1:8765/mcp", + "IRRIGATION_TUYA_DEVICE_ID": " dev ", "IRRIGATION_TUYA_CLIENT_ID": "cid", "IRRIGATION_TUYA_CLIENT_SECRET": "sec"} + for k, v in env.items(): + monkeypatch.setenv(k, v) + for value, hour in (("", 18), ("6", 6), ("0", 0), ("23", 23), ("24", 18), ("noon", 18), ("-1", 18)): + monkeypatch.setenv("IRRIGATION_CHECK_HOUR", value) + assert Config.from_env(program="irrigation").irrigation_check_hour == hour, value + monkeypatch.setenv("IRRIGATION_TUYA_BASE_URL", "https://openapi.tuyaus.com/") + irrigation = Config.from_env(program="irrigation") + assert irrigation.tuya_base_url == "https://openapi.tuyaus.com" and irrigation.tuya_device_id == "dev" and irrigation.irrigation + bot = Config.from_env() # the bot reads none of them (step 8b) + assert not bot.irrigation and bot.tuya_device_id == "" and bot.irrigation_mcp_url == "" + + +# ---------- the daily check ---------- +class Station: + """The weather station: readings whose daily rain total rises by the given amounts.""" + + def __init__(self, *rises, fail=False): + total, self.rows, self.fail = 0.0, [], fail + for i, rise in enumerate(rises): + total += rise + self.rows.append((1_000_000 + i * 300, {"rainfall.daily": total})) + + async def rain_mm(self, hours): + """The measured rain as ecobot-mcp's summary of the rain gives it (lib/irrigation/ecobot.ServiceRain): the rises of the daily total.""" + from lib.ecowitt.rain import rain_amount + assert hours == 24 + if self.fail: + raise RuntimeError("Ecowitt is down") + return rain_amount(self.rows, self.rows[0][0], self.rows[-1][0]) if self.rows else None + + +class Forecast: + def __init__(self, *chances): + self.days = [{"date": datetime(2026, 10, 8 + i).date(), "rain_1mm_pct": c} for i, c in enumerate(chances)] + [ + {"date": datetime(2026, 10, 10).date(), "rain_1mm_pct": 90}] # the day after tomorrow never counts + self.fetched_at = datetime(2026, 10, 8, 17, 45, tzinfo=TZ).timestamp() + + def now(self): + return datetime(2026, 10, 8, 18, 0) + + def upcoming(self, count=2): + return self.days[:count] + + +NOW = datetime(2026, 10, 8, 18, 0) + + +def daily(tmp_path, device, station=None, forecast=None): + state, sent = IrrigationState(tmp_path / "irrigation_state.json"), [] + + async def notify(text, link=None, **kw): + sent.append((text, kw)) + return IrrigationMonitor(device, state, notify, TZ, 18, station, forecast), state, sent + + +@pytest.mark.parametrize("station, forecast, delayed", [ + (Station(0, 0.5, 0.4), Forecast(10, 20), False), # 0.9 mm: not more than 1 + (Station(0, 0.6, 0.6), Forecast(10, 20), True), # 1.2 mm fell + (Station(0, 0, 0), Forecast(10, 50), True), # tomorrow 50%: at the line + (Station(0, 0, 0), Forecast(55, 0), True), # today + (Station(0, 0, 0), Forecast(45, 49), False), # both under the line + (Station(0, 0, 0), Forecast(None, None), False), # no ensemble figure: nothing to go on + (None, Forecast(0, 80), True), # no station: the forecast decides + (Station(0, 3, 0), None, True), # no forecast: the measured rain decides + (Station(fail=True), Forecast(0, 80), True), # the station failing leaves the forecast + (Station(fail=True), Forecast(0, 0), False), + (None, None, False), + (Station(2, 0, 0), Forecast(0, 0), False), # the first reading's total fell before the window: only rises count +]) +async def test_the_check_delays_a_day_when_more_than_1_mm_fell_or_is_likely(tmp_path, station, forecast, delayed): + device = Device() + m, state, sent = daily(tmp_path, device, station, forecast) + await m.check(NOW) + assert device.commands == ([("delay", "24h")] if delayed else []) + assert [(text.startswith("☔ Irrigation paused for 24 hours: ") and text.endswith("."), kw) for text, kw in sent] == ( + [(True, {"kind": "irrigation_pause"})] if delayed else []) # told once when it paused, never otherwise + assert state.monitor["irrigation_monitor"]["checked"] == "2026-10-08" + + +async def test_a_delay_already_set_is_never_shortened_or_repeated(tmp_path): + device = Device(weather_delay="72h") + m, _, sent = daily(tmp_path, device, Station(0, 5), Forecast(90, 90)) + await m.check(NOW) + assert device.commands == [] and sent == [] # nothing changed: nothing to tell + + +async def test_the_bots_own_pause_from_yesterday_is_started_again_and_one_someone_set_is_not(tmp_path): + device = Device() + m, state, sent = daily(tmp_path, device, Station(0, 3)) + await m.check(NOW) # paused at 6pm + await m.check(NOW + timedelta(days=1)) # 6pm the next day: still on, for seconds + assert device.commands == [("delay", "24h"), ("delay", "cancel"), ("delay", "24h")] + assert sent[1][0] == "☔ Irrigation paused for another 24 hours: 3 mm of rain in the last 24 hours." + m.station = Station(0, 0) + await m.check(NOW + timedelta(days=2)) # dry: it lapses + m.station = Station(0, 3) + await m.check(NOW + timedelta(days=4)) # a 24h someone set (the bot's is days old) + assert len(device.commands) == 3 and len(sent) == 2 + + +async def test_a_forecast_more_than_a_day_old_does_not_decide(tmp_path, caplog): + stale = Forecast(90, 90) + stale.fetched_at -= 25 * 3600 + device = Device() + m, state, sent = daily(tmp_path, device, Station(0, 0), stale) + with caplog.at_level("INFO"): + await m.check(NOW) + assert device.commands == [] and sent == [] and "over a day old: only the measured rain decides" in caplog.text + + +async def test_a_battery_under_5_percent_is_told_once_a_day_to_the_irrigation_alert_type(tmp_path): + device = Device(battery_percentage=4) + m, state, sent = daily(tmp_path, device) + await m.check(NOW) + await m.check(NOW) + assert len(sent) == 1 and sent[0][1] == {"kind": "irrigation_battery"} and "4%" in sent[0][0] and "🪫" in sent[0][0] + await m.check(datetime(2026, 10, 9, 18, 0)) # the next day: again, until it is charged + assert len(sent) == 2 + device.status_now["battery_percentage"] = 5 # 5% is not below 5% + await m.check(datetime(2026, 10, 10, 18, 0)) + assert len(sent) == 2 + + +async def test_the_battery_is_still_told_when_the_delay_cannot_be_sent_and_not_told_twice_on_the_retry(tmp_path): + class Failing(Device): + async def delay(self, duration): + raise IrrigationError("Tuya error 28841002: no permission") + m, state, sent = daily(tmp_path, Failing(battery_percentage=2), None, Forecast(90, 90)) + with pytest.raises(IrrigationError): + await m.check(NOW) + assert len(sent) == 1 and "checked" not in state.monitor["irrigation_monitor"] # not recorded: the next try repeats the check + with pytest.raises(IrrigationError): + await m.check(NOW) + assert len(sent) == 1 and sent[0][1] == {"kind": "irrigation_battery"} # no "paused" alert for a pause that was not made + + +def test_a_check_is_due_once_a_day_after_the_hour_and_the_next_is_the_following_18_00(tmp_path): + m, state, _ = daily(tmp_path, Device()) + assert not m.due(datetime(2026, 10, 8, 17, 59)) and m.due(datetime(2026, 10, 8, 18, 0)) and m.due(datetime(2026, 10, 8, 23, 0)) + state.monitor["irrigation_monitor"] = {"checked": "2026-10-08"} + assert not m.due(datetime(2026, 10, 8, 23, 0)) and not m.due(datetime(2026, 10, 9, 3, 0)) and m.due(datetime(2026, 10, 9, 18, 0)) + assert m.seconds_until_next(datetime(2026, 10, 8, 17, 0)) == 3600 and m.seconds_until_next(datetime(2026, 10, 8, 18, 0)) == 86400 + assert m.seconds_until_next(datetime(2026, 10, 8, 23, 30)) == 18.5 * 3600 + assert m.seconds_until_next(datetime(2026, 10, 3, 18, 0)) == 23 * 3600 # the clocks go forward that night: 23 real hours, not 24 + + +async def test_run_checks_when_due_retries_after_a_failure_and_then_waits_for_tomorrow(tmp_path, monkeypatch): + device = Device() + device.down = True + m, state, _ = daily(tmp_path, device, None, Forecast(90, 90)) + sleeps = [] + + async def fake_sleep(seconds): + sleeps.append(seconds) + if len(sleeps) == 1: + device.down = False # the controller is back after the first wait + if len(sleeps) == 3: + raise asyncio.CancelledError + monkeypatch.setattr(monitor_module.asyncio, "sleep", fake_sleep) + monkeypatch.setattr(monitor_module, "now_local", lambda tz: NOW) + with pytest.raises(asyncio.CancelledError): + await m.run() + assert sleeps[0] == 1800 and device.commands == [("delay", "24h")] # tried, failed, waited 30 minutes, tried, did it + assert state.monitor["irrigation_monitor"]["checked"] == "2026-10-08" + assert sleeps[1] == 86400 # then until 18:00 tomorrow (now is exactly 18:00 here) + + +async def test_the_watchdog_closes_a_valve_that_is_still_open_after_the_run_and_survives_a_restart(tmp_path): + clock, state = [1000.0], IrrigationState(tmp_path / "irrigation_state.json") + device = Device(switch=True) + dog = Watchdog(device, state, clock=lambda: clock[0]) + await dog.check() + assert device.commands == [] # nothing armed: the controller is not even asked + dog.arm(10) + clock[0] = 1000 + 600 + 29 + await dog.check() + assert device.commands == [] and dog.off_at # inside the grace period: the device's own countdown may still end it + clock[0] = 1000 + 600 + 31 + reborn = Watchdog(device, IrrigationState(tmp_path / "irrigation_state.json"), clock=lambda: clock[0]) # irrigation-mcp restarted in the middle of the run + await reborn.check() + assert device.commands == [("switch", False)] and reborn.off_at is None + + +async def test_the_watchdog_leaves_a_closed_valve_alone_tries_again_on_failure_and_disarms_on_request(tmp_path): + clock, state = [0.0], IrrigationState(tmp_path / "irrigation_state.json") + device = Device(switch=False) + dog = Watchdog(device, state, clock=lambda: clock[0]) + dog.arm(5) + clock[0] = 400 + await dog.check() + assert device.commands == [] and dog.off_at is None # it ended by itself + dog.arm(5) + device.down, device.status_now["switch"] = True, True + clock[0] = 800 + with pytest.raises(IrrigationError): + await dog.check() + assert dog.off_at is not None # kept: the next minute tries again + device.down = False + await dog.check() + assert device.commands == [("switch", False)] + dog.arm(5) + dog.disarm() + assert dog.off_at is None + + + +@pytest.mark.parametrize("station, forecast, why", [ + (Station(0, 0.6, 0.6), None, "1.2 mm of rain in the last 24 hours"), + (None, Forecast(10, 50), "50% chance of at least 1 mm tomorrow"), + (None, Forecast(55, 0), "55% chance of at least 1 mm today"), + (Station(0, 3, 0), Forecast(90, 90), "3 mm of rain in the last 24 hours"), # what fell comes first +]) +async def test_the_pause_alert_says_why(tmp_path, station, forecast, why): + m, _, sent = daily(tmp_path, Device(), station, forecast) + await m.check(NOW) + assert sent == [(f"☔ Irrigation paused for 24 hours: {why}.", {"kind": "irrigation_pause"})] + + +async def test_a_pause_that_fails_and_is_retried_is_told_exactly_once(tmp_path): + class Flaky(Device): + failures = 1 # the first command is refused, the second goes through + + async def delay(self, duration): + if self.failures: + self.failures -= 1 + raise IrrigationError("Tuya request failed (ConnectError)") + await super().delay(duration) + device = Flaky() + m, state, sent = daily(tmp_path, device, None, Forecast(90, 90)) + with pytest.raises(IrrigationError): + await m.check(NOW) + assert sent == [] and "checked" not in state.monitor["irrigation_monitor"] # nothing told for a pause that was not made + await m.check(NOW) + assert device.commands == [("delay", "24h")] and len(sent) == 1 and state.monitor["irrigation_monitor"]["checked"] == "2026-10-08" + + +async def test_the_irrigation_check_runs_on_the_forecast_last_read_when_the_service_cant_be_reached(caplog): + from datetime import date + from types import SimpleNamespace as NS + from mcp.shared.exceptions import MCPError + from lib.irrigation.ecobot import ServiceForecast, ServiceRain + + class Down: # (ecobot-mcp unreachable: lib/upstream refuses with an MCPError) + tz = TZ + + async def call_text(self, *a, **k): + raise MCPError(-32603, "ecobot-mcp isn't reachable") + + async def resource(self, uri, wait=None): + raise MCPError(-32603, "ecobot-mcp isn't reachable") + forecast = ServiceForecast(Down()) + now = datetime(2026, 11, 10, 18, 0, tzinfo=TZ) + forecast.days, forecast.fetched_at = [{"date": date(2026, 11, 11), "rain_1mm_pct": 70}], now.timestamp() - 3600 # (read an hour ago) + forecast.now = lambda: now + monitor = IrrigationMonitor(None, NS(monitor={}), None, TZ, station=ServiceRain(Down()), forecast=forecast) + assert await monitor.rain_reason(now) == "70% chance of at least 1 mm tomorrow" + assert "the measured rain is unavailable" in caplog.text and "using the one last read" in caplog.text + + +async def test_the_irrigation_check_is_timed_again_in_a_zone_read_later(tmp_path, monkeypatch): + """The irrigation check's wait for 18:00 is cut short when the station's zone arrives, and timed again in it.""" + from types import SimpleNamespace as NS + from zoneinfo import ZoneInfo + utc = ZoneInfo("Etc/UTC") + monitor = IrrigationMonitor(None, NS(monitor={"irrigation_monitor": {}}), None, utc, 18) + waits = [] + + def now_local(tz): + return datetime(2026, 11, 10, 6, 0) if str(tz) == "Etc/UTC" else datetime(2026, 11, 10, 17, 0) # (06:00 UTC: 17:00 there) + monkeypatch.setattr(monitor_module, "now_local", now_local) + timed = monitor.seconds_until_next + monitor.seconds_until_next = lambda now: waits.append(timed(now)) or waits[-1] # (the waits themselves are real) + task = asyncio.create_task(monitor.run()) + try: + await until(lambda: waits, what="the first wait") + monitor.tz = TZ + await until(lambda: len(waits) == 2, what="the wait timed again") + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert waits == [12 * 3600, 3600] # 12 hours to 18:00 UTC; then the hour to 18:00 in Melbourne diff --git a/tests/test_irrigation_mcp.py b/tests/test_irrigation_mcp.py new file mode 100644 index 00000000..c8fddf08 --- /dev/null +++ b/tests/test_irrigation_mcp.py @@ -0,0 +1,545 @@ +"""irrigation-mcp (docs/ecobot-mcp.md 3.9, step 8): the irrigation controller's own MCP server. Its tools over the SDK's in-memory +transport with a fake controller (and once with the fake Tuya cloud, signed); the watchdog closing a run after a restart; the daily check +asking ecobot-mcp (in memory) for the rain and the forecast, pausing on either and leaving a delay someone set, and going on the forecast +last read when ecobot-mcp can't be reached; its alerts heard through a listen; its state copied once from the bot's; the token and the +Host checked over HTTP; `python -m irrigation_mcp` starting and stopping; and what it imports (no Telegram, no model client, no Pillow, +no source).""" + +import asyncio +import contextlib +import json +import logging +import os +import signal +import socket +import time +from datetime import datetime, timedelta + +import httpx +import pytest +from mcp import Client + +from lib import upstream +from lib.alert_log import AlertLog +from lib.irrigation import Tuya, Watchdog +from lib.irrigation import server as server_module +from lib.irrigation.check import IrrigationMonitor +from lib.irrigation.ecobot import EcobotWeather +from lib.irrigation.server import ALERTS_URI, TOOLS, IrrigationServer, http_app +from lib.irrigation.state import IrrigationState +from lib.mcp_http import Uvicorn, server_config +from lib.timeutil import now_local +from lib.upstream import VERSION, Upstream, http_transport +from tests.fakes import TUYA_SECRET, TUYA_STATUS, TZ, FakeController, FakeTuya, StandInService, tuya_config +from tests.served import ecobot_mcp + +TOKENS = ("irrigation-s3cret", "phone-s3cret") + + +async def until(check, seconds: float = 10.0, what: str = "it"): + deadline = time.monotonic() + seconds + while not check(): + if time.monotonic() > deadline: + raise AssertionError(f"timed out waiting for {what}") + await asyncio.sleep(0.02) + + +@pytest.fixture +def served(tmp_path): + """irrigation-mcp's server over a fake controller, its watchdog keeping its state in tmp_path, its own alert log.""" + device = FakeController() + state = IrrigationState(tmp_path / "irrigation_state.json") + alerts = AlertLog(tmp_path / "irrigation_alerts.sqlite", TZ) + server = IrrigationServer(device, Watchdog(device, state), alerts, tz=TZ) + yield server + alerts.close() + + +async def call(client, name, args=None): + result = await client.call_tool(name, args or {}) + return result.is_error, json.loads(result.content[0].text) + + +# ---------- the tools ---------- +async def test_the_four_tools_are_listed_with_their_hints_and_schemas(served): + async with Client(served.server) as client: + tools = {t.name: t for t in (await client.list_tools()).tools} + assert list(tools) == ["irrigation_status", "water", "stop", "delay"] + assert tools["irrigation_status"].annotations.read_only_hint and not tools["irrigation_status"].annotations.destructive_hint + for name in ("water", "stop", "delay"): + assert tools[name].annotations.destructive_hint and not tools[name].annotations.read_only_hint, name + assert tools["water"].input_schema["properties"]["minutes"] == {**TOOLS["water"][1]["properties"]["minutes"]} + assert tools["water"].input_schema["properties"]["minutes"]["maximum"] == 60 + assert tools["delay"].input_schema["properties"]["duration"]["enum"] == ["24h", "48h", "72h", "cancel"] + + +async def test_status_water_stop_and_delay_act_on_the_controller_and_water_is_watched(served): + device, dog = served.device, served.watchdog + async with Client(served.server) as client: + error, status = await call(client, "irrigation_status") + assert not error and status == {"switch": False, "countdown": None, "weather_delay": "cancel", "paused": False, + "battery_percentage": 100, "work_state": "idle"} # (no off_at: nothing watched) + before = time.time() + error, out = await call(client, "water", {"minutes": 10}) + assert not error and out["done"] == "Watering for 10 minutes" and device.commands == [("water", 10)] + assert before + 600 <= dog.off_at <= time.time() + 600 # the watchdog armed + error, status = await call(client, "irrigation_status") + assert status["switch"] is True and status["countdown"] == 600 and status["work_state"] == "manual" + assert status["off_at"] == out["off_at"] == datetime.fromtimestamp(dog.off_at, TZ).isoformat(timespec="seconds") + error, out = await call(client, "stop") + assert not error and out == {"done": "Switched off"} and device.commands[-1] == ("switch", False) and dog.off_at is None + error, out = await call(client, "delay", {"duration": "48h"}) + assert not error and out == {"done": "Paused 48h", "weather_delay": "48h"} and device.commands[-1] == ("delay", "48h") + error, status = await call(client, "irrigation_status") + assert status["paused"] is True and status["weather_delay"] == "48h" and "off_at" not in status + error, out = await call(client, "delay", {"duration": "cancel"}) + assert out["done"] == "Unpaused" and not (await call(client, "irrigation_status"))[1]["paused"] + + +async def test_water_is_refused_while_a_weather_delay_is_on_saying_so(served): + served.device.status_now["weather_delay"] = "24h" + async with Client(served.server) as client: + error, out = await call(client, "water", {"minutes": 5}) + assert error and "paused (weather delay 24h)" in out["error"] and "cancel" in out["error"] and out["refused"] == "paused" + assert served.device.commands == [] and served.watchdog.off_at is None + + +@pytest.mark.parametrize("name, args, says", [ + ("water", {"minutes": 0}, "from 1 to 60"), ("water", {"minutes": 61}, "from 1 to 60"), ("water", {"minutes": "ten"}, "from 1 to 60"), + ("water", {"minutes": True}, "from 1 to 60"), ("water", {"minutes": 2.5}, "from 1 to 60"), ("water", {}, "needs minutes"), + ("water", {"minutes": 5, "zone": 2}, "not zone"), ("delay", {"duration": "96h"}, "one of 24h, 48h, 72h, cancel"), + ("delay", {}, "needs duration"), ("stop", {"now": True}, "takes no arguments"), ("irrigation_status", {"x": 1}, "takes no arguments")]) +async def test_wrong_arguments_are_refused_saying_what_is_wrong_and_nothing_is_sent(served, name, args, says): + async with Client(served.server) as client: + error, out = await call(client, name, args) + assert error and says in out["error"] and out["refused"] == "arguments" + assert served.device.commands == [] and served.watchdog.off_at is None + + +async def test_a_controller_that_cant_be_reached_is_a_tool_error_safe_to_show_and_a_lost_water_reply_is_still_watched(served, tmp_path): + served.device.down = True + async with Client(served.server) as client: + error, out = await call(client, "irrigation_status") + assert error and out == {"error": "The irrigation controller couldn't be reached: Tuya request failed (ConnectError)."} + + class Lost(FakeController): + async def water(self, minutes): + await super().water(minutes) # the valve opened + from lib.irrigation import IrrigationError + raise IrrigationError("Tuya request failed (ReadTimeout)") # but the reply never came + served.device = served.watchdog.device = Lost() + error, out = await call(client, "water", {"minutes": 5}) + assert error and "ReadTimeout" in out["error"] and served.watchdog.off_at is not None + + def refuse(request): # (the real client: its message names no secret) + raise httpx.ConnectError("no route to https://openapi.tuyaeu.com?secret=" + TUYA_SECRET) + served.device = Tuya(tuya_config(tmp_path), transport=httpx.MockTransport(refuse)) + async with Client(served.server) as client: + error, out = await call(client, "irrigation_status") + assert error and TUYA_SECRET not in json.dumps(out) and "ConnectError" in out["error"] + await served.device.close() + + +async def test_the_tools_over_the_tuya_cloud_send_signed_commands(tmp_path): + fake = FakeTuya() + device = Tuya(tuya_config(tmp_path), transport=httpx.MockTransport(fake)) + state = IrrigationState(tmp_path / "irrigation_state.json") + server = IrrigationServer(device, Watchdog(device, state), None, tz=TZ) + async with Client(server.server) as client: + assert (await call(client, "irrigation_status"))[1]["battery_percentage"] == 100 + assert not (await call(client, "water", {"minutes": 3}))[0] + assert not (await call(client, "stop"))[0] + assert (await client.list_resources()).resources == [] # (no alert log: no alerts) + assert [(m, p, b) for m, p, b, _ in fake.calls if m == "POST"] == [ + ("POST", "/v1.0/devices/dev1/commands", {"commands": [{"code": "countdown", "value": 180}, {"code": "switch", "value": True}]}), + ("POST", "/v1.0/devices/dev1/commands", {"commands": [{"code": "switch", "value": False}]})] + await device.close() + + +# ---------- the watchdog and the state ---------- +async def test_a_run_started_through_the_tools_is_closed_by_the_watchdog_after_a_restart(served, tmp_path): + async with Client(served.server) as client: + await call(client, "water", {"minutes": 10}) + off_at = served.watchdog.off_at + device = served.device # the valve is still open (its own countdown failed) + reborn = Watchdog(device, IrrigationState(tmp_path / "irrigation_state.json"), clock=lambda: off_at + 31) # irrigation-mcp restarted + assert reborn.off_at == off_at + await reborn.check() + assert device.commands[-1] == ("switch", False) and reborn.off_at is None + assert json.loads((tmp_path / "irrigation_state.json").read_text()) == {"irrigation_watchdog": {}} + + +def bot_state(tmp_path, monitor: dict) -> str: + path = tmp_path / "bot_state.json" + path.write_text(json.dumps({"chats": {"1": {"title": "Rob"}}, "monitor": monitor, "charts": {}})) + return path.read_text() + + +async def test_at_its_first_start_the_bots_watchdog_and_check_state_is_copied_once(tmp_path, caplog): + caplog.set_level("INFO") + off_at = time.time() - 100 + bots = bot_state(tmp_path, {"irrigation_watchdog": {"off_at": off_at}, "rain": {"since": 5}, + "irrigation_monitor": {"checked": "2026-11-11", "paused": "2026-11-11", "battery_warned": "2026-11-10"}}) + state = IrrigationState(tmp_path / "irrigation_state.json", tmp_path / "bot_state.json") + assert state.monitor == {"irrigation_watchdog": {"off_at": off_at}, + "irrigation_monitor": {"checked": "2026-11-11", "paused": "2026-11-11", "battery_warned": "2026-11-10"}} + assert json.loads((tmp_path / "irrigation_state.json").read_text()) == state.monitor # (kept at once: copied this once only) + assert (tmp_path / "bot_state.json").read_text() == bots # the bot's file as it was + assert caplog.text.count("copied from") == 1 + device = FakeController(switch=True) + await Watchdog(device, state).check() # a run the old bot armed: closed + assert device.commands == [("switch", False)] + m = IrrigationMonitor(device, state, None, TZ, 18) + assert not m.due(datetime(2026, 11, 11, 19, 0)) and m.due(datetime(2026, 11, 12, 18, 0)) # the bot's day is not checked again + caplog.clear() + again = IrrigationState(tmp_path / "irrigation_state.json", tmp_path / "bot_state.json") # the next start: its own file + assert again.monitor == {"irrigation_watchdog": {}, "irrigation_monitor": state.monitor["irrigation_monitor"]} + assert "copied" not in caplog.text + + +def test_without_the_bots_entries_nothing_is_copied_not_even_at_a_later_start_and_a_damaged_bot_file_is_left_alone(tmp_path, caplog): + caplog.set_level("INFO") + mine = tmp_path / "irrigation_state.json" + bot_state(tmp_path, {"rain": {"since": 5}}) + assert IrrigationState(mine, tmp_path / "bot_state.json").monitor == {} + assert json.loads(mine.read_text()) == {} # written at the first start, with nothing in it + bot_state(tmp_path, {"irrigation_watchdog": {"off_at": 5.0}}) # (an old bot run since): not copied at a later start + assert IrrigationState(mine, tmp_path / "bot_state.json").monitor == {} and "copied" not in caplog.text + mine.unlink() + assert IrrigationState(mine, tmp_path / "none.json").monitor == {} + mine.unlink() + (tmp_path / "bot_state.json").write_text("{not json") + assert IrrigationState(mine, tmp_path / "bot_state.json").monitor == {} + assert (tmp_path / "bot_state.json").read_text() == "{not json" and "copied" not in caplog.text + + +# ---------- the daily check, as ecobot-mcp's client ---------- +class Ecobot: + """ecobot-mcp in memory with stand-in tools (summary's rain total) and a forecast (ecobot://forecast), and irrigation-mcp's client of + it (lib/irrigation/ecobot.EcobotWeather), connected.""" + + def __init__(self, rain_mm=0.0, chances=(10, 20)): + self.rain_mm, self.chances, self.fetched = rain_mm, list(chances), now_local(TZ) - timedelta(hours=1) + self.service = StandInService(summary=lambda args, meta: {"rain_total_mm": self.rain_mm, "period": args.get("period")}) + + async def forecast(self) -> dict: + today = now_local(TZ).date() + return {"place": "Home", "fetched_at": self.fetched.isoformat(timespec="seconds"), + "days": [{"date": (today + timedelta(days=i)).isoformat(), "rain_1mm_pct": c} for i, c in enumerate(self.chances)]} + + +@contextlib.asynccontextmanager +async def connected(ecobot: Ecobot): + async with ecobot_mcp(tools=ecobot.service, sources=["Ecowitt", "Forecast"]) as remote: + remote.server.forecast = ecobot.forecast + weather = EcobotWeather(remote.server.server, tz=None) + zones = [] + weather.on_zone = zones.append + task = asyncio.create_task(weather.run()) + try: + await asyncio.wait_for(weather.listening.wait(), 10) + await until(lambda: weather.forecast.days, what="the forecast") + weather.zones = zones + yield weather + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + await weather.close() + + +def checker(tmp_path, device, weather): + state, sent = IrrigationState(tmp_path / "irrigation_state.json"), [] + + async def notify(text, kind): + sent.append((kind, text)) + return IrrigationMonitor(device, state, notify, weather.tz, 18, weather.rain, weather.forecast), state, sent + + +@pytest.mark.parametrize("rain_mm, chances, reason", [ + (3.0, (0, 0), "3 mm of rain in the last 24 hours"), + (0.0, (10, 80), "80% chance of at least 1 mm tomorrow"), + (0.4, (55, 0), "55% chance of at least 1 mm today"), + (0.9, (10, 49), None)]) +async def test_the_check_asks_ecobot_mcp_for_the_rain_and_the_forecast_and_pauses_on_either(tmp_path, rain_mm, chances, reason): + ecobot = Ecobot(rain_mm, chances) + async with connected(ecobot) as weather: + assert str(weather.tz) == str(TZ) and [str(z) for z in weather.zones] == [str(TZ)] # the station's zone, read + device = FakeController() + m, state, sent = checker(tmp_path, device, weather) + await m.check(now_local(TZ)) + assert ("summary", {"readings": ["rain"], "period": "last 24 hours"}) in ecobot.service.calls + assert device.commands == ([("delay", "24h")] if reason else []) + assert sent == ([("irrigation_pause", f"☔ Irrigation paused for 24 hours: {reason}.")] if reason else []) + assert state.monitor["irrigation_monitor"]["checked"] == now_local(TZ).date().isoformat() + + +async def test_the_check_leaves_a_delay_someone_set(tmp_path): + async with connected(Ecobot(5.0, (90, 90))) as weather: + device = FakeController(weather_delay="48h") + m, _, sent = checker(tmp_path, device, weather) + await m.check(now_local(TZ)) + assert device.commands == [] and sent == [] + + +async def test_with_ecobot_mcp_unreachable_the_check_goes_on_the_forecast_last_read_without_the_measured_rain(tmp_path, monkeypatch, caplog): + monkeypatch.setattr(upstream, "CONNECT_WAIT", 0.1) + ecobot = Ecobot(0.0, (10, 80)) + async with connected(ecobot) as weather: + pass # the forecast read; then ecobot-mcp goes away + assert weather.upstream.client is None and weather.forecast.days + ecobot.service.calls.clear() + device = FakeController() + m, _, sent = checker(tmp_path, device, weather) + await m.check(now_local(TZ)) + assert ecobot.service.calls == [] and device.commands == [("delay", "24h")] + assert sent == [("irrigation_pause", "☔ Irrigation paused for 24 hours: 80% chance of at least 1 mm tomorrow.")] + assert "the measured rain is unavailable" in caplog.text and "using the one last read" in caplog.text + never = EcobotWeather("http://127.0.0.1:9/mcp", tz=TZ) # never reached: no forecast to go on + (tmp_path / "fresh").mkdir() + m, _, sent = checker(tmp_path / "fresh", FakeController(), never) + await m.check(now_local(TZ)) + assert sent == [] and "there is none to go on" in caplog.text + + +# ---------- its alerts ---------- +async def test_its_alerts_are_heard_through_a_listen_and_read_in_ecobot_alerts_shape(served, tmp_path): + publishing = asyncio.create_task(served.run()) + heard, listening = [], asyncio.Event() + + async def on_event(event): + heard.append(str(event.uri)) + + async def on_listening(): + listening.set() + up = Upstream(served.server, on_event=on_event, on_listening=on_listening) + supervisor = asyncio.create_task(up.run()) + try: + await asyncio.wait_for(listening.wait(), 10) + served.device.status_now["battery_percentage"] = 3 + m = IrrigationMonitor(served.device, served.watchdog.state, served.notify, TZ, 18) + await m.check(now_local(TZ)) + await until(lambda: heard == [ALERTS_URI], what="the alert's ResourceUpdated") + client = await up.get() + listed = (await client.list_resources()).resources + templates = (await client.list_resource_templates()).resource_templates + data = json.loads((await client.read_resource(ALERTS_URI)).contents[0].text) + later = json.loads((await client.read_resource(f"{ALERTS_URI}?since=1")).contents[0].text) + with pytest.raises(Exception, match="whole number"): + await client.read_resource(f"{ALERTS_URI}?since=x") + with pytest.raises(Exception, match="No resource"): + await client.read_resource("irrigation://nothing") + finally: + supervisor.cancel() + publishing.cancel() + await asyncio.gather(supervisor, publishing, return_exceptions=True) + assert [str(r.uri) for r in listed] == [ALERTS_URI] and templates[0].uri_template == "irrigation://alerts{?since,expired}" + assert data["last_id"] == 1 and data["identity"] == served.alert_log.identity and later["alerts"] == [] + (alert,) = data["alerts"] + assert alert["kind"] == "irrigation_battery" and alert["title"] == "Irrigation battery low" and alert["id"] == 1 + assert alert["text"] == "🪫 The irrigation battery is at 3%. Replace or recharge it soon, or watering will stop." + assert datetime.fromisoformat(alert["expires"]) - datetime.fromisoformat(alert["time"]) == timedelta(hours=24) + + +# ---------- over HTTP ---------- +def free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +@contextlib.asynccontextmanager +async def serving(app, port): + web = Uvicorn(server_config(app, "127.0.0.1", port, 0.25)) + task = asyncio.create_task(web.serve()) + await until(lambda: web.started or task.done(), what="uvicorn to start") + try: + yield web + finally: + web.should_exit = True + await task + + +async def test_a_request_without_the_token_with_a_wrong_or_revoked_one_or_to_a_host_not_allowed_is_refused(served, caplog): + caplog.set_level("INFO", logger="lib.irrigation.server.requests") + port = free_port() + url = f"http://127.0.0.1:{port}/mcp" + app = http_app(served, tokens=TOKENS, allowed_hosts=("127.0.0.1", "irrigation.lan")) + body = {"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": {"io.modelcontextprotocol/protocolVersion": VERSION}}} + + async def post(token=None, host=None) -> int: + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", "Mcp-Protocol-Version": VERSION, + "Mcp-Method": "server/discover", **({"Authorization": f"Bearer {token}"} if token else {}), **({"Host": host} if host else {})} + async with httpx.AsyncClient() as http: + return (await http.post(url, headers=headers, json=body)).status_code + async with serving(app, port): + assert await post() == 401 and await post("nope") == 401 and await post(TOKENS[0].upper()) == 401 + assert await post(TOKENS[1], host="evil.example") == 421 + assert await post(TOKENS[1], host=f"irrigation.lan:{port}") != 421 + async with Client(http_transport(url, TOKENS[1]), mode=VERSION) as client: + assert not (await client.call_tool("water", {"minutes": 4})).is_error + app.state.tokens.revoke(TOKENS[1]) + assert await post(TOKENS[1]) == 401 + async with Client(http_transport(url, TOKENS[0]), mode=VERSION) as client: + assert json.loads((await client.call_tool("irrigation_status", {})).content[0].text)["switch"] is True + lines = [r.getMessage() for r in caplog.records if r.name == "lib.irrigation.server.requests"] + assert any("POST /mcp tools/call water 4 -> 200" in line for line in lines), lines + assert any("-> 401, no token, or one that isn't in AUTH_TOKENS" in line for line in lines), lines + assert any("-> 421, its Host isn't in IRRIGATION_ALLOWED_HOSTS (Host evil.example)" in line for line in lines), lines + assert not any(t in line for t in TOKENS for line in lines) + + +async def test_python_m_irrigation_mcp_starts_answers_with_the_generated_token_and_stops_on_sigterm(tmp_path, monkeypatch, caplog): + """A deploy check: main() with the fake Tuya cloud, AUTH_TOKENS unset (the token generated in the data folder, the one ecobot-mcp + would use), ecobot-mcp not reachable: it starts all the same, answers a tool call through IRRIGATION_ALLOWED_HOSTS' name, keeps one + process per data folder, and SIGTERM closes it.""" + import irrigation_mcp.__main__ as main_module + from lib import auth_token + from lib.config import Config + caplog.set_level("INFO") + port = free_port() + cfg = tuya_config(tmp_path, irrigation_bind=("127.0.0.1", port), irrigation_allowed_hosts=("irrigation.lan",), + irrigation_ecobot_mcp_url="http://127.0.0.1:9/mcp") + monkeypatch.setattr(Config, "from_env", classmethod(lambda cls, bot=True, program=None: cfg)) + monkeypatch.setattr(main_module, "STARTUP_WAIT", 0.2) + monkeypatch.setattr(main_module, "SHUTDOWN_SECONDS", 0.25) + fake = FakeTuya() + monkeypatch.setattr(Tuya, "__init__", lambda self, c, transport=None, orig=Tuya.__init__: orig(self, c, httpx.MockTransport(fake))) + answered = {} + + async def ask_then_stop(): + await until(lambda: "MCP: http://127.0.0.1:" in caplog.text, 30, "irrigation-mcp to listen") + token = auth_token.read(tmp_path) + url = f"http://127.0.0.1:{port}/mcp" + + @contextlib.asynccontextmanager + async def through_the_proxy(): + from mcp.client.streamable_http import streamable_http_client + from mcp.shared._httpx_utils import create_mcp_http_client + async with create_mcp_http_client(headers={"Authorization": f"Bearer {token}", "Host": "irrigation.lan"}) as http: + async with streamable_http_client(url, http_client=http) as streams: + yield streams + async with Client(through_the_proxy(), mode=VERSION) as client: + answered["status"] = json.loads((await client.call_tool("irrigation_status", {})).content[0].text) + from lib.mcp_http import hold_folder + with contextlib.ExitStack() as second: # (a second on the same folder stops) + with pytest.raises(SystemExit, match="Another irrigation-mcp"): + hold_folder(tmp_path, main_module.LOCK, "irrigation-mcp", "python -m irrigation_mcp", second) + await until(lambda: "the daily check at" in caplog.text, 10, "the daily check to start") # (after STARTUP_WAIT) + os.kill(os.getpid(), signal.SIGTERM) + asker = asyncio.create_task(ask_then_stop()) + await main_module.main() + await asker + assert answered["status"]["battery_percentage"] == 100 and answered["status"]["paused"] is False + assert f"the token in {tmp_path / 'auth_token'}" in caplog.text and "ecobot-mcp at http://127.0.0.1:9/mcp isn't reachable yet" in caplog.text + assert "the daily check at 18:00" in caplog.text and "Telegram" not in caplog.text + assert (tmp_path / "irrigation.lock").exists() + + +async def test_at_start_the_watchdog_and_the_tools_dont_wait_for_ecobot_mcp(tmp_path, monkeypatch, caplog): + """A restart mid-run with ecobot-mcp unreachable: the run left armed (past its end, the valve still open) is closed at once, and the + tools answer, while the daily check still waits for ecobot-mcp's time zone (STARTUP_WAIT, long here); SIGTERM during that wait stops it.""" + import irrigation_mcp.__main__ as main_module + from lib import auth_token + from lib.config import Config + caplog.set_level("INFO") + port = free_port() + cfg = tuya_config(tmp_path, irrigation_bind=("127.0.0.1", port), irrigation_ecobot_mcp_url="http://127.0.0.1:9/mcp") + (tmp_path / "irrigation_state.json").write_text(json.dumps({"irrigation_watchdog": {"off_at": time.time() - 120}})) + monkeypatch.setattr(Config, "from_env", classmethod(lambda cls, bot=True, program=None: cfg)) + monkeypatch.setattr(main_module, "STARTUP_WAIT", 60) + monkeypatch.setattr(main_module, "SHUTDOWN_SECONDS", 0.25) + fake = FakeTuya(status=[{"code": "switch", "value": True}, *TUYA_STATUS[1:]]) + monkeypatch.setattr(Tuya, "__init__", lambda self, c, transport=None, orig=Tuya.__init__: orig(self, c, httpx.MockTransport(fake))) + answered = {} + + async def ask_then_stop(): + started = time.monotonic() + await until(lambda: any(p.endswith("/commands") for _, p, _, _ in fake.calls), 10, "the watchdog to close the valve") + await until(lambda: "MCP: http://127.0.0.1:" in caplog.text, 10, "irrigation-mcp to listen") + async with Client(http_transport(f"http://127.0.0.1:{port}/mcp", auth_token.read(tmp_path)), mode=VERSION) as client: + answered["status"] = json.loads((await client.call_tool("irrigation_status", {})).content[0].text) + answered["after"] = time.monotonic() - started + os.kill(os.getpid(), signal.SIGTERM) + asker = asyncio.create_task(ask_then_stop()) + await asyncio.wait_for(main_module.main(), 30) + await asker + commands = [body for _, p, body, _ in fake.calls if p.endswith("/commands")] + assert commands == [{"commands": [{"code": "switch", "value": False}]}] and "valve was still open" in caplog.text + assert "battery_percentage" in answered["status"] and "off_at" not in answered["status"] and answered["after"] < 20 + assert "the daily check at" not in caplog.text # (it was still waiting for ecobot-mcp when stopped) + assert json.loads((tmp_path / "irrigation_state.json").read_text())["irrigation_watchdog"] == {} + + +def test_the_watchdog_checks_again_when_the_run_is_due_not_a_whole_minute_later(tmp_path): + from lib.irrigation.state import IrrigationState + from lib.irrigation.watchdog import CHECK_SECONDS, GRACE_SECONDS + now = [1000.0] + watchdog = Watchdog(FakeController(), IrrigationState(tmp_path / "irrigation_state.json"), clock=lambda: now[0]) + assert watchdog.next_check() == CHECK_SECONDS # nothing armed + watchdog.arm(1) + assert watchdog.next_check() == CHECK_SECONDS # due in 90 s + now[0] += 50 + assert watchdog.next_check() == 60 + GRACE_SECONDS - 50 # due in 40 s: then + now[0] += 39.5 + assert watchdog.next_check() == 1.0 # (never sooner than a second) + now[0] += 10 + assert watchdog.next_check() == CHECK_SECONDS # past it (its check failed): the usual minute + + +def test_without_the_controllers_settings_irrigation_mcp_stops_saying_which_with_the_status_its_unit_doesnt_restart(monkeypatch, + tmp_path, caplog): + """Its unit restarts it on a failure, but not on this one (RestartPreventExitStatus=78): until the settings change it would only + fail again, every 10 seconds, for good (ecobot.service wants irrigation-mcp.service, so an installed one is started at every boot).""" + import irrigation_mcp.__main__ as main_module + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + monkeypatch.setenv("IRRIGATION_TUYA_DEVICE_ID", "dev") + with pytest.raises(SystemExit) as stopped: + asyncio.run(main_module.main()) + assert stopped.value.code == main_module.SETTINGS_EXIT == 78 + assert "IRRIGATION_TUYA_CLIENT_ID, IRRIGATION_TUYA_CLIENT_SECRET not set" in caplog.text + + +def test_it_sends_ecobot_mcp_the_first_of_auth_tokens_else_the_generated_one(tmp_path): + from irrigation_mcp.__main__ import ecobot_token + from lib import auth_token + assert ecobot_token(tuya_config(tmp_path, auth_tokens=("first", "second"))) == "first" + read = ecobot_token(tuya_config(tmp_path)) + assert read() is None # (none yet: read again for each connection) + token = auth_token.ensure(tmp_path) + assert read() == token + + +# ---------- what it imports ---------- +NOT_IRRIGATIONS = ("telegram", "openai", "PIL", "lib.ecowitt", "lib.airgradient", "lib.forecast", "lib.pollen", "lib.storage", + "lib.service", "lib.mcp_server", "lib.bot", "lib.weather", "lib.charts", "lib.draw", "lib.gauges", "ecobot_mcp", "ecobot") + + +def test_irrigation_mcp_imports_no_telegram_no_model_client_no_pillow_and_no_source(tmp_path): + """irrigation-mcp runs beside the valve on its own packages: building everything it runs (the server, the watchdog, the check, its + state, its client of ecobot-mcp, the HTTP app) imports nothing of the bot's, nothing that draws, and none of ecobot-mcp's sources, + readings file or tools.""" + import subprocess + import sys + from lib.config import ROOT + code = ("import sys, irrigation_mcp, irrigation_mcp.__main__; from zoneinfo import ZoneInfo; " + "from lib.alert_log import AlertLog; from lib.irrigation import Tuya, Watchdog; " + "from lib.irrigation.check import IrrigationMonitor; from lib.irrigation.ecobot import EcobotWeather; " + "from lib.irrigation.server import IrrigationServer, http_app; from lib.irrigation.state import IrrigationState; " + "from lib.config import Config; from lib.warm import Tasks, every; " + f"folder = {str(tmp_path)!r}; " + "cfg = Config.from_env(program='irrigation'); tz = ZoneInfo('UTC'); " + "state = IrrigationState(cfg.irrigation_state_path, cfg.state_path); device = Tuya(cfg); dog = Watchdog(device, state); " + "w = EcobotWeather(cfg.irrigation_ecobot_mcp_url, 't', tz); log = AlertLog(cfg.irrigation_alert_log_path, tz); " + "s = IrrigationServer(device, dog, log, tz=tz); IrrigationMonitor(device, state, s.notify, tz, 18, w.rain, w.forecast); " + "http_app(s, tokens=('t',)); " + f"print(sorted(m for m in sys.modules if m.split('.')[0] in {NOT_IRRIGATIONS!r} or m.startswith(tuple(n + '.' for n in {NOT_IRRIGATIONS!r}))))") + env = {**os.environ, "DATA_DIR": str(tmp_path), "IRRIGATION_TUYA_DEVICE_ID": "d", "IRRIGATION_TUYA_CLIENT_ID": "c", + "IRRIGATION_TUYA_CLIENT_SECRET": "s"} + done = subprocess.run([sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True, timeout=120, env=env) + assert done.returncode == 0, done.stderr + assert done.stdout.strip().splitlines()[-1] == "[]" + + +def test_the_server_module_names_what_it_runs(): + assert set(server_module.ALERTS) == {"irrigation_battery", "irrigation_pause"} == set(IrrigationMonitor.KINDS) + assert logging.getLogger("lib.irrigation.server.requests") is server_module.requests_log diff --git a/tests/test_lines.py b/tests/test_lines.py index 9d6f3b30..534d1394 100644 --- a/tests/test_lines.py +++ b/tests/test_lines.py @@ -72,3 +72,18 @@ def test_a_band_is_drawn_wherever_there_is_a_range_even_for_a_short_part_of_the_ assert line.low[:100] == line.y[:100] == line.high[:100] # no range before it: nothing shaded assert all(lo < y < hi for lo, y, hi in zip(line.low[100:], line.y[100:], line.high[100:])) # its range after assert build_line(readings(144, 300, 300), TZ, 143 * 300).low is None # no range anywhere: no band + + +def test_day_of_places_every_reading_in_the_day_local_date_does_in_any_zone(): + """daily_summary's day of a reading (lines.day_of keeps the day's span) is local_date's, readings in order or not, in zones with + clock changes at midnight and offsets of half and three-quarter hours.""" + import random + from zoneinfo import ZoneInfo + from lib.lines import day_of + from lib.timeutil import local_date + rng = random.Random(7) + for zone in ("Australia/Melbourne", "America/Santiago", "America/Havana", "Asia/Kathmandu", "Australia/Lord_Howe", "Pacific/Chatham"): + tz = ZoneInfo(zone) + key = day_of(tz) + times = [*range(1_700_000_000, 1_700_000_000 + 86400 * 400, 900), *(rng.randrange(1_600_000_000, 1_800_000_000) for _ in range(3000))] + assert [key(t) for t in times] == [local_date(t, tz) for t in times], zone diff --git a/tests/test_live_bands.py b/tests/test_live_bands.py index 3a476317..ccb35741 100644 --- a/tests/test_live_bands.py +++ b/tests/test_live_bands.py @@ -6,6 +6,7 @@ from lib.ecowitt.live import BUCKET, readings_in from lib.tools import Turn from tests.fakes import archived_station +from tests import engines T = 1_800_000_000 // BUCKET * BUCKET @@ -29,7 +30,7 @@ async def chart_of_the_last_day(eco): now = datetime.now(eco.tz) args = {"groups": "outdoor", "start_date": f"{(now - timedelta(days=1)):%Y-%m-%d %H:%M:%S}", "end_date": f"{now:%Y-%m-%d %H:%M:%S}", "chart": True} turn = Turn() - await eco.tools[1].handler(args, turn) + await engines.history(eco, args, turn) return turn.charts[0].panels[0].lines[0] @@ -68,7 +69,7 @@ async def test_a_chart_of_a_week_has_the_true_extremes_of_each_half_hour_in_its_ async def line(): turn = Turn() - await eco.tools[1].handler(args, turn) + await engines.history(eco, args, turn) return turn.charts[0].panels[0].lines[0] plain = await line() slot = plain.x[len(plain.x) // 2] # a half hour in the middle of the period diff --git a/tests/test_logs.py b/tests/test_logs.py index a3b46058..9b4f007a 100644 --- a/tests/test_logs.py +++ b/tests/test_logs.py @@ -77,5 +77,5 @@ async def nowhere(host): text = caplog.text assert ("AirGradient: (airgradient_d83bda1c1e08.local) did not answer (OSError: airgradient_d83bda1c1e08.local was not found on " "the network); " + ("using the cloud, " if cloud else "") + "trying again in 5 min") in text - assert ("put the IP address in AIRGRADIENT_LOCAL_URL, or put the container on the host network" in text) == private + assert ("put the IP address in MCP_AIRGRADIENT_LOCAL_URL, or put the container on the host network" in text) == private await sensor.close() diff --git a/tests/test_mcp_listen.py b/tests/test_mcp_listen.py new file mode 100644 index 00000000..c662a491 --- /dev/null +++ b/tests/test_mcp_listen.py @@ -0,0 +1,279 @@ +"""The service over the network (docs/ecobot-mcp.md 7, "a client that listens", "a deploy check"): the real Streamable HTTP app under +uvicorn on a localhost port each test starts and stops, not the in-memory transport (a connection can't fail there, and it buffers a +listen stream). A client that listens hears a new alert, loses its listen when the service stops, listens again once it is back and +reads the alerts after its last id, once; a request without the token, with a wrong or revoked one, or to a Host not allowed is +refused; and `python -m ecobot_mcp` runs the sources and answers a tool call through the name a proxy uses.""" + +import asyncio +import contextlib +import json +import os +import signal +import socket +import time +from datetime import datetime, timedelta, timezone +from zoneinfo import ZoneInfo + +import httpx +import pytest +from mcp import Client + +from lib import upstream +from ecobot_mcp.__main__ import Uvicorn, server_config +from lib.upstream import Upstream, http_transport +from lib.alert_log import AlertLog +from lib.mcp_server import ALERTS_URI, EcobotServer, http_app +from lib.service.context import Context + +TZ = ZoneInfo("Australia/Melbourne") +TOKENS = {"bot": "bot-s3cret", "phone": "phone-s3cret"} + + +def free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +async def until(check, seconds: float = 10.0, what: str = "it"): + """Wait until check() is true (polled), failing after `seconds`.""" + deadline = time.monotonic() + seconds + while not check(): + if time.monotonic() > deadline: + raise AssertionError(f"timed out waiting for {what}") + await asyncio.sleep(0.02) + + +class Serving: + """The app under uvicorn on 127.0.0.1:port, started and stopped by the test.""" + + def __init__(self, app, port: int): + self.web = Uvicorn(server_config(app, "127.0.0.1", port)) + self.task: asyncio.Task | None = None + + async def __aenter__(self): + self.task = asyncio.create_task(self.web.serve()) + await until(lambda: self.web.started or self.task.done(), what="uvicorn to start") + return self + + async def stop(self): + self.web.should_exit = True + await self.task + + async def __aexit__(self, *exc): + if not self.task.done(): + await self.stop() + + +@pytest.fixture(autouse=True) +def quick_shutdown(monkeypatch): + """A listen stream still open when a test's server stops is ended after a quarter of a second, not ecobot-mcp's SHUTDOWN_SECONDS (3): + the client loses its listen either way, and no test here is about how long that takes (tests/test_web_dashboard.py's stream, which + must not hold the shutdown up, keeps the 3 s).""" + import ecobot_mcp.__main__ as service_main + monkeypatch.setattr(service_main, "SHUTDOWN_SECONDS", 0.25) + + +@pytest.fixture +def service(tmp_path): + alerts = AlertLog(tmp_path / "alerts.sqlite", TZ) + server = EcobotServer(Context(tz=TZ), alerts) + yield server + alerts.close() + + +async def test_a_client_that_listens_hears_an_alert_and_after_a_lost_listen_listens_again_and_reads_what_it_missed(service, monkeypatch): + monkeypatch.setattr(upstream, "BACKOFF", (0.1,)) + alerts, port = service.alert_log, free_port() + url = f"http://127.0.0.1:{port}/mcp" + publishing = asyncio.create_task(service.watch_alerts()) + handled, connections = [], [] + + async def read_new(*_): + """The client's delivery: the alerts after the last id it handled, each once.""" + after = handled[-1] if handled else 0 + got = json.loads((await up.client.read_resource(f"{ALERTS_URI}?since={after}")).contents[0].text) + handled.extend(a["id"] for a in got["alerts"] if a["id"] > (handled[-1] if handled else 0)) + + async def listening(): + connections.append(True) + await read_new() + up = Upstream(url, TOKENS["bot"], on_event=read_new, on_listening=listening) + supervisor = asyncio.create_task(up.run()) + try: + async with Serving(http_app(service, tokens=TOKENS.values()), port) as first: + await until(lambda: connections and service.listen._streams, what="the listen") + alerts.append("rain", "🌧️ It's started raining", "Rain started", expires=time.time() + 3600) + await until(lambda: handled == [1], what="alert 1") + await first.stop() # the service goes away: the listen is lost + await until(lambda: not up.connected.is_set(), what="the client to notice") + alerts.append("gusts", "💨 A gust of 72 km/h", "Gusts", expires=time.time() + 3600) # missed while it was down + alerts.append("uv", "UV 9", "UV", expires=time.time() - 1) # ... and already expired: never news + async with Serving(http_app(service, tokens=TOKENS.values()), port): + await until(lambda: len(connections) == 2, what="the client to listen again") + await until(lambda: handled == [1, 2], what="alert 2, read after its last id") + alerts.append("temps", "Warmer outside", "Temperatures", expires=time.time() + 3600) + await until(lambda: handled == [1, 2, 4], what="alert 4 on the new listen") + finally: + supervisor.cancel() + publishing.cancel() + await asyncio.gather(supervisor, publishing, return_exceptions=True) + assert handled == [1, 2, 4] + + +async def test_a_request_without_the_token_with_a_wrong_or_revoked_one_or_to_a_host_not_allowed_is_refused(service): + port = free_port() + url = f"http://127.0.0.1:{port}/mcp" + app = http_app(service, tokens=TOKENS.values(), allowed_hosts=("127.0.0.1", "weather.lan")) + body = {"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": { + "io.modelcontextprotocol/protocolVersion": "2026-07-28"}}} + + async def post(token=None, host=None) -> int: + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "Mcp-Protocol-Version": "2026-07-28", "Mcp-Method": "server/discover"} + if token: + headers["Authorization"] = f"Bearer {token}" + if host: + headers["Host"] = host + async with httpx.AsyncClient() as http: + return (await http.post(url, headers=headers, json=body)).status_code + async with Serving(app, port): + assert await post() == 401 and await post("nope") == 401 and await post(TOKENS["bot"].upper()) == 401 + assert await post(TOKENS["phone"], host="evil.example") == 421 # DNS rebinding: a Host not allowed + async with Client(http_transport(url, TOKENS["phone"]), mode="2026-07-28") as client: + assert not (await client.call_tool("about", {})).is_error + app.state.tokens.revoke(TOKENS["phone"]) # one client's token revoked alone + assert await post(TOKENS["phone"]) == 401 + with pytest.raises(BaseException): + async with Client(http_transport(url, TOKENS["phone"]), mode="2026-07-28") as client: + await client.call_tool("about", {}) + async with Client(http_transport(url, TOKENS["bot"]), mode="2026-07-28") as client: + assert not (await client.call_tool("about", {})).is_error + + +async def test_the_service_runs_the_sources_and_answers_a_tool_call_through_the_proxys_name(tmp_path, monkeypatch, caplog): + """A deploy check: `python -m ecobot_mcp` (main) with the fake sources, MCP_ALLOWED_HOSTS the name a reverse proxy sends, a + tool call with a token through that name answered, the archives run, then SIGTERM closes it all.""" + import ecobot_mcp.__main__ as service_main + from ecobot_mcp import core + from lib.config import Config + from lib.ecowitt import archive + from lib.airgradient import source as air_source + from tests.fakes import air_transport, config, ecowitt_transport + caplog.set_level("INFO") + port = free_port() + cfg = config(tmp_path, telegram_token="", auth_tokens=("pr0xy",), mcp_bind=("127.0.0.1", port), + mcp_allowed_hosts=("weather.lan",)) + eco_t, _ = ecowitt_transport(history_days=10) + air_t, _ = air_transport(oldest=datetime.now(timezone.utc) - timedelta(days=5)) + monkeypatch.setattr(Config, "from_env", classmethod(lambda cls, bot=True: cfg)) + 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.setattr(archive, "PACE_SECONDS", 0) + monkeypatch.setattr(air_source, "BACKFILL_PACE", 0) + monkeypatch.setattr(air_source, "BACKFILL_EMPTY_STOP", 3) + answered = {} + + async def ask_then_stop(): + await until(lambda: "MCP: http://127.0.0.1:" in caplog.text, 30, "the service to listen") + url = f"http://127.0.0.1:{port}/mcp" + from mcp.shared._httpx_utils import create_mcp_http_client + import contextlib + from mcp.client.streamable_http import streamable_http_client + + @contextlib.asynccontextmanager + async def through_the_proxy(): + headers = {"Authorization": "Bearer pr0xy", "Host": "weather.lan"} + async with create_mcp_http_client(headers=headers) as http: + async with streamable_http_client(url, http_client=http) as streams: + yield streams + async with Client(through_the_proxy(), mode="2026-07-28") as client: + answered["tools"] = [t.name for t in (await client.list_tools()).tools] + answered["current"] = json.loads((await client.call_tool("current", {"readings": ["temperature"]})).content[0].text) + answered["health"] = json.loads((await client.read_resource("ecobot://health")).contents[0].text) + answered["stranger"] = await post_status(url, "evil.example") # a Host it doesn't answer (127.0.0.1, localhost and its own + answered["own name"] = await post_status(url, socket.gethostname()) # hostname always are, beside MCP_ALLOWED_HOSTS) + await until(lambda: any("Backfill Ecowitt: " in l and " fetched/failed, " in l for l in caplog.text.splitlines()) + and "Backfill AirGradient:" in caplog.text, 60, "the archives") + os.kill(os.getpid(), signal.SIGTERM) + + async def post_status(url, host) -> int: + async with httpx.AsyncClient() as http: + return (await http.post(url, headers={"Authorization": "Bearer pr0xy", "Content-Type": "application/json", "Host": host}, + json={})).status_code + asker = asyncio.create_task(ask_then_stop()) + await service_main.main() + await asker + log = caplog.text + assert "Ecowitt: 'Fairleigh' (" in log and "Tools: current, summary" in log and "1 token(s)" in log + assert "MCP 127.0.0.1: POST /mcp tools/call current temperature -> 200" in log and "-> 421, its Host isn't in" in log # (the request log) + assert answered["tools"] == ["current", "summary", "readings", "days", "relate", "scan", "outlook", "about"] # (no forecast, no pollen) + assert answered["current"]["sensors"]["outdoor"]["temperature"]["unit"] + assert answered["stranger"] == 421 and answered["own name"] != 421 + assert "Ecowitt refresh" in answered["health"]["loops"] and answered["health"]["file"]["bytes"] > 0 + assert "Alerts NOT running" not in log and "Telegram" not in log + + +async def test_the_bot_s_warning_says_why_ecobot_mcp_refused_it(service, monkeypatch, caplog): + """The SDK reports every HTTP error as "Server returned an error response": the warning names the status and what to change.""" + monkeypatch.setattr(upstream, "BACKOFF", (0.1,)) + port = free_port() + async with Serving(http_app(service, tokens=TOKENS.values(), allowed_hosts=("localhost",)), port): + for url, token, want in ((f"http://localhost:{port}/mcp", "wrong", "401: the token sent isn't one ecobot-mcp accepts"), + (f"http://127.0.0.1:{port}/mcp", TOKENS["bot"], "421: ecobot-mcp doesn't answer to this address")): + caplog.clear() + task = asyncio.create_task(Upstream(url, token).run()) + for _ in range(100): + if want in caplog.text: + break + await asyncio.sleep(0.05) + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + assert want in caplog.text, caplog.text + + +async def test_each_request_is_logged_with_who_asked_what_and_a_refusal_with_its_reason(service, caplog): + caplog.set_level("INFO", logger="lib.mcp_server.requests") + port = free_port() + url = f"http://127.0.0.1:{port}/mcp" + async with Serving(http_app(service, tokens=TOKENS.values(), allowed_hosts=("127.0.0.1",)), port): + async with Client(http_transport(url, TOKENS["bot"]), mode="2026-07-28") as client: + assert not (await client.call_tool("about", {})).is_error + await client.call_tool("summary", {"readings": ["rain"], "period": "1d", "chart": True}) + await client.read_resource("ecobot://health") + async with httpx.AsyncClient() as http: + await http.post(url, json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, + headers={"Authorization": "Bearer wrong", "Accept": "application/json, text/event-stream"}) + await http.post(url, json={}, headers={"Authorization": f"Bearer {TOKENS['bot']}", "Host": "192.168.1.208:8765"}) + lines = [r.getMessage() for r in caplog.records if r.name == "lib.mcp_server.requests"] + assert any("MCP 127.0.0.1: POST /mcp tools/call about -> 200" in line for line in lines), lines + assert any("tools/call summary rain 1d -> 200" in line for line in lines), lines + assert any("resources/read ecobot://health -> 200" in line for line in lines), lines + assert any("refused: POST /mcp tools/list -> 401, no token, or one that isn't in AUTH_TOKENS" in line for line in lines), lines + assert any("-> 421, its Host isn't in MCP_ALLOWED_HOSTS (Host 192.168.1.208:8765)" in line for line in lines), lines + assert not any(TOKENS["bot"] in line or "wrong" in line for line in lines) + + +async def test_ecobot_mcp_down_for_a_moment_isnt_a_warning_but_down_for_longer_or_refusing_is(service, monkeypatch, caplog): + """A start or restart of either takes a few seconds: only QUIET_SECONDS of not reaching it is warned about, and the connection after + says how long it was down. A refusal (here the token) is warned about at once: it won't go away by itself.""" + caplog.set_level("DEBUG", logger="lib.upstream") + monkeypatch.setattr(upstream, "BACKOFF", (0.1,)) + 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(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): + for _ in range(100): + if "again, after" in caplog.text: + break + await asyncio.sleep(0.05) + assert f"connected to http://127.0.0.1:{port}/mcp again, after" in caplog.text + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py new file mode 100644 index 00000000..50031faa --- /dev/null +++ b/tests/test_mcp_server.py @@ -0,0 +1,666 @@ +"""The service over MCP (lib/mcp_server.py, docs/ecobot-mcp.md 3.4-3.8): the ten tools listed and called over the SDK's in-memory +transport with the same answers as the ServiceTools themselves, the resources and the alerts' template, the prompts, the publishing of +changes, the auth and the allowed hosts. The listen over the network is tests/test_mcp_listen.py's (under uvicorn, +as docs 7 asks).""" + +import asyncio +import base64 +import json +import os +import subprocess +import sys +import time +from types import SimpleNamespace as NS +from zoneinfo import ZoneInfo + +import mcp_types as types +import pytest +from mcp import Client +from mcp.server.subscriptions import ResourceUpdated, ToolsListChanged +from mcp.shared.exceptions import MCPError + +from lib import chart_images, charts, mcp_server +from lib.config import ROOT +from lib.alert_log import AlertLog +from lib.mcp_server import (ALERTS_TEMPLATE, ALERTS_URI, COMPLETE, PROMPTS, EcobotServer, TokenCheck, host_settings, prompt, + tool_result) +from lib.service.common import AS_DRAWN, CHART_POINTS +from lib.service.context import Context +from lib.service.names import Catalogue +from tests import evalkit, evalworld + +TZ = ZoneInfo("Australia/Melbourne") +EXPECT = evalkit.load_service_cases() + + +def at_eval_now(patch: pytest.MonkeyPatch): + evalworld.at_eval_now(patch, __name__) + + +@pytest.fixture(scope="module") +def eval_archive(shared_archive): + """The fake station's whole archive (its ecobot.sqlite) built at EVAL_NOW, the air's month held in it too (real_context), once for every + worker and run (tests/evalworld.py's).""" + return evalworld.shared_eval_archive(shared_archive) + + +@pytest.fixture +async def world(tmp_path, eval_archive, monkeypatch): + """The four sources (faked, the clock at the evals' NOW), an alert log, and the server over them.""" + at_eval_now(monkeypatch) + ctx = await evalworld.real_context(tmp_path, eval_archive) + alerts = AlertLog(tmp_path / "alerts.sqlite", ctx.zone) + server = EcobotServer(ctx, alerts, health=lambda: {"loops": {"Ecowitt refresh": {"last_ok": "now"}}}) + yield server + alerts.close() + await evalworld.close(ctx) + + +def first_call(tool: str) -> dict: + """An argument set the evals expect of this tool (any accepted call will do).""" + return next((args for expect in EXPECT.values() for name, args in evalkit.example_calls(expect) if name == tool), {}) + + +# ---------- tools ---------- +async def test_every_tool_is_listed_with_its_schema_and_hints_and_answers_as_the_service_tool_does(world): + async with Client(world.server) as client: + listed = {t.name: t for t in (await client.list_tools()).tools} + assert list(listed) == [t.name for t in world.service] and len(listed) == 10 + for tool in world.service: + entry = listed[tool.name] + assert entry.description == tool.description and entry.input_schema == tool.parameters + assert entry.annotations.read_only_hint is True and entry.annotations.open_world_hint is tool.open_world + args = first_call(tool.name) + for _ in range(10): # (what a call fetches inline, fetched first: the answers are then the same each time) + if await tool.call(args) == await tool.call(args): + break + got = await client.call_tool(tool.name, args) + assert got.content[0].text == await tool.call(args), tool.name + assert got.is_error is ("error" in json.loads(got.content[0].text)) + + +async def test_a_refusal_is_an_error_result_with_what_teaches_the_right_call_and_an_unknown_tool_a_protocol_error(world): + async with Client(world.server) as client: + got = await client.call_tool("summary", {"period": "the age of the dinosaurs"}) + assert got.is_error and "forms" in json.loads(got.content[0].text) + with pytest.raises(MCPError, match="No tool 'weather_now'"): + await client.call_tool("weather_now", {}) + + +async def test_the_requests_meta_reaches_the_tool_charts_come_whole_and_sized_by_chart_points(world): + args = {"readings": ["temperature"], "period": "last 7 days", "chart": True} + async with Client(world.server) as client: + default = json.loads((await client.call_tool("summary", args)).content[0].text) + small = json.loads((await client.call_tool("summary", args, meta={"chart_points": 40})).content[0].text) + (chart,) = default["charts"] + assert {"title", "period", "source", "drawn_by", "panels"} <= set(chart) # the full chart JSON (3.7) + longest = lambda c: max(len(s["points"]) for p in c["panels"] for s in p["series"]) + assert 40 < longest(chart) <= CHART_POINTS and longest(small["charts"][0]) <= 40 + assert default == json.loads(await world.service["summary"].call(args)) + + +async def test_a_complete_answer_carries_its_reply_for_the_person_and_the_complete_mark(world): + args = {"readings": ["pressure"], "period": "this week", "chart_answers_it": True} + async with Client(world.server) as client: + got = await client.call_tool("summary", args) + plain = await client.call_tool("summary", {"readings": ["pressure"], "period": "this week"}) + data = json.loads(got.content[0].text) + assert data["complete"] is True and len(got.content) == 2 + reply = got.content[1] + assert reply.text == data["reply"] and reply.annotations.audience == ["user"] + assert got.meta[COMPLETE] is True + assert len(plain.content) == 1 and COMPLETE not in (plain.meta or {}) + + +def test_a_result_is_complete_only_with_a_reply_and_no_error(): + assert tool_result('{"complete": true, "reply": "Pressure ...", "charts": []}').meta == {COMPLETE: True} + assert tool_result('{"complete": true}').meta is None and len(tool_result('{"complete": true}').content) == 1 + assert tool_result('{"error": "no"}').is_error and tool_result("not json").content[0].text == "not json" + + +async def test_the_tools_are_built_again_when_the_catalogue_gains_a_reading_and_listeners_are_told(world, monkeypatch): + seen = [] + world.bus.subscribe(seen.append) + assert await world.refresh_catalogue() is False and seen == [] # (nothing gained: nothing sent) + held = world.ctx.readings() + new = "outdoor.dew_point" # (as if the station had just sent it for the first time) + assert new in held.names + world.ctx.catalogue = Catalogue([r for r in held if r.name != new]) + world._service = world.service.of(world.ctx) + described = lambda: world.service["readings"].parameters["properties"]["reading"]["description"] + assert new not in described() + assert await world.refresh_catalogue() is True + assert seen == [ToolsListChanged(), ResourceUpdated("ecobot://station")] + assert new in described() and new in world.server.instructions or new.split(".")[1] in world.server.instructions + + +# ---------- the instructions ---------- +async def test_the_instructions_are_the_services_and_come_with_discover(world): + from lib.service.instructions import instructions + async with Client(world.server) as client: + assert client.instructions == instructions(world.ctx) and "Australia/Melbourne" in client.instructions + + +# ---------- resources ---------- +async def test_each_resource_is_listed_and_readable_as_json(world): + world.alert_log.append("rain", "🌧️ It's started raining", "Rain started", data={"mm": 0.4}, expires=None) + async with Client(world.server) as client: + assert json.loads((await client.read_resource("ecobot://now/weather")).contents[0].text)["unavailable"] # (none kept yet) + for name in ("current", "forecast"): # (the station's live reading and the forecast asked for, and kept: a resource fetches nothing) + await world.service[name].call({}) + listed = [r.uri for r in (await client.list_resources()).resources] + assert listed == list(mcp_server.RESOURCES) + read = {} + for uri in listed: + contents = (await client.read_resource(uri)).contents + content = contents[0] + assert content.mime_type == "application/json" and content.uri == uri + read[uri] = json.loads(content.text) + if uri == mcp_server.STATUS_URI: # the Status picture: its readings as JSON, then the picture (test_the_status_picture...) + assert [c.mime_type for c in contents] == ["application/json", "image/png"] + else: + assert len(contents) == 1 + station = read["ecobot://station"] + assert station["name"] == world.ctx.eco.station_name and station["time_zone"] == "Australia/Melbourne" + assert {"station", "air"} == set(station["sensors"]) and "temperature" in station["words"] + assert {r["name"] for r in station["sensors"]["station"]["readings"]} >= {"outdoor.temperature", "pressure.relative"} + assert set(station["sources"]) == {"Ecowitt", "AirGradient", "Forecast", "Pollen"} and station["history"]["station"]["held"] + assert {a["kind"] for a in station["alerts"]} >= {"rain", "gusts", "particulates", "forecast", "pollen_and_asthma"} + weather = read["ecobot://now/weather"] + assert weather["sensors"]["outdoor"]["temperature"]["unit"] and weather["lines"] and weather["as_of"] + air = read["ecobot://now/air"] + assert air["sensors"]["air"]["pm2_5"]["rating"] and "aqi_us" in air["sensors"]["air"]["pm2_5"] + assert [a["kind"] for a in read[ALERTS_URI]["alerts"]] == ["rain"] and read[ALERTS_URI]["last_id"] == 1 + forecast = read["ecobot://forecast"] + assert forecast["place"] == "Melbourne" and forecast["days"] and {"date", "min_c", "max_c", "text"} <= set(forecast["days"][0]) + assert {"in_season", "grass", "asthma", "fetched_at"} <= set(read["ecobot://pollen"]) + health = read["ecobot://health"] + assert health["file"]["bytes"] > 0 and health["alert_log"] == {"last_id": 1} and "Ecowitt refresh" in health["loops"] + assert read["ecobot://schema/chart"]["$id"] == "ecobot://schema/chart" + assert [g["title"] for g in read[mcp_server.STATUS_URI]["gauges"]] == ["Temperature", "Humidity", "Rain"] + + +async def test_the_status_picture_is_three_gauges_as_a_png_with_their_readings_as_json(world, monkeypatch): + """ecobot://status: the report in words (current's sections, today's forecast, the pollen: written in code, no model) and the + station's temperature, humidity and rain gauges drawn as a PNG (lib/gauges.py, from current with context, the three readings named), + after their readings and highs and lows as JSON; without Pillow, the JSON alone with a note.""" + import io + from PIL import Image + from lib import gauge_sheet, gauges, status + asked = [] + current = world.service["current"] + real = current.call + + async def call(args=None, meta=None): + asked.append(args) + return await real(args, meta) + monkeypatch.setattr(current, "call", call) + async with Client(world.server) as client: + (entry,) = [r for r in (await client.list_resources()).resources if str(r.uri) == mcp_server.STATUS_URI] + assert entry.mime_type == "image/png" + text, blob = (await client.read_resource(mcp_server.STATUS_URI)).contents + assert sorted(asked, key=len) == [{}, gauge_sheet.call(gauge_sheet.STATUS)] # the report's readings now, and the gauges' + data = json.loads(text.text) + assert data["report"] == await status.report(world.service) and data["report"].startswith("Weather station (") # written in code + assert "\n\nForecast (" in data["report"] + sheet = gauge_sheet.sheet(json.loads(await real(gauge_sheet.call(gauge_sheet.STATUS))), gauge_sheet.STATUS) + assert data["gauges"] == [status.gauge(t) for t in sheet.tiles] and data["lines"] == [status.line(t) for t in sheet.tiles] + assert data["gauges"][0]["value"] == sheet.tiles[0].value and set(data["gauges"][0]["rows"]) == {"Daily", "Monthly", "Yearly"} + assert data["lines"][0].startswith(f"Temperature: {sheet.tiles[0].value:.1f} °C (Daily: Max ") + png = base64.b64decode(blob.blob) + assert png == gauges.render(sheet) and Image.open(io.BytesIO(png)).size == (3 * gauges.CELL_W + 2 * gauges.MARGIN, + gauges.TILE_H + 2 * gauges.MARGIN) + monkeypatch.setattr(status, "_renderer", lambda: None) # (no Pillow) + async with Client(world.server) as client: + (alone,) = (await client.read_resource(mcp_server.STATUS_URI)).contents + assert json.loads(alone.text)["image_note"] == status.UNAVAILABLE_NOTE + + +async def test_a_resource_there_is_none_of_is_refused_naming_those_there_are(tmp_path): + server = EcobotServer(Context(tz=TZ), AlertLog(tmp_path / "a.sqlite", TZ)) + async with Client(server.server) as client: + listed = [r.uri for r in (await client.list_resources()).resources] + assert listed == ["ecobot://station", ALERTS_URI, "ecobot://health", "ecobot://schema/chart"] # (no sensor, no forecast, no pollen) + for uri in ("ecobot://now/weather", "ecobot://status", "ecobot://nowhere", "ecobot://health?x=1"): + with pytest.raises(MCPError, match="No resource") as e: + await client.read_resource(uri) + assert e.value.error.code == mcp_server.RESOURCE_NOT_FOUND + + +async def test_the_alerts_template_reads_after_an_id_and_leaves_the_expired_out_unless_asked(tmp_path): + alerts = AlertLog(tmp_path / "a.sqlite", TZ) + server = EcobotServer(Context(tz=TZ), alerts) + now = time.time() + alerts.append("rain", "It rained", "Rain", expires=now - 60) # 1: expired + alerts.append("gusts", "Gusty", "Gusts", expires=now + 3600) # 2 + alerts.append("uv", "UV high", "UV", expires=None) # 3: never expires + async with Client(server.server) as client: + (template,) = (await client.list_resource_templates()).resource_templates + assert template.uri_template == ALERTS_TEMPLATE + + async def ids(uri): + return [a["id"] for a in json.loads((await client.read_resource(uri)).contents[0].text)["alerts"]] + assert await ids(ALERTS_URI) == [2, 3] + assert await ids(f"{ALERTS_URI}?since=2") == [3] + assert await ids(f"{ALERTS_URI}?expired=true") == [1, 2, 3] + assert await ids(f"{ALERTS_URI}?since=1&expired=true") == [2, 3] + assert await ids(f"{ALERTS_URI}?since=3") == [] + with pytest.raises(MCPError, match="whole number"): + await ids(f"{ALERTS_URI}?since=last") + whole = json.loads((await client.read_resource(ALERTS_URI)).contents[0].text) + assert whole["last_id"] == 3 and whole["identity"] == alerts.identity + alerts.close() + + +# ---------- publishing ---------- +async def test_a_live_resource_is_published_when_its_reading_changes_and_not_when_it_repeats(tmp_path): + eco = NS(_live=None, storage=None, tz=TZ) + ctx = Context(eco=eco, tz=TZ) + ctx.catalogue = Catalogue([]) + server = EcobotServer(ctx, None) + seen = [] + server.bus.subscribe(seen.append) + assert await server.publish_changes() == [] # nothing kept yet + eco._live = (time.time(), {"outdoor": {"temperature": {"value": "12.3", "unit": "℃", "time": "1000"}}}) + assert await server.publish_changes() == ["ecobot://now/weather"] + eco._live = (time.time() + 5, {"outdoor": {"temperature": {"value": "12.3", "unit": "℃", "time": "1000"}}}) # the same reading again + assert await server.publish_changes() == [] + eco._live = (time.time() + 10, {"outdoor": {"temperature": {"value": "12.4", "unit": "℃", "time": "1060"}}}) + assert await server.publish_changes() == ["ecobot://now/weather"] + assert seen == [ResourceUpdated("ecobot://now/weather")] * 2 + + +async def test_a_new_alert_is_published_to_a_listener(tmp_path): + alerts = AlertLog(tmp_path / "a.sqlite", TZ) + server = EcobotServer(Context(tz=TZ), alerts) + publishing = asyncio.create_task(server.watch_alerts()) + try: + async with Client(server.server) as client: + async with client.listen(resource_subscriptions=[ALERTS_URI, "ecobot://now/weather"]) as sub: + alerts.append("gusts", "💨 A gust of 72 km/h", "Gusts", expires=time.time() + 3600) + event = await asyncio.wait_for(sub.__anext__(), 5) + assert event == ResourceUpdated(ALERTS_URI) + got = json.loads((await client.read_resource(f"{ALERTS_URI}?since=0")).contents[0].text) + assert [a["text"] for a in got["alerts"]] == ["💨 A gust of 72 km/h"] + finally: + publishing.cancel() + alerts.close() + + +# ---------- prompts ---------- +async def test_the_prompts_are_questions_in_words_with_their_period_an_argument(world): + async with Client(world.server) as client: + listed = {p.name: p for p in (await client.list_prompts()).prompts} + assert list(listed) == ["now", "report", "will_it_rain", "weather_chart", "chart", "rainfall", "air"] == list(PROMPTS) + assert [a.name for a in listed["chart"].arguments] == ["reading", "period"] and listed["chart"].arguments[0].required + got = await client.get_prompt("chart", {"reading": "pressure", "period": "this week"}) + assert got.messages[0].role == "user" and got.messages[0].content.text == "Chart pressure over this week." + with pytest.raises(MCPError, match="needs reading"): + await client.get_prompt("chart", {}) + assert prompt("rainfall").messages[0].content.text == "How much rain fell over today?" + assert prompt("air").messages[0].content.text == "How is the air quality now?" + assert prompt("air", {"period": "last week"}).messages[0].content.text == "How was the air quality over last week?" + assert prompt("weather_chart").messages[0].content.text == "Chart every weather reading, a panel each, over the last 7 days." + with pytest.raises(MCPError, match="No prompt"): + prompt("lightning") + + +# ---------- auth and hosts ---------- +async def test_a_token_is_one_of_auth_tokens_and_one_can_be_revoked_alone(): + check = TokenCheck(("s3cret-bot", "s3cret-phone")) + assert await check.verify_token("s3cret-bot") and await check.verify_token("s3cret-phone") + for wrong in ("", "s3cret", "s3cret-bot ", "S3CRET-BOT"): + assert await check.verify_token(wrong) is None + check.revoke("s3cret-phone") + assert await check.verify_token("s3cret-phone") is None and await check.verify_token("s3cret-bot") + + +def test_the_allowed_hosts_take_any_port_unless_one_is_named(): + settings = host_settings(("127.0.0.1", "weather.lan:443")) + assert settings.enable_dns_rebinding_protection + assert settings.allowed_hosts == ["127.0.0.1", "127.0.0.1:*", "weather.lan:443"] + assert "https://weather.lan:443" in settings.allowed_origins and "http://127.0.0.1:*" in settings.allowed_origins + + +def test_the_service_reads_its_settings_and_needs_no_telegram_token(monkeypatch, tmp_path, caplog): + from lib.config import Config + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + for key, value in {"MCP_ECOWITT_API_KEY": "a", "MCP_ECOWITT_APP_KEY": "b", "BOT_TELEGRAM_TOKEN": ""}.items(): + monkeypatch.setenv(key, value) + for key in ("AUTH_TOKENS", "MCP_BIND", "MCP_ALLOWED_HOSTS"): + monkeypatch.delenv(key, raising=False) + with pytest.raises(SystemExit, match="BOT_TELEGRAM_TOKEN is not set"): + Config.from_env() # the bot can't start without it ... + cfg = Config.from_env(bot=False) # ... the service can + assert cfg.auth_tokens == () and cfg.mcp_bind == ("127.0.0.1", 8765) and cfg.mcp_allowed_hosts == ("127.0.0.1", "localhost") + monkeypatch.setenv("AUTH_TOKENS", " s3cret , t0k:en,, s3cret") + monkeypatch.setenv("MCP_BIND", "0.0.0.0:9000") + monkeypatch.setenv("MCP_ALLOWED_HOSTS", "weather.lan, 192.168.1.5:9000") + cfg = Config.from_env(bot=False) + assert cfg.auth_tokens == ("s3cret", "t0k:en") and "s3cret" not in caplog.text + assert cfg.mcp_bind == ("0.0.0.0", 9000) and cfg.mcp_allowed_hosts == ("weather.lan", "192.168.1.5:9000") + for value, want in (("[::1]:8800", ("::1", 8800)), ("9001", ("127.0.0.1", 9001)), ("host:port", ("127.0.0.1", 8765)), + ("h:70000", ("127.0.0.1", 8765))): + monkeypatch.setenv("MCP_BIND", value) + assert Config.from_env(bot=False).mcp_bind == want, value + + +def test_one_service_per_data_folder(tmp_path): + """Two of python -m ecobot_mcp on one folder would both fetch and both write each alert.""" + import contextlib + from types import SimpleNamespace + + from ecobot_mcp.core import hold_data_folder + cfg = SimpleNamespace(state_path=tmp_path / "bot_state.json") + with contextlib.ExitStack() as first: + hold_data_folder(cfg, first) + with contextlib.ExitStack() as second, pytest.raises(SystemExit, match="Another ecobot-mcp .* already runs on"): + hold_data_folder(cfg, second) + with contextlib.ExitStack() as again: # free once the first has closed + hold_data_folder(cfg, again) + + +# ---------- chart images (3.7) ---------- +CHARTED = {"readings": ["temperature"], "period": "last 7 days", "chart": True} + + +def ours(result) -> dict: + """The result's _meta that is the service's own (not the SDK's serverInfo).""" + return {k: v for k, v in (result.meta or {}).items() if k.startswith("ecobot/")} + + +def images_of(result) -> list[bytes]: + return [base64.b64decode(b.data) for b in result.content if b.type == "image"] + + +async def test_without_images_asked_a_chart_comes_as_json_alone_as_before(world): + async with Client(world.server) as client: + plain = await client.call_tool("summary", CHARTED) + none = await client.call_tool("summary", CHARTED, meta={"chart_image": "none"}) + for got in (plain, none): + assert [b.type for b in got.content] == ["text"] and not ours(got) + assert got.content[0].text == await world.service["summary"].call(CHARTED) + + +async def test_a_call_asking_for_images_gets_each_chart_as_a_png_after_the_figures_and_the_charts_json_in_meta(world): + async with Client(world.server) as client: + got = await client.call_tool("summary", CHARTED, meta={"chart_image": "png"}) + dark = await client.call_tool("summary", CHARTED, meta={"chart_image": "png", "chart_dark": True}) + told = json.loads(got.content[0].text) + whole = json.loads(await world.service["summary"].call(CHARTED, {"chart_points": AS_DRAWN})) # (drawn from every point, as the bot's) + assert told["charts"] == [{"title": c["title"], "period": c["period"]} for c in whole["charts"]] + assert told["chart_note"] == chart_images.IMAGE_NOTE and told["caption"] == whole["caption"] + assert {k: v for k, v in told.items() if k not in ("charts", "chart_note")} == {k: v for k, v in whole.items() if k not in ("charts", "chart_note")} + assert got.meta[chart_images.CHARTS_META] == whole["charts"] and got.meta[chart_images.DARK_META] is False + (png,) = images_of(got) + assert got.content[1].mime_type == "image/png" and png.startswith(b"\x89PNG") + assert png == charts.render_data(whole["charts"][0], TZ, dark=False) # the bot's renderer, byte for byte + assert dark.meta[chart_images.DARK_META] is True and images_of(dark)[0] == charts.render_data(whole["charts"][0], TZ, dark=True) + assert not got.is_error and COMPLETE not in got.meta + + +async def test_a_complete_answer_with_images_still_carries_its_reply_for_the_person_last(world): + args = {"readings": ["pressure"], "period": "this week", "chart_answers_it": True} + async with Client(world.server) as client: + got = await client.call_tool("summary", args, meta={"chart_image": "png"}) + data = json.loads(got.content[0].text) + assert [b.type for b in got.content] == ["text", "image", "text"] and data["complete"] is True + assert got.content[2].text == data["reply"] and got.content[2].annotations.audience == ["user"] + assert got.meta[COMPLETE] is True and len(got.meta[chart_images.CHARTS_META]) == 1 + + +async def test_a_refusal_or_an_answer_without_a_chart_is_as_it_was_with_images_asked(world): + async with Client(world.server) as client: + refused = await client.call_tool("summary", {"period": "the age of the dinosaurs"}, meta={"chart_image": "png"}) + plain = await client.call_tool("current", {"readings": ["temperature"]}, meta={"chart_image": "png"}) + assert refused.is_error and [b.type for b in refused.content] == ["text"] and not ours(refused) + assert [b.type for b in plain.content] == ["text"] and not ours(plain) and "charts" not in json.loads(plain.content[0].text) + + +async def test_without_pillow_images_asked_for_give_the_json_with_a_note_and_one_warning(world, monkeypatch, caplog): + monkeypatch.setitem(sys.modules, "lib.charts", None) # (as if Pillow weren't installed: the import fails) + monkeypatch.setattr(chart_images, "_warned", False) + async with Client(world.server) as client: + first = await client.call_tool("summary", CHARTED, meta={"chart_image": "png"}) + again = await client.call_tool("summary", CHARTED, meta={"chart_image": "png"}) + for got in (first, again): + data = json.loads(got.content[0].text) + assert [b.type for b in got.content] == ["text"] and not ours(got) + assert data["chart_image_note"] == chart_images.UNAVAILABLE_NOTE + assert {k: v for k, v in data.items() if k != "chart_image_note"} == json.loads(await world.service["summary"].call(CHARTED)) + warned = [r for r in caplog.records if r.name == "lib.chart_images" and r.levelname == "WARNING"] + assert len(warned) == 1 and "requirements-charts.txt" in warned[0].getMessage() + + +def test_images_are_wanted_per_call_else_per_connection(): + assert not chart_images.wanted({}) and not chart_images.wanted({}, "json") and chart_images.wanted({}, "png") + assert chart_images.wanted({"chart_image": "png"}) and chart_images.wanted({"chart_image": "PNG"}, None) + assert not chart_images.wanted({"chart_image": "none"}, "png") and chart_images.wanted({"chart_image": "jpeg"}, "png") + assert chart_images.asked_dark({"chart_dark": True}) is True and chart_images.asked_dark({"chart_dark": "yes"}) is None + + +def test_the_service_imports_no_pillow_until_an_image_is_asked_for_and_no_telegram_ever(tmp_path): + """Importing the server and building its app (as python -m ecobot_mcp does) imports neither Pillow nor the renderer, nor the + Telegram library: the service knows nothing of Telegram.""" + code = ("import sys, ecobot_mcp.__main__; from zoneinfo import ZoneInfo; from lib.mcp_server import EcobotServer, http_app; " + "from lib.service.context import Context; http_app(EcobotServer(Context(tz=ZoneInfo('UTC'))), tokens=('t',)); " + "print(sorted(m for m in sys.modules if m.split('.')[0] in ('PIL', 'telegram') or m in ('lib.charts', 'lib.draw', 'lib.gauges')))") + done = subprocess.run([sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True, timeout=120, + env={**os.environ, "DATA_DIR": str(tmp_path)}) + assert done.returncode == 0, done.stderr + assert done.stdout.strip() == "[]" + + +async def test_over_http_the_connections_url_asks_for_images_and_a_call_can_say_otherwise(world): + from lib.upstream import http_transport + from tests.test_mcp_listen import Serving, free_port + port = free_port() + base = f"http://127.0.0.1:{port}/mcp" + async with Serving(mcp_server.http_app(world, tokens=("t",)), port): + async with Client(http_transport(f"{base}?charts=png", "t"), mode="2026-07-28") as client: + images = await client.call_tool("summary", CHARTED) + without = await client.call_tool("summary", CHARTED, meta={"chart_image": "none"}) + async with Client(http_transport(base, "t"), mode="2026-07-28") as client: + plain = await client.call_tool("summary", CHARTED) + asked = await client.call_tool("summary", CHARTED, meta={"chart_image": "png"}) + for got in (images, asked): + assert [b.type for b in got.content] == ["text", "image"] and len(got.meta[chart_images.CHARTS_META]) == 1 + assert images_of(got)[0] == charts.render_data(got.meta[chart_images.CHARTS_META][0], TZ, dark=False) + for got in (without, plain): + assert [b.type for b in got.content] == ["text"] and not ours(got) + assert got.content[0].text == await world.service["summary"].call(CHARTED) + + +def test_every_prompt_name_is_a_telegram_command_and_none_is_one_of_the_bots_own(): + """The bot offers each prompt as a /command (docs/ecobot-mcp.md step 6c): Telegram's form, and no clash with the keyboard's.""" + import re + from lib import templates + from lib.mcp_server import PROMPTS + for name in PROMPTS: + assert re.fullmatch(r"[a-z0-9_]{1,32}", name), name + assert not set(PROMPTS) & (set(templates.COMMANDS) - {"report"}) # (/report becomes the report prompt, step 6c) + + +# ---------- chart links (3.7: ?charts=link) ---------- +BASE = "https://example.org/ecobot-charts" + + +def link_ids(result) -> list[str]: + """The ids of a link-mode result's pictures, from its resource links.""" + return [str(b.uri).rsplit("/", 1)[-1].removesuffix(".png") for b in result.content if b.type == "resource_link"] + + +def headers_transport(url: str, token: str, headers: dict): + """http_transport with extra headers on every request (as a proxy would add them).""" + import contextlib + import httpx2 + from mcp.client.streamable_http import streamable_http_client + from mcp.shared._httpx_utils import create_mcp_http_client + + @contextlib.asynccontextmanager + async def connect(): + async with create_mcp_http_client(headers={"Authorization": f"Bearer {token}", **headers}, timeout=httpx2.Timeout(30.0)) as http: + async with streamable_http_client(url, http_client=http) as streams: + yield streams + return connect() + + +async def test_a_call_asking_for_links_gets_each_chart_s_url_and_markdown_and_a_resource_link_but_no_image(world): + world.chart_base_url = BASE + async with Client(world.server) as client: + got = await client.call_tool("summary", CHARTED, meta={"chart_image": "link"}) + png = await client.call_tool("summary", CHARTED, meta={"chart_image": "png"}) + told = json.loads(got.content[0].text) + whole = json.loads(await world.service["summary"].call(CHARTED, {"chart_points": AS_DRAWN})) + assert [b.type for b in got.content] == ["text", "resource_link"] and not images_of(got) + (chart,) = told["charts"] + (key,) = link_ids(got) + assert chart == {"title": whole["charts"][0]["title"], "period": whole["charts"][0]["period"], "url": f"{BASE}/{key}.png", + "markdown": f"![{whole['charts'][0]['title']}]({BASE}/{key}.png)"} + assert told["chart_note"] == chart_images.LINK_NOTE and "markdown" in told["chart_note"] + assert {k: v for k, v in told.items() if k not in ("charts", "chart_note")} == {k: v for k, v in whole.items() if k not in ("charts", "chart_note")} + link = got.content[1] + assert str(link.uri) == chart["url"] and link.name == chart["title"] and link.mime_type == "image/png" + assert got.meta[chart_images.CHARTS_META] == whole["charts"] and got.meta[chart_images.DARK_META] is False + assert len(key) >= 22 and world.chart_links.get(key)[0] == images_of(png)[0] # the picture png mode sends, byte for byte + assert not got.is_error and COMPLETE not in got.meta + + +async def test_a_complete_answer_with_links_has_the_markdown_image_in_its_reply_for_the_person(world): + world.chart_base_url = BASE + args = {"readings": ["pressure"], "period": "this week", "chart_answers_it": True} + async with Client(world.server) as client: + got = await client.call_tool("summary", args, meta={"chart_image": "link"}) + data = json.loads(got.content[0].text) + assert [b.type for b in got.content] == ["text", "resource_link", "text"] and data["complete"] is True + (chart,) = data["charts"] + assert data["reply"].endswith("\n\n" + chart["markdown"]) and got.content[2].text == data["reply"] + assert got.content[2].annotations.audience == ["user"] and got.meta[COMPLETE] is True + + +async def test_links_without_pillow_or_without_a_chart_are_as_with_images(world, monkeypatch): + async with Client(world.server) as client: + refused = await client.call_tool("summary", {"period": "the age of the dinosaurs"}, meta={"chart_image": "link"}) + plain = await client.call_tool("current", {"readings": ["temperature"]}, meta={"chart_image": "link"}) + monkeypatch.setitem(sys.modules, "lib.charts", None) + monkeypatch.setattr(chart_images, "_warned", True) + unavailable = await client.call_tool("summary", CHARTED, meta={"chart_image": "link"}) + assert refused.is_error and [b.type for b in refused.content] == ["text"] and not ours(refused) + assert [b.type for b in plain.content] == ["text"] and not ours(plain) + data = json.loads(unavailable.content[0].text) + assert [b.type for b in unavailable.content] == ["text"] and data["chart_image_note"] == chart_images.UNAVAILABLE_NOTE + assert "url" not in data["charts"][0] and len(world.chart_links) == 0 + + +def test_links_are_wanted_per_call_else_per_connection(): + assert chart_images.wanted({}, "link") == "link" and chart_images.wanted({"chart_image": "link"}) == "link" + assert chart_images.wanted({"chart_image": "png"}, "link") == "png" and chart_images.wanted({"chart_image": "link"}, "png") == "link" + assert chart_images.wanted({"chart_image": "none"}, "link") is None and chart_images.wanted({}, "LINK") == "link" + + +def test_the_links_store_is_bounded_by_count_and_bytes_and_forgets_after_its_hours(): + now = [1000.0] + links = chart_images.Links(hours=2, most=3, most_bytes=10, clock=lambda: now[0]) + a, b, c = links.put(b"aaa"), links.put(b"bbb"), links.put(b"ccc") + assert len({a, b, c}) == 3 and all(len(k) >= 22 for k in (a, b, c)) + assert links.get(a) == (b"aaa", 7200.0) + d = links.put(b"d") # a fourth: the oldest goes + assert links.get(a) is None and links.get(d)[0] == b"d" and len(links) == 3 + e = links.put(b"eeee") # 3 + 3 + 1 + 4 = 11 bytes > 10: the oldest goes again + assert links.get(b) is None and links.bytes == 8 and links.get(e)[0] == b"eeee" + now[0] += 3600 + assert links.get(c)[1] == 3600.0 + now[0] += 3600 # their two hours are up + assert links.get(c) is None and links.get(e) is None and len(links) == 0 and links.bytes == 0 + assert links.get("nope") is None + + +def test_a_charts_markdown_keeps_its_brackets_and_lines_out_of_the_way(): + assert chart_images.markdown("Rain [mm]\nlast week", "u") == "![Rain (mm) last week](u)" + assert chart_images.markdown(None, "u") == "![Chart](u)" + + +async def test_over_http_a_link_serves_the_png_without_a_token_or_an_allowed_host_while_mcp_still_needs_both(world, monkeypatch, caplog): + import httpx + from lib.upstream import http_transport + from tests.test_mcp_listen import Serving, free_port + caplog.set_level("INFO", logger="lib.mcp_server.requests") + now = [time.time()] + world.chart_links = chart_images.Links(hours=24, clock=lambda: now[0]) + port = free_port() + base = f"http://127.0.0.1:{port}/mcp" + async with Serving(mcp_server.http_app(world, tokens=("t",), dashboard=False), port): + async with Client(http_transport(f"{base}?charts=link", "t"), mode="2026-07-28") as client: + linked = await client.call_tool("summary", CHARTED) + as_png = await client.call_tool("summary", CHARTED, meta={"chart_image": "png"}) + without = await client.call_tool("summary", CHARTED, meta={"chart_image": "none"}) + async with Client(http_transport(f"{base}?charts=png", "t"), mode="2026-07-28") as client: + asked = await client.call_tool("summary", CHARTED, meta={"chart_image": "link"}) + async with Client(headers_transport(base, "t", {"X-Forwarded-Proto": "https", "X-Forwarded-Host": "weather.example.org"}), + mode="2026-07-28") as client: + forwarded = await client.call_tool("summary", CHARTED, meta={"chart_image": "link"}) + url = json.loads(linked.content[0].text)["charts"][0]["url"] + assert url == f"http://127.0.0.1:{port}/charts/{link_ids(linked)[0]}.png" # the MCP request's own address, with /charts + assert json.loads(forwarded.content[0].text)["charts"][0]["url"].startswith("https://weather.example.org/charts/") + async with httpx.AsyncClient() as http: + got = await http.get(url, headers={"Host": "evil.example"}) # no token, any Host + missing = await http.get(f"http://127.0.0.1:{port}/charts/{'x' * 22}.png") + other = await http.get(f"http://127.0.0.1:{port}/charts/{link_ids(linked)[0]}") + refused = await http.post(base, json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, + headers={"Accept": "application/json, text/event-stream"}) + now[0] += 24 * 3600 + 1 + expired = await http.get(url) + assert got.status_code == 200 and got.headers["content-type"] == "image/png" and got.content == images_of(as_png)[0] + assert got.headers["cache-control"].startswith("private, max-age=") and 0 < int(got.headers["cache-control"].rsplit("=")[-1]) <= 86400 + assert missing.status_code == other.status_code == expired.status_code == 404 and refused.status_code == 401 + assert [b.type for b in as_png.content] == ["text", "image"] and [b.type for b in without.content] == ["text"] + assert [b.type for b in asked.content] == ["text", "resource_link"] + lines = [r.getMessage() for r in caplog.records if r.name == "lib.mcp_server.requests"] + key = link_ids(linked)[0] + assert any(f"GET /charts/{key[:6]}….png -> 200" in line for line in lines), lines + assert any("-> 404, the chart's link has expired, or never was" in line for line in lines), lines + assert not any(key in line for line in lines) + + +async def test_the_links_base_url_is_the_setting_when_set(world): + from lib.upstream import http_transport + from tests.test_mcp_listen import Serving, free_port + world.chart_base_url = BASE + port = free_port() + async with Serving(mcp_server.http_app(world, tokens=("t",)), port): + async with Client(headers_transport(f"http://127.0.0.1:{port}/mcp?charts=link", "t", {"X-Forwarded-Host": "other.example"}), + mode="2026-07-28") as client: + got = await client.call_tool("summary", CHARTED) + assert json.loads(got.content[0].text)["charts"][0]["url"] == f"{BASE}/{link_ids(got)[0]}.png" + + +def test_the_request_base_reads_the_proxy_s_headers_else_the_request_s_own(): + from starlette.requests import Request + from lib.mcp_server import request_base + + def request(*headers): + return Request({"type": "http", "scheme": "http", "server": ("127.0.0.1", 8765), "path": "/mcp", "query_string": b"", + "headers": [(k.encode(), v.encode()) for k, v in headers]}) + assert request_base(request(("host", "127.0.0.1:8765"))) == "http://127.0.0.1:8765" + assert request_base(request(("host", "127.0.0.1:8765"), ("x-forwarded-proto", "https, http"), + ("x-forwarded-host", "api.example.org"))) == "https://api.example.org" + assert request_base(None) == "" + + +async def test_the_bot_on_a_link_connection_still_gets_its_pictures_and_its_charts_json(world): + from lib.weather import RemoteWeather + from tests.test_mcp_listen import Serving, free_port + port = free_port() + async with Serving(mcp_server.http_app(world, tokens=("t",)), port): + remote = RemoteWeather(f"http://127.0.0.1:{port}/mcp?charts=link", "t") + task = asyncio.create_task(remote.run()) + try: + await asyncio.wait_for(remote.listening.wait(), 20) + out, image = await remote.chart_image("summary", CHARTED, {"chart_dark": False}) + plain = json.loads(await remote.call_text("summary", CHARTED)) + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + await remote.close() + assert image.png == charts.render_data(out["charts"][0], TZ, dark=False) and "url" not in out["charts"][0] + assert "panels" in plain["charts"][0] and "url" not in plain["charts"][0] and len(world.chart_links) == 0 diff --git a/tests/test_migrate_env.py b/tests/test_migrate_env.py new file mode 100644 index 00000000..23950684 --- /dev/null +++ b/tests/test_migrate_env.py @@ -0,0 +1,124 @@ +"""scripts/migrate_env.py: an environment file's settings renamed to their new names, values, comments and order kept.""" + +import os +import stat +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) +import migrate_env # noqa: E402 + +from lib.config import Config, old_names # noqa: E402 +from dataclasses import fields # noqa: E402 + +OLD = """# keys +TELEGRAM_BOT_TOKEN=123:abc +export ECOWITT_API_KEY = "k e y" + +PLACE=Melbourne +WEATHER_MCP_URL=http://ecobot-service:8765/mcp +MCP_SERVICE_ALLOWED_HOSTS=127.0.0.1,localhost,ecobot-service +MCP_SERVICE_TOKENS=other,s3cret +WEATHER_MCP_TOKEN=s3cret +TZ=Australia/Melbourne +""" + + +def test_every_renamed_setting_is_found_from_the_configs_text(): + want = {old: f.metadata["env"] for f in fields(Config) for old in old_names(f)} + assert migrate_env.renames() == want + + +def test_a_file_is_renamed_keeping_values_comments_quotes_and_order_and_the_token_goes_first(): + out, notes = migrate_env.migrate(OLD.splitlines(keepends=True), migrate_env.renames()) + assert "".join(out) == """# keys +BOT_TELEGRAM_TOKEN=123:abc +export MCP_ECOWITT_API_KEY = "k e y" + +MCP_PLACE=Melbourne +BOT_MCP_URL=http://ecobot-mcp:8765/mcp +MCP_ALLOWED_HOSTS=127.0.0.1,localhost,ecobot-mcp +AUTH_TOKENS=s3cret,other +TZ=Australia/Melbourne +""" + assert any("put first" in n for n in notes) and any("WEATHER_MCP_TOKEN removed" in n for n in notes) + again, _ = migrate_env.migrate(out, migrate_env.renames()) + assert again == out # (run again: nothing changes) + + +def test_the_retired_token_alone_becomes_the_list(): + out, _ = migrate_env.migrate(["WEATHER_MCP_TOKEN=t0k\n"], migrate_env.renames()) + assert out == ["AUTH_TOKENS=t0k\n"] + + +def test_an_old_and_a_new_name_set_differently_stop_it_and_the_same_value_drops_the_old_line(): + with pytest.raises(SystemExit, match="PLACE and MCP_PLACE"): + migrate_env.migrate(["PLACE=a\n", "MCP_PLACE=b\n"], migrate_env.renames()) + out, _ = migrate_env.migrate(["PLACE=a\n", "MCP_PLACE=a\n"], migrate_env.renames()) + assert out == ["MCP_PLACE=a\n"] + + +def test_without_write_nothing_changes_and_secrets_are_masked_with_write_a_backup_keeps_mode(tmp_path, capsys): + env = tmp_path / "ecobot.env" + env.write_text(OLD) + os.chmod(env, 0o600) + assert migrate_env.main([str(env)]) == 0 + shown = capsys.readouterr().out + assert env.read_text() == OLD and "123:abc" not in shown and "s3cret" not in shown and "+BOT_TELEGRAM_TOKEN=****" in shown + assert migrate_env.main([str(env), "--write"]) == 0 + assert "BOT_TELEGRAM_TOKEN=123:abc" in env.read_text() and stat.S_IMODE(env.stat().st_mode) == 0o600 + backups = list(tmp_path.glob("ecobot.env.bak-*")) + assert len(backups) == 1 and backups[0].read_text() == OLD and stat.S_IMODE(backups[0].stat().st_mode) == 0o600 + assert migrate_env.main([str(env), "--write"]) == 0 and "nothing to rename" in capsys.readouterr().out + + +def test_a_setting_with_two_old_names_takes_either_and_the_irrigation_check_hour_keeps_its_name(): + """IRRIGATION_TUYA_* was BOT_TUYA_*, and before that TUYA_*; IRRIGATION_CHECK_HOUR was BOT_IRRIGATION_CHECK_HOUR (and before that + IRRIGATION_CHECK_HOUR itself, which stays as it is).""" + names = migrate_env.renames() + assert names["BOT_TUYA_DEVICE_ID"] == names["TUYA_DEVICE_ID"] == "IRRIGATION_TUYA_DEVICE_ID" + assert names["BOT_IRRIGATION_CHECK_HOUR"] == "IRRIGATION_CHECK_HOUR" and "IRRIGATION_CHECK_HOUR" not in names + out, _ = migrate_env.migrate(["TUYA_DEVICE_ID=d\n", "BOT_TUYA_CLIENT_ID=c\n", "IRRIGATION_CHECK_HOUR=7\n"], names) + assert out == ["IRRIGATION_TUYA_DEVICE_ID=d\n", "IRRIGATION_TUYA_CLIENT_ID=c\n", "BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp\n", + "IRRIGATION_CHECK_HOUR=7\n"] # (the bot's way to irrigation-mcp added: below) + out, notes = migrate_env.migrate(["TUYA_CLIENT_SECRET=s\n", "BOT_TUYA_CLIENT_SECRET=s\n"], names) # both old ones, the same value + assert out == ["IRRIGATION_TUYA_CLIENT_SECRET=s\n"] and any("BOT_TUYA_CLIENT_SECRET removed" in n for n in notes) + out, _ = migrate_env.migrate(["BOT_IRRIGATION_CHECK_HOUR=6\n", "IRRIGATION_CHECK_HOUR=6\n"], names) + assert out == ["IRRIGATION_CHECK_HOUR=6\n"] + with pytest.raises(SystemExit, match="BOT_TUYA_CLIENT_SECRET and TUYA_CLIENT_SECRET"): + migrate_env.migrate(["TUYA_CLIENT_SECRET=a\n", "BOT_TUYA_CLIENT_SECRET=b\n"], names) + with pytest.raises(SystemExit, match="BOT_IRRIGATION_CHECK_HOUR and IRRIGATION_CHECK_HOUR"): + migrate_env.migrate(["BOT_IRRIGATION_CHECK_HOUR=6\n", "IRRIGATION_CHECK_HOUR=7\n"], names) + + +def test_the_irrigation_controllers_settings_bring_the_bots_way_to_irrigation_mcp_once(): + """Step 8b: the controller is irrigation-mcp's and the bot its client; a file with any Tuya setting (any of its names, set) and no + BOT_IRRIGATION_MCP_URL gets it, after them, as systemd reaches irrigation-mcp, with a note (Docker's address in it).""" + names = migrate_env.renames() + out, notes = migrate_env.migrate(["TUYA_DEVICE_ID=d\n", "BOT_TUYA_CLIENT_SECRET=s\n", "TZ=Australia/Melbourne"], names) + assert out == ["IRRIGATION_TUYA_DEVICE_ID=d\n", "IRRIGATION_TUYA_CLIENT_SECRET=s\n", "BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp\n", + "TZ=Australia/Melbourne"] + assert any("BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp added" in n and "http://irrigation-mcp:8766/mcp" in n for n in notes) + again, notes = migrate_env.migrate(out, names) + assert again == out and notes == [] # (run again: nothing changes) + out, _ = migrate_env.migrate(["IRRIGATION_TUYA_DEVICE_ID=d"], names) # the last line, without its newline + assert out == ["IRRIGATION_TUYA_DEVICE_ID=d\n", "BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp\n"] + kept = ["IRRIGATION_TUYA_DEVICE_ID=d\n", "BOT_IRRIGATION_MCP_URL=http://irrigation-mcp:8766/mcp\n"] + assert migrate_env.migrate(kept, names) == (kept, []) # one already there (Docker's) is left alone + for none in (["TZ=UTC\n"], ["TUYA_DEVICE_ID=\n"], ["# TUYA_DEVICE_ID=d\n"], # no controller (unset, or commented out) + ["TUYA_BASE_URL=https://x\n"], ["BOT_TUYA_CLIENT_ID=c\n", "TUYA_CLIENT_SECRET=s\n"]): # (no device id: no controller) + assert "BOT_IRRIGATION_MCP_URL" not in "".join(migrate_env.migrate(none, names)[0]), none + + +@pytest.mark.parametrize("named", ["WEATHER_MCP_URL=http://ecobot-service:8765/mcp", "BOT_MCP_URL=http://ecobot-mcp:8765/mcp", + "MCP_ALLOWED_HOSTS=ecobot-mcp,ecobot.lan", "IRRIGATION_ECOBOT_MCP_URL=http://ecobot-mcp:8765/mcp"]) +def test_in_a_docker_install_s_file_the_bots_way_to_irrigation_mcp_is_its_container(named): + """A file that names ecobot-mcp's container (or its old name) in a URL or an allowed host is a Docker install's: there 127.0.0.1 is + the bot's own container, so the line added is http://irrigation-mcp:8766/mcp, and the note says so.""" + out, notes = migrate_env.migrate([named + "\n", "TUYA_DEVICE_ID=d\n"], migrate_env.renames()) + assert out[-1] == "BOT_IRRIGATION_MCP_URL=http://irrigation-mcp:8766/mcp\n" + assert any("BOT_IRRIGATION_MCP_URL=http://irrigation-mcp:8766/mcp added" in n and "Docker" in n for n in notes) + out, _ = migrate_env.migrate(["BOT_MCP_URL=http://my-ecobot-mcp.lan:8765/mcp\n", "TUYA_DEVICE_ID=d\n"], migrate_env.renames()) + assert out[-1] == "BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp\n" # (another name that merely contains it: systemd's) diff --git a/tests/test_minute_lines.py b/tests/test_minute_lines.py index b535e4bd..ecc9458c 100644 --- a/tests/test_minute_lines.py +++ b/tests/test_minute_lines.py @@ -5,12 +5,13 @@ from lib.ecowitt.api import MINUTE, cycle_seconds from lib.tools import Turn from tests.fakes import config, ecowitt_transport, home_assistant_transport +from tests import engines async def chart(eco, hours, groups="outdoor"): now = eco.now() turn = Turn() - out = json.loads(await eco.tools[1].handler({"groups": groups, "chart": True, "start_date": f"{now - timedelta(hours=hours):%Y-%m-%d %H:%M:%S}", + out = json.loads(await engines.history(eco, {"groups": groups, "chart": True, "start_date": f"{now - timedelta(hours=hours):%Y-%m-%d %H:%M:%S}", "end_date": f"{now:%Y-%m-%d %H:%M:%S}"}, turn)) return out, turn diff --git a/tests/test_packaging.py b/tests/test_packaging.py new file mode 100644 index 00000000..e547a99f --- /dev/null +++ b/tests/test_packaging.py @@ -0,0 +1,199 @@ +"""The programs as they are installed: three Docker images from one Dockerfile (each with only its own packages: the bot's no Pillow +and no source's, docs/ecobot-mcp.md step 6b; irrigation-mcp's no Telegram, no model client, no Pillow, step 8), compose running each from +its own, and the systemd units: ecobot-mcp's without the bot's +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 re +from dataclasses import fields +from pathlib import Path + +from lib.config import Config, old_names + +ROOT = Path(__file__).resolve().parent.parent + + +def requirements(name: str) -> set[str]: + found = set() + for line in (ROOT / name).read_text().splitlines(): + line = line.split("#")[0].strip() + if line.startswith("-r "): + found |= requirements(line[3:].strip()) + elif line: + found.add(re.split(r"[=<>!\[ ]", line)[0].lower()) + return found + + +def test_ecobot_mcp_needs_no_telegram_and_no_model_client_and_the_bot_only_its_own_packages(): + mcp, bot, both = requirements("requirements-mcp.txt"), requirements("requirements-bot.txt"), requirements("requirements.txt") + irrigation = requirements("requirements-irrigation.txt") + assert {"mcp", "uvicorn", "httpx"} <= mcp and not {"python-telegram-bot", "openai"} & mcp + assert bot == {"python-telegram-bot", "openai", "mcp", "httpx"} # no Pillow, no source's packages (holidays, zeroconf) + assert irrigation == {"mcp", "uvicorn", "httpx"} # irrigation-mcp: the server, its client, Tuya's client + assert both == mcp | bot | irrigation # (a systemd install's one venv: every program) + pins = lambda name: {line.split("#")[0].strip() for line in (ROOT / name).read_text().splitlines() if line.startswith(("mcp", "uvicorn"))} + assert {p for p in pins("requirements-mcp.txt") if p.startswith("mcp")} == pins("requirements-bot.txt") # the sides of MCP upgraded together + assert pins("requirements-irrigation.txt") == pins("requirements-mcp.txt") + + +def test_one_dockerfile_builds_both_images_each_checked_at_build(): + text = (ROOT / "Dockerfile").read_text() + assert re.search(r"^FROM app AS ecobot-mcp$", text, re.M) and re.search(r"^FROM app AS ecobot$", text, re.M) + mcp, bot = text.split("FROM app AS ecobot-mcp")[1].split("FROM app AS ecobot\n") + mcp, irrigation = mcp.split("FROM app AS irrigation-mcp") + assert "requirements-mcp.txt" in text.split("FROM base AS venv-mcp")[1].split("FROM base AS venv-bot")[0] + venv_bot = text.split("FROM base AS venv-bot")[1].split("FROM base AS venv-irrigation")[0] + venv_irrigation = text.split("FROM base AS venv-irrigation")[1].split("FROM base AS app")[0] + assert "-r /tmp/requirements-irrigation.txt" in venv_irrigation and "requirements-charts" not in venv_irrigation + assert "-r /tmp/requirements-bot.txt" in venv_bot and not re.search(r"requirements(-mcp|-charts)?\.txt", venv_bot.replace("requirements-bot.txt", "")) + assert 'CMD ["python", "-m", "ecobot_mcp"]' in mcp and "import ecobot_mcp.__main__" in mcp and "find_spec('telegram') is None" in mcp + assert 'CMD ["python", "ecobot.py"]' in bot and "import lib.bot, ecobot" in bot and "find_spec('PIL') is None" in bot + assert all(f"'{m}'" in bot for m in ("lib.ecowitt", "lib.airgradient", "lib.forecast", "lib.pollen", "lib.storage", + "lib.irrigation.tuya", "lib.irrigation.watchdog", "lib.irrigation.check")) # (irrigation-mcp's, 8b) + assert "lib.irrigation_remote" in bot + assert 'CMD ["python", "-m", "irrigation_mcp"]' in irrigation and "import irrigation_mcp.__main__" in irrigation + assert "find_spec('telegram') is None" in irrigation and "find_spec('PIL') is None" in irrigation and "'lib.storage'" in irrigation + ignored = (ROOT / ".dockerignore").read_text() + assert all(f"!{name}" in ignored for name in ("requirements-mcp.txt", "requirements-bot.txt", "requirements-irrigation.txt", "irrigation_mcp/")) + + +def test_compose_runs_each_program_from_its_own_image(): + text = (ROOT / "compose.yaml").read_text() + services = dict(re.findall(r"^ ([\w-]+):\n((?: .*\n|\s*\n)+)", text, re.M)) + mcp, bot, irrigation = services["ecobot-mcp"], services["ecobot"], services["irrigation-mcp"] + assert "image: irrigation-mcp" in irrigation and "target: irrigation-mcp" in irrigation and "profiles: [irrigation]" in irrigation + assert "IRRIGATION_BIND: 0.0.0.0:8766" in irrigation and "- 8766:8766" in irrigation and "docker/irrigation.env" in irrigation + assert "IRRIGATION_ECOBOT_MCP_URL=http://ecobot-mcp:8765/mcp" in (ROOT / "docker" / "irrigation.env").read_text() + assert "image: ecobot-mcp" in mcp and "target: ecobot-mcp" in mcp and "hostname: ecobot-mcp" in mcp and "- 8765:8765" in mcp + assert "image: ecobot\n" in bot and "target: ecobot\n" in bot and "profiles: [bot]" in bot and "depends_on: [ecobot-mcp]" in bot + assert "BOT_MCP_URL=http://ecobot-mcp:8765/mcp" in (ROOT / "docker" / "bot.env").read_text() + + +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()) + by_env = {f.metadata["env"]: old_names(f) for f in fields(Config) if f.metadata.get("env")} + for name in ("BOT_TELEGRAM_TOKEN", "BOT_OPENROUTER_API_KEY", "IRRIGATION_TUYA_CLIENT_ID", "IRRIGATION_TUYA_CLIENT_SECRET"): + assert {name, *by_env[name]} <= unset, name + assert "AUTH_TOKENS" not in unset and "ExecStart=/opt/ecobot/.venv/bin/python -m ecobot_mcp" in text + + +def test_an_old_ecobot_service_unit_still_starts_ecobot_mcp_without_the_bots_secrets_by_their_new_names(monkeypatch): + # an ecobot-mcp.service copied in before the rename runs python -m ecobot_service and unsets the bot's secrets by their old names + import ecobot_mcp.__main__ + import ecobot_service.__main__ as old + unit = set(re.search(r"^UnsetEnvironment=(.*)$", (ROOT / "ecobot-mcp.service").read_text(), re.M)[1].split()) + assert set(old.BOT_SECRETS) <= unit + environ = {name: "secret" for name in old.BOT_SECRETS} | {"MCP_ECOWITT_API_KEY": "k", "AUTH_TOKENS": "t"} + old.drop_bot_secrets(environ) + assert environ == {"MCP_ECOWITT_API_KEY": "k", "AUTH_TOKENS": "t"} + ran = [] + monkeypatch.setattr(ecobot_mcp.__main__, "run", lambda: ran.append(True)) + monkeypatch.setenv("BOT_TELEGRAM_TOKEN", "secret") + old.run() + assert ran == [True] and "BOT_TELEGRAM_TOKEN" not in __import__("os").environ + + +def test_the_systemd_upgrade_copies_the_ecobot_mcp_unit_in_again(): + text = (ROOT / "README.md").read_text() + upgrade = text.split("### systemd", 2)[2].split("### Docker")[0] + assert "sudo cp /opt/ecobot/ecobot-mcp.service /opt/ecobot/ecobot.service /etc/systemd/system/ && sudo systemctl daemon-reload && " \ + "sudo systemctl restart ecobot-mcp ecobot" in upgrade + assert "BOT_MCP_URL=http://127.0.0.1:8765/mcp" in upgrade and "sudo systemctl enable --now ecobot-mcp.service" in upgrade # (a bot + # that ran alone) + + +def test_the_bots_unit_wants_ecobot_mcps_and_starts_after_it_and_the_readme_installs_both(): + """Under systemd the bot is ecobot-mcp's client (step 6b): its unit pulls ecobot-mcp's in and starts after it, and the install + enables both, ecobot-mcp first.""" + unit = (ROOT / "ecobot.service").read_text() + wants = re.search(r"^Wants=(.*)$", unit, re.M)[1].split() + after = re.search(r"^After=(.*)$", unit, re.M)[1].split() + assert "ecobot-mcp.service" in wants and "ecobot-mcp.service" in after + readme = (ROOT / "README.md").read_text() + install = readme.split("### systemd", 1)[1].split("### ", 1)[0] + assert "sudo systemctl enable --now ecobot-mcp.service ecobot.service" in install # ecobot-mcp first + assert "/opt/ecobot/ecobot-mcp.service /opt/ecobot/ecobot.service /etc/systemd/system/" in install + assert "BOT_MCP_URL=http://127.0.0.1:8765/mcp" in install and "on its own (optional)" not in readme + + +def unit(name: str) -> tuple[str, dict[str, list[str]]]: + text = (ROOT / name).read_text() + keys = ("Wants", "After", "Before", "UnsetEnvironment", "ExecStart", "User", "StateDirectory", "Restart", "RestartPreventExitStatus") + return text, {k: (m[1].split() if (m := re.search(rf"^{k}=(.*)$", text, re.M)) else []) for k in keys} + + +def test_irrigation_mcps_unit_runs_it_after_ecobot_mcp_and_before_the_bot_without_the_others_secrets(): + """Step 8b: irrigation-mcp's own unit, from the same checkout and venv, the same dynamic user and data folder; it wants ecobot-mcp's + (its daily check asks it) and starts before the bot's; it drops the bot's and ecobot-mcp's secrets, by every name they have had.""" + text, irrigation = unit("irrigation-mcp.service") + assert irrigation["ExecStart"] == ["/opt/ecobot/.venv/bin/python", "-m", "irrigation_mcp"] + assert "ecobot-mcp.service" in irrigation["Wants"] and "ecobot-mcp.service" in irrigation["After"] and "ecobot.service" in irrigation["Before"] + assert irrigation["User"] == ["ecobot"] and irrigation["StateDirectory"] == ["ecobot"] # (the folder and its owner the others') + by_env = {f.metadata["env"]: old_names(f) for f in fields(Config) if f.metadata.get("env")} + for name in ("BOT_TELEGRAM_TOKEN", "BOT_OPENROUTER_API_KEY", "MCP_ECOWITT_API_KEY", "MCP_ECOWITT_APP_KEY", "MCP_AIRGRADIENT_API_TOKEN", + "MCP_HOMEASSISTANT_TOKEN"): + assert {name, *by_env[name]} <= set(irrigation["UnsetEnvironment"]), name + assert not any(n.startswith("IRRIGATION_") or n == "AUTH_TOKENS" for n in irrigation["UnsetEnvironment"]) + assert "WantedBy=multi-user.target" in text + from irrigation_mcp.__main__ import SETTINGS_EXIT # (without its settings it isn't restarted every 10 s for good) + assert irrigation["Restart"] == ["on-failure"] and irrigation["RestartPreventExitStatus"] == [str(SETTINGS_EXIT)] + + +def test_the_bots_unit_wants_irrigation_mcps_only_as_a_wish_and_drops_the_tuya_secrets(): + """The bot's unit wants irrigation-mcp's and starts after it (Wants=: a unit that isn't installed changes nothing, so the bot starts + without it), and never sees the controller's secrets, by any of their names; ecobot-mcp's starts before irrigation-mcp's.""" + _, bot = unit("ecobot.service") + assert "irrigation-mcp.service" in bot["Wants"] and "irrigation-mcp.service" in bot["After"] + assert not re.search(r"^(Requires|BindsTo|Requisite)=.*irrigation", (ROOT / "ecobot.service").read_text(), re.M) + by_env = {f.metadata["env"]: old_names(f) for f in fields(Config) if f.metadata.get("env")} + for name in ("IRRIGATION_TUYA_CLIENT_ID", "IRRIGATION_TUYA_CLIENT_SECRET"): + assert {name, *by_env[name]} <= set(bot["UnsetEnvironment"]), name + assert "IRRIGATION_TUYA_DEVICE_ID" not in bot["UnsetEnvironment"] # (kept: the bot warns when it is set and BOT_IRRIGATION_MCP_URL isn't) + assert "irrigation-mcp.service" in unit("ecobot-mcp.service")[1]["Before"] + + +def test_docker_leaves_the_bot_without_irrigation_unless_set_and_every_compose_file_covers_irrigation_mcp(): + bot_env = (ROOT / "docker" / "bot.env").read_text() + assert re.search(r"^BOT_IRRIGATION_MCP_URL=$", bot_env, re.M) and "http://irrigation-mcp:8766/mcp" in bot_env # (empty; how to set it) + host = (ROOT / "compose.host-network.yaml").read_text() + irrigation = host.split(" irrigation-mcp:\n")[1] + assert "network_mode: host" in irrigation and "ports: !reset []" in irrigation + assert "IRRIGATION_ECOBOT_MCP_URL: http://127.0.0.1:8765/mcp" in irrigation and "BOT_IRRIGATION_MCP_URL:" not in host + journald = (ROOT / "compose.journald.yaml").read_text() + assert all(f" {name}:\n logging: !override\n driver: journald" in journald for name in ("ecobot", "ecobot-mcp", "irrigation-mcp")) + services = dict(re.findall(r"^ ([\w-]+):\n((?: .*\n|\s*\n)+)", (ROOT / "compose.yaml").read_text(), re.M)) + irrigation = services["irrigation-mcp"] + assert "depends_on: [ecobot-mcp]" in irrigation and "- /var/lib/private/ecobot:/data" in irrigation + assert "env_file: [docker/irrigation.env, /etc/ecobot.env]" in irrigation # (/etc/ecobot.env after: its settings win, as the bot's) + + +def test_the_readme_installs_and_upgrades_irrigation_mcp_for_systemd_and_docker(): + readme = (ROOT / "README.md").read_text() + irrigation = readme.split("### Irrigation\n", 1)[1].split("\n## ", 1)[0] + assert "BOT_IRRIGATION_MCP_URL=http://127.0.0.1:8766/mcp" in irrigation and "BOT_IRRIGATION_MCP_URL=http://irrigation-mcp:8766/mcp" in irrigation + assert "sudo cp /opt/ecobot/irrigation-mcp.service /etc/systemd/system/" in irrigation and "COMPOSE_PROFILES=bot,irrigation" in irrigation + assert "sudo systemctl enable --now irrigation-mcp.service" in irrigation + assert all(f"IRRIGATION_TUYA_{n}=" in irrigation for n in ("DEVICE_ID", "CLIENT_ID", "CLIENT_SECRET")) + upgrade = readme.split("## Upgrading", 1)[1].split("\n## ", 1)[0] + systemd, docker = upgrade.split("### systemd", 1)[1].split("### Docker", 1) + assert "irrigation-mcp.service" in systemd and "From a bot that ran the irrigation controller itself" in systemd + assert "From a bot that ran the irrigation controller itself" in docker and "http://irrigation-mcp:8766/mcp" in docker + + +def test_no_workflow_has_a_plain_value_yaml_would_read_as_a_mapping(): + # A plain (unquoted) value with ": " in it, or ending in ":", is a YAML error, and GitHub then fails the workflow at once with no + # job (docker.yml's "Charts drawn … (the bot's draws none: it has no Pillow)" did). PyYAML isn't a dependency, so this reads the + # one-line `key: value` forms the workflows use, leaving block scalars (`run: |`) and quoted or flow values alone. + bad = [] + for path in sorted((ROOT / ".github" / "workflows").glob("*.yml")): + for n, line in enumerate(path.read_text().splitlines(), 1): + m = re.match(r"^\s*(?:- )?[\w-]+: (.+)$", line) + if not m: + continue + value = re.sub(r"\s+#.*$", "", m.group(1)).strip() + if not value or value[0] in "\"'[{|>&*!": + continue + if ": " in value or value.endswith(":"): + bad.append(f"{path.name}:{n}: {line.strip()}") + assert not bad, "quote these values:\n" + "\n".join(bad) diff --git a/tests/test_partday.py b/tests/test_partday.py new file mode 100644 index 00000000..05a50c20 --- /dev/null +++ b/tests/test_partday.py @@ -0,0 +1,244 @@ +"""Part of each day (lib/partday.py): a sensor's figures over a stretch of each day, checked against stretches worked out by hand on a +small file, and for the whole day against the day rows.""" + +import random +from datetime import date, datetime, time, timedelta + +import pytest + +from lib.partday import CLOCK_CHANGE, NOT_HELD, NOT_OVER, SECONDS, Stretch, over, parse_stretch, stretch_figures +from lib.storage import Storage +from lib.storage.catalogue import CLOUD, RAIN_COUNTERS +from lib.storage.days import utc_days +from lib.storage.read import DAY_PARTS +from lib.timeutil import day_bounds, local_epoch +from tests.fakes import TZ + +MAC, LOC = "M", "42" +NOW = local_epoch(datetime(2026, 11, 10, 14, 5), TZ) # Tue 10 Nov 2026 2:05pm +DAY = timedelta(days=1) + + +def at(d: date, hour: int, minute: int = 0) -> int: + """The epoch of a local time (the first, in the hour that happens twice).""" + return local_epoch(datetime.combine(d, time(hour, minute)), TZ) + + +@pytest.fixture +def storage(tmp_path): + s = Storage(tmp_path / "ecobot.sqlite", TZ) + yield s + s.close() + + +def put(storage, group: str, res: str, rows: list[dict], start: int, end: int): + """Readings written as a source writes them (an Ecowitt group's, or the air sensor's: "air"), [start, end] held at `res`.""" + def write(w): + s = w.air_sensor(LOC) if group == "air" else w.ecowitt_sensor(MAC, group) + w.put(s, res, rows, CLOUD) + w.cover(s, res, start, end) + return s + return storage.writer.run(write, ()) + + +def figures(storage, sensor, first: date, last: date, stretch: str, columns: list[str] | None = None, now: int = NOW): + return storage.reader.run(lambda r: stretch_figures(r, sensor.kind, sensor, first, last, stretch, columns, TZ, now), ()) + + +# ---------- the stretches ---------- +def test_a_stretch_is_named_two_times_on_the_half_hour_or_a_moment_and_anything_else_says_what_is_allowed(): + assert parse_stretch(" Night ") == Stretch(22 * 60, 6 * 60, "night") and parse_stretch("night").overnight + assert [(parse_stretch(n).start, parse_stretch(n).end) for n in ("morning", "afternoon", "evening", "daytime")] == [ + (360, 720), (720, 1080), (1080, 1440), (360, 1080)] + assert parse_stretch("22:30-06:00") == Stretch(1350, 360) and parse_stretch("22:30-06:00").overnight + assert parse_stretch("18:00-00:00") == parse_stretch("18:00-24:00") == Stretch(1080, 1440) # to midnight, not the evening before + assert parse_stretch("15:00") == parse_stretch("15:00-15:05") == Stretch(900, 905) and parse_stretch("15:00").moment + assert parse_stretch("night").text == "night (22:00–06:00)" and parse_stretch("15:30").text == "15:30" + for wrong in ("15:10", "15:00-15:10", "15:00-15:07", "3pm", "24:00-02:00", "06:00-06:00", "15:60", "25:00", "dawn", ""): + with pytest.raises(ValueError, match=r"night \(22:00-06:00\).*a moment on the hour or half hour"): + parse_stretch(wrong) + + +def test_today_counts_once_its_stretch_is_over(storage): + today = date(2026, 11, 10) + night, three = parse_stretch("night"), parse_stretch("15:00") + assert not over(night, today, TZ, at(today, 5, 59)) and over(night, today, TZ, at(today, 6)) + assert not over(three, today, TZ, at(today, 15, 4)) and over(three, today, TZ, at(today, 15, 5)) + seven = at(today, 7) + s = put(storage, "outdoor", "5min", [{"ts": t, "temperature": 9.0} for t in range(at(today - DAY, 12), seven, 300)], + at(today - DAY, 12), seven - 1) + assert figures(storage, s, today, today, "night", now=seven).days.day == [today] # last night, asked this morning + assert figures(storage, s, today, today, "morning", now=seven).left_out == {today: NOT_OVER} + + +# ---------- the figures ---------- +def test_a_night_starts_the_evening_before_and_belongs_to_the_day_it_ends_on(storage): + mon, tue = date(2026, 11, 2), date(2026, 11, 3) + coldest = at(tue, 4, 30) + temp = lambda t: round(2 + abs(t - coldest) / 3600, 2) # 2° at 4:30am, a degree warmer for each hour either side + s = put(storage, "outdoor", "5min", [{"ts": t, "temperature": temp(t)} for t in range(at(mon, 0), at(tue, 12), 300)], + at(mon, 0), at(tue, 12) - 1) + got = figures(storage, s, mon, tue, "night", ["temperature"]) + assert got.left_out == {mon: NOT_HELD} # (Monday's night began on Sunday evening, which isn't held) + assert got.windows == {tue: (at(mon, 22), at(tue, 6))} and got.missing == [] + days, night = got.days, [temp(t) for t in range(at(mon, 22), at(tue, 6), 300)] + assert (days.day, days.source, days.complete, days.n) == ([tue], ["5min"], [True], [96]) + assert (days.lo["temperature"], days.lo_ts["temperature"]) == ([2.0], [coldest]) + assert (days.hi["temperature"], days.hi_ts["temperature"]) == ([8.5], [at(mon, 22)]) # not 9:55pm's 8.58: before the night + assert days.mean["temperature"] == [pytest.approx(sum(night) / len(night))] + + +def test_the_clock_changes_make_a_night_9_or_7_hours_and_the_hour_october_skips_is_left_out(storage): + april, october = date(2026, 4, 5), date(2026, 10, 4) # Melbourne: 2am happens twice, then 2am is 3am + for d in (april, october): + start, end = at(d - DAY, 0), at(d + DAY, 0) + s = put(storage, "outdoor", "5min", [{"ts": t, "temperature": 10.0 + (t - start) / 3600} for t in range(start, end, 300)], + start, end - 1) + night = figures(storage, s, april, october, "night") + assert night.days.day == [april, october] and night.days.n == [9 * 12, 7 * 12] + assert set(night.left_out.values()) == {NOT_HELD} + skipped, twice = (figures(storage, s, d, d, "02:00-03:00") for d in (october, april)) + assert (skipped.left_out, skipped.days.day) == ({october: CLOCK_CHANGE}, []) + assert twice.days.n == [24] and twice.windows[april] == (at(april, 2), at(april, 3)) # 2:00 AEDT to 3:00 AEST: both of its 2ams + part = figures(storage, s, october, october, "01:30-02:30") # what is left of it: 1:30 to the jump + assert part.days.n == [6] and part.windows[october] == (at(october, 1, 30), at(october, 3)) + assert figures(storage, s, october, october, "02:30").left_out == {october: CLOCK_CHANGE} + first = figures(storage, s, april, april, "02:30") # the first 2:30 of the two + assert first.windows[april] == (at(april, 2, 30), at(april, 2, 30) + 300) and first.days.n == [1] + + +def test_a_moment_is_the_5_minute_reading_at_that_time_or_on_a_coarser_day_the_half_hour_or_hour_that_holds_it(storage): + coarse, fine = date(2026, 11, 2), date(2026, 11, 3) + a, b = day_bounds(fine, TZ, True) + s = put(storage, "outdoor", "5min", [{"ts": t, "temperature": 10 + (t - a) / 30000} for t in range(a, b, 300)], a, b) + a, b = day_bounds(coarse, TZ, True) + put(storage, "outdoor", "30min", [{"ts": t, "temperature": 20 + i, "temperature_lo": 19.5 + i, "temperature_hi": 21 + i} + for i, t in enumerate(range(a, b, 1800))], a, b) + got = figures(storage, s, coarse, fine, "15:00") + days = got.days + assert days.day == [coarse, fine] and days.source == ["30min", "5min"] and days.n == [1, 1] + assert got.windows == {coarse: (at(coarse, 15), at(coarse, 15, 30)), fine: (at(fine, 15), at(fine, 15, 5))} + assert days.mean["temperature"] == [50.0, pytest.approx(10 + 15 * 3600 / 30000)] # (not 3:05's) + assert days.lo["temperature"] == [49.5, pytest.approx(10 + 15 * 3600 / 30000)] + assert days.hi["temperature"] == [51.0, pytest.approx(10 + 15 * 3600 / 30000)] # the half hour's own lowest and highest + assert days.hi_ts["temperature"] == [at(coarse, 15), at(fine, 15)] + assert got.note == "15:00 is the 5-minute reading at that time; on 1 day held only as 30-minute averages, the half hour from it." + a, b = day_bounds(coarse, TZ, True) + air = put(storage, "air", "1hour", [{"ts": t, "pm2_5": float(i)} for i, t in enumerate(range(a, b, 3600))], a, b) + hourly = figures(storage, air, coarse, coarse, "15:30") + assert hourly.windows == {coarse: (at(coarse, 15), at(coarse, 16))} and hourly.days.mean["pm2_5"] == [15.0] + assert "on 1 day held only as hourly averages, the hour that holds it" in hourly.note + assert figures(storage, s, fine, fine, "15:00").note is None + + +def test_a_day_held_only_as_daily_records_or_in_part_is_left_out_and_one_held_with_no_readings_is_missing(storage): + old, off, part = date(2025, 3, 10), date(2025, 3, 11), date(2025, 3, 12) + first, last = utc_days(old, TZ) + with storage.writer.transaction() as w: + s = w.ecowitt_sensor(MAC, "outdoor") + w.put(s, "1day", [{"ts": first, "temperature": 15.0, "temperature_lo": 8.0, "temperature_hi": 22.0}]) + w.put(s, "4hour", [{"ts": first + 4 * 3600 * i, "temperature": 15.0} for i in range(6)]) + w.cover(s, "1day", first, last + 86400 - 1) + w.cover(s, "4hour", first, last + 86400 - 1) + w.cover(s, "5min", *day_bounds(off, TZ, True)) # the station was off + w.put(s, "5min", [{"ts": t, "temperature": 11.0} for t in range(at(part, 0), at(part, 12), 300)]) + w.cover(s, "5min", at(part, 0), at(part, 12) - 1) # the morning held, the afternoon not + assert storage.reader.run(lambda r: r.days("climate", [s.id], old, old)[s.id].source, ()) == ["1day"] # (a day row, all the same) + got = figures(storage, s, old, part, "00:00-24:00") + assert got.left_out == {old: NOT_HELD, part: NOT_HELD} and got.missing == [off] and got.days.day == [] + assert figures(storage, s, part, part, "morning").days.n == [72] + + +def test_rain_over_a_stretch_is_what_fell_in_it_not_the_running_total_since_midnight(storage): + mon, tue, wed = date(2026, 11, 2), date(2026, 11, 3), date(2026, 11, 4) + fell = {at(mon, 18) + 300 * i: 0.2 for i in range(30)} # 6 mm on Monday evening, then dry all night + fell |= {at(tue, 15) + 300 * i: 0.2 for i in range(5)} # 1 mm on Tuesday afternoon + fell |= {at(tue, 23) + 300 * i: 0.1 for i in range(5)} # 0.5 mm late on Tuesday evening ... + fell |= {at(wed, 2) + 300 * i: 0.1 for i in range(3)} # ... and 0.3 after midnight + start, end = at(mon, 0), at(wed, 12) + rows, total = [], 0.0 + for t in range(start, end, 300): + total = (0.0 if t in (at(tue, 0), at(wed, 0)) else total) + fell.get(t, 0.0) # the daily total, from 0 at midnight + rows.append({"ts": t, "daily": round(total, 1), "rain_rate": 2.4 if t in fell else 0.0}) + s = put(storage, "rainfall", "5min", rows, start, end - 1) + nights = figures(storage, s, tue, wed, "night", ["daily", "rain_rate"]).days + assert nights.hi["daily"] == [0.0, pytest.approx(0.8)] # not Monday's 6 mm, held all night as the day's total + assert nights.hi_ts["daily"] == [None, at(wed, 2, 10)] and nights.mean["daily"] == nights.lo["daily"] == [None, None] + assert nights.hi["rain_rate"] == [0.0, 2.4] # (the rest as a day row has them) + window = (s.id, tue, at(mon, 22), at(tue, 6) - 1, "5min") + assert storage.reader.run(lambda r: r.part_days("rain", [window], ["daily"])[s.id].hi["daily"], ()) == [6.0] # (what it isn't) + assert figures(storage, s, mon, tue, "evening", ["daily"]).days.hi["daily"] == [pytest.approx(6.0), pytest.approx(0.5)] + assert figures(storage, s, mon, tue, "afternoon", ["daily"]).days.hi["daily"] == [0.0, pytest.approx(1.0)] + + +def test_the_reading_before_a_stretch_may_be_at_the_other_resolution(storage): + """A 5-minute day after one held only at 30 minutes: the rain in its first 5 minutes is the rise from the half hour before.""" + mon, tue = date(2026, 11, 2), date(2026, 11, 3) + a, b = day_bounds(mon, TZ, True) + put(storage, "rainfall", "30min", [{"ts": t, "daily": 3.0} for t in range(a, b, 1800)], a, b) + a, b = day_bounds(tue, TZ, True) + s = put(storage, "rainfall", "5min", [{"ts": t, "daily": 0.4} for t in range(a, b, 300)], a, b) # 0.4 mm in its first 5 minutes + assert figures(storage, s, tue, tue, "00:00-24:00", ["daily"]).days.hi["daily"] == [0.4] + + +def test_an_air_glitch_inside_the_stretch_is_taken_out_and_a_rise_that_lasts_is_not(storage): + d = date(2026, 11, 3) + start, end = at(d - DAY, 12), at(d, 12) + pm = {t: 5.0 for t in range(start, end, 300)} + pm[at(d - DAY, 22)] = pm[at(d, 2)] = 60.0 # one reading far above those either side: a glitch (at the night's edge too) + pm[at(d, 4)] = pm[at(d, 4, 5)] = 30.0 # two in a row: the air + s = put(storage, "air", "5min", [{"ts": t, "pm2_5": v} for t, v in pm.items()], start, end - 1) + days = figures(storage, s, d, d, "night", ["pm2_5"]).days + assert (days.hi["pm2_5"], days.hi_ts["pm2_5"]) == ([30.0], [at(d, 4)]) + assert days.n == [96 - 2] # (the two glitches' readings held nothing else) + assert figures(storage, s, d, d, "02:00-03:00", ["pm2_5"]).days.hi["pm2_5"] == [5.0] + + +# ---------- the whole day ---------- +def _same(got: list, row: list) -> bool: + return all(g == pytest.approx(r) if isinstance(r, float) else g == r for g, r in zip(got, row, strict=True)) + + +def _running(times: range, rng: random.Random): + """(ts, the day's running rain total) at each reading: from 0 at local midnight, a shower now and then after the day's first hour.""" + total = 0.0 + for t in times: + local = datetime.fromtimestamp(t, TZ) + if local.time() == time(0): + total = 0.0 + elif local.hour >= 1: + total += rng.choice([0.0] * 6 + [0.2, 0.6]) + yield t, round(total, 1) + + +@pytest.mark.parametrize("group, res", [("outdoor", "5min"), ("outdoor", "30min"), ("air", "5min"), ("air", "1hour")]) +def test_the_whole_day_has_its_day_rows_figures_wherever_it_is_held_whole(storage, group, res): + """"00:00-24:00" over days held whole, a clock-change day among those at 5 minutes: each reading's figures, n and the resolution are + its day row's (the rain counters' total too: the day's starts at midnight).""" + rng = random.Random(f"{group} {res}") + first, last = (date(2026, 4, 4), date(2026, 4, 6)) if res == "5min" else (date(2026, 2, 27), date(2026, 3, 1)) + start, end = at(first, 0), at(last + DAY, 0) + times = range(start, end, SECONDS[res]) + if group == "air": # a glitch now and then + rows = [{"ts": t, "pm2_5": 60.0 if rng.random() < 0.05 else rng.uniform(3, 9), "co2": rng.uniform(400, 900)} for t in times] + else: + rows = [{"ts": t, "temperature": round(rng.uniform(5, 25), 1), "humidity": float(round(rng.uniform(40, 99)))} for t in times] + if res == "30min": + rows = [row | {"temperature_lo": row["temperature"] - rng.uniform(0, 2), "temperature_hi": row["temperature"] + rng.uniform(0, 2)} + for row in rows] + sensors = [put(storage, group, res, rows, start, end - 1)] + if group == "outdoor": + if res == "5min": # the half hours' own lows and highs, which a day of 5-minute readings takes in + put(storage, "outdoor", "30min", [{"ts": t, "temperature": 15.0, "temperature_lo": rng.uniform(1, 5), + "temperature_hi": rng.uniform(26, 30)} for t in range(start, end, 1800)], start, end - 1) + sensors.append(put(storage, "rainfall", res, [{"ts": t, "daily": v} for t, v in _running(times, rng)], start, end - 1)) + for s in sensors: + got = figures(storage, s, first, last, "00:00-24:00").days + row = storage.reader.run(lambda r: r.days(s.kind, [s.id], first, last)[s.id], ()) + assert got.day == row.day == [first, first + DAY, last] and got.source == row.source == [res] * 3 + assert (got.n, got.complete, set(got.mean)) == (row.n, row.complete, set(row.mean)) + for c in row.mean: + for part in ("hi", "hi_ts") if c in RAIN_COUNTERS else DAY_PARTS: + assert _same(getattr(got, part)[c], getattr(row, part)[c]), (c, part) + if res == "5min": + assert got.n[1] == 25 * 12 # (the day the clocks went back) diff --git a/tests/test_periods.py b/tests/test_periods.py index bfb00c89..7399ac5c 100644 --- a/tests/test_periods.py +++ b/tests/test_periods.py @@ -1,14 +1,19 @@ +import asyncio import json from datetime import datetime from types import SimpleNamespace as NS from lib import bot as botmod -from lib import intent, periods +from lib import periods from lib.bot import Bot -from lib.specs import Chart, Line, Panel -from tests.fakes import TZ, StandInTools +from lib.service.summary import OVER_TIME +from lib.specs import Chart, Line, Panel, to_json +from tests.fakes import draws, TZ +from tests.served import unreached NOW = datetime(2026, 10, 2, 12, 0) +SORRY = "Sorry, I couldn't draw that chart, please ask again" +ROW = [("1D", "pd:1d"), ("7D", "pd:7d"), ("1M", "pd:1m"), ("3M", "pd:3m"), ("1Y", "pd:1y")] # summary's periods, as its drawn_by lists them def labels(markup): @@ -20,62 +25,97 @@ def shaded(markup): return [b.text for row in markup.inline_keyboard for b in row if b.style == "primary"] -def test_the_row_is_always_week_month_quarter_and_year(): - assert labels(periods.keyboard()) == [[("1D", "pd:1"), ("7D", "pd:7"), ("1M", "pd:30"), ("3M", "pd:90"), ("1Y", "pd:365")]] - assert [t for t, _ in labels(periods.keyboard(30))[0]] == ["1D", "7D", "1M", "3M", "1Y"] and shaded(periods.keyboard(30)) == ["1M"] # the chart's own period is shaded - assert shaded(periods.keyboard(61)) == [] and shaded(periods.keyboard()) == [] - assert shaded(periods.keyboard(365)) == ["1Y"] - assert periods.days_in("pd:1") == 1 and periods.days_in("pd:90") == 90 and periods.days_in("pd:365") == 365 and periods.days_in("pd:30000") is None and periods.days_in("al:on:x") is None +def test_a_charts_buttons_are_its_drawn_bys_periods_labelled_as_the_service_labels_them_its_own_shaded(): + drawn_by = {"tool": "summary", "arguments": {"readings": ["outdoor.temperature"], "period": "last 30 days", "chart": True}, + "periods": list(OVER_TIME)} + own = periods.own_period(drawn_by, NOW, TZ) + assert own == "1m" and labels(periods.periods_keyboard(drawn_by, own)) == [ROW] and shaded(periods.periods_keyboard(drawn_by, own)) == ["1M"] + assert periods.periods_keyboard({**drawn_by, "periods": []}) is None # none listed: no buttons + months = {"tool": "days", "arguments": {"group_by": "month", "period": "2026-01-01 to 2026-10-01"}, + "periods": [{"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}, {"period": "on record", "label": "All"}]} + assert labels(periods.periods_keyboard(months)) == [[("3M", "pd:3m"), ("1Y", "pd:1y"), ("All", "pd:on record")]] # no 1D for a count per month + assert periods.period_in("pd:on record") == "on record" and periods.with_period(months, "1y") == {"group_by": "month", "period": "1y"} + assert periods.call_key("summary", {"b": 1, "a": [2]}) == periods.call_key("summary", {"a": [2], "b": 1}) == 'summary {"a":[2],"b":1}' -def test_a_question_keeps_its_words_and_swaps_its_period(): - for ask, expected in (("Temperature chart 30d", "Temperature chart 90d"), ("chart air quality last month", "chart air quality 90d"), - ("rain chart for the last week", "rain chart 90d"), ("weather chart", "weather chart 90d"), - ("plot humidity and rain 3m", "plot humidity and rain 90d")): - assert intent.with_period(ask, 90, NOW) == expected - assert intent.period_days("Temperature chart 30d", NOW) == 30 and intent.period_days("weather chart", NOW) == 1 - assert intent.period_days("chart 24h", NOW) == 1 and intent.period_days("chart 365d", NOW) == 365 - - -def test_only_the_newest_questions_are_remembered(): +def test_only_the_newest_charts_are_remembered(): charted = periods.Charted() for i in range(periods.REMEMBERED + 5): charted.remember(1, i, f"q{i}") assert len(charted.store) == periods.REMEMBERED and charted.get(1, 0) is None and charted.get(1, periods.REMEMBERED + 4) -def test_the_questions_behind_charts_survive_a_restart(tmp_path): +def test_the_calls_behind_charts_survive_a_restart(tmp_path): from lib.alerts.notify import AlertState state = AlertState(tmp_path / "s.json") - Bot(NS(tz=TZ), None, [], state).charted.remember(1, 101, "Temperature chart 7d") - again = Bot(NS(tz=TZ), None, [], AlertState(tmp_path / "s.json")) - assert again.charted.get(1, 101) == "Temperature chart 7d" + record = {"drawn_by": {"tool": "summary", "arguments": {"period": "7d"}, "periods": list(OVER_TIME)}, "words": False} + Bot(NS(tz=TZ), None, state, service=unreached()).charted.remember(1, 101, record) # (ecobot-mcp is asked nothing) + again = Bot(NS(tz=TZ), None, AlertState(tmp_path / "s.json"), service=unreached()) + assert again.charted.get(1, 101) == record + +class Summary: + """The service's summary as the stand-in draws it: a temperature chart of the period asked (its picture is the period's words, so a + test can tell which period it is), with its drawn_by; `refuse` the periods it refuses, `slow` those it waits on.""" + name = "summary" -class Tools(StandInTools): def __init__(self): - self.calls = [] + self.calls, self.refuse, self.slow = [], set(), {} + + async def call(self, args, meta=None): + self.calls.append(dict(args)) + period = args.get("period") or "last 24 hours" + if period in self.slow: + await self.slow[period].wait() + if period in self.refuse: + return json.dumps({"error": f"Nothing is held for {period}."}) + chart = Chart("Temperature", "", [Panel("Temperature", "°C", [Line("Outdoor", [1, 2], [1.0, 2.0])])]) + if args.get("start"): # set times, as the real summary keeps them: no periods to offer + arguments, listed = dict(args), [] + else: + arguments, listed = {**{k: v for k, v in args.items() if k not in ("start", "end")}, "period": period}, [dict(p) for p in OVER_TIME] + data = {**to_json(chart, TZ), "drawn_by": {"tool": "summary", "arguments": arguments, "periods": listed}} + return json.dumps({"caption": "Fri 25 Sep – Thu 1 Oct 2026\nTemperature: low 1 °C · high 2 °C", "charts": [data]}) + + +async def make_bot(serve, alert_state, monkeypatch, preload=False): + """A bot over ecobot-mcp in memory with the weather station, whose summary is the stand-in's (drawn by ecobot-mcp: the picture is + the period's words). Without `preload` a chart's other periods are not fetched in the background (preloading_bot's are), so a test + sees only the calls it makes.""" + class Agent: + async def run(self, *a, **k): + raise AssertionError("no model for a button's chart") + draws(monkeypatch, lambda data, tz, times=None: str(data["drawn_by"]["arguments"].get("period") + or data["drawn_by"]["arguments"]["start"]).encode()) + weather = await serve(tools=[Summary()], sources=["Ecowitt"]) + bot = Bot(NS(tz=TZ), Agent(), alert_state, service=weather) + if not preload: + bot.preload_soon = lambda *a: None + return bot - async def call(self, name, raw, turn=None): - self.calls.append((name, json.loads(raw))) - turn.charts.append(Chart("Temperature", "", [Panel("Temperature", "°C", [Line("Outdoor", [1, 2], [1.0, 2.0])])])) - return json.dumps({"period": "Fri 25 Sep 2026 - Thu 01 Oct 2026", "series": {"outdoor.temperature": {"unit": "℃", "low": "1", "high": "2"}}}) +def temperature(period: str) -> tuple[str, dict]: + """The call of a temperature chart over `period`, as a keyboard button's (the Temperature button's is 1d: templates.CALLS).""" + return "summary", {"readings": ["temperature"], "period": period, "chart": True} -def make_bot(alert_state, monkeypatch): - class Agent: - tools = Tools() - async def run(self, *a, **k): - raise AssertionError("no model for a plain chart") - monkeypatch.setattr(botmod, "render_chart", lambda spec, tz, times=None: b"png") - sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] - return Bot(NS(tz=TZ), Agent(), sources, alert_state) +async def ask_chart(bot, update, context, period: str): + """The temperature chart over `period`, answered as a button is (Bot.respond with its call: no model, no words read).""" + await bot.respond(update, context, f"Temperature chart {period}", call=temperature(period)) + + +def summary(bot) -> Summary: + """The stand-in summary behind the bot's ecobot-mcp.""" + return bot.weather.server.service["summary"].tool + + +def calls(bot) -> list[dict]: + """The calls the bot made of the service's summary (the stand-in's, behind ecobot-mcp).""" + return summary(bot).calls -async def test_closing_the_bot_cancels_its_uploads_still_running(alert_state, monkeypatch): - import asyncio - bot = make_bot(alert_state, monkeypatch) +async def test_closing_the_bot_cancels_its_uploads_still_running(serve, alert_state, monkeypatch): + bot = await make_bot(serve, alert_state, monkeypatch) upload = asyncio.create_task(asyncio.Event().wait()) bot.tasks.running.add(upload) await bot.tasks.close() @@ -100,43 +140,95 @@ async def send_chat_action(*a, **k): CONTEXT = NS(bot=NS(send_chat_action=send_chat_action, send_message_draft=send_chat_action, id=99)) -async def test_a_chart_is_sent_with_the_other_periods_under_it_and_its_question_is_remembered(alert_state, monkeypatch): - bot, sent = make_bot(alert_state, monkeypatch), [] +def press(msg, data, answer): + return NS(callback_query=NS(data=data, message=msg, answer=answer), effective_message=msg, effective_chat=msg.chat, + effective_user=NS(username="rob", full_name="Rob")) + + +async def test_a_chart_is_sent_with_its_periods_under_it_and_its_call_is_remembered(serve, alert_state, monkeypatch): + bot, sent = await make_bot(serve, alert_state, monkeypatch), [] msg = chat_message(sent) update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - await bot.respond(update, CONTEXT, "Temperature chart 30d") + await ask_chart(bot, update, CONTEXT, "30d") caption, markup = sent[0] - assert caption == "Temperature" and labels(markup) == [[("1D", "pd:1"), ("7D", "pd:7"), ("1M", "pd:30"), ("3M", "pd:90"), ("1Y", "pd:365")]] - assert bot.charted.get(1, 101) == "Temperature chart 30d" + assert caption == "Temperature" and labels(markup) == [ROW] and shaded(markup) == ["1M"] + assert calls(bot) == [{"readings": ["temperature"], "period": "30d", "chart": True}] # its call + record = bot.charted.get(1, 101) + assert record["drawn_by"]["arguments"]["period"] == "30d" and record["words"] is False -async def test_pressing_a_period_redraws_the_chart_in_place_with_that_period_left_out(alert_state, monkeypatch): - bot, edits = make_bot(alert_state, monkeypatch), [] +async def test_pressing_a_period_replays_the_charts_call_with_that_period_in_place(serve, alert_state, monkeypatch): + bot, edits = await make_bot(serve, alert_state, monkeypatch), [] msg = chat_message([], edits) - bot.charted.remember(1, 50, "Temperature chart 30d") + drawn_by = {"tool": "summary", "arguments": {"readings": ["outdoor.temperature"], "period": "last 30 days", "chart": True}, + "periods": [dict(p) for p in OVER_TIME]} + bot.charted.remember(1, 50, {"drawn_by": drawn_by, "words": False}) answers = [] - async def answer(text=None): + async def answer(text=None, **k): answers.append(text) - query = NS(data="pd:90", message=msg, answer=answer) - update = NS(callback_query=query, effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - await bot.on_period_button(update, CONTEXT) - name, args = bot.agent.tools.calls[0] - assert name == "weather_history" and args["start_date"].startswith("2026-") and answers == ["Drawing 3M..."] + await bot.on_period_button(press(msg, "pd:3m", answer), CONTEXT) + assert calls(bot) == [{"readings": ["outdoor.temperature"], "period": "3m", "chart": True}] and answers == ["Drawing 3M..."] caption, markup = edits[0] - assert caption == "Temperature" and [t for t, _ in labels(markup)[0]] == ["1D", "7D", "1M", "3M", "1Y"] and shaded(markup) == ["3M"] - assert bot.charted.get(1, 50) == "Temperature chart 90d" + assert caption == "Temperature" and labels(markup) == [ROW] and shaded(markup) == ["3M"] + assert bot.charted.get(1, 50)["drawn_by"]["arguments"]["period"] == "3m" + + +async def test_a_replay_the_service_refuses_shows_its_refusal_on_the_button(serve, alert_state, monkeypatch): + bot, edits = await make_bot(serve, alert_state, monkeypatch), [] + summary(bot).refuse.add("1y") + msg = chat_message([], edits) + bot.charted.remember(1, 50, {"drawn_by": {"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]}}) + answers = [] + + async def answer(text=None, **k): + answers.append(text) + await bot.on_period_button(press(msg, "pd:1y", answer), CONTEXT) + assert answers == ["Nothing is held for 1y."] and edits == [] + await bot.on_period_button(press(msg, "pd:2y", answer), CONTEXT) # a period the chart doesn't list + assert answers[-1] == "That chart is out of date, please ask again" + +async def test_a_replayed_chart_that_cannot_be_drawn_or_sent_says_sorry_on_the_button_and_raises_nothing(serve, alert_state, monkeypatch): + from telegram.error import BadRequest, NetworkError + bot, edits = await make_bot(serve, alert_state, monkeypatch), [] + msg = chat_message([], edits) + record = {"drawn_by": {"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]}, "words": False} + bot.charted.remember(1, 50, record) + answers = [] + + async def answer(text=None, **k): # Telegram takes one answer per press + if answers: + raise BadRequest("Query is too old and response timeout expired or query id is invalid") + answers.append(text) + + def broken(data, tz, times=None): + raise ValueError("no panels") + draws(monkeypatch, broken) + await bot.on_period_button(press(msg, "pd:3m", answer), CONTEXT) # a chart that fails to render + assert answers == [SORRY] and edits == [] + + async def offline(media, reply_markup=None): + raise NetworkError("connection reset") + draws(monkeypatch, lambda data, tz, times=None: b"png") + said = [] -async def test_a_button_on_a_chart_from_before_a_restart_says_so(alert_state, monkeypatch): - bot = make_bot(alert_state, monkeypatch) + async def reply_text(text, **k): + said.append(text) + msg.edit_media, msg.reply_text, answers[:] = offline, reply_text, [] + await bot.on_period_button(press(msg, "pd:1y", answer), CONTEXT) # Telegram failing other than refusing the edit, after "Drawing" + assert answers == ["Drawing 1Y..."] and said == [SORRY] # (the press is answered once: the sorry goes in the chat) + + +async def test_a_button_on_a_chart_from_before_a_restart_says_so(serve, alert_state, monkeypatch): + bot = await make_bot(serve, alert_state, monkeypatch) answers = [] async def answer(text=None): answers.append(text) msg = chat_message([]) - await bot.on_period_button(NS(callback_query=NS(data="pd:7", message=msg, answer=answer)), CONTEXT) - assert answers == ["That chart is out of date, please ask again"] and not bot.agent.tools.calls + await bot.on_period_button(press(msg, "pd:7d", answer), CONTEXT) + assert answers == ["That chart is out of date, please ask again"] and not calls(bot) async def test_a_reply_with_period_buttons_leaves_the_persistent_keyboard_for_the_next_reply(): @@ -147,17 +239,18 @@ class Replies: async def reply_photo(self, photo, **kw): sent.append(kw["reply_markup"]) return NS(message_id=7) - got = await botmod.deliver(Replies(), "", [b"p"], markup=keyboard(), titles=["T"], period_row=periods.keyboard()) + row = periods.periods_keyboard({"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]}) + got = await botmod.deliver(Replies(), "", [b"p"], markup=keyboard(), titles=["T"], period_row=row) assert got.carried is False and labels(sent[0])[0][0][0] == "1D" and got.photo.message_id == 7 def test_a_chart_drawn_lately_comes_back_from_the_cache_until_it_is_too_old_or_pushed_out(): clock = [0.0] cache = periods.ImageCache(lambda: clock[0]) - key = cache.key("Temperature chart 30d", 30, NOW) - assert key == cache.key("temperature chart for the last month", 30, NOW) and cache.get(key) is None - cache.put(key, b"png", "Temperature") - assert cache.get(key) == (b"png", "Temperature") + key = periods.call_key("summary", {"readings": ["outdoor.temperature"], "period": "last 30 days", "chart": True}) + assert cache.get(key) is None + cache.put(key, b"png", "Temperature", drawn_by={"tool": "summary", "arguments": {"period": "1m"}, "periods": []}) + assert cache.get(key) == (b"png", "Temperature") == cache.get('summary {"period":"1m"}') # under the call drawn_by states too clock[0] = periods.ImageCache.CHART_TTL + 1 assert cache.get(key) is None for i in range(periods.ImageCache.CHART_IMAGES + 3): @@ -165,25 +258,24 @@ def test_a_chart_drawn_lately_comes_back_from_the_cache_until_it_is_too_old_or_p assert len(cache.items) == periods.ImageCache.CHART_IMAGES and "q0" not in cache.items -async def test_toggling_back_to_a_period_just_drawn_uses_the_cached_image_and_asks_nothing_again(alert_state, monkeypatch): - bot, sent, edits = make_bot(alert_state, monkeypatch), [], [] +async def test_toggling_back_to_a_period_just_drawn_uses_the_cached_image_and_asks_nothing_again(serve, alert_state, monkeypatch): + bot, sent, edits = await make_bot(serve, alert_state, monkeypatch), [], [] msg = chat_message(sent, edits) update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - await bot.respond(update, CONTEXT, "Temperature chart 7d") + await ask_chart(bot, update, CONTEXT, "7d") answers = [] async def answer(text=None): answers.append(text) msg.message_id = 101 - for days in (30, 30, 7, 30, 7): - await bot.on_period_button(NS(callback_query=NS(data=f"pd:{days}", message=msg, answer=answer), effective_message=msg, - effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")), CONTEXT) - assert len(bot.agent.tools.calls) == 2 # the first send and the first 30d: the rest came from the cache (a press on the shown 30d does nothing) - assert [e[0] for e in edits] == ["Temperature"] * 4 # the repeated 30d press edited nothing and bot.charted[(1, 101)] == "Temperature chart 7d" + for period in ("1m", "1m", "7d", "1m", "7d"): + await bot.on_period_button(press(msg, f"pd:{period}", answer), CONTEXT) + assert len(calls(bot)) == 2 # the first send and the first 1M: the rest came from the cache (a press on the shown 1M does nothing) + assert [e[0] for e in edits] == ["Temperature"] * 4 # the repeated 1M press edited nothing -async def test_a_chart_once_sent_goes_again_as_telegrams_copy_not_a_new_upload(alert_state, monkeypatch): - bot, uploads, edits = make_bot(alert_state, monkeypatch), [], [] +async def test_a_chart_once_sent_goes_again_as_telegrams_copy_not_a_new_upload(serve, alert_state, monkeypatch): + bot, uploads, edits = await make_bot(serve, alert_state, monkeypatch), [], [] async def reply_photo(photo, caption=None, **kw): uploads.append(photo) @@ -195,33 +287,13 @@ async def edit_media(media, reply_markup=None): msg = NS(chat_id=1, message_id=101, message_thread_id=None, is_topic_message=False, reply_photo=reply_photo, edit_media=edit_media, chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - await bot.respond(update, CONTEXT, "Temperature chart 7d") + await ask_chart(bot, update, CONTEXT, "7d") async def answer(text=None): pass - for days in (30, 7, 30): - await bot.on_period_button(NS(callback_query=NS(data=f"pd:{days}", message=msg, answer=answer), effective_message=msg, - effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")), CONTEXT) - assert uploads == [b"png"] and edits == ["upload", "7d", "edit 1"] # 30d drawn and uploaded once; then both by Telegram's copy - - -async def test_redrawing_a_chart_from_a_button_shows_no_typing_or_thinking(alert_state, monkeypatch): - bot = make_bot(alert_state, monkeypatch) - actions = [] - - async def chat_action(*a, **k): - actions.append(a) - drafts = [] - - async def draft(*a, **k): - drafts.append(a) - context = NS(bot=NS(send_chat_action=chat_action, send_message_draft=draft, id=99)) - msg = chat_message([], []) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - await bot.respond(update, context, "Temperature chart 30d", redraw=msg) - assert actions == [] and drafts == [] - await bot.respond(update, context, "Temperature chart 7d") # a question of its own still does - assert actions + for period in ("1m", "7d", "1m"): + await bot.on_period_button(press(msg, f"pd:{period}", answer), CONTEXT) + assert uploads == [b"7d"] and edits == ["upload", "7d", "edit 1"] # 1M drawn and uploaded once; then both by Telegram's copy def pressed(bot, sent): @@ -234,46 +306,41 @@ async def reply_photo(photo, caption=None, **kw): return NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) -async def test_a_chart_just_drawn_is_sent_again_at_once_and_then_as_telegrams_copy(alert_state, monkeypatch): - bot, sent = make_bot(alert_state, monkeypatch), [] +async def test_a_chart_just_drawn_is_sent_again_at_once_and_then_as_telegrams_copy(serve, alert_state, monkeypatch): + bot, sent = await make_bot(serve, alert_state, monkeypatch), [] update = pressed(bot, sent) - await bot.respond(update, CONTEXT, "Temperature chart 1d") - calls = len(bot.agent.tools.calls) - assert calls >= 1 and sent == [(b"png", "Temperature")] - await bot.respond(update, CONTEXT, "Temperature chart 1d") - assert len(bot.agent.tools.calls) == calls and sent[-1] == ("copy 1", "Temperature") # drawn lately: no new question, Telegram's copy + await ask_chart(bot, update, CONTEXT, "1d") + asked = len(calls(bot)) + assert asked == 1 and sent == [(b"1d", "Temperature")] + await ask_chart(bot, update, CONTEXT, "1d") + assert len(calls(bot)) == asked and sent[-1] == ("copy 1", "Temperature") # drawn lately: no new call, Telegram's copy history = bot.chats[(1, None)].history - assert history[-1]["role"] == "assistant" and history[-1]["content"] # its text is kept, as a drawn one's is + assert history[-1]["role"] == "assistant" and history[-1]["content"] # its text is kept, as a drawn one's is -async def test_a_chart_is_drawn_again_once_it_is_stale_and_never_answers_other_words(alert_state, monkeypatch): +async def test_a_chart_is_drawn_again_once_it_is_stale_and_never_answers_another_call(serve, alert_state, monkeypatch): clock = [0.0] - bot, sent = make_bot(alert_state, monkeypatch), [] + bot, sent = await make_bot(serve, alert_state, monkeypatch), [] bot.images = periods.ImageCache(lambda: clock[0]) - await bot.respond(pressed(bot, sent), CONTEXT, "Temperature chart 1d") - calls = len(bot.agent.tools.calls) - await bot.respond(pressed(bot, sent), CONTEXT, "temperature chart today") # kept under the 1d key, but since midnight: drawn - assert len(bot.agent.tools.calls) == calls + 1 - calls = len(bot.agent.tools.calls) + await ask_chart(bot, pressed(bot, sent), CONTEXT, "1d") + asked = len(calls(bot)) + await ask_chart(bot, pressed(bot, sent), CONTEXT, "today") # since midnight: another call, drawn + assert len(calls(bot)) == asked + 1 + asked = len(calls(bot)) clock[0] = periods.ImageCache.FRESH + 1 - await bot.respond(pressed(bot, sent), CONTEXT, "Temperature chart 1d") # too old to send as it is - assert len(bot.agent.tools.calls) == calls + 1 + await ask_chart(bot, pressed(bot, sent), CONTEXT, "1d") # too old to send as it is + assert len(calls(bot)) == asked + 1 -def preloading_bot(alert_state, monkeypatch, refuse=None, clock=None): - """A bot with TELEGRAM_PRELOAD_CHAT set, and the (chat, photo, silent) of every upload to it. The periods are uploaded side by side, - in no fixed order, so each period's picture is its question's words and its file id "file " and those words; context.refused.error +async def preloading_bot(serve, alert_state, monkeypatch, refuse=None, clock=None): + """A bot with BOT_TELEGRAM_PRELOAD_CHAT set, and the (chat, photo, silent) of every upload to it. The periods are uploaded side by side, + in no fixed order, so each period's picture is its period's words and its file id "file " and those words; context.refused.error is what the uploads raise (none: they go through).""" - bot, uploads, refused = make_bot(alert_state, monkeypatch), [], NS(error=refuse) + bot, uploads, refused = await make_bot(serve, alert_state, monkeypatch, preload=True), [], NS(error=refuse) bot.cfg = NS(tz=TZ, telegram_preload_chat=-1001) if clock: bot.images = periods.ImageCache(lambda: clock[0]) - draw = bot._draw_ahead - - async def draw_ahead(text, now): - key, _, title, caption, newest = await draw(text, now) - return key, text.encode(), title, caption, newest - bot._draw_ahead = draw_ahead + bot.alert_charts.images = bot.images async def send_photo(chat, photo, caption=None, disable_notification=False): if refused.error: @@ -283,18 +350,17 @@ async def send_photo(chat, photo, caption=None, disable_notification=False): return bot, uploads, NS(bot=NS(send_chat_action=send_chat_action, send_message_draft=send_chat_action, send_photo=send_photo, id=99), refused=refused) -def uploads_of(*days): - """What the uploads to the preload chat are, in any order, when they are the Temperature charts of these periods.""" - return sorted((-1001, f"Temperature chart {d}d".encode(), True) for d in days) +def uploads_of(*periods_): + """What the uploads to the preload chat are, in any order, when they are the charts of these periods.""" + return sorted((-1001, p.encode(), True) for p in periods_) async def settle(bot): - import asyncio await asyncio.gather(*bot.tasks.running) -async def test_the_other_periods_of_a_chart_are_uploaded_ahead_and_a_press_edits_by_file_id(alert_state, monkeypatch): - bot, uploads, context = preloading_bot(alert_state, monkeypatch) +async def test_the_other_periods_of_a_chart_are_uploaded_ahead_and_a_press_edits_by_file_id(serve, alert_state, monkeypatch): + bot, uploads, context = await preloading_bot(serve, alert_state, monkeypatch) sent, edits = [], [] async def edit_media(media, reply_markup=None): @@ -302,233 +368,259 @@ async def edit_media(media, reply_markup=None): return NS(photo=()) msg = chat_message(sent, edits) msg.edit_media, msg.message_id = edit_media, 101 - await bot.respond(NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")), - context, "Temperature chart 7d") + await ask_chart(bot, NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")), + context, "7d") await settle(bot) - assert sorted(uploads) == uploads_of(1, 30, 90, 365) # 1D, 1M, 3M, 1Y: not the 7D just sent - calls = len(bot.agent.tools.calls) + assert sorted(uploads) == uploads_of("1d", "1m", "3m", "1y") # 1D, 1M, 3M, 1Y: not the 7D just sent + assert all(c["period"] in ("7d", "1d", "1m", "3m", "1y") for c in calls(bot)) + asked = len(calls(bot)) async def answer(text=None): pass - await bot.on_period_button(NS(callback_query=NS(data="pd:90", message=msg, answer=answer), effective_message=msg, - effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")), context) - assert len(bot.agent.tools.calls) == calls and edits[0] == "file Temperature chart 90d" # Telegram's copy of the 3M, no new question or upload + await bot.on_period_button(press(msg, "pd:3m", answer), context) + assert len(calls(bot)) == asked and edits[0] == "file 3m" # Telegram's copy of the 3M, no new call or upload -async def test_nothing_is_uploaded_ahead_without_the_setting_and_a_refused_upload_stops_it_with_one_warning(alert_state, monkeypatch, caplog): - bot, uploads, context = preloading_bot(alert_state, monkeypatch) +async def test_nothing_is_uploaded_ahead_without_the_setting_and_a_refused_upload_stops_it_with_one_warning(serve, alert_state, monkeypatch, caplog): + bot, uploads, context = await preloading_bot(serve, alert_state, monkeypatch) bot.cfg = NS(tz=TZ) update = pressed(bot, []) - await bot.respond(update, context, "Temperature chart 7d") + await ask_chart(bot, update, context, "7d") await settle(bot) assert uploads == [] and not bot.tasks.running from telegram.error import BadRequest - bot, uploads, context = preloading_bot(alert_state, monkeypatch, refuse=BadRequest("Chat not found")) + bot, uploads, context = await preloading_bot(serve, alert_state, monkeypatch, refuse=BadRequest("Chat not found")) with caplog.at_level("WARNING"): - await bot.respond(pressed(bot, []), context, "Temperature chart 7d") + await ask_chart(bot, pressed(bot, []), context, "7d") await settle(bot) - await bot.respond(pressed(bot, []), context, "Temperature chart 30d") + await ask_chart(bot, pressed(bot, []), context, "30d") await settle(bot) - assert [r for r in caplog.records if "TELEGRAM_PRELOAD_CHAT" in r.getMessage()].__len__() == 1 and uploads == [] and bot.preload_off + assert [r for r in caplog.records if "BOT_TELEGRAM_PRELOAD_CHAT" in r.getMessage()].__len__() == 1 and uploads == [] and bot.preload_off -async def test_a_flood_limit_or_a_timeout_skips_those_uploads_and_the_next_chart_uploads_again(alert_state, monkeypatch, caplog): +async def test_a_flood_limit_or_a_timeout_skips_those_uploads_and_the_next_chart_uploads_again(serve, alert_state, monkeypatch, caplog): import warnings from telegram.error import RetryAfter, TimedOut with warnings.catch_warnings(): warnings.simplefilter("ignore") # python-telegram-bot 22 warns whenever it builds a RetryAfter flood = RetryAfter(30) - bot, uploads, context = preloading_bot(alert_state, monkeypatch) - for error, asked in ((flood, "Temperature chart 7d"), (TimedOut(), "Temperature chart 30d")): + bot, uploads, context = await preloading_bot(serve, alert_state, monkeypatch) + for error, asked in ((flood, "7d"), (TimedOut(), "30d")): context.refused.error = error with caplog.at_level("WARNING"): - await bot.respond(pressed(bot, []), context, asked) + await ask_chart(bot, pressed(bot, []), context, asked) await settle(bot) assert uploads == [] and not bot.preload_off - assert len([r for r in caplog.records if "TELEGRAM_PRELOAD_CHAT" in r.getMessage()]) == 2 # one a chart, though several uploads were skipped + assert len([r for r in caplog.records if "BOT_TELEGRAM_PRELOAD_CHAT" in r.getMessage()]) == 2 # one a chart, though several uploads were skipped context.refused.error = None - await bot.respond(pressed(bot, []), context, "Temperature chart 90d") + await ask_chart(bot, pressed(bot, []), context, "90d") await settle(bot) - assert sorted(uploads) == uploads_of(1, 365) # the 7D and the 1M were sent as the questions' own charts - + assert sorted(uploads) == uploads_of("1d", "3m", "1y") # the 7D and the 1M were sent as the questions' own charts (3M is 91 days) -async def test_a_period_that_cannot_be_drawn_is_left_out_and_the_others_are_uploaded(alert_state, monkeypatch): - bot, uploads, context = preloading_bot(alert_state, monkeypatch) - draw = bot._draw_ahead - async def draw_ahead(text, now): - if text.endswith("90d"): - raise ValueError("no readings") - return await draw(text, now) - bot._draw_ahead = draw_ahead - await bot.respond(pressed(bot, []), context, "Temperature chart 7d") +async def test_a_period_that_cannot_be_drawn_is_left_out_and_the_others_are_uploaded(serve, alert_state, monkeypatch): + bot, uploads, context = await preloading_bot(serve, alert_state, monkeypatch) + summary(bot).refuse.add("3m") + await ask_chart(bot, pressed(bot, []), context, "7d") await settle(bot) - assert sorted(uploads) == uploads_of(1, 30, 365) - assert bot.images.has_copy(bot.images.key("Temperature chart 30d", 30, NOW)) and not bot.images.has_copy(bot.images.key("Temperature chart 90d", 90, NOW)) + assert sorted(uploads) == uploads_of("1d", "1m", "1y") + drawn_by = bot.images.held(periods.call_key("summary", {"readings": ["temperature"], "period": "7d", "chart": True})).drawn_by + key = lambda p: periods.call_key("summary", periods.with_period(drawn_by, p)) + assert bot.images.has_copy(key("1m")) and not bot.images.has_copy(key("3m")) -async def test_each_period_is_uploaded_as_soon_as_it_is_drawn_not_when_the_slowest_is(alert_state, monkeypatch): - import asyncio - bot, uploads, context = preloading_bot(alert_state, monkeypatch) - slow, three, draw, send = asyncio.Event(), asyncio.Event(), bot._draw_ahead, context.bot.send_photo - - async def draw_ahead(text, now): - if text.endswith("chart 1d"): - await slow.wait() - return await draw(text, now) +async def test_each_period_is_uploaded_as_soon_as_it_is_drawn_not_when_the_slowest_is(serve, alert_state, monkeypatch): + bot, uploads, context = await preloading_bot(serve, alert_state, monkeypatch) + slow, three, send = asyncio.Event(), asyncio.Event(), context.bot.send_photo + summary(bot).slow["1d"] = slow async def send_photo(chat, photo, **kw): message = await send(chat, photo, **kw) if len(uploads) == 3: three.set() return message - bot._draw_ahead, context.bot.send_photo = draw_ahead, send_photo - bot.preload_soon(context.bot, "Temperature chart 7d") + context.bot.send_photo = send_photo + bot.preload_soon(context.bot, {"tool": "summary", "arguments": {"readings": ["outdoor.temperature"], "period": "7d", "chart": True}, + "periods": [dict(p) for p in OVER_TIME]}) await asyncio.wait_for(three.wait(), 5) - assert sorted(uploads) == uploads_of(30, 90, 365) # the 1D, first in line, is still being drawn + assert sorted(uploads) == uploads_of("1m", "3m", "1y") # the 1D, first in line, is still being drawn slow.set() await asyncio.wait_for(settle(bot), 5) - assert sorted(uploads) == uploads_of(1, 30, 90, 365) + assert sorted(uploads) == uploads_of("1d", "1m", "3m", "1y") -async def test_a_chart_uploaded_ahead_is_used_for_30_minutes_and_then_drawn_afresh(alert_state, monkeypatch): +async def test_a_chart_uploaded_ahead_is_used_for_30_minutes_and_then_drawn_afresh(serve, alert_state, monkeypatch): clock = [0.0] - bot, uploads, context = preloading_bot(alert_state, monkeypatch, clock=clock) - await bot.respond(pressed(bot, []), context, "Temperature chart 7d") + bot, uploads, context = await preloading_bot(serve, alert_state, monkeypatch, clock=clock) + await ask_chart(bot, pressed(bot, []), context, "7d") await settle(bot) - key = bot.images.key("Temperature chart 30d", 30, NOW) + key = periods.call_key("summary", {"readings": ["temperature"], "period": "1m", "chart": True}) clock[0] = 29 * 60 assert bot.images.has_copy(key) and isinstance(bot.images.get(key)[0], str) clock[0] = 31 * 60 assert not bot.images.has_copy(key) and bot.images.get(key) is None -async def test_a_redrawn_chart_carries_a_short_answer_in_its_caption_and_a_long_one_follows_as_a_message(alert_state, monkeypatch): - bot, edits, replies = make_bot(alert_state, monkeypatch), [], [] +async def test_a_redrawn_chart_carries_a_short_answer_in_its_caption_and_a_long_one_follows_as_a_message(serve, alert_state, monkeypatch): + bot, edits, replies = await make_bot(serve, alert_state, monkeypatch), [], [] msg = chat_message([], edits) async def reply_text(text, **kw): replies.append(text) msg.reply_text = reply_text - assert await bot._redraw(msg, "Last 7 days: 72% avg.", b"png", "Humidity", periods.keyboard(7), "q") + row = periods.periods_keyboard({"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]}) + assert await bot._redraw(msg, "Last 7 days: 72% avg.", b"png", "Humidity", row, {}) assert edits[0][0] == "Humidity\n\nLast 7 days: 72% avg." and replies == [] # one message, as when the chart was first sent - assert await bot._redraw(msg, "x" * botmod.CAPTION_LIMIT, b"png", "Humidity", periods.keyboard(7), "q") + assert await bot._redraw(msg, "x" * botmod.CAPTION_LIMIT, b"png", "Humidity", row, {}) assert edits[1][0] == "Humidity" and replies == ["x" * botmod.CAPTION_LIMIT] # too long for a caption: its own message -async def test_pressing_a_period_under_a_chart_the_model_drew_keeps_its_answer_in_the_caption(alert_state, monkeypatch): - bot, edits, replies = make_bot(alert_state, monkeypatch), [], [] +def test_a_chart_knows_the_time_of_its_newest_reading(): + from lib.specs import Bars + assert Chart("Temperature", "", [Panel("Temperature", "°C", [Line("Outdoor", [1, 2], [1.0, 2.0]), Line("Indoor", [1, 5], [1.0, 2.0])])]).newest == 5 + assert Chart("Rain", "", [Panel("Rain", "mm", [], bars=Bars("Rain", "mm", [0, 3600], [0.0, 1.0], 3600))]).newest == 3600 - class Agent: - ready = True - async def run(self, working, system, effort, turn=None, **kw): - turn.charts.append(Chart("Humidity and Temperature", "", [Panel("Humidity", "%", [Line("Ecowitt", [1, 2], [1.0, 2.0])])])) - return "Last 7 days (21-27 Oct):\nHumidity: Ecowitt 72.1% avg." - bot.agent = Agent() +def test_a_chart_drawn_in_one_theme_is_not_sent_again_after_the_theme_changes(monkeypatch): + from lib import theme + images = periods.ImageCache(lambda: 0.0) + monkeypatch.setattr(theme, "MODE", "off") + images.put("summary {}", b"light", "T", "caption") + assert images.get("summary {}") and images.ready("summary {}") + monkeypatch.setattr(theme, "MODE", "on") # 8pm under DARKMODE=8pm-8am + assert images.ready("summary {}") is None and images.get("summary {}") is None + + +def test_a_chart_with_no_periods_to_offer_gets_a_reload_when_its_period_runs_to_now(): + """A chart whose call lists no periods gets a 🔄 when its period runs to the present (to now; for a tool of whole days, through + yesterday), so it can be drawn again with what has come in since; one over a fixed past stretch gets nothing.""" + reload = [[("🔄", "pd:reload")]] + + def row(tool, **arguments): + markup = periods.periods_keyboard({"tool": tool, "arguments": arguments, "periods": []}, None, NOW, TZ) + return labels(markup) if markup else None + assert row("summary", readings=["outdoor.temperature"], start="2026-10-02 09:00") == reload # since 9am: to now + assert row("summary", start="2026-10-01 09:00", end="2026-10-01 18:00") is None # a fixed stretch + assert row("summary", period="today") == reload and row("summary", period="yesterday") is None + assert row("days", group_by="year", period="on record") == reload # through yesterday + assert row("days", group_by="year", period="2024-01-01 to 2025-12-31") is None + assert row("days", group_by="year", period="2025-01-01 to now") == reload + for fixed in ("2026-09-01 to 2026-10-01", "September", "last month", "2025"): # fixed dates, even ending yesterday: never more + assert row("days", group_by="year", period=fixed) is None, fixed + assert periods.periods_keyboard({"tool": "summary", "arguments": {"start": "2026-10-02 09:00"}, "periods": []}) is None # no clock: none + listed = {"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]} + assert labels(periods.periods_keyboard(listed, "7d", NOW, TZ)) == [ROW] # periods listed: those + + +async def test_pressing_reload_draws_the_same_call_again_in_place_with_the_reload_under_it(serve, alert_state, monkeypatch): + bot, edits, sent = await make_bot(serve, alert_state, monkeypatch), [], [] + msg = chat_message(sent, edits) + start = f"{datetime.now(TZ):%Y-%m-%d} 00:00" + drawn_by = {"tool": "summary", "arguments": {"readings": ["outdoor.temperature"], "start": start, "chart": True}, "periods": []} + bot.charted.remember(1, 50, {"drawn_by": drawn_by, "words": False}) + key = periods.call_key("summary", drawn_by["arguments"]) + bot.images.put(key, b"old picture", "Temperature", drawn_by=drawn_by) # drawn a moment ago: a reload draws it afresh all the same + answers = [] + + async def answer(text=None, **k): + answers.append(text) + await bot.on_period_button(press(msg, "pd:reload", answer), CONTEXT) + assert calls(bot) == [drawn_by["arguments"]] and answers == ["Drawing again..."] + caption, markup = edits[0] + assert caption == "Temperature" and labels(markup) == [[("🔄", "pd:reload")]] + assert bot.charted.get(1, 50)["drawn_by"]["arguments"] == drawn_by["arguments"] and bot.images.held(key).png == start.encode() + listed = {"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]} + bot.charted.remember(1, 50, {"drawn_by": listed, "words": False}) + await bot.on_period_button(press(msg, "pd:reload", answer), CONTEXT) # a chart with periods has no 🔄 + assert answers[-1] == "That chart is out of date, please ask again" and len(calls(bot)) == 1 + + +async def test_pressing_a_1d_charts_own_button_draws_it_again_and_a_longer_ones_does_nothing(serve, alert_state, monkeypatch): + """The shaded 1D under a chart that runs to now draws it again, past the picture cache, with the latest readings; the shaded + button of a longer period changes nothing (a few minutes more barely show on a week).""" + bot, edits = await make_bot(serve, alert_state, monkeypatch), [] msg = chat_message([], edits) + day = {"tool": "summary", "arguments": {"readings": ["outdoor.temperature"], "period": "last 24 hours", "chart": True}, + "periods": [dict(p) for p in OVER_TIME]} + bot.charted.remember(1, 50, {"drawn_by": day, "words": False}) + key = periods.call_key("summary", day["arguments"]) + bot.images.put(key, b"old picture", "Temperature", drawn_by=day) + answers = [] - async def reply_text(text, **kw): - replies.append(text) - msg.reply_text = reply_text - bot.charted.remember(1, 50, "overlay ecowitt outdoor humidity with airgradient humidity, on another axis the temperatures") + async def answer(text=None, **k): + answers.append(text) + await bot.on_period_button(press(msg, "pd:1d", answer), CONTEXT) + assert calls(bot) == [day["arguments"]] and answers == ["Drawing 1D..."] + caption, markup = edits[0] + assert labels(markup) == [ROW] and shaded(markup) == ["1D"] and bot.images.held(key).png == b"last 24 hours" + week = {**day, "arguments": {**day["arguments"], "period": "7d"}} + bot.charted.remember(1, 50, {"drawn_by": week, "words": False}) + await bot.on_period_button(press(msg, "pd:7d", answer), CONTEXT) + assert len(calls(bot)) == 1 and answers[-1] is None and len(edits) == 1 + yesterday = {**day, "arguments": {**day["arguments"], "period": "yesterday"}} # (a 1D over a day that is over: nothing new) + bot.charted.remember(1, 50, {"drawn_by": yesterday, "words": False}) + if periods.own_period(yesterday, botmod.now_local(TZ), TZ) == "1d": + await bot.on_period_button(press(msg, "pd:1d", answer), CONTEXT) + assert len(calls(bot)) == 1 + + +async def test_without_the_preload_chat_a_charts_other_periods_are_fetched_in_the_background_and_a_press_asks_nothing(serve, alert_state, + monkeypatch): + """Step 6c: nothing is drawn ahead on a timer any more; after a chart is sent its other periods are fetched from ecobot-mcp (background + requests, every point as drawn), with no preload chat uploaded nowhere, so a period button answers at once with the chart held.""" + bot, uploads, context = await preloading_bot(serve, alert_state, monkeypatch) + bot.cfg = NS(tz=TZ) # no BOT_TELEGRAM_PRELOAD_CHAT + metas, call = [], summary(bot).call + + async def counting(args, meta=None): + metas.append((args.get("period"), meta)) + return await call(args, meta) + summary(bot).call = counting + sent, edits = [], [] + msg = chat_message(sent, edits) + await ask_chart(bot, NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")), + context, "7d") + await settle(bot) + assert uploads == [] and sorted(p for p, _ in metas) == ["1d", "1m", "1y", "3m", "7d"] + assert all(m["priority"] == "background" and m["chart_points"] == "drawn" for p, m in metas if p != "7d") + asked = len(calls(bot)) + msg.message_id = 101 async def answer(text=None): pass - update = NS(callback_query=NS(data="pd:7", message=msg, answer=answer), effective_message=msg, effective_chat=msg.chat, - effective_user=NS(username="rob", full_name="Rob")) - await bot.on_period_button(update, CONTEXT) - assert replies == [] and edits and "Humidity: Ecowitt 72.1% avg." in edits[0][0] + await bot.on_period_button(press(msg, "pd:3m", answer), context) + assert len(calls(bot)) == asked and edits[0][0] == "Temperature" # the 3M held: no new call -async def test_the_keyboards_charts_are_drawn_ahead_and_a_press_is_answered_from_them(alert_state, monkeypatch): - from lib.timeutil import now_local - clock = [0.0] - bot, uploads, context = preloading_bot(alert_state, monkeypatch, clock=clock) - bot.cfg = NS(tz=TZ) # no preload chat: drawn, not uploaded - await bot.draw_buttons_ahead(context.bot) - now = now_local(TZ) - assert uploads == [] and bot.images.ready("Temperature chart 1d", now) # (the stand-in's tools only have temperature) - assert bot.images.ready("Air quality all metrics 1d", now) is None # no air sensor here: nothing to draw - calls, sent = len(bot.agent.tools.calls), [] - await bot.respond(pressed(bot, sent), context, "Temperature chart 1d") - assert len(bot.agent.tools.calls) == calls and sent[0][0] == b"Temperature chart 1d" # the one drawn ahead: no new question - clock[0] += 400 # too old to answer with: the press draws afresh - await bot.respond(pressed(bot, sent), context, "Temperature chart 1d") - assert len(bot.agent.tools.calls) == calls + 1 - drawn, draw = [], bot._draw_ahead - - async def counting(text, now): - drawn.append(text) - return await draw(text, now) - bot._draw_ahead = counting - await bot.draw_buttons_ahead(context.bot) - assert "Humidity chart 1d" in drawn and "Temperature chart 1d" not in drawn # just drawn for the press: left alone this time - - -async def test_the_keyboards_charts_are_uploaded_ahead_only_while_the_bot_is_in_use(alert_state, monkeypatch): - import time - from lib.bot import USED_SECONDS - clock = [0.0] - bot, uploads, context = preloading_bot(alert_state, monkeypatch, clock=clock) - await bot.draw_buttons_ahead(context.bot) - assert uploads == [] and not bot.used_lately # nobody has used the bot: drawn, not uploaded - bot.noticed() - clock[0] += 120 - await bot.draw_buttons_ahead(context.bot) - assert (-1001, b"Temperature chart 1d", True) in uploads - sent = [] - await bot.respond(pressed(bot, sent), context, "Temperature chart 1d") - assert sent[0][0] == "file Temperature chart 1d" # a press sends Telegram's copy - await settle(bot) # (the press's other periods, uploaded ahead) - uploads.clear() - clock[0] += 120 - bot.last_used = time.monotonic() - USED_SECONDS - 1 # 15 minutes without a message or a press - await bot.draw_buttons_ahead(context.bot) - assert uploads == [] - - -def test_a_chart_knows_the_time_of_its_newest_reading(): - from lib.specs import Bars - assert Chart("Temperature", "", [Panel("Temperature", "°C", [Line("Outdoor", [1, 2], [1.0, 2.0]), Line("Indoor", [1, 5], [1.0, 2.0])])]).newest == 5 - assert Chart("Rain", "", [Panel("Rain", "mm", [], bars=Bars("Rain", "mm", [0, 3600], [0.0, 1.0], 3600))]).newest == 3600 - - -async def test_the_chart_of_an_alert_sent_lately_is_drawn_ahead_with_the_keyboards(alert_state, monkeypatch): - from lib.alerts.pictures import AlertCharts - clock = [0.0] - bot, uploads, context = preloading_bot(alert_state, monkeypatch, clock=clock) - bot.alert_charts.clock = lambda: clock[0] - drawn = [] - - async def counting(text, now): # draws any request (the stand-in's tools draw only temperature) - drawn.append(text) - return bot.images.canonical(text, now), text.encode(), text, "caption", 0 - bot._draw_ahead = counting - await bot.draw_buttons_ahead(context.bot) - assert "UV chart 1d" not in drawn and "Temperature chart 1d" in drawn # UV is no button: not drawn until an alert - bot.alert_charts.sent("uv", NS(photo=(NS(file_id="large"),))) - bot.alert_charts.sent("temps", NS(photo=(NS(file_id="large"),))) - drawn.clear() - clock[0] += 300 - await bot.draw_buttons_ahead(context.bot) - assert drawn.count("UV chart 1d") == 1 and drawn.count("Temperature chart 1d") == 1 # the alert's chart too, the button's once - bot.noticed() - clock[0] += 300 - await bot.draw_buttons_ahead(context.bot) - assert (-1001, b"UV chart 1d", True) in uploads # uploaded ahead with the keyboard's - drawn.clear() - clock[0] += AlertCharts.WARM_SECONDS - await bot.draw_buttons_ahead(context.bot) - assert "UV chart 1d" not in drawn # six hours on: no longer kept warm - - -def test_a_chart_drawn_in_one_theme_is_not_sent_again_after_the_theme_changes(monkeypatch): - from lib import charts - images = periods.ImageCache(lambda: 0.0) - monkeypatch.setattr(charts, "MODE", "off") - images.put("temperature chart 1d", b"light", "T", "caption") - assert images.get("temperature chart 1d") and images.ready("Temperature chart 1d", NOW) - monkeypatch.setattr(charts, "MODE", "on") # 8pm under DARKMODE=8pm-8am - assert images.ready("Temperature chart 1d", NOW) is None and images.get("temperature chart 1d") is None +async def test_a_press_while_its_period_is_being_fetched_waits_for_that_fetch_and_asks_nothing_more(serve, alert_state, monkeypatch): + """A period button pressed just after its chart, while that period is still being fetched in the background, waits for that fetch + (the press's own call would queue behind it) and puts in the chart it brings: ecobot-mcp is asked for that period once.""" + bot, uploads, context = await preloading_bot(serve, alert_state, monkeypatch) + bot.cfg = NS(tz=TZ) + asked, call, gate = [], summary(bot).call, asyncio.Event() + + async def held_back(args, meta=None): + asked.append(args.get("period")) + if args.get("period") == "3m": + await gate.wait() + return await call(args, meta) + summary(bot).call = held_back + sent, edits = [], [] + msg = chat_message(sent, edits) + await ask_chart(bot, NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")), + context, "7d") + for _ in range(50): + if "3m" in asked: + break + await asyncio.sleep(0.01) + msg.message_id = 101 + async def answer(text=None): + pass + pressed = asyncio.create_task(bot.on_period_button(press(msg, "pd:3m", answer), context)) + await asyncio.sleep(0.05) + assert not pressed.done() and asked.count("3m") == 1 # waiting for the fetch, not asking again + gate.set() + await pressed + await settle(bot) + assert asked.count("3m") == 1 and edits and edits[0][0] == "Temperature" diff --git a/tests/test_periods_text.py b/tests/test_periods_text.py new file mode 100644 index 00000000..c7d41aaf --- /dev/null +++ b/tests/test_periods_text.py @@ -0,0 +1,426 @@ +"""Periods in words (lib/periods_text.py): the table of docs/ecobot-mcp.md 3.2 read at fixed times, every answer worked out by hand. +Melbourne's clocks go back an hour at 3am on 5 Apr 2026 (2am to 3am happens twice) and forward at 2am on 4 Oct 2026 (2am to 3am +never happens).""" + +from datetime import datetime + +import pytest + +from lib.periods_text import PeriodError, read_period +from tests.fakes import TZ + + +def at(*when, fold: int = 0) -> datetime: + """A time on the station's clock.""" + return datetime(*when, tzinfo=TZ, fold=fold) + + +def read(words, now, start=None, end=None, **kw): + return read_period(words, start, end, now=now, tz=TZ, default="today", **kw) + + +def hours(period) -> float: + """The period's length in real hours (on one clock, aware datetimes subtract as wall times).""" + return (period.end.timestamp() - period.start.timestamp()) / 3600 + + +def check(now, words, start, end, text, **kw): + """Each of the words (a "|" between the ones that mean the same) reads as start to end, written as text.""" + for said in words.split("|"): + period = read(said.strip(), now, **kw) + assert (period.asked, period.start, period.end, period.text) == (said.strip(), at(*start), at(*end), text), said + + +def rows(*table): + return pytest.mark.parametrize("words, start, end, text", table, ids=[row[0].split("|")[0].strip() for row in table]) + + +HELD = at(2024, 3, 1, 15, 20) # the first reading held, for "on record" + +# ---------- Tue 10 Nov 2026 14:05: the doc's examples, every row of the table ---------- +TUESDAY = at(2026, 11, 10, 14, 5) +NOW = (2026, 11, 10, 14, 5) + + +@rows( + ("today | Today | so far today", (2026, 11, 10), NOW, "today: Tue 10 Nov 2026"), + ("yesterday", (2026, 11, 9), (2026, 11, 10), "yesterday: Mon 9 Nov 2026"), + ("last 30 minutes | 30 min | 30min | 30 mins | the past 30 minutes", (2026, 11, 10, 13, 35), NOW, + "the last 30 minutes: Tue 10 Nov 2026 1:35pm – 2:05pm"), + ("last 6 hours | 6h | 6 hrs | the past six hours", (2026, 11, 10, 8, 5), NOW, "the last 6 hours: Tue 10 Nov 2026 8:05am – 2:05pm"), + ("last 24 hours | 24h | 1d | last day | the past day | last 1 day | in the last 24 hours", (2026, 11, 9, 14, 5), NOW, + "the last 24 hours: Mon 9 Nov 2:05pm – Tue 10 Nov 2026 2:05pm"), + ("last hour | the past hour | 1h", (2026, 11, 10, 13, 5), NOW, "the last hour: Tue 10 Nov 2026 1:05pm – 2:05pm"), + ("last 7 days | 7d | 7D | seven days | the past 7 days | over the last seven days", (2026, 11, 4), NOW, + "the last 7 days: Wed 4 – Tue 10 Nov 2026"), + ("this week | past week | the past week | the last week | week | 1w | in the last week | This Week", (2026, 11, 4), NOW, + "the last 7 days: Wed 4 – Tue 10 Nov 2026"), + ("last 2 weeks | 2w | two weeks", (2026, 10, 28), NOW, "the last 2 weeks: Wed 28 Oct – Tue 10 Nov 2026"), + ("fortnight | the last fortnight", (2026, 10, 28), NOW, "the last 14 days: Wed 28 Oct – Tue 10 Nov 2026"), + ("past month | the last month | the past month | month | 1m | 1M | last 30 days | last 1 month", (2026, 10, 12), NOW, + "the last 30 days: Mon 12 Oct – Tue 10 Nov 2026"), + ("last 3 months | 3m | 3 mo | 3M | past three months", (2026, 8, 12), NOW, "the last 3 months: Wed 12 Aug – Tue 10 Nov 2026"), + ("5m | 5 months", (2026, 6, 12), NOW, "the last 5 months: Fri 12 Jun – Tue 10 Nov 2026"), # round(5×365/12) = 152 days: never minutes + ("past year | the last year | in the last year | year | 1y", (2025, 11, 11), NOW, "the last 365 days: Tue 11 Nov 2025 – Tue 10 Nov 2026"), + ("last 12 months | last twelve months", (2025, 11, 11), NOW, "the last 12 months: Tue 11 Nov 2025 – Tue 10 Nov 2026"), + ("last 2 years | 2y | past two years | the past 2 years", (2024, 11, 11), NOW, "the last 2 years: Mon 11 Nov 2024 – Tue 10 Nov 2026"), + ("week to date", (2026, 11, 9), NOW, "week to date: Mon 9 – Tue 10 Nov 2026"), + ("since Monday", (2026, 11, 9), NOW, "since Monday: Mon 9 – Tue 10 Nov 2026"), + ("last week", (2026, 11, 2), (2026, 11, 9), "last week: Mon 2 – Sun 8 Nov 2026"), + ("this month", (2026, 11, 1), NOW, "this month: Sun 1 – Tue 10 Nov 2026"), + ("last month", (2026, 10, 1), (2026, 11, 1), "last month: Thu 1 – Sat 31 Oct 2026"), + ("this year", (2026, 1, 1), NOW, "this year: Thu 1 Jan – Tue 10 Nov 2026"), + ("last year", (2025, 1, 1), (2026, 1, 1), "last year: Wed 1 Jan – Wed 31 Dec 2025"), + ("2025", (2025, 1, 1), (2026, 1, 1), "2025: Wed 1 Jan – Wed 31 Dec 2025"), + ("2026", (2026, 1, 1), NOW, "2026: Thu 1 Jan – Tue 10 Nov 2026"), + ("October 2025 | Oct 2025", (2025, 10, 1), (2025, 11, 1), "October 2025: Wed 1 – Fri 31 Oct 2025"), + ("October | oct", (2026, 10, 1), (2026, 11, 1), "October 2026: Thu 1 – Sat 31 Oct 2026"), + ("November", (2026, 11, 1), NOW, "November 2026: Sun 1 – Tue 10 Nov 2026"), + ("December", (2025, 12, 1), (2026, 1, 1), "December 2025: Mon 1 – Wed 31 Dec 2025"), # the latest December that has begun + ("June to August 2026 | between June and August 2026 | from June to August 2026 | June - August 2026", (2026, 6, 1), (2026, 9, 1), + "June 2026 to August 2026: Mon 1 Jun – Mon 31 Aug 2026"), + ("December to February", (2025, 12, 1), (2026, 3, 1), "December 2025 to February 2026: Mon 1 Dec 2025 – Sat 28 Feb 2026"), + ("5 to 10 Sep | 5 Sep to 10 Sep | Sat 5 – Thu 10 Sep 2026", (2026, 9, 5), (2026, 9, 11), "Sat 5 – Thu 10 Sep 2026"), + ("Saturday to Sunday", (2026, 11, 7), (2026, 11, 9), "Saturday to Sunday: Sat 7 – Sun 8 Nov 2026"), + ("Monday to now", (2026, 11, 9), NOW, "Monday to now: Mon 9 – Tue 10 Nov 2026"), + ("2026-09-05 | 5 Sep | 5 September | Sat 5 Sep | Saturday 5 September 2026 | 5th of September | September 5 | on 5 Sep", + (2026, 9, 5), (2026, 9, 6), "Sat 5 Sep 2026"), + ("5 September 2025 | Sep 5, 2025", (2025, 9, 5), (2025, 9, 6), "Fri 5 Sep 2025"), + ("29 Feb", (2024, 2, 29), (2024, 3, 1), "Thu 29 Feb 2024"), # the latest that has been + ("Monday | last Monday | on Monday", (2026, 11, 9), (2026, 11, 10), "Monday: Mon 9 Nov 2026"), + ("Tuesday | tue", (2026, 11, 3), (2026, 11, 4), "Tuesday: Tue 3 Nov 2026"), # the latest before today: never today + ("last Saturday | Saturday | sat", (2026, 11, 7), (2026, 11, 8), "Saturday: Sat 7 Nov 2026"), + ("Christmas Day | Christmas | christmas day 2025", (2025, 12, 25), (2025, 12, 26), "Christmas Day: Thu 25 Dec 2025"), + ("Melbourne Cup | Melbourne Cup Day | the Melbourne Cup | cup day", (2026, 11, 3), (2026, 11, 4), "Melbourne Cup Day: Tue 3 Nov 2026"), + ("Melbourne Cup 2025", (2025, 11, 4), (2025, 11, 5), "Melbourne Cup Day: Tue 4 Nov 2025"), + ("Christmas to New Year's Day", (2025, 12, 25), (2026, 1, 2), "Christmas Day to New Year's Day: Thu 25 Dec 2025 – Thu 1 Jan 2026"), + ("this morning", (2026, 11, 10, 6), (2026, 11, 10, 12), "this morning: Tue 10 Nov 2026 6am – 12pm"), + ("this afternoon", (2026, 11, 10, 12), NOW, "this afternoon: Tue 10 Nov 2026 12pm – 2:05pm"), + ("yesterday afternoon", (2026, 11, 9, 12), (2026, 11, 9, 18), "yesterday afternoon: Mon 9 Nov 2026 12pm – 6pm"), + ("Tuesday evening", (2026, 11, 3, 18), (2026, 11, 4), "Tuesday evening: Tue 3 Nov 2026 6pm – midnight"), + ("Saturday morning", (2026, 11, 7, 6), (2026, 11, 7, 12), "Saturday morning: Sat 7 Nov 2026 6am – 12pm"), + ("last night | overnight", (2026, 11, 9, 22), (2026, 11, 10, 6), "last night: Mon 9 Nov 10pm – Tue 10 Nov 2026 6am"), + ("Tuesday night", (2026, 11, 2, 22), (2026, 11, 3, 6), "Tuesday night: Mon 2 Nov 10pm – Tue 3 Nov 2026 6am"), + ("since 6am | since 6 am | since 06:00", (2026, 11, 10, 6), NOW, "since 6am: Tue 10 Nov 2026 6am – 2:05pm"), + ("since 3pm | since 15:00", (2026, 11, 9, 15), NOW, "since 3pm: Mon 9 Nov 3pm – Tue 10 Nov 2026 2:05pm"), # the latest 3pm + ("since midnight", (2026, 11, 10), NOW, "since midnight: Tue 10 Nov 2026 12am – 2:05pm"), + ("since 5 Sep", (2026, 9, 5), NOW, "Sat 5 Sep – Tue 10 Nov 2026"), + ("on record | all time | all-time | ever | of all time | the whole record", (2024, 3, 1), NOW, "on record: Fri 1 Mar 2024 – Tue 10 Nov 2026"), +) +def test_every_row_of_the_table_on_a_tuesday(words, start, end, text): + check(TUESDAY, words, start, end, text, first_held=HELD) + + +def test_a_period_hands_back_its_days_and_the_strings_todays_tools_take(): + week = read("last week", TUESDAY) + assert (week.first_day, week.last_day, week.cut) == (at(2026, 11, 2).date(), at(2026, 11, 8).date(), None) + assert week.as_naive_strings() == ("2026-11-02 00:00:00", "2026-11-08 23:59:59") + assert read("today", TUESDAY).as_naive_strings() == ("2026-11-10 00:00:00", "2026-11-10 14:04:59") + assert read("last night", TUESDAY).as_naive_strings() == ("2026-11-09 22:00:00", "2026-11-10 05:59:59") + assert read_period(None, None, None, now=TUESDAY, tz=TZ, default="last 24 hours").asked == "last 24 hours" # nothing asked: the default + assert read_period("", " ", None, now=TUESDAY, tz=TZ, default="yesterday").text == "yesterday: Mon 9 Nov 2026" # blanks aren't asking + + +# ---------- Mon 9 Nov 2026 10:00 ---------- +MONDAY = at(2026, 11, 9, 10) + + +@rows( + ("week to date", (2026, 11, 9), (2026, 11, 9, 10), "week to date: Mon 9 Nov 2026"), + ("since Monday", (2026, 11, 9), (2026, 11, 9, 10), "since Monday: Mon 9 Nov 2026"), # this Monday: today + ("Monday | last Monday", (2026, 11, 2), (2026, 11, 3), "Monday: Mon 2 Nov 2026"), # the latest before today + ("Sunday", (2026, 11, 8), (2026, 11, 9), "Sunday: Sun 8 Nov 2026"), + ("last week", (2026, 11, 2), (2026, 11, 9), "last week: Mon 2 – Sun 8 Nov 2026"), + ("this week", (2026, 11, 3), (2026, 11, 9, 10), "the last 7 days: Tue 3 – Mon 9 Nov 2026"), + ("Monday night", (2026, 11, 1, 22), (2026, 11, 2, 6), "Monday night: Sun 1 Nov 10pm – Mon 2 Nov 2026 6am"), + ("Sunday evening", (2026, 11, 8, 18), (2026, 11, 9), "Sunday evening: Sun 8 Nov 2026 6pm – midnight"), + ("Saturday to Sunday", (2026, 11, 7), (2026, 11, 9), "Saturday to Sunday: Sat 7 – Sun 8 Nov 2026"), +) +def test_on_a_monday(words, start, end, text): + check(MONDAY, words, start, end, text) + + +# ---------- Sun 1 Nov 2026 14:05: the 1st of a month ---------- +FIRST = at(2026, 11, 1, 14, 5) +FIRST_NOW = (2026, 11, 1, 14, 5) + + +@rows( + ("this month", (2026, 11, 1), FIRST_NOW, "this month: Sun 1 Nov 2026"), + ("last month", (2026, 10, 1), (2026, 11, 1), "last month: Thu 1 – Sat 31 Oct 2026"), + ("November", (2026, 11, 1), FIRST_NOW, "November 2026: Sun 1 Nov 2026"), + ("October", (2026, 10, 1), (2026, 11, 1), "October 2026: Thu 1 – Sat 31 Oct 2026"), + ("December", (2025, 12, 1), (2026, 1, 1), "December 2025: Mon 1 – Wed 31 Dec 2025"), + ("this week", (2026, 10, 26), FIRST_NOW, "the last 7 days: Mon 26 Oct – Sun 1 Nov 2026"), + ("last week", (2026, 10, 19), (2026, 10, 26), "last week: Mon 19 – Sun 25 Oct 2026"), + ("week to date", (2026, 10, 26), FIRST_NOW, "week to date: Mon 26 Oct – Sun 1 Nov 2026"), + ("past month", (2026, 10, 3), FIRST_NOW, "the last 30 days: Sat 3 Oct – Sun 1 Nov 2026"), + ("1 Nov", (2026, 11, 1), FIRST_NOW, "Sun 1 Nov 2026"), + ("Sunday", (2026, 10, 25), (2026, 10, 26), "Sunday: Sun 25 Oct 2026"), + ("since Sunday", (2026, 11, 1), FIRST_NOW, "since Sunday: Sun 1 Nov 2026"), # since a weekday: today, if it is that day + ("yesterday", (2026, 10, 31), (2026, 11, 1), "yesterday: Sat 31 Oct 2026"), + ("October to November", (2026, 10, 1), FIRST_NOW, "October 2026 to November 2026: Thu 1 Oct – Sun 1 Nov 2026"), +) +def test_on_the_first_of_a_month(words, start, end, text): + check(FIRST, words, start, end, text) + + +# ---------- Fri 1 Jan 2027 09:00 ---------- +NEW_YEAR = at(2027, 1, 1, 9) +NEW_YEAR_NOW = (2027, 1, 1, 9) + + +@rows( + ("this year", (2027, 1, 1), NEW_YEAR_NOW, "this year: Fri 1 Jan 2027"), + ("last year", (2026, 1, 1), (2027, 1, 1), "last year: Thu 1 Jan – Thu 31 Dec 2026"), + ("2026", (2026, 1, 1), (2027, 1, 1), "2026: Thu 1 Jan – Thu 31 Dec 2026"), + ("this month", (2027, 1, 1), NEW_YEAR_NOW, "this month: Fri 1 Jan 2027"), + ("last month", (2026, 12, 1), (2027, 1, 1), "last month: Tue 1 – Thu 31 Dec 2026"), + ("December", (2026, 12, 1), (2027, 1, 1), "December 2026: Tue 1 – Thu 31 Dec 2026"), + ("January", (2027, 1, 1), NEW_YEAR_NOW, "January 2027: Fri 1 Jan 2027"), + ("February", (2026, 2, 1), (2026, 3, 1), "February 2026: Sun 1 – Sat 28 Feb 2026"), + ("Christmas Day", (2026, 12, 25), (2026, 12, 26), "Christmas Day: Fri 25 Dec 2026"), + ("New Year's Day | new years day", (2027, 1, 1), NEW_YEAR_NOW, "New Year's Day: Fri 1 Jan 2027"), + ("last week", (2026, 12, 21), (2026, 12, 28), "last week: Mon 21 – Sun 27 Dec 2026"), + ("this week", (2026, 12, 26), NEW_YEAR_NOW, "the last 7 days: Sat 26 Dec 2026 – Fri 1 Jan 2027"), + ("31 Dec", (2026, 12, 31), (2027, 1, 1), "Thu 31 Dec 2026"), + ("5 Jan", (2026, 1, 5), (2026, 1, 6), "Mon 5 Jan 2026"), + ("past year", (2026, 1, 2), NEW_YEAR_NOW, "the last 365 days: Fri 2 Jan 2026 – Fri 1 Jan 2027"), + ("December to January", (2026, 12, 1), NEW_YEAR_NOW, "December 2026 to January 2027: Tue 1 Dec 2026 – Fri 1 Jan 2027"), + ("yesterday", (2026, 12, 31), (2027, 1, 1), "yesterday: Thu 31 Dec 2026"), +) +def test_on_new_years_day(words, start, end, text): + check(NEW_YEAR, words, start, end, text) + + +# ---------- Tue 29 Feb 2028 14:05 ---------- +LEAP = at(2028, 2, 29, 14, 5) +LEAP_NOW = (2028, 2, 29, 14, 5) + + +@rows( + ("29 Feb | 29 February 2028", (2028, 2, 29), LEAP_NOW, "Tue 29 Feb 2028"), + ("28 Feb", (2028, 2, 28), (2028, 2, 29), "Mon 28 Feb 2028"), + ("this month", (2028, 2, 1), LEAP_NOW, "this month: Tue 1 – Tue 29 Feb 2028"), + ("February", (2028, 2, 1), LEAP_NOW, "February 2028: Tue 1 – Tue 29 Feb 2028"), + ("last month", (2028, 1, 1), (2028, 2, 1), "last month: Sat 1 – Mon 31 Jan 2028"), + ("last year", (2027, 1, 1), (2028, 1, 1), "last year: Fri 1 Jan – Fri 31 Dec 2027"), + ("past year | 1y", (2027, 3, 2), LEAP_NOW, "the last 365 days: Tue 2 Mar 2027 – Tue 29 Feb 2028"), + ("3m", (2027, 12, 1), LEAP_NOW, "the last 3 months: Wed 1 Dec 2027 – Tue 29 Feb 2028"), + ("February 2027", (2027, 2, 1), (2027, 3, 1), "February 2027: Mon 1 – Sun 28 Feb 2027"), +) +def test_on_29_february(words, start, end, text): + check(LEAP, words, start, end, text) + + +def test_29_february_in_a_year_without_one_is_no_date(): + with pytest.raises(PeriodError, match="29 February 2027 isn't a date"): + read("29 Feb 2027", LEAP) + with pytest.raises(PeriodError, match="isn't a date"): + read("31 Sep", LEAP) + + +# ---------- Tue 10 Nov 2026 00:30 ---------- +LATE = at(2026, 11, 10, 0, 30) +LATE_NOW = (2026, 11, 10, 0, 30) + + +@rows( + ("today", (2026, 11, 10), LATE_NOW, "today: Tue 10 Nov 2026"), + ("yesterday", (2026, 11, 9), (2026, 11, 10), "yesterday: Mon 9 Nov 2026"), + ("last 2 hours", (2026, 11, 9, 22, 30), LATE_NOW, "the last 2 hours: Mon 9 Nov 10:30pm – Tue 10 Nov 2026 12:30am"), + ("since 6am", (2026, 11, 9, 6), LATE_NOW, "since 6am: Mon 9 Nov 6am – Tue 10 Nov 2026 12:30am"), + ("last night | overnight", (2026, 11, 9, 22), LATE_NOW, "last night: Mon 9 Nov 10pm – Tue 10 Nov 2026 12:30am"), # still going + ("yesterday evening", (2026, 11, 9, 18), (2026, 11, 10), "yesterday evening: Mon 9 Nov 2026 6pm – midnight"), + ("last 7 days", (2026, 11, 4), LATE_NOW, "the last 7 days: Wed 4 – Tue 10 Nov 2026"), +) +def test_at_half_past_midnight(words, start, end, text): + check(LATE, words, start, end, text) + + +def test_at_half_past_midnight_this_morning_is_still_ahead(): + with pytest.raises(PeriodError, match="in the future .*use forecast"): + read("this morning", LATE) + + +# ---------- the days the clocks change ---------- +def test_the_day_the_clocks_go_back_has_25_hours_and_its_hours_are_real(): + noon = at(2026, 4, 5, 12) + assert hours(read("today", noon)) == 13 # midnight was summer time + assert read("last 24 hours", noon).start == at(2026, 4, 4, 13) and hours(read("last 24 hours", noon)) == 24 + night = read("last night", noon) + assert (night.start, night.end, hours(night)) == (at(2026, 4, 4, 22), at(2026, 4, 5, 6), 9) + assert hours(read("yesterday", at(2026, 4, 6, 12))) == 25 + since = read("since 2am", noon) # the second 2am: the latest + assert (since.start.fold, since.start.timestamp(), hours(since)) == (1, at(2026, 4, 5, 2, fold=1).timestamp(), 10) + early = read("last 3 hours", at(2026, 4, 5, 4)) # 4am back to the first 2am + assert (early.start.fold, hours(early), early.text) == (0, 3, "the last 3 hours: Sun 5 Apr 2026 2am – 4am") + assert read("Easter Sunday", noon).text == "Easter Sunday: Sun 5 Apr 2026" + two = read("last 2 days", at(2026, 4, 6, 12), whole_days=True) + assert (two.start, two.end, hours(two), two.text) == (at(2026, 4, 4), at(2026, 4, 6), 49, "the last 2 days: Sat 4 – Sun 5 Apr 2026") + + +def test_the_day_the_clocks_go_forward_has_23_hours_and_its_hours_are_real(): + noon = at(2026, 10, 4, 12) + assert hours(read("today", noon)) == 11 + assert read("last 24 hours", noon).start == at(2026, 10, 3, 11) and hours(read("last 24 hours", noon)) == 24 + night = read("last night", noon) + assert (night.start, night.end, hours(night)) == (at(2026, 10, 3, 22), at(2026, 10, 4, 6), 7) + assert hours(read("yesterday", at(2026, 10, 5, 12))) == 23 + early = read("last 3 hours", at(2026, 10, 4, 4)) # three real hours: 2am to 3am never happened + assert (early.start, early.text) == (at(2026, 10, 4), "the last 3 hours: Sun 4 Oct 2026 12am – 4am") + skipped = read("since 2:30am", noon) # a time that never happened: when the clocks jump + assert (skipped.start, hours(skipped)) == (at(2026, 10, 4, 3), 9) + assert read(None, noon, start="2026-10-04 02:30").start == at(2026, 10, 4, 3) + + +# ---------- whole-day tools ---------- +CUT = "to Mon 9 Nov: today isn't over" +WHOLE_DAYS = [ # (words, start, end, text, cut) at TUESDAY + ("last 7 days", (2026, 11, 3), (2026, 11, 10), "the last 7 days: Tue 3 – Mon 9 Nov 2026", CUT), # that many whole days to yesterday + ("this week", (2026, 11, 3), (2026, 11, 10), "the last 7 days: Tue 3 – Mon 9 Nov 2026", CUT), + ("3m", (2026, 8, 11), (2026, 11, 10), "the last 3 months: Tue 11 Aug – Mon 9 Nov 2026", CUT), + ("past year", (2025, 11, 10), (2026, 11, 10), "the last 365 days: Mon 10 Nov 2025 – Mon 9 Nov 2026", CUT), + ("1d", (2026, 11, 9), (2026, 11, 10), "the last day: Mon 9 Nov 2026", CUT), + ("last 48 hours", (2026, 11, 8), (2026, 11, 10), "the last 2 days: Sun 8 – Mon 9 Nov 2026", CUT), + ("this month", (2026, 11, 1), (2026, 11, 10), "this month: Sun 1 – Mon 9 Nov 2026", CUT), # a calendar one runs to yesterday + ("this year", (2026, 1, 1), (2026, 11, 10), "this year: Thu 1 Jan – Mon 9 Nov 2026", CUT), + ("since Monday", (2026, 11, 9), (2026, 11, 10), "since Monday: Mon 9 Nov 2026", CUT), + ("on record", (2024, 3, 1), (2026, 11, 10), "on record: Fri 1 Mar 2024 – Mon 9 Nov 2026", CUT), + ("yesterday", (2026, 11, 9), (2026, 11, 10), "yesterday: Mon 9 Nov 2026", None), # nothing of today: not cut + ("last week", (2026, 11, 2), (2026, 11, 9), "last week: Mon 2 – Sun 8 Nov 2026", None), + ("October", (2026, 10, 1), (2026, 11, 1), "October 2026: Thu 1 – Sat 31 Oct 2026", None), + ("Christmas Day", (2025, 12, 25), (2025, 12, 26), "Christmas Day: Thu 25 Dec 2025", None), +] + + +@pytest.mark.parametrize("words, start, end, text, cut", WHOLE_DAYS, ids=[row[0] for row in WHOLE_DAYS]) +def test_whole_day_tools_take_whole_days_to_yesterday(words, start, end, text, cut): + period = read(words, TUESDAY, whole_days=True, first_held=HELD) + assert (period.start, period.end, period.text, period.cut) == (at(*start), at(*end), text, cut) + + +def test_whole_day_tools_cut_on_other_days_too(): + monday = read("this week", MONDAY, whole_days=True) + assert (monday.text, monday.cut) == ("the last 7 days: Mon 2 – Sun 8 Nov 2026", "to Sun 8 Nov: today isn't over") + leap = read("this month", LEAP, whole_days=True) + assert (leap.text, leap.cut) == ("this month: Tue 1 – Mon 28 Feb 2028", "to Mon 28 Feb: today isn't over") + assert read("1y", LEAP, whole_days=True).text == "the last 365 days: Mon 1 Mar 2027 – Mon 28 Feb 2028" + assert read("past year", NEW_YEAR, whole_days=True).text == "the last 365 days: Thu 1 Jan – Thu 31 Dec 2026" + assert read("this year", FIRST, whole_days=True).text == "this year: Thu 1 Jan – Sat 31 Oct 2026" + + +@pytest.mark.parametrize("words, now", [ + ("today", TUESDAY), ("last 5 hours", TUESDAY), ("30 min", TUESDAY), ("this month", FIRST), ("November", FIRST), + ("week to date", MONDAY), ("since Monday", MONDAY), ("this year", NEW_YEAR), ("New Year's Day", NEW_YEAR), ("29 Feb", LEAP), +]) +def test_a_whole_day_tool_refuses_what_leaves_no_whole_day(words, now): + with pytest.raises(PeriodError, match=r"leaves no whole day.*use summary or readings") as caught: + read(words, now, whole_days=True) + assert caught.value.forms == () + + +@pytest.mark.parametrize("words", ["this morning", "yesterday afternoon", "last night", "Tuesday night", "since 6am"]) +def test_a_whole_day_tool_refuses_part_of_a_day(words): + with pytest.raises(PeriodError, match=r"is part of a day.*use summary or readings"): + read(words, TUESDAY, whole_days=True) + + +def test_a_whole_day_tool_takes_dates_only_and_cuts_them_to_yesterday(): + period = read(None, TUESDAY, start="2026-11-01", whole_days=True) + assert (period.start, period.end, period.text, period.cut) == (at(2026, 11, 1), at(2026, 11, 10), "Sun 1 – Mon 9 Nov 2026", CUT) + period = read(None, TUESDAY, start="2026-10-01", end="2026-10-31", whole_days=True) + assert (period.start, period.end, period.cut) == (at(2026, 10, 1), at(2026, 11, 1), None) + with pytest.raises(PeriodError, match=r"has a time.*use summary or readings"): + read(None, TUESDAY, start="2026-11-01 06:00", whole_days=True) + with pytest.raises(PeriodError, match="leaves no whole day"): + read(None, TUESDAY, start="2026-11-10", whole_days=True) + + +# ---------- start and end ---------- +def test_start_and_end_are_the_stations_clock_and_a_date_end_includes_the_day(): + period = read(None, TUESDAY, start="2026-11-01", end="2026-11-03") + assert (period.asked, period.start, period.end, period.text) == ("start/end", at(2026, 11, 1), at(2026, 11, 4), "Sun 1 – Tue 3 Nov 2026") + assert (period.first_day, period.last_day, period.as_naive_strings()) == ( + at(2026, 11, 1).date(), at(2026, 11, 3).date(), ("2026-11-01 00:00:00", "2026-11-03 23:59:59")) + period = read(None, TUESDAY, start="2026-11-01 06:00", end="2026-11-01 09:30") # an end with a time stops at it + assert (period.start, period.end, period.text) == (at(2026, 11, 1, 6), at(2026, 11, 1, 9, 30), "Sun 1 Nov 2026 6am – 9:30am") + assert read(None, TUESDAY, start="2026-11-01").end == TUESDAY # no end: to now + assert read(None, TUESDAY, start="2026-11-01", end="2026-12-25").end == TUESDAY # nor past it + + +def test_a_start_or_end_with_an_offset_is_moved_to_the_stations_clock(): + assert read(None, TUESDAY, start="2026-11-09T20:00:00Z").start == at(2026, 11, 10, 7) # UTC: 7am in daylight saving + period = read(None, TUESDAY, start="2026-11-01T00:00:00+00:00", end="2026-11-01T06:00:00+00:00") + assert (period.start, period.end) == (at(2026, 11, 1, 11), at(2026, 11, 1, 17)) + assert read(None, at(2026, 6, 10, 12), start="2026-06-01T00:00:00Z").start == at(2026, 6, 1, 10) # standard time + + +@pytest.mark.parametrize("period, start, end, says", [ + ("today", "2026-11-01", None, "not both"), + ("today", None, "2026-11-03", "not both"), + (None, None, "2026-11-03", "needs a `start`"), + (None, "1 Nov", None, "isn't a date or time"), + (None, "2026-11-05", "2026-11-03", "must be before"), + (None, "2026-11-11", None, "in the future.*use forecast"), +]) +def test_start_and_end_errors_say_what_to_send(period, start, end, says): + with pytest.raises(PeriodError, match=says) as caught: + read(period, TUESDAY, start=start, end=end) + assert "It is now Tue 10 Nov 2026 2:05pm." in str(caught.value) + + +# ---------- errors that teach ---------- +@pytest.mark.parametrize("words", ["yesterday afternoon and", "June, July", "last summer", "the last 7 days please", "rain this week", + "0 days", "last thirteen days", "m", "5", "tonight"]) +def test_words_outside_the_table_list_the_forms_with_what_each_means_now(words): + with pytest.raises(PeriodError) as caught: + read(words, TUESDAY, first_held=HELD) + error = caught.value + assert f"{words!r} isn't a period this tool can read" in error.message and "It is now Tue 10 Nov 2026 2:05pm." in error.message + forms = dict(error.forms) + assert forms["today"] == "today: Tue 10 Nov 2026" + assert forms["last N days, Nd (N from 2)"] == "the last 7 days: Wed 4 – Tue 10 Nov 2026" + assert forms["last N months, Nm, N mo (m is months, never minutes)"] == "the last 3 months: Wed 12 Aug – Tue 10 Nov 2026" + assert forms["last week (the previous Monday to Sunday)"] == "last week: Mon 2 – Sun 8 Nov 2026" + assert forms["a year, such as 2025"] == "2025: Wed 1 Jan – Wed 31 Dec 2025" + assert forms["a day, such as 2026-09-05, 5 Sep, 5 September 2025, Sat 5 Sep (with no year, the latest not after today)"] == \ + "5 Sep: Sat 5 Sep 2026" + assert forms["on record, all time, ever (from the first reading held)"] == "on record: Fri 1 Mar 2024 – Tue 10 Nov 2026" + assert "- last N days, Nd (N from 2) → the last 7 days: Wed 4 – Tue 10 Nov 2026" in str(error) + assert len(forms) == 27 + + +def test_a_whole_day_tools_forms_are_its_own(): + with pytest.raises(PeriodError) as caught: + read("last summer", TUESDAY, whole_days=True) + forms = dict(caught.value.forms) + assert "as dates ('YYYY-MM-DD')" in caught.value.message + assert forms["last N days, Nd (N from 2)"] == "the last 7 days: Tue 3 – Mon 9 Nov 2026" + assert not {"today", "last N minutes, N min", "since 6am, since Monday"} & set(forms) + assert forms["on record, all time, ever (from the first reading held)"] == "from the first reading held, for the readings asked about, to now" + + +@pytest.mark.parametrize("words", ["tomorrow", "tomorrow morning", "next week", "the next 3 days", "December 2026", "2027", + "Christmas Day 2026", "5 Dec 2026", "this evening"]) +def test_a_future_period_points_to_the_forecast(words): + with pytest.raises(PeriodError, match=r"is in the future.*for what's ahead, use forecast") as caught: + read(words, TUESDAY) + assert caught.value.forms == () and "It is now Tue 10 Nov 2026 2:05pm." in str(caught.value) + + +def test_a_weekday_that_does_not_match_the_date_is_named(): + with pytest.raises(PeriodError, match=r"5 September 2026 is a Saturday, not a Friday: send 'Sat 5 Sep 2026'"): + read("Fri 5 Sep", TUESDAY) + + +def test_longer_than_anything_held_points_to_on_record(): + with pytest.raises(PeriodError, match="longer than ten years.*'on record'"): + read("last 20 years", TUESDAY) + assert read("last 10 years", TUESDAY).start == at(2016, 11, 13) # 3650 days: today and the 3649 before + + +def test_on_record_needs_the_first_reading_held(): + with pytest.raises(PeriodError, match="Nothing is held yet"): + read("on record", TUESDAY) + assert read("on record", TUESDAY, first_held=at(2025, 6, 1).date()).start == at(2025, 6, 1) diff --git a/tests/test_pollen.py b/tests/test_pollen.py index ce95c4c9..3a19dabc 100644 --- a/tests/test_pollen.py +++ b/tests/test_pollen.py @@ -55,8 +55,7 @@ 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() assert pollen.lines() == ["Grass pollen forecast: 🔴 High", "Thunderstorm asthma forecast: 🔴 High"] - out = json.loads(await pollen.handle({})) - assert out["lines"] == pollen.lines() and "Central" not in json.dumps(out) and out["asthma_updated"] == "1 Oct 2026 4:00pm" + assert "Central" not in json.dumps(pollen.lines()) and pollen.current()["asthma"]["updated"] == "1 Oct 2026 4:00pm" await pollen.close() @@ -65,7 +64,7 @@ async def test_a_forecast_for_another_day_and_a_missing_asthma_forecast_are_said with caplog.at_level("WARNING"): await pollen.start() assert pollen.lines() == ["Grass pollen forecast: 🟠 Moderate (forecast for Wed 11 Nov)"] - assert json.loads(await pollen.handle({}))["asthma_note"] == "The page had no thunderstorm asthma level for this district when it was last read." + 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 await pollen.close() @@ -84,7 +83,7 @@ async def test_the_district_is_the_sites_whatever_its_case_and_one_it_lacks_is_w await pollen.close() with caplog.at_level("WARNING"): pollen, _ = make(tmp_path, pollen_district="Centrl") - assert pollen.district == "Centrl" and "POLLEN_DISTRICT 'Centrl' is not one of the site's districts" in caplog.text + assert pollen.district == "Centrl" and "MCP_POLLEN_DISTRICT 'Centrl' is not one of the site's districts" in caplog.text await pollen.close() @@ -124,20 +123,10 @@ def handler(request): pollen = Pollen(config(tmp_path, pollen=True), httpx.MockTransport(handler)) pollen.now = lambda: datetime.combine(SEASON_DAY, dtime(12, 0)) await pollen.start() - assert pollen.lines() == [] and "No pollen levels" in await pollen.handle({}) + assert pollen.lines() == [] await pollen.close() -def test_pollen_words_need_data_and_a_bare_pollen_question_is_fetched_without_the_model(): - from lib import intent - now = datetime(2026, 10, 1, 12, 0) - for text in ("pollen", "Hay fever", "thunderstorm asthma risk"): - assert intent.read(text, now, ["Ecowitt", "AirGradient", "Pollen"]).fast[0] == "pollen_asthma" - assert intent.read("pollen", now).fast is None - for text in ("is the pollen bad today?", "any asthma risk"): - assert intent.read(text, now, ["Ecowitt", "AirGradient", "Pollen"]).needs_data - - def make_on(tmp_path, day, hour=12, html=None): """A Pollen source whose clock says this day (the season is October to December).""" pollen, calls = make(tmp_path, html) @@ -157,25 +146,19 @@ async def test_out_of_season_nothing_is_fetched_not_even_at_start_with_an_empty_ pollen, calls = make_on(tmp_path, date(2027, 2, 10)) await pollen.start() assert await pollen.warm(True) == "Pollen out of season" and await pollen.warm(False) == "Pollen out of season" - assert calls == [] and pollen.lines() == [] - out = json.loads(await pollen.handle({})) - assert out == {"error": "Pollen and thunderstorm asthma forecasts only run from October to December."} and calls == [] + assert calls == [] and pollen.lines() == [] and not pollen.in_season() await pollen.close() -async def test_last_seasons_page_is_not_shown_and_the_report_leaves_the_block_out(tmp_path): - from lib import report +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() assert pollen.lines()[0].startswith("Grass pollen forecast: 🔴 High") - assert json.loads(await pollen.handle({"cached": True}))["time"] # when the page was fetched, for the report's heading + 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() assert january.data is not None and january.lines() == [] and january.current()["grass"] is None and calls == [] - result = await january.handle({"cached": True}) - assert "error" in json.loads(result) - assert "Pollen" not in report.report({"pollen_asthma": result}, date(2027, 1, 5)) # no block in the report await january.close() diff --git a/tests/test_report.py b/tests/test_report.py deleted file mode 100644 index b3cc5f1d..00000000 --- a/tests/test_report.py +++ /dev/null @@ -1,275 +0,0 @@ -import json -from datetime import date - -from lib import report - -# What `python scripts/report_inputs.py` printed on the real station (rain, night), its time as the station now writes it -NOW = ('{"time":"Fri 2 Oct 2026 2:21am","outdoor":{"temperature":"12.3 ℃","feels_like":"12.3 ℃","app_temp":"12.7 ℃","dew_point":"11.3 ℃",' - '"vpd":"0.085 kPa","humidity":"94 %"},"indoor":{"temperature":"18.3 ℃","humidity":"63 %","dew_point":"11.1 ℃","feels_like":"18.3 ℃",' - '"app_tempin":"18.7 ℃"},"solar_and_uvi":{"solar":"0.0 W/m²","uvi":"0"},"rainfall":{"rain_rate":"1.8 mm/hr","daily":"6.3 mm",' - '"event":"49.8 mm","1_hour":"1.3 mm","weekly":"49.8 mm","monthly":"49.8 mm","yearly":"5105.7 mm"},"wind":{"wind_speed":"0.0 km/h",' - '"wind_gust":"0.0 km/h","wind_direction":"131 º"},"pressure":{"relative":"1025.0 hPa","absolute":"1009.5 hPa"},' - '"emoji":{"outdoor.temperature":"🧥","outdoor.feels_like":"🧥","outdoor.app_temp":"🧥",' - '"outdoor.humidity":"💦","indoor.temperature":"🧥","indoor.feels_like":"🧥","indoor.app_tempin":"🧥","rainfall.rain_rate":"🌧️",' - '"rainfall.daily":"☔","pressure.relative":"🗜️"}}') -AIR = ('{"sensor": "Fairleigh", "sensor_type": "outdoor", "time": "Fri 2 Oct 2026 2:22am", "pm2_5": {"value": 1.4, "unit": "µg/m³", ' - '"rating": "🟢 good", "aqi_us": 8, "band": "good"}, "pm10": {"value": 3.0, "unit": "µg/m³", "rating": "🟢 good"}, "pm1": {"value": 1.0, ' - '"unit": "µg/m³", "rating": "🟢 good"}, "co2": {"value": 433.0, "unit": "ppm", "rating": "🟢 good"}, "voc_index": {"value": 88.0, ' - '"unit": "relative index (100 = this sensor\'s recent average)", "rating": "🟢 good"}, "nox_index": {"value": 1.0, ' - '"unit": "relative index (1 = baseline)", "rating": "🟢 good"}}') -POLLEN = '{"lines": ["Grass pollen forecast: 🟢 Low", "Thunderstorm asthma forecast: 🟢 Low"], "place": "Melbourne", "source": "melbournepollen.com.au", "time": "Fri 2 Oct 2026 6:00pm"}' -FORECAST = ('{"lines": ["Today: 🌦️ Showers. 11–16°C, 97% chance of rain", "Saturday: ⛈️ Thunderstorm. 12–20°C, 95% chance of rain"], ' - '"place": "Melbourne", "source": "Open-Meteo", "time": "Fri 2 Oct 2026 6:05pm"}') - -TODAY = date(2026, 10, 2) # the day the results above are from - -WEATHER = """\ -• Outdoor: 🧥 12.3 °C, 💦 94 % -• Indoor: 🧥 18.3 °C, 63 % -• Pressure: 🗜️ 1025.0 hPa -• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)""" # night and calm: no Sun or Wind line - - -def test_the_report_is_laid_out_in_code_with_emoji_before_the_readings_they_belong_to(): - got = report.report({"weather_now": NOW, "air_quality": AIR, "pollen_asthma": POLLEN, "weather_forecast": FORECAST}, TODAY) - assert got == f"""Weather station (2:21am) -{WEATHER} - -Air quality (2:22am) -• PM2.5: 1.4 µg/m³ 🟢 good (AQI 8) -• PM10: 3.0 µg/m³ 🟢 good -• PM1: 1.0 µg/m³ 🟢 good -• CO₂: 433 ppm 🟢 good -• VOC index: 88 🟢 good -• NOx index: 1.0 🟢 good - -Pollen & asthma (Melbourne, 6:00pm) -• Grass pollen forecast: 🟢 Low -• Thunderstorm asthma forecast: 🟢 Low - -Forecast (Melbourne, 6:05pm) -• Today: 🌦️ Showers. 11–16°C, 97% chance of rain -• Saturday: ⛈️ Thunderstorm. 12–20°C, 95% chance of rain""" - assert not got.startswith("Current report") - - -def test_weather_now_is_just_the_weather_stations_bullets(): - assert report.weather_now(NOW) == WEATHER - assert report.weather_now("Error calling tool: timed out") is None and report.weather_now(None) is None - - -def test_a_dry_calm_day_has_no_rain_line_noise(): - dry = ('{"outdoor":{"temperature":"21.0 ℃","humidity":"50 %"},"rainfall":{"rain_rate":"0.0 mm/hr","daily":"0.0 mm","monthly":"12.0 mm"},' - '"wind":{"wind_speed":"12.0 km/h","wind_gust":"20.0 km/h","wind_direction":"270 º"},"emoji":{}}') - lines = report.weather_now(dry).splitlines() - assert lines == ["• Outdoor: 21.0 °C, 50 %", "• Rain today: 0.0 mm (month total 12.0 mm)", "• Wind: 12.0 km/h from 270°, gust 20.0 km/h"] - drizzle = dry.replace('"0.0 mm/hr"', '"0.6 mm/hr"').replace('"emoji":{}', '"emoji":{"rainfall.rain_rate":"🌧️"}') - assert "; 🌧️ raining (0.6 mm/h)" in report.weather_now(drizzle) - assert "raining" not in report.weather_now(dry.replace('"0.0 mm/hr"', '"0.00 mm/hr"')) # however the zero is written - - -def test_a_failed_or_missing_source_is_left_out_or_said_so_and_the_forecast_without_a_tag_has_a_plain_heading(): - got = report.report({"weather_now": "Error calling tool: boom", "air_quality": AIR, - "pollen_asthma": '{"error": "No pollen levels are available right now."}', - "weather_forecast": '{"lines": ["Today: ☀️ Sunny. 20–25°C"]}'}, TODAY) - assert got.startswith("Weather station\n• not available right now\n\nAir quality (2:22am)\n• PM2.5:") - assert "Pollen" not in got and got.endswith("Forecast\n• Today: ☀️ Sunny. 20–25°C") - assert report.report({}, TODAY) == "No readings are available right now." - - -def test_sun_uv_and_wind_are_left_out_when_zero_and_shown_when_not(): - day = NOW.replace('"solar":"0.0 W/m²","uvi":"0"', '"solar":"612.5 W/m²","uvi":"7"').replace( - '"wind_speed":"0.0 km/h","wind_gust":"0.0 km/h"', '"wind_speed":"14.0 km/h","wind_gust":"31.0 km/h"') - got = report.weather_now(day).splitlines() - assert got[-2:] == ["• Sun: solar radiation 612.5 W/m² (high), UV index 7", "• Wind: 14.0 km/h from 131°, gust 31.0 km/h"] - only_uv = report.weather_now(NOW.replace('"uvi":"0"', '"uvi":"3"')) - assert "• Sun: UV index 3" in only_uv and "solar" not in only_uv - gusty = report.weather_now(NOW.replace('"wind_gust":"0.0 km/h"', '"wind_gust":"9.0 km/h"')) - assert "• Wind: 0.0 km/h from 131°, gust 9.0 km/h" in gusty - assert "Sun" not in report.weather_now(NOW) and "Wind" not in report.weather_now(NOW) - - -def test_every_emoji_threshold_the_station_reports_shows_in_the_report_at_its_reading(): - from lib.ecowitt.glance import glance - now = ('{"outdoor":{"temperature":"36.0 ℃","humidity":"90 %","dew_point":"18.0 ℃","vpd":"1.300 kPa"},"indoor":{"temperature":"29.0 ℃","humidity":"20 %"},' - '"pressure":{"relative":"1030.0 hPa"},"rainfall":{"rain_rate":"2.0 mm/hr","daily":"3.0 mm","monthly":"9.0 mm"},' - '"solar_and_uvi":{"solar":"800.0 W/m²","uvi":"10"},"wind":{"wind_speed":"55.0 km/h","wind_gust":"70.0 km/h","wind_direction":"90 º"}}') - import json - data = json.loads(now) - data["emoji"] = {f"{g}.{f}": e for g, fields in data.items() for f, v in fields.items() - if (e := glance(g, f, float(v.split()[0])))} - got = report.weather_now(json.dumps(data)) - assert got.splitlines() == [ - "• Outdoor: 🔥 36.0 °C, 💦 90 %", - "• Indoor: 🥵 29.0 °C, 🏜️ 20 %", - "• Pressure: 🗜️ 1030.0 hPa", - "• Rain today: ☔ 3.0 mm (month total 9.0 mm); 🌧️ raining (2.0 mm/h)", - "• Sun: ☀️ solar radiation 800.0 W/m² (high), 🧴 UV index 10", - "• Wind: 🌪️ 55.0 km/h from 90°, gust 🌪️ 70.0 km/h"] - - -def test_solar_radiation_is_rated_low_medium_or_high(): - from lib.ecowitt.glance import solar_band - assert [solar_band(v) for v in (0.1, 40.2, 199.9, 200, 599.9, 600, 1000)] == ["low", "low", "low", "medium", "medium", "high", "high"] - - def sun(solar): - return report.weather_now('{"solar_and_uvi":{"solar":"%s","uvi":"0"},"emoji":{}}' % solar) - assert sun("40.2 W/m²") == "• Sun: solar radiation 40.2 W/m² (low)" - assert sun("350.0 W/m²") == "• Sun: solar radiation 350.0 W/m² (medium)" - assert sun("0.0 W/m²") == "" # zero is left out, so there is no Sun line - assert sun("n/a") == "• Sun: solar radiation n/a" # unreadable: shown as it came, with no rating - - -# ---------- chart captions ---------- -def _turn(**kw): - from types import SimpleNamespace as NS - from lib.specs import Bars, Chart, Panel - bars = Bars("Rain", "mm", [1759000000, 1759086400, 1759172800], [0.0, 7.2, 1.4], 86400, "day") - return NS(charts=[Chart("Rain", "", [Panel("Rain", "mm", bars=bars)])], chart_fields=[], chart_field=None, average_asked=False, **kw) - - -def test_a_weather_chart_caption_gives_the_period_then_low_and_high_per_series(): - from zoneinfo import ZoneInfo - result = json.dumps({"period": "Tue 29 Sep 2026 - Tue 06 Oct 2026", "series": { - "outdoor.temperature": {"unit": "℃", "low": "8.1", "low_when": "at 5:30am", "low_date": "Wed 30 Sep 2026", - "high": "24.3", "high_when": "around 3pm", "high_date": "Sat 3 Oct 2026"}, - "indoor.temperature": {"unit": "℃", "low": "18.0", "low_when": "at 6am", "low_date": "Wed 30 Sep 2026", - "high": "22.5", "high_when": "at 4pm", "high_date": "Sat 3 Oct 2026"}}}) - caption = report.chart_caption("weather_history", {}, result, _turn(), ZoneInfo("Australia/Melbourne")) - assert caption.splitlines() == ["Tue 29 Sep – Tue 06 Oct 2026", - "Temperature (outdoor): low 8.1 °C, Wed 30 Sep at 5:30am · high 24.3 °C, Sat 3 Oct around 3pm", - "Temperature (indoor): low 18.0 °C, Wed 30 Sep at 6am · high 22.5 °C, Sat 3 Oct at 4pm"] - - -def test_an_average_chart_caption_leads_with_the_average(): - from zoneinfo import ZoneInfo - turn = _turn() - turn.average_asked = True - result = json.dumps({"period": "Tue 29 Sep 2026 - Tue 06 Oct 2026", "series": { - "outdoor.temperature": {"unit": "℃", "low": "8.1", "high": "24.3", "average": "15.2"}}}) - assert report.chart_caption("weather_history", {}, result, turn, ZoneInfo("UTC")).splitlines()[1] == \ - "Temperature: average 15.2 °C (low 8.1, high 24.3)" - - -def test_a_rain_chart_caption_is_the_least_and_most_rain(): - from zoneinfo import ZoneInfo - turn = _turn() - turn.chart_fields = ["rain"] - result = json.dumps({"period": "Tue 29 Sep 2026 - Tue 06 Oct 2026", "series": {"rainfall.daily": {"unit": "mm", "low": "0", "high": "7.2"}}}) - lines = report.chart_caption("weather_history", {}, result, turn, ZoneInfo("UTC")).splitlines() - assert lines[1].startswith("☔ Rain per day: least 0 mm (") and "most 7.2 mm (" in lines[1] and "8.6 mm in all" in lines[1] - assert len(lines) == 2 - - -def test_an_air_chart_caption_gives_each_metrics_peak_rating_and_average(): - from zoneinfo import ZoneInfo - result = json.dumps({"period": "Tue 29 Sep 2026 - Tue 06 Oct 2026", "pm2_5": { - "unit": "µg/m³", "high": 34.2, "high_time": "Wed 30 Sep 2026 3:00pm", "high_rating": "🟠 Poor", "average": 8.1}, - "pm10": {"unit": "µg/m³", "high": 50, "high_time": "x", "average": 9}}) - caption = report.chart_caption("air_quality", {"metrics": ["pm2_5"]}, result, _turn(), ZoneInfo("UTC")) - assert caption.splitlines()[1] == "• PM2.5: peak 34.2 µg/m³ (Wed 30 Sep 3:00pm) · 🟠 Poor · average 8.1" - assert len(caption.splitlines()) == 2 - - -def test_no_caption_when_the_tool_failed_or_drew_nothing(): - from zoneinfo import ZoneInfo - from types import SimpleNamespace as NS - assert report.chart_caption("weather_history", {}, json.dumps({"error": "x"}), _turn(), ZoneInfo("UTC")) is None - assert report.chart_caption("weather_history", {}, json.dumps({"series": {}}), NS(charts=[]), ZoneInfo("UTC")) is None - - -# ---------- plain lookups ---------- -def test_a_reading_lookup_prints_only_what_was_asked(): - now = json.loads(NOW) - assert report.reading_lines(now, ["temperature"], ["outdoor", "indoor"]) == [ - "• Outdoor: 🧥 12.3 °C, feels like 12.3 °C", "• Indoor: 🧥 18.3 °C, feels like 18.3 °C"] - assert report.reading_lines(now, ["humidity"], ["outdoor"]) == ["• Outdoor: 💦 94 %"] - assert report.reading_lines(now, ["wind"], []) == ["• Wind: calm"] - assert report.reading_lines(now, ["pressure"], []) == ["• Pressure: 🗜️ 1025.0 hPa"] - assert report.reading_lines(now, ["dew_point"], ["indoor"]) == ["• Dew point (indoor): 11.1 °C"] # "indoor dew point" - assert report.reading_lines(now, ["feels_like"], ["outdoor", "indoor"])[0].startswith("• Feels like: ") # unasked: outdoor - assert report.reading_lines(now, ["rain"], [])[0].startswith("• Rain today: ☔ 6.3 mm") and "raining (1.8 mm/h)" in report.reading_lines(now, ["rain"], [])[0] - windy = json.loads(NOW.replace('"wind_speed":"0.0 km/h"', '"wind_speed":"14.0 km/h"')) - assert [line for line in report.weather_lines(windy) if line.startswith(("• Wind", "• Rain"))] == \ - report.reading_lines(windy, ["rain", "wind"], []) # the same words as the report's - - -def test_air_pollen_and_forecast_lookups_print_the_tools_own_lines(): - assert report.lookup("air", AIR, ["pm10"], [], TODAY) == "• PM10: 3.0 µg/m³ 🟢 good" - assert report.lookup("air", AIR, [], [], TODAY).splitlines()[0] == "• PM2.5: 1.4 µg/m³ 🟢 good (AQI 8)" - assert report.lookup("pollen", POLLEN, [], [], TODAY) == "Pollen & asthma (Melbourne, 6:00pm)\n• Grass pollen forecast: 🟢 Low\n• Thunderstorm asthma forecast: 🟢 Low" - assert report.lookup("forecast", FORECAST, [], [], TODAY).startswith("Forecast (Melbourne, 6:05pm)\n• Today: ") - assert report.lookup("pollen", json.dumps({"error": "off season"}), [], [], TODAY) is None - - -def test_a_short_period_highs_and_lows_lookup_gives_each_sides_extremes_with_their_times(): - result = json.dumps({"period": "Fri 02 Oct 2026 - Fri 02 Oct 2026", "series": { - "outdoor.temperature": {"unit": "℃", "low": "9.0", "low_when": "at 5am", "low_date": "Fri 2 Oct 2026", - "high": "16.2", "high_when": "at 2pm", "high_date": "Fri 2 Oct 2026"}, - "outdoor.humidity": {"unit": "%", "low": "40", "high": "95"}}}) - assert report.lookup("extremes", result, [], [], TODAY) == ("Fri 02 Oct – Fri 02 Oct 2026\n" - "• Temperature: low 9.0 °C, Fri 2 Oct at 5am · high 16.2 °C, Fri 2 Oct at 2pm") - - -def test_an_average_or_highs_lookup_covers_the_readings_named(): - result = json.dumps({"period": "Thu 01 Oct 2026 - Thu 01 Oct 2026", "series": { - "outdoor.temperature": {"unit": "℃", "low": "9.0", "high": "16.2", "average": "12.4"}, - "outdoor.humidity": {"unit": "%", "low": "40", "high": "95", "low_when": "at 3pm", "low_date": "Thu 1 Oct 2026", "high_when": "at 5am", "high_date": "Thu 1 Oct 2026"}, - "wind.wind_speed": {"unit": "km/h", "low": "0", "high": "14"}, "wind.wind_gust": {"unit": "km/h", "low": "0", "high": "31", "high_when": "at 2pm", "high_date": "Thu 1 Oct 2026"}}}) - assert report.lookup("extremes", result, ["temperature"], [], TODAY).splitlines()[1] == "• Temperature: average 12.4 °C (low 9.0, high 16.2)" - assert report.lookup("extremes", result, ["humidity"], [], TODAY).splitlines()[1] == "• Humidity: low 40 %, Thu 1 Oct at 3pm · high 95 %, Thu 1 Oct at 5am" - assert [line.split(":")[0] for line in report.lookup("extremes", result, ["wind"], [], TODAY).splitlines()[1:]] == ["• Wind", "• Wind gust"] - - -def test_a_days_count_lookup_gives_the_count_the_condition_and_the_period(): - result = json.dumps({"period": "Wed 5 Oct 2022 - Sat 3 Oct 2026", "days_checked": 1454, "matching_days": 137, "condition": "UV index ≥ 10"}) - assert report.lookup("days", result, [], [], TODAY) == "137 of 1,454 days with UV index ≥ 10 (Wed 5 Oct 2022 – Sat 3 Oct 2026)." - averaged = json.dumps({"period": "a - b", "days_checked": 10, "matching_days": 2, "note_averaged": "x"}) - assert "may fall slightly short" in report.lookup("days", averaged, [], [], TODAY) - assert report.lookup("days", json.dumps({"error": "bad"}), [], [], TODAY) is None - - -def test_a_figure_per_period_lookup_gives_the_figure_over_the_whole_period(): - result = json.dumps({"period": "Fri 4 Oct 2024 - Sat 3 Oct 2026", "days_checked": 731, "matching_days": 731, - "stat": {"what": "Total rain", "of": "rain", "unit": "mm"}, "value": 1234.5, "by_month": {"2024-10": 0.0}}) - assert report.lookup("days", result, [], [], TODAY) == "Total rain: 1234.5 mm over 731 days (Fri 4 Oct 2024 – Sat 3 Oct 2026)." - hot = json.dumps({"period": "a 2025 - b 2026", "days_checked": 3, "matching_days": 3, "stat": {"what": "Highest temperature", "of": "temp_max", "unit": "℃"}, "value": 41.2}) - assert report.lookup("days", hot, [], [], TODAY).startswith("Highest temperature: 41.2 °C over 3 days") - - -def test_a_heading_carries_the_place_and_the_time_of_day_of_its_data(): - assert report._heading("Forecast", {"place": "Melbourne", "time": "Fri 2 Oct 2026 6:05pm"}, TODAY) == "Forecast (Melbourne, 6:05pm)" - assert report._heading("Weather station", {"time": "Fri 2 Oct 2026 12:07am"}, TODAY) == "Weather station (12:07am)" - assert report._heading("Weather station", {"time": "Fri 2 Oct 2026 1:30pm"}, TODAY) == "Weather station (1:30pm)" - assert report._heading("Air quality", {"time": "Fri 2 Oct 2026 12:00pm"}, TODAY) == "Air quality (12:00pm)" - assert report._heading("Forecast", {"place": "Melbourne"}, TODAY) == "Forecast (Melbourne)" # no time: as before - assert report._heading("Air quality", {"time": "yesterday"}, TODAY) == "Air quality" and report._heading("Air quality", {"time": None}, TODAY) == "Air quality" - - -def test_a_heading_gives_the_day_of_data_that_is_not_todays(): - stale = report.report({"weather_now": NOW, "pollen_asthma": POLLEN}, date(2026, 10, 4)) # the station has been silent since Friday - assert stale.startswith("Weather station (Fri 2 Oct 2:21am)\n") and "\nPollen & asthma (Melbourne, Fri 2 Oct 6:00pm)\n" in stale - assert report.lookup("forecast", FORECAST, [], [], date(2026, 10, 3)).startswith("Forecast (Melbourne, Fri 2 Oct 6:05pm)\n") - assert [e.length for e in report.heading_entities(stale)] == [len("Weather station"), len("Pollen & asthma")] # still bold - - -def test_when_gives_the_form_the_tools_use_in_their_time_field(): - from datetime import datetime - from lib.timeutil import when - tz = ZoneInfo("Australia/Melbourne") - assert when(int(datetime(2026, 10, 2, 18, 5, tzinfo=tz).timestamp()), tz) == "Fri 2 Oct 2026 6:05pm" - assert when(int(datetime(2026, 10, 2, 0, 7, tzinfo=tz).timestamp()), tz) == "Fri 2 Oct 2026 12:07am" - - -from zoneinfo import ZoneInfo # noqa: E402 - - -def test_only_the_name_of_each_heading_is_bold_not_its_brackets_or_time(): - text = report.report({"weather_now": NOW, "air_quality": AIR, "pollen_asthma": POLLEN, "weather_forecast": FORECAST}, TODAY) - units = lambda s: len(s.encode("utf-16-le")) // 2 - names = [text.encode("utf-16-le")[2 * e.offset:2 * (e.offset + e.length)].decode("utf-16-le") for e in report.heading_entities(text)] - assert names == ["Weather station", "Air quality", "Pollen & asthma", "Forecast"] - assert all(e.type == "bold" for e in report.heading_entities(text)) - after_emoji = report.heading_entities("• Rain today: ☔ 6.3 mm 🌧️\nForecast (Melbourne, 6:05pm)\n• Today") # emoji count as two units - assert [(e.offset, e.length) for e in after_emoji] == [(units("• Rain today: ☔ 6.3 mm 🌧️\n"), len("Forecast"))] - assert report.heading_entities("Forecast\n• x") and report.heading_entities("• Forecast: sunny\nForecasts") == [] diff --git a/tests/test_service_about.py b/tests/test_service_about.py new file mode 100644 index 00000000..52c82d94 --- /dev/null +++ b/tests/test_service_about.py @@ -0,0 +1,166 @@ +"""The `about` tool (lib/service/about.py): what the service measures and doesn't, how far back each kind of history goes, the alerts +there are with their thresholds; the lists the bot's prompt and Help had, the same.""" + +import json +import time +from datetime import timedelta +from types import SimpleNamespace as NS + +from lib import templates +from lib.airgradient import AirGradient +from lib.alerts import forecast as forecast_alert, menu, particulates, weather +from lib.ecowitt.glance import UVI_ALERT +from lib.service import about as ab +from lib.service.about import AboutTool +from lib.service.common import request_meta +from lib.service.context import Context +from lib.service.names import AIR_DEVICE, STATION +from lib.storage.catalogue import BOT +from lib.storage.coverage import merge +from lib.timeutil import day_bounds, day_text, local_date +from tests.fakes import TZ, air_transport, archived_station, config + +EVERY = ["Ecowitt", "AirGradient", "Pollen", "Forecast"] + + +async def call(ctx: Context, args=None) -> dict: + return json.loads(await AboutTool(ctx).tool().call(args or {})) + + +async def world(tmp_path, archived_cache, *, air=True, others=True): + """A Context over the archived station, the fake air sensor's cloud beside it in the same file, and (others) stand-ins for the + forecast and the pollen sources (about only asks whether they are there).""" + eco, _ = await archived_station(tmp_path, archived_cache) + sensor = None + if air: + transport, _ = air_transport() + sensor = AirGradient(config(tmp_path), transport=transport, storage=eco.storage, owned=False) + return await Context.open(eco=eco, air=sensor, forecast=NS() if others else None, pollen=NS() if others else None) + + +async def close(ctx: Context): + if ctx.air: + await ctx.air.close() + await ctx.eco.close() + + +# ---------- the tool ---------- +def test_the_description_says_what_it_answers_and_that_alerts_cant_be_added_by_asking(): + d = ab.DESCRIPTION + assert len(d) < 1500 + for said in ("what can you do", "lightning", "how far back", "what alerts are there", "{} (no arguments)", + "can't be added or changed by asking", "current (now)", "summary (a period)", "history", "alerts_note", "lines"): + assert said in d, said + (tool,) = ab.tools(Context()) + assert tool.name == "about" and tool.parameters == {"type": "object", "properties": {}} + assert tool.annotations == {"readOnlyHint": True, "openWorldHint": False} + + +async def test_arguments_are_refused_with_how_to_call_it(): + got = json.loads(await AboutTool(Context()).tool().call({"topic": "alerts"})) + assert got == {"error": "about takes no arguments, not 'topic': call it with {}.", "arguments": []} + + +def test_the_lists_are_the_ones_the_bots_prompt_menu_and_help_had(): + assert "lightning" in ab.NEVER_AVAILABLE and set(ab.WITHOUT) == {"Pollen", "Forecast"} and "gusts" in ab.ALERT_WORDS # (the old prompt's lists, kept here) + assert ab.TYPES == {kind: v for kind, v in menu.TYPES.items() if v[1] != "Irrigation"} # (irrigation: a server of its own) + assert ab.MEASURES == templates.MEASURES + for sources in (EVERY, ["Ecowitt"], ["AirGradient", "Pollen"], []): + assert "\n".join(ab.measure_lines(sources)) == templates.capabilities_text(sources) # the Help list, word for word + + +# ---------- what it measures ---------- +async def test_what_it_measures_and_doesnt_for_the_sources_there_are(tmp_path, archived_cache): + ctx = await world(tmp_path, archived_cache) + got = await call(ctx) + assert "period" not in got and "as_of" not in got and "fresh" not in got # no figures of the weather, nothing to call again + m = got["measures"] + assert list(m) == [STATION, AIR_DEVICE, "forecast", "pollen"] + assert m[STATION]["text"].startswith("Weather station (Ecowitt): outdoor and indoor temperature") + assert m[STATION]["readings"]["outdoor.temperature"] == "Outdoor temperature (°C)" and m[AIR_DEVICE]["readings"]["air.voc_index"] == "VOC index" + assert set(m[STATION]["readings"]) | set(m[AIR_DEVICE]["readings"]) == set(ctx.readings().names) # the readings the file holds + assert got["not_available"] == ab.NEVER_AVAILABLE + assert list(got["tools"]) == ["current", "summary", "readings", "days", "relate", "scan", "outlook", "forecast", "pollen"] + assert [a["kind"] for a in got["alerts"]] == list(ab.TYPES) + assert got["lines"] == templates.capabilities_text(EVERY).splitlines() + assert json.loads(await AboutTool(ctx).tool().call({}, request_meta({"fetch": False}))) == got # (it reads only what is held) + await close(ctx) + + (tmp_path / "alone").mkdir() + alone = await world(tmp_path / "alone", archived_cache, air=False, others=False) + got = await call(alone) + assert list(got["measures"]) == [STATION] + assert got["not_available"] == [*ab.NEVER_AVAILABLE, *ab.WITHOUT.values(), "air quality"] + assert [a["kind"] for a in got["alerts"]] == ["rain", "gusts", "uv", "temps"] # the station's alerts alone + assert "scan" not in got["tools"] and "forecast" not in got["tools"] and "outlook" in got["tools"] + await close(alone) + + +# ---------- the alerts ---------- +def test_each_alert_has_its_rule_and_the_thresholds_the_rules_use(monkeypatch): + rules = {a["kind"]: a for a in ab.alerts(EVERY)} + assert rules["gusts"]["thresholds"]["gust_kmh"] == weather.GUST_ALERT_KMH and "over 40 km/h" in rules["gusts"]["rule"] + assert rules["uv"]["thresholds"] == {"uv_index": UVI_ALERT, "readings_in_a_row": 2, "rearm_minutes": weather.UV_REARM_SECONDS // 60} + assert rules["temps"]["thresholds"]["margin_c"] == weather.CROSS_MARGIN + p = rules["particulates"]["thresholds"] + assert (p["mask_pm2_5"], p["mask_pm10"], p["safe_pm2_5"], p["safe_pm10"]) == (particulates.MASK_PM25, particulates.MASK_PM10, + particulates.SAFE_PM25, particulates.SAFE_PM10) + assert "55.5 µg/m³" in rules["particulates"]["rule"] and "AQI 151" in rules["particulates"]["rule"] + assert rules["forecast"]["thresholds"]["max_change_c"] == forecast_alert.TEMP_CHANGE_C + assert rules["pollen_and_asthma"]["thresholds"] == {"from_level": "High"} and "from 7:30am" in rules["pollen_and_asthma"]["rule"] + assert rules["rain"]["thresholds"] == {"dry_minutes": 60, "quiet_hours": "00:00-06:00"} + assert rules["rain"]["rule"].endswith("None from 12am to 6am: one summary of the rain in those hours after them.") + assert all(a["what"] == ab.ALERT_WORDS[a["kind"]] and a["name"] == menu.LABELS[a["kind"]] for a in rules.values()) + monkeypatch.setattr(ab, "RAIN_QUIET_HOURS", None) # ecobot-mcp's settings, as the config sets them + monkeypatch.setattr(ab, "ALERT_COOLDOWN_MINUTES", 90) + rules = {a["kind"]: a for a in ab.alerts(EVERY)} + assert rules["rain"]["thresholds"] == {"dry_minutes": 90, "quiet_hours": None} and "None from" not in rules["rain"]["rule"] + assert "at most one every 90 minutes" in rules["temps"]["rule"] + assert "can't be added or changed by asking" in ab.ALERTS_NOTE + + +# ---------- how far back ---------- +async def test_the_history_is_what_the_file_holds_at_each_resolution(tmp_path, archived_cache): + ctx = await world(tmp_path, archived_cache) + eco, air = ctx.eco, ctx.air + now = time.time() + minutes = {"outdoor": {"temperature": {"unit": "℃", "list": {str(int(now) // 60 * 60 - 60 * k): "12.3" for k in range(5)}}}} + await eco.storage.write(lambda w: w.put_minutes(eco.mac, minutes, now)) + day = local_date(int(now), TZ) - timedelta(days=3) + start = day_bounds(day, TZ)[0] + await air.store.save_day(day, [{"ts": start + 300 * k, "pm2_5": 5.0} for k in range(288)]) # a day at 5 minutes + older = day - timedelta(days=200) + await air.store.save_day(older, [{"ts": day_bounds(older, TZ)[0] + 3600 * k, "pm2_5": 5.0} for k in range(24)]) # one of hourly averages + await air.store.add_minutes([{"ts": int(now) // 60 * 60, "pm2_5": 4.0}], BOT, now) + got = (await call(ctx))["history"] + + station = got[STATION] + sensors = list(eco.storage.station(eco.mac).values()) + for res in ("5min", "30min", "4hour", "1day"): + spans = merge([s for sensor in sensors for s in eco.storage.coverage.of(sensor.id, res)]) + assert station["held"][res] == {"from": local_date(spans[0][0], TZ).isoformat(), "to": local_date(spans[-1][1], TZ).isoformat(), + "days": sum(e - s + 1 for s, e in spans) // 86400}, res + first_5min = local_date(merge([s for sensor in sensors for s in eco.storage.coverage.of(sensor.id, "5min")])[0][0], TZ) + minute = local_date(int(now) // 60 * 60 - 240, TZ) + assert station["held"]["1min"]["from"] == minute.isoformat() + assert station["text"].startswith(f"Weather station: minute readings from {day_text(minute)} (kept 10 days), 5-minute readings from " + f"{day_text(first_5min)}, 30-minute readings from ") + assert "daily records from " in station["text"] and ", each 10am to 10am" in station["text"] + + sky = got[AIR_DEVICE] + assert sky["held"]["5min"] == {"from": day.isoformat(), "to": day.isoformat(), "days": (day_bounds(day, TZ)[1] - start) // 86400} + assert sky["held"]["1hour"]["from"] == older.isoformat() and "1min" in sky["held"] + today = local_date(int(now) // 60 * 60, TZ) + assert sky["text"] == (f"Air sensor: minute readings from {day_text(today)} (kept 10 days), 5-minute readings from {day_text(day)}, " + f"hourly averages from {day_text(older)}. The tools use the finest held for each part of a period.") + await close(ctx) + + +async def test_a_sensor_with_nothing_held_says_so(tmp_path, archived_cache): + ctx = await world(tmp_path, archived_cache) + assert (await call(ctx))["history"][AIR_DEVICE] == {"text": "Air sensor: nothing held yet.", "held": {}} + await close(ctx) + + +def test_the_module_says_what_it_offers(): + assert all(hasattr(ab, name) for name in ab.__all__) diff --git a/tests/test_service_base.py b/tests/test_service_base.py new file mode 100644 index 00000000..ccfb2514 --- /dev/null +++ b/tests/test_service_base.py @@ -0,0 +1,452 @@ +"""What the service's tools stand on (lib/service): the request's metadata, answers and refusals, periods read from words, the chart +budget, the reading names and the words for them, and a day's look.""" + +import json +from datetime import date, datetime + +import pytest + +from lib.periods_text import PeriodError +from lib.service import common, daylook, names +from lib.service.common import (CHART_NOTE, FRESH, Refusal, ServiceTool, answer, charts_field, period_properties, read_period, refuse, + refuse_period, request_meta, with_charts) +from lib.service.daylook import LOOKS, clear_sky_mean, day_look +from lib.service.names import CATALOGUE, Catalogue, UnknownReading, resolve +from lib.specs import Chart, Line, Panel, from_json +from lib.storage import Storage +from lib.storage.catalogue import CLOUD +from lib.tools import Tools, Turn +from tests.fakes import TZ + +NOW = datetime(2026, 11, 10, 14, 5, tzinfo=TZ) # Tue 10 Nov 2026 2:05pm, as the plan's periods table is asked +MELBOURNE = -37.8 + + +def got(text: str) -> dict: + return json.loads(text) + + +def named(*words, default="temperature", catalogue: Catalogue | None = None) -> list[str]: + return [r.name for r in resolve(list(words), default=default, catalogue=catalogue)] + + +# ---------- the request's metadata ---------- +def test_the_metadata_a_handler_reads_has_its_defaults_and_is_checked(): + assert request_meta() == request_meta({}) == {"chart_points": 150, "fetch": True, "priority": "normal"} + assert request_meta({"chart_points": 500})["chart_points"] == 500 and request_meta({"chart_points": 10000})["chart_points"] == 500 + assert request_meta({"chart_points": 1})["chart_points"] == 2 and request_meta({"chart_points": "300"})["chart_points"] == 300 + assert request_meta({"chart_points": "lots"})["chart_points"] == request_meta({"chart_points": True})["chart_points"] == 150 + assert request_meta({"fetch": False})["fetch"] is False and request_meta({"fetch": "false"})["fetch"] is False + assert request_meta({"fetch": None})["fetch"] is True and request_meta({"fetch": True})["fetch"] is True + assert request_meta({"priority": "Background"})["priority"] == "background" and request_meta({"priority": "soon"})["priority"] == "normal" + assert request_meta({"progressToken": 7})["progressToken"] == 7 # what it doesn't read is passed on as it came + + +def test_a_turn_carries_its_own_metadata(): + a, b = Turn(), Turn() + a.meta["fetch"] = False + assert b.meta == {} + + +async def test_a_service_tool_is_sent_its_arguments_and_the_requests_metadata_and_nothing_else(): + seen = [] + + async def handler(args, meta): + seen.append((args, meta)) + return answer(period=None, as_of=None, ok=True) + tool = ServiceTool("probe", "A probe.", {"type": "object", "properties": {}}, handler, open_world=True) + assert tool.annotations == {"readOnlyHint": True, "openWorldHint": True} + tools = Tools([tool.tool()]) + assert got(await tools.call("probe", '{"x": 1}', Turn(chart_asked=True, meta={"chart_points": 500}))) == {"ok": True} + assert seen[-1] == ({"x": 1}, {"chart_points": 500, "fetch": True, "priority": "normal"}) # the Turn's words never reach it + await tools.call("probe", "{}", Turn(ahead=True)) # a chart drawn ahead is a background request + assert seen[-1][1]["priority"] == "background" + await tools.call("probe", "{}", Turn(ahead=True, meta={"priority": "normal"})) # (the request's own metadata wins) + assert seen[-1][1]["priority"] == "normal" + await tools.call("probe", "{}") + assert seen[-1] == ({}, {"chart_points": 150, "fetch": True, "priority": "normal"}) + assert tools.schemas[0]["function"]["parameters"] == {"type": "object", "properties": {}} # (no `source` argument: charts name theirs) + + +async def test_a_refusal_raised_in_a_handler_is_the_tools_answer_and_a_plain_function_will_do(): + def handler(args, meta): + if "reading" not in args: + raise Refusal("Which reading?", names=["outdoor.temperature"]) + return refuse("not yet") + tool = ServiceTool("probe", "A probe.", {"type": "object", "properties": {}}, handler) + assert got(await tool.call({})) == {"error": "Which reading?", "names": ["outdoor.temperature"]} + assert got(await tool.call({"reading": "x"})) == {"error": "not yet"} + assert "error" in got(await tool.call(["not", "an", "object"])) + assert tool.annotations == {"readOnlyHint": True, "openWorldHint": False} + + +# ---------- answers and refusals ---------- +def test_an_answer_starts_with_its_period_and_the_time_of_its_figures(): + period = read_period({"period": "this week"}, tz=TZ, now=NOW, default="today") + out = got(answer(period=period, as_of=NOW, series={"outdoor.temperature": {}}, missing=[])) + assert list(out) == ["period", "as_of", "fresh", "series", "missing"] + assert out["period"] == {"asked": "this week", "text": "the last 7 days: Wed 4 – Tue 10 Nov 2026", + "start": "2026-11-04T00:00:00+11:00", "end": "2026-11-10T14:05:00+11:00"} + assert out["as_of"] == {"text": "Tue 10 Nov 2026 2:05pm", "time": "2026-11-10T14:05:00+11:00"} + assert out["fresh"] == FRESH and "as_of" in FRESH and "called again" in FRESH + cut = got(answer(period=read_period({"period": "this week"}, tz=TZ, now=NOW, default="on record", whole_days=True), as_of=NOW)) + assert cut["period"]["cut"] == "to Mon 9 Nov: today isn't over" and cut["period"]["end"] == "2026-11-10T00:00:00+11:00" + assert got(answer(period=None, as_of=None, verdict="likely")) == {"verdict": "likely"} # no period (outlook), no figures (about) + assert "°" in answer(period=None, as_of=None, unit="°C") and " " not in answer(period=None, as_of=None, a=1, b=2) # compact, unescaped + finished = got(answer(period=None, as_of=NOW, series={}, **common.complete("Pressure, the last 7 days: …"))) + assert list(finished)[-2:] == ["reply", "complete"] and finished["complete"] is True # a chart that is the whole answer (3.7) + assert common.iso(int(NOW.timestamp()), TZ) == common.iso(NOW) == "2026-11-10T14:05:00+11:00" + with pytest.raises(ValueError): + answer(period=None, as_of=NOW, fresh="mine") + with pytest.raises(ValueError): + answer(period=None, as_of=datetime(2026, 11, 10, 14, 5)) # a time without its zone can't be written + + +def test_a_refusal_is_its_error_and_what_teaches_the_right_call(): + assert got(refuse("too many rows", fits="1hour", max_rows=300)) == {"error": "too many rows", "fits": "1hour", "max_rows": 300} + assert list(got(refuse("x", a=1))) == ["error", "a"] + with pytest.raises(ValueError): + refuse("x", error="y") + plain = got(refuse_period(PeriodError("Not now."))) + assert plain == {"error": "Not now."} + + +# ---------- periods ---------- +def test_a_period_is_read_from_the_words_or_dates_or_else_the_default(): + assert read_period({}, tz=TZ, now=NOW, default="last 24 hours").text == "the last 24 hours: Mon 9 Nov 2:05pm – Tue 10 Nov 2026 2:05pm" + assert read_period({"period": " "}, tz=TZ, now=NOW, default="today").asked == "today" + assert read_period({"period": "in the last year"}, tz=TZ, now=NOW, default="today").text == \ + "the last 365 days: Tue 11 Nov 2025 – Tue 10 Nov 2026" + dated = read_period({"start": "2026-11-01", "end": "2026-11-02"}, tz=TZ, now=NOW, default="today") + assert dated.asked == "start/end" and (dated.start.day, dated.end.day) == (1, 3) + first = read_period({"period": "on record"}, tz=TZ, now=NOW, default="today", first_held=date(2024, 3, 1)) + assert first.start.date() == date(2024, 3, 1) + + +def test_words_that_are_no_form_are_refused_with_every_form_and_what_it_means_now(): + with pytest.raises(Refusal) as e: + read_period({"period": "the other week"}, tz=TZ, now=NOW, default="today") + out = got(e.value.text) + assert "'the other week' isn't a period" in out["error"] and out["error"].endswith("It is now Tue 10 Nov 2026 2:05pm.") + assert out["forms"]["today"] == "today: Tue 10 Nov 2026" + assert out["forms"]["this week, past week, the last week, week, 1w"] == "the last 7 days: Wed 4 – Tue 10 Nov 2026" + assert "since 6am, since Monday" in out["forms"] + with pytest.raises(Refusal) as e: + read_period({"period": "next week"}, tz=TZ, now=NOW, default="today") + assert "use forecast" in e.value.message and "forms" not in got(e.value.text) + + +def test_a_period_sent_beside_start_and_end_that_are_junk_or_the_same_span_is_read_with_a_note(): + # a model may fill in every argument it sees: the live evals' uv-days-two-years sent period with start 'count_only', end 'cancel', + # and most-rain-days-jja 'June to August 2026' with start 2026-06-01, end 2026-08-31 (the same span) + for dates in ({"start": "count_only", "end": "cancel"}, {"start": "count_only"}, {"start": "2026-11-04", "end": "cancel"}): + read = read_period({"period": "this week", **dates}, tz=TZ, now=NOW, default="today") + assert read.text == "the last 7 days: Wed 4 – Tue 10 Nov 2026" and read.note == common.IGNORED_DATES, dates + assert common.period_field(read)["note"] == common.IGNORED_DATES + for dates in ({"start": "2026-11-04"}, {"start": "2026-11-04", "end": "2026-11-10"}, {"start": "2026-11-04 00:10"}): + read = read_period({"period": "this week", **dates}, tz=TZ, now=NOW, default="today") + assert read.asked == "this week" and read.note == common.SAME_DATES, dates + jja = read_period({"period": "June to August 2026", "start": "2026-06-01", "end": "2026-08-31"}, tz=TZ, now=NOW, + default="on record", whole_days=True) + assert jja.text == "June 2026 to August 2026: Mon 1 Jun – Mon 31 Aug 2026" and jja.note == common.SAME_DATES + held = read_period({"period": "on record", "start": "2020-01-01"}, tz=TZ, now=NOW, default="on record", whole_days=True, + first_held=date(2022, 10, 1)) # before the first reading held: the same span as on record + assert held.note == common.SAME_DATES + alone = read_period({"period": "this week", "start": "", "end": None}, tz=TZ, now=NOW, default="today") + assert alone.note is None and "note" not in common.period_field(alone) + + +def test_a_period_and_dates_that_read_as_different_spans_are_refused_naming_both(): + # the live evals' use-five-minute-data sent days {period: "on record", start: "2025-01-01", end: "2026-09-28"} + with pytest.raises(Refusal) as e: + read_period({"period": "on record", "start": "2025-01-01"}, tz=TZ, now=NOW, default="on record", whole_days=True, + first_held=date(2022, 10, 1)) + assert e.value.message == ("`period` 'on record' is Sat 1 Oct 2022 – Mon 9 Nov 2026 but `start`/`end` say Wed 1 Jan 2025 – " + "Mon 9 Nov 2026: send one of them (`period` alone, or `start` and `end` without it).") + with pytest.raises(Refusal) as e: + read_period({"period": "on record", "start": "2025-01-01"}, tz=TZ, now=NOW, default="today", first_held=date(2022, 10, 1)) + assert "is Sat 1 Oct 2022 – Tue 10 Nov 2026 but `start`/`end` say Wed 1 Jan 2025 – now: send one of them" in e.value.message + with pytest.raises(Refusal) as e: + read_period({"period": "this week", "start": "2026-06-01", "end": "2026-08-31"}, tz=TZ, now=NOW, default="today") + assert "`period` 'this week' is Wed 4 – Tue 10 Nov 2026 but `start`/`end` say Mon 1 Jun – Mon 31 Aug 2026" in e.value.message + with pytest.raises(Refusal) as e: # dates this tool can't take (a time, to a whole-day tool): refused too, not set aside + read_period({"period": "on record", "start": "2025-01-01 06:00"}, tz=TZ, now=NOW, default="on record", whole_days=True, + first_held=date(2022, 10, 1)) + assert "can't be read as this tool takes them" in e.value.message and "has a time" in e.value.message + + +def test_a_period_that_cant_be_read_beside_dates_says_the_dates_were_set_aside_and_how_to_use_them(): + with pytest.raises(Refusal) as e: + read_period({"period": "JJA 2026", "start": "2026-06-01", "end": "2026-08-31"}, tz=TZ, now=NOW, default="on record", + whole_days=True) + out = got(e.value.text) + assert "'JJA 2026' isn't a period" in out["error"] and out["error"].endswith(common.SET_ASIDE) and out["forms"] + assert "send them without `period` to use them" in common.SET_ASIDE + with pytest.raises(Refusal) as e: # junk beside it: the plain refusal of the words + read_period({"period": "the other week", "start": "count_only"}, tz=TZ, now=NOW, default="today") + assert "'the other week' isn't a period" in e.value.message and common.SET_ASIDE not in e.value.message + + +def test_a_whole_day_tool_refuses_what_leaves_no_whole_day_and_points_elsewhere(): + for asked in ({"period": "today"}, {"period": "last 5 hours"}, {"period": "this morning"}, {"start": "2026-11-09 06:00"}): + with pytest.raises(Refusal) as e: + read_period(asked, tz=TZ, now=NOW, default="on record", whole_days=True, first_held=date(2024, 1, 1)) + assert "use summary or readings" in e.value.message, asked + with pytest.raises(Refusal) as e: + read_period({"period": "fortnightly"}, tz=TZ, now=NOW, default="on record", whole_days=True) + assert "today" not in got(e.value.text)["forms"] and "yesterday" in got(e.value.text)["forms"] # only the forms it takes + week = read_period({"period": "last 7 days"}, tz=TZ, now=NOW, default="on record", whole_days=True) + assert week.text == "the last 7 days: Tue 3 – Mon 9 Nov 2026" and week.cut == "to Mon 9 Nov: today isn't over" + + +def test_the_period_properties_tell_a_model_the_forms_the_dates_and_the_default(): + props = period_properties("last 24 hours") + assert list(props) == ["period", "start", "end"] and all(p["type"] == "string" for p in props.values()) + words = props["period"]["description"] + for form in ("today", "yesterday", "last N hours/days/weeks/months/years", "this week", "last week", "week to date", "this month", + "last month", "this year", "last year", "a month or a year", "5 Sep", "a weekday", "this morning", + "yesterday afternoon", "last night", "since 6am", "Christmas Day", "on record", "A to B"): + assert form in words, form + assert "own words" in words and "unchanged" in words and words.endswith("Default: last 24 hours.") + assert "'YYYY-MM-DD HH:MM'" in props["start"]["description"] and "never with it" in props["start"]["description"] + assert "Default: now." in props["end"]["description"] + whole = period_properties("on record", whole_days=True) + assert "yesterday" in whole["period"]["description"] and whole["period"]["description"].endswith("Default: on record.") + assert not any(form in whole["period"]["description"] for form in ("today,", "hours", "this morning", "since 6am")) + assert "HH:MM" not in whole["start"]["description"] and "Default: yesterday." in whole["end"]["description"] + + +# ---------- charts ---------- +def a_chart(points: int) -> Chart: + start = int(NOW.timestamp()) - points * 60 + x = [start + 60 * i for i in range(points)] + return Chart("Temperature", "", [Panel("Temperature", "°C", [Line("Outdoor", x, [15 + (i % 50) / 10 for i in range(points)])], + reading="temperature")]) + + +def test_a_chart_is_sent_as_data_within_the_requests_budget(): + chart = a_chart(1200) + lengths = lambda out: [len(s["points"]) for c in out for p in c["panels"] for s in p["series"]] + assert max(lengths(charts_field([chart], TZ))) <= 150 + assert 150 < max(lengths(charts_field([chart], TZ, {"chart_points": 500}))) <= 500 + assert max(lengths(charts_field([chart], TZ, {"chart_points": 5000}))) <= 500 # (at most today's budget) + assert lengths(charts_field([a_chart(40)], TZ)) == [40] # a short line as it is + sent = charts_field([chart], TZ)[0] + assert sent["panels"][0]["series"][0]["records"]["high"][1] == 19.9 # the true extremes stay + assert sent["panels"][0]["series"][0]["points"][0][0].endswith("+11:00") # local times with their offset + from_json(sent) # and it reads back as a chart + assert with_charts([], TZ) == {} + fields = with_charts([chart], TZ) + assert list(fields) == ["chart_note", "charts"] and fields["chart_note"] == CHART_NOTE and len(fields["charts"]) == 1 + assert "draw it" in CHART_NOTE and "describe" in CHART_NOTE + + +# ---------- reading names ---------- +def test_every_word_stands_for_the_readings_it_lists(): + for word, targets in names.ALIASES.items(): + expected = [n for n in (sum((names.BARE[r] for r in names.in_all()), ()) if targets == names.ALL else targets)] + assert named(word) == expected, word + + +def test_the_words_people_use(): + assert named("pressure") == named("barometer") == ["pressure.relative"] + assert named("uv") == named("UV index") == ["solar_and_uvi.uvi"] and named("solar") == ["solar_and_uvi.solar"] + assert named("rain") == ["rainfall.rain"] and named("rain rate") == named("rain_rate") == ["rainfall.rain_rate"] + assert named("gust") == named("gusts") == named("Wind Gusts") == ["wind.wind_gust"] + assert named("dew point") == named("dew_point") == named("dewpoint") == ["outdoor.dew_point"] + assert named("feels like") == named("feels-like") == ["outdoor.feels_like"] and named("vpd") == ["outdoor.vpd"] + for word in ("pm2.5", "pm25", "PM 2.5", "pm2_5", "air.pm2.5", "ag pm2.5"): + assert named(word) == ["air.pm2_5"], word + assert named("pm10") == ["air.pm10"] and named("pm1") == ["air.pm1"] and named("PM1.0") == ["air.pm1"] + assert named("co2") == named("CO₂") == ["air.co2"] and named("voc") == ["air.voc_index"] and named("nox") == ["air.nox_index"] + assert named("outdoor humidity") == named("outside humidity") == named("outdoor.humidity") == ["outdoor.humidity"] + assert named("indoor temp") == named("inside temperature") == ["indoor.temperature"] + assert named("rainfall.daily") == ["rainfall.rain"] and named("air_humidity") == ["air.humidity"] # today's names + + +def test_wind_is_its_speed_shaded_up_to_the_gusts_with_its_direction(): + speed, direction = resolve("wind", default="all") + assert (speed.name, speed.band, speed.drawn) == ("wind.wind_speed", "wind.wind_gust", "line") + assert (direction.name, direction.drawn, direction.combine) == ("wind.wind_direction", "rose", "last") + assert CATALOGUE.get("wind.wind_gust").combine == "max" and CATALOGUE.get("wind.wind_gust").unit == "km/h" + assert Catalogue.of({"wind": {"wind_speed": "km/h"}}, air=False).get("wind.wind_speed").band is None # no gusts held: no band + + +def test_a_bare_temperature_or_humidity_is_the_stations_outdoor_and_indoor_never_the_air_sensors(): + assert named("temperature") == named("temp") == ["outdoor.temperature", "indoor.temperature"] + assert named("humidity") == ["outdoor.humidity", "indoor.humidity"] + assert named("air.temperature") == named("airgradient temperature") == named("ag temp") == named("air.temp") == ["air.temperature"] + assert named("air gradient humidity") == ["air.humidity"] + with pytest.raises(UnknownReading) as e: + resolve("air temperature", default="all") + assert "outdoor.temperature" in e.value.message and "air.temperature" in e.value.message + + +def test_a_sensors_name_is_its_usual_set(): + assert named("outdoor") == ["outdoor.temperature", "outdoor.humidity", "outdoor.dew_point", "outdoor.feels_like"] + assert named("indoor") == named("inside") == ["indoor.temperature", "indoor.humidity"] + assert named("wind") == ["wind.wind_speed", "wind.wind_direction"] + assert named("rainfall") == ["rainfall.rain", "rainfall.rain_rate"] + six = ["air.pm2_5", "air.pm10", "air.pm1", "air.co2", "air.voc_index", "air.nox_index"] + assert named("air") == named("air quality") == six + assert named("ag") == named("airgradient") == named("air gradient") == six # the devices' nicknames + assert named("ecowitt") == named("weather station") == named("all") + + +def test_all_is_every_station_reading_in_the_usual_chart_order_with_the_settings(monkeypatch): + usual = ["outdoor.temperature", "indoor.temperature", "outdoor.humidity", "indoor.humidity", "solar_and_uvi.solar", "pressure.relative", + "rainfall.rain", "outdoor.dew_point", "wind.wind_speed", "wind.wind_direction"] + assert named("all") == usual and not any(n.startswith("air.") for n in named("all")) + monkeypatch.setattr(names, "FEELS_LIKE_IN_ALL", True) + monkeypatch.setattr(names, "VPD_IN_ALL", True) + assert named("all") == [*usual[:8], "outdoor.feels_like", "outdoor.vpd", *usual[8:]] + held = Catalogue.of({"outdoor": {"temperature": "℃"}, "indoor": {"temperature": "℃"}, "pressure": {"relative": "hPa"}, + "wind": {"wind_speed": "km/h"}, "rainfall": {"daily": "mm"}, "rainfall_piezo": {"daily": "mm"}, + "solar_and_uvi": {"uvi": ""}}, air=False) + assert named("weather station", catalogue=held) == ["outdoor.temperature", "indoor.temperature", "pressure.relative", "rainfall.rain", + "wind.wind_speed"] # what is held of it + + +def test_names_come_in_the_order_asked_each_once_and_none_is_the_default(): + assert named("rain, temperature and pressure") == ["rainfall.rain", "outdoor.temperature", "indoor.temperature", "pressure.relative"] + assert named("outdoor.temperature", "temperature") == ["outdoor.temperature", "indoor.temperature"] + assert named(default="outdoor") == [r.name for r in resolve(None, default="outdoor")] == named("outdoor") + assert named() == named("temperature") + assert [r.name for r in resolve("", default=["temperature", "humidity"])] == named("temperature", "humidity") + + +def test_an_unknown_name_is_refused_with_the_names_and_the_words(): + with pytest.raises(UnknownReading) as e: + resolve(["temperature", "sunniness"], default="all") + out = got(e.value.text) + assert "'sunniness' isn't a reading" in out["error"] + assert out["names"] == CATALOGUE.names and "air.temperature" in out["names"] + assert out["words"]["temperature"] == ["outdoor.temperature", "indoor.temperature"] and out["words"]["pm2.5"] == ["air.pm2_5"] + assert isinstance(e.value, Refusal) # (so a tool answers with it) + + +def test_the_catalogue_is_what_the_file_holds(): + station = Catalogue.of({"outdoor": {"temperature": "℃", "humidity": "%"}, "rainfall": {"daily": "mm"}}, air=False) + assert station.names[:3] == ["outdoor.temperature", "outdoor.humidity", "indoor.temperature"] # (indoor sent nothing: all its kind) + assert "outdoor.dew_point" not in station and "air.pm2_5" not in station + assert [r.name for r in station.resolve("rainfall", default="all")] == ["rainfall.rain"] # (no rain rate held) + with pytest.raises(UnknownReading) as e: + station.resolve("pm2.5", default="all") + assert "doesn't hold" in e.value.message + air = Catalogue.of(station=False) + assert all(r.device == "air" for r in air) + with pytest.raises(UnknownReading): + air.resolve("humidity", default="all") # a bare humidity is never the air sensor's + assert "pm2.5" not in names.names_description(station) and "ecowitt" not in names.names_description(air) + + +async def test_the_catalogue_reads_the_stations_fields_from_the_file(tmp_path): + from types import SimpleNamespace + storage = Storage(tmp_path / "ecobot.sqlite", TZ) + try: + def write(w): + sensor = w.ecowitt_sensor("M", "outdoor") + w.fields(sensor, "5min", {"temperature": "℃", "humidity": "%"}) + w.put(sensor, "5min", [{"ts": int(NOW.timestamp()) // 300 * 300, "temperature": 15.0, "humidity": 50.0}], CLOUD) + storage.writer.run(write, ()) + found = await Catalogue.open(SimpleNamespace(storage=storage, mac="M"), None) + assert [n for n in found.names if n.startswith("outdoor.")] == ["outdoor.temperature", "outdoor.humidity"] + assert not any(n.startswith("air.") for n in found.names) + finally: + storage.close() + + +def test_each_reading_says_what_it_is_and_how_it_is_read(): + t = CATALOGUE.get("outdoor.temperature") + assert (t.label, t.unit, t.device, t.kind, t.column, t.combine, t.series, t.sensor, t.reading) == \ + ("Outdoor temperature", "°C", "station", "climate", "temperature", "mean", "temperature", "outdoor", "temperature") + rain = CATALOGUE.get("rainfall.rain") + assert (rain.label, rain.unit, rain.kind, rain.column, rain.combine, rain.drawn, rain.series) == \ + ("Rain", "mm", "rain", "daily", "rain", "bars", "rain") + own = CATALOGUE.get("air.temperature") + assert (own.label, own.unit, own.device, own.column, own.series) == ("AirGradient temperature", "°C", "air", "air_temperature", + "air_temperature") + assert CATALOGUE.get("air.voc_index").unit == "" and CATALOGUE.get("solar_and_uvi.uvi").label == "UV index" + assert CATALOGUE.get("pressure.relative").metric.name == "pressure.relative" # (what lib/history.py reads it with) + assert set(names.BARE) == set(names.ALL_ORDER) and set(names.SENSOR_SETS) <= {*(r.sensor for r in CATALOGUE)} + + +def test_the_names_description_lists_the_names_the_words_and_the_rule_for_bare_names(): + text = names.names_description() + assert all(name in text for name in CATALOGUE.names) + for words in ("temperature and humidity are outdoor and indoor", "only ever air.temperature and air.humidity", "pressure is relative", + "rain is the main gauge", "pm2.5", "co2", "wind (its speed shaded up to the gusts", "usual set", "all is every", + "ecowitt", "weather station", "airgradient", "air gradient"): + assert words in text, words + + +# ---------- a day's look ---------- +SUMMER = date(2026, 12, 21) + + +def look(day=SUMMER, latitude=MELBOURNE, **figures) -> str | None: + found = day_look({"rain": 0.0, "wind_gust": 20.0, "temp_max": 24.0, "temp_min": 12.0} | figures, latitude=latitude, day=day) + return found and f"{found['word']} {found['emoji']}" + + +def test_a_days_look_takes_the_first_of_its_rules_that_holds(): + clear = clear_sky_mean(SUMMER, MELBOURNE) + assert look(rain=12.0, wind_gust=65.0, solar_avg=clear) == "stormy ⛈️" + assert look(rain=12.0, wind_gust=40.0) == look(rain=5.0) == "wet 🌧️" # heavy rain with no strong gust is wet + assert look(rain=1.0, solar_avg=clear) == look(rain=4.9, wind_gust=70.0) == "showery 🌦️" + assert look(rain=0.9, wind_gust=50.0) == "windy 💨" # a trace is no rainy day + assert look(temp_max=35.0, solar_avg=clear) == "very hot 🥵" + assert look(day=date(2026, 6, 21), temp_max=9.5) == look(temp_min=0.0, solar_avg=clear) == "very cold 🥶" + assert look(solar_avg=0.9 * clear) == "sunny ☀️" and look(solar_avg=0.7 * clear) == "mostly sunny 🌤️" + assert look(solar_avg=0.4 * clear) == "partly cloudy ⛅" and look(solar_avg=0.2 * clear) == "overcast ☁️" + winter = clear_sky_mean(date(2026, 6, 21), MELBOURNE) + assert look(day=date(2026, 6, 21), temp_max=14.0, temp_min=4.0, solar_avg=0.9 * winter) == "sunny ☀️" # set against its own date's sky + + +def test_a_day_with_no_solar_radiation_has_no_cloud_step(): + assert look() is None and look(latitude=None, solar_avg=300.0) is None + assert look(rain=6.0) == "wet 🌧️" # (the other steps still hold) + assert day_look({}, latitude=MELBOURNE, day=SUMMER) is None + assert day_look({"rain": None, "solar_avg": "350.0"}, latitude=MELBOURNE, day=SUMMER) == {"word": "sunny", "emoji": "☀️"} + today = {"rain": 0.0, "temp_max": 24.0, "solar_avg": 350.0} + assert day_look(today, latitude=MELBOURNE, day=SUMMER, so_far=True) is None # a day not over: its solar mean is no whole day's + assert day_look(today | {"temp_max": 36.0}, latitude=MELBOURNE, day=SUMMER, so_far=True)["word"] == "very hot" + + +def test_a_days_look_uses_only_the_weather_emojis_the_bot_always_used(): + allowed = "☀️ 🌤️ ⛅ ☁️ 🌦️ 🌧️ ⛈️ 💨 🥵 🥶 🌫️" # (the old prompt's list) + assert all(emoji in allowed for emoji in LOOKS.values()) + assert daylook.FIGURES == ("rain", "wind_gust", "temp_max", "temp_min", "solar_avg") # the days tool's names + + +def test_a_clear_sky_follows_the_season_and_the_latitude(): + summer, winter = clear_sky_mean(SUMMER, MELBOURNE), clear_sky_mean(date(2026, 6, 21), MELBOURNE) + assert 29 < summer * 86400 / 1e6 < 34 and 8 < winter * 86400 / 1e6 < 12 # MJ/m² a day: Melbourne's clear days, about 32 and 10 + assert clear_sky_mean(date(2026, 6, 21), -80.0) == 0.0 # the polar night + assert clear_sky_mean(date(2026, 6, 21), 37.8) == pytest.approx(summer, rel=0.02) # the other hemisphere's summer + assert day_look({"solar_avg": 10.0}, latitude=-80.0, day=date(2026, 6, 21)) is None + + +def test_the_service_modules_say_what_they_offer(): + for module in (common, names, daylook): + assert all(hasattr(module, name) for name in module.__all__), module.__name__ + + +def test_the_ten_are_built_in_order_each_where_its_source_is_and_found_by_name(): + from lib.service.context import Context + from types import SimpleNamespace as NS + from lib.service import ORDER, Service, build + from tests.fakes import TZ + station = NS(name="Ecowitt", tz=TZ, storage=None, latitude=-37.8) + everything = build(Context(eco=station, air=NS(name="AirGradient", tz=TZ), forecast=NS(), pollen=NS(), tz=TZ)) + assert [t.name for t in everything] == list(ORDER) + assert [t.name for t in build(Context(tz=TZ))] == ["summary", "readings", "relate", "scan", "about"] # no source: what needs none + service = Service(everything) + assert service["summary"] is service.get("summary") and "days" in service and service.get("nothing") is None + assert [t.name for t in service] == list(ORDER) and service.held(["a"]) == ["a"] # (no context: every name is held) + + +def test_the_bot_asks_for_its_charts_as_drawn(): + from lib.service.common import AS_DRAWN, MAX_CHART_POINTS, request_meta + assert request_meta({"chart_points": AS_DRAWN})["chart_points"] == AS_DRAWN + assert request_meta({"chart_points": 10_000})["chart_points"] == MAX_CHART_POINTS diff --git a/tests/test_service_current.py b/tests/test_service_current.py new file mode 100644 index 00000000..4b650361 --- /dev/null +++ b/tests/test_service_current.py @@ -0,0 +1,530 @@ +"""The `current` tool (lib/service/current.py): the readings now from both sensors, every one or those named, with the gauges' highs and +lows beside them on request, and the bot's own words for them (its report, "weather now" and plain lookups), unchanged.""" + +import json +from pathlib import Path +import re +import time +from datetime import date, datetime + +import pytest + +from lib.airgradient import AirGradient +from lib.ecowitt.days import day_values_on +from lib.service import current as cur +from lib.service.common import FRESH +from lib.service.context import Context +from lib.service.current import CurrentTool, heading +from lib.service.names import AIR_DEVICE, STATION, Catalogue +from lib.timeutil import clock_text, to_local +from tests.clocks import pin +from tests.fakes import TZ, air_transport, archived_station, config + +WHEN = re.compile(r"^(at|around) \d{1,2}(:\d\d)?[ap]m$|^sometime between ") + + +def live(at: float, **changes) -> dict: + """A live reading as Ecowitt's real_time gives it ({group: {field: {time, unit, value}}}): the station's own on a wet night (what the + report written in code was first written from, until step 6c), with `changes` ("outdoor.temperature": "36.0", or None to leave a reading out).""" + t = str(int(at)) + data = {"outdoor": {"temperature": ("12.3", "℃"), "feels_like": ("12.3", "℃"), "app_temp": ("12.7", "℃"), "dew_point": ("11.3", "℃"), + "vpd": ("0.085", "kPa"), "humidity": ("94", "%")}, + "indoor": {"temperature": ("18.3", "℃"), "humidity": ("63", "%"), "dew_point": ("11.1", "℃"), "feels_like": ("18.3", "℃"), + "app_tempin": ("18.7", "℃")}, + "solar_and_uvi": {"solar": ("0.0", "W/m²"), "uvi": ("0", "")}, + "rainfall": {"rain_rate": ("1.8", "mm/hr"), "daily": ("6.3", "mm"), "event": ("49.8", "mm"), "1_hour": ("1.3", "mm"), + "weekly": ("49.8", "mm"), "monthly": ("49.8", "mm"), "yearly": ("5105.7", "mm")}, + "wind": {"wind_speed": ("0.0", "km/h"), "wind_gust": ("0.0", "km/h"), "wind_direction": ("131", "º")}, + "pressure": {"relative": ("1025.0", "hPa"), "absolute": ("1009.5", "hPa")}} + out = {g: {f: {"time": t, "unit": u, "value": v} for f, (v, u) in fields.items()} for g, fields in data.items()} + for name, value in changes.items(): + group, field = name.split(".") + if value is None: + out[group].pop(field, None) + else: + out[group][field] = {**out[group].get(field, {"time": t, "unit": ""}), "value": value} + return out + + +DAY = {"solar_and_uvi.solar": "612.5", "solar_and_uvi.uvi": "7", "wind.wind_speed": "14.0", "wind.wind_gust": "31.0"} # sunny and breezy +HOT = {"outdoor.temperature": "36.0", "outdoor.humidity": "90", "indoor.temperature": "29.0", "indoor.humidity": "20", + "pressure.relative": "1030.0", "rainfall.rain_rate": "2.0", "rainfall.daily": "3.0", "rainfall.monthly": "9.0", + "solar_and_uvi.solar": "800.0", "solar_and_uvi.uvi": "10", "wind.wind_speed": "55.0", "wind.wind_gust": "70.0", + "wind.wind_direction": "90"} # every emoji there is +DRY = {"rainfall.rain_rate": "0.0", "rainfall.daily": "0.0", "rainfall.monthly": "12.0", "wind.wind_speed": "12.0", + "wind.wind_gust": "20.0", "wind.wind_direction": "270"} + + +class Station: + """The archived fake station, its live reading what the test says (a request counted, and whether it was urgent).""" + + def __init__(self, eco, data: dict | None): + self.eco, self.data, self.asked = eco, data, [] + eco.api.realtime = self.realtime + + async def realtime(self, mac, groups, urgent=False): + self.asked.append(urgent) + if isinstance(self.data, Exception): + raise self.data + return json.loads(json.dumps(self.data)) + + def reads(self, data): + """A new live reading, asked for afresh (the kept one forgotten).""" + self.data, self.eco._live = data, None + + +async def world(tmp_path, archived_cache, data=None, *, air=True, station=True, catalogue=None): + """(the tool, the Station, the AirGradient or None): the archived station reading `data` now (default: the wet night), the fake air + sensor's cloud beside it in the same file. catalogue "file": the readings the file holds (Catalogue.open); None: every reading.""" + eco, _ = await archived_station(tmp_path, archived_cache) + stand_in = Station(eco, live(time.time()) if data is None else data) + sensor = None + if air: + transport, _ = air_transport() + sensor = AirGradient(config(tmp_path), transport=transport, storage=eco.storage, owned=False) + await sensor.start() + ctx = Context(eco=eco if station else None, air=sensor) + if catalogue == "file": + ctx.catalogue = await Catalogue.open(ctx.eco, ctx.air) + tool = CurrentTool(ctx) + tool.opened = [s for s in (sensor, eco) if s is not None] # (what close() closes: the station too, when the tool isn't given it) + return tool, stand_in, sensor + + +async def close(tool): + for source in tool.opened: + await source.close() + + +async def call(tool, meta=None, **args) -> dict: + return json.loads(await tool.tool().call(args, meta)) + + +# ---------- the tool ---------- +def test_the_description_says_what_it_answers_with_an_example_each_and_where_the_rest_goes(): + d = cur.DESCRIPTION + assert len(d) < 1500 + for said in ("{}", "{readings: [\"temperature\"]}", "{readings: [\"rain\"]}", "{context: true}", "report, status or sitrep", + "forecast", "pollen", "will it rain (outlook)", "(summary)", "\"ecowitt week\", \"weather week\" (summary)", "(readings)", "lines", "missing", "unavailable"): + assert said in d, said + schema = cur.parameters("Readings, as `sensor.reading`.") + assert set(schema["properties"]) == {"readings", "context"} and "required" not in schema + assert schema["properties"]["readings"]["description"].endswith("Default: every reading the station and the air sensor have now.") + + +async def test_it_is_offered_with_a_sensor_and_says_it_asks_the_devices(tmp_path, archived_cache): + assert cur.tools(Context()) == [] + tool, _, _ = await world(tmp_path, archived_cache) + (made,) = cur.tools(tool.ctx) + assert made.name == "current" and made.annotations == {"readOnlyHint": True, "openWorldHint": True} + assert "outdoor.temperature" in made.parameters["properties"]["readings"]["description"] + await close(tool) + + +# ---------- the readings now ---------- +async def test_every_reading_now_with_its_value_unit_words_and_emoji(tmp_path, archived_cache): + tool, station, _ = await world(tmp_path, archived_cache) + got = await call(tool) + assert "period" not in got and got["fresh"] == FRESH and "charts" not in got and "missing" not in got + s = got["sensors"] + assert s["outdoor"]["temperature"] == {"value": 12.3, "unit": "°C", "text": "12.3 °C", "emoji": "🧥"} + assert s["outdoor"]["humidity"] == {"value": 94, "unit": "%", "text": "94 %", "emoji": "💦"} + assert s["indoor"]["app_temp"]["text"] == "18.7 °C" # (the station calls it app_tempin) + assert s["outdoor"]["vpd"] == {"value": 0.085, "unit": "kPa", "text": "0.085 kPa"} # nothing to notice: no emoji + assert s["rainfall"]["rain"] == {"value": 6.3, "unit": "mm", "text": "6.3 mm", "emoji": "☔"} # today's rain so far + assert s["rainfall"]["rain_rate"]["text"] == "1.8 mm/h" and s["rainfall"]["rain_rate"]["emoji"] == "🌧️" + assert s["wind"]["wind_direction"] == {"value": 131, "unit": "°", "text": "131°", "compass": "SE"} + assert s["solar_and_uvi"]["uvi"] == {"value": 0, "unit": "", "text": "0"} + assert s["pressure"]["absolute"]["text"] == "1009.5 hPa" + assert "rainfall_piezo" not in s # every reading the sensors have now: this station has no piezo gauge + pm = s["air"]["pm2_5"] + assert pm["value"] == 12.0 and pm["unit"] == "µg/m³" and pm["text"] == "12.0 µg/m³" and pm["band"] == ("good" if pm["aqi_us"] <= 50 else "moderate" if pm["aqi_us"] <= 100 else pm["band"]) # (moves with the clock) + assert pm["rating"].endswith(("good", "poor")) + assert s["air"]["co2"]["text"] == "450 ppm" and s["air"]["nox_index"]["text"] == "1.0" and s["air"]["voc_index"]["text"] == "100" + assert s["air"]["temperature"]["unit"] == "°C" and "rating" not in s["air"]["temperature"] # the sensor's own: no rating + newest = datetime.fromisoformat(got["as_of"]["time"]) + assert abs(newest.timestamp() - time.time()) < 60 and got["as_of"]["text"].endswith(clock_text(newest)) + assert station.asked == [True] # someone is waiting: the station's request goes first + await close(tool) + + +async def test_named_readings_alone_each_once_in_the_order_named(tmp_path, archived_cache): + tool, _, _ = await world(tmp_path, archived_cache) + got = await call(tool, readings=["rain", "temperature", "pm2.5", "gust"]) + assert [(g, list(r)) for g, r in got["sensors"].items()] == [("rainfall", ["rain"]), ("outdoor", ["temperature"]), + ("indoor", ["temperature"]), ("wind", ["wind_gust"]), ("air", ["pm2_5"])] + assert set(got["lines"]) == {STATION, AIR_DEVICE} and got["lines"][AIR_DEVICE] == ["• PM2.5: " + got["sensors"]["air"]["pm2_5"]["text"] + + f" {got['sensors']['air']['pm2_5']['rating']} (AQI {got['sensors']['air']['pm2_5']['aqi_us']})"] + assert (await call(tool, readings="indoor temperature, outdoor humidity"))["sensors"] == { + "indoor": {"temperature": {"value": 18.3, "unit": "°C", "text": "18.3 °C", "emoji": "🧥"}}, + "outdoor": {"humidity": {"value": 94, "unit": "%", "text": "94 %", "emoji": "💦"}}} # (a string of names will do) + only_air = await call(tool, readings=["air"]) + assert list(only_air["sensors"]) == ["air"] and list(only_air["sensors"]["air"]) == ["pm2_5", "pm10", "pm1", "co2", "voc_index", + "nox_index"] + assert set(only_air["lines"]) == {AIR_DEVICE} + await close(tool) + + +async def test_a_reading_named_that_isnt_being_read_now_is_missing(tmp_path, daytime_archive): + tool, station, _ = await world(tmp_path, daytime_archive, live(time.time(), **{"indoor.temperature": None})) + got = await call(tool, readings=["indoor temperature", "pressure", "piezo rain"]) + assert got["missing"] == ["indoor.temperature", "rainfall_piezo.rain"] and list(got["sensors"]) == ["pressure"] + with_context = await call(tool, readings=["indoor temperature"], context=True) # a gauge with no reading now: its figures, dimmed + entry = with_context["sensors"]["indoor"]["temperature"] + assert entry["value"] is None and entry["unit"] == "°C" and entry["year"]["high"] > entry["year"]["low"] + assert with_context["missing"] == ["indoor.temperature"] + await close(tool) + + +async def test_the_readings_listed_are_those_the_file_holds(tmp_path, archived_cache): + tool, _, _ = await world(tmp_path, archived_cache, catalogue="file") # the fake station's history has no indoor humidity + got = await call(tool) + assert list(got["sensors"]["indoor"]) == ["temperature"] and "• Indoor: 🧥 18.3 °C, 63 %" in got["lines"][STATION] # (the report's words: as today) + await close(tool) + + +# ---------- the words: the bot's, unchanged ---------- +# Each case's lines, as the bot's old words wrote them for the same readings (checked against them, tests/report_words.py, until step +# 6c deleted that oracle): pinned in tests/current_words.json. "{pm2.5}" stands for the air sensor's PM2.5 line, whose rating and AQI +# follow the fake's clock: it is written here from the sensor's own reading. +WORDS = json.loads((Path(__file__).parent / "current_words.json").read_text()) + + +async def pinned(air, lines: list[str]) -> list[str]: + """`lines` as pinned, the PM2.5 line written from the air sensor's reading now (its rating and US AQI).""" + pm = (await air.latest()).reading["pm2_5"] + said = f"• PM2.5: {pm['value']} {pm['unit']} {pm['rating']} (AQI {pm['aqi_us']})" + return [said if line == "{pm2.5}" else line for line in lines] + + +@pytest.mark.parametrize("changes", [{}, DAY, HOT, DRY], ids=["wet-night", "sunny", "every-emoji", "dry"]) +async def test_the_lines_are_the_reports_and_weather_nows_words(tmp_path, archived_cache, changes, request): + tool, _, air = await world(tmp_path, archived_cache, live(time.time(), **changes)) + got = await call(tool) + want = WORDS[request.node.callspec.id]["all"] + assert got["lines"][STATION] == want[STATION] and got["lines"][AIR_DEVICE] == await pinned(air, want[AIR_DEVICE]) + assert list(got["headings"]) == [STATION, AIR_DEVICE] and got["headings"][STATION].startswith("Weather station") + await close(tool) + + +# (the bot's plain lookup: the readings the words name, and the sides) -> what a model sends for the same question +LOOKUPS = [(["temperature"], ["outdoor", "indoor"], ["temperature"]), # "how hot is it" + (["temperature"], ["indoor"], ["indoor temperature"]), # "indoor temperature" + (["humidity"], ["outdoor"], ["outdoor humidity"]), + (["rain"], ["outdoor", "indoor"], ["rain"]), # "is it raining" + (["wind"], ["outdoor", "indoor"], ["wind"]), + (["uv"], ["outdoor", "indoor"], ["uv"]), + (["pressure"], ["outdoor", "indoor"], ["pressure"]), + (["solar"], ["outdoor", "indoor"], ["solar"]), + (["dew_point"], ["outdoor", "indoor"], ["dew point"]), + (["dew_point"], ["indoor"], ["indoor dew point"]), + (["feels_like"], ["outdoor", "indoor"], ["feels like"]), + (["temperature", "rain"], ["outdoor", "indoor"], ["temperature", "rain"])] + + +@pytest.mark.parametrize("changes", [{}, DAY, DRY], ids=["wet-night", "sunny", "dry"]) +async def test_named_readings_are_worded_as_the_bots_plain_lookups(tmp_path, archived_cache, changes, request): + tool, _, air = await world(tmp_path, archived_cache, live(time.time(), **changes)) + want = WORDS[request.node.callspec.id] + for (names, sides, asked), lines in zip(LOOKUPS, want["lookups"], strict=True): + got = await call(tool, readings=asked) + assert got["lines"][STATION] == lines, asked + for asked, lines in zip((["pm10"], ["co2", "pm2.5"], ["air"], ["airgradient"]), want["air"], strict=True): + got = await call(tool, readings=asked) + assert got["lines"][AIR_DEVICE] == await pinned(air, lines), asked + await close(tool) + + +async def test_readings_the_bot_never_worded_have_a_line_of_their_own(tmp_path, archived_cache): + tool, _, _ = await world(tmp_path, archived_cache, live(time.time(), **DAY)) + got = await call(tool, readings=["gust", "wind direction", "rain rate", "absolute pressure", "airgradient temperature"]) + assert got["lines"][STATION] == ["• Wind gust: 🌬️ 31.0 km/h", "• Wind direction: 131°", "• Rain rate: 🌧️ 1.8 mm/h", + "• Absolute pressure: 1009.5 hPa"] + assert got["lines"][AIR_DEVICE] == [f"• AirGradient temperature: {got['sensors']['air']['temperature']['text']}"] + wind = await call(tool, readings=["wind", "gust"]) # the gusts are in the wind's line already + assert wind["lines"][STATION] == ["• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h"] + await close(tool) + + +def test_the_heading_has_the_time_of_the_reading_with_its_day_when_that_isnt_today(): + today = date(2026, 11, 10) + assert heading(STATION, datetime(2026, 11, 10, 2, 21, tzinfo=TZ), today) == "Weather station (2:21am)" + assert heading(AIR_DEVICE, datetime(2026, 11, 9, 23, 45, tzinfo=TZ), today) == "Air quality (Mon 9 Nov 11:45pm)" + assert heading(STATION, None, today) == "Weather station" + + +# ---------- 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 + days = periods_of(eco.now().date()) + names = sorted({n for g in GAUGES for n in (g.highest, g.lowest) 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} + if g.total and now is not None: + out[g.title]["Daily"] = (None, now) + return out + + +async def test_context_is_the_gauges_figures_with_when_each_happened(tmp_path, daytime_archive): + data = live(time.time(), **DAY) + tool, _, _ = await world(tmp_path, daytime_archive, data) # (a fixed day: a year so far with summer in it, a month of days) + got = await call(tool, context=True) + tiles = await gauge_rows(tool.ctx.eco, data) + s = got["sensors"] + for title, (sensor, reading) in (("Temperature", ("outdoor", "temperature")), ("Humidity", ("outdoor", "humidity")), + ("Atmospheric pressure", ("pressure", "relative")), ("Dew point", ("outdoor", "dew_point")), + ("Indoor temperature", ("indoor", "temperature"))): + entry = s[sensor][reading] + for row, key in cur.PERIODS: + assert (entry[key]["high"], entry[key]["low"]) == tiles[title][row], (title, row) + assert WHEN.match(entry[key]["high_when"]) and WHEN.match(entry[key]["low_when"]), entry[key] + assert ("high_date" in entry[key]) is (key != "today") + 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 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 + for row, key in cur.PERIODS[1:]: + wettest, total = tiles["Rain"][row] + assert rain[key]["total"] == total and rain[key]["wettest_day"]["rain"] == wettest + assert s["solar_and_uvi"]["uvi"]["year"]["high_text"] == "11" # written as the station writes it + assert "today" not in s["outdoor"]["vpd"] # no gauge, no context + pm = s["air"]["pm2_5"] # the air sensor's: its day rows' highs and lows + assert pm["today"]["high"] >= pm["value"] >= pm["today"]["low"] and pm["year"]["high"] >= pm["month"]["high"] >= pm["today"]["high"] + assert pm["year"]["high_text"] == f"{pm['year']['high']:.1f} µg/m³" and "high_date" in pm["year"] and "high_when" not in pm["year"] + await close(tool) + + +async def test_with_context_every_gauge_the_station_sends_is_there_though_its_file_hasnt_recorded_it_yet(tmp_path, archived_cache): + """The catalogue is what the file has recorded; with context, a gauge's reading the station sends now but the file doesn't hold yet + (the archived fake has no feels like, rain rate nor indoor humidity) is there too, with its figures (the reading now alone), as the + gauges show every reading the station sends. Without context, or with readings named, only the catalogue's.""" + tool, _, _ = await world(tmp_path, archived_cache, catalogue="file") + held = tool.ctx.readings() + assert not {"outdoor.feels_like", "rainfall.rain_rate", "indoor.humidity"} & set(held.names) + s = (await call(tool, context=True))["sensors"] + feels, rate, inside = s["outdoor"]["feels_like"], s["rainfall"]["rain_rate"], s["indoor"]["humidity"] + assert (feels["value"], feels["text"]) == (12.3, "12.3 °C") and rate["value"] == 1.8 and inside["value"] == 63 + assert feels["today"]["high"] == feels["today"]["low"] == 12.3 and rate["year"]["high"] == 1.8 + assert "app_temp" not in s["outdoor"] and "vpd" not in s["outdoor"] # (no gauge: only the catalogue's) + assert "feels_like" not in (await call(tool))["sensors"]["outdoor"] + named = (await call(tool, readings=["outdoor temperature"], context=True))["sensors"] + assert list(named) == ["outdoor"] and list(named["outdoor"]) == ["temperature"] # named: just those + await close(tool) + + +async def test_a_reading_named_in_full_that_the_file_hasnt_recorded_is_answered_from_the_reading_now(tmp_path, archived_cache): + """current is about now: a reading the service knows, named in full, that the station sends but the file hasn't recorded yet (a new + station's first minutes) is answered, not refused; a word still reads the file's catalogue. So the gauges name their readings and + only the station is read: the air sensor isn't asked (a slow one doesn't hold up the dashboard).""" + from lib import gauge_sheet + tool, _, sensor = await world(tmp_path, archived_cache, catalogue="file") + assert "outdoor.feels_like" not in tool.ctx.readings() + got = await call(tool, readings=["outdoor.feels_like", "rainfall.rain_rate", "temperature"]) + assert got["sensors"]["outdoor"]["feels_like"]["text"] == "12.3 °C" and got["sensors"]["rainfall"]["rain_rate"]["value"] == 1.8 + assert got["sensors"]["outdoor"]["temperature"]["value"] == 12.3 and "error" not in got + + async def no_air(*a, **k): + raise AssertionError("the gauges don't read the air sensor") + sensor.latest = no_air + gauges = await call(tool, **gauge_sheet.call()) + assert "air" not in gauges["sensors"] and gauges["sensors"]["outdoor"]["feels_like"]["today"]["high"] == 12.3 + assert gauge_sheet.sheet(gauges) is not None + await close(tool) + + +@pytest.mark.parametrize("when", [datetime(2026, 11, 11, 0, 5, tzinfo=TZ), datetime(2027, 1, 1, 0, 5, tzinfo=TZ)], + ids=["12:05am", "12:05am on 1 Jan"]) +async def test_just_after_midnight_the_highest_gust_is_the_gust_now_not_the_wind_speed(tmp_path, pinned_archive, monkeypatch, when): + """Before today's row has a gust (and on 1 Jan, before any day of the year has), the Wind gauge's Max, its highest gust, was the + live wind speed counted in (14 km/h while it gusted 31): it is the live gust, as wind_gust's own figures are.""" + cache = pinned_archive(when) + pin(monkeypatch, when) + tool, _, _ = await world(tmp_path, cache, live(time.time(), **DAY)) # (the speed now 14.0 km/h, the gust 31.0) + s = (await call(tool, readings=["wind speed", "wind gust"], context=True))["sensors"]["wind"] + rows = ("today", "month", "year") if when.month == 1 else ("today",) + 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)}" + await close(tool) + + +async def test_a_high_or_low_is_the_day_rows_with_its_day_or_the_live_reading_when_it_beats_them(tmp_path, daytime_archive): + tool, station, _ = await world(tmp_path, daytime_archive) + got = await call(tool, readings=["outdoor temperature"], context=True) + year = got["sensors"]["outdoor"]["temperature"]["year"] + on = datetime.strptime(year["high_date"], "%a %d %b %Y").date() + eco = tool.ctx.eco + values, _ = await eco.storage.read(day_values_on, eco.mac, ["temp_max"], [on]) + assert values["temp_max"][on] == year["high"] # the day whose row has it + at = time.time() + station.reads(live(at, **{"outdoor.temperature": "45.0"})) # hotter than any day held + hot = (await call(tool, readings=["outdoor temperature"], context=True))["sensors"]["outdoor"]["temperature"] + clock = f"at {clock_text(to_local(int(at), TZ), whole_hours=True)}" + for key in ("today", "month", "year"): + assert hot[key]["high"] == 45.0 and hot[key]["high_when"] == clock and hot[key]["high_text"] == "45.0 °C" + assert hot["month"]["high_date"] == f"{to_local(int(at), TZ):%a} {to_local(int(at), TZ).day} {to_local(int(at), TZ):%b %Y}" + await close(tool) + + +# ---------- refusals that teach, and devices that don't answer ---------- +async def test_a_wrong_call_is_refused_with_what_fixes_it(tmp_path, archived_cache): + tool, _, _ = await world(tmp_path, archived_cache) + then = await call(tool, period="yesterday") + assert "summary" in then["error"] and "readings" in then["error"] and then["arguments"] == ["readings", "context"] + other = await call(tool, groups="outdoor") + assert other["error"] == "'groups' is not an argument of current." and other["arguments"] == ["readings", "context"] + unknown = await call(tool, readings=["lightning"]) + assert "isn't a reading" in unknown["error"] and "outdoor.temperature" in unknown["names"] and "rain" in unknown["words"] + assert "true or false" in (await call(tool, context="maybe"))["error"] + assert (await call(tool, context="true"))["sensors"]["outdoor"]["temperature"]["today"] # (true written as a word will do) + await close(tool) + + (tmp_path / "station").mkdir() + tool, _, _ = await world(tmp_path / "station", archived_cache, air=False) + no_air = await call(tool, readings=["pm2.5"]) + assert no_air["error"] == "air.pm2_5 is the air sensor's, and this service has no air sensor." and "air.pm2_5" not in no_air["names"] + assert "air" not in (await call(tool))["sensors"] # unnamed: just the sensors there are + await close(tool) + + +async def test_a_device_that_doesnt_answer_is_said_so_and_the_other_still_answers(tmp_path, archived_cache): + tool, station, air = await world(tmp_path, archived_cache, RuntimeError("Ecowitt: System is busy.")) + got = await call(tool) + assert got["unavailable"] == {STATION: "The weather station isn't answering right now."} + assert got["lines"][STATION] == ["• not available right now"] and got["headings"][STATION] == "Weather station" + assert list(got["sensors"]) == ["air"] and got["as_of"] + assert got["lines"][AIR_DEVICE] == await pinned(air, WORDS["wet-night"]["all"][AIR_DEVICE]) # the air sensor's, as ever + + async def down(extras=()): + raise RuntimeError("AirGradient current failed: HTTP 500") + air.latest = down + station.reads(live(time.time())) + got = await call(tool) + assert got["unavailable"] == {AIR_DEVICE: "The air sensor isn't answering right now."} and "air" not in got["sensors"] + assert f"{got['headings'][AIR_DEVICE]}\n{got['lines'][AIR_DEVICE][0]}" == "Air quality\n• not available right now" + neither = RuntimeError("down") + station.reads(neither) + nothing = await call(tool) + assert set(nothing["unavailable"]) == {STATION, AIR_DEVICE} and nothing["sensors"] == {} and "as_of" not in nothing + await close(tool) + + +# ---------- the request's metadata ---------- +async def test_without_fetching_it_answers_from_the_reading_held(tmp_path, archived_cache): + tool, station, _ = await world(tmp_path, archived_cache) + nothing = await call(tool, {"fetch": False}, readings=["temperature"]) + assert nothing["unavailable"] == {STATION: "No reading of the weather station is held (and `fetch` is off)."} and station.asked == [] + await call(tool, readings=["temperature"]) + station.data = live(time.time(), **{"outdoor.temperature": "20.0"}) + tool.ctx.eco._live = (time.time() - 3600, tool.ctx.eco._live[1]) # an hour old: a question would ask again + held = await call(tool, {"fetch": False}, readings=["outdoor temperature"]) + assert held["sensors"]["outdoor"]["temperature"]["value"] == 12.3 and station.asked == [True] + assert (await call(tool, readings=["outdoor temperature"]))["sensors"]["outdoor"]["temperature"]["value"] == 20.0 + await close(tool) + + +async def test_without_fetching_the_air_sensor_answers_from_its_held_reading_whatever_its_age_and_asks_it_nothing( + tmp_path, archived_cache, monkeypatch): + """The dashboard's data (every gauge, with context, fetch off): with the air sensor's held reading stale (it isn't answering), it is + still the answer, rated on the readings it already has; neither the reading nor today's history is fetched again.""" + import sys + calls, made = [], air_transport + + def counted(*a, **k): + transport, seen = made(*a, **k) + calls.append(seen) + return transport, seen + monkeypatch.setattr(sys.modules[__name__], "air_transport", counted) + tool, _, sensor = await world(tmp_path, archived_cache) + asked = calls[0] # (start() read it once) + fetched = await call(tool, context=True) + assert "past" in asked # today's history, for the rating + pm = fetched["sensors"]["air"]["pm2_5"]["value"] + stale = time.time() - 3600 # an hour old: past FRESH_SECONDS + sensor._current = (sensor._current[0], stale) + sensor._recent = {day: (rows, stale) for day, (rows, _) in sensor._recent.items()} + asked.clear() + held = [await call(tool, {"fetch": False}, context=True) for _ in range(3)] + assert asked == [] + assert all(h["sensors"]["air"]["pm2_5"]["value"] == pm and AIR_DEVICE not in (h.get("unavailable") or {}) for h in held) + assert held[0]["sensors"]["air"]["pm2_5"]["band"] == fetched["sensors"]["air"]["pm2_5"]["band"] # rated as when fetched + await call(tool, context=True) + assert "current" in asked # (a question still asks it again) + await close(tool) + + +async def test_the_kept_reading_answers_while_fresh_and_a_group_it_lacks_is_asked_for_when_named(tmp_path, archived_cache): + tool, station, _ = await world(tmp_path, archived_cache, air=False, catalogue="file") + assert "rainfall_piezo.rain" in tool.ctx.readings() # (a group that never sent anything is offered whole) + await call(tool) + await call(tool, context=True) + await call(tool, readings=["temperature", "rain"]) + assert station.asked == [True] # one request: the reading the station keeps answers the rest + await call(tool, readings=["piezo rain"]) + assert station.asked == [True, True] # a group "weather now" doesn't show: asked for when named + await close(tool) + + +async def test_a_background_request_asks_the_station_behind_those_someone_waits_for(tmp_path, archived_cache): + tool, station, _ = await world(tmp_path, archived_cache, air=False) + await call(tool, {"priority": "background"}) + station.reads(live(time.time())) + await call(tool) + assert station.asked == [False, True] + await close(tool) + + +async def test_the_air_sensor_alone_and_its_own_temperature(tmp_path, archived_cache): + tool, station, _ = await world(tmp_path, archived_cache, station=False) + got = await call(tool, readings=["airgradient temperature", "airgradient humidity"]) + t, h = got["sensors"]["air"]["temperature"], got["sensors"]["air"]["humidity"] + assert t["unit"] == "°C" and t["text"] == f"{t['value']:.1f} °C" and h["text"] == f"{h['value']:.0f} %" + assert got["lines"] == {AIR_DEVICE: [f"• AirGradient temperature: {t['text']}", f"• AirGradient humidity: {h['text']}"]} + everything = await call(tool) + assert list(everything["sensors"]) == ["air"] and list(everything["lines"]) == [AIR_DEVICE] and station.asked == [] + assert everything["headings"][AIR_DEVICE].startswith("Air quality (") + await close(tool) + + +def test_the_module_says_what_it_offers(): + assert all(hasattr(cur, name) for name in cur.__all__) + + +def test_the_air_sensors_context_is_its_day_rows_highs_and_lows_with_the_reading_now_counted_in(): + today, first = date(2026, 10, 27), date(2026, 2, 3) + values = {"pm2_5_max": {first: 80.0, date(2026, 10, 2): 20.0, today: 9.5}, "pm2_5_min": {first: 2.0, today: 4.0}} + got = cur.air_context_of("pm2_5", 12.0, "µg/m³", values, today) + assert got["today"] == {"high": 12.0, "high_text": "12.0 µg/m³", "low": 4.0, "low_text": "4.0 µg/m³"} # 12 now: above today's 9.5 + assert (got["month"]["high"], got["month"]["high_date"], got["month"]["low"]) == (20.0, "Fri 2 Oct 2026", 4.0) + assert (got["year"]["high"], got["year"]["high_date"], got["year"]["low_date"]) == (80.0, "Tue 3 Feb 2026", "Tue 3 Feb 2026") + assert cur.air_context_of("co2", None, "ppm", {}, today) == {} # nothing held + assert cur.air_context_of("co2", 450, "ppm", {}, today)["year"]["high_text"] == "450 ppm" + + +async def test_with_context_an_air_sensor_not_answering_gives_its_readings_figures_alone(tmp_path, daytime_archive): + """A gauge with no reading now is drawn dimmed with its figures: the air sensor not answering, its readings are there with their + day rows' highs and lows and no value (and the sensor is said to be unavailable); without context, nothing of it.""" + tool, _, sensor = await world(tmp_path, daytime_archive, live(time.time(), **DAY)) + await sensor.store.add_recorded({"ts": int(time.time()) // 300 * 300 - 600, "pm2_5": 48.5, "co2": 610.0}) # the day's own row + up = (await call(tool, context=True))["sensors"]["air"] + assert up["pm2_5"]["today"]["high"] == 48.5 and up["pm2_5"]["today"]["high_text"] == "48.5 µg/m³" # from the air sensor's day rows + assert up["pm2_5"]["year"]["high"] == 48.5 and up["co2"]["today"]["high"] == 610 + + async def down(*a, **k): + raise RuntimeError("no answer") + sensor.latest = down + got = await call(tool, context=True) + pm = got["sensors"]["air"]["pm2_5"] + assert pm["value"] is None and pm["today"]["high"] == 48.5 and "air" in got["unavailable"] + assert "voc_index" not in got["sensors"]["air"] # no figures held: left out + assert "temperature" not in got["sensors"]["air"] # (its own: no gauge, no context) + assert "air" not in (await call(tool))["sensors"] + await close(tool) diff --git a/tests/test_service_days.py b/tests/test_service_days.py new file mode 100644 index 00000000..57a96157 --- /dev/null +++ b/tests/test_service_days.py @@ -0,0 +1,490 @@ +"""The `days` tool (lib/service/days.py): its arguments and defaults, its result, its refusals, its periods, its charts and their +`drawn_by`, the merged rule over both sensors, part of each day (`hours`), and its answer line, on the fake station's archive with an air +sensor added. (Until step 6c these were also held to weather_days' and air_days' engines and the bot's old words, tests/old_tools.py and +tests/report_words.py, deleted with them: their answers for the same cases are pinned since in tests/days_words.json, and +tests/test_days.py holds the tool's station answers to the fake station's own figures.)""" + +import copy +import dataclasses +import json +import shutil +from datetime import date, datetime, time, timedelta +from pathlib import Path + +import pytest + +from lib.airgradient.readings import AirReadings +from lib.partday import over, parse_stretch +from lib.service import days as days_tool +from lib.service.common import CHART_NOTE, FRESH +from lib.service.context import Context +from lib.service.daylook import LOOKS +from lib.storage import Storage +from lib.storage.catalogue import CLOUD +from lib.timeutil import day_bounds, day_text, local_epoch +from tests import clocks +from tests.clocks import yesterday_at +from tests.fakes import TZ, archived_station, rain_day, temp +from tests.test_chart_json import errors as schema_errors + +LOC = "42" +AIR_DAYS = 40 # the air sensor's 5-minute readings: the last 40 days +OLD_AIR = (390, 375) # ... and hourly averages of days this long ago, before the station's 30-minute archive (its daily records) + + +def pm(ts: int) -> float: + """PM2.5: a level for each day (2 to 32 µg/m³), a microgram higher from noon.""" + local = datetime.fromtimestamp(ts, TZ) + return 2.0 + local.toordinal() % 7 * 5 + (local.hour >= 12) + + +def air_row(ts: int) -> dict: + v = pm(ts) + return {"ts": ts, "pm2_5": v, "pm10": v * 1.5, "pm1": v * 0.7, "co2": 420.0, "voc_index": 100.0, "nox_index": 1.0, + "air_temperature": 18.0, "air_humidity": 60.0} + + +@pytest.fixture(scope="module") +def air_cache(archived_cache, tmp_path_factory): + """The archive with an air sensor's readings added (built once for these tests): the last AIR_DAYS days at 5 minutes, and OLD_AIR's + days as hourly averages.""" + return with_air(archived_cache, tmp_path_factory.mktemp("days") / "ecobot.sqlite") + + +def with_air(archive, path): + """A copy of `archive` at `path` with the air sensor's readings added (AIR_DAYS at 5 minutes, OLD_AIR hourly), up to the clock.""" + shutil.copy(archive, path) + storage = Storage(path, TZ) + today = datetime.now(TZ).date() + + def write(w): + sensor = w.air_sensor(LOC) + start, end = day_bounds(today - timedelta(days=AIR_DAYS), TZ)[0], int(datetime.now(TZ).timestamp()) // 300 * 300 + w.put(sensor, "5min", [air_row(t) for t in range(start, end, 300)], CLOUD) + w.cover(sensor, "5min", start, end - 1) + start, end = day_bounds(today - timedelta(days=OLD_AIR[0]), TZ)[0], day_bounds(today - timedelta(days=OLD_AIR[1]), TZ)[1] + w.put(sensor, "1hour", [air_row(t) for t in range(start, end, 3600)], CLOUD) + w.cover(sensor, "1hour", start, end - 1) + storage.writer.run(write, ()) + storage.close() + return path + + +class Air: + """The part of the air source the tool uses: its readings in the file.""" + tz = TZ + + def __init__(self, storage): + self.store = AirReadings(storage, LOC, TZ) + + +@pytest.fixture +async def world(tmp_path, air_cache): + eco, fake = await archived_station(tmp_path, air_cache) + yield Context(eco=eco, air=Air(eco.storage)) + await eco.close() + assert fake.calls == [] # answered from the file alone + + +@pytest.fixture +async def pinned_world(tmp_path, daytime_archive): + """world, with the clock pinned at 2:05pm Tue 10 Nov 2026 (conftest's daytime_archive): for the answers pinned word for word.""" + (tmp_path / "station").mkdir() + eco, fake = await archived_station(tmp_path / "station", with_air(daytime_archive, tmp_path / "air.sqlite")) + yield Context(eco=eco, air=Air(eco.storage)) + await eco.close() + assert fake.calls == [] + + +def tool(ctx): + (found,) = days_tool.tools(ctx) + return found + + +async def ask(ctx, meta=None, **args) -> dict: + return json.loads(await tool(ctx).call(args, meta)) + + +def ago(n: int) -> date: + return datetime.now(TZ).date() - timedelta(days=n) + + +def label(d: date) -> str: + return day_text(d) + + +def truth(d: date) -> tuple[float, float]: + """(temp_max, rain) of a local day, from the fake's functions alone.""" + ticks = range(day_bounds(d, TZ)[0], day_bounds(d, TZ)[1], 300) + return max(temp(t) for t in ticks), max(rain_day(t) for t in ticks) + + +# ---------- the tool ---------- +async def test_the_tool_offers_the_fields_of_the_sensors_there_are_and_says_what_it_is_for(world): + t = tool(world) + assert t.name == "days" and t.annotations == {"readOnlyHint": True, "openWorldHint": False} + props = t.parameters["properties"] + assert set(props) == set(days_tool.ARGUMENTS) + fields = props["where"]["items"]["properties"]["field"]["enum"] + assert {"temp_max", "rain", "indoor_humidity_min", "uv_max", "pm2_5_max", "co2_avg"} <= set(fields) + assert props["sort_by"]["enum"] == props["of"]["enum"] == fields + assert "on record" in props["period"]["description"] and "last 30 days" in props["period"]["description"] + assert "Whole days only" in props["period"]["description"] and "night (22:00-06:00" in props["hours"]["description"] + d = t.description + assert len(d) < 1500 and all(word in d for word in ("summary", "readings", "relate", "day_look", "hours", "only", "count_only")) + # the live evals: "days with most rain" sent no sort_by (ranked by temp_max), "average temperature per year" no group_by + assert 'a record ("hottest ever"), wind direction or a chart over time (summary)' in d + assert 'sort_by is the field the days are ranked by: the wettest days, most rain {sort_by: "rain"}' in d + assert '"per year", "each year", "by month"), group_by' in d and '{stat: "avg", of: "temp_avg", group_by: "year"}' in d + assert '"most rain"' in props["sort_by"]["description"] and '"each year"' in props["group_by"]["description"] + station_only = days_tool.tools(Context(eco=world.eco))[0].parameters["properties"] + assert "pm2_5_max" not in station_only["where"]["items"]["properties"]["field"]["enum"] + assert "Air sensor" not in station_only["where"]["description"] + air_only = days_tool.tools(Context(air=world.air))[0].parameters["properties"] + assert air_only["where"]["items"]["properties"]["field"]["enum"] == list(days_tool.AIR_UNITS) + assert days_tool.tools(Context()) == [] + + +async def test_with_nothing_sent_it_ranks_every_day_on_record_by_the_high_and_answers_ready_to_pass_on(world): + out = await ask(world) + assert list(out)[:4] == ["period", "as_of", "fresh", "answer"] and out["fresh"] == FRESH + first = await world.storage.read(lambda r: min(date.fromisoformat(d) for (d,) in r.db.execute("SELECT day FROM climate_day"))) + assert out["period"]["asked"] == "on record" and out["period"]["start"].startswith(first.isoformat()) + assert out["period"]["cut"] == f"to {day_text(ago(1), year=False)}: today isn't over" + assert out["days_checked"] == out["matching_days"] == (ago(1) - first).days + 1 # (no condition: every day held matches) + rows = out["days"] + assert len(rows) == 5 and [r["temp_max"] for r in rows] == sorted((r["temp_max"] for r in rows), reverse=True) + assert set(rows[0]) >= {"date", "day_look", "source", "temp_max", "temp_min", "rain"} + assert all(r["day_look"]["emoji"] == LOOKS[r["day_look"]["word"]] for r in rows) + assert out["answer"].startswith(f"{out['matching_days']:,} of {out['days_checked']:,} days (") + assert "charts" not in out and "complete" not in out and "note_daily" in out # (its oldest days are Ecowitt's daily records) + + +# ---------- the same answers as weather_days and air_days ---------- +STATION_CASES = [ + {"where": [{"field": "rain", "op": ">", "value": 0}], "sort_by": "temp_max", "limit": 3}, + {"where": [{"field": "rain", "op": ">=", "value": 1}], "sort_by": "temp_max", "limit": 4}, # a trace day ranks higher + {"where": [{"field": "temp_max", "op": ">", "value": 18}], "count_only": True}, + {"sort_by": "temp_min", "order": "asc", "limit": 2}, + {"stat": "sum", "of": "rain", "group_by": "month"}, + {"where": [{"field": "humidity_min", "op": "<", "value": 60}], "stat": "avg", "of": "humidity_avg"}, # note_averaged + {"where": [{"field": "rain", "op": "=", "value": 0}], "only": "weekend", "limit": 20}, +] + + +@pytest.mark.parametrize("case", STATION_CASES) +async def test_station_fields_answer_from_the_day_rows(world, case): + first, last = ago(80), ago(2) + out = await ask(world, start=str(first), end=str(last), **case) + span = [first + timedelta(days=k) for k in range((last - first).days + 1)] + assert out["days_checked"] == len([d for d in span if case.get("only") != "weekend" or d.weekday() >= 5]) and out["answer"] + assert all(r["source"] == "exact" for r in out.get("days", [])) + + +async def test_the_older_days_say_they_come_from_daily_records(world): + args = {"where": [{"field": "temp_max", "op": ">", "value": 0}], "limit": 20} + out = await ask(world, start=str(ago(540)), end=str(ago(2)), **args) + assert out["exact_from"] and "10am to 10am" in out["note_daily"] + old = await ask(world, start=str(ago(540)), end=str(ago(510)), **args) + assert old["days"] and all(r["source"] == "daily" for r in old["days"]) + + +AIR_CASES = [ + {"where": [{"field": "pm2_5_max", "op": ">", "value": 20}], "limit": 3}, + {"stat": "max", "of": "pm2_5_max", "group_by": "month"}, + {"sort_by": "pm10_avg", "order": "asc", "count_only": True}, +] + + +@pytest.mark.parametrize("case", AIR_CASES) +async def test_air_fields_answer_from_the_air_sensors_day_rows(world, case): + first, last = ago(AIR_DAYS + 10), ago(2) + out = await ask(world, start=str(first), end=str(last), **case) + assert out["note_missing"].startswith("10 day(s)") and out["answer"] # (the 10 days before the sensor) + for row in out.get("days", []): + assert row["source"] == "exact" and "day_look" in row # each day's weather, from the station + + +async def test_an_air_question_shows_and_ranks_by_pm2_5_and_its_days_carry_the_weather(world): + out = await ask(world, period="last 20 days", where=[{"field": "co2_avg", "op": ">", "value": 0}]) + assert out["units"] == {"pm2_5_max": "µg/m³", "co2_avg": "ppm"} and out["days_checked"] == 20 # (ranked by co2_avg, as named) + assert "temp_max" not in out["days"][0] and "day_look" in out["days"][0] + air_only = json.loads(await days_tool.tools(Context(air=world.air))[0].call({"period": "last 20 days"})) + assert [r["pm2_5_max"] for r in air_only["days"]] == sorted((r["pm2_5_max"] for r in air_only["days"]), reverse=True) + expected = max(pm(t) for d in (ago(n) for n in range(1, 21)) for t in range(*day_bounds(d, TZ), 300)) + assert air_only["days"][0]["pm2_5_max"] == expected and air_only["units"] == {"pm2_5_max": "µg/m³"} + assert "day_look" not in air_only["days"][0] # (no station: no weather to look at) + + +# ---------- the answers, word for word ---------- +# Each STATION_CASES and AIR_CASES result (all but its period and as_of), and the answer line of each kind of result, as weather_days +# and air_days answered and the bot worded them: recorded with the clock pinned (pinned_world) from the tree where every one was still +# checked against those engines and words (tests/old_tools.py, tests/report_words.py, before step 6c deleted them): days_words.json. +WORDS = json.loads((Path(__file__).parent / "days_words.json").read_text()) + + +async def test_the_station_and_air_answers_are_as_recorded(pinned_world): + assert WORDS["clock"] == clocks.DAYTIME.isoformat() + assert [c["arguments"] for c in WORDS["station"]] == STATION_CASES and [c["arguments"] for c in WORDS["air"]] == AIR_CASES + for cases, back in ((WORDS["station"], 80), (WORDS["air"], AIR_DAYS + 10)): + for case in cases: + out = await ask(pinned_world, start=str(ago(back)), end=str(ago(2)), **case["arguments"]) + assert {k: v for k, v in out.items() if k not in ("period", "as_of")} == case["result"], case["arguments"] + + +@pytest.mark.parametrize("case", WORDS["answer_lines"], ids=["count", "averaged", "total-rain", "highest-uv", "no-value", "no-condition"]) +def test_the_answer_line_is_the_bots_days_lookup_word_for_word(case): + data = case["data"] + assert days_tool.answer_line({k: v for k, v in data.items() if k != "period"}, data["period"]) == case["answer"] + + +# ---------- the answer line ---------- +def test_the_answer_line_says_the_count_and_the_period(): + data = {"period": "Tue 29 Sep 2026 - Tue 6 Oct 2026", "days_checked": 1454, "matching_days": 137, "condition": "UV index ≥ 10"} + assert days_tool.answer_line(data, data["period"]) == "137 of 1,454 days with UV index ≥ 10 (Tue 29 Sep – Tue 6 Oct 2026)." + night, three = parse_stretch("night"), parse_stretch("15:00") + assert days_tool.answer_line(data, data["period"], night).startswith("Each night (22:00–06:00): 137 of 1,454 days") + assert days_tool.answer_line(data, data["period"], three).startswith("Each day at 15:00: 137 of") + assert days_tool.answer_line(data, data["period"], parse_stretch("15:00-16:00")).startswith("Each day 15:00–16:00: 137 of") + + +# ---------- refusals ---------- +async def test_a_call_it_cant_use_is_refused_with_what_to_send_instead(world): + bad = await ask(world, where=[{"field": "temperature", "op": ">", "value": 30}]) + assert "Did you mean temp_max, temp_min, temp_avg?" in bad["error"] and "pm2_5_max" in bad["fields"] + assert "pm2_5_max, pm2_5_min, pm2_5_avg" in (await ask(world, sort_by="pm2.5"))["error"] + assert (await ask(world, where=[{"field": "rain", "op": "gt", "value": 1}]))["ops"] == [">", ">=", "<", "<=", "="] + assert "a number" in (await ask(world, where=[{"field": "rain", "op": ">", "value": "lots"}]))["error"] + assert "rain" in (await ask(world, where=["rain > 1"]))["error"] + assert "needs `of`" in (await ask(world, stat="sum"))["error"] + assert "month or year" in (await ask(world, group_by="week"))["error"] + assert "desc" in (await ask(world, order="up"))["error"] + assert "public_holiday or weekend" in (await ask(world, only="holiday"))["error"] + old = await ask(world, start_date="2026-01-01", end_date="2026-01-31") + assert "`start_date` is `start`" in old["error"] and "period" in old["arguments"] + hours = await ask(world, hours="dawn") + assert "isn't a part of the day" in hours["error"] or "not a part of the day" in hours["error"] + assert "night (22:00-06:00)" in hours["hours"] + assert "use forecast" in (await ask(world, period="next week"))["error"] + forms = await ask(world, period="the other week") + assert "isn't a period" in forms["error"] and "on record, all time, ever (from the first reading held)" in forms["forms"] + assert "today" not in forms["forms"] # (a whole-day tool lists only the forms it reads) + long = await ask(world, hours="night", period="on record") + assert "at most 400 days" in long["error"] and long["fits"] == "past year" + no_air = days_tool.tools(Context(eco=world.eco))[0] + refused = json.loads(await no_air.call({"where": [{"field": "pm2_5_max", "op": ">", "value": 1}]})) + assert "this service has no air sensor" in refused["error"] + + +async def test_a_part_of_today_is_refused_pointing_to_the_tools_that_read_one(world): + """Whole days only: today isn't over. At 2:05pm each part of today asked for points to summary or readings.""" + ctx = dataclasses.replace(world, clock=yesterday_at(14, 5, TZ).timestamp) + for words in ("today", "last 5 hours", "this morning"): + assert "use summary or readings" in (await ask(ctx, period=words))["error"], words + + +async def test_just_after_midnight_this_morning_is_still_ahead_and_points_to_forecast(world): + """At 12:05am "today" and "last 5 hours" still point to summary or readings, but this morning (6am to 12pm) hasn't begun: it is + refused as in the future, pointing to forecast, with the time now.""" + ctx = dataclasses.replace(world, clock=yesterday_at(0, 5, TZ).timestamp) + for words in ("today", "last 5 hours"): + assert "use summary or readings" in (await ask(ctx, period=words))["error"], words + error = (await ask(ctx, period="this morning"))["error"] + assert "'this morning' is in the future" in error and "use forecast" in error and error.endswith("12:05am.") + + +async def test_a_period_before_the_record_says_where_the_record_starts(world): + first = await world.storage.read(lambda r: min(date.fromisoformat(d) for (d,) in r.db.execute("SELECT day FROM air_day"))) + out = await ask(world, start=str(first - timedelta(days=30)), end=str(first - timedelta(days=1)), sort_by="pm2_5_max") + assert out["days_checked"] == 0 and out["note"] == f"No readings are held for this period: the record of what was asked about " \ + f"starts {day_text(first)}." + assert out["answer"].startswith("0 of 0 days (") and "days" in out and out["days"] == [] + + +async def test_the_holiday_and_weekend_filter_is_the_models_own(world): + out = await ask(world, period="last 8 weeks", only="weekend", limit=20) + days = [datetime.strptime(r["date"], "%a %d %b %Y").date() for r in out["days"]] + assert out["days_checked"] == 16 and all(d.weekday() >= 5 for d in days) + holidays = await ask(world, period="past year", only="public_holiday", sort_by="rain") + assert 5 <= holidays["days_checked"] <= 18 and all(r["holiday"] for r in holidays["days"]) # (two Easters, some years) + + +# ---------- both sensors ---------- +async def test_a_question_over_both_sensors_counts_the_days_both_have(world): + first, last = ago(AIR_DAYS + 10), ago(2) + where = [{"field": "rain", "op": ">=", "value": 1}, {"field": "pm2_5_max", "op": ">", "value": 10}] + out = await ask(world, start=str(first), end=str(last), where=where, sort_by="temp_max", limit=20) + days = [first + timedelta(days=k) for k in range((last - first).days + 1)] + both = [d for d in days if d >= ago(AIR_DAYS)] + wet = [d for d in both if truth(d)[1] >= 1 and max(pm(t) for t in range(*day_bounds(d, TZ), 300)) > 10] + assert out["days_checked"] == len(both) and out["matching_days"] == len(wet) + assert sorted(r["date"] for r in out["days"]) == sorted(label(d) for d in wet) + assert [r["temp_max"] for r in out["days"]] == sorted((r["temp_max"] for r in out["days"]), reverse=True) + assert out["units"] == {"temp_max": "°C", "temp_min": "°C", "rain": "mm", "pm2_5_max": "µg/m³"} # both sensors' shown fields + row = out["days"][0] + assert row["source"] == {"station": "exact", "air": "exact"} and row["day_look"]["word"] in ("wet", "showery", "stormy") + assert out["condition"] == "rain ≥ 1 mm and PM2.5 > 10 µg/m³" and out["note_missing"].startswith("10 day(s)") + when = days_tool.period_words(f"{day_text(first)} - {day_text(last)}") + assert out["answer"] == f"{len(wet)} of {len(both)} days with rain ≥ 1 mm and PM2.5 > 10 µg/m³ ({when})." + + +async def test_days_whose_station_figures_are_daily_records_are_left_out_of_a_mixed_question_and_counted(world): + first, last = ago(OLD_AIR[0]), ago(OLD_AIR[1]) + out = await ask(world, start=str(first), end=str(last), where=[{"field": "pm2_5_max", "op": ">", "value": 0}], sort_by="rain") + assert out["days_checked"] == 0 and out["daily_left_out"] == OLD_AIR[0] - OLD_AIR[1] + 1 + assert "daily records, which run 1" in out["note_daily_left_out"] and "note_daily" not in out and "note" in out + alone = await ask(world, start=str(first), end=str(last), where=[{"field": "pm2_5_max", "op": ">", "value": 0}]) + assert alone["days_checked"] == OLD_AIR[0] - OLD_AIR[1] + 1 and "note_hourly" in alone # the air sensor alone: every day + assert all(r["source"] == "hourly" for r in alone["days"]) + + +# ---------- part of each day ---------- +async def test_hours_works_out_each_days_figures_over_the_stretch(world): + afternoon = await ask(world, hours="afternoon", period="last 30 days", where=[{"field": "rain", "op": ">=", "value": 1}], + sort_by="rain", limit=20) + morning = await ask(world, hours="morning", period="last 30 days", where=[{"field": "rain", "op": ">", "value": 0}]) + whole = await ask(world, period="last 30 days", where=[{"field": "rain", "op": ">=", "value": 1}], limit=20) + assert morning["matching_days"] == 0 # the fake's rain falls from 2pm + assert afternoon["matching_days"] == whole["matching_days"] > 0 # ... all of it in the afternoon + assert {r["date"]: r["rain"] for r in afternoon["days"]} == {r["date"]: r["rain"] for r in whole["days"]} + assert afternoon["hours"]["text"] == "afternoon (12:00–18:00)" and "mm that fell in it" in afternoon["hours"]["how_to_read"] + assert afternoon["answer"].startswith("Each afternoon (12:00–18:00): ") + assert afternoon["period"]["asked"] == "last 30 days" + + +async def test_a_moment_is_the_reading_at_that_time_each_day(world): + out = await ask(world, hours="15:00", start=str(ago(10)), end=str(ago(2)), stat="avg", of="temp_avg") + at_three = [round(temp(local_epoch(datetime.combine(d, time(15)), TZ)), 1) for d in (ago(n) for n in range(2, 11))] + assert out["days_checked"] == 9 and out["value"] == round(sum(at_three) / len(at_three), 1) + assert out["answer"] == f"Each day at 15:00: Average temperature: {out['value']:g} °C over 9 days " \ + f"({days_tool.period_words(f'{day_text(ago(10))} - {day_text(ago(2))}')})." + + +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) + + +async def test_a_whole_day_stretch_gives_the_day_rows_figures_and_leaves_out_days_held_only_as_daily_records(world): + first, last = ago(374), ago(356) # across the start of the station's 30-minute archive: every day listed + args = {"start": str(first), "end": str(last), "sort_by": "temp_max", "limit": 20, "where": [{"field": "rain", "op": ">=", "value": 0}]} + whole, stretch = await ask(world, **args), await ask(world, hours="00:00-24:00", **args) + figures = lambda rows: {r["date"]: (r["temp_max"], r["temp_min"], r["rain"]) for r in rows} + exact = figures(r for r in whole["days"] if r["source"] == "exact") + assert whole["days_checked"] == 19 and 0 < len(exact) < 19 + assert figures(stretch["days"]) == exact and stretch["days_checked"] == len(exact) + assert stretch["left_out"] == {"not held finely enough": 19 - len(exact)} and "note_left_out" in stretch and "note_daily" not in stretch + assert stretch["hours"]["text"] == "00:00–24:00" + + +# ---------- charts ---------- +def chart_of(out: dict) -> dict: + (chart,) = out["charts"] + return chart + + +async def test_a_figure_per_month_is_drawn_and_its_drawn_by_redraws_it_over_each_period_it_lists(world): + out = await ask(world, period="last 6 months", stat="sum", of="rain", group_by="month", chart_answers_it=True) + chart = chart_of(out) + assert out["chart_note"] == CHART_NOTE and "chart" not in out and out["by_month"] + assert chart["title"] == "Total rain" and chart["source"] == "Ecowitt weather station" + assert schema_errors(chart) == [] + drawn = chart["drawn_by"] + assert drawn == {"tool": "days", "arguments": {"where": [], "sort_by": "rain", "order": "desc", "count_only": False, "group_by": "month", + "stat": "sum", "of": "rain", "limit": 5, "period": "last 6 months", "chart_answers_it": True}, + "periods": [{"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}, {"period": "on record", "label": "All"}]} + again = await ask(world, **drawn["arguments"]) + assert chart_of(again) == chart + for p in drawn["periods"]: + redrawn = await ask(world, **{**drawn["arguments"], "period": p["period"]}) + assert "error" not in redrawn and chart_of(redrawn)["drawn_by"]["arguments"]["period"] == p["period"], p + assert chart_of(redrawn)["title"] == chart["title"] + assert out["reply"] == out["answer"] and out["complete"] is True # the chart is the whole answer (3.7) + assert out["answer"].startswith("Total rain: ") and " mm over 182 days (" in out["answer"] + + +async def test_a_chart_drawn_with_dates_names_them_as_its_period_and_per_year_it_lists_no_other(world): + out = await ask(world, start=str(ago(200)), end=str(ago(2)), where=[{"field": "rain", "op": ">=", "value": 1}], group_by="year") + drawn = chart_of(out)["drawn_by"] + assert drawn["arguments"]["period"] == f"{ago(200).isoformat()} to {ago(2).isoformat()}" and drawn["periods"] == [] + assert chart_of(await ask(world, **drawn["arguments"])) == chart_of(out) + assert "complete" not in out # (chart_answers_it wasn't set) + for end in ({}, {"end": str(ago(-3))}): # a start with no end, or an end today or later: "to now", so a replay moves on with the clock + drawn = chart_of(await ask(world, start=str(ago(200)), where=[{"field": "rain", "op": ">=", "value": 1}], group_by="year", **end))["drawn_by"] + assert drawn["arguments"]["period"] == f"{ago(200).isoformat()} to now" + + +async def test_a_period_sent_with_start_and_end_beside_it_wins_and_its_chart_is_drawn_by_the_words(world): + # the live evals: period with start 'count_only', end 'cancel' (a model filling in every argument) + out = await ask(world, period="last 30 days", start="count_only", end="cancel", where=[{"field": "rain", "op": ">=", "value": 1}], + group_by="month") + assert "error" not in out and out["period"]["asked"] == "last 30 days" and "were ignored" in out["period"]["note"] + assert chart_of(out)["drawn_by"]["arguments"]["period"] == "last 30 days" + noted = await ask(world, period="last 30 days", start="count_only", where=[{"field": "rain", "op": ">=", "value": 1}], + group_by="month", chart_answers_it=True) + assert "charts" in noted and noted["period"]["note"] and "complete" not in noted and "reply" not in noted # the model reads it + other = await ask(world, period="on record", start=str(ago(20)), sort_by="rain") + assert "but `start`/`end` say" in other["error"] # real dates that disagree: refused, naming both + + +async def test_a_chart_is_not_the_whole_answer_when_a_note_needs_the_models_words(world): + out = await ask(world, period="on record", stat="max", of="temp_max", group_by="month", chart_answers_it=True) + assert "charts" in out and "note_daily" in out and "complete" not in out and "reply" not in out + averaged = await ask(world, period="last 6 months", where=[{"field": "humidity_max", "op": ">", "value": 70}], group_by="month", + chart_answers_it=True) + assert "note_averaged" in averaged and averaged["complete"] is True # (the answer line says it) + assert averaged["reply"].endswith("Older days use averages, so a count near the limit may fall slightly short.") + plain = await ask(world, period="past year", where=[{"field": "rain", "op": ">=", "value": 1}], chart_answers_it=True) + assert "charts" not in plain and "complete" not in plain # no chart, nothing complete + + +async def test_a_chart_of_part_of_each_day_lists_the_whole_record_only_while_it_is_within_400_days(world): + out = await ask(world, hours="night", period="3m", where=[{"field": "temp_min", "op": "<", "value": 12}], group_by="month") + drawn = chart_of(out)["drawn_by"] + assert drawn["arguments"]["hours"] == "night" and [p["period"] for p in drawn["periods"]] == ["3m", "1y"] # (548 days held) + assert "night (22:00–06:00)" in chart_of(out)["subtitle"] + for p in drawn["periods"]: + assert "error" not in await ask(world, **{**drawn["arguments"], "period": p["period"]}) + air = await ask(world, hours="afternoon", period="last 30 days", stat="avg", of="pm2_5_avg", group_by="month") + assert [p["period"] for p in chart_of(air)["drawn_by"]["periods"]] == ["3m", "1y", "on record"] # the air sensor's record is short + assert chart_of(air)["source"] == "AirGradient sensor" + for p in chart_of(air)["drawn_by"]["periods"]: + assert "error" not in await ask(world, **{**chart_of(air)["drawn_by"]["arguments"], "period": p["period"]}) + + +async def test_charts_are_sent_to_the_requests_budget(world): + args = {"period": "on record", "stat": "sum", "of": "rain", "group_by": "month"} + assert chart_of(await ask(world, {"chart_points": 500}, **args)) == chart_of(await ask(world, **args)) # (bars aren't bucketed) + both = await ask(world, period="last 30 days", where=[{"field": "rain", "op": ">=", "value": 0}, + {"field": "pm2_5_max", "op": ">", "value": 0}], group_by="month") + assert chart_of(both)["source"] == "Ecowitt weather station and AirGradient sensor" + replay = copy.deepcopy(chart_of(both)["drawn_by"]["arguments"]) + assert chart_of(await ask(world, **replay)) == chart_of(both) + + +async def test_one_figure_over_months_says_how_to_get_one_per_month_or_year(world): + """A stat or a count over more than a month with no group_by is one figure; the result says how to get one per month or year, so a + model that left group_by out ("rain per month") calls again, and it is never the whole answer.""" + from lib.service.days import GROUP_BY_NOTE + whole = await ask(world, stat="sum", of="rain", period="last 90 days", chart_answers_it=True) + assert whole["note_group_by"] == GROUP_BY_NOTE and "complete" not in whole + assert "note_group_by" not in await ask(world, stat="sum", of="rain", period="last 90 days", group_by="month") + assert "note_group_by" not in await ask(world, stat="sum", of="rain", period="last 7 days") # (a week: one figure is the answer) + counted = await ask(world, where=[{"field": "rain", "op": ">=", "value": 1}], count_only=True, period="last 90 days") + assert counted["note_group_by"] == GROUP_BY_NOTE + + +async def test_of_without_stat_is_refused_saying_to_send_stat_not_counted_as_days(world): + """`of` with no `stat` used to count the days and drop `of` ("rain per month" answered "313 of 313 days"); it is refused, saying + to send stat too, so a model corrects it in its next call.""" + out = await ask(world, of="rain", group_by="month", period="past year") + assert "error" in out and "send `stat` too" in out["error"] and "sum" in out["error"] + fixed = await ask(world, stat="sum", of="rain", group_by="month", period="past year") + assert "error" not in fixed and fixed["answer"].startswith("Total rain") + assert "error" not in await ask(world, where=[{"field": "rain", "op": ">=", "value": 1}], period="past year") # (a count: no `of`) diff --git a/tests/test_service_evals.py b/tests/test_service_evals.py new file mode 100644 index 00000000..cd030a19 --- /dev/null +++ b/tests/test_service_evals.py @@ -0,0 +1,585 @@ +"""The saved questions in service terms (tests/evals/service_cases.json): what a model given only the service's ten tools should call for +every case in cases.json, checked without a model. Every case has an expectation; every tool in it is one of the ten; every call it +describes, made concrete, is one the real tool answers rather than refuses; the tool list itself is one any model can read. (What a +real model does with the ten is `scripts/eval_prompts.py --live --service`; its plumbing is tested here with a scripted model.) + +The expectations are written for evalkit.NOW (Tue 29 Sep 2026 14:05), and a period is matched by what it means then ({"means"}), sent +in words or as start and end. The real tools are called with the clock fixed at that time (at_eval_now) over the fake station built +under it, so that check is of the arguments being taken (names, words, forms, start and end), not of the figures, and holds on any +real date.""" + +import asyncio +import json +import os +import shutil +import subprocess +import sys +from datetime import datetime +from pathlib import Path +from types import SimpleNamespace as NS + +import pytest + +from lib.service.context import Context +from tests import evalkit, evalworld +from tests.fakes import TZ + +CASES = evalkit.load_cases() +EXPECT = evalkit.load_service_cases() +ROOT = Path(__file__).resolve().parent.parent + + +# ---------- the expectations ---------- +def test_every_case_has_a_service_expectation_and_no_other_id_does(): + ids = [c.id for c in CASES] + assert [i for i in ids if i not in EXPECT] == [] and [i for i in EXPECT if i not in ids] == [] + assert list(EXPECT) == ids # (kept in cases.json's order, so the two files read side by side) + + +@pytest.mark.parametrize("case", CASES, ids=[c.id for c in CASES]) +def test_each_expectation_names_only_the_ten_tools_and_their_own_arguments(case): + expect = EXPECT[case.id] + assert evalkit.service_problems(expect) == [] + assert expect.get("note"), "say why: the expectation is a reading of the question and of 3.3's routing rules" + for name, args in evalkit.example_calls(expect): # each concrete call passes the checker it was made from + assert evalkit.check_calls([(name, args)], {"args": {name: expect.get("args", {}).get(name, {})}}) == [], (name, args) + + +def test_the_checker_reads_names_words_and_periods_as_the_service_does(): + check = evalkit.check_args + assert check({"readings": ["temperature"]}, {"readings": {"reads": ["outdoor.temperature"]}}) == [] + assert check({"readings": "outdoor humidity"}, {"readings": {"reads": ["outdoor.humidity"], "not": ["outdoor.temperature"]}}) == [] + assert check({"readings": ["humidity", "temp"]}, {"readings": {"reads": ["outdoor.humidity"], "not": ["outdoor.temperature"]}}) + assert check({"readings": ["airgradient humidity"]}, {"readings": {"reads": ["air.humidity"]}}) == [] + assert check({"chart_readings": ["air.pm2_5:rating"]}, {"chart_readings": {"reads": ["air.pm2_5"]}}) == [] + assert "lacks" in check({"readings": ["pressure"]}, {"readings": {"reads": ["rainfall.rain"]}})[0] + assert check({"readings": ["lightning"]}, {"readings": {"reads": ["rainfall.rain"]}}) # (not a reading: refused, so a failure) + assert check({}, {"readings": {"reads": ["outdoor.temperature"], "optional": True}}) == [] + assert check({}, {"readings": {"reads": ["outdoor.temperature"]}}) == ["readings: no readings sent"] + assert check({"readings": ["rain rate"]}, {"readings": {"reads_any": ["rainfall.rain", "rainfall.rain_rate"]}}) == [] + # periods: the same span at NOW (Tue 29 Sep 2026 14:05), whatever the words + for same in ("this week", "past week", "7d", "last 7 days", "the last week", "1w"): + assert check({"period": same}, {"period": {"means": "this week"}}) == [], same + assert check({"period": "last week"}, {"period": {"means": "this week"}}) # (the previous Monday to Sunday) + assert check({"period": "3 months"}, {"period": {"means": "3m"}}) == [] and check({"period": "3d"}, {"period": {"means": "3m"}}) + assert check({"period": "all time"}, {"period": {"means": "on record"}}) == [] + assert check({"period": "Tuesday"}, {"period": {"means": ["Tuesday", "today"]}}) == [] + assert "can't be read" in check({"period": "sometime"}, {"period": {"means": "today"}})[0] + assert check({"x": 1}, {"x": {"one_of": [1, 2]}}) == [] and check({"x": 3}, {"x": {"one_of": [1, 2]}}) + + +def test_a_condition_list_is_matched_by_its_keys_and_numbers_not_its_spelling(): + check = evalkit.check_args + want = {"where": {"conditions": [{"field": "uv_max", "op": [">=", ">"], "value": 9}]}} + for same in ([{"field": "uv_max", "op": ">=", "value": 9}], [{"value": 9, "op": ">=", "field": "uv_max"}], + [{"field": "uv_max", "op": ">=", "value": 9.0}], [{"field": "uv_max", "op": "≥", "value": "9"}], + [{"field": " uv_max", "op": "=>", "value": 9, "note": "after value"}], {"field": "uv_max", "op": ">", "value": 9}): + assert check({"where": same}, want) == [], same + for wrong in ([{"field": "uv_avg", "op": ">=", "value": 9}], [{"field": "uv_max", "op": "<", "value": 9}], + [{"field": "uv_max", "op": ">=", "value": 10}], [{"field": "uv_max", "op": ">=", "value": "nine"}], + [{"field": "uv_max", "op": ">=", "value": True}], [{"field": "uv_max", "op": ">="}], [], None, "uv_max >= 9", + [{"field": "uv_max", "op": ">=", "value": 9}, {"field": "rain", "op": ">=", "value": 1}]): + assert check({"where": wrong}, want), wrong + two = {"where": {"conditions": [{"field": "temp_max", "op": [">", ">="], "value": 35}, {"field": "rain", "op": [">", ">="]}]}} + assert check({"where": [{"op": ">", "value": 0.2, "field": "rain"}, {"field": "temp_max", "value": 35.0, "op": "≥"}]}, two) == [] + assert check({"where": [{"field": "temp_max", "op": ">", "value": 35}]}, two) # (the rain condition missing) + either = {"where": {"conditions": [{"field": ["pm2_5_max", "pm2_5_avg"], "op": [">"], "value": 25}]}} + assert check({"where": [{"field": "pm2_5_avg", "op": ">", "value": 25}]}, either) == [] + assert evalkit.example_value(two["where"]) == [{"field": "temp_max", "op": ">", "value": 35}, {"field": "rain", "op": ">", "value": 1}] + + +def test_every_where_is_matched_as_conditions_so_a_correct_call_in_any_key_order_passes(): + wheres = {cid: w for cid, expect in EXPECT.items() for alternatives in expect.get("args", {}).values() + for alt in (alternatives if isinstance(alternatives, list) else [alternatives]) if (w := alt.get("where"))} + assert wheres and all(set(w) <= {"conditions", "e.g."} and "conditions" in w for w in wheres.values()), wheres + for cid in ("uv-days-two-years", "uv-days-per-year", "days-over-limit-by-year", "air-days-per-year", "count-pm25-days-per-year", + "days-two-readings-go-to-the-model", "hottest-day-that-rained", "rainy-days-in-september"): + (name, args), *_ = evalkit.example_calls(EXPECT[cid]) + backwards = {**args, "where": [{"note": "x", **dict(reversed(list(c.items())))} for c in args["where"]]} + assert evalkit.check_calls([(name, backwards)], EXPECT[cid]) == [], cid + + +def test_a_period_sent_as_start_and_end_is_matched_by_what_it_means_as_the_tool_reads_it(): + check = evalkit.check_calls + # days reads whole days to yesterday: September from its first day is the month to the 28th, as "September" is + assert check([("days", {"start": "2026-09-01"})], {"args": {"days": {"period": {"means": "September"}}}}) == [] + assert check([("days", {"start": "2026-09-01", "end": "2026-09-28"})], {"args": {"days": {"period": {"means": "this month"}}}}) == [] + assert check([("days", {"start": "2026-08-01"})], {"args": {"days": {"period": {"means": "September"}}}}) + # summary reads to the minute: one day is that day's start and end; a start alone runs to now + assert check([("summary", {"start": "2026-06-11", "end": "2026-06-11"})], {"args": {"summary": {"period": {"means": "11 June"}}}}) == [] + assert check([("summary", {"start": "2026-06-11"})], {"args": {"summary": {"period": {"means": "11 June"}}}}) + assert check([("readings", {"start": "2026-09-29"})], {"args": {"readings": {"period": {"means": "today"}}}}) == [] + assert "no period sent" in check([("days", {})], {"args": {"days": {"period": {"means": "September"}}}})[0] + assert check([("days", {})], {"args": {"days": {"period": {"means": "on record", "optional": True}}}}) == [] + for cid, call in (("most-rain-days-jja", ("days", {"sort_by": "rain", "start": "2026-06-01", "end": "2026-08-31"})), + ("rainy-days-in-september", ("days", {"where": [{"field": "rain", "op": ">=", "value": 1}], "start": "2026-09-01"})), + ("rain-on-a-named-day", ("days", {"start": "2026-09-05", "end": "2026-09-05"})), + ("weather-on-june-11", ("summary", {"start": "2026-06-11", "end": "2026-06-11"})), + ("temperature-every-30-minutes", + ("readings", {"reading": "temperature", "interval": "30min", "start": "2026-09-29"}))): + assert check([call], EXPECT[cid]) == [], cid + + +def test_the_whole_day_tools_are_those_whose_period_is_described_as_whole_days(): + tools = {t.name: t for t in evalkit.service_tools()} + assert evalkit.WHOLE_DAY_TOOLS == {n for n, t in tools.items() if "Whole days only" in t.parameters.get("properties", {}) + .get("period", {}).get("description", "")} + + +def test_a_hottest_day_of_a_period_may_be_found_by_days_as_well(): + for cid, period in (("think-hottest-week", "this week"), ("hottest-coldest-this-month", "this month")): + assert evalkit.check_calls([("days", {"sort_by": "temp_max", "period": period})], EXPECT[cid]) == [], cid + assert evalkit.check_calls([("days", {"period": period})], EXPECT[cid]) == [], cid + + +def test_alternatives_pass_when_any_one_does(): + expect = {"args": {"days": [{"period": {"means": "September"}}, {"start": "2026-09-01"}]}} + assert evalkit.check_calls([("days", {"period": "this month"})], expect) == [] + assert evalkit.check_calls([("days", {"start": "2026-09-01"})], expect) == [] + fails = evalkit.check_calls([("days", {"period": "August"})], expect) + assert len(fails) == 1 and "| or:" in fails[0] + + +# ---------- the tool list a model is offered ---------- +def test_the_tool_list_is_the_ten_service_tools_with_their_own_descriptions_and_schemas(): + built = evalkit.service_tools() + assert [t.name for t in built] == evalkit.service_tool_names() + offered = evalkit.make_service_tools([]) + assert set(offered.by_name) == set(evalkit.service_tool_names()) + for tool, schema in zip(built, offered.schemas): + assert schema == {"type": "function", "function": {"name": tool.name, "description": tool.description, + "parameters": tool.parameters}} + + +JSON_TYPES = {"object", "array", "string", "number", "integer", "boolean", "null"} + + +def schema_problems(schema, where: str) -> list[str]: + """What isn't JSON Schema as function-calling APIs read it: a type each, a description on each property, enums of the type's values, + `required` naming properties, items for an array.""" + out = [] + kind = schema.get("type") + if kind not in JSON_TYPES: + out.append(f"{where}: type {kind!r}") + if kind == "object": + props = schema.get("properties") + if not isinstance(props, dict): + out.append(f"{where}: an object needs properties") + props = {} + out += [f"{where}: required {r!r} is no property" for r in schema.get("required", []) if r not in props] + for name, prop in props.items(): + out += schema_problems(prop, f"{where}.{name}") + if kind == "array": + out += schema_problems(schema["items"], f"{where}[]") if isinstance(schema.get("items"), dict) else [f"{where}: no items"] + if "enum" in schema: + py = {"string": str, "integer": int, "number": (int, float)}.get(kind, object) + if not schema["enum"] or not all(isinstance(v, py) for v in schema["enum"]) or len(set(schema["enum"])) != len(schema["enum"]): + out.append(f"{where}: enum {schema['enum']!r}") + if extra := set(schema) - {"type", "properties", "required", "items", "enum", "description", "additionalProperties"}: + out.append(f"{where}: unknown keys {sorted(extra)}") + return out + + +@pytest.mark.parametrize("name", evalkit.service_tool_names()) +def test_each_description_is_short_and_each_schema_is_json_schema(name): + (tool,) = [t for t in evalkit.service_tools() if t.name == name] + assert 0 < len(tool.description) < 1500 + assert tool.parameters.get("type") == "object" and schema_problems(tool.parameters, name) == [] + json.dumps(tool.parameters) # (serialisable as it is) + for prop_name, prop in tool.parameters.get("properties", {}).items(): + if "properties" not in prop: # (a condition's own fields are described by the array that holds them) + assert prop.get("description"), f"{name}.{prop_name} has no description" + + +# ---------- every expected call is one the real tool answers ---------- +# At the evals' NOW (Tue 29 Sep 2026 14:05, Melbourne), whatever the real date: the expectations are written for it ("this month" is +# September to the 28th, "June to August 2026" is in the fake's history). Every datetime.now(), date.today() and time.time() in lib/ +# and tests/ reads it, and the fake station's archive is built under it (the idea of tests/test_service_switch.py's freeze, kept here). +EVAL_NOW = evalworld.EVAL_NOW + + +def at_eval_now(patch: pytest.MonkeyPatch): + """evalworld.at_eval_now, this module included (whatever pytest names it).""" + evalworld.at_eval_now(patch, __name__) + + +@pytest.fixture(scope="module") +def eval_archive(shared_archive): + """The fake station's whole archive (its ecobot.sqlite) built at EVAL_NOW, the air's month held in it too (real_context), once for every + worker and run (tests/evalworld.py's).""" + return evalworld.shared_eval_archive(shared_archive) + + +def calls_for(tool: str) -> list[tuple[str, dict]]: + return [(cid, args) for cid, expect in EXPECT.items() for name, args in evalkit.example_calls(expect) if name == tool] + + +async def real_context(tmp_path, archive) -> Context: + return await evalworld.real_context(tmp_path, archive) + + +@pytest.mark.parametrize("tool", evalkit.service_tool_names()) +async def test_every_expected_call_is_answered_not_refused(tool, tmp_path, eval_archive, monkeypatch): + calls = calls_for(tool) + if not calls: + pytest.skip(f"no case expects {tool}") + at_eval_now(monkeypatch) + assert datetime.now(TZ).strftime("%a %d %b %Y %H:%M") == "Tue 29 Sep 2026 14:05" + ctx = await real_context(tmp_path, eval_archive) + try: + (service_tool,) = [t for t in evalkit.service_tools(ctx) if t.name == tool] + refused = {} + for case_id, args in calls: + out = json.loads(await service_tool.call(args)) + if "error" in out: + refused[case_id] = (args, out["error"]) + assert refused == {}, json.dumps(refused, indent=1, ensure_ascii=False) + finally: + await evalworld.close(ctx) + + +# ---------- the live run, with a scripted model ---------- +class ScriptedModel: + """An OpenAI-style client whose answers are scripted per question: {question: [(tool, args), ...] or a text}. Each question gets its + calls, then a one-line reply. Every request is kept.""" + + def __init__(self, script: dict): + self.script, self.requests = script, [] + self.chat = NS(completions=NS(create=self.create)) + + async def create(self, **kw): + self.requests.append(kw) + asked = next(m["content"] for m in reversed(kw["messages"]) if m["role"] == "user") + answered = kw["messages"][-1]["role"] == "tool" + step = "Done." if answered else self.script.get(asked, "Nothing to look up.") + calls = None if isinstance(step, str) else [NS(id=f"c{i}", function=NS(name=n, arguments=json.dumps(a))) + for i, (n, a) in enumerate(step)] + msg = NS(content=step if isinstance(step, str) else "", tool_calls=calls) + return NS(choices=[NS(message=msg)], usage=None) + + +def case(case_id: str): + return next(c for c in CASES if c.id == case_id) + + +async def test_a_live_service_run_offers_the_ten_tools_alone_with_no_prompt_of_ours_and_scores_the_calls(): + picked = [case("3m-average"), case("will-it-rain"), case("hello"), case("pushback-cooler-this-week")] + model = ScriptedModel({"average temp 3m": [("summary", {"readings": ["temperature"], "period": "last 3 months", "average": True})], + "will it rain later?": [("forecast", {})], # wrong: outlook + "Wrong. It was cooler this week": [("summary", {"period": "past week"})]}) + lines = [] + failed = await evalkit.run_service(picked, EXPECT, model, "m", out=lines.append) + assert failed == 1 + text = "\n".join(lines) + assert "1/1 3m-average" in text and "0/1 FAIL will-it-rain" in text and "did not call outlook (called: forecast)" in text + assert "1/1 hello" in text and "1/1 pushback-cooler-this-week" in text + assert text.endswith("3 of 4 cases pass (the service's ten tools alone)") + first = model.requests[0] + assert [t["function"]["name"] for t in first["tools"]] == evalkit.service_tool_names() + assert first["tool_choice"] == "auto" and first["extra_body"] == {"reasoning": {"effort": evalkit.SERVICE_EFFORT}} + system = first["messages"][0] + assert system == {"role": "system", "content": evalkit.service_system()} + assert system["content"] == ("You answer questions about a home weather station and air sensor using the tools.\n" + "Now: Tuesday 29 September 2026, 14:05 (Australia/Melbourne time).") + assert first["messages"][1:] == [{"role": "user", "content": "average temp 3m"}] + follow_up = next(r for r in model.requests if r["messages"][-1].get("content") == "Wrong. It was cooler this week") + assert [m["role"] for m in follow_up["messages"]] == ["system", "user", "assistant", "user"] # (the case's history, as it was) + assert 'called: forecast {}' in text # a run that fails shows what was called + + +async def test_with_the_instructions_the_system_line_carries_the_servers_instructions_after_the_neutral_line(): + from lib.service.instructions import instructions + model = ScriptedModel({"average temp 3m": [("summary", {"readings": ["temperature"], "period": "last 3 months", "average": True})]}) + lines = [] + told = evalkit.service_instructions() + assert told == instructions(evalkit.eval_context()) and "AirGradient" in told and "Australia/Melbourne" in told + assert await evalkit.run_service([case("3m-average")], EXPECT, model, "m", instructions=told, out=lines.append) == 0 + system = model.requests[0]["messages"][0]["content"] + assert system == evalkit.service_system(instructions=told) == f"{evalkit.service_system()}\n\n{told}" + assert system.startswith(evalkit.SERVICE_SYSTEM) and lines[-1].endswith("(the service's ten tools alone, with its instructions)") + assert [t["function"]["name"] for t in model.requests[0]["tools"]] == evalkit.service_tool_names() # (the same tools) + + +async def test_without_a_model_the_service_run_checks_only_the_expectations(): + lines = [] + assert await evalkit.run_service(CASES, EXPECT, out=lines.append) == 0 + assert lines[-1] == f"\n{len(CASES)} of {len(CASES)} cases pass (the service's ten tools alone)" + assert await evalkit.run_service([case("hello")], {}, out=lines.append) == 1 and "no service expectation" in lines[-2] + + +def script(*args: str, key: str | None = None) -> subprocess.CompletedProcess: + env = {k: v for k, v in os.environ.items() if not k.startswith("OPENROUTER_")} + if key: + env["OPENROUTER_API_KEY"] = key + return subprocess.run([sys.executable, str(ROOT / "scripts" / "eval_prompts.py"), *args], capture_output=True, text=True, env=env, + cwd=ROOT, timeout=120) + + +def test_the_script_runs_the_service_evals_offline_and_needs_a_key_to_ask_a_model(): + run = script("--service", "--ids", "3m-average,hello") + assert run.returncode == 0 and "2 of 2 cases pass (the service's ten tools alone)" in run.stdout + run = script("--live", "--service") + assert run.returncode != 0 and "--live needs OPENROUTER_API_KEY" in run.stderr + run = script("--service", "--instructions", "--ids", "hello") # (offline it checks the expectations, as without) + assert run.returncode == 0 and "1 of 1 cases pass (the service's ten tools alone, with its instructions)" in run.stdout + run = script("--instructions") + assert run.returncode != 0 and "--instructions goes with --service" in run.stderr + + +def test_a_rolling_period_in_words_is_not_a_month_that_its_days_happen_to_cover(): + """A period sent in words is read as words: "last 28 days" is not "September", though on the 29th its whole days to yesterday are + 1 to 28 September; start and end are still read in whole days as days reads them.""" + from tests import evalkit as ek + for words in ("last 28 days", "4w", "past 4 weeks"): + assert ek._means({"period": words}, "September", "days") is not None + assert ek._means({"period": words}, "this month", "days") is not None + assert ek._means({"period": "September"}, "September", "days") is None + assert ek._means({"start": "2026-09-01"}, "September", "days") is None + + +def test_a_bare_word_read_fairly_passes_and_a_chat_line_with_any_call_fails(): + """The calls the first live run made that answer the question as a client with only the tool list reads it (each case's note says + why): "metrics" as the readings now, a weather report for today (Tuesday) as the report. A chat line ("only that it's cold", "ok + now what?") is not a request: any call fails it, so the eval shows a model that fetches readings for small talk.""" + check = evalkit.check_calls + assert check([("current", {})], EXPECT["metrics-bare"]) == [] and check([("about", {})], EXPECT["metrics-bare"]) == [] + report = [("current", {}), ("forecast", {"period": "today"}), ("pollen", {})] + assert check(report, EXPECT["weather-report-for-a-day"]) == [] + for cid in ("only-that-its-cold", "now-what"): + assert check([], EXPECT[cid]) == [], cid + for call in (report, [("current", {"readings": ["temperature"]})], [("summary", {"period": "today"})]): + assert check(call, EXPECT[cid]), (cid, call) + assert check([("summary", {})], EXPECT["metrics-bare"]) + + +def test_a_period_sent_with_start_and_end_beside_it_is_scored_as_the_tools_read_it(): + """common.read_period: beside junk start and end, or dates that read as the same span, the period is read, so the checker scores + the period (the live run's uv-days-two-years sent period with start 'count_only', end 'cancel'; most-rain-days-jja sent 'June to + August 2026' with the matching start 2026-06-01, end 2026-08-31). Dates that read as another span are refused by the tools, so the + checker fails them (use-five-minute-data sent days {period: "on record", start: "2025-01-01", end: "2026-09-28"}).""" + from tests import evalkit as ek + assert ek._means({"period": "June to August", "start": "count_only", "end": "cancel"}, "June to August", "days") is None + assert ek._means({"period": "June to August 2026", "start": "2026-06-01", "end": "2026-08-31"}, "June to August", "days") is None + assert ek._means({"period": "this week", "start": "2026-06-01", "end": "2026-08-31"}, "June to August", "days") is not None + disagree = ek._means({"period": "on record", "start": "2025-01-01", "end": "2026-09-28"}, "on record", "days") + assert disagree and "refused" in disagree and "but `start`/`end` say" in disagree + call = ("days", {"sort_by": "rain", "period": "June to August", "start": "count_only", "end": "cancel"}) + assert ek.check_calls([call], EXPECT["most-rain-days-jja"]) == [] + + +def test_a_rating_with_rain_passes_in_chart_readings_or_in_readings_but_not_as_pm25_alone(): + """rating-against-rainfall: deepseek put "air.pm2_5:rating" in `readings` (10 Nov 2026); summary takes it there too (summarised, + drawn as its rating), so the case takes either place, but not a rating dropped by chart_readings sent without it.""" + from tests import evalkit as ek + want = EXPECT["rating-against-rainfall"] + base = {"period": "last 30 days", "chart": True} + assert ek.check_calls([("summary", {**base, "chart_readings": ["air.pm2_5:rating", "rainfall.rain"]})], want) == [] + assert ek.check_calls([("summary", {**base, "readings": ["air.pm2_5:rating", "rain"]})], want) == [] + assert ek.check_calls([("summary", {**base, "readings": ["air.pm2_5:rating", "rain"], "chart_readings": ["pm2.5", "rain"]})], want) + assert ek.check_calls([("summary", {**base, "readings": ["pm2.5", "rain"]})], want) + + +def test_the_hottest_day_ranked_by_days_must_be_the_hottest(): + """think-hottest-week's days call ranks the hottest first: the coldest (order asc), a count or a statistic isn't the answer.""" + from tests import evalkit as ek + want = ek.load_service_cases()["think-hottest-week"]["args"]["days"] + + def fails(args): + return [k for k, w in want.items() if k != "period" and ek._matches(args.get(k), w)] + assert fails({"sort_by": "temp_max", "period": "this week"}) == [] + assert fails({"sort_by": "temp_max", "order": "asc"}) == ["order"] + assert fails({"sort_by": "temp_max", "count_only": True}) == ["count_only"] + assert fails({"stat": "avg", "of": "temp_avg"}) == ["stat"] + + +# ---------- the bot's live run over the frozen world, with a scripted model ---------- +# `--live` answers the bot's model from the real ten tools (evalworld.world), so a turn can take more than one round: it is scored over +# the whole turn. These run it with a model that reads what its calls gave, over the same world (the module's archive, at EVAL_NOW, +# copied fresh for each run). +class Reacting: + """An OpenAI-style client whose steps are scripted: each a text (the reply), a list of (tool, args), or a function of what the last + step's calls gave (each result as the model was sent it, parsed) that returns one. Past the script it says "Done.".""" + + def __init__(self, *steps): + self.steps, self.requests, self.seen = list(steps), [], [] + self.chat = NS(completions=NS(create=self.create)) + + async def create(self, **kw): + self.requests.append(kw) + given = [] + for m in reversed(kw["messages"]): + if m["role"] != "tool": + break + text = m["content"].split("\n", 1)[-1] if m["content"].startswith(evalkit.REPEATED) else m["content"] + given.insert(0, json.loads(text)) + self.seen.append(given) + step = self.steps.pop(0) if self.steps else "Done." + step = step(given) if callable(step) else step + calls = None if isinstance(step, str) else [NS(id=f"c{i}", function=NS(name=n, arguments=json.dumps(a))) + for i, (n, a) in enumerate(step)] + return NS(choices=[NS(message=NS(content=step if isinstance(step, str) else "", tool_calls=calls))], usage=None) + + +@pytest.fixture +def eval_world(tmp_path, eval_archive, monkeypatch): + """The frozen world (what evalworld.world gives a run: fresh tools over a new copy of the archive for each run), on the module's + archive.""" + at_eval_now(monkeypatch) + return evalworld.World(tmp_path, eval_archive) + + +async def bot_run(case_id: str, model: Reacting, world) -> tuple[int, str]: + lines = [] + failed = await evalkit.run_service([case(case_id)], EXPECT, model, "m", bot=True, world=world, out=lines.append) + return failed, "\n".join(lines) + + +async def test_a_refused_call_then_a_corrected_one_passes_and_the_refusal_is_counted(eval_world): + model = Reacting([("summary", {"readings": ["flux capacitor"], "period": "3m", "average": True})], + lambda given: [("summary", {"readings": ["temperature"], "period": "3m", "average": True})] if "error" in given[0] + else "gave up", + "Averaged 14.2 °C.") + failed, text = await bot_run("3m-average", model, eval_world) + assert failed == 0, text + assert "1/1 3m-average" in text and '2 calls, 1 refused: "Averaged 14.2 °C."' in text + assert "isn't a reading this service knows" in model.seen[1][0]["error"] # (the real refusal, as the model was sent it) + async with eval_world.fresh() as service: + assert model.requests[0]["messages"][0]["content"] == evalkit.bot_system(ctx=service.ctx) + + +async def test_a_second_call_made_on_a_note_passes(eval_world): + """rain-per-month: one figure for the year comes back with days' note_group_by; the model acts on it and asks again by month.""" + asked = {"stat": "sum", "of": "rain", "period": "this year"} + model = Reacting([("days", asked)], + lambda given: [("days", {**asked, "group_by": "month"})] if "note_group_by" in given[0] else "One figure.", + lambda given: f"{len(given[0]['by_month'])} months.") + failed, text = await bot_run("rain-per-month", model, eval_world) + assert failed == 0, text + assert '2 calls, 0 refused: "9 months."' in text # (January to September: the real days, by month) + without = Reacting([("days", asked)], lambda given: "One figure.") + failed, text = await bot_run("rain-per-month", without, eval_world) + assert failed == 1 and "group_by" in text and '1 call, 0 refused: "One figure."' in text + + +async def test_a_forbidden_tool_in_a_later_round_fails(eval_world): + model = Reacting([("relate", {})], [("days", {"stat": "max", "of": "pressure_max", "group_by": "month"})], "Weak.") + failed, text = await bot_run("pressure-rain-correlation", model, eval_world) + assert failed == 1 and "0/1 FAIL pressure-rain-correlation" in text and "should not have called days" in text + assert "2 calls, 0 refused" in text + + +async def test_a_turn_of_more_than_eight_calls_has_run_away_and_fails(eval_world): + many = [[("days", {"stat": "sum", "of": "rain", "group_by": "month", "period": f"last {n} days"})] for n in range(40, 49)] + failed, text = await bot_run("rain-per-month", Reacting(*many, "Rain by month."), eval_world) + assert failed == 1 and "ran away: 9 calls (more than 8)" in text and "9 calls, 0 refused" in text + failed, text = await bot_run("rain-per-month", Reacting(*many[:8], "Rain by month."), eval_world) + assert "ran away" not in text and '8 calls, 0 refused: "Rain by month."' in text + + +async def test_a_turn_is_capped_at_the_agents_steps(): + """However long the model keeps calling, the turn takes at most lib/llm.py's MAX_STEPS (10) steps of calls, then it is made to + answer.""" + from lib import llm + assert llm.MAX_STEPS == 10 + model = Reacting(*[[("about", {})]] * 30) + turn = await evalkit.run_live(case("3m-average"), model, "m") + assert len(model.requests) == llm.MAX_STEPS + 1 and len(turn.calls) == llm.MAX_STEPS + assert model.requests[-1]["tool_choice"] == "none" + + +async def test_the_world_is_built_at_the_frozen_clock_and_its_tools_give_real_results_then_the_clock_is_put_back(eval_archive, monkeypatch): + """(world() builds its archive with build_archive, under the frozen clock: here it is given a copy of the one build_archive made under + it for the module, eval_archive, rather than build the same again.)""" + import time + + async def built(folder): + assert time.time() == EVAL_NOW + return Path(shutil.copy(eval_archive, folder / "ecobot.sqlite")) + monkeypatch.setattr(evalworld, "build_archive", built) + async with evalworld.world() as world, world.fresh() as service: + assert time.time() == EVAL_NOW + out = json.loads(await service["days"].call({"stat": "sum", "of": "rain", "group_by": "month", "period": "this year"})) + assert "error" not in out and out["period"]["text"] == "this year: Thu 1 Jan – Mon 28 Sep 2026" + assert list(out["by_month"]) == [f"2026-{m:02d}" for m in range(1, 10)] and out["days_checked"] + assert [t.name for t in service] == evalkit.service_tool_names() + assert time.time() != EVAL_NOW + + +async def test_each_run_has_its_own_copy_of_the_world_so_a_case_scores_the_same_whatever_ran_before(eval_world): + """A call can fill the station's file from the fakes (a day in 2023, fetched and stored, moves "on record" back to it): each run of + each case gets fresh tools over a new copy of the archive, so the same case run first and again after another gives the same.""" + def holidays(): + return Reacting([("days", {"only": "public_holiday", "sort_by": "temp_max"})], lambda given: given[0]["period"]["text"]) + first = await bot_run("public-holidays", holidays(), eval_world) + assert first[0] == 0 and '"on record: Sat 29 Mar 2025 – Mon 28 Sep 2026"' in first[1] + old_day = {"readings": ["outdoor.temperature"], "start": "2023-11-10 11:00", "end": "2023-11-11 11:00"} + assert (await bot_run("a-day-in-2023", Reacting([("summary", old_day)], "Mild."), eval_world))[0] == 0 + assert await bot_run("public-holidays", holidays(), eval_world) == first + + +async def test_a_matching_call_that_was_refused_meets_nothing_and_a_forbidden_one_still_fails(eval_world): + """3m-average: the expected summary, with an argument it doesn't take, is refused; an answered call follows, then a give-up reply.""" + refused = ("summary", {"readings": ["temperature"], "period": "3m", "average": True, "bogus": 1}) + assert evalkit.check_calls([refused], EXPECT["3m-average"]) == [] # (its tool and arguments match: only its refusal tells) + failed, text = await bot_run("3m-average", Reacting([refused], [("about", {})], "Sorry, I can't average that."), eval_world) + assert failed == 1 and "did not call summary (called: about)" in text and "2 calls, 1 refused" in text + failed, text = await bot_run("pressure-rain-correlation", + Reacting([("relate", {})], [("days", {"stat": "max", "of": "pressure_max", "bogus": 1})], + [("about", {})], "Weak."), eval_world) + assert failed == 1 and "should not have called days" in text and "3 calls, 1 refused" in text + + +async def test_a_turn_whose_reply_is_empty_or_the_fallback_or_that_ends_on_a_refusal_fails(eval_world): + from lib.llm import FALLBACK + asked = ("summary", {"readings": ["temperature"], "period": "3m", "average": True}) + failed, text = await bot_run("3m-average", Reacting([asked], ""), eval_world) # (the Agent replies FALLBACK) + assert failed == 1 and "the reply is the Agent's fallback" in text and f'1 call, 0 refused: "{FALLBACK}"' in text + bad = ("summary", {**asked[1], "bogus": 1}) + failed, text = await bot_run("3m-average", Reacting([asked], [bad], "Averaged 14.2 °C."), eval_world) + assert failed == 1 and "a refused call was not corrected (summary" in text and '2 calls, 1 refused: "Averaged 14.2 °C."' in text + failed, text = await bot_run("3m-average", Reacting([bad], [asked], "Averaged 14.2 °C."), eval_world) + assert failed == 0, text + assert evalkit.check_turn(evalkit.LiveTurn([asked], " ", [False]), EXPECT["3m-average"]) == ["the reply is empty"] + assert evalkit.check_turn(evalkit.LiveTurn([asked], "Averaged.", [False]), EXPECT["3m-average"]) == [] + + +# A refusal is corrected by a call to the same tool answered in a later step: not by one to another tool after it, and not by one made +# in the same step (calls of one step are made together, so their order in it changes nothing). +ASKED = ("summary", {"readings": ["temperature"], "period": "3m", "average": True}) +BAD = ("summary", {**ASKED[1], "bogus": 1}) + + +async def test_a_refused_call_followed_by_another_tools_answered_call_fails(eval_world): + failed, text = await bot_run("3m-average", Reacting([ASKED], [BAD], [("about", {})], "Averaged 14.2 °C."), eval_world) + assert failed == 1 and "a refused call was not corrected (summary" in text and "3 calls, 1 refused" in text + + +async def test_a_refused_call_in_a_step_fails_whatever_the_order_of_the_steps_calls(eval_world): + for step in ([BAD, ("about", {})], [("about", {}), BAD], [BAD, ASKED]): + failed, text = await bot_run("3m-average", Reacting(step, "Averaged 14.2 °C."), eval_world) + assert failed == 1 and "a refused call was not corrected (summary" in text and "2 calls, 1 refused" in text, step + + +async def test_a_refused_call_corrected_in_a_later_step_by_the_same_tool_passes(eval_world): + model = Reacting([ASKED], [BAD, ("about", {})], [("about", {}), ASKED], "Averaged 14.2 °C.") + turn = await evalkit.run_live(case("3m-average"), model, "m", service=None) + assert turn.steps == [0, 1, 1, 2, 2] and turn.uncorrected() == [] + failed, text = await bot_run("3m-average", Reacting([ASKED], [BAD, ("about", {})], [("about", {}), ASKED], "Averaged 14.2 °C."), + eval_world) + assert failed == 0, text + assert '5 calls, 1 refused: "Averaged 14.2 °C."' in text + assert evalkit.LiveTurn([ASKED, BAD, ASKED], "Averaged.", [False, True, False], steps=[0, 1, 1]).uncorrected() == [BAD] + assert evalkit.LiveTurn([BAD, ASKED], "Averaged.", [True, False]).uncorrected() == [] # (no steps: each call is its own) + + +async def test_the_tools_alone_answer_no_data_to_every_call_and_score_every_call_of_the_turn(): + """--service: every call is answered CANNED and the model may call again (the Agent's loop): a call in its second round counts, + and the docs say so (not "the first round").""" + import ast + model = Reacting([("forecast", {})], lambda given: [("outlook", {})] if given == [json.loads(evalkit.CANNED)] else "?", "No data.") + lines = [] + assert await evalkit.run_service([case("will-it-rain")], EXPECT, model, "m", out=lines.append) == 0, lines + assert len(model.requests) == 3 + script_doc = ast.get_docstring(ast.parse((ROOT / "scripts" / "eval_prompts.py").read_text())) + for text in (script_doc, evalkit.run_service.__doc__, evalkit.__doc__, (ROOT / "docs" / "ecobot-mcp.md").read_text()): + assert "first round" not in text and "(one round)" not in text diff --git a/tests/test_service_forecast.py b/tests/test_service_forecast.py new file mode 100644 index 00000000..eb0840c6 --- /dev/null +++ b/tests/test_service_forecast.py @@ -0,0 +1,224 @@ +"""The `forecast` tool (lib/service/forecast.py): the days ahead in words, read here; the forecast source's lines, each day's figures, +its text, what is held when the request says not to fetch, and refusals that teach. (Until step 6c also held to weather_forecast's +answers and the bot's old words, tests/old_tools.py and tests/report_words.py, deleted with them.)""" + +import json +from datetime import date, datetime, time as dtime, timedelta + +import httpx +import pytest + +from lib.forecast import Forecast +from lib.service.common import FRESH, Refusal +from lib.service.context import Context +from lib.service.forecast import DESCRIPTION, PARAMETERS, days_text, read_ahead, tools +from lib.timeutil import day_text +from tests.fakes import TZ, config + +NOW = datetime(2026, 11, 10, 14, 5, tzinfo=TZ) # Tue 10 Nov 2026 2:05pm, as the plan's periods table is asked + + +def got(text: str) -> dict: + return json.loads(text) + + +def ahead(words, now=NOW) -> tuple[str, str]: + period = read_ahead(words, now, TZ) + return period.text, f"{period.first_day} {period.last_day}" + + +# ---------- the days ahead, in words ---------- +@pytest.mark.parametrize("words, text, days", [ + (None, "the next 7 days: Tue 10 – Mon 16 Nov 2026", "2026-11-10 2026-11-16"), + ("today", "today: Tue 10 Nov 2026", "2026-11-10 2026-11-10"), + ("Tonight", "today: Tue 10 Nov 2026", "2026-11-10 2026-11-10"), + ("tomorrow", "tomorrow: Wed 11 Nov 2026", "2026-11-11 2026-11-11"), + ("for tomorrow", "tomorrow: Wed 11 Nov 2026", "2026-11-11 2026-11-11"), + ("the day after tomorrow", "the day after tomorrow: Thu 12 Nov 2026", "2026-11-12 2026-11-12"), + ("next 3 days", "the next 3 days: Tue 10 – Thu 12 Nov 2026", "2026-11-10 2026-11-12"), + ("in the next three days", "the next 3 days: Tue 10 – Thu 12 Nov 2026", "2026-11-10 2026-11-12"), + ("3d", "the next 3 days: Tue 10 – Thu 12 Nov 2026", "2026-11-10 2026-11-12"), + ("1 day", "today: Tue 10 Nov 2026", "2026-11-10 2026-11-10"), + ("the next 7 days", "the next 7 days: Tue 10 – Mon 16 Nov 2026", "2026-11-10 2026-11-16"), + ("this week", "the next 7 days: Tue 10 – Mon 16 Nov 2026", "2026-11-10 2026-11-16"), + ("the week ahead", "the next 7 days: Tue 10 – Mon 16 Nov 2026", "2026-11-10 2026-11-16"), + ("this weekend", "this weekend: Sat 14 – Sun 15 Nov 2026", "2026-11-14 2026-11-15"), + ("over the weekend", "this weekend: Sat 14 – Sun 15 Nov 2026", "2026-11-14 2026-11-15"), + ("next week", "next week: Mon 16 – Sun 22 Nov 2026", "2026-11-16 2026-11-22"), + ("Saturday", "Saturday: Sat 14 Nov 2026", "2026-11-14 2026-11-14"), + ("on Sat", "Saturday: Sat 14 Nov 2026", "2026-11-14 2026-11-14"), + ("Tuesday", "Tuesday: Tue 10 Nov 2026", "2026-11-10 2026-11-10"), # a bare weekday is today when it is one + ("next Tuesday", "Tuesday: Tue 17 Nov 2026", "2026-11-17 2026-11-17"), + ("2026-11-12", "Thu 12 Nov 2026", "2026-11-12 2026-11-12"), +]) +def test_the_days_ahead_are_read_from_the_words_and_say_how(words, text, days): + assert ahead(words) == (text, days) + + +def test_the_weekend_from_a_saturday_or_a_sunday_starts_today(): + saturday, sunday = datetime(2026, 11, 14, 9, tzinfo=TZ), datetime(2026, 11, 15, 9, tzinfo=TZ) + assert ahead("this weekend", saturday) == ("this weekend: Sat 14 – Sun 15 Nov 2026", "2026-11-14 2026-11-15") + assert ahead("this weekend", sunday) == ("this weekend: Sun 15 Nov 2026", "2026-11-15 2026-11-15") + assert ahead("the next 7 days", datetime(2026, 12, 28, 9, tzinfo=TZ))[0] == "the next 7 days: Mon 28 Dec 2026 – Sun 3 Jan 2027" + + +def test_a_period_is_whole_days_on_the_stations_clock(): + period = read_ahead("this weekend", NOW, TZ) + assert period.asked == "this weekend" and period.cut is None + assert period.start == datetime(2026, 11, 14, tzinfo=TZ) and period.end == datetime(2026, 11, 16, tzinfo=TZ) + assert read_ahead(None, NOW, TZ).asked == "the next 7 days" + assert days_text(date(2026, 11, 10), date(2026, 11, 10)) == "Tue 10 Nov 2026" + + +def test_the_past_is_refused_pointing_to_summary_and_every_form_says_what_it_means_now(): + with pytest.raises(Refusal) as e: + read_ahead("yesterday", NOW, TZ) + assert "'yesterday' reads as a period that has been measured (yesterday: Mon 9 Nov 2026)" in e.value.message + assert "use summary" in e.value.message and "It is now Tue 10 Nov 2026 2:05pm." in e.value.message + forms = e.value.teach["forms"] + assert forms["tomorrow"] == "tomorrow: Wed 11 Nov 2026" + assert forms["this weekend, the weekend (Saturday and Sunday; from today when it is one)"] == "this weekend: Sat 14 – Sun 15 Nov 2026" + assert forms["a date, YYYY-MM-DD"] == "Thu 12 Nov 2026" + with pytest.raises(Refusal) as e: + read_ahead("2026-11-01", NOW, TZ) + assert e.value.message.startswith("'2026-11-01' is in the past (Sun 1 Nov 2026)") and "use summary" in e.value.message + with pytest.raises(Refusal) as e: + read_ahead("a fortnight from now", NOW, TZ) + assert e.value.message.startswith("'a fortnight from now' isn't a period the forecast can read") and len(e.value.teach["forms"]) == 9 + with pytest.raises(Refusal): + read_ahead("in 3 days", NOW, TZ) # (one day, three days from now: not "the next 3 days") + with pytest.raises(Refusal): + read_ahead("next 0 days", NOW, TZ) + + +# ---------- the tool ---------- +def open_meteo(calls, days=7): + """Open-Meteo: `days` days from today (the station's), each a little different; its ensemble's chance for every other day.""" + def handler(request: httpx.Request) -> httpx.Response: + calls.append(request.url.host) + today = datetime.now(TZ).date() + if request.url.host.startswith("ensemble"): + hourly = {"time": [f"{today + timedelta(days=n)}T{h:02d}:00" for n in range(days) for h in range(24)]} + members = [[(3.0 if n % 2 else 0.0) if h == 0 else 0.0 for n in range(days) for h in range(24)] for _ in range(4)] + members[0] = [0.0] * len(hourly["time"]) # one member dry every day: 75% on the wet ones + return httpx.Response(200, json={"hourly": {**hourly, "precipitation": members[0], + **{f"precipitation_member{m:02d}": s for m, s in enumerate(members[1:], 1)}}}) + return httpx.Response(200, json={"daily": { + "time": [str(today + timedelta(days=n)) for n in range(days)], "temperature_2m_min": [10.5 + n for n in range(days)], + "temperature_2m_max": [16 + n for n in range(days)], "precipitation_probability_max": [10 * n for n in range(days)], + "weather_code": [[63, 0, 95, 2, 80, 3, 61][n % 7] for n in range(days)]}}) + return httpx.MockTransport(handler) + + +def make(tmp_path, days=7, place="Melbourne"): + """(the forecast source, its requests, the context the tool is built over), all on the clock at noon today.""" + calls = [] + forecast = Forecast(config(tmp_path, forecast=True, forecast_lat=-37.8, forecast_lon=144.9, place=place), None, open_meteo(calls, days)) + noon = datetime.combine(datetime.now(TZ).date(), dtime(12, 0)) + forecast.now = lambda: noon + ctx = Context(forecast=forecast, tz=TZ, clock=lambda: noon.replace(tzinfo=TZ).timestamp()) + return forecast, calls, ctx + + +def tool(ctx): + (it,) = tools(ctx) + return it + + +async def test_the_lines_are_weather_forecasts_and_each_day_has_its_figures(tmp_path): + forecast, calls, ctx = make(tmp_path) + forecast_tool = tool(ctx) + assert forecast_tool.name == "forecast" and forecast_tool.annotations == {"readOnlyHint": True, "openWorldHint": True} + out = got(await forecast_tool.call({})) + assert calls == ["api.open-meteo.com", "ensemble-api.open-meteo.com"] # nothing held: fetched, as weather_forecast does + assert out["lines"] == forecast.lines(7) and len(out["lines"]) == 7 and out["lines"][0].startswith("Today: 🌧️ Rain. 11–16°C") + today = forecast.now().date() + assert out["period"]["asked"] == "the next 7 days" and out["period"]["text"].startswith("the next 7 days: ") + assert out["period"]["start"] == datetime.combine(today, dtime(), tzinfo=TZ).isoformat() + assert out["days"][0] == {"date": today.isoformat(), "min": 10.5, "max": 16, "summary": "🌧️ Rain.", "rain_chance": 0, + "rain_1mm_pct": 0} + assert out["days"][1] == {"date": (today + timedelta(days=1)).isoformat(), "min": 11.5, "max": 17, "summary": "☀️ Clear.", + "rain_chance": 10, "rain_1mm_pct": 75} + assert out["place"] == "Melbourne" and out["source"] == "Open-Meteo" and out["fresh"] == FRESH + fetched = datetime.fromtimestamp(int(forecast.fetched_at), TZ) + assert out["fetched_at"] == fetched.isoformat() and out["as_of"]["time"] == fetched.isoformat() + assert list(out) == ["period", "as_of", "fresh", "text", "lines", "days", "place", "source", "fetched_at"] + for n in range(1, 8): # "next N days" is the source's first N lines, line for line + assert got(await forecast_tool.call({"period": f"next {n} days"}))["lines"] == forecast.lines(n) + await forecast.close() + + +async def test_a_day_ahead_has_its_own_line_as_weather_forecast_writes_it(tmp_path): + forecast, _, ctx = make(tmp_path) + tomorrow = got(await tool(ctx).call({"period": "tomorrow"})) # (fetched: nothing was held) + week = forecast.lines(7) + assert tomorrow["lines"] == [week[1]] and tomorrow["period"]["text"].startswith("tomorrow: ") + day = forecast.now().date() + timedelta(days=4) + named = got(await tool(ctx).call({"period": f"{day:%A}"})) + assert named["lines"] == [week[4]] and named["days"][0]["date"] == day.isoformat() + await forecast.close() + + +async def test_its_text_is_its_heading_and_a_bullet_per_line(tmp_path): + forecast, _, ctx = make(tmp_path) + today = forecast.now().date() + for words, days in (("next 3 days", 3), ("the next 7 days", 7), ("today", 1)): + out = got(await tool(ctx).call({"period": words})) + heading, *bullets = out["text"].split("\n") + assert heading.startswith("Forecast (Melbourne, ") and bullets == [f"• {line}" for line in forecast.lines(days)], words + fetched = datetime.fromtimestamp(int(forecast.fetched_at), TZ) + stamp = f"{fetched:%-I:%M%p}".lower() + assert out["text"].startswith(f"Forecast (Melbourne, {stamp})\n• Today: ") # fetched today: its time alone + later = today + timedelta(days=1) # asked the next day, the time it was fetched has its day + assert got(await tool(Context(forecast=forecast, tz=TZ, clock=lambda: datetime.combine(later, dtime(9), tzinfo=TZ).timestamp())) + .call({"period": "today"}))["text"].startswith(f"Forecast (Melbourne, {fetched:%a %-d %b} {stamp})\n• Today: ") + await forecast.close() + + +async def test_with_no_place_the_heading_has_only_the_time(tmp_path): + forecast, _, ctx = make(tmp_path, place="") + out = got(await tool(ctx).call({"period": "today"})) + assert "place" not in out and out["text"].split("\n")[0].startswith("Forecast (") and "," not in out["text"].split("\n")[0] + await forecast.close() + + +async def test_with_fetch_false_it_answers_from_what_is_held_and_fetches_nothing(tmp_path): + forecast, calls, ctx = make(tmp_path) + out = got(await tool(ctx).call({}, {"fetch": False})) + assert out == {"error": "No forecast is available right now."} and calls == [] + await forecast.warm(True) + calls.clear() + held = got(await tool(ctx).call({"period": "tomorrow"}, {"fetch": False})) + assert len(held["lines"]) == 1 and calls == [] + await forecast.close() + + +async def test_days_beyond_the_forecast_are_said_so_or_refused_with_how_far_it_reaches(tmp_path): + forecast, _, ctx = make(tmp_path, days=3) + today = forecast.now().date() + week = got(await tool(ctx).call({"period": "this week"})) + assert len(week["lines"]) == 3 and week["note"] == \ + f"The forecast reaches only {day_text(today + timedelta(days=2), year=False)}: the days after it aren't forecast yet." + far, reaches = today + timedelta(days=5), today + timedelta(days=2) + out = got(await tool(ctx).call({"period": far.isoformat()})) + assert out["error"] == f"The days asked for ({days_text(far, far)}) are beyond the forecast, which reaches {day_text(reaches)}: ask " \ + "for days up to then (the next 7 days is all of it)." + assert out["reaches"] == reaches.isoformat() + await forecast.close() + + +async def test_refusals_teach_the_call_that_works(tmp_path): + forecast, calls, ctx = make(tmp_path) + out = got(await tool(ctx).call({"period": "last week"})) + assert "reads as a period that has been measured" in out["error"] and "use summary" in out["error"] and "forms" in out + out = got(await tool(ctx).call({"start": "2026-11-12"})) + assert out["error"].startswith("The forecast takes `period` in words, not `start` and `end`") and "tomorrow" in out["forms"] + assert calls == [] # (nothing is fetched for a call that is refused) + await forecast.close() + + +def test_it_is_offered_only_with_a_forecast_and_its_description_carries_the_rules(): + assert tools(Context(tz=TZ)) == [] + assert len(DESCRIPTION) < 1500 and "outlook" in DESCRIPTION and "summary" in DESCRIPTION and '{"period": "tomorrow"}' in DESCRIPTION + assert '"weather week", "ecowitt week": the past week, summary' in DESCRIPTION and "Only what is ahead is forecast." in DESCRIPTION + assert list(PARAMETERS["properties"]) == ["period"] and "Default: the next 7 days." in PARAMETERS["properties"]["period"]["description"] diff --git a/tests/test_service_instructions.py b/tests/test_service_instructions.py new file mode 100644 index 00000000..583162ca --- /dev/null +++ b/tests/test_service_instructions.py @@ -0,0 +1,56 @@ +"""The server's instructions (lib/service/instructions.py; docs/ecobot-mcp.md 3.2): the devices and their nicknames, Indoor and Outdoor, +the units, built from the Context's sources and the catalogue.""" + +from zoneinfo import ZoneInfo + +from lib.service.context import Context +from lib.service.instructions import INSTRUCTIONS, instructions, names, units +from lib.service.names import CATALOGUE, Catalogue + +MELBOURNE = ZoneInfo("Australia/Melbourne") + + +def test_the_default_names_every_device_its_nicknames_indoor_and_outdoor_and_the_units(): + text = INSTRUCTIONS + for words in ('"ecowitt"', '"the weather station"', "AirGradient", '"ag"', '"airgradient"', '"air gradient"', "Open-Meteo", + "pollen", "Indoor and Outdoor", "outdoor.temperature, indoor.temperature", "air.temperature and air.humidity", + "no indoor air quality", "°C: temperature", "%: humidity", "hPa: pressure", "km/h: wind speed, wind gust", + "mm: rain", "µg/m³: PM2.5, PM10, PM1", "ppm: CO₂", "no unit (an index): UV index, VOC index, NOx index", + "person's own words"): + assert words in text, words + assert len(text) < 1500 and text == instructions() + # every reading's name (a live run made up rain.rain_rate for rainfall.rain_rate) + assert "Names (sensor.reading): outdoor and indoor: temperature, humidity, dew_point" in text + assert "rainfall and rainfall_piezo: rain_rate, rain" in text and "air: pm2_5, pm10" in text + + +def test_every_question_is_fetched_afresh_a_follow_up_and_a_challenge_too(): + # the results say so (common.FRESH), but the bot drops tool turns from its history: the model decides a follow-up without them + for text in (INSTRUCTIONS, instructions(Context(eco=object(), tz=MELBOURNE)), instructions(Context(air=object(), tz=MELBOURNE))): + last = text.splitlines()[-1] + assert "every question" in last and "never reuse earlier figures" in last + assert "follow-up" in last and "challenge" in last and "at once, unasked" in last + + +def test_names_list_each_sensor_with_its_readings_sensors_alike_together(): + listed = names(CATALOGUE) + assert listed.startswith("outdoor and indoor: temperature, humidity") and "; pressure: relative, absolute; " in listed + assert all(n.partition(".")[2] in listed for n in CATALOGUE.names) + + +def test_units_list_each_unit_once_with_its_readings_sides_and_devices_aside(): + listed = units(CATALOGUE) + assert listed.count("°C:") == 1 and "Outdoor" not in listed and "Indoor" not in listed and "AirGradient" not in listed + assert listed.split("; ")[0] == "°C: temperature, dew point, feels like, apparent temperature" + + +def test_a_service_without_the_air_sensor_forecast_or_pollen_names_only_what_it_has_and_its_zone(): + station = Catalogue(r for r in CATALOGUE if not r.name.startswith("air.")) + text = instructions(Context(eco=object(), catalogue=station, tz=MELBOURNE)) + assert "Ecowitt" in text and "AirGradient" not in text and "µg/m³" not in text and "air.temperature" not in text + assert "Open-Meteo" not in text and "pollen" not in text + assert "The station's clock is Australia/Melbourne time" in text + # the catalogue isn't read yet (every reading known): only the devices there are give units + assert "ppm" not in instructions(Context(eco=object(), tz=MELBOURNE)) + air = instructions(Context(air=object(), tz=MELBOURNE)) + assert "AirGradient" in air and "Ecowitt" not in air and "Indoor and Outdoor" not in air and "°C: temperature" in air diff --git a/tests/test_service_outlook.py b/tests/test_service_outlook.py new file mode 100644 index 00000000..c40a1260 --- /dev/null +++ b/tests/test_service_outlook.py @@ -0,0 +1,359 @@ +"""The `outlook` tool (lib/service/outlook.py): will it rain in the next few hours, by the prompt's rules worked out in code from the +station's last 3 hours and its reading now: each rule alone, their combination, the result's shape, the forecast's lines beside it, +what is held when the request says not to fetch, and the refusal when there is nothing to read.""" + +import json +import time +from datetime import datetime, timedelta + +import pytest + +from lib.ecowitt.source import LIVE_GROUPS +from lib.service.common import FRESH +from lib.service.context import Context +from lib.service.outlook import DESCRIPTION, GROUPS, HOW_TO_READ, PARAMETERS, dew_point, read, tools +from tests.clocks import pin +from tests.fakes import TZ, archived_station + +NOW = datetime(2026, 11, 10, 14, 5, tzinfo=TZ) # Tue 10 Nov 2026 2:05pm +NOW_TS = int(NOW.timestamp()) +STEPS = 36 # 5-minute readings over the 3 hours: 37 of them, the last at NOW + + +def got(text: str) -> dict: + return json.loads(text) + + +def at(spec, i: int): + """A reading's value at step i of STEPS: a constant, (first, last) in a straight line, or a function of i.""" + if callable(spec): + return spec(i) + if isinstance(spec, tuple): + return round(spec[0] + (spec[1] - spec[0]) * i / STEPS, 2) + return spec + + +def station(pressure=(1012.0, 1012.0), humidity=70.0, temperature=15.0, dew=8.0, daily=0.0, rate=0.0, wind=10.0, now_ts=NOW_TS, + gauge="rainfall") -> list[tuple[int, dict]]: + """The station's last 3 hours of 5-minute readings to `now_ts`, as Ecowitt.recent gives them; a reading given as None is left out.""" + rows = [] + for i in range(STEPS + 1): + row = {"pressure.relative": at(pressure, i), "outdoor.humidity": at(humidity, i), "outdoor.temperature": at(temperature, i), + "outdoor.dew_point": at(dew, i), f"{gauge}.daily": at(daily, i), f"{gauge}.rain_rate": at(rate, i), + "wind.wind_speed": at(wind, i)} + rows.append((now_ts - (STEPS - i) * 300, {k: v for k, v in row.items() if v is not None})) + return rows + + +def outlook(rows=None, live=None, live_ts=None, **kw) -> dict: + return read(rows if rows is not None else station(**kw), live, NOW_TS, live_ts) + + +# ---------- each rule ---------- +@pytest.mark.parametrize("pressure, verdict, tendency, change", [ + ((1012.0, 1008.5), "likely", "falling", -3.5), # down more than 3 hPa + ((1012.0, 1009.0), "possible", "falling", -3.0), # 1 to 3 hPa: possible (3 is not more than 3) + ((1012.0, 1009.6), "possible", "falling", -2.4), + ((1012.0, 1011.0), "possible", "falling", -1.0), + ((1012.0, 1011.1), "unlikely", "steady", -0.9), # under 1 hPa: steady + ((1009.0, 1011.0), "unlikely", "rising", 2.0), + ((1012.0, 1012.0), "unlikely", "steady", 0.0), +]) +def test_the_pressure_tendency_over_3_hours_sets_the_verdict(pressure, verdict, tendency, change): + out = outlook(pressure=pressure) + assert (out["verdict"], out["pressure"]["tendency"], out["pressure"]["change_hpa"]) == (verdict, tendency, change) + assert out["pressure"]["level"] == "normal" and out["pressure"]["hpa"] == pressure[1] + + +def test_falling_or_rising_is_whether_the_high_or_the_low_came_first_not_where_it_ends(): + dip = lambda i: 1012.0 - 3.5 * min(i, 30) / 30 + (0.5 if i > 30 else 0) # down 3.5 hPa, then back up a little at the end + out = outlook(pressure=dip) + assert out["pressure"]["tendency"] == "falling" and out["pressure"]["change_hpa"] == -3.5 and out["verdict"] == "likely" + rise = lambda i: 1008.5 + 3.5 * min(i, 30) / 30 - (0.5 if i > 30 else 0) # up 3.5, then down a little + assert outlook(pressure=rise)["pressure"]["tendency"] == "rising" and outlook(pressure=rise)["verdict"] == "unlikely" + + +def test_the_reason_cites_one_or_two_readings_ready_to_quote(): + out = outlook(pressure=(1012.0, 1009.6), humidity=91.0) + assert out["verdict"] == "likely" and out["reason"] == "pressure down 2.4 hPa in 3 hours, humidity 91%" # the prompt's example + assert out["pressure"]["text"] == "1009.6 hPa, down 2.4 hPa in 3 hours" + assert outlook(pressure=(1012.0, 1008.5))["reason"] == "pressure down 3.5 hPa in 3 hours, humidity 70%" + assert outlook(pressure=(1009.0, 1011.0))["reason"] == "pressure up 2.0 hPa in 3 hours, humidity 70%" + steady = outlook(pressure=(1012.0, 1011.4)) + assert steady["reason"] == "pressure steady, humidity 70%" + assert steady["pressure"]["text"] == "1011.4 hPa, steady (down 0.6 hPa in 3 hours)" + + +def test_the_pressure_level_unsettled_or_settled_moves_the_verdict_a_step(): + low = outlook(pressure=(1003.4, 1003.0)) + assert low["pressure"]["level"] == "unsettled" and low["verdict"] == "possible" + assert low["reason"] == "low pressure (1003.0 hPa), pressure steady" and low["pressure"]["text"].endswith("; under 1005 hPa: unsettled") + high = outlook(pressure=(1026.0, 1024.0)) + assert high["pressure"]["level"] == "settled" and high["verdict"] == "unlikely" # falling 2 hPa, but settled + assert high["reason"] == "high pressure (1024.0 hPa), pressure down 2.0 hPa in 3 hours" + assert high["pressure"]["text"].endswith("; over 1020 hPa: settled") + assert outlook(pressure=(1005.0, 1005.0))["pressure"]["level"] == outlook(pressure=(1020.0, 1020.0))["pressure"]["level"] == "normal" + + +def test_moist_air_by_humidity_or_by_the_dew_point_moves_the_verdict_a_step(): + humid = outlook(humidity=90.0) + assert humid["moisture"] == {"humidity": 90, "dew_point_spread": 7.0, "moist": True, + "text": "humidity 90%, 7.0 °C above the dew point"} + assert humid["verdict"] == "possible" and humid["reason"] == "humidity 90%, pressure steady" + near = outlook(humidity=85.0, temperature=15.0, dew=13.5) + assert near["moisture"]["moist"] and near["moisture"]["dew_point_spread"] == 1.5 and near["verdict"] == "possible" + assert near["reason"] == "temperature within 1.5 °C of the dew point, pressure steady" + dry = outlook(humidity=89.0, dew=12.9) + assert not dry["moisture"]["moist"] and dry["moisture"]["dew_point_spread"] == 2.1 and dry["verdict"] == "unlikely" + at_dew = outlook(humidity=None, temperature=12.0, dew=12.0) + assert at_dew["moisture"] == {"humidity": None, "dew_point_spread": 0.0, "moist": True, "text": "at the dew point"} + + +def test_a_station_without_a_dew_point_has_it_worked_out(): + assert dew_point(20.0, 50.0) == pytest.approx(9.26, abs=0.05) and dew_point(15.0, 100.0) == pytest.approx(15.0, abs=0.01) + out = outlook(dew=None, temperature=15.0, humidity=88.0) + assert out["moisture"]["dew_point_spread"] == 2.0 and out["moisture"]["moist"] and "missing" not in out + + +def test_rain_now_or_in_the_last_hour_makes_it_likely_whatever_the_pressure(): + raining = outlook(pressure=(1009.0, 1011.0), rate=lambda i: 1.8 if i == STEPS else 0.0, daily=lambda i: 0.2 if i == STEPS else 0.0) + assert raining["verdict"] == "likely" and raining["recent_rain"] == {"rained": True, "raining_now": True, "rate_mm_h": 1.8, + "last_hour_mm": 0.2, + "text": "raining now (1.8 mm/h), 0.2 mm in the last hour"} + assert raining["reason"] == "raining now (1.8 mm/h), pressure up 2.0 hPa in 3 hours" + shower = outlook(daily=lambda i: 0.0 if i < 30 else 0.6) # 0.6 mm 30 minutes ago, dry since + assert shower["verdict"] == "likely" and shower["recent_rain"]["raining_now"] is False + assert shower["recent_rain"]["text"] == "0.6 mm in the last hour" and shower["reason"] == "0.6 mm in the last hour, pressure steady" + earlier = outlook(daily=lambda i: 0.0 if i < 10 else 0.6) # 2 hours ago: not recent + assert earlier["verdict"] == "unlikely" and earlier["recent_rain"]["rained"] is False + assert earlier["recent_rain"]["text"] == "no rain in the last hour" and earlier["recent_rain"]["last_hour_mm"] == 0.0 + trace = outlook(daily=lambda i: 0.0 if i < 30 else 0.02) + assert trace["recent_rain"]["text"] == "a trace of rain in the last hour" and trace["verdict"] == "likely" + + +def test_rain_across_midnight_counts_the_reset(): + late = NOW.replace(hour=0, minute=20) + rows = station(now_ts=int(late.timestamp()), daily=lambda i: 3.0 if i < 32 else 0.0 if i == 32 else 0.4) # reset at midnight + out = read(rows, None, int(late.timestamp())) + assert out["recent_rain"]["last_hour_mm"] == 0.4 and out["verdict"] == "likely" + + +def test_the_piezo_gauge_is_read_when_the_station_has_no_other(): + out = outlook(gauge="rainfall_piezo", rate=lambda i: 2.0 if i == STEPS else 0.0) + assert out["recent_rain"]["raining_now"] and out["verdict"] == "likely" + + +def test_wind_picking_up_strengthens_a_falling_pressure_only(): + picking_up = lambda i: 5.0 if i < 12 else 14.0 + out = outlook(pressure=(1012.0, 1010.0), wind=picking_up) + assert out["wind_trend"] == {"trend": "picking up", "first_hour_kmh": 5.0, "last_hour_kmh": 14.0, + "text": "picking up: 14.0 km/h on average in the last hour, 5.0 km/h 2 to 3 hours ago"} + assert out["verdict"] == "likely" and out["reason"] == "pressure down 2.0 hPa in 3 hours, wind picking up" + assert outlook(pressure=(1010.0, 1012.0), wind=picking_up)["verdict"] == "unlikely" # rising pressure: it doesn't count + assert outlook(pressure=(1012.0, 1011.6), wind=picking_up)["verdict"] == "unlikely" # nor with steady pressure + assert outlook(wind=lambda i: 15.0 if i < 12 else 9.0)["wind_trend"]["trend"] == "easing" + assert outlook(wind=lambda i: 10.0 if i < 12 else 14.0)["wind_trend"]["trend"] == "steady" + + +# ---------- the rules together ---------- +@pytest.mark.parametrize("kw, verdict", [ + (dict(pressure=(1004.0, 1001.0), humidity=95.0, wind=lambda i: 5.0 if i < 12 else 14.0), "likely"), # everything: no more than likely + (dict(pressure=(1012.0, 1010.0), humidity=93.0), "likely"), # possible, and moist + (dict(pressure=(1004.0, 1003.5), humidity=93.0), "likely"), # steady, but unsettled and moist + (dict(pressure=(1024.0, 1024.2), humidity=93.0), "unlikely"), # moist, but settled + (dict(pressure=(1025.0, 1021.0)), "possible"), # likely, but settled + (dict(pressure=(1025.0, 1021.0), rate=0.4), "likely"), # ... and it's raining + (dict(pressure=(1010.0, 1014.0), humidity=60.0), "unlikely"), +]) +def test_the_rules_together_stay_between_unlikely_and_likely(kw, verdict): + assert outlook(**kw)["verdict"] == verdict + + +def test_the_reading_now_is_used_when_it_is_newer_than_the_5_minute_readings(): + rows = station(pressure=(1012.0, 1010.0), now_ts=NOW_TS - 240) + live = {"pressure.relative": 1008.0, "rainfall.rain_rate": 0.0, "outdoor.humidity": 92.0, "outdoor.temperature": 14.0, + "outdoor.dew_point": 12.7} + out = read(rows, live, NOW_TS, NOW_TS - 30) + assert out["pressure"]["change_hpa"] == -4.0 and out["moisture"]["humidity"] == 92 and out["newest"] == NOW_TS - 30 + stale = read(rows, live, NOW_TS, NOW_TS - 600) # older than the newest 5 minutes': the rows say it all + assert stale["pressure"]["change_hpa"] == -2.0 and stale["newest"] == NOW_TS - 240 + + +def test_what_the_station_lacks_is_listed_and_the_verdict_rests_on_the_rest(): + rows = [(ts, {k: v for k, v in r.items() if not k.startswith("pressure")}) for ts, r in station(humidity=95.0)] + out = read(rows, None, NOW_TS) + assert out["pressure"] is None and out["missing"] == ["pressure"] and out["verdict"] == "possible" and out["reason"] == "humidity 95%" + assert read([], None, NOW_TS) == {"verdict": "unlikely", "reason": "too few readings in the last 3 hours to tell", "pressure": None, + "moisture": None, "recent_rain": None, "wind_trend": None, + "missing": ["pressure", "humidity and dew point", "rain", "wind"], "newest": None} + + +# ---------- the tool ---------- +class Station: + """A stand-in for lib.ecowitt.Ecowitt: what the outlook reads of it, and what it was asked.""" + + def __init__(self, rows, live=None): + self.rows, self.tz, self.mac, self.groups = rows, TZ, "M", ["outdoor", "indoor", "pressure", "wind", "rainfall", "solar_and_uvi"] + self._live = (time.time(), live) if live else None + self.asked = [] + self.storage = self # (its read() is the file's) + + def fetcher(self, groups, urgent=False): + self.asked.append(("fetcher", tuple(groups), urgent)) + return self + + async def get(self, cycle, start, end, refresh=False, load=True): + self.asked.append(("get", cycle, start, end)) + return self.rows + + async def read(self, fn, mac, groups, cycle, start, end): + self.asked.append(("held", fn.__name__, tuple(groups), cycle, start, end)) + return self.rows + + async def _live_data(self, groups, max_age=90, urgent=True): + self.asked.append(("live", tuple(groups), urgent)) + return self._live[1] if self._live else {} + + +def live_reading(ts=NOW_TS, **values) -> dict: + """A real_time response: {group: {field: {value, unit, time}}}.""" + out = {} + for name, value in values.items(): + group, field = name.split("__") + out.setdefault(group, {})[field] = {"value": str(value), "unit": "", "time": str(ts)} + return out + + +class HeldForecast: + """A stand-in for lib.forecast.Forecast with its days held.""" + + def __init__(self, days): + self.days, self.fetched_at, self.place, self.tz, self.warmed = days, NOW_TS - 600, "Melbourne", TZ, 0 + + async def warm(self, fresh=True): + self.warmed += 1 + + +def context(eco, forecast=None, now_ts=NOW_TS) -> Context: + return Context(eco=eco, forecast=forecast, tz=TZ, clock=lambda: now_ts) + + +async def test_the_result_has_the_verdict_its_reason_each_rules_figures_and_the_forecasts_lines(): + eco = Station(station(pressure=(1012.0, 1009.6), humidity=91.0, now_ts=NOW_TS - 120), + live_reading(rainfall__rain_rate=0.0, pressure__relative=1009.5)) + today = NOW.date() + days = [{"date": today - timedelta(days=1), "min_c": 9, "max_c": 15, "summary": "☁️ Overcast.", "rain_chance_pct": 20}, + {"date": today, "min_c": 11, "max_c": 17, "summary": "🌧️ Rain.", "rain_chance_pct": 80, "rain_1mm_pct": 65}, + {"date": today + timedelta(days=1), "min_c": 10, "max_c": 18, "summary": "🌦️ Showers.", "rain_chance_pct": 60}, + {"date": today + timedelta(days=2), "min_c": 12, "max_c": 22, "summary": "☀️ Clear.", "rain_chance_pct": 0}] + (outlook_tool,) = tools(context(eco, HeldForecast(days))) + assert outlook_tool.name == "outlook" and outlook_tool.annotations == {"readOnlyHint": True, "openWorldHint": True} + out = got(await outlook_tool.call({})) + assert list(out) == ["as_of", "fresh", "verdict", "reason", "pressure", "moisture", "recent_rain", "wind_trend", "forecast", + "how_to_read"] + assert out["as_of"] == {"text": "Tue 10 Nov 2026 2:05pm", "time": NOW.isoformat()} and out["fresh"] == FRESH + assert out["verdict"] == "likely" and out["reason"] == "pressure down 2.5 hPa in 3 hours, humidity 91%" + assert out["pressure"] == {"hpa": 1009.5, "change_hpa": -2.5, "tendency": "falling", "level": "normal", + "text": "1009.5 hPa, down 2.5 hPa in 3 hours"} + assert out["moisture"]["humidity"] == 91 and out["recent_rain"]["text"] == "no rain in the last hour" + assert out["wind_trend"]["trend"] == "steady" + assert out["forecast"] == ["Today: 🌧️ Rain. 11–17°C, 65% chance of at least 1 mm", + "Wednesday: 🌦️ Showers. 10–18°C, 60% chance of rain"] # (yesterday's and the day after's left out) + assert out["how_to_read"] == HOW_TO_READ + groups = ("outdoor", "pressure", "rainfall", "wind") # (the station has no piezo gauge) + assert eco.asked[0][:3] == ("fetcher", groups, True) and eco.asked[1][:2] == ("get", "5min") + assert eco.asked[2] == ("live", tuple(LIVE_GROUPS), True) # (every group, as the report asks: the reading is kept for the next) + assert eco.asked[1][2:] == (datetime(2026, 11, 10, 11, 5), datetime(2026, 11, 10, 14, 5)) # the last 3 hours, on the station's clock + + +async def test_with_fetch_false_it_reads_what_is_held_and_drawn_ahead_its_fetches_wait_their_turn(): + eco = Station(station(), live_reading(pressure__relative=1012.0)) + forecast = HeldForecast([]) + out = got(await tools(context(eco, forecast))[0].call({}, {"fetch": False})) + assert [a[0] for a in eco.asked] == ["held"] and eco.asked[0][1:4] == ("rows_on", ("outdoor", "pressure", "rainfall", "wind"), "5min") + assert eco.asked[0][4:] == (NOW_TS - 3 * 3600, NOW_TS) and forecast.warmed == 0 + assert out["forecast"] == [] and out["forecast_note"] == "No forecast is available right now: the station's read is the whole answer." + eco.asked.clear() + await tools(context(eco))[0].call({}, {"priority": "background"}) + assert eco.asked[0][2] is False and eco.asked[2][2] is False # (not urgent: nobody is waiting) + + +async def test_without_the_forecast_the_stations_read_is_the_whole_answer_and_an_old_reading_is_warned_about(): + eco = Station(station(now_ts=NOW_TS - 3600)) + out = got(await tools(context(eco))[0].call({})) + assert "forecast" not in out and out["as_of"]["text"] == "Tue 10 Nov 2026 1:05pm" + assert out["warning"] == "The station's newest reading is from Tue 10 Nov 1:05pm: this read may be out of date." + + +async def test_with_no_readings_it_is_refused_pointing_to_the_forecast(): + out = got(await tools(context(Station([]), HeldForecast([])))[0].call({})) + assert out == {"error": "The weather station has no readings from the last 3 hours, so there is nothing to read the next few hours " + "from. Ask forecast for today's forecast."} + + +async def pinned_station(when, tmp_path, pinned_archive, monkeypatch): + """(Ecowitt, fake) over the fake station's archive as it was at `when`, with the clock pinned there.""" + cache = pinned_archive(when) + pin(monkeypatch, when) + return await archived_station(tmp_path, cache) + + +async def test_on_the_fake_station_it_reads_the_last_3_hours_from_the_file_and_the_reading_now(tmp_path, pinned_archive, monkeypatch): + eco, fake = await pinned_station(NOW, tmp_path, pinned_archive, monkeypatch) # (2:05pm: the last 3 hours are all today's) + try: + ctx = Context(eco=eco) + nothing = got(await tools(ctx)[0].call({}, {"fetch": False})) # the archive holds no 5-minute readings of today yet + assert fake.calls == [] and nothing["error"].startswith("The weather station has no readings from the last 3 hours") + out = got(await tools(ctx)[0].call({})) + assert {(c["path"], c.get("cycle_type")) for c in fake.calls} == {("history", "5min"), ("real_time", None)} + fake.calls.clear() + held = got(await tools(ctx)[0].call({}, {"fetch": False})) # now held: nothing asked of Ecowitt + assert fake.calls == [] and held["pressure"] == out["pressure"] and held["verdict"] == out["verdict"] + rows = await eco.recent(3) + last = rows[-1][1] + assert out["pressure"]["hpa"] == round(last["pressure.relative"], 1) # (the reading now has no pressure: the newest 5 minutes') + assert out["moisture"]["dew_point_spread"] == 0.0 and out["moisture"]["moist"] # (the fake's dew point is its temperature) + assert out["verdict"] in ("possible", "likely") + assert datetime.fromisoformat(out["as_of"]["time"]) > NOW - timedelta(minutes=10) + finally: + await eco.close() + + +async def test_just_after_midnight_the_last_3_hours_are_yesterdays_evening_read_from_the_file(tmp_path, pinned_archive, monkeypatch): + """At 12:05am the last 3 hours are yesterday's from 9:05pm, a finished day the archive holds (up to its settled edge, 10:50pm): + without fetching, the read is made from them (nothing asked of Ecowitt), as of its newest reading and warned about when that is + over half an hour old; fetching adds the rest and the reading now. (By day the archive holds nothing of the last 3 hours: the + test above.)""" + midnight = datetime(2026, 11, 11, 0, 5, tzinfo=TZ) + eco, fake = await pinned_station(midnight, tmp_path, pinned_archive, monkeypatch) + try: + ctx = Context(eco=eco) + held = got(await tools(ctx)[0].call({}, {"fetch": False})) + assert fake.calls == [] and "error" not in held and held["verdict"] in ("unlikely", "possible", "likely") + newest = datetime.fromisoformat(held["as_of"]["time"]) + assert midnight - timedelta(hours=3) <= newest < midnight and newest.date() == midnight.date() - timedelta(days=1) + assert ("warning" in held) is (midnight - newest > timedelta(minutes=30)) + out = got(await tools(ctx)[0].call({})) + assert {(c["path"], c.get("cycle_type")) for c in fake.calls} == {("history", "5min"), ("real_time", None)} + assert midnight - timedelta(minutes=10) < datetime.fromisoformat(out["as_of"]["time"]) <= midnight and "warning" not in out + finally: + await eco.close() + + +def test_it_is_offered_only_with_a_station_and_its_description_carries_the_rules(): + assert tools(Context(tz=TZ)) == [] + assert len(DESCRIPTION) < 1500 and PARAMETERS == {"type": "object", "properties": {}} + for rule in ("high came before its low", "more than 3 hPa", "1005 hPa", "1020 hPa", "humidity 90%", "within 2 °C of the dew point", + "wind picking up", "rain rate above 0 now", "forecast", "summary", "relate"): + assert rule in DESCRIPTION, rule + assert set(GROUPS) == {"outdoor", "pressure", "rainfall", "rainfall_piezo", "wind"} # (the prefetch's groups) + + +def test_the_last_hour_ends_at_the_newest_reading_so_stale_readings_still_count_their_rain(): + """Read without fetching just after midnight, the newest readings can be over an hour old: their last hour's rain (and wind) is + counted from the newest reading, not from the clock, so the rain in them isn't dropped and the verdict doesn't flip to unlikely.""" + stale = NOW_TS - 75 * 60 # the newest reading 75 minutes before the time asked + rows = station(daily=lambda i: 0.0 if i < STEPS - 6 else 0.4 * (i - STEPS + 6), rate=lambda i: 0.0, now_ts=stale) + out = read(rows, None, NOW_TS) + assert out["recent_rain"]["rained"] and out["recent_rain"]["last_hour_mm"] == 2.4 and out["verdict"] != "unlikely" + assert out["newest"] == stale diff --git a/tests/test_service_pollen.py b/tests/test_service_pollen.py new file mode 100644 index 00000000..a29ab547 --- /dev/null +++ b/tests/test_service_pollen.py @@ -0,0 +1,87 @@ +"""The `pollen` tool (lib/service/pollen.py): the pollen source's lines, each level with its emoji and its day, its text, what is held +when the request says not to fetch, and the off-season answer. (Until step 6c also held to pollen_asthma's answers and the bot's old +words, tests/old_tools.py and tests/report_words.py, deleted with them.)""" + +import json +from datetime import date, datetime, time as dtime, timedelta + +from lib.pollen.source import OFF_SEASON +from lib.service.common import FRESH +from lib.service.context import Context +from lib.service.pollen import DESCRIPTION, PARAMETERS, tools +from tests.fakes import TZ +from tests.test_pollen import SEASON_DAY, make, page + + +def got(text: str) -> dict: + return json.loads(text) + + +def context(pollen, day: date = SEASON_DAY, hour: int = 12) -> Context: + """The context the tool is built over, its clock at `hour` on `day` (the pollen source's own clock says the same, make()).""" + return Context(pollen=pollen, tz=TZ, clock=lambda: datetime.combine(day, dtime(hour), tzinfo=TZ).timestamp()) + + +def tool(ctx): + (it,) = tools(ctx) + return it + + +async def test_the_lines_are_pollen_asthmas_and_each_level_has_its_emoji_and_day(tmp_path): + pollen, calls = make(tmp_path, lambda: page(grass="High", asthma="Moderate")) + pollen_tool = tool(context(pollen)) + assert pollen_tool.name == "pollen" and pollen_tool.annotations == {"readOnlyHint": True, "openWorldHint": True} + out = got(await pollen_tool.call({})) + assert len(calls) == 1 # nothing held: fetched, as pollen_asthma does + assert out["lines"] == pollen.lines() == ["Grass pollen forecast: 🔴 High", "Thunderstorm asthma forecast: 🟠 Moderate"] + assert out["grass"] == {"level": "High", "emoji": "🔴", "day": "2026-11-10", "day_text": "Tue 10 Nov 2026"} + assert out["asthma"] == {"level": "Moderate", "emoji": "🟠", "updated": "1 Oct 2026 4:00pm"} + assert out["in_season"] is True and out["season"] == "October to December" and out["scale"] == ["Low", "Moderate", "High", "Extreme"] + assert out["place"] == pollen.place and out["source"].startswith("melbournepollen.com.au") and out["fresh"] == FRESH and "period" not in out + fetched = datetime.fromtimestamp(int(pollen.fetched_at), TZ) + assert out["fetched_at"] == out["as_of"]["time"] == fetched.isoformat() + assert "Central" not in json.dumps(out) # (the district is never named, as in pollen_asthma's) + await pollen.close() + + +async def test_its_text_is_its_heading_and_a_bullet_per_line(tmp_path): + pollen, _ = make(tmp_path, lambda: page(grass="Low", asthma="Low")) + out = got(await tool(context(pollen)).call({})) + assert out["text"].startswith("Pollen & asthma (") and out["text"].endswith("\n• Grass pollen forecast: 🟢 Low\n• Thunderstorm asthma forecast: 🟢 Low") + later = SEASON_DAY + timedelta(days=1) + assert got(await tool(context(pollen, later)).call({}))["text"].endswith(out["text"].split("\n", 1)[1]) + await pollen.close() + + +async def test_a_forecast_for_another_day_says_its_day_and_a_missing_asthma_level_is_said_so(tmp_path): + pollen, _ = make(tmp_path, lambda: page(grass="Moderate", day=SEASON_DAY + timedelta(days=1), season=False)) + out = got(await tool(context(pollen)).call({})) + assert out["lines"] == pollen.lines() == ["Grass pollen forecast: 🟠 Moderate (forecast for Wed 11 Nov)"] + assert out["grass"]["day"] == "2026-11-11" and out["asthma"] is None + assert out["asthma_note"] == "The page had no thunderstorm asthma level for this district when it was last read." + await pollen.close() + + +async def test_with_fetch_false_it_answers_from_what_is_held_and_fetches_nothing(tmp_path): + pollen, calls = make(tmp_path) + out = got(await tool(context(pollen)).call({}, {"fetch": False})) + assert out == {"error": "No pollen levels are available right now."} and calls == [] + await pollen.warm(True) + calls.clear() + held = got(await tool(context(pollen)).call({}, {"fetch": False})) + assert held["lines"] == pollen.lines() and calls == [] + await pollen.close() + + +async def test_out_of_season_it_gives_pollen_asthmas_answer_and_fetches_nothing(tmp_path): + pollen, calls = make(tmp_path) + pollen.now = lambda: datetime(2026, 1, 15, 12, 0) + out = await tool(context(pollen, date(2026, 1, 15))).call({}) + assert got(out) == {"error": OFF_SEASON} and calls == [] + await pollen.close() + + +def test_it_is_offered_only_with_the_pollen_source_and_its_description_says_what_it_is_not_for(): + assert tools(Context(tz=TZ)) == [] + assert len(DESCRIPTION) < 1500 and "forecast" in DESCRIPTION and "October to December" in DESCRIPTION and "{}" in DESCRIPTION + assert PARAMETERS == {"type": "object", "properties": {}} diff --git a/tests/test_service_readings.py b/tests/test_service_readings.py new file mode 100644 index 00000000..f243c681 --- /dev/null +++ b/tests/test_service_readings.py @@ -0,0 +1,201 @@ +"""The service's `readings` tool (lib/service/readings.py): one reading's values at an interval, over a period in words (its engine, +lib/history.py, is tests/test_history.py's).""" + +import json +from datetime import datetime +from types import SimpleNamespace + +import pytest + +from lib.history import INTERVALS, MAX_ROWS +from lib.service import readings +from lib.service.common import FRESH +from lib.service.context import Context +from lib.service.names import Catalogue +from lib.storage import Storage +from lib.storage.catalogue import CLOUD +from lib.timeutil import local_epoch +from lib.tools import Tools, Turn +from tests.fakes import TZ + +MAC, LOC = "M", "42" +NOW = local_epoch(datetime(2026, 11, 9, 1, 47), TZ) # Mon 9 Nov 2026 1:47am, as lib/history.py's tests ask +SENT = {"outdoor": {"temperature": "℃", "temperature_low": "℃", "humidity": "%"}, "indoor": {"temperature": "℃", "humidity": "%"}, + "wind": {"wind_speed": "km/h", "wind_gust": "km/h", "wind_direction": "º"}, "rainfall": {"daily": "mm", "rain_rate": "mm/hr"}} + + +def at(day: int, hour: int, minute: int = 0) -> int: + return local_epoch(datetime(2026, 11, day, hour, minute), TZ) + + +@pytest.fixture +def storage(tmp_path): + s = Storage(tmp_path / "ecobot.sqlite", TZ) + yield s + s.close() + + +def put(storage, sensor: str, res: str, rows: list[dict]): + """Readings written as a source writes them: an Ecowitt group's, or the air sensor's ("air").""" + def write(w): + s = w.air_sensor(LOC) if sensor == "air" else w.ecowitt_sensor(MAC, sensor) + w.put(s, res, rows, CLOUD) + storage.writer.run(write, ()) + + +class AirStore: + """The air sensor's readings in the file, as AirGradient keeps them (lib/airgradient/readings.py): its sensor is a property.""" + + def __init__(self, storage): + self.storage = storage + + @property + def sensor(self): + return self.storage.air_sensor(LOC) + + +def sources(storage): + """(the station, the air sensor) as the tools read them: the file, the station's MAC, the air sensor's place in the file.""" + return SimpleNamespace(storage=storage, mac=MAC, tz=TZ), SimpleNamespace(store=AirStore(storage), tz=TZ) + + +def tool(storage): + station, air = sources(storage) + (made,) = readings.tools(Context(eco=station, air=air, catalogue=Catalogue.of(SENT), tz=TZ, clock=lambda: NOW)) + return made + + +async def ask(storage, meta: dict | None = None, **args) -> dict: + return json.loads(await tool(storage).call(args, meta)) + + +# ---------- what it takes ---------- +def test_it_takes_one_reading_a_period_in_words_and_an_interval(storage): + made = tool(storage) + props = made.parameters["properties"] + assert made.name == "readings" and made.parameters["required"] == ["reading", "interval"] + assert set(props) == {"reading", "period", "start", "end", "interval"} and props["interval"]["enum"] == list(INTERVALS) + assert "Default: last 24 hours" in props["period"]["description"] and "this week" in props["period"]["description"] + assert "outdoor.humidity" in props["reading"]["description"] and "ONE reading" in props["reading"]["description"] + assert len(made.description) < 1500 and all(f"({tool})" in made.description for tool in ("summary", "days", "current")) + assert 'a record ("hottest ever", even "use 5 minute data": summary, period "on record")' in made.description + assert '"past week" (the last 7 days) is never sent as "last week"' in props["period"]["description"] + assert made.description.count("{reading:") >= 3 and "`value_is`" in made.description and "`fits`" in made.description + assert made.annotations == {"readOnlyHint": True, "openWorldHint": False} # it reads the file only + + +# ---------- the rows ---------- +async def test_the_rows_are_the_bots_readings_over_the_period_the_words_name(storage): + put(storage, "outdoor", "30min", [{"ts": at(8, 20) + 1800 * i, "humidity": 60 + 10 * (i // 2)} for i in range(4)]) # 8pm to 9:30pm + put(storage, "outdoor", "5min", [{"ts": at(8, 22) + 300 * i, "humidity": 70 + (i // 12)} for i in range(12 * 4 - 2)]) # 10pm on + out = await ask(storage, reading="outdoor.humidity", period="last 5 hours", interval="1hour") # "humidity each hour for the last 5 hours" + assert list(out)[:3] == ["period", "as_of", "fresh"] and out["fresh"] == FRESH + assert out["period"]["asked"] == "last 5 hours" and out["period"]["text"] == "the last 5 hours: Sun 8 Nov 8:47pm – Mon 9 Nov 2026 1:47am" + assert out["as_of"] == {"text": "Mon 9 Nov 2026 1:47am", "time": "2026-11-09T01:47:00+11:00"} + assert list(out)[3:8] == ["reading", "label", "unit", "interval", "value_is"] + assert (out["reading"], out["label"], out["unit"], out["interval"]) == ("outdoor.humidity", "Outdoor humidity", "%", "1hour") + assert [r[1] for r in out["rows"]] == [60, 70, 70, 71, 72, 73] and out["from"] == ["5min", "30min"] and "note_last" in out + + +async def test_with_no_period_it_reads_the_last_24_hours(storage): + put(storage, "outdoor", "5min", [{"ts": at(8, 1) + 300 * i, "temperature": 10.0 + i % 12} for i in range(24 * 12 + 9)]) + out = await ask(storage, reading="temperature", interval="1hour") + assert out["period"]["asked"] == "last 24 hours" and out["period"]["start"] == "2026-11-08T01:47:00+11:00" + assert len(out["rows"]) == 25 and out["rows"][0][0] == "Sun 8 Nov 2026 1:00am" and out["rows"][-1][0] == "Mon 9 Nov 2026 1:00am" + + +async def test_rain_gusts_and_days_are_read_as_the_bot_reads_them(storage): + put(storage, "rainfall", "5min", [{"ts": at(8, 22, 30), "daily": 0.0}, {"ts": at(8, 23), "daily": 0.0}, {"ts": at(8, 23, 30), "daily": 1.0}, + {"ts": at(8, 23, 55), "daily": 2.0}, {"ts": at(9, 0), "daily": 0.0}, {"ts": at(9, 0, 30), "daily": 0.5}]) + out = await ask(storage, reading="rain", start="2026-11-08 23:00", end="2026-11-09 00:59", interval="hourly") + assert out["reading"] == "rainfall.rain" and out["interval"] == "1hour" and [r[1] for r in out["rows"]] == [2.0, 0.5] # the midnight reset + assert out["value_is"] == "the mm of rain that fell in the interval" and out["columns"] == ["time", "value"] + put(storage, "wind", "5min", [{"ts": at(8, 22) + 300 * i, "wind_speed": 5.0, "wind_gust": 10.0 + i} for i in range(24)]) + out = await ask(storage, reading="gust", start="2026-11-08 22:00", end="2026-11-08 23:59", interval="1hour") + assert out["reading"] == "wind.wind_gust" and [r[1] for r in out["rows"]] == [21.0, 33.0] + put(storage, "outdoor", "5min", [{"ts": at(6, 0) + 300 * i, "temperature": 10.0 + (i % 288 == 180) * 10} for i in range(288 * 2)]) + out = await ask(storage, reading="outdoor.temperature", start="2026-11-06", end="2026-11-07", interval="1day") # dates: whole days + assert out["columns"] == ["day", "value", "low", "low_time", "high", "high_time"] and out["rows"][0][:5] == ["Fri 6 Nov 2026", 10.0, 10.0, "12:00am", 20.0] + + +async def test_the_air_sensors_readings_and_its_own_temperature(storage): + rows = [{"ts": at(8, 22) + 300 * i, "pm2_5": 5.0, "pm10": 8.0, "pm1": 3.0, "air_temperature": 18.0 + i} for i in range(6)] + rows[3] |= {"pm2_5": 50.0, "pm10": 60.0, "pm1": 40.0} # a glitch of the sensor, taken out as air_quality takes it out + put(storage, "air", "5min", rows) + out = await ask(storage, reading="pm2.5", start="2026-11-08 22:00", end="2026-11-08 22:29", interval="30min") + assert out["reading"] == "air.pm2_5" and out["unit"] == "µg/m³" and out["rows"] == [["Sun 8 Nov 2026 10:00pm", 5.0, 5.0, 5.0]] + out = await ask(storage, reading="airgradient temperature", start="2026-11-08 22:00", end="2026-11-08 22:29", interval="30min") + assert (out["reading"], out["label"], out["unit"]) == ("air.temperature", "AirGradient temperature", "°C") and out["rows"][0][1:] == [20.5, 18.0, 23.0] + + +async def test_a_word_for_several_readings_reads_the_first_and_names_the_others(storage): + put(storage, "outdoor", "5min", [{"ts": at(9, 1), "humidity": 80}]) + out = await ask(storage, reading="humidity", period="last 30 minutes", interval="5min") + assert out["reading"] == "outdoor.humidity" and "indoor.humidity" in out["note_others"] and "call it again" in out["note_others"] + out = await ask(storage, reading="wind", period="last 30 minutes", interval="5min") + assert out["reading"] == "wind.wind_speed" and "note_others" not in out # wind is its speed: its direction goes with it only on a chart + put(storage, "wind", "5min", [{"ts": at(9, 1, 5 * i), "wind_speed": 5.0, "wind_direction": 90 + i} for i in range(9)]) + out = await ask(storage, reading="wind direction", period="last 30 minutes", interval="5min") + assert out["reading"] == "wind.wind_direction" and out["columns"] == ["time", "value"] and out["rows"][-2:] == [["Mon 9 Nov 2026 1:40am", 98], ["Mon 9 Nov 2026 1:45am", None]] + + +# ---------- refusals that teach ---------- +async def test_a_reading_or_an_interval_it_cant_read_lists_those_it_can(storage): + out = await ask(storage, reading="soil moisture", interval="1hour") + assert "isn't a reading" in out["error"] and "outdoor.humidity" in out["names"] and out["words"]["pressure"] == ["pressure.relative"] + out = await ask(storage, interval="1hour") + assert out["error"].startswith("Send `reading`") and "rainfall.rain" in out["names"] + out = await ask(storage, reading="humidity") + assert out["error"].startswith("Send `interval`") and out["intervals"] == list(INTERVALS) + out = await ask(storage, reading="humidity", interval="fortnightly") + assert "'fortnightly' isn't one" in out["error"] and out["intervals"] == list(INTERVALS) + + +async def test_a_period_it_cant_read_says_what_it_can(storage): + out = await ask(storage, reading="humidity", period="the other day", interval="1hour") + assert "isn't a period" in out["error"] and any(form.startswith("last N hours") for form in out["forms"]) + assert "It is now Mon 9 Nov 2026 1:47am." in out["error"] + assert "use forecast" in (await ask(storage, reading="humidity", period="tomorrow", interval="1hour"))["error"] + both = await ask(storage, reading="humidity", period="today", start="2026-11-08", interval="1hour") # two spans: refused + assert "`period` 'today' is Mon 9 Nov 2026 but `start`/`end` say Sun 8 Nov 2026 – now: send one of them" in both["error"] + junk = await ask(storage, reading="humidity", period="today", start="count_only", interval="1hour") # junk: the period, said so + assert "error" not in junk and junk["period"]["asked"] == "today" and "were ignored" in junk["period"]["note"] + out = await ask(storage, reading="humidity", period="on record", interval="1day") + assert "Nothing is held yet" in out["error"] + + +async def test_too_many_rows_are_refused_with_the_interval_that_fits_and_that_one_is_accepted(storage): + out = await ask(storage, reading="outdoor.temperature", period="last 3 days", interval="5min") + assert out["error"].startswith("Too many rows: the last 3 days") and out["rows"] > MAX_ROWS and out["max_rows"] == MAX_ROWS + assert out["fits"] == "30min" and "Ask again with interval 30min." in out["error"] + assert "error" not in await ask(storage, reading="outdoor.temperature", period="last 3 days", interval=out["fits"]) + out = await ask(storage, reading="outdoor.temperature", period="last 2 years", interval="1day") + assert out["fits"] is None and "summary" in out["error"] and "days" in out["error"] + + +async def test_on_record_starts_at_the_first_day_held(storage): + put(storage, "outdoor", "5min", [{"ts": at(6, 12) + 300 * i, "temperature": 12.0} for i in range(12)]) + out = await ask(storage, reading="outdoor.temperature", period="on record", interval="1day") + assert out["period"]["start"] == "2026-11-06T00:00:00+11:00" and [r[0] for r in out["rows"]] == \ + ["Fri 6 Nov 2026", "Sat 7 Nov 2026", "Sun 8 Nov 2026", "Mon 9 Nov 2026"] and out["missing"] == 3 + + +async def test_what_isnt_held_is_said_never_filled(storage): + out = await ask(storage, reading="outdoor.humidity", period="last 2 hours", interval="1hour") + assert out["rows"] == [] and out["note"] == "Nothing is stored for this sensor yet." + put(storage, "outdoor", "5min", [{"ts": at(7, 12), "temperature": 12.0}]) # the sensor has readings, none of them here + out = await ask(storage, reading="outdoor.temperature", start="2026-11-09 01:00", end="2026-11-09 01:10", interval="1min") + assert out["missing"] == 10 and "note_minutes" in out and "never fill the gap" in out["note"] # (an end with a time stops at it) + put(storage, "outdoor", "5min", [{"ts": at(9, 1, 5 * i), "temperature": 12.0} for i in range(3)]) + out = await ask(storage, reading="outdoor.temperature", start="2026-11-09 01:00", end="2026-11-09 01:10", interval="1min") + assert out["fits"] == "5min" and "note_coarser" in out + + +# ---------- only its arguments reach it ---------- +async def test_only_the_arguments_reach_it_and_its_metadata_changes_nothing(storage): + put(storage, "outdoor", "5min", [{"ts": at(9, 1, 5 * i), "humidity": 80 + i} for i in range(9)]) + args = {"reading": "outdoor.humidity", "period": "last hour", "interval": "5min"} + direct = await tool(storage).call(args) + via_bot = await Tools([tool(storage).tool()]).call("readings", json.dumps(args), Turn(per_day=True)) + assert via_bot == direct and json.loads(direct)["interval"] == "5min" + assert await tool(storage).call(args, {"fetch": False, "priority": "background"}) == direct # nothing is fetched here anyway diff --git a/tests/test_service_relate.py b/tests/test_service_relate.py new file mode 100644 index 00000000..c14a8e9f --- /dev/null +++ b/tests/test_service_relate.py @@ -0,0 +1,239 @@ +"""The service's `relate` tool (lib/service/relate.py): rain against one reading over whole days, with the findings of the bot's +weather_link (pressure, humidity, wind) and air_link (PM2.5, PM10), and a chart that says how to draw it again.""" + +import dataclasses +import json +import time +from datetime import date, timedelta +from types import SimpleNamespace + +from lib.airgradient.readings import NOT_HELD, Held +from lib.compose import Composer +from lib.ecowitt.link import link +from lib.service import relate +from lib.service.common import CHART_NOTE +from lib.service.context import Context +from lib.timeutil import local_date +from lib.tools import Tools, Turn +from tests.clocks import yesterday_at +from tests.fakes import TZ, archived_station +from tests.test_chart_json import errors +from tests.test_compose import StubAir + + +class HeldStubAir(StubAir): + """The air sensor as the composer reads it (StubAir), its readings also held in its file (`store`), as AirGradient's are: what a + request that may not fetch reads. `fetched` counts the reads that may fetch.""" + + def __init__(self, days=40): + super().__init__(days) + self.fetched = 0 + self.store = SimpleNamespace(held=self._held, load=self._load) + + async def rows(self, t0, t1): + self.fetched += 1 + return await super().rows(t0, t1) + + async def _held(self, days): + have = {local_date(r["ts"], TZ) for r in self.readings} + return {d: Held(288, False) if d in have else NOT_HELD for d in days} + + async def _load(self, lo, hi): + return [r for r in self.readings if lo <= r["ts"] < hi] + + +async def world(tmp_path, archived_cache): + """(the context over the archived station and a stand-in air sensor, at one moment; the station).""" + eco, _ = await archived_station(tmp_path, archived_cache) + sensor, now = HeldStubAir(), int(time.time()) + ctx = Context(eco=eco, air=sensor, composer=Composer(eco, sensor), tz=TZ, clock=lambda: now) + return ctx, eco + + +async def ask(ctx, meta: dict | None = None, **args) -> dict: + (made,) = relate.tools(ctx) + return json.loads(await made.call(args, meta)) + + +def days_of(out: dict) -> tuple[date, date]: + """The first and last day a result's period covers.""" + start, end = (date.fromisoformat(out["period"][k][:10]) for k in ("start", "end")) + return start, end - timedelta(days=1) + + +async def replays(ctx, chart: dict, **swap) -> dict: + """The call a chart says drew it, made again (with `swap` in its arguments).""" + drawn = chart["drawn_by"] + return await ask(ctx, **{**drawn["arguments"], **swap}) + + +# ---------- what it takes ---------- +async def test_it_takes_a_reading_whole_days_and_a_chart_and_says_what_it_is_not_for(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + (made,) = relate.tools(ctx) + props = made.parameters["properties"] + assert made.name == "relate" and set(props) == {"reading", "period", "start", "end", "chart"} and "required" not in made.parameters + assert "Whole days only, up to yesterday" in props["period"]["description"] and "the last 90 days" in props["period"]["description"] + assert all(name in props["reading"]["description"] for name in ("pressure.relative", "outdoor.humidity", "wind.wind_speed", "air.pm2_5", "air.pm10")) + assert len(made.description) < 1500 and "\"X against rain\" is this tool" in made.description + assert '"plot the traffic light rating against rainfall": summary' in made.description # (a live run sent it here) + assert all(f"({tool})" in made.description for tool in ("scan", "summary", "days")) and made.description.count("{reading:") >= 3 + assert made.annotations == {"readOnlyHint": True, "openWorldHint": True} # the air sensor's missing days are fetched + (station_only,) = relate.tools(Context(eco=eco, tz=TZ)) + assert station_only.annotations["openWorldHint"] is False + await eco.close() + + +# ---------- the findings ---------- +async def test_with_nothing_named_it_is_pressure_against_rain_over_the_last_90_days_as_weather_link_finds(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx) + assert list(out)[:9] == ["period", "as_of", "fresh", "reading", "label", "unit", "verdict", "how_to_read", "findings"] + assert (out["reading"], out["label"], out["unit"]) == ("pressure.relative", "Pressure", "hPa") + assert out["period"]["asked"] == "last 90 days" and out["period"]["cut"].endswith("today isn't over") + first, last = days_of(out) + assert last == ctx.now().date() - timedelta(days=1) and (last - first).days == 89 + before, _, _, _ = link(eco.storage.read_now, eco.mac, TZ, {"start_date": str(first), "end_date": str(last)}, ctx.now()) + assert {k: v for k, v in out.items() if k in before and k != "period"} == \ + {k: v for k, v in before.items() if k not in ("period", "driver")} + assert "charts" not in out and "chart_note" not in out and "driver" not in out # a chart only when asked + await eco.close() + + +async def test_the_words_people_use_name_the_reading(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + for words, name in (("humidity", "outdoor.humidity"), ("wind", "wind.wind_speed"), ("barometer", "pressure.relative"), + ("outdoor humidity", "outdoor.humidity"), ("PM2.5", "air.pm2_5"), ("pm10", "air.pm10")): + out = await ask(ctx, reading=words, period="last 30 days") + assert out["reading"] == name and out["verdict"] and "note_others" not in out, words + out = await ask(ctx, reading="pm2.5") + assert out["period"]["asked"] == "last 60 days" and out["label"] == "PM2.5" # the air's own default + out = await ask(ctx, reading="air", period="last 30 days") # the air sensor: its first that rain relates to + assert out["reading"] == "air.pm2_5" and "air.pm10" in out["note_others"] + out = await ask(ctx, reading="pressure and humidity", period="last 30 days") + assert out["reading"] == "pressure.relative" and "outdoor.humidity" in out["note_others"] and "call again" in out["note_others"] + await eco.close() + + +async def test_air_against_rain_is_air_links_findings(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx, reading="air.pm10", period="last 3 weeks") + first, last = days_of(out) + before = json.loads(await ctx.composer.air_link({"metric": "pm10", "start_date": str(first), "end_date": str(last)}, Turn())) + assert {k: v for k, v in out.items() if k in before and k != "period"} == \ + {k: v for k, v in before.items() if k not in ("period", "metric", "chart")} + assert out["how_to_read"].startswith("Open with `verdict`") and (out["reading"], out["unit"]) == ("air.pm10", "µg/m³") + await eco.close() + + +async def test_a_request_that_may_not_fetch_reads_the_air_from_the_file(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + fetched = await ask(ctx, reading="pm2.5", chart=True) + assert ctx.air.fetched == 1 + held = await ask(ctx, {"fetch": False}, reading="pm2.5", chart=True) + assert ctx.air.fetched == 1 and held["notes"] == {"missing": "20 older day(s) aren't in the bot's cache yet and were left out"} + assert {k: v for k, v in held.items() if k != "notes"} == fetched # (the 40 days it holds: those the stand-in has) + await eco.close() + + +# ---------- refusals that teach ---------- +async def test_what_it_cant_relate_is_refused_with_what_it_can(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx, reading="temperature") + assert "can't be set against rain" in out["error"] and out["readings"] == ["pressure.relative", "outdoor.humidity", "wind.wind_speed", + "air.pm2_5", "air.pm10"] + out = await ask(ctx, reading="rain") + assert "rainfall.rain" in out["error"] and "use days" in out["error"] + out = await ask(ctx, reading="soil moisture") + assert "isn't a reading" in out["error"] and "pressure.relative" in out["names"] + assert "needs both the weather station and the air sensor" in (await ask(Context(eco=eco, tz=TZ), reading="air.pm2_5"))["error"] + await eco.close() + + +async def test_a_period_that_isnt_whole_days_points_to_the_tools_that_read_one(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + pinned = dataclasses.replace(ctx, clock=yesterday_at(14, 5, TZ).timestamp) # (at 2:05pm: this morning is over) + for period in ("today", "last 5 hours", "this morning"): + out = await ask(pinned, period=period) + assert "use summary or readings" in out["error"], period + midnight = dataclasses.replace(ctx, clock=yesterday_at(0, 5, TZ).timestamp) # at 12:05am this morning is still ahead + assert "use summary or readings" in (await ask(midnight, period="today"))["error"] + ahead = (await ask(midnight, period="this morning"))["error"] + assert "'this morning' is in the future" in ahead and "use forecast" in ahead and ahead.endswith("12:05am.") + assert "has a time" in (await ask(ctx, start="2026-09-01 10:00"))["error"] + assert "use forecast" in (await ask(ctx, period="next week"))["error"] + out = await ask(ctx, period="whenever") + assert "isn't a period" in out["error"] and "on record, all time, ever (from the first reading held)" in out["forms"] + await eco.close() + + +async def test_on_record_starts_where_both_the_reading_and_the_rain_are_held(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx, period="on record") + first, last = days_of(out) + assert out["verdict"] and (last - first).days > 500 and out["period"]["text"].startswith("on record: ") + await eco.close() + + +# ---------- the chart ---------- +async def test_a_chart_when_asked_carries_the_call_that_draws_it_again(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx, reading="pressure", chart=True) + (chart,) = out["charts"] + assert out["chart_note"] == CHART_NOTE and chart["title"] == "Pressure, Rain" and chart["source"] == "Ecowitt weather station" + assert errors(chart) == [] + assert chart["drawn_by"] == {"tool": "relate", "arguments": {"reading": "pressure.relative", "period": "last 90 days", "chart": True}, + "periods": [{"period": "1m", "label": "1M"}, {"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}]} + assert await replays(ctx, chart) == out # the same call again: the same answer + for each in chart["drawn_by"]["periods"]: + again = await replays(ctx, chart, period=each["period"]) + assert "error" not in again and again["period"]["asked"] == each["period"], each + (redrawn,) = again["charts"] + assert redrawn["title"] == chart["title"] and redrawn["period"] == [str(d) for d in days_of(again)] + assert redrawn["drawn_by"] == {**chart["drawn_by"], "arguments": {**chart["drawn_by"]["arguments"], "period": each["period"]}} + await eco.close() + + +async def test_a_chart_of_dates_is_drawn_again_from_those_dates(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + yesterday = ctx.now().date() - timedelta(days=1) + first, last = yesterday - timedelta(days=40), yesterday - timedelta(days=10) + out = await ask(ctx, reading="humidity", start=str(first), end=str(last), chart=True) + (chart,) = out["charts"] + assert chart["drawn_by"]["arguments"] == {"reading": "outdoor.humidity", "period": f"{first} to {last}", "chart": True} + again = await replays(ctx, chart) + assert again["charts"] == out["charts"] and again["findings"] == out["findings"] and again["period"]["text"] == out["period"]["text"] + await eco.close() + + +async def test_the_air_against_rain_is_drawn_with_its_zones_and_drawn_again_over_each_period(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx, reading="pm2.5", chart=True) + (chart,) = out["charts"] + assert chart["title"] == "PM2.5, Rain" and chart["source"] == "Ecowitt weather station and AirGradient sensor" + assert chart["panels"][0]["zones"] == [9.0, 55.4] and errors(chart) == [] + assert chart["drawn_by"]["arguments"] == {"reading": "air.pm2_5", "period": "last 60 days", "chart": True} + assert await replays(ctx, chart) == out + for each in chart["drawn_by"]["periods"]: + again = await replays(ctx, chart, period=each["period"]) + assert "error" not in again and [c["title"] for c in again["charts"]] == ["PM2.5, Rain"], each + await eco.close() + + +async def test_a_chart_is_sent_in_the_points_the_request_asks_for_and_only_when_the_arguments_ask(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + small = await ask(ctx, {"chart_points": 20}, reading="humidity", chart=True) + lines = [s for p in small["charts"][0]["panels"] for s in p["series"] if s["kind"] in ("line", "band")] + assert lines and all(len(s["points"]) <= 20 for s in lines) + (made,) = relate.tools(ctx) + asked = json.loads(await Tools([made.tool()]).call("relate", "{}", Turn(chart_asked=True))) + assert "charts" not in asked # the words of the question never reach it: only `chart` draws + await eco.close() + + +def test_a_period_sent_beside_start_and_end_is_the_words_a_replay_is_drawn_by(): + from datetime import datetime + from lib.periods_text import Period + period = Period("this week", datetime(2026, 11, 3), datetime(2026, 11, 10), "the last 7 days") + assert relate.whole_day_words({"period": "this week", "start": "2026-11-01", "end": "2026-11-02"}, period) == "this week" + assert relate.whole_day_words({"start": "2026-11-03"}, period) == "2026-11-03 to 2026-11-09" diff --git a/tests/test_service_scan.py b/tests/test_service_scan.py new file mode 100644 index 00000000..1377252c --- /dev/null +++ b/tests/test_service_scan.py @@ -0,0 +1,162 @@ +"""The service's `scan` tool (lib/service/scan.py): each air reading against every weather reading over whole days, with the findings of +the bot's air_scan, at most 400 days, and a chart of the strongest pair that says how to draw it again.""" + +import json +import time +from datetime import date, datetime, timedelta + +from lib.compose import Composer +from lib.service import scan +from lib.service.common import CHART_NOTE, read_period +from lib.service.context import Context +from lib.tools import Turn +from tests.fakes import TZ, archived_station, pressure +from tests.test_chart_json import errors +from tests.test_service_relate import HeldStubAir, days_of + + +class PressureAir(HeldStubAir): + """An air sensor whose PM2.5 follows the station's pressure (and whose PM10 changes by the day): a relationship that stands out, + so the scan has a strongest pair to draw.""" + + def __init__(self, days=60): + super().__init__(days=0) + now = datetime.now(TZ).replace(minute=0, second=0, microsecond=0) + for i in range(days * 288, 0, -1): + when = now - timedelta(minutes=5 * i) + ts = int(when.timestamp()) + self.readings.append({"ts": ts, "pm2_5": 2 * (pressure(ts) - 1000), "pm10": 10.0 + when.day % 3}) + + +async def world(tmp_path, archived_cache, air=None): + eco, _ = await archived_station(tmp_path, archived_cache) + sensor, now = air or PressureAir(), int(time.time()) + return Context(eco=eco, air=sensor, composer=Composer(eco, sensor), tz=TZ, clock=lambda: now), eco + + +async def ask(ctx, meta: dict | None = None, **args) -> dict: + (made,) = scan.tools(ctx) + return json.loads(await made.call(args, meta)) + + +async def replays(ctx, chart: dict, **swap) -> dict: + return await ask(ctx, **{**chart["drawn_by"]["arguments"], **swap}) + + +# ---------- what it takes ---------- +async def test_it_takes_an_air_reading_or_all_whole_days_and_a_chart(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + (made,) = scan.tools(ctx) + props = made.parameters["properties"] + assert made.name == "scan" and set(props) == {"reading", "period", "start", "end", "chart"} and "required" not in made.parameters + assert "Whole days only, up to yesterday" in props["period"]["description"] and "at most 400 days" in props["period"]["description"] + assert all(name in props["reading"]["description"] for name in ("air.pm2_5", "air.co2", "air.voc_index", "all of them")) + assert len(made.description) < 1500 and all(f"({tool})" in made.description for tool in ("relate", "summary", "current")) + assert "{reading: \"co2\"}" in made.description and "At most 400 days" in made.description + assert made.annotations == {"readOnlyHint": True, "openWorldHint": True} + await eco.close() + + +# ---------- the findings ---------- +async def test_with_nothing_named_it_scans_every_air_reading_over_the_last_90_days_as_air_scan_does(tmp_path, daytime_archive): + ctx, eco = await world(tmp_path, daytime_archive) + out = await ask(ctx) + assert list(out)[:7] == ["period", "as_of", "fresh", "reading", "verdict", "how_to_read", "findings"] + assert out["reading"] == "all" and out["period"]["asked"] == "last 90 days" and out["period"]["cut"].endswith("today isn't over") + assert out["verdict"] == "Yes - 1 relationship stands out" and "pressure" in out["findings"][0] + first, last = days_of(out) + assert last == ctx.now().date() - timedelta(days=1) and (last - first).days == 89 + before = json.loads(await ctx.composer.air_scan({"start_date": str(first), "end_date": str(last)}, Turn())) + assert {k: v for k, v in out.items() if k in before and k != "period"} == {k: v for k, v in before.items() if k not in ("period", "chart")} + assert "charts" not in out and "chart" not in out # a chart only when asked + await eco.close() + + +async def test_the_words_people_use_name_the_air_reading(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + for words, name in (("pm2.5", "air.pm2_5"), ("CO2", "air.co2"), ("voc", "air.voc_index"), ("air.nox_index", "air.nox_index"), + ("air", "all"), ("airgradient", "all"), ("everything", "all"), (["all"], "all"), ("", "all")): + out = await ask(ctx, reading=words, period="last 2 weeks") + assert out["reading"] == name and out["verdict"], words + await eco.close() + + +async def test_a_reading_with_nothing_to_scan_says_so(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) # (the stand-in measures no CO2) + out = await ask(ctx, reading="co2", chart=True) + assert out["verdict"] == "Not enough data to say" and out["findings"] and "charts" not in out + await eco.close() + + +async def test_what_it_cant_scan_is_refused_with_what_it_can(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + readings = ["all", "air.pm2_5", "air.pm10", "air.co2", "air.voc_index", "air.nox_index"] + out = await ask(ctx, reading="pm1") + assert "isn't an air reading this tool scans" in out["error"] and out["readings"] == readings + out = await ask(ctx, reading="temperature") + assert "use relate" in out["error"] and out["readings"] == readings + out = await ask(ctx, reading="pm2.5 and pm10") + assert "names 2 air readings: send one, or all" in out["error"] + assert "use summary or readings" in (await ask(ctx, period="today"))["error"] + assert "needs both the weather station and the air sensor" in (await ask(Context(eco=eco, tz=TZ)))["error"] + await eco.close() + + +def test_a_period_longer_than_400_days_is_cut_to_its_latest_and_says_so(): + now = datetime(2026, 11, 10, 14, 5, tzinfo=TZ) + two = read_period({"period": "2y"}, tz=TZ, now=now, default="last 90 days", whole_days=True) + cut, note = scan.latest_days(two, TZ) + assert (cut.first_day, cut.last_day) == (date(2025, 10, 6), date(2026, 11, 9)) and cut.asked == "2y" and cut.cut == two.cut + assert cut.start == datetime(2025, 10, 6, tzinfo=TZ) and cut.text == "its last 400 days: Mon 6 Oct 2025 – Mon 9 Nov 2026" + assert note == ("Only the last 400 days can be scanned in one call: this covers Mon 6 Oct 2025 – Mon 9 Nov 2026, not all of the last " + "2 years: Sun 10 Nov 2024 – Mon 9 Nov 2026.") + one = read_period({"period": "1y"}, tz=TZ, now=now, default="last 90 days", whole_days=True) + assert scan.latest_days(one, TZ) == (one, None) + + +async def test_a_long_period_is_scanned_over_its_latest_400_days_and_drawn_again_over_them(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + yesterday = ctx.now().date() - timedelta(days=1) + long = await ask(ctx, start=str(yesterday - timedelta(days=500)), chart=True) + assert days_of(long) == (yesterday - timedelta(days=399), yesterday) and long["period"]["text"].startswith("its last 400 days: ") + assert long["note_period"].startswith("Only the last 400 days can be scanned in one call") + (chart,) = long["charts"] + assert chart["drawn_by"]["arguments"]["period"] == f"{yesterday - timedelta(days=399)} to {yesterday}" # the days it scanned + again = await replays(ctx, chart) + assert again["charts"] == long["charts"] and again["findings"] == long["findings"] and "note_period" not in again + await eco.close() + + +async def test_a_request_that_may_not_fetch_reads_the_air_from_the_file(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + fetched = await ask(ctx, reading="pm2.5", period="last 30 days") + held = await ask(ctx, {"fetch": False}, reading="pm2.5", period="last 30 days") + assert ctx.air.fetched == 1 and held == fetched + await eco.close() + + +# ---------- the chart ---------- +async def test_a_chart_of_the_strongest_pair_carries_the_call_that_draws_it_again(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx, chart=True) + (chart,) = out["charts"] + assert out["chart_note"] == CHART_NOTE and chart["title"] == "PM2.5, Pressure" and errors(chart) == [] + assert chart["source"] == "Ecowitt weather station and AirGradient sensor" + assert chart["drawn_by"] == {"tool": "scan", "arguments": {"reading": "all", "period": "last 90 days", "chart": True}, + "periods": [{"period": "1m", "label": "1M"}, {"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}]} + assert await replays(ctx, chart) == out + for each in chart["drawn_by"]["periods"]: + again = await replays(ctx, chart, period=each["period"]) + assert "error" not in again and again["period"]["asked"] == each["period"], each + (redrawn,) = again["charts"] + assert redrawn["title"] == chart["title"] and redrawn["period"] == [str(d) for d in days_of(again)] + small = await ask(ctx, {"chart_points": 30}, chart=True) + assert all(len(s["points"]) <= 30 for p in small["charts"][0]["panels"] for s in p["series"] if s["kind"] in ("line", "band")) + await eco.close() + + +async def test_no_chart_when_nothing_stands_out(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache, air=HeldStubAir()) # PM2.5 by the day, nothing to do with the weather + out = await ask(ctx, reading="pm2.5", chart=True) + assert out["verdict"].startswith("Nothing stands out") and "charts" not in out and "chart_note" not in out + await eco.close() diff --git a/tests/test_service_summary.py b/tests/test_service_summary.py new file mode 100644 index 00000000..4d950f77 --- /dev/null +++ b/tests/test_service_summary.py @@ -0,0 +1,487 @@ +"""The `summary` tool (lib/service/summary.py): its arguments and defaults, the shape of what it answers, the refusals that teach, the +periods it reads, its charts with drawn_by (replayed, and over every period it lists), and the caption the bot wrote for the same +chart (the old lib/report.py), word for word: held to that oracle until step 6c deleted it (tests/report_words.py), pinned since in +tests/summary_words.json.""" + +import json +import re +from datetime import datetime, timedelta +from pathlib import Path + +from lib.airgradient import AirGradient +from lib.compose import Composer +from lib.ecowitt.days import day_values_on +from lib.service import summary +from lib.service.common import FRESH, ServiceTool +from lib.service.context import Context +from lib.service.daylook import FIGURES, day_look +from lib.tools import Turn +from lib.timeutil import day_bounds +from tests.fakes import TZ, air_transport, archived_station, config, rain_day +from tests.test_chart_json import errors as schema_errors +from tests import clocks, engines + + +async def make(tmp_path, archived_cache, air: bool = False, **air_options): + """(the tool, its Context, the fake Ecowitt): the archived station, and with `air` an AirGradient on the same file.""" + eco, fake = await archived_station(tmp_path, archived_cache) + source = None + if air: + transport, _ = air_transport(**{"rows_per_day": 288, **air_options}) + source = AirGradient(config(tmp_path), transport=transport, storage=eco.storage) + await source.start() + ctx = await Context.open(eco=eco, air=source, composer=Composer(eco, source) if source else None) + return summary.tools(ctx)[0], ctx, fake + + +async def close(ctx): + if ctx.air: + await ctx.air.close() + await ctx.eco.close() + + +async def ask(tool: ServiceTool, meta: dict | None = None, **args) -> dict: + return json.loads(await tool.call(args, meta)) + + +def without_drawn_by(chart: dict) -> dict: + return {k: v for k, v in chart.items() if k != "drawn_by"} + + +def days_ago(n: int) -> str: + return str(datetime.now(TZ).date() - timedelta(days=n)) + + +# ---------- the tool ---------- +async def test_the_tool_says_what_it_answers_what_it_is_not_for_and_how_to_read_it(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + assert tool.name == "summary" and tool.annotations == {"readOnlyHint": True, "openWorldHint": True} + assert list(tool.parameters["properties"]) == ["readings", "period", "start", "end", "average", "every_day", "chart", "chart_readings", + "layout", "invert_second_axis", "chart_answers_it"] + text = tool.description + assert len(text) <= 1500 + for words in ("{readings: [\"temperature\"], period: \"this week\"}", "chart_answers_it: true", "average: true", "\"all\"", "pm2.5", + ": days", ": readings", ": relate", ": current", ": forecast", "low_text", "day_look", "complete"): + assert words in text, words + # what the live runs got wrong: a device and a period is the past; "past week" isn't "last week"; a record with when is summary's + for words in ('"weather week"', '"ecowitt week"', 'the past, charted', '"past week" is the last 7 days', + '"last week" the previous Monday to Sunday', '"use 5 minute data"', 'period: "on record"', '"pm2.5:rating"', + '"wind 3m" {readings: ["wind"], period: "3m", chart: true}', '"lowest and highest humidity"', 'period: "yesterday to today"'): + assert words in text, words + readings = tool.parameters["properties"]["readings"]["description"] + assert "outdoor.temperature" in readings and "air.pm2_5" not in readings and readings.endswith( # (what this station holds) + "Default: outdoor and indoor temperature and humidity.") + assert tool.parameters["properties"]["period"]["description"].endswith("Default: today; with chart true and no period, the last 24 hours.") + assert tool.parameters["properties"]["layout"]["enum"] == ["auto", "panels", "two_axes", "same_axis"] + await close(ctx) + + +async def test_by_default_it_is_todays_outdoor_and_indoor_temperature_and_humidity_with_no_chart(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool) + assert list(out)[:4] == ["period", "as_of", "fresh", "series"] and out["fresh"] == FRESH + assert out["period"]["asked"] == "today" and out["period"]["text"].startswith("today: ") + assert list(out["series"]) == ["outdoor.temperature", "indoor.temperature", "outdoor.humidity"] # (the fake's indoor has no humidity) + assert "charts" not in out and "caption" not in out and "complete" not in out + await close(ctx) + + +# ---------- the figures ---------- +async def test_each_record_comes_with_its_wording_its_day_and_that_days_look(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["outdoor.temperature", "pressure"], period="this week", chart=False) + assert list(out["series"]) == ["outdoor.temperature", "pressure.relative"] and "charts" not in out + values, _ = await ctx.eco.storage.read(day_values_on, ctx.eco.mac, list(FIGURES), + [ctx.now().date() - timedelta(days=n) for n in range(7)]) + today = ctx.now().date() + + def looked(day): + return day_look({n: values[n].get(day) for n in FIGURES}, latitude=-37.8, day=day, so_far=day == today) + temp = out["series"]["outdoor.temperature"] + assert temp["unit"] == "°C" and isinstance(temp["low"], float) and temp["low"] <= temp["high"] + for want in ("low", "high"): + assert temp[f"{want}_text"] == f"{temp[want]} °C" + assert temp[f"{want}_when"].startswith(("at ", "around ")) and re.search(r" 20\d\d$", temp[f"{want}_date"]) + day = datetime.strptime(temp[f"{want}_date"], "%a %d %b %Y").date() + assert temp.get(f"{want}_day_look") == looked(day) + rows = temp["daily"] + assert len(rows) == 7 and list(rows)[-1] == f"{today:%a} {today.day} {today:%b}" + for label, row in rows.items(): + day = next(d for d in (today - timedelta(days=n) for n in range(7)) if f"{d:%a} {d.day} {d:%b}" == label) + assert row.get("day_look") == looked(day) and row["low"] <= row["high"] + # the fake's every 8th day of the year is wet (from 2pm): a week whose finished days hold one shows it (some weeks have none) + if any(rain_day(day_bounds(today - timedelta(days=n), TZ, last_second=True)[1]) >= 5 for n in range(1, 7)): + assert any(row.get("day_look", {}).get("word") == "wet" for row in rows.values()) + assert "average" not in temp + await close(ctx) + + +async def test_an_average_is_by_time_and_comes_with_each_days(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["outdoor.temperature"], period="this week", average=True, chart=False) + temp = out["series"]["outdoor.temperature"] + assert temp["low"] < temp["average"] < temp["high"] and temp["average_text"] == f"{temp['average']} °C" + assert all("average" in row for row in temp["daily"].values()) + old = json.loads(await engines.history(ctx.eco, {"start_date": f"{days_ago(6)} 00:00:00", "end_date": datetime.now(TZ).strftime( + "%Y-%m-%d %H:%M:%S"), "groups": "outdoor", "average": True})) + assert float(old["series"]["outdoor.temperature"]["average"]) == temp["average"] # weather_history's own + await close(ctx) + + +async def test_a_period_over_a_week_lists_the_days_of_its_records_or_with_every_day_all_of_them(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + some = (await ask(tool, readings=["outdoor.temperature"], period="last 14 days", chart=False))["series"]["outdoor.temperature"] + assert 1 <= len(some["daily"]) <= 2 and {some["low_date"][:-5], some["high_date"][:-5]} == set(some["daily"]) + every = (await ask(tool, readings=["outdoor.temperature"], period="last 14 days", chart=False, every_day=True))["series"] + assert len(every["outdoor.temperature"]["daily"]) == 14 + longer = (await ask(tool, readings=["outdoor.temperature"], period="last 40 days", chart=False, every_day=True))["series"] + assert "monthly" in longer["outdoor.temperature"] and "daily" not in longer["outdoor.temperature"] # by month, past 31 days + await close(ctx) + + +async def test_rain_is_the_mm_that_fell_its_total_and_its_wettest_day(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["rain"], period="last 14 days", chart=False) + rain = out["series"]["rainfall.rain"] + assert "charts" not in out and out["rain_total_mm"] == rain["total"] > 0 and rain["total_text"] == f"{rain['total']:.1f} mm" + assert rain["wettest_day"]["mm"] == 5.0 and rain["wettest_day"]["day_look"]["word"] == "wet" # the fake's wet day: 5 mm + assert list(rain["daily"]) == [next(iter(rain["daily"]))] and "low" not in rain # 14 days: only the wettest listed + every = await ask(tool, readings=["rain"], period="last 14 days", chart=False, every_day=True) + assert len(every["series"]["rainfall.rain"]["daily"]) == 14 + assert round(sum(r["total"] for r in every["series"]["rainfall.rain"]["daily"].values()), 1) == rain["total"] + drawn = await ask(tool, readings=["rain"], period="last 14 days") # the chart's total is the same + old_turn = Turn() + old = json.loads(await engines.history(ctx.eco, {"start_date": f"{days_ago(13)} 00:00:00", "end_date": datetime.now(TZ).strftime( + "%Y-%m-%d %H:%M:%S"), "groups": "rainfall", "chart_field": "rain", "chart": True}, old_turn)) + assert drawn["rain_total_mm"] == old["rain_total_mm"] == rain["total"] + long = await ask(tool, readings=["rain"], period="3m", chart=False) + assert re.fullmatch(r"[A-Z][a-z]{2} 20\d\d", list(long["series"]["rainfall.rain"]["monthly"])[0]) + await close(ctx) + + +async def test_wind_is_its_speed_and_its_direction_by_compass_point(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["wind", "gust"], period="this week", chart=False) + assert list(out["series"]) == ["wind.wind_speed", "wind.wind_direction", "wind.wind_gust"] + direction = out["series"]["wind.wind_direction"] + assert direction["most_common"].startswith(("N ", "NNW", "NNE")) and direction["steadiness"] and "low" not in direction + assert "daily" in direction + await close(ctx) + + +async def test_the_air_sensors_figures_are_air_qualitys_with_their_wording(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True) + out = await ask(tool, readings=["pm2.5", "co2", "air.temperature"], period="last 2 days", chart=False) + assert list(out["series"]) == ["air.pm2_5", "air.co2", "air.temperature"] + start, end = (datetime.fromisoformat(out["period"][k]).strftime("%Y-%m-%d %H:%M:%S") for k in ("start", "end")) + old = json.loads(await engines.air_history(ctx.air, {"start_date": start, "end_date": end, "metrics": ["air_temperature"]})) + pm = out["series"]["air.pm2_5"] + for k in ("low", "high", "average", "high_rating", "average_rating", "high_aqi_us", "high_band", "average_aqi_us", "average_band"): + assert pm[k] == old["pm2_5"][k], k + at = datetime.strptime(old["pm2_5"]["high_time"], "%a %d %b %Y %I:%M%p") # "Wed 4 Nov 2026 10:00am" + assert pm["high_text"] == f"{pm['high']} µg/m³" and pm["high_date"] == f"{at:%a} {at.day} {at:%b %Y}" + assert pm["high_when"] == f"at {at.hour % 12 or 12}{'' if not at.minute else f':{at:%M}'}{'am' if at.hour < 12 else 'pm'}" + assert out["series"]["air.temperature"]["average"] == old["air_temperature"]["average"] + assert "high_rating" not in out["series"]["air.temperature"] # its own temperature has no rating + await close(ctx) + + +# ---------- periods ---------- +async def test_a_chart_comes_for_three_days_or_more_and_chart_true_alone_is_the_last_24_hours(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + assert "charts" not in await ask(tool, readings=["pressure"], period="yesterday") + assert len((await ask(tool, readings=["pressure"], period="last 3 days"))["charts"]) == 1 + assert "charts" not in await ask(tool, readings=["pressure"], period="last 3 days", chart=False) + out = await ask(tool, readings=["pressure"], chart=True) + assert out["period"]["asked"] == "last 24 hours" and len(out["charts"]) == 1 + assert out["charts"][0]["drawn_by"]["arguments"]["period"] == "last 24 hours" + assert (await ask(tool, readings=["pressure"], chart="true"))["period"]["asked"] == "last 24 hours" # (as text too) + await close(ctx) + + +async def test_on_record_starts_at_the_first_day_held(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["outdoor.temperature"], period="on record", chart=False) + first = datetime.fromisoformat(out["period"]["start"]).date() + assert (ctx.now().date() - first).days in range(540, 560) # the fake station is 548 days old + assert "monthly" in out["series"]["outdoor.temperature"] + await close(ctx) + + +async def test_whole_days_sent_as_dates_are_drawn_by_as_words_and_a_time_lists_no_periods(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + dated = await ask(tool, readings=["pressure"], start=days_ago(9), end=days_ago(5)) + words = dated["charts"][0]["drawn_by"] + assert words["arguments"]["period"] == f"{days_ago(9)} to {days_ago(5)}" and "start" not in words["arguments"] + assert [p["period"] for p in words["periods"]] == ["1d", "7d", "1m", "3m", "1y"] + again = await ask(tool, **words["arguments"]) + assert without_drawn_by(again["charts"][0]) == without_drawn_by(dated["charts"][0]) and again["period"]["text"] == dated["period"]["text"] + beside = await ask(tool, readings=["pressure"], period="this week", start="count_only", end="cancel", chart=True) # junk dates + assert "were ignored" in beside["period"]["note"] and beside["charts"][0]["drawn_by"]["arguments"]["period"] == "this week" + other = await ask(tool, readings=["pressure"], period="this week", start=days_ago(30), end=days_ago(20), chart=True) + assert "send one of them" in other["error"] and "charts" not in other # dates that disagree with the period: refused + since = await ask(tool, readings=["pressure"], start=days_ago(4)) + assert since["charts"][0]["drawn_by"]["arguments"]["period"] == f"{days_ago(4)} to now" + timed = await ask(tool, readings=["pressure"], start=f"{days_ago(4)} 06:00", chart=True) + by = timed["charts"][0]["drawn_by"] + assert by["arguments"]["start"] == f"{days_ago(4)} 06:00" and "period" not in by["arguments"] and by["periods"] == [] + assert without_drawn_by((await ask(tool, **by["arguments"]))["charts"][0]) == without_drawn_by(timed["charts"][0]) + await close(ctx) + + +# ---------- charts and drawn_by ---------- +async def replays(tool: ServiceTool, out: dict) -> dict: + """Check the result's chart: drawn_by draws it again, and draws a chart over each period it lists, never refused.""" + (chart,) = out["charts"] + by = chart["drawn_by"] + assert by["tool"] == "summary" and set(by) == {"tool", "arguments", "periods"} + assert schema_errors(chart) == [] # drawn_by and all + again = await ask(tool, **by["arguments"]) + assert [without_drawn_by(c) for c in again["charts"]] == [without_drawn_by(chart)] and again["charts"][0]["drawn_by"] == by + for period in by["periods"]: + other = await ask(tool, **{**by["arguments"], "period": period["period"]}) + assert "error" not in other and len(other["charts"]) == 1, (period, other.get("error")) + assert other["charts"][0]["title"] == chart["title"], period + return by + + +async def test_a_station_chart_says_how_to_draw_it_again_and_over_which_periods(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, period="this week") # the usual set: a panel each, outdoor and indoor lines in each + chart = out["charts"][0] + assert [p["label"] for p in chart["panels"]] == ["Temperature", "Humidity"] and chart["source"] == "Ecowitt weather station" + assert [s["name"] for s in chart["panels"][0]["series"]] == ["Indoor", "Outdoor"] + by = await replays(tool, out) + assert by["arguments"] == {"readings": ["outdoor.temperature", "indoor.temperature", "outdoor.humidity"], "period": "this week", + "average": False, "every_day": False, "chart": True, + "chart_readings": ["outdoor.temperature", "indoor.temperature", "outdoor.humidity"], "layout": "auto", + "invert_second_axis": False, "chart_answers_it": False} + assert by["periods"] == [{"period": "1d", "label": "1D"}, {"period": "7d", "label": "7D"}, {"period": "1m", "label": "1M"}, + {"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}] + assert out["chart_note"] and max(len(s["points"]) for p in chart["panels"] for s in p["series"]) <= 150 + await close(ctx) + + +async def test_wind_is_drawn_with_its_compass_and_one_reading_named_draws_only_that_one(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["wind"], period="this week") + chart = out["charts"][0] + assert chart["title"] == "Wind" and "compass" in chart["panels"][0] + await replays(tool, out) + outdoor = await ask(tool, readings=["temperature"], chart_readings=["indoor.temperature"], period="this week") + assert [s["name"] for s in outdoor["charts"][0]["panels"][0]["series"]] == ["Indoor"] # figures for both, the line asked for + assert list(outdoor["series"]) == ["outdoor.temperature", "indoor.temperature"] + everything = await ask(tool, readings=["all"], period="this week") + assert [p["label"] for p in everything["charts"][0]["panels"]] == ["Temperature", "Humidity", "Solar radiation", "Pressure", + "Dew point", "Wind"] # (rain behind the humidity) + await close(ctx) + + +async def test_an_average_draws_each_days_average_and_lists_no_one_day_period(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["pressure"], period="this week", average=True) + assert "daily averages" in out["charts"][0]["subtitle"] + by = await replays(tool, out) + assert [p["period"] for p in by["periods"]] == ["7d", "1m", "3m", "1y"] + short = await ask(tool, readings=["pressure"], period="today", average=True, chart=True) + assert "charts" not in short and "whole day" in short["note_chart"] + await close(ctx) + + +async def test_two_axes_and_the_second_axis_upside_down(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["outdoor.temperature", "pressure"], period="this week", layout="two_axes", invert_second_axis=True) + (panel,) = out["charts"][0]["panels"] + assert panel["flip_right"] is True and [s["right"] for s in panel["series"]] == [False, True] + await replays(tool, out) + plain = await ask(tool, readings=["outdoor.temperature", "pressure"], period="this week", layout="two_axes") + assert plain["charts"][0]["panels"][0]["flip_right"] is False + same = await ask(tool, readings=["outdoor.temperature", "dew point"], period="this week", layout="same_axis") + (panel,) = same["charts"][0]["panels"] + assert len(panel["series"]) == 2 and same["charts"][0]["period"][1] == days_ago(1) # plot_chart's: whole days to yesterday + await close(ctx) + + +async def test_an_air_chart_is_the_air_sensors_and_an_average_one_is_each_days(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True, rows_per_day=24) + out = await ask(tool, readings=["pm2.5", "co2"], period="last 3 days") + chart = out["charts"][0] + assert chart["title"] == "Air quality" and [p["label"] for p in chart["panels"]] == ["PM2.5", "CO₂"] + assert chart["source"] == "AirGradient sensor" + await replays(tool, out) + daily = await ask(tool, readings=["pm2.5"], period="last 3 days", average=True) + assert "daily averages" in daily["charts"][0]["subtitle"] and len(daily["charts"][0]["panels"][0]["series"][0]["points"]) == 2 + await close(ctx) + + +async def test_a_chart_of_both_sensors_or_a_rating_is_drawn_over_whole_days_and_says_so(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True, rows_per_day=24) + out = await ask(tool, readings=["pm2.5", "rain"], chart_readings=["air.pm2_5:rating", "rain"], period="this week") + chart = out["charts"][0] + assert chart["source"] == "Ecowitt weather station and AirGradient sensor" and chart["period"] == [days_ago(6), days_ago(1)] + assert chart["panels"][0]["series"][0]["kind"] == "rating" and chart["panels"][1]["series"][0]["kind"] == "bars" + assert "up to yesterday" in out["notes"]["chart"] and out["notes"]["chart"] in out["caption"] + assert list(out["series"]) == ["air.pm2_5", "rainfall.rain"] and out["rain_total_mm"] >= 0 + by = await replays(tool, out) + assert by["arguments"]["chart_readings"] == ["air.pm2_5:rating", "rainfall.rain"] + # the live evals' rating-against-rainfall put the rating in `readings`: summarised as the reading, drawn as its rating + sent = await ask(tool, readings=["air.pm2_5:rating", "rain"], period="this week") + assert list(sent["series"]) == ["air.pm2_5", "rainfall.rain"] and sent["charts"][0]["panels"][0]["series"][0]["kind"] == "rating" + assert sent["charts"][0]["drawn_by"]["arguments"]["chart_readings"] == ["air.pm2_5:rating", "rainfall.rain"] + assert sent["charts"][0]["drawn_by"]["arguments"]["readings"] == ["air.pm2_5", "rainfall.rain"] + short = await ask(tool, readings=["pm2.5:rating"], period="yesterday") # a rating is only ever drawn: chart on + assert short["charts"][0]["panels"][0]["series"][0]["kind"] == "rating" + await close(ctx) + + +async def test_a_chart_of_both_sensors_has_each_readings_line_and_the_cut_in_its_caption(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True) + mixed = await ask(tool, readings=["outdoor.temperature", "pm2.5"], period="last 3 days", chart_answers_it=True) + assert [p["label"] for p in mixed["charts"][0]["panels"]] == ["Temperature", "PM2.5"] + lines = mixed["caption"].splitlines() + assert lines[1].startswith("Temperature: low ") and lines[2].startswith("• PM2.5: peak ") and lines[3].startswith("(The chart draws") + assert mixed["reply"] == mixed["caption"] and mixed["complete"] is True # the cut is in the caption: nothing left for the model + await close(ctx) + + +# ---------- the caption and the text: their shape at any time, their words at a pinned one (summary_words.json) ---------- +async def test_the_caption_is_the_period_then_a_line_per_reading_drawn(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True) + for args in ({"readings": ["pressure"], "period": "this week"}, {"period": "this week"}, + {"readings": ["temperature"], "period": "this week", "average": True}, {"readings": ["rain", "wind"], "period": "last 10 days"}, + {"readings": ["wind"], "period": "last 3 days"}, {"readings": ["rain"], "period": "last 3 days"}): + out = await ask(tool, **args) + assert out["charts"] and len(out["caption"].splitlines()) >= 2, args + out = await ask(tool, readings=["pm2.5", "co2"], period="last 3 days") + assert out["caption"].splitlines()[1].startswith("• PM2.5: peak ") + await close(ctx) + + +# The words themselves: each case's caption (a chart drawn) and text (no chart), as the bot's old words wrote them for the same figures, +# recorded with the clock pinned (conftest's daytime_archive, 2:05pm Tue 10 Nov 2026) from the tree where they were still checked +# against that oracle (tests/report_words.py, before step 6c deleted it): tests/summary_words.json. +WORDS = json.loads((Path(__file__).parent / "summary_words.json").read_text()) + + +async def test_the_captions_and_texts_are_the_bots_words_pinned(tmp_path, daytime_archive): + assert WORDS["clock"] == clocks.DAYTIME.isoformat() + tool, ctx, _ = await make(tmp_path, daytime_archive, air=True) + for case in WORDS["captions"]: + out = await ask(tool, **case["arguments"]) + assert out["charts"] and out["caption"] == case["caption"], case["arguments"] + for case in WORDS["texts"]: + out = await ask(tool, **case["arguments"]) + assert "charts" not in out and out["text"] == case["text"], case["arguments"] + await close(ctx) + + +async def test_with_no_chart_the_figures_come_in_the_words_the_bot_writes_for_a_lookup_today(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True) + for args, old, names in (({"period": "yesterday"}, {"groups": "outdoor,indoor"}, ["temperature", "humidity"]), + ({"readings": ["temperature"], "period": "yesterday", "average": True}, + {"groups": "outdoor,indoor", "average": True}, ["temperature"]), + ({"readings": ["wind"], "period": "yesterday"}, {"groups": "wind"}, ["wind"]), + ({"readings": ["outdoor.humidity", "pressure"], "period": "yesterday"}, {"groups": "outdoor,pressure"}, + ["humidity", "pressure"])): + out = await ask(tool, **args) + lines = out["text"].splitlines() + assert "charts" not in out and lines[0].endswith("2026") and len(lines) >= 1 + len(names), args # the period, then the figures + assert all(line.startswith("• ") for line in lines[1:]), args + rain = await ask(tool, readings=["rain", "pm2.5"], period="yesterday") + lines = rain["text"].splitlines() + assert lines[1].startswith("☔ Rain per hour: least 0 mm") and lines[1].endswith(f" · {rain['rain_total_mm']:.1f} mm in all") + assert lines[2].startswith("• PM2.5: peak ") and len(lines) == 3 + direction = await ask(tool, readings=["wind direction"], period="yesterday") + assert direction["text"].splitlines()[1].startswith("🧭 Mostly from the N") + await close(ctx) + + +async def test_a_chart_that_answers_the_question_comes_with_its_reply_unless_a_note_needs_words(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True, hourly_before=datetime.now(TZ) - timedelta(days=3)) + out = await ask(tool, readings=["pressure"], period="this week", chart_answers_it=True) + assert out["reply"] == out["caption"] and out["complete"] is True and list(out)[-2:] == ["reply", "complete"] + assert out["charts"][0]["drawn_by"]["arguments"]["chart_answers_it"] is True + assert "complete" not in await ask(tool, readings=["pressure"], period="this week") # not asked + assert "complete" not in await ask(tool, readings=["pressure"], period="yesterday", chart_answers_it=True) # no chart + noted = await ask(tool, readings=["pressure"], period="this week", start="count_only", chart_answers_it=True) + assert noted["period"]["note"] and "caption" in noted and "complete" not in noted and "reply" not in noted # the model reads it + hourly = await ask(tool, readings=["pm2.5"], period="last 7 days", chart_answers_it=True) + assert "resolution" in hourly["notes"]["air"] and "caption" in hourly and "complete" not in hourly # the model words the note + assert summary.Summary._needs_words({"warning": "x", "missing": ["y"], "notes": {"air": {"missing": "z"}, "chart": "c"}}) is False + assert summary.Summary._needs_words({"monthly_note": "x"}) and summary.Summary._needs_words({"note_no_readings": "x"}) + await close(ctx) + + +# ---------- refusals that teach ---------- +async def test_a_call_that_cant_be_answered_is_refused_with_what_to_send_instead(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True) + out = await ask(tool, start_date="2026-11-01") + assert "start_date" in out["error"] and "`start`" in out["error"] and "period" in out["arguments"] + out = await ask(tool, readings=["sunniness"]) + assert "'sunniness' isn't a reading" in out["error"] and "outdoor.temperature" in out["names"] and out["words"]["rain"] + out = await ask(tool, period="the other week") + assert "isn't a period" in out["error"] and "today" in out["forms"] + assert "use forecast" in (await ask(tool, period="next week"))["error"] + out = await ask(tool, readings=["pressure"], chart=True, layout="stacked") + assert out["layouts"] == ["auto", "panels", "two_axes", "same_axis"] + assert "needs layout two_axes" in (await ask(tool, readings=["pressure"], chart=True, invert_second_axis=True))["error"] + assert "two readings or more" in (await ask(tool, readings=["pressure"], chart=True, layout="two_axes"))["error"] + assert "rain (bars)" in (await ask(tool, readings=["pressure", "rain"], chart=True, layout="two_axes"))["error"] + assert "have a rating" in (await ask(tool, chart_readings=["temperature:rating"], chart=True))["error"] + out = await ask(tool, readings=["indoor.temperature", "pm2.5"], chart=True, period="this week") + assert "indoor.temperature can't go on a chart that mixes" in out["error"] and "air.pm2_5" in out["drawable"] + out = await ask(tool, readings=["pm2.5", "pm10", "co2", "voc", "rain"], chart=True, period="this week") + assert "at most 4 readings" in out["error"] + out = await ask(tool, readings=["pm2.5", "rain"], chart=True, period="today") + assert "whole days" in out["error"] and "'last 7 days'" in out["error"] + assert "true or false" in (await ask(tool, chart="maybe"))["error"] + assert "names no reading" in (await ask(tool, chart=True, chart_readings=[":rating"]))["error"] + every = summary.tools(Context(eco=ctx.eco))[0] # (every reading the service knows: rain rate is drawn only alone) + out = await ask(every, readings=["pressure", "rain rate"], chart=True) + assert "rainfall.rain_rate can only be drawn on a chart of its own" in out["error"] + assert "the piezo rain gauge" in (await ask(every, readings=["piezo"], chart=True))["error"].lower() + out = await ask(tool, readings=["pressure"], period="2021") + assert "goes back 4 years" in out["error"] and out["held_from"] + await close(ctx) + + +async def test_with_only_the_air_sensor_its_readings_are_the_default_and_no_day_has_a_look(tmp_path): + transport, _ = air_transport(rows_per_day=288) + air = AirGradient(config(tmp_path), transport=transport) + await air.start() + ctx = await Context.open(air=air) + tool = summary.tools(ctx)[0] + out = await ask(tool, period="last 2 days") + assert list(out["series"]) == ["air.pm2_5", "air.pm10", "air.pm1", "air.co2", "air.voc_index", "air.nox_index"] + assert not any("low_day_look" in s or "high_day_look" in s for s in out["series"].values()) + assert out["text"].splitlines()[1].startswith("• PM2.5: peak ") and len(out["text"].splitlines()) == 7 + out = await ask(tool, readings=["pm2.5", "pm10"], chart=True, period="last 2 days", layout="two_axes") + assert "only where there is a weather station" in out["error"] + assert "doesn't hold" in (await ask(tool, readings=["temperature"]))["error"] # a bare temperature is the station's + await air.close() + + +async def test_nothing_held_is_refused_with_where_the_record_starts(tmp_path, archived_cache): + tool, ctx, fake = await make(tmp_path, archived_cache) + out = await ask(tool, {"fetch": False}, readings=["pressure"], period="June 2024") # before the fake station, asking nobody + assert out["error"].startswith("Nothing is held of pressure.relative for June 2024") and out["held_from"] + assert fake.calls == [] + await close(ctx) + + +# ---------- the request's metadata ---------- +async def test_a_chart_drawn_ahead_asks_after_the_rest_and_a_chart_points_budget_is_kept(tmp_path, archived_cache, monkeypatch): + tool, ctx, _ = await make(tmp_path, archived_cache) + urgent = [] + real = summary.Fetcher.__init__ + + def recorded(self, *args, **kwargs): + real(self, *args, **kwargs) + urgent.append(self.urgent) + monkeypatch.setattr(summary.Fetcher, "__init__", recorded) + await ask(tool, {"priority": "background"}, readings=["pressure"], period="this week") + await ask(tool, readings=["pressure"], period="this week") + assert urgent == [False, True] + big = await ask(tool, {"chart_points": 500}, readings=["pressure"], period="this week") + assert max(len(s["points"]) for s in big["charts"][0]["panels"][0]["series"]) > 150 + await close(ctx) diff --git a/tests/test_service_switch.py b/tests/test_service_switch.py new file mode 100644 index 00000000..6823f9ec --- /dev/null +++ b/tests/test_service_switch.py @@ -0,0 +1,451 @@ +"""The bot's own answers (everything it answers without the model) pinned word for word, chart for chart, on the archived fake station +at a fixed time (Tue 10 Nov 2026 2:05pm, Melbourne), so moving them onto the service's tools (docs/ecobot-mcp.md 6, step 2) changes +nothing the person sees but what is meant to change. Since step 6c the bot answers no typed question in code: what it once did (the +report, "weather now", a named reading's chart and a period) goes to the model, and only the keyboard's charts, an alert's chart and a +period button's redraw are its own. + +What is pinned, for each of those (the keyboard's charts, an alert's chart, a period button's redraw): every message sent (its text or caption, and its buttons), the +text the answer leaves in the chat's history, and each chart as JSON (specs.to_json, less `drawn_by`, which only the service's charts +carry) and the gauges' sheet. They are recorded in tests/service_switch.json: `ECOBOT_RECORD_SWITCH=1 pytest tests/test_service_switch.py` +writes it afresh (only ever on purpose). + +The clock: every `datetime.now()`, `date.today()` and `time.time()` in lib/ and tests/ reads the fixed time, and the station's archive is +built under it (once per module), so every figure, time and point is the same on every run.""" + +import hashlib +import json +import os +import shutil +import sys +import time as _time +from datetime import date as _date, datetime as _datetime +from pathlib import Path +from types import SimpleNamespace as NS +from zoneinfo import ZoneInfo + +import pytest + +GOLDEN = Path(__file__).with_name("service_switch.json") +RECORD = os.environ.get("ECOBOT_RECORD_SWITCH") == "1" +FROZEN = _datetime(2026, 11, 10, 14, 5, tzinfo=ZoneInfo("Australia/Melbourne")).timestamp() +_REAL = (_datetime, _date) # the real classes, where freeze() can't rebind them (it rebinds module globals, never a tuple's items) + + +# ---------- the clock, fixed ---------- +class _DatetimeType(type(_REAL[0])): # (type, unless ECOBOT_CLOCK moved the clock: tests/clocks.py) + def __instancecheck__(cls, obj): + return isinstance(obj, _REAL[0]) + + def __subclasscheck__(cls, sub): + return issubclass(sub, _REAL[0]) + + +class FrozenDatetime(_datetime, metaclass=_DatetimeType): + """datetime whose now() and today() are the fixed time (anything else, and its instances, are the real datetime's).""" + + @classmethod + def now(cls, tz=None): + return _REAL[0].fromtimestamp(FROZEN, tz) + + @classmethod + def today(cls): + return _REAL[0].fromtimestamp(FROZEN) + + +class _DateType(type(_REAL[1])): + def __instancecheck__(cls, obj): + return isinstance(obj, _REAL[1]) + + def __subclasscheck__(cls, sub): + return issubclass(sub, _REAL[1]) + + +class FrozenDate(_date, metaclass=_DateType): + @classmethod + def today(cls): + return _REAL[0].fromtimestamp(FROZEN).date() + + +def freeze(patch): + """Fix the clock in every module of lib/ and tests/ (and ecobot.py) loaded so far, with `patch` (a MonkeyPatch).""" + import lib.alerts.pictures, lib.bot, lib.compose, lib.ecowitt.archive, lib.forecast, lib.history, lib.pollen, lib.service.about # noqa: F401 + import lib.service.current, lib.service.days, lib.service.forecast, lib.service.pollen, lib.service.summary # noqa: F401 + import tests.fakes, tests.test_service_forecast, tests.test_pollen # noqa: F401 + patch.setattr(_time, "time", lambda: FROZEN) + for name, module in list(sys.modules.items()): + if module is None or not (name == "lib" or name.startswith(("lib.", "tests.")) or name == "ecobot"): + continue + if vars(module) is globals(): # (this module keeps the real classes, whatever it is loaded as: the frozen ones are built on them) + continue + for attr, value in list(vars(module).items()): + if value is _REAL[0]: + patch.setattr(module, attr, FrozenDatetime) + elif value is _REAL[1]: + patch.setattr(module, attr, FrozenDate) + patch.setattr(sys.modules["lib.ecowitt.archive"], "epoch_now", lambda: FROZEN) + + +def test_the_clock_is_fixed_in_every_module_whatever_order_they_were_loaded_in(monkeypatch): + """freeze() reaches a module loaded after this one too (it keeps its own names for the real classes, and leaves this module be), + and the frozen classes still tell real dates and times apart.""" + import datetime as real + import types + late = types.ModuleType("tests._loaded_late") + late.datetime, late.date = real.datetime, real.date + monkeypatch.setitem(sys.modules, "tests.test_service_switch", sys.modules[__name__]) # (as --import-mode=importlib names it) + monkeypatch.setitem(sys.modules, late.__name__, late) # (after this module in sys.modules) + freeze(monkeypatch) + assert late.datetime is FrozenDatetime and late.date is FrozenDate + assert sys.modules[__name__]._datetime is real.datetime and sys.modules[__name__]._date is real.date + now = FrozenDatetime.now(ZoneInfo("Australia/Melbourne")) + assert now.timestamp() == FROZEN and isinstance(now, FrozenDatetime) and isinstance(FrozenDate.today(), FrozenDate) + assert issubclass(real.datetime, FrozenDatetime) and not isinstance(now.date(), FrozenDatetime) + + +@pytest.fixture(scope="module") +def frozen_archive(pinned_archive): + """The fake station's whole archive, built at the fixed time: conftest's pinned_archive (built once for every worker and run, with + tests/clocks.pin, which fixes the clock as freeze() does: the same file).""" + return pinned_archive(_datetime.fromtimestamp(FROZEN, ZoneInfo("Australia/Melbourne"))) + + +# ---------- the bot over every source ---------- +def summary_of(chart: dict) -> dict: + """What a chart's JSON is pinned as: its hash (less drawn_by), and enough of it to see where two differ.""" + chart = {k: v for k, v in chart.items() if k != "drawn_by"} + panels = [{"label": p["label"], "unit": p["unit"], + "series": [[s["name"], s["kind"], len(s["points"]), s["points"][:1], s["points"][-1:]] for s in p["series"]]} + for p in chart["panels"]] + digest = hashlib.sha256(json.dumps(chart, sort_keys=True, ensure_ascii=False).encode()).hexdigest()[:16] + return {"title": chart["title"], "subtitle": chart["subtitle"], "period": chart["period"], "source": chart["source"], + "panels": panels, "sha": digest} + + +def buttons(markup) -> list | None: + rows = getattr(markup, "inline_keyboard", None) + return [[[b.text, b.callback_data] for b in row] for row in rows] if rows else None + + +class World: + """The archived station (its live reading the wet night of tests/test_service_current), the fake AirGradient on the same file, the + forecast and the pollen, all at the fixed time; and what the bot drew and sent.""" + + def __init__(self): + self.charts: list[dict] = [] + self.drawn_by: list[dict | None] = [] # each chart's drawn_by (the service's charts only) + self.sheets: list[str] = [] + self.sent: list[list] = [] + self.edits: list[list] = [] + self.toasts: list = [] + + async def open(self, tmp_path, archive): + from lib.airgradient import AirGradient + from lib.compose import Composer + from lib.ecowitt import Ecowitt + from lib.forecast import Forecast + from tests.fakes import TZ, config, ecowitt_transport + from tests.test_pollen import make as make_pollen, page + from tests.test_service_current import Station, live + from tests.test_service_forecast import open_meteo + cfg = config(tmp_path) + shutil.copy(archive, cfg.storage_path) + transport, _ = ecowitt_transport() + eco = Ecowitt(cfg, transport=transport) + await eco.start() + Station(eco, live(FROZEN, **{"solar_and_uvi.solar": "412.5", "solar_and_uvi.uvi": "6", "wind.wind_speed": "14.0", + "wind.wind_gust": "31.0", "indoor.humidity": None})) # (the fake station has no indoor humidity) + air_transport_, _ = __import__("tests.fakes", fromlist=["air_transport"]).air_transport() + air = AirGradient(cfg, transport=air_transport_, storage=eco.storage, owned=False) + await air.start() + forecast = Forecast(config(tmp_path, forecast=True, forecast_lat=-37.8, forecast_lon=144.9, place="Melbourne"), None, + open_meteo([], 7)) + await forecast.warm(True) + pollen, _ = make_pollen(tmp_path, lambda: page(grass="Moderate", asthma="Low")) + pollen.now = lambda: _datetime.fromtimestamp(FROZEN, TZ).replace(tzinfo=None) + await pollen.warm(True) + self.eco, self.air, self.pollen, self.forecast = eco, air, pollen, forecast + self.composer = Composer(eco, air) + from lib.service import Service + from lib.service.context import Context + self.ctx = await Context.open(eco=eco, air=air, composer=self.composer, forecast=forecast, pollen=pollen, tz=TZ, + clock=lambda: FROZEN) + self.service = Service.of(self.ctx) + self.tz, self.cfg = TZ, cfg + return self + + async def close(self): + for source in (self.air, self.eco, self.forecast, self.pollen): + close = getattr(source, "close", None) + if close: + await close() + + async def ecobot_mcp(self, monkeypatch, serve): + """ecobot-mcp in memory over this world, the bot's client of it connected: its charts and Status picture drawn as noted.""" + from lib import chart_images, gauges as gauges_module + + def render(data, tz, dark=None): # (the service's drawing in this process: the bot draws nothing) + self.charts.append(summary_of(data)) + self.drawn_by.append(data.get("drawn_by")) + return b"png", bool(dark) + + def gauges(sheet): # (the Status picture, drawn by the service: lib/status.py) + self.sheets.append(hashlib.sha256(repr(sheet).encode()).hexdigest()[:16]) + return b"gauges" + monkeypatch.setattr(chart_images, "render", render) + monkeypatch.setattr(gauges_module, "render", gauges) + return await serve(self.ctx) + + async def bot(self, alert_state, monkeypatch, serve): + """The bot, ecobot-mcp's client (in memory, over this world), with no model.""" + from lib import bot as botmod + from lib import model_tools + from lib.llm import Agent + weather = await self.ecobot_mcp(monkeypatch, serve) + self.tools = model_tools.tools(weather) + bot = botmod.Bot(NS(tz=self.tz), Agent(None, "m", self.tools), alert_state, service=weather) + bot.preload_soon = lambda *a: None # (a chart's other periods not fetched in the background: what is drawn is what is asked) + return bot + + def message(self, message_id=50): + world = self + + async def reply_text(body, **kw): + world.sent.append(["text", body, buttons(kw.get("reply_markup"))]) + return NS(message_id=100 + len(world.sent)) + + async def reply_photo(photo, caption=None, **kw): + world.sent.append(["photo", caption, buttons(kw.get("reply_markup"))]) + return NS(message_id=100 + len(world.sent), photo=[NS(file_id=f"file{len(world.sent)}")]) + + async def reply_media_group(media, **kw): + world.sent.append(["photos", [m.caption for m in media], None]) + + async def edit_media(media, reply_markup=None): + world.edits.append(["photo", media.caption, buttons(reply_markup)]) + return NS(photo=[NS(file_id="edited")]) + return NS(chat_id=-5, message_id=message_id, message_thread_id=None, is_topic_message=False, reply_text=reply_text, + reply_photo=reply_photo, reply_media_group=reply_media_group, edit_media=edit_media, + chat=NS(type="supergroup", title="Weather", id=-5), from_user=NS(full_name="Rob"), reply_to_message=None, photo=None) + + +async def nothing(*a, **k): + pass + + +CONTEXT = NS(bot=NS(send_chat_action=nothing, send_message_draft=nothing, id=99, username="ecobot")) + + +@pytest.fixture +async def world(tmp_path, frozen_archive, monkeypatch): + freeze(monkeypatch) + w = await World().open(tmp_path, frozen_archive) + yield w + await w.close() + + +# ---------- what is pinned ---------- +def golden() -> dict: + return json.loads(GOLDEN.read_text()) if GOLDEN.exists() else {} + + +def period_rows(sent: list) -> list: + """The period buttons under each message sent (None for a message with none, or with other buttons).""" + return [s[2] if s[2] and all(d.startswith("pd:") for row in s[2] for _, d in row) else None for s in sent] + + +def without_period_rows(record: dict) -> dict: + """What was done, less the period buttons (deliberately changed: they come from the chart's drawn_by now).""" + record = json.loads(json.dumps(record, ensure_ascii=False)) + for s, row in zip(record.get("sent", []), period_rows(record.get("sent", []))): + if row is not None: + s[2] = None + return record + + +def pinned(name: str, got: dict): + """Compare what the bot did with the recording (or record it), its period buttons aside (period_buttons_are_drawn_bys).""" + if RECORD: + data = golden() + data[name] = got + GOLDEN.write_text(json.dumps(data, indent=1, ensure_ascii=False, sort_keys=True) + "\n") + return + if dump := os.environ.get("ECOBOT_SWITCH_DUMP"): # (a folder: what was done, to compare with the recording by hand) + Path(dump).mkdir(parents=True, exist_ok=True) + (Path(dump) / f"{hashlib.sha1(name.encode()).hexdigest()[:10]}.json").write_text( + json.dumps({"name": name, "got": got}, indent=1, ensure_ascii=False, sort_keys=True)) + want = golden().get(name) + assert want is not None, f"{name} isn't recorded: run with ECOBOT_RECORD_SWITCH=1" + assert without_period_rows(got) == without_period_rows(want) + + +def period_buttons_are_drawn_bys(world, got: dict): + """The deliberate change: a single chart's buttons are its drawn_by's periods, each labelled as the service labels it (none when it + lists none: a count per month no longer offers 1D), each button's data the period alone, within Telegram's 64 bytes.""" + rows = [row for row in period_rows(got["sent"]) if row is not None] + photos = [s for s in got["sent"] if s[0] == "photo"] + drawn = [d for d in world.drawn_by if d] + if len(photos) == 1 and len(world.charts) == 1 and drawn: + listed = drawn[0]["periods"] + assert rows == ([[[[p["label"], f"pd:{p['period']}"] for p in listed]]] if listed else []) + assert all(len(d.encode()) <= 64 for row in rows for r in row for _, d in r) + else: + assert rows == [] + + +async def asked(serve, world, alert_state, monkeypatch, text) -> dict: + """Ask the bot `text`, as a group's message to it (a keyboard button's sentence: pressed, Bot.press), and return what it did.""" + bot = await world.bot(alert_state, monkeypatch, serve) + msg = world.message() + update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob", id=7)) + await (bot.press if text in templates.CALLS else bot.respond)(update, CONTEXT, text) + history = bot.chats[(msg.chat_id, None)].history + said = history[-1]["content"] if history and history[-1]["role"] == "assistant" else None + return {"sent": world.sent, "charts": world.charts, "gauges": world.sheets, "history": said} + + +# Every question the bot answers in code: the keyboard's charts (templates.CALLS, each a fixed call; with irrigation only Wind goes) +from lib import templates # noqa: E402 + +KEYBOARD = list(templates.CALLS) +# What the bot answered in code until step 3 (the dashboard until step 6, the report, "weather now" and a named reading's chart and a +# period until step 6c) and the model answers now (with no model: NO_MODEL) +TO_THE_MODEL = [ + "Report", "weather now", "status", # the report and "weather now", until 6c + "temperature chart 7d", "humidity 7d", "rain chart 7d", "pressure chart this month", "temperature and rain chart 7d", # a chart and + "weather 30d", "indoor temperature chart 7d", "wind direction plot 3m", "temperature chart last month", # a period, typed, + "air quality chart 7d", "pm2.5 chart 3d", "temperature 1d", "co2 1d", "pm2.5 1d", "rain chart 1d", # until 6c + "how hot is it", "is it raining", "humidity", "wind", "indoor temperature", "uv", "pressure", # a reading now + "air quality now", "co2", "how's the air", # the air now + "pollen", "forecast", "what can you do", + "how many days was the temperature over 18 this year", "how many days was humidity under 60 last month", # days + "how many days was pm2.5 over 15 this week", "days with uv over 9 per month this year", + "rain by month this year", "average temperature per month this year", + "highest temperature yesterday", "high and low today", "lowest humidity yesterday", "average pressure yesterday", # extremes + "strongest gust today", "temps today", + "weather all week", "average temperature 7d", "plot uv and solar on two axes 7d", "lowest temperature on record", # charts beside + "highest humidity this week", "temps this week", "chart weather", # a question + "dashboard", # the Telegram dashboard, until step 6 (its live page is ecobot-mcp's /dashboard) +] + + +@pytest.mark.parametrize("text", TO_THE_MODEL) +async def test_what_was_answered_in_code_goes_to_the_model(serve, world, alert_state, monkeypatch, text): + from lib.bot import NO_MODEL + got = await asked(serve, world, alert_state, monkeypatch, text) + assert got["history"] == NO_MODEL and got["charts"] == [] and got["gauges"] == [] + + +@pytest.mark.parametrize("text", KEYBOARD) +async def test_the_bots_own_answers_are_unchanged(serve, world, alert_state, monkeypatch, text): + got = await asked(serve, world, alert_state, monkeypatch, text) + pinned(text, got) + if not RECORD: + period_buttons_are_drawn_bys(world, got) + + +@pytest.mark.parametrize("question, press, recorded", [("Temperature chart 1d", "7D", "Temperature chart 1d"), ("Rain chart 1d", "1M", "Rain chart 1d"), + ("Humidity chart 1d", "1Y", "humidity 7d")]) +async def test_a_period_button_redraws_the_same_chart_as_before(serve, world, alert_state, monkeypatch, question, press, recorded): + """A press on a period button under a chart: the chart over that period, put into the same message. (1Y was recorded under the typed + "humidity 7d", drawn in code until step 6c: under the Humidity button its press is the same call, and the same chart.)""" + bot = await world.bot(alert_state, monkeypatch, serve) # (its chart's other periods not fetched ahead: the press draws its chart) + msg = world.message() + update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob", id=7)) + await bot.press(update, CONTEXT, question) + sent_id = 100 + len(world.sent) + row = next((s[2] for s in world.sent if s[0] == "photo" and s[2]), None) + assert row, "a single chart with its period buttons" + data = next(d for r in row for t, d in r if t == press) + under = world.message(sent_id) + under.reply_markup = NS(inline_keyboard=[[NS(text=t, callback_data=d) for t, d in r] for r in row]) + world.charts.clear() + + async def answer(text=None, **k): + world.toasts.append(text) + query = NS(data=data, message=under, answer=answer) + await bot.on_period_button(NS(callback_query=query, effective_message=under, effective_chat=under.chat, + effective_user=NS(username="rob", full_name="Rob", id=7)), CONTEXT) + got = {"charts": world.charts, "edits": [e[:2] for e in world.edits]} + pinned(f"press {press} under {recorded}", got) + + +@pytest.mark.parametrize("kind", ["gusts", "uv", "temps", "particulates"]) +async def test_an_alerts_chart_is_the_same_as_before(serve, world, monkeypatch, kind): + """An alert's chart (and its 🔄), drawn by ecobot-mcp: the chart drawn is the one pinned.""" + from lib.alerts import pictures + weather = await world.ecobot_mcp(monkeypatch, serve) + picture = await pictures.chart(pictures.CHARTS[kind], world.tz, weather) + got = {"title": picture.title, "newest": picture.newest, "charts": world.charts} + if RECORD: + pinned(f"alert {kind}", got) + return + # The deliberate change: an alert's chart is the service's chart of its request, the very chart the keyboard's button draws ("Wind + # chart 1d"), so it names its source under it as that one does (the old drew it through the tool's handler, which named none). + want = golden()[f"alert {kind}"] + (chart,), (old,) = got["charts"], want["charts"] + assert old["source"] == "" and chart["source"] == ("AirGradient sensor" if kind == "particulates" else "Ecowitt weather station") + assert {k: v for k, v in chart.items() if k not in ("source", "sha")} == {k: v for k, v in old.items() if k not in ("source", "sha")} + assert {k: v for k, v in got.items() if k != "charts"} == {k: v for k, v in want.items() if k != "charts"} + sentence = next((said for said, call in templates.CALLS.items() if call == pictures.CHARTS[kind]), None) + keyboard = golden().get(sentence) if sentence else None + assert (keyboard is None) is (kind == "uv") + if keyboard: # (the UV chart is no button) + assert chart == keyboard["charts"][0] + + +# ---------- what follows from the model's calls ---------- +class Scripted: + """A model that makes these steps' calls ([(tool, arguments)] each), then answers `reply` (an exception: raised instead).""" + + def __init__(self, steps: list[list[tuple[str, dict]]], reply): + self.steps, self.reply = list(steps), reply + self.chat = NS(completions=self) + + async def create(self, **kw): + if self.steps: + calls = [NS(id=f"c{i}", function=NS(name=name, arguments=json.dumps(args))) for i, (name, args) in enumerate(self.steps.pop(0))] + return NS(choices=[NS(message=NS(content="", tool_calls=calls))], usage=None) + if isinstance(self.reply, BaseException): + raise self.reply + return NS(choices=[NS(message=NS(content=self.reply, tool_calls=None))], usage=None) + + +async def asked_the_model(serve, world, alert_state, monkeypatch, text, steps, reply="ok") -> list: + """Ask the bot `text` with a scripted model (Scripted), the air sensor's live-chart link configured: the text or caption of each + message it sent.""" + from lib.llm import Agent + world.air.link = ("live chart", "https://air.example") # (ecobot://station names it: read as the bot connects) + bot = await world.bot(alert_state, monkeypatch, serve) + bot.agent = Agent(Scripted(steps, reply), "m", world.tools) + msg = world.message() + update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob", id=7)) + await bot.respond(update, CONTEXT, text) + return [s[1] for s in world.sent] + + +LINK_CASES = [ # (question, the model's steps, does the live-chart link go under the reply) + ("what's the temperature outside", [[("current", {})]], False), # every sensor read: not an air answer + ("what's it like out", [[("current", {"readings": ["all"]})]], False), + ("how much rain this week", [[("summary", {"readings": ["rainfall total"]})], # a refusal lists every reading's words + [("summary", {"readings": ["rain"], "period": "7d"})]], False), + ("temperature readings", [[("readings", {"readings": ["temperature"], "period": "today"})]], False), # refused (bad arguments) + ("hottest days", [[("days", {"sort_by": "temp_max", "period": "this month"})]], False), + ("how's the air", [[("current", {"readings": ["air"]})]], True), + ("pm2.5 and temperature now", [[("current", {"readings": ["pm2.5", "temperature"]})]], True), + ("how was the air this week?", [[("summary", {"readings": ["pm2.5"], "period": "7d"})]], True), + ("smoky days", [[("days", {"where": [{"field": "pm2_5_max", "op": ">", "value": 15}], "period": "this month"})]], True), +] + + +@pytest.mark.parametrize("text, steps, link", LINK_CASES) +async def test_the_air_link_goes_under_an_answer_that_read_the_air_and_no_other(serve, world, alert_state, monkeypatch, text, steps, link): + """The live-chart link follows what was read (as before the swap, when air_quality's call brought it), never a key or a word + anywhere in a result: not `current` of every sensor, nor a refusal's catalogue of readings.""" + said = await asked_the_model(serve, world, alert_state, monkeypatch, text, steps) + assert said and all(("live chart" in s) is link for s in said), said + + +async def test_an_error_reply_gets_no_air_link(serve, world, alert_state, monkeypatch): + """The air was read, then the model timed out: the apology goes alone.""" + said = await asked_the_model(serve, world, alert_state, monkeypatch, "how's the air", [[("current", {"readings": ["air"]})]], TimeoutError()) + assert said == ["Sorry, that took too long. Please try again in a moment."] diff --git a/tests/test_settings.py b/tests/test_settings.py new file mode 100644 index 00000000..9f48145f --- /dev/null +++ b/tests/test_settings.py @@ -0,0 +1,253 @@ +"""The settings' names (docs/configuration.md): ecobot-mcp's start with MCP_, irrigation-mcp's with IRRIGATION_, the bot's with BOT_, the +shared ones have none of them; an old name (or either of two) still works when the new one is unset, with one warning naming the new name (never the value). And the token: AUTH_TOKENS, or the +one ecobot-mcp generates in the data folder, which the bot reads from there (lib/auth_token.py).""" + +import logging +import os +import stat +from dataclasses import fields + +import pytest + +import ecobot +from ecobot_mcp import __main__ as mcp_main +from lib import auth_token +from lib.config import Config, env +from tests.fakes import config + +SHARED = {"DARKMODE", "LOG_LEVEL", "AUTH_TOKENS"} +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", + "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"} + + +def test_every_setting_is_named_for_the_program_that_reads_it(): + for f in fields(Config): + name = f.metadata.get("env") + if not name or name == "WEATHER_MCP_TOKEN": # (retired) + continue + if name in SHARED: + assert not name.startswith(("MCP_", "BOT_", "IRRIGATION_")), name + elif f.name in IRRIGATION_ONLY: + assert name.startswith("IRRIGATION_"), name + elif f.name in MCP_ONLY: + assert name.startswith("MCP_"), name + else: + assert name.startswith("BOT_"), name + + +def bot_settings(monkeypatch, tmp_path): + """What both programs need to start: the bot's token and ecobot-mcp's address (the bot's), a station (ecobot-mcp's).""" + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + monkeypatch.setenv("BOT_TELEGRAM_TOKEN", "1:x") + monkeypatch.setenv("BOT_MCP_URL", "http://127.0.0.1:8765/mcp") + monkeypatch.setenv("MCP_ECOWITT_API_KEY", "a") + monkeypatch.setenv("MCP_ECOWITT_APP_KEY", "b") + monkeypatch.setenv("IRRIGATION_TUYA_DEVICE_ID", "dev") # (irrigation-mcp's: the three it needs) + monkeypatch.setenv("IRRIGATION_TUYA_CLIENT_ID", "cid") + monkeypatch.setenv("IRRIGATION_TUYA_CLIENT_SECRET", "sec") + + +def read_by(name: str) -> dict: + """How the program that reads a setting reads its settings: ecobot-mcp's (MCP_) by ecobot-mcp, irrigation-mcp's (IRRIGATION_) by + irrigation-mcp, the others by the bot.""" + return {"program": "mcp" if name.startswith("MCP_") else "irrigation" if name.startswith("IRRIGATION_") else "bot"} + + +OLD_AND_NEW = [("ECOWITT_API_KEY", "MCP_ECOWITT_API_KEY", "ecowitt_api_key", "k3y", "k3y"), + ("HOMEASSISTANT_URL", "MCP_HOMEASSISTANT_URL", "homeassistant_url", "http://ha:8123/", "http://ha:8123"), + ("PLACE", "MCP_PLACE", "place", "Hobart", "Hobart"), + ("RAIN_QUIET_HOURS", "MCP_RAIN_QUIET_HOURS", "rain_quiet_hours", "22-6", (22, 6)), + ("CHART_ALL_VPD", "MCP_CHART_ALL_VPD", "chart_all_vpd", "on", True), + ("MCP_SERVICE_BIND", "MCP_BIND", "mcp_bind", "0.0.0.0:9000", ("0.0.0.0", 9000)), + ("MCP_SERVICE_ALLOWED_HOSTS", "MCP_ALLOWED_HOSTS", "mcp_allowed_hosts", "weather.lan", ("weather.lan",)), + ("MCP_SERVICE_TOKENS", "AUTH_TOKENS", "auth_tokens", "s3cret,other", ("s3cret", "other")), + ("OPENROUTER_API_KEY", "BOT_OPENROUTER_API_KEY", "openrouter_api_key", "sk-s3cret", "sk-s3cret"), + ("OPENROUTER_MODEL", "BOT_OPENROUTER_MODEL", "openrouter_model", "a/model", "a/model"), + ("ADMIN_ONLY", "BOT_ADMIN_ONLY", "admin_only", "on", True), + ("ADMIN_CHAT_IDS", "BOT_ADMIN_CHAT_IDS", "admin_chat_ids", "5 -9", frozenset({5, -9})), + ("LOG_WIDTH", "BOT_LOG_WIDTH", "log_width", "80", 80), + ("WEATHER_MCP_URL", "BOT_MCP_URL", "mcp_url", "http://ecobot-mcp:8765/mcp", "http://ecobot-mcp:8765/mcp"), + ("TUYA_CLIENT_SECRET", "IRRIGATION_TUYA_CLIENT_SECRET", "tuya_client_secret", "tuya-s3cret", "tuya-s3cret"), + ("BOT_TUYA_CLIENT_SECRET", "IRRIGATION_TUYA_CLIENT_SECRET", "tuya_client_secret", "tuya-s3cret", "tuya-s3cret"), + ("BOT_TUYA_BASE_URL", "IRRIGATION_TUYA_BASE_URL", "tuya_base_url", "https://openapi.tuyaus.com/", "https://openapi.tuyaus.com"), + ("TUYA_BASE_URL", "IRRIGATION_TUYA_BASE_URL", "tuya_base_url", "https://openapi.tuyaus.com", "https://openapi.tuyaus.com"), + ("BOT_IRRIGATION_CHECK_HOUR", "IRRIGATION_CHECK_HOUR", "irrigation_check_hour", "7", 7), + ("TELEGRAM_PRELOAD_CHAT", "BOT_TELEGRAM_PRELOAD_CHAT", "telegram_preload_chat", "-100", -100)] + + +@pytest.mark.parametrize("old, new, attr, text, want", OLD_AND_NEW, ids=[f"{row[0]}->{row[1]}" for row in OLD_AND_NEW]) +def test_a_setting_is_read_by_its_new_name_or_its_old_one_with_a_warning(monkeypatch, tmp_path, caplog, old, new, attr, text, want): + bot_settings(monkeypatch, tmp_path) + if new == "BOT_MCP_URL": + monkeypatch.delenv(new) + monkeypatch.setenv(new, text) + caplog.clear() + assert getattr(Config.from_env(**read_by(new)), attr) == want and "Old setting names" not in caplog.text + monkeypatch.delenv(new) + monkeypatch.setenv(old, text) + caplog.clear() + assert getattr(Config.from_env(**read_by(new)), attr) == want + warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING and "Old setting names" in r.getMessage()] + assert len(warnings) == 1 and f"{old} -> {new}" in warnings[0] and (len(text) < 5 or text not in warnings[0]) # (never the value) + assert env(new) == text.strip() # (the scripts' way in, old names too) + + +def test_the_old_names_are_one_warning_and_a_new_name_wins_over_its_old_one(monkeypatch, tmp_path, caplog): + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + for old, value in (("TELEGRAM_BOT_TOKEN", "1:s3cret"), ("ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b")): + monkeypatch.setenv(old, value) + monkeypatch.setenv("BOT_LOG_WIDTH", "30") + monkeypatch.setenv("LOG_WIDTH", "99") + cfg = Config.from_env(bot=False) # (ecobot-mcp reads every name; the bot only its own and the shared ones, below) + assert cfg.telegram_token == "1:s3cret" and cfg.ecowitt and cfg.log_width == 30 + warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] + renamed = [w for w in warnings if "Old setting names" in w] + assert len(renamed) == 1 and "TELEGRAM_BOT_TOKEN -> BOT_TELEGRAM_TOKEN" in renamed[0] and "ECOWITT_APP_KEY -> MCP_ECOWITT_APP_KEY" in renamed[0] + assert any("Ignoring LOG_WIDTH" in w for w in warnings) and "s3cret" not in caplog.text and "99" not in caplog.text + + +def test_of_two_old_names_the_newer_is_read_and_the_older_named_as_ignored(monkeypatch, tmp_path, caplog): + """IRRIGATION_TUYA_CLIENT_SECRET was BOT_TUYA_CLIENT_SECRET, and before that TUYA_CLIENT_SECRET: either is still read, the newer + when both are set; each set beside a newer one is named as ignored (never their values).""" + bot_settings(monkeypatch, tmp_path) + monkeypatch.delenv("IRRIGATION_TUYA_CLIENT_SECRET") + monkeypatch.setenv("TUYA_CLIENT_SECRET", "oldest-s3cret") + monkeypatch.setenv("BOT_TUYA_CLIENT_SECRET", "older-s3cret") + caplog.clear() + assert Config.from_env(program="irrigation").tuya_client_secret == "older-s3cret" + warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] + assert any("BOT_TUYA_CLIENT_SECRET -> IRRIGATION_TUYA_CLIENT_SECRET" in w for w in warnings) + assert any("Ignoring TUYA_CLIENT_SECRET: a newer name is set" in w for w in warnings) and "s3cret" not in caplog.text + monkeypatch.setenv("IRRIGATION_TUYA_CLIENT_SECRET", "new-s3cret") + caplog.clear() + assert Config.from_env(program="irrigation").tuya_client_secret == "new-s3cret" and "Old setting names" not in caplog.text + assert "Ignoring BOT_TUYA_CLIENT_SECRET, TUYA_CLIENT_SECRET: a newer name is set" in caplog.text + + +def test_irrigation_mcp_reads_only_its_own_settings_and_the_shared_ones_and_cannot_start_without_the_controller(monkeypatch, tmp_path, + caplog): + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + for name, value in (("BOT_TELEGRAM_TOKEN", "1:x"), ("BOT_MCP_URL", "http://x/mcp"), ("MCP_PLACE", "Hobart"), ("MCP_BIND", "0.0.0.0:9"), + ("WEATHER_MCP_TOKEN", "r3tired"), ("AUTH_TOKENS", "s3cret"), ("LOG_LEVEL", "debug"), + ("IRRIGATION_TUYA_DEVICE_ID", "dev")): + monkeypatch.setenv(name, value) + with pytest.raises(SystemExit, match="irrigation-mcp needs the irrigation controller's Tuya settings") as stopped: + Config.from_env(program="irrigation") + assert "IRRIGATION_TUYA_CLIENT_ID, IRRIGATION_TUYA_CLIENT_SECRET not set" in str(stopped.value) + monkeypatch.setenv("TUYA_CLIENT_ID", "cid") # (an old name does) + monkeypatch.setenv("BOT_TUYA_CLIENT_SECRET", "sec") + monkeypatch.setenv("IRRIGATION_BIND", "0.0.0.0:9100") + monkeypatch.setenv("IRRIGATION_ALLOWED_HOSTS", "irrigation.lan") + monkeypatch.setenv("IRRIGATION_ECOBOT_MCP_URL", "http://ecobot-mcp:8765/mcp/") + cfg = Config.from_env(program="irrigation") + assert (cfg.tuya_device_id, cfg.tuya_client_id, cfg.tuya_client_secret) == ("dev", "cid", "sec") + assert cfg.irrigation_bind == ("0.0.0.0", 9100) and cfg.irrigation_allowed_hosts == ("irrigation.lan",) + assert cfg.irrigation_ecobot_mcp_url == "http://ecobot-mcp:8765/mcp" and cfg.irrigation_check_hour == 18 + assert cfg.auth_tokens == ("s3cret",) and cfg.log_level == "DEBUG" # the shared ones + for f in fields(Config): + if f.metadata.get("env", "").startswith(("MCP_", "BOT_")) or f.metadata.get("env") == "WEATHER_MCP_TOKEN": + assert getattr(cfg, f.name) == f.default, f.name # the others': left at their defaults + assert cfg.irrigation_state_path == tmp_path / "irrigation_state.json" + assert cfg.irrigation_alert_log_path == tmp_path / "irrigation_alerts.sqlite" + monkeypatch.setenv("MCP_ECOWITT_API_KEY", "a") + monkeypatch.setenv("MCP_ECOWITT_APP_KEY", "b") + service = Config.from_env(program="mcp") + assert service.tuya_device_id == "" and service.irrigation_bind == ("127.0.0.1", 8766) # ecobot-mcp reads none of irrigation-mcp's + + +def test_the_bot_reads_none_of_irrigation_mcps_settings_and_reaches_it_at_bot_irrigation_mcp_url(monkeypatch, tmp_path, caplog): + """Step 8b: the controller is irrigation-mcp's; the bot is its client (BOT_IRRIGATION_MCP_URL, unset: no irrigation), and reads no + IRRIGATION_ setting, nor their old names (BOT_TUYA_*, TUYA_*, BOT_IRRIGATION_CHECK_HOUR), so it warns of none of them either.""" + bot_settings(monkeypatch, tmp_path) + for name, value in (("BOT_TUYA_CLIENT_ID", "old"), ("TUYA_DEVICE_ID", "older"), ("BOT_IRRIGATION_CHECK_HOUR", "6"), ("IRRIGATION_BIND", "0.0.0.0:1")): + monkeypatch.setenv(name, value) + cfg = Config.from_env() + for f in fields(Config): + if f.metadata.get("env", "").startswith("IRRIGATION_"): + assert getattr(cfg, f.name) == f.default, f.name + assert cfg.irrigation_mcp_url == "" and not cfg.irrigation and "Old setting names" not in caplog.text + monkeypatch.setenv("BOT_IRRIGATION_MCP_URL", "http://127.0.0.1:8766/mcp/") + assert Config.from_env().irrigation_mcp_url == "http://127.0.0.1:8766/mcp" + assert Config.from_env(program="irrigation").irrigation_mcp_url == "" # (irrigation-mcp doesn't read the bot's) + + +def test_irrigation_mcp_s_settings_have_their_defaults(): + defaults = {f.name: f.default for f in fields(Config)} + assert defaults["irrigation_bind"] == ("127.0.0.1", 8766) and defaults["irrigation_allowed_hosts"] == ("127.0.0.1", "localhost") + assert defaults["irrigation_ecobot_mcp_url"] == "http://127.0.0.1:8765/mcp" and defaults["irrigation_check_hour"] == 18 + assert defaults["tuya_base_url"] == "https://openapi.tuyaeu.com" + + +def test_a_value_an_old_name_gives_is_checked_under_that_name(monkeypatch, tmp_path, caplog): + bot_settings(monkeypatch, tmp_path) + monkeypatch.setenv("ADMIN_ONLY", "ture") + assert Config.from_env().admin_only is False and "ADMIN_ONLY: 'ture' is not on or off" in caplog.text + + +def test_the_bot_reads_only_its_own_settings_and_the_shared_ones_and_cannot_start_without_ecobot_mcp(monkeypatch, tmp_path, caplog): + """The bot is ecobot-mcp's client (docs/ecobot-mcp.md step 6b): ecobot-mcp's settings (MCP_, and their old names) are not read by + it, and it stops, saying what to do, without BOT_MCP_URL; it needs no source's settings.""" + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + monkeypatch.setenv("BOT_TELEGRAM_TOKEN", "1:x") + with pytest.raises(SystemExit, match="BOT_MCP_URL is not set: the bot is a client of ecobot-mcp") as stopped: + Config.from_env() + assert "python -m ecobot_mcp" in str(stopped.value) and "http://127.0.0.1:8765/mcp" in str(stopped.value) + monkeypatch.setenv("BOT_MCP_URL", "http://127.0.0.1:8765/mcp") + for name, value in (("MCP_PLACE", "Hobart"), ("RAIN_QUIET_HOURS", "22-6"), ("MCP_ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b"), + ("MCP_BIND", "0.0.0.0:9000"), ("DARKMODE", "on"), ("AUTH_TOKENS", "s3cret")): + monkeypatch.setenv(name, value) + caplog.clear() + cfg, service = Config.from_env(), Config.from_env(bot=False) + for f in fields(Config): + if f.name in MCP_ONLY: + assert getattr(cfg, f.name) == f.default, f.name # ecobot-mcp's: left at their defaults + assert (service.place, service.rain_quiet_hours, service.ecowitt_api_key, service.mcp_bind) == ("Hobart", (22, 6), "a", ("0.0.0.0", 9000)) + assert cfg.dark_mode == "on" and cfg.auth_tokens == ("s3cret",) and cfg.mcp_url == "http://127.0.0.1:8765/mcp" # shared, and its own + assert sum("RAIN_QUIET_HOURS" in r.getMessage() for r in caplog.records) == 1 # (ecobot-mcp's old name: said by ecobot-mcp alone) + + +# ---------- the token ---------- +def test_ecobot_mcp_generates_a_token_once_keeps_it_private_and_says_where_never_what(tmp_path, caplog): + caplog.set_level("INFO") + cfg = config(tmp_path) + token = mcp_main.generated_token(cfg) + kept = tmp_path / "auth_token" + assert len(token) >= 40 and kept.read_text().strip() == token + assert stat.S_IMODE(kept.stat().st_mode) == 0o600 + assert mcp_main.generated_token(cfg) == token # used again at the next start + assert str(kept) in caplog.text and token not in caplog.text + assert [p.name for p in tmp_path.iterdir() if p.name.startswith(".auth_token")] == [] # (no file of its own left behind) + + +def test_an_empty_token_file_is_replaced_and_an_unwritable_folder_stops_ecobot_mcp_saying_why(tmp_path): + (tmp_path / "auth_token").write_text("\n") + token = auth_token.ensure(tmp_path) + assert token and auth_token.read(tmp_path) == token + if os.geteuid() != 0: # (root writes anywhere) + locked = tmp_path / "locked" + locked.mkdir(mode=0o500) + with pytest.raises(SystemExit, match="AUTH_TOKENS is not set"): + mcp_main.generated_token(config(locked)) + + +def test_the_bot_sends_the_first_of_auth_tokens_else_the_retired_one_else_the_generated_one(tmp_path, caplog): + assert ecobot.mcp_token(config(tmp_path, auth_tokens=("first", "second"))) == "first" + assert ecobot.mcp_token(config(tmp_path, auth_tokens=("first",), retired_mcp_token="old")) == "first" + assert "WEATHER_MCP_TOKEN is retired and ignored" in caplog.text + caplog.clear() + assert ecobot.mcp_token(config(tmp_path, retired_mcp_token="r3tired")) == "r3tired" + assert "move it into AUTH_TOKENS" in caplog.text and "r3tired" not in caplog.text + caplog.clear() + read = ecobot.mcp_token(config(tmp_path)) # ecobot-mcp hasn't written its token yet: read again later, + assert callable(read) and read() is None and "no token" not in caplog.text # and not said at once (it may be a moment away) + assert ecobot.no_token_yet(config(tmp_path), read) and f"there is no token at {tmp_path / 'auth_token'}" in caplog.text # said + caplog.clear() # when ecobot-mcp can't be reached + token = auth_token.ensure(tmp_path) + assert read() == token and not ecobot.no_token_yet(config(tmp_path), read) and "no token" not in caplog.text + caplog.clear() + assert ecobot.mcp_token(config(tmp_path))() == token and "no token" not in caplog.text diff --git a/tests/test_snapshots.py b/tests/test_snapshots.py index 87620855..cc99fdc0 100644 --- a/tests/test_snapshots.py +++ b/tests/test_snapshots.py @@ -1,15 +1,12 @@ -import json from datetime import datetime, time as dtime -from lib import intent from lib.forecast import Forecast from lib.forecast.source import FORECAST_REFRESH_SECONDS -from lib.pollen import Pollen from lib.snapshots import KEEP_SECONDS, Snapshots 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, transport as pollen_transport +from tests.test_pollen import SEASON_DAY, make as make_pollen, page def rows(store, kind: str) -> int: @@ -103,19 +100,6 @@ async def test_the_forecast_is_kept_warm_every_15_minutes_and_a_failure_is_logge await broken.close() -async def test_the_report_always_uses_the_cache_for_pollen_and_forecast(tmp_path): - calls = [] - pollen = Pollen(config(tmp_path, pollen=True), pollen_transport(lambda: page(), calls)) - forecast = Forecast(config(tmp_path, forecast=True, forecast_lat=-37.8, forecast_lon=144.9), None, forecast_transport(calls)) - assert not pollen.wants("report") and not forecast.wants("sitrep") and pollen.wants("pollen today") and forecast.wants("forecast") - for tool, args in intent.report_calls(["Pollen", "Forecast"]): - out = json.loads(await {"pollen_asthma": pollen.handle, "weather_forecast": forecast.handle}[tool](args)) - assert "error" in out # nothing cached yet: the report goes without it, no request made - assert calls == [] - await pollen.close() - await forecast.close() - - async def test_a_forecast_saved_by_the_older_bom_version_still_loads(tmp_path): """Its summary has no emoji until the first fetch (the Open-Meteo table carries them); its source and tag are ignored.""" from lib.snapshots import Snapshots diff --git a/tests/test_specs.py b/tests/test_specs.py index 2ab01cc5..daed994c 100644 --- a/tests/test_specs.py +++ b/tests/test_specs.py @@ -243,10 +243,11 @@ def test_a_bar_below_zero_has_its_bright_end_at_the_bottom(monkeypatch): def test_darkmode_is_off_by_default_on_always_and_a_time_range_dark_between_its_ends(monkeypatch): from datetime import datetime from zoneinfo import ZoneInfo - from lib import charts + from lib import charts, theme zone = ZoneInfo("Australia/Melbourne") at = lambda hour, minute=0: datetime(2026, 11, 1, hour, minute, tzinfo=zone) - monkeypatch.setattr(charts, "MODE", "off") + monkeypatch.setattr(theme, "MODE", "off") + monkeypatch.setattr(theme, "ZONE", None) assert not charts.dark_now(at(23)) charts.configure("on", zone) assert charts.dark_now(at(12)) diff --git a/tests/test_startup.py b/tests/test_startup.py index 16a92ee6..603dc9bb 100644 --- a/tests/test_startup.py +++ b/tests/test_startup.py @@ -1,5 +1,8 @@ -"""Runs ecobot.main() end to end against fake sources and a fake Telegram.""" +"""Runs the programs' main() end to end against fakes: ecobot-mcp's (python -m ecobot_mcp) over the fake sources, which runs them, +their archives and the alert rules; and the bot's (ecobot.main), ecobot-mcp's client (docs/ecobot-mcp.md step 6b), against ecobot-mcp +under uvicorn on a localhost port and a fake Telegram.""" +import contextlib import logging import asyncio import os @@ -9,11 +12,20 @@ import pytest import ecobot +import ecobot_mcp.__main__ as service_main +from ecobot_mcp import core +from lib.alert_log import AlertLog +from lib.config import Config from lib.ecowitt import archive +from lib.mcp_server import EcobotServer, http_app +from lib.service.context import Context from datetime import datetime, timedelta, timezone from lib.airgradient import source as air_source -from tests.fakes import air_transport, config, ecowitt_transport +from tests.fakes import TZ, air_transport, config, ecowitt_transport +from tests.test_mcp_listen import Serving, free_port, until + +TOKEN = "s3cret" @pytest.fixture(autouse=True) @@ -28,21 +40,16 @@ def the_log_as_it_was(): @pytest.fixture(autouse=True) -def buttons_not_drawn_ahead(monkeypatch): - """The keyboard's charts are not drawn ahead here (seven charts a start; test_periods.py tests the drawing): only noted.""" - drawn = [] - - async def note(self, tg_bot): - drawn.append(tg_bot) - monkeypatch.setattr(ecobot.Bot, "draw_buttons_ahead", note) - return drawn +def quick_shutdown(monkeypatch): + """A listen stream still open when ecobot-mcp stops is ended after a quarter of a second, not SHUTDOWN_SECONDS (3).""" + monkeypatch.setattr(service_main, "SHUTDOWN_SECONDS", 0.25) class FakeApp: def __init__(self): - self.sent, self.handlers = [], [] + self.sent, self.handlers, self.menus = [], [], [] self.updater = NS(start_polling=self._noop, stop=self._noop) - self.bot = NS(username="testbot", send_message=self.send_message) + self.bot = NS(username="testbot", send_message=self.send_message, set_my_commands=self.set_my_commands) async def _noop(self, *a, **k): pass @@ -50,6 +57,9 @@ async def _noop(self, *a, **k): async def send_message(self, chat_id, text, **kw): self.sent.append((chat_id, text, kw)) + async def set_my_commands(self, commands): + self.menus.append([c.command for c in commands]) + initialize = shutdown = start = stop = _noop def add_handler(self, h, group=0): @@ -67,69 +77,56 @@ def __getattr__(self, name): return lambda *a, **k: self if name != "build" else self.app -async def test_main_starts_warms_and_shuts_down_cleanly(tmp_path, monkeypatch, caplog, buttons_not_drawn_ahead): - caplog.set_level("INFO") - cfg = config(tmp_path, log_width=120) - monkeypatch.setattr(ecobot._format, "width", 0) # put back after the test - eco_t, _ = ecowitt_transport(history_days=30) +# ---------- ecobot-mcp (python -m ecobot_mcp): the sources, their archives, the alert rules ---------- +def ecobot_mcp_settings(tmp_path, monkeypatch, history_days=10, **over) -> Config: + """ecobot-mcp's settings (the fake station and air sensor, a free port), its sources' fakes plugged in, the archives unpaced.""" + cfg = config(tmp_path, telegram_token="", auth_tokens=(TOKEN,), mcp_bind=("127.0.0.1", free_port()), **over) + eco_t, _ = ecowitt_transport(history_days=history_days) air_t, _ = air_transport(oldest=datetime.now(timezone.utc) - timedelta(days=5)) - app = FakeApp() - monkeypatch.setattr(ecobot.Config, "from_env", classmethod(lambda cls: cfg)) - for cls, transport in ((ecobot.Ecowitt, eco_t), (ecobot.AirGradient, air_t)): + monkeypatch.setattr(Config, "from_env", classmethod(lambda cls, bot=True: cfg)) + 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.setattr(ecobot.Application, "builder", staticmethod(lambda: FakeBuilder(app))) monkeypatch.setattr(archive, "PACE_SECONDS", 0) monkeypatch.setattr(air_source, "BACKFILL_PACE", 0) monkeypatch.setattr(air_source, "BACKFILL_EMPTY_STOP", 3) + return cfg + - async def stop_when_archived(): # the background archives finish, then we shut down +async def run_ecobot_mcp_until_archived(caplog): + """ecobot-mcp's main() until both background archives have finished, then stopped (SIGTERM).""" + async def stop_when_archived(): for _ in range(300): if any("Backfill Ecowitt: " in l and " fetched/failed, " in l for l in caplog.text.splitlines()) and "Backfill AirGradient:" in caplog.text: break await asyncio.sleep(0.1) os.kill(os.getpid(), signal.SIGTERM) stopper = asyncio.create_task(stop_when_archived()) - await ecobot.main() + await service_main.main() await stopper + + +async def test_ecobot_mcp_starts_warms_archives_and_shuts_down_cleanly(tmp_path, monkeypatch, caplog): + caplog.set_level("INFO") + ecobot_mcp_settings(tmp_path, monkeypatch, history_days=30) + await run_ecobot_mcp_until_archived(caplog) log = caplog.text - assert "Ecowitt: 'Fairleigh' (" in log and "): cloud (" in log and "Telegram: @testbot, Model: " in log + assert "Ecowitt: 'Fairleigh' (" in log and "): cloud (" in log and "MCP: http://127.0.0.1:" in log assert not any(line.startswith(("Sources:", "Refreshing every")) or "Alerts: " in line and " chats" in line for line in log.splitlines()) assert "Startup fetch:" not in log and " requests to fetch" in log and "Backfill AirGradient:" in log final = next(line for line in log.splitlines() if "Backfill Ecowitt: " in line and " fetched/failed, " in line) assert "/0 fetched/failed, " in final and "d held (5m/30m/4h/1d)" in final - assert len(app.handlers) == 11 # start+help, reset, keyboard, alerts, usage, report, the one button handler, other updates, membership, messages, errors - assert "Alerts NOT running" not in log - assert ecobot._format.width == 120 # LOG_WIDTH reaches the bot's own log lines - assert buttons_not_drawn_ahead == [app.bot] # the keyboard's charts are drawn ahead once the sources are warm + assert "Alerts NOT running" not in log and "Telegram" not in log 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") - cfg = config(tmp_path) - eco_t, _ = ecowitt_transport(history_days=10) - air_t, _ = air_transport(oldest=datetime.now(timezone.utc) - timedelta(days=5)) - app = FakeApp() - monkeypatch.setattr(ecobot.Config, "from_env", classmethod(lambda cls: cfg)) - for cls, transport in ((ecobot.Ecowitt, eco_t), (ecobot.AirGradient, air_t)): - monkeypatch.setattr(cls, "__init__", lambda self, c, transport=None, orig=cls.__init__, t=transport, **kw: orig(self, c, t, **kw)) - monkeypatch.setattr(ecobot.Application, "builder", staticmethod(lambda: FakeBuilder(app))) - monkeypatch.setattr(archive, "PACE_SECONDS", 0) - monkeypatch.setattr(air_source, "BACKFILL_PACE", 0) - monkeypatch.setattr(air_source, "BACKFILL_EMPTY_STOP", 3) + ecobot_mcp_settings(tmp_path, monkeypatch) async def broken(self): raise RuntimeError("no readings") - monkeypatch.setattr(ecobot.WeatherMonitor, "init", broken) - - async def stop_when_archived(): - for _ in range(300): - if any("Backfill Ecowitt: " in l and " fetched/failed, " in l for l in caplog.text.splitlines()) and "Backfill AirGradient:" in caplog.text: - break - await asyncio.sleep(0.1) - os.kill(os.getpid(), signal.SIGTERM) - stopper = asyncio.create_task(stop_when_archived()) - await ecobot.main() - await stopper + monkeypatch.setattr(WeatherMonitor, "init", broken) + await run_ecobot_mcp_until_archived(caplog) log = caplog.text assert "Weather alerts couldn't start" in log assert "Alerts NOT running: rain, gusts, UV, temperature crossing (see the error above)" in log @@ -139,32 +136,13 @@ async def test_a_failed_first_refresh_does_not_stop_the_alerts_or_the_archives(t """If the first Ecowitt or AirGradient refresh raises, the archive and the backfill (and the alert monitor) must still start: the regular refreshes then catch up.""" caplog.set_level("INFO") - cfg = config(tmp_path) - eco_t, _ = ecowitt_transport(history_days=10) - air_t, _ = air_transport(oldest=datetime.now(timezone.utc) - timedelta(days=5)) - app = FakeApp() - monkeypatch.setattr(ecobot.Config, "from_env", classmethod(lambda cls: cfg)) - for cls, transport in ((ecobot.Ecowitt, eco_t), (ecobot.AirGradient, air_t)): - monkeypatch.setattr(cls, "__init__", lambda self, c, transport=None, orig=cls.__init__, t=transport, **kw: orig(self, c, t, **kw)) - monkeypatch.setattr(ecobot.Application, "builder", staticmethod(lambda: FakeBuilder(app))) - monkeypatch.setattr(archive, "PACE_SECONDS", 0) - monkeypatch.setattr(air_source, "BACKFILL_PACE", 0) - monkeypatch.setattr(air_source, "BACKFILL_EMPTY_STOP", 3) + ecobot_mcp_settings(tmp_path, monkeypatch) async def broken(self, fresh=True): raise RuntimeError("the network dropped") - monkeypatch.setattr(ecobot.Ecowitt, "warm", broken) - monkeypatch.setattr(ecobot.AirGradient, "warm", broken) - - async def stop_when_archived(): - for _ in range(300): - if any("Backfill Ecowitt: " in l and " fetched/failed, " in l for l in caplog.text.splitlines()) and "Backfill AirGradient:" in caplog.text: - break - await asyncio.sleep(0.1) - os.kill(os.getpid(), signal.SIGTERM) - stopper = asyncio.create_task(stop_when_archived()) - await ecobot.main() - await stopper + monkeypatch.setattr(core.Ecowitt, "warm", broken) + monkeypatch.setattr(core.AirGradient, "warm", broken) + await run_ecobot_mcp_until_archived(caplog) log = caplog.text assert "the network dropped" in log # the reason is in the log assert "Backfill Ecowitt: " in log and "Backfill AirGradient:" in log # yet both archives ran @@ -173,67 +151,34 @@ async def stop_when_archived(): async def test_a_source_that_cannot_even_be_made_is_left_out_and_the_others_start(tmp_path, monkeypatch, caplog): eco_t, _ = ecowitt_transport(history_days=10) - monkeypatch.setattr(ecobot.Ecowitt, "__init__", lambda self, c, orig=ecobot.Ecowitt.__init__, **kw: orig(self, c, eco_t, **kw)) + monkeypatch.setattr(core.Ecowitt, "__init__", lambda self, c, orig=core.Ecowitt.__init__, **kw: orig(self, c, eco_t, **kw)) def broken(self, cfg, transport=None, **kw): raise OSError("the cache folder is read-only") - monkeypatch.setattr(ecobot.AirGradient, "__init__", broken) - sources, _ = await ecobot.start_sources(config(tmp_path)) + monkeypatch.setattr(core.AirGradient, "__init__", broken) + sources, _ = await core.start_sources(config(tmp_path)) for s in sources: await s.close() 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_a_failure_part_way_through_starting_closes_everything_already_open(tmp_path, monkeypatch, caplog): - """Telegram fails once the sources, the model's client and the connection are up: each is closed, the last opened first, - and a close that fails doesn't stop the rest. The bot stops with the error that stopped it.""" - cfg = config(tmp_path) - eco_t, _ = ecowitt_transport(history_days=10) - air_t, _ = air_transport(oldest=datetime.now(timezone.utc) - timedelta(days=5)) - app, closed = FakeApp(), [] - app.stop = lambda: closed.append("telegram") or app._noop() - monkeypatch.setattr(ecobot.Config, "from_env", classmethod(lambda cls: cfg)) - for cls, transport in ((ecobot.Ecowitt, eco_t), (ecobot.AirGradient, air_t)): - monkeypatch.setattr(cls, "__init__", lambda self, c, transport=None, orig=cls.__init__, t=transport, **kw: orig(self, c, t, **kw)) - monkeypatch.setattr(ecobot.Application, "builder", staticmethod(lambda: FakeBuilder(app))) - - async def stuck_disk(self): - closed.append("Ecowitt") - raise OSError("disk I/O error") - monkeypatch.setattr(ecobot.Ecowitt, "close", stuck_disk) - monkeypatch.setattr(ecobot.AirGradient, "close", lambda self, orig=ecobot.AirGradient.close: closed.append("AirGradient") or orig(self)) - - class Client: - def __init__(self, **settings): - pass - - async def close(self): - closed.append("model") - monkeypatch.setattr(ecobot, "AsyncOpenAI", Client) - - async def down(self, bot): - raise RuntimeError("Telegram is down") - monkeypatch.setattr(ecobot.Bot, "publish_commands", down) - with pytest.raises(RuntimeError, match="Telegram is down"): - await ecobot.main() - assert closed == ["telegram", "model", "AirGradient", "Ecowitt"] and "disk I/O error" in caplog.text - - async def test_pollen_and_forecast_start_only_when_switched_on_and_the_forecast_uses_the_stations_location(tmp_path, monkeypatch): + from lib.forecast import Forecast + from lib.pollen import Pollen from tests.test_forecast import transport as forecast_transport from tests.test_pollen import page, transport as pollen_transport eco_t, _ = ecowitt_transport(history_days=10) calls = [] - eco_init, pollen_init, forecast_init = ecobot.Ecowitt.__init__, ecobot.Pollen.__init__, ecobot.Forecast.__init__ - monkeypatch.setattr(ecobot.Ecowitt, "__init__", lambda self, c, **kw: eco_init(self, c, eco_t, **kw)) - monkeypatch.setattr(ecobot.Pollen, "__init__", lambda self, c: pollen_init(self, c, pollen_transport(page, calls))) - monkeypatch.setattr(ecobot.Forecast, "__init__", lambda self, c, place=None: forecast_init(self, c, place, forecast_transport(calls))) - monkeypatch.setattr(ecobot.Pollen, "now", lambda self: datetime(2026, 11, 10, 12, 0)) # in the pollen season, whatever day the test runs - off, _ = await ecobot.start_sources(config(tmp_path, airgradient_token="", airgradient_location="")) + eco_init, pollen_init, forecast_init = core.Ecowitt.__init__, Pollen.__init__, Forecast.__init__ + monkeypatch.setattr(core.Ecowitt, "__init__", lambda self, c, **kw: eco_init(self, c, eco_t, **kw)) + monkeypatch.setattr(Pollen, "__init__", lambda self, c: pollen_init(self, c, pollen_transport(page, calls))) + monkeypatch.setattr(Forecast, "__init__", lambda self, c, place=None: forecast_init(self, c, place, forecast_transport(calls))) + monkeypatch.setattr(Pollen, "now", lambda self: datetime(2026, 11, 10, 12, 0)) # in the pollen season, whatever day the test runs + off, _ = await core.start_sources(config(tmp_path, airgradient_token="", airgradient_location="")) assert [s.name for s in off] == ["Ecowitt"] for s in off: await s.close() - on, _ = await ecobot.start_sources(config(tmp_path, airgradient_token="", airgradient_location="", pollen=True, forecast=True)) + on, _ = await core.start_sources(config(tmp_path, airgradient_token="", airgradient_location="", pollen=True, forecast=True)) 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() for s in on: @@ -244,23 +189,101 @@ async def test_the_other_sources_run_in_the_weather_station_s_time_zone(tmp_path from zoneinfo import ZoneInfo eco_t, _ = ecowitt_transport(history_days=10) air_t, _ = air_transport(oldest=datetime.now(timezone.utc) - timedelta(days=5)) - for cls, transport in ((ecobot.Ecowitt, eco_t), (ecobot.AirGradient, air_t)): + 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") - sources, cfg = await ecobot.start_sources(config(tmp_path, tz=ZoneInfo("UTC"))) # TZ says UTC; the station is in Melbourne + sources, cfg = await core.start_sources(config(tmp_path, tz=ZoneInfo("UTC"))) # TZ says UTC; the station is in Melbourne for s in sources: await s.close() assert [s.name for s in sources] == ["Ecowitt", "AirGradient"] and str(cfg.tz) == "Australia/Melbourne" assert all(str(s.tz) == "Australia/Melbourne" for s in sources) assert "TZ=UTC is not the weather station's time zone; using the station's, Australia/Melbourne" in caplog.text assert "has no name" not in caplog.text - sources, cfg = await ecobot.start_sources(config(tmp_path, ecowitt_api_key="", tz=timezone(timedelta(hours=10)))) + sources, cfg = await core.start_sources(config(tmp_path, ecowitt_api_key="", tz=timezone(timedelta(hours=10)))) for s in sources: await s.close() assert [s.name for s in sources] == ["AirGradient"] and cfg.tz == timezone(timedelta(hours=10)) # no station: the configured zone assert "The time zone has no name, only an offset (UTC+10:00)" in caplog.text +# ---------- the bot (ecobot.main), ecobot-mcp's client ---------- +@contextlib.asynccontextmanager +async def ecobot_mcp_up(tmp_path): + """ecobot-mcp (its server with no sources, and its alert log) under uvicorn on a free localhost port: its URL, the bot's + BOT_MCP_URL.""" + port = free_port() + alerts = AlertLog(tmp_path / "alerts.sqlite", TZ) + try: + async with Serving(http_app(EcobotServer(Context(tz=TZ), alerts), tokens=(TOKEN,)), port): + yield f"http://127.0.0.1:{port}/mcp" + finally: + alerts.close() + + +def bot_settings(tmp_path, monkeypatch, url: str, app, **over) -> Config: + """The bot's settings, ecobot-mcp at `url` with the token it accepts; `app` its Telegram.""" + cfg = config(tmp_path, mcp_url=url, auth_tokens=(TOKEN,), **over) + monkeypatch.setattr(ecobot.Config, "from_env", classmethod(lambda cls: cfg)) + monkeypatch.setattr(ecobot.Application, "builder", staticmethod(lambda: FakeBuilder(app))) + return cfg + + +async def run_bot_until(check, what: str): + """The bot's main() until check() is true, then stopped (SIGTERM).""" + async def stop_then(): + try: + await until(check, 20, what) + finally: + os.kill(os.getpid(), signal.SIGTERM) + stopper = asyncio.create_task(stop_then()) + await ecobot.main() + await stopper + + +async def test_main_starts_as_ecobot_mcps_client_and_shuts_down_cleanly(tmp_path, monkeypatch, caplog): + """The command menu is the bot's own commands and one per ecobot-mcp prompt (step 6c); no chart is drawn ahead.""" + from lib import templates + from lib.mcp_server import PROMPTS + caplog.set_level("INFO") + monkeypatch.setattr(ecobot._format, "width", 0) # put back after the test + app = FakeApp() + async with ecobot_mcp_up(tmp_path) as url: + bot_settings(tmp_path, monkeypatch, url, app, log_width=120) + await run_bot_until(lambda: app.menus, "the command menu set") + log = caplog.text + assert "Telegram: @testbot, Model: " in log and f"ecobot-mcp: {url}" in log and "Ecowitt: " not in log + assert len(app.handlers) == 12 # start+help, reset, keyboard, alerts, usage, the buttons' commands, the prompts' commands, the one button handler, other updates, membership, messages, errors + assert ecobot._format.width == 120 # BOT_LOG_WIDTH reaches the bot's own log lines + own = [name for name, _ in templates.MENU] + assert app.menus == [[*own[:own.index("alerts")], *PROMPTS, *own[own.index("alerts"):]]] # once: the prompts read before it was set + + +async def test_a_failure_part_way_through_starting_closes_everything_already_open(tmp_path, monkeypatch, caplog): + """Telegram fails once ecobot-mcp's connection, the model's client and Telegram are up: each is closed, the last opened first, + and a close that fails doesn't stop the rest. The bot stops with the error that stopped it.""" + app, closed = FakeApp(), [] + app.stop = lambda: closed.append("telegram") or app._noop() + + class Client: + def __init__(self, **settings): + pass + + async def close(self): + closed.append("model") + raise OSError("connection reset") + monkeypatch.setattr(ecobot, "AsyncOpenAI", Client) + monkeypatch.setattr(ecobot.RemoteWeather, "close", lambda self, orig=ecobot.RemoteWeather.close: closed.append("ecobot-mcp") or orig(self)) + + async def down(self, bot): + raise RuntimeError("Telegram is down") + monkeypatch.setattr(ecobot.Bot, "publish_commands", down) + async with ecobot_mcp_up(tmp_path) as url: + bot_settings(tmp_path, monkeypatch, url, app) + with pytest.raises(RuntimeError, match="Telegram is down"): + await ecobot.main() + assert closed == ["telegram", "model", "ecobot-mcp"] and "connection reset" in caplog.text + + def test_the_time_zone_without_a_station_is_tz_else_the_one_etc_localtime_links_to(monkeypatch, caplog): from lib import config as config_module from lib.config import local_tz @@ -277,20 +300,21 @@ def test_the_time_zone_without_a_station_is_tz_else_the_one_etc_localtime_links_ def test_the_alert_cooldown_is_configurable_with_a_default_and_limits(monkeypatch): from lib.config import Config - monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "t") - monkeypatch.setenv("OPENROUTER_API_KEY", "k") - monkeypatch.setenv("ECOWITT_API_KEY", "a") - monkeypatch.setenv("ECOWITT_APP_KEY", "b") - monkeypatch.delenv("ALERT_COOLDOWN_MINUTES", raising=False) - assert Config.from_env().alert_cooldown_minutes == 60 + monkeypatch.setenv("BOT_TELEGRAM_TOKEN", "t") + monkeypatch.setenv("BOT_OPENROUTER_API_KEY", "k") + monkeypatch.setenv("MCP_ECOWITT_API_KEY", "a") + monkeypatch.setenv("MCP_ECOWITT_APP_KEY", "b") + monkeypatch.delenv("MCP_ALERT_COOLDOWN_MINUTES", raising=False) + assert Config.from_env(bot=False).alert_cooldown_minutes == 60 # (ecobot-mcp's: the alert rules are its) for value, want in (("45", 45), ("1", 5), ("0", 5), ("-3", 5), ("999", 150), ("junk", 60)): # 0 is under 5 like 1 is - monkeypatch.setenv("ALERT_COOLDOWN_MINUTES", value) - assert Config.from_env().alert_cooldown_minutes == want, value + monkeypatch.setenv("MCP_ALERT_COOLDOWN_MINUTES", value) + assert Config.from_env(bot=False).alert_cooldown_minutes == want, value def test_the_log_level_is_a_setting_and_a_typo_keeps_info_with_a_warning(monkeypatch, caplog): from lib.config import Config - for k, v in (("TELEGRAM_BOT_TOKEN", "t"), ("OPENROUTER_API_KEY", "k"), ("ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b")): + for k, v in (("BOT_TELEGRAM_TOKEN", "t"), ("BOT_OPENROUTER_API_KEY", "k"), ("BOT_MCP_URL", "http://127.0.0.1:8765/mcp"), + ("MCP_ECOWITT_API_KEY", "a"), ("MCP_ECOWITT_APP_KEY", "b")): monkeypatch.setenv(k, v) monkeypatch.delenv("LOG_LEVEL", raising=False) assert Config.from_env().log_level == "INFO" @@ -303,86 +327,91 @@ def test_the_log_level_is_a_setting_and_a_typo_keeps_info_with_a_warning(monkeyp def test_a_blank_setting_means_its_default_and_a_missing_key_says_which(monkeypatch, caplog): from lib.config import Config - for k, v in (("TELEGRAM_BOT_TOKEN", " t "), ("OPENROUTER_API_KEY", "k"), ("ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b")): + for k, v in (("BOT_TELEGRAM_TOKEN", " t "), ("BOT_OPENROUTER_API_KEY", "k"), ("BOT_MCP_URL", "http://127.0.0.1:8765/mcp"), + ("MCP_ECOWITT_API_KEY", "a"), ("MCP_ECOWITT_APP_KEY", "b")): monkeypatch.setenv(k, v) - for k in ("OPENROUTER_MODEL", "OPENROUTER_BASE_URL", "PLACE", "POLLEN_DISTRICT", "TUYA_BASE_URL"): + for k in ("BOT_OPENROUTER_MODEL", "BOT_OPENROUTER_BASE_URL", "PLACE", "MCP_POLLEN_DISTRICT", "IRRIGATION_TUYA_BASE_URL"): monkeypatch.setenv(k, " ") monkeypatch.setenv("POLLEN", "enabled") - cfg = Config.from_env() - assert (cfg.telegram_token, cfg.openrouter_model, cfg.openrouter_base_url, cfg.place, cfg.pollen_district, cfg.tuya_base_url) == ( + cfg, service = Config.from_env(), Config.from_env(bot=False) # (the bot's settings; ecobot-mcp's) + for k, v in (("IRRIGATION_TUYA_DEVICE_ID", "d"), ("IRRIGATION_TUYA_CLIENT_ID", "c"), ("IRRIGATION_TUYA_CLIENT_SECRET", "s")): + monkeypatch.setenv(k, v) + irrigation = Config.from_env(program="irrigation") # (irrigation-mcp's) + assert (cfg.telegram_token, cfg.openrouter_model, cfg.openrouter_base_url, service.place, service.pollen_district, irrigation.tuya_base_url) == ( "t", "deepseek/deepseek-v4.1-flash-1017", "https://openrouter.ai/api/v1", "Melbourne", "Central", "https://openapi.tuyaeu.com") - assert cfg.pollen is False and "POLLEN: 'enabled' is not on or off; keeping the default (off)" in caplog.text - monkeypatch.setenv("OPENROUTER_API_KEY", " ") + assert service.pollen is False and "POLLEN: 'enabled' is not on or off; keeping the default (off)" in caplog.text + monkeypatch.setenv("BOT_OPENROUTER_API_KEY", " ") assert Config.from_env().openrouter_api_key == "" # no model is allowed: the bot then answers only what it works out itself - monkeypatch.setenv("TELEGRAM_BOT_TOKEN", " ") - with pytest.raises(SystemExit, match="TELEGRAM_BOT_TOKEN is not set"): + monkeypatch.setenv("BOT_TELEGRAM_TOKEN", " ") + with pytest.raises(SystemExit, match="BOT_TELEGRAM_TOKEN is not set"): Config.from_env() def test_the_rain_quiet_hours_are_configurable(): from lib.config import _hours - hours = lambda text: _hours(text, (0, 6), "RAIN_QUIET_HOURS") + hours = lambda text: _hours(text, (0, 6), "MCP_RAIN_QUIET_HOURS") assert hours("") == (0, 6) and hours("22-6") == (22, 6) and hours("off") is None assert hours("junk") == (0, 6) and hours("6-6") == (0, 6) and hours("0-25") == (0, 6) def test_feels_like_in_chart_all_is_off_by_default_and_a_config_option_turns_it_on(monkeypatch): from lib.config import Config - monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "t") - monkeypatch.setenv("OPENROUTER_API_KEY", "k") - monkeypatch.setenv("ECOWITT_API_KEY", "a") - monkeypatch.setenv("ECOWITT_APP_KEY", "b") - monkeypatch.delenv("CHART_ALL_FEELS_LIKE", raising=False) - assert Config.from_env().chart_all_feels_like is False - monkeypatch.setenv("CHART_ALL_FEELS_LIKE", "on") - assert Config.from_env().chart_all_feels_like is True + monkeypatch.setenv("BOT_TELEGRAM_TOKEN", "t") + monkeypatch.setenv("BOT_OPENROUTER_API_KEY", "k") + monkeypatch.setenv("MCP_ECOWITT_API_KEY", "a") + monkeypatch.setenv("MCP_ECOWITT_APP_KEY", "b") + monkeypatch.delenv("MCP_CHART_ALL_FEELS_LIKE", raising=False) + assert Config.from_env(bot=False).chart_all_feels_like is False # (ecobot-mcp's: it draws the charts) + monkeypatch.setenv("MCP_CHART_ALL_FEELS_LIKE", "on") + assert Config.from_env(bot=False).chart_all_feels_like is True def test_vpd_in_chart_all_is_off_by_default_and_a_config_option_turns_it_on(monkeypatch): from lib.config import Config - for k, v in (("TELEGRAM_BOT_TOKEN", "t"), ("OPENROUTER_API_KEY", "k"), ("ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b")): + for k, v in (("BOT_TELEGRAM_TOKEN", "t"), ("BOT_OPENROUTER_API_KEY", "k"), ("BOT_MCP_URL", "http://127.0.0.1:8765/mcp"), + ("MCP_ECOWITT_API_KEY", "a"), ("MCP_ECOWITT_APP_KEY", "b")): monkeypatch.setenv(k, v) - monkeypatch.delenv("CHART_ALL_VPD", raising=False) - assert Config.from_env().chart_all_vpd is False - monkeypatch.setenv("CHART_ALL_VPD", "on") - assert Config.from_env().chart_all_vpd is True - - -async def test_main_with_the_irrigation_controller_starts_its_check_and_watchdog_and_closes_it(tmp_path, monkeypatch, caplog): - import httpx - from lib.irrigation import tuya as tuya_module + monkeypatch.delenv("MCP_CHART_ALL_VPD", raising=False) + assert Config.from_env(bot=False).chart_all_vpd is False + monkeypatch.setenv("MCP_CHART_ALL_VPD", "on") + assert Config.from_env(bot=False).chart_all_vpd is True + + +async def test_main_with_irrigation_mcp_is_its_client_listening_to_its_alerts_and_runs_no_controller_itself(tmp_path, monkeypatch, caplog): + """BOT_IRRIGATION_MCP_URL (step 8b): the bot connects to irrigation-mcp (under uvicorn here, with the same token) as it does to + ecobot-mcp, its Irrigation button on the keyboard, its alerts delivered (their last id kept apart); no Tuya client, watchdog or daily + check runs in the bot.""" + from lib.irrigation import Watchdog + from lib.irrigation import server as irrigation_server + from lib.irrigation.state import IrrigationState + from lib.alerts.notify import AlertState + from tests.fakes import FakeController caplog.set_level("INFO") - cfg = config(tmp_path, tuya_device_id="dev1", tuya_client_id="cid", tuya_client_secret="s") - eco_t, _ = ecowitt_transport(history_days=10) - air_t, _ = air_transport(oldest=datetime.now(timezone.utc) - timedelta(days=5)) - closed = [] - - def tuya(request): - if request.url.path.startswith("/v1.0/token"): - return httpx.Response(200, json={"success": True, "result": {"access_token": "t", "expire_time": 7200}}) - return httpx.Response(200, json={"success": True, "result": [{"code": "battery_percentage", "value": 80}]}) + app, port = FakeApp(), free_port() + device = FakeController() + alerts = AlertLog(tmp_path / "irrigation_alerts.sqlite", TZ) + server = irrigation_server.IrrigationServer(device, Watchdog(device, IrrigationState(tmp_path / "irrigation_state.json")), alerts, tz=TZ) + publishing = asyncio.create_task(server.run()) + try: + async with ecobot_mcp_up(tmp_path) as url, Serving(irrigation_server.http_app(server, tokens=(TOKEN,)), port): + bot_settings(tmp_path, monkeypatch, url, app, irrigation_mcp_url=f"http://127.0.0.1:{port}/mcp") + await run_bot_until(lambda: "irrigation-mcp" in AlertState(tmp_path / "state.json").marks, "the irrigation alerts' delivery") + finally: + publishing.cancel() + await asyncio.gather(publishing, return_exceptions=True) + alerts.close() + assert f"irrigation-mcp: connected to http://127.0.0.1:{port}/mcp" in caplog.text and len(app.handlers) == 12 + assert device.commands == [] # nothing asked of the controller at start + + +async def test_without_bot_irrigation_mcp_url_there_is_no_irrigation_and_old_tuya_settings_are_a_warning(tmp_path, monkeypatch, caplog): app = FakeApp() - monkeypatch.setattr(ecobot.Config, "from_env", classmethod(lambda cls: cfg)) - for cls, transport in ((ecobot.Ecowitt, eco_t), (ecobot.AirGradient, air_t)): - monkeypatch.setattr(cls, "__init__", lambda self, c, transport=None, orig=cls.__init__, t=transport, **kw: orig(self, c, t, **kw)) - monkeypatch.setattr(tuya_module.Tuya, "__init__", lambda self, c, transport=None, orig=tuya_module.Tuya.__init__: orig(self, c, httpx.MockTransport(tuya))) - monkeypatch.setattr(tuya_module.Tuya, "close", lambda self, orig=tuya_module.Tuya.close: closed.append(1) or orig(self)) - monkeypatch.setattr(ecobot.Application, "builder", staticmethod(lambda: FakeBuilder(app))) - monkeypatch.setattr(archive, "PACE_SECONDS", 0) - monkeypatch.setattr(air_source, "BACKFILL_PACE", 0) - monkeypatch.setattr(air_source, "BACKFILL_EMPTY_STOP", 3) - - async def stop_when_archived(): - for _ in range(300): - if any("Backfill Ecowitt: " in l and " fetched/failed, " in l for l in caplog.text.splitlines()) and "Backfill AirGradient:" in caplog.text: - break - await asyncio.sleep(0.1) - os.kill(os.getpid(), signal.SIGTERM) - stopper = asyncio.create_task(stop_when_archived()) - await ecobot.main() - await stopper - assert "Alerts NOT running" not in caplog.text # the irrigation alerts started with the rest - assert len(app.handlers) == 11 and closed == [1] # the same handlers (buttons share one entry point), and the client closed at shutdown + monkeypatch.setenv("BOT_TUYA_DEVICE_ID", "dev1") # (the bot ran the controller itself before) + async with ecobot_mcp_up(tmp_path) as url: + bot_settings(tmp_path, monkeypatch, url, app) + await run_bot_until(lambda: app.menus, "the command menu set") + assert "The irrigation controller's settings are set but BOT_IRRIGATION_MCP_URL isn't" in caplog.text + assert "irrigation-mcp:" not in caplog.text def test_only_the_lines_that_are_not_ordinary_are_marked_with_their_level(): @@ -437,23 +466,25 @@ def test_a_traceback_is_logged_whole_after_its_message(): def test_the_log_width_is_24_unless_set_and_0_keeps_whole_messages(monkeypatch): from lib.config import Config - for k, v in (("TELEGRAM_BOT_TOKEN", "t"), ("OPENROUTER_API_KEY", "k"), ("ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b")): + for k, v in (("BOT_TELEGRAM_TOKEN", "t"), ("BOT_OPENROUTER_API_KEY", "k"), ("BOT_MCP_URL", "http://127.0.0.1:8765/mcp"), + ("MCP_ECOWITT_API_KEY", "a"), ("MCP_ECOWITT_APP_KEY", "b")): monkeypatch.setenv(k, v) - monkeypatch.delenv("LOG_WIDTH", raising=False) + monkeypatch.delenv("BOT_LOG_WIDTH", raising=False) assert Config.from_env().log_width == 24 for value, want in (("120", 120), ("0", 0), ("junk", 24), ("-5", 24), ("7.5", 24), ("²", 24)): - monkeypatch.setenv("LOG_WIDTH", value) + monkeypatch.setenv("BOT_LOG_WIDTH", value) assert Config.from_env().log_width == want, value def test_the_preload_chat_is_a_chat_id_or_off(monkeypatch): from lib.config import Config - for k, v in (("TELEGRAM_BOT_TOKEN", "t"), ("OPENROUTER_API_KEY", "k"), ("ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b")): + for k, v in (("BOT_TELEGRAM_TOKEN", "t"), ("BOT_OPENROUTER_API_KEY", "k"), ("BOT_MCP_URL", "http://127.0.0.1:8765/mcp"), + ("MCP_ECOWITT_API_KEY", "a"), ("MCP_ECOWITT_APP_KEY", "b")): monkeypatch.setenv(k, v) - monkeypatch.delenv("TELEGRAM_PRELOAD_CHAT", raising=False) + monkeypatch.delenv("BOT_TELEGRAM_PRELOAD_CHAT", raising=False) assert Config.from_env().telegram_preload_chat is None for value, want in (("-1001234567890", -1001234567890), ("42", 42), ("", None), ("junk", None)): - monkeypatch.setenv("TELEGRAM_PRELOAD_CHAT", value) + monkeypatch.setenv("BOT_TELEGRAM_PRELOAD_CHAT", value) assert Config.from_env().telegram_preload_chat == want, value @@ -472,14 +503,9 @@ async def test_a_token_telegram_rejects_stops_the_bot_with_a_plain_message_that_ class Rejecting(FakeApp): async def initialize(self): raise InvalidToken("The token `SECRET-TOKEN-123` was rejected by the server.") - cfg = config(tmp_path) - eco_t, _ = ecowitt_transport(history_days=3) - air_t, _ = air_transport() - monkeypatch.setattr(ecobot.Config, "from_env", classmethod(lambda cls: cfg)) - for cls, transport in ((ecobot.Ecowitt, eco_t), (ecobot.AirGradient, air_t)): - monkeypatch.setattr(cls, "__init__", lambda self, c, transport=None, orig=cls.__init__, t=transport, **kw: orig(self, c, t, **kw)) - monkeypatch.setattr(ecobot.Application, "builder", staticmethod(lambda: FakeBuilder(Rejecting()))) - with pytest.raises(SystemExit) as stopped: - await ecobot.main() - assert "TELEGRAM_BOT_TOKEN was rejected by Telegram" in str(stopped.value) and "SECRET" not in str(stopped.value) + async with ecobot_mcp_up(tmp_path) as url: + bot_settings(tmp_path, monkeypatch, url, Rejecting()) + with pytest.raises(SystemExit) as stopped: + await ecobot.main() + assert "BOT_TELEGRAM_TOKEN was rejected by Telegram" in str(stopped.value) and "SECRET" not in str(stopped.value) assert stopped.value.__cause__ is None and stopped.value.__suppress_context__ diff --git a/tests/test_templates.py b/tests/test_templates.py index 4b2a3e09..c94187cb 100644 --- a/tests/test_templates.py +++ b/tests/test_templates.py @@ -2,38 +2,40 @@ from datetime import datetime from types import SimpleNamespace as NS -from lib import intent, templates +from lib import templates from lib.bot import Bot from tests.fakes import EVERY_SOURCE, TZ +from tests.served import unreached NOW = datetime(2026, 10, 1, 12, 0, tzinfo=TZ) def test_a_button_label_is_its_sentence_without_the_emoji_and_typed_text_is_left_alone(): - assert templates.sentence("\U0001f4cb Status") == "Report" + assert templates.sentence("\U0001f4cb Status") == templates.STATUS == "Status" assert templates.sentence("\U0001f4c8 Temperature") == "Temperature chart 1d" assert templates.sentence(templates.CAPABILITIES) == "What can you do?" - assert templates.sentence("report") is None and templates.sentence("Report") is None + assert templates.sentence("report") is None and templates.sentence("Status") is None and templates.sentence("Rain chart 1d") is None assert len(templates.SENTENCES) == 9 def test_every_button_asks_something_the_bot_understands(): + """Status is Status (the gauges and the report prompt: Bot.status); each chart button is a fixed call, a named reading's chart over a + day: summary with the readings the service reads its words as. (Help & Alerts is bot.on_message's: about and the alert settings.)""" + from lib.service.names import CATALOGUE + def read(label): - return intent.read(templates.sentence(label), NOW) - assert read("\U0001f4cb Status").report - weather = read("\U0001f326️ Weather") - assert intent.wants_chart_all(templates.sentence("\U0001f326️ Weather")) and weather.chart_in_code - assert weather.chart_fields[0] == "temperature" and weather.chart_fields[-1] == "wind" - for label, groups in (("\U0001f327️ Rain", "rainfall"), ("\U0001f4c8 Temperature", "outdoor,indoor"), - ("\U0001f4a7 Humidity", "outdoor,indoor"), ("\U0001f4a8 Wind", "wind")): - name, args, _ = read(label).fast - assert name == "weather_history" and args["chart"] is True and args["groups"] == groups and read(label).chart_in_code - assert read("\U0001f4a7 Humidity").chart_field == "humidity" and read("\U0001f327️ Rain").rain_caption - name, args, _ = read("\U0001f3ed Air Quality").fast - assert name == "air_quality" and args["chart"] is True and set(args["metrics"]) == {"pm1", "pm2_5", "pm10", "co2", "voc_index", "nox_index"} - name, args, _ = read("\U0001f52c Particulates").fast - assert name == "air_quality" and args["chart"] is True and set(args["metrics"]) == {"pm1", "pm2_5", "pm10"} - assert read(templates.CAPABILITIES).about_the_bot + return templates.call(templates.sentence(label)) + assert templates.sentence("\U0001f4cb Status") == templates.STATUS and read("\U0001f4cb Status") is None + for label, names in (("\U0001f327️ Rain", ["rainfall.rain"]), ("\U0001f4c8 Temperature", ["outdoor.temperature", "indoor.temperature"]), + ("\U0001f4a7 Humidity", ["outdoor.humidity", "indoor.humidity"]), ("\U0001f4a8 Wind", ["wind.wind_speed", "wind.wind_direction"]), + ("\U0001f3ed Air Quality", ["air.pm2_5", "air.pm10", "air.pm1", "air.co2", "air.voc_index", "air.nox_index"]), + ("\U0001f52c Particulates", ["air.pm2_5", "air.pm10", "air.pm1"])): + tool, args = read(label) + assert tool == "summary" and args["chart"] is True and args["period"] == "1d", label + assert [r.name for r in CATALOGUE.resolve(args["readings"], default=None)] == names, label + tool, args = read("\U0001f326️ Weather") + readings = [r.name for r in CATALOGUE.resolve(args["readings"], default=None)] + assert readings[0] == "outdoor.temperature" and readings[-1] == "wind.wind_direction" def test_the_keyboard_is_persistent_and_has_every_button(): @@ -45,11 +47,14 @@ def test_the_keyboard_is_persistent_and_has_every_button(): class Recorder(Bot): def __init__(self, state): - super().__init__(NS(tz=TZ), None, [], state) + super().__init__(NS(tz=TZ), None, state, service=unreached()) # (it asks nothing: respond and status are recorded) self.asked, self.alerts = [], 0 - async def respond(self, update, context, text): - self.asked.append(text) + async def respond(self, update, context, text, call=None): + self.asked.append((text, call)) + + async def status(self, update, context): + self.asked.append("status") async def on_alerts(self, update, context): self.alerts += 1 @@ -66,10 +71,13 @@ async def reply_text(body, **kw): async def test_tapping_a_button_asks_its_sentence_and_capabilities_and_alerts_prints_both(alert_state): + """Status is Status; a chart button its sentence with its fixed call (no model); anything typed goes to the model as it is (no call), + "rain chart 1d" typed included (step 6c).""" bot = Recorder(alert_state) - for text in ("\U0001f4cb Status", "weather now", templates.CAPABILITIES): + for text in ("\U0001f4cb Status", "weather now", "\U0001f327️ Rain", "rain chart 1d", templates.CAPABILITIES): await bot.on_message(message(text)[0], NS(bot=NS(username="b", id=99))) - assert bot.asked == ["Report", "weather now"] and bot.alerts == 1 # capabilities are not sent to the model + assert bot.asked == ["status", ("weather now", None), ("Rain chart 1d", templates.CALLS["Rain chart 1d"]), ("rain chart 1d", None)] + assert bot.alerts == 1 # capabilities are not sent to the model async def test_start_carries_the_keyboard_in_private_chats_only_and_keyboard_off_removes_it(alert_state): @@ -138,7 +146,7 @@ async def test_a_chat_with_an_old_or_no_keyboard_gets_the_current_one_with_its_n from lib.alerts.notify import AlertState state = AlertState(tmp_path / "s.json") state.add_chat(1, "Rob") - bot = Bot(NS(tz=TZ), None, [], state) + bot = Bot(NS(tz=TZ), None, state, service=unreached()) # (the keyboard alone: ecobot-mcp is asked nothing) msg = Replies() assert bot._keyboard_stale(msg) # never had it state.set_keyboard(1, "old1234") @@ -154,7 +162,7 @@ async def test_start_and_keyboard_commands_record_which_keyboard_the_chat_has(tm from lib.alerts.notify import AlertState state = AlertState(tmp_path / "s.json") state.add_chat(1, "Rob") - bot = Bot(NS(tz=TZ), None, [], state) + bot = Bot(NS(tz=TZ), None, state, service=unreached()) # (the keyboard alone: ecobot-mcp is asked nothing) update, _ = message("/keyboard off") await bot.on_keyboard(update, NS(args=["off"])) assert state.keyboard(1) == templates.HIDDEN @@ -167,7 +175,7 @@ async def test_start_and_keyboard_commands_record_which_keyboard_the_chat_has(tm assert state.keyboard(1) == templates.version() -async def test_a_reply_in_a_private_chat_carries_the_new_keyboard_once(tmp_path): +async def test_a_reply_in_a_private_chat_carries_the_new_keyboard_once(serve, tmp_path): from lib.alerts.notify import AlertState class Agent: @@ -176,7 +184,7 @@ async def run(self, *a, **k): state = AlertState(tmp_path / "s.json") state.add_chat(1, "Rob") state.set_keyboard(1, "old1234") - bot = Bot(NS(tz=TZ), Agent(), [], state) + bot = Bot(NS(tz=TZ), Agent(), state, service=await serve()) async def ask(): update, sent = message("how hot is it") @@ -207,15 +215,16 @@ def test_the_capabilities_list_adds_pollen_and_forecast_only_when_they_are_on(): assert full[-3:] == ["• Pollen and thunderstorm asthma risk (October to December)", "• Forecast", "• History charts"] -def test_every_chart_and_report_button_has_a_command_of_the_same_name(): - assert templates.COMMANDS == {"report": "Report", "dashboard": "Dashboard", "status": "Report", "rain": "Rain chart 1d", "weather": "Weather chart 1d", +def test_every_chart_and_status_button_has_a_command_of_the_same_name(): + """(/report is ecobot-mcp's report prompt now, step 6c: not one of the bot's own.)""" + assert templates.COMMANDS == {"status": "Status", "rain": "Rain chart 1d", "weather": "Weather chart 1d", "temperature": "Temperature chart 1d", "humidity": "Humidity chart 1d", "air_quality": "Air quality all metrics 1d", "particulates": "Particulates chart 1d", "wind": "Wind chart 1d"} assert all(re.fullmatch(r"[a-z0-9_]{1,32}", name) for name in templates.COMMANDS) # what Telegram accepts as a command -async def test_the_command_menu_is_sent_to_telegram_and_a_refusal_is_only_logged(caplog): +async def test_the_command_menu_is_sent_to_telegram_and_a_refusal_is_only_logged(caplog, alert_state): sent = [] class TG: @@ -226,8 +235,10 @@ class Refusing: async def set_my_commands(self, commands): raise RuntimeError("no") - await Bot.publish_commands(TG()) - await Bot.publish_commands(Refusing()) + bot = Bot(NS(tz=TZ), None, alert_state, service=unreached()) # (ecobot-mcp not reached: no prompts, the bot's own commands alone) + await bot.publish_commands(TG()) + await bot.publish_commands(TG()) # the same menu again: not sent again + await Bot(NS(tz=TZ), None, alert_state, service=unreached()).publish_commands(Refusing()) assert sent == [templates.MENU] and "Couldn't set the command menu: RuntimeError: no" in caplog.text known = {*templates.COMMANDS, "alerts", "usage", "keyboard", "reset"} assert all(re.fullmatch(r"[a-z0-9_]{1,32}", name) and 3 <= len(text) <= 256 and name in known for name, text in templates.MENU) diff --git a/tests/test_timeutil.py b/tests/test_timeutil.py index 9a06fdab..dff3a946 100644 --- a/tests/test_timeutil.py +++ b/tests/test_timeutil.py @@ -60,3 +60,9 @@ def test_at_hour_is_that_local_clock_time_on_either_side_of_a_daylight_saving_ch from lib.timeutil import at_hour assert at_hour(date(2026, 4, 5), 12, TZ) == int(datetime(2026, 4, 5, 2, tzinfo=UTC).timestamp()) # standard time, UTC+10 assert at_hour(date(2026, 4, 4), 12, TZ) == int(datetime(2026, 4, 4, 1, tzinfo=UTC).timestamp()) # daylight time, UTC+11 + + +def test_when_gives_the_form_the_tools_use_in_their_time_field(): + from lib.timeutil import when + assert when(int(datetime(2026, 10, 2, 18, 5, tzinfo=TZ).timestamp()), TZ) == "Fri 2 Oct 2026 6:05pm" + assert when(int(datetime(2026, 10, 2, 0, 7, tzinfo=TZ).timestamp()), TZ) == "Fri 2 Oct 2026 12:07am" diff --git a/tests/test_warm.py b/tests/test_warm.py index d6411213..f4d0a6c4 100644 --- a/tests/test_warm.py +++ b/tests/test_warm.py @@ -4,39 +4,24 @@ from lib.warm import Warmer, every, safely -async def test_a_warmer_runs_one_refresh_at_a_time(): - """A timed refresh waits for a question's to finish, and a question that arrives during a refresh starts none of its own.""" - release, started, seen = asyncio.Event(), asyncio.Event(), [] +async def test_a_warmer_refreshes_every_interval_as_a_timed_refresh_then_runs_its_checks_and_a_failure_stops_neither(): + seen = [] async def refresh(fresh): - seen.append(("start", fresh)) - started.set() - await release.wait() - seen.append(("end", fresh)) + seen.append(("refresh", fresh)) + if len(seen) == 1: + raise ConnectionError("no route to host") + + async def check(): + seen.append(("check",)) warmer = Warmer(refresh, interval=0) - warmer.poke() - await started.wait() # a question's refresh is running - timer = asyncio.create_task(warmer.run()) # and the timed one falls due at once - warmer.poke() # another question meanwhile - for _ in range(5): - await asyncio.sleep(0) - assert seen == [("start", False)] - release.set() - for _ in range(10): + warmer.after.append(check) + task = asyncio.create_task(warmer.run()) + for _ in range(20): await asyncio.sleep(0) - timer.cancel() - assert seen[:3] == [("start", False), ("end", False), ("start", True)] - assert all(a[0] != b[0] for a, b in zip(seen, seen[1:])) # every refresh ends before the next starts - - -async def test_stopping_a_warmer_cancels_the_refresh_a_question_started(): - async def refresh(fresh): - await asyncio.Event().wait() # never ends by itself - warmer = Warmer(refresh) - warmer.poke() - await asyncio.sleep(0) - await warmer.stop() - assert warmer._task.cancelled() + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert seen[:4] == [("refresh", True), ("check",), ("refresh", True), ("check",)] async def test_a_background_failure_has_its_traceback_logged_only_when_it_points_at_code(caplog): diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py new file mode 100644 index 00000000..d2813b8a --- /dev/null +++ b/tests/test_web_dashboard.py @@ -0,0 +1,368 @@ +"""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, +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.""" + +import asyncio +import json +import re +import os +import shutil +import subprocess +import time +from pathlib import Path +from datetime import date +from types import SimpleNamespace as NS + +import httpx +import pytest + +from lib import gauge_sheet +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 air_readings_of, readings_of +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 + +TOKEN = "s3cret" +AS_OF = {"text": "Tue 27 Oct 2026 6:42pm", "time": "2026-10-27T18:42:00+11:00"} +BROWSER = Path(__file__).with_name("web_dashboard_browser.js") + + +RAW = {"pm2_5": "pm02", "pm10": "pm10", "pm1": "pm01", "co2": "rco2", "voc_index": "tvocIndex", "nox_index": "noxIndex"} # the monitor's names + + +class Station: + """The fake station and air sensor: the station's kept live reading and the air sensor's latest (what ecobot://now/weather and + ecobot://now/air are compared from) and current's result with context over them (the days' figures of chart_samples' October + evening: the air sensor sends no NOx index just now).""" + + def __init__(self): + self.live, self.values, self.today = _station() + 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._keep_air() + + def _keep_air(self): + row = {"timestamp": "2026-10-27T07:42:00Z", **{RAW[k]: e["value"] for k, e in self.latest.items()}} + self.air._current = (row, time.time()) + + def current(self, args, meta): + assert args == gauge_sheet.call() and meta == {"fetch": False} # every gauge's reading, with context; from what is held + return {"as_of": AS_OF, **gauges_result(self.live, self.values, self.today, self.latest, self.air_values)} + + def reads(self, group: str, field: str, value: str): + self.live = json.loads(json.dumps(self.live)) + self.live[group][field]["value"] = value + self.eco._live = (time.time(), self.live) + + 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} + if value is not None: + self.latest[column] = {"value": value, "unit": ""} + self._keep_air() + + +@pytest.fixture +def station(): + return Station() + + +@pytest.fixture +def server(station): + ctx = Context(eco=station.eco, air=station.air, tz=TZ) + ctx.catalogue = Catalogue([]) + server = EcobotServer(ctx, None) + server._service = StandInService(current=station.current) + return server + + +async def get(url: str, **headers) -> httpx.Response: + async with httpx.AsyncClient() as http: + return await http.get(url, headers=headers) + + +async def test_the_page_and_its_data_are_served_without_a_token_to_any_host_and_the_data_is_gauge_sheets_tiles(server, station): + port = free_port() + base = f"http://127.0.0.1:{port}" + async with Serving(http_app(server, tokens=(TOKEN,), allowed_hosts=("127.0.0.1",)), port): + page = await get(f"{base}/dashboard", Host="deb1:8765") # by the machine's name: not an allowed host + data = await get(f"{base}/dashboard/data", Host="deb1:8765") + mcp = await get(f"{base}/mcp", Host="deb1:8765", Authorization=f"Bearer {TOKEN}") + no_token = await get(f"{base}/mcp", Accept="text/event-stream") + assert page.status_code == 200 and page.headers["content-type"].startswith("text/html") + html = page.text + assert html.startswith("") and "