- New Schaad.OpenData.Hydrology project: LindasHydroClient fetches the
current level, discharge, water temperature and danger level of nine
BAFU stations around Thurgau from LINDAS every 10 minutes
- LINDAS has no history, so the server keeps readings per day (60 days)
and fills gaps from the 7-day plot JSON of hydrodaten.admin.ch
- API: /api/hydrology/meta, /stations, /stations/{id}/history
- Combined map: "Gewässer (live)" layer with river circles (size by
discharge, colour by danger level or water temperature), lake level
badges, station panel with 7-day chart, overview and municipality
context entries
- Docs: docs/datasets/gewaesser.md, overview in docs/datasets.md,
CLAUDE.md; Docker and appsettings wiring
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
104 lines
4.6 KiB
C#
104 lines
4.6 KiB
C#
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();
|
|
}
|