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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
// (C) 2009-2026, Kees Verruijt, Harlingen, The Netherlands.

//! Actisense NGT-1 binary protocol — sans-I/O byte framer.
//!
//! Frames on the wire look like:
//!
//! ```text
//!   DLE STX <cmd> <len> <payload...> <checksum> DLE ETX
//! ```
//!
//! Where:
//!   - DLE = 0x10, STX = 0x02, ETX = 0x03
//!   - Inside the framed region, every literal `DLE` is doubled
//!     (`DLE DLE`) so the receiver can unambiguously detect frame
//!     boundaries.
//!   - `len` is the unescaped payload length.
//!   - The 8-bit sum of cmd + len + payload + checksum is zero
//!     modulo 256.
//!
//! Commands we care about for v0:
//!   - `N2K_MSG_RECEIVED` (0x93) — an incoming N2K frame from the bus.
//!     The payload is:
//!     `prio(1) pgn(3, LE) dst(1) src(1) ts(4, LE ms) dlen(1) data(dlen)`.
//!
//! The framer emits [`NgtEvent`]s as soon as it finishes (or rejects)
//! a frame. It performs no I/O — the caller decides how bytes get fed
//! in (sync `Read::read`, tokio `AsyncReadExt::read_buf`, …).

use crate::engine::frame::RawFrame;

// Framing bytes are shared with the `.ebl` encoder and decoder in
// [`crate::engine::format::ebl`], hence `pub(crate)`.
pub(crate) const DLE: u8 = 0x10;
pub(crate) const STX: u8 = 0x02;
pub(crate) const ETX: u8 = 0x03;
/// The EBL escape byte. `.ebl` log files wrap the gateway's byte stream in
/// a second escaping layer, with `ESC SOH … ESC LF` metatags; see
/// [`crate::engine::format::ebl`].
pub(crate) const ESC: u8 = 0x1b;
pub(crate) const SOH: u8 = 0x01;
pub(crate) const LF: u8 = 0x0a;

/// Difference between the Windows FILETIME epoch (1601-01-01) and the
/// Unix epoch (1970-01-01), in milliseconds. EBL timestamp records carry
/// a FILETIME (100-ns ticks since 1601); divide by 10_000 to get ms and
/// subtract this to land on Unix ms.
pub(crate) const FILETIME_TO_UNIX_MS: u64 = 11_644_473_600_000;
/// The EBL `TimeUTC` metatag.
pub(crate) const EBL_TIMESTAMP: u8 = 0x03;

/// Receive an N2K frame off the bus.
pub const N2K_MSG_RECEIVED: u8 = 0x93;
/// Send an N2K frame onto the bus.
pub const N2K_MSG_SEND: u8 = 0x94;
/// Send an NGT-specific message (0xA0 is the matching "received" code).
pub const NGT_MSG_SEND: u8 = 0xA1;

/// One fully-decoded NGT-1 protocol message (cmd + unescaped payload).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NgtMessage {
    pub command: u8,
    pub payload: Vec<u8>,
}

#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
pub enum NgtError {
    #[error("NGT message shorter than 3 bytes (cmd + len + checksum)")]
    ShortMessage,
    #[error("NGT checksum mismatch")]
    BadChecksum,
    #[error("NGT declared payload length {declared} does not match received {actual}")]
    LengthMismatch { declared: u8, actual: usize },
    #[error("NGT escape byte 0x{0:02x} not followed by STX/ETX/DLE")]
    BadEscape(u8),
    #[error("NGT message longer than {MAX_COLLECT} bytes without an end, discarded")]
    TooLong,
}

/// Most bytes collected for one message or EBL record before it is given
/// up on. A real NGT-1 message is at most 258 (cmd, len, 255 payload,
/// checksum); the margin keeps garbage without a `DLE ETX` from growing
/// the buffer without limit.
const MAX_COLLECT: usize = 1024;

/// Events emitted by [`Ngt1Decoder::push_byte`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NgtEvent {
    /// A complete NGT-1 message was decoded.
    Message(NgtMessage),
    /// The decoder rejected a frame (resync to next DLE STX).
    Error(NgtError),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
    /// Outside any frame, looking for DLE.
    Idle,
    /// Inside a `DLE STX … DLE ETX` NGT-1 frame, collecting bytes.
    InFrame,
    /// Just consumed a DLE; `in_frame` says whether inside a frame.
    Escape { in_frame: bool },
}

/// Streaming NGT-1 byte decoder. Feed bytes; pull events.
///
/// For an Actisense `.ebl` log file, which wraps this stream in a second
/// escaping layer, use [`crate::engine::format::ebl::EblDecoder`].
pub struct Ngt1Decoder {
    state: State,
    /// Accumulating frame payload (command + length + payload + checksum).
    buf: Vec<u8>,
    /// The bytes seen outside any frame, kept only once
    /// [`Self::collect_text`] asks for them.
    text: Option<Vec<u8>>,
}

impl Default for Ngt1Decoder {
    fn default() -> Self {
        Self::new()
    }
}

