Add network name lookup, command picker, and batch command runner

This commit is contained in:
Clarth 2026-12-03 20:12:30 -05:00
parent 9e016b251f
commit 2414409d49
4 changed files with 223 additions and 3 deletions

13
api.php
View file

@ -160,15 +160,24 @@ try {
foreach ($foundIps as $ip) { foreach ($foundIps as $ip) {
$k = $knownByIp[$ip] ?? null; $k = $knownByIp[$ip] ?? null;
$a = $adbByIp[$ip] ?? null; $a = $adbByIp[$ip] ?? null;
$name = trim((string) ($k['name'] ?? ''));
$lookup = lookup_device_name($ip);
if ($lookup !== null && $lookup !== '') {
$name = $lookup;
}
$results[] = [ $results[] = [
'ip' => $ip, 'ip' => $ip,
'port_open' => true, 'port_open' => true,
'name' => $k['name'] ?? '', 'name' => $name,
'last_seen' => gmdate('c'), 'last_seen' => gmdate('c'),
'last_connected' => $k['last_connected'] ?? null, 'last_connected' => $k['last_connected'] ?? null,
'adb_state' => $a['state'] ?? null, 'adb_state' => $a['state'] ?? null,
]; ];
upsert_device($ip, ['last_seen' => gmdate('c')]); $save = ['last_seen' => gmdate('c')];
if ($name !== '') {
$save['name'] = $name;
}
upsert_device($ip, $save);
} }
// Also include known devices that were not found in this scan // Also include known devices that were not found in this scan

View file

@ -19,6 +19,12 @@
commandAlert: document.getElementById('commandAlert'), commandAlert: document.getElementById('commandAlert'),
textForm: document.getElementById('textForm'), textForm: document.getElementById('textForm'),
textInput: document.getElementById('textInput'), textInput: document.getElementById('textInput'),
commandSelect: document.getElementById('commandSelect'),
commandDesc: document.getElementById('commandDesc'),
sendCommandBtn: document.getElementById('sendCommandBtn'),
batchInput: document.getElementById('batchInput'),
runBatchBtn: document.getElementById('runBatchBtn'),
clearBatchBtn: document.getElementById('clearBatchBtn'),
commandLog: document.getElementById('commandLog'), commandLog: document.getElementById('commandLog'),
}; };
@ -46,6 +52,60 @@
return d.toLocaleString(); return d.toLocaleString();
} }
const COMMANDS = [
{ key: 'KEYCODE_HOME', label: 'Home', desc: 'Go to the Android TV home screen.' },
{ key: 'KEYCODE_BACK', label: 'Back', desc: 'Go back / close current dialog or screen.' },
{ key: 'KEYCODE_DPAD_UP', label: 'D-Pad Up', desc: 'Move selection up.' },
{ key: 'KEYCODE_DPAD_DOWN', label: 'D-Pad Down', desc: 'Move selection down.' },
{ key: 'KEYCODE_DPAD_LEFT', label: 'D-Pad Left', desc: 'Move selection left.' },
{ key: 'KEYCODE_DPAD_RIGHT', label: 'D-Pad Right', desc: 'Move selection right.' },
{ key: 'KEYCODE_DPAD_CENTER', label: 'D-Pad Center / OK', desc: 'Select the focused item.' },
{ key: 'KEYCODE_ENTER', label: 'Enter', desc: 'Confirm/enter (similar to OK on some devices).' },
{ key: 'KEYCODE_MENU', label: 'Menu', desc: 'Open context menu where supported.' },
{ key: 'KEYCODE_APP_SWITCH', label: 'App Switch', desc: 'Show recent apps / app switcher.' },
{ key: 'KEYCODE_SETTINGS', label: 'Settings', desc: 'Open system settings.' },
{ key: 'KEYCODE_INFO', label: 'Info', desc: 'Show info/details for current content where supported.' },
{ key: 'KEYCODE_GUIDE', label: 'Guide', desc: 'Open program guide where supported.' },
{ key: 'KEYCODE_VOLUME_UP', label: 'Volume Up', desc: 'Increase volume.' },
{ key: 'KEYCODE_VOLUME_DOWN', label: 'Volume Down', desc: 'Decrease volume.' },
{ key: 'KEYCODE_MUTE', label: 'Mute', desc: 'Mute/unmute audio.' },
{ key: 'KEYCODE_MEDIA_PLAY_PAUSE', label: 'Play/Pause', desc: 'Toggle media playback.' },
{ key: 'KEYCODE_MEDIA_PLAY', label: 'Play', desc: 'Start media playback.' },
{ key: 'KEYCODE_MEDIA_PAUSE', label: 'Pause', desc: 'Pause media playback.' },
{ key: 'KEYCODE_MEDIA_NEXT', label: 'Next', desc: 'Skip to next track/chapter.' },
{ key: 'KEYCODE_MEDIA_PREVIOUS', label: 'Previous', desc: 'Go to previous track/chapter.' },
{ key: 'KEYCODE_MEDIA_STOP', label: 'Stop', desc: 'Stop media playback.' },
{ key: 'KEYCODE_MEDIA_REWIND', label: 'Rewind', desc: 'Rewind media.' },
{ key: 'KEYCODE_MEDIA_FAST_FORWARD', label: 'Fast Forward', desc: 'Fast-forward media.' },
{ key: 'KEYCODE_CHANNEL_UP', label: 'Channel Up', desc: 'Next channel (where supported).' },
{ key: 'KEYCODE_CHANNEL_DOWN', label: 'Channel Down', desc: 'Previous channel (where supported).' },
{ key: 'KEYCODE_POWER', label: 'Power', desc: 'Toggle power/sleep (device behavior varies).' },
{ key: 'KEYCODE_SLEEP', label: 'Sleep', desc: 'Put device to sleep.' },
{ key: 'KEYCODE_WAKEUP', label: 'Wake Up', desc: 'Wake device.' },
{ key: 'KEYCODE_SEARCH', label: 'Search', desc: 'Open search where supported.' },
{ key: 'KEYCODE_DEL', label: 'Delete', desc: 'Backspace/delete character.' },
{ key: 'KEYCODE_SPACE', label: 'Space', desc: 'Insert a space.' },
];
function normalizeKeycode(raw) {
let k = String(raw || '').trim().toUpperCase();
if (!k) return '';
if (!k.startsWith('KEYCODE_')) k = 'KEYCODE_' + k;
return k;
}
function initCommandPicker() {
if (!els.commandSelect) return;
els.commandSelect.innerHTML = '<option value="">Select a command…</option>' +
COMMANDS.map(c => `<option value="${escapeHtml(c.key)}">${escapeHtml(c.label)} — ${escapeHtml(c.key)}</option>`).join('');
const updateDesc = () => {
const cmd = COMMANDS.find(c => c.key === els.commandSelect.value);
els.commandDesc.textContent = cmd ? cmd.desc : 'Select a command to see what it does.';
};
els.commandSelect.addEventListener('change', updateDesc);
updateDesc();
}
function setAlert(el, msg, type = '') { function setAlert(el, msg, type = '') {
if (!msg) { if (!msg) {
el.hidden = true; el.hidden = true;
@ -379,6 +439,86 @@
} }
} }
async function sendSelectedCommand() {
const device = getSelectedDevice();
if (!device) {
setAlert(els.commandAlert, 'Select a device first.', 'warning');
return;
}
const key = els.commandSelect.value;
if (!key) {
setAlert(els.commandAlert, 'Pick a command from the dropdown first.', 'warning');
return;
}
setLoading(els.sendCommandBtn, true, 'Sending…');
setAlert(els.commandAlert, '');
try {
const data = await api('command', { ip: device.ip, command: 'key', keycode: key }, 'POST');
log(`KEY ${key} -> ${device.ip}: ${data.ok ? 'ok' : (data.error || data.output || 'failed')}`);
if (data.ok) {
setAlert(els.commandAlert, `Sent ${key}.`, 'success');
} else {
setAlert(els.commandAlert, data.error || data.output || 'Command failed.', 'urgent');
}
} catch (e) {
setAlert(els.commandAlert, 'Command error: ' + e.message, 'urgent');
} finally {
setLoading(els.sendCommandBtn, false);
}
}
async function runBatch() {
const device = getSelectedDevice();
if (!device) {
setAlert(els.commandAlert, 'Select a device first.', 'warning');
return;
}
const lines = String(els.batchInput.value || '').split(/\r?\n/);
const commands = lines
.map(l => l.trim())
.filter(l => l && !l.startsWith('#'))
.map(normalizeKeycode);
if (!commands.length) {
setAlert(els.commandAlert, 'Enter at least one command (one per line).', 'warning');
return;
}
setLoading(els.runBatchBtn, true, 'Running…');
setAlert(els.commandAlert, '');
let okCount = 0;
let failCount = 0;
for (let i = 0; i < commands.length; i++) {
const key = commands[i];
els.scanMeta.textContent = `Batch: ${i + 1}/${commands.length} ${key}`;
try {
const data = await api('command', { ip: device.ip, command: 'key', keycode: key }, 'POST');
if (data.ok) {
okCount++;
log(`BATCH ${i + 1}/${commands.length} ${key} -> ${device.ip}: ok`);
} else {
failCount++;
log(`BATCH ${i + 1}/${commands.length} ${key} -> ${device.ip}: ${data.error || data.output || 'failed'}`);
}
} catch (e) {
failCount++;
log(`BATCH ${i + 1}/${commands.length} ${key} -> ${device.ip}: ${e.message}`);
}
if (i < commands.length - 1) {
await new Promise(r => setTimeout(r, 250));
}
}
setLoading(els.runBatchBtn, false);
els.scanMeta.textContent = `Batch finished: ${okCount} ok, ${failCount} failed.`;
if (failCount) {
setAlert(els.commandAlert, `Batch finished: ${okCount} succeeded, ${failCount} failed. See command log.`, 'warning');
} else {
setAlert(els.commandAlert, `Batch finished: ${okCount} command(s) sent successfully.`, 'success');
}
}
function bindEvents() { function bindEvents() {
els.scanBtn.addEventListener('click', scan); els.scanBtn.addEventListener('click', scan);
els.refreshBtn.addEventListener('click', async () => { els.refreshBtn.addEventListener('click', async () => {
@ -394,6 +534,19 @@
btn.addEventListener('click', () => sendKey(btn.dataset.key, btn)); btn.addEventListener('click', () => sendKey(btn.dataset.key, btn));
}); });
if (els.sendCommandBtn) {
els.sendCommandBtn.addEventListener('click', sendSelectedCommand);
}
if (els.runBatchBtn) {
els.runBatchBtn.addEventListener('click', runBatch);
}
if (els.clearBatchBtn) {
els.clearBatchBtn.addEventListener('click', () => {
els.batchInput.value = '';
setAlert(els.commandAlert, '');
});
}
els.textForm.addEventListener('submit', (e) => { els.textForm.addEventListener('submit', (e) => {
e.preventDefault(); e.preventDefault();
const text = els.textInput.value.trim(); const text = els.textInput.value.trim();
@ -402,6 +555,7 @@
}); });
} }
initCommandPicker();
bindEvents(); bindEvents();
loadStatus(); loadStatus();
})(); })();

