- New Schaad.OpenData.Weather project: MeteoSwissClient reads the
10-minute CSV of the five SwissMetNet stations in Thurgau every 10
minutes (station list once a day) and backfills the last 7 days from
the yearly file when the cache has less than 6 days
- History kept as JSON per day (60 days); a failing station does not
stop the others
- API: /api/weather/meta, /stations (current values, 1 h/24 h rain,
24 h min/max, strongest gust), /stations/{abbr}/history
- Combined map: "Wetter (live)" layer with station badges (temperature,
24 h rain or wind), wind arrows, rain marker, station panel with
hourly 7-day chart, overview and municipality context entries
- Docs: docs/datasets/wetter.md, overview in docs/datasets.md,
CLAUDE.md; Docker and appsettings wiring
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
123 lines
4.7 KiB
C#
123 lines
4.7 KiB
C#
using System.Globalization;
|
|
using System.Text;
|
|
using Microsoft.Extensions.Options;
|
|
using Schaad.OpenData.Weather.Models;
|
|
|
|
namespace Schaad.OpenData.Weather.Source;
|
|
|
|
public class MeteoSwissClient(HttpClient httpClient, IOptions<WeatherOptions> options)
|
|
{
|
|
private const string TimestampFormat = "dd.MM.yyyy HH:mm";
|
|
|
|
private string BaseUrl => options.Value.BaseUrl.TrimEnd('/');
|
|
|
|
public virtual async Task<IReadOnlyList<WeatherStation>> FetchStationsAsync(IReadOnlyCollection<string> abbreviations, CancellationToken cancellationToken)
|
|
{
|
|
var wanted = abbreviations.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
|
var stations = new List<WeatherStation>();
|
|
await foreach (var row in ReadRowsAsync($"{BaseUrl}/ogd-smn_meta_stations.csv", Encoding.Latin1, cancellationToken))
|
|
{
|
|
var abbr = row.GetValueOrDefault("station_abbr");
|
|
if (abbr is null || !wanted.Contains(abbr)
|
|
|| Number(row, "station_coordinates_wgs84_lat") is not { } lat
|
|
|| Number(row, "station_coordinates_wgs84_lon") is not { } lon)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
stations.Add(new WeatherStation(
|
|
abbr.ToUpperInvariant(),
|
|
row.GetValueOrDefault("station_name") ?? abbr,
|
|
row.GetValueOrDefault("station_canton") ?? string.Empty,
|
|
Number(row, "station_height_masl"),
|
|
lat,
|
|
lon));
|
|
}
|
|
|
|
return stations;
|
|
}
|
|
|
|
public virtual Task<IReadOnlyList<WeatherReading>> FetchRecentAsync(string abbr, CancellationToken cancellationToken) =>
|
|
FetchReadingsAsync(abbr, "t_now", DateTimeOffset.MinValue, cancellationToken);
|
|
|
|
public virtual Task<IReadOnlyList<WeatherReading>> FetchHistoryAsync(string abbr, DateTimeOffset from, CancellationToken cancellationToken) =>
|
|
FetchReadingsAsync(abbr, "t_recent", from, cancellationToken);
|
|
|
|
private async Task<IReadOnlyList<WeatherReading>> FetchReadingsAsync(string abbr, string kind, DateTimeOffset from, CancellationToken cancellationToken)
|
|
{
|
|
if (abbr.Length == 0 || !abbr.All(char.IsAsciiLetterOrDigit))
|
|
{
|
|
return [];
|
|
}
|
|
|
|
var lower = abbr.ToLowerInvariant();
|
|
var readings = new List<WeatherReading>();
|
|
await foreach (var row in ReadRowsAsync($"{BaseUrl}/{lower}/ogd-smn_{lower}_{kind}.csv", Encoding.UTF8, cancellationToken))
|
|
{
|
|
if (!DateTime.TryParseExact(row.GetValueOrDefault("reference_timestamp"), TimestampFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var timestamp))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var time = new DateTimeOffset(DateTime.SpecifyKind(timestamp, DateTimeKind.Utc));
|
|
if (time < from)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
readings.Add(new WeatherReading(
|
|
abbr.ToUpperInvariant(),
|
|
time,
|
|
Number(row, "tre200s0"),
|
|
Number(row, "ure200s0"),
|
|
Number(row, "rre150z0"),
|
|
Number(row, "sre000z0"),
|
|
Number(row, "fu3010z0"),
|
|
Number(row, "fu3010z1"),
|
|
Number(row, "dkl010z0"),
|
|
Number(row, "pp0qffs0")));
|
|
}
|
|
|
|
return readings;
|
|
}
|
|
|
|
private async IAsyncEnumerable<Dictionary<string, string>> ReadRowsAsync(
|
|
string url,
|
|
Encoding encoding,
|
|
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
|
|
{
|
|
using var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
|
response.EnsureSuccessStatusCode();
|
|
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
|
|
using var reader = new StreamReader(stream, encoding);
|
|
|
|
var header = await reader.ReadLineAsync(cancellationToken);
|
|
if (header is null)
|
|
{
|
|
yield break;
|
|
}
|
|
|
|
var columns = CsvLine.Split(header.TrimStart('\uFEFF'));
|
|
while (await reader.ReadLineAsync(cancellationToken) is { } line)
|
|
{
|
|
if (line.Length == 0)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var values = CsvLine.Split(line);
|
|
var row = new Dictionary<string, string>(StringComparer.Ordinal);
|
|
for (var i = 0; i < columns.Count && i < values.Count; i++)
|
|
{
|
|
row[columns[i]] = values[i];
|
|
}
|
|
|
|
yield return row;
|
|
}
|
|
}
|
|
|
|
private static double? Number(Dictionary<string, string> row, string column) =>
|
|
row.TryGetValue(column, out var text) && double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var value)
|
|
? value
|
|
: null;
|
|
}
|