From 05f4fa78f675294435bd28bfd08131a0c1412d5c Mon Sep 17 00:00:00 2001 From: Claudio Schaad Date: Thu, 19 Nov 2026 06:04:15 +0100 Subject: [PATCH] Add live weather layer from MeteoSwiss stations - 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 --- CLAUDE.md | 27 ++- Dockerfile | 5 +- OpenDataVisualizer.sln | 14 ++ Schaad.OpenData.Server/Program.cs | 4 + .../Schaad.OpenData.Server.csproj | 1 + .../Weather/WeatherEndpoints.cs | 47 ++++ .../Weather/WeatherMetaResponse.cs | 9 + Schaad.OpenData.Server/appsettings.json | 5 + .../MeteoSwissClientTestShould.cs | 91 ++++++++ .../Schaad.OpenData.Tests.csproj | 1 + .../WeatherAnalysisTestShould.cs | 55 +++++ .../WeatherCacheStorageTestShould.cs | 51 +++++ .../WeatherRefresherTestShould.cs | 105 +++++++++ Schaad.OpenData.Tests/WeatherTestData.cs | 20 ++ .../Analysis/WeatherAnalysis.cs | 62 ++++++ .../Analysis/WeatherHistoryPoint.cs | 8 + .../Analysis/WeatherStationView.cs | 23 ++ .../Models/WeatherReading.cs | 13 ++ .../Models/WeatherStation.cs | 3 + .../Schaad.OpenData.Weather.csproj | 15 ++ Schaad.OpenData.Weather/Source/CsvLine.cs | 41 ++++ .../Source/MeteoSwissClient.cs | 123 +++++++++++ .../Storage/WeatherCacheMeta.cs | 3 + .../Storage/WeatherCacheStorage.cs | 88 ++++++++ .../Storage/WeatherDataStore.cs | 10 + .../Storage/WeatherSnapshot.cs | 55 +++++ Schaad.OpenData.Weather/WeatherOptions.cs | 21 ++ .../WeatherRefreshService.cs | 42 ++++ Schaad.OpenData.Weather/WeatherRefresher.cs | 102 +++++++++ .../WeatherServiceCollectionExtensions.cs | 30 +++ client/src/api/weather.ts | 56 +++++ .../combined/MunicipalityContext.tsx | 28 ++- .../src/components/combined/OverviewPanel.tsx | 50 ++++- .../src/components/weather/WeatherLayer.tsx | 134 +++++++++++ .../src/components/weather/WeatherLegend.tsx | 38 ++++ .../weather/WeatherStationPanel.tsx | 208 ++++++++++++++++++ client/src/pages/ThurgauCombinedPage.tsx | 88 +++++++- client/src/styles.css | 58 +++++ client/src/weather/format.ts | 150 +++++++++++++ client/src/weather/useWeatherData.ts | 41 ++++ docs/datasets.md | 17 +- docs/datasets/wetter.md | 39 ++++ 42 files changed, 1960 insertions(+), 21 deletions(-) create mode 100644 Schaad.OpenData.Server/Weather/WeatherEndpoints.cs create mode 100644 Schaad.OpenData.Server/Weather/WeatherMetaResponse.cs create mode 100644 Schaad.OpenData.Tests/MeteoSwissClientTestShould.cs create mode 100644 Schaad.OpenData.Tests/WeatherAnalysisTestShould.cs create mode 100644 Schaad.OpenData.Tests/WeatherCacheStorageTestShould.cs create mode 100644 Schaad.OpenData.Tests/WeatherRefresherTestShould.cs create mode 100644 Schaad.OpenData.Tests/WeatherTestData.cs create mode 100644 Schaad.OpenData.Weather/Analysis/WeatherAnalysis.cs create mode 100644 Schaad.OpenData.Weather/Analysis/WeatherHistoryPoint.cs create mode 100644 Schaad.OpenData.Weather/Analysis/WeatherStationView.cs create mode 100644 Schaad.OpenData.Weather/Models/WeatherReading.cs create mode 100644 Schaad.OpenData.Weather/Models/WeatherStation.cs create mode 100644 Schaad.OpenData.Weather/Schaad.OpenData.Weather.csproj create mode 100644 Schaad.OpenData.Weather/Source/CsvLine.cs create mode 100644 Schaad.OpenData.Weather/Source/MeteoSwissClient.cs create mode 100644 Schaad.OpenData.Weather/Storage/WeatherCacheMeta.cs create mode 100644 Schaad.OpenData.Weather/Storage/WeatherCacheStorage.cs create mode 100644 Schaad.OpenData.Weather/Storage/WeatherDataStore.cs create mode 100644 Schaad.OpenData.Weather/Storage/WeatherSnapshot.cs create mode 100644 Schaad.OpenData.Weather/WeatherOptions.cs create mode 100644 Schaad.OpenData.Weather/WeatherRefreshService.cs create mode 100644 Schaad.OpenData.Weather/WeatherRefresher.cs create mode 100644 Schaad.OpenData.Weather/WeatherServiceCollectionExtensions.cs create mode 100644 client/src/api/weather.ts create mode 100644 client/src/components/weather/WeatherLayer.tsx create mode 100644 client/src/components/weather/WeatherLegend.tsx create mode 100644 client/src/components/weather/WeatherStationPanel.tsx create mode 100644 client/src/weather/format.ts create mode 100644 client/src/weather/useWeatherData.ts create mode 100644 docs/datasets/wetter.md diff --git a/CLAUDE.md b/CLAUDE.md index 7a4b1d3..41f62fc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,12 +32,13 @@ There is no lint step besides `tsc` (strict, no unused locals/parameters). `dotn ## Architecture -Visualizes open data from opendata.swiss. Three datasets from the canton of Thurgau on data.tg.ch plus live water data from the federal government: +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 | |---|---| @@ -45,8 +46,9 @@ Visualizes open data from opendata.swiss. Three datasets from the canton of Thur | `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.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`), serves the built client from `wwwroot` with SPA fallback | -| `Schaad.OpenData.Tests` | Tests for the Traffic, Watercraft, Vehicles and Hydrology libraries | +| `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 @@ -62,7 +64,7 @@ TrafficRefreshService (BackgroundService, checks every 15 min) → 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` and `Hydrology` 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. +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) @@ -120,6 +122,21 @@ HydrologyRefreshService (BackgroundService, checks every minute, refreshes every 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`. @@ -135,6 +152,6 @@ Stations default to `HydrologyOptions.DefaultStationIds` (Thurgau and the Thur c - **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`) use `virtual` methods instead of single-implementation interfaces. +- 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 `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). diff --git a/Dockerfile b/Dockerfile index 0f9c563..f85deb0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,12 +15,14 @@ COPY Schaad.OpenData.Traffic/Schaad.OpenData.Traffic.csproj Schaad.OpenData.Traf COPY Schaad.OpenData.Watercraft/Schaad.OpenData.Watercraft.csproj Schaad.OpenData.Watercraft/ COPY Schaad.OpenData.Vehicles/Schaad.OpenData.Vehicles.csproj Schaad.OpenData.Vehicles/ COPY Schaad.OpenData.Hydrology/Schaad.OpenData.Hydrology.csproj Schaad.OpenData.Hydrology/ +COPY Schaad.OpenData.Weather/Schaad.OpenData.Weather.csproj Schaad.OpenData.Weather/ RUN dotnet restore Schaad.OpenData.Server/Schaad.OpenData.Server.csproj COPY Schaad.OpenData.Server/ Schaad.OpenData.Server/ COPY Schaad.OpenData.Traffic/ Schaad.OpenData.Traffic/ COPY Schaad.OpenData.Watercraft/ Schaad.OpenData.Watercraft/ COPY Schaad.OpenData.Vehicles/ Schaad.OpenData.Vehicles/ COPY Schaad.OpenData.Hydrology/ Schaad.OpenData.Hydrology/ +COPY Schaad.OpenData.Weather/ Schaad.OpenData.Weather/ COPY --from=build-client /src/Schaad.OpenData.Server/wwwroot Schaad.OpenData.Server/wwwroot RUN dotnet publish Schaad.OpenData.Server/Schaad.OpenData.Server.csproj -c Release -o /app --no-restore @@ -34,7 +36,8 @@ ENV ASPNETCORE_HTTP_PORTS=8080 \ Traffic__DataPath=/app/data \ Watercraft__DataPath=/app/data \ Vehicles__DataPath=/app/data \ - Hydrology__DataPath=/app/data + Hydrology__DataPath=/app/data \ + Weather__DataPath=/app/data VOLUME /app/data EXPOSE 8080 ENTRYPOINT ["dotnet", "Schaad.OpenData.Server.dll"] diff --git a/OpenDataVisualizer.sln b/OpenDataVisualizer.sln index 37af000..a5bb7d4 100644 --- a/OpenDataVisualizer.sln +++ b/OpenDataVisualizer.sln @@ -15,6 +15,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Schaad.OpenData.Vehicles", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Schaad.OpenData.Hydrology", "Schaad.OpenData.Hydrology\Schaad.OpenData.Hydrology.csproj", "{165B08D9-D777-4D3D-8341-093A30F60B63}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Schaad.OpenData.Weather", "Schaad.OpenData.Weather\Schaad.OpenData.Weather.csproj", "{D4CEFB51-F8D6-487C-AC05-C12E2AF14723}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -97,6 +99,18 @@ Global {165B08D9-D777-4D3D-8341-093A30F60B63}.Release|x64.Build.0 = Release|Any CPU {165B08D9-D777-4D3D-8341-093A30F60B63}.Release|x86.ActiveCfg = Release|Any CPU {165B08D9-D777-4D3D-8341-093A30F60B63}.Release|x86.Build.0 = Release|Any CPU + {D4CEFB51-F8D6-487C-AC05-C12E2AF14723}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D4CEFB51-F8D6-487C-AC05-C12E2AF14723}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D4CEFB51-F8D6-487C-AC05-C12E2AF14723}.Debug|x64.ActiveCfg = Debug|Any CPU + {D4CEFB51-F8D6-487C-AC05-C12E2AF14723}.Debug|x64.Build.0 = Debug|Any CPU + {D4CEFB51-F8D6-487C-AC05-C12E2AF14723}.Debug|x86.ActiveCfg = Debug|Any CPU + {D4CEFB51-F8D6-487C-AC05-C12E2AF14723}.Debug|x86.Build.0 = Debug|Any CPU + {D4CEFB51-F8D6-487C-AC05-C12E2AF14723}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D4CEFB51-F8D6-487C-AC05-C12E2AF14723}.Release|Any CPU.Build.0 = Release|Any CPU + {D4CEFB51-F8D6-487C-AC05-C12E2AF14723}.Release|x64.ActiveCfg = Release|Any CPU + {D4CEFB51-F8D6-487C-AC05-C12E2AF14723}.Release|x64.Build.0 = Release|Any CPU + {D4CEFB51-F8D6-487C-AC05-C12E2AF14723}.Release|x86.ActiveCfg = Release|Any CPU + {D4CEFB51-F8D6-487C-AC05-C12E2AF14723}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Schaad.OpenData.Server/Program.cs b/Schaad.OpenData.Server/Program.cs index 68fc827..7700aa8 100644 --- a/Schaad.OpenData.Server/Program.cs +++ b/Schaad.OpenData.Server/Program.cs @@ -3,9 +3,11 @@ using Schaad.OpenData.Server.Hydrology; using Schaad.OpenData.Server.Traffic; using Schaad.OpenData.Server.Vehicles; using Schaad.OpenData.Server.Watercraft; +using Schaad.OpenData.Server.Weather; using Schaad.OpenData.Traffic; using Schaad.OpenData.Vehicles; using Schaad.OpenData.Watercraft; +using Schaad.OpenData.Weather; var builder = WebApplication.CreateBuilder(args); @@ -13,6 +15,7 @@ builder.Services.AddTraffic(builder.Configuration); builder.Services.AddWatercraft(builder.Configuration); builder.Services.AddVehicles(builder.Configuration); builder.Services.AddHydrology(builder.Configuration); +builder.Services.AddWeather(builder.Configuration); builder.Services.AddResponseCompression(options => options.EnableForHttps = true); var app = builder.Build(); @@ -24,6 +27,7 @@ app.MapTrafficEndpoints(); app.MapWatercraftEndpoints(); app.MapVehicleEndpoints(); app.MapHydrologyEndpoints(); +app.MapWeatherEndpoints(); app.MapFallbackToFile("index.html"); app.Run(); diff --git a/Schaad.OpenData.Server/Schaad.OpenData.Server.csproj b/Schaad.OpenData.Server/Schaad.OpenData.Server.csproj index 6296be9..b4c54f7 100644 --- a/Schaad.OpenData.Server/Schaad.OpenData.Server.csproj +++ b/Schaad.OpenData.Server/Schaad.OpenData.Server.csproj @@ -5,6 +5,7 @@ + diff --git a/Schaad.OpenData.Server/Weather/WeatherEndpoints.cs b/Schaad.OpenData.Server/Weather/WeatherEndpoints.cs new file mode 100644 index 0000000..97c2e8e --- /dev/null +++ b/Schaad.OpenData.Server/Weather/WeatherEndpoints.cs @@ -0,0 +1,47 @@ +using Microsoft.Extensions.Options; +using Schaad.OpenData.Weather; +using Schaad.OpenData.Weather.Analysis; +using Schaad.OpenData.Weather.Storage; + +namespace Schaad.OpenData.Server.Weather; + +public static class WeatherEndpoints +{ + private const int DefaultHistoryDays = 7; + + public static IEndpointRouteBuilder MapWeatherEndpoints(this IEndpointRouteBuilder endpoints) + { + var group = endpoints.MapGroup("/api/weather"); + + group.MapGet("/meta", (WeatherDataStore store, IOptions options) => + new WeatherMetaResponse( + "Automatische Wetterstationen – Messwerte (SwissMetNet)", + "MeteoSchweiz", + "https://opendata.swiss/de/dataset/automatische-wetterstationen-messwerte", + "CC BY 4.0", + options.Value.HistoryDays, + store.Current.LastRefresh)); + + group.MapGet("/stations", (WeatherDataStore store) => WeatherAnalysis.BuildStations(store.Current)); + + group.MapGet("/stations/{abbr}/history", ( + string abbr, + int? tage, + WeatherDataStore store, + IOptions options, + TimeProvider timeProvider) => + { + var snapshot = store.Current; + var key = abbr.ToUpperInvariant(); + if (snapshot.Stations.All(s => s.Abbr != key)) + { + return Results.NotFound(); + } + + var days = Math.Clamp(tage ?? DefaultHistoryDays, 1, options.Value.HistoryDays); + return Results.Ok(WeatherAnalysis.BuildHistory(snapshot, key, timeProvider.GetUtcNow().AddDays(-days))); + }); + + return endpoints; + } +} diff --git a/Schaad.OpenData.Server/Weather/WeatherMetaResponse.cs b/Schaad.OpenData.Server/Weather/WeatherMetaResponse.cs new file mode 100644 index 0000000..bd97019 --- /dev/null +++ b/Schaad.OpenData.Server/Weather/WeatherMetaResponse.cs @@ -0,0 +1,9 @@ +namespace Schaad.OpenData.Server.Weather; + +public sealed record WeatherMetaResponse( + string Title, + string Publisher, + string SourceUrl, + string License, + int HistoryDays, + DateTimeOffset? LastRefresh); diff --git a/Schaad.OpenData.Server/appsettings.json b/Schaad.OpenData.Server/appsettings.json index 7341043..98340f6 100644 --- a/Schaad.OpenData.Server/appsettings.json +++ b/Schaad.OpenData.Server/appsettings.json @@ -23,5 +23,10 @@ "DataPath": "../data", "RefreshInterval": "00:10:00", "HistoryDays": 60 + }, + "Weather": { + "DataPath": "../data", + "RefreshInterval": "00:10:00", + "HistoryDays": 60 } } diff --git a/Schaad.OpenData.Tests/MeteoSwissClientTestShould.cs b/Schaad.OpenData.Tests/MeteoSwissClientTestShould.cs new file mode 100644 index 0000000..9a6c43a --- /dev/null +++ b/Schaad.OpenData.Tests/MeteoSwissClientTestShould.cs @@ -0,0 +1,91 @@ +using System.Net; +using System.Text; +using Microsoft.Extensions.Options; +using Schaad.OpenData.Weather; +using Schaad.OpenData.Weather.Models; +using Schaad.OpenData.Weather.Source; + +namespace Schaad.OpenData.Tests; + +public class MeteoSwissClientTestShould +{ + private sealed class StubHandler(Dictionary bodies) : HttpMessageHandler + { + public List Requests { get; } = []; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var url = request.RequestUri!.AbsoluteUri; + Requests.Add(url); + return Task.FromResult(bodies.TryGetValue(url, out var body) + ? new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(body) } + : new HttpResponseMessage(HttpStatusCode.NotFound)); + } + } + + private const string BaseUrl = "https://data.example/ogd-smn"; + + private const string DataHeader = + "station_abbr;reference_timestamp;tre200s0;ure200s0;rre150z0;sre000z0;fu3010z0;fu3010z1;dkl010z0;pp0qffs0"; + + private static MeteoSwissClient Client(StubHandler handler) => + new(new HttpClient(handler), Options.Create(new WeatherOptions { BaseUrl = BaseUrl + "/" })); + + [Fact] + public async Task ReadWantedStationsFromLatin1MetadataWhenFetchingStations() + { + var csv = + "station_abbr;station_name;station_canton;station_height_masl;station_coordinates_wgs84_lat;station_coordinates_wgs84_lon;station_exposition_de\n" + + "GUT;Güttingen;TG;440;47.601733;9.279428;\"Ebene; See\"\n" + + "TAE;Aadorf / Tänikon;TG;539;47.479;8.905;Ebene\n" + + "KLO;Zürich / Kloten;ZH;426;47.48;8.536;Ebene\n"; + var handler = new StubHandler(new() { [$"{BaseUrl}/ogd-smn_meta_stations.csv"] = Encoding.Latin1.GetBytes(csv) }); + + var stations = await Client(handler).FetchStationsAsync(["gut", "TAE"], CancellationToken.None); + + stations.ShouldBe([ + new WeatherStation("GUT", "Güttingen", "TG", 440, 47.601733, 9.279428), + new WeatherStation("TAE", "Aadorf / Tänikon", "TG", 539, 47.479, 8.905), + ]); + } + + [Fact] + public async Task ParseTenMinuteValuesAsUtcWhenFetchingRecentData() + { + var csv = DataHeader + "\n" + + "GUT;18.11.2026 18:50;8.6;89.2;0.1;0;12.7;50.8;243;1001.4\n" + + "GUT;18.11.2026 19:00;8.4;87.7;0;;11.8;;237;1001.4\n"; + var handler = new StubHandler(new() { [$"{BaseUrl}/gut/ogd-smn_gut_t_now.csv"] = Encoding.UTF8.GetBytes(csv) }); + + var readings = await Client(handler).FetchRecentAsync("GUT", CancellationToken.None); + + readings.ShouldBe([ + new WeatherReading("GUT", new DateTimeOffset(2026, 11, 18, 18, 50, 0, TimeSpan.Zero), 8.6, 89.2, 0.1, 0, 12.7, 50.8, 243, 1001.4), + new WeatherReading("GUT", new DateTimeOffset(2026, 11, 18, 19, 0, 0, TimeSpan.Zero), 8.4, 87.7, 0, null, 11.8, null, 237, 1001.4), + ]); + } + + [Fact] + public async Task KeepOnlyValuesSinceStartWhenFetchingHistory() + { + var csv = DataHeader + "\n" + + "GUT;01.01.2026 00:00;-4.9;94.3;0;0;3.8;14;220;1023.9\n" + + "GUT;12.11.2026 00:00;10.2;70;0;0;5;9;200;1010\n"; + var handler = new StubHandler(new() { [$"{BaseUrl}/gut/ogd-smn_gut_t_recent.csv"] = Encoding.UTF8.GetBytes(csv) }); + + var readings = await Client(handler).FetchHistoryAsync("GUT", new DateTimeOffset(2026, 11, 11, 0, 0, 0, TimeSpan.Zero), CancellationToken.None); + + readings.ShouldHaveSingleItem().Temperature.ShouldBe(10.2); + } + + [Fact] + public async Task SkipRequestWhenAbbreviationIsInvalid() + { + var handler = new StubHandler([]); + + var readings = await Client(handler).FetchRecentAsync("../x", CancellationToken.None); + + readings.ShouldBeEmpty(); + handler.Requests.ShouldBeEmpty(); + } +} diff --git a/Schaad.OpenData.Tests/Schaad.OpenData.Tests.csproj b/Schaad.OpenData.Tests/Schaad.OpenData.Tests.csproj index e8ae5ee..20c0a11 100644 --- a/Schaad.OpenData.Tests/Schaad.OpenData.Tests.csproj +++ b/Schaad.OpenData.Tests/Schaad.OpenData.Tests.csproj @@ -23,6 +23,7 @@ + diff --git a/Schaad.OpenData.Tests/WeatherAnalysisTestShould.cs b/Schaad.OpenData.Tests/WeatherAnalysisTestShould.cs new file mode 100644 index 0000000..d059ecb --- /dev/null +++ b/Schaad.OpenData.Tests/WeatherAnalysisTestShould.cs @@ -0,0 +1,55 @@ +using Schaad.OpenData.Weather.Analysis; +using Schaad.OpenData.Weather.Storage; +using static Schaad.OpenData.Tests.WeatherTestData; + +namespace Schaad.OpenData.Tests; + +public class WeatherAnalysisTestShould +{ + [Fact] + public void SummarizeLastHourAndDayWhenBuildingStations() + { + var snapshot = new WeatherSnapshot( + [Station(), Station("STK", "Steckborn")], + [ + Reading("GUT", Now.AddDays(-2), temperature: -5, precipitation: 9), + Reading("GUT", Now.AddHours(-20), temperature: 3, precipitation: 1.2, windGust: 61), + Reading("GUT", Now.AddMinutes(-50), temperature: 7, precipitation: 0.3), + Reading("GUT", Now.AddMinutes(-10), temperature: 8.6, precipitation: 0.1, windGust: 50.8), + Reading("GUT", Now, temperature: 8.4, precipitation: 0, windGust: null), + ], + Now, + Now); + + var stations = WeatherAnalysis.BuildStations(snapshot); + + stations.Select(s => s.Abbr).ShouldBe(["GUT", "STK"]); + var gut = stations[0]; + gut.Time.ShouldBe(Now); + gut.Temperature.ShouldBe(8.4); + gut.WindGust.ShouldBe(50.8); + gut.Precipitation1h.ShouldBe(0.4); + gut.Precipitation24h.ShouldBe(1.6); + gut.TemperatureMin24h.ShouldBe(3); + gut.TemperatureMax24h.ShouldBe(8.6); + gut.WindGustMax24h.ShouldBe(61); + gut.HistoryFrom.ShouldBe(Now.AddDays(-2)); + var stk = stations[1]; + stk.Time.ShouldBeNull(); + stk.Precipitation24h.ShouldBeNull(); + } + + [Fact] + public void ReturnReadingsOfStationSinceStartWhenBuildingHistory() + { + var snapshot = new WeatherSnapshot( + [Station()], + [Reading("GUT", Now.AddDays(-8)), Reading("GUT", Now.AddDays(-1), temperature: 5), Reading("STK", Now)], + Now, + Now); + + var history = WeatherAnalysis.BuildHistory(snapshot, "GUT", Now.AddDays(-7)); + + history.ShouldBe([new WeatherHistoryPoint(Now.AddDays(-1), 5, 0, 10, 20)]); + } +} diff --git a/Schaad.OpenData.Tests/WeatherCacheStorageTestShould.cs b/Schaad.OpenData.Tests/WeatherCacheStorageTestShould.cs new file mode 100644 index 0000000..6d75b36 --- /dev/null +++ b/Schaad.OpenData.Tests/WeatherCacheStorageTestShould.cs @@ -0,0 +1,51 @@ +using Microsoft.Extensions.Options; +using Schaad.OpenData.Weather; +using Schaad.OpenData.Weather.Storage; +using static Schaad.OpenData.Tests.WeatherTestData; + +namespace Schaad.OpenData.Tests; + +public sealed class WeatherCacheStorageTestShould : IDisposable +{ + private readonly string dataPath = Path.Combine(Path.GetTempPath(), "odv-tests-" + Guid.NewGuid().ToString("N")); + private readonly WeatherCacheStorage storage; + + public WeatherCacheStorageTestShould() + { + storage = new WeatherCacheStorage(Options.Create(new WeatherOptions { DataPath = dataPath })); + } + + public void Dispose() + { + if (Directory.Exists(dataPath)) + { + Directory.Delete(dataPath, true); + } + } + + [Fact] + public async Task ReturnEmptySnapshotWhenCacheDoesNotExist() + { + var snapshot = await storage.LoadAsync(CancellationToken.None); + + snapshot.Stations.ShouldBeEmpty(); + snapshot.Readings.ShouldBeEmpty(); + snapshot.StationsFetched.ShouldBeNull(); + } + + [Fact] + public async Task RestoreStationsReadingsAndTimesWhenLoading() + { + var readings = new[] { Reading("GUT", Now.AddDays(-1)), Reading("STK", Now, temperature: null) }; + var snapshot = new WeatherSnapshot([Station(), Station("STK", "Steckborn")], readings, Now, Now.AddHours(-3)); + + await storage.SaveAsync(snapshot, [new DateOnly(2026, 11, 17), new DateOnly(2026, 11, 18)], CancellationToken.None); + var loaded = await storage.LoadAsync(CancellationToken.None); + + loaded.Stations.ShouldBe([Station(), Station("STK", "Steckborn")]); + loaded.Readings.ShouldBe(readings); + loaded.LastRefresh.ShouldBe(Now); + loaded.StationsFetched.ShouldBe(Now.AddHours(-3)); + Directory.GetFiles(Path.Combine(dataPath, "weather", "thurgau", "days")).Length.ShouldBe(2); + } +} diff --git a/Schaad.OpenData.Tests/WeatherRefresherTestShould.cs b/Schaad.OpenData.Tests/WeatherRefresherTestShould.cs new file mode 100644 index 0000000..1acb367 --- /dev/null +++ b/Schaad.OpenData.Tests/WeatherRefresherTestShould.cs @@ -0,0 +1,105 @@ +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using Schaad.OpenData.Weather; +using Schaad.OpenData.Weather.Models; +using Schaad.OpenData.Weather.Source; +using Schaad.OpenData.Weather.Storage; +using static Schaad.OpenData.Tests.WeatherTestData; + +namespace Schaad.OpenData.Tests; + +public class WeatherRefresherTestShould +{ + private readonly WeatherOptions settings = new() { Stations = ["GUT", "STK"] }; + private readonly MeteoSwissClient client; + private readonly WeatherCacheStorage storage; + private readonly WeatherDataStore store = new(); + private readonly TimeProvider timeProvider = Substitute.For(); + private readonly WeatherRefresher refresher; + + public WeatherRefresherTestShould() + { + var options = Options.Create(settings); + client = Substitute.For(new HttpClient(), options); + client.FetchStationsAsync(Arg.Any>(), Arg.Any()) + .Returns([Station(), Station("STK", "Steckborn")]); + client.FetchRecentAsync(Arg.Any(), Arg.Any()) + .Returns(call => [Reading(call.Arg(), Now)]); + client.FetchHistoryAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(call => [Reading(call.Arg(), Now.AddDays(-7))]); + storage = Substitute.For(options); + timeProvider.GetUtcNow().Returns(Now); + refresher = new WeatherRefresher(client, storage, store, options, timeProvider, NullLogger.Instance); + } + + private static WeatherSnapshot Covered(DateTimeOffset? stationsFetched) => + new( + [Station(), Station("STK", "Steckborn")], + [Reading("GUT", Now.AddDays(-7)), Reading("GUT", Now.AddMinutes(-10)), Reading("STK", Now.AddDays(-7)), Reading("STK", Now.AddMinutes(-10))], + Now.AddMinutes(-10), + stationsFetched); + + [Fact] + public async Task FetchStationsAndBackfillSevenDaysWhenCacheIsEmpty() + { + await refresher.RefreshAsync(CancellationToken.None); + + await client.Received(1).FetchStationsAsync( + Arg.Is>(a => a.SequenceEqual(new[] { "GUT", "STK" })), + Arg.Any()); + await client.Received(1).FetchHistoryAsync("GUT", Now.AddDays(-7), Arg.Any()); + await client.Received(1).FetchHistoryAsync("STK", Now.AddDays(-7), Arg.Any()); + store.Current.Stations.Count.ShouldBe(2); + store.Current.Readings.Count.ShouldBe(4); + store.Current.StationsFetched.ShouldBe(Now); + await storage.Received(1).SaveAsync( + store.Current, + Arg.Is>(days => days.Order().SequenceEqual(new[] { new DateOnly(2026, 11, 11), new DateOnly(2026, 11, 18) })), + Arg.Any()); + } + + [Fact] + public async Task FetchOnlyRecentValuesWhenCacheIsCovered() + { + store.Replace(Covered(Now.AddHours(-1))); + + await refresher.RefreshAsync(CancellationToken.None); + + await client.DidNotReceive().FetchStationsAsync(Arg.Any>(), Arg.Any()); + await client.DidNotReceive().FetchHistoryAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await client.Received(2).FetchRecentAsync(Arg.Any(), Arg.Any()); + store.Current.Readings.Count.ShouldBe(6); + } + + [Fact] + public async Task RefreshStationMetadataOnceADayWhenRefreshing() + { + store.Replace(Covered(Now.AddDays(-1))); + + await refresher.RefreshAsync(CancellationToken.None); + + await client.Received(1).FetchStationsAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task KeepOtherStationsWhenOneStationFails() + { + store.Replace(Covered(Now.AddHours(-1))); + client.FetchRecentAsync("GUT", Arg.Any()).ThrowsAsync(new HttpRequestException("404")); + + await refresher.RefreshAsync(CancellationToken.None); + + store.Current.Readings.Where(r => r.Time == Now).Select(r => r.StationAbbr).ShouldBe(["STK"]); + } + + [Fact] + public void RequireRefreshWhenLastRefreshIsOlderThanInterval() + { + store.Replace(new WeatherSnapshot([], [], Now.AddMinutes(-11), null)); + + refresher.IsRefreshDue(TimeSpan.FromMinutes(10)).ShouldBeTrue(); + refresher.IsRefreshDue(TimeSpan.FromMinutes(15)).ShouldBeFalse(); + } +} diff --git a/Schaad.OpenData.Tests/WeatherTestData.cs b/Schaad.OpenData.Tests/WeatherTestData.cs new file mode 100644 index 0000000..d9e7839 --- /dev/null +++ b/Schaad.OpenData.Tests/WeatherTestData.cs @@ -0,0 +1,20 @@ +using Schaad.OpenData.Weather.Models; + +namespace Schaad.OpenData.Tests; + +internal static class WeatherTestData +{ + public static readonly DateTimeOffset Now = new(2026, 11, 18, 19, 0, 0, TimeSpan.Zero); + + public static WeatherStation Station(string abbr = "GUT", string name = "Güttingen") => + new(abbr, name, "TG", 440, 47.60, 9.28); + + public static WeatherReading Reading( + string abbr, + DateTimeOffset time, + double? temperature = 8.0, + double? precipitation = 0, + double? windGust = 20, + double? windSpeed = 10) => + new(abbr, time, temperature, 80, precipitation, 0, windSpeed, windGust, 240, 1001); +} diff --git a/Schaad.OpenData.Weather/Analysis/WeatherAnalysis.cs b/Schaad.OpenData.Weather/Analysis/WeatherAnalysis.cs new file mode 100644 index 0000000..1999e9a --- /dev/null +++ b/Schaad.OpenData.Weather/Analysis/WeatherAnalysis.cs @@ -0,0 +1,62 @@ +using Schaad.OpenData.Weather.Models; +using Schaad.OpenData.Weather.Storage; + +namespace Schaad.OpenData.Weather.Analysis; + +public static class WeatherAnalysis +{ + private static readonly TimeSpan CurrentTolerance = TimeSpan.FromMinutes(30); + + public static IReadOnlyList BuildStations(WeatherSnapshot snapshot) + { + var byStation = snapshot.Readings.ToLookup(r => r.StationAbbr); + return snapshot.Stations + .Select(station => ToView(station, byStation[station.Abbr].ToList())) + .ToList(); + } + + public static IReadOnlyList BuildHistory(WeatherSnapshot snapshot, string abbr, DateTimeOffset from) => + snapshot.Readings + .Where(r => r.StationAbbr == abbr && r.Time >= from) + .Select(r => new WeatherHistoryPoint(r.Time, r.Temperature, r.Precipitation, r.WindSpeed, r.WindGust)) + .ToList(); + + private static WeatherStationView ToView(WeatherStation station, IReadOnlyList readings) + { + var latest = readings.Count > 0 ? readings[^1] : null; + var recent = latest is null ? [] : readings.Where(r => r.Time > latest.Time - CurrentTolerance).Reverse().ToList(); + var lastHour = latest is null ? [] : readings.Where(r => r.Time > latest.Time.AddHours(-1)).ToList(); + var lastDay = latest is null ? [] : readings.Where(r => r.Time > latest.Time.AddDays(-1)).ToList(); + + return new WeatherStationView( + station.Abbr, + station.Name, + station.Canton, + station.HeightMasl, + station.Lat, + station.Lon, + latest?.Time, + Current(recent, r => r.Temperature), + Current(recent, r => r.Humidity), + Current(recent, r => r.WindSpeed), + Current(recent, r => r.WindGust), + Current(recent, r => r.WindDirection), + Current(recent, r => r.Pressure), + Sum(lastHour, r => r.Precipitation), + Sum(lastDay, r => r.Precipitation), + Sum(lastDay, r => r.Sunshine), + lastDay.Select(r => r.Temperature).Min(), + lastDay.Select(r => r.Temperature).Max(), + lastDay.Select(r => r.WindGust).Max(), + readings.Count > 0 ? readings[0].Time : null); + } + + private static double? Current(IReadOnlyList newestFirst, Func value) => + newestFirst.Select(value).FirstOrDefault(v => v.HasValue); + + private static double? Sum(IReadOnlyList readings, Func value) + { + var values = readings.Select(value).Where(v => v.HasValue).ToList(); + return values.Count == 0 ? null : Math.Round(values.Sum(v => v!.Value), 1); + } +} diff --git a/Schaad.OpenData.Weather/Analysis/WeatherHistoryPoint.cs b/Schaad.OpenData.Weather/Analysis/WeatherHistoryPoint.cs new file mode 100644 index 0000000..ba30c74 --- /dev/null +++ b/Schaad.OpenData.Weather/Analysis/WeatherHistoryPoint.cs @@ -0,0 +1,8 @@ +namespace Schaad.OpenData.Weather.Analysis; + +public sealed record WeatherHistoryPoint( + DateTimeOffset Time, + double? Temperature, + double? Precipitation, + double? WindSpeed, + double? WindGust); diff --git a/Schaad.OpenData.Weather/Analysis/WeatherStationView.cs b/Schaad.OpenData.Weather/Analysis/WeatherStationView.cs new file mode 100644 index 0000000..6b0c8af --- /dev/null +++ b/Schaad.OpenData.Weather/Analysis/WeatherStationView.cs @@ -0,0 +1,23 @@ +namespace Schaad.OpenData.Weather.Analysis; + +public sealed record WeatherStationView( + string Abbr, + string Name, + string Canton, + double? HeightMasl, + double Lat, + double Lon, + DateTimeOffset? Time, + double? Temperature, + double? Humidity, + double? WindSpeed, + double? WindGust, + double? WindDirection, + double? Pressure, + double? Precipitation1h, + double? Precipitation24h, + double? Sunshine24h, + double? TemperatureMin24h, + double? TemperatureMax24h, + double? WindGustMax24h, + DateTimeOffset? HistoryFrom); diff --git a/Schaad.OpenData.Weather/Models/WeatherReading.cs b/Schaad.OpenData.Weather/Models/WeatherReading.cs new file mode 100644 index 0000000..a5ce399 --- /dev/null +++ b/Schaad.OpenData.Weather/Models/WeatherReading.cs @@ -0,0 +1,13 @@ +namespace Schaad.OpenData.Weather.Models; + +public sealed record WeatherReading( + string StationAbbr, + DateTimeOffset Time, + double? Temperature, + double? Humidity, + double? Precipitation, + double? Sunshine, + double? WindSpeed, + double? WindGust, + double? WindDirection, + double? Pressure); diff --git a/Schaad.OpenData.Weather/Models/WeatherStation.cs b/Schaad.OpenData.Weather/Models/WeatherStation.cs new file mode 100644 index 0000000..4b32216 --- /dev/null +++ b/Schaad.OpenData.Weather/Models/WeatherStation.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Weather.Models; + +public sealed record WeatherStation(string Abbr, string Name, string Canton, double? HeightMasl, double Lat, double Lon); diff --git a/Schaad.OpenData.Weather/Schaad.OpenData.Weather.csproj b/Schaad.OpenData.Weather/Schaad.OpenData.Weather.csproj new file mode 100644 index 0000000..66bf7e7 --- /dev/null +++ b/Schaad.OpenData.Weather/Schaad.OpenData.Weather.csproj @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/Schaad.OpenData.Weather/Source/CsvLine.cs b/Schaad.OpenData.Weather/Source/CsvLine.cs new file mode 100644 index 0000000..94de443 --- /dev/null +++ b/Schaad.OpenData.Weather/Source/CsvLine.cs @@ -0,0 +1,41 @@ +using System.Text; + +namespace Schaad.OpenData.Weather.Source; + +internal static class CsvLine +{ + public static IReadOnlyList Split(string line) + { + var fields = new List(); + var field = new StringBuilder(); + var quoted = false; + for (var i = 0; i < line.Length; i++) + { + var c = line[i]; + if (c == '"') + { + if (quoted && i + 1 < line.Length && line[i + 1] == '"') + { + field.Append('"'); + i++; + } + else + { + quoted = !quoted; + } + } + else if (c == ';' && !quoted) + { + fields.Add(field.ToString()); + field.Clear(); + } + else + { + field.Append(c); + } + } + + fields.Add(field.ToString()); + return fields; + } +} diff --git a/Schaad.OpenData.Weather/Source/MeteoSwissClient.cs b/Schaad.OpenData.Weather/Source/MeteoSwissClient.cs new file mode 100644 index 0000000..5383687 --- /dev/null +++ b/Schaad.OpenData.Weather/Source/MeteoSwissClient.cs @@ -0,0 +1,123 @@ +using System.Globalization; +using System.Text; +using Microsoft.Extensions.Options; +using Schaad.OpenData.Weather.Models; + +namespace Schaad.OpenData.Weather.Source; + +public class MeteoSwissClient(HttpClient httpClient, IOptions options) +{ + private const string TimestampFormat = "dd.MM.yyyy HH:mm"; + + private string BaseUrl => options.Value.BaseUrl.TrimEnd('/'); + + public virtual async Task> FetchStationsAsync(IReadOnlyCollection abbreviations, CancellationToken cancellationToken) + { + var wanted = abbreviations.ToHashSet(StringComparer.OrdinalIgnoreCase); + var stations = new List(); + await foreach (var row in ReadRowsAsync($"{BaseUrl}/ogd-smn_meta_stations.csv", Encoding.Latin1, cancellationToken)) + { + var abbr = row.GetValueOrDefault("station_abbr"); + if (abbr is null || !wanted.Contains(abbr) + || Number(row, "station_coordinates_wgs84_lat") is not { } lat + || Number(row, "station_coordinates_wgs84_lon") is not { } lon) + { + continue; + } + + stations.Add(new WeatherStation( + abbr.ToUpperInvariant(), + row.GetValueOrDefault("station_name") ?? abbr, + row.GetValueOrDefault("station_canton") ?? string.Empty, + Number(row, "station_height_masl"), + lat, + lon)); + } + + return stations; + } + + public virtual Task> FetchRecentAsync(string abbr, CancellationToken cancellationToken) => + FetchReadingsAsync(abbr, "t_now", DateTimeOffset.MinValue, cancellationToken); + + public virtual Task> FetchHistoryAsync(string abbr, DateTimeOffset from, CancellationToken cancellationToken) => + FetchReadingsAsync(abbr, "t_recent", from, cancellationToken); + + private async Task> FetchReadingsAsync(string abbr, string kind, DateTimeOffset from, CancellationToken cancellationToken) + { + if (abbr.Length == 0 || !abbr.All(char.IsAsciiLetterOrDigit)) + { + return []; + } + + var lower = abbr.ToLowerInvariant(); + var readings = new List(); + await foreach (var row in ReadRowsAsync($"{BaseUrl}/{lower}/ogd-smn_{lower}_{kind}.csv", Encoding.UTF8, cancellationToken)) + { + if (!DateTime.TryParseExact(row.GetValueOrDefault("reference_timestamp"), TimestampFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var timestamp)) + { + continue; + } + + var time = new DateTimeOffset(DateTime.SpecifyKind(timestamp, DateTimeKind.Utc)); + if (time < from) + { + continue; + } + + readings.Add(new WeatherReading( + abbr.ToUpperInvariant(), + time, + Number(row, "tre200s0"), + Number(row, "ure200s0"), + Number(row, "rre150z0"), + Number(row, "sre000z0"), + Number(row, "fu3010z0"), + Number(row, "fu3010z1"), + Number(row, "dkl010z0"), + Number(row, "pp0qffs0"))); + } + + return readings; + } + + private async IAsyncEnumerable> ReadRowsAsync( + string url, + Encoding encoding, + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken) + { + using var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + response.EnsureSuccessStatusCode(); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + using var reader = new StreamReader(stream, encoding); + + var header = await reader.ReadLineAsync(cancellationToken); + if (header is null) + { + yield break; + } + + var columns = CsvLine.Split(header.TrimStart('\uFEFF')); + while (await reader.ReadLineAsync(cancellationToken) is { } line) + { + if (line.Length == 0) + { + continue; + } + + var values = CsvLine.Split(line); + var row = new Dictionary(StringComparer.Ordinal); + for (var i = 0; i < columns.Count && i < values.Count; i++) + { + row[columns[i]] = values[i]; + } + + yield return row; + } + } + + private static double? Number(Dictionary row, string column) => + row.TryGetValue(column, out var text) && double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) + ? value + : null; +} diff --git a/Schaad.OpenData.Weather/Storage/WeatherCacheMeta.cs b/Schaad.OpenData.Weather/Storage/WeatherCacheMeta.cs new file mode 100644 index 0000000..5e6f49f --- /dev/null +++ b/Schaad.OpenData.Weather/Storage/WeatherCacheMeta.cs @@ -0,0 +1,3 @@ +namespace Schaad.OpenData.Weather.Storage; + +public sealed record WeatherCacheMeta(DateTimeOffset? LastRefresh, DateTimeOffset? StationsFetched); diff --git a/Schaad.OpenData.Weather/Storage/WeatherCacheStorage.cs b/Schaad.OpenData.Weather/Storage/WeatherCacheStorage.cs new file mode 100644 index 0000000..872263b --- /dev/null +++ b/Schaad.OpenData.Weather/Storage/WeatherCacheStorage.cs @@ -0,0 +1,88 @@ +using System.Globalization; +using System.Text.Json; +using Microsoft.Extensions.Options; +using Schaad.OpenData.Weather.Models; + +namespace Schaad.OpenData.Weather.Storage; + +public class WeatherCacheStorage(IOptions options) +{ + private const string DayFormat = "yyyy-MM-dd"; + + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); + + private string RootPath => Path.Combine(Path.GetFullPath(options.Value.DataPath), "weather", "thurgau"); + + private string DaysPath => Path.Combine(RootPath, "days"); + + public virtual async Task LoadAsync(CancellationToken cancellationToken) + { + var meta = await ReadAsync(Path.Combine(RootPath, "meta.json"), cancellationToken); + var stations = await ReadAsync>(Path.Combine(RootPath, "stations.json"), cancellationToken) ?? []; + var readings = new List(); + if (Directory.Exists(DaysPath)) + { + foreach (var file in Directory.EnumerateFiles(DaysPath, "*.json").Order(StringComparer.Ordinal)) + { + readings.AddRange(await ReadAsync>(file, cancellationToken) ?? []); + } + } + + return new WeatherSnapshot(stations, readings, meta?.LastRefresh, meta?.StationsFetched); + } + + public virtual async Task SaveAsync(WeatherSnapshot snapshot, IReadOnlyCollection changedDays, CancellationToken cancellationToken) + { + var byDay = snapshot.Readings.ToLookup(r => DateOnly.FromDateTime(r.Time.UtcDateTime)); + foreach (var day in changedDays) + { + await WriteAsync(DayPath(day), byDay[day].ToList(), cancellationToken); + } + + await WriteAsync(Path.Combine(RootPath, "stations.json"), snapshot.Stations, cancellationToken); + await WriteAsync(Path.Combine(RootPath, "meta.json"), new WeatherCacheMeta(snapshot.LastRefresh, snapshot.StationsFetched), cancellationToken); + } + + public virtual void DeleteDaysBefore(DateOnly firstKeptDay) + { + if (!Directory.Exists(DaysPath)) + { + return; + } + + foreach (var file in Directory.EnumerateFiles(DaysPath, "*.json")) + { + if (DateOnly.TryParseExact(Path.GetFileNameWithoutExtension(file), DayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var day) + && day < firstKeptDay) + { + File.Delete(file); + } + } + } + + private string DayPath(DateOnly day) => + Path.Combine(DaysPath, day.ToString(DayFormat, CultureInfo.InvariantCulture) + ".json"); + + private static async Task ReadAsync(string path, CancellationToken cancellationToken) + { + if (!File.Exists(path)) + { + return default; + } + + await using var stream = File.OpenRead(path); + return await JsonSerializer.DeserializeAsync(stream, JsonOptions, cancellationToken); + } + + private static async Task WriteAsync(string path, T value, CancellationToken cancellationToken) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var tempPath = path + ".tmp"; + await using (var stream = File.Create(tempPath)) + { + await JsonSerializer.SerializeAsync(stream, value, JsonOptions, cancellationToken); + } + + File.Move(tempPath, path, true); + } +} diff --git a/Schaad.OpenData.Weather/Storage/WeatherDataStore.cs b/Schaad.OpenData.Weather/Storage/WeatherDataStore.cs new file mode 100644 index 0000000..f779635 --- /dev/null +++ b/Schaad.OpenData.Weather/Storage/WeatherDataStore.cs @@ -0,0 +1,10 @@ +namespace Schaad.OpenData.Weather.Storage; + +public sealed class WeatherDataStore +{ + private volatile WeatherSnapshot current = WeatherSnapshot.Empty; + + public WeatherSnapshot Current => current; + + public void Replace(WeatherSnapshot snapshot) => current = snapshot; +} diff --git a/Schaad.OpenData.Weather/Storage/WeatherSnapshot.cs b/Schaad.OpenData.Weather/Storage/WeatherSnapshot.cs new file mode 100644 index 0000000..708ae4a --- /dev/null +++ b/Schaad.OpenData.Weather/Storage/WeatherSnapshot.cs @@ -0,0 +1,55 @@ +using Schaad.OpenData.Weather.Models; + +namespace Schaad.OpenData.Weather.Storage; + +public sealed class WeatherSnapshot +{ + public static readonly WeatherSnapshot Empty = new([], [], null, null); + + public WeatherSnapshot( + IEnumerable stations, + IEnumerable readings, + DateTimeOffset? lastRefresh, + DateTimeOffset? stationsFetched) + { + Stations = stations + .GroupBy(s => s.Abbr) + .Select(g => g.Last()) + .OrderBy(s => s.Abbr, StringComparer.Ordinal) + .ToList(); + Readings = readings + .GroupBy(r => (r.StationAbbr, r.Time)) + .Select(g => g.Last()) + .OrderBy(r => r.Time) + .ThenBy(r => r.StationAbbr, StringComparer.Ordinal) + .ToList(); + LastRefresh = lastRefresh; + StationsFetched = stationsFetched; + } + + public IReadOnlyList Stations { get; } + + public IReadOnlyList Readings { get; } + + public DateTimeOffset? LastRefresh { get; } + + public DateTimeOffset? StationsFetched { get; } + + public WeatherSnapshot With( + IReadOnlyList stations, + IEnumerable readings, + DateTimeOffset lastRefresh, + DateTimeOffset? stationsFetched, + DateTimeOffset keepFrom) => + new( + Stations.Concat(stations), + Readings.Concat(readings).Where(r => r.Time >= keepFrom), + lastRefresh, + stationsFetched ?? StationsFetched); + + public IReadOnlyList NewReadings(IEnumerable readings) + { + var known = Readings.Select(r => (r.StationAbbr, r.Time)).ToHashSet(); + return readings.Where(r => !known.Contains((r.StationAbbr, r.Time))).ToList(); + } +} diff --git a/Schaad.OpenData.Weather/WeatherOptions.cs b/Schaad.OpenData.Weather/WeatherOptions.cs new file mode 100644 index 0000000..744d2bd --- /dev/null +++ b/Schaad.OpenData.Weather/WeatherOptions.cs @@ -0,0 +1,21 @@ +namespace Schaad.OpenData.Weather; + +public sealed class WeatherOptions +{ + public const string SectionName = "Weather"; + + public static readonly IReadOnlyList DefaultStations = ["GUT", "STK", "BIZ", "TAE", "HAI"]; + + public string DataPath { get; set; } = "data"; + + public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromMinutes(10); + + public int HistoryDays { get; set; } = 60; + + public string BaseUrl { get; set; } = "https://data.geo.admin.ch/ch.meteoschweiz.ogd-smn"; + + public string[] Stations { get; set; } = []; + + public IReadOnlyList EffectiveStations => + (Stations.Length > 0 ? Stations : DefaultStations).Select(s => s.Trim().ToUpperInvariant()).ToList(); +} diff --git a/Schaad.OpenData.Weather/WeatherRefreshService.cs b/Schaad.OpenData.Weather/WeatherRefreshService.cs new file mode 100644 index 0000000..8de75e2 --- /dev/null +++ b/Schaad.OpenData.Weather/WeatherRefreshService.cs @@ -0,0 +1,42 @@ +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace Schaad.OpenData.Weather; + +public sealed class WeatherRefreshService( + WeatherRefresher refresher, + IOptions options, + ILogger logger) : BackgroundService +{ + private static readonly TimeSpan CheckInterval = TimeSpan.FromMinutes(1); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + try + { + await refresher.LoadCacheAsync(stoppingToken); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + logger.LogError(exception, "Could not load the weather cache"); + } + + while (!stoppingToken.IsCancellationRequested) + { + try + { + if (refresher.IsRefreshDue(options.Value.RefreshInterval)) + { + await refresher.RefreshAsync(stoppingToken); + } + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + logger.LogError(exception, "Weather refresh failed"); + } + + await Task.Delay(CheckInterval, stoppingToken); + } + } +} diff --git a/Schaad.OpenData.Weather/WeatherRefresher.cs b/Schaad.OpenData.Weather/WeatherRefresher.cs new file mode 100644 index 0000000..e39abc0 --- /dev/null +++ b/Schaad.OpenData.Weather/WeatherRefresher.cs @@ -0,0 +1,102 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Schaad.OpenData.Weather.Models; +using Schaad.OpenData.Weather.Source; +using Schaad.OpenData.Weather.Storage; + +namespace Schaad.OpenData.Weather; + +public class WeatherRefresher( + MeteoSwissClient client, + WeatherCacheStorage storage, + WeatherDataStore store, + IOptions options, + TimeProvider timeProvider, + ILogger logger) +{ + private static readonly TimeSpan StationsInterval = TimeSpan.FromDays(1); + private static readonly TimeSpan BackfillWindow = TimeSpan.FromDays(7); + private static readonly TimeSpan RequiredCoverage = TimeSpan.FromDays(6); + private static readonly TimeSpan MaxGap = TimeSpan.FromHours(20); + private static readonly TimeSpan BackfillRetry = TimeSpan.FromHours(1); + + private readonly Dictionary lastBackfill = []; + + public async Task LoadCacheAsync(CancellationToken cancellationToken) + { + var snapshot = await storage.LoadAsync(cancellationToken); + store.Replace(snapshot); + logger.LogInformation( + "Loaded weather cache with {Stations} stations and {Readings} readings", + snapshot.Stations.Count, + snapshot.Readings.Count); + } + + public bool IsRefreshDue(TimeSpan interval) => + store.Current.LastRefresh is not { } lastRefresh || timeProvider.GetUtcNow() - lastRefresh >= interval; + + public async Task RefreshAsync(CancellationToken cancellationToken) + { + var now = timeProvider.GetUtcNow(); + var current = store.Current; + var abbreviations = options.Value.EffectiveStations; + + IReadOnlyList stations = []; + DateTimeOffset? stationsFetched = null; + if (current.StationsFetched is not { } fetched || now - fetched >= StationsInterval + || abbreviations.Any(a => current.Stations.All(s => s.Abbr != a))) + { + stations = await client.FetchStationsAsync(abbreviations, cancellationToken); + stationsFetched = now; + } + + var byStation = current.Readings.ToLookup(r => r.StationAbbr); + var fetchedReadings = new List(); + var backfilled = 0; + foreach (var abbr in abbreviations) + { + try + { + if (NeedsBackfill(byStation[abbr].ToList(), now) + && (!lastBackfill.TryGetValue(abbr, out var last) || now - last >= BackfillRetry)) + { + lastBackfill[abbr] = now; + var history = await client.FetchHistoryAsync(abbr, now - BackfillWindow, cancellationToken); + backfilled += history.Count; + fetchedReadings.AddRange(history); + } + + fetchedReadings.AddRange(await client.FetchRecentAsync(abbr, cancellationToken)); + } + catch (Exception exception) when (exception is HttpRequestException or IOException or TaskCanceledException + && !cancellationToken.IsCancellationRequested) + { + logger.LogWarning(exception, "Could not fetch weather station {Station}", abbr); + } + } + + var added = current.NewReadings(fetchedReadings); + var firstKeptDay = DateOnly.FromDateTime(now.UtcDateTime).AddDays(-options.Value.HistoryDays); + var keepFrom = new DateTimeOffset(firstKeptDay.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + + var updated = current.With(stations, fetchedReadings, now, stationsFetched, keepFrom); + var changedDays = added + .Select(r => DateOnly.FromDateTime(r.Time.UtcDateTime)) + .Where(day => day >= firstKeptDay) + .Distinct() + .ToList(); + await storage.SaveAsync(updated, changedDays, cancellationToken); + storage.DeleteDaysBefore(firstKeptDay); + store.Replace(updated); + logger.LogInformation( + "Fetched weather for {Stations} stations, {Added} new readings ({Backfilled} from the recent files)", + abbreviations.Count, + added.Count, + backfilled); + } + + private static bool NeedsBackfill(IReadOnlyList readings, DateTimeOffset now) => + readings.Count == 0 + || readings[0].Time > now - RequiredCoverage + || readings[^1].Time < now - MaxGap; +} diff --git a/Schaad.OpenData.Weather/WeatherServiceCollectionExtensions.cs b/Schaad.OpenData.Weather/WeatherServiceCollectionExtensions.cs new file mode 100644 index 0000000..6e9483a --- /dev/null +++ b/Schaad.OpenData.Weather/WeatherServiceCollectionExtensions.cs @@ -0,0 +1,30 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Schaad.OpenData.Weather.Source; +using Schaad.OpenData.Weather.Storage; + +namespace Schaad.OpenData.Weather; + +public static class WeatherServiceCollectionExtensions +{ + private const string UserAgent = "OpenDataVisualizer/1.0"; + + public static IServiceCollection AddWeather(this IServiceCollection services, IConfiguration configuration) + { + services.Configure(configuration.GetSection(WeatherOptions.SectionName)); + services.TryAddSingleton(TimeProvider.System); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddHostedService(); + + services.AddHttpClient(client => + { + client.Timeout = TimeSpan.FromMinutes(2); + client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent); + }); + + return services; + } +} diff --git a/client/src/api/weather.ts b/client/src/api/weather.ts new file mode 100644 index 0000000..d9362c9 --- /dev/null +++ b/client/src/api/weather.ts @@ -0,0 +1,56 @@ +export interface WeatherMeta { + title: string; + publisher: string; + sourceUrl: string; + license: string; + historyDays: number; + lastRefresh: string | null; +} + +export interface WeatherStation { + abbr: string; + name: string; + canton: string; + heightMasl: number | null; + lat: number; + lon: number; + time: string | null; + temperature: number | null; + humidity: number | null; + windSpeed: number | null; + windGust: number | null; + windDirection: number | null; + pressure: number | null; + precipitation1h: number | null; + precipitation24h: number | null; + sunshine24h: number | null; + temperatureMin24h: number | null; + temperatureMax24h: number | null; + windGustMax24h: number | null; + historyFrom: string | null; +} + +export interface WeatherHistoryPoint { + time: string; + temperature: number | null; + precipitation: number | null; + windSpeed: number | null; + windGust: number | null; +} + +async function getJson(url: string): Promise { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`${response.status} ${response.statusText}`); + } + return (await response.json()) as T; +} + +export const fetchWeatherMeta = () => getJson('/api/weather/meta'); + +export const fetchWeatherStations = () => getJson('/api/weather/stations'); + +export const fetchWeatherHistory = (abbr: string, days: number) => + getJson( + `/api/weather/stations/${encodeURIComponent(abbr)}/history?tage=${days}`, + ); diff --git a/client/src/components/combined/MunicipalityContext.tsx b/client/src/components/combined/MunicipalityContext.tsx index 1afe92f..4d0f2c7 100644 --- a/client/src/components/combined/MunicipalityContext.tsx +++ b/client/src/components/combined/MunicipalityContext.tsx @@ -1,6 +1,7 @@ import type { HydroStation } from '../../api/hydrology'; import type { DayView, Station } from '../../api/traffic'; import type { LocationSummary } from '../../api/watercraft'; +import type { WeatherStation } from '../../api/weather'; import { dischargeTrend, formatDecimal, formatDischarge } from '../../hydrology/format'; import { formatNumber } from '../../traffic/format'; import { sumCounts } from '../../traffic/vehicleClasses'; @@ -9,26 +10,30 @@ interface MunicipalityContextProps { stations: Station[] | null; locations: LocationSummary[] | null; hydroStations: HydroStation[] | null; + weatherStations: WeatherStation[] | null; day: DayView | null; hour: number; year: number; onSelectStation: (code: number) => void; onSelectLocation: (name: string) => void; onSelectHydroStation: (id: string) => void; + onSelectWeatherStation: (abbr: string) => void; } export function MunicipalityContext({ stations, locations, hydroStations, + weatherStations, day, hour, year, onSelectStation, onSelectLocation, onSelectHydroStation, + onSelectWeatherStation, }: MunicipalityContextProps) { - if (!stations && !locations && !hydroStations) { + if (!stations && !locations && !hydroStations && !weatherStations) { return null; } @@ -102,6 +107,27 @@ export function MunicipalityContext({ ))} )} + + {weatherStations && weatherStations.length > 0 && ( +
    + {weatherStations.map((station) => ( +
  • + +
  • + ))} +
