canboat 9.1.0

NMEA 2000 decoding, encoding and live-bus access: the CANboat PGN database as a library, plus the canboat CLI (convert / interface / server / tui).
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
501
502
503
504
505
506
507
508
509
510
511
512
513
// (C) 2009-2026, Kees Verruijt, Harlingen, The Netherlands.

//! Integration smoke for the frame-level `convert --to` output formats.
//! Drives the real `canboat convert` binary: PLAIN in → each new format
//! → (for the text formats) parse back to PLAIN and confirm the header
//! and payload survive the round trip.

use std::io::Write;
use std::process::{Command, Stdio};

fn canboat() -> &'static str {
    env!("CARGO_BIN_EXE_canboat")
}

/// Run `canboat <args>` feeding `input` on stdin; return stdout, or
/// panic with stderr on a non-zero exit.
fn run(args: &[&str], input: &[u8]) -> Vec<u8> {
    let mut child = Command::new(canboat())
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn canboat");
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(input)
        .expect("write stdin");
    let out = child.wait_with_output().expect("wait canboat");
    assert!(
        out.status.success(),
        "canboat {args:?} exited {:?}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );
    out.stdout
}

/// Two different `--protocol` values are refused on every path, including
/// the frame-level one that never consults a PGN table.
#[test]
fn two_buses_are_refused_before_any_output() {
    let out = Command::new(canboat())
        .args([
            "convert",
            "--to",
            "plain",
            "--protocol",
            "nmea2000",
            "--protocol",
            "j1939",
        ])
        .stdin(Stdio::null())
        .output()
        .expect("run canboat");
    assert!(!out.status.success());
    assert!(out.stdout.is_empty());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("not supported yet"), "{stderr}");
}

/// A J1939 Engine Hours, Revolutions (65253) frame: 500 h, 10^9 revolutions.
const J1939_PLAIN: &[u8] = b"2026-01-01T00:00:00.000Z,6,65253,0,255,8,10,27,00,00,40,42,0f,00\n";
const J1939_BODY: &str = ",6,65253,0,255,8,10,27,00,00,40,42,0f,00\n";

/// A single received fast-packet PGN 127251 record.
const PLAIN: &[u8] = b"2026-01-01T00:00:00.000Z,3,127251,27,255,8,00,ca,8f,f3,ff,25,02,ff\n";
const BODY: &str = ",3,127251,27,255,8,00,ca,8f,f3,ff,25,02,ff";

#[test]
fn ydwg02_round_trips_to_plain() {
    let ydwg = run(&["convert", "--to", "ydwg02"], PLAIN);
    assert!(
        String::from_utf8_lossy(&ydwg).contains(" R 0DF1131B "),
        "ydwg: {ydwg:?}"
    );
    let back = run(&["convert", "--from", "ydwg02", "--to", "plain"], &ydwg);
    let s = String::from_utf8(back).unwrap();
    assert!(s.contains(BODY), "round-trip lost the body: {s}");
}

/// A fast-packet in its `$MXPGN` frames comes out in the same frames: they
/// are joined first, not split a second time.
#[test]
fn mxpgn_round_trips_to_mxpgn() {
    let input = "$MXPGN,01F805,3824,C69C803AF1E62B00*16\r\n\
                 $MXPGN,01F805,3824,EB49AA3812000D01*60\r\n\
                 $MXPGN,01F805,3824,FB95440C00075102*6D\r\n\
                 $MXPGN,01F805,3824,0033E14000B81503*1A\r\n\
                 $MXPGN,01F805,3824,09FC130000000004*1D\r\n\
                 $MXPGN,01F805,3824,FFFFFF008C005A05*1D\r\n\
                 $MXPGN,01F805,3824,FFFFFFFFFF007F06*60\r\n\
                 $MXPGN,01F801,2801,C1308AC40C5DE343*19\r\n";
    let out = run(
        &["convert", "--from", "mxpgn", "--to", "mxpgn"],
        input.as_bytes(),
    );
    assert_eq!(String::from_utf8(out).unwrap(), input);
}

