Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1257 Zeilen
40KB

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