impl Ngt1Decoder {
    pub fn new() -> Self {
        Self {
            state: State::Idle,
            // Worst-case frame: 1 cmd + 1 len + 255 payload + 1 cksum.
            buf: Vec::with_capacity(258),
            text: None,
        }
    }

    /// Keep the bytes that arrive outside any frame, for
    /// [`Self::take_text`]: a gateway that also speaks a text protocol on
    /// the same port (the AOS simulator's JSON) answers there. Off by
    /// default, when they are dropped.
    pub fn collect_text(&mut self) {
        self.text.get_or_insert_with(Vec::new);
    }

    /// The bytes seen outside any frame since the last call, when
    /// [`Self::collect_text`] is on. At most [`MAX_COLLECT`] are kept: the
    /// oldest go first.
    pub fn take_text(&mut self) -> Vec<u8> {
        self.text.as_mut().map(std::mem::take).unwrap_or_default()
    }

    /// Feed one byte. Returns `Some(event)` when a frame completes or
    /// fails; `None` while bytes are accumulating.
    pub fn push_byte(&mut self, b: u8) -> Option<NgtEvent> {
        match self.state {
            State::Idle => {
                if b == DLE {
                    self.state = State::Escape { in_frame: false };
                } else if let Some(text) = &mut self.text {
                    if text.len() >= MAX_COLLECT {
                        text.remove(0);
                    }
                    text.push(b);
                }
                None
            }
            State::InFrame => {
                if b == DLE {
                    self.state = State::Escape { in_frame: true };
                    None
                } else {
                    self.collect(b)
                }
            }
            State::Escape { in_frame } => match b {
                STX => {
                    self.buf.clear();
                    self.state = State::InFrame;
                    None
                }
                ETX => {
                    let r = self.finish_frame();
                    self.state = State::Idle;
                    r
                }
                DLE if in_frame => {
                    self.state = State::InFrame;
                    self.collect(DLE)
                }
                DLE => {
                    self.state = State::Idle;
                    None
                }
                other => {
                    self.state = State::Idle;
                    self.buf.clear();
                    // A DLE that wasn't followed by a frame delimiter
                    // outside any frame is just stray serial noise —
                    // surface no error. Only flag when we were
                    // mid-message and the bad sequence corrupted it.
                    in_frame.then_some(NgtEvent::Error(NgtError::BadEscape(other)))
                }
            },
        }
    }

    /// Add a byte to the message being collected, or give the message up
    /// once it passes [`MAX_COLLECT`].
    fn collect(&mut self, b: u8) -> Option<NgtEvent> {
        if self.buf.len() >= MAX_COLLECT {
            self.buf.clear();
            self.state = State::Idle;
            return Some(NgtEvent::Error(NgtError::TooLong));
        }
        self.buf.push(b);
        None
    }

    /// Convenience helper to feed a byte slice. Returns every event
    /// produced in order.
    pub fn push_bytes(&mut self, bytes: &[u8]) -> Vec<NgtEvent> {
        let mut out = Vec::new();
        for &b in bytes {
            if let Some(ev) = self.push_byte(b) {
                out.push(ev);
            }
        }
        out
    }

    fn finish_frame(&mut self) -> Option<NgtEvent> {
        let raw = std::mem::take(&mut self.buf);
        self.state = State::Idle;
        if raw.len() < 3 {
            return Some(NgtEvent::Error(NgtError::ShortMessage));
        }
        let cksum: u8 = raw.iter().copied().fold(0u8, u8::wrapping_add);
        if cksum != 0 {
            return Some(NgtEvent::Error(NgtError::BadChecksum));
        }
        let command = raw[0];
        let declared = raw[1];
        let actual_payload_len = raw.len() - 3; // - cmd - len - checksum
        if declared as usize != actual_payload_len {
            return Some(NgtEvent::Error(NgtError::LengthMismatch {
                declared,
                actual: actual_payload_len,
            }));
        }
        let payload = raw[2..raw.len() - 1].to_vec();
        Some(NgtEvent::Message(NgtMessage { command, payload }))
    }
}

/// Wrap `(cmd, payload)` in NGT-1 framing for transmission to the
/// device: `DLE STX <cmd> <len> <payload...> <checksum> DLE ETX`,
/// with DLE-stuffing inside the framed region and an 8-bit checksum
/// such that `(cmd + len + payload + checksum) ≡ 0 (mod 256)`.
///
/// The output is appended to `out`. `payload.len()` must be ≤ 255.
pub fn encode_ngt_message(cmd: u8, payload: &[u8], out: &mut Vec<u8>) {
    assert!(
        payload.len() <= u8::MAX as usize,
        "NGT payload exceeds 255 bytes"
    );
    out.push(DLE);
    out.push(STX);
    write_stuffed(out, cmd);
    write_stuffed(out, payload.len() as u8);
    let mut sum = cmd.wrapping_add(payload.len() as u8);
    for &b in payload {
        write_stuffed(out, b);
        sum = sum.wrapping_add(b);
    }
    let checksum = 0u8.wrapping_sub(sum);
    write_stuffed(out, checksum);
    out.push(DLE);
    out.push(ETX);
}

