No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

1260 líneas
41KB

  1. const qs = (id) => document.getElementById(id);
  2. const navCanvas = qs('navCanvas');
  3. const spectrumCanvas = qs('spectrum');
  4. const waterfallCanvas = qs('waterfall');
  5. const occupancyCanvas = qs('occupancy');
  6. const timelineCanvas = qs('timeline');
  7. const detailSpectrogram = qs('detailSpectrogram');
  8. const wsBadge = qs('wsBadge');
  9. const metaLine = qs('metaLine');
  10. const heroSubtitle = qs('heroSubtitle');
  11. const configStatusEl = qs('configStatus');
  12. const timelineRangeEl = qs('timelineRange');
  13. const metricCenter = qs('metricCenter');
  14. const metricSpan = qs('metricSpan');
  15. const metricRes = qs('metricRes');
  16. const metricSignals = qs('metricSignals');
  17. const metricGpu = qs('metricGpu');
  18. const metricSource = qs('metricSource');
  19. const centerInput = qs('centerInput');
  20. const spanInput = qs('spanInput');
  21. const sampleRateSelect = qs('sampleRateSelect');
  22. const bwSelect = qs('bwSelect');
  23. const fftSelect = qs('fftSelect');
  24. const gainRange = qs('gainRange');
  25. const gainInput = qs('gainInput');
  26. const thresholdRange = qs('thresholdRange');
  27. const thresholdInput = qs('thresholdInput');
  28. const agcToggle = qs('agcToggle');
  29. const dcToggle = qs('dcToggle');
  30. const iqToggle = qs('iqToggle');
  31. const avgSelect = qs('avgSelect');
  32. const maxHoldToggle = qs('maxHoldToggle');
  33. const gpuToggle = qs('gpuToggle');
  34. const signalList = qs('signalList');
  35. const eventList = qs('eventList');
  36. const recordingList = qs('recordingList');
  37. const signalCountBadge = qs('signalCountBadge');
  38. const eventCountBadge = qs('eventCountBadge');
  39. const recordingCountBadge = qs('recordingCountBadge');
  40. const healthBuffer = qs('healthBuffer');
  41. const healthDropped = qs('healthDropped');
  42. const healthResets = qs('healthResets');
  43. const healthAge = qs('healthAge');
  44. const healthGpu = qs('healthGpu');
  45. const healthFps = qs('healthFps');
  46. const drawerEl = qs('eventDrawer');
  47. const drawerCloseBtn = qs('drawerClose');
  48. const detailSubtitle = qs('detailSubtitle');
  49. const detailCenterEl = qs('detailCenter');
  50. const detailBwEl = qs('detailBw');
  51. const detailStartEl = qs('detailStart');
  52. const detailEndEl = qs('detailEnd');
  53. const detailSnrEl = qs('detailSnr');
  54. const detailDurEl = qs('detailDur');
  55. const detailClassEl = qs('detailClass');
  56. const jumpToEventBtn = qs('jumpToEventBtn');
  57. const exportEventBtn = qs('exportEventBtn');
  58. const liveListenEventBtn = qs('liveListenEventBtn');
  59. const decodeEventBtn = qs('decodeEventBtn');
  60. const decodeModeSelect = qs('decodeMode');
  61. const recordingMetaEl = qs('recordingMeta');
  62. const recordingMetaLink = qs('recordingMetaLink');
  63. const recordingIQLink = qs('recordingIQLink');
  64. const recordingAudioLink = qs('recordingAudioLink');
  65. const followBtn = qs('followBtn');
  66. const fitBtn = qs('fitBtn');
  67. const resetMaxBtn = qs('resetMaxBtn');
  68. const timelineFollowBtn = qs('timelineFollowBtn');
  69. const timelineFreezeBtn = qs('timelineFreezeBtn');
  70. const modeButtons = Array.from(document.querySelectorAll('.mode-btn'));
  71. const railTabs = Array.from(document.querySelectorAll('.rail-tab'));
  72. const tabPanels = Array.from(document.querySelectorAll('.tab-panel'));
  73. const presetButtons = Array.from(document.querySelectorAll('.preset-btn'));
  74. const liveListenBtn = qs('liveListenBtn');
  75. let latest = null;
  76. let currentConfig = null;
  77. let stats = { buffer_samples: 0, dropped: 0, resets: 0, last_sample_ago_ms: -1 };
  78. let gpuInfo = { available: false, active: false, error: '' };
  79. let zoom = 1;
  80. let pan = 0;
  81. let followLive = true;
  82. let maxHold = false;
  83. let avgAlpha = 0;
  84. let avgSpectrum = null;
  85. let maxSpectrum = null;
  86. let lastFFTSize = null;
  87. let pendingConfigUpdate = null;
  88. let pendingSettingsUpdate = null;
  89. let configTimer = null;
  90. let settingsTimer = null;
  91. let isSyncingConfig = false;
  92. let isDraggingSpectrum = false;
  93. let dragStartX = 0;
  94. let dragStartPan = 0;
  95. let navDrag = false;
  96. let timelineFrozen = false;
  97. let renderFrames = 0;
  98. let renderFps = 0;
  99. let lastFpsTs = performance.now();
  100. let wsReconnectTimer = null;
  101. let eventsFetchInFlight = false;
  102. const events = [];
  103. const eventsById = new Map();
  104. let lastEventEndMs = 0;
  105. let selectedEventId = null;
  106. let timelineRects = [];
  107. let liveSignalRects = [];
  108. let recordings = [];
  109. let recordingsFetchInFlight = false;
  110. const GAIN_MAX = 60;
  111. const timelineWindowMs = 5 * 60 * 1000;
  112. function setConfigStatus(text) {
  113. configStatusEl.textContent = text;
  114. }
  115. function setWsBadge(text, kind = 'neutral') {
  116. wsBadge.textContent = text;
  117. wsBadge.style.borderColor = kind === 'ok'
  118. ? 'rgba(124, 251, 131, 0.35)'
  119. : kind === 'bad'
  120. ? 'rgba(255, 107, 129, 0.35)'
  121. : 'rgba(112, 150, 207, 0.18)';
  122. }
  123. function toMHz(hz) { return hz / 1e6; }
  124. function fromMHz(mhz) { return mhz * 1e6; }
  125. function fmtMHz(hz, digits = 3) { return `${(hz / 1e6).toFixed(digits)} MHz`; }
  126. function fmtKHz(hz, digits = 2) { return `${(hz / 1e3).toFixed(digits)} kHz`; }
  127. function fmtHz(hz) {
  128. if (hz >= 1e6) return `${(hz / 1e6).toFixed(3)} MHz`;
  129. if (hz >= 1e3) return `${(hz / 1e3).toFixed(2)} kHz`;
  130. return `${hz.toFixed(0)} Hz`;
  131. }
  132. function fmtMs(ms) {
  133. if (ms < 1000) return `${Math.max(0, Math.round(ms))} ms`;
  134. return `${(ms / 1000).toFixed(2)} s`;
  135. }
  136. function colorMap(v) {
  137. const x = Math.max(0, Math.min(1, v));
  138. const r = Math.floor(255 * Math.pow(x, 0.55));
  139. const g = Math.floor(255 * Math.pow(x, 1.08));
  140. const b = Math.floor(220 * Math.pow(1 - x, 1.15));
  141. return [r, g, b];
  142. }
  143. function snrColor(snr) {
  144. const norm = Math.max(0, Math.min(1, (snr + 5) / 35));
  145. const [r, g, b] = colorMap(norm);
  146. return `rgb(${r}, ${g}, ${b})`;
  147. }
  148. function binForFreq(freq, centerHz, sampleRate, n) {
  149. return Math.floor((freq - (centerHz - sampleRate / 2)) / (sampleRate / n));
  150. }
  151. function maxInBinRange(spectrum, b0, b1) {
  152. const n = spectrum.length;
  153. let start = Math.max(0, Math.min(n - 1, b0));
  154. let end = Math.max(0, Math.min(n - 1, b1));
  155. if (end < start) [start, end] = [end, start];
  156. let max = -1e9;
  157. for (let i = start; i <= end; i++) {
  158. if (spectrum[i] > max) max = spectrum[i];
  159. }
  160. return max;
  161. }
  162. function processSpectrum(spectrum) {
  163. if (!spectrum) return spectrum;
  164. let base = spectrum;
  165. if (avgAlpha > 0) {
  166. if (!avgSpectrum || avgSpectrum.length !== spectrum.length) {
  167. avgSpectrum = spectrum.slice();
  168. } else {
  169. for (let i = 0; i < spectrum.length; i++) {
  170. avgSpectrum[i] = avgAlpha * spectrum[i] + (1 - avgAlpha) * avgSpectrum[i];
  171. }
  172. }
  173. base = avgSpectrum;
  174. }
  175. if (maxHold) {
  176. if (!maxSpectrum || maxSpectrum.length !== base.length) {
  177. maxSpectrum = base.slice();
  178. } else {
  179. for (let i = 0; i < base.length; i++) {
  180. if (base[i] > maxSpectrum[i]) maxSpectrum[i] = base[i];
  181. }
  182. }
  183. base = maxSpectrum;
  184. }
  185. return base;
  186. }
  187. function resetProcessingCaches() {
  188. avgSpectrum = null;
  189. maxSpectrum = null;
  190. }
  191. function resizeCanvas(canvas) {
  192. if (!canvas) return;
  193. const rect = canvas.getBoundingClientRect();
  194. const dpr = window.devicePixelRatio || 1;
  195. const width = Math.max(1, Math.floor(rect.width * dpr));
  196. const height = Math.max(1, Math.floor(rect.height * dpr));
  197. if (canvas.width !== width || canvas.height !== height) {
  198. canvas.width = width;
  199. canvas.height = height;
  200. }
  201. }
  202. function resizeAll() {
  203. [navCanvas, spectrumCanvas, waterfallCanvas, occupancyCanvas, timelineCanvas, detailSpectrogram].forEach(resizeCanvas);
  204. }
  205. window.addEventListener('resize', resizeAll);
  206. resizeAll();
  207. function setSelectValueOrNearest(selectEl, numericValue) {
  208. if (!selectEl) return;
  209. const options = Array.from(selectEl.options || []);
  210. const exact = options.find(o => Number.parseFloat(o.value) === numericValue);
  211. if (exact) {
  212. selectEl.value = exact.value;
  213. return;
  214. }
  215. let best = options[0];
  216. let bestDist = Infinity;
  217. for (const opt of options) {
  218. const dist = Math.abs(Number.parseFloat(opt.value) - numericValue);
  219. if (dist < bestDist) {
  220. best = opt;
  221. bestDist = dist;
  222. }
  223. }
  224. if (best) selectEl.value = best.value;
  225. }
  226. function applyConfigToUI(cfg) {
  227. if (!cfg) return;
  228. isSyncingConfig = true;
  229. centerInput.value = toMHz(cfg.center_hz).toFixed(6);
  230. setSelectValueOrNearest(sampleRateSelect, cfg.sample_rate / 1e6);
  231. setSelectValueOrNearest(bwSelect, cfg.tuner_bw_khz || 1536);
  232. setSelectValueOrNearest(fftSelect, cfg.fft_size);
  233. if (lastFFTSize !== cfg.fft_size) {
  234. resetProcessingCaches();
  235. lastFFTSize = cfg.fft_size;
  236. }
  237. const uiGain = Math.max(0, Math.min(GAIN_MAX, GAIN_MAX - cfg.gain_db));
  238. gainRange.value = uiGain;
  239. gainInput.value = uiGain;
  240. thresholdRange.value = cfg.detector.threshold_db;
  241. thresholdInput.value = cfg.detector.threshold_db;
  242. agcToggle.checked = !!cfg.agc;
  243. dcToggle.checked = !!cfg.dc_block;
  244. iqToggle.checked = !!cfg.iq_balance;
  245. gpuToggle.checked = !!cfg.use_gpu_fft;
  246. maxHoldToggle.checked = maxHold;
  247. spanInput.value = (cfg.sample_rate / zoom / 1e6).toFixed(3);
  248. isSyncingConfig = false;
  249. }
  250. async function loadConfig() {
  251. try {
  252. const res = await fetch('/api/config');
  253. if (!res.ok) throw new Error('config');
  254. currentConfig = await res.json();
  255. applyConfigToUI(currentConfig);
  256. setConfigStatus('Config synced');
  257. } catch {
  258. setConfigStatus('Config offline');
  259. }
  260. }
  261. async function loadStats() {
  262. try {
  263. const res = await fetch('/api/stats');
  264. if (!res.ok) return;
  265. stats = await res.json();
  266. } catch {}
  267. }
  268. async function loadGPU() {
  269. try {
  270. const res = await fetch('/api/gpu');
  271. if (!res.ok) return;
  272. gpuInfo = await res.json();
  273. } catch {}
  274. }
  275. function queueConfigUpdate(partial) {
  276. if (isSyncingConfig) return;
  277. pendingConfigUpdate = { ...(pendingConfigUpdate || {}), ...partial };
  278. setConfigStatus('Applying…');
  279. clearTimeout(configTimer);
  280. configTimer = setTimeout(sendConfigUpdate, 180);
  281. }
  282. function queueSettingsUpdate(partial) {
  283. if (isSyncingConfig) return;
  284. pendingSettingsUpdate = { ...(pendingSettingsUpdate || {}), ...partial };
  285. setConfigStatus('Applying…');
  286. clearTimeout(settingsTimer);
  287. settingsTimer = setTimeout(sendSettingsUpdate, 120);
  288. }
  289. async function sendConfigUpdate() {
  290. if (!pendingConfigUpdate) return;
  291. const payload = pendingConfigUpdate;
  292. pendingConfigUpdate = null;
  293. try {
  294. const res = await fetch('/api/config', {
  295. method: 'POST',
  296. headers: { 'Content-Type': 'application/json' },
  297. body: JSON.stringify(payload),
  298. });
  299. if (!res.ok) throw new Error('apply');
  300. currentConfig = await res.json();
  301. applyConfigToUI(currentConfig);
  302. setConfigStatus('Config applied');
  303. } catch {
  304. setConfigStatus('Config apply failed');
  305. }
  306. }
  307. async function sendSettingsUpdate() {
  308. if (!pendingSettingsUpdate) return;
  309. const payload = pendingSettingsUpdate;
  310. pendingSettingsUpdate = null;
  311. try {
  312. const res = await fetch('/api/sdr/settings', {
  313. method: 'POST',
  314. headers: { 'Content-Type': 'application/json' },
  315. body: JSON.stringify(payload),
  316. });
  317. if (!res.ok) throw new Error('apply');
  318. currentConfig = await res.json();
  319. applyConfigToUI(currentConfig);
  320. setConfigStatus('Settings applied');
  321. } catch {
  322. setConfigStatus('Settings apply failed');
  323. }
  324. }
  325. function updateHeroMetrics() {
  326. if (!latest) return;
  327. const span = latest.sample_rate / zoom;
  328. const binHz = latest.sample_rate / Math.max(1, latest.spectrum_db?.length || latest.fft_size || 1);
  329. metricCenter.textContent = fmtMHz(latest.center_hz, 6);
  330. metricSpan.textContent = fmtHz(span);
  331. metricRes.textContent = `${binHz.toFixed(1)} Hz/bin`;
  332. metricSignals.textContent = String(latest.signals?.length || 0);
  333. metricGpu.textContent = gpuInfo.active ? 'ON' : (gpuInfo.available ? 'OFF' : 'N/A');
  334. metricSource.textContent = stats.last_sample_ago_ms >= 0 ? `${stats.last_sample_ago_ms} ms` : 'n/a';
  335. const gpuText = gpuInfo.active ? 'GPU active' : (gpuInfo.available ? 'GPU ready' : 'GPU n/a');
  336. metaLine.textContent = `${fmtMHz(latest.center_hz, 3)} · ${fmtHz(span)} span · ${gpuText}`;
  337. heroSubtitle.textContent = `${latest.signals?.length || 0} live signals · ${events.length} recent events tracked`;
  338. healthBuffer.textContent = String(stats.buffer_samples ?? '-');
  339. healthDropped.textContent = String(stats.dropped ?? '-');
  340. healthResets.textContent = String(stats.resets ?? '-');
  341. healthAge.textContent = stats.last_sample_ago_ms >= 0 ? `${stats.last_sample_ago_ms} ms` : 'n/a';
  342. healthGpu.textContent = gpuInfo.error ? `${gpuInfo.active ? 'ON' : 'OFF'} · ${gpuInfo.error}` : (gpuInfo.active ? 'ON' : (gpuInfo.available ? 'Ready' : 'N/A'));
  343. healthFps.textContent = `${renderFps.toFixed(0)} fps`;
  344. }
  345. function renderBandNavigator() {
  346. if (!latest) return;
  347. const ctx = navCanvas.getContext('2d');
  348. const w = navCanvas.width;
  349. const h = navCanvas.height;
  350. ctx.clearRect(0, 0, w, h);
  351. const display = processSpectrum(latest.spectrum_db);
  352. const minDb = -120;
  353. const maxDb = 0;
  354. ctx.fillStyle = '#071018';
  355. ctx.fillRect(0, 0, w, h);
  356. ctx.strokeStyle = 'rgba(102, 169, 255, 0.25)';
  357. ctx.lineWidth = 1;
  358. ctx.beginPath();
  359. for (let x = 0; x < w; x++) {
  360. const idx = Math.min(display.length - 1, Math.floor((x / w) * display.length));
  361. const v = display[idx];
  362. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 10) - 5;
  363. if (x === 0) ctx.moveTo(x, y);
  364. else ctx.lineTo(x, y);
  365. }
  366. ctx.stroke();
  367. const span = latest.sample_rate / zoom;
  368. const fullStart = latest.center_hz - latest.sample_rate / 2;
  369. const viewStart = latest.center_hz - span / 2 + pan * span;
  370. const viewEnd = latest.center_hz + span / 2 + pan * span;
  371. const x1 = ((viewStart - fullStart) / latest.sample_rate) * w;
  372. const x2 = ((viewEnd - fullStart) / latest.sample_rate) * w;
  373. ctx.fillStyle = 'rgba(102, 240, 209, 0.10)';
  374. ctx.strokeStyle = 'rgba(102, 240, 209, 0.85)';
  375. ctx.lineWidth = 2;
  376. ctx.fillRect(x1, 4, Math.max(2, x2 - x1), h - 8);
  377. ctx.strokeRect(x1, 4, Math.max(2, x2 - x1), h - 8);
  378. }
  379. function drawSpectrumGrid(ctx, w, h, startHz, endHz) {
  380. ctx.strokeStyle = 'rgba(86, 109, 148, 0.18)';
  381. ctx.lineWidth = 1;
  382. for (let i = 1; i < 6; i++) {
  383. const y = (h / 6) * i;
  384. ctx.beginPath();
  385. ctx.moveTo(0, y);
  386. ctx.lineTo(w, y);
  387. ctx.stroke();
  388. }
  389. for (let i = 1; i < 8; i++) {
  390. const x = (w / 8) * i;
  391. ctx.beginPath();
  392. ctx.moveTo(x, 0);
  393. ctx.lineTo(x, h);
  394. ctx.stroke();
  395. const hz = startHz + (i / 8) * (endHz - startHz);
  396. ctx.fillStyle = 'rgba(173, 192, 220, 0.72)';
  397. ctx.font = `${Math.max(11, Math.floor(h / 26))}px Inter, sans-serif`;
  398. ctx.fillText((hz / 1e6).toFixed(3), x + 4, h - 8);
  399. }
  400. }
  401. function renderSpectrum() {
  402. if (!latest) return;
  403. const ctx = spectrumCanvas.getContext('2d');
  404. const w = spectrumCanvas.width;
  405. const h = spectrumCanvas.height;
  406. ctx.clearRect(0, 0, w, h);
  407. const display = processSpectrum(latest.spectrum_db);
  408. const n = display.length;
  409. const span = latest.sample_rate / zoom;
  410. const startHz = latest.center_hz - span / 2 + pan * span;
  411. const endHz = latest.center_hz + span / 2 + pan * span;
  412. spanInput.value = (span / 1e6).toFixed(3);
  413. drawSpectrumGrid(ctx, w, h, startHz, endHz);
  414. const minDb = -120;
  415. const maxDb = 0;
  416. const fill = ctx.createLinearGradient(0, 0, 0, h);
  417. fill.addColorStop(0, 'rgba(102, 240, 209, 0.20)');
  418. fill.addColorStop(1, 'rgba(102, 240, 209, 0.02)');
  419. ctx.beginPath();
  420. for (let x = 0; x < w; x++) {
  421. const f1 = startHz + (x / w) * (endHz - startHz);
  422. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  423. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  424. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  425. const v = maxInBinRange(display, b0, b1);
  426. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 18) - 6;
  427. if (x === 0) ctx.moveTo(x, y);
  428. else ctx.lineTo(x, y);
  429. }
  430. ctx.lineTo(w, h);
  431. ctx.lineTo(0, h);
  432. ctx.closePath();
  433. ctx.fillStyle = fill;
  434. ctx.fill();
  435. ctx.strokeStyle = '#66f0d1';
  436. ctx.lineWidth = 2;
  437. ctx.beginPath();
  438. liveSignalRects = [];
  439. for (let x = 0; x < w; x++) {
  440. const f1 = startHz + (x / w) * (endHz - startHz);
  441. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  442. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  443. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  444. const v = maxInBinRange(display, b0, b1);
  445. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 18) - 6;
  446. if (x === 0) ctx.moveTo(x, y);
  447. else ctx.lineTo(x, y);
  448. }
  449. ctx.stroke();
  450. if (Array.isArray(latest.signals)) {
  451. latest.signals.forEach((s, index) => {
  452. const left = s.center_hz - s.bw_hz / 2;
  453. const right = s.center_hz + s.bw_hz / 2;
  454. if (right < startHz || left > endHz) return;
  455. const x1 = ((left - startHz) / (endHz - startHz)) * w;
  456. const x2 = ((right - startHz) / (endHz - startHz)) * w;
  457. const boxW = Math.max(2, x2 - x1);
  458. const color = snrColor(s.snr_db || 0);
  459. ctx.fillStyle = color.replace('rgb', 'rgba').replace(')', ', 0.14)');
  460. ctx.strokeStyle = color;
  461. ctx.lineWidth = 1.5;
  462. ctx.fillRect(x1, 10, boxW, h - 28);
  463. ctx.strokeRect(x1, 10, boxW, h - 28);
  464. ctx.fillStyle = color;
  465. ctx.font = '12px Inter, sans-serif';
  466. const label = `${(s.center_hz / 1e6).toFixed(4)} MHz`;
  467. ctx.fillText(label, Math.max(4, x1 + 4), 24 + (index % 3) * 16);
  468. liveSignalRects.push({
  469. x: x1,
  470. y: 10,
  471. w: boxW,
  472. h: h - 28,
  473. signal: s,
  474. });
  475. });
  476. }
  477. }
  478. function renderWaterfall() {
  479. if (!latest) return;
  480. const ctx = waterfallCanvas.getContext('2d');
  481. const w = waterfallCanvas.width;
  482. const h = waterfallCanvas.height;
  483. const prev = ctx.getImageData(0, 0, w, h - 1);
  484. ctx.putImageData(prev, 0, 1);
  485. const display = processSpectrum(latest.spectrum_db);
  486. const n = display.length;
  487. const span = latest.sample_rate / zoom;
  488. const startHz = latest.center_hz - span / 2 + pan * span;
  489. const endHz = latest.center_hz + span / 2 + pan * span;
  490. const minDb = -120;
  491. const maxDb = 0;
  492. const row = ctx.createImageData(w, 1);
  493. for (let x = 0; x < w; x++) {
  494. const f1 = startHz + (x / w) * (endHz - startHz);
  495. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  496. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  497. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  498. const v = maxInBinRange(display, b0, b1);
  499. const norm = Math.max(0, Math.min(1, (v - minDb) / (maxDb - minDb)));
  500. const [r, g, b] = colorMap(norm);
  501. row.data[x * 4] = r;
  502. row.data[x * 4 + 1] = g;
  503. row.data[x * 4 + 2] = b;
  504. row.data[x * 4 + 3] = 255;
  505. }
  506. ctx.putImageData(row, 0, 0);
  507. }
  508. function renderOccupancy() {
  509. const ctx = occupancyCanvas.getContext('2d');
  510. const w = occupancyCanvas.width;
  511. const h = occupancyCanvas.height;
  512. ctx.clearRect(0, 0, w, h);
  513. ctx.fillStyle = '#071018';
  514. ctx.fillRect(0, 0, w, h);
  515. if (!latest || events.length === 0) return;
  516. const bins = new Array(Math.max(32, Math.min(160, Math.floor(w / 8)))).fill(0);
  517. const bandStart = latest.center_hz - latest.sample_rate / 2;
  518. const bandEnd = latest.center_hz + latest.sample_rate / 2;
  519. const now = Date.now();
  520. const windowStart = now - timelineWindowMs;
  521. for (const ev of events) {
  522. if (ev.end_ms < windowStart || ev.start_ms > now) continue;
  523. const left = ev.center_hz - ev.bandwidth_hz / 2;
  524. const right = ev.center_hz + ev.bandwidth_hz / 2;
  525. const normL = Math.max(0, Math.min(1, (left - bandStart) / (bandEnd - bandStart)));
  526. const normR = Math.max(0, Math.min(1, (right - bandStart) / (bandEnd - bandStart)));
  527. let b0 = Math.floor(normL * bins.length);
  528. let b1 = Math.floor(normR * bins.length);
  529. if (b1 < b0) [b0, b1] = [b1, b0];
  530. for (let i = Math.max(0, b0); i <= Math.min(bins.length - 1, b1); i++) {
  531. bins[i] += Math.max(0.3, (ev.snr_db || 0) / 12 + 1);
  532. }
  533. }
  534. const maxBin = Math.max(1, ...bins);
  535. bins.forEach((v, i) => {
  536. const norm = v / maxBin;
  537. const [r, g, b] = colorMap(norm);
  538. ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
  539. const x = (i / bins.length) * w;
  540. const bw = Math.ceil(w / bins.length) + 1;
  541. ctx.fillRect(x, 0, bw, h);
  542. });
  543. }
  544. function renderTimeline() {
  545. const ctx = timelineCanvas.getContext('2d');
  546. const w = timelineCanvas.width;
  547. const h = timelineCanvas.height;
  548. ctx.clearRect(0, 0, w, h);
  549. ctx.fillStyle = '#071018';
  550. ctx.fillRect(0, 0, w, h);
  551. if (events.length === 0) {
  552. timelineRangeEl.textContent = 'No events yet';
  553. return;
  554. }
  555. const endMs = Date.now();
  556. const startMs = endMs - timelineWindowMs;
  557. timelineRangeEl.textContent = `${new Date(startMs).toLocaleTimeString()} - ${new Date(endMs).toLocaleTimeString()}`;
  558. let minHz = Infinity;
  559. let maxHz = -Infinity;
  560. if (latest) {
  561. minHz = latest.center_hz - latest.sample_rate / 2;
  562. maxHz = latest.center_hz + latest.sample_rate / 2;
  563. } else {
  564. for (const ev of events) {
  565. minHz = Math.min(minHz, ev.center_hz - ev.bandwidth_hz / 2);
  566. maxHz = Math.max(maxHz, ev.center_hz + ev.bandwidth_hz / 2);
  567. }
  568. }
  569. if (!isFinite(minHz) || !isFinite(maxHz) || minHz === maxHz) {
  570. minHz = 0;
  571. maxHz = 1;
  572. }
  573. ctx.strokeStyle = 'rgba(86, 109, 148, 0.18)';
  574. ctx.lineWidth = 1;
  575. for (let i = 1; i < 6; i++) {
  576. const y = (h / 6) * i;
  577. ctx.beginPath();
  578. ctx.moveTo(0, y);
  579. ctx.lineTo(w, y);
  580. ctx.stroke();
  581. }
  582. for (let i = 1; i < 8; i++) {
  583. const x = (w / 8) * i;
  584. ctx.beginPath();
  585. ctx.moveTo(x, 0);
  586. ctx.lineTo(x, h);
  587. ctx.stroke();
  588. }
  589. timelineRects = [];
  590. for (const ev of events) {
  591. if (ev.end_ms < startMs || ev.start_ms > endMs) continue;
  592. const x1 = ((Math.max(ev.start_ms, startMs) - startMs) / (endMs - startMs)) * w;
  593. const x2 = ((Math.min(ev.end_ms, endMs) - startMs) / (endMs - startMs)) * w;
  594. const topHz = ev.center_hz + ev.bandwidth_hz / 2;
  595. const bottomHz = ev.center_hz - ev.bandwidth_hz / 2;
  596. const y1 = ((maxHz - topHz) / (maxHz - minHz)) * h;
  597. const y2 = ((maxHz - bottomHz) / (maxHz - minHz)) * h;
  598. const rect = { x: x1, y: y1, w: Math.max(2, x2 - x1), h: Math.max(3, y2 - y1), id: ev.id };
  599. timelineRects.push(rect);
  600. ctx.fillStyle = snrColor(ev.snr_db || 0).replace('rgb', 'rgba').replace(')', ', 0.85)');
  601. ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
  602. }
  603. if (selectedEventId) {
  604. const hit = timelineRects.find(r => r.id === selectedEventId);
  605. if (hit) {
  606. ctx.strokeStyle = '#ffffff';
  607. ctx.lineWidth = 2;
  608. ctx.strokeRect(hit.x - 1, hit.y - 1, hit.w + 2, hit.h + 2);
  609. }
  610. }
  611. }
  612. function renderDetailSpectrogram() {
  613. const ev = eventsById.get(selectedEventId);
  614. const ctx = detailSpectrogram.getContext('2d');
  615. const w = detailSpectrogram.width;
  616. const h = detailSpectrogram.height;
  617. ctx.clearRect(0, 0, w, h);
  618. ctx.fillStyle = '#071018';
  619. ctx.fillRect(0, 0, w, h);
  620. if (!latest || !ev) return;
  621. const display = processSpectrum(latest.spectrum_db);
  622. const n = display.length;
  623. const localSpan = Math.min(latest.sample_rate, Math.max(ev.bandwidth_hz * 4, latest.sample_rate / 10));
  624. const startHz = ev.center_hz - localSpan / 2;
  625. const endHz = ev.center_hz + localSpan / 2;
  626. const minDb = -120;
  627. const maxDb = 0;
  628. const row = ctx.createImageData(w, 1);
  629. for (let x = 0; x < w; x++) {
  630. const f1 = startHz + (x / w) * (endHz - startHz);
  631. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  632. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  633. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  634. const v = maxInBinRange(display, b0, b1);
  635. const norm = Math.max(0, Math.min(1, (v - minDb) / (maxDb - minDb)));
  636. const [r, g, b] = colorMap(norm);
  637. row.data[x * 4] = r;
  638. row.data[x * 4 + 1] = g;
  639. row.data[x * 4 + 2] = b;
  640. row.data[x * 4 + 3] = 255;
  641. }
  642. for (let y = 0; y < h; y++) ctx.putImageData(row, 0, y);
  643. const centerX = w / 2;
  644. ctx.strokeStyle = 'rgba(255,255,255,0.65)';
  645. ctx.lineWidth = 1;
  646. ctx.beginPath();
  647. ctx.moveTo(centerX, 0);
  648. ctx.lineTo(centerX, h);
  649. ctx.stroke();
  650. }
  651. function renderLists() {
  652. const signals = Array.isArray(latest?.signals) ? [...latest.signals] : [];
  653. signals.sort((a, b) => (b.snr_db || 0) - (a.snr_db || 0));
  654. signalCountBadge.textContent = `${signals.length} live`;
  655. metricSignals.textContent = String(signals.length);
  656. if (signals.length === 0) {
  657. signalList.innerHTML = '<div class="empty-state">No live signals yet.</div>';
  658. } else {
  659. signalList.innerHTML = signals.slice(0, 24).map((s) => `
  660. <button class="list-item signal-item" type="button" data-center="${s.center_hz}" data-bw="${s.bw_hz || 0}" data-class="${s.class?.mod_type || ''}">
  661. <div class="item-top">
  662. <span class="item-title">${fmtMHz(s.center_hz, 6)}</span>
  663. <span class="item-badge" style="color:${snrColor(s.snr_db || 0)}">${(s.snr_db || 0).toFixed(1)} dB</span>
  664. </div>
  665. <div class="item-bottom">
  666. <span class="item-meta">BW ${fmtKHz(s.bw_hz || 0)}</span>
  667. <span class="item-meta">${s.class?.mod_type || 'live carrier'}</span>
  668. </div>
  669. </button>
  670. `).join('');
  671. }
  672. const recent = [...events].sort((a, b) => b.end_ms - a.end_ms);
  673. eventCountBadge.textContent = `${recent.length} stored`;
  674. if (recent.length === 0) {
  675. eventList.innerHTML = '<div class="empty-state">No events yet.</div>';
  676. } else {
  677. eventList.innerHTML = recent.slice(0, 40).map((ev) => `
  678. <button class="list-item event-item ${selectedEventId === ev.id ? 'active' : ''}" type="button" data-event-id="${ev.id}">
  679. <div class="item-top">
  680. <span class="item-title">${fmtMHz(ev.center_hz, 6)}</span>
  681. <span class="item-badge" style="color:${snrColor(ev.snr_db || 0)}">${(ev.snr_db || 0).toFixed(1)} dB</span>
  682. </div>
  683. <div class="item-bottom">
  684. <span class="item-meta">${fmtKHz(ev.bandwidth_hz || 0)} · ${fmtMs(ev.duration_ms || 0)}</span>
  685. <span class="item-meta">${new Date(ev.end_ms).toLocaleTimeString()}</span>
  686. </div>
  687. </button>
  688. `).join('');
  689. }
  690. if (recordingList && recordingCountBadge) {
  691. recordingCountBadge.textContent = `${recordings.length}`;
  692. if (recordings.length === 0) {
  693. recordingList.innerHTML = '<div class="empty-state">No recordings yet.</div>';
  694. } else {
  695. recordingList.innerHTML = recordings.slice(0, 50).map((rec) => `
  696. <button class="list-item recording-item" type="button" data-id="${rec.id}">
  697. <div class="item-top">
  698. <span class="item-title">${new Date(rec.start).toLocaleString()}</span>
  699. <span class="item-badge">${fmtMHz(rec.center_hz || 0, 6)}</span>
  700. </div>
  701. <div class="item-bottom">
  702. <span class="item-meta">${rec.id}</span>
  703. <span class="item-meta">recording</span>
  704. </div>
  705. </button>
  706. `).join('');
  707. }
  708. }
  709. }
  710. function normalizeEvent(ev) {
  711. const startMs = new Date(ev.start).getTime();
  712. const endMs = new Date(ev.end).getTime();
  713. return {
  714. ...ev,
  715. start_ms: startMs,
  716. end_ms: endMs,
  717. duration_ms: Math.max(0, endMs - startMs),
  718. };
  719. }
  720. function upsertEvents(list, replace = false) {
  721. if (replace) {
  722. events.length = 0;
  723. eventsById.clear();
  724. }
  725. for (const raw of list) {
  726. if (!raw || !raw.id || eventsById.has(raw.id)) continue;
  727. const ev = normalizeEvent(raw);
  728. eventsById.set(ev.id, ev);
  729. events.push(ev);
  730. }
  731. events.sort((a, b) => a.end_ms - b.end_ms);
  732. const maxEvents = 1500;
  733. if (events.length > maxEvents) {
  734. const drop = events.length - maxEvents;
  735. for (let i = 0; i < drop; i++) eventsById.delete(events[i].id);
  736. events.splice(0, drop);
  737. }
  738. if (events.length > 0) lastEventEndMs = events[events.length - 1].end_ms;
  739. renderLists();
  740. }
  741. async function fetchEvents(initial) {
  742. if (eventsFetchInFlight || timelineFrozen) return;
  743. eventsFetchInFlight = true;
  744. try {
  745. let url = '/api/events?limit=1000';
  746. if (!initial && lastEventEndMs > 0) url = `/api/events?since=${lastEventEndMs - 1}`;
  747. const res = await fetch(url);
  748. if (!res.ok) return;
  749. const data = await res.json();
  750. if (Array.isArray(data)) upsertEvents(data, initial);
  751. } finally {
  752. eventsFetchInFlight = false;
  753. }
  754. }
  755. async function fetchRecordings() {
  756. if (recordingsFetchInFlight || !recordingList) return;
  757. recordingsFetchInFlight = true;
  758. try {
  759. const res = await fetch('/api/recordings');
  760. if (!res.ok) return;
  761. const data = await res.json();
  762. if (Array.isArray(data)) {
  763. recordings = data;
  764. renderLists();
  765. }
  766. } finally {
  767. recordingsFetchInFlight = false;
  768. }
  769. }
  770. function openDrawer(ev) {
  771. if (!ev) return;
  772. selectedEventId = ev.id;
  773. detailSubtitle.textContent = `Event ${ev.id}`;
  774. detailCenterEl.textContent = fmtMHz(ev.center_hz, 6);
  775. detailBwEl.textContent = fmtKHz(ev.bandwidth_hz || 0);
  776. detailStartEl.textContent = new Date(ev.start_ms).toLocaleString();
  777. detailEndEl.textContent = new Date(ev.end_ms).toLocaleString();
  778. detailSnrEl.textContent = `${(ev.snr_db || 0).toFixed(1)} dB`;
  779. detailDurEl.textContent = fmtMs(ev.duration_ms || 0);
  780. detailClassEl.textContent = ev.class?.mod_type || '-';
  781. if (recordingMetaEl) {
  782. recordingMetaEl.textContent = 'Recording: -';
  783. }
  784. if (recordingMetaLink) {
  785. recordingMetaLink.href = '#';
  786. recordingIQLink.href = '#';
  787. recordingAudioLink.href = '#';
  788. }
  789. drawerEl.classList.add('open');
  790. drawerEl.setAttribute('aria-hidden', 'false');
  791. renderDetailSpectrogram();
  792. renderLists();
  793. }
  794. function closeDrawer() {
  795. drawerEl.classList.remove('open');
  796. drawerEl.setAttribute('aria-hidden', 'true');
  797. selectedEventId = null;
  798. renderLists();
  799. }
  800. function fitView() {
  801. zoom = 1;
  802. pan = 0;
  803. followLive = true;
  804. }
  805. function tuneToFrequency(centerHz) {
  806. if (!Number.isFinite(centerHz)) return;
  807. followLive = true;
  808. centerInput.value = (centerHz / 1e6).toFixed(6);
  809. queueConfigUpdate({ center_hz: centerHz });
  810. }
  811. function connect() {
  812. clearTimeout(wsReconnectTimer);
  813. const proto = location.protocol === 'https:' ? 'wss' : 'ws';
  814. const ws = new WebSocket(`${proto}://${location.host}/ws`);
  815. setWsBadge('Connecting', 'neutral');
  816. ws.onopen = () => setWsBadge('Live', 'ok');
  817. ws.onmessage = (ev) => {
  818. latest = JSON.parse(ev.data);
  819. if (followLive) pan = 0;
  820. updateHeroMetrics();
  821. renderLists();
  822. };
  823. ws.onclose = () => {
  824. setWsBadge('Retrying', 'bad');
  825. wsReconnectTimer = setTimeout(connect, 1000);
  826. };
  827. ws.onerror = () => ws.close();
  828. }
  829. function renderLoop() {
  830. renderFrames += 1;
  831. const now = performance.now();
  832. if (now - lastFpsTs >= 1000) {
  833. renderFps = (renderFrames * 1000) / (now - lastFpsTs);
  834. renderFrames = 0;
  835. lastFpsTs = now;
  836. }
  837. if (latest) {
  838. renderBandNavigator();
  839. renderSpectrum();
  840. renderWaterfall();
  841. renderOccupancy();
  842. renderTimeline();
  843. if (drawerEl.classList.contains('open')) renderDetailSpectrogram();
  844. }
  845. updateHeroMetrics();
  846. requestAnimationFrame(renderLoop);
  847. }
  848. function handleSpectrumClick(ev) {
  849. const rect = spectrumCanvas.getBoundingClientRect();
  850. const x = (ev.clientX - rect.left) * (spectrumCanvas.width / rect.width);
  851. const y = (ev.clientY - rect.top) * (spectrumCanvas.height / rect.height);
  852. for (let i = liveSignalRects.length - 1; i >= 0; i--) {
  853. const r = liveSignalRects[i];
  854. if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
  855. tuneToFrequency(r.signal.center_hz);
  856. return;
  857. }
  858. }
  859. if (!latest) return;
  860. const span = latest.sample_rate / zoom;
  861. const startHz = latest.center_hz - span / 2 + pan * span;
  862. const clickedHz = startHz + (x / spectrumCanvas.width) * span;
  863. tuneToFrequency(clickedHz);
  864. }
  865. function handleNavPosition(ev) {
  866. if (!latest) return;
  867. const rect = navCanvas.getBoundingClientRect();
  868. const x = Math.max(0, Math.min(rect.width, ev.clientX - rect.left));
  869. const norm = x / rect.width;
  870. const fullStart = latest.center_hz - latest.sample_rate / 2;
  871. const newViewCenter = fullStart + norm * latest.sample_rate;
  872. const span = latest.sample_rate / zoom;
  873. const desiredPan = (newViewCenter - latest.center_hz) / span;
  874. pan = Math.max(-0.5, Math.min(0.5, desiredPan));
  875. followLive = false;
  876. }
  877. function exportSelectedEvent() {
  878. const ev = eventsById.get(selectedEventId);
  879. if (!ev) return;
  880. const blob = new Blob([JSON.stringify(ev, null, 2)], { type: 'application/json' });
  881. const a = document.createElement('a');
  882. a.href = URL.createObjectURL(blob);
  883. a.download = `event-${ev.id}.json`;
  884. a.click();
  885. URL.revokeObjectURL(a.href);
  886. }
  887. spectrumCanvas.addEventListener('wheel', (ev) => {
  888. ev.preventDefault();
  889. const direction = Math.sign(ev.deltaY);
  890. zoom = Math.max(0.25, Math.min(24, zoom * (direction > 0 ? 1.12 : 0.89)));
  891. followLive = false;
  892. });
  893. spectrumCanvas.addEventListener('mousedown', (ev) => {
  894. isDraggingSpectrum = true;
  895. dragStartX = ev.clientX;
  896. dragStartPan = pan;
  897. });
  898. window.addEventListener('mouseup', () => {
  899. isDraggingSpectrum = false;
  900. navDrag = false;
  901. });
  902. window.addEventListener('mousemove', (ev) => {
  903. if (isDraggingSpectrum) {
  904. const dx = ev.clientX - dragStartX;
  905. pan = Math.max(-0.5, Math.min(0.5, dragStartPan - dx / spectrumCanvas.clientWidth));
  906. followLive = false;
  907. }
  908. if (navDrag) handleNavPosition(ev);
  909. });
  910. spectrumCanvas.addEventListener('dblclick', fitView);
  911. spectrumCanvas.addEventListener('click', handleSpectrumClick);
  912. navCanvas.addEventListener('mousedown', (ev) => {
  913. navDrag = true;
  914. handleNavPosition(ev);
  915. });
  916. navCanvas.addEventListener('click', handleNavPosition);
  917. centerInput.addEventListener('change', () => {
  918. const mhz = parseFloat(centerInput.value);
  919. if (Number.isFinite(mhz)) tuneToFrequency(fromMHz(mhz));
  920. });
  921. spanInput.addEventListener('change', () => {
  922. const mhz = parseFloat(spanInput.value);
  923. if (!Number.isFinite(mhz) || mhz <= 0) return;
  924. const baseRate = currentConfig?.sample_rate || latest?.sample_rate;
  925. if (!baseRate) return;
  926. zoom = Math.max(0.25, Math.min(24, baseRate / fromMHz(mhz)));
  927. followLive = false;
  928. });
  929. sampleRateSelect.addEventListener('change', () => {
  930. const mhz = parseFloat(sampleRateSelect.value);
  931. if (Number.isFinite(mhz)) queueConfigUpdate({ sample_rate: Math.round(fromMHz(mhz)) });
  932. });
  933. bwSelect.addEventListener('change', () => {
  934. const bw = parseInt(bwSelect.value, 10);
  935. if (Number.isFinite(bw)) queueConfigUpdate({ tuner_bw_khz: bw });
  936. });
  937. fftSelect.addEventListener('change', () => {
  938. const size = parseInt(fftSelect.value, 10);
  939. if (Number.isFinite(size)) queueConfigUpdate({ fft_size: size });
  940. });
  941. gainRange.addEventListener('input', () => {
  942. gainInput.value = gainRange.value;
  943. const uiVal = parseFloat(gainRange.value);
  944. if (Number.isFinite(uiVal)) queueConfigUpdate({ gain_db: Math.max(0, Math.min(GAIN_MAX, GAIN_MAX - uiVal)) });
  945. });
  946. gainInput.addEventListener('change', () => {
  947. const uiVal = parseFloat(gainInput.value);
  948. if (Number.isFinite(uiVal)) {
  949. gainRange.value = uiVal;
  950. queueConfigUpdate({ gain_db: Math.max(0, Math.min(GAIN_MAX, GAIN_MAX - uiVal)) });
  951. }
  952. });
  953. thresholdRange.addEventListener('input', () => {
  954. thresholdInput.value = thresholdRange.value;
  955. queueConfigUpdate({ detector: { threshold_db: parseFloat(thresholdRange.value) } });
  956. });
  957. thresholdInput.addEventListener('change', () => {
  958. const v = parseFloat(thresholdInput.value);
  959. if (Number.isFinite(v)) {
  960. thresholdRange.value = v;
  961. queueConfigUpdate({ detector: { threshold_db: v } });
  962. }
  963. });
  964. agcToggle.addEventListener('change', () => queueSettingsUpdate({ agc: agcToggle.checked }));
  965. dcToggle.addEventListener('change', () => queueSettingsUpdate({ dc_block: dcToggle.checked }));
  966. iqToggle.addEventListener('change', () => queueSettingsUpdate({ iq_balance: iqToggle.checked }));
  967. gpuToggle.addEventListener('change', () => queueConfigUpdate({ use_gpu_fft: gpuToggle.checked }));
  968. avgSelect.addEventListener('change', () => {
  969. avgAlpha = parseFloat(avgSelect.value) || 0;
  970. avgSpectrum = null;
  971. });
  972. maxHoldToggle.addEventListener('change', () => {
  973. maxHold = maxHoldToggle.checked;
  974. if (!maxHold) maxSpectrum = null;
  975. });
  976. resetMaxBtn.addEventListener('click', () => { maxSpectrum = null; });
  977. followBtn.addEventListener('click', () => { followLive = true; pan = 0; });
  978. fitBtn.addEventListener('click', fitView);
  979. timelineFollowBtn.addEventListener('click', () => { timelineFrozen = false; });
  980. timelineFreezeBtn.addEventListener('click', () => {
  981. timelineFrozen = !timelineFrozen;
  982. timelineFreezeBtn.textContent = timelineFrozen ? 'Frozen' : 'Freeze';
  983. });
  984. presetButtons.forEach((btn) => {
  985. btn.addEventListener('click', () => {
  986. const mhz = parseFloat(btn.dataset.center);
  987. if (Number.isFinite(mhz)) tuneToFrequency(fromMHz(mhz));
  988. });
  989. });
  990. railTabs.forEach((tab) => {
  991. tab.addEventListener('click', () => {
  992. railTabs.forEach(t => t.classList.toggle('active', t === tab));
  993. tabPanels.forEach(panel => panel.classList.toggle('active', panel.dataset.panel === tab.dataset.tab));
  994. });
  995. });
  996. modeButtons.forEach((btn) => {
  997. btn.addEventListener('click', () => {
  998. modeButtons.forEach(b => b.classList.toggle('active', b === btn));
  999. document.body.classList.remove('mode-live', 'mode-hunt', 'mode-review', 'mode-lab');
  1000. document.body.classList.add(`mode-${btn.dataset.mode}`);
  1001. });
  1002. });
  1003. document.body.classList.add('mode-live');
  1004. drawerCloseBtn.addEventListener('click', closeDrawer);
  1005. exportEventBtn.addEventListener('click', exportSelectedEvent);
  1006. if (liveListenEventBtn) {
  1007. liveListenEventBtn.addEventListener('click', () => {
  1008. const ev = eventsById.get(selectedEventId);
  1009. if (!ev) return;
  1010. const freq = ev.center_hz;
  1011. const bw = ev.bandwidth_hz || 12000;
  1012. const mode = (listenModeSelect?.value || ev.class?.mod_type || 'NFM');
  1013. const sec = parseInt(listenSecondsInput?.value || '2', 10);
  1014. const url = `/api/demod?freq=${freq}&bw=${bw}&mode=${mode}&sec=${sec}`;
  1015. const audio = new Audio(url);
  1016. audio.play();
  1017. });
  1018. }
  1019. if (decodeEventBtn) {
  1020. decodeEventBtn.addEventListener('click', async () => {
  1021. const ev = eventsById.get(selectedEventId);
  1022. if (!ev) return;
  1023. if (!recordingMetaEl) return;
  1024. const rec = recordings.find(r => r.event_id === ev.id) || recordings.find(r => r.center_hz === ev.center_hz);
  1025. if (!rec) {
  1026. decodeResultEl.textContent = 'Decode: no recording';
  1027. return;
  1028. }
  1029. const mode = decodeModeSelect?.value || ev.class?.mod_type || 'FT8';
  1030. const res = await fetch(`/api/recordings/${rec.id}/decode?mode=${mode}`);
  1031. if (!res.ok) {
  1032. decodeResultEl.textContent = 'Decode: failed';
  1033. return;
  1034. }
  1035. const data = await res.json();
  1036. decodeResultEl.textContent = `Decode: ${String(data.stdout || '').slice(0, 80)}`;
  1037. });
  1038. }
  1039. jumpToEventBtn.addEventListener('click', () => {
  1040. const ev = eventsById.get(selectedEventId);
  1041. if (!ev) return;
  1042. tuneToFrequency(ev.center_hz);
  1043. });
  1044. timelineCanvas.addEventListener('click', (ev) => {
  1045. const rect = timelineCanvas.getBoundingClientRect();
  1046. const x = (ev.clientX - rect.left) * (timelineCanvas.width / rect.width);
  1047. const y = (ev.clientY - rect.top) * (timelineCanvas.height / rect.height);
  1048. for (let i = timelineRects.length - 1; i >= 0; i--) {
  1049. const r = timelineRects[i];
  1050. if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
  1051. openDrawer(eventsById.get(r.id));
  1052. return;
  1053. }
  1054. }
  1055. });
  1056. signalList.addEventListener('click', (ev) => {
  1057. const target = ev.target.closest('.signal-item');
  1058. if (!target) return;
  1059. const center = parseFloat(target.dataset.center);
  1060. if (Number.isFinite(center)) tuneToFrequency(center);
  1061. });
  1062. if (liveListenBtn) {
  1063. liveListenBtn.addEventListener('click', async () => {
  1064. const first = signalList.querySelector('.signal-item');
  1065. if (!first) return;
  1066. const freq = parseFloat(first.dataset.center);
  1067. const bw = parseFloat(first.dataset.bw || '12000');
  1068. const mode = first.dataset.class || 'NFM';
  1069. const url = `/api/demod?freq=${freq}&bw=${bw}&mode=${mode}&sec=2`;
  1070. const audio = new Audio(url);
  1071. audio.play();
  1072. });
  1073. }
  1074. eventList.addEventListener('click', (ev) => {
  1075. const target = ev.target.closest('.event-item');
  1076. if (!target) return;
  1077. const id = target.dataset.eventId;
  1078. openDrawer(eventsById.get(id));
  1079. });
  1080. if (recordingList) {
  1081. recordingList.addEventListener('click', async (ev) => {
  1082. const target = ev.target.closest('.recording-item');
  1083. if (!target) return;
  1084. const id = target.dataset.id;
  1085. const audio = new Audio(`/api/recordings/${id}/audio`);
  1086. audio.play();
  1087. if (recordingMetaEl) recordingMetaEl.textContent = `Recording: ${id}`;
  1088. if (recordingMetaLink) {
  1089. recordingMetaLink.href = `/api/recordings/${id}`;
  1090. recordingIQLink.href = `/api/recordings/${id}/iq`;
  1091. recordingAudioLink.href = `/api/recordings/${id}/audio`;
  1092. }
  1093. });
  1094. }
  1095. window.addEventListener('keydown', (ev) => {
  1096. if (ev.target && ['INPUT', 'SELECT', 'TEXTAREA'].includes(ev.target.tagName)) return;
  1097. if (ev.key === ' ') {
  1098. ev.preventDefault();
  1099. followLive = true;
  1100. pan = 0;
  1101. } else if (ev.key.toLowerCase() === 'f') {
  1102. fitView();
  1103. } else if (ev.key.toLowerCase() === 'm') {
  1104. maxHold = !maxHold;
  1105. maxHoldToggle.checked = maxHold;
  1106. if (!maxHold) maxSpectrum = null;
  1107. } else if (ev.key.toLowerCase() === 'g') {
  1108. gpuToggle.checked = !gpuToggle.checked;
  1109. queueConfigUpdate({ use_gpu_fft: gpuToggle.checked });
  1110. } else if (ev.key === '[') {
  1111. zoom = Math.max(0.25, zoom * 0.88);
  1112. } else if (ev.key === ']') {
  1113. zoom = Math.min(24, zoom * 1.12);
  1114. } else if (ev.key === 'ArrowLeft') {
  1115. pan = Math.max(-0.5, pan - 0.04);
  1116. followLive = false;
  1117. } else if (ev.key === 'ArrowRight') {
  1118. pan = Math.min(0.5, pan + 0.04);
  1119. followLive = false;
  1120. }
  1121. });
  1122. loadConfig();
  1123. loadStats();
  1124. loadGPU();
  1125. fetchEvents(true);
  1126. fetchRecordings();
  1127. connect();
  1128. requestAnimationFrame(renderLoop);
  1129. setInterval(loadStats, 1000);
  1130. setInterval(loadGPU, 1000);
  1131. setInterval(() => fetchEvents(false), 2000);
  1132. setInterval(fetchRecordings, 5000);