No description
  • Python 86.8%
  • Go Template 7%
  • Shell 5.4%
  • Dockerfile 0.5%
  • Makefile 0.3%
Find a file
2026-10-28 08:06:55 +00:00
src built 2026-10-28 08:06:55 +00:00
.dockerignore docker 2026-10-27 16:56:55 +00:00
.gitignore init 2026-10-27 14:03:10 +00:00
cleanup.py cleanip 2026-10-27 18:45:42 +00:00
collect.py init 2026-10-27 14:03:10 +00:00
cron.txt built 2026-10-28 08:06:55 +00:00
cron_home.txt built 2026-10-28 08:06:55 +00:00
docker-compose.yml docker 2026-10-27 16:56:55 +00:00
docker-entrypoint.sh docker 2026-10-27 16:56:55 +00:00
Dockerfile docker 2026-10-27 16:56:55 +00:00
ingest.py bus/train/counter 2026-10-28 07:50:28 +00:00
Makefile bus/train/counter 2026-10-28 07:50:28 +00:00
monitor.py bus/train/counter 2026-10-28 07:50:28 +00:00
PROJECT.md init 2026-10-27 14:03:10 +00:00
ran_that.txt init 2026-10-27 14:03:10 +00:00
Readme.md built 2026-10-28 08:06:55 +00:00
requirements.txt docker 2026-10-27 16:56:55 +00:00
run_this.sh init 2026-10-27 14:03:10 +00:00
test_live.sh built 2026-10-28 08:06:55 +00:00

Dawlish monitor: plan

TODO

[DONE] = finished and confirmed by a real run. [WRITTEN] = code exists but has not been confirmed yet. Update this list as work finishes.

Foundation

  • [DONE] Plan, data sources, and the layout of the code (this file)
  • [DONE] Root collect.py and monitor.py, with src/common.py, config.py, services.py
  • [DONE] cron.txt (server) and cron_home.txt (home machine) written; the Docker image installs cron.txt itself
  • [DONE] test_live.sh: runs every cron job once, then leaves the page running

Data services (each: scraper in src/, test on a saved page, entry in services.py)

  • [DONE] buoy.py: wave buoy readings (live fetch works, 3 tests pass)
  • [DONE] scrape_metoffice.py: weather and tides (live fetch works)
  • [DONE] surf.py: 3-hourly wave forecast, scraped from surf-forecast.com (live fetch works; uses the /forecasts/latest URL, not six_day)
  • [DONE] Webcam: the page embeds the YouTube stream, loaded only when you click "Show the webcam" (no webcam.py; a still-frame service is a possible later job)
  • [WRITTEN] buses.py: routes 2, 11, 186 at Coronation Avenue, read from the three bustimes.org timetable pages (scheduled times only; fixture tests; needs one live run)
  • [DONE] ingest.py + src/fetch.sh + cron_home.txt: pages the server is blocked from (buses, buoy) are downloaded on a home machine and sent to the server
  • [DONE] rtt.py: Realtime Trains API access (token works; the free token allows a whole-day query; real replies saved as fixtures)
  • [WRITTEN] train_timetable.py: works on real data (50 + 51 trains saved). Polsloe Bridge failed because its code is POL, not PLB (fixed, needs one clean re-run to confirm). The "To Exeter" board now carries arrival at Exeter St Davids
  • [WRITTEN] trains.py: live board merged onto the timetable (live times and a cancellation seen on the page; the second call hit a 429, retry added)

Page panels (the page shows these top to bottom)

  • [DONE] Weather: next 6 hours (src/panels.py, src/views/weather.tpl)
  • [DONE] Tides: curve from 12 hours ago to 24 hours ahead, with next high and low
  • [DONE] Waves, last 6 hours: buoy chart
  • Sea section: webcam picture next to the tide and wave panels
  • [DONE] Waves, next 12 hours: cards from the surf forecast, one per 3 hours
  • [DONE] Failure handling: parts of a fetch fail independently, each panel shows "failed." and a small "last fetch: yyyy/mm/dd hh:mm (x minutes ago)" line
  • [DONE] Trains to Exeter St Davids, Exeter St Thomas, Exeter Central, Polsloe Bridge, Totnes, Newton Abbot: real data shown with arrival times, "xx minutes away", highlight, cancellations, and a change journey
  • [DONE] Dawlish trains: next 5 each way, with "xx minutes away" and the catchable highlight (shown with real data)
  • [WRITTEN] Buses: next 5 each way (src/views/buses.tpl)

