OpenDataVisualizer/CLAUDE.md
Claudio Schaad bd2981ffb8 Add live weather layer from MeteoSwiss stations (#7)
- New Schaad.OpenData.Weather project: MeteoSwissClient reads the
  10-minute CSV of the five SwissMetNet stations in Thurgau every 10
  minutes (station list once a day) and backfills the last 7 days from
  the yearly file when the cache has less than 6 days
- History kept as JSON per day (60 days); a failing station does not
  stop the others
- API: /api/weather/meta, /stations (current values, 1 h/24 h rain,
  24 h min/max, strongest gust), /stations/{abbr}/history
- Combined map: "Wetter (live)" layer with station badges (temperature,
  24 h rain or wind), wind arrows, rain marker, station panel with
  hourly 7-day chart, overview and municipality context entries
- Docs: docs/datasets/wetter.md, overview in docs/datasets.md,
  CLAUDE.md; Docker and appsettings wiring

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
2026-11-19 05:04:46 +00:00

17 KiB
Raw Blame History

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Commands

# Build the client and start the server in one go (PowerShell; -SkipClient, -Install)
.
un.ps1

# Backend (ASP.NET Core 10) — API + static client at http://localhost:5080
dotnet build
dotnet run --project Schaad.OpenData.Server --launch-profile http

# Tests (xUnit + NSubstitute + Shouldly)
dotnet test
dotnet test --filter "FullyQualifiedName~RoadPathBuilderTestShould"

# Client (Vite + React + TypeScript), run from client/
npm install
npm run dev          # http://localhost:5173, proxies /api to :5080
npm run build        # tsc + vite build into Schaad.OpenData.Server/wwwroot
npm run typecheck
npm run format       # prettier

# Docker
docker compose up --build   # http://localhost:8080, data in volume opendatavisualizer-data

There is no lint step besides tsc (strict, no unused locals/parameters). dotnet build with the server running fails on locked DLLs; build or test only Schaad.OpenData.Tests in that case. The server serves the client from Schaad.OpenData.Server/wwwroot (gitignored), which dotnet run does not rebuild: after client changes run npm run build or run.ps1.

Architecture

Visualizes open data from opendata.swiss. Three datasets from the canton of Thurgau on data.tg.ch plus live water and weather data from the federal government:

  • hourly traffic counts by vehicle class (dbu-tba-1, CC0): 64 counting stations, each with exactly two directions, 10 vehicle classes (SWISS10)
  • registered watercraft (one dataset per year, djs-kpo-5/8/7/9/10 for 2021–2025, CC BY 4.0): ~7000 boats, one row per boat with location (harbour village or ohne festen Standort), type, propulsion, fuel, emission group, length and power
  • road vehicle stock (djs-stv-17, CC BY 4.0, yearly from 2023): count per municipality (BFS number), vehicle group, vehicle type and brand at 31.12.; brands with fewer than 5 vehicles per municipality and type are folded into Andere. Population per municipality comes from sk-stat-56
  • current water level, discharge, water temperature and flood danger level of BAFU stations on rivers and lakes (LINDAS foen/hydro, opendata.swiss BY), every 10 minutes; LINDAS only has the latest value, so the server collects the history itself
  • 10-minute values of the five SwissMetNet weather stations in Thurgau (MeteoSwiss, STAC collection ch.meteoschweiz.ogd-smn on data.geo.admin.ch, CC BY 4.0): temperature, humidity, precipitation, sunshine, wind, gusts, pressure
Project Role
Schaad.OpenData.Traffic Fetching, JSON cache, road geometry, analysis — everything except HTTP hosting
Schaad.OpenData.Watercraft Watercraft: catalog lookup, JSON cache, aggregation per location
Schaad.OpenData.Vehicles Vehicle stock: dataset fetch, municipality boundaries, JSON cache, aggregation per municipality
Schaad.OpenData.Hydrology Water stations: LINDAS SPARQL fetch, collected history as JSON per day, current view and history per station
Schaad.OpenData.Weather Weather stations: MeteoSwiss CSV fetch, history as JSON per day, current values with 1 h/24 h sums and history per station
Schaad.OpenData.Server Minimal API (/api/traffic/* in Traffic/TrafficEndpoints.cs, /api/watercraft/* in Watercraft/WatercraftEndpoints.cs, /api/vehicles/* in Vehicles/VehicleEndpoints.cs, /api/hydrology/* in Hydrology/HydrologyEndpoints.cs, /api/weather/* in Weather/WeatherEndpoints.cs), serves the built client from wwwroot with SPA fallback
Schaad.OpenData.Tests Tests for the Traffic, Watercraft, Vehicles, Hydrology and Weather libraries
client/ React SPA: Leaflet map with animated traffic, Chart.js station charts

Data flow

TrafficRefreshService (BackgroundService, checks every 15 min)
  → TrafficRefresher
      → ThurgauTrafficClient   data.tg.ch JSON export (only the last ~14 days are available there)
      → TrafficSnapshot.Merge  imported days replace cached days, older days are kept
      → TrafficCacheStorage    {DataPath}/traffic/thurgau/{stations.json, meta.json, counts/yyyy-MM-dd.json, geometry-vN.json}
      → StationGeometryService road path per station direction (once per station)
  → TrafficDataStore          immutable TrafficSnapshot swapped atomically, read by the endpoints
  → TrafficAnalysis           shapes the snapshot for the API (DayView for the map, StationSummary for charts)

The cache accumulates history beyond the source's two-week window; refreshes only fetch from the last cached day minus one (where=datum >= …). RefreshInterval and DataPath are configured under Traffic, Watercraft, Vehicles, Hydrology and Weather in appsettings.json (the …__DataPath variables are /app/data in Docker). Yearly archives back to 2011 exist as https://ogdtg.ch/verkehrsdaten/fahrzeugklassen/{year}_fzkl_data.csv.gz but are not imported yet.

Road geometry (for the direction animation)

The source has one point per station and directions as text (nach X, von X, or just X). StationGeometryService turns that into a road polyline per direction, oriented in driving direction:

  1. SwisstopoClient.GetRoadSegmentsAsync loads swissTLM3D road segments around the station (api3.geo.admin.ch identify, paged by 200) with their street name. verkehrsbedeutung != 999998 marks main roads; objektart 12–19 are paths and lane markings (15/16 seen in practice), everything else is a road — note that 20 is a regular road type.
  2. RoadPathBuilder.BuildRoadPath snaps to a main road within 60 m (else the nearest drivable road), stitches connected segments (≤ 60° turn, penalty for changing road class) and trims to ±300 m.
  3. Stations named … Kreisel … sit on a roundabout arm. The roundabout centre is the average position of all stations sharing the name part before - (e.g. the four WEINFELDEN Kreisel West stations), and the arm target is a point 3 km outward from that centre through the station (StationGeometryService.OutwardTarget), so no geocoding is needed. BuildArmPath follows every segment within 80 m outward for 600 m, preferring segments named like the station's address (the arm's street), and keeps the arm that gets furthest outward; a ring loops back and is rejected. A roundabout with a single station falls back to the geocoded target.
  4. Otherwise SwisstopoClient.FindPlaceAsync geocodes the target town (SearchServer, municipalities + gazetteer, label must contain the name with ä→ae etc., nearest candidate wins — "Landquart" is also a place in Arbon). Names with / are split, since the SearchServer returns 503 for slashes. Directions can be nach/zur/zum/Richtung X (toward) or von/vom X (from); targets like Umfahrung, Zentrum or street names cannot be geocoded.
  5. RoadPathBuilder.Orient points each direction toward or away from its target; the two directions of a station are always opposite.

When the geometry algorithm changes, bump GeometryFileName in TrafficCacheStorage so all stations are rebuilt.

Watercraft

WatercraftRefreshService (BackgroundService, checks every 30 min, refreshes daily)
  → WatercraftRefresher
      → ThurgauWatercraftClient.FindDatasetsAsync   catalog search, keeps titles "Bestand der bei der Schifffahrtskontrolle … {year}"
      → ThurgauWatercraftClient.FetchAsync          only for years that are new or whose dataset id / modified date changed
      → WatercraftCacheStorage                     {DataPath}/watercraft/thurgau/{meta.json, years/{year}.json}
  → WatercraftDataStore
  → WatercraftAnalysis   categories per dimension (ordered by frequency over all years, so client colors stay stable), per location and canton: counts per category, length/power bins, medians, licence-required count (> 6 kW or > 15 m² sail)

The source has no coordinates. WatercraftLocations maps each location name to a point on the shore (village point from the swisstopo gazetteer snapped to the nearest Bodensee/Untersee shoreline and pushed 150 m into the lake, or onto the Rhine). An unknown name gets no position and is listed beside the map instead of on it. Missing values become categories (Ohne Motor, Keine Angabe, Ohne besondere Verwendung), which the client draws in grey.

Vehicle stock

VehicleRefreshService (BackgroundService, checks every 30 min, refreshes daily)
  → VehicleRefresher
      → ThurgauVehicleClient.GetVersionAsync      catalog `modified` of djs-stv-17 and sk-stat-56; a dataset is only re-exported when it changed
      → ThurgauVehicleClient.FetchStockAsync / FetchPopulationAsync
      → MunicipalityBoundaryClient.FetchAsync     swissBOUNDARIES3D outline per BFS number (api3.geo.admin.ch, WGS84, rounded to 5 decimals), only for municipalities without a cached outline
      → VehicleCacheStorage                       {DataPath}/vehicles/thurgau/{meta.json, stock.json, population.json, outlines-v1.json}
  → VehicleDataStore
  → VehicleAnalysis   groups/types/brands ordered by frequency over all years (count arrays in the API are positional), per municipality and canton: counts per group, type and passenger-car brand plus population; missing population years fall back to the latest earlier year

Brand counts only include the group Personenwagen, with Andere always last. When the outline processing changes, bump OutlinesFileName in VehicleCacheStorage.

Hydrology

HydrologyRefreshService (BackgroundService, checks every minute, refreshes every 10 min)
  → HydrologyRefresher
      → LindasHydroClient.FetchAsync   one SPARQL POST to lindas.admin.ch/query, stations matched by IRI …/foen/hydro/station/{id} (the id is an integer literal)
      → HydrodatenPlotClient           backfill from hydrodaten.admin.ch 7-day plot JSON (undocumented) when a station has < 6 days or a > 45 min gap, max once per hour per station; 10-minute marks only, LINDAS values win
      → HydrologySnapshot.With         readings deduplicated by station and time, older than HistoryDays dropped
      → HydrologyCacheStorage          {DataPath}/hydrology/thurgau/{meta.json, stations.json, days/yyyy-MM-dd.json}, old day files deleted
  → HydrologyDataStore
  → HydrologyAnalysis   latest value per station plus level change and discharge 24 h earlier (reading within ±1 h), history per station

Stations default to HydrologyOptions.DefaultStationIds (Thurgau and the Thur catchment) unless Hydrology:StationIds is set. Lake vs river comes from the observation IRI; the isLiter flag is true everywhere and ignored.

Weather

WeatherRefreshService (BackgroundService, checks every minute, refreshes every 10 min)
  → WeatherRefresher
      → MeteoSwissClient.FetchStationsAsync   ogd-smn_meta_stations.csv (Latin-1), once a day or when a configured station is missing
      → MeteoSwissClient.FetchHistoryAsync    {abbr}/ogd-smn_{abbr}_t_recent.csv (since 1 Jan, ~6 MB), only last 7 days kept; when a station has < 6 days or a > 20 h gap, max once per hour
      → MeteoSwissClient.FetchRecentAsync     {abbr}/ogd-smn_{abbr}_t_now.csv (yesterday 00:00 until now); a failing station does not stop the others
      → WeatherCacheStorage                   {DataPath}/weather/thurgau/{meta.json, stations.json, days/yyyy-MM-dd.json}
  → WeatherDataStore
  → WeatherAnalysis   newest non-empty value per field within 30 min, precipitation/sunshine sums over 1 h and 24 h, 24 h min/max, history per station

Timestamps (dd.MM.yyyy HH:mm) are UTC. Stations default to WeatherOptions.DefaultStations (GUT, STK, BIZ, TAE, HAI) unless Weather:Stations is set; Steckborn only measures wind.

Client

  • Routing with react-router-dom: / is the start page (pages/HomePage.tsx) with one large tile per entry in src/maps.ts. Only the combined map has a tile; the single maps are reached through the "Einzelkarte" links in its layer cards. Each map has its own page (/verkehr/thurgau → pages/TrafficThurgauPage.tsx, /schifffahrt/thurgau?jahr=2023 → pages/WatercraftThurgauPage.tsx, /fahrzeuge/thurgau?jahr=2025 → pages/VehiclesThurgauPage.tsx, /karte/thurgau?ebenen=fahrzeuge,boote,verkehr&jahr=2025 → pages/ThurgauCombinedPage.tsx). A new map needs a route in App.tsx and a layer card on the combined page; only a new standalone map needs an entry in src/maps.ts (with a preview image in public/previews/). Deep links work because the server falls back to index.html.
  • map/MapHost.tsx owns the single Leaflet map (base layers, resize, the odv-areas pane at z-index 350 below the default overlay pane) and provides it via map/mapContext.ts (useMap, useMapAttribution). Each dataset is a layer component that renders null and attaches to that map: components/TrafficLayer.tsx, components/watercraft/WatercraftLayer.tsx, components/vehicles/VehicleLayer.tsx. Layers add their data credit to the attribution control themselves and remove everything they added on unmount, so several can share one map. Data loading and per-dataset UI state live in hooks (traffic/useTrafficData.ts, watercraft/useWatercraftData.ts, vehicles/useVehicleData.ts, plus map/useYearPlayback.ts for the jahr param and year playback), used by both the single pages and the combined page.
  • Combined page: one MapHost with the layers toggled from components/combined/LayerPanel.tsx / LayerCard.tsx; the year list is the union of the active yearly layers. The side panel shows the selected municipality, location or station, otherwise OverviewPanel. The municipality panel adds MunicipalityContext (stations and harbours assigned with map/geometry.ts assignToOutlines).
  • traffic/flowAnimator.ts owns the animation clock (time of day in hours, play/pause, speed) and draws on a canvas above Leaflet's overlay pane. Dots spawn per direction at a rate proportional to the interpolated hourly count, colored and sized by vehicle group, offset to the right of the driving direction. It reports the time to React at ~10 Hz via onTick; React components only get the integer hour, so markers and charts don't re-render every frame.
  • The vehicle class order in traffic/vehicleClasses.ts must match the VehicleClass enum / VehicleCounts.ToArray() order; count arrays in the API are positional.
  • Watercraft page: components/watercraft/WatercraftLayer.tsx draws one SVG donut per location (area ∝ boats, segments by the selected dimension); markers are created once and resized in place, so year changes animate via CSS. watercraft/categories.ts folds categories into at most six coloured groups plus grey Übrige and grey "absent" groups; legend chips hide groups, which shrinks the donuts. The panel shows the canton or the selected location for the selected year plus a stacked trend over all years.
  • Vehicle page: components/vehicles/VehicleLayer.tsx draws a choropleth of the municipality outlines (polygons created once, restyled in place). vehicles/metrics.ts defines the metric (vehicles per 1000 inhabitants for all or one group, or a brand's share of passenger cars) and a 7-class quantile scale computed over all years, so colours stay comparable while playing through the years. YearControls is shared with the watercraft page.
  • UI language is German (de-CH). Base maps (shared in map/baseLayers.ts) are swisstopo WMTS layers (grey pixelkarte-grau as default, colour pixelkarte-farbe, aerial swissimage), switchable via Leaflet's layer control; the choice is stored in localStorage (odv.baseMap).

Conventions

  • Keep the dataset docs up to date (mandatory): every change that adds a dataset or map, or changes where data comes from, how it is fetched, how often it is refreshed or where it is cached, must update the docs in the same change. Each dataset has its own file in docs/datasets/ (source, publisher, licence, fetch, refresh, cache, code, Mermaid flowchart, notes); a new dataset gets a new file with the same structure. docs/datasets.md is the overview: update its overview diagram and add or change the dataset's table row, linked to its file. Write in German, like the existing pages, and check the Mermaid syntax renders (quote labels containing {}, () or /).
  • C#: var, primary constructors, file-scoped namespaces, one type per file, no comments, DateOnly for dates, central package versions in Directory.Packages.props, shared settings in Directory.Build.props.
  • Classes that tests need to mock (SwisstopoClient, StationGeometryService, ThurgauTrafficClient, TrafficCacheStorage, ThurgauWatercraftClient, WatercraftCacheStorage, ThurgauVehicleClient, MunicipalityBoundaryClient, VehicleCacheStorage, LindasHydroClient, HydrodatenPlotClient, HydrologyCacheStorage, MeteoSwissClient, WeatherCacheStorage) use virtual methods instead of single-implementation interfaces.
  • Tests: one <Subject>TestShould class per subject, method names DoThisWhenThat, Shouldly assertions (no Assert.*). HTTP clients are tested with a stub HttpMessageHandler, storage with a temp directory cleaned up in Dispose.
  • TypeScript: Prettier config in client/.prettierrc.json (single quotes, width 100).