+ )} ); } diff --git a/client/src/components/combined/OverviewPanel.tsx b/client/src/components/combined/OverviewPanel.tsx index cd1a753..67e9181 100644 --- a/client/src/components/combined/OverviewPanel.tsx +++ b/client/src/components/combined/OverviewPanel.tsx @@ -1,5 +1,6 @@ import type { HydroStation } from '../../api/hydrology'; import type { VehicleMeta, VehicleYearView } from '../../api/vehicles'; +import type { WeatherStation } from '../../api/weather'; import type { YearView } from '../../api/watercraft'; import { dangerColor, @@ -23,6 +24,7 @@ interface OverviewPanelProps { firstDate: string | null; } | null; hydrology: { stations: HydroStation[] } | null; + weather: { stations: WeatherStation[] } | null; } export function OverviewPanel({ @@ -31,6 +33,7 @@ export function OverviewPanel({ watercraft, traffic, hydrology, + weather, }: OverviewPanelProps) { const carIndex = vehicles?.meta.groups.indexOf('Personenwagen') ?? -1; const carDensity = @@ -47,7 +50,7 @@ export function OverviewPanel({ - {!vehicles && !watercraft && !traffic && !hydrology && ( + {!vehicles && !watercraft && !traffic && !hydrology && !weather && (

Schalte links mindestens eine Ebene ein.

)} @@ -128,6 +131,8 @@ export function OverviewPanel({ {hydrology && } + {weather && } +

Klicke auf eine Gemeinde, einen Bootsstandort oder eine Zählstelle, um Details zu sehen.

@@ -174,3 +179,46 @@ function HydrologyOverview({ stations }: { stations: HydroStation[] }) { ); } + +function WeatherOverview({ stations }: { stations: WeatherStation[] }) { + const temperatures = stations.flatMap((s) => (s.temperature === null ? [] : [s.temperature])); + const wettest = stations + .filter((s) => s.precipitation24h !== null) + .sort((a, b) => (b.precipitation24h ?? 0) - (a.precipitation24h ?? 0))[0]; + const windiest = stations + .filter((s) => s.windGustMax24h !== null) + .sort((a, b) => (b.windGustMax24h ?? 0) - (a.windGustMax24h ?? 0))[0]; + const latest = stations.reduce( + (value, s) => (s.time && (!value || s.time > value) ? s.time : value), + null, + ); + const format = (value: number) => value.toLocaleString('de-CH', { maximumFractionDigits: 1 }); + + return ( +
+

Wetter, Stand {formatTime(latest)}

+
+
+ + {temperatures.length > 0 + ? `${format(Math.min(...temperatures))} bis ${format(Math.max(...temperatures))} °C` + : '–'} + + Lufttemperatur an {stations.length} Stationen +
+ {wettest && ( +
+ {format(wettest.precipitation24h ?? 0)} mm + meister Regen in 24 h ({wettest.name}) +
+ )} + {windiest && ( +
+ {Math.round(windiest.windGustMax24h ?? 0)} km/h + stärkste Böe in 24 h ({windiest.name}) +
+ )} +
+
+ ); +} diff --git a/client/src/components/weather/WeatherLayer.tsx b/client/src/components/weather/WeatherLayer.tsx new file mode 100644 index 0000000..5296d9f --- /dev/null +++ b/client/src/components/weather/WeatherLayer.tsx @@ -0,0 +1,134 @@ +import L from 'leaflet'; +import { useEffect, useRef } from 'react'; +import type { WeatherStation } from '../../api/weather'; +import { escapeHtml } from '../../map/baseLayers'; +import { useMap, useMapAttribution } from '../../map/mapContext'; +import { + compassDirection, + formatDecimal, + formatTime, + stationColor, + stationLabel, + type WeatherMetric, +} from '../../weather/format'; + +interface WeatherLayerProps { + stations: WeatherStation[]; + metric: WeatherMetric; + selectedAbbr: string | null; + onSelect: (abbr: string) => void; +} + +const DATA_ATTRIBUTION = 'Wetter: MeteoSchweiz'; + +export function WeatherLayer({ stations, metric, selectedAbbr, onSelect }: WeatherLayerProps) { + const map = useMap(); + useMapAttribution(DATA_ATTRIBUTION); + const markersRef = useRef>(new Map()); + const onSelectRef = useRef(onSelect); + onSelectRef.current = onSelect; + + useEffect(() => { + const markers = markersRef.current; + return () => { + markers.forEach((marker) => marker.remove()); + markers.clear(); + }; + }, [map]); + + useEffect(() => { + const abbrs = new Set(stations.map((s) => s.abbr)); + markersRef.current.forEach((marker, abbr) => { + if (!abbrs.has(abbr)) { + marker.remove(); + markersRef.current.delete(abbr); + } + }); + + for (const station of stations) { + let marker = markersRef.current.get(station.abbr); + if (!marker) { + marker = L.marker([station.lat, station.lon], { + icon: L.divIcon({ className: 'weather-marker-anchor', html: '', iconSize: [0, 0] }), + keyboard: true, + title: station.name, + }) + .on('click', () => onSelectRef.current(station.abbr)) + .addTo(map); + markersRef.current.set(station.abbr, marker); + } + + const element = marker.getElement(); + if (element) { + element.innerHTML = markerHtml(station, metric, station.abbr === selectedAbbr); + } + marker.setZIndexOffset(station.abbr === selectedAbbr ? 10_000 : 2_000); + marker.bindTooltip(tooltipHtml(station), { direction: 'top', offset: [0, -20] }); + } + }, [map, stations, metric, selectedAbbr]); + + return null; +} + +function markerHtml(station: WeatherStation, metric: WeatherMetric, selected: boolean): string { + const color = stationColor(station, metric); + const arrow = + station.windDirection !== null && station.windSpeed !== null && station.windSpeed >= 1 + ? arrowHtml( + station.windDirection, + metric === 'wind' ? 8 + Math.min(station.windSpeed, 60) * 0.4 : 8, + ) + : ''; + const rain = + metric !== 'precipitation' && (station.precipitation1h ?? 0) > 0 + ? '💧' + : ''; + const unit = metric === 'precipitation' ? 'mm' : metric === 'wind' ? 'km/h' : ''; + return ( + arrow + + `
` + + `${escapeHtml(stationLabel(station, metric))}${unit ? `${unit}` : ''}
` + + rain + ); +} + +const BADGE_RADIUS = 19; + +function arrowHtml(fromDegrees: number, length: number): string { + const height = 2 * (BADGE_RADIUS + length); + const head = Math.min(7, length); + return ( + `` + + `` + + `` + + `` + ); +} + +function tooltipHtml(station: WeatherStation): string { + const rows = [ + row( + 'Temperatur', + station.temperature === null ? '–' : `${formatDecimal(station.temperature, 1)} °C`, + ), + row( + 'Niederschlag', + `${formatDecimal(station.precipitation1h, 1)} mm/h · ${formatDecimal(station.precipitation24h, 1)} mm/24 h`, + ), + row( + 'Wind', + station.windSpeed === null + ? '–' + : `${Math.round(station.windSpeed)} km/h aus ${compassDirection(station.windDirection)}` + + (station.windGust !== null ? `, Böen ${Math.round(station.windGust)}` : ''), + ), + ]; + return ( + `${escapeHtml(station.name)} · ${station.heightMasl ?? '–'} m
` + + `MeteoSchweiz, Stand ${formatTime(station.time)}${rows.join('')}` + ); +} + +function row(label: string, value: string): string { + return `
${label}${value}
`; +} diff --git a/client/src/components/weather/WeatherLegend.tsx b/client/src/components/weather/WeatherLegend.tsx new file mode 100644 index 0000000..297b7dd --- /dev/null +++ b/client/src/components/weather/WeatherLegend.tsx @@ -0,0 +1,38 @@ +import { WEATHER_METRICS, legendFor, type WeatherMetric } from '../../weather/format'; + +interface WeatherLegendProps { + metric: WeatherMetric; + onMetricChange: (metric: WeatherMetric) => void; +} + +export function WeatherLegend({ metric, onMetricChange }: WeatherLegendProps) { + return ( +
+
+ {WEATHER_METRICS.map((m) => ( + + ))} +
+
+ {legendFor(metric).map((item) => ( + + + {item.label} + + ))} +
+ + Pfeil zeigt, wohin der Wind weht (zehnminütiges Mittel); 💧 = Regen in der letzten Stunde + +
+ ); +} diff --git a/client/src/components/weather/WeatherStationPanel.tsx b/client/src/components/weather/WeatherStationPanel.tsx new file mode 100644 index 0000000..54ea6ad --- /dev/null +++ b/client/src/components/weather/WeatherStationPanel.tsx @@ -0,0 +1,208 @@ +import { useQuery } from '@tanstack/react-query'; +import { + BarController, + BarElement, + CategoryScale, + Chart as ChartJS, + Legend, + LinearScale, + LineController, + LineElement, + PointElement, + Tooltip, + type ChartData, + type ChartOptions, +} from 'chart.js'; +import { useMemo } from 'react'; +import { Chart } from 'react-chartjs-2'; +import { fetchWeatherHistory, type WeatherStation } from '../../api/weather'; +import { compassDirection, formatDecimal, formatTime, toHourly } from '../../weather/format'; + +ChartJS.register( + CategoryScale, + LinearScale, + BarController, + BarElement, + LineController, + LineElement, + PointElement, + Tooltip, + Legend, +); + +type MixedType = 'bar' | 'line'; + +const HISTORY_DAYS = 7; +const TEMPERATURE_COLOR = '#eb6834'; +const PRECIPITATION_COLOR = '#2a78d6'; +const GRID_COLOR = '#e2e8f0'; + +interface WeatherStationPanelProps { + station: WeatherStation; + lastRefresh: string | null; + onClose: () => void; +} + +export function WeatherStationPanel({ station, lastRefresh, onClose }: WeatherStationPanelProps) { + const historyQuery = useQuery({ + queryKey: ['weather-history', station.abbr, lastRefresh], + queryFn: () => fetchWeatherHistory(station.abbr, HISTORY_DAYS), + staleTime: Infinity, + }); + const hourly = useMemo(() => toHourly(historyQuery.data ?? []), [historyQuery.data]); + const hasTemperature = hourly.some((h) => h.temperature !== null); + const hasPrecipitation = hourly.some((h) => h.precipitation !== null); + + const first = hourly[0]?.time; + const coversFullRange = + first !== undefined && Date.now() - first.getTime() >= (HISTORY_DAYS - 1) * 24 * 3_600_000; + const chartTitle = + coversFullRange || first === undefined + ? `Verlauf der letzten ${HISTORY_DAYS} Tage (Stundenwerte)` + : `Verlauf seit ${first.toLocaleString('de-CH', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}`; + + const data: ChartData = { + labels: hourly.map((h) => + h.time.toLocaleString('de-CH', { + weekday: 'short', + day: '2-digit', + month: '2-digit', + hour: '2-digit', + minute: '2-digit', + }), + ), + datasets: [ + ...(hasTemperature + ? [ + { + type: 'line' as const, + label: 'Temperatur (°C)', + data: hourly.map((h) => h.temperature), + borderColor: TEMPERATURE_COLOR, + backgroundColor: TEMPERATURE_COLOR, + borderWidth: 2, + spanGaps: true, + yAxisID: 'y', + }, + ] + : []), + ...(hasPrecipitation + ? [ + { + type: 'bar' as const, + label: 'Niederschlag (mm/h)', + data: hourly.map((h) => h.precipitation), + backgroundColor: PRECIPITATION_COLOR, + yAxisID: 'y1', + }, + ] + : []), + ], + }; + + const options: ChartOptions = { + responsive: true, + maintainAspectRatio: false, + animation: false, + interaction: { mode: 'index', intersect: false }, + elements: { point: { radius: 0 }, line: { tension: 0.2 } }, + plugins: { legend: { position: 'bottom', labels: { boxWidth: 10, boxHeight: 10 } } }, + scales: { + x: { grid: { display: false }, ticks: { maxTicksLimit: 7, autoSkip: true } }, + y: { + display: hasTemperature, + grid: { color: GRID_COLOR }, + title: { display: true, text: '°C' }, + }, + y1: { + display: hasPrecipitation, + position: 'right', + beginAtZero: true, + grid: { display: false }, + title: { display: true, text: 'mm/h' }, + }, + }, + }; + + return ( + + ); +} diff --git a/client/src/pages/ThurgauCombinedPage.tsx b/client/src/pages/ThurgauCombinedPage.tsx index faa80e1..4724499 100644 --- a/client/src/pages/ThurgauCombinedPage.tsx +++ b/client/src/pages/ThurgauCombinedPage.tsx @@ -19,6 +19,9 @@ import { CategoryLegend } from '../components/watercraft/CategoryLegend'; import { LocationPanel } from '../components/watercraft/LocationPanel'; import { WatercraftLayer } from '../components/watercraft/WatercraftLayer'; import { YearControls } from '../components/watercraft/YearControls'; +import { WeatherLayer } from '../components/weather/WeatherLayer'; +import { WeatherLegend } from '../components/weather/WeatherLegend'; +import { WeatherStationPanel } from '../components/weather/WeatherStationPanel'; import { formatTime } from '../hydrology/format'; import { useHydrologyData } from '../hydrology/useHydrologyData'; import { THURGAU_CENTER } from '../map/baseLayers'; @@ -29,24 +32,27 @@ import { formatDate, formatNumber } from '../traffic/format'; import { useTrafficData } from '../traffic/useTrafficData'; import { useVehicleData } from '../vehicles/useVehicleData'; import { useWatercraftData } from '../watercraft/useWatercraftData'; +import { useWeatherData } from '../weather/useWeatherData'; const MemoStationPanel = memo(StationPanel); const MemoLocationPanel = memo(LocationPanel); const MemoMunicipalityPanel = memo(MunicipalityPanel); -type LayerKey = 'fahrzeuge' | 'boote' | 'verkehr' | 'gewaesser'; +type LayerKey = 'fahrzeuge' | 'boote' | 'verkehr' | 'gewaesser' | 'wetter'; type Selection = | { layer: 'fahrzeuge'; id: string } | { layer: 'boote'; name: string } | { layer: 'verkehr'; code: number } - | { layer: 'gewaesser'; id: string }; + | { layer: 'gewaesser'; id: string } + | { layer: 'wetter'; abbr: string }; -const LAYER_ORDER: LayerKey[] = ['fahrzeuge', 'boote', 'verkehr', 'gewaesser']; +const LAYER_ORDER: LayerKey[] = ['fahrzeuge', 'boote', 'verkehr', 'gewaesser', 'wetter']; const LAYER_PARAM = 'ebenen'; const STATION_MAX_DISTANCE_M = 250; const HARBOUR_MAX_DISTANCE_M = 1500; const HYDRO_MAX_DISTANCE_M = 500; +const WEATHER_MAX_DISTANCE_M = 500; const SHARED_FILL_OPACITY = 0.55; function parseLayers(value: string | null): Set { @@ -64,6 +70,7 @@ export function ThurgauCombinedPage() { const showBoats = active.has('boote'); const showTraffic = active.has('verkehr'); const showWater = active.has('gewaesser'); + const showWeather = active.has('wetter'); const toggleLayer = useCallback( (key: LayerKey) => @@ -85,6 +92,7 @@ export function ThurgauCombinedPage() { const watercraft = useWatercraftData(); const vehicles = useVehicleData(); const hydrology = useHydrologyData(); + const weather = useWeatherData(); const yearList = useMemo(() => { const all = new Set([ @@ -145,6 +153,13 @@ export function ThurgauCombinedPage() { ), [], ); + const selectWeatherStation = useCallback( + (abbr: string) => + setSelection((current) => + current?.layer === 'wetter' && current.abbr === abbr ? null : { layer: 'wetter', abbr }, + ), + [], + ); const clearSelection = useCallback(() => setSelection(null), []); const outlines = vehicles.shapes; @@ -168,6 +183,11 @@ export function ThurgauCombinedPage() { assignToOutlines(outlines, hydrology.stations, (s) => [s.lon, s.lat], HYDRO_MAX_DISTANCE_M), [outlines, hydrology.stations], ); + const weatherStationsByMunicipality = useMemo( + () => + assignToOutlines(outlines, weather.stations, (s) => [s.lon, s.lat], WEATHER_MAX_DISTANCE_M), + [outlines, weather.stations], + ); const unplaced = boatView?.locations.filter((l) => l.lat === null) ?? []; const selectedStation = @@ -178,6 +198,10 @@ export function ThurgauCombinedPage() { visibleSelection?.layer === 'gewaesser' ? (hydrology.stations.find((s) => s.id === visibleSelection.id) ?? null) : null; + const selectedWeatherStation = + visibleSelection?.layer === 'wetter' + ? (weather.stations.find((s) => s.abbr === visibleSelection.abbr) ?? null) + : null; let panel: ReactNode; if (visibleSelection?.layer === 'fahrzeuge' && vehicles.meta && year !== null) { @@ -196,12 +220,14 @@ export function ThurgauCombinedPage() { stations={showTraffic ? (stationsByMunicipality.get(id) ?? []) : null} locations={showBoats && boatView ? (locationsByMunicipality.get(id) ?? []) : null} hydroStations={showWater ? (hydroStationsByMunicipality.get(id) ?? []) : null} + weatherStations={showWeather ? (weatherStationsByMunicipality.get(id) ?? []) : null} day={traffic.day} hour={traffic.hour} year={year} onSelectStation={selectStation} onSelectLocation={selectLocation} onSelectHydroStation={selectHydroStation} + onSelectWeatherStation={selectWeatherStation} /> ); @@ -240,6 +266,14 @@ export function ThurgauCombinedPage() { onClose={clearSelection} /> ); + } else if (selectedWeatherStation) { + panel = ( + + ); } else { panel = ( ); } @@ -270,12 +305,14 @@ export function ThurgauCombinedPage() { (showVehicles ? vehicles.error : null) ?? (showBoats ? watercraft.error : null) ?? (showTraffic ? traffic.error : null) ?? - (showWater ? hydrology.error : null); + (showWater ? hydrology.error : null) ?? + (showWeather ? weather.error : null); const loading = (showVehicles && vehicles.loading) || (showBoats && watercraft.loading) || (showTraffic && traffic.loading) || - (showWater && hydrology.loading); + (showWater && hydrology.loading) || + (showWeather && weather.loading); const missingYearNote = (firstYear: number | undefined) => year !== null && firstYear !== undefined && year < firstYear @@ -297,7 +334,7 @@ export function ThurgauCombinedPage() { / Thurgau – alle Daten - Fahrzeugbestand, Wasserfahrzeuge, Strassenverkehr und Gewässer auf einer Karte + Fahrzeugbestand, Wasserfahrzeuge, Strassenverkehr, Gewässer und Wetter auf einer Karte @@ -334,7 +371,11 @@ export function ThurgauCombinedPage() { scale={vehicles.scale} selectedId={visibleSelection?.layer === 'fahrzeuge' ? visibleSelection.id : null} onSelect={selectMunicipality} - fillOpacity={showBoats || showTraffic || showWater ? SHARED_FILL_OPACITY : undefined} + fillOpacity={ + showBoats || showTraffic || showWater || showWeather + ? SHARED_FILL_OPACITY + : undefined + } fitToData={false} /> )} @@ -368,6 +409,14 @@ export function ThurgauCombinedPage() { onSelect={selectHydroStation} /> )} + {showWeather && ( + + )} @@ -455,6 +504,20 @@ export function ThurgauCombinedPage() { > + toggleLayer('wetter')} + > + +
@@ -539,6 +602,17 @@ export function ThurgauCombinedPage() { ·{' '} )} + {weather.meta && ( + <> + {' '} + ·{' '} + + )} Karten, Gemeindegrenzen und Strassennetz © swisstopo · Bearbeitung: Werte pro Gemeinde, Standort und Zählstelle aggregiert, Zuordnung zu Gemeinden über die Lage diff --git a/client/src/styles.css b/client/src/styles.css index f425660..1837dc3 100644 --- a/client/src/styles.css +++ b/client/src/styles.css @@ -1142,3 +1142,61 @@ select { .hydro-badge.selected { outline: 2px solid #0f172a; } + +.weather-marker-anchor { + background: none; + border: none; +} + +.weather-badge { + position: absolute; + transform: translate(-50%, -50%); + min-width: 34px; + height: 34px; + padding: 0 4px; + box-sizing: border-box; + border-radius: 17px; + border: 2px solid white; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + color: white; + font-size: 12px; + line-height: 1; + font-variant-numeric: tabular-nums; + text-shadow: 0 0 2px rgba(15, 23, 42, 0.8); + box-shadow: 0 2px 6px rgba(15, 23, 42, 0.35); + cursor: pointer; + white-space: nowrap; +} + +.weather-badge small { + font-size: 8px; + opacity: 0.9; +} + +.weather-badge.selected { + border: 3px solid #0f172a; +} + +.weather-arrow { + position: absolute; + left: 0; + top: 0; + transform-origin: 50% 50%; + pointer-events: none; + display: flex; +} + +.weather-arrow svg { + overflow: visible; +} + +.weather-rain { + position: absolute; + left: 10px; + top: -24px; + font-size: 12px; + pointer-events: none; +} diff --git a/client/src/weather/format.ts b/client/src/weather/format.ts new file mode 100644 index 0000000..6dd07ea --- /dev/null +++ b/client/src/weather/format.ts @@ -0,0 +1,150 @@ +import type { WeatherHistoryPoint, WeatherStation } from '../api/weather'; + +export type WeatherMetric = 'temperature' | 'precipitation' | 'wind'; + +export const WEATHER_METRICS: { key: WeatherMetric; label: string }[] = [ + { key: 'temperature', label: 'Temperatur' }, + { key: 'precipitation', label: 'Niederschlag 24 h' }, + { key: 'wind', label: 'Wind' }, +]; + +const NO_VALUE_COLOR = '#94a3b8'; + +const TEMPERATURE_STOPS: [number, string][] = [ + [-Infinity, '#312e81'], + [-5, '#1d4ed8'], + [0, '#0ea5e9'], + [5, '#14b8a6'], + [10, '#84cc16'], + [15, '#eab308'], + [20, '#f97316'], + [25, '#dc2626'], +]; + +const PRECIPITATION_STOPS: [number, string][] = [ + [0, '#e2e8f0'], + [0.1, '#bae6fd'], + [2, '#60a5fa'], + [5, '#2563eb'], + [10, '#1e40af'], + [20, '#312e81'], +]; + +const WIND_STOPS: [number, string][] = [ + [0, '#94a3b8'], + [10, '#14b8a6'], + [20, '#eab308'], + [40, '#f97316'], + [60, '#dc2626'], +]; + +function stopColor(stops: [number, string][], value: number | null): string { + if (value === null) { + return NO_VALUE_COLOR; + } + let color = stops[0][1]; + for (const [threshold, stop] of stops) { + if (value >= threshold) { + color = stop; + } + } + return color; +} + +export const temperatureColor = (value: number | null) => stopColor(TEMPERATURE_STOPS, value); +export const precipitationColor = (value: number | null) => stopColor(PRECIPITATION_STOPS, value); +export const windColor = (value: number | null) => stopColor(WIND_STOPS, value); + +export function legendFor(metric: WeatherMetric): { label: string; color: string }[] { + if (metric === 'temperature') { + return TEMPERATURE_STOPS.map(([t, color]) => ({ + label: t === -Infinity ? 'unter −5 °C' : `ab ${t} °C`, + color, + })); + } + if (metric === 'precipitation') { + return PRECIPITATION_STOPS.map(([t, color]) => ({ + label: t === 0 ? 'trocken' : `ab ${formatDecimal(t, t < 1 ? 1 : 0)} mm`, + color, + })); + } + return WIND_STOPS.map(([t, color]) => ({ label: `ab ${t} km/h`, color })); +} + +export function formatDecimal(value: number | null, digits: number): string { + return value === null + ? '–' + : value.toLocaleString('de-CH', { + minimumFractionDigits: digits, + maximumFractionDigits: digits, + }); +} + +const COMPASS = ['N', 'NO', 'O', 'SO', 'S', 'SW', 'W', 'NW']; + +export function compassDirection(degrees: number | null): string { + return degrees === null ? '–' : COMPASS[Math.round((((degrees % 360) + 360) % 360) / 45) % 8]; +} + +export function formatTime(value: string | null): string { + return value + ? new Date(value).toLocaleTimeString('de-CH', { hour: '2-digit', minute: '2-digit' }) + : '–'; +} + +export function stationLabel(station: WeatherStation, metric: WeatherMetric): string { + if (metric === 'precipitation') { + return station.precipitation24h === null ? '–' : formatDecimal(station.precipitation24h, 1); + } + if (metric === 'wind') { + return station.windSpeed === null ? '–' : `${Math.round(station.windSpeed)}`; + } + return station.temperature === null ? '–' : `${formatDecimal(station.temperature, 1)}°`; +} + +export function stationColor(station: WeatherStation, metric: WeatherMetric): string { + if (metric === 'precipitation') { + return precipitationColor(station.precipitation24h); + } + if (metric === 'wind') { + return windColor(station.windSpeed); + } + return temperatureColor(station.temperature); +} + +export interface HourlyPoint { + time: Date; + temperature: number | null; + precipitation: number | null; + windGust: number | null; +} + +export function toHourly(points: WeatherHistoryPoint[]): HourlyPoint[] { + const hours = new Map(); + for (const point of points) { + const time = new Date(point.time); + time.setMinutes(0, 0, 0); + const key = time.getTime(); + hours.set(key, [...(hours.get(key) ?? []), point]); + } + + return [...hours.entries()] + .sort(([a], [b]) => a - b) + .map(([key, values]) => { + const temperatures = values.flatMap((v) => (v.temperature === null ? [] : [v.temperature])); + const precipitation = values.flatMap((v) => + v.precipitation === null ? [] : [v.precipitation], + ); + const gusts = values.flatMap((v) => (v.windGust === null ? [] : [v.windGust])); + return { + time: new Date(key), + temperature: + temperatures.length > 0 + ? temperatures.reduce((sum, t) => sum + t, 0) / temperatures.length + : null, + precipitation: + precipitation.length > 0 ? precipitation.reduce((sum, p) => sum + p, 0) : null, + windGust: gusts.length > 0 ? Math.max(...gusts) : null, + }; + }); +} diff --git a/client/src/weather/useWeatherData.ts b/client/src/weather/useWeatherData.ts new file mode 100644 index 0000000..dcb485c --- /dev/null +++ b/client/src/weather/useWeatherData.ts @@ -0,0 +1,41 @@ +import { useQuery } from '@tanstack/react-query'; +import { useMemo, useState } from 'react'; +import { fetchWeatherMeta, fetchWeatherStations } from '../api/weather'; +import type { WeatherMetric } from './format'; + +const REFRESH_MS = 5 * 60_000; + +export function useWeatherData() { + const metaQuery = useQuery({ + queryKey: ['weather-meta'], + queryFn: fetchWeatherMeta, + refetchInterval: REFRESH_MS, + }); + const stationsQuery = useQuery({ + queryKey: ['weather-stations', metaQuery.data?.lastRefresh ?? null], + queryFn: fetchWeatherStations, + enabled: !!metaQuery.data, + staleTime: Infinity, + }); + const [metric, setMetric] = useState('temperature'); + + const stations = useMemo(() => stationsQuery.data ?? [], [stationsQuery.data]); + const latestTime = useMemo( + () => + stations.reduce( + (latest, s) => (s.time && (!latest || s.time > latest) ? s.time : latest), + null, + ), + [stations], + ); + + return { + meta: metaQuery.data, + stations, + latestTime, + metric, + setMetric, + error: metaQuery.error ?? stationsQuery.error, + loading: metaQuery.isLoading || stationsQuery.isLoading || stations.length === 0, + }; +} diff --git a/docs/datasets.md b/docs/datasets.md index 265c3ed..a283f6d 100644 --- a/docs/datasets.md +++ b/docs/datasets.md @@ -16,6 +16,7 @@ flowchart LR end lindas["LINDAS (BAFU)
Abfluss und Pegel"] + smn["data.geo.admin.ch
MeteoSchweiz SwissMetNet"] subgraph geo["swisstopo API"] tlm["swissTLM3D Strassen
+ SearchServer"] @@ -29,10 +30,11 @@ flowchart LR wr["WatercraftRefresher
täglich"] vr["VehicleRefresher
täglich"] hr["HydrologyRefresher
alle 10 min"] + we["WeatherRefresher
alle 10 min"] end cache[("JSON-Cache
{DataPath}/…")] - api["/api/traffic
/api/watercraft
/api/vehicles
/api/hydrology"] + api["/api/traffic
/api/watercraft
/api/vehicles
/api/hydrology
/api/weather"] client["React-Client"] traffic --> tr @@ -42,7 +44,8 @@ flowchart LR pop --> vr bound -->|einmal pro Gemeinde| vr lindas --> hr - tr & wr & vr & hr --> cache + smn --> we + tr & wr & vr & hr & we --> cache cache --> api --> client wmts -->|direkt im Browser| client ``` @@ -81,11 +84,12 @@ sequenceDiagram | [Wohnbevölkerung](datasets/wohnbevoelkerung.md) | data.tg.ch `sk-stat-56` (Amt für Daten und Statistik TG) | CC BY 4.0 | JSON-Export des ganzen Datensatzes | wie Fahrzeugbestand | `vehicles/thurgau/population.json` | | [Gemeindegrenzen](datasets/gemeindegrenzen.md) | swisstopo swissBOUNDARIES3D | swisstopo OGD | Feature pro BFS-Nummer (WGS84) | einmal pro Gemeinde; neu bei geänderter `OutlinesFileName` | `vehicles/thurgau/outlines-v1.json` | | [Gewässer](datasets/gewaesser.md) | LINDAS `foen/hydro` (BAFU) | opendata.swiss BY | SPARQL-Abfrage der aktuellen Werte gewählter Stationen | Prüfung jede Minute, Abruf alle 10 min; Verlauf selbst gesammelt, Lücken aus den 7-Tage-Grafiken von hydrodaten.admin.ch ergänzt | `hydrology/thurgau/days/yyyy-MM-dd.json`, `stations.json` (60 Tage) | +| [Wetter](datasets/wetter.md) | data.geo.admin.ch `ch.meteoschweiz.ogd-smn` (MeteoSchweiz) | CC BY 4.0 | CSV pro Station (`_t_now`), einmalig `_t_recent` für fehlende Tage | Prüfung jede Minute, Abruf alle 10 min | `weather/thurgau/days/yyyy-MM-dd.json`, `stations.json` (60 Tage) | | [Grundkarten](datasets/grundkarten.md) | swisstopo WMTS (`pixelkarte-grau/-farbe`, `swissimage`) | swisstopo OGD | Kacheln direkt vom Browser | nie gecacht vom Server | – | ## Kombinierte Karte -Die Seite `/karte/thurgau` zeigt Fahrzeugbestand, Wasserfahrzeuge, Strassenverkehr und Gewässer als Ebenen auf einer Karte. Sie lädt keine eigenen Daten, sondern ruft dieselben Endpunkte wie die Einzelkarten auf (`/api/vehicles`, `/api/watercraft`, `/api/traffic`); Quellen, Abruf, Aktualisierung und Cache sind also die der Datensätze oben. +Die Seite `/karte/thurgau` zeigt Fahrzeugbestand, Wasserfahrzeuge, Strassenverkehr, Gewässer und Wetter als Ebenen auf einer Karte. Sie lädt keine eigenen Daten, sondern ruft dieselben Endpunkte wie die Einzelkarten auf (`/api/vehicles`, `/api/watercraft`, `/api/traffic`); Quellen, Abruf, Aktualisierung und Cache sind also die der Datensätze oben. ```mermaid flowchart LR @@ -93,11 +97,12 @@ flowchart LR w["/api/watercraft
Bootsstandorte pro Jahr"] --> page t["/api/traffic
Zählstellen pro Stunde"] --> page h["/api/hydrology
Gewässer live"] --> page + we["/api/weather
Wetter live"] --> page page["Kombinierte Karte
/karte/thurgau"] --> assign["Zuordnung im Browser:
Zählstelle in Gemeindegrenze,
Bootsstandort zur nächsten Gemeinde"] ``` -- Die Ebenen stehen in der URL (`?ebenen=fahrzeuge,boote,verkehr,gewaesser&jahr=2025`); ohne `ebenen` sind alle eingeschaltet. Die Gewässer zeigen immer den neusten Stand, unabhängig von Jahr und Verkehrstag. +- Die Ebenen stehen in der URL (`?ebenen=fahrzeuge,boote,verkehr,gewaesser,wetter&jahr=2025`); ohne `ebenen` sind alle eingeschaltet. Gewässer und Wetter zeigen immer den neusten Stand, unabhängig von Jahr und Verkehrstag. - Das Jahr gilt für Fahrzeugbestand (ab 2023) und Wasserfahrzeuge (ab 2021). Ist eine Ebene für das gewählte Jahr leer, zeigt die Ebene einen Hinweis. Die Verkehrszählungen haben kein Jahr, sondern Tag und Stunde aus dem Verkehrs-Cache. -- „In dieser Gemeinde“ ordnet Zählstellen über die Gemeindegrenze zu (bis 250 m daneben) und Bootsstandorte der nächsten Gemeinde bis 1,5 km, weil die Uferpunkte im See und damit ausserhalb der Grenzen liegen. Gewässerstationen zählen bis 500 m ausserhalb der Grenze, weil Flüsse oft selbst die Gemeindegrenze bilden. +- „In dieser Gemeinde“ ordnet Zählstellen über die Gemeindegrenze zu (bis 250 m daneben) und Bootsstandorte der nächsten Gemeinde bis 1,5 km, weil die Uferpunkte im See und damit ausserhalb der Grenzen liegen. Gewässer- und Wetterstationen zählen bis 500 m ausserhalb der Grenze, weil Flüsse oft selbst die Gemeindegrenze bilden. -Alle Intervalle und Pfade sind in `appsettings.json` unter `Traffic`, `Watercraft`, `Vehicles` und `Hydrology` konfigurierbar (`DataPath`, `RefreshInterval`). Die Quellenangaben, die die Lizenzen verlangen, stehen in der Fusszeile jeder Karte. Details, Ablaufdiagramm und Besonderheiten stehen in der Datei des jeweiligen Datensatzes. +Alle Intervalle und Pfade sind in `appsettings.json` unter `Traffic`, `Watercraft`, `Vehicles`, `Hydrology` und `Weather` konfigurierbar (`DataPath`, `RefreshInterval`). Die Quellenangaben, die die Lizenzen verlangen, stehen in der Fusszeile jeder Karte. Details, Ablaufdiagramm und Besonderheiten stehen in der Datei des jeweiligen Datensatzes. diff --git a/docs/datasets/wetter.md b/docs/datasets/wetter.md new file mode 100644 index 0000000..3e95278 --- /dev/null +++ b/docs/datasets/wetter.md @@ -0,0 +1,39 @@ +# Wetter (SwissMetNet) + +[← Übersicht](../datasets.md) + +| | | +|---|---| +| Datensatz | «Automatische Wetterstationen – Messwerte» (SwissMetNet, STAC-Collection `ch.meteoschweiz.ogd-smn`) | +| Quelle | [data.geo.admin.ch](https://data.geo.admin.ch/api/stac/v1/collections/ch.meteoschweiz.ogd-smn), Dokumentation auf [opendatadocs.meteoswiss.ch](https://opendatadocs.meteoswiss.ch/a-data-groundbased/a1-automatic-weather-stations), Katalogeintrag auf [opendata.swiss](https://opendata.swiss/de/dataset/automatische-wetterstationen-messwerte) | +| Herausgeber | MeteoSchweiz | +| Lizenz | CC BY 4.0 («Quelle: MeteoSchweiz») | +| Inhalt | Zehnminutenwerte pro Station; verwendet werden Lufttemperatur 2 m (`tre200s0`), relative Feuchte (`ure200s0`), Niederschlag (`rre150z0`, Summe 10 min), Sonnenschein (`sre000z0`, Minuten), Wind (`fu3010z0`, km/h), Böenspitze (`fu3010z1`, km/h), Windrichtung (`dkl010z0`), Luftdruck QFF (`pp0qffs0`) | +| Stationen | Standard (`WeatherOptions.DefaultStations`): die fünf Thurgauer Stationen Güttingen (GUT), Steckborn (STK), Bischofszell/Sitterdorf (BIZ), Aadorf/Tänikon (TAE), Salen-Reutenen (HAI); änderbar mit `Weather:Stations`. Steckborn misst nur Wind. | +| Verwendet in | Ebene «Wetter (live)» der Karte `/karte/thurgau` | +| Abruf | Stationsliste `ogd-smn_meta_stations.csv` (Latin-1) einmal pro Tag; pro Station `{abbr}/ogd-smn_{abbr}_t_now.csv` (gestern 00:00 bis jetzt, ca. 16 KB); fehlen Tage, einmalig `{abbr}/ogd-smn_{abbr}_t_recent.csv` (1. Januar bis gestern, ca. 6 MB), davon nur die letzten 7 Tage | +| Aktualisierung | Prüfung jede Minute, Abruf alle 10 min (`Weather:RefreshInterval`); MeteoSchweiz aktualisiert die Dateien laut Dokumentation alle 20 min; der Browser lädt alle 5 min neu | +| Cache | `{DataPath}/weather/thurgau/meta.json`, `stations.json`, `days/yyyy-MM-dd.json` (Messwerte pro UTC-Tag); Tage älter als `Weather:HistoryDays` (Standard 60) werden gelöscht | +| Code | `Schaad.OpenData.Weather` (`MeteoSwissClient`, `WeatherRefresher`, `WeatherCacheStorage`, `WeatherAnalysis`) | + +## Ablauf + +```mermaid +flowchart LR + S["WeatherRefreshService
jede Minute"] --> R{"letzter Abruf
älter als 10 min?"} + R -- ja --> M{"Stationsliste
älter als 1 Tag?"} + M -- ja --> ST["ogd-smn_meta_stations.csv"] --> C + M -- nein --> C{"Cache deckt 6 Tage ab
und ohne Lücke?"} + C -- nein --> H["{abbr}_t_recent.csv
letzte 7 Tage"] --> N + C -- ja --> N["{abbr}_t_now.csv"] + N --> D[("days/yyyy-MM-dd.json")] + D --> P["Tage älter als
HistoryDays löschen"] +``` + +## Hinweise + +- Die Zeitstempel (`reference_timestamp`, `dd.MM.yyyy HH:mm`) sind UTC. +- `_t_now.csv` reicht bis gestern 00:00 zurück; Lücken bis knapp einen Tag schliessen sich damit von selbst. Fehlen mehr als 6 Tage oder ist der neuste Wert älter als 20 Stunden, liest der Server einmalig `_t_recent.csv` (höchstens einmal pro Stunde und Station). +- Fällt eine Station aus, werden die anderen trotzdem aktualisiert (Warnung im Log). +- Aktuelle Werte nehmen pro Grösse den neusten vorhandenen Wert der letzten 30 Minuten, weil einzelne Felder (z. B. Böen) im neusten Zeitschritt manchmal noch fehlen. Niederschlag und Sonnenschein werden über die letzte Stunde bzw. 24 Stunden summiert. +- Das Diagramm im Seitenpanel fasst die Zehnminutenwerte zu Stunden zusammen (Temperatur gemittelt, Niederschlag summiert).