Add live water layer from BAFU hydrology data #6
48 changed files with 2109 additions and 29 deletions
29
CLAUDE.md
29
CLAUDE.md
|
|
@ -32,19 +32,21 @@ There is no lint step besides `tsc` (strict, no unused locals/parameters). `dotn
|
|||
|
||||
## Architecture
|
||||
|
||||
Visualizes open data from opendata.swiss. Three datasets so far, all from the canton of Thurgau on data.tg.ch:
|
||||
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:
|
||||
|
||||
- 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
|
||||
|
||||
| Project | Role |
|
||||
|---|---|
|
||||
| `Schaad.OpenData.Traffic` | Fetching, JSON cache, road geometry, analysis — everything except HTTP hosting |
|
||||
| `Schaad.OpenData.Watercraft` | Watercraft: catalog lookup, JSON cache, aggregation per location |
|
||||
| `Schaad.OpenData.Vehicles` | Vehicle stock: dataset fetch, municipality boundaries, JSON cache, aggregation per municipality |
|
||||
| `Schaad.OpenData.Server` | Minimal API (`/api/traffic/*` in `Traffic/TrafficEndpoints.cs`, `/api/watercraft/*` in `Watercraft/WatercraftEndpoints.cs`, `/api/vehicles/*` in `Vehicles/VehicleEndpoints.cs`), serves the built client from `wwwroot` with SPA fallback |
|
||||
| `Schaad.OpenData.Tests` | Tests for the Traffic, Watercraft and Vehicles libraries |
|
||||
| `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 |
|
||||
| `client/` | React SPA: Leaflet map with animated traffic, Chart.js station charts |
|
||||
|
||||
### Data flow
|
||||
|
|
@ -60,7 +62,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` and `Vehicles` in `appsettings.json` (`Traffic__DataPath`, `Watercraft__DataPath` and `Vehicles__DataPath` 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` 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.
|
||||
|
||||
### Road geometry (for the direction animation)
|
||||
|
||||
|
|
@ -103,11 +105,26 @@ VehicleRefreshService (BackgroundService, checks every 30 min, refreshes daily)
|
|||
|
||||
Brand counts only include the group `Personenwagen`, with `Andere` always last. When the outline processing changes, bump `OutlinesFileName` in `VehicleCacheStorage`.
|
||||
|
||||
### Hydrology
|
||||
|
||||
```
|
||||
HydrologyRefreshService (BackgroundService, checks every minute, refreshes every 10 min)
|
||||
→ HydrologyRefresher
|
||||
→ LindasHydroClient.FetchAsync one SPARQL POST to lindas.admin.ch/query, stations matched by IRI …/foen/hydro/station/{id} (the id is an integer literal)
|
||||
→ HydrodatenPlotClient backfill from hydrodaten.admin.ch 7-day plot JSON (undocumented) when a station has < 6 days or a > 45 min gap, max once per hour per station; 10-minute marks only, LINDAS values win
|
||||
→ HydrologySnapshot.With readings deduplicated by station and time, older than HistoryDays dropped
|
||||
→ HydrologyCacheStorage {DataPath}/hydrology/thurgau/{meta.json, stations.json, days/yyyy-MM-dd.json}, old day files deleted
|
||||
→ HydrologyDataStore
|
||||
→ HydrologyAnalysis latest value per station plus level change and discharge 24 h earlier (reading within ±1 h), history per station
|
||||
```
|
||||
|
||||
Stations default to `HydrologyOptions.DefaultStationIds` (Thurgau and the Thur catchment) unless `Hydrology:StationIds` is set. Lake vs river comes from the observation IRI; the `isLiter` flag is `true` everywhere and ignored.
|
||||
|
||||
### Client
|
||||
|
||||
- Routing with `react-router-dom`: `/` is the start page (`pages/HomePage.tsx`) with one large tile per entry in `src/maps.ts`. Only the combined map has a tile; the single maps are reached through the "Einzelkarte" links in its layer cards. Each map has its own page (`/verkehr/thurgau` → `pages/TrafficThurgauPage.tsx`, `/schifffahrt/thurgau?jahr=2023` → `pages/WatercraftThurgauPage.tsx`, `/fahrzeuge/thurgau?jahr=2025` → `pages/VehiclesThurgauPage.tsx`, `/karte/thurgau?ebenen=fahrzeuge,boote,verkehr&jahr=2025` → `pages/ThurgauCombinedPage.tsx`). A new map needs a route in `App.tsx` and a layer card on the combined page; only a new standalone map needs an entry in `src/maps.ts` (with a preview image in `public/previews/`). Deep links work because the server falls back to `index.html`.
|
||||
- `map/MapHost.tsx` owns the single Leaflet map (base layers, resize, the `odv-areas` pane at z-index 350 below the default overlay pane) and provides it via `map/mapContext.ts` (`useMap`, `useMapAttribution`). Each dataset is a layer component that renders `null` and attaches to that map: `components/TrafficLayer.tsx`, `components/watercraft/WatercraftLayer.tsx`, `components/vehicles/VehicleLayer.tsx`. Layers add their data credit to the attribution control themselves and remove everything they added on unmount, so several can share one map. Data loading and per-dataset UI state live in hooks (`traffic/useTrafficData.ts`, `watercraft/useWatercraftData.ts`, `vehicles/useVehicleData.ts`, plus `map/useYearPlayback.ts` for the `jahr` param and year playback), used by both the single pages and the combined page.
|
||||
- Combined page: one `MapHost` with the three layers toggled from `components/combined/LayerPanel.tsx` / `LayerCard.tsx`; the year list is the union of the active yearly layers. The side panel shows the selected municipality, location or station, otherwise `OverviewPanel`. The municipality panel adds `MunicipalityContext` (stations and harbours assigned with `map/geometry.ts` `assignToOutlines`).
|
||||
- Combined page: one `MapHost` with the layers toggled from `components/combined/LayerPanel.tsx` / `LayerCard.tsx`; the year list is the union of the active yearly layers. The side panel shows the selected municipality, location or station, otherwise `OverviewPanel`. The municipality panel adds `MunicipalityContext` (stations and harbours assigned with `map/geometry.ts` `assignToOutlines`).
|
||||
- `traffic/flowAnimator.ts` owns the animation clock (time of day in hours, play/pause, speed) and draws on a canvas above Leaflet's overlay pane. Dots spawn per direction at a rate proportional to the interpolated hourly count, colored and sized by vehicle group, offset to the right of the driving direction. It reports the time to React at ~10 Hz via `onTick`; React components only get the integer hour, so markers and charts don't re-render every frame.
|
||||
- The vehicle class order in `traffic/vehicleClasses.ts` must match the `VehicleClass` enum / `VehicleCounts.ToArray()` order; count arrays in the API are positional.
|
||||
- Watercraft page: `components/watercraft/WatercraftLayer.tsx` draws one SVG donut per location (area ∝ boats, segments by the selected dimension); markers are created once and resized in place, so year changes animate via CSS. `watercraft/categories.ts` folds categories into at most six coloured groups plus grey `Übrige` and grey "absent" groups; legend chips hide groups, which shrinks the donuts. The panel shows the canton or the selected location for the selected year plus a stacked trend over all years.
|
||||
|
|
@ -118,6 +135,6 @@ Brand counts only include the group `Personenwagen`, with `Andere` always last.
|
|||
|
||||
- **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`) 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`) 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).
|
||||
|
|
|
|||
|
|
@ -14,11 +14,13 @@ COPY Schaad.OpenData.Server/Schaad.OpenData.Server.csproj Schaad.OpenData.Server
|
|||
COPY Schaad.OpenData.Traffic/Schaad.OpenData.Traffic.csproj Schaad.OpenData.Traffic/
|
||||
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/
|
||||
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 --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
|
||||
|
||||
|
|
@ -31,7 +33,8 @@ USER $APP_UID
|
|||
ENV ASPNETCORE_HTTP_PORTS=8080 \
|
||||
Traffic__DataPath=/app/data \
|
||||
Watercraft__DataPath=/app/data \
|
||||
Vehicles__DataPath=/app/data
|
||||
Vehicles__DataPath=/app/data \
|
||||
Hydrology__DataPath=/app/data
|
||||
VOLUME /app/data
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["dotnet", "Schaad.OpenData.Server.dll"]
|
||||
|
|
|
|||
|
|
@ -13,6 +13,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Schaad.OpenData.Watercraft"
|
|||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Schaad.OpenData.Vehicles", "Schaad.OpenData.Vehicles\Schaad.OpenData.Vehicles.csproj", "{CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Schaad.OpenData.Hydrology", "Schaad.OpenData.Hydrology\Schaad.OpenData.Hydrology.csproj", "{165B08D9-D777-4D3D-8341-093A30F60B63}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
|
|
@ -83,6 +85,18 @@ Global
|
|||
{CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Release|x64.Build.0 = Release|Any CPU
|
||||
{CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{CD0AFF9C-EADC-4B2F-9A84-F65C34AF10A1}.Release|x86.Build.0 = Release|Any CPU
|
||||
{165B08D9-D777-4D3D-8341-093A30F60B63}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{165B08D9-D777-4D3D-8341-093A30F60B63}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{165B08D9-D777-4D3D-8341-093A30F60B63}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{165B08D9-D777-4D3D-8341-093A30F60B63}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{165B08D9-D777-4D3D-8341-093A30F60B63}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{165B08D9-D777-4D3D-8341-093A30F60B63}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{165B08D9-D777-4D3D-8341-093A30F60B63}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{165B08D9-D777-4D3D-8341-093A30F60B63}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{165B08D9-D777-4D3D-8341-093A30F60B63}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{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
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
|
|
|||
3
Schaad.OpenData.Hydrology/Analysis/HistoryPoint.cs
Normal file
3
Schaad.OpenData.Hydrology/Analysis/HistoryPoint.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Hydrology.Analysis;
|
||||
|
||||
public sealed record HistoryPoint(DateTimeOffset Time, double? WaterLevel, double? Discharge, double? WaterTemperature);
|
||||
49
Schaad.OpenData.Hydrology/Analysis/HydrologyAnalysis.cs
Normal file
49
Schaad.OpenData.Hydrology/Analysis/HydrologyAnalysis.cs
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
using Schaad.OpenData.Hydrology.Models;
|
||||
using Schaad.OpenData.Hydrology.Storage;
|
||||
|
||||
namespace Schaad.OpenData.Hydrology.Analysis;
|
||||
|
||||
public static class HydrologyAnalysis
|
||||
{
|
||||
private static readonly TimeSpan CompareTolerance = TimeSpan.FromHours(1);
|
||||
|
||||
public static IReadOnlyList<StationView> BuildStations(HydrologySnapshot snapshot)
|
||||
{
|
||||
var byStation = snapshot.Readings.ToLookup(r => r.StationId);
|
||||
return snapshot.Stations
|
||||
.Select(station => ToView(station, byStation[station.Id].ToList()))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public static IReadOnlyList<HistoryPoint> BuildHistory(HydrologySnapshot snapshot, string stationId, DateTimeOffset from) =>
|
||||
snapshot.Readings
|
||||
.Where(r => r.StationId == stationId && r.Time >= from)
|
||||
.Select(r => new HistoryPoint(r.Time, r.WaterLevel, r.Discharge, r.WaterTemperature))
|
||||
.ToList();
|
||||
|
||||
private static StationView ToView(HydroStation station, IReadOnlyList<HydroReading> readings)
|
||||
{
|
||||
var latest = readings.Count > 0 ? readings[^1] : null;
|
||||
var dayBefore = latest is null ? null : Closest(readings, latest.Time.AddDays(-1));
|
||||
return new StationView(
|
||||
station.Id,
|
||||
station.Name,
|
||||
station.WaterBody,
|
||||
station.Kind,
|
||||
station.Lat,
|
||||
station.Lon,
|
||||
latest?.Time,
|
||||
latest?.WaterLevel,
|
||||
latest?.Discharge,
|
||||
latest?.WaterTemperature,
|
||||
latest?.DangerLevel,
|
||||
latest?.WaterLevel - dayBefore?.WaterLevel,
|
||||
dayBefore?.Discharge,
|
||||
readings.Count > 0 ? readings[0].Time : null);
|
||||
}
|
||||
|
||||
private static HydroReading? Closest(IReadOnlyList<HydroReading> readings, DateTimeOffset target) =>
|
||||
readings
|
||||
.Where(r => (r.Time - target).Duration() <= CompareTolerance)
|
||||
.MinBy(r => (r.Time - target).Duration());
|
||||
}
|
||||
19
Schaad.OpenData.Hydrology/Analysis/StationView.cs
Normal file
19
Schaad.OpenData.Hydrology/Analysis/StationView.cs
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
using Schaad.OpenData.Hydrology.Models;
|
||||
|
||||
namespace Schaad.OpenData.Hydrology.Analysis;
|
||||
|
||||
public sealed record StationView(
|
||||
string Id,
|
||||
string Name,
|
||||
string WaterBody,
|
||||
HydroStationKind Kind,
|
||||
double Lat,
|
||||
double Lon,
|
||||
DateTimeOffset? Time,
|
||||
double? WaterLevel,
|
||||
double? Discharge,
|
||||
double? WaterTemperature,
|
||||
int? DangerLevel,
|
||||
double? WaterLevelChange24h,
|
||||
double? Discharge24hAgo,
|
||||
DateTimeOffset? HistoryFrom);
|
||||
23
Schaad.OpenData.Hydrology/HydrologyOptions.cs
Normal file
23
Schaad.OpenData.Hydrology/HydrologyOptions.cs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
namespace Schaad.OpenData.Hydrology;
|
||||
|
||||
public sealed class HydrologyOptions
|
||||
{
|
||||
public const string SectionName = "Hydrology";
|
||||
|
||||
public static readonly IReadOnlyList<string> DefaultStationIds =
|
||||
["2032", "2043", "2181", "2044", "2303", "2386", "2126", "2312", "2468"];
|
||||
|
||||
public string DataPath { get; set; } = "data";
|
||||
|
||||
public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromMinutes(10);
|
||||
|
||||
public int HistoryDays { get; set; } = 60;
|
||||
|
||||
public string SparqlUrl { get; set; } = "https://lindas.admin.ch/query";
|
||||
|
||||
public string PlotsUrl { get; set; } = "https://www.hydrodaten.admin.ch/plots";
|
||||
|
||||
public string[] StationIds { get; set; } = [];
|
||||
|
||||
public IReadOnlyList<string> EffectiveStationIds => StationIds.Length > 0 ? StationIds : DefaultStationIds;
|
||||
}
|
||||
42
Schaad.OpenData.Hydrology/HydrologyRefreshService.cs
Normal file
42
Schaad.OpenData.Hydrology/HydrologyRefreshService.cs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Schaad.OpenData.Hydrology;
|
||||
|
||||
public sealed class HydrologyRefreshService(
|
||||
HydrologyRefresher refresher,
|
||||
IOptions<HydrologyOptions> options,
|
||||
ILogger<HydrologyRefreshService> 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 hydrology 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, "Hydrology refresh failed");
|
||||
}
|
||||
|
||||
await Task.Delay(CheckInterval, stoppingToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
102
Schaad.OpenData.Hydrology/HydrologyRefresher.cs
Normal file
102
Schaad.OpenData.Hydrology/HydrologyRefresher.cs
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Schaad.OpenData.Hydrology.Models;
|
||||
using Schaad.OpenData.Hydrology.Source;
|
||||
using Schaad.OpenData.Hydrology.Storage;
|
||||
|
||||
namespace Schaad.OpenData.Hydrology;
|
||||
|
||||
public class HydrologyRefresher(
|
||||
LindasHydroClient client,
|
||||
HydrodatenPlotClient plotClient,
|
||||
HydrologyCacheStorage storage,
|
||||
HydrologyDataStore store,
|
||||
IOptions<HydrologyOptions> options,
|
||||
TimeProvider timeProvider,
|
||||
ILogger<HydrologyRefresher> logger)
|
||||
{
|
||||
private static readonly TimeSpan RequiredCoverage = TimeSpan.FromDays(6);
|
||||
private static readonly TimeSpan MaxGap = TimeSpan.FromMinutes(45);
|
||||
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 hydrology 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 measurements = await client.FetchAsync(options.Value.EffectiveStationIds.ToList(), cancellationToken);
|
||||
var backfilled = await BackfillAsync(current, measurements.Stations, now, cancellationToken);
|
||||
var combined = new HydroMeasurements(
|
||||
measurements.Stations,
|
||||
current.NewReadings(backfilled).Concat(measurements.Readings).ToList());
|
||||
|
||||
var added = current.NewReadings(combined.Readings);
|
||||
var firstKeptDay = DateOnly.FromDateTime(now.UtcDateTime).AddDays(-options.Value.HistoryDays);
|
||||
var keepFrom = new DateTimeOffset(firstKeptDay.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
|
||||
|
||||
var updated = current.With(combined, now, 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 {Stations} hydrology stations, {Added} new readings ({Backfilled} from hydrodaten.admin.ch)",
|
||||
measurements.Stations.Count,
|
||||
added.Count,
|
||||
backfilled.Count);
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<HydroReading>> BackfillAsync(
|
||||
HydrologySnapshot current,
|
||||
IReadOnlyList<HydroStation> stations,
|
||||
DateTimeOffset now,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var byStation = current.Readings.ToLookup(r => r.StationId);
|
||||
var readings = new List<HydroReading>();
|
||||
foreach (var station in stations)
|
||||
{
|
||||
if (!NeedsBackfill(byStation[station.Id].ToList(), now)
|
||||
|| (lastBackfill.TryGetValue(station.Id, out var last) && now - last < BackfillRetry))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
lastBackfill[station.Id] = now;
|
||||
try
|
||||
{
|
||||
readings.AddRange(await plotClient.FetchRecentAsync(station.Id, cancellationToken));
|
||||
}
|
||||
catch (Exception exception) when (exception is HttpRequestException or System.Text.Json.JsonException or TaskCanceledException
|
||||
&& !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
logger.LogWarning(exception, "Could not backfill hydrology station {Station}", station.Id);
|
||||
}
|
||||
}
|
||||
|
||||
return readings;
|
||||
}
|
||||
|
||||
private static bool NeedsBackfill(IReadOnlyList<HydroReading> readings, DateTimeOffset now) =>
|
||||
readings.Count == 0
|
||||
|| readings[0].Time > now - RequiredCoverage
|
||||
|| readings[^1].Time < now - MaxGap;
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Schaad.OpenData.Hydrology.Source;
|
||||
using Schaad.OpenData.Hydrology.Storage;
|
||||
|
||||
namespace Schaad.OpenData.Hydrology;
|
||||
|
||||
public static class HydrologyServiceCollectionExtensions
|
||||
{
|
||||
private const string UserAgent = "OpenDataVisualizer/1.0";
|
||||
|
||||
public static IServiceCollection AddHydrology(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.Configure<HydrologyOptions>(configuration.GetSection(HydrologyOptions.SectionName));
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
services.AddSingleton<HydrologyDataStore>();
|
||||
services.AddSingleton<HydrologyCacheStorage>();
|
||||
services.AddSingleton<HydrologyRefresher>();
|
||||
services.AddHostedService<HydrologyRefreshService>();
|
||||
|
||||
services.AddHttpClient<LindasHydroClient>(client =>
|
||||
{
|
||||
client.Timeout = TimeSpan.FromMinutes(1);
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
|
||||
});
|
||||
services.AddHttpClient<HydrodatenPlotClient>(client =>
|
||||
{
|
||||
client.Timeout = TimeSpan.FromMinutes(1);
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
3
Schaad.OpenData.Hydrology/Models/HydroMeasurements.cs
Normal file
3
Schaad.OpenData.Hydrology/Models/HydroMeasurements.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Hydrology.Models;
|
||||
|
||||
public sealed record HydroMeasurements(IReadOnlyList<HydroStation> Stations, IReadOnlyList<HydroReading> Readings);
|
||||
9
Schaad.OpenData.Hydrology/Models/HydroReading.cs
Normal file
9
Schaad.OpenData.Hydrology/Models/HydroReading.cs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
namespace Schaad.OpenData.Hydrology.Models;
|
||||
|
||||
public sealed record HydroReading(
|
||||
string StationId,
|
||||
DateTimeOffset Time,
|
||||
double? WaterLevel,
|
||||
double? Discharge,
|
||||
double? WaterTemperature,
|
||||
int? DangerLevel);
|
||||
3
Schaad.OpenData.Hydrology/Models/HydroStation.cs
Normal file
3
Schaad.OpenData.Hydrology/Models/HydroStation.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Hydrology.Models;
|
||||
|
||||
public sealed record HydroStation(string Id, string Name, string WaterBody, HydroStationKind Kind, double Lat, double Lon);
|
||||
10
Schaad.OpenData.Hydrology/Models/HydroStationKind.cs
Normal file
10
Schaad.OpenData.Hydrology/Models/HydroStationKind.cs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Schaad.OpenData.Hydrology.Models;
|
||||
|
||||
[JsonConverter(typeof(JsonStringEnumConverter<HydroStationKind>))]
|
||||
public enum HydroStationKind
|
||||
{
|
||||
River,
|
||||
Lake,
|
||||
}
|
||||
15
Schaad.OpenData.Hydrology/Schaad.OpenData.Hydrology.csproj
Normal file
15
Schaad.OpenData.Hydrology/Schaad.OpenData.Hydrology.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>
|
||||
88
Schaad.OpenData.Hydrology/Source/HydrodatenPlotClient.cs
Normal file
88
Schaad.OpenData.Hydrology/Source/HydrodatenPlotClient.cs
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Schaad.OpenData.Hydrology.Models;
|
||||
|
||||
namespace Schaad.OpenData.Hydrology.Source;
|
||||
|
||||
public class HydrodatenPlotClient(HttpClient httpClient, IOptions<HydrologyOptions> options)
|
||||
{
|
||||
private const string LevelTrace = "Wasserstand";
|
||||
private const string DischargeTrace = "Abfluss";
|
||||
private const string TemperatureTrace = "Temperatur";
|
||||
private const int StepMinutes = 10;
|
||||
|
||||
public virtual async Task<IReadOnlyList<HydroReading>> FetchRecentAsync(string stationId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (stationId.Length == 0 || !stationId.All(char.IsAsciiDigit))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var baseUrl = options.Value.PlotsUrl.TrimEnd('/');
|
||||
var levels = await ReadTracesAsync($"{baseUrl}/p_q_7days/{stationId}_p_q_7days_de.json", cancellationToken);
|
||||
var temperatures = await ReadTracesAsync($"{baseUrl}/temperature_7days/{stationId}_temperature_7days_de.json", cancellationToken);
|
||||
|
||||
var level = levels.GetValueOrDefault(LevelTrace) ?? [];
|
||||
var discharge = levels.GetValueOrDefault(DischargeTrace) ?? [];
|
||||
var temperature = temperatures.GetValueOrDefault(TemperatureTrace) ?? [];
|
||||
|
||||
return level.Keys
|
||||
.Concat(discharge.Keys)
|
||||
.Concat(temperature.Keys)
|
||||
.Distinct()
|
||||
.Order()
|
||||
.Select(time => new HydroReading(
|
||||
stationId,
|
||||
time,
|
||||
level.GetValueOrDefault(time),
|
||||
discharge.GetValueOrDefault(time),
|
||||
temperature.GetValueOrDefault(time),
|
||||
null))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private async Task<Dictionary<string, Dictionary<DateTimeOffset, double?>>> ReadTracesAsync(string url, CancellationToken cancellationToken)
|
||||
{
|
||||
var traces = new Dictionary<string, Dictionary<DateTimeOffset, double?>>();
|
||||
using var response = await httpClient.GetAsync(url, cancellationToken);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
return traces;
|
||||
}
|
||||
|
||||
response.EnsureSuccessStatusCode();
|
||||
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
|
||||
using var document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken);
|
||||
if (!document.RootElement.TryGetProperty("plot", out var plot) || !plot.TryGetProperty("data", out var data))
|
||||
{
|
||||
return traces;
|
||||
}
|
||||
|
||||
foreach (var trace in data.EnumerateArray())
|
||||
{
|
||||
if (!trace.TryGetProperty("name", out var name) || name.GetString() is not { } traceName
|
||||
|| !trace.TryGetProperty("x", out var xs) || !trace.TryGetProperty("y", out var ys))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var values = new Dictionary<DateTimeOffset, double?>();
|
||||
foreach (var (x, y) in xs.EnumerateArray().Zip(ys.EnumerateArray()))
|
||||
{
|
||||
if (x.GetString() is { } text
|
||||
&& DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out var time)
|
||||
&& time.Minute % StepMinutes == 0
|
||||
&& y.ValueKind == JsonValueKind.Number)
|
||||
{
|
||||
values[time] = y.GetDouble();
|
||||
}
|
||||
}
|
||||
|
||||
traces[traceName] = values;
|
||||
}
|
||||
|
||||
return traces;
|
||||
}
|
||||
}
|
||||
104
Schaad.OpenData.Hydrology/Source/LindasHydroClient.cs
Normal file
104
Schaad.OpenData.Hydrology/Source/LindasHydroClient.cs
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
using System.Globalization;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Schaad.OpenData.Hydrology.Models;
|
||||
|
||||
namespace Schaad.OpenData.Hydrology.Source;
|
||||
|
||||
public partial class LindasHydroClient(HttpClient httpClient, IOptions<HydrologyOptions> options)
|
||||
{
|
||||
private const string StationBaseUri = "https://environment.ld.admin.ch/foen/hydro/station/";
|
||||
|
||||
private const string QueryTemplate = """
|
||||
PREFIX schema: <http://schema.org/>
|
||||
PREFIX geo: <http://www.opengis.net/ont/geosparql#>
|
||||
PREFIX h: <https://environment.ld.admin.ch/foen/hydro/dimension/>
|
||||
SELECT ?obs ?id ?name ?water ?wkt ?time ?level ?discharge ?temperature ?danger WHERE {
|
||||
VALUES ?station { {stations} }
|
||||
?station schema:identifier ?id ;
|
||||
schema:name ?name ;
|
||||
schema:containedInPlace/schema:name ?water ;
|
||||
geo:hasGeometry/geo:asWKT ?wkt .
|
||||
GRAPH <https://lindas.admin.ch/foen/hydro> {
|
||||
?obs h:station ?station ;
|
||||
h:measurementTime ?time .
|
||||
OPTIONAL { ?obs h:waterLevel ?level }
|
||||
OPTIONAL { ?obs h:discharge ?discharge }
|
||||
OPTIONAL { ?obs h:waterTemperature ?temperature }
|
||||
OPTIONAL { ?obs h:dangerLevel ?danger }
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
public virtual async Task<HydroMeasurements> FetchAsync(IReadOnlyCollection<string> stationIds, CancellationToken cancellationToken)
|
||||
{
|
||||
var stations = string.Join(
|
||||
" ",
|
||||
stationIds.Where(id => id.Length > 0 && id.All(char.IsAsciiDigit)).Select(id => $"<{StationBaseUri}{id}>"));
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, options.Value.SparqlUrl)
|
||||
{
|
||||
Content = new FormUrlEncodedContent([new KeyValuePair<string, string>("query", QueryTemplate.Replace("{stations}", stations))]),
|
||||
};
|
||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/sparql-results+json"));
|
||||
|
||||
using var response = await httpClient.SendAsync(request, cancellationToken);
|
||||
response.EnsureSuccessStatusCode();
|
||||
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
|
||||
using var document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken);
|
||||
|
||||
var found = new Dictionary<string, HydroStation>();
|
||||
var readings = new List<HydroReading>();
|
||||
foreach (var binding in document.RootElement.GetProperty("results").GetProperty("bindings").EnumerateArray())
|
||||
{
|
||||
var id = Text(binding, "id");
|
||||
var time = Text(binding, "time");
|
||||
if (id is null || time is null || ParsePoint(Text(binding, "wkt")) is not { } point)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var kind = Text(binding, "obs")?.Contains("/lake/", StringComparison.Ordinal) == true
|
||||
? HydroStationKind.Lake
|
||||
: HydroStationKind.River;
|
||||
found[id] = new HydroStation(
|
||||
id,
|
||||
Text(binding, "name")?.Trim() ?? id,
|
||||
Text(binding, "water")?.Trim() ?? string.Empty,
|
||||
kind,
|
||||
point.Lat,
|
||||
point.Lon);
|
||||
readings.Add(new HydroReading(
|
||||
id,
|
||||
DateTimeOffset.Parse(time, CultureInfo.InvariantCulture),
|
||||
Number(binding, "level"),
|
||||
kind == HydroStationKind.River ? Number(binding, "discharge") : null,
|
||||
Number(binding, "temperature"),
|
||||
Number(binding, "danger") is { } danger ? (int)danger : null));
|
||||
}
|
||||
|
||||
return new HydroMeasurements(found.Values.OrderBy(s => s.Id, StringComparer.Ordinal).ToList(), readings);
|
||||
}
|
||||
|
||||
private static string? Text(JsonElement binding, string name) =>
|
||||
binding.TryGetProperty(name, out var value) && value.TryGetProperty("value", out var text) ? text.GetString() : null;
|
||||
|
||||
private static double? Number(JsonElement binding, string name) =>
|
||||
double.TryParse(Text(binding, name), NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? value : null;
|
||||
|
||||
private static (double Lat, double Lon)? ParsePoint(string? wkt)
|
||||
{
|
||||
if (wkt is null || PointPattern().Match(wkt) is not { Success: true } match)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
double.Parse(match.Groups["lat"].Value, CultureInfo.InvariantCulture),
|
||||
double.Parse(match.Groups["lon"].Value, CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"POINT\s*\(\s*(?<lon>-?[\d.]+)\s+(?<lat>-?[\d.]+)\s*\)")]
|
||||
private static partial Regex PointPattern();
|
||||
}
|
||||
3
Schaad.OpenData.Hydrology/Storage/HydrologyCacheMeta.cs
Normal file
3
Schaad.OpenData.Hydrology/Storage/HydrologyCacheMeta.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
namespace Schaad.OpenData.Hydrology.Storage;
|
||||
|
||||
public sealed record HydrologyCacheMeta(DateTimeOffset? LastRefresh);
|
||||
88
Schaad.OpenData.Hydrology/Storage/HydrologyCacheStorage.cs
Normal file
88
Schaad.OpenData.Hydrology/Storage/HydrologyCacheStorage.cs
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Schaad.OpenData.Hydrology.Models;
|
||||
|
||||
namespace Schaad.OpenData.Hydrology.Storage;
|
||||
|
||||
public class HydrologyCacheStorage(IOptions<HydrologyOptions> 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), "hydrology", "thurgau");
|
||||
|
||||
private string DaysPath => Path.Combine(RootPath, "days");
|
||||
|
||||
public virtual async Task<HydrologySnapshot> LoadAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var meta = await ReadAsync<HydrologyCacheMeta>(Path.Combine(RootPath, "meta.json"), cancellationToken);
|
||||
var stations = await ReadAsync<List<HydroStation>>(Path.Combine(RootPath, "stations.json"), cancellationToken) ?? [];
|
||||
var readings = new List<HydroReading>();
|
||||
if (Directory.Exists(DaysPath))
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(DaysPath, "*.json").Order(StringComparer.Ordinal))
|
||||
{
|
||||
readings.AddRange(await ReadAsync<List<HydroReading>>(file, cancellationToken) ?? []);
|
||||
}
|
||||
}
|
||||
|
||||
return new HydrologySnapshot(stations, readings, meta?.LastRefresh);
|
||||
}
|
||||
|
||||
public virtual async Task SaveAsync(HydrologySnapshot 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 HydrologyCacheMeta(snapshot.LastRefresh), 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.Hydrology/Storage/HydrologyDataStore.cs
Normal file
10
Schaad.OpenData.Hydrology/Storage/HydrologyDataStore.cs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
namespace Schaad.OpenData.Hydrology.Storage;
|
||||
|
||||
public sealed class HydrologyDataStore
|
||||
{
|
||||
private volatile HydrologySnapshot current = HydrologySnapshot.Empty;
|
||||
|
||||
public HydrologySnapshot Current => current;
|
||||
|
||||
public void Replace(HydrologySnapshot snapshot) => current = snapshot;
|
||||
}
|
||||
42
Schaad.OpenData.Hydrology/Storage/HydrologySnapshot.cs
Normal file
42
Schaad.OpenData.Hydrology/Storage/HydrologySnapshot.cs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
using Schaad.OpenData.Hydrology.Models;
|
||||
|
||||
namespace Schaad.OpenData.Hydrology.Storage;
|
||||
|
||||
public sealed class HydrologySnapshot
|
||||
{
|
||||
public static readonly HydrologySnapshot Empty = new([], [], null);
|
||||
|
||||
public HydrologySnapshot(IEnumerable<HydroStation> stations, IEnumerable<HydroReading> readings, DateTimeOffset? lastRefresh)
|
||||
{
|
||||
Stations = stations
|
||||
.GroupBy(s => s.Id)
|
||||
.Select(g => g.Last())
|
||||
.OrderBy(s => s.Id, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
Readings = readings
|
||||
.GroupBy(r => (r.StationId, r.Time))
|
||||
.Select(g => g.Last())
|
||||
.OrderBy(r => r.Time)
|
||||
.ThenBy(r => r.StationId, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
LastRefresh = lastRefresh;
|
||||
}
|
||||
|
||||
public IReadOnlyList<HydroStation> Stations { get; }
|
||||
|
||||
public IReadOnlyList<HydroReading> Readings { get; }
|
||||
|
||||
public DateTimeOffset? LastRefresh { get; }
|
||||
|
||||
public HydrologySnapshot With(HydroMeasurements measurements, DateTimeOffset lastRefresh, DateTimeOffset keepFrom) =>
|
||||
new(
|
||||
Stations.Concat(measurements.Stations),
|
||||
Readings.Concat(measurements.Readings).Where(r => r.Time >= keepFrom),
|
||||
lastRefresh);
|
||||
|
||||
public IReadOnlyList<HydroReading> NewReadings(IEnumerable<HydroReading> readings)
|
||||
{
|
||||
var known = Readings.Select(r => (r.StationId, r.Time)).ToHashSet();
|
||||
return readings.Where(r => !known.Contains((r.StationId, r.Time))).ToList();
|
||||
}
|
||||
}
|
||||
46
Schaad.OpenData.Server/Hydrology/HydrologyEndpoints.cs
Normal file
46
Schaad.OpenData.Server/Hydrology/HydrologyEndpoints.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
using Microsoft.Extensions.Options;
|
||||
using Schaad.OpenData.Hydrology;
|
||||
using Schaad.OpenData.Hydrology.Analysis;
|
||||
using Schaad.OpenData.Hydrology.Storage;
|
||||
|
||||
namespace Schaad.OpenData.Server.Hydrology;
|
||||
|
||||
public static class HydrologyEndpoints
|
||||
{
|
||||
private const int DefaultHistoryDays = 7;
|
||||
|
||||
public static IEndpointRouteBuilder MapHydrologyEndpoints(this IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
var group = endpoints.MapGroup("/api/hydrology");
|
||||
|
||||
group.MapGet("/meta", (HydrologyDataStore store, IOptions<HydrologyOptions> options) =>
|
||||
new HydrologyMetaResponse(
|
||||
"Hydrologische Daten: aktuelle Messwerte von Flüssen und Seen",
|
||||
"Bundesamt für Umwelt BAFU",
|
||||
"https://www.hydrodaten.admin.ch/",
|
||||
"opendata.swiss BY",
|
||||
options.Value.HistoryDays,
|
||||
store.Current.LastRefresh));
|
||||
|
||||
group.MapGet("/stations", (HydrologyDataStore store) => HydrologyAnalysis.BuildStations(store.Current));
|
||||
|
||||
group.MapGet("/stations/{id}/history", (
|
||||
string id,
|
||||
int? tage,
|
||||
HydrologyDataStore store,
|
||||
IOptions<HydrologyOptions> options,
|
||||
TimeProvider timeProvider) =>
|
||||
{
|
||||
var snapshot = store.Current;
|
||||
if (snapshot.Stations.All(s => s.Id != id))
|
||||
{
|
||||
return Results.NotFound();
|
||||
}
|
||||
|
||||
var days = Math.Clamp(tage ?? DefaultHistoryDays, 1, options.Value.HistoryDays);
|
||||
return Results.Ok(HydrologyAnalysis.BuildHistory(snapshot, id, timeProvider.GetUtcNow().AddDays(-days)));
|
||||
});
|
||||
|
||||
return endpoints;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
namespace Schaad.OpenData.Server.Hydrology;
|
||||
|
||||
public sealed record HydrologyMetaResponse(
|
||||
string Title,
|
||||
string Publisher,
|
||||
string SourceUrl,
|
||||
string License,
|
||||
int HistoryDays,
|
||||
DateTimeOffset? LastRefresh);
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
using Schaad.OpenData.Hydrology;
|
||||
using Schaad.OpenData.Server.Hydrology;
|
||||
using Schaad.OpenData.Server.Traffic;
|
||||
using Schaad.OpenData.Server.Vehicles;
|
||||
using Schaad.OpenData.Server.Watercraft;
|
||||
|
|
@ -10,6 +12,7 @@ var builder = WebApplication.CreateBuilder(args);
|
|||
builder.Services.AddTraffic(builder.Configuration);
|
||||
builder.Services.AddWatercraft(builder.Configuration);
|
||||
builder.Services.AddVehicles(builder.Configuration);
|
||||
builder.Services.AddHydrology(builder.Configuration);
|
||||
builder.Services.AddResponseCompression(options => options.EnableForHttps = true);
|
||||
|
||||
var app = builder.Build();
|
||||
|
|
@ -20,6 +23,7 @@ app.UseStaticFiles();
|
|||
app.MapTrafficEndpoints();
|
||||
app.MapWatercraftEndpoints();
|
||||
app.MapVehicleEndpoints();
|
||||
app.MapHydrologyEndpoints();
|
||||
app.MapFallbackToFile("index.html");
|
||||
|
||||
app.Run();
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Schaad.OpenData.Hydrology\Schaad.OpenData.Hydrology.csproj" />
|
||||
<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" />
|
||||
|
|
|
|||
|
|
@ -18,5 +18,10 @@
|
|||
"Vehicles": {
|
||||
"DataPath": "../data",
|
||||
"RefreshInterval": "1.00:00:00"
|
||||
},
|
||||
"Hydrology": {
|
||||
"DataPath": "../data",
|
||||
"RefreshInterval": "00:10:00",
|
||||
"HistoryDays": 60
|
||||
}
|
||||
}
|
||||
|
|
|
|||
82
Schaad.OpenData.Tests/HydrodatenPlotClientTestShould.cs
Normal file
82
Schaad.OpenData.Tests/HydrodatenPlotClientTestShould.cs
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
using System.Net;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Schaad.OpenData.Hydrology;
|
||||
using Schaad.OpenData.Hydrology.Models;
|
||||
using Schaad.OpenData.Hydrology.Source;
|
||||
|
||||
namespace Schaad.OpenData.Tests;
|
||||
|
||||
public class HydrodatenPlotClientTestShould
|
||||
{
|
||||
private sealed class StubHandler(Dictionary<string, string> 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 StringContent(body, Encoding.UTF8, "application/json") }
|
||||
: new HttpResponseMessage(HttpStatusCode.NotFound));
|
||||
}
|
||||
}
|
||||
|
||||
private const string LevelUrl = "https://hydro.example/plots/p_q_7days/2181_p_q_7days_de.json";
|
||||
private const string TemperatureUrl = "https://hydro.example/plots/temperature_7days/2181_temperature_7days_de.json";
|
||||
|
||||
private const string LevelPlot = """
|
||||
{"plot":{"layout":{},"data":[
|
||||
{"name":"Wasserstand","type":"scatter","x":["2026-11-12T00:00:00.000+01:00","2026-11-12T00:05:00.000+01:00","2026-11-12T00:10:00.000+01:00"],"y":[455.835,455.839,455.843]},
|
||||
{"name":"Abfluss","type":"scatter","x":["2026-11-12T00:00:00.000+01:00","2026-11-12T00:05:00.000+01:00","2026-11-12T00:10:00.000+01:00"],"y":[28.243,28.576,null]}
|
||||
]},"hoverInfo":{}}
|
||||
""";
|
||||
|
||||
private const string TemperaturePlot = """
|
||||
{"plot":{"layout":{},"data":[
|
||||
{"name":"Temperatur","type":"scatter","x":["2026-11-12T00:00:00.000+01:00","2026-11-12T00:20:00.000+01:00"],"y":[10.37,10.36]}
|
||||
]},"hoverInfo":{}}
|
||||
""";
|
||||
|
||||
private static HydrodatenPlotClient Client(StubHandler handler) =>
|
||||
new(new HttpClient(handler), Options.Create(new HydrologyOptions { PlotsUrl = "https://hydro.example/plots/" }));
|
||||
|
||||
[Fact]
|
||||
public async Task CombineTracesOnTenMinuteMarksWhenFetchingRecentValues()
|
||||
{
|
||||
var handler = new StubHandler(new() { [LevelUrl] = LevelPlot, [TemperatureUrl] = TemperaturePlot });
|
||||
|
||||
var readings = await Client(handler).FetchRecentAsync("2181", CancellationToken.None);
|
||||
|
||||
var offset = TimeSpan.FromHours(1);
|
||||
readings.ShouldBe([
|
||||
new HydroReading("2181", new DateTimeOffset(2026, 11, 12, 0, 0, 0, offset), 455.835, 28.243, 10.37, null),
|
||||
new HydroReading("2181", new DateTimeOffset(2026, 11, 12, 0, 10, 0, offset), 455.843, null, null, null),
|
||||
new HydroReading("2181", new DateTimeOffset(2026, 11, 12, 0, 20, 0, offset), null, null, 10.36, null),
|
||||
]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReturnLevelsOnlyWhenTemperaturePlotIsMissing()
|
||||
{
|
||||
var handler = new StubHandler(new() { [LevelUrl] = LevelPlot });
|
||||
|
||||
var readings = await Client(handler).FetchRecentAsync("2181", CancellationToken.None);
|
||||
|
||||
readings.Count.ShouldBe(2);
|
||||
readings.ShouldAllBe(r => r.WaterTemperature == null);
|
||||
handler.Requests.ShouldBe([LevelUrl, TemperatureUrl]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SkipRequestWhenStationIdIsNotNumeric()
|
||||
{
|
||||
var handler = new StubHandler([]);
|
||||
|
||||
var readings = await Client(handler).FetchRecentAsync("../2181", CancellationToken.None);
|
||||
|
||||
readings.ShouldBeEmpty();
|
||||
handler.Requests.ShouldBeEmpty();
|
||||
}
|
||||
}
|
||||
59
Schaad.OpenData.Tests/HydrologyAnalysisTestShould.cs
Normal file
59
Schaad.OpenData.Tests/HydrologyAnalysisTestShould.cs
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
using Schaad.OpenData.Hydrology.Analysis;
|
||||
using Schaad.OpenData.Hydrology.Storage;
|
||||
using static Schaad.OpenData.Tests.HydrologyTestData;
|
||||
|
||||
namespace Schaad.OpenData.Tests;
|
||||
|
||||
public class HydrologyAnalysisTestShould
|
||||
{
|
||||
[Fact]
|
||||
public void ReturnLatestValuesAndChangeOverOneDayWhenBuildingStations()
|
||||
{
|
||||
var snapshot = new HydrologySnapshot(
|
||||
[River(), Lake()],
|
||||
[
|
||||
Reading("2181", Now.AddDays(-2), discharge: 30),
|
||||
Reading("2181", Now.AddDays(-1).AddMinutes(20), level: 455.5, discharge: 40),
|
||||
Reading("2181", Now.AddMinutes(-10), level: 455.9, discharge: 43),
|
||||
Reading("2181", Now, level: 456.0, discharge: 44.5),
|
||||
],
|
||||
Now);
|
||||
|
||||
var stations = HydrologyAnalysis.BuildStations(snapshot);
|
||||
|
||||
stations.Select(s => s.Id).ShouldBe(["2032", "2181"]);
|
||||
var lake = stations[0];
|
||||
lake.Time.ShouldBeNull();
|
||||
lake.WaterLevelChange24h.ShouldBeNull();
|
||||
var river = stations[1];
|
||||
river.Time.ShouldBe(Now);
|
||||
river.Discharge.ShouldBe(44.5);
|
||||
river.Discharge24hAgo.ShouldBe(40);
|
||||
river.WaterLevelChange24h!.Value.ShouldBe(0.5, 1e-9);
|
||||
river.HistoryFrom.ShouldBe(Now.AddDays(-2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LeaveChangeEmptyWhenNoReadingNearOneDayAgo()
|
||||
{
|
||||
var snapshot = new HydrologySnapshot([River()], [Reading("2181", Now.AddHours(-3)), Reading("2181", Now)], Now);
|
||||
|
||||
var river = HydrologyAnalysis.BuildStations(snapshot).ShouldHaveSingleItem();
|
||||
|
||||
river.WaterLevelChange24h.ShouldBeNull();
|
||||
river.Discharge24hAgo.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReturnReadingsOfStationSinceStartWhenBuildingHistory()
|
||||
{
|
||||
var snapshot = new HydrologySnapshot(
|
||||
[River(), Lake()],
|
||||
[Reading("2181", Now.AddDays(-8)), Reading("2181", Now.AddDays(-1), discharge: 40), Reading("2032", Now)],
|
||||
Now);
|
||||
|
||||
var history = HydrologyAnalysis.BuildHistory(snapshot, "2181", Now.AddDays(-7));
|
||||
|
||||
history.ShouldBe([new HistoryPoint(Now.AddDays(-1), 456.0, 40, 9.1)]);
|
||||
}
|
||||
}
|
||||
74
Schaad.OpenData.Tests/HydrologyCacheStorageTestShould.cs
Normal file
74
Schaad.OpenData.Tests/HydrologyCacheStorageTestShould.cs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
using Microsoft.Extensions.Options;
|
||||
using Schaad.OpenData.Hydrology;
|
||||
using Schaad.OpenData.Hydrology.Storage;
|
||||
using static Schaad.OpenData.Tests.HydrologyTestData;
|
||||
|
||||
namespace Schaad.OpenData.Tests;
|
||||
|
||||
public sealed class HydrologyCacheStorageTestShould : IDisposable
|
||||
{
|
||||
private readonly string dataPath = Path.Combine(Path.GetTempPath(), "odv-tests-" + Guid.NewGuid().ToString("N"));
|
||||
private readonly HydrologyCacheStorage storage;
|
||||
|
||||
public HydrologyCacheStorageTestShould()
|
||||
{
|
||||
storage = new HydrologyCacheStorage(Options.Create(new HydrologyOptions { DataPath = dataPath }));
|
||||
}
|
||||
|
||||
private string DaysPath => Path.Combine(dataPath, "hydrology", "thurgau", "days");
|
||||
|
||||
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.LastRefresh.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RestoreStationsAndReadingsWhenLoading()
|
||||
{
|
||||
var yesterday = Reading("2181", Now.AddDays(-1), discharge: 40.2);
|
||||
var today = Reading("2032", Now, level: 394.876, discharge: null, temperature: null, danger: null);
|
||||
var snapshot = new HydrologySnapshot([River(), Lake()], [yesterday, today], Now);
|
||||
|
||||
await storage.SaveAsync(snapshot, [DateOnly.FromDateTime(Now.UtcDateTime.AddDays(-1)), DateOnly.FromDateTime(Now.UtcDateTime)], CancellationToken.None);
|
||||
var loaded = await storage.LoadAsync(CancellationToken.None);
|
||||
|
||||
loaded.Stations.ShouldBe([Lake(), River()]);
|
||||
loaded.Readings.ShouldBe([yesterday, today]);
|
||||
loaded.LastRefresh.ShouldBe(Now);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WriteOnlyChangedDaysWhenSaving()
|
||||
{
|
||||
var snapshot = new HydrologySnapshot([River()], [Reading("2181", Now.AddDays(-1)), Reading("2181", Now)], Now);
|
||||
|
||||
await storage.SaveAsync(snapshot, [new DateOnly(2026, 11, 18)], CancellationToken.None);
|
||||
|
||||
Directory.GetFiles(DaysPath).Select(Path.GetFileName).ShouldBe(["2026-11-18.json"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteOnlyOlderDayFilesWhenPruning()
|
||||
{
|
||||
var snapshot = new HydrologySnapshot([River()], [Reading("2181", Now.AddDays(-2)), Reading("2181", Now)], Now);
|
||||
await storage.SaveAsync(snapshot, [new DateOnly(2026, 11, 16), new DateOnly(2026, 11, 18)], CancellationToken.None);
|
||||
File.WriteAllText(Path.Combine(DaysPath, "notes.json"), "[]");
|
||||
|
||||
storage.DeleteDaysBefore(new DateOnly(2026, 11, 17));
|
||||
|
||||
Directory.GetFiles(DaysPath).Select(Path.GetFileName).Order().ShouldBe(["2026-11-18.json", "notes.json"]);
|
||||
}
|
||||
}
|
||||
124
Schaad.OpenData.Tests/HydrologyRefresherTestShould.cs
Normal file
124
Schaad.OpenData.Tests/HydrologyRefresherTestShould.cs
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using NSubstitute.ExceptionExtensions;
|
||||
using Schaad.OpenData.Hydrology;
|
||||
using Schaad.OpenData.Hydrology.Models;
|
||||
using Schaad.OpenData.Hydrology.Source;
|
||||
using Schaad.OpenData.Hydrology.Storage;
|
||||
using static Schaad.OpenData.Tests.HydrologyTestData;
|
||||
|
||||
namespace Schaad.OpenData.Tests;
|
||||
|
||||
public class HydrologyRefresherTestShould
|
||||
{
|
||||
private readonly HydrologyOptions settings = new() { HistoryDays = 60 };
|
||||
private readonly LindasHydroClient client;
|
||||
private readonly HydrodatenPlotClient plotClient;
|
||||
private readonly HydrologyCacheStorage storage;
|
||||
private readonly HydrologyDataStore store = new();
|
||||
private readonly TimeProvider timeProvider = Substitute.For<TimeProvider>();
|
||||
private readonly HydrologyRefresher refresher;
|
||||
|
||||
public HydrologyRefresherTestShould()
|
||||
{
|
||||
var options = Options.Create(settings);
|
||||
client = Substitute.For<LindasHydroClient>(new HttpClient(), options);
|
||||
plotClient = Substitute.For<HydrodatenPlotClient>(new HttpClient(), options);
|
||||
plotClient.FetchRecentAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns([]);
|
||||
storage = Substitute.For<HydrologyCacheStorage>(options);
|
||||
timeProvider.GetUtcNow().Returns(Now);
|
||||
refresher = new HydrologyRefresher(client, plotClient, storage, store, options, timeProvider, NullLogger<HydrologyRefresher>.Instance);
|
||||
}
|
||||
|
||||
private static HydrologySnapshot CoveredSnapshot(params HydroReading[] extra) =>
|
||||
new([River()], [Reading("2181", Now.AddDays(-7)), Reading("2181", Now.AddMinutes(-10)), .. extra], Now.AddMinutes(-10));
|
||||
|
||||
[Fact]
|
||||
public async Task FetchDefaultStationsAndSaveDaysOfNewReadingsWhenRefreshing()
|
||||
{
|
||||
store.Replace(CoveredSnapshot());
|
||||
client.FetchAsync(Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new HydroMeasurements([River()], [Reading("2181", Now)]));
|
||||
|
||||
await refresher.RefreshAsync(CancellationToken.None);
|
||||
|
||||
await client.Received(1).FetchAsync(
|
||||
Arg.Is<IReadOnlyCollection<string>>(ids => ids.SequenceEqual(HydrologyOptions.DefaultStationIds)),
|
||||
Arg.Any<CancellationToken>());
|
||||
store.Current.Readings.Count.ShouldBe(3);
|
||||
store.Current.LastRefresh.ShouldBe(Now);
|
||||
await storage.Received(1).SaveAsync(
|
||||
store.Current,
|
||||
Arg.Is<IReadOnlyCollection<DateOnly>>(days => days.SequenceEqual(new[] { new DateOnly(2026, 11, 18) })),
|
||||
Arg.Any<CancellationToken>());
|
||||
storage.Received(1).DeleteDaysBefore(new DateOnly(2026, 9, 19));
|
||||
await plotClient.DidNotReceive().FetchRecentAsync(Arg.Any<string>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UseConfiguredStationsWhenRefreshing()
|
||||
{
|
||||
settings.StationIds = ["2386"];
|
||||
client.FetchAsync(Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new HydroMeasurements([], []));
|
||||
|
||||
await refresher.RefreshAsync(CancellationToken.None);
|
||||
|
||||
await client.Received(1).FetchAsync(
|
||||
Arg.Is<IReadOnlyCollection<string>>(ids => ids.SequenceEqual(new[] { "2386" })),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BackfillRecentDaysAndKeepLiveValueWhenHistoryIsMissing()
|
||||
{
|
||||
client.FetchAsync(Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new HydroMeasurements([River()], [Reading("2181", Now, discharge: 44.5, danger: 2)]));
|
||||
plotClient.FetchRecentAsync("2181", Arg.Any<CancellationToken>())
|
||||
.Returns([Reading("2181", Now.AddDays(-6), danger: null), Reading("2181", Now, discharge: 44.4, danger: null)]);
|
||||
|
||||
await refresher.RefreshAsync(CancellationToken.None);
|
||||
|
||||
store.Current.Readings.Select(r => (r.Time, r.Discharge, r.DangerLevel))
|
||||
.ShouldBe([(Now.AddDays(-6), 44.5, (int?)null), (Now, 44.5, 2)]);
|
||||
await storage.Received(1).SaveAsync(
|
||||
store.Current,
|
||||
Arg.Is<IReadOnlyCollection<DateOnly>>(days => days.Order().SequenceEqual(new[] { new DateOnly(2026, 11, 12), new DateOnly(2026, 11, 18) })),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BackfillAfterGapButNotAgainWithinAnHourWhenRefreshing()
|
||||
{
|
||||
store.Replace(new HydrologySnapshot([River()], [Reading("2181", Now.AddDays(-7)), Reading("2181", Now.AddHours(-2))], null));
|
||||
client.FetchAsync(Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new HydroMeasurements([River()], []));
|
||||
|
||||
await refresher.RefreshAsync(CancellationToken.None);
|
||||
await refresher.RefreshAsync(CancellationToken.None);
|
||||
|
||||
await plotClient.Received(1).FetchRecentAsync("2181", Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task KeepRefreshingWhenBackfillFails()
|
||||
{
|
||||
client.FetchAsync(Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new HydroMeasurements([River()], [Reading("2181", Now)]));
|
||||
plotClient.FetchRecentAsync("2181", Arg.Any<CancellationToken>()).ThrowsAsync(new HttpRequestException("503"));
|
||||
|
||||
await refresher.RefreshAsync(CancellationToken.None);
|
||||
|
||||
store.Current.Readings.ShouldHaveSingleItem().Time.ShouldBe(Now);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequireRefreshWhenLastRefreshIsOlderThanInterval()
|
||||
{
|
||||
store.Replace(new HydrologySnapshot([], [], Now.AddMinutes(-11)));
|
||||
|
||||
refresher.IsRefreshDue(TimeSpan.FromMinutes(10)).ShouldBeTrue();
|
||||
refresher.IsRefreshDue(TimeSpan.FromMinutes(15)).ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
43
Schaad.OpenData.Tests/HydrologySnapshotTestShould.cs
Normal file
43
Schaad.OpenData.Tests/HydrologySnapshotTestShould.cs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
using Schaad.OpenData.Hydrology.Models;
|
||||
using Schaad.OpenData.Hydrology.Storage;
|
||||
using static Schaad.OpenData.Tests.HydrologyTestData;
|
||||
|
||||
namespace Schaad.OpenData.Tests;
|
||||
|
||||
public class HydrologySnapshotTestShould
|
||||
{
|
||||
[Fact]
|
||||
public void KeepOneReadingPerStationAndTimeWhenMerging()
|
||||
{
|
||||
var snapshot = new HydrologySnapshot([River()], [Reading("2181", Now.AddMinutes(-10), level: 455.9)], null);
|
||||
var measurements = new HydroMeasurements(
|
||||
[River(name: "Halden neu")],
|
||||
[Reading("2181", Now.AddMinutes(-10), level: 456.1), Reading("2181", Now)]);
|
||||
|
||||
var merged = snapshot.With(measurements, Now, Now.AddDays(-60));
|
||||
|
||||
merged.Stations.ShouldHaveSingleItem().Name.ShouldBe("Halden neu");
|
||||
merged.Readings.Select(r => (r.Time, r.WaterLevel)).ShouldBe([(Now.AddMinutes(-10), 456.1), (Now, 456.0)]);
|
||||
merged.LastRefresh.ShouldBe(Now);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DropReadingsBeforeRetentionWhenMerging()
|
||||
{
|
||||
var snapshot = new HydrologySnapshot([River()], [Reading("2181", Now.AddDays(-61)), Reading("2181", Now.AddDays(-1))], null);
|
||||
|
||||
var merged = snapshot.With(new HydroMeasurements([], []), Now, Now.AddDays(-60));
|
||||
|
||||
merged.Readings.ShouldHaveSingleItem().Time.ShouldBe(Now.AddDays(-1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReturnOnlyUnknownReadingsWhenComparing()
|
||||
{
|
||||
var snapshot = new HydrologySnapshot([River()], [Reading("2181", Now.AddMinutes(-10))], null);
|
||||
|
||||
var added = snapshot.NewReadings([Reading("2181", Now.AddMinutes(-10)), Reading("2181", Now), Reading("2032", Now)]);
|
||||
|
||||
added.Select(r => (r.StationId, r.Time)).ShouldBe([("2181", Now), ("2032", Now)]);
|
||||
}
|
||||
}
|
||||
23
Schaad.OpenData.Tests/HydrologyTestData.cs
Normal file
23
Schaad.OpenData.Tests/HydrologyTestData.cs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
using Schaad.OpenData.Hydrology.Models;
|
||||
|
||||
namespace Schaad.OpenData.Tests;
|
||||
|
||||
internal static class HydrologyTestData
|
||||
{
|
||||
public static readonly DateTimeOffset Now = new(2026, 11, 18, 19, 0, 0, TimeSpan.Zero);
|
||||
|
||||
public static HydroStation River(string id = "2181", string name = "Halden") =>
|
||||
new(id, name, "Thur", HydroStationKind.River, 47.5, 9.2);
|
||||
|
||||
public static HydroStation Lake(string id = "2032", string name = "Romanshorn") =>
|
||||
new(id, name, "Bodensee, Obersee", HydroStationKind.Lake, 47.56, 9.38);
|
||||
|
||||
public static HydroReading Reading(
|
||||
string stationId,
|
||||
DateTimeOffset time,
|
||||
double? level = 456.0,
|
||||
double? discharge = 44.5,
|
||||
double? temperature = 9.1,
|
||||
int? danger = 1) =>
|
||||
new(stationId, time, level, discharge, temperature, danger);
|
||||
}
|
||||
87
Schaad.OpenData.Tests/LindasHydroClientTestShould.cs
Normal file
87
Schaad.OpenData.Tests/LindasHydroClientTestShould.cs
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
using System.Net;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Schaad.OpenData.Hydrology;
|
||||
using Schaad.OpenData.Hydrology.Models;
|
||||
using Schaad.OpenData.Hydrology.Source;
|
||||
|
||||
namespace Schaad.OpenData.Tests;
|
||||
|
||||
public class LindasHydroClientTestShould
|
||||
{
|
||||
private sealed class StubHandler(string body) : HttpMessageHandler
|
||||
{
|
||||
public List<(Uri Uri, string Body, string Accept)> Requests { get; } = [];
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var content = request.Content is null ? string.Empty : await request.Content.ReadAsStringAsync(cancellationToken);
|
||||
Requests.Add((request.RequestUri!, content, request.Headers.Accept.ToString()));
|
||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
||||
{
|
||||
Content = new StringContent(body, Encoding.UTF8, "application/sparql-results+json"),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private const string Response = """
|
||||
{"head":{"vars":["obs","id","name","water","wkt","time","level","discharge","temperature","danger"]},
|
||||
"results":{"bindings":[
|
||||
{"obs":{"type":"uri","value":"https://environment.ld.admin.ch/foen/hydro/lake/observation/2032"},
|
||||
"id":{"type":"literal","value":"2032"},"name":{"type":"literal","value":"Romanshorn"},
|
||||
"water":{"type":"literal","value":"Bodensee, Obersee"},
|
||||
"wkt":{"type":"literal","value":"POINT(9.380992701081867 47.56479123049356)"},
|
||||
"time":{"type":"literal","value":"2026-11-18T20:00:00+01:00"},
|
||||
"level":{"type":"literal","value":"394.876"},
|
||||
"danger":{"type":"literal","value":"1"}},
|
||||
{"obs":{"type":"uri","value":"https://environment.ld.admin.ch/foen/hydro/river/observation/2044"},
|
||||
"id":{"type":"literal","value":"2044"},"name":{"type":"literal","value":"Andelfingen "},
|
||||
"water":{"type":"literal","value":"Thur"},
|
||||
"wkt":{"type":"literal","value":"POINT(8.68 47.6)"},
|
||||
"time":{"type":"literal","value":"2026-11-18T20:00:00+01:00"},
|
||||
"level":{"type":"literal","value":"355.126"},"discharge":{"type":"literal","value":"36.103"},
|
||||
"temperature":{"type":"literal","value":"9.6"},
|
||||
"danger":{"type":"uri","value":"https://cube.link/Undefined"}},
|
||||
{"obs":{"type":"uri","value":"https://environment.ld.admin.ch/foen/hydro/river/observation/9999"},
|
||||
"id":{"type":"literal","value":"9999"},"name":{"type":"literal","value":"Ohne Lage"},
|
||||
"time":{"type":"literal","value":"2026-11-18T20:00:00+01:00"}}
|
||||
]}}
|
||||
""";
|
||||
|
||||
private static LindasHydroClient Client(StubHandler handler) =>
|
||||
new(new HttpClient(handler), Options.Create(new HydrologyOptions { SparqlUrl = "https://lindas.example/query" }));
|
||||
|
||||
[Fact]
|
||||
public async Task MapStationsAndReadingsWhenFetching()
|
||||
{
|
||||
var handler = new StubHandler(Response);
|
||||
|
||||
var result = await Client(handler).FetchAsync(["2032", "2044"], CancellationToken.None);
|
||||
|
||||
result.Stations.ShouldBe([
|
||||
new HydroStation("2032", "Romanshorn", "Bodensee, Obersee", HydroStationKind.Lake, 47.56479123049356, 9.380992701081867),
|
||||
new HydroStation("2044", "Andelfingen", "Thur", HydroStationKind.River, 47.6, 8.68),
|
||||
]);
|
||||
var time = new DateTimeOffset(2026, 11, 18, 20, 0, 0, TimeSpan.FromHours(1));
|
||||
result.Readings.ShouldBe([
|
||||
new HydroReading("2032", time, 394.876, null, null, 1),
|
||||
new HydroReading("2044", time, 355.126, 36.103, 9.6, null),
|
||||
]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestOnlyNumericStationIdsAsJsonWhenFetching()
|
||||
{
|
||||
var handler = new StubHandler(Response);
|
||||
|
||||
await Client(handler).FetchAsync(["2032", "20\"44", "abc"], CancellationToken.None);
|
||||
|
||||
var request = handler.Requests.ShouldHaveSingleItem();
|
||||
request.Uri.AbsoluteUri.ShouldBe("https://lindas.example/query");
|
||||
request.Accept.ShouldBe("application/sparql-results+json");
|
||||
var query = Uri.UnescapeDataString(request.Body.Replace('+', ' '));
|
||||
query.ShouldContain("VALUES ?station { <https://environment.ld.admin.ch/foen/hydro/station/2032> }");
|
||||
query.ShouldNotContain("abc");
|
||||
query.ShouldNotContain("20\"44");
|
||||
}
|
||||
}
|
||||
|
|
@ -19,6 +19,7 @@
|
|||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Schaad.OpenData.Hydrology\Schaad.OpenData.Hydrology.csproj" />
|
||||
<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" />
|
||||
|
|
|
|||
51
client/src/api/hydrology.ts
Normal file
51
client/src/api/hydrology.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
export type HydroStationKind = 'River' | 'Lake';
|
||||
|
||||
export interface HydrologyMeta {
|
||||
title: string;
|
||||
publisher: string;
|
||||
sourceUrl: string;
|
||||
license: string;
|
||||
historyDays: number;
|
||||
lastRefresh: string | null;
|
||||
}
|
||||
|
||||
export interface HydroStation {
|
||||
id: string;
|
||||
name: string;
|
||||
waterBody: string;
|
||||
kind: HydroStationKind;
|
||||
lat: number;
|
||||
lon: number;
|
||||
time: string | null;
|
||||
waterLevel: number | null;
|
||||
discharge: number | null;
|
||||
waterTemperature: number | null;
|
||||
dangerLevel: number | null;
|
||||
waterLevelChange24h: number | null;
|
||||
discharge24hAgo: number | null;
|
||||
historyFrom: string | null;
|
||||
}
|
||||
|
||||
export interface HydroHistoryPoint {
|
||||
time: string;
|
||||
waterLevel: number | null;
|
||||
discharge: number | null;
|
||||
waterTemperature: 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 fetchHydrologyMeta = () => getJson<HydrologyMeta>('/api/hydrology/meta');
|
||||
|
||||
export const fetchHydroStations = () => getJson<HydroStation[]>('/api/hydrology/stations');
|
||||
|
||||
export const fetchHydroHistory = (id: string, days: number) =>
|
||||
getJson<HydroHistoryPoint[]>(
|
||||
`/api/hydrology/stations/${encodeURIComponent(id)}/history?tage=${days}`,
|
||||
);
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
const LICENSE_URLS: Record<string, string> = {
|
||||
'CC BY 4.0': 'https://creativecommons.org/licenses/by/4.0/deed.de',
|
||||
'CC0 1.0': 'https://creativecommons.org/publicdomain/zero/1.0/deed.de',
|
||||
'OPENDATA.SWISS BY': 'https://opendata.swiss/de/terms-of-use#terms_by',
|
||||
};
|
||||
|
||||
interface DatasetCreditProps {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ interface LayerCardProps {
|
|||
subtitle: string;
|
||||
color: string;
|
||||
active: boolean;
|
||||
detailPath: string;
|
||||
detailPath?: string;
|
||||
note?: string | null;
|
||||
onToggle: () => void;
|
||||
children?: ReactNode;
|
||||
|
|
@ -33,9 +33,11 @@ export function LayerCard({
|
|||
<span className="layer-card-subtitle">{subtitle}</span>
|
||||
</span>
|
||||
</label>
|
||||
<Link to={detailPath} className="layer-card-link" title={`Einzelkarte ${title}`}>
|
||||
Einzelkarte
|
||||
</Link>
|
||||
{detailPath && (
|
||||
<Link to={detailPath} className="layer-card-link" title={`Einzelkarte ${title}`}>
|
||||
Einzelkarte
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
{active && note && <p className="layer-card-note">{note}</p>}
|
||||
{active && children && <div className="layer-card-body">{children}</div>}
|
||||
|
|
|
|||
|
|
@ -1,28 +1,34 @@
|
|||
import type { HydroStation } from '../../api/hydrology';
|
||||
import type { DayView, Station } from '../../api/traffic';
|
||||
import type { LocationSummary } from '../../api/watercraft';
|
||||
import { dischargeTrend, formatDecimal, formatDischarge } from '../../hydrology/format';
|
||||
import { formatNumber } from '../../traffic/format';
|
||||
import { sumCounts } from '../../traffic/vehicleClasses';
|
||||
|
||||
interface MunicipalityContextProps {
|
||||
stations: Station[] | null;
|
||||
locations: LocationSummary[] | null;
|
||||
hydroStations: HydroStation[] | null;
|
||||
day: DayView | null;
|
||||
hour: number;
|
||||
year: number;
|
||||
onSelectStation: (code: number) => void;
|
||||
onSelectLocation: (name: string) => void;
|
||||
onSelectHydroStation: (id: string) => void;
|
||||
}
|
||||
|
||||
export function MunicipalityContext({
|
||||
stations,
|
||||
locations,
|
||||
hydroStations,
|
||||
day,
|
||||
hour,
|
||||
year,
|
||||
onSelectStation,
|
||||
onSelectLocation,
|
||||
onSelectHydroStation,
|
||||
}: MunicipalityContextProps) {
|
||||
if (!stations && !locations) {
|
||||
if (!stations && !locations && !hydroStations) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
@ -76,6 +82,26 @@ export function MunicipalityContext({
|
|||
) : (
|
||||
<p className="panel-note">Kein Bootsstandort.</p>
|
||||
))}
|
||||
|
||||
{hydroStations && hydroStations.length > 0 && (
|
||||
<ul className="context-list">
|
||||
{hydroStations.map((station) => (
|
||||
<li key={station.id}>
|
||||
<button type="button" onClick={() => onSelectHydroStation(station.id)}>
|
||||
<span className="context-kind">Gewässer</span>
|
||||
<span className="context-name">
|
||||
{station.waterBody} – {station.name}
|
||||
</span>
|
||||
<span className="context-value">
|
||||
{station.kind === 'Lake'
|
||||
? `${formatDecimal(station.waterLevel, 2)} m ü. M.`
|
||||
: `${formatDischarge(station.discharge)} ${dischargeTrend(station)}`}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,13 @@
|
|||
import type { HydroStation } from '../../api/hydrology';
|
||||
import type { VehicleMeta, VehicleYearView } from '../../api/vehicles';
|
||||
import type { YearView } from '../../api/watercraft';
|
||||
import {
|
||||
dangerColor,
|
||||
dangerLabel,
|
||||
formatDecimal,
|
||||
formatLevelChange,
|
||||
formatTime,
|
||||
} from '../../hydrology/format';
|
||||
import { formatDate, formatNumber } from '../../traffic/format';
|
||||
import { metricValue } from '../../vehicles/metrics';
|
||||
|
||||
|
|
@ -14,9 +22,16 @@ interface OverviewPanelProps {
|
|||
hourTotal: number;
|
||||
firstDate: string | null;
|
||||
} | null;
|
||||
hydrology: { stations: HydroStation[] } | null;
|
||||
}
|
||||
|
||||
export function OverviewPanel({ year, vehicles, watercraft, traffic }: OverviewPanelProps) {
|
||||
export function OverviewPanel({
|
||||
year,
|
||||
vehicles,
|
||||
watercraft,
|
||||
traffic,
|
||||
hydrology,
|
||||
}: OverviewPanelProps) {
|
||||
const carIndex = vehicles?.meta.groups.indexOf('Personenwagen') ?? -1;
|
||||
const carDensity =
|
||||
vehicles?.view && carIndex >= 0
|
||||
|
|
@ -32,7 +47,7 @@ export function OverviewPanel({ year, vehicles, watercraft, traffic }: OverviewP
|
|||
</div>
|
||||
</header>
|
||||
|
||||
{!vehicles && !watercraft && !traffic && (
|
||||
{!vehicles && !watercraft && !traffic && !hydrology && (
|
||||
<p className="panel-note">Schalte links mindestens eine Ebene ein.</p>
|
||||
)}
|
||||
|
||||
|
|
@ -111,9 +126,51 @@ export function OverviewPanel({ year, vehicles, watercraft, traffic }: OverviewP
|
|||
</section>
|
||||
)}
|
||||
|
||||
{hydrology && <HydrologyOverview stations={hydrology.stations} />}
|
||||
|
||||
<p className="panel-note overview-hint">
|
||||
Klicke auf eine Gemeinde, einen Bootsstandort oder eine Zählstelle, um Details zu sehen.
|
||||
</p>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
function HydrologyOverview({ stations }: { stations: HydroStation[] }) {
|
||||
const lakes = stations.filter((s) => s.kind === 'Lake');
|
||||
const highest = stations.reduce<number | null>(
|
||||
(max, s) =>
|
||||
s.dangerLevel !== null && (max === null || s.dangerLevel > max) ? s.dangerLevel : max,
|
||||
null,
|
||||
);
|
||||
const latest = stations.reduce<string | null>(
|
||||
(value, s) => (s.time && (!value || s.time > value) ? s.time : value),
|
||||
null,
|
||||
);
|
||||
|
||||
return (
|
||||
<section>
|
||||
<h3>Gewässer, Stand {formatTime(latest)}</h3>
|
||||
<div className="stat-tiles">
|
||||
{lakes.map((lake) => (
|
||||
<div key={lake.id} className="stat-tile">
|
||||
<span className="stat-tile-value">{formatDecimal(lake.waterLevel, 2)} m</span>
|
||||
<span className="stat-tile-label">
|
||||
{lake.waterBody} ({lake.name})
|
||||
{lake.waterLevelChange24h !== null &&
|
||||
` · ${formatLevelChange(lake.waterLevelChange24h)} in 24 h`}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">
|
||||
<span className="legend-dot small" style={{ background: dangerColor(highest) }} />
|
||||
{highest ?? '–'}
|
||||
</span>
|
||||
<span className="stat-tile-label">
|
||||
Höchste Gefahrenstufe an {stations.length} Stationen: {dangerLabel(highest)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
197
client/src/components/hydrology/HydroStationPanel.tsx
Normal file
197
client/src/components/hydrology/HydroStationPanel.tsx
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import {
|
||||
CategoryScale,
|
||||
Chart as ChartJS,
|
||||
Legend,
|
||||
LinearScale,
|
||||
LineElement,
|
||||
PointElement,
|
||||
Tooltip,
|
||||
type ChartOptions,
|
||||
} from 'chart.js';
|
||||
import { Line } from 'react-chartjs-2';
|
||||
import { fetchHydroHistory, type HydroStation } from '../../api/hydrology';
|
||||
import {
|
||||
dangerColor,
|
||||
dangerLabel,
|
||||
dischargeTrend,
|
||||
formatDecimal,
|
||||
formatDischarge,
|
||||
formatLevelChange,
|
||||
formatTime,
|
||||
stationUrl,
|
||||
} from '../../hydrology/format';
|
||||
|
||||
ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Tooltip, Legend);
|
||||
|
||||
const HISTORY_DAYS = 7;
|
||||
const MAIN_COLOR = '#2a78d6';
|
||||
const TEMPERATURE_COLOR = '#eb6834';
|
||||
const GRID_COLOR = '#e2e8f0';
|
||||
|
||||
interface HydroStationPanelProps {
|
||||
station: HydroStation;
|
||||
lastRefresh: string | null;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function HydroStationPanel({ station, lastRefresh, onClose }: HydroStationPanelProps) {
|
||||
const historyQuery = useQuery({
|
||||
queryKey: ['hydrology-history', station.id, lastRefresh],
|
||||
queryFn: () => fetchHydroHistory(station.id, HISTORY_DAYS),
|
||||
staleTime: Infinity,
|
||||
});
|
||||
const history = historyQuery.data ?? [];
|
||||
const isLake = station.kind === 'Lake';
|
||||
const mainLabel = isLake ? 'Pegel (m ü. M.)' : 'Abfluss (m³/s)';
|
||||
const hasTemperature = history.some((p) => p.waterTemperature !== null);
|
||||
const firstTime = history[0]?.time;
|
||||
const coversFullRange =
|
||||
firstTime !== undefined &&
|
||||
Date.now() - new Date(firstTime).getTime() >= (HISTORY_DAYS - 1) * 24 * 3_600_000;
|
||||
const chartTitle =
|
||||
coversFullRange || firstTime === undefined
|
||||
? `Verlauf der letzten ${HISTORY_DAYS} Tage`
|
||||
: `Verlauf seit ${new Date(firstTime).toLocaleString('de-CH', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})}`;
|
||||
|
||||
const options: ChartOptions<'line'> = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
animation: false,
|
||||
interaction: { mode: 'index', intersect: false },
|
||||
spanGaps: true,
|
||||
elements: { point: { radius: 0 }, line: { borderWidth: 2, tension: 0.2 } },
|
||||
plugins: { legend: { position: 'bottom', labels: { boxWidth: 10, boxHeight: 10 } } },
|
||||
scales: {
|
||||
x: { grid: { display: false }, ticks: { maxTicksLimit: 7, autoSkip: true } },
|
||||
y: { grid: { color: GRID_COLOR }, title: { display: true, text: mainLabel } },
|
||||
...(hasTemperature
|
||||
? {
|
||||
y1: {
|
||||
position: 'right' as const,
|
||||
grid: { display: false },
|
||||
title: { display: true, text: '°C' },
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
};
|
||||
|
||||
const labels = history.map((p) =>
|
||||
new Date(p.time).toLocaleString('de-CH', {
|
||||
weekday: 'short',
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}),
|
||||
);
|
||||
|
||||
return (
|
||||
<aside className="station-panel">
|
||||
<header className="station-panel-header">
|
||||
<div>
|
||||
<h2>
|
||||
{station.waterBody} – {station.name}
|
||||
</h2>
|
||||
<p>
|
||||
{isLake ? 'Seepegel' : 'Fluss'} · BAFU-Station {station.id} · Stand{' '}
|
||||
{formatTime(station.time)}
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" className="close-button" onClick={onClose} aria-label="Schliessen">
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<section className="stat-tiles">
|
||||
{!isLake && (
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">
|
||||
{formatDischarge(station.discharge)} {dischargeTrend(station)}
|
||||
</span>
|
||||
<span className="stat-tile-label">
|
||||
Abfluss
|
||||
{station.discharge24hAgo !== null &&
|
||||
` · vor 24 h ${formatDischarge(station.discharge24hAgo)}`}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">{formatDecimal(station.waterLevel, 2)} m</span>
|
||||
<span className="stat-tile-label">
|
||||
Pegel über Meer
|
||||
{station.waterLevelChange24h !== null &&
|
||||
` · ${formatLevelChange(station.waterLevelChange24h)} in 24 h`}
|
||||
</span>
|
||||
</div>
|
||||
{station.waterTemperature !== null && (
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">{formatDecimal(station.waterTemperature, 1)} °C</span>
|
||||
<span className="stat-tile-label">Wassertemperatur</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">
|
||||
<span
|
||||
className="legend-dot small"
|
||||
style={{ background: dangerColor(station.dangerLevel) }}
|
||||
/>
|
||||
{station.dangerLevel ?? '–'}
|
||||
</span>
|
||||
<span className="stat-tile-label">Gefahrenstufe: {dangerLabel(station.dangerLevel)}</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>{chartTitle}</h3>
|
||||
{history.length > 1 ? (
|
||||
<div className="chart">
|
||||
<Line
|
||||
options={options}
|
||||
data={{
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: mainLabel,
|
||||
data: history.map((p) => (isLake ? p.waterLevel : p.discharge)),
|
||||
borderColor: MAIN_COLOR,
|
||||
backgroundColor: MAIN_COLOR,
|
||||
yAxisID: 'y',
|
||||
},
|
||||
...(hasTemperature
|
||||
? [
|
||||
{
|
||||
label: 'Wassertemperatur (°C)',
|
||||
data: history.map((p) => p.waterTemperature),
|
||||
borderColor: TEMPERATURE_COLOR,
|
||||
backgroundColor: TEMPERATURE_COLOR,
|
||||
yAxisID: 'y1',
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<p className="panel-note">Noch zu wenige Messwerte für einen Verlauf.</p>
|
||||
)}
|
||||
<p className="panel-note">
|
||||
Aktuelle Werte alle 10 Minuten aus LINDAS; fehlende Tage ergänzt der Server aus den
|
||||
7-Tage-Grafiken von hydrodaten.admin.ch. Rohdaten, noch nicht geprüft.
|
||||
</p>
|
||||
<p className="panel-note">
|
||||
<a href={stationUrl(station.id)} target="_blank" rel="noreferrer">
|
||||
Station auf hydrodaten.admin.ch
|
||||
</a>
|
||||
</p>
|
||||
</section>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
132
client/src/components/hydrology/HydrologyLayer.tsx
Normal file
132
client/src/components/hydrology/HydrologyLayer.tsx
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
import L from 'leaflet';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import type { HydroStation } from '../../api/hydrology';
|
||||
import {
|
||||
dangerColor,
|
||||
dangerLabel,
|
||||
dischargeTrend,
|
||||
formatDecimal,
|
||||
formatDischarge,
|
||||
formatLevelChange,
|
||||
formatTime,
|
||||
stationColor,
|
||||
type HydroMetric,
|
||||
} from '../../hydrology/format';
|
||||
import { escapeHtml } from '../../map/baseLayers';
|
||||
import { useMap, useMapAttribution } from '../../map/mapContext';
|
||||
|
||||
interface HydrologyLayerProps {
|
||||
stations: HydroStation[];
|
||||
metric: HydroMetric;
|
||||
selectedId: string | null;
|
||||
onSelect: (id: string) => void;
|
||||
}
|
||||
|
||||
const DATA_ATTRIBUTION = 'Gewässer: <a href="https://www.hydrodaten.admin.ch/">BAFU</a>';
|
||||
|
||||
export function riverRadius(discharge: number | null): number {
|
||||
return discharge === null || discharge <= 0 ? 6 : 6 + Math.sqrt(discharge) * 2.2;
|
||||
}
|
||||
|
||||
export function HydrologyLayer({ stations, metric, selectedId, onSelect }: HydrologyLayerProps) {
|
||||
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 ids = new Set(stations.map((s) => s.id));
|
||||
markersRef.current.forEach((marker, id) => {
|
||||
if (!ids.has(id)) {
|
||||
marker.remove();
|
||||
markersRef.current.delete(id);
|
||||
}
|
||||
});
|
||||
|
||||
for (const station of stations) {
|
||||
let marker = markersRef.current.get(station.id);
|
||||
if (!marker) {
|
||||
marker = L.marker([station.lat, station.lon], {
|
||||
icon: L.divIcon({ className: 'hydro-marker-anchor', html: '', iconSize: [0, 0] }),
|
||||
keyboard: true,
|
||||
title: station.name,
|
||||
})
|
||||
.on('click', () => onSelectRef.current(station.id))
|
||||
.addTo(map);
|
||||
markersRef.current.set(station.id, marker);
|
||||
}
|
||||
|
||||
const selected = station.id === selectedId;
|
||||
const element = marker.getElement();
|
||||
if (element) {
|
||||
element.innerHTML = markerHtml(station, metric, selected);
|
||||
}
|
||||
marker.setZIndexOffset(selected ? 10_000 : station.kind === 'Lake' ? 1_000 : 0);
|
||||
const offset = station.kind === 'Lake' ? 18 : riverRadius(station.discharge) + 2;
|
||||
marker.bindTooltip(tooltipHtml(station), { direction: 'top', offset: [0, -offset] });
|
||||
}
|
||||
}, [map, stations, metric, selectedId]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function markerHtml(station: HydroStation, metric: HydroMetric, selected: boolean): string {
|
||||
const color = stationColor(station, metric);
|
||||
const selectedClass = selected ? ' selected' : '';
|
||||
if (station.kind === 'Lake') {
|
||||
return (
|
||||
`<div class="hydro-badge${selectedClass}" style="border-color:${dangerColor(station.dangerLevel)}">` +
|
||||
`<strong>${formatDecimal(station.waterLevel, 2)} m</strong>` +
|
||||
`<span>${escapeHtml(formatLevelChange(station.waterLevelChange24h) || 'ü. M.')}</span></div>`
|
||||
);
|
||||
}
|
||||
|
||||
const size = riverRadius(station.discharge) * 2;
|
||||
const label =
|
||||
metric !== 'temperature'
|
||||
? `${formatDischarge(station.discharge)} ${dischargeTrend(station)}`
|
||||
: station.waterTemperature !== null
|
||||
? `${formatDecimal(station.waterTemperature, 1)} °C`
|
||||
: '';
|
||||
return (
|
||||
`<div class="hydro-dot${selectedClass}" style="width:${size}px;height:${size}px;background:${color}"></div>` +
|
||||
`<span class="hydro-label" style="top:${size / 2 + 2}px">${escapeHtml(label.trim())}</span>`
|
||||
);
|
||||
}
|
||||
|
||||
function tooltipHtml(station: HydroStation): string {
|
||||
const rows: string[] = [];
|
||||
if (station.discharge !== null) {
|
||||
rows.push(row('Abfluss', `${formatDischarge(station.discharge)} ${dischargeTrend(station)}`));
|
||||
}
|
||||
if (station.waterLevel !== null) {
|
||||
const change = formatLevelChange(station.waterLevelChange24h);
|
||||
rows.push(
|
||||
row(
|
||||
'Pegel',
|
||||
`${formatDecimal(station.waterLevel, 2)} m ü. M.${change ? ` (${change})` : ''}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (station.waterTemperature !== null) {
|
||||
rows.push(row('Wassertemperatur', `${formatDecimal(station.waterTemperature, 1)} °C`));
|
||||
}
|
||||
rows.push(row('Gefahrenstufe', escapeHtml(dangerLabel(station.dangerLevel))));
|
||||
return (
|
||||
`<strong>${escapeHtml(station.waterBody)} – ${escapeHtml(station.name)}</strong><br/>` +
|
||||
`<span class="muted">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>`;
|
||||
}
|
||||
51
client/src/components/hydrology/HydrologyLegend.tsx
Normal file
51
client/src/components/hydrology/HydrologyLegend.tsx
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import {
|
||||
DANGER_LEVELS,
|
||||
HYDRO_METRICS,
|
||||
TEMPERATURE_LEGEND,
|
||||
type HydroMetric,
|
||||
} from '../../hydrology/format';
|
||||
|
||||
interface HydrologyLegendProps {
|
||||
metric: HydroMetric;
|
||||
onMetricChange: (metric: HydroMetric) => void;
|
||||
}
|
||||
|
||||
export function HydrologyLegend({ metric, onMetricChange }: HydrologyLegendProps) {
|
||||
const items =
|
||||
metric === 'temperature'
|
||||
? TEMPERATURE_LEGEND
|
||||
: DANGER_LEVELS.map((d) => ({ label: `${d.level} ${d.label}`, color: d.color }));
|
||||
|
||||
return (
|
||||
<div className="legend category-legend">
|
||||
<div className="dimension-tabs" role="tablist" aria-label="Flüsse färben nach">
|
||||
{HYDRO_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">
|
||||
{items.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">
|
||||
{metric === 'temperature'
|
||||
? 'Farbe = Wassertemperatur, Grösse = Abfluss'
|
||||
: 'Farbe = BAFU-Gefahrenstufe, Grösse = Abfluss'}
|
||||
; Seen zeigen den Pegel und die Änderung in 24 h
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
101
client/src/hydrology/format.ts
Normal file
101
client/src/hydrology/format.ts
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import type { HydroStation } from '../api/hydrology';
|
||||
|
||||
export type HydroMetric = 'discharge' | 'temperature';
|
||||
|
||||
export const HYDRO_METRICS: { key: HydroMetric; label: string }[] = [
|
||||
{ key: 'discharge', label: 'Abfluss' },
|
||||
{ key: 'temperature', label: 'Wassertemperatur' },
|
||||
];
|
||||
|
||||
export const DANGER_LEVELS = [
|
||||
{ level: 1, label: 'keine oder geringe Gefahr', color: '#16a34a' },
|
||||
{ level: 2, label: 'mässige Gefahr', color: '#eab308' },
|
||||
{ level: 3, label: 'erhebliche Gefahr', color: '#f97316' },
|
||||
{ level: 4, label: 'grosse Gefahr', color: '#dc2626' },
|
||||
{ level: 5, label: 'sehr grosse Gefahr', color: '#7f1d1d' },
|
||||
];
|
||||
|
||||
const NO_VALUE_COLOR = '#94a3b8';
|
||||
|
||||
const TEMPERATURE_STOPS: [number, string][] = [
|
||||
[0, '#1e3a8a'],
|
||||
[5, '#2563eb'],
|
||||
[10, '#0ea5e9'],
|
||||
[15, '#14b8a6'],
|
||||
[20, '#f59e0b'],
|
||||
[25, '#dc2626'],
|
||||
];
|
||||
|
||||
export function dangerColor(level: number | null): string {
|
||||
return DANGER_LEVELS.find((d) => d.level === level)?.color ?? NO_VALUE_COLOR;
|
||||
}
|
||||
|
||||
export function dangerLabel(level: number | null): string {
|
||||
return DANGER_LEVELS.find((d) => d.level === level)?.label ?? 'keine Angabe';
|
||||
}
|
||||
|
||||
export function temperatureColor(value: number | null): string {
|
||||
if (value === null) {
|
||||
return NO_VALUE_COLOR;
|
||||
}
|
||||
let color = TEMPERATURE_STOPS[0][1];
|
||||
for (const [threshold, stopColor] of TEMPERATURE_STOPS) {
|
||||
if (value >= threshold) {
|
||||
color = stopColor;
|
||||
}
|
||||
}
|
||||
return color;
|
||||
}
|
||||
|
||||
export const TEMPERATURE_LEGEND = TEMPERATURE_STOPS.map(([threshold, color]) => ({
|
||||
label: `ab ${threshold} °C`,
|
||||
color,
|
||||
}));
|
||||
|
||||
export function stationColor(station: HydroStation, metric: HydroMetric): string {
|
||||
return metric === 'temperature'
|
||||
? temperatureColor(station.waterTemperature)
|
||||
: dangerColor(station.dangerLevel);
|
||||
}
|
||||
|
||||
export function formatDecimal(value: number | null, digits: number): string {
|
||||
return value === null
|
||||
? '–'
|
||||
: value.toLocaleString('de-CH', {
|
||||
minimumFractionDigits: digits,
|
||||
maximumFractionDigits: digits,
|
||||
});
|
||||
}
|
||||
|
||||
export function formatDischarge(value: number | null): string {
|
||||
return value === null ? '–' : `${formatDecimal(value, value < 10 ? 2 : 1)} m³/s`;
|
||||
}
|
||||
|
||||
export function formatLevelChange(meters: number | null): string {
|
||||
if (meters === null) {
|
||||
return '';
|
||||
}
|
||||
const cm = Math.round(meters * 100);
|
||||
return cm === 0 ? '± 0 cm' : `${cm > 0 ? '▲ +' : '▼ −'}${Math.abs(cm)} cm`;
|
||||
}
|
||||
|
||||
export function dischargeTrend(station: HydroStation): string {
|
||||
if (station.discharge === null || station.discharge24hAgo === null) {
|
||||
return '';
|
||||
}
|
||||
const change = station.discharge - station.discharge24hAgo;
|
||||
if (Math.abs(change) < Math.max(0.05, station.discharge24hAgo * 0.03)) {
|
||||
return '→';
|
||||
}
|
||||
return change > 0 ? '↗' : '↘';
|
||||
}
|
||||
|
||||
export function formatTime(value: string | null): string {
|
||||
return value
|
||||
? new Date(value).toLocaleTimeString('de-CH', { hour: '2-digit', minute: '2-digit' })
|
||||
: '–';
|
||||
}
|
||||
|
||||
export function stationUrl(id: string): string {
|
||||
return `https://www.hydrodaten.admin.ch/de/seen-und-fluesse/stationen-und-daten/${encodeURIComponent(id)}`;
|
||||
}
|
||||
41
client/src/hydrology/useHydrologyData.ts
Normal file
41
client/src/hydrology/useHydrologyData.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { fetchHydroStations, fetchHydrologyMeta } from '../api/hydrology';
|
||||
import type { HydroMetric } from './format';
|
||||
|
||||
const REFRESH_MS = 5 * 60_000;
|
||||
|
||||
export function useHydrologyData() {
|
||||
const metaQuery = useQuery({
|
||||
queryKey: ['hydrology-meta'],
|
||||
queryFn: fetchHydrologyMeta,
|
||||
refetchInterval: REFRESH_MS,
|
||||
});
|
||||
const stationsQuery = useQuery({
|
||||
queryKey: ['hydrology-stations', metaQuery.data?.lastRefresh ?? null],
|
||||
queryFn: fetchHydroStations,
|
||||
enabled: !!metaQuery.data,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
const [metric, setMetric] = useState<HydroMetric>('discharge');
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
|
@ -5,6 +5,9 @@ import { LayerPanel } from '../components/combined/LayerPanel';
|
|||
import { MunicipalityContext } from '../components/combined/MunicipalityContext';
|
||||
import { OverviewPanel } from '../components/combined/OverviewPanel';
|
||||
import { DatasetCredit, LicenseLink } from '../components/DatasetCredit';
|
||||
import { HydrologyLayer } from '../components/hydrology/HydrologyLayer';
|
||||
import { HydrologyLegend } from '../components/hydrology/HydrologyLegend';
|
||||
import { HydroStationPanel } from '../components/hydrology/HydroStationPanel';
|
||||
import { Legend } from '../components/Legend';
|
||||
import { StationPanel } from '../components/StationPanel';
|
||||
import { TimeControls } from '../components/TimeControls';
|
||||
|
|
@ -16,6 +19,8 @@ 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 { formatTime } from '../hydrology/format';
|
||||
import { useHydrologyData } from '../hydrology/useHydrologyData';
|
||||
import { THURGAU_CENTER } from '../map/baseLayers';
|
||||
import { assignToOutlines } from '../map/geometry';
|
||||
import { MapHost } from '../map/MapHost';
|
||||
|
|
@ -29,17 +34,19 @@ const MemoStationPanel = memo(StationPanel);
|
|||
const MemoLocationPanel = memo(LocationPanel);
|
||||
const MemoMunicipalityPanel = memo(MunicipalityPanel);
|
||||
|
||||
type LayerKey = 'fahrzeuge' | 'boote' | 'verkehr';
|
||||
type LayerKey = 'fahrzeuge' | 'boote' | 'verkehr' | 'gewaesser';
|
||||
|
||||
type Selection =
|
||||
| { layer: 'fahrzeuge'; id: string }
|
||||
| { layer: 'boote'; name: string }
|
||||
| { layer: 'verkehr'; code: number };
|
||||
| { layer: 'verkehr'; code: number }
|
||||
| { layer: 'gewaesser'; id: string };
|
||||
|
||||
const LAYER_ORDER: LayerKey[] = ['fahrzeuge', 'boote', 'verkehr'];
|
||||
const LAYER_ORDER: LayerKey[] = ['fahrzeuge', 'boote', 'verkehr', 'gewaesser'];
|
||||
const LAYER_PARAM = 'ebenen';
|
||||
const STATION_MAX_DISTANCE_M = 250;
|
||||
const HARBOUR_MAX_DISTANCE_M = 1500;
|
||||
const HYDRO_MAX_DISTANCE_M = 500;
|
||||
const SHARED_FILL_OPACITY = 0.55;
|
||||
|
||||
function parseLayers(value: string | null): Set<LayerKey> {
|
||||
|
|
@ -56,6 +63,7 @@ export function ThurgauCombinedPage() {
|
|||
const showVehicles = active.has('fahrzeuge');
|
||||
const showBoats = active.has('boote');
|
||||
const showTraffic = active.has('verkehr');
|
||||
const showWater = active.has('gewaesser');
|
||||
|
||||
const toggleLayer = useCallback(
|
||||
(key: LayerKey) =>
|
||||
|
|
@ -76,6 +84,7 @@ export function ThurgauCombinedPage() {
|
|||
const traffic = useTrafficData();
|
||||
const watercraft = useWatercraftData();
|
||||
const vehicles = useVehicleData();
|
||||
const hydrology = useHydrologyData();
|
||||
|
||||
const yearList = useMemo(() => {
|
||||
const all = new Set([
|
||||
|
|
@ -129,6 +138,13 @@ export function ThurgauCombinedPage() {
|
|||
),
|
||||
[],
|
||||
);
|
||||
const selectHydroStation = useCallback(
|
||||
(id: string) =>
|
||||
setSelection((current) =>
|
||||
current?.layer === 'gewaesser' && current.id === id ? null : { layer: 'gewaesser', id },
|
||||
),
|
||||
[],
|
||||
);
|
||||
const clearSelection = useCallback(() => setSelection(null), []);
|
||||
|
||||
const outlines = vehicles.shapes;
|
||||
|
|
@ -147,12 +163,21 @@ export function ThurgauCombinedPage() {
|
|||
),
|
||||
[outlines, boatView],
|
||||
);
|
||||
const hydroStationsByMunicipality = useMemo(
|
||||
() =>
|
||||
assignToOutlines(outlines, hydrology.stations, (s) => [s.lon, s.lat], HYDRO_MAX_DISTANCE_M),
|
||||
[outlines, hydrology.stations],
|
||||
);
|
||||
|
||||
const unplaced = boatView?.locations.filter((l) => l.lat === null) ?? [];
|
||||
const selectedStation =
|
||||
visibleSelection?.layer === 'verkehr'
|
||||
? (traffic.stations.find((s) => s.code === visibleSelection.code) ?? null)
|
||||
: null;
|
||||
const selectedHydroStation =
|
||||
visibleSelection?.layer === 'gewaesser'
|
||||
? (hydrology.stations.find((s) => s.id === visibleSelection.id) ?? null)
|
||||
: null;
|
||||
|
||||
let panel: ReactNode;
|
||||
if (visibleSelection?.layer === 'fahrzeuge' && vehicles.meta && year !== null) {
|
||||
|
|
@ -170,11 +195,13 @@ export function ThurgauCombinedPage() {
|
|||
<MunicipalityContext
|
||||
stations={showTraffic ? (stationsByMunicipality.get(id) ?? []) : null}
|
||||
locations={showBoats && boatView ? (locationsByMunicipality.get(id) ?? []) : null}
|
||||
hydroStations={showWater ? (hydroStationsByMunicipality.get(id) ?? []) : null}
|
||||
day={traffic.day}
|
||||
hour={traffic.hour}
|
||||
year={year}
|
||||
onSelectStation={selectStation}
|
||||
onSelectLocation={selectLocation}
|
||||
onSelectHydroStation={selectHydroStation}
|
||||
/>
|
||||
</MemoMunicipalityPanel>
|
||||
);
|
||||
|
|
@ -205,6 +232,14 @@ export function ThurgauCombinedPage() {
|
|||
onClose={clearSelection}
|
||||
/>
|
||||
);
|
||||
} else if (selectedHydroStation) {
|
||||
panel = (
|
||||
<HydroStationPanel
|
||||
station={selectedHydroStation}
|
||||
lastRefresh={hydrology.meta?.lastRefresh ?? null}
|
||||
onClose={clearSelection}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
panel = (
|
||||
<OverviewPanel
|
||||
|
|
@ -226,6 +261,7 @@ export function ThurgauCombinedPage() {
|
|||
}
|
||||
: null
|
||||
}
|
||||
hydrology={showWater ? { stations: hydrology.stations } : null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -233,11 +269,13 @@ export function ThurgauCombinedPage() {
|
|||
const error =
|
||||
(showVehicles ? vehicles.error : null) ??
|
||||
(showBoats ? watercraft.error : null) ??
|
||||
(showTraffic ? traffic.error : null);
|
||||
(showTraffic ? traffic.error : null) ??
|
||||
(showWater ? hydrology.error : null);
|
||||
const loading =
|
||||
(showVehicles && vehicles.loading) ||
|
||||
(showBoats && watercraft.loading) ||
|
||||
(showTraffic && traffic.loading);
|
||||
(showTraffic && traffic.loading) ||
|
||||
(showWater && hydrology.loading);
|
||||
|
||||
const missingYearNote = (firstYear: number | undefined) =>
|
||||
year !== null && firstYear !== undefined && year < firstYear
|
||||
|
|
@ -259,7 +297,7 @@ export function ThurgauCombinedPage() {
|
|||
<span className="title-separator">/</span> Thurgau – alle Daten
|
||||
</h1>
|
||||
<span className="subtitle">
|
||||
Fahrzeugbestand, Wasserfahrzeuge und Strassenverkehr auf einer Karte
|
||||
Fahrzeugbestand, Wasserfahrzeuge, Strassenverkehr und Gewässer auf einer Karte
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -296,7 +334,7 @@ export function ThurgauCombinedPage() {
|
|||
scale={vehicles.scale}
|
||||
selectedId={visibleSelection?.layer === 'fahrzeuge' ? visibleSelection.id : null}
|
||||
onSelect={selectMunicipality}
|
||||
fillOpacity={showBoats || showTraffic ? SHARED_FILL_OPACITY : undefined}
|
||||
fillOpacity={showBoats || showTraffic || showWater ? SHARED_FILL_OPACITY : undefined}
|
||||
fitToData={false}
|
||||
/>
|
||||
)}
|
||||
|
|
@ -322,6 +360,14 @@ export function ThurgauCombinedPage() {
|
|||
fitToData={false}
|
||||
/>
|
||||
)}
|
||||
{showWater && (
|
||||
<HydrologyLayer
|
||||
stations={hydrology.stations}
|
||||
metric={hydrology.metric}
|
||||
selectedId={visibleSelection?.layer === 'gewaesser' ? visibleSelection.id : null}
|
||||
onSelect={selectHydroStation}
|
||||
/>
|
||||
)}
|
||||
</MapHost>
|
||||
|
||||
<LayerPanel>
|
||||
|
|
@ -395,6 +441,20 @@ export function ThurgauCombinedPage() {
|
|||
>
|
||||
<Legend />
|
||||
</LayerCard>
|
||||
<LayerCard
|
||||
title="Gewässer (live)"
|
||||
subtitle="Abfluss und Pegel · alle 10 Minuten"
|
||||
color="#0ea5e9"
|
||||
active={showWater}
|
||||
note={
|
||||
hydrology.latestTime
|
||||
? `Stand ${formatTime(hydrology.latestTime)}; unabhängig von Jahr und Verkehrstag.`
|
||||
: null
|
||||
}
|
||||
onToggle={() => toggleLayer('gewaesser')}
|
||||
>
|
||||
<HydrologyLegend metric={hydrology.metric} onMetricChange={hydrology.setMetric} />
|
||||
</LayerCard>
|
||||
</LayerPanel>
|
||||
|
||||
<div className="overlay-bottom">
|
||||
|
|
@ -467,7 +527,18 @@ export function ThurgauCombinedPage() {
|
|||
<a href={traffic.meta?.sourceUrl} target="_blank" rel="noreferrer">
|
||||
{traffic.meta?.publisher ?? 'Kanton Thurgau'}
|
||||
</a>{' '}
|
||||
(Verkehrszählungen, Lizenz <LicenseLink license={traffic.meta?.license ?? 'CC0 1.0'} />) ·
|
||||
(Verkehrszählungen, Lizenz <LicenseLink license={traffic.meta?.license ?? 'CC0 1.0'} />) ·{' '}
|
||||
{hydrology.meta && (
|
||||
<>
|
||||
<DatasetCredit
|
||||
title={hydrology.meta.title}
|
||||
publisher={hydrology.meta.publisher}
|
||||
url={hydrology.meta.sourceUrl}
|
||||
license={hydrology.meta.license}
|
||||
/>{' '}
|
||||
·{' '}
|
||||
</>
|
||||
)}
|
||||
Karten, Gemeindegrenzen und Strassennetz © swisstopo · Bearbeitung: Werte pro Gemeinde,
|
||||
Standort und Zählstelle aggregiert, Zuordnung zu Gemeinden über die Lage
|
||||
</footer>
|
||||
|
|
|
|||
|
|
@ -1079,3 +1079,66 @@ select {
|
|||
max-height: calc(100% - 140px);
|
||||
}
|
||||
}
|
||||
|
||||
.hydro-marker-anchor {
|
||||
background: none;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.hydro-dot {
|
||||
position: absolute;
|
||||
transform: translate(-50%, -50%);
|
||||
border-radius: 50%;
|
||||
border: 2px solid white;
|
||||
box-shadow: 0 1px 4px rgba(15, 23, 42, 0.45);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
width 0.4s,
|
||||
height 0.4s;
|
||||
}
|
||||
|
||||
.hydro-dot.selected {
|
||||
border: 3px solid #0f172a;
|
||||
}
|
||||
|
||||
.hydro-label {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
transform: translateX(-50%);
|
||||
white-space: nowrap;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: #0f172a;
|
||||
text-shadow:
|
||||
0 0 3px white,
|
||||
0 0 3px white,
|
||||
0 0 3px white;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.hydro-badge {
|
||||
position: absolute;
|
||||
transform: translate(-50%, -50%);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
background: white;
|
||||
border: 3px solid;
|
||||
border-radius: 8px;
|
||||
padding: 2px 7px;
|
||||
font-size: 11px;
|
||||
line-height: 1.25;
|
||||
white-space: nowrap;
|
||||
box-shadow: 0 2px 6px rgba(15, 23, 42, 0.3);
|
||||
cursor: pointer;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.hydro-badge span {
|
||||
color: var(--muted);
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.hydro-badge.selected {
|
||||
outline: 2px solid #0f172a;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,8 @@ flowchart LR
|
|||
pop["sk-stat-56<br/>Wohnbevölkerung"]
|
||||
end
|
||||
|
||||
lindas["LINDAS (BAFU)<br/>Abfluss und Pegel"]
|
||||
|
||||
subgraph geo["swisstopo API"]
|
||||
tlm["swissTLM3D Strassen<br/>+ SearchServer"]
|
||||
bound["swissBOUNDARIES3D<br/>Gemeindegrenzen"]
|
||||
|
|
@ -26,10 +28,11 @@ flowchart LR
|
|||
tr["TrafficRefresher<br/>alle 6 h"]
|
||||
wr["WatercraftRefresher<br/>täglich"]
|
||||
vr["VehicleRefresher<br/>täglich"]
|
||||
hr["HydrologyRefresher<br/>alle 10 min"]
|
||||
end
|
||||
|
||||
cache[("JSON-Cache<br/>{DataPath}/…")]
|
||||
api["/api/traffic<br/>/api/watercraft<br/>/api/vehicles"]
|
||||
api["/api/traffic<br/>/api/watercraft<br/>/api/vehicles<br/>/api/hydrology"]
|
||||
client["React-Client"]
|
||||
|
||||
traffic --> tr
|
||||
|
|
@ -38,7 +41,8 @@ flowchart LR
|
|||
stock --> vr
|
||||
pop --> vr
|
||||
bound -->|einmal pro Gemeinde| vr
|
||||
tr & wr & vr --> cache
|
||||
lindas --> hr
|
||||
tr & wr & vr & hr --> cache
|
||||
cache --> api --> client
|
||||
wmts -->|direkt im Browser| client
|
||||
```
|
||||
|
|
@ -56,7 +60,7 @@ sequenceDiagram
|
|||
S->>R: LoadCacheAsync()
|
||||
R->>C: lesen
|
||||
R->>D: Snapshot ersetzen
|
||||
loop alle 15 bzw. 30 Minuten
|
||||
loop jede Minute bis alle 30 Minuten
|
||||
S->>R: IsRefreshDue(RefreshInterval)?
|
||||
alt fällig
|
||||
R->>Q: nur Neues / Geändertes abrufen
|
||||
|
|
@ -76,22 +80,24 @@ sequenceDiagram
|
|||
| [Strassenfahrzeugbestand](datasets/strassenfahrzeugbestand.md) | data.tg.ch `djs-stv-17` (Strassenverkehrsamt TG) | CC BY 4.0 | JSON-Export des ganzen Datensatzes | Prüfung alle 30 min, täglich; Export nur bei geändertem `modified` | `vehicles/thurgau/stock.json` |
|
||||
| [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) |
|
||||
| [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 und Strassenverkehr 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 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.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
v["/api/vehicles<br/>Gemeinden pro Jahr"] --> page
|
||||
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
|
||||
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&jahr=2025`); ohne `ebenen` sind alle eingeschaltet.
|
||||
- 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.
|
||||
- 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.
|
||||
- „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.
|
||||
|
||||
Alle Intervalle und Pfade sind in `appsettings.json` unter `Traffic`, `Watercraft` und `Vehicles` 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` 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.
|
||||
|
|
|
|||
41
docs/datasets/gewaesser.md
Normal file
41
docs/datasets/gewaesser.md
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
# Gewässer (Abfluss und Pegel)
|
||||
|
||||
[← Übersicht](../datasets.md)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Datensatz | Hydrologische Daten des BAFU, aktuelle Messwerte der Stationen an Flüssen und Seen (LINDAS-Cubes `foen/hydro/river` und `foen/hydro/lake`) |
|
||||
| Quelle | [LINDAS](https://lindas.admin.ch/), SPARQL-Endpunkt `https://lindas.admin.ch/query`, Graph `https://lindas.admin.ch/foen/hydro`; Verlauf ergänzt aus den 7-Tage-Grafiken von [hydrodaten.admin.ch](https://www.hydrodaten.admin.ch/) (`/plots/p_q_7days/{id}_p_q_7days_de.json`, `/plots/temperature_7days/{id}_temperature_7days_de.json`) |
|
||||
| Herausgeber | Bundesamt für Umwelt BAFU |
|
||||
| Lizenz | opendata.swiss «Freie Nutzung. Quellenangabe ist Pflicht.» ([BY](https://opendata.swiss/de/terms-of-use#terms_by)) |
|
||||
| Inhalt | pro Station nur der **aktuelle** Messwert: Zeitpunkt, Pegel (m ü. M.), Abfluss (m³/s, nur Flüsse), Wassertemperatur (°C, nicht überall), Hochwasser-Gefahrenstufe 1–5; dazu Name, Gewässer und Lage der Station |
|
||||
| Stationen | Standard (`HydrologyOptions.DefaultStationIds`): Bodensee Romanshorn (2032), Untersee Berlingen (2043), Thur Halden (2181), Andelfingen (2044) und Jonschwil (2303), Murg Frauenfeld (2386) und Wängi (2126), Aach Salmsach (2312), Sitter St. Gallen (2468); änderbar mit `Hydrology:StationIds` |
|
||||
| Verwendet in | Ebene «Gewässer (live)» der Karte `/karte/thurgau` |
|
||||
| Abruf | eine SPARQL-Abfrage (POST, Antwort als `application/sparql-results+json`) für alle gewählten Stationen; pro Station zusätzlich die beiden 7-Tage-Grafiken, wenn der Cache keine 6 Tage abdeckt oder der letzte Wert älter als 45 min ist (höchstens einmal pro Stunde und Station) |
|
||||
| Aktualisierung | Prüfung jede Minute, Abruf alle 10 min (`Hydrology:RefreshInterval`); der Browser lädt die Werte alle 5 min neu |
|
||||
| Cache | `{DataPath}/hydrology/thurgau/meta.json`, `stations.json`, `days/yyyy-MM-dd.json` (Messwerte pro UTC-Tag); Tage älter als `Hydrology:HistoryDays` (Standard 60) werden gelöscht |
|
||||
| Code | `Schaad.OpenData.Hydrology` (`LindasHydroClient`, `HydrodatenPlotClient`, `HydrologyRefresher`, `HydrologyCacheStorage`, `HydrologyAnalysis`) |
|
||||
|
||||
## Ablauf
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
S["HydrologyRefreshService<br/>jede Minute"] --> R{"letzter Abruf<br/>älter als 10 min?"}
|
||||
R -- ja --> Q["SPARQL-Abfrage<br/>lindas.admin.ch/query"]
|
||||
Q --> L{"Cache deckt 6 Tage ab<br/>und ohne Lücke?"}
|
||||
L -- nein --> G["7-Tage-Grafiken<br/>hydrodaten.admin.ch/plots"] --> N
|
||||
L -- ja --> N{"Messzeit schon<br/>im Cache?"}
|
||||
N -- nein --> D[("days/yyyy-MM-dd.json")]
|
||||
N -- ja --> K[verwerfen]
|
||||
D --> P["Tage älter als<br/>HistoryDays löschen"]
|
||||
```
|
||||
|
||||
## Hinweise
|
||||
|
||||
- LINDAS hat keinen Verlauf, nur den neusten Wert pro Station. Den Verlauf sammelt der Server selbst. Damit das Diagramm schon beim ersten Start sieben Tage zeigt und Lücken nach einem Unterbruch verschwinden, liest er die JSON-Dateien, mit denen hydrodaten.admin.ch seine 7-Tage-Grafiken zeichnet. Das ist keine dokumentierte Schnittstelle: Ändert sie sich, schlägt nur die Ergänzung fehl (Warnung im Log), der Live-Abruf läuft weiter.
|
||||
- Aus den Grafiken werden nur Werte auf 10-Minuten-Marken übernommen (Pegel und Abfluss liegen dort alle 5 min vor), damit sie zu den LINDAS-Werten passen. Sie haben keine Gefahrenstufe; gibt es zur selben Zeit einen LINDAS-Wert, gilt dieser.
|
||||
- Es sind Rohdaten. Das BAFU prüft sie später und kann sie korrigieren; korrigierte Werte werden nicht nachgeladen.
|
||||
- Die Stationen werden über ihre IRI `https://environment.ld.admin.ch/foen/hydro/station/{id}` abgefragt (die Nummer ist in LINDAS ein Integer-Literal). Ob es eine See- oder Flussstation ist, ergibt sich aus der Beobachtung (`…/lake/observation/…` bzw. `…/river/observation/…`).
|
||||
- Das Feld `isLiter` ist bei allen Stationen `true` und sagt nichts über die Einheit aus; es wird ignoriert. Kleine Messstellen ausserhalb der Standardliste (z. B. Rietholzbach) melden ihren Abfluss vermutlich in l/s.
|
||||
- Eine Gefahrenstufe `https://cube.link/Undefined` wird als «keine Angabe» behandelt.
|
||||
- Die 24-Stunden-Änderung (Seepegel, Abfluss-Trend) braucht einen Messwert, der höchstens eine Stunde von «vor 24 Stunden» entfernt ist; dank der Ergänzung ist er gleich nach dem ersten Abruf da.
|
||||
Loading…
Reference in a new issue