// DME Simulation: Modular, Physics-respecting, Fully Documented // (c) for user: Physicist/Software Developer //------------------- Utility -------------------------// const log = (side, msg) => { const el = document.getElementById(side + '-log'); const li = document.createElement('li'); li.className = 'list-group-item py-1'; li.textContent = `[${(performance.now()/1000).toFixed(3)}s] ${msg}`; if(el.children.length > 200) el.removeChild(el.children[0]); el.appendChild(li); el.scrollTop = el.scrollHeight; }; const setIndicator = (id, isActive) => document.getElementById(id).classList.toggle('active', isActive); //-----------------------------------------------------// //------------------- Pulse Class --------------------// class Pulse { /** * @param {Object} params * @param {number} params.frequency - Pulse frequency in Hz * @param {number} params.spacingMs - Spacing between pulses in ms * @param {number} params.morseUnitMs - Morse timing unit in ms */ constructor({ frequency, spacingMs, morseUnitMs }) { this.frequency = frequency; this.spacingMs = spacingMs; this.morseUnitMs = morseUnitMs; this.defaultDurationMs = 15; // Default pulse duration this.gainValue = 0.4; } // Envelope shaping function (Hann window) shapeEnvelope(ctx, gain, start, duration) { gain.gain.setValueAtTime(0, start); gain.gain.linearRampToValueAtTime(this.gainValue, start + duration / 2); gain.gain.linearRampToValueAtTime(0, start + duration); } // Create a single shaped pulse createPulse(ctx, startTime, durationMs, indicatorCb) { const osc = ctx.createOscillator(); const gain = ctx.createGain(); osc.frequency.value = this.frequency; osc.type = 'sine'; osc.connect(gain).connect(ctx.destination); this.shapeEnvelope(ctx, gain, startTime, durationMs / 1000); osc.start(startTime); osc.stop(startTime + durationMs / 1000); if (indicatorCb) osc.onended = () => indicatorCb(false); indicatorCb && indicatorCb(true); return osc; } // Concatenate pulses with specific spacing playConcatenated(ctx, count, durationMs, spacingMs, indicatorCb) { const now = ctx.currentTime; for (let i = 0; i < count; i++) { this.createPulse(ctx, now + (i * spacingMs) / 1000, durationMs, indicatorCb); } } // Double pulse method playDoublePulse(ctx, durationMs = this.defaultDurationMs, spacingMs = this.spacingMs, indicatorCb) { this.playConcatenated(ctx, 2, durationMs, spacingMs, indicatorCb); } // Morse code to ident pulses playIdent(ctx, morseString, indicatorCb) { // Morse: dot = 1 unit, dash = 3 units, intra-char space = 1 unit, inter-char = 3 units const now = ctx.currentTime; let timeOffset = 0; for (let i = 0; i < morseString.length; i++) { const char = morseString[i]; if (char === '.') { this.createPulse(ctx, now + timeOffset / 1000, this.morseUnitMs, indicatorCb); timeOffset += this.morseUnitMs + this.morseUnitMs; // dot + intra-char space } else if (char === '-') { this.createPulse(ctx, now + timeOffset / 1000, 3 * this.morseUnitMs, indicatorCb); timeOffset += 3 * this.morseUnitMs + this.morseUnitMs; // dash + intra-char space } else if (char === ' ') { timeOffset += 2 * this.morseUnitMs; // inter-char space (total 3 units) } } } } //-----------------------------------------------------// //------------------- Aircraft Class ------------------// class Aircraft { constructor() { this.ctx = null; this.active = false; this.pulseFreq = 1500; this.pulseSpacing = 12; this.interrogatePeriod = 3000; this.listenTime = 800; this.lastInterrogate = 0; this.periodicTimer = null; this.sending = false; this.listening = false; } setConfig({ freq, spacing, period, listen, duration }) { this.pulseFreq = freq; this.pulseSpacing = spacing; this.interrogatePeriod = period; this.listenTime = listen; this.pulseDuration = duration; } on() { if(this.active) return; this.active = true; log('aircraft', "Aircraft system ON"); this.periodic(); } off() { this.active = false; clearTimeout(this.periodicTimer); this.periodicTimer = null; this.sending = false; this.listening = false; log('aircraft', "Aircraft system OFF"); } // Periodic interrogation: send double pulse periodic() { if(!this.active) return; const now = performance.now(); if(now - this.lastInterrogate > this.interrogatePeriod) { this.lastInterrogate = now; if (!this.ctx) this.ctx = new (window.AudioContext || window.webkitAudioContext)(); // Always use current parameters this.pulse = new Pulse({ frequency: this.pulseFreq, spacingMs: this.pulseSpacing, morseUnitMs: this.listenTime // Use listenTime as morseUnitMs for demo }); const duration = this.pulseDuration || 15; this.sending = true; log('aircraft', `Sent double pulse. Freq: ${this.pulseFreq} Hz, Spacing: ${this.pulseSpacing} ms, Duration: ${duration} ms`); this.pulse.playDoublePulse(this.ctx, duration, this.pulseSpacing, a => setIndicator('aircraft-pulse', a)); // Start listening immediately when sending this.startListeningForReplyOrIdent(); setTimeout(() => { this.sending = false; }, 2 * duration + this.pulseSpacing); } // Keep periodic this.periodicTimer = setTimeout(() => this.periodic(), 80); } // Start listening for reply or ident and keep listening until system is OFF startListeningForReplyOrIdent() { // Get receiver parameters from UI const threshold = +document.getElementById('ac-rx-threshold').value; const spacingAccuracy = +document.getElementById('ac-rx-spacing-accuracy').value; const fixedDelay = +document.getElementById('ac-fixed-delay').value; const speedSound = +document.getElementById('ac-speed-sound').value; // Stop previous receiver if any if (this.receiver && this.receiver.listening) this.receiver.stop(); // Start listening this.receiver = new Receiver({ frequency: +document.getElementById('ac-rx-frequency').value, spacing: this.pulseSpacing, duration: this.pulseDuration || 15, threshold, spacingAccuracy, onDoublePulse: (time, spacing) => { // Calculate DME time (ms) const dmeTime = Math.max(0, spacing - fixedDelay); if (document.getElementById('ac-display-dme-time')) { document.getElementById('ac-display-dme-time').textContent = dmeTime.toFixed(1); } // Calculate distance in cm: distance = (dmeTime / 1000) * speedSound * 100 const distanceCm = ((dmeTime / 1000) * speedSound * 100).toFixed(1); if (document.getElementById('ac-display-dme-distance')) { document.getElementById('ac-display-dme-distance').textContent = distanceCm; } log('aircraft', `Reply detected! DME time: ${dmeTime.toFixed(1)} ms, Distance: ${distanceCm} cm`); setIndicator('aircraft-pulse', true); setTimeout(() => setIndicator('aircraft-pulse', false), 200); }, onIdent: (morse, ident) => { document.getElementById('ac-display-ident').textContent = ident || '(unreadable)'; log('aircraft', `IDENT received: Morse="${morse}" Decoded="${ident}"`); } }); this.listening = true; this.receiver.start(); log('aircraft', 'Listening for reply/ident...'); } // Stop listening (called when system is turned off) stopListening() { if (this.receiver && this.receiver.listening) { this.receiver.stop(); this.listening = false; log('aircraft', 'Stopped listening.'); } } } //-----------------------------------------------------// //------------------- Groundstation Class -------------// class Groundstation { constructor() { this.ctx = null; this.active = false; this.pulseFreq = 1500; this.pulseSpacing = 12; this.replyDelay = 100; this.identInterval = 30; // sec this.lastIdent = 0; this.listening = false; this.sendingReply = false; this.identTimer = null; } setConfig({ freq, spacing, reply, ident, duration }) { this.pulseFreq = freq; this.pulseSpacing = spacing; this.replyDelay = reply; this.identInterval = ident; this.pulseDuration = duration; } on() { if(this.active) return; this.active = true; log('ground', "Groundstation ON"); this.sendIdent(); // Immediately send ident on ON this.listenLoop(); this.scheduleIdent(); } off() { this.active = false; this.listening = false; this.sendingReply = false; clearTimeout(this.identTimer); log('ground', "Groundstation OFF"); } // Ident broadcast every identInterval, unless replying scheduleIdent() { if(!this.active) return; const now = performance.now(); const sinceLastIdent = (now - this.lastIdent) / 1000; let wait = Math.max(this.identInterval - sinceLastIdent, 0.1); this.identTimer = setTimeout(() => { this.lastIdent = performance.now(); if(this.active && !this.sendingReply) { this.sendIdent(); } this.scheduleIdent(); }, wait * 1000); } // Morse code dictionary static morseDict = { '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': '----.' }; // Translate IDENT string to Morse code identToMorse(identStr) { return identStr.toUpperCase().split('').map(ch => Groundstation.morseDict[ch] || '').join(' '); } sendIdent() { if (!this.active) return; if (!this.ctx) this.ctx = new (window.AudioContext || window.webkitAudioContext)(); // Get IDENT string from UI const identStr = document.getElementById('gs-ident-str')?.value || ''; const morse = this.identToMorse(identStr); // Display Morse in UI const morseEl = document.getElementById('gs-morse'); if (morseEl) morseEl.textContent = morse; log('ground', `Broadcasting IDENT: ${identStr} (${morse}) Freq: ${this.pulseFreq} Hz, Spacing: ${this.pulseSpacing} ms, MorseUnit: ${this.identInterval} ms`); // Always use current parameters this.pulse = new Pulse({ frequency: this.pulseFreq, spacingMs: this.pulseSpacing, morseUnitMs: this.identInterval // Use identInterval as morseUnitMs for demo }); const duration = this.pulseDuration || 15; // Play ident with adjustable duration this.pulse.playConcatenated = function(ctx, count, durationMs, spacingMs, indicatorCb) { const now = ctx.currentTime; for (let i = 0; i < count; i++) { this.createPulse(ctx, now + (i * spacingMs) / 1000, durationMs, indicatorCb); } }; // Override playIdent to use duration this.pulse.playIdentWithDuration = (ctx, morseString, durationMs, indicatorCb) => { const now = ctx.currentTime; let timeOffset = 0; for (let i = 0; i < morseString.length; i++) { const char = morseString[i]; if (char === '.') { this.pulse.createPulse(ctx, now + timeOffset / 1000, durationMs, indicatorCb); timeOffset += durationMs + durationMs; } else if (char === '-') { this.pulse.createPulse(ctx, now + timeOffset / 1000, 3 * durationMs, indicatorCb); timeOffset += 3 * durationMs + durationMs; } else if (char === ' ') { timeOffset += 2 * durationMs; } } }; this.pulse.playIdentWithDuration(this.ctx, morse, duration, a => setIndicator('ground-pulse', a)); } // Ground listens all the time unless sending reply/ident listenLoop() { // Listen for interrogations (double pulse) between idents if (this.receiver && this.receiver.listening) this.receiver.stop(); this.receiver = new Receiver({ frequency: +document.getElementById('gs-rx-frequency').value, spacing: this.pulseSpacing, duration: this.pulseDuration || 15, threshold: +document.getElementById('gs-rx-threshold').value, spacingAccuracy: +document.getElementById('gs-rx-spacing-accuracy').value, onDoublePulse: (time, spacing) => { log('ground', `Interrogation detected! Will reply after ${this.replyDelay} ms.`); this.sendingReply = true; setTimeout(() => { this.sendReply(); this.sendingReply = false; }, this.replyDelay - performance.now() + time); }, onIdent: null // Groundstation does not decode ident }); this.listening = true; this.receiver.start(); log('ground', 'Listening for interrogations...'); } // Reply after delay sendReply() { if (!this.active) return; if (!this.ctx) this.ctx = new (window.AudioContext || window.webkitAudioContext)(); // Use current parameters this.pulse = new Pulse({ frequency: this.pulseFreq, spacingMs: this.pulseSpacing, morseUnitMs: this.identInterval // Not used for reply }); const duration = this.pulseDuration || 15; log('ground', `Replying with double pulse. Freq: ${this.pulseFreq} Hz, Spacing: ${this.pulseSpacing} ms, Duration: ${duration} ms`); this.pulse.playDoublePulse(this.ctx, duration, this.pulseSpacing, a => setIndicator('ground-pulse', a)); } } //-----------------------------------------------------// //------------- DME Listen/Detection Engine -----------// //------------------- Receiver Class -------------------// class Receiver { /** * @param {Object} params * @param {number} params.frequency - Expected pulse frequency (Hz) * @param {number} params.spacing - Expected spacing between pulses (ms) * @param {number} params.duration - Expected pulse duration (ms) * @param {number} params.threshold - Detection threshold * @param {number} params.spacingAccuracy - Allowed deviation for spacing (ms) * @param {function} params.onDoublePulse - Callback for double pulse: (time, spacing) => void * @param {function} params.onIdent - Callback for ident: (morseString, decodedIdent) => void */ constructor({ frequency, spacing, duration, threshold, spacingAccuracy, onDoublePulse, onIdent }) { this.frequency = frequency; this.spacing = spacing; this.duration = duration; this.threshold = threshold; this.spacingAccuracy = spacingAccuracy || 6; this.onDoublePulse = onDoublePulse; this.onIdent = onIdent; this.stream = null; this.ctx = null; this.listening = false; this.pulseTimes = []; this.morseBuffer = []; this.lastPulse = 0; this.identCandidates = []; } start() { if (this.listening) return; navigator.mediaDevices.getUserMedia({ audio: true }) .then(stream => { this.stream = stream; this.ctx = new (window.AudioContext || window.webkitAudioContext)(); const source = this.ctx.createMediaStreamSource(stream); const analyser = this.ctx.createAnalyser(); analyser.fftSize = 256; const data = new Float32Array(analyser.fftSize); source.connect(analyser); this.listening = true; this.pulseTimes = []; this.morseBuffer = []; this.lastPulse = 0; this.identCandidates = []; let identActive = false; let identWindowStart = 0; const MIN_PULSE_SEPARATION = 12; // ms, increased for robustness const MAX_DOUBLE_SPACING = this.spacing + this.spacingAccuracy; const MIN_DOUBLE_SPACING = Math.max(3, this.spacing - this.spacingAccuracy); const MAX_IDENT_WINDOW = 2000; // ms, covers longer Morse idents const MIN_IDENT_PULSES = 10; // minimum pulses for a valid ident, increased const listenLoop = () => { if (!this.listening) return; analyser.getFloatTimeDomainData(data); let energy = 0; for (let i = 0; i < data.length; ++i) energy += Math.abs(data[i]); energy /= data.length; const now = performance.now(); if (energy > this.threshold && (now - this.lastPulse > MIN_PULSE_SEPARATION)) { this.lastPulse = now; this.pulseTimes.push(now); if (this.pulseTimes.length > 20) this.pulseTimes.shift(); // Double pulse detection (reply window) if (this.pulseTimes.length >= 2) { const dt = this.pulseTimes[this.pulseTimes.length - 1] - this.pulseTimes[this.pulseTimes.length - 2]; if (dt >= MIN_DOUBLE_SPACING && dt <= MAX_DOUBLE_SPACING) { // Abort ident detection if reply found identActive = false; this.morseBuffer = []; if (this.onDoublePulse) { this.onDoublePulse(now, dt); } return; // Don't process ident in this window } } // Ident detection (larger window) if (!identActive) { identActive = true; identWindowStart = now; this.morseBuffer = [now]; } else { // Only keep pulses within the ident window this.morseBuffer = this.morseBuffer.filter(t => t >= identWindowStart); this.morseBuffer.push(now); // If window is too old, reset if (now - identWindowStart > MAX_IDENT_WINDOW) { identActive = false; this.morseBuffer = []; } // Try to decode ident if enough pulses if (this.morseBuffer.length >= MIN_IDENT_PULSES) { const intervals = []; for (let i = 1; i < this.morseBuffer.length; i++) { intervals.push(this.morseBuffer[i] - this.morseBuffer[i - 1]); } // Only decode if intervals show Morse-like variation let morse = ''; for (let intv of intervals) { if (intv < 2 * this.duration) morse += '.'; else if (intv < 4 * this.duration) morse += '-'; else morse += ' '; } // Require at least one dash or space for valid ident if (morse.includes('-') || morse.includes(' ')) { const decoded = this.decodeMorse(morse); if (this.onIdent) { this.onIdent(morse, decoded); } identActive = false; this.morseBuffer = []; } } } } setTimeout(listenLoop, 5); }; listenLoop(); }) .catch(e => { log('aircraft', 'Receiver error: ' + e); }); } stop() { this.listening = false; if (this.stream) { this.stream.getTracks().forEach(t => t.stop()); this.stream = null; } if (this.ctx) { this.ctx.close(); this.ctx = null; } } // Very basic Morse decoder (for demo) decodeMorse(morse) { // Morse code dictionary const dict = Groundstation.morseDict; // Reverse lookup let result = ''; let chars = morse.split(' '); for (let code of chars) { for (let k in dict) { if (dict[k] === code) { result += k; break; } } } return result; } } //-----------------------------------------------------// //----------------- UI Handling -----------------------// const aircraft = new Aircraft(); const ground = new Groundstation(); document.getElementById('aircraft-on').onclick = () => aircraft.on(); document.getElementById('aircraft-off').onclick = () => { aircraft.off(); aircraft.stopListening(); }; document.getElementById('ground-on').onclick = () => ground.on(); document.getElementById('ground-off').onclick = () => ground.off(); // Config controls document.getElementById('aircraft-config').onchange = e => { aircraft.setConfig({ freq: +document.getElementById('ac-freq').value, spacing: +document.getElementById('ac-spacing').value, period: +document.getElementById('ac-period').value, listen: +document.getElementById('ac-listen').value, duration: +document.getElementById('ac-duration').value, }); }; document.getElementById('ground-config').onchange = e => { ground.setConfig({ freq: +document.getElementById('gs-freq').value, spacing: +document.getElementById('gs-spacing').value, reply: +document.getElementById('gs-reply').value, ident: +document.getElementById('gs-ident').value, duration: +document.getElementById('gs-duration').value, }); }; // Clear indicators if not pulsing setInterval(() => { if (!aircraft.sending && !aircraft.listening) setIndicator('aircraft-pulse', false); if (!ground.sendingReply && !ground.listening) setIndicator('ground-pulse', false); }, 200); //--------------------- End --------------------------//