Files
WaveShare_ESP32_BoomCast_FW/BoomCast_Waveshare_Arduino/boomcast_web.cpp
T
2026-10-10 16:03:44 +02:00

410 lines
30 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "boomcast_web.h"
#include "boomcast_audio.h"
#include "boomcast_monitor.h"
#include "boomcast_config.h"
#include "boomcast_network.h"
#include "boomcast_queue.h"
#include "boomcast_state.h"
#include <stdio.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],input[type=time],input[type=number],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>
<p class="mono" id="firmwareVersion">Firmware: —</p>
</section>
<section class="card full" aria-labelledby="scheduleHeading">
<h2 id="scheduleHeading">Scheduled monitoring</h2>
<p class="sub">Europe/Amsterdam · adjusts for daylight saving. Overnight hours belong to the day they start. Equal start and end means 24 hours.</p>
<p id="monitorState" role="status">Loading monitoring status…</p>
<p id="monitorNext" class="sub"></p>
<p id="monitorFault" role="status"></p>
<form id="scheduleForm">
<div class="field"><label><input type="checkbox" id="scheduleEnabled"> Enable scheduled monitoring</label></div>
<div class="wifi-form">
<div class="field"><label for="weekdayStart">Monday–Friday start</label><input id="weekdayStart" type="text" inputmode="numeric" pattern="([01][0-9]|2[0-3]):[0-5][0-9]" maxlength="5" placeholder="HH:MM" title="24-hour time, HH:MM" required value="12:00"></div>
<div class="field"><label for="weekdayEnd">Monday–Friday end</label><input id="weekdayEnd" type="text" inputmode="numeric" pattern="([01][0-9]|2[0-3]):[0-5][0-9]" maxlength="5" placeholder="HH:MM" title="24-hour time, HH:MM" required value="01:00"></div>
<div class="field"><label for="weekendStart">Saturday–Sunday start</label><input id="weekendStart" type="text" inputmode="numeric" pattern="([01][0-9]|2[0-3]):[0-5][0-9]" maxlength="5" placeholder="HH:MM" title="24-hour time, HH:MM" required value="12:00"></div>
<div class="field"><label for="weekendEnd">Saturday–Sunday end</label><input id="weekendEnd" type="text" inputmode="numeric" pattern="([01][0-9]|2[0-3]):[0-5][0-9]" maxlength="5" placeholder="HH:MM" title="24-hour time, HH:MM" required value="02:00"></div>
<div class="field"><label for="powerPreference">Outside monitoring hours</label><select id="powerPreference"><option value="1">Idle + Wi-Fi power saving</option><option value="0">Idle + responsive Wi-Fi</option></select></div>
<div class="field"><label for="overrideMinutes">Temporary monitoring (minutes)</label><input id="overrideMinutes" type="number" min="1" max="1440" value="30" required></div>
</div>
<p class="sub">Idle stops the microphone and keeps this page reachable. Hardware sleep is unavailable in this release pending V2 power-hold testing. BOOT wakes listening from idle; PWR keeps its existing function.</p>
<div class="row"><button type="submit" id="saveSchedule">Save schedule</button><button type="button" class="secondary" id="monitorOverride">Monitor temporarily</button><button type="button" class="secondary" id="monitorReturn">Return to schedule</button></div>
<div id="scheduleMessage" class="message" role="status"></div>
</form>
</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. Discard permanently removes recordings from this device and adjusts today's count.</p></div><div class="row"><button id="sendAll">Send all</button><button class="danger" id="clearQueue">Clear queue</button><button class="secondary" id="resetToday">Reset today count</button></div></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,queueFingerprint='',previewAudio=null,previewButton=null;
function stopPreview(){if(previewAudio){previewAudio.onended=null;previewAudio.onerror=null;previewAudio.pause();previewAudio.removeAttribute('src');previewAudio=null}if(previewButton){previewButton.textContent='Play';previewButton.setAttribute('aria-label','Play recording');previewButton=null}}
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;$('clearQueue').disabled=!s.queue;$('mic').textContent=s.capturing?'Saving':(s.monitoring.microphoneActive?'Listening':'Off');renderMonitor(s.monitoring);$('sd').textContent=s.sd?'Ready':'Missing';$('deviceAddress').textContent='IP: '+s.ip;$('ssidLine').textContent='Wi-Fi: '+(s.ssid||'—');$('firmwareVersion').textContent='Firmware: '+(s.version||'—');$('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');const fingerprint=JSON.stringify(items);if(fingerprint===queueFingerprint)return;stopPreview();queueFingerprint=fingerprint;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 actions=document.createElement('div');actions.className='row';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)}};const discard=document.createElement('button');discard.className='danger';discard.textContent='Discard';discard.setAttribute('aria-label','Discard '+item.name);discard.onclick=async()=>{if(!confirm('Permanently discard '+item.name+' from this device?'))return;discard.disabled=true;try{await api('/api/events/discard',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded','X-BoomCast-Action':'discard'},body:new URLSearchParams({file:item.name})});$('syncMessage').textContent='Discarded '+item.name;await refreshQueue();await refreshStatus()}catch(e){$('syncMessage').textContent=e.message}finally{discard.disabled=false}};const play=document.createElement('button');play.className='secondary';play.textContent='Play';play.setAttribute('aria-label','Play '+item.name);play.onclick=async()=>{if(previewAudio&&previewButton===play){if(previewAudio.paused){try{await previewAudio.play();play.textContent='Pause';play.setAttribute('aria-label','Pause '+item.name)}catch(e){$('syncMessage').textContent='Could not play '+item.name}}else{previewAudio.pause();play.textContent='Play';play.setAttribute('aria-label','Play '+item.name)}return}stopPreview();const audio=new Audio('/api/events/audio?file='+encodeURIComponent(item.name));previewAudio=audio;previewButton=play;audio.onended=()=>stopPreview();audio.onerror=()=>{$('syncMessage').textContent='Could not load '+item.name;stopPreview()};try{await audio.play();play.textContent='Pause';play.setAttribute('aria-label','Pause '+item.name)}catch(e){$('syncMessage').textContent='Could not play '+item.name;stopPreview()}};actions.append(b,play,discard);row.append(info,actions);box.appendChild(row)})}catch(e){queueFingerprint='';$('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}};
$('clearQueue').onclick=async()=>{const count=Number($('queued').textContent)||0;if(!count)return;if(!confirm('Permanently discard all '+count+' queued recording(s) from this device? They cannot be recovered.'))return;const b=$('clearQueue');b.disabled=true;try{const result=await api('/api/events/discard',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded','X-BoomCast-Action':'discard'},body:new URLSearchParams({all:'1'})});$('syncMessage').textContent='Discarded '+result.removed+' queued recording(s).';await refreshQueue();await refreshStatus()}catch(e){$('syncMessage').textContent=e.message}finally{b.disabled=false}};
$('resetToday').onclick=async()=>{if(!confirm('Reset the ePaper today count to zero? Queued recordings will stay on the SD card.'))return;const b=$('resetToday');b.disabled=true;try{await api('/api/today/reset',{method:'POST',headers:{'X-BoomCast-Action':'discard'}});$('syncMessage').textContent='Today count reset.';await refreshStatus()}catch(e){$('syncMessage').textContent=e.message}finally{b.disabled=false}};
$('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}};
let scheduleLoaded=false;
const scheduleTimes=['weekdayStart','weekdayEnd','weekendStart','weekendEnd'];
function renderMonitor(m){
const names={MONITORING:'Monitoring',SCHEDULED_IDLE:'Scheduled idle',SCHEDULED_SLEEP:'Scheduled sleep',MANUAL_OVERRIDE:'Temporary monitoring'};
$('monitorState').textContent=(names[m.state]||m.state)+(m.overrideRemaining?' · '+Math.ceil(m.overrideRemaining/60)+' min remaining':'');
$('monitorNext').textContent='Next schedule transition: '+m.nextTransition+' · Last wake: '+m.wakeReason;
$('monitorFault').textContent=m.fault||'';
$('monitorReturn').disabled=!m.overrideRemaining;
if(!scheduleLoaded){
$('scheduleEnabled').checked=m.enabled;$('powerPreference').value=m.modemSleep?'1':'0';$('overrideMinutes').value=m.overrideMinutes;
scheduleTimes.forEach(id=>{$(id).value=String(Math.floor(m[id]/60)).padStart(2,'0')+':'+String(m[id]%60).padStart(2,'0')});
scheduleLoaded=true;
}
}
$('scheduleForm').onsubmit=async e=>{e.preventDefault();const button=$('saveSchedule');button.disabled=true;const body=new URLSearchParams({enabled:$('scheduleEnabled').checked?'1':'0',modemSleep:$('powerPreference').value,overrideMinutes:$('overrideMinutes').value});scheduleTimes.forEach(id=>body.set(id,$(id).value));try{await api('/api/monitoring',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded','X-BoomCast-Action':'monitoring'},body});$('scheduleMessage').textContent='Schedule saved. Changes take effect after any current recording finishes.';await refreshStatus()}catch(err){$('scheduleMessage').textContent=err.message}finally{button.disabled=false}};
async function monitorAction(action){try{await api('/api/monitoring/'+action,{method:'POST',headers:{'X-BoomCast-Action':'monitoring'}});$('scheduleMessage').textContent=action==='override'?'Temporary monitoring requested.':'Returning to schedule.';await refreshStatus()}catch(err){$('scheduleMessage').textContent=err.message}}
$('monitorOverride').onclick=()=>monitorAction('override');$('monitorReturn').onclick=()=>monitorAction('return');
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() {
const char* actionHeaders[] = {"X-BoomCast-Action"};
server_.collectHeaders(actionHeaders, 1);
server_.on("/", HTTP_GET, [this]() { handleRoot(); });
server_.on("/api/status", HTTP_GET, [this]() { handleStatus(); });
server_.on("/api/monitoring", HTTP_POST, [this]() {
if (!authorise()) return;
if (server_.header("X-BoomCast-Action") != "monitoring") { sendJson(403, "{\"error\":\"Missing monitoring action header\"}"); return; }
BoomScheduleConfig c;
auto parseTime = [this](const char* key, uint16_t& value) {
String v = server_.arg(key);
if (v.length() != 5 || v[2] != ':' || !isDigit(v[0]) || !isDigit(v[1]) || !isDigit(v[3]) || !isDigit(v[4])) return false;
int h = v.substring(0,2).toInt(), m = v.substring(3).toInt();
if (h > 23 || m > 59) return false;
value = h * 60 + m; return true;
};
String minutes = server_.arg("overrideMinutes");
bool numeric = minutes.length() > 0 && minutes.length() <= 4;
for (size_t i = 0; i < minutes.length(); ++i) numeric = numeric && isDigit(minutes[i]);
String enabled = server_.arg("enabled"), modem = server_.arg("modemSleep");
c.enabled = enabled == "1"; c.modemSleep = modem == "1"; c.overrideMinutes = minutes.toInt();
if (!numeric || (enabled != "0" && enabled != "1") || (modem != "0" && modem != "1") ||
!parseTime("weekdayStart", c.weekdayStart) || !parseTime("weekdayEnd", c.weekdayEnd) ||
!parseTime("weekendStart", c.weekendStart) || !parseTime("weekendEnd", c.weekendEnd) || !c.valid()) {
sendJson(400, "{\"error\":\"Use valid 24-hour times and 1–1440 override minutes\"}"); return;
}
if (!boomMonitor.save(c)) { sendJson(500, "{\"error\":\"Could not persist schedule\"}"); return; }
sendJson(200, "{\"ok\":true}");
});
server_.on("/api/monitoring/override", HTTP_POST, [this]() {
if (!authorise()) return;
if (server_.header("X-BoomCast-Action") != "monitoring") { sendJson(403, "{\"error\":\"Missing monitoring action header\"}"); return; }
boomMonitor.overrideNow(); sendJson(200, "{\"ok\":true}");
});
server_.on("/api/monitoring/return", HTTP_POST, [this]() {
if (!authorise()) return;
if (server_.header("X-BoomCast-Action") != "monitoring") { sendJson(403, "{\"error\":\"Missing monitoring action header\"}"); return; }
boomMonitor.returnToSchedule(); sendJson(200, "{\"ok\":true}");
});
server_.on("/api/events", HTTP_GET, [this]() { handleEvents(); });
server_.on("/api/events/audio", HTTP_GET, [this]() { handleEventAudio(); });
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/events/discard", HTTP_POST, [this]() { handleDiscard(); });
server_.on("/api/today/reset", HTTP_POST, [this]() { handleTodayReset(); });
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 += ",\"monitoring\":" + boomMonitor.json();
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::handleEventAudio() {
if (!authorise()) return;
String file = server_.arg("file");
if (!file.length() || file.indexOf('/') >= 0 || file.indexOf('\\') >= 0 ||
!file.endsWith(".wav") || !boomQueue.exists(file)) {
sendJson(404, "{\"error\":\"Queued recording not found\"}");
return;
}
FILE* recording = fopen(boomQueue.absolutePath(file).c_str(), "rb");
if (!recording) {
sendJson(500, "{\"error\":\"Could not open recording\"}");
return;
}
size_t remaining = boomQueue.fileSize(file);
addNoCache();
server_.setContentLength(remaining);
server_.send(200, "audio/wav", "");
NetworkClient& output = server_.client();
uint8_t chunk[1024];
while (remaining && output.connected()) {
size_t read = fread(chunk, 1, min(sizeof(chunk), remaining), recording);
if (!read) break;
size_t written = 0;
while (written < read && output.connected()) {
size_t n = output.write(chunk + written, read - written);
if (!n) break;
written += n;
}
if (written != read) break;
remaining -= read;
}
fclose(recording);
if (remaining) Serial.printf("[Web] audio preview interrupted: %s (%u bytes left)\n", file.c_str(), unsigned(remaining));
}
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::handleDiscard() {
if (!authorise()) return;
// Require a non-simple request header so another site cannot submit a
// cross-origin form using cached HTTP Basic credentials.
if (server_.header("X-BoomCast-Action") != "discard") {
sendJson(403, "{\"error\":\"Discard action header required\"}");
return;
}
if (!boomQueue.ready()) {
sendJson(503, "{\"error\":\"SD card is unavailable\"}");
return;
}
if (server_.arg("all") == "1") {
int removed = boomQueue.clearAll();
if (removed < 0) {
sendJson(500, "{\"error\":\"Could not remove every queued recording\"}");
return;
}
boomState.setSyncing(false, "Discarded " + String(removed) + " queued recording(s)");
sendJson(200, "{\"ok\":true,\"removed\":" + String(removed) + "}");
return;
}
String file = server_.arg("file");
if (!file.length() || file.indexOf('/') >= 0 || file.indexOf('\\') >= 0 || !file.endsWith(".wav")) {
sendJson(400, "{\"error\":\"Valid queued filename required\"}");
return;
}
if (!boomQueue.exists(file)) {
sendJson(404, "{\"error\":\"Queued recording not found\"}");
return;
}
if (!boomQueue.discard(file)) {
sendJson(500, "{\"error\":\"Could not discard recording\"}");
return;
}
boomState.setSyncing(false, "Discarded " + file);
sendJson(200, "{\"ok\":true,\"removed\":1}");
}
void BoomWeb::handleTodayReset() {
if (!authorise()) return;
if (server_.header("X-BoomCast-Action") != "discard") {
sendJson(403, "{\"error\":\"Reset action header required\"}");
return;
}
boomState.resetTodayEvents();
boomState.setSyncing(false, "Today count reset");
sendJson(200, "{\"ok\":true,\"today\":0}");
}
void BoomWeb::handleReboot() {
if (!authorise()) return;
sendJson(200, "{\"ok\":true,\"rebooting\":true}");
boomState.requestReboot(900);
}