code-smore 0.1.34

A morse code practice tool
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
#![allow(unused_imports)]
use crate::prelude::*;
use anyhow;
use anyhow::Context;
#[cfg(feature = "audio")]
use rodio::{OutputStream, Sink, Source};
#[cfg(feature = "gpio")]
use rppal;
#[cfg(feature = "audio")]
use serialport::SerialPort;
use std::collections::HashMap;
use std::sync::Arc;
#[allow(unused_imports)]
use std::thread::{self, sleep};
use std::time::Duration;

/// Custom audio source for generating tones
#[allow(dead_code)]
struct Tone {
    freq: f32,        // Frequency of the tone in Hz
    duration: u32,    // Duration of the tone in milliseconds
    sample_rate: u32, // Sample rate in Hz
    current_sample: u32,
}

impl Iterator for Tone {
    type Item = f32;

    fn next(&mut self) -> Option<Self::Item> {
        let total_samples = self.sample_rate * self.duration / 1000;
        if self.current_sample >= total_samples {
            return None; // End of the tone
        }

        // Generate a sine wave
        let t = self.current_sample as f32 / self.sample_rate as f32;
        let sample = (2.0 * std::f32::consts::PI * self.freq * t).sin();

        // Apply envelope (attack and release)
        let amplitude = if self.current_sample < (0.001 * self.sample_rate as f32) as u32 {
            // Attack phase
            self.current_sample as f32 / (0.001 * self.sample_rate as f32)
        } else if self.current_sample > total_samples - (0.001 * self.sample_rate as f32) as u32 {
            // Release phase
            (total_samples - self.current_sample) as f32 / (0.001 * self.sample_rate as f32)
        } else {
            // Sustain phase
            1.0
        };

        self.current_sample += 1;
        Some(sample * amplitude)
    }
}

#[cfg(feature = "audio")]
impl Source for Tone {
    fn current_frame_len(&self) -> Option<usize> {
        None
    }

    fn channels(&self) -> u16 {
        1 // Mono
    }

    fn sample_rate(&self) -> u32 {
        self.sample_rate
    }

    fn total_duration(&self) -> Option<Duration> {
        Some(Duration::from_millis(self.duration.into()))
    }
}

/// Converts words per minute (WPM) into a dot length in milliseconds
/// Based on standard Morse code timing where "PARIS" defines one word.
pub fn wpm_to_dot_length(wpm: u32) -> u32 {
    1200 / wpm
}

fn get_morse_maps() -> (HashMap<char, String>, HashMap<String, char>) {
    let forward_map = vec![
        ('A', ".-".to_string()),
        ('B', "-...".to_string()),
        ('C', "-.-.".to_string()),
        ('D', "-..".to_string()),
        ('E', ".".to_string()),
        ('F', "..-.".to_string()),
        ('G', "--.".to_string()),
        ('H', "....".to_string()),
        ('I', "..".to_string()),
        ('J', ".---".to_string()),
        ('K', "-.-".to_string()),
        ('L', ".-..".to_string()),
        ('M', "--".to_string()),
        ('N', "-.".to_string()),
        ('O', "---".to_string()),
        ('P', ".--.".to_string()),
        ('Q', "--.-".to_string()),
        ('R', ".-.".to_string()),
        ('S', "...".to_string()),
        ('T', "-".to_string()),
        ('U', "..-".to_string()),
        ('V', "...-".to_string()),
        ('W', ".--".to_string()),
        ('X', "-..-".to_string()),
        ('Y', "-.--".to_string()),
        ('Z', "--..".to_string()),
        ('1', ".----".to_string()),
        ('2', "..---".to_string()),
        ('3', "...--".to_string()),
        ('4', "....-".to_string()),
        ('5', ".....".to_string()),
        ('6', "-....".to_string()),
        ('7', "--...".to_string()),
        ('8', "---..".to_string()),
        ('9', "----.".to_string()),
        ('0', "-----".to_string()),
        ('.', ".-.-.-".to_string()),
        (',', "--..--".to_string()),
        ('?', "..--..".to_string()),
        ('!', "-.-.--".to_string()),
        ('-', "-....-".to_string()),
        ('/', "-..-.".to_string()),
        ('@', ".--.-.".to_string()),
        ('(', "-.--.".to_string()),
        (')', "-.--.-".to_string()),
    ];

    let mut forward_hashmap = HashMap::new();
    let mut reverse_hashmap = HashMap::new();

    for (ch, code) in forward_map {
        forward_hashmap.insert(ch, code.clone());
        reverse_hashmap.insert(code, ch);
    }
    (forward_hashmap, reverse_hashmap)
}

