www/esp_proxmox.php

183 lines
9.7 KiB
PHP
Raw Normal View History

<?php
require_once __DIR__.'/inc/common.php';
define('PMX_API', 'http://192.168.10.106:8765/?key=esp_api_xupas_2025');
// Lista lida do MySQL local (cagalhao) — atualizado ao vivo pelo
// mqtt_listener.php deste container. (A API do 106 servia uma SQLite
// morta do antigo listener python; fica só para comandos MQTT.)
function pmx_get(): array {
try {
$pdo = new PDO('mysql:host=localhost;dbname=cagalhao;charset=utf8',
'master', 'master',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
return $pdo->query("
SELECT uid, online, blocked, current_broker, last_seen,
brightness, heap, rssi, fw_ver, fw_ver,
TIMESTAMPDIFF(SECOND, last_seen, NOW()) AS ago_s
FROM contadores
ORDER BY uid ASC
")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
return [];
}
}
function pmx_post(array $data): array {
$ch = curl_init(PMX_API);
curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query($data),CURLOPT_TIMEOUT=>8]);
$r = json_decode(curl_exec($ch),true); curl_close($ch);
return $r ?? [];
}
$msg = ''; $msgOk = true;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$uid = preg_replace('/[^0-9A-Fa-f]/', '', $_POST['uid'] ?? '');
if (!$uid) { $msg = 'UID invalido.'; $msgOk = false; }
else {
2026-06-27 21:35:49 +00:00
$action = $_POST['action'] ?? '';
try {
$pdo = new PDO('mysql:host=localhost;dbname=cagalhao;charset=utf8',
'master', 'master',
[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
if ($action === 'approve') {
$pdo->prepare("UPDATE contadores SET blocked=0 WHERE uid=?")->execute([$uid]);
// sincronizar na VPS
$vps = ['http'=>['method'=>'POST','header'=>'Content-Type: application/x-www-form-urlencoded',
'content'=>http_build_query(['action'=>'approve','uid'=>$uid]),'timeout'=>4]];
@file_get_contents('https://web.xpto.ooguy.com/esp_api.php?key=esp_api_xupas_2025', false, stream_context_create($vps));
$msg = "[$uid] aprovado OK"; $msgOk = true;
} elseif ($action === 'block') {
$pdo->prepare("UPDATE contadores SET blocked=1,online=0 WHERE uid=?")->execute([$uid]);
// sincronizar na VPS
$vps = ['http'=>['method'=>'POST','header'=>'Content-Type: application/x-www-form-urlencoded',
'content'=>http_build_query(['action'=>'block','uid'=>$uid]),'timeout'=>4]];
@file_get_contents('https://web.xpto.ooguy.com/esp_api.php?key=esp_api_xupas_2025', false, stream_context_create($vps));
$msg = "[$uid] bloqueado OK"; $msgOk = true;
} elseif ($action === 'delete') {
// CT106 api.py: envia DELETE_CERT via MQTT + apaga CT106 SQLite + apaga VPS SQLite
pmx_post(['uid'=>$uid,'action'=>'delete']);
// apagar também do CT102 MySQL (esta BD)
$pdo->prepare("DELETE FROM contadores WHERE uid=?")->execute([$uid]);
$msg = "[$uid] eliminado OK"; $msgOk = true;
} else {
// cmd, switch_pair, brightness — envia via CT106 api.py (MQTT)
$res = pmx_post($_POST);
if (!empty($res['ok'])) { $msg = "[$uid] $action OK"; $msgOk = true; }
else { $msg = $res['error'] ?? 'Erro'; $msgOk = false; }
}
} catch (Throwable $e) {
$msg = 'Erro BD: '.$e->getMessage(); $msgOk = false;
}
}
$qs = $msg ? ($msgOk ? '?ok='.urlencode($msg) : '?err='.urlencode($msg)) : '';
header("Location: /esp_proxmox.php$qs"); exit;
}
if (isset($_GET['ok'])) { $msg = htmlspecialchars($_GET['ok']); $msgOk = true; }
if (isset($_GET['err'])) { $msg = htmlspecialchars($_GET['err']); $msgOk = false; }
$devices = pmx_get();
$title = "ESP Devices — Proxmox";
ob_start();
?>
<div class="page-header">
<div>
<div class="breadcrumb"><a href="/painel.php">Painel</a><span class="sep"></span>ESP Devices<span class="sep"></span>Proxmox</div>
<h1>ESP Devices <span style="color:var(--muted);font-weight:400;font-size:16px">Proxmox broker</span></h1>
</div>
<a href="/esp_vps.php" class="btn btn-secondary"> Ver VPS</a>
</div>
<?php if ($msg): ?>
<div class="alert <?= $msgOk ? 'alert-success' : 'alert-error' ?>"><?= $msgOk ? '✓' : '⚠' ?> <?= $msg ?></div>
<?php endif; ?>
<?php if (!$devices): ?>
<div class="empty-state"><p>Sem dispositivos ou erro a ligar ao broker Proxmox.</p></div>
<?php else: ?>
<div class="card">
<div class="card-header">
<h2>Dispositivos <span style="color:var(--muted);font-weight:400;font-size:13px">(<?= count($devices) ?>)</span></h2>
</div>
<div class="table-wrap">
<table>
<thead><tr><th>UID</th><th>Versão</th><th>Versão</th><th>Ultimo contacto</th><th>Online</th><th>Estado</th><th>Brilho</th><th>Ações</th><th>Broker</th></tr></thead>
<tbody>
<?php foreach ($devices as $d):
$uid=$d['uid']; $blocked=(bool)$d['blocked']; $online=(bool)$d['online'];
$broker=$d['current_broker']??'--';
$last=$d['last_seen']??'-'; $bri=(int)($d['brightness']??128);
// idade calculada no MySQL (TIMESTAMPDIFF) — imune a fusos PHP/DB
$diff=isset($d['ago_s'])?(int)$d['ago_s']:($last&&$last!=='-'?time()-strtotime($last):null);
// bolinha verde no botão do broker onde está ligado
$isPmx=$online && strpos((string)$broker,'remote')===0;
$isVps=$online && !$isPmx && $broker!=='--';
$dot='<span style="display:inline-block;width:7px;height:7px;border-radius:50%;background:#3fb950;box-shadow:0 0 5px #3fb950;margin-right:4px;vertical-align:middle"></span>';
$ago=$diff===null?'-':($diff<60?$diff.'s':($diff<3600?round($diff/60).'min':round($diff/3600).'h')).' atras';
?>
<tr>
<td style="font-family:monospace;font-size:12px"><?= h($uid) ?></td><td style="font-size:12px;color:#8b949e"><?= ($d['fw_ver']??'')!=='' ? h($d['fw_ver']) : '—' ?></td>
<td style="font-size:12px;color:var(--muted)"><?= h($d['fw_ver'] ?? '—') ?></td>
<td style="color:var(--muted);font-size:12px"><?= h($last) ?><br><span style="font-size:11px"><?= $ago ?></span></td>
<td><?php if($online):?><span class="badge" style="background:#0d2818;color:#3fb950">online</span><?php else:?><span class="badge" style="background:#1e2733;color:var(--muted)">offline</span><?php endif;?></td>
<td><?php if($blocked):?><span class="badge" style="background:#2d1a1a;color:#f85149">bloqueado</span><?php else:?><span class="badge" style="background:#0d2818;color:#3fb950">aprovado</span><?php endif;?></td>
<td><div style="display:flex;align-items:center;gap:6px">
<input type="range" min="0" max="255" value="<?= $bri ?>" id="bri_<?= h($uid) ?>" style="width:90px;accent-color:var(--accent)" oninput="setBri('<?= h($uid) ?>',this.value)" <?= $online?'':'disabled'?>>
<span id="brival_<?= h($uid) ?>" style="font-size:11px;color:var(--muted);min-width:24px"><?= $bri ?></span>
</div></td>
<td style="white-space:nowrap">
<?php if($blocked):?>
<button class="btn btn-secondary btn-sm" data-uid="<?= h($uid) ?>" data-act="approve">Aprovar</button>
<?php else:?>
<button class="btn btn-danger btn-sm" data-uid="<?= h($uid) ?>" data-act="block">Bloquear</button>
<?php endif;?>
<button class="btn btn-secondary btn-sm" data-uid="<?= h($uid) ?>" data-act="cmd" data-cmd="REBOOT">Reboot</button>
<button class="btn btn-danger btn-sm" data-uid="<?= h($uid) ?>" data-act="delete"></button>
</td>
2026-06-27 21:42:20 +00:00
<td style="text-align:center">
<div style="font-size:10px;color:var(--muted);margin-bottom:3px"><?= $isVps?'VPS':($isPmx?'PMX':'—') ?></div>
<span title="VPS" data-uid="<?= h($uid) ?>" data-act="switch_pair" data-pair="0"
style="cursor:pointer;display:inline-block;width:10px;height:10px;border-radius:50%;margin:0 3px;
background:<?= $isVps?'#3fb950':'#333' ?>;<?= $isVps?'box-shadow:0 0 5px #3fb950;':'' ?>"></span>
<span title="Proxmox" data-uid="<?= h($uid) ?>" data-act="switch_pair" data-pair="1"
style="cursor:pointer;display:inline-block;width:10px;height:10px;border-radius:50%;margin:0 3px;
background:<?= $isPmx?'#3fb950':'#333' ?>;<?= $isPmx?'box-shadow:0 0 5px #3fb950;':'' ?>"></span>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
</div>
<?php endif;?>
<script>
const _bt={};
function act(uid, action, extra){
const fd=new FormData(); fd.append('uid',uid); fd.append('action',action);
if(extra) Object.keys(extra).forEach(k=>fd.append(k,extra[k]));
fetch('/esp_proxmox.php',{method:'POST',body:fd}).then(()=>location.reload());
}
document.addEventListener('click',function(e){
2026-06-27 21:42:20 +00:00
const b=e.target.closest('[data-act]'); if(!b) return;
if(b.dataset.act==='delete' && !confirm('Remover '+b.dataset.uid+'?')) return;
const extra={};
if(b.dataset.pair!==undefined) extra.pair=b.dataset.pair;
if(b.dataset.cmd!==undefined) extra.cmd=b.dataset.cmd;
act(b.dataset.uid,b.dataset.act,extra);
});
function setBri(uid,val){
document.getElementById('brival_'+uid).textContent=val;
clearTimeout(_bt[uid]);
_bt[uid]=setTimeout(()=>{
const fd=new FormData();
fd.append('action','brightness');fd.append('uid',uid);fd.append('value',val);
fetch('/esp_proxmox.php',{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});
},400);
}
</script>
<?php $content = ob_get_clean(); require __DIR__.'/inc/layout.php';