選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

1330 行
44KB

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