Initial php-adb: LAN Android TV scanner and ADB controller

This commit is contained in:
Clarth 2026-12-03 20:05:28 -05:00
commit 9e016b251f
8 changed files with 1361 additions and 0 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
/data/devices.json
/data/*.tmp
.DS_Store

17
Agents.md Normal file
View file

@ -0,0 +1,17 @@
git remote add origin https://git.claytonia.net/Clarth/php-adb.git
git push -u origin main
The git credentials are stored at ~/.config/git/credentials, which is the store configured for git.claytonia.net, http only no ssh.
I want a php app that scans 192.168.1.* and 192.168.2.* for android tv boxes and get their names to display
I think want to use the webpage to control the boxes and send ADB commands to them
it shouldnt try to connect to a box unless told to
make it modern css and js animations and tooling
will be run on LAN only

310
api.php Normal file
View file

@ -0,0 +1,310 @@
<?php
declare(strict_types=1);
require __DIR__ . '/lib/adb.php';
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
function json_out(array $data, int $status = 200): never
{
http_response_code($status);
echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
exit;
}
function read_input(): array
{
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (stripos($contentType, 'application/json') !== false) {
$raw = file_get_contents('php://input');
$decoded = json_decode($raw ?: '', true);
if (is_array($decoded)) {
return $decoded;
}
}
return $_POST;
}
function scan_subnets(): array
{
$subnets = ['192.168.1.', '192.168.2.'];
$targets = [];
foreach ($subnets as $prefix) {
for ($i = 1; $i <= 254; $i++) {
$targets[] = $prefix . $i;
}
}
$pending = []; // ip => [socket, deadline]
$found = [];
$timeout = 1.2;
$start = microtime(true);
foreach ($targets as $ip) {
$errno = 0;
$errstr = '';
$sock = @stream_socket_client(
'tcp://' . $ip . ':5555',
$errno,
$errstr,
0.1,
STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT
);
if (is_resource($sock)) {
stream_set_blocking($sock, false);
$pending[$ip] = ['sock' => $sock, 'deadline' => $start + $timeout];
}
}
while (!empty($pending)) {
$write = [];
$except = [];
foreach ($pending as $ip => $info) {
$write[] = $info['sock'];
$except[] = $info['sock'];
}
$read = null;
$ready = @stream_select($read, $write, $except, 0, 100000); // 100ms
$now = microtime(true);
$writable = [];
foreach ($write as $s) {
$writable[(int) $s] = $s;
}
$errored = [];
foreach ($except as $s) {
$errored[(int) $s] = $s;
}
foreach ($pending as $ip => $info) {
$id = (int) $info['sock'];
$isWritable = isset($writable[$id]);
$isErrored = isset($errored[$id]);
$isExpired = $now >= $info['deadline'];
if ($isWritable || $isErrored) {
$open = false;
if ($isWritable && !$isErrored) {
// For async connects, writable usually means connected; verify SO_ERROR when possible.
$err = null;
if (function_exists('socket_import_stream') && function_exists('socket_get_option')) {
$sockRes = @socket_import_stream($info['sock']);
if ($sockRes !== false && $sockRes !== null) {
$err = @socket_get_option($sockRes, SOL_SOCKET, SO_ERROR);
}
}
$open = ($err === 0 || $err === null);
}
if ($open) {
$found[] = $ip;
}
fclose($info['sock']);
unset($pending[$ip]);
continue;
}
if ($isExpired) {
fclose($info['sock']);
unset($pending[$ip]);
}
}
if ($ready === 0) {
// loop will handle expirations
}
}
sort($found, SORT_NATURAL);
return $found;
}
$action = $_GET['action'] ?? ($_POST['action'] ?? '');
$input = read_input();
if ($action === '' && isset($input['action'])) {
$action = (string) $input['action'];
}
$action = trim((string) $action);
try {
switch ($action) {
case 'status': {
$devices = load_devices();
$adb = adb_devices();
json_out([
'ok' => true,
'adb_available' => adb_available(),
'adb_devices' => $adb,
'known_devices' => $devices,
]);
}
case 'scan': {
$foundIps = scan_subnets();
$known = load_devices();
$knownByIp = [];
foreach ($known as $d) {
if (isset($d['ip'])) {
$knownByIp[$d['ip']] = $d;
}
}
$adb = adb_devices();
$adbByIp = [];
foreach ($adb as $d) {
if (!empty($d['ip'])) {
$adbByIp[$d['ip']] = $d;
}
}
$results = [];
foreach ($foundIps as $ip) {
$k = $knownByIp[$ip] ?? null;
$a = $adbByIp[$ip] ?? null;
$results[] = [
'ip' => $ip,
'port_open' => true,
'name' => $k['name'] ?? '',
'last_seen' => gmdate('c'),
'last_connected' => $k['last_connected'] ?? null,
'adb_state' => $a['state'] ?? null,
];
upsert_device($ip, ['last_seen' => gmdate('c')]);
}
// Also include known devices that were not found in this scan
foreach ($known as $k) {
$ip = $k['ip'] ?? '';
if (!is_allowed_ip($ip)) {
continue;
}
if (in_array($ip, $foundIps, true)) {
continue;
}
$a = $adbByIp[$ip] ?? null;
$results[] = [
'ip' => $ip,
'port_open' => false,
'name' => $k['name'] ?? '',
'last_seen' => $k['last_seen'] ?? null,
'last_connected' => $k['last_connected'] ?? null,
'adb_state' => $a['state'] ?? null,
];
}
usort($results, function ($a, $b) {
if (($a['port_open'] ?? false) !== ($b['port_open'] ?? false)) {
return ($a['port_open'] ? 0 : 1) <=> ($b['port_open'] ? 0 : 1);
}
return strnatcmp($a['ip'], $b['ip']);
});
json_out([
'ok' => true,
'adb_available' => adb_available(),
'devices' => $results,
'scanned_at' => gmdate('c'),
]);
}
case 'connect': {
$ip = normalize_ip((string) ($input['ip'] ?? ''));
if ($ip === null) {
json_out(['ok' => false, 'error' => 'Invalid IP. Only 192.168.1.* and 192.168.2.* are allowed.'], 400);
}
if (!adb_available()) {
json_out(['ok' => false, 'error' => 'adb is not installed or not in PATH.'], 500);
}
$res = adb_connect($ip);
$name = null;
if ($res['ok']) {
$name = adb_get_name($ip);
upsert_device($ip, [
'name' => $name ?? '',
'last_seen' => gmdate('c'),
'last_connected' => gmdate('c'),
]);
}
$devices = load_devices();
json_out([
'ok' => $res['ok'],
'ip' => $ip,
'name' => $name,
'output' => $res['output'],
'known_devices' => $devices,
'adb_devices' => adb_devices(),
]);
}
case 'disconnect': {
$ip = normalize_ip((string) ($input['ip'] ?? ''));
if ($ip === null) {
json_out(['ok' => false, 'error' => 'Invalid IP.'], 400);
}
if (!adb_available()) {
json_out(['ok' => false, 'error' => 'adb is not installed or not in PATH.'], 500);
}
$res = adb_disconnect($ip);
json_out([
'ok' => $res['ok'],
'ip' => $ip,
'output' => $res['output'],
'adb_devices' => adb_devices(),
]);
}
case 'command': {
$ip = normalize_ip((string) ($input['ip'] ?? ''));
if ($ip === null) {
json_out(['ok' => false, 'error' => 'Invalid IP.'], 400);
}
if (!adb_available()) {
json_out(['ok' => false, 'error' => 'adb is not installed or not in PATH.'], 500);
}
$cmdType = trim((string) ($input['command'] ?? ''));
$result = ['ok' => false, 'output' => 'Unknown command'];
if ($cmdType === 'key') {
$key = strtoupper(trim((string) ($input['keycode'] ?? '')));
$allowed = [
'KEYCODE_HOME', 'KEYCODE_BACK', 'KEYCODE_DPAD_UP', 'KEYCODE_DPAD_DOWN',
'KEYCODE_DPAD_LEFT', 'KEYCODE_DPAD_RIGHT', 'KEYCODE_DPAD_CENTER',
'KEYCODE_ENTER', 'KEYCODE_MENU', 'KEYCODE_APP_SWITCH', 'KEYCODE_POWER',
'KEYCODE_VOLUME_UP', 'KEYCODE_VOLUME_DOWN', 'KEYCODE_MUTE',
'KEYCODE_MEDIA_PLAY_PAUSE', 'KEYCODE_MEDIA_PLAY', 'KEYCODE_MEDIA_PAUSE',
'KEYCODE_MEDIA_NEXT', 'KEYCODE_MEDIA_PREVIOUS', 'KEYCODE_MEDIA_STOP',
'KEYCODE_MEDIA_REWIND', 'KEYCODE_MEDIA_FAST_FORWARD',
'KEYCODE_CHANNEL_UP', 'KEYCODE_CHANNEL_DOWN',
'KEYCODE_INFO', 'KEYCODE_GUIDE', 'KEYCODE_SETTINGS',
'KEYCODE_SLEEP', 'KEYCODE_WAKEUP', 'KEYCODE_SOFT_SLEEP',
'KEYCODE_0','KEYCODE_1','KEYCODE_2','KEYCODE_3','KEYCODE_4',
'KEYCODE_5','KEYCODE_6','KEYCODE_7','KEYCODE_8','KEYCODE_9',
'KEYCODE_DEL', 'KEYCODE_FORWARD_DEL', 'KEYCODE_SPACE',
'KEYCODE_SEARCH', 'KEYCODE_NAVIGATE_PREVIOUS', 'KEYCODE_NAVIGATE_NEXT',
];
if (!in_array($key, $allowed, true)) {
json_out(['ok' => false, 'error' => 'Keycode not allowed.'], 400);
}
$result = adb_send_key($ip, $key);
} elseif ($cmdType === 'text') {
$text = (string) ($input['text'] ?? '');
$result = adb_send_text($ip, $text);
} elseif ($cmdType === 'launch_home') {
$result = adb_send_key($ip, 'KEYCODE_HOME');
} else {
json_out(['ok' => false, 'error' => 'Unsupported command type.'], 400);
}
json_out([
'ok' => $result['ok'],
'ip' => $ip,
'command' => $cmdType,
'output' => $result['output'],
]);
}
default:
json_out(['ok' => false, 'error' => 'Unknown action.'], 400);
}
} catch (Throwable $e) {
json_out(['ok' => false, 'error' => 'Server error: ' . $e->getMessage()], 500);
}

219
assets/app.css Normal file
View file

@ -0,0 +1,219 @@
/* Scoped additions on top of the shared stylesheet */
.no-margin-top { margin-top: 0 !important; }
.wrap-actions { flex-wrap: wrap; }
.hero-card {
background: linear-gradient(180deg, rgba(79, 163, 255, 0.06), transparent 60%);
}
.status-pill {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
border: 1px solid var(--line);
border-radius: 999px;
font-size: .8rem;
color: var(--muted);
white-space: nowrap;
transition: border-color .25s ease, color .25s ease, background .25s ease;
}
.status-pill.is-ok {
color: var(--success);
border-color: rgba(123, 220, 162, .45);
background: rgba(123, 220, 162, .06);
}
.status-pill.is-bad {
color: var(--urgent);
border-color: rgba(239, 101, 101, .45);
background: rgba(239, 101, 101, .06);
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 0 0 currentColor;
}
.status-pill.is-ok .status-dot,
.status-pill.is-bad .status-dot {
animation: pulse-dot 2s ease-in-out infinite;
}
@keyframes pulse-dot {
0%, 100% { box-shadow: 0 0 0 0 rgba(127,127,127,0); opacity: 1; }
50% { box-shadow: 0 0 0 5px rgba(127,127,127,0.12); opacity: .8; }
}
.dashboard-grid {
grid-template-columns: minmax(0, 1.1fr) minmax(0, .9fr);
align-items: start;
}
.device-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 12px;
min-height: 120px;
}
.device-card {
display: flex;
flex-direction: column;
gap: 8px;
padding: 14px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: transparent;
cursor: pointer;
text-align: left;
width: 100%;
transition: transform .18s ease, border-color .18s ease, background .18s ease, box-shadow .18s ease;
animation: card-in .28s ease both;
}
.device-card:hover {
transform: translateY(-2px);
border-color: rgba(79, 163, 255, .5);
background: var(--hover);
}
.device-card:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.device-card.is-selected {
border-color: var(--accent);
background: rgba(79, 163, 255, .08);
box-shadow: inset 0 0 0 1px rgba(79, 163, 255, .25);
}
.device-card.is-offline {
opacity: .72;
}
.device-card.is-offline:hover { opacity: 1; }
@keyframes card-in {
from { opacity: 0; transform: translateY(8px) scale(.985); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
.device-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
}
.device-name {
font-weight: 600;
font-size: .95rem;
line-height: 1.3;
overflow-wrap: anywhere;
}
.device-ip {
font-family: var(--mono);
font-size: .8rem;
color: var(--muted);
}
.device-meta {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: auto;
}
.badge.is-open {
color: var(--success);
border-color: rgba(123, 220, 162, .45);
}
.badge.is-closed {
color: var(--muted);
}
.badge.is-adb {
color: var(--accent);
border-color: rgba(79, 163, 255, .45);
}
.hint-foot { margin: 14px 0 0; }
.selected-device {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px;
border: 1px solid var(--line);
border-radius: var(--radius);
margin-bottom: 14px;
background: rgba(128,128,128,.03);
}
.selected-name {
margin: 0;
font-size: 1.05rem;
font-weight: 600;
}
.remote-section { margin-top: 16px; }
.remote-section .section-title { margin-bottom: 8px; }
.remote-grid {
display: grid;
grid-template-columns: repeat(3, 64px);
gap: 8px;
justify-content: start;
}
.remote-btn {
min-height: 52px;
font-size: 1rem;
padding: 0;
user-select: none;
transition: transform .08s ease, border-color .15s ease, background .15s ease;
}
.remote-btn:active,
.remote-btn.is-pressed {
transform: scale(.96);
}
.remote-btn.sent {
border-color: var(--success);
color: var(--success);
}
.command-log-details { margin-top: 16px; }
.command-log {
margin: 0;
max-height: 220px;
overflow: auto;
font-size: .78rem;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-word;
}
#scanAlert, #commandAlert { margin-bottom: 12px; }
.is-loading {
position: relative;
pointer-events: none;
opacity: .7;
}
.is-loading::after {
content: "";
width: 14px;
height: 14px;
border: 2px solid currentColor;
border-right-color: transparent;
border-radius: 50%;
display: inline-block;
animation: spin .7s linear infinite;
margin-left: 2px;
}
@keyframes spin { to { transform: rotate(360deg); } }
@media (max-width: 900px) {
.dashboard-grid { grid-template-columns: 1fr; }
}
@media (max-width: 560px) {
.selected-device { flex-direction: column; align-items: stretch; }
.remote-grid { grid-template-columns: repeat(3, minmax(56px, 72px)); }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; }
}

