Settings gets a Driver tab (/settings/editor). It sends a driver its settings through PUT /devices/<id>, which now forwards name too, and runs the tools/driver_ota.py session from the browser. The firmware embeds the led-driver files and a manifest of their hashes, because crypto.subtle is unavailable over plain HTTP. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
192 lines
6.8 KiB
JavaScript
192 lines
6.8 KiB
JavaScript
(function () {
|
|
const messageEl = document.getElementById('flash');
|
|
|
|
function flash(text, isError) {
|
|
if (!messageEl) return;
|
|
messageEl.textContent = text;
|
|
messageEl.className = isError ? 'flash error show' : 'flash show';
|
|
setTimeout(() => messageEl.classList.remove('show'), 5000);
|
|
}
|
|
|
|
function errorMessage(e) {
|
|
if (!e) return 'Unknown error';
|
|
if (typeof e === 'string') return e;
|
|
return e.message || String(e);
|
|
}
|
|
|
|
// ESP-NOW: PUT /devices/<id> stores the fields and sends them to the driver in one message
|
|
const espnowDevice = document.getElementById('espnow-device');
|
|
const espnowSend = document.getElementById('espnow-send');
|
|
const espnowFields = document.querySelectorAll('[data-espnow]');
|
|
let espnowDevices = {};
|
|
|
|
function showEspnowDevice() {
|
|
const dev = espnowDevices[espnowDevice.value] || {};
|
|
espnowFields.forEach((el) => {
|
|
const v = dev[el.getAttribute('data-espnow')];
|
|
el.value = v === undefined || v === null ? '' : String(v);
|
|
});
|
|
}
|
|
|
|
async function loadEspnowDevices() {
|
|
const res = await fetch('/devices');
|
|
if (!res.ok) throw new Error(`Could not list drivers (${res.status})`);
|
|
const all = await res.json();
|
|
espnowDevices = {};
|
|
espnowDevice.innerHTML = '';
|
|
for (const [id, dev] of Object.entries(all)) {
|
|
if (dev.transport !== 'espnow') continue;
|
|
espnowDevices[id] = dev;
|
|
const opt = document.createElement('option');
|
|
opt.value = id;
|
|
opt.textContent = `${dev.name || id} (${id})`;
|
|
espnowDevice.appendChild(opt);
|
|
}
|
|
espnowSend.disabled = !espnowDevice.options.length;
|
|
showEspnowDevice();
|
|
showOtaTargets();
|
|
}
|
|
|
|
function espnowChanges() {
|
|
const dev = espnowDevices[espnowDevice.value] || {};
|
|
const out = {};
|
|
espnowFields.forEach((el) => {
|
|
const key = el.getAttribute('data-espnow');
|
|
const raw = el.value.trim();
|
|
if (raw === '' || raw === String(dev[key] ?? '')) return;
|
|
if (el.type === 'number') out[key] = parseInt(raw, 10);
|
|
else if (key === 'reversed') out[key] = raw === 'true';
|
|
else out[key] = raw;
|
|
});
|
|
return out;
|
|
}
|
|
|
|
espnowDevice.addEventListener('change', showEspnowDevice);
|
|
|
|
espnowSend.addEventListener('click', async () => {
|
|
const id = espnowDevice.value;
|
|
const body = espnowChanges();
|
|
if (!Object.keys(body).length) {
|
|
flash('Nothing has changed.', true);
|
|
return;
|
|
}
|
|
espnowSend.disabled = true;
|
|
try {
|
|
const res = await fetch(`/devices/${encodeURIComponent(id)}`, {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(body),
|
|
});
|
|
const data = await res.json();
|
|
if (!res.ok) throw new Error(data.error || `Send failed (${res.status})`);
|
|
espnowDevices[id] = data;
|
|
espnowDevice.selectedOptions[0].textContent = `${data.name || id} (${id})`;
|
|
flash(`Sent to ${data.name || id}.`, false);
|
|
} catch (e) {
|
|
flash(errorMessage(e), true);
|
|
} finally {
|
|
espnowSend.disabled = false;
|
|
}
|
|
});
|
|
|
|
// Driver code: the session tools/driver_ota.py runs, one driver at a time
|
|
const otaTarget = document.getElementById('ota-target');
|
|
const otaStart = document.getElementById('ota-start');
|
|
const otaStatus = document.getElementById('ota-status');
|
|
|
|
function showOtaTargets() {
|
|
otaTarget.innerHTML = '<option value="all">All drivers</option>';
|
|
for (const [id, dev] of Object.entries(espnowDevices)) {
|
|
const opt = document.createElement('option');
|
|
opt.value = id;
|
|
opt.textContent = `${dev.name || id} (${id})`;
|
|
otaTarget.appendChild(opt);
|
|
}
|
|
otaStart.disabled = !Object.keys(espnowDevices).length;
|
|
}
|
|
|
|
async function otaRequest(action, mac, sess, params = '', body) {
|
|
// The controller does not URL-decode, so the query goes as it is
|
|
const res = await fetch(`/drivers/ota/${action}?mac=${mac}&sess=${sess}${params}`, {
|
|
method: 'POST',
|
|
headers: body ? { 'Content-Type': 'application/octet-stream' } : {},
|
|
body,
|
|
});
|
|
const data = await res.json();
|
|
if (!res.ok) throw new Error(data.error || `${action} failed (${res.status})`);
|
|
return data[mac] || { result: 'error', code: 'missing from reply' };
|
|
}
|
|
|
|
async function otaFile(path) {
|
|
const res = await fetch(`/static/driver/${path}`);
|
|
if (!res.ok) throw new Error(`${path}: ${res.status}`);
|
|
return res.arrayBuffer();
|
|
}
|
|
|
|
// Resolves once the driver acks the link again after its reset
|
|
async function otaWaitBack(id) {
|
|
const t0 = Date.now();
|
|
await new Promise((r) => setTimeout(r, 2000));
|
|
while (Date.now() - t0 < 30000) {
|
|
const st = await fetch('/devices/status').then((r) => r.json()).catch(() => ({}));
|
|
const age = st[id] ? st[id].last_ack_ms_ago : -1;
|
|
if (age >= 0 && age < Date.now() - t0) return true;
|
|
await new Promise((r) => setTimeout(r, 1000));
|
|
}
|
|
return false;
|
|
}
|
|
|
|
async function otaDriver(id, files, label) {
|
|
const mac = espnowDevices[id].address;
|
|
const sess = 1 + Math.floor(Math.random() * 0xffff);
|
|
let written = 0;
|
|
try {
|
|
for (let i = 0; i < files.length; i++) {
|
|
const f = files[i];
|
|
otaStatus.textContent = `${label}: ${i + 1}/${files.length} ${f.path}`;
|
|
const r = await otaRequest('file', mac, sess, `&path=${f.path}&sha=${f.sha}`, await otaFile(f.path));
|
|
if (r.result === 'error') throw new Error(`${f.path}: ${r.code}`);
|
|
if (r.result === 'written') written++;
|
|
}
|
|
} catch (e) {
|
|
await otaRequest('abort', mac, sess).catch(() => {});
|
|
throw e;
|
|
}
|
|
const r = await otaRequest('commit', mac, sess);
|
|
if (r.result !== 'ok') throw new Error(`commit: ${r.code || r.result}`);
|
|
if (!written) return `${label}: already up to date`;
|
|
otaStatus.textContent = `${label}: ${written} files written, waiting for the reset`;
|
|
const back = await otaWaitBack(id);
|
|
return `${label}: ${written} files written, ${back ? 'back online' : 'not back within 30 s'}`;
|
|
}
|
|
|
|
otaStart.addEventListener('click', async () => {
|
|
const ids = otaTarget.value === 'all' ? Object.keys(espnowDevices) : [otaTarget.value];
|
|
otaStart.disabled = true;
|
|
const done = [];
|
|
let failed = false;
|
|
try {
|
|
const res = await fetch('/static/driver/manifest.json');
|
|
if (!res.ok) throw new Error(`manifest: ${res.status}`);
|
|
const { files } = await res.json();
|
|
for (const id of ids) {
|
|
const label = espnowDevices[id].name || id;
|
|
try {
|
|
done.push(await otaDriver(id, files, label));
|
|
} catch (e) {
|
|
failed = true;
|
|
done.push(`${label}: ${errorMessage(e)}`);
|
|
}
|
|
}
|
|
} catch (e) {
|
|
failed = true;
|
|
done.push(errorMessage(e));
|
|
}
|
|
otaStatus.textContent = done.join('; ');
|
|
flash(failed ? 'Driver update failed.' : 'Driver update finished.', failed);
|
|
otaStart.disabled = false;
|
|
});
|
|
|
|
loadEspnowDevices().catch((e) => flash(e.message, true));
|
|
})();
|