msrt 0.1.5

Portable MSRT protocol implementation.
Documentation
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
use std::{
    env, io,
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

mod support;

use msrt::{
    core::ErrorKind,
    endpoint::{ClientEndpoint, EndpointPoll, PeerState},
    engine::EngineConfig,
};

use support::noise::{
    NoiseConfig, NoiseLcg, NoiseStats, has_noise, mutate_or_copy, parse_percent_per_mille,
};

const TX_BUF_BYTES: usize = 256;
const RX_BUF_BYTES: usize = 256;
const DEFAULT_BAUD: u32 = 115_200;
const DEFAULT_INTERVAL_MS: u64 = 1_000;
const DEFAULT_MESSAGE: &[u8] = b"ping";
const REOPEN_INTERVAL: Duration = Duration::from_millis(500);
const STATS_INTERVAL: Duration = Duration::from_secs(60);
const TEST_FRAGMENT_BYTES: usize = 48;

#[derive(Clone, Debug)]
struct Args {
    port: String,
    baud: u32,
    interval: Duration,
    message: Vec<u8>,
    noise: NoiseConfig,
    verbose: bool,
}

#[derive(Debug)]
struct FrontendStats {
    received_messages: usize,
    backpressure: usize,
    noise_state: NoiseLcg,
    noise_stats: NoiseStats,
    last_stats: Instant,
}

impl FrontendStats {
    fn new() -> Self {
        Self {
            received_messages: 0,
            backpressure: 0,
            noise_state: NoiseLcg::with_seed(0x53455231),
            noise_stats: NoiseStats::default(),
            last_stats: Instant::now(),
        }
    }
}

impl Args {
    fn parse() -> Result<Self, String> {
        let mut args = env::args().skip(1);
        let mut parsed = Self {
            port: String::new(),
            baud: DEFAULT_BAUD,
            interval: Duration::from_millis(DEFAULT_INTERVAL_MS),
            message: DEFAULT_MESSAGE.to_vec(),
            noise: NoiseConfig::default(),
            verbose: false,
        };

        while let Some(arg) = args.next() {
            match arg.as_str() {
                "--port" => parsed.port = next_value(&mut args, "--port")?,
                "--baud" => {
                    parsed.baud = next_value(&mut args, "--baud")?
                        .parse()
                        .map_err(|error| format!("invalid --baud: {error}"))?;
                }
                "--interval-ms" => {
                    let millis = next_value(&mut args, "--interval-ms")?
                        .parse()
                        .map_err(|error| format!("invalid --interval-ms: {error}"))?;
                    parsed.interval = Duration::from_millis(millis);
                }
                "--message" => parsed.message = next_value(&mut args, "--message")?.into_bytes(),
                "--noise-percent" => {
                    let total = parse_percent_per_mille(
                        next_value(&mut args, "--noise-percent")?,
                        "--noise-percent",
                    )?;
                    set_mixed_noise(&mut parsed.noise, total);
                }
                "--drop-byte-percent" => {
                    parsed.noise.drop_byte_per_mille = parse_percent_per_mille(
                        next_value(&mut args, "--drop-byte-percent")?,
                        "--drop-byte-percent",
                    )?;
                }
                "--insert-byte-percent" => {
                    parsed.noise.insert_byte_per_mille = parse_percent_per_mille(
                        next_value(&mut args, "--insert-byte-percent")?,
                        "--insert-byte-percent",
                    )?;
                }
                "--burst-corrupt-percent" => {
                    parsed.noise.burst_corrupt_per_mille = parse_percent_per_mille(
                        next_value(&mut args, "--burst-corrupt-percent")?,
                        "--burst-corrupt-percent",
                    )?;
                }
                "--burst-drop-percent" => {
                    parsed.noise.burst_drop_per_mille = parse_percent_per_mille(
                        next_value(&mut args, "--burst-drop-percent")?,
                        "--burst-drop-percent",
                    )?;
                }
                "--packet-drop-percent" => {
                    parsed.noise.packet_drop_per_mille = parse_percent_per_mille(
                        next_value(&mut args, "--packet-drop-percent")?,
                        "--packet-drop-percent",
                    )?;
                }
                "--verbose" => parsed.verbose = true,
                "--help" | "-h" => return Err(usage()),
                other => return Err(format!("unknown argument: {other}\n\n{}", usage())),
            }
        }

        if parsed.port.is_empty() {
            return Err(format!("--port is required\n\n{}", usage()));
        }

        Ok(parsed)
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args = match Args::parse() {
        Ok(args) => args,
        Err(message) => {
            eprintln!("{message}");
            std::process::exit(2);
        }
    };

    println!(
        "msrt serial frontend port={} baud={} interval={}ms message_len={} noise={} corrupt={} drop_byte={} insert_byte={} burst_corrupt={} burst_drop={} packet_drop={} verbose={}",
        args.port,
        args.baud,
        args.interval.as_millis(),
        args.message.len(),
        percent_text(noise_total(args.noise)),
        percent_text(args.noise.corrupt_per_mille),
        percent_text(args.noise.drop_byte_per_mille),
        percent_text(args.noise.insert_byte_per_mille),
        percent_text(args.noise.burst_corrupt_per_mille),
        percent_text(args.noise.burst_drop_per_mille),
        percent_text(args.noise.packet_drop_per_mille),
        args.verbose
    );

    let start = Instant::now();
    let mut endpoint = ClientEndpoint::new(test_config());
    let mut serial = open_serial(&args)?;
    let mut last_state = PeerState::Disconnected;
    let mut last_send = Instant::now() - args.interval;
    let mut last_reopen = Instant::now();
    let mut sent_messages = 0usize;
    let mut stats = FrontendStats::new();
    let mut rx_buf = [0; RX_BUF_BYTES];

    connect_endpoint(&mut endpoint, 0, &mut last_state)?;

    loop {
        let now_ms = elapsed_ms(start);

        if serial.is_none() {
            if last_reopen.elapsed() >= REOPEN_INTERVAL {
                last_reopen = Instant::now();
                serial = open_serial(&args)?;
                connect_endpoint(&mut endpoint, now_ms, &mut last_state)?;
            }
            std::thread::sleep(Duration::from_millis(10));
            continue;
        }

        let link = serial.as_mut().expect("serial exists");
        if let Err(error) = read_serial(&mut **link, &mut endpoint, now_ms, &mut rx_buf) {
            drop_serial(&mut serial, &mut endpoint, &mut last_state, "read", error);
            continue;
        }

        if let Err(error) = pump_endpoint(
            &mut **link,
            &mut endpoint,
            now_ms,
            &mut last_state,
            &args,
            &mut stats,
        ) {
            drop_serial(&mut serial, &mut endpoint, &mut last_state, "write", error);
            continue;
        }

        log_state_change(&mut last_state, endpoint.peer().state());

        if !endpoint.peer().has_session() {
            connect_endpoint(&mut endpoint, now_ms, &mut last_state)?;
            last_send = Instant::now();
        }

        if endpoint.peer().is_connected() && last_send.elapsed() >= args.interval {
            match endpoint.peer_mut().send(&args.message) {
                Ok(Some(_)) => {
                    sent_messages += 1;
                    last_send = Instant::now();
                    if args.verbose {
                        println!("frontend send count={sent_messages}");
                    }
                }
                Ok(None) => {}
                Err(error) if error.kind() == ErrorKind::Engine => {
                    stats.backpressure += 1;
                    last_send = Instant::now();
                    if args.verbose {
                        println!("frontend send backpressure count={}", stats.backpressure);
                    }
                }
                Err(error) => {
                    println!("frontend send error: {error:?}");
                }
            }
        }

        print_stats_if_due(start, &args, &mut stats, sent_messages);

        std::thread::sleep(Duration::from_millis(1));
    }
}

fn open_serial(args: &Args) -> io::Result<Option<Box<dyn serialport::SerialPort>>> {
    match serialport::new(&args.port, args.baud)
        .timeout(Duration::from_millis(1))
        .open()
    {
        Ok(serial) => {
            println!("frontend serial open port={}", args.port);
            Ok(Some(serial))
        }
        Err(error) => {
            println!("frontend serial wait port={} error={error}", args.port);
            Ok(None)
        }
    }
}

fn drop_serial(
    serial: &mut Option<Box<dyn serialport::SerialPort>>,
    endpoint: &mut ClientEndpoint,
    last_state: &mut PeerState,
    operation: &str,
    error: io::Error,
) {
    println!("frontend serial disconnect operation={operation} error={error}");
    *serial = None;
    endpoint.disconnect();
    log_state_change(last_state, endpoint.peer().state());
}

fn connect_endpoint(
    endpoint: &mut ClientEndpoint,
    now_ms: u64,
    last_state: &mut PeerState,
) -> io::Result<()> {
    endpoint.connect(now_ms).map_err(msrt_io_error)?;
    log_state_change(last_state, endpoint.peer().state());
    Ok(())
}

fn read_serial(
    serial: &mut dyn serialport::SerialPort,
    endpoint: &mut ClientEndpoint,
    now_ms: u64,
    rx_buf: &mut [u8],
) -> io::Result<()> {
    loop {
        match serial.read(rx_buf) {
            Ok(0) => return Ok(()),
            Ok(len) => {
                for byte in &rx_buf[..len] {
                    let _ = endpoint.receive(now_ms, core::slice::from_ref(byte));
                }
            }
            Err(error) if error.kind() == io::ErrorKind::TimedOut => return Ok(()),
            Err(error) => return Err(error),
        }
    }
}

fn pump_endpoint(
    serial: &mut dyn serialport::SerialPort,
    endpoint: &mut ClientEndpoint,
    now_ms: u64,
    last_state: &mut PeerState,
    args: &Args,
    stats: &mut FrontendStats,
) -> io::Result<()> {
    loop {
        let mut tx_buf = [0; TX_BUF_BYTES];
        match endpoint.poll(now_ms, &mut tx_buf).map_err(msrt_io_error)? {
            EndpointPoll::Transmit { bytes, .. } => {
                let noise = if endpoint.peer().is_connected() {
                    args.noise
                } else {
                    NoiseConfig::default()
                };
                let (tx_bytes, noise_delta) = mutate_or_copy(&mut stats.noise_state, bytes, noise);
                stats.noise_stats.add(noise_delta);
                if args.verbose && has_noise(noise) && noise_delta.any() {
                    println!(
                        "frontend noise corrupted={} dropped={} inserted={} burst_corrupted={} burst_dropped={} packet_dropped={}",
                        stats.noise_stats.corrupted,
                        stats.noise_stats.dropped,
                        stats.noise_stats.inserted,
                        stats.noise_stats.burst_corrupted,
                        stats.noise_stats.burst_dropped,
                        stats.noise_stats.packet_dropped
                    );
                }
                if tx_bytes.is_empty() {
                    continue;
                }
                serial.write_all(&tx_bytes)?;
                serial.flush()?;
            }
            EndpointPoll::Message(message) => {
                stats.received_messages += 1;
                if args.verbose {
                    println!(
                        "frontend message count={} packet_type={:?} len={} text={}",
                        stats.received_messages,
                        message.packet_type,
                        message.as_bytes().len(),
                        printable(message.as_bytes())
                    );
                }
            }
            EndpointPoll::SendFailed(failed) => {
                println!(
                    "frontend send_failed packet_type={:?} msg={}",
                    failed.packet_type,
                    failed.message_id.get()
                );
                log_state_change(last_state, endpoint.peer().state());
            }
            EndpointPoll::Idle => return Ok(()),
        }
    }
}

fn print_stats_if_due(
    start: Instant,
    args: &Args,
    stats: &mut FrontendStats,
    sent_messages: usize,
) {
    if stats.last_stats.elapsed() < STATS_INTERVAL {
        return;
    }

    stats.last_stats = Instant::now();
    println!(
        "frontend stats elapsed={}s sent={} received={} backpressure={} corrupted={} dropped={} inserted={} burst_corrupted={} burst_dropped={} packet_dropped={}",
        start.elapsed().as_secs(),
        sent_messages,
        stats.received_messages,
        stats.backpressure,
        stats.noise_stats.corrupted,
        stats.noise_stats.dropped,
        stats.noise_stats.inserted,
        stats.noise_stats.burst_corrupted,
        stats.noise_stats.burst_dropped,
        stats.noise_stats.packet_dropped
    );

    if args.verbose && !has_noise(args.noise) {
        println!("frontend stats noise=disabled");
    }
}

fn log_state_change(last: &mut PeerState, current: PeerState) {
    if *last == current {
        return;
    }

    match current {
        PeerState::Disconnected => println!("frontend disconnect"),
        PeerState::Connecting => println!("frontend connect state=Connecting"),
        PeerState::Connected => println!("frontend connect state=Connected"),
    }
    *last = current;
}

fn printable(bytes: &[u8]) -> String {
    bytes
        .iter()
        .map(|byte| {
            if byte.is_ascii_graphic() || *byte == b' ' {
                char::from(*byte)
            } else {
                '.'
            }
        })
        .collect()
}

fn elapsed_ms(start: Instant) -> u64 {
    start.elapsed().as_millis().try_into().unwrap_or(u64::MAX)
}

fn msrt_io_error(error: msrt::core::Error) -> io::Error {
    io::Error::other(format!("{error:?}"))
}

fn process_session_id() -> u32 {
    let millis = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or(Duration::ZERO)
        .as_millis();

    millis as u32
}

fn test_config() -> EngineConfig {
    let session_id = process_session_id();
    EngineConfig {
        initial_message_id: msrt::core::MessageId::new(session_id),
        fragment_bytes: TEST_FRAGMENT_BYTES,
        ..EngineConfig::default()
    }
}

fn next_value(args: &mut impl Iterator<Item = String>, name: &str) -> Result<String, String> {
    args.next()
        .ok_or_else(|| format!("{name} requires a value\n\n{}", usage()))
}

fn usage() -> String {
    "usage: msrt-serial-frontend --port PATH [--baud N] [--interval-ms N] [--message TEXT] [--noise-percent N] [--drop-byte-percent N] [--insert-byte-percent N] [--burst-corrupt-percent N] [--burst-drop-percent N] [--packet-drop-percent N] [--verbose]".to_string()
}

fn percent_text(per_mille: u16) -> String {
    format!("{:.1}", f32::from(per_mille) / 10.0)
}

fn set_mixed_noise(noise: &mut NoiseConfig, total_per_mille: u16) {
    let base = total_per_mille / 6;
    let remainder = total_per_mille % 6;

    noise.corrupt_per_mille = base + u16::from(remainder > 0);
    noise.drop_byte_per_mille = base + u16::from(remainder > 1);
    noise.insert_byte_per_mille = base + u16::from(remainder > 2);
    noise.burst_corrupt_per_mille = base + u16::from(remainder > 3);
    noise.burst_drop_per_mille = base + u16::from(remainder > 4);
    noise.packet_drop_per_mille = base;
}

fn noise_total(noise: NoiseConfig) -> u16 {
    noise
        .corrupt_per_mille
        .saturating_add(noise.drop_byte_per_mille)
        .saturating_add(noise.insert_byte_per_mille)
        .saturating_add(noise.burst_corrupt_per_mille)
        .saturating_add(noise.burst_drop_per_mille)
        .saturating_add(noise.packet_drop_per_mille)
}

trait NoiseStatsExt {
    fn add(&mut self, other: Self);
    fn any(self) -> bool;
}

impl NoiseStatsExt for NoiseStats {
    fn add(&mut self, other: Self) {
        self.corrupted += other.corrupted;
        self.dropped += other.dropped;
        self.inserted += other.inserted;
        self.burst_corrupted += other.burst_corrupted;
        self.burst_dropped += other.burst_dropped;
        self.packet_dropped += other.packet_dropped;
    }

    fn any(self) -> bool {
        self.corrupted != 0
            || self.dropped != 0
            || self.inserted != 0
            || self.burst_corrupted != 0
            || self.burst_dropped != 0
            || self.packet_dropped != 0
    }
}