407
assets/app.js Normal file
View file

@ -0,0 +1,407 @@
(() => {
'use strict';
const els = {
adbStatus: document.getElementById('adbStatus'),
scanBtn: document.getElementById('scanBtn'),
refreshBtn: document.getElementById('refreshBtn'),
scanMeta: document.getElementById('scanMeta'),
scanAlert: document.getElementById('scanAlert'),
devicesList: document.getElementById('devicesList'),
deviceCount: document.getElementById('deviceCount'),
selectedBadge: document.getElementById('selectedBadge'),
controlEmpty: document.getElementById('controlEmpty'),
controlPanel: document.getElementById('controlPanel'),
selectedName: document.getElementById('selectedName'),
selectedIp: document.getElementById('selectedIp'),
connectBtn: document.getElementById('connectBtn'),
disconnectBtn: document.getElementById('disconnectBtn'),
commandAlert: document.getElementById('commandAlert'),
textForm: document.getElementById('textForm'),
textInput: document.getElementById('textInput'),
commandLog: document.getElementById('commandLog'),
};
const state = {
devices: [],
adbDevices: [],
selectedIp: null,
adbAvailable: false,
scanning: false,
};
function escapeHtml(str) {
return String(str)
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}
function fmtTime(iso) {
if (!iso) return 'Never';
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return iso;
return d.toLocaleString();
}
function setAlert(el, msg, type = '') {
if (!msg) {
el.hidden = true;
el.textContent = '';
el.className = 'alert';
return;
}
el.hidden = false;
el.textContent = msg;
el.className = 'alert' + (type ? ' is-' + type : '');
}
function setLoading(btn, loading, label) {
if (!btn) return;
btn.disabled = loading;
btn.classList.toggle('is-loading', loading);
if (label) {
if (loading) {
btn.dataset.originalText = btn.textContent;
btn.textContent = label;
} else {
btn.textContent = btn.dataset.originalText || btn.textContent;
}
}
}
function log(line) {
const ts = new Date().toLocaleTimeString();
const entry = `[${ts}] ${line}`;
if (els.commandLog.textContent === 'No commands sent yet.') {
els.commandLog.textContent = entry;
} else {
els.commandLog.textContent = entry + '\n' + els.commandLog.textContent;
}
}
async function api(action, payload = null, method = 'GET') {
const opts = { headers: { 'Accept': 'application/json' } };
let url = `api.php?action=${encodeURIComponent(action)}`;
if (payload && method === 'GET') {
const params = new URLSearchParams(payload);
url += '&' + params.toString();
}
if (method !== 'GET') {
opts.method = method;
opts.headers['Content-Type'] = 'application/json';
opts.body = JSON.stringify(payload || {});
}
const res = await fetch(url, opts);
const data = await res.json().catch(() => ({ ok: false, error: 'Invalid JSON response' }));
if (!res.ok && !data.error) {
data.error = `HTTP ${res.status}`;
}
return data;
}
function updateAdbStatus() {
const pill = els.adbStatus;
const text = pill.querySelector('.status-text');
pill.classList.remove('is-ok', 'is-bad');
if (state.adbAvailable) {
pill.classList.add('is-ok');
text.textContent = 'ADB available';
} else {
pill.classList.add('is-bad');
text.textContent = 'ADB not found';
}
}
function getSelectedDevice() {
return state.devices.find(d => d.ip === state.selectedIp) || null;
}
function isAdbConnected(ip) {
return state.adbDevices.some(d => d.ip === ip && d.state === 'device');
}
function renderDevices() {
const devices = state.devices;
els.deviceCount.textContent = String(devices.length);
if (!devices.length) {
els.devicesList.innerHTML = '<p class="empty">No devices found. Run a scan to discover boxes with port 5555 open.</p>';
return;
}
const html = devices.map((d, i) => {
const selected = d.ip === state.selectedIp ? ' is-selected' : '';
const offline = d.port_open ? '' : ' is-offline';
const name = d.name ? escapeHtml(d.name) : 'Unknown device';
const ip = escapeHtml(d.ip);
const portBadge = d.port_open
? '<span class="badge is-open">Port 5555 open</span>'
: '<span class="badge is-closed">Not found on scan</span>';
const adbState = d.adb_state || (isAdbConnected(d.ip) ? 'device' : '');
const adbBadge = adbState
? `<span class="badge is-adb">ADB: ${escapeHtml(adbState)}</span>`
: '';
const seen = d.last_seen ? `Seen: ${escapeHtml(fmtTime(d.last_seen))}` : 'Never seen';
const delay = Math.min(i * 30, 300);
return `
<button type="button" class="device-card${selected}${offline}" data-ip="${ip}" style="animation-delay:${delay}ms">
<div class="device-top">
<div>
<div class="device-name">${name}</div>
<div class="device-ip">${ip}</div>
</div>
</div>
<div class="device-meta">
${portBadge}
${adbBadge}
</div>
<div class="muted small">${seen}</div>
</button>`;
}).join('');
els.devicesList.innerHTML = html;
els.devicesList.querySelectorAll('.device-card').forEach(btn => {
btn.addEventListener('click', () => selectDevice(btn.dataset.ip));
});
}
function renderControl() {
const device = getSelectedDevice();
if (!device) {
els.controlEmpty.hidden = false;
els.controlPanel.hidden = true;
els.selectedBadge.textContent = 'No device selected';
return;
}
els.controlEmpty.hidden = true;
els.controlPanel.hidden = false;
els.selectedName.textContent = device.name || 'Unknown device';
els.selectedIp.textContent = device.ip;
const connected = isAdbConnected(device.ip) || device.adb_state === 'device';
els.selectedBadge.textContent = connected ? 'Connected' : 'Selected';
els.connectBtn.disabled = false;
els.disconnectBtn.disabled = false;
}
function selectDevice(ip) {
state.selectedIp = ip;
renderDevices();
renderControl();
setAlert(els.commandAlert, '');
}
function mergeDevices(incoming) {
const byIp = new Map(state.devices.map(d => [d.ip, d]));
for (const d of incoming) {
const prev = byIp.get(d.ip) || {};
byIp.set(d.ip, { ...prev, ...d });
}
state.devices = Array.from(byIp.values()).sort((a, b) => {
if (!!a.port_open !== !!b.port_open) return a.port_open ? -1 : 1;
return a.ip.localeCompare(b.ip, undefined, { numeric: true });
});
}
async function loadStatus() {
try {
const data = await api('status');
if (data.ok) {
state.adbAvailable = !!data.adb_available;
state.adbDevices = data.adb_devices || [];
if (Array.isArray(data.known_devices)) {
const known = data.known_devices.map(d => ({
ip: d.ip,
name: d.name || '',
last_seen: d.last_seen || null,
last_connected: d.last_connected || null,
port_open: false,
adb_state: (state.adbDevices.find(a => a.ip === d.ip) || {}).state || null,
}));
mergeDevices(known);
}
updateAdbStatus();
renderDevices();
renderControl();
}
} catch (e) {
setAlert(els.scanAlert, 'Failed to load status: ' + e.message, 'urgent');
}
}
async function scan() {
if (state.scanning) return;
state.scanning = true;
setLoading(els.scanBtn, true, 'Scanning…');
setAlert(els.scanAlert, '');
els.scanMeta.textContent = 'Scanning 192.168.1.* and 192.168.2.* for port 5555…';
try {
const data = await api('scan');
if (!data.ok) {
throw new Error(data.error || 'Scan failed');
}
state.adbAvailable = !!data.adb_available;
state.devices = (data.devices || []).sort((a, b) => {
if (!!a.port_open !== !!b.port_open) return a.port_open ? -1 : 1;
return a.ip.localeCompare(b.ip, undefined, { numeric: true });
});
// refresh adb states from status
const st = await api('status');
if (st.ok) {
state.adbDevices = st.adb_devices || [];
state.adbAvailable = !!st.adb_available;
for (const d of state.devices) {
const a = state.adbDevices.find(x => x.ip === d.ip);
d.adb_state = a ? a.state : d.adb_state;
}
}
updateAdbStatus();
renderDevices();
renderControl();
const found = state.devices.filter(d => d.port_open).length;
els.scanMeta.textContent = `Scanned at ${fmtTime(data.scanned_at)} — ${found} open port(s) found.`;
if (found === 0) {
setAlert(els.scanAlert, 'No devices with port 5555 open were found. Known devices (if any) are shown below.', 'warning');
}
} catch (e) {
setAlert(els.scanAlert, 'Scan error: ' + e.message, 'urgent');
els.scanMeta.textContent = 'Scan failed.';
} finally {
state.scanning = false;
setLoading(els.scanBtn, false);
}
}
async function connectSelected() {
const device = getSelectedDevice();
if (!device) return;
setLoading(els.connectBtn, true, 'Connecting…');
setAlert(els.commandAlert, '');
try {
const data = await api('connect', { ip: device.ip }, 'POST');
log(`CONNECT ${device.ip}: ${data.output || (data.ok ? 'ok' : 'failed')}`);
if (data.ok) {
state.adbDevices = data.adb_devices || state.adbDevices;
if (Array.isArray(data.known_devices)) {
mergeDevices(data.known_devices.map(d => ({ ...d, port_open: device.port_open })));
}
if (data.name) {
const d = state.devices.find(x => x.ip === device.ip);
if (d) d.name = data.name;
}
const d = state.devices.find(x => x.ip === device.ip);
if (d) d.adb_state = 'device';
setAlert(els.commandAlert, `Connected to ${device.ip}${data.name ? ' (' + data.name + ')' : ''}.`, 'success');
} else {
setAlert(els.commandAlert, data.error || data.output || 'Connect failed.', 'urgent');
}
renderDevices();
renderControl();
} catch (e) {
setAlert(els.commandAlert, 'Connect error: ' + e.message, 'urgent');
} finally {
setLoading(els.connectBtn, false);
}
}
async function disconnectSelected() {
const device = getSelectedDevice();
if (!device) return;
setLoading(els.disconnectBtn, true, 'Disconnecting…');
setAlert(els.commandAlert, '');
try {
const data = await api('disconnect', { ip: device.ip }, 'POST');
log(`DISCONNECT ${device.ip}: ${data.output || (data.ok ? 'ok' : 'failed')}`);
if (data.ok) {
state.adbDevices = data.adb_devices || [];
const d = state.devices.find(x => x.ip === device.ip);
if (d) d.adb_state = null;
setAlert(els.commandAlert, `Disconnected from ${device.ip}.`, 'success');
} else {
setAlert(els.commandAlert, data.error || data.output || 'Disconnect failed.', 'urgent');
}
renderDevices();
renderControl();
} catch (e) {
setAlert(els.commandAlert, 'Disconnect error: ' + e.message, 'urgent');
} finally {
setLoading(els.disconnectBtn, false);
}
}
async function sendKey(keycode, btn) {
const device = getSelectedDevice();
if (!device) {
setAlert(els.commandAlert, 'Select a device first.', 'warning');
return;
}
btn.classList.add('is-pressed');
setTimeout(() => btn.classList.remove('is-pressed'), 120);
setAlert(els.commandAlert, '');
try {
const data = await api('command', { ip: device.ip, command: 'key', keycode }, 'POST');
log(`KEY ${keycode} -> ${device.ip}: ${data.ok ? 'ok' : (data.error || data.output || 'failed')}`);
if (data.ok) {
btn.classList.add('sent');
setTimeout(() => btn.classList.remove('sent'), 350);
} else {
setAlert(els.commandAlert, data.error || data.output || 'Command failed.', 'urgent');
}
} catch (e) {
setAlert(els.commandAlert, 'Command error: ' + e.message, 'urgent');
}
}
async function sendText(text) {
const device = getSelectedDevice();
if (!device) {
setAlert(els.commandAlert, 'Select a device first.', 'warning');
return;
}
const submitBtn = els.textForm.querySelector('button[type="submit"]');
setLoading(submitBtn, true, 'Sending…');
setAlert(els.commandAlert, '');
try {
const data = await api('command', { ip: device.ip, command: 'text', text }, 'POST');
log(`TEXT -> ${device.ip}: ${data.ok ? 'ok' : (data.error || data.output || 'failed')}`);
if (data.ok) {
els.textInput.value = '';
setAlert(els.commandAlert, 'Text sent.', 'success');
} else {
setAlert(els.commandAlert, data.error || data.output || 'Failed to send text.', 'urgent');
}
} catch (e) {
setAlert(els.commandAlert, 'Text error: ' + e.message, 'urgent');
} finally {
setLoading(submitBtn, false);
}
}
function bindEvents() {
els.scanBtn.addEventListener('click', scan);
els.refreshBtn.addEventListener('click', async () => {
setLoading(els.refreshBtn, true, 'Refreshing…');
await loadStatus();
setLoading(els.refreshBtn, false);
els.scanMeta.textContent = 'Status refreshed.';
});
els.connectBtn.addEventListener('click', connectSelected);
els.disconnectBtn.addEventListener('click', disconnectSelected);
document.querySelectorAll('[data-key]').forEach(btn => {
btn.addEventListener('click', () => sendKey(btn.dataset.key, btn));
});
els.textForm.addEventListener('submit', (e) => {
e.preventDefault();
const text = els.textInput.value.trim();
if (!text) return;
sendText(text);
});
}
bindEvents();
loadStatus();
})();