fn write_stuffed(out: &mut Vec<u8>, b: u8) {
    out.push(b);
    if b == DLE {
        out.push(DLE);
    }
}

/// Build the inner payload of a `N2K_MSG_SEND` (0x94) command from a
/// [`RawFrame`]. The NGT-1 transmit format is six header bytes —
/// `prio, pgn[0..2] (LE), dst, dlen` — followed by the data bytes.
/// Unlike the receive direction there is no `src` field (the NGT-1
/// supplies its own claimed source address) and no NGT timestamp.
///
/// `frame.data.len()` must be ≤ 223 (canboat's `FASTPACKET_MAX_SIZE`).
pub fn encode_n2k_send_payload(frame: &RawFrame) -> Vec<u8> {
    let mut out = Vec::with_capacity(6 + frame.data.len());
    out.push(frame.prio);
    out.push((frame.pgn & 0xff) as u8);
    out.push(((frame.pgn >> 8) & 0xff) as u8);
    out.push(((frame.pgn >> 16) & 0xff) as u8);
    out.push(frame.dst);
    out.push(frame.data.len() as u8);
    out.extend_from_slice(&frame.data);
    out
}

/// Build a complete NGT-1 transmit byte string from a `RawFrame`:
/// `encode_ngt_message(N2K_MSG_SEND, encode_n2k_send_payload(...))`.
/// Caller writes the bytes verbatim to the serial port.
pub fn encode_n2k_send_frame(frame: &RawFrame) -> Vec<u8> {
    let payload = encode_n2k_send_payload(frame);
    let mut out = Vec::with_capacity(payload.len() + 8);
    encode_ngt_message(N2K_MSG_SEND, &payload, &mut out);
    out
}

/// The bytes an NGT-1 emits for a frame it received from the bus: an
/// `N2K_MSG_RECEIVED` (0x93) message with the header `prio, pgn[0..2]
/// (LE), dst, src, timestamp (u32 LE), dlen`, then the data. The inverse of
/// [`NgtMessage::to_raw_frame`], for simulating a gateway in tests and
/// harnesses. `timestamp_ms` is the NGT-1's own counter (ms since it
/// started). `None` when the data does not fit one NGT-1 message (more
/// than 244 bytes).
pub fn encode_n2k_received_frame(frame: &RawFrame, timestamp_ms: u32) -> Option<Vec<u8>> {
    const HEADER: usize = 11;
    if HEADER + frame.data.len() > u8::MAX as usize {
        return None;
    }
    let mut payload = Vec::with_capacity(HEADER + frame.data.len());
    payload.push(frame.prio);
    payload.extend_from_slice(&frame.pgn.to_le_bytes()[..3]);
    payload.push(frame.dst);
    payload.push(frame.src);
    payload.extend_from_slice(&timestamp_ms.to_le_bytes());
    payload.push(frame.data.len() as u8);
    payload.extend_from_slice(&frame.data);
    let mut out = Vec::with_capacity(payload.len() + 8);
    encode_ngt_message(N2K_MSG_RECEIVED, &payload, &mut out);
    Some(out)
}

/// Actisense's "NGT-specific message received" command: the gateway's
/// BEM responses to [`NGT_MSG_SEND`] commands.
pub const NGT_MSG_RECEIVED: u8 = 0xA0;

/// BEM `0x11`, Get / Set Operating Mode
/// ([SDK](https://github.com/Actisense/SDK/blob/main/docs/DataFormats/Binary/bem-detail/operating-mode.md)):
/// with a 16-bit LE mode it sets the mode (with no data it only reads it).
/// The answer carries the mode in force either way.
pub const BEM_OPERATING_MODE: u8 = 0x11;

/// BEM `0x41`, Get Product Info
/// ([SDK](https://github.com/Actisense/SDK/blob/main/docs/DataFormats/Binary/bem-detail/product-info.md)).
pub const BEM_PRODUCT_INFO: u8 = 0x41;
/// BEM `0xF0`, Startup Status: sent unsolicited when the gateway has
/// (re)started.
pub const BEM_STARTUP_STATUS: u8 = 0xF0;
/// BEM `0xF1`, Error Report: sent unsolicited when the gateway hits an
/// error.
pub const BEM_ERROR_REPORT: u8 = 0xF1;
/// BEM `0xF2`, System Status: bus load and error counts, about once a
/// second when P-codes are on.
pub const BEM_SYSTEM_STATUS: u8 = 0xF2;
/// BEM `0xF4`, Negative Ack: the gateway could not carry out a command.
pub const BEM_NEGATIVE_ACK: u8 = 0xF4;