Finishing

  • Open http://localhost:8080 and check how the panels actually look (the data in them is confirmed, the layout is not)
  • [DONE] Confirm the tests pass (67 passed at the last check)
  • Install the cron jobs (crontab -e, paste cron.txt, set PYTHON= to which python3)
  • [DONE] Check the RTT free-tier window and token (whole day works; 10/min, 100/hour, 1000/day)
  • [DONE] Confirm the surf-forecast table has 3-hour columns (it does on /forecasts/latest: 23 columns over 3 days; six_day is only AM/PM/Night)
  • Polish: delay colours, "leave now" marker, dark mode check (the trains' "xx minutes away" is already in)
  • ecmwf.py (TODO, not started): the latest ECMWF 10-day meteogram for Dawlish, shown as an image at the bottom of the page, just before the Credits (the links).
    • Page to fetch: https://charts.ecmwf.int/products/opencharts_meteogram?base_time=<yyyymmdd>0000&epsgram=classical_10d&lat=50.5812&lon=-3.46644&station_name=Dawlish (base_time is the forecast run, 0000 or 1200, so it must be the latest run).
    • It is a JavaScript page, so it needs the home machine's browser: ./src/fetch.py "<url>" data/downloaded/dawlish.html gave an HTML (a sample is data/downloaded/dawlish.html) with <img alt="Tue 27 Oct 2026 00 UTC" src="https://charts.ecmwf.int/streaming/20261027-1230/c1/render-worker-....png">. The class names (jss560 ...) are generated and will change: select the image by something steadier, such as src starting https://charts.ecmwf.int/streaming/ or the alt text.
    • Fetch twice a day, 1 hour after each run: 01:00 and 13:00 (cron_home.txt), then take the newest image (the src of the <img>; download the PNG too if the streaming URL expires, to be checked).
    • Name it ecmwf (NAME = "ecmwf", src/ecmwf.py, a panel and template src/views/ecmwf.tpl), add it to services.py, ingest.py, src/fetch.sh (fetch.sh ecmwf), cron_home.txt, the credits and these docs.
  • Later: e-paper script for the Raspberry Pi

A small web page (Bottle) showing weather, tides, waves, trains and buses for Dawlish. This file is the plan, the data sources, and what we must sort out.

Target: a browser tab first. Later a Raspberry Pi with an e-paper screen, reusing the same data files.

This code will be maintained by an intern. So the main rule is that it must be simple and obvious over clever:

  • One file per service. Each has the same shape and one clear top-level function, fetch(), that reads like a recipe.
  • All services are listed in one place (services.py), and everything else loops over that list.
  • Shared code lives once in common.py: downloading, saving/loading dumps, time conversion, the chart.
  • Plain dicts and lists (JSON-friendly), not classes. Times are ISO strings in UTC, converted to Europe/London only for display.
  • No caching layers, threads, or background jobs inside the web app. Cron fetches, files store, the web app just reads files.
  • Short functions with docstrings, and descriptive names over comments.

Location: Dawlish, Devon (lat 50.581, lon -3.465).

Panels

Shown on the page in this order:

# Panel Content Service file Source
1 Weather Next 6h, hourly scrape_metoffice.py Met Office beach page, Coryton Cove
2 Sea Webcam (embedded live stream, click to load), with the three sea panels: none (an embed, src/views/webcam.tpl) Sea Breeze Cam YouTube live stream
2a Tides Sinusoid from now-12h to now+24h, times and heights labelled scrape_metoffice.py same Met Office page
2b Waves (past) Wave height plot, last 6h buoy.py (fetched from home) Surfline buoy 103 "Dawlish"
2c Waves (forecast) Wave forecast, next 12h (3-hourly) surf.py surf-forecast.com, Dawlish Warren
3 Trains to... Next 5 from Dawlish to Exeter St Davids, Exeter St Thomas, Exeter Central, Polsloe Bridge, Totnes, Newton Abbot, with arrival time trains.py Realtime Trains API (free tier)
4 Dawlish trains Next 5 departures each direction ("To Exeter" also shows the arrival at Exeter St Davids) trains.py same
5 Buses Next 5 departures each direction at Coronation Avenue (scheduled times) buses.py (fetched from home) bustimes.org timetable pages

The Sea section puts the webcam next to the tide curve and wave info, so you can see what the sea is doing and why. The webcam is last on the page, and nothing is loaded from YouTube until you click it (to save bandwidth).

At the very bottom are the Credits: each source, how often it is polled, and its link (panels.credits(); the polling text is written by hand, so change it when a cron line changes), then the build number and time (see "Build and run in Docker").

How it fits together

 cron ──> collect.py ──> for each service in services.py:
                           raw  = service.download()
                           data = service.parse(raw)
                           common.save_dump(service.NAME, raw, data)
                                     │
                                     ▼
                  data/downloaded/<service>/<yyyymmddhh>.json  (+ .raw)
                                     │
                                     ▼
 browser ──> monitor.py ──> common.load_latest(name) for each panel ──> src/views/*.tpl

 Buses and the buoy (their sites block the server) take a detour:
 home machine cron ──> src/fetch.sh ──> downloads the page with Firefox ──> rsync to the server:
                       data/downloaded/<service>/from_home*  ──> ingest.py (server cron, every minute)
                       ──> parse + common.save_dump, same as collect.py would

Three moving parts:

  1. collect.py (run by cron) fetches and saves what the server can fetch itself.
  2. ingest.py (run by cron) parses and saves what the home machine sent.
  3. monitor.py (Bottle) reads the newest saved file per service and renders it.

They never call each other. If a fetch breaks, the page still shows the last good data with its age.

When something fails

Rule: one failure must never take anything else down. There are three layers:

  1. A service fails (network down, page changed, bad data). collect.py catches it, writes a line to data/downloaded/<service>/errors.log, and carries on with the next service. The failure never overwrites the last good dump.
  2. One part of a service fails. A service's data is split into independent parts, run with common.run_parts({...}). If one part raises, the others still run and are saved. The failed part is None and its message goes under "errors" in the saved data. So if the Met Office tides break, the weather still updates. (Later: one train destination failing must not stop the other five.) If every part fails, run_parts raises, which is layer 1. A dump file is named by the hour, so a later fetch in the same hour overwrites it. To stop a worse fetch replacing a better one, common.save_dump() keeps the earlier copy of any part that failed this time (the failure is still reported, so the page says "failed." and shows the older data). This happened for real: a second timetable run hit rate limits and wiped out destinations that the first run had.
  3. A panel breaks while building the page. panels.safe() catches it and the panel shows a message and "failed." while the other panels render normally.

On the trains-to panel, a destination is marked "failed." only when its own data failed. If the whole live fetch failed (for example a rate limit), that is shown once in the footer, so a page full of good data doesn't look broken six times over.

What you see on the page, under every panel:

  • A red "⚠ failed." when the latest fetch of that panel's data failed (hover it for the error). The panel keeps showing the last good data, so a failure doesn't blank the screen.
  • Very small grey text: "last fetch: 2026/10/27 12:28 (8 minutes ago) · Source: ..." This is the time of the data being shown, which may be older than the latest attempt.
  • The panel is greyed out when the data is more than 3 hours old.

How the page knows (common.load_status(service, part)): the newest dump that has good data for that part, plus "failed" if errors.log has an entry newer than the newest dump, or the newest dump's "errors" names that part.

Files

The root holds only what you run or read. All other code lives in src/.

watchmen/
  monitor.py             RUN: Bottle web app (load latest dumps, render page, build number). Thin
  collect.py             RUN (by cron): fetch + save every (or named) service. Thin, about 40 lines
  ingest.py              RUN (by cron, every minute): parse + save the pages the home machine sent
  cleanup.py             RUN (by cron): delete old raw data, zip yesterday's dumps
  cron.txt               server crontab lines (the Docker entrypoint installs this)
  cron_home.txt          crontab lines for the home machine (runs src/fetch.sh)
  Dockerfile  docker-compose.yml  docker-entrypoint.sh  Makefile   build and run in Docker
  requirements.txt       Python dependencies
  Readme.md              this plan
  PROJECT.md             working rules: Claude can't run Python, writes run_this.sh for you to run
  run_this.sh            the current "please run this and paste the output" script
  test_live.sh           run every collect.py line of cron.txt once, then serve the page

  src/
    __init__.py
    grab_frames_dawlish.sh  old webcam still-frame script, not used (the page embeds the stream)
    fetch.sh  fetch.py   RUN ON THE HOME MACHINE: download buses/buoy pages with Firefox, send to the server
    counter.txt  built.txt   build number and time; `make build` updates them, the page shows them
    config.py            constants: URLs, bus routes and stops, station codes, MINUTES_TO_STATION, token file path
    services.py          THE list of services. The only place a service is registered
    common.py            shared helpers used by everything (see below)
    scrape_metoffice.py  weather + tides (scraper, kept easy to fix)
    buoy.py              wave buoy readings
    surf.py              wave forecast (scraper)
    rtt.py               Realtime Trains API access (token + one query function)
    train_timetable.py   today's train timetable, once a day
    trains.py            live train board merged onto the timetable
    buses.py             bus departures, from the bustimes.org timetable pages
    views/
      page.tpl           page layout, includes one template per panel
      weather.tpl  tides.tpl  waves_past.tpl  waves_forecast.tpl  webcam.tpl
      trains_to.tpl  trains.tpl  train_row.tpl  buses.tpl  credits.tpl  status.tpl
    tests/
      test_<service>.py  one per service, parses a saved file from fixtures/
      fixtures/          one saved raw response per service (copied from data/downloaded)

  data/                  written at runtime, not in git
    downloaded/<service>/<yyyymmddhh>.json|.raw
    downloaded/buses|buoy/from_home*   the pages the home machine sent
    downloaded/archive/<yyyy-mm-dd>.zip   yesterday's dumps
    rtt_access_token.json
    cron.log

How the imports work (kept boring on purpose):

  • monitor.py and collect.py run from the root, so Python can already see src/. They do from src import services, common, config.
  • Inside src/, modules import each other the same way, e.g. from src import common, config. One style everywhere, no relative-import puzzles.
  • monitor.py points Bottle at the templates with bottle.TEMPLATE_PATH.insert(0, "src/views").
  • Tests: python -m pytest src/tests from the root.

The two root scripts stay thin. They parse arguments, loop over services.SERVICES, and call into src/. Any real logic belongs in src/.

src/services.py: the one place

from src import buoy, buses, scrape_metoffice, surf, train_timetable, trains

SERVICES = [scrape_metoffice, buoy, surf, train_timetable, trains, buses]

Adding a service means writing its file and adding it to this list. Nothing else.

Every service file has the same shape

"""Wave buoy readings for Dawlish, from Surfline."""
from src import common, config

NAME = "buoy"                      # folder name under data/downloaded/

def fetch():
    """Top level: download and parse. This is what collect.py calls."""
    raw = download()
    return raw, parse(raw)

def download():
    """Get the raw response (text). No parsing here."""
    return common.download(config.BUOY_URL)

def parse(raw):
    """Turn the raw response into plain dicts. No network here, so tests can call it."""
    ...

Splitting download from parse matters. Tests run parse() on saved files from src/tests/fixtures/, so a broken parser can be fixed and re-run against the saved .raw dumps without hitting the network.

common.py: reused by everything

  • download(url, headers=None): one requests call with a browser User-Agent, a timeout and raise_for_status(). Every service uses it.
  • save_dump(name, raw, data): writes data/downloaded/<name>/<yyyymmddhh>.json and .raw. Writes a temp file and renames it, so readers never see half a file.
  • load_latest(name): newest .json for a service, or None.
  • load_recent(name, hours): all dumps from the last N hours (used for tide history).
  • utc_now(), to_local(iso_string), minutes_until(iso_string).
  • line_chart_svg(points, ...): one SVG line-chart function, used by both the tide curve and the buoy plot.

collect.py

python collect.py                  # every service
python collect.py trains buses     # just these

For each service it calls fetch() inside try/except and saves the result. On failure it appends the error to data/downloaded/<service>/errors.log (a failure must never overwrite a good dump from the same hour), then carries on with the next service. The panel greys out because its newest dump gets old.

Dump envelope: {"service", "fetched_at", "data"}.

  • File name yyyymmddhh is UTC (so the autumn clock change can't produce two files with the same name). A second run within the same hour overwrites that hour's file. So trains/buses keep the latest snapshot per hour, which is fine.
  • Retention: delete .raw files older than 30 days. Keep the JSON (small).

Cron: see cron.txt (ready to paste into crontab -e). It has one line per refresh rate:

What When
collect.py scrape_metoffice surf every hour, at HH:00
ingest.py (buses and buoy sent from home) every minute
collect.py trains every 10 min, 06:00-23:50 (RTT free-tier limits)
collect.py train_timetable 03:30 daily
cleanup.py raw / cleanup.py archive HH:15 / 00:01
monitor.py, plus collect.py scrape_metoffice surf trains at boot

All times are Europe/London (CRON_TZ; the container uses TZ), and output goes to data/cron.log.

The home machine (cron_home.txt) runs src/fetch.sh buses every 30 min (HH:00, HH:30) and src/fetch.sh buoy every 30 min at HH:05 and HH:35.

The timetable at boot. The boot job does not name train_timetable. trains.fetch() checks whether the latest train_timetable dump is from today, and only if it isn't does it call train_timetable.fetch() first (17 RTT calls, 7 s apart). So a restart with today's timetable saved costs nothing, a machine that was off at 03:30 fetches it on its next start, and to refetch on purpose you delete data/downloaded/train_timetable/ and restart the container (or run python collect.py train_timetable). A timetable with a failed part (for example one destination that hit a 429) is kept until then, since it is from today.

monitor.py

  • GET /: for each panel, load_latest(...), pass it to its template. If the newest file is too old (over 2h for hourly services, over 10 min for trains/buses) or ok is false, the panel greys out and shows "last updated hh:mm".
  • GET /api/<service>: returns the latest dump as JSON, handy for debugging and later for the e-paper.
  • The page refreshes itself every 60 s with a few lines of JavaScript in page.tpl: it fetches the page again and swaps every section except the webcam, so the video isn't restarted. Charts are inline SVG.
  • The last line of the page is the build number and time (monitor.build_label()).
  • Filtering out departed trains/buses happens at render time, so a dump from 90 s ago still shows correctly.

Data sources

1 and 2a. scrape_metoffice.py: weather and tides

  • URL: https://weather.metoffice.gov.uk/forecast/gbvx9nfmf ("Dawlish - Coryton Cove (Beach)"). We use the web page, not DataHub, which is unreliable.
  • Checked 2026-10-27: server-rendered HTML (about 1.2 MB), returns 200 with a browser User-Agent. It contains:
    • Hourly forecast tables: tr.step-time (times), weather symbol row, tr.weather-temperature-row, feels-like, tr.precipitation-chance-row, tr.wind-row (wind/gust), UV. Values in data-value / data-unit.
    • Tide times: .tide-times-card / .tide-event blocks with time, high/low and .tide-event-height. Source: "Teignmouth (Approaches) tidal station, 1.9 miles away", for about 10 days.
    • Beach rows (beach-wave, beach-wind), a possible hourly wave forecast.

Designed to be easy to fix when the Met Office changes their HTML:

  1. All selectors in one dict at the top of the file. When the page changes, this is usually the only thing to edit:
    SELECTORS = {
        "day_table":    "table.forecast-table",   # one per day (placeholder names until we write the parser)
        "time_row":     "tr.step-time",
        "symbol_row":   "tr.weather-symbol-row",
        "temp_row":     "tr.weather-temperature-row",
        "rain_row":     "tr.precipitation-chance-row",
        "wind_row":     "tr.wind-row",
        "tide_card":    ".tide-times-card",
        "tide_event":   ".tide-event",
        "tide_height":  ".tide-event-height",
    }
    
  2. Small single-purpose functions, each testable on its own:
    fetch()                        top level: download, parse
    download()                     common.download(URL)
    parse(html)                    soup = BeautifulSoup(html); return {"weather": parse_weather(soup), "tides": parse_tides(soup)}
    parse_weather(soup)            loops over day tables, joins the rows below into hourly dicts
      read_times(table)            -> ["2026-10-27T14:00Z", ...]
      read_row_values(table, key)  -> one list per row (generic, reused for temp, rain, wind...)
      read_symbols(table)          -> weather codes
    parse_tides(soup)              -> [{"time", "type": "high"|"low", "height_m"}]
      read_tide_event(element)     -> one dict
    find(soup_or_tag, key)         the ONLY place selectors are used; raises
                                   ScrapeError("metoffice: 'temp_row' matched nothing, page layout changed?")
    
  3. Loud, specific failures. find() raises an error naming the selector that found nothing. Sanity checks (e.g. "row lengths match the number of hours", "tide heights between -1 and 7 m") raise with a clear message too. collect.py saves that message in the dump, so the page says what broke.
  4. Tests on saved pages: src/tests/test_scrape_metoffice.py parses src/tests/fixtures/metoffice.html and checks the counts and first values. When the site changes: save the new page as a fixture, run the test, fix the selector, done.

Weather panel: next 6 hours: time, symbol (one dict mapping Met Office code to emoji), temperature, feels like, rain %, wind + gust + direction.

Tide panel:

  • The page starts at today, so tides earlier than midnight are missing in the early morning. Fix: common.load_recent("metoffice", 24), merge their tide lists, and remove duplicates by time. No separate history file needed.
  • Curve: cosine between consecutive high/low points h = (h1+h2)/2 + (h1-h2)/2 * cos(pi * (t-t1)/(t2-t1)), sampled every 10 min from now-12h to now+24h. Drawn with common.line_chart_svg. Each high/low is labelled with local time and height, plus a "now" line.
  • Credit line: "Tides: Teignmouth (Approaches), via Met Office".

2. Webcam: Sea Breeze Cam

What is built: src/views/webcam.tpl embeds the YouTube live stream (config.WEBCAM_EMBED_URL, made from config.WEBCAM_URL). It shows a "Show the webcam" button, and only a click creates the iframe, so nothing is loaded from YouTube until then. YouTube wants the embedding site's origin, which the script adds. Nothing is collected by cron.

Not built, an idea for stills (e-paper later): a webcam.py service. Based on the existing grab_frames_dawlish.sh, which does it in two steps:

  1. yt-dlp -g -f "best[height<=1080]" https://www.youtube.com/watch?v=dODxHaxdT0w gets a fresh direct stream URL (they expire after a few hours, so get a new one every time).
  2. ffmpeg -loglevel error -y -i <stream> -frames:v 1 -q:v 2 out.jpg grabs one frame.

As a service it has the same shape as the others:

  • download() runs those two commands with subprocess.run(..., check=True, timeout=60) and returns the JPEG bytes.
  • parse(raw) returns {"image": "<yyyymmddhh>.jpg", "size_bytes": n}. Sanity check: if the file is tiny, raise an error (the stream may be offline, or ffmpeg grabbed a black frame).
  • save_dump stores the image as data/downloaded/webcam/<yyyymmddhh>.jpg. common.save_dump takes an optional file extension for the raw file, the only change needed to support binary data. Cron runs it every 5 min, so each hour's file is overwritten and the page always shows the newest frame. (If you'd like a timelapse history, the webcam could use <yyyymmddhhmm> names instead.)
  • monitor.py serves the image with Bottle's static_file at /webcam/latest.jpg, plus a caption "Sea Breeze Cam, hh:mm".
  • The stream URL goes in config.WEBCAM_URL, since the stream ID changes occasionally.
  • Needs yt-dlp (pip) and ffmpeg (system package). If either is missing or the stream is offline, the panel shows the last good frame with its age.
  • For e-paper later: convert the frame to greyscale and dither it with Pillow.

2b. buoy.py: waves, last 6h

  • Page: https://www.surfline.com/buoy-report/dawlish-103--buoy-103/6e131283-be12-409d-8e2e-d6a2b2bdd0d7
  • We use the JSON behind it (undocumented, checked 2026-10-27): https://services.surfline.com/kbyg/buoys/report/6e131283-be12-409d-8e2e-d6a2b2bdd0d7?days=1
    • data[]: newest first, one reading every 30 min. days=1 gave 22 readings (about 10.5h).
    • Fields used: timestamp (unix UTC), height, period, direction, waterTemperature.
    • Heights are in feet (associated.units.waveHeight == "FT"). Convert to metres, and raise an error if the unit is ever something else.
  • Surfline blocks the server, so the page is downloaded on the home machine (src/fetch.sh buoy, every 30 min at HH:05 and HH:35) and ingest.py parses it (from_home.raw).
  • Panel: common.line_chart_svg of the last 6h, plus latest height, period, direction arrow, water temperature.
  • If Surfline breaks: the buoy is probably the Channel Coastal Observatory Dawlish buoy, so CCO's feed is the backup.

2c. surf.py: waves, next 12h

  • URL: https://www.surf-forecast.com/breaks/Dawlish-Warren/forecasts/latest/six_day
  • Plain-text values in an HTML table. Same pattern as the Met Office scraper: a SELECTORS dict, small read_* functions, a find() that fails loudly, and a fixture test.
  • Rows: rating, wave height (m), direction, period (s), energy, wind, wind state, swells, tides.
  • 3-hourly forecast, so the next 12h is 4 values. Show them as a row of 4 cards: time, height, period, direction arrow, wind, rating. (My quick check earlier only saw AM/PM/Night labels. Confirm the 3-hour columns in the saved fixture when writing the parser.)

3 and 4. Trains: rtt.py, train_timetable.py, trains.py

The old Realtime Trains API closed on 1 October 2026. Its replacement is free for personal, non-commercial use. We have a free account.

Our free account (from the portal):

  • Namespace GB (Network Rail) only, no extra entitlements, 14 days of history.
  • Rate limits: 10/min, 100/hour, 1000/day, 10000/week. This drives the design.
  • Token: a long-life refresh token in ~/.rtt-token.txt (path in config.RTT_TOKEN_FILE, never committed). It is exchanged for a short-life access token.

API basics:

  • Spec: https://realtimetrains.github.io/api-specification (OpenAPI file at .../specification/main.yml). Base URL https://data.rtt.io, header Authorization: Bearer <token>.
  • GET /api/get_access_token (bearer = refresh token) returns {token, validUntil}. Saved to data/rtt_access_token.json and reused until it expires, so it costs about 1 call per expiry, not one per request.
  • GET /gb-nr/location?code=<CRS>&filterTo=<CRS>&filterFrom=<CRS>&timeFrom=..&timeTo=..
    • filterTo=X: only trains that later call at X. filterFrom=X: only trains that earlier called at X.
    • Default window 60 min, max 23h59 (the free token may be capped lower, to be tested).
    • Responses carry X-RateLimit-Remaining-* headers.

Why the naive plan doesn't fit: about 10 calls every 2 min is 300/hour, 3× over the hourly limit. But the timetable barely changes during a day. Only delays and cancellations are live. So we split the work:

Job When Calls What it gets
train_timetable once a day, 03:30 (and at boot only if there is none from today) 17 Today's full timetable: every train from Dawlish to each destination, with departure and arrival times, plus the Exeter St Davids → Exeter Central / Polsloe Bridge connections
trains every 10 min, 06:00-23:50 1 Live Dawlish board (next 60 min): delays, cancellations, platforms. Merged onto today's timetable

Total: about 125 calls/day, 6/hour. That's far inside all limits, with plenty of room for retries and testing. The daily job waits 7 s between calls to stay under 10/min. Departed trains are filtered out when the page renders, so the list stays correct between the 10-minute refreshes.

What the real replies look like (checked 2026-10-27 against saved replies in src/tests/fixtures/rtt_*.json):

  • Whole-day queries work on the free token (101 services at Dawlish). api/info: namespace gb-nr only, 14 days of history, no extra entitlements.
  • Times are London local time with no offset (2026-10-27T13:49:00), so rtt.read_time() converts to UTC.
  • A train has scheduleMetadata.uniqueIdentity (the same in every reply, so we match trains by it), temporalData.departure/arrival with scheduleAdvertised (booked) and realtimeForecast (live; missing for trains more than about an hour away), displayAs (CALL or CANCELLED), and locationMetadata.platform.planned/forecast.
  • A Dawlish query only has Dawlish times. The arrival at Exeter (and so on) comes from asking that station "which trains called at Dawlish first" (filterFrom), then matching by id.
  • The Paignton-Exmouth trains run Dawlish, Exeter St Davids, Exeter Central, Polsloe Bridge (POL; it is not PLB, which RTT answers with 400 Bad Request), Exmouth, so those are direct for Exeter Central and Polsloe Bridge. Everything else changes at Exeter St Davids.
  • Direction: a Dawlish train that goes on to call at Exeter St Davids is "To Exeter", all others "To Teignmouth".
  • The 17 calls are: the board (1), then for each of the 6 destinations "to" and "arrive" (12), then for each of Exeter Central and Polsloe Bridge the change legs (4). The "To Exeter" board takes its arrival time at Exeter St Davids from the Exeter St Davids "arrive" reply, so it costs no extra call. "To Teignmouth" trains have no arrival time (it would need a Teignmouth query).

Journeys with a change (Exeter Central, Polsloe Bridge): for each train that reaches Exeter St Davids and isn't a through train, take the earliest Exmouth-line train leaving at least 5 minutes after it arrives (config.MINIMUM_CHANGE_MINUTES). When several Dawlish trains connect onto the same Exmouth train, only the latest is kept, since catching it gets you there at the same time. Not done yet: if the first train is running late, the change may be missed ("check connection").

rtt.py (shared by both train services, the only code that talks to RTT):

get_access_token()        read cached token, refresh it if expired
get_location(code, filter_to=None, filter_from=None, time_from=None, time_to=None)
                          one API call, returns the parsed reply
read_calls(reply)         the trains in a reply as simple dicts (UTC times)
get(path, token)          every call goes through here (see below)

Rate limits are handled in one place, rtt.get(): it leaves 7 seconds between calls (config.RTT_CALL_PAUSE_SECONDS), and if RTT still answers "429 too many requests" it waits for the Retry-After time (at most 90 s) and tries again, twice, before giving up. (A 429 was seen once when two runs overlapped: separate programs share the one limit, so don't run test_live.sh and run_this.sh at the same time.)

train_timetable.py, fetch() reads top to bottom:

  1. board = get_location("DWL", whole day): all Dawlish departures, both directions.
  2. For each destination in config.TRAIN_DESTINATIONS (EXD, EXT, EXC, POL, TOT, NTA): get_location(dest, filter_from="DWL", whole day): trains that called at Dawlish and then at the destination. This gives the arrival time at the destination. Match to step 1 by service id for the Dawlish departure time. These are the direct trains (including the Paignton to Exmouth through trains for EXC/POL).
  3. For EXC and POL (Exeter to Exmouth line), also the connection legs: get_location("EXD", filter_to=dest) and get_location(dest, filter_from="EXD"), which give departure from St Davids and arrival at the destination.
  4. Build journeys: direct trains, plus for EXC/POL "Dawlish → EXD, change (5 min minimum), → destination". Save as one list per destination.

The free token allows a whole day, so no chunking is needed.

trains.py (live), fetch() reads top to bottom: 0. load_timetable(): today's timetable from the saved dump, fetching it first only if there is none from today.

  1. timetable = common.load_latest("train_timetable")
  2. live = get_location("DWL"): one call, next 60 min.
  3. apply_live(timetable, live): match by service id, then set expected time, platform and cancelled.
  4. Drop departed trains, keep the next 5 per direction and per destination.
  5. Return panel-ready data.

Known limits:

  • Live info only covers the next 60 min from Dawlish. Later trains show timetable times (fine, they're shown as "scheduled").
  • For journeys with a change, the second leg is timetable only. A delay on the first leg can break the connection, so mark it "check connection" when the first leg is late by more than the change time.

Other details:

  • Codes: Dawlish DWL; Exeter St Davids EXD, Exeter St Thomas EXT, Exeter Central EXC, Polsloe Bridge POL, Totnes TOT, Newton Abbot NTA.
  • Directions on the Dawlish board: "To Exeter" (north-east) and "To Teignmouth" (west: Newton Abbot / Paignton / Plymouth).
  • Output per train: departure (booked/expected), destination, platform, status (on time / late / cancelled), arrival at the target station, direct or change.

Catchable trains (highlight): from the house it takes about 20 min to get to Dawlish station. So:

  • config.MINUTES_TO_STATION = 20, the one number to change.
  • A train is catchable if it leaves Dawlish 20 or more minutes from now, using the expected time when live data has one (a late train can become catchable again), otherwise the booked time.
  • Catchable trains are highlighted (bold, coloured background). Trains leaving in under 20 min are still listed but dimmed. Cancelled trains are never highlighted.
  • Applies to both train panels. For "trains to X" journeys with a change, it uses the departure from Dawlish.
  • Worked out at render time in panels.show_train(), not in collect.py. The data is up to 10 min old, but the page reloads every 60 s, so the highlight stays correct to the minute. common.minutes_until() does the sums, and buses can reuse it later with their own walking time.
  • "xx minutes away" is shown on every train row ("35 minutes away", "1 minute away", "leaving now", and "2 h 15 min away" from 100 minutes up). It uses the same live-or-booked time as the highlight.
  • Row layout: time, destination, minutes away, and a small line underneath with status (on time / 5 min late / cancelled), platform, and arrival ("arrives 12:55"; on the "To Exeter" board "arrives Exeter St Davids 12:55", since the train's destination may be further on). Cancelled trains are struck through.

The train shape the trains service must save (times are UTC ISO strings; panels.py documents the same thing next to the code that reads it):

{"departure": booked time leaving Dawlish, "expected_departure": live time or None,
 "destination": "Paignton", "platform": "2" or None, "cancelled": False,
 "arrival": time at the station asked about, or None,
 "change": None, or "Exeter St Davids" when the journey needs a change there}

data = {"board": {"To Exeter": [train, ...], "To Teignmouth": [train, ...]},
        "to_EXD": [train, ...], "to_EXT": [...], "to_EXC": [...],
        "to_POL": [...], "to_TOT": [...], "to_NTA": [...], "errors": {...}}

Each destination is its own part (see "When something fails"), so one destination failing doesn't stop the other five.

  • The line runs along the Dawlish sea wall and closes in storms, so make cancellations and replacement buses obvious.
  • Free backup if RTT's free tier is unsuitable: National Rail Live Departure Boards (Darwin) via the Rail Data Marketplace (raildata.org.uk), free with registration.

5. buses.py: Coronation Avenue

  • Warning: the bus timetables are badly messed up and need a human brain to look at them before anyone trusts the bus panel or changes this code. The routes are odd (the 186 is a loop, the 11 and 2 run in several tables and directions, and the times and destinations don't always match what you'd expect). Open the three pages and read them first:
  • Routes: 2, 11 and 186 (all three are shown, both directions).
  • Stops and timetable pages (checked 2026-10-28, in src/config.py):
    BUS_STOPS = {
        "To Exeter":     "1100DEC11098",   # Dawlish Coronation Avenue (NE-bound)
        "To Teignmouth": "1100DEA57298",   # Dawlish Coronation Avenue (W-bound)
    }
    BUS_ROUTES = ["2", "11", "186"]
    BUS_SERVICES = {"2": "2-exeter-newton-abbot-2", "11": "11-dawlish-warren-teignmouth-torbay-cary-parade",
                    "186": "186-dawlish-dawlish-sainsburys"}   # https://bustimes.org/services/<slug>
    
  • Source: bustimes.org, free, no key, unofficial. It blocks the server (403), so the pages are downloaded on the home machine (src/fetch.sh buses, every 30 min) and sent over; ingest.py parses them. buses.fetch() can still download them directly (used by collect.py buses if the block lifts).
  • We read the timetable pages, not the stop pages. The stop page (/stops/<code>/departures) has live times, but its table has only 3 columns when no bus is tracked, which broke the parser (the Teignmouth stop showed "failed." for that reason). The service page has a table per direction of travel, a row per stop and a column per trip, and a blank cell where a trip doesn't call. buses.parse_page() takes the rows for our two stop codes. Times after midnight look like 00:10⁺¹.
  • The date is chosen with ?date=YYYY-MM-DD. We fetch today's and tomorrow's page of each route (from_home_<route>.html and from_home_<route>_next.html) so there are buses late in the evening.
  • Scheduled times only: there is no live "on time / 2 min early" on the bus panel any more. expected_departure is kept in the data (always None) so the panel code is unchanged.
  • The destination is the end of the table's heading, so route 11 reads "Dawlish Warren Beach Road" and route 2 "Exeter Bus Station". At the west-bound stop only the 186 runs, as the stop page also showed.
  • Same scraper pattern as the Met Office: a SELECTORS dict, small read_* functions, loud failures, and fixture tests (src/tests/fixtures/buses_{2,11,186}.html, the real pages of 2026-10-28).
  • Free official backup: Bus Open Data Service (data.bus-data.dft.gov.uk), free key, but much more work (GTFS timetable parsing).

Setup

No virtualenv. The system python3 (NixOS, Python 3.13) must provide bottle, requests, beautifulsoup4, yt-dlp and pytest (listed in requirements.txt for reference), plus ffmpeg for the webcam. run_this.sh checks for them and says which are missing.

  1. mkdir -p data
  2. RTT refresh token in ~/.rtt-token.txt (done).
  3. Run python3 collect.py once, then copy one .raw per service into src/tests/fixtures/ for the tests.
  4. python3 monitor.py serves http://localhost:8080.
  5. crontab -e and paste the contents of cron.txt. Set PYTHON= in it to the output of which python3.
  6. On a home machine (for buses and the buoy): copy src/fetch.sh and src/fetch.py to ~/, make them executable, and paste cron_home.txt into its crontab. Needs Firefox + geckodriver + selenium, rsync, and an ssh key to the server.

Build and run in Docker

make builds the image and pushes it (make build / make push). The image has the code in /code, cron, and the data folder mounted at /data (docker-compose.yml). docker-entrypoint.sh installs cron.txt as the crontab (without the monitor.py line, and with paths and the RTT token adapted for the container), starts cron, then runs monitor.py as the main process.

Which build is running: each make build adds 1 to src/counter.txt and writes the date and time to src/built.txt; the page shows build 12, 2026-10-28 08:15 at the bottom.

Reset the train timetable: delete data/downloaded/train_timetable/ on the data volume and restart the container.

Build order (follows the page, each step works on its own)

  1. src/ skeleton (common.py, config.py, services.py), root collect.py (with one dummy service) and monitor.py with an empty page. All service files below go in src/.
  2. scrape_metoffice.py weather + test, then the weather panel.
  3. Tides parsing, history merge and the tide chart (line_chart_svg).
  4. The Sea section layout and the webcam embed (click to load).
  5. buoy.py + chart (reuses line_chart_svg).
  6. surf.py + cards.
  7. rtt.py (token + get_location). First test what window the free token allows. Then train_timetable.py (direct trains, then the Exeter Central / Polsloe Bridge connections), then trains.py (live merge).
  8. buses.py.
  9. Polish. Then the e-paper script (reads data/downloaded/ and draws with Pillow, so no web app is needed on the Pi).

Nice touches (after it works)

  • "in N min" next to departure times, and colour for delays over 5 min and cancellations.
  • Optional "leave now" marker on the first catchable train (leaving in 20-25 min), so the one to hurry for stands out.
  • A walking-time setting for buses too (reusing is_catchable).
  • A "rough sea" highlight when the buoy height is high near high tide.
  • Large type and dark mode for a wall display.
  • python monitor.py --demo renders from src/tests/fixtures/, for layout work offline.

Decisions made

  • "Next 5 trains to X" = departures from Dawlish, with arrival time at X shown.
  • Trains leaving 20+ min from now (expected time) are highlighted as catchable from the house. Ones leaving sooner are dimmed.
  • Surf forecast is 3-hourly, shown as 4 cards for the next 12h.
  • Live trains refresh every 10 min (06:00-23:50), timetable once a day.
  • Buses: routes 2, 11, 186. "To Exeter" = NE-bound stop, "To Teignmouth" = W-bound stop.
  • Webcam: the Sea Breeze Cam live stream is embedded, loaded on click, below the other panels.
  • Buses and the buoy are fetched on a home machine and sent to the server, because their sites block it.
  • Buses use the timetable pages (scheduled times), not the stop pages (live, but a layout that broke).
  • The train timetable is fetched at 03:30, and at boot only if there is none from today.

Still to check

  • That ~/.rtt-token.txt can be read by the code (it wasn't visible from Claude's sandbox), and what time window the free RTT token allows.
  • That the surf-forecast table really has 3-hour columns (confirm in the fixture).