/// The same `$MXPGN` frames as SeaSmart: one `$PCDIN` per whole message,
/// which reads back to the same data.
#[test]
fn mxpgn_frames_become_whole_seasmart_messages() {
    let input = "$MXPGN,01F805,3824,C69C803AF1E62B00*16\r\n\
                 $MXPGN,01F805,3824,EB49AA3812000D01*60\r\n\
                 $MXPGN,01F805,3824,FB95440C00075102*6D\r\n\
                 $MXPGN,01F805,3824,0033E14000B81503*1A\r\n\
                 $MXPGN,01F805,3824,09FC130000000004*1D\r\n\
                 $MXPGN,01F805,3824,FFFFFF008C005A05*1D\r\n\
                 $MXPGN,01F805,3824,FFFFFFFFFF007F06*60\r\n\
                 $MXPGN,01F801,2801,C1308AC40C5DE343*19\r\n";
    let out = run(
        &["convert", "--from", "mxpgn", "--to", "seasmart"],
        input.as_bytes(),
    );
    let pcdin = String::from_utf8(out).unwrap();
    assert_eq!(
        pcdin,
        "$PCDIN,01F805,00000000,24,E6F13A809CC60D001238AA49EB5107000C4495FB15B80040E1\
         33000000000013FC095A008C00FFFFFF7F00*2D\r\n\
         $PCDIN,01F801,00000000,01,43E35D0CC48A30C1*23\r\n"
    );
    let back = run(
        &["convert", "--from", "seasmart", "--to", "plain"],
        pcdin.as_bytes(),
    );
    let back = String::from_utf8(back).unwrap();
    assert!(
        back.contains(",0,129025,1,255,8,43,e3,5d,0c,c4,8a,30,c1"),
        "{back}"
    );
    assert!(back.contains(",0,129029,36,255,43,e6,f1,3a,80,"), "{back}");
}

/// A wrong checksum drops the sentence, unless --ignore-checksum.
#[test]
fn ignore_checksum_takes_a_wrong_one() {
    let wrong = b"$PCDIN,01F119,00000000,0F,2AAF00D1067414FF*21\n";
    let out = run(&["convert", "--from", "seasmart", "--to", "plain"], wrong);
    assert!(out.is_empty(), "{}", String::from_utf8_lossy(&out));
    let out = run(&["convert", "--to", "plain", "--ignore-checksum"], wrong);
    let out = String::from_utf8(out).unwrap();
    assert!(
        out.contains(",0,127257,15,255,8,2a,af,00,d1,06,74,14,ff"),
        "{out}"
    );
}

#[test]
fn actisense_round_trips_to_plain() {
    let acti = run(&["convert", "--to", "actisense"], PLAIN);
    assert!(
        String::from_utf8_lossy(&acti).starts_with('A'),
        "acti: {acti:?}"
    );
    let back = run(&["convert", "--from", "actisense", "--to", "plain"], &acti);
    let s = String::from_utf8(back).unwrap();
    assert!(s.contains(BODY), "round-trip lost the body: {s}");
}

