Add live weather layer from MeteoSwiss stations (#7)
- New Schaad.OpenData.Weather project: MeteoSwissClient reads the
10-minute CSV of the five SwissMetNet stations in Thurgau every 10
minutes (station list once a day) and backfills the last 7 days from
the yearly file when the cache has less than 6 days
- History kept as JSON per day (60 days); a failing station does not
stop the others
- API: /api/weather/meta, /stations (current values, 1 h/24 h rain,
24 h min/max, strongest gust), /stations/{abbr}/history
- Combined map: "Wetter (live)" layer with station badges (temperature,
24 h rain or wind), wind arrows, rain marker, station panel with
hourly 7-day chart, overview and municipality context entries
- Docs: docs/datasets/wetter.md, overview in docs/datasets.md,
CLAUDE.md; Docker and appsettings wiring
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
This commit is contained in:
parent
58e4079ced
commit
bd2981ffb8
42 changed files with 1960 additions and 21 deletions
27
CLAUDE.md
27
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 `<Subject>TestShould` class per subject, method names `DoThisWhenThat`, Shouldly assertions (no `Assert.*`). HTTP clients are tested with a stub `HttpMessageHandler`, storage with a temp directory cleaned up in `Dispose`.
|
||||
- TypeScript: Prettier config in `client/.prettierrc.json` (single quotes, width 100).
|
||||
|
|
|
|||
|
|
@ -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"]
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
<ProjectReference Include="..\Schaad.OpenData.Traffic\Schaad.OpenData.Traffic.csproj" />
|
||||
<ProjectReference Include="..\Schaad.OpenData.Vehicles\Schaad.OpenData.Vehicles.csproj" />
|
||||
<ProjectReference Include="..\Schaad.OpenData.Watercraft\Schaad.OpenData.Watercraft.csproj" />
|
||||
<ProjectReference Include="..\Schaad.OpenData.Weather\Schaad.OpenData.Weather.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
47
Schaad.OpenData.Server/Weather/WeatherEndpoints.cs
Normal file
47
Schaad.OpenData.Server/Weather/WeatherEndpoints.cs
Normal file
|
|
@ -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<WeatherOptions> 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<WeatherOptions> 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;
|
||||
}
|
||||
}
|
||||
9
Schaad.OpenData.Server/Weather/WeatherMetaResponse.cs
Normal file
9
Schaad.OpenData.Server/Weather/WeatherMetaResponse.cs
Normal file
|
|
@ -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);
|
||||
|
|
@ -23,5 +23,10 @@
|
|||
"DataPath": "../data",
|
||||
"RefreshInterval": "00:10:00",
|
||||
"HistoryDays": 60
|
||||
},
|
||||
"Weather": {
|
||||
"DataPath": "../data",
|
||||
"RefreshInterval": "00:10:00",
|
||||
"HistoryDays": 60
|
||||
}
|
||||
}
|
||||
|
|
|
|||
91
Schaad.OpenData.Tests/MeteoSwissClientTestShould.cs
Normal file
91
Schaad.OpenData.Tests/MeteoSwissClientTestShould.cs
Normal file
|
|
@ -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<string, byte[]> bodies) : HttpMessageHandler
|
||||
{
|
||||
public List<string> Requests { get; } = [];
|
||||
|
||||
protected override Task<HttpResponseMessage> 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();
|
||||
}
|
||||
}
|
||||
|
|
@ -23,6 +23,7 @@
|
|||
<ProjectReference Include="..\Schaad.OpenData.Traffic\Schaad.OpenData.Traffic.csproj" />
|
||||
<ProjectReference Include="..\Schaad.OpenData.Vehicles\Schaad.OpenData.Vehicles.csproj" />
|
||||
<ProjectReference Include="..\Schaad.OpenData.Watercraft\Schaad.OpenData.Watercraft.csproj" />
|
||||
<ProjectReference Include="..\Schaad.OpenData.Weather\Schaad.OpenData.Weather.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
55
Schaad.OpenData.Tests/WeatherAnalysisTestShould.cs
Normal file
55
Schaad.OpenData.Tests/WeatherAnalysisTestShould.cs
Normal file
|
|
@ -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)]);
|
||||
}
|
||||
}
|
||||
51
Schaad.OpenData.Tests/WeatherCacheStorageTestShould.cs
Normal file
51
Schaad.OpenData.Tests/WeatherCacheStorageTestShould.cs
Normal file
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
105
Schaad.OpenData.Tests/WeatherRefresherTestShould.cs
Normal file
105
Schaad.OpenData.Tests/WeatherRefresherTestShould.cs
Normal file
|
|
@ -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<TimeProvider>();
|
||||
private readonly WeatherRefresher refresher;
|
||||
|
||||
public WeatherRefresherTestShould()
|
||||
{
|
||||
var options = Options.Create(settings);
|
||||
client = Substitute.For<MeteoSwissClient>(new HttpClient(), options);
|
||||
client.FetchStationsAsync(Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns([Station(), Station("STK", "Steckborn")]);
|
||||
client.FetchRecentAsync(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(call => [Reading(call.Arg<string>(), Now)]);
|
||||
client.FetchHistoryAsync(Arg.Any<string>(), Arg.Any<DateTimeOffset>(), Arg.Any<CancellationToken>())
|
||||
.Returns(call => [Reading(call.Arg<string>(), Now.AddDays(-7))]);
|
||||
storage = Substitute.For<WeatherCacheStorage>(options);
|
||||
timeProvider.GetUtcNow().Returns(Now);
|
||||
refresher = new WeatherRefresher(client, storage, store, options, timeProvider, NullLogger<WeatherRefresher>.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<IReadOnlyCollection<string>>(a => a.SequenceEqual(new[] { "GUT", "STK" })),
|
||||
Arg.Any<CancellationToken>());
|
||||
await client.Received(1).FetchHistoryAsync("GUT", Now.AddDays(-7), Arg.Any<CancellationToken>());
|
||||
await client.Received(1).FetchHistoryAsync("STK", Now.AddDays(-7), Arg.Any<CancellationToken>());
|
||||
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<IReadOnlyCollection<DateOnly>>(days => days.Order().SequenceEqual(new[] { new DateOnly(2026, 11, 11), new DateOnly(2026, 11, 18) })),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FetchOnlyRecentValuesWhenCacheIsCovered()
|
||||
{
|
||||
store.Replace(Covered(Now.AddHours(-1)));
|
||||
|
||||
await refresher.RefreshAsync(CancellationToken.None);
|
||||
|
||||
await client.DidNotReceive().FetchStationsAsync(Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>());
|
||||
await client.DidNotReceive().FetchHistoryAsync(Arg.Any<string>(), Arg.Any<DateTimeOffset>(), Arg.Any<CancellationToken>());
|
||||
await client.Received(2).FetchRecentAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
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<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task KeepOtherStationsWhenOneStationFails()
|
||||
{
|
||||
store.Replace(Covered(Now.AddHours(-1)));
|
||||
client.FetchRecentAsync("GUT", Arg.Any<CancellationToken>()).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();
|
||||
}
|
||||
}
|
||||
20
Schaad.OpenData.Tests/WeatherTestData.cs
Normal file
20
Schaad.OpenData.Tests/WeatherTestData.cs
Normal file
|
|
@ -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);
|
||||
}
|
||||
62
Schaad.OpenData.Weather/Analysis/WeatherAnalysis.cs
Normal file
62
Schaad.OpenData.Weather/Analysis/WeatherAnalysis.cs
Normal file
|
|
@ -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<WeatherStationView> 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<WeatherHistoryPoint> 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<WeatherReading> 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<WeatherReading> newestFirst, Func<WeatherReading, double?> value) =>
|
||||
newestFirst.Select(value).FirstOrDefault(v => v.HasValue);
|
||||
|
||||
private static double? Sum(IReadOnlyList<WeatherReading> readings, Func<WeatherReading, double?> value)
|
||||
{
|
||||
var values = readings.Select(value).Where(v => v.HasValue).ToList();
|
||||
return values.Count == 0 ? null : Math.Round(values.Sum(v => v!.Value), 1);
|
||||
}
|
||||
}
|
||||
8
Schaad.OpenData.Weather/Analysis/WeatherHistoryPoint.cs
Normal file
8
Schaad.OpenData.Weather/Analysis/WeatherHistoryPoint.cs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
namespace Schaad.OpenData.Weather.Analysis;
|
||||
|
||||
public sealed record WeatherHistoryPoint(
|
||||
DateTimeOffset Time,
|
||||
double? Temperature,
|
||||
double? Precipitation,
|
||||
double? WindSpeed,
|
||||
double? WindGust);
|
||||
23
Schaad.OpenData.Weather/Analysis/WeatherStationView.cs
Normal file
23
Schaad.OpenData.Weather/Analysis/WeatherStationView.cs
Normal file
|
|
@ -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);
|
||||
13
Schaad.OpenData.Weather/Models/WeatherReading.cs
Normal file
13
Schaad.OpenData.Weather/Models/WeatherReading.cs
Normal file
|
|
@ -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);
|
||||
3
Schaad.OpenData.Weather/Models/WeatherStation.cs
Normal file
3
Schaad.OpenData.Weather/Models/WeatherStation.cs
Normal file
|
|
@ -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);
|
||||
15
Schaad.OpenData.Weather/Schaad.OpenData.Weather.csproj
Normal file
15
Schaad.OpenData.Weather/Schaad.OpenData.Weather.csproj
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Schaad.OpenData.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
41
Schaad.OpenData.Weather/Source/CsvLine.cs
Normal file
41
Schaad.OpenData.Weather/Source/CsvLine.cs
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
using System.Text;
|
||||
|
||||
namespace Schaad.OpenData.Weather.Source;
|
||||
|
||||
internal static class CsvLine
|
||||
{
|
||||
public static IReadOnlyList<string> Split(string line)
|
||||
{
|
||||
var fields = new List<string>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
123
Schaad.OpenData.Weather/Source/MeteoSwissClient.cs
Normal file
123
Schaad.OpenData.Weather/Source/MeteoSwissClient.cs
Normal file
|
|
@ -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<WeatherOptions> options)
|
||||
{
|
||||
private const string TimestampFormat = "dd.MM.yyyy HH:mm";
|
||||
|
||||
private string BaseUrl => options.Value.BaseUrl.TrimEnd('/');
|
||||
|
||||
public virtual async Task<IReadOnlyList<WeatherStation>> FetchStationsAsync(IReadOnlyCollection<string> abbreviations, CancellationToken cancellationToken)
|
||||
{
|
||||
var wanted = abbreviations.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var stations = new List<WeatherStation>();
|
||||
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<IReadOnlyList<WeatherReading>> FetchRecentAsync(string abbr, CancellationToken cancellationToken) =>
|
||||
FetchReadingsAsync(abbr, "t_now", DateTimeOffset.MinValue, cancellationToken);
|
||||
|
||||
public virtual Task<IReadOnlyList<WeatherReading>> FetchHistoryAsync(string abbr, DateTimeOffset from, CancellationToken cancellationToken) =>
|
||||
FetchReadingsAsync(abbr, "t_recent", from, cancellationToken);
|
||||
|
||||
private async Task<IReadOnlyList<WeatherReading>> 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<WeatherReading>();
|
||||
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<Dictionary<string, string>> 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<string, string>(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<string, string> row, string column) =>
|
||||
row.TryGetValue(column, out var text) && double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var value)
|
||||
? value
|
||||
: null;
|
||||
}
|
||||
3
Schaad.OpenData.Weather/Storage/WeatherCacheMeta.cs
Normal file
3
Schaad.OpenData.Weather/Storage/WeatherCacheMeta.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Weather.Storage;
|
||||
|
||||
public sealed record WeatherCacheMeta(DateTimeOffset? LastRefresh, DateTimeOffset? StationsFetched);
|
||||
88
Schaad.OpenData.Weather/Storage/WeatherCacheStorage.cs
Normal file
88
Schaad.OpenData.Weather/Storage/WeatherCacheStorage.cs
Normal file
|
|
@ -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<WeatherOptions> 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<WeatherSnapshot> LoadAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var meta = await ReadAsync<WeatherCacheMeta>(Path.Combine(RootPath, "meta.json"), cancellationToken);
|
||||
var stations = await ReadAsync<List<WeatherStation>>(Path.Combine(RootPath, "stations.json"), cancellationToken) ?? [];
|
||||
var readings = new List<WeatherReading>();
|
||||
if (Directory.Exists(DaysPath))
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(DaysPath, "*.json").Order(StringComparer.Ordinal))
|
||||
{
|
||||
readings.AddRange(await ReadAsync<List<WeatherReading>>(file, cancellationToken) ?? []);
|
||||
}
|
||||
}
|
||||
|
||||
return new WeatherSnapshot(stations, readings, meta?.LastRefresh, meta?.StationsFetched);
|
||||
}
|
||||
|
||||
public virtual async Task SaveAsync(WeatherSnapshot snapshot, IReadOnlyCollection<DateOnly> 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<T?> ReadAsync<T>(string path, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
await using var stream = File.OpenRead(path);
|
||||
return await JsonSerializer.DeserializeAsync<T>(stream, JsonOptions, cancellationToken);
|
||||
}
|
||||
|
||||
private static async Task WriteAsync<T>(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);
|
||||
}
|
||||
}
|
||||
10
Schaad.OpenData.Weather/Storage/WeatherDataStore.cs
Normal file
10
Schaad.OpenData.Weather/Storage/WeatherDataStore.cs
Normal file
|
|
@ -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;
|
||||
}
|
||||
55
Schaad.OpenData.Weather/Storage/WeatherSnapshot.cs
Normal file
55
Schaad.OpenData.Weather/Storage/WeatherSnapshot.cs
Normal file
|
|
@ -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<WeatherStation> stations,
|
||||
IEnumerable<WeatherReading> 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<WeatherStation> Stations { get; }
|
||||
|
||||
public IReadOnlyList<WeatherReading> Readings { get; }
|
||||
|
||||
public DateTimeOffset? LastRefresh { get; }
|
||||
|
||||
public DateTimeOffset? StationsFetched { get; }
|
||||
|
||||
public WeatherSnapshot With(
|
||||
IReadOnlyList<WeatherStation> stations,
|
||||
IEnumerable<WeatherReading> readings,
|
||||
DateTimeOffset lastRefresh,
|
||||
DateTimeOffset? stationsFetched,
|
||||
DateTimeOffset keepFrom) =>
|
||||
new(
|
||||
Stations.Concat(stations),
|
||||
Readings.Concat(readings).Where(r => r.Time >= keepFrom),
|
||||
lastRefresh,
|
||||
stationsFetched ?? StationsFetched);
|
||||
|
||||
public IReadOnlyList<WeatherReading> NewReadings(IEnumerable<WeatherReading> readings)
|
||||
{
|
||||
var known = Readings.Select(r => (r.StationAbbr, r.Time)).ToHashSet();
|
||||
return readings.Where(r => !known.Contains((r.StationAbbr, r.Time))).ToList();
|
||||
}
|
||||
}
|
||||
21
Schaad.OpenData.Weather/WeatherOptions.cs
Normal file
21
Schaad.OpenData.Weather/WeatherOptions.cs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
namespace Schaad.OpenData.Weather;
|
||||
|
||||
public sealed class WeatherOptions
|
||||
{
|
||||
public const string SectionName = "Weather";
|
||||
|
||||
public static readonly IReadOnlyList<string> 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<string> EffectiveStations =>
|
||||
(Stations.Length > 0 ? Stations : DefaultStations).Select(s => s.Trim().ToUpperInvariant()).ToList();
|
||||
}
|
||||
42
Schaad.OpenData.Weather/WeatherRefreshService.cs
Normal file
42
Schaad.OpenData.Weather/WeatherRefreshService.cs
Normal file
|
|
@ -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<WeatherOptions> options,
|
||||
ILogger<WeatherRefreshService> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
102
Schaad.OpenData.Weather/WeatherRefresher.cs
Normal file
102
Schaad.OpenData.Weather/WeatherRefresher.cs
Normal file
|
|
@ -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<WeatherOptions> options,
|
||||
TimeProvider timeProvider,
|
||||
ILogger<WeatherRefresher> 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<string, DateTimeOffset> 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<WeatherStation> 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<WeatherReading>();
|
||||
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<WeatherReading> readings, DateTimeOffset now) =>
|
||||
readings.Count == 0
|
||||
|| readings[0].Time > now - RequiredCoverage
|
||||
|| readings[^1].Time < now - MaxGap;
|
||||
}
|
||||
|
|
@ -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<WeatherOptions>(configuration.GetSection(WeatherOptions.SectionName));
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
services.AddSingleton<WeatherDataStore>();
|
||||
services.AddSingleton<WeatherCacheStorage>();
|
||||
services.AddSingleton<WeatherRefresher>();
|
||||
services.AddHostedService<WeatherRefreshService>();
|
||||
|
||||
services.AddHttpClient<MeteoSwissClient>(client =>
|
||||
{
|
||||
client.Timeout = TimeSpan.FromMinutes(2);
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
56
client/src/api/weather.ts
Normal file
56
client/src/api/weather.ts
Normal file
|
|
@ -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<T>(url: string): Promise<T> {
|
||||
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<WeatherMeta>('/api/weather/meta');
|
||||
|
||||
export const fetchWeatherStations = () => getJson<WeatherStation[]>('/api/weather/stations');
|
||||
|
||||
export const fetchWeatherHistory = (abbr: string, days: number) =>
|
||||
getJson<WeatherHistoryPoint[]>(
|
||||
`/api/weather/stations/${encodeURIComponent(abbr)}/history?tage=${days}`,
|
||||
);
|
||||
|
|
@ -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({
|
|||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{weatherStations && weatherStations.length > 0 && (
|
||||
<ul className="context-list">
|
||||
{weatherStations.map((station) => (
|
||||
<li key={station.abbr}>
|
||||
<button type="button" onClick={() => onSelectWeatherStation(station.abbr)}>
|
||||
<span className="context-kind">Wetter</span>
|
||||
<span className="context-name">{station.name}</span>
|
||||
<span className="context-value">
|
||||
{station.temperature !== null
|
||||
? `${station.temperature.toLocaleString('de-CH', { maximumFractionDigits: 1 })} °C · `
|
||||
: ''}
|
||||
{station.precipitation24h !== null
|
||||
? `${station.precipitation24h.toLocaleString('de-CH', { maximumFractionDigits: 1 })} mm in 24 h`
|
||||
: `Wind ${station.windSpeed === null ? '–' : Math.round(station.windSpeed)} km/h`}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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({
|
|||
</div>
|
||||
</header>
|
||||
|
||||
{!vehicles && !watercraft && !traffic && !hydrology && (
|
||||
{!vehicles && !watercraft && !traffic && !hydrology && !weather && (
|
||||
<p className="panel-note">Schalte links mindestens eine Ebene ein.</p>
|
||||
)}
|
||||
|
||||
|
|
@ -128,6 +131,8 @@ export function OverviewPanel({
|
|||
|
||||
{hydrology && <HydrologyOverview stations={hydrology.stations} />}
|
||||
|
||||
{weather && <WeatherOverview stations={weather.stations} />}
|
||||
|
||||
<p className="panel-note overview-hint">
|
||||
Klicke auf eine Gemeinde, einen Bootsstandort oder eine Zählstelle, um Details zu sehen.
|
||||
</p>
|
||||
|
|
@ -174,3 +179,46 @@ function HydrologyOverview({ stations }: { stations: HydroStation[] }) {
|
|||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
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<string | null>(
|
||||
(value, s) => (s.time && (!value || s.time > value) ? s.time : value),
|
||||
null,
|
||||
);
|
||||
const format = (value: number) => value.toLocaleString('de-CH', { maximumFractionDigits: 1 });
|
||||
|
||||
return (
|
||||
<section>
|
||||
<h3>Wetter, Stand {formatTime(latest)}</h3>
|
||||
<div className="stat-tiles">
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">
|
||||
{temperatures.length > 0
|
||||
? `${format(Math.min(...temperatures))} bis ${format(Math.max(...temperatures))} °C`
|
||||
: '–'}
|
||||
</span>
|
||||
<span className="stat-tile-label">Lufttemperatur an {stations.length} Stationen</span>
|
||||
</div>
|
||||
{wettest && (
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">{format(wettest.precipitation24h ?? 0)} mm</span>
|
||||
<span className="stat-tile-label">meister Regen in 24 h ({wettest.name})</span>
|
||||
</div>
|
||||
)}
|
||||
{windiest && (
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">{Math.round(windiest.windGustMax24h ?? 0)} km/h</span>
|
||||
<span className="stat-tile-label">stärkste Böe in 24 h ({windiest.name})</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
134
client/src/components/weather/WeatherLayer.tsx
Normal file
134
client/src/components/weather/WeatherLayer.tsx
Normal file
|
|
@ -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: <a href="https://www.meteoschweiz.admin.ch/">MeteoSchweiz</a>';
|
||||
|
||||
export function WeatherLayer({ stations, metric, selectedAbbr, onSelect }: WeatherLayerProps) {
|
||||
const map = useMap();
|
||||
useMapAttribution(DATA_ATTRIBUTION);
|
||||
const markersRef = useRef<Map<string, L.Marker>>(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
|
||||
? '<span class="weather-rain" title="Regen in der letzten Stunde">💧</span>'
|
||||
: '';
|
||||
const unit = metric === 'precipitation' ? 'mm' : metric === 'wind' ? 'km/h' : '';
|
||||
return (
|
||||
arrow +
|
||||
`<div class="weather-badge${selected ? ' selected' : ''}" style="background:${color}">` +
|
||||
`<strong>${escapeHtml(stationLabel(station, metric))}</strong>${unit ? `<small>${unit}</small>` : ''}</div>` +
|
||||
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 (
|
||||
`<span class="weather-arrow" style="transform:translate(-50%, -50%) rotate(${fromDegrees + 180}deg)">` +
|
||||
`<svg viewBox="0 0 14 ${height}" width="14" height="${height}">` +
|
||||
`<path d="M7 ${length} L7 ${head}" stroke="#0f172a" stroke-width="2.5"/>` +
|
||||
`<path d="M1 ${head + 1} L7 0 L13 ${head + 1} Z" fill="#0f172a"/></svg></span>`
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
`<strong>${escapeHtml(station.name)}</strong> · ${station.heightMasl ?? '–'} m<br/>` +
|
||||
`<span class="muted">MeteoSchweiz, Stand ${formatTime(station.time)}</span>${rows.join('')}`
|
||||
);
|
||||
}
|
||||
|
||||
function row(label: string, value: string): string {
|
||||
return `<div class="tooltip-row">${label}<span class="tooltip-value">${value}</span></div>`;
|
||||
}
|
||||
38
client/src/components/weather/WeatherLegend.tsx
Normal file
38
client/src/components/weather/WeatherLegend.tsx
Normal file
|
|
@ -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 (
|
||||
<div className="legend category-legend">
|
||||
<div className="dimension-tabs" role="tablist" aria-label="Wetterstationen zeigen">
|
||||
{WEATHER_METRICS.map((m) => (
|
||||
<button
|
||||
key={m.key}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={m.key === metric}
|
||||
className={m.key === metric ? 'active' : ''}
|
||||
onClick={() => onMetricChange(m.key)}
|
||||
>
|
||||
{m.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="category-chips">
|
||||
{legendFor(metric).map((item) => (
|
||||
<span key={item.label} className="legend-item">
|
||||
<span className="legend-dot small" style={{ background: item.color }} />
|
||||
{item.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<span className="legend-note">
|
||||
Pfeil zeigt, wohin der Wind weht (zehnminütiges Mittel); 💧 = Regen in der letzten Stunde
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
208
client/src/components/weather/WeatherStationPanel.tsx
Normal file
208
client/src/components/weather/WeatherStationPanel.tsx
Normal file
|
|
@ -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<MixedType, (number | null)[], string> = {
|
||||
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<MixedType> = {
|
||||
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 (
|
||||
<aside className="station-panel">
|
||||
<header className="station-panel-header">
|
||||
<div>
|
||||
<h2>{station.name}</h2>
|
||||
<p>
|
||||
Wetterstation {station.abbr} · {station.heightMasl ?? '–'} m ü. M. · Stand{' '}
|
||||
{formatTime(station.time)}
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" className="close-button" onClick={onClose} aria-label="Schliessen">
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<section className="stat-tiles">
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">
|
||||
{station.temperature === null ? '–' : `${formatDecimal(station.temperature, 1)} °C`}
|
||||
</span>
|
||||
<span className="stat-tile-label">
|
||||
Lufttemperatur
|
||||
{station.temperatureMin24h !== null &&
|
||||
` · 24 h: ${formatDecimal(station.temperatureMin24h, 1)} bis ${formatDecimal(station.temperatureMax24h, 1)} °C`}
|
||||
</span>
|
||||
</div>
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">
|
||||
{station.precipitation24h === null
|
||||
? '–'
|
||||
: `${formatDecimal(station.precipitation24h, 1)} mm`}
|
||||
</span>
|
||||
<span className="stat-tile-label">
|
||||
Niederschlag 24 h
|
||||
{station.precipitation1h !== null &&
|
||||
` · letzte Stunde ${formatDecimal(station.precipitation1h, 1)} mm`}
|
||||
</span>
|
||||
</div>
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">
|
||||
{station.windSpeed === null ? '–' : `${Math.round(station.windSpeed)} km/h`}
|
||||
</span>
|
||||
<span className="stat-tile-label">
|
||||
Wind aus {compassDirection(station.windDirection)}
|
||||
{station.windGust !== null && ` · Böen ${Math.round(station.windGust)} km/h`}
|
||||
{station.windGustMax24h !== null &&
|
||||
` · max. ${Math.round(station.windGustMax24h)} in 24 h`}
|
||||
</span>
|
||||
</div>
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">
|
||||
{station.sunshine24h === null ? '–' : `${Math.round(station.sunshine24h)} min`}
|
||||
</span>
|
||||
<span className="stat-tile-label">
|
||||
Sonnenschein 24 h
|
||||
{station.humidity !== null && ` · Feuchte ${Math.round(station.humidity)} %`}
|
||||
{station.pressure !== null && ` · ${formatDecimal(station.pressure, 0)} hPa`}
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>{chartTitle}</h3>
|
||||
{hourly.length > 1 ? (
|
||||
<div className="chart">
|
||||
<Chart<MixedType, (number | null)[], string> type="bar" options={options} data={data} />
|
||||
</div>
|
||||
) : (
|
||||
<p className="panel-note">Noch zu wenige Messwerte für einen Verlauf.</p>
|
||||
)}
|
||||
{!hasTemperature && (
|
||||
<p className="panel-note">
|
||||
Diese Station misst keine Temperatur und keinen Niederschlag.
|
||||
</p>
|
||||
)}
|
||||
<p className="panel-note">
|
||||
Zehnminutenwerte von MeteoSchweiz (SwissMetNet), im Diagramm zu Stunden zusammengefasst.
|
||||
</p>
|
||||
</section>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
|
@ -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<LayerKey> {
|
||||
|
|
@ -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}
|
||||
/>
|
||||
</MemoMunicipalityPanel>
|
||||
);
|
||||
|
|
@ -240,6 +266,14 @@ export function ThurgauCombinedPage() {
|
|||
onClose={clearSelection}
|
||||
/>
|
||||
);
|
||||
} else if (selectedWeatherStation) {
|
||||
panel = (
|
||||
<WeatherStationPanel
|
||||
station={selectedWeatherStation}
|
||||
lastRefresh={weather.meta?.lastRefresh ?? null}
|
||||
onClose={clearSelection}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
panel = (
|
||||
<OverviewPanel
|
||||
|
|
@ -262,6 +296,7 @@ export function ThurgauCombinedPage() {
|
|||
: null
|
||||
}
|
||||
hydrology={showWater ? { stations: hydrology.stations } : null}
|
||||
weather={showWeather ? { stations: weather.stations } : null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -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() {
|
|||
<span className="title-separator">/</span> Thurgau – alle Daten
|
||||
</h1>
|
||||
<span className="subtitle">
|
||||
Fahrzeugbestand, Wasserfahrzeuge, Strassenverkehr und Gewässer auf einer Karte
|
||||
Fahrzeugbestand, Wasserfahrzeuge, Strassenverkehr, Gewässer und Wetter auf einer Karte
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -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 && (
|
||||
<WeatherLayer
|
||||
stations={weather.stations}
|
||||
metric={weather.metric}
|
||||
selectedAbbr={visibleSelection?.layer === 'wetter' ? visibleSelection.abbr : null}
|
||||
onSelect={selectWeatherStation}
|
||||
/>
|
||||
)}
|
||||
</MapHost>
|
||||
|
||||
<LayerPanel>
|
||||
|
|
@ -455,6 +504,20 @@ export function ThurgauCombinedPage() {
|
|||
>
|
||||
<HydrologyLegend metric={hydrology.metric} onMetricChange={hydrology.setMetric} />
|
||||
</LayerCard>
|
||||
<LayerCard
|
||||
title="Wetter (live)"
|
||||
subtitle="SwissMetNet-Stationen · alle 10 Minuten"
|
||||
color="#eab308"
|
||||
active={showWeather}
|
||||
note={
|
||||
weather.latestTime
|
||||
? `Stand ${formatTime(weather.latestTime)}; unabhängig von Jahr und Verkehrstag.`
|
||||
: null
|
||||
}
|
||||
onToggle={() => toggleLayer('wetter')}
|
||||
>
|
||||
<WeatherLegend metric={weather.metric} onMetricChange={weather.setMetric} />
|
||||
</LayerCard>
|
||||
</LayerPanel>
|
||||
|
||||
<div className="overlay-bottom">
|
||||
|
|
@ -539,6 +602,17 @@ export function ThurgauCombinedPage() {
|
|||
·{' '}
|
||||
</>
|
||||
)}
|
||||
{weather.meta && (
|
||||
<>
|
||||
<DatasetCredit
|
||||
title={weather.meta.title}
|
||||
publisher={weather.meta.publisher}
|
||||
url={weather.meta.sourceUrl}
|
||||
license={weather.meta.license}
|
||||
/>{' '}
|
||||
·{' '}
|
||||
</>
|
||||
)}
|
||||
Karten, Gemeindegrenzen und Strassennetz © swisstopo · Bearbeitung: Werte pro Gemeinde,
|
||||
Standort und Zählstelle aggregiert, Zuordnung zu Gemeinden über die Lage
|
||||
</footer>
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
150
client/src/weather/format.ts
Normal file
150
client/src/weather/format.ts
Normal file
|
|
@ -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<number, WeatherHistoryPoint[]>();
|
||||
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,
|
||||
};
|
||||
});
|
||||
}
|
||||
41
client/src/weather/useWeatherData.ts
Normal file
41
client/src/weather/useWeatherData.ts
Normal file
|
|
@ -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<WeatherMetric>('temperature');
|
||||
|
||||
const stations = useMemo(() => stationsQuery.data ?? [], [stationsQuery.data]);
|
||||
const latestTime = useMemo(
|
||||
() =>
|
||||
stations.reduce<string | null>(
|
||||
(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,
|
||||
};
|
||||
}
|
||||
|
|
@ -16,6 +16,7 @@ flowchart LR
|
|||
end
|
||||
|
||||
lindas["LINDAS (BAFU)<br/>Abfluss und Pegel"]
|
||||
smn["data.geo.admin.ch<br/>MeteoSchweiz SwissMetNet"]
|
||||
|
||||
subgraph geo["swisstopo API"]
|
||||
tlm["swissTLM3D Strassen<br/>+ SearchServer"]
|
||||
|
|
@ -29,10 +30,11 @@ flowchart LR
|
|||
wr["WatercraftRefresher<br/>täglich"]
|
||||
vr["VehicleRefresher<br/>täglich"]
|
||||
hr["HydrologyRefresher<br/>alle 10 min"]
|
||||
we["WeatherRefresher<br/>alle 10 min"]
|
||||
end
|
||||
|
||||
cache[("JSON-Cache<br/>{DataPath}/…")]
|
||||
api["/api/traffic<br/>/api/watercraft<br/>/api/vehicles<br/>/api/hydrology"]
|
||||
api["/api/traffic<br/>/api/watercraft<br/>/api/vehicles<br/>/api/hydrology<br/>/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<br/>Bootsstandorte pro Jahr"] --> page
|
||||
t["/api/traffic<br/>Zählstellen pro Stunde"] --> page
|
||||
h["/api/hydrology<br/>Gewässer live"] --> page
|
||||
we["/api/weather<br/>Wetter live"] --> page
|
||||
page["Kombinierte Karte<br/>/karte/thurgau"] --> assign["Zuordnung im Browser:<br/>Zählstelle in Gemeindegrenze,<br/>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.
|
||||
|
|
|
|||
39
docs/datasets/wetter.md
Normal file
39
docs/datasets/wetter.md
Normal file
|
|
@ -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<br/>jede Minute"] --> R{"letzter Abruf<br/>älter als 10 min?"}
|
||||
R -- ja --> M{"Stationsliste<br/>älter als 1 Tag?"}
|
||||
M -- ja --> ST["ogd-smn_meta_stations.csv"] --> C
|
||||
M -- nein --> C{"Cache deckt 6 Tage ab<br/>und ohne Lücke?"}
|
||||
C -- nein --> H["{abbr}_t_recent.csv<br/>letzte 7 Tage"] --> N
|
||||
C -- ja --> N["{abbr}_t_now.csv"]
|
||||
N --> D[("days/yyyy-MM-dd.json")]
|
||||
D --> P["Tage älter als<br/>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).
|
||||
Loading…
Reference in a new issue