OpenDataVisualizer/Schaad.OpenData.Traffic/Storage/TrafficCacheStorage.cs
Claudio Schaad e729ea3403 Add Thurgau traffic visualizer with animated map
ASP.NET Core 10 API and React client that visualize the canton of
Thurgau's hourly traffic counts by vehicle class (data.tg.ch, CC0).

- Background refresh from data.tg.ch every 6 h into a per-day JSON
  cache, so history grows beyond the source's two-week window
- Road geometry per station direction from swisstopo swissTLM3D,
  oriented by geocoding the direction's target town; roundabout arms
  follow the road outward only
- Leaflet map with canvas animation: dots drive along the road in
  both directions, density by hourly count, colour by vehicle class,
  right-hand traffic; play/pause, time slider and day selection
- Station panel with per-class counts and Chart.js charts (hourly,
  weekday/weekend profile, daily totals, class mix)
- swisstopo base map switcher (grey, colour, aerial)
- Dockerfile and docker-compose with a data volume
- xUnit tests for mapping, cache, geometry, geocoding and analysis

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 20:33:58 +01:00

74 lines
3.2 KiB
C#

using System.Globalization;
using System.Text.Json;
using Microsoft.Extensions.Options;
using Schaad.OpenData.Traffic.Models;
namespace Schaad.OpenData.Traffic.Storage;
public class TrafficCacheStorage(IOptions<TrafficOptions> options)
{
private const string DayFormat = "yyyy-MM-dd";
private const string GeometryFileName = "geometry-v5.json";
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { WriteIndented = true };
private string RootPath => Path.Combine(Path.GetFullPath(options.Value.DataPath), "traffic", "thurgau");
private string CountsPath => Path.Combine(RootPath, "counts");
public virtual async Task<TrafficSnapshot> LoadAsync(CancellationToken cancellationToken)
{
var stations = await ReadAsync<List<Station>>(Path.Combine(RootPath, "stations.json"), cancellationToken) ?? [];
var geometry = await ReadAsync<List<StationGeometry>>(Path.Combine(RootPath, GeometryFileName), cancellationToken) ?? [];
var meta = await ReadAsync<TrafficCacheMeta>(Path.Combine(RootPath, "meta.json"), cancellationToken);
var counts = new List<HourlyCount>();
if (Directory.Exists(CountsPath))
{
foreach (var file in Directory.EnumerateFiles(CountsPath, "*.json").Order(StringComparer.Ordinal))
{
counts.AddRange(await ReadAsync<List<HourlyCount>>(file, cancellationToken) ?? []);
}
}
return new TrafficSnapshot(stations, counts, geometry, meta?.LastRefresh);
}
public virtual async Task SaveAsync(TrafficSnapshot snapshot, IReadOnlyCollection<DateOnly> changedDays, CancellationToken cancellationToken)
{
await WriteAsync(Path.Combine(RootPath, "stations.json"), snapshot.Stations.Values.OrderBy(s => s.Code).ToList(), cancellationToken);
foreach (var day in changedDays)
{
var path = Path.Combine(CountsPath, day.ToString(DayFormat, CultureInfo.InvariantCulture) + ".json");
await WriteAsync(path, snapshot.CountsByDate.GetValueOrDefault(day).ToList(), cancellationToken);
}
await WriteAsync(Path.Combine(RootPath, "meta.json"), new TrafficCacheMeta(snapshot.LastRefresh), cancellationToken);
}
public virtual Task SaveGeometryAsync(TrafficSnapshot snapshot, CancellationToken cancellationToken) =>
WriteAsync(Path.Combine(RootPath, GeometryFileName), snapshot.Geometry.Values.OrderBy(g => g.StationCode).ToList(), cancellationToken);
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);
}
}