1
data/.gitkeep Normal file
View file

@ -0,0 +1 @@

137
index.php Normal file
View file

@ -0,0 +1,137 @@
<?php
declare(strict_types=1);
?><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PHP ADB TV Control</title>
<link rel="stylesheet" href="https://vps0.claygarth.com/style.css">
<link rel="stylesheet" href="assets/app.css">
</head>
<body>
<div class="container stack">
<header class="card hero-card">
<div class="card-header">
<div>
<p class="section-title">LAN Controller</p>
<h1 class="no-margin">Android TV ADB</h1>
<p class="muted no-margin">Scan 192.168.1.* and 192.168.2.* for Android TV boxes, then connect only when you choose.</p>
</div>
<div class="status-pill" id="adbStatus" aria-live="polite">
<span class="status-dot" aria-hidden="true"></span>
<span class="status-text">Checking ADB…</span>
</div>
</div>
<div class="row between">
<div class="actions no-margin-top">
<button type="button" class="button button-primary" id="scanBtn">
<span class="btn-icon" aria-hidden="true">⌕</span>
Scan Network
</button>
<button type="button" class="button" id="refreshBtn">
Refresh Status
</button>
</div>
<p class="muted small no-margin" id="scanMeta">Not scanned yet.</p>
</div>
</header>
<div class="grid dashboard-grid">
<section class="card" aria-labelledby="devices-title">
<div class="card-header">
<h2 class="section-title" id="devices-title">Discovered Devices</h2>
<span class="badge" id="deviceCount">0</span>
</div>
<div id="scanAlert" class="alert" hidden></div>
<div id="devicesList" class="device-grid" aria-live="polite">
<p class="empty">No scan yet. Click <strong>Scan Network</strong> to look for devices with port 5555 open.</p>
</div>
<p class="muted small hint-foot">Discovery probes TCP port 5555 only. It does not run <code>adb connect</code> until you press Connect.</p>
</section>
<section class="card" aria-labelledby="control-title">
<div class="card-header">
<h2 class="section-title" id="control-title">Remote Control</h2>
<span class="badge" id="selectedBadge">No device selected</span>
</div>
<div id="controlEmpty" class="empty">
Select a device from the left to connect and send commands.
</div>
<div id="controlPanel" hidden>
<div class="selected-device">
<div>
<p class="selected-name" id="selectedName">Unknown device</p>
<p class="muted small no-margin" id="selectedIp">—</p>
</div>
<div class="actions no-margin-top">
<button type="button" class="button button-primary button-small" id="connectBtn">Connect</button>
<button type="button" class="button button-danger button-small" id="disconnectBtn">Disconnect</button>
</div>
</div>
<div id="commandAlert" class="alert" hidden></div>
<div class="remote-section">
<p class="section-title">Navigation</p>
<div class="remote-grid" aria-label="Directional controls">
<span></span>
<button type="button" class="button remote-btn" data-key="KEYCODE_DPAD_UP" aria-label="Up">▲</button>
<span></span>
<button type="button" class="button remote-btn" data-key="KEYCODE_DPAD_LEFT" aria-label="Left">◀</button>
<button type="button" class="button remote-btn button-primary" data-key="KEYCODE_DPAD_CENTER" aria-label="OK">OK</button>
<button type="button" class="button remote-btn" data-key="KEYCODE_DPAD_RIGHT" aria-label="Right">▶</button>
<span></span>
<button type="button" class="button remote-btn" data-key="KEYCODE_DPAD_DOWN" aria-label="Down">▼</button>
<span></span>
</div>
</div>
<div class="remote-section">
<p class="section-title">Quick Actions</p>
<div class="actions no-margin-top wrap-actions">
<button type="button" class="button button-small" data-key="KEYCODE_HOME">Home</button>
<button type="button" class="button button-small" data-key="KEYCODE_BACK">Back</button>
<button type="button" class="button button-small" data-key="KEYCODE_MENU">Menu</button>
<button type="button" class="button button-small" data-key="KEYCODE_APP_SWITCH">Apps</button>
<button type="button" class="button button-small" data-key="KEYCODE_SETTINGS">Settings</button>
<button type="button" class="button button-small" data-key="KEYCODE_INFO">Info</button>
</div>
</div>
<div class="remote-section">
<p class="section-title">Playback &amp; Volume</p>
<div class="actions no-margin-top wrap-actions">
<button type="button" class="button button-small" data-key="KEYCODE_MEDIA_PREVIOUS">Prev</button>
<button type="button" class="button button-small" data-key="KEYCODE_MEDIA_PLAY_PAUSE">Play/Pause</button>
<button type="button" class="button button-small" data-key="KEYCODE_MEDIA_NEXT">Next</button>
<button type="button" class="button button-small" data-key="KEYCODE_VOLUME_DOWN">Vol -</button>
<button type="button" class="button button-small" data-key="KEYCODE_MUTE">Mute</button>
<button type="button" class="button button-small" data-key="KEYCODE_VOLUME_UP">Vol +</button>
</div>
</div>
<div class="remote-section">
<p class="section-title">Send Text</p>
<form id="textForm" class="input-group" autocomplete="off">
<label class="sr-only" for="textInput">Text to send</label>
<input id="textInput" type="text" maxlength="200" placeholder="Type text to send to device…" inputmode="text">
<button type="submit" class="button button-primary">Send</button>
</form>
<p class="hint">Uses <code>adb shell input text</code>. Basic ASCII characters work best.</p>
</div>
<details class="command-log-details">
<summary>Command log</summary>
<pre id="commandLog" class="command-log" aria-live="polite">No commands sent yet.</pre>
</details>
</div>
</section>
</div>
</div>
<script src="assets/app.js" defer></script>
</body>
</html>

