240 lines
17 KiB
C++
240 lines
17 KiB
C++
#include "boomcast_web.h"
|
|
#include "boomcast_audio.h"
|
|
#include "boomcast_config.h"
|
|
#include "boomcast_network.h"
|
|
#include "boomcast_queue.h"
|
|
#include "boomcast_state.h"
|
|
|
|
BoomWeb boomWeb;
|
|
|
|
static String webJsonEscape(String value) {
|
|
value.replace("\\", "\\\\");
|
|
value.replace("\"", "\\\"");
|
|
value.replace("\r", "\\r");
|
|
value.replace("\n", "\\n");
|
|
return value;
|
|
}
|
|
|
|
static const char MANAGEMENT_HTML[] PROGMEM = R"BOOMHTML(
|
|
<!doctype html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>BoomCast</title>
|
|
<style>
|
|
:root{color-scheme:light;--ink:#18201e;--muted:#64706d;--line:#d9e1df;--paper:#f5f7f6;--card:#fff;--accent:#143f35;--soft:#e6efec;--warn:#fff5d8;--bad:#ffe7e3}*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:15px/1.45 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}.wrap{max-width:920px;margin:auto;padding:24px 16px 56px}header{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:20px}.brand{display:flex;align-items:center;gap:12px}.logo{width:44px;height:44px;border:2px solid var(--ink);border-radius:14px;display:grid;place-items:center;font-size:23px;background:white}.brand h1{font-size:22px;margin:0}.brand p{margin:1px 0 0;color:var(--muted);font-size:13px}.pill{border:1px solid var(--line);border-radius:999px;padding:7px 11px;background:white;font-size:12px}.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.metric,.card{background:var(--card);border:1px solid var(--line);border-radius:16px}.metric{padding:14px}.metric b{display:block;font-size:22px;margin-top:2px}.metric span{color:var(--muted);font-size:12px}.cards{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-top:14px}.card{padding:18px}.card.full{grid-column:1/-1}.card h2{font-size:16px;margin:0 0 4px}.sub{color:var(--muted);font-size:13px;margin:0 0 15px}.row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.statusdot{width:9px;height:9px;border-radius:50%;display:inline-block;background:#9aa4a1;margin-right:6px}.statusdot.ok{background:#18794e}.statusdot.warn{background:#c48400}.statusdot.bad{background:#c73a30}button,input,select{font:inherit}button{border:0;border-radius:10px;padding:10px 13px;background:var(--accent);color:white;font-weight:650;cursor:pointer}button.secondary{background:var(--soft);color:var(--ink)}button.danger{background:#8f2e28}button:disabled{opacity:.5;cursor:not-allowed}input[type=text],input[type=password],select{width:100%;border:1px solid var(--line);border-radius:10px;padding:10px;background:white;color:var(--ink)}label{font-size:12px;color:var(--muted);display:block;margin-bottom:6px}.field{margin-bottom:12px}.sliderline{display:grid;grid-template-columns:1fr auto;gap:14px;align-items:center}.sliderline input{width:100%}.sens{font-size:24px;font-weight:750;min-width:54px;text-align:right}canvas{width:100%;height:128px;border:1px solid var(--line);border-radius:12px;background:#fbfcfc;display:block}.queue{display:grid;gap:8px}.event{border:1px solid var(--line);border-radius:11px;padding:10px 11px;display:grid;grid-template-columns:1fr auto;gap:10px;align-items:center}.event strong{font-size:13px;word-break:break-all}.event small{display:block;color:var(--muted);margin-top:2px}.empty{color:var(--muted);padding:8px 0}.message{margin-top:10px;font-size:13px;color:var(--muted);min-height:20px}.privacy{padding:12px 14px;background:var(--soft);border-radius:12px;font-size:13px}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px}.switcher{display:flex;gap:8px;align-items:center}.wifi-form{display:grid;grid-template-columns:1fr 1fr;gap:10px}.wifi-form .wide{grid-column:1/-1}@media(max-width:700px){.grid{grid-template-columns:1fr 1fr}.cards{grid-template-columns:1fr}.card.full{grid-column:auto}.wifi-form{grid-template-columns:1fr}.wifi-form .wide{grid-column:auto}}@media(max-width:420px){.grid{grid-template-columns:1fr 1fr}header{align-items:flex-start;flex-direction:column}.event{grid-template-columns:1fr}.event button{width:100%}}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="wrap">
|
|
<header>
|
|
<div class="brand"><div class="logo">✦</div><div><h1>BoomCast</h1><p>Firework sensor · local management</p></div></div>
|
|
<div class="pill"><span id="netDot" class="statusdot"></span><span id="networkTop">Loading…</span></div>
|
|
</header>
|
|
|
|
<section class="grid">
|
|
<div class="metric"><span>Today</span><b id="today">—</b></div>
|
|
<div class="metric"><span>Queued</span><b id="queued">—</b></div>
|
|
<div class="metric"><span>Microphone</span><b id="mic">—</b></div>
|
|
<div class="metric"><span>Storage</span><b id="sd">—</b></div>
|
|
</section>
|
|
|
|
<div class="cards">
|
|
<section class="card full">
|
|
<h2>Live microphone shape</h2>
|
|
<p class="sub">A low-resolution level preview. This graph is generated locally from the current sample block; it is not an audio stream.</p>
|
|
<canvas id="wave" width="840" height="128" aria-label="Live microphone waveform"></canvas>
|
|
</section>
|
|
|
|
<section class="card">
|
|
<h2>Detection sensitivity</h2>
|
|
<p class="sub">Higher means easier to trigger. This changes BoomCast's software thresholds, not microphone gain.</p>
|
|
<div class="sliderline"><input id="sensitivity" type="range" min="1" max="100" value="55"><div class="sens"><span id="sensValue">55</span>%</div></div>
|
|
<div class="message" id="sensMessage"></div>
|
|
</section>
|
|
|
|
<section class="card">
|
|
<h2>Device</h2>
|
|
<p class="sub">Open this page again from the address shown on the e-paper status screen.</p>
|
|
<div class="privacy"><b>Listening for bangs, not conversations.</b><br>BoomCast keeps a rolling RAM buffer and writes a short clip to SD only around a detected event.</div>
|
|
<p class="mono" id="deviceAddress">IP: —</p>
|
|
<p class="mono" id="ssidLine">Wi-Fi: —</p>
|
|
</section>
|
|
|
|
<section class="card full">
|
|
<div class="row" style="justify-content:space-between"><div><h2>Upload queue</h2><p class="sub">Files stay on the SD card until the server returns a successful response.</p></div><button id="sendAll">Send all</button></div>
|
|
<div class="queue" id="eventList"><div class="empty">Loading queue…</div></div>
|
|
<div class="message" id="syncMessage"></div>
|
|
</section>
|
|
|
|
<section class="card full">
|
|
<div class="row" style="justify-content:space-between"><div><h2>Wi-Fi setup</h2><p class="sub">Scan nearby networks, save credentials, and reboot into station mode.</p></div><button class="secondary" id="scanWifi">Scan</button></div>
|
|
<div class="wifi-form">
|
|
<div class="field wide"><label for="wifiSelect">Nearby networks</label><select id="wifiSelect"><option value="">Choose a network or type it below</option></select></div>
|
|
<div class="field"><label for="ssidInput">SSID</label><input id="ssidInput" type="text" autocomplete="off"></div>
|
|
<div class="field"><label for="passwordInput">Password</label><input id="passwordInput" type="password" autocomplete="new-password"></div>
|
|
<div class="row wide"><button id="saveWifi">Save & reboot</button><button class="secondary" id="forgetWifi">Forget saved Wi-Fi</button><button class="secondary" id="reboot">Reboot</button></div>
|
|
</div>
|
|
<div class="message" id="wifiMessage"></div>
|
|
</section>
|
|
</div>
|
|
</div>
|
|
<script>
|
|
const $=id=>document.getElementById(id);let statusBusy=false,queueBusy=false;
|
|
function fmtBytes(n){if(n<1024)return n+' B';if(n<1048576)return (n/1024).toFixed(1)+' kB';return (n/1048576).toFixed(1)+' MB'}
|
|
function drawWave(points){const c=$('wave'),g=c.getContext('2d'),w=c.width,h=c.height;g.clearRect(0,0,w,h);g.strokeStyle='#d9e1df';g.lineWidth=1;g.beginPath();g.moveTo(0,h/2+.5);g.lineTo(w,h/2+.5);g.stroke();if(!points||!points.length)return;g.strokeStyle='#143f35';g.lineWidth=2;g.beginPath();points.forEach((p,i)=>{const x=i*(w/(points.length-1));const y=h/2-(p/100)*(h*.43);i?g.lineTo(x,y):g.moveTo(x,y)});g.stroke()}
|
|
async function api(path,opts={}){const r=await fetch(path,{cache:'no-store',...opts});let data={};try{data=await r.json()}catch(e){}if(!r.ok)throw new Error(data.error||('HTTP '+r.status));return data}
|
|
async function refreshStatus(){if(statusBusy)return;statusBusy=true;try{const s=await api('/api/status');$('today').textContent=s.today;$('queued').textContent=s.queue;$('mic').textContent=s.capturing?'Saving':'Listening';$('sd').textContent=s.sd?'Ready':'Missing';$('deviceAddress').textContent='IP: '+s.ip;$('ssidLine').textContent='Wi-Fi: '+(s.ssid||'—');$('networkTop').textContent=s.wifi?('Connected · '+s.ip):(s.ap?'Setup AP · '+s.ip:'Offline');$('netDot').className='statusdot '+(s.wifi?'ok':(s.ap?'warn':'bad'));if(document.activeElement!==$('sensitivity')){$('sensitivity').value=s.sensitivity;$('sensValue').textContent=s.sensitivity}$('syncMessage').textContent=s.syncMessage||'';drawWave(s.waveform)}catch(e){$('networkTop').textContent='Interface unavailable';$('netDot').className='statusdot bad'}finally{statusBusy=false}}
|
|
async function refreshQueue(){if(queueBusy)return;queueBusy=true;try{const items=await api('/api/events'),box=$('eventList');box.textContent='';if(!items.length){const e=document.createElement('div');e.className='empty';e.textContent='Queue is empty. Nice.';box.appendChild(e)}else items.forEach(item=>{const row=document.createElement('div');row.className='event';const info=document.createElement('div');const name=document.createElement('strong');name.textContent=item.name;const size=document.createElement('small');size.textContent=fmtBytes(item.bytes);info.append(name,size);const b=document.createElement('button');b.className='secondary';b.textContent='Send';b.onclick=async()=>{b.disabled=true;try{await api('/api/sync',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({file:item.name})});$('syncMessage').textContent='Upload queued: '+item.name}catch(e){$('syncMessage').textContent=e.message}finally{setTimeout(refreshQueue,1200)}};row.append(info,b);box.appendChild(row)})}catch(e){$('eventList').textContent='Could not read queue: '+e.message}finally{queueBusy=false}}
|
|
$('sensitivity').addEventListener('input',e=>$('sensValue').textContent=e.target.value);$('sensitivity').addEventListener('change',async e=>{try{const d=await api('/api/sensitivity',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({value:e.target.value})});$('sensMessage').textContent='Saved at '+d.value+'%'}catch(err){$('sensMessage').textContent=err.message}});
|
|
$('sendAll').onclick=async()=>{try{await api('/api/sync',{method:'POST'});$('syncMessage').textContent='Upload of queued events requested.'}catch(e){$('syncMessage').textContent=e.message}};
|
|
$('scanWifi').onclick=async()=>{const b=$('scanWifi');b.disabled=true;$('wifiMessage').textContent='Scanning…';try{const nets=await api('/api/wifi/scan'),sel=$('wifiSelect');sel.textContent='';const empty=document.createElement('option');empty.value='';empty.textContent='Choose a network or type it below';sel.appendChild(empty);nets.forEach(n=>{const o=document.createElement('option');o.value=n.ssid;o.textContent=n.ssid+' · '+n.rssi+' dBm'+(n.secure?' · secured':'');sel.appendChild(o)});$('wifiMessage').textContent=nets.length+' network(s) found.'}catch(e){$('wifiMessage').textContent=e.message}finally{b.disabled=false}};
|
|
$('wifiSelect').onchange=e=>{if(e.target.value)$('ssidInput').value=e.target.value};
|
|
$('saveWifi').onclick=async()=>{const ssid=$('ssidInput').value.trim(),password=$('passwordInput').value;if(!ssid){$('wifiMessage').textContent='Enter an SSID first.';return}try{await api('/api/wifi',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({ssid,password})});$('wifiMessage').textContent='Saved. BoomCast is rebooting…'}catch(e){$('wifiMessage').textContent=e.message}};
|
|
$('forgetWifi').onclick=async()=>{if(!confirm('Forget the saved Wi-Fi credentials and return to setup AP mode?'))return;try{await api('/api/wifi/forget',{method:'POST'});$('wifiMessage').textContent='Credentials removed. Rebooting…'}catch(e){$('wifiMessage').textContent=e.message}};
|
|
$('reboot').onclick=async()=>{try{await api('/api/reboot',{method:'POST'});$('wifiMessage').textContent='Rebooting…'}catch(e){$('wifiMessage').textContent=e.message}};
|
|
refreshStatus();refreshQueue();setInterval(refreshStatus,1000);setInterval(refreshQueue,4000);
|
|
</script>
|
|
</body>
|
|
</html>
|
|
)BOOMHTML";
|
|
|
|
bool BoomWeb::authorise() {
|
|
String password = boomState.prefs().getString("mgmt_pass", "");
|
|
if (password.length() && server_.authenticate(MANAGEMENT_USER, password.c_str())) return true;
|
|
server_.requestAuthentication(BASIC_AUTH, "BoomCast");
|
|
return false;
|
|
}
|
|
|
|
void BoomWeb::addNoCache() {
|
|
server_.sendHeader("Cache-Control", "no-store, max-age=0");
|
|
server_.sendHeader("Pragma", "no-cache");
|
|
}
|
|
|
|
void BoomWeb::sendJson(int code, const String& json) {
|
|
addNoCache();
|
|
server_.send(code, "application/json; charset=utf-8", json);
|
|
}
|
|
|
|
void BoomWeb::begin() {
|
|
server_.on("/", HTTP_GET, [this]() { handleRoot(); });
|
|
server_.on("/api/status", HTTP_GET, [this]() { handleStatus(); });
|
|
server_.on("/api/events", HTTP_GET, [this]() { handleEvents(); });
|
|
server_.on("/api/wifi/scan", HTTP_GET, [this]() { handleWifiScan(); });
|
|
server_.on("/api/wifi", HTTP_POST, [this]() { handleWifiSave(); });
|
|
server_.on("/api/wifi/forget", HTTP_POST, [this]() { handleWifiForget(); });
|
|
server_.on("/api/sensitivity", HTTP_POST, [this]() { handleSensitivity(); });
|
|
server_.on("/api/sync", HTTP_POST, [this]() { handleSync(); });
|
|
server_.on("/api/reboot", HTTP_POST, [this]() { handleReboot(); });
|
|
server_.onNotFound([this]() {
|
|
if (!authorise()) return;
|
|
sendJson(404, "{\"error\":\"Not found\"}");
|
|
});
|
|
server_.begin();
|
|
Serial.println("[Web] management interface listening on port 80");
|
|
}
|
|
|
|
void BoomWeb::handle() {
|
|
server_.handleClient();
|
|
}
|
|
|
|
void BoomWeb::handleRoot() {
|
|
if (!authorise()) return;
|
|
addNoCache();
|
|
server_.send_P(200, "text/html; charset=utf-8", MANAGEMENT_HTML);
|
|
}
|
|
|
|
void BoomWeb::handleStatus() {
|
|
if (!authorise()) return;
|
|
BoomStateSnapshot s = boomState.snapshot();
|
|
String json;
|
|
json.reserve(900);
|
|
json += "{\"version\":\"" + String(BOOMCAST_FIRMWARE_VERSION) + "\"";
|
|
json += ",\"wifi\":" + String(s.wifiConnected ? "true" : "false");
|
|
json += ",\"ap\":" + String(s.apMode ? "true" : "false");
|
|
json += ",\"sd\":" + String(s.sdReady ? "true" : "false");
|
|
json += ",\"capturing\":" + String(s.capturing ? "true" : "false");
|
|
json += ",\"syncing\":" + String(s.syncing ? "true" : "false");
|
|
json += ",\"ip\":\"" + webJsonEscape(s.ip) + "\"";
|
|
json += ",\"ssid\":\"" + webJsonEscape(s.ssid) + "\"";
|
|
json += ",\"queue\":" + String(s.queueCount);
|
|
json += ",\"today\":" + String(s.todayEvents);
|
|
json += ",\"sensitivity\":" + String(s.sensitivity);
|
|
json += ",\"syncMessage\":\"" + webJsonEscape(s.lastSyncMessage) + "\"";
|
|
json += ",\"waveform\":[";
|
|
for (size_t i = 0; i < BOOMCAST_WAVEFORM_POINTS; ++i) {
|
|
if (i) json += ',';
|
|
json += String((int)s.waveform[i]);
|
|
}
|
|
json += "]}";
|
|
sendJson(200, json);
|
|
}
|
|
|
|
void BoomWeb::handleEvents() {
|
|
if (!authorise()) return;
|
|
sendJson(200, boomQueue.listJson(MAX_QUEUE_ITEMS_SHOWN));
|
|
}
|
|
|
|
void BoomWeb::handleWifiScan() {
|
|
if (!authorise()) return;
|
|
sendJson(200, boomNetwork.scanJson());
|
|
}
|
|
|
|
void BoomWeb::handleWifiSave() {
|
|
if (!authorise()) return;
|
|
String ssid = server_.arg("ssid");
|
|
String password = server_.arg("password");
|
|
ssid.trim();
|
|
if (!ssid.length()) {
|
|
sendJson(400, "{\"error\":\"SSID is required\"}");
|
|
return;
|
|
}
|
|
if (!boomNetwork.saveCredentials(ssid, password)) {
|
|
sendJson(500, "{\"error\":\"Could not save Wi-Fi credentials\"}");
|
|
return;
|
|
}
|
|
sendJson(200, "{\"ok\":true,\"rebooting\":true}");
|
|
boomState.requestReboot(1200);
|
|
}
|
|
|
|
void BoomWeb::handleWifiForget() {
|
|
if (!authorise()) return;
|
|
boomNetwork.clearCredentials();
|
|
sendJson(200, "{\"ok\":true,\"rebooting\":true}");
|
|
boomState.requestReboot(1200);
|
|
}
|
|
|
|
void BoomWeb::handleSensitivity() {
|
|
if (!authorise()) return;
|
|
if (!server_.hasArg("value")) {
|
|
sendJson(400, "{\"error\":\"value is required\"}");
|
|
return;
|
|
}
|
|
int value = constrain(server_.arg("value").toInt(), 1, 100);
|
|
boomState.setSensitivity((uint8_t)value, true);
|
|
boomAudio.setSensitivity((uint8_t)value);
|
|
sendJson(200, "{\"ok\":true,\"value\":" + String(value) + "}");
|
|
}
|
|
|
|
void BoomWeb::handleSync() {
|
|
if (!authorise()) return;
|
|
if (!boomNetwork.connected()) {
|
|
sendJson(409, "{\"error\":\"No station Wi-Fi connection; upload unavailable in setup-AP-only mode\"}");
|
|
return;
|
|
}
|
|
String file = server_.arg("file");
|
|
if (file.length() && !boomQueue.exists(file)) {
|
|
sendJson(404, "{\"error\":\"Queued file not found\"}");
|
|
return;
|
|
}
|
|
boomState.requestSync(file);
|
|
sendJson(202, "{\"ok\":true,\"queued\":true}");
|
|
}
|
|
|
|
void BoomWeb::handleReboot() {
|
|
if (!authorise()) return;
|
|
sendJson(200, "{\"ok\":true,\"rebooting\":true}");
|
|
boomState.requestReboot(900);
|
|
}
|