parrot-repeater/data/app.js

472 lines
21 KiB
JavaScript

// ESP32 Parrot Repeater - Frontend Controller
let audioCtx = null;
let currentConfig = {};
let dtmfBuffer = "";
// DTMF Frequencies (Hz)
const DTMF_FREQS = {
'1': [697, 1209], '2': [697, 1336], '3': [697, 1477], 'A': [697, 1633],
'4': [770, 1209], '5': [770, 1336], '6': [770, 1477], 'B': [770, 1633],
'7': [852, 1209], '8': [852, 1336], '9': [852, 1477], 'C': [852, 1633],
'*': [941, 1209], '0': [941, 1336], '#': [941, 1477], 'D': [941, 1633]
};
// Morse Code Dictionary
const MORSE_MAP = {
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..',
'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.',
'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-',
'Y': '-.--', 'Z': '--..', '0': '-----', '1': '.----', '2': '..---',
'3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...',
'8': '---..', '9': '----.', '/': '-..-.', '?': '..--..'
};
function getAudioContext() {
if (!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
if (audioCtx.state === 'suspended') {
audioCtx.resume();
}
return audioCtx;
}
// Show Toast Notification
function showToast(msg) {
const toast = document.getElementById('toast');
toast.innerText = msg;
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), 3500);
}
// Initialize Tabs
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
btn.classList.add('active');
const tabId = btn.getAttribute('data-tab');
const panel = document.getElementById(tabId);
if (panel) panel.classList.add('active');
});
});
// Sync Range Input Text Values
function bindRangeDisplay(rangeId, textId, suffix = '%') {
const range = document.getElementById(rangeId);
const txt = document.getElementById(textId);
if (!range || !txt) return;
range.addEventListener('input', () => {
txt.innerText = range.value + suffix;
if (rangeId === 'cfg_vox_threshold') {
updateVoxLineMarker(range.value);
}
});
}
bindRangeDisplay('cfg_vox_threshold', 'voxValText');
bindRangeDisplay('cfg_rx_gain', 'rxGainText');
bindRangeDisplay('cfg_tx_volume', 'txVolText');
function updateVoxLineMarker(val) {
const marker = document.getElementById('voxLineMarker');
if (marker) marker.style.left = `${val}%`;
}
// Callsign to Morse pattern translation
function textToMorse(text) {
return text.toUpperCase().split('').map(ch => MORSE_MAP[ch] || '').filter(s => s.length > 0).join(' ');
}
document.getElementById('cfg_callsign').addEventListener('input', (e) => {
const val = e.target.value.toUpperCase();
document.getElementById('headerCallsign').innerText = val || 'N0CALL';
document.getElementById('morseSymbolsDisplay').innerText = textToMorse(val || 'N0CALL');
});
// DTMF Web Audio Keypad Playback
function playDtmfTone(char, durationMs = 150) {
const freqs = DTMF_FREQS[char.toUpperCase()];
if (!freqs) return;
const ctx = getAudioContext();
const osc1 = ctx.createOscillator();
const osc2 = ctx.createOscillator();
const gain = ctx.createGain();
osc1.frequency.value = freqs[0];
osc2.frequency.value = freqs[1];
gain.gain.setValueAtTime(0.15, ctx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + (durationMs / 1000));
osc1.connect(gain);
osc2.connect(gain);
gain.connect(ctx.destination);
osc1.start();
osc2.start();
osc1.stop(ctx.currentTime + (durationMs / 1000));
osc2.stop(ctx.currentTime + (durationMs / 1000));
}
// Keypad Button Clicks
document.querySelectorAll('.key-btn').forEach(btn => {
btn.addEventListener('click', () => {
const key = btn.getAttribute('data-key');
playDtmfTone(key);
if (dtmfBuffer.length < 16) {
dtmfBuffer += key;
document.getElementById('dtmfDisplay').innerText = dtmfBuffer;
}
});
});
document.getElementById('btnClearDtmf').addEventListener('click', () => {
dtmfBuffer = "";
document.getElementById('dtmfDisplay').innerText = "_";
});
document.getElementById('btnSendDtmf').addEventListener('click', async () => {
if (!dtmfBuffer) {
showToast("Please enter DTMF digits on the keypad first");
return;
}
try {
const res = await fetch('/api/dtmf', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code: dtmfBuffer })
});
const data = await res.json();
showToast(data.message || "DTMF Command Dispatched");
dtmfBuffer = "";
document.getElementById('dtmfDisplay').innerText = "_";
} catch (e) {
showToast("Error sending DTMF command");
}
});
// Audio Previews in Browser using Web Audio API
document.getElementById('btnPreviewBeep').addEventListener('click', () => {
const ctx = getAudioContext();
const type = parseInt(document.getElementById('cfg_roger_beep_type').value);
const f1 = parseInt(document.getElementById('cfg_roger_freq1_hz').value) || 1200;
const f2 = parseInt(document.getElementById('cfg_roger_freq2_hz').value) || 1500;
const dur = (parseInt(document.getElementById('cfg_roger_duration_ms').value) || 120) / 1000;
if (type === 0) {
showToast("Roger Beep is set to Disabled");
return;
}
const osc = ctx.createOscillator();
const gain = ctx.createGain();
gain.gain.setValueAtTime(0.2, ctx.currentTime);
if (type === 1) { // Single tone
osc.frequency.setValueAtTime(f1, ctx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + dur);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start();
osc.stop(ctx.currentTime + dur);
} else if (type === 2) { // NASA Quindar dual tone
const osc2 = ctx.createOscillator();
osc.frequency.value = 2524;
osc2.frequency.value = 2475;
osc.connect(gain);
osc2.connect(gain);
gain.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + dur);
gain.connect(ctx.destination);
osc.start();
osc2.start();
osc.stop(ctx.currentTime + dur);
osc2.stop(ctx.currentTime + dur);
} else if (type === 3) { // Beep Boop
osc.frequency.setValueAtTime(f2, ctx.currentTime);
osc.frequency.setValueAtTime(f1, ctx.currentTime + (dur / 2));
gain.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + dur);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start();
osc.stop(ctx.currentTime + dur);
}
});
document.getElementById('btnPreviewMorse').addEventListener('click', () => {
const call = document.getElementById('cfg_callsign').value || 'N0CALL';
const wpm = parseInt(document.getElementById('cfg_cw_speed_wpm').value) || 18;
const pitch = parseInt(document.getElementById('cfg_cw_pitch_hz').value) || 750;
const dotSec = 1.2 / wpm;
const ctx = getAudioContext();
const pattern = textToMorse(call);
let time = ctx.currentTime + 0.05;
for (let char of pattern) {
if (char === '.') {
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.frequency.value = pitch;
gain.gain.setValueAtTime(0.2, time);
gain.gain.setValueAtTime(0.2, time + dotSec - 0.005);
gain.gain.linearRampToValueAtTime(0.0001, time + dotSec);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start(time);
osc.stop(time + dotSec);
time += dotSec * 2; // dot + inter-element space
} else if (char === '-') {
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.frequency.value = pitch;
gain.gain.setValueAtTime(0.2, time);
gain.gain.setValueAtTime(0.2, time + (dotSec * 3) - 0.005);
gain.gain.linearRampToValueAtTime(0.0001, time + (dotSec * 3));
osc.connect(gain);
gain.connect(ctx.destination);
osc.start(time);
osc.stop(time + (dotSec * 3));
time += dotSec * 4; // dash + inter-element space
} else if (char === ' ') {
time += dotSec * 3; // letter space
}
}
showToast(`Playing CW preview for ${call}`);
});
// Fetch Configuration from ESP32
async function loadConfig() {
try {
const res = await fetch('/api/config');
if (!res.ok) throw new Error("Config fetch failed");
currentConfig = await res.json();
// Populate fields
document.getElementById('cfg_repeater_enabled').checked = currentConfig.repeater_enabled ?? true;
document.getElementById('cfg_callsign').value = currentConfig.callsign || 'N0CALL';
document.getElementById('headerCallsign').innerText = currentConfig.callsign || 'N0CALL';
document.getElementById('morseSymbolsDisplay').innerText = textToMorse(currentConfig.callsign || 'N0CALL');
document.getElementById('cfg_max_record_sec').value = currentConfig.max_record_sec || 30;
document.getElementById('cfg_anti_kerchunk_ms').value = currentConfig.anti_kerchunk_ms || 400;
document.getElementById('cfg_squelch_tail_ms').value = currentConfig.squelch_tail_ms || 600;
document.getElementById('cfg_tx_delay_ms').value = currentConfig.tx_delay_ms || 250;
document.getElementById('cfg_tx_tail_ms').value = currentConfig.tx_tail_ms || 200;
if (currentConfig.squelch_mode === 'cos') {
document.getElementById('modeCos').checked = true;
} else {
document.getElementById('modeVox').checked = true;
}
document.getElementById('cfg_vox_threshold').value = currentConfig.vox_threshold || 45;
document.getElementById('voxValText').innerText = (currentConfig.vox_threshold || 45) + '%';
updateVoxLineMarker(currentConfig.vox_threshold || 45);
document.getElementById('cfg_vox_release_ms').value = currentConfig.vox_release_ms || 350;
document.getElementById('cfg_rx_gain').value = currentConfig.rx_gain || 80;
document.getElementById('rxGainText').innerText = (currentConfig.rx_gain || 80) + '%';
document.getElementById('cfg_tx_volume').value = currentConfig.tx_volume || 75;
document.getElementById('txVolText').innerText = (currentConfig.tx_volume || 75) + '%';
document.getElementById('cfg_tone_burst_access').checked = currentConfig.tone_burst_access || false;
document.getElementById('cfg_roger_beep_type').value = currentConfig.roger_beep_type ?? 2;
document.getElementById('cfg_roger_freq1_hz').value = currentConfig.roger_freq1_hz || 1200;
document.getElementById('cfg_roger_freq2_hz').value = currentConfig.roger_freq2_hz || 1500;
document.getElementById('cfg_roger_duration_ms').value = currentConfig.roger_duration_ms || 120;
document.getElementById('cfg_beacon_enabled').checked = currentConfig.beacon_enabled ?? true;
document.getElementById('cfg_beacon_interval_min').value = currentConfig.beacon_interval_min || 10;
document.getElementById('cfg_cw_speed_wpm').value = currentConfig.cw_speed_wpm || 18;
document.getElementById('cfg_cw_pitch_hz').value = currentConfig.cw_pitch_hz || 750;
document.getElementById('cfg_dtmf_enabled').checked = currentConfig.dtmf_enabled ?? true;
document.getElementById('cfg_dtmf_pin').value = currentConfig.dtmf_pin || '1234';
document.getElementById('cfg_wifi_ssid').value = currentConfig.wifi_ssid || '';
document.getElementById('cfg_hostname').value = currentConfig.hostname || 'parrot';
document.getElementById('cfg_use_dhcp').checked = currentConfig.use_dhcp ?? true;
document.getElementById('cfg_ap_ssid').value = currentConfig.ap_ssid || 'Parrot-Repeater-AP';
updateMuteButton(currentConfig.repeater_enabled ?? true);
} catch (e) {
console.warn("Could not load config from ESP32 (running simulated preview):", e);
}
}
// Save Settings to ESP32
async function saveSettings() {
const payload = {
repeater_enabled: document.getElementById('cfg_repeater_enabled').checked,
callsign: document.getElementById('cfg_callsign').value.trim().toUpperCase(),
max_record_sec: parseInt(document.getElementById('cfg_max_record_sec').value),
anti_kerchunk_ms: parseInt(document.getElementById('cfg_anti_kerchunk_ms').value),
squelch_tail_ms: parseInt(document.getElementById('cfg_squelch_tail_ms').value),
tx_delay_ms: parseInt(document.getElementById('cfg_tx_delay_ms').value),
tx_tail_ms: parseInt(document.getElementById('cfg_tx_tail_ms').value),
squelch_mode: document.getElementById('modeCos').checked ? 'cos' : 'vox',
vox_threshold: parseInt(document.getElementById('cfg_vox_threshold').value),
vox_release_ms: parseInt(document.getElementById('cfg_vox_release_ms').value),
rx_gain: parseInt(document.getElementById('cfg_rx_gain').value),
tx_volume: parseInt(document.getElementById('cfg_tx_volume').value),
tone_burst_access: document.getElementById('cfg_tone_burst_access').checked,
roger_beep_type: parseInt(document.getElementById('cfg_roger_beep_type').value),
roger_freq1_hz: parseInt(document.getElementById('cfg_roger_freq1_hz').value),
roger_freq2_hz: parseInt(document.getElementById('cfg_roger_freq2_hz').value),
roger_duration_ms: parseInt(document.getElementById('cfg_roger_duration_ms').value),
beacon_enabled: document.getElementById('cfg_beacon_enabled').checked,
beacon_interval_min: parseInt(document.getElementById('cfg_beacon_interval_min').value),
cw_speed_wpm: parseInt(document.getElementById('cfg_cw_speed_wpm').value),
cw_pitch_hz: parseInt(document.getElementById('cfg_cw_pitch_hz').value),
dtmf_enabled: document.getElementById('cfg_dtmf_enabled').checked,
dtmf_pin: document.getElementById('cfg_dtmf_pin').value.trim(),
wifi_ssid: document.getElementById('cfg_wifi_ssid').value.trim(),
wifi_pass: document.getElementById('cfg_wifi_pass').value,
hostname: document.getElementById('cfg_hostname').value.trim(),
use_dhcp: document.getElementById('cfg_use_dhcp').checked,
ap_ssid: document.getElementById('cfg_ap_ssid').value.trim(),
ap_pass: document.getElementById('cfg_ap_pass').value
};
try {
const res = await fetch('/api/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
const data = await res.json();
showToast(data.message || "Settings Saved Successfully!");
currentConfig = payload;
updateMuteButton(payload.repeater_enabled);
} catch (e) {
showToast("Error saving configuration to ESP32");
}
}
function updateMuteButton(enabled) {
const btn = document.getElementById('quickMuteBtn');
const txt = document.getElementById('quickMuteText');
if (enabled) {
btn.classList.remove('btn-danger-outline');
btn.classList.add('btn-icon');
txt.innerText = "Mute";
} else {
btn.classList.remove('btn-icon');
btn.classList.add('btn-danger-outline');
txt.innerText = "Unmute (Muted)";
}
}
// Trigger Backend Actions
async function triggerAction(actionName) {
try {
const res = await fetch(`/api/action?cmd=${actionName}`, { method: 'POST' });
const data = await res.json();
showToast(data.message || `Action ${actionName} executed`);
if (actionName === 'toggle_mute') {
currentConfig.repeater_enabled = !currentConfig.repeater_enabled;
document.getElementById('cfg_repeater_enabled').checked = currentConfig.repeater_enabled;
updateMuteButton(currentConfig.repeater_enabled);
}
} catch (e) {
showToast(`Failed to execute ${actionName}`);
}
}
document.getElementById('quickMuteBtn').addEventListener('click', () => triggerAction('toggle_mute'));
document.getElementById('btnSimulateRx').addEventListener('click', () => triggerAction('sim_rx'));
document.getElementById('btnTestRoger').addEventListener('click', () => triggerAction('test_beep'));
document.getElementById('btnTestCW').addEventListener('click', () => triggerAction('test_cw'));
document.getElementById('btnClearBuffer').addEventListener('click', () => triggerAction('clear_buffer'));
document.getElementById('btnRestartESP').addEventListener('click', () => {
if (confirm("Are you sure you want to reboot the ESP32?")) triggerAction('reboot');
});
document.getElementById('btnResetDefaults').addEventListener('click', () => {
if (confirm("Reset ALL settings to factory defaults?")) triggerAction('reset_defaults');
});
// Format Seconds into HH:MM:SS
function formatUptime(seconds) {
const h = Math.floor(seconds / 3600).toString().padStart(2, '0');
const m = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
const s = (seconds % 60).toString().padStart(2, '0');
return `${h}:${m}:${s}`;
}
// Live Status Polling
async function pollStatus() {
try {
const res = await fetch('/api/status');
if (!res.ok) throw new Error("Status failed");
const s = await res.json();
// Update State Pill
const pill = document.getElementById('masterStatePill');
const stateTxt = document.getElementById('masterStateText');
pill.className = 'status-pill';
if (s.state_name === 'RECEIVING' || s.state_name === 'RECORDING') {
pill.classList.add('rx');
stateTxt.innerText = `RX / RECORDING (${(s.rec_sec || 0).toFixed(1)}s)`;
} else if (s.state_name === 'TRANSMITTING') {
pill.classList.add('tx');
stateTxt.innerText = `TX / REPLAYING (${(s.rec_sec || 0).toFixed(1)}s)`;
} else if (s.state_name === 'PLAYING_BEACON') {
pill.classList.add('beacon');
stateTxt.innerText = "TRANSMITTING CW ID";
} else {
pill.classList.add('idle');
stateTxt.innerText = s.repeater_enabled ? "STANDBY / IDLE" : "MUTED / STANDBY";
}
// Indicators
document.getElementById('indicatorSquelch').classList.toggle('active', !!s.squelch_open);
document.getElementById('indicatorPTT').classList.toggle('active', !!s.ptt_active);
document.getElementById('indicatorBeacon').classList.toggle('active', s.state_name === 'PLAYING_BEACON');
// Audio VU Meter
const audioLvl = Math.min(100, Math.max(0, s.audio_level || 0));
document.getElementById('audioVuBar').style.width = `${audioLvl}%`;
document.getElementById('audioLevelText').innerText = `${Math.round(audioLvl)}%`;
// Buffer Bar
const maxSec = s.max_sec || 30;
const curSec = s.rec_sec || 0;
const pct = Math.min(100, (curSec / maxSec) * 100);
document.getElementById('bufferProgressBar').style.width = `${pct}%`;
document.getElementById('bufferTimeText').innerText = `${curSec.toFixed(1)}s / ${maxSec}.0s (${Math.round(pct)}%)`;
// Telemetry Stats
document.getElementById('statUptime').innerText = formatUptime(s.uptime || 0);
document.getElementById('statReplays').innerText = s.total_replays || 0;
document.getElementById('statTxCount').innerText = s.total_tx || 0;
document.getElementById('statRssi').innerText = s.wifi_rssi ? `${s.wifi_rssi} dBm` : 'N/A';
document.getElementById('statIP').innerText = s.ip || '192.168.4.1';
document.getElementById('statHeap').innerText = `${Math.round((s.free_heap || 0) / 1024)} KB`;
document.getElementById('telemetryConn').innerText = "ONLINE";
// DTMF History Table
if (s.dtmf_history && s.dtmf_history.length > 0) {
const tbody = document.getElementById('dtmfHistoryTable');
tbody.innerHTML = s.dtmf_history.map(item => `
<tr>
<td>${item.time_ago}s ago</td>
<td class="font-mono text-primary font-bold">${item.code}</td>
<td>${item.desc}</td>
<td><span class="badge ${item.auth ? 'badge-tech' : 'badge-danger'}">${item.auth ? 'ACCEPTED' : 'IGNORED'}</span></td>
</tr>
`).join('');
}
} catch (e) {
document.getElementById('telemetryConn').innerText = "CONNECTING...";
}
}
// Initial Bootstrap
window.addEventListener('DOMContentLoaded', () => {
loadConfig();
setInterval(pollStatus, 750);
});