View file

@ -47,7 +47,7 @@ declare(strict_types=1);
<div id="devicesList" class="device-grid" aria-live="polite"> <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> <p class="empty">No scan yet. Click <strong>Scan Network</strong> to look for devices with port 5555 open.</p>
</div> </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> <p class="muted small hint-foot">Discovery probes TCP port 5555 and reads device name via local network lookup (no <code>adb connect</code> until you press Connect).</p>
</section> </section>
<section class="card" aria-labelledby="control-title"> <section class="card" aria-labelledby="control-title">
@ -113,6 +113,31 @@ declare(strict_types=1);
</div> </div>
</div> </div>
<div class="remote-section">
<p class="section-title">Command Picker</p>
<div class="field">
<label for="commandSelect">Choose a command</label>
<select id="commandSelect"></select>
<p class="hint" id="commandDesc">Select a command to see what it does.</p>
</div>
<div class="actions no-margin-top">
<button type="button" class="button button-primary button-small" id="sendCommandBtn">Send Command</button>
</div>
</div>
<div class="remote-section">
<p class="section-title">Batch Commands</p>
<div class="field">
<label for="batchInput">Paste commands (one per line)</label>
<textarea id="batchInput" rows="5" placeholder="KEYCODE_HOME&#10;KEYCODE_DPAD_DOWN&#10;KEYCODE_DPAD_CENTER"></textarea>
<p class="hint">Runs keycodes in order, one per line. Lines starting with <code>#</code> and empty lines are ignored. Only whitelisted keycodes are accepted.</p>
</div>
<div class="actions no-margin-top">
<button type="button" class="button button-primary button-small" id="runBatchBtn">Run Batch</button>
<button type="button" class="button button-small" id="clearBatchBtn">Clear</button>
</div>
</div>
<div class="remote-section"> <div class="remote-section">
<p class="section-title">Send Text</p> <p class="section-title">Send Text</p>
<form id="textForm" class="input-group" autocomplete="off"> <form id="textForm" class="input-group" autocomplete="off">

View file

@ -166,6 +166,38 @@ function adb_get_name(string $ip): ?string
return null; return null;
} }
function lookup_device_name(string $ip): ?string
{
// Try Google Cast / Android TV eureka_info (no ADB, no auth)
$url = 'http://' . $ip . ':8008/setup/eureka_info';
$ctx = stream_context_create([
'http' => [
'method' => 'GET',
'timeout' => 1.5,
'ignore_errors' => true,
'header' => "Accept: application/json\r\n",
],
]);
$raw = @file_get_contents($url, false, $ctx);
if (is_string($raw) && $raw !== '') {
$data = json_decode($raw, true);
if (is_array($data)) {
$name = trim((string) ($data['name'] ?? ''));
if ($name !== '') {
return $name;
}
}
}
// Fallback: reverse DNS
$host = @gethostbyaddr($ip);
if (is_string($host) && $host !== '' && $host !== $ip) {
return $host;
}
return null;
}
function adb_send_key(string $ip, string $keycode): array function adb_send_key(string $ip, string $keycode): array
{ {
if (!preg_match('/^KEYCODE_[A-Z0-9_]+$/', $keycode)) { if (!preg_match('/^KEYCODE_[A-Z0-9_]+$/', $keycode)) {