77 lines
2.0 KiB
PHP
77 lines
2.0 KiB
PHP
<?php
|
|
// API para obtener estados en tiempo real desde Redis
|
|
// Reemplaza SSE: devuelve online, ip, pines actualizados por MQTT
|
|
|
|
require_once __DIR__ . '/bootstrap.php';
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
// Conectar a Redis (mismo que listener)
|
|
try {
|
|
$redis = new Redis();
|
|
$redis->connect('127.0.0.1', 6379);
|
|
} catch (\Throwable $e) {
|
|
json_error('Error conectando Redis', 500);
|
|
}
|
|
|
|
// Cache key
|
|
$cacheKey = 'api:get_estados_realtime';
|
|
$cacheTTL = 1; // 1 segundo
|
|
|
|
// Verificar cache
|
|
$cached = $redis->get($cacheKey);
|
|
if ($cached) {
|
|
echo $cached;
|
|
exit;
|
|
}
|
|
|
|
// Si no cache, calcular
|
|
$mensajes = $redis->hGetAll('mqtt:mensajes');
|
|
$estados = [];
|
|
|
|
foreach ($mensajes as $topic => $datosJson) {
|
|
$datos = json_decode($datosJson, true);
|
|
if (!$datos || !isset($datos['payload'])) continue;
|
|
|
|
$parts = explode('/', $topic);
|
|
if (count($parts) < 3 || $parts[0] !== 'dispositivo') continue;
|
|
|
|
$chipid = $parts[1];
|
|
$tipo = $parts[2];
|
|
$subtipo = $parts[3] ?? null;
|
|
$payload = $datos['payload'];
|
|
|
|
if (!isset($estados[$chipid])) {
|
|
$estados[$chipid] = ['online' => null, 'ip' => null, 'pines' => []];
|
|
}
|
|
|
|
switch ($tipo) {
|
|
case 'state':
|
|
$estados[$chipid]['online'] = ($payload === 'online');
|
|
break;
|
|
case 'ip':
|
|
$estados[$chipid]['ip'] = $payload;
|
|
break;
|
|
case 'pin':
|
|
if ($subtipo) {
|
|
$estados[$chipid]['pines'][$subtipo] = $payload;
|
|
}
|
|
break;
|
|
case 'comando':
|
|
// Payload es JSON: {"alias": "D5", "valor": "ON"}
|
|
$data = json_decode($payload, true);
|
|
if ($data && isset($data['alias']) && isset($data['valor'])) {
|
|
$estados[$chipid]['pines'][$data['alias']] = $data['valor'];
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
|
|
$response = json_encode($estados);
|
|
|
|
// Cachear por 1 segundo
|
|
$redis->setEx($cacheKey, $cacheTTL, $response);
|
|
|
|
echo $response;
|
|
?>
|