various tweaks and improvements
This commit is contained in:
@@ -4,6 +4,7 @@
|
||||
#include "boomcast_network.h"
|
||||
#include "boomcast_queue.h"
|
||||
#include "boomcast_state.h"
|
||||
#include <stdio.h>
|
||||
|
||||
BoomWeb boomWeb;
|
||||
|
||||
@@ -60,6 +61,7 @@ static const char MANAGEMENT_HTML[] PROGMEM = R"BOOMHTML(
|
||||
<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">
|
||||
@@ -81,12 +83,13 @@ static const char MANAGEMENT_HTML[] PROGMEM = R"BOOMHTML(
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
const $=id=>document.getElementById(id);let statusBusy=false,queueBusy=false;
|
||||
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':'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 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}};actions.append(b,discard);row.append(info,actions);box.appendChild(row)})}catch(e){$('eventList').textContent='Could not read queue: '+e.message}finally{queueBusy=false}}
|
||||
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':'Listening';$('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}};
|
||||
@@ -125,6 +128,7 @@ 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/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(); });
|
||||
@@ -182,6 +186,41 @@ void BoomWeb::handleEvents() {
|
||||
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());
|
||||
|
||||
Reference in New Issue
Block a user