/// The Actisense SDK's name for the (negative) error code in a BEM
/// response, for the codes it documents. The SDK publishes only part of
/// the list, so other codes have no name.
pub fn error_name(code: i32) -> Option<&'static str> {
    Some(match code {
        -1137 => "BST-BEM message not valid",
        -1138 => "model ID unknown",
        -1139 => "no definition for the datatype",
        -1140 => "bad comms data",
        -1152 => "command does not fit the model",
        -1153 => "invalid stream",
        -1154 => "invalid address",
        -1156 => "unexpected datatype",
        -1158 => "command timeout",
        -1159 => "command data out of range",
        -1160 => "command buffer overrun",
        -1168 => "invalid checksum",
        -1169 => "buffer underflow",
        -1170 => "buffer overflow",
        -1173 => "invalid baud rate",
        -1176 => "port does not exist",
        -1177 => "port number out of range",
        -1497 => "EEPROM sector error",
        -1498 => "malloc/free error",
        -1499 => "model ID invalid",
        -1995 => "null value",
        -1997 => "bad pointer",
        -1998 => "null pointer",
        _ => return None,
    })
}

/// `code` with its SDK name, if it has one: `-1158 (command timeout)`.
pub fn describe_error(code: i32) -> String {
    match error_name(code) {
        Some(name) => format!("{code} ({name})"),
        None => code.to_string(),
    }
}

/// Encode BEM Get Product Info as a ready-to-write byte string.
pub fn encode_get_product_info() -> Vec<u8> {
    let mut out = Vec::with_capacity(8);
    encode_ngt_message(NGT_MSG_SEND, &[BEM_PRODUCT_INFO], &mut out);
    out
}

/// A gateway's product information, from its answer(s) to Get Product
/// Info. Older firmware (the NGT-1, NGW-1) answers in five parts, numbered
/// 1 to 5 by the sequence byte; newer firmware may answer in one, numbered
/// 6.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProductInfo {
    /// NMEA 2000 version × 1000.
    pub nmea2000_version: u16,
    pub product_code: u16,
    pub model: String,
    pub software_version: String,
    pub hardware_version: String,
    pub serial_number: String,
    /// Which parts have arrived, by bit: 1 to 5.
    parts: u8,
}

impl ProductInfo {
    /// Take in one Product Info answer; true once the information is
    /// complete.
    pub fn add(&mut self, response: &BemResponse<'_>) -> bool {
        let d = response.data;
        let u16_at = |i: usize| u16::from_le_bytes([d[i], d[i + 1]]);
        match (response.sequence, d.len()) {
            (6, 138..) => {
                self.nmea2000_version = u16_at(4);
                self.product_code = u16_at(6);
                self.model = product_string(&d[8..40]);
                self.software_version = product_string(&d[40..72]);
                self.hardware_version = product_string(&d[72..104]);
                self.serial_number = product_string(&d[104..136]);
                self.parts = 0b11_1110;
            }
            (1, 6..) => {
                self.nmea2000_version = u16_at(0);
                self.product_code = u16_at(2);
                self.parts |= 1 << 1;
            }
            (part @ 2..=5, 32..) => {
                let text = product_string(&d[..32]);
                match part {
                    2 => self.model = text,
                    3 => self.software_version = text,
                    4 => self.hardware_version = text,
                    _ => self.serial_number = text,
                }
                self.parts |= 1 << part;
            }
            _ => {}
        }
        self.parts == 0b11_1110
    }

    /// The firmware version × 1000: the last `major.minor` number in the
    /// software version, which an NGT-1 gives as `"1.100, 2.690"`.
    pub fn firmware(&self) -> Option<u16> {
        self.software_version
            .split(|c: char| !c.is_ascii_digit() && c != '.')
            .filter_map(|word| {
                let (major, minor) = word.split_once('.')?;
                let major: u16 = major.parse().ok()?;
                if minor.is_empty() || minor.len() > 3 {
                    return None;
                }
                let minor: u16 = format!("{minor:0<3}").parse().ok()?;
                major.checked_mul(1000)?.checked_add(minor)
            })
            .next_back()
    }
}

/// A Product Info string: ASCII, ended by a NUL or 0xFF padding.
fn product_string(bytes: &[u8]) -> String {
    let end = bytes
        .iter()
        .position(|&b| b == 0 || b == 0xff)
        .unwrap_or(bytes.len());
    String::from_utf8_lossy(&bytes[..end]).trim().to_string()
}

/// The firmware version and reset status a Startup Status carries:
/// `(version × 1000, reset status)`. The reset status is one byte on older
/// firmware, four on newer.
pub fn startup_status(response: &BemResponse<'_>) -> Option<(u16, u32)> {
    match response.data {
        [v0, v1, r0, r1, r2, r3, ..] => Some((
            u16::from_le_bytes([*v0, *v1]),
            u32::from_le_bytes([*r0, *r1, *r2, *r3]),
        )),
        [v0, v1, r0, ..] => Some((u16::from_le_bytes([*v0, *v1]), u32::from(*r0))),
        _ => None,
    }
}

/// An Actisense gateway's operating mode, numbered and named as in the
/// Actisense SDK (`operating_mode.hpp`). Only the NGT / NGX modes are
/// listed; a gateway reporting another mode shows as [`Self::Other`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum OperatingMode {
    /// "NGT Transfer Normal Mode": the Receive and Transmit PGN Enable
    /// lists both apply, so only listed PGNs reach the host.
    NgTransferNormal,
    /// "NGT Transfer Rx All Mode": every received PGN is forwarded; the
    /// Transmit PGN Enable list still applies. What canboat has always
    /// set, as the reverse-engineered "startup sequence".
    NgTransferRxAll,
    /// "NGT Transfer Raw Mode": never implemented by the NGT-1, and a
    /// spare slot on the NGX (raw CAN moved to mode 5, CAN Packet).
    NgTransferRaw,
    /// "NGW Convert Normal Mode": NMEA 0183 conversion (NGW-1, NGX).
    NgConvertNormal,
    /// "CAN Packet": raw CAN frames as BST-95, both ways (NGX).
    CanPacket,
    /// "CAN Packet ASCII": raw CAN frames as ASCII (NGX).
    CanPacketAscii,
    /// Any other mode number.
    Other(u16),
}

impl OperatingMode {
    /// The mode's number on the wire.
    pub fn code(self) -> u16 {
        match self {
            Self::NgTransferNormal => 1,
            Self::NgTransferRxAll => 2,
            Self::NgTransferRaw => 3,
            Self::NgConvertNormal => 4,
            Self::CanPacket => 5,
            Self::CanPacketAscii => 6,
            Self::Other(code) => code,
        }
    }

    /// The mode numbered `code`.
    pub fn from_code(code: u16) -> Self {
        match code {
            1 => Self::NgTransferNormal,
            2 => Self::NgTransferRxAll,
            3 => Self::NgTransferRaw,
            4 => Self::NgConvertNormal,
            5 => Self::CanPacket,
            6 => Self::CanPacketAscii,
            _ => Self::Other(code),
        }
    }
}

impl std::fmt::Display for OperatingMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NgTransferNormal => f.write_str("NGT Transfer Normal Mode"),
            Self::NgTransferRxAll => f.write_str("NGT Transfer Rx All Mode"),
            Self::NgTransferRaw => f.write_str("NGT Transfer Raw Mode"),
            Self::NgConvertNormal => f.write_str("NGW Convert Normal Mode"),
            Self::CanPacket => f.write_str("CAN Packet Mode"),
            Self::CanPacketAscii => f.write_str("CAN Packet ASCII Mode"),
            Self::Other(code) => write!(f, "operating mode {code}"),
        }
    }
}

/// Encode BEM Set Operating Mode as a ready-to-write byte string.
pub fn encode_set_operating_mode(mode: OperatingMode) -> Vec<u8> {
    let [lo, hi] = mode.code().to_le_bytes();
    let mut out = Vec::with_capacity(12);
    encode_ngt_message(NGT_MSG_SEND, &[BEM_OPERATING_MODE, lo, hi], &mut out);
    out
}

/// A BEM response: the payload of an [`NGT_MSG_RECEIVED`] message
/// ([SDK](https://github.com/Actisense/SDK/blob/main/docs/DataFormats/Binary/bst-bem-response.md)).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BemResponse<'a> {
    /// The BEM command this answers.
    pub bem: u8,
    /// Sequence number; a long answer comes in several parts.
    pub sequence: u8,
    /// Actisense (ARL) model id of the gateway.
    pub model_id: u16,
    pub serial: u32,
    /// Actisense (ARL) error code; 0 is success, an error is negative.
    pub error: i32,
    /// The command's own data.
    pub data: &'a [u8],
}

impl<'a> BemResponse<'a> {
    /// Split `payload` into the 12-byte BEM header and its data; `None`
    /// when it is shorter than the header.
    pub fn parse(payload: &'a [u8]) -> Option<Self> {
        if payload.len() < 12 {
            return None;
        }
        Some(Self {
            bem: payload[0],
            sequence: payload[1],
            model_id: u16::from_le_bytes([payload[2], payload[3]]),
            serial: u32::from_le_bytes([payload[4], payload[5], payload[6], payload[7]]),
            error: i32::from_le_bytes([payload[8], payload[9], payload[10], payload[11]]),
            data: &payload[12..],
        })
    }

    /// The operating mode an Operating Mode answer reports.
    pub fn operating_mode(&self) -> Option<OperatingMode> {
        match (self.bem, self.data) {
            (BEM_OPERATING_MODE, [lo, hi, ..]) => {
                Some(OperatingMode::from_code(u16::from_le_bytes([*lo, *hi])))
            }
            _ => None,
        }
    }
}

impl NgtMessage {
    /// Convert a `N2K_MSG_RECEIVED` (0x93) message into a [`RawFrame`].
    /// Other commands return `None` — they carry NGT-1-internal state,
    /// not N2K traffic.
    pub fn to_raw_frame(&self) -> Option<RawFrame> {
        if self.command != N2K_MSG_RECEIVED {
            return None;
        }
        // Header: prio(1) pgn(3 LE) dst(1) src(1) ts(4 LE) dlen(1)
        const HEADER: usize = 11;
        if self.payload.len() < HEADER {
            return None;
        }
        let prio = self.payload[0];
        let pgn = u32::from(self.payload[1])
            | (u32::from(self.payload[2]) << 8)
            | (u32::from(self.payload[3]) << 16);
        let dst = self.payload[4];
        let src = self.payload[5];
        // Bytes 6..10 = NGT-1 timestamp (ms since startup). We preserve
        // it as a string for downstream PLAIN/FAST emission.
        let ts_ms = u32::from(self.payload[6])
            | (u32::from(self.payload[7]) << 8)
            | (u32::from(self.payload[8]) << 16)
            | (u32::from(self.payload[9]) << 24);
        let dlen = self.payload[10] as usize;
        if HEADER + dlen > self.payload.len() {
            return None;
        }
        let data = self.payload[HEADER..HEADER + dlen]
            .iter()
            .copied()
            .collect::<smallvec::SmallVec<[u8; 8]>>();
        Some(RawFrame {
            timestamp: Some(ts_ms.to_string()),
            prio,
            pgn,
            src,
            dst,
            data,
        })
    }
}

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

    #[test]
    fn firmware_is_the_last_version_in_the_software_version() {
        let firmware = |software: &str| {
            ProductInfo {
                software_version: software.into(),
                ..Default::default()
            }
            .firmware()
        };
        assert_eq!(firmware("1.100, 2.690"), Some(2_690));
        assert_eq!(firmware("2.190"), Some(2_190));
        assert_eq!(firmware("v2.500"), Some(2_500));
        assert_eq!(firmware("2.5"), Some(2_500));
        assert_eq!(firmware("Rev B"), None);
        assert_eq!(firmware(""), None);
    }

    /// A `DLE STX` never followed by `DLE ETX` gives up at the limit, once,
    /// and the decoder then reads the next message normally.
    #[test]
    fn an_unterminated_message_is_given_up_on() {
        let mut d = Ngt1Decoder::new();
        let mut junk = vec![DLE, STX];
        junk.extend(std::iter::repeat_n(0x55, 10 * MAX_COLLECT));
        let events = d.push_bytes(&junk);
        assert_eq!(events, [NgtEvent::Error(NgtError::TooLong)]);
        assert!(d.buf.len() <= MAX_COLLECT);
        let frame = RawFrame::new(None, 2, 130306, 35, 255, [1, 2, 3, 4, 5, 6, 7, 8]);
        let ok = d.push_bytes(&encode_n2k_received_frame(&frame, 0).unwrap());
        assert!(matches!(&ok[..], [NgtEvent::Message(_)]), "{ok:?}");
    }

    /// A received-frame message decodes back to the frame it was built
    /// from, the NGT-1 counter surfacing as the timestamp.
    #[test]
    fn received_frame_round_trips() {
        let frame = RawFrame::new(None, 2, 130306, 35, 255, [0x10, 0x10, 3, 4, 5, 6, 7, 8]);
        let bytes = encode_n2k_received_frame(&frame, 1234).expect("fits");
        let mut d = Ngt1Decoder::new();
        let events = d.push_bytes(&bytes);
        let [NgtEvent::Message(msg)] = &events[..] else {
            panic!("expected one message, got {events:?}")
        };
        let back = msg.to_raw_frame().expect("an N2K frame");
        assert_eq!(back.timestamp.as_deref(), Some("1234"));
        assert_eq!(
            (back.prio, back.pgn, back.src, back.dst),
            (2, 130306, 35, 255)
        );
        assert_eq!(back.data, frame.data);
    }

    /// 11 header bytes + data must fit the one-byte NGT-1 length: 244
    /// bytes of data encode, 245 are refused rather than panicking.
    #[test]
    fn received_frame_longer_than_one_message_is_refused() {
        let mut frame = RawFrame::new(None, 6, 126996, 35, 255, [0u8; 8]);
        frame.data = std::iter::repeat_n(0xab, 244).collect();
        let bytes = encode_n2k_received_frame(&frame, 0).expect("244 bytes fit");
        let events = Ngt1Decoder::new().push_bytes(&bytes);
        let [NgtEvent::Message(msg)] = &events[..] else {
            panic!("expected one message, got {events:?}")
        };
        assert_eq!(msg.to_raw_frame().expect("a frame").data.len(), 244);
        frame.data.push(0xab);
        assert_eq!(encode_n2k_received_frame(&frame, 0), None);
    }

    /// Build a valid NGT-1 frame from command + payload, applying
    /// DLE-stuffing and computing the checksum.
    fn encode_frame(cmd: u8, payload: &[u8]) -> Vec<u8> {
        let mut inner = vec![cmd, payload.len() as u8];
        inner.extend_from_slice(payload);
        let cksum = inner.iter().copied().fold(0u8, u8::wrapping_add);
        inner.push(0u8.wrapping_sub(cksum));
        // Now DLE-stuff and wrap.
        let mut out = vec![DLE, STX];
        for b in &inner {
            out.push(*b);
            if *b == DLE {
                out.push(DLE);
            }
        }
        out.extend_from_slice(&[DLE, ETX]);
        out
    }

    #[test]
    fn decodes_a_simple_frame() {
        let frame = encode_frame(0x42, &[0x01, 0x02, 0x03]);
        let mut d = Ngt1Decoder::new();
        let events = d.push_bytes(&frame);
        assert_eq!(events.len(), 1);
        match &events[0] {
            NgtEvent::Message(m) => {
                assert_eq!(m.command, 0x42);
                assert_eq!(m.payload, vec![0x01, 0x02, 0x03]);
            }
            other => panic!("expected Message, got {other:?}"),
        }
    }

    #[test]
    fn unescapes_dle_in_payload() {
        // Payload contains a literal DLE byte; it must be doubled on
        // the wire and surface as a single 0x10 in the decoded payload.
        let frame = encode_frame(0xA0, &[0xAA, DLE, 0xBB]);
        let mut d = Ngt1Decoder::new();
        let events = d.push_bytes(&frame);
        assert_eq!(events.len(), 1);
        match &events[0] {
            NgtEvent::Message(m) => assert_eq!(m.payload, vec![0xAA, DLE, 0xBB]),
            other => panic!("expected Message, got {other:?}"),
        }
    }

    #[test]
    fn rejects_bad_checksum() {
        // Build a valid frame, then flip the checksum.
        let mut frame = encode_frame(0x42, &[0x01]);
        // Find the checksum byte (just before DLE ETX); flip a bit.
        let n = frame.len();
        frame[n - 3] = frame[n - 3].wrapping_add(1);
        let mut d = Ngt1Decoder::new();
        let events = d.push_bytes(&frame);
        assert_eq!(events.len(), 1);
        assert!(matches!(events[0], NgtEvent::Error(NgtError::BadChecksum)));
    }

    #[test]
    fn split_across_pushes() {
        // Feed one byte at a time — must produce the same single event.
        let frame = encode_frame(0x42, &[0x01, 0x02]);
        let mut d = Ngt1Decoder::new();
        let mut total = Vec::new();
        for b in &frame {
            if let Some(ev) = d.push_byte(*b) {
                total.push(ev);
            }
        }
        assert_eq!(total.len(), 1);
        match &total[0] {
            NgtEvent::Message(m) => assert_eq!(m.command, 0x42),
            other => panic!("expected Message, got {other:?}"),
        }
    }

    #[test]
    fn ignores_garbage_before_frame() {
        // Pre- and post-amble noise must not trip the decoder.
        let mut bytes = vec![0xFF, 0xAA, 0x10, 0x99]; // bogus DLE-no-STX
        bytes.extend_from_slice(&encode_frame(0x42, &[0x01]));
        bytes.extend_from_slice(&[0x55, 0x66]);
        let mut d = Ngt1Decoder::new();
        let events = d.push_bytes(&bytes);
        assert_eq!(events.len(), 1);
        assert!(matches!(events[0], NgtEvent::Message(_)));
    }

    #[test]
    fn encoder_round_trips_through_decoder() {
        // Build a frame with a DLE byte in payload, encode it, then
        // feed back through the decoder and confirm we get the same
        // (cmd, payload) out.
        let payload = vec![0x00, 0x10, 0xff, 0x10, 0xab];
        let mut wire = Vec::new();
        encode_ngt_message(0x42, &payload, &mut wire);

        let mut d = Ngt1Decoder::new();
        let events = d.push_bytes(&wire);
        assert_eq!(events.len(), 1);
        match &events[0] {
            NgtEvent::Message(m) => {
                assert_eq!(m.command, 0x42);
                assert_eq!(m.payload, payload);
            }
            other => panic!("expected Message, got {other:?}"),
        }
    }

    #[test]
    fn encoder_handles_dle_in_length_and_checksum() {
        // Exercise the DLE-stuffing path for the length byte and the
        // checksum byte (both can equal 0x10 for some payload sizes /
        // contents). Pick a payload of 16 bytes — length = 0x10 = DLE.
        let payload = vec![0u8; 0x10];
        let mut wire = Vec::new();
        encode_ngt_message(0x42, &payload, &mut wire);
        let mut d = Ngt1Decoder::new();
        let events = d.push_bytes(&wire);
        assert_eq!(events.len(), 1);
        match &events[0] {
            NgtEvent::Message(m) => {
                assert_eq!(m.command, 0x42);
                assert_eq!(m.payload.len(), 0x10);
            }
            other => panic!("got {other:?}"),
        }
    }

    #[test]
    fn n2k_send_payload_layout_matches_canboat() {
        let frame = RawFrame {
            timestamp: None,
            prio: 6,
            pgn: 60928,
            src: 0, // ignored in send
            dst: 255,
            data: smallvec::smallvec![0xfb, 0x9b, 0x70, 0x22, 0x00, 0x9b, 0x50, 0xc0],
        };
        let payload = encode_n2k_send_payload(&frame);
        // prio (1) + pgn LE (3) + dst (1) + dlen (1) + data (8) = 14 bytes.
        assert_eq!(payload.len(), 14);
        // 60928 = 0xEE00 → LE bytes 0x00, 0xee, 0x00.
        assert_eq!(payload[0], 6);
        assert_eq!(payload[1], 0x00);
        assert_eq!(payload[2], 0xee);
        assert_eq!(payload[3], 0x00);
        assert_eq!(payload[4], 0xff);
        assert_eq!(payload[5], 8);
        assert_eq!(&payload[6..], &frame.data[..]);
    }

    /// The SDK's Set Operating Mode example: `A1 03 11 02 00`, which is
    /// the old reverse-engineered "startup sequence".
    #[test]
    fn set_operating_mode_matches_the_sdk_example() {
        let bytes = encode_set_operating_mode(OperatingMode::NgTransferRxAll);
        let mut d = Ngt1Decoder::new();
        let events = d.push_bytes(&bytes);
        assert_eq!(events.len(), 1);
        match &events[0] {
            NgtEvent::Message(m) => {
                assert_eq!(m.command, NGT_MSG_SEND);
                assert_eq!(m.payload, [0x11, 0x02, 0x00]);
            }
            other => panic!("got {other:?}"),
        }
    }

    /// The SDK's Get Operating Mode response example, less its BST id and
    /// length: `11 05 0E 00 78 56 34 12 00 00 00 00 02 00`.
    #[test]
    fn bem_response_reports_the_operating_mode() {
        let payload = [
            0x11, 0x05, 0x0e, 0x00, 0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0, 0x02, 0x00,
        ];
        let r = BemResponse::parse(&payload).unwrap();
        assert_eq!(r.bem, BEM_OPERATING_MODE);
        assert_eq!(r.sequence, 5);
        assert_eq!(r.model_id, 0x000e);
        assert_eq!(r.serial, 0x1234_5678);
        assert_eq!(r.error, 0);
        assert_eq!(r.operating_mode(), Some(OperatingMode::NgTransferRxAll));
        assert_eq!(
            r.operating_mode().unwrap().to_string(),
            "NGT Transfer Rx All Mode"
        );
        assert!(BemResponse::parse(&payload[..11]).is_none());
    }

    #[test]
    fn operating_mode_codes_round_trip() {
        for code in 0..=8 {
            assert_eq!(OperatingMode::from_code(code).code(), code);
        }
        assert_eq!(OperatingMode::from_code(512), OperatingMode::Other(512));
    }

    #[test]
    fn n2k_msg_received_decodes_to_raw_frame() {
        // Header: prio=3, pgn=129025 (0x1F801), dst=0xFF, src=36,
        //         ts=0, dlen=8, data=[0xE6 .. 0xB3].
        let pgn = 129025u32;
        let mut payload = vec![
            3,                  // prio
            (pgn & 0xff) as u8, // pgn LE
            ((pgn >> 8) & 0xff) as u8,
            ((pgn >> 16) & 0xff) as u8,
            0xff, // dst
            36,   // src
            0,
            0,
            0,
            0, // ts (4 bytes)
            8, // dlen
        ];
        payload.extend_from_slice(&[0xe6, 0xf1, 0x3a, 0x80, 0x9c, 0xc6, 0x0d, 0xb3]);
        let frame = encode_frame(N2K_MSG_RECEIVED, &payload);

        let mut d = Ngt1Decoder::new();
        let events = d.push_bytes(&frame);
        assert_eq!(events.len(), 1);
        let m = match &events[0] {
            NgtEvent::Message(m) => m,
            other => panic!("{other:?}"),
        };
        let raw = m.to_raw_frame().expect("convert");
        assert_eq!(raw.prio, 3);
        assert_eq!(raw.pgn, 129025);
        assert_eq!(raw.src, 36);
        assert_eq!(raw.dst, 0xff);
        assert_eq!(
            &raw.data[..],
            &[0xe6, 0xf1, 0x3a, 0x80, 0x9c, 0xc6, 0x0d, 0xb3]
        );
    }

    /// ESC is no escape byte on an NGT-1 link — a payload byte of 0x1b in
    /// a regular NGT-1 / Yacht Device `.dle` stream is ordinary data, not a
    /// frame marker. (It is in an `.ebl` file.)
    #[test]
    fn esc_in_payload_is_literal() {
        let payload = vec![0x1b, 0x00, 0x1b, 0xff];
        let mut wire = Vec::new();
        encode_ngt_message(0x42, &payload, &mut wire);
        let mut d = Ngt1Decoder::new();
        let events = d.push_bytes(&wire);
        assert_eq!(events.len(), 1);
        match &events[0] {
            NgtEvent::Message(m) => assert_eq!(m.payload, payload),
            other => panic!("got {other:?}"),
        }
    }
}