diff --git a/api/mqtt_listener.php b/api/mqtt_listener.php index 7ff97ee..419712a 100644 --- a/api/mqtt_listener.php +++ b/api/mqtt_listener.php @@ -179,6 +179,58 @@ $subscribeTls = function () use ($mqttTls, $db, $deviceSecret) { }, 0); + // EVENTOS DE JOGO (contadores) — esp//event, assinados HMAC. + // O ESP só reporta; os contadores vivem AQUI (MySQL): + // credit → entradas(+total) += value + // spin → jogadas += 1, saidas(+total) += won + $mqttTls->subscribe('esp/+/event', function (string $topic, string $msg) + use ($db, $deviceSecret) + { + $uid = explode('/', $topic)[1] ?? null; + if (!$uid) return; + + $j = json_decode($msg, true); + $type = (string)($j['type'] ?? ''); + $value = (int)($j['value'] ?? 0); + $won = (int)($j['won'] ?? 0); + $balance = (int)($j['balance'] ?? 0); + $hmac = strtoupper((string)($j['hmac'] ?? '')); + + if ($type === '' || $hmac === '') { + logmsg("EVENT malformado $uid — ignorado", LOG_ERROR); + return; + } + + // mesma dupla de segredos dos STATUS: global OU per-device (Fase C) + $_m = "$uid|$type|$value|$won|$balance"; + $_eg = strtoupper(hash_hmac('sha256', $_m, $deviceSecret)); + $_dsec = hash_hmac('sha256', $uid, 'af2e8f1b5411d7df7c9b3dba45fa4ca4517329d28d2550d29be898d34b015952'); + $_ed = strtoupper(hash_hmac('sha256', $_m, $_dsec)); + if (!hash_equals($_ed, $hmac) && !hash_equals($_eg, $hmac)) { + logmsg("EVENT HMAC INVÁLIDO $uid ($type) — ignorado", LOG_ERROR); + return; + } + + if ($type === 'credit') { + $db->prepare("UPDATE contadores SET + entradas = entradas + :v, + entradas_total = entradas_total + :v2 + WHERE uid = :uid") + ->execute(['v' => $value, 'v2' => $value, 'uid' => $uid]); + logmsg("EVENT credit $uid +$value bal=$balance"); + } elseif ($type === 'spin') { + $db->prepare("UPDATE contadores SET + jogadas = jogadas + 1, + saidas = saidas + :w, + saidas_total = saidas_total + :w2 + WHERE uid = :uid") + ->execute(['w' => $won, 'w2' => $won, 'uid' => $uid]); + logmsg("EVENT spin $uid won=$won bal=$balance"); + } else { + logmsg("EVENT tipo desconhecido '$type' de $uid — ignorado", LOG_ERROR); + } + }, 1); + // PEDIDO DE HORA GLOBAL $mqttTls->subscribe('time/request', function (string $topic, string $msg) use ($mqttTls) { $payload = json_encode(['h' => (int)date('H'), 'm' => (int)date('i')]);