pub fn code_to_text(code: &str) -> String {
    let morse_map = get_morse_maps().1;
    regex::Regex::new(r"\s{3,}") // Match three or more spaces
        .unwrap()
        .replace_all(code, " / ")
        .split(" / ") // Split by word gaps
        .map(|word| {
            word.split_whitespace() // Split by character gaps
                .filter_map(|morse| morse_map.get(morse)) // Lookup each Morse code
                .collect::<String>() // Collect decoded characters into a string (word)
        })
        .collect::<Vec<String>>() // Collect words into a vector
        .join(" ") // Join words with spaces
}

pub fn text_to_morse(text: &str) -> String {
    text.split_whitespace()
        .map(|word| {
            word.chars()
                .filter_map(|ch| {
                    get_morse_maps().0.iter().find_map(|(c, m)| {
                        if *c == ch.to_ascii_uppercase() {
                            Some(m.clone())
                        } else {
                            None
                        }
                    })
                })
                .collect::<Vec<String>>()
                .join(" ")
        })
        .collect::<Vec<String>>()
        .join(" / ") // word gap
}

#[allow(dead_code)]
fn encode_morse(text: &str, dot_duration: u32, tone_freq: f32) -> Vec<(f32, u32)> {
    let morse_code = text_to_morse(text);
    let morse_code = regex::Regex::new(r"\s{3,}") // Match three or more spaces
        .unwrap()
        .replace_all(&morse_code, "/")
        .to_string();
    let morse_code = regex::Regex::new(r"\s{2}") // Match exactly two spaces
        .unwrap()
        .replace_all(&morse_code, " ")
        .to_string();

    morse_to_tones(&morse_code, dot_duration, tone_freq)
}

#[allow(dead_code)]
fn morse_to_tones(morse_code: &str, dot_duration: u32, tone_freq: f32) -> Vec<(f32, u32)> {
    let dash_duration = dot_duration * 3; // Duration of a dash
    let char_gap_duration = dot_duration * 3; // Gap between characters
    let word_gap_duration = dot_duration * 7; // Gap between words

    let mut tones = Vec::new();

    for symbol in morse_code.chars() {
        match symbol {
            '.' => tones.push((tone_freq, dot_duration)),
            '-' => tones.push((tone_freq, dash_duration)),
            ' ' => tones.push((0.0, char_gap_duration)),
            '/' => tones.push((0.0, word_gap_duration)),
            _ => {}
        }
        tones.push((0.0, dot_duration)); // Gap between dots/dashes
    }

    tones
}

/// RAII guard that asserts RTS on construction and de-asserts on drop.
#[cfg(feature = "audio")]
struct RtsGuard {
    port: Box<dyn SerialPort>,
}

#[cfg(feature = "audio")]
impl RtsGuard {
    pub fn new(port_name: &str) -> anyhow::Result<Self> {
        let mut port = serialport::new(port_name, 9_600)
            .timeout(Duration::from_millis(100))
            .open()
            .with_context(|| format!("opening serial port `{}`", port_name))?;
        port.write_request_to_send(true).context("asserting RTS")?;
        debug!("RTS ON");
        Ok(RtsGuard { port })
    }
}

