50 lines
1.3 KiB
PHP
50 lines
1.3 KiB
PHP
|
|
<?php
|
||
|
|
require __DIR__ . '/../db.php';
|
||
|
|
|
||
|
|
// Lê o JSON do POST
|
||
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
||
|
|
if (!$input || empty($input['uid'])) {
|
||
|
|
http_response_code(400);
|
||
|
|
echo json_encode(['ok' => false, 'err' => 'missing uid']);
|
||
|
|
exit;
|
||
|
|
}
|
||
|
|
|
||
|
|
$uid = $input['uid'];
|
||
|
|
$limit = isset($input['limit']) ? (int)$input['limit'] : 20;
|
||
|
|
|
||
|
|
$pdo->beginTransaction();
|
||
|
|
|
||
|
|
// Bloqueia o device
|
||
|
|
$stmt = $pdo->prepare("SELECT id FROM devices WHERE uid=? LIMIT 1 FOR UPDATE");
|
||
|
|
$stmt->execute([$uid]);
|
||
|
|
$dev = $stmt->fetchColumn();
|
||
|
|
if (!$dev) {
|
||
|
|
$pdo->rollBack();
|
||
|
|
http_response_code(404);
|
||
|
|
echo json_encode(['ok' => false, 'err' => 'device']);
|
||
|
|
exit;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Seleciona comandos pendentes
|
||
|
|
$stmt = $pdo->prepare("
|
||
|
|
SELECT id, cmd, params
|
||
|
|
FROM commands
|
||
|
|
WHERE device_id=? AND status='pending'
|
||
|
|
ORDER BY queued_at ASC
|
||
|
|
LIMIT $limit
|
||
|
|
FOR UPDATE
|
||
|
|
");
|
||
|
|
$stmt->execute([$dev]);
|
||
|
|
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||
|
|
|
||
|
|
if ($rows) {
|
||
|
|
$ids = implode(',', array_map('intval', array_column($rows, 'id')));
|
||
|
|
$pdo->exec("UPDATE commands SET status='sent', sent_at=NOW() WHERE id IN ($ids)");
|
||
|
|
$pdo->prepare("UPDATE devices SET status='online', last_seen=NOW() WHERE id=?")->execute([$dev]);
|
||
|
|
}
|
||
|
|
|
||
|
|
$pdo->commit();
|
||
|
|
|
||
|
|
header('Content-Type: application/json');
|
||
|
|
echo json_encode(['ok' => true, 'commands' => $rows], JSON_UNESCAPED_SLASHES);
|