/// `--to json` leads with the same producer banner `analyzer` emits.
/// `n2kd` reads `"units"` off it to pick the schema it rebuilds records
/// against, so a missing banner means a stream decoded in the wrong
/// unit system, silently.
#[test]
fn json_leads_with_the_version_banner() {
    let out = run(&["convert", "--to", "json"], PLAIN);
    let s = String::from_utf8(out).unwrap();
    let banner = s.lines().next().expect("a first line");
    assert!(banner.starts_with(r#"{"version":"#), "banner: {banner}");
    assert!(banner.contains(r#""units":"si""#), "banner: {banner}");
    assert!(
        banner.contains(r#""showLookupValues":false"#),
        "banner: {banner}"
    );
    // …and the records still follow it.
    assert!(
        s.lines()
            .nth(1)
            .is_some_and(|l| l.contains("\"pgn\":127251"))
    );
}

#[test]
fn banner_tracks_the_output_shape() {
    let metric = String::from_utf8(run(
        &["convert", "--to", "json", "--units", "metric", "--nv"],
        PLAIN,
    ))
    .unwrap();
    let banner = metric.lines().next().unwrap();
    assert!(banner.contains(r#""units":"std""#), "banner: {banner}");
    assert!(
        banner.contains(r#""showLookupValues":true"#),
        "banner: {banner}"
    );
}

/// The banner names the table the records were decoded against: the
/// same PGN number means different things on NMEA 2000 and J1939.
#[test]
fn banner_names_the_protocol() {
    let n2k = String::from_utf8(run(&["convert", "--to", "json"], PLAIN)).unwrap();
    let banner = n2k.lines().next().unwrap();
    assert!(
        banner.contains(r#""protocol":"nmea2000""#),
        "banner: {banner}"
    );

    let j1939 = String::from_utf8(run(
        &["convert", "--to", "json", "--protocol", "j1939"],
        J1939_PLAIN,
    ))
    .unwrap();
    let banner = j1939.lines().next().unwrap();
    assert!(banner.contains(r#""protocol":"j1939""#), "banner: {banner}");
}

/// A J1939 JSON stream re-encodes against the J1939 table when asked
/// to, and is refused, naming the fix, when read as NMEA 2000.
#[test]
fn a_j1939_json_stream_needs_protocol_j1939() {
    let json = run(
        &["convert", "--to", "json", "--protocol", "j1939"],
        J1939_PLAIN,
    );
    let plain = String::from_utf8(run(
        &[
            "convert",
            "--from",
            "json",
            "--to",
            "plain",
            "--protocol",
            "j1939",
        ],
        &json,
    ))
    .unwrap();
    assert!(plain.ends_with(J1939_BODY), "round trip: {plain}");

    let out = Command::new(canboat())
        .args(["convert", "--from", "json", "--to", "plain"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .and_then(|mut child| {
            child.stdin.take().unwrap().write_all(&json)?;
            child.wait_with_output()
        })
        .expect("run canboat");
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("--protocol j1939"), "{stderr}");
}

#[test]
fn no_banner_suppresses_it_and_text_never_has_one() {
    let bare = String::from_utf8(run(&["convert", "--to", "json", "--no-banner"], PLAIN)).unwrap();
    assert!(
        !bare.contains("\"version\""),
        "banner leaked through --no-banner: {bare}"
    );
    // canboat C emits no banner in text mode either.
    let text = String::from_utf8(run(&["convert", "--to", "text"], PLAIN)).unwrap();
    assert!(!text.contains("\"version\""), "text got a banner: {text}");
}

/// The banner must not break `--from json`: it is not a record, and the
/// re-encoder skips `{"version":…}` lines. Uses PGN 127250 rather than
/// the shared `PLAIN` fixture because 127251's trailing Reserved field
/// renders as a hex display string that the encoder can't take back —
/// a pre-existing limitation, unrelated to the banner.
const HEADING: &[u8] = b"2026-01-01T00:00:00.000Z,3,127250,27,255,8,00,ca,8f,ff,7f,ff,7f,fd\n";

#[test]
fn json_round_trips_through_its_own_banner() {
    let json = run(&["convert", "--to", "json", "--nv"], HEADING);
    assert!(String::from_utf8_lossy(&json).starts_with(r#"{"version":"#));
    let back = run(&["convert", "--from", "json", "--to", "plain"], &json);
    assert_eq!(
        String::from_utf8(back).unwrap().as_bytes(),
        HEADING,
        "round trip through the banner is not byte-exact"
    );
}

/// `--from json` reads bare physical values against the unit system the
/// input's *banner* declares, not the one `--units` asks for on output.
/// That makes the pair a unit converter — and, more importantly, stops a
/// canboat C `"units":"std"` stream from having its degrees re-encoded
/// as radians now that SI is the default.
#[test]
fn json_input_follows_the_banners_units() {
    // Metric out: heading in degrees, banner says "std".
    let metric = run(&["convert", "--to", "json", "--units", "metric"], HEADING);
    let s = String::from_utf8(metric.clone()).unwrap();
    assert!(s.lines().next().unwrap().contains(r#""units":"std""#));
    assert!(s.contains(r#""heading":210.9"#), "metric json: {s}");

    // Feed it back with the default (SI) output: the same record must
    // come out in radians, not have 210.9 read as radians.
    let si = String::from_utf8(run(&["convert", "--from", "json"], &metric)).unwrap();
    assert!(si.lines().next().unwrap().contains(r#""units":"si""#));
    assert!(si.contains(r#""heading":3.68"#), "si json: {si}");
}

#[test]
fn the_banner_outranks_the_units_flag_on_input() {
    // SI-bannered input, `--units metric` on the command line: the flag
    // governs the output, the banner governs how the input is read, so
    // the wire bits survive.
    let si_json = run(&["convert", "--to", "json"], HEADING);
    let back = run(
        &[
            "convert", "--from", "json", "--to", "plain", "--units", "metric",
        ],
        &si_json,
    );
    assert_eq!(
        String::from_utf8(back).unwrap().as_bytes(),
        HEADING,
        "banner-declared input units were ignored"
    );
}

#[test]
fn actisense_ebl_emits_binary_framing() {
    // EBL is output-only; assert it produced a binary record that opens
    // with the `ESC SOH` timestamp-header framing.
    let ebl = run(&["convert", "--to", "actisense-ebl"], PLAIN);
    assert!(ebl.len() > 16, "ebl too short: {ebl:?}");
    assert_eq!(&ebl[..2], &[0x1b, 0x01], "expected ESC SOH opener");
}

/// Drop every `"timestamp":"…",` from JSON lines: a BST-D0 message
/// carries only the device's own clock, so its frames have none.
fn without_timestamps(json: &[u8]) -> String {
    let text = String::from_utf8_lossy(json);
    let mut out = String::new();
    let mut rest = text.as_ref();
    while let Some(i) = rest.find("\"timestamp\":\"") {
        out.push_str(&rest[..i]);
        let after = &rest[i + "\"timestamp\":\"".len()..];
        let end = after
            .find("\",")
            .expect("timestamp is followed by another field");
        rest = &after[end + 2..];
    }
    out.push_str(rest);
    out
}

/// Actisense BST-D0 messages (#993), as a W2K-1 sends them in its
/// Actisense mode. The fixture is pgn-test.in's 31 messages, 23 of them
/// fast-packets, written from the Actisense SDK's description of BST-D0
/// and BDTP (13 of its DLEs are doubled). They decode exactly as
/// pgn-test.in does.
#[test]
fn bst_d0_decodes_as_pgn_test() {
    let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../analyzer/tests");
    let plain = std::fs::read(dir.join("pgn-test.in")).expect("read pgn-test.in");
    let bst = std::fs::read(dir.join("pgn-test-bst-d0.bin")).expect("read fixture");
    let want = without_timestamps(&run(&["convert", "--no-banner"], &plain));
    let got = without_timestamps(&run(
        &["convert", "--no-banner", "--from", "n2k-actisense"],
        &bst,
    ));
    assert_eq!(got.lines().count(), 31);
    assert_eq!(got, want);
}

/// Actisense BST-95 raw CAN frames (#1011), as a PRO-NDC-1E2K or W2K-1
/// sends them in its "CAN Actisense" mode. The fixture is pgn-test.in's 31
/// messages as 115 CAN frames: the 26 fast-packets split into their frames,
/// written from the Actisense SDK's description of BST-95 and BDTP (18 of
/// its DLEs are doubled). Joined again, they decode exactly as pgn-test.in
/// does.
#[test]
fn bst_95_decodes_as_pgn_test() {
    let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../analyzer/tests");
    let plain = std::fs::read(dir.join("pgn-test.in")).expect("read pgn-test.in");
    let bst = std::fs::read(dir.join("pgn-test-bst-95.bin")).expect("read fixture");
    let want = without_timestamps(&run(&["convert", "--no-banner"], &plain));
    let got = without_timestamps(&run(
        &["convert", "--no-banner", "--from", "raw-actisense"],
        &bst,
    ));
    assert_eq!(got.lines().count(), 31);
    assert_eq!(got, want);
}

/// Waveshare USB-CAN-A frames (#1016), as the adapter sends them on its
/// serial port. The fixture is pgn-test.in's 31 messages as 115 20-byte
/// frames, the fast-packets split per canboat.json, written by a script
/// apart from canboat's encoder, from Waveshare's description of the
/// protocol. Joined again, they decode exactly as pgn-test.in does.
#[test]
fn usb_can_a_decodes_as_pgn_test() {
    let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../analyzer/tests");
    let plain = std::fs::read(dir.join("pgn-test.in")).expect("read pgn-test.in");
    let capture = std::fs::read(dir.join("pgn-test-usb-can-a.bin")).expect("read fixture");
    assert_eq!(capture.len(), 115 * 20);
    let want = without_timestamps(&run(&["convert", "--no-banner"], &plain));
    let got = without_timestamps(&run(
        &["convert", "--no-banner", "--from", "usb-can-a"],
        &capture,
    ));
    assert_eq!(got.lines().count(), 31);
    assert_eq!(got, want);
}

/// `canboat convert --to plain` on `candump2analyzer/tests/<name>.in`, with
/// the timestamp column taken off each line, against `<name>.out` there.
/// The candump styles in these files carry no time and candump2analyzer
/// stamps them with the wall clock, so both sides compare what follows.
fn candump_matches_candump2analyzer(name: &str) -> usize {
    let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../candump2analyzer/tests");
    let input = std::fs::read(dir.join(format!("{name}.in"))).expect("read .in");
    let want = std::fs::read_to_string(dir.join(format!("{name}.out"))).expect("read .out");
    let out = run(&["convert", "--no-banner", "--to", "plain"], &input);
    let got: String = String::from_utf8(out)
        .expect("utf-8")
        .lines()
        .map(|l| format!("{}\n", l.split_once(',').map_or(l, |(_, rest)| rest)))
        .collect();
    assert_eq!(got, want.replace("\r\n", "\n"), "{name}");
    got.lines().count()
}

/// candump in the style of the Angstrom distribution's can-utils (#998).
/// The capture starts with candump's `interface = …` banner, which must
/// not make format detection pick PLAIN.
#[test]
fn candump_angstrom_matches_candump2analyzer() {
    assert_eq!(candump_matches_candump2analyzer("angstrom"), 51);
}

/// Lines whose bytes do not match their `[len]` (cut short, more bytes
/// than declared, or more than 8) are skipped by both readers, in both
/// styles that declare a length. Tabs and runs of spaces between the bytes
/// are read as they come, and `candump -a`'s ASCII column is allowed.
#[test]
fn candump_bad_lengths_match_candump2analyzer() {
    assert_eq!(candump_matches_candump2analyzer("angstrom-bad-length"), 5);
    assert_eq!(candump_matches_candump2analyzer("debian-bad-length"), 2);
}

/// One BDTP-framed BST-95 message from the bus: `data` (at most 8 bytes)
/// with the identifier of `prio`, `pgn` (PDU2), `src`.
fn bst95(prio: u8, pgn: u32, src: u8, data: &[u8]) -> Vec<u8> {
    let mut m = vec![
        0x95,
        6 + data.len() as u8,
        0,
        0,
        src,
        pgn as u8,
        (pgn >> 8) as u8,
        (prio << 2) | (pgn >> 16) as u8,
    ];
    m.extend_from_slice(data);
    let sum = m.iter().fold(0u8, |s, &b| s.wrapping_add(b));
    m.push(0u8.wrapping_sub(sum));
    let mut out = vec![0x10, 0x02];
    for b in m {
        out.push(b);
        if b == 0x10 {
            out.push(0x10);
        }
    }
    out.extend_from_slice(&[0x10, 0x03]);
    out
}

/// PGN 130816 is a fast-packet on NMEA 2000 but a single frame on J1939, so
/// a BST-95 capture read with `--protocol j1939` gives the frame as it is,
/// where NMEA 2000 waits for the rest of a fast-packet that never comes.
#[test]
fn bst_95_follows_the_protocol() {
    // Read as a fast-packet, its first two bytes say: sequence 1, frame 0,
    // a message of 20 bytes.
    let frame = bst95(6, 130816, 0x2a, &[0x20, 0x14, 2, 3, 4, 5, 6, 7]);
    let j1939 = run(
        &[
            "convert",
            "--from",
            "raw-actisense",
            "--protocol",
            "j1939",
            "--to",
            "plain",
        ],
        &frame,
    );
    let j1939 = String::from_utf8(j1939).unwrap();
    assert!(
        j1939.contains(",6,130816,42,255,8,20,14,02,03,04,05,06,07"),
        "{j1939}"
    );
    let n2k = run(
        &["convert", "--from", "raw-actisense", "--to", "plain"],
        &frame,
    );
    assert!(
        !String::from_utf8(n2k).unwrap().contains("130816"),
        "on NMEA 2000 it is the first frame of a fast-packet"
    );
}