fox/app/Console/Commands/BroadcastSystemStats.php

63 lines
2.1 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Events\SystemStatsBroadcast;
use App\Events\UptimeBroadcast;
use App\Events\WeatherBroadcast;
use App\Services\SystemStatsService;
use App\Services\UptimeService;
use App\Services\WeatherService;
use Illuminate\Console\Command;
/**
* Single producer für alle HUD-Tick-Broadcasts. Vermeidet Polling im Browser.
*/
class BroadcastSystemStats extends Command
{
protected $signature = 'fox:broadcast-stats
{--interval=5 : Sekunden zwischen System-Stats-Pushes}
{--uptime-every=6 : Wie viele Ticks zwischen Uptime-Pushes (Default: alle 30s bei interval=5)}
{--weather-every=120 : Wie viele Ticks zwischen Weather-Pushes (Default: alle 10min bei interval=5)}';
protected $description = 'Broadcastet HUD-Daten (Stats, Uptime, Weather) periodisch via Reverb.';
public function handle(
SystemStatsService $stats,
UptimeService $uptime,
WeatherService $weather,
): int {
$interval = max(1, (int) $this->option('interval'));
$uptimeEvery = max(1, (int) $this->option('uptime-every'));
$weatherEvery = max(1, (int) $this->option('weather-every'));
$this->info("HUD-Broadcaster läuft - stats:{$interval}s uptime:".($interval * $uptimeEvery)."s weather:".($interval * $weatherEvery).'s');
$tick = 0;
while (true) {
$this->safeBroadcast(fn () => broadcast(new SystemStatsBroadcast($stats->collect())), 'stats');
if ($tick % $uptimeEvery === 0) {
$this->safeBroadcast(fn () => broadcast(new UptimeBroadcast($uptime->collect())), 'uptime');
}
if ($tick % $weatherEvery === 0) {
$this->safeBroadcast(fn () => broadcast(new WeatherBroadcast($weather->fetch())), 'weather');
}
$tick++;
sleep($interval);
}
}
protected function safeBroadcast(\Closure $fn, string $label): void
{
try {
$fn();
} catch (\Throwable $e) {
$this->error("Broadcast {$label} fehlgeschlagen: ".$e->getMessage());
}
}
}