-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMorseDecoder.html
More file actions
480 lines (440 loc) · 14.8 KB
/
Copy pathMorseDecoder.html
File metadata and controls
480 lines (440 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Morse Code Decoder (650–900 Hz, 50 wpm Max)</title>
<style>
body {
font-family: sans-serif;
margin: 20px;
}
#decodedOutput {
width: 100%;
box-sizing: border-box;
height: 150px;
border: 1px solid #ccc;
padding: 10px;
font-size: 1.2em;
margin-top: 10px;
white-space: pre-wrap;
/* Enable vertical scrolling: */
overflow-y: auto;
}
/* Tone indicator bar graph */
#indicator {
width: 100px;
height: 20px;
border: 1px solid #ccc;
background-color: #eee;
display: inline-block;
margin-left: 10px;
}
#indicatorFill {
height: 100%;
background-color: green;
width: 0;
}
#spectrum {
vertical-align: bottom;
}
/* Media query for smaller devices */
@media (max-width: 600px) {
body {
margin: 10px;
}
h1 {
font-size: 1.5em;
}
#decodedOutput {
font-size: 1em;
}
#indicator {
width: 80px;
height: 16px;
}
}
</style>
</head>
<body>
<h1>Morse Code Decoder (650–900 Hz, 12 - 50 wpm)</h1>
<button id="startButton">Start</button>
<button id="stopButton" disabled>Stop</button>
<button id="resetButton" disabled>Reset</button>
<button id="CleartextButton">Clear Text</button>
<span style="margin-left:20px;">Input Tone Indicator:
<div id="indicator">
<div id="indicatorFill"></div>
</div>
</span>
<div id="decodedOutput"></div>
<br />
Center the signal between the white lines.
<div><canvas id="spectrum" width="512" height="50"></canvas></div>
<div><canvas id="waterfall" width="512" height="150"></canvas></div>
<script>
"use strict"
// Global variables and constants.
let audioContext, microphoneStream, scriptProcessor, analyser;
let isRunning = false;
const BUFFER_SIZE = 512;
// Frequency scanning range.
const FREQ_MIN = 650;
const FREQ_MAX = 900;
const FREQ_STEP = 10;
const FFTSIZE = 2048;
// Hysteresis thresholds.
const THRESHOLD_ON = 10; // must exceed this to register tone-on
const THRESHOLD_OFF = 8; // tone remains active until mag < this
let lastStateChangeTime = performance.now();
let currentToneState = false; // false: silence, true: tone present
let letterBuffer = "";
let decodedText = "";
let dotDuration = 90; // initial dot duration (ms)
const MIN_DOT_DURATION = 35; // ~ 35 wpm
let animationFrameId;
let lastLetters = []; // FIFO buffer for last 6 letters
// Expanded Morse code dictionary.
const MORSE_CODE = {
".-": "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",
".-.-.-": ".", "--..--": ",", "..--..": "?", ".----.": "'",
"-.-.--": "!", "-..-.": "/", "-.--.": "(", "-.--.-": ")",
".-...": "&", "---...": ":", "-.-.-.": ";", "-...-": "=",
".-.-.": "+", "-....-": "-", "..--.-": "_", ".-..-.": "\"",
"...-..-": "$", ".--.-.": "@", "-----.": "Ö"
};
// Define a 4-bit (16 values) RGB modified rainbow colormap from blue to red
// to use for the waterfall display. A few additional colormap entries are
// also included.
let alpha = 0xFF
let colormap = [
[0x30, 0x12, 0x3b, alpha], [0x41, 0x43, 0xa7, alpha],
[0x47, 0x71, 0xe9, alpha], [0x3e, 0x9b, 0xfe, alpha],
[0x22, 0xc5, 0xe2, alpha], [0x1a, 0xe4, 0xb6, alpha],
[0x46, 0xf8, 0x84, alpha], [0x88, 0xff, 0x4e, alpha],
[0xb9, 0xf6, 0x35, alpha], [0xe1, 0xdd, 0x37, alpha],
[0xfa, 0xba, 0x39, alpha], [0xfd, 0x8d, 0x27, alpha],
[0xf0, 0x5b, 0x12, alpha], [0xd6, 0x35, 0x06, alpha],
[0xaf, 0x18, 0x01, alpha], [0x7a, 0x04, 0x03, alpha],
// special values
[0x00, 0x00, 0x00, alpha], // 16 black
[0xFF, 0xFF, 0xFF, alpha], // 17 white
[0xD0, 0xD0, 0xD0, alpha], // 18 light gray
];
// TODO: Adjust plotxscale based on width?
let plotxscale = 6;
let plotyscale = 1;
let output = document.getElementById("decodedOutput");
let wfWidth = 512;
let wfHeight = 150;
const wfCanvas = document.getElementById("waterfall");
const wfCtx = wfCanvas.getContext("2d");
wfCtx.fillStyle = "#000000";
wfCtx.fillRect(0, 0, wfWidth, wfHeight);
let spWidth = 512;
let spHeight = 50;
const spCanvas = document.getElementById("spectrum");
const spCtx = spCanvas.getContext("2d");
spCtx.fillStyle = "#000000";
spCtx.fillRect(0, 0, spWidth, spHeight);
const drawSpectrum = (values, lowIndex, highIndex) => {
spCtx.fillStyle = "#000";
spCtx.fillRect(0, 0, plotxscale * spWidth, plotyscale * spHeight);
spCtx.beginPath();
spCtx.moveTo(0, plotyscale * spHeight);
for(var i=0; i<values.length; i++) {
spCtx.lineTo(
plotxscale * i,
plotyscale * (spHeight - values[i]*(spHeight/256)));
}
spCtx.lineTo(plotxscale * spWidth, plotyscale * spHeight);
spCtx.moveTo(0, plotyscale * spHeight); // close for fill
spCtx.fillStyle = "#CCC";
spCtx.strokeStyle = "#CCC";
spCtx.fill();
// draw target frequency markers
spCtx.beginPath();
spCtx.moveTo(plotxscale * lowIndex, 0);
spCtx.lineTo(plotxscale * lowIndex, plotyscale * spHeight)
spCtx.moveTo(plotxscale * highIndex, 0);
spCtx.lineTo(plotxscale * highIndex, plotyscale * spHeight)
spCtx.strokeStyle = "#FFF";
spCtx.stroke();
spCtx.beginPath();
let centerIndex = Math.round(plotxscale * (lowIndex + highIndex) / 2);
spCtx.moveTo(centerIndex, 0);
spCtx.lineTo(centerIndex, plotyscale * spHeight)
spCtx.strokeStyle = "#000";
spCtx.stroke();
};
const addWaterfallLine = (values, lowIndex, highIndex) => {
// shift the existing image down by plotyscale pixels
wfCtx.drawImage(
wfCtx.canvas,
0,
0,
plotxscale * wfWidth,
plotyscale * wfHeight,
0,
plotyscale,
plotxscale * wfWidth,
plotyscale * wfHeight);
// expand values (uint8) to colormap values (RGBA per pixel)
let colorValues = new Uint8ClampedArray(
plotxscale * (values.length) * 4); // filled with 0
for(var i=0; i<values.length; i++) {
for (var k=0; k<plotxscale; k++) {
for (var j=0; j<4; j++) { // r, g, b
colorValues[
((plotxscale*i + k) * 4) + j
] = colormap[values[i]>>4][j]; // RGBA
}
}
}
let centercolor = 16; // black
let edgecolor = 17; // white
let centerIndex = Math.round(plotxscale * (lowIndex + highIndex) / 2);
for (var j=0; j<4; j++) { // r, g, b
colorValues[plotxscale * lowIndex*4 + j] = colormap[edgecolor][j];
colorValues[centerIndex * 4 + j] = colormap[centercolor][j];
colorValues[plotxscale * highIndex*4 + j] = colormap[edgecolor][j];
}
let imageData = new ImageData(
colorValues, plotxscale * values.length, 1);
for (k=0; k<plotyscale; k++) {
wfCtx.putImageData(imageData, 0, k);
}
};
// ======================================================
// Partial Reset (without clearing decodedText)
// ======================================================
function partialReset() {
console.log("Partial reset triggered (many E/T).");
// Just reset internal timing/state – do NOT clear decodedText
letterBuffer = "";
dotDuration = 100;
currentToneState = false;
lastStateChangeTime = performance.now();
}
// ======================================================
// Handle a freshly decoded letter
// ======================================================
function handleDecodedLetter(letter) {
// Trim in case there's stray whitespace
letter = letter.trim();
// Append to the visible text
decodedText += letter;
output.innerText = decodedText;
// If it's not a space, track it in 'lastLetters'
if (letter !== "") {
// Exclude actual "space" char from partial reset detection
if (letter !== " ") {
lastLetters.push(letter);
if (lastLetters.length > MAX_LAST_LETTERS) {
lastLetters.shift();
}
// If we have exactly 6 non-space letters, check if all E/T
if (lastLetters.length === MAX_LAST_LETTERS) {
const allET = lastLetters.every(ch => ch === "E" || ch === "T");
if (allET) {
partialReset();
}
}
}
}
}
// Decodes a Morse string (e.g. ".-") to its corresponding character.
function decodeMorse(code) {
return MORSE_CODE[code] || "?";
}
// Goertzel algorithm implementation.
function goertzel(samples, sampleRate, targetFreq) {
const numSamples = samples.length;
const k = Math.round(0.5 + ((numSamples * targetFreq) / sampleRate));
const omega = (2.0 * Math.PI * k) / numSamples;
const cosine = Math.cos(omega);
const coeff = 2.0 * cosine;
let q0 = 0, q1 = 0, q2 = 0;
for (let i = 0; i < numSamples; i++) {
q0 = coeff * q1 - q2 + samples[i];
q2 = q1;
q1 = q0;
}
return Math.sqrt(q1 * q1 + q2 * q2 - q1 * q2 * coeff);
}
// Audio processing: detect tone presence, decode Morse.
function processAudio(event) {
const inputBuffer = event.inputBuffer;
const samples = inputBuffer.getChannelData(0);
// Scan candidate frequencies.
let bestMagnitude = 0;
let bestFrequency = 700; // default
for (let f = FREQ_MIN; f <= FREQ_MAX; f += FREQ_STEP) {
const mag = goertzel(samples, audioContext.sampleRate, f);
if (mag > bestMagnitude) {
bestMagnitude = mag;
bestFrequency = f;
}
}
const magnitude = bestMagnitude;
// Hysteresis threshold:
const toneDetected = currentToneState ? (magnitude > THRESHOLD_OFF) : (magnitude > THRESHOLD_ON);
// Update tone indicator bar graph
let fillWidth = 0;
if (magnitude > THRESHOLD_ON) {
fillWidth = Math.min(100, (magnitude - THRESHOLD_ON) * 5);
}
document.getElementById("indicatorFill").style.width = fillWidth + "px";
// On/off transitions for Morse decoding
if (toneDetected !== currentToneState) {
const now = performance.now();
const duration = now - lastStateChangeTime;
lastStateChangeTime = now;
if (currentToneState) {
// Tone ended => dot or dash
if (duration < 1.5 * dotDuration) {
letterBuffer += ".";
dotDuration = Math.max(
MIN_DOT_DURATION,
0.9 * dotDuration + 0.1 * duration
);
} else {
letterBuffer += "-";
// console.log("Detected dash, duration " + duration.toFixed(2));
}
} else {
// Silence ended => letter gap or word gap
if (duration >= 1.5 * dotDuration && duration < 3.5 * dotDuration) {
const letter = decodeMorse(letterBuffer);
decodedText += letter;
letterBuffer = "";
output.innerText = decodedText;
// scroll to show new output
output.scrollTop = output.scrollHeight;
} else if (duration >= 3.5 * dotDuration) {
if (letterBuffer.length > 0) {
const letter = decodeMorse(letterBuffer);
decodedText += letter;
letterBuffer = "";
}
decodedText += " ";
output.innerText = decodedText;
// scroll to show new output
output.scrollTop = output.scrollHeight;
}
}
currentToneState = toneDetected;
}
}
// Resets the decoder's internal parameters
function resetParameters() {
lastStateChangeTime = performance.now();
currentToneState = false;
letterBuffer = "";
decodedText = "";
dotDuration = 100;
document.getElementById("decodedOutput").innerText = "";
console.log("Decoder parameters have been reset.");
}
// Clear text only
function Cleartext() {
decodedText = "";
output.innerText = "";
}
// Update the frequency plots
function updatePlots() {
if (!analyser) {
animationFrameId = requestAnimationFrame(updateFreqGraph);
return;
}
const freqData = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(freqData);
let startIndex = Math.floor(FREQ_MIN / (audioContext.sampleRate / FFTSIZE));
let endIndex = Math.ceil(FREQ_MAX / (audioContext.sampleRate / FFTSIZE));
drawSpectrum(freqData, startIndex, endIndex);
addWaterfallLine(freqData, startIndex, endIndex);
animationFrameId = requestAnimationFrame(updatePlots);
}
// Start decoding
function startMorseDecoder() {
if (isRunning) return;
isRunning = true;
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
microphoneStream = audioContext.createMediaStreamSource(stream);
// Analyser for plots
analyser = audioContext.createAnalyser();
analyser.fftSize = FFTSIZE;
microphoneStream.connect(analyser);
// ScriptProcessor for decoding
scriptProcessor = audioContext.createScriptProcessor(BUFFER_SIZE, 1, 1);
scriptProcessor.onaudioprocess = processAudio;
microphoneStream.connect(scriptProcessor);
scriptProcessor.connect(audioContext.destination);
document.getElementById("startButton").disabled = true;
document.getElementById("stopButton").disabled = false;
document.getElementById("resetButton").disabled = false;
// Reset variables
lastStateChangeTime = performance.now();
currentToneState = false;
letterBuffer = "";
decodedText = "";
dotDuration = 100;
output.innerText = "";
// Begin updating the frequency plots
updatePlots();
})
.catch(err => {
console.error("Error accessing microphone: ", err);
});
}
// Stop decoding
function stopMorseDecoder() {
if (!isRunning) return;
isRunning = false;
if (scriptProcessor) {
scriptProcessor.disconnect();
scriptProcessor.onaudioprocess = null;
}
if (microphoneStream) {
microphoneStream.disconnect();
}
if (analyser) {
analyser.disconnect();
}
if (audioContext) {
audioContext.close();
}
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
console.log("Morse decoder stopped.");
document.getElementById("startButton").disabled = false;
document.getElementById("stopButton").disabled = true;
document.getElementById("resetButton").disabled = true;
}
// Resize canvases for responsiveness
function resizeCanvases() {
// Set the canvas width to 90% of the body's width.
wfWidth = Math.round(document.body.clientWidth * 0.9);
wfCanvas.width = wfWidth;
spWidth = wfWidth;
spCanvas.width = wfWidth;
}
window.addEventListener('resize', resizeCanvases);
resizeCanvases(); // initial
document.getElementById("startButton").addEventListener("click", startMorseDecoder);
document.getElementById("stopButton").addEventListener("click", stopMorseDecoder);
document.getElementById("resetButton").addEventListener("click", partialReset);
document.getElementById("CleartextButton").addEventListener("click", Cleartext);
</script>
</body>
</html>