267
lib/adb.php Normal file
View file

@ -0,0 +1,267 @@
<?php
declare(strict_types=1);
function adb_bin(): string
{
static $bin = null;
if ($bin !== null) {
return $bin;
}
$found = trim((string) shell_exec('command -v adb 2>/dev/null'));
$bin = $found !== '' ? $found : 'adb';
return $bin;
}
function adb_available(): bool
{
$bin = adb_bin();
$out = [];
$code = 1;
exec(escapeshellcmd($bin) . ' version 2>&1', $out, $code);
return $code === 0;
}
function is_allowed_ip(string $ip): bool
{
if (!preg_match('/^192\.168\.(1|2)\.([0-9]{1,3})$/', $ip, $m)) {
return false;
}
$octet = (int) $m[2];
return $octet >= 1 && $octet <= 254;
}
function normalize_ip(string $ip): ?string
{
$ip = trim($ip);
return is_allowed_ip($ip) ? $ip : null;
}
function adb_target(string $ip): string
{
return $ip . ':5555';
}
function run_cmd(string $cmd, int $timeout = 10): array
{
$descriptors = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$proc = proc_open($cmd, $descriptors, $pipes, null, null);
if (!is_resource($proc)) {
return ['ok' => false, 'code' => 1, 'stdout' => '', 'stderr' => 'Failed to start process', 'timed_out' => false];
}
fclose($pipes[0]);
stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false);
$stdout = '';
$stderr = '';
$start = microtime(true);
$timedOut = false;
while (true) {
$status = proc_get_status($proc);
$stdout .= stream_get_contents($pipes[1]);
$stderr .= stream_get_contents($pipes[2]);
if (!$status['running']) {
break;
}
if ((microtime(true) - $start) > $timeout) {
$timedOut = true;
proc_terminate($proc, 9);
break;
}
usleep(50000);
}
$stdout .= stream_get_contents($pipes[1]);
$stderr .= stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$code = proc_close($proc);
if ($timedOut) {
$code = 124;
}
return [
'ok' => $code === 0 && !$timedOut,
'code' => $code,
'stdout' => trim($stdout),
'stderr' => trim($stderr),
'timed_out' => $timedOut,
];
}
function adb_connect(string $ip): array
{
$target = adb_target($ip);
$cmd = escapeshellcmd(adb_bin()) . ' connect ' . escapeshellarg($target) . ' 2>&1';
$res = run_cmd($cmd, 12);
$out = trim($res['stdout'] . "\n" . $res['stderr']);
$ok = stripos($out, 'connected') !== false || stripos($out, 'already connected') !== false;
return ['ok' => $ok, 'output' => $out, 'target' => $target];
}
function adb_disconnect(string $ip): array
{
$target = adb_target($ip);
$cmd = escapeshellcmd(adb_bin()) . ' disconnect ' . escapeshellarg($target) . ' 2>&1';
$res = run_cmd($cmd, 8);
$out = trim($res['stdout'] . "\n" . $res['stderr']);
return ['ok' => $res['code'] === 0, 'output' => $out, 'target' => $target];
}
function adb_devices(): array
{
$cmd = escapeshellcmd(adb_bin()) . ' devices -l 2>&1';
$res = run_cmd($cmd, 8);
$devices = [];
$lines = preg_split('/\r?\n/', $res['stdout']);
foreach ($lines as $line) {
$line = trim((string) $line);
if ($line === '' || str_starts_with($line, 'List of devices') || str_starts_with($line, '*')) {
continue;
}
if (preg_match('/^(\S+)\s+(device|offline|unauthorized|connecting)\b(.*)$/', $line, $m)) {
$serial = $m[1];
$state = $m[2];
$meta = trim($m[3]);
$ip = null;
if (preg_match('/^(\d+\.\d+\.\d+\.\d+):\d+$/', $serial, $im)) {
$candidate = $im[1];
if (is_allowed_ip($candidate)) {
$ip = $candidate;
}
}
$devices[] = [
'serial' => $serial,
'state' => $state,
'meta' => $meta,
'ip' => $ip,
];
}
}
return $devices;
}
function adb_shell(string $ip, string $shellCmd, int $timeout = 10): array
{
$target = adb_target($ip);
$cmd = escapeshellcmd(adb_bin()) . ' -s ' . escapeshellarg($target) . ' shell ' . $shellCmd . ' 2>&1';
return run_cmd($cmd, $timeout);
}
function adb_get_name(string $ip): ?string
{
$props = [
'ro.product.model',
'ro.product.name',
'ro.product.device',
];
foreach ($props as $prop) {
$res = adb_shell($ip, escapeshellarg('getprop') . ' ' . escapeshellarg($prop), 8);
$val = trim($res['stdout']);
if ($res['code'] === 0 && $val !== '' && strtolower($val) !== 'unknown') {
return $val;
}
}
return null;
}
function adb_send_key(string $ip, string $keycode): array
{
if (!preg_match('/^KEYCODE_[A-Z0-9_]+$/', $keycode)) {
return ['ok' => false, 'output' => 'Invalid keycode'];
}
$res = adb_shell($ip, 'input keyevent ' . escapeshellarg($keycode), 8);
$out = trim($res['stdout'] . "\n" . $res['stderr']);
return ['ok' => $res['ok'], 'output' => $out];
}
function adb_send_text(string $ip, string $text): array
{
$text = str_replace(["\r", "\n"], ' ', $text);
$text = trim($text);
if ($text === '') {
return ['ok' => false, 'output' => 'Text is empty'];
}
$len = function_exists('mb_strlen') ? mb_strlen($text) : strlen($text);
if ($len > 200) {
return ['ok' => false, 'output' => 'Text too long (max 200 chars)'];
}
// adb input text uses %s for spaces and requires escaping certain chars.
$encoded = '';
$chars = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);
foreach ($chars as $ch) {
if ($ch === ' ') {
$encoded .= '%s';
} elseif (preg_match('/[A-Za-z0-9._@,:\/-]/', $ch)) {
$encoded .= $ch;
} else {
// Fallback: skip unsupported chars to avoid shell injection/adb quirks.
$encoded .= '';
}
}
if ($encoded === '') {
return ['ok' => false, 'output' => 'Text contains no supported characters for adb input text'];
}
$res = adb_shell($ip, 'input text ' . escapeshellarg($encoded), 10);
$out = trim($res['stdout'] . "\n" . $res['stderr']);
return ['ok' => $res['ok'], 'output' => $out];
}
function devices_path(): string
{
return __DIR__ . '/../data/devices.json';
}
function load_devices(): array
{
$path = devices_path();
if (!is_file($path)) {
return [];
}
$raw = file_get_contents($path);
if ($raw === false || trim($raw) === '') {
return [];
}
$data = json_decode($raw, true);
return is_array($data) ? $data : [];
}
function save_devices(array $devices): bool
{
$path = devices_path();
$dir = dirname($path);
if (!is_dir($dir)) {
mkdir($dir, 0775, true);
}
$tmp = $path . '.tmp';
$json = json_encode(array_values($devices), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
if ($json === false) {
return false;
}
$ok = file_put_contents($tmp, $json . "\n", LOCK_EX) !== false;
if (!$ok) {
return false;
}
return rename($tmp, $path);
}
function upsert_device(string $ip, array $fields): array
{
$devices = load_devices();
$found = false;
foreach ($devices as &$d) {
if (($d['ip'] ?? '') === $ip) {
$d = array_merge($d, $fields);
$d['ip'] = $ip;
$found = true;
break;
}
}
unset($d);
if (!$found) {
$devices[] = array_merge(['ip' => $ip, 'name' => '', 'last_seen' => null, 'last_connected' => null], $fields);
}
save_devices($devices);
return $devices;
}