feat: DashboardService with per-source cache and stale fallback, FixtureSource
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,160 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Weerscherm;
|
||||
|
||||
/**
|
||||
* Bouwt de JSON-payload voor /api/data.php: haalt per bron data op (via cache of de WeatherSource),
|
||||
* valt bij een storing terug op de laatst gecachte data en markeert die als stale.
|
||||
*/
|
||||
final class DashboardService
|
||||
{
|
||||
private const ERR_NETATMO_AUTH = 'netatmo_auth';
|
||||
private const ERR_NETATMO = 'netatmo_unavailable';
|
||||
private const ERR_FORECAST = 'forecast_unavailable';
|
||||
|
||||
/** @var list<string> */
|
||||
private array $errors = [];
|
||||
|
||||
/**
|
||||
* @param array{stations: int, measure: int, forecast: int} $ttl
|
||||
* @param array<string, string> $indoorModules
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly WeatherSource $source,
|
||||
private readonly Cache $cache,
|
||||
private readonly array $ttl,
|
||||
private readonly string $timezoneFallback,
|
||||
private readonly ?float $forecastLat,
|
||||
private readonly ?float $forecastLon,
|
||||
private readonly array $indoorModules,
|
||||
private readonly ?string $deviceId,
|
||||
private readonly ?\DateTimeImmutable $now = null,
|
||||
) {
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function build(): array
|
||||
{
|
||||
$this->errors = [];
|
||||
$nowUtc = $this->now ?? new \DateTimeImmutable('now');
|
||||
|
||||
$stations = $this->fetch('stations', fn() => $this->source->stationsData(), self::ERR_NETATMO);
|
||||
$station = StationMapper::map($stations['data'] ?? [], $this->deviceId, $this->indoorModules);
|
||||
|
||||
$tz = $this->timezone($station['timezone']);
|
||||
$now = $nowUtc->setTimezone($tz);
|
||||
|
||||
$rain = $this->rain($station, $now);
|
||||
$forecast = $this->forecast($station, $tz);
|
||||
|
||||
return [
|
||||
'generated_at' => $now->format(\DATE_ATOM),
|
||||
'timezone' => $tz->getName(),
|
||||
'station' => [
|
||||
'measured_at' => $this->iso($station['measured_at'], $tz),
|
||||
'stale' => $stations['stale'],
|
||||
],
|
||||
'outdoor' => [
|
||||
'temp' => $station['outdoor']['temp'],
|
||||
'trend' => $station['outdoor']['trend'],
|
||||
'min' => $station['outdoor']['min'],
|
||||
'min_at' => $this->iso($station['outdoor']['min_at'], $tz),
|
||||
'max' => $station['outdoor']['max'],
|
||||
'max_at' => $this->iso($station['outdoor']['max_at'], $tz),
|
||||
],
|
||||
'indoor' => $station['indoor'],
|
||||
'rain' => $rain,
|
||||
'forecast' => $forecast['days'],
|
||||
'forecast_stale' => $forecast['stale'],
|
||||
'errors' => $this->errors,
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array{today: ?float, previous_days: list<array{date: string, mm: ?float}>, month_total: ?float, stale: bool} */
|
||||
private function rain(array $station, \DateTimeImmutable $now): array
|
||||
{
|
||||
$empty = RainCalculator::compute([], $now, null) + ['stale' => false];
|
||||
if ($station['device_id'] === null || $station['rain_module_id'] === null) {
|
||||
return $empty;
|
||||
}
|
||||
$begin = RainCalculator::dateBegin($now)->getTimestamp();
|
||||
$measure = $this->fetch(
|
||||
'measure',
|
||||
fn() => $this->source->measure($station['device_id'], $station['rain_module_id'], $begin, $now->getTimestamp()),
|
||||
self::ERR_NETATMO,
|
||||
);
|
||||
if ($measure['data'] === null) {
|
||||
return ['today' => $station['sum_rain_24'], 'stale' => true] + $empty;
|
||||
}
|
||||
return RainCalculator::compute($measure['data'], $now, $station['sum_rain_24']) + ['stale' => $measure['stale']];
|
||||
}
|
||||
|
||||
/** @return array{days: list<array>, stale: bool} */
|
||||
private function forecast(array $station, \DateTimeZone $tz): array
|
||||
{
|
||||
$lat = $this->forecastLat ?? $station['lat'];
|
||||
$lon = $this->forecastLon ?? $station['lon'];
|
||||
if ($lat === null || $lon === null) {
|
||||
$this->addError(self::ERR_FORECAST);
|
||||
return ['days' => [], 'stale' => true];
|
||||
}
|
||||
$daily = $this->fetch('forecast', fn() => $this->source->forecast($lat, $lon, $tz->getName()), self::ERR_FORECAST);
|
||||
return [
|
||||
'days' => $daily['data'] === null ? [] : ForecastMapper::map($daily['data']),
|
||||
'stale' => $daily['stale'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Cache-first per bron. Bij een fout: stale cache (ongeacht leeftijd) en een foutcode, anders null.
|
||||
*
|
||||
* @param callable(): array $fetcher
|
||||
* @return array{data: ?array, stale: bool}
|
||||
*/
|
||||
private function fetch(string $key, callable $fetcher, string $errorCode): array
|
||||
{
|
||||
$now = ($this->now ?? new \DateTimeImmutable('now'))->getTimestamp();
|
||||
$ttl = $this->ttl[$key] ?? 0;
|
||||
if ($ttl > 0 && $this->cache->isFresh($key, $ttl, $now)) {
|
||||
return ['data' => $this->cache->read($key)['data'], 'stale' => false];
|
||||
}
|
||||
try {
|
||||
$data = $fetcher();
|
||||
if ($ttl > 0) {
|
||||
$this->cache->write($key, $data, $now);
|
||||
}
|
||||
return ['data' => $data, 'stale' => false];
|
||||
} catch (NetatmoAuthException) {
|
||||
$this->addError(self::ERR_NETATMO_AUTH);
|
||||
} catch (\Throwable $e) {
|
||||
error_log("weerscherm: $key: " . $e->getMessage());
|
||||
$this->addError($errorCode);
|
||||
}
|
||||
$cached = $this->cache->read($key);
|
||||
return ['data' => $cached['data'] ?? null, 'stale' => true];
|
||||
}
|
||||
|
||||
private function addError(string $code): void
|
||||
{
|
||||
if (!in_array($code, $this->errors, true)) {
|
||||
$this->errors[] = $code;
|
||||
}
|
||||
}
|
||||
|
||||
private function timezone(?string $name): \DateTimeZone
|
||||
{
|
||||
foreach ([$name, $this->timezoneFallback, 'UTC'] as $candidate) {
|
||||
if ($candidate !== null && in_array($candidate, \DateTimeZone::listIdentifiers(), true)) {
|
||||
return new \DateTimeZone($candidate);
|
||||
}
|
||||
}
|
||||
return new \DateTimeZone('UTC');
|
||||
}
|
||||
|
||||
private function iso(?int $timestamp, \DateTimeZone $tz): ?string
|
||||
{
|
||||
return $timestamp === null ? null : (new \DateTimeImmutable('@' . $timestamp))->setTimezone($tz)->format(\DATE_ATOM);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Weerscherm;
|
||||
|
||||
/**
|
||||
* Vaste voorbeelddata, relatief aan het huidige moment, zodat de frontend zonder Netatmo-koppeling
|
||||
* gebouwd en bekeken kan worden en altijd "vandaag" laat zien.
|
||||
*/
|
||||
final class FixtureSource implements WeatherSource
|
||||
{
|
||||
private const RAIN_PER_DAY = [4.3, 0, 3.2, 5.1, 0, 0, 15.5, 1.2, 6.8, 0.0, 2.4, 0.6, 3.9, 0, 1.1];
|
||||
|
||||
private readonly \DateTimeImmutable $now;
|
||||
|
||||
public function __construct(?\DateTimeImmutable $now = null, private readonly string $timezone = 'Europe/Berlin')
|
||||
{
|
||||
$this->now = ($now ?? new \DateTimeImmutable('now'))->setTimezone(new \DateTimeZone($this->timezone));
|
||||
}
|
||||
|
||||
public function stationsData(): array
|
||||
{
|
||||
$at = fn(string $time) => (int) $this->now->modify($time)->format('U');
|
||||
$today = fn(string $hm) => (int) $this->now->setTime((int) substr($hm, 0, 2), (int) substr($hm, 3, 2))->format('U');
|
||||
|
||||
return ['devices' => [[
|
||||
'_id' => '70:ee:50:00:00:01', 'type' => 'NAMain', 'station_name' => 'Thuis', 'module_name' => 'Woonkamer', 'reachable' => true,
|
||||
'place' => ['timezone' => $this->timezone, 'location' => [6.55, 51.82]],
|
||||
'dashboard_data' => ['time_utc' => $at('-2 minutes'), 'Temperature' => 21.3, 'min_temp' => 20.4, 'max_temp' => 22.1,
|
||||
'date_min_temp' => $today('05:50'), 'date_max_temp' => $today('13:40'), 'temp_trend' => 'stable'],
|
||||
'modules' => [
|
||||
['_id' => '02:00:00:00:00:01', 'type' => 'NAModule1', 'module_name' => 'Buiten', 'reachable' => true,
|
||||
'dashboard_data' => ['time_utc' => $at('-3 minutes'), 'Temperature' => 16.4, 'min_temp' => 9.2, 'max_temp' => 19.8,
|
||||
'date_min_temp' => $today('06:10'), 'date_max_temp' => $today('13:05'), 'temp_trend' => 'down']],
|
||||
['_id' => '03:00:00:00:00:02', 'type' => 'NAModule4', 'module_name' => 'Slaapkamer', 'reachable' => true,
|
||||
'dashboard_data' => ['time_utc' => $at('-4 minutes'), 'Temperature' => 18.9, 'min_temp' => 18.1, 'max_temp' => 19.6, 'temp_trend' => 'up']],
|
||||
['_id' => '03:00:00:00:00:03', 'type' => 'NAModule4', 'module_name' => 'Kantoor', 'reachable' => true,
|
||||
'dashboard_data' => ['time_utc' => $at('-4 minutes'), 'Temperature' => 20.2, 'min_temp' => 19.0, 'max_temp' => 21.0, 'temp_trend' => 'stable']],
|
||||
['_id' => '05:00:00:00:00:04', 'type' => 'NAModule3', 'module_name' => 'Regenmeter', 'reachable' => true,
|
||||
'dashboard_data' => ['time_utc' => $at('-3 minutes'), 'Rain' => 0, 'sum_rain_1' => 0, 'sum_rain_24' => 2.4]],
|
||||
],
|
||||
]]];
|
||||
}
|
||||
|
||||
public function measure(string $deviceId, string $moduleId, int $begin, int $end): array
|
||||
{
|
||||
$body = [];
|
||||
$count = count(self::RAIN_PER_DAY);
|
||||
foreach (self::RAIN_PER_DAY as $i => $mm) {
|
||||
$day = $this->now->setTime(3, 17)->modify('-' . ($count - 1 - $i) . ' days');
|
||||
if ($day->getTimestamp() >= $begin) {
|
||||
$body[(string) $day->getTimestamp()] = [$mm];
|
||||
}
|
||||
}
|
||||
return $body;
|
||||
}
|
||||
|
||||
public function forecast(float $lat, float $lon, string $timezone): array
|
||||
{
|
||||
$dates = [];
|
||||
for ($i = 0; $i < 6; $i++) {
|
||||
$dates[] = $this->now->modify("+$i days")->format('Y-m-d');
|
||||
}
|
||||
return [
|
||||
'time' => $dates,
|
||||
'weather_code' => [3, 2, 0, 61, 80, 95],
|
||||
'temperature_2m_max' => [17.9, 18.3, 20.1, 17.4, 15.2, 16.0],
|
||||
'temperature_2m_min' => [11.0, 10.1, 11.3, 12.0, 9.4, 8.1],
|
||||
'precipitation_sum' => [0.0, 0.4, 0.0, 8.2, 3.1, 0.2],
|
||||
'precipitation_probability_max' => [10, 20, 5, 80, 60, 15],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Weerscherm;
|
||||
|
||||
/** Ruwe data van de drie upstream-bronnen. Implementaties: LiveSource (echte API's) en FixtureSource (voorbeelddata). */
|
||||
interface WeatherSource
|
||||
{
|
||||
/** @return array<string, mixed> de "body" van Netatmo getstationsdata */
|
||||
public function stationsData(): array;
|
||||
|
||||
/** @return array<string|int, mixed> de "body" van Netatmo getmeasure (timestamp => [mm]) */
|
||||
public function measure(string $deviceId, string $moduleId, int $begin, int $end): array;
|
||||
|
||||
/** @return array<string, mixed> het "daily"-blok van Open-Meteo */
|
||||
public function forecast(float $lat, float $lon, string $timezone): array;
|
||||
}
|
||||
Reference in New Issue
Block a user