#[cfg(feature = "audio")]
impl Drop for RtsGuard {
    fn drop(&mut self) {
        // best-effort deassert
        let _ = self.port.write_request_to_send(false);
        debug!("RTS OFF");
    }
}

/// Play a sequence of (frequency, duration_ms) via the given Sink.
/// If `rts_port` is `Some("/dev/ttyUSB0")` it will raise RTS for the
/// entire duration of the playback, then lower it at the end.
#[cfg(feature = "audio")]
pub fn play_morse_code(
    tones: Vec<(f32, u32)>,
    sink: &Sink,
    rts_port: Option<&str>,
) -> anyhow::Result<()> {
    // If requested, open the port and assert RTS.
    // The guard lives until end of this function (i.e. until after playback).
    let _rts = match rts_port {
        Some(port_name) => Some(RtsGuard::new(port_name)?),
        None => None,
    };

    let sample_rate = 44_100;
    for (freq, duration) in tones {
        sink.append(Tone {
            freq,
            duration,
            sample_rate,
            current_sample: 0,
        });
    }

    // block current thread until playback finishes
    sink.sleep_until_end();

    // _rts goes out of scope here, dropping RtsGuard and de-asserting RTS
    Ok(())
}

#[cfg(feature = "gpio")]
fn gpio_morse_code(tones: Vec<(f32, u32)>, pin_number: u8) {
    let mut pin = rppal::gpio::Gpio::new()
        .expect("Failed to access GPIO")
        .get(pin_number)
        .expect("Failed to get GPIO pin")
        .into_output();
    for (frequency, duration) in tones {
        if frequency == 0. || duration == 0 {
            //info!("gap: d: {duration}");
            pin.set_low();
        } else {
            //info!("f: {frequency} d: {duration}");
            pin.set_high();
        }
        sleep(Duration::from_millis(duration.into()));
    }
    pin.set_low();
}

pub struct MorsePlayer {
    #[cfg(feature = "audio")]
    #[allow(dead_code)]
    stream: Arc<OutputStream>, // Keep the stream alive

    #[cfg(feature = "audio")]
    stream_handle: Arc<rodio::OutputStreamHandle>, // Shareable stream handle
}

impl MorsePlayer {
    pub fn new() -> Self {
        #[cfg(feature = "audio")]
        {
            // Set up the audio output once
            let stream = OutputStream::try_default().unwrap();
            let stream_handle = Arc::new(stream.1);

            return Self {
                #[allow(clippy::arc_with_non_send_sync)]
                stream: Arc::new(stream.0),
                stream_handle,
            };
        }

        #[cfg(not(feature = "audio"))]
        {
            Self {}
        }
    }

    #[cfg(feature = "audio")]
    pub fn play_gap(&self, dot_duration: u32, rts_port: Option<&str>) {
        let tones = vec![(0.0, dot_duration)];
        let sink = Sink::try_new(&self.stream_handle).unwrap();
        let _ = play_morse_code(tones, &sink, rts_port);
        sink.sleep_until_end();
    }

    #[cfg(not(feature = "audio"))]
    pub fn play_gap(&self, _dot_duration: u32, rts_port: Option<&str>) {
        error!("'audio' feature is disabled in this Cargo build. Program cannot play audio.");
    }

    #[cfg(feature = "audio")]
    pub fn play_nonblocking_tone(&self, dot_duration: u32, tone_freq: f32, rts_port: Option<&str>) {
        // clone the port name into an owned String so it can live in the 'static thread
        let owned_rts: Option<String> = rts_port.map(|s| s.to_string());
        let stream_handle = self.stream_handle.clone();

        std::thread::spawn(move || {
            let tones = vec![(tone_freq, dot_duration)];
            let sink = Sink::try_new(&stream_handle).unwrap();

            // pass a `&str` into play_morse_code by calling `.as_deref()` on the owned String
            play_morse_code(tones, &sink, owned_rts.as_deref()).unwrap();
            sink.sleep_until_end();
        });
    }

    #[cfg(not(feature = "audio"))]
    pub fn play_nonblocking_tone(
        &self,
        _dot_duration: u32,
        _tone_freq: f32,
        rts_port: Option<&str>,
    ) {
        error!("Error: Audio feature is disabled. Cannot play non-blocking tone.");
    }

    #[cfg(feature = "audio")]
    pub fn play_morse(
        &self,
        message: &str,
        dot_duration: u32,
        tone_freq: f32,
        rts_port: Option<&str>,
    ) {
        let sink = Sink::try_new(&self.stream_handle).unwrap();
        let tones = morse_to_tones(message, dot_duration, tone_freq);
        let _ = play_morse_code(tones, &sink, rts_port);
        sink.sleep_until_end();
    }

    #[cfg(feature = "audio")]
    pub fn play(&self, message: &str, dot_duration: u32, tone_freq: f32, rts_port: Option<&str>) {
        let sink = Sink::try_new(&self.stream_handle).unwrap();
        let tones = encode_morse(message, dot_duration, tone_freq);
        let _ = play_morse_code(tones, &sink, rts_port);
        sink.sleep_until_end();
    }

    #[cfg(not(feature = "audio"))]
    pub fn play(
        &self,
        _message: &str,
        _dot_duration: u32,
        _tone_freq: f32,
        rts_port: Option<&str>,
    ) {
        error!("Error: Audio feature is disabled. Cannot play Morse code.");
    }

    #[cfg(not(feature = "audio"))]
    pub fn play_morse(
        &self,
        _message: &str,
        _dot_duration: u32,
        _tone_freq: f32,
        rts_port: Option<&str>,
    ) {
        error!("Error: Audio feature is disabled. Cannot play Morse code.");
    }

    #[cfg(feature = "gpio")]
    pub fn gpio_morse(&self, message: &str, dot_duration: u32, pin_number: u8) {
        let tones = morse_to_tones(message, dot_duration, 333.); //frequncy is unused but must be >0
        gpio_morse_code(tones, pin_number);
    }

    #[cfg(feature = "gpio")]
    pub fn gpio(&self, message: &str, dot_duration: u32, pin_number: u8) {
        let tones = encode_morse(message, dot_duration, 333.); //frequency is unused but must be >0
        gpio_morse_code(tones, pin_number);
    }

    #[cfg(not(feature = "gpio"))]
    pub fn gpio_morse(&self, _message: &str, _dot_duration: u32, _gpio_pin: u8) {
        error!("Error: GPIO feature is disabled. Cannot play Morse code via GPIO.");
    }

    #[cfg(not(feature = "gpio"))]
    pub fn gpio(&self, _message: &str, _dot_duration: u32, _gpio_pin: u8) {
        error!("Error: GPIO feature is disabled. Cannot perform GPIO operations.");
    }

    #[cfg(feature = "gpio")]
    pub fn gpio_gap(&self, dot_duration: u32, pin_number: u8) {
        let mut pin = rppal::gpio::Gpio::new()
            .expect("Failed to access GPIO")
            .get(pin_number)
            .expect("Failed to get GPIO pin")
            .into_output();
        pin.set_low();
        sleep(Duration::from_millis(dot_duration.into()));
    }

    #[cfg(not(feature = "gpio"))]
    pub fn gpio_gap(&self, _dot_duration: u32, _gpio_pin: u8) {
        error!("Error: GPIO feature is disabled. Cannot perform GPIO gap.");
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_text_to_morse() {
        assert_eq!(text_to_morse("SOS"), "... --- ...");
        assert_eq!(
            text_to_morse("Hello   World 123. How are you?"),
            ".... . .-.. .-.. --- / .-- --- .-. .-.. -.. / .---- ..--- ...-- .-.-.- / .... --- .-- / .- .-. . / -.-- --- ..- ..--.."
        );
    }
}