Files
corescope-rx/src/app.js
T
efiten a39504826d feat(app): recently-heard nodes list (latest SNR, colour-coded) + debug log toggle
Clean list of the last 20 heard nodes with their latest SNR (green→red), hit
count; raw debug log collapsed behind a toggle. Node-name lookup deferred (needs
a CORS allowance for rx.on8ar.eu on the analyzer API + full node-list fetch).
2026-06-09 19:14:56 +02:00

204 lines
7.8 KiB
JavaScript
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.
// corescope-rx — wiring + minimal field UI + on-screen debug.
// Pipeline: companion BLE 0x88 frame → parse raw packet → direct-heard filter →
// tag with phone GPS → IndexedDB queue → MQTT publish to CoreScope's ingestor.
// The companion's own pubkey (from SELF_INFO) is the identity / clientId / topic;
// the user never types it.
import { WebBluetoothTransport } from './transport.js';
import { parseFrame, PUSH_CODE_LOG_RX_DATA } from './frames.js';
import { parsePacket, deriveHeardKey, bytesToHex } from './meshpacket.js';
import { requestSelfInfo } from './selfinfo.js';
import { Gps } from './gps.js';
import { Queue } from './queue.js';
import { Publisher } from './publisher.js';
const els = (id) => document.getElementById(id);
const state = { transport: null, gps: new Gps(), queue: new Queue(), publisher: null, heard: 0, companionPubkey: '', connected: false, recent: [] };
const RECENT_MAX = 20;
// SNR → colour bucket (LoRa-ish). Returns a CSS colour.
function snrColor(snr) {
if (snr == null) return '#95a5a6';
if (snr >= 5) return '#2ecc71';
if (snr >= -3) return '#f1c40f';
if (snr >= -10) return '#e67e22';
return '#e74c3c';
}
// noteHeard upserts a heard node into the recent list (most-recent first).
function noteHeard(key, keylen, snr, rssi, src) {
let e = state.recent.find((x) => x.key === key);
if (e) state.recent = state.recent.filter((x) => x !== e);
else e = { key, keylen, count: 0, src };
e.count++; e.snr = snr; e.rssi = rssi; e.last = Date.now();
state.recent.unshift(e);
state.recent = state.recent.slice(0, RECENT_MAX);
renderRecent();
}
function renderRecent() {
const el = els('recent');
if (!state.recent.length) { el.innerHTML = '<div class="muted">— nothing yet —</div>'; return; }
el.innerHTML = state.recent.map((e) => {
const snr = e.snr != null ? e.snr.toFixed(1) + ' dB' : 'no sig';
return '<div class="rr">' +
'<span class="dot" style="background:' + snrColor(e.snr) + '"></span>' +
'<span class="rk">' + e.key + '</span>' +
'<span class="rsnr" style="color:' + snrColor(e.snr) + '">' + snr + '</span>' +
'<span class="rc">×' + e.count + '</span></div>';
}).join('');
}
// MQTT config from build-time env (Vite); never the UI. Treat as a shared,
// publish-only ingest account (EMQX ACL); not a real secret.
const MQTT_CFG = {
url: import.meta.env.VITE_MQTT_URL,
username: import.meta.env.VITE_MQTT_USERNAME,
password: import.meta.env.VITE_MQTT_PASSWORD,
};
function log(msg) { els('status').textContent = msg; }
function dbg(msg) {
const el = els('log');
el.textContent = '[' + new Date().toLocaleTimeString() + '] ' + msg + '\n' + el.textContent;
if (el.textContent.length > 8000) el.textContent = el.textContent.slice(0, 8000);
}
function setButton() {
const b = els('btnConnect');
b.textContent = state.connected ? 'Disconnect' : 'Connect companion (BLE)';
b.classList.toggle('danger', state.connected);
}
// Stepped progress block under the button.
function progressReset() { els('progress').innerHTML = ''; }
function step(msg, cls) {
const d = document.createElement('div');
d.textContent = msg;
if (cls) d.className = cls;
els('progress').appendChild(d);
return d;
}
async function refreshCounters() {
els('heard').textContent = String(state.heard);
els('pending').textContent = String(await state.queue.count());
els('gps').textContent = currentFix() ? '✓ fix' : '… no fix';
}
function currentFix() {
return state.gps.latest();
}
async function processFrame(dv) {
const f = parseFrame(dv);
if (!f || f.code !== PUSH_CODE_LOG_RX_DATA) return;
const rawHex = bytesToHex(f.raw);
dbg('0x88 RX snr=' + f.snr + ' rssi=' + f.rssi + ' raw=' + rawHex.slice(0, 32) + (rawHex.length > 32 ? '…' : ''));
const pkt = parsePacket(f.raw);
const hk = deriveHeardKey('rx', pkt);
if (!hk) { dbg(' → not attributable (tx / 1-byte hop / no advert) — skip'); return; }
dbg(' → heard ' + hk.heardKey + ' (' + hk.heardKeyLen + 'B, ' + hk.src + ')');
noteHeard(hk.heardKey, hk.heardKeyLen, f.snr, f.rssi, hk.src); // show in the list even without a GPS fix
const fix = currentFix();
if (!fix) { dbg(' → no GPS fix — skip'); return; }
const rec = { rx_at: new Date().toISOString(), raw: rawHex, snr: f.snr, rssi: f.rssi, lat: fix.lat, lon: fix.lon, acc_m: fix.acc_m };
await state.queue.add(rec);
state.heard++;
refreshCounters();
}
async function drainLoop() {
if (state.publisher && state.publisher.connected() && state.companionPubkey) {
try {
const rows = await state.queue.takeAll();
const done = [];
for (const r of rows) { await state.publisher.publish(state.companionPubkey, r); done.push(r.id); }
if (done.length) { await state.queue.remove(done); dbg('published ' + done.length + ' record(s)'); }
} catch (e) { dbg('publish error (kept buffered): ' + e.message); }
refreshCounters();
}
setTimeout(drainLoop, 5000);
}
async function connectAll() {
els('btnConnect').disabled = true;
progressReset();
els('companionInfo').textContent = '';
log('');
const s1 = step('① Connecting to companion…', 'pending');
try {
state.transport = new WebBluetoothTransport();
state.transport.onFrame(processFrame);
state.transport.onStatus((s) => {
dbg('BLE: ' + s);
if (state.connected) log(s === 'connected' ? 'capturing' : 'BLE ' + s + '…');
});
await state.transport.connect();
s1.textContent = '① Companion connected ✓';
s1.className = '';
const s2 = step('② Reading companion ID…', 'pending');
const info = await requestSelfInfo(state.transport);
state.companionPubkey = info.pubkey.toLowerCase();
s2.textContent = '② Companion: ' + (info.name || '(unnamed)') + ' ✓';
s2.className = '';
els('companionInfo').textContent = state.companionPubkey.slice(0, 20) + '…';
dbg('SELF_INFO → ' + (info.name || '(unnamed)') + ' ' + state.companionPubkey);
state.gps.start();
const s3 = step('③ Connecting to ON8AR CoreScope…', 'pending');
if (MQTT_CFG.url) {
state.publisher = new Publisher({ ...MQTT_CFG, clientId: state.companionPubkey });
await state.publisher.connect();
s3.textContent = '③ ON8AR CoreScope connected ✓';
s3.className = '';
} else {
s3.textContent = '③ MQTT not configured (.env.local)';
s3.className = 'err';
}
step('✅ All connected — capturing');
state.connected = true;
setButton();
log('capturing as ' + (info.name || state.companionPubkey.slice(0, 12)));
} catch (e) {
step('✗ ' + e.message, 'err');
dbg('connect failed: ' + e.message);
log('connect failed: ' + e.message);
await disconnectAll(true);
}
els('btnConnect').disabled = false;
refreshCounters();
}
async function disconnectAll(keepProgress) {
if (state.publisher) { state.publisher.end(); state.publisher = null; }
try { state.gps.stop(); } catch (e) {}
if (state.transport) { try { await state.transport.disconnect(); } catch (e) {} state.transport = null; }
state.connected = false;
els('companionInfo').textContent = '';
if (!keepProgress) { progressReset(); log('disconnected.'); }
setButton();
}
window.addEventListener('DOMContentLoaded', () => {
setButton();
els('btnConnect').addEventListener('click', () => (state.connected ? disconnectAll() : connectAll()));
els('btnClear').addEventListener('click', () => { els('log').textContent = ''; });
els('btnDbg').addEventListener('click', () => {
const log = els('log');
const show = log.style.display === 'none';
log.style.display = show ? 'block' : 'none';
els('btnDbg').textContent = show ? 'Hide debug log' : 'Show debug log';
});
renderRecent();
refreshCounters();
drainLoop();
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').catch(() => {});
}
});