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
// (C) 2009-2026, Kees Verruijt, Harlingen, The Netherlands.
//! `canboat` — NMEA 2000 (canboat) decoding, encoding, and live-bus access.
//!
//! This is the single crate an external consumer depends on. Its public
//! surface is deliberately small and feature-gated; think in terms of
//! [`Frame`] ⇆ [`DecodedPgn`] (decode) and [`PgnBuilder`] → [`Frame`]
//! (encode). See `doc/library-api-plan.md` in the repository for the full design.
//!
//! canboat is the fruit of reverse-engineering NMEA 2000 — a closed,
//! pay-to-read standard — out on the water since 2009. This crate embeds the
//! whole distilled result: **nearly 600 PGN message definitions** across some
//! 350 PGNs — over 220 standardized, plus 370-odd *company-specific* variants
//! spanning ~25 manufacturers (Simrad, Furuno, Garmin, Raymarine, B&G, …) —
//! and it both decodes **and** encodes every one of them.
//!
//! # Quick start
//!
//! Everything below is in the baseline `decode` feature — no I/O, no threads.
//! The pivot is [`Frame`] (a raw PGN on the wire) and [`Database`] (the
//! compiled canboat schema). Fields are addressed by a generated **`FieldId`
//! constant** ([`ids::field`]) — the recommended path on both sides:
//! [`PgnBuilder::push`] to encode, [`DecodedPgn::field`] to read back. It is
//! `O(1)` (a single array index by the field's schema position) and
//! compile-checked: a typo, or a field from the wrong PGN, fails the build
//! instead of erroring at runtime.
//!
//! ```
//! use canboat::{Database, EncodeValue, FieldValue, Units};
//! use canboat::ids::field::wind_data as wd;
//!
//! let db = Database::embedded(Units::Metric);
//!
//! // Encode PGN 130306 "Wind Data": 5.23 m/s at 1.5 rad, apparent wind.
//! // Unset fields (and proprietary manufacturer/industry selectors) fall
//! // back to their schema defaults.
//! let frame: canboat::Frame = db
//! .encode("windData")?
//! .push(wd::WIND_SPEED, 5.23)?
//! .push(wd::WIND_ANGLE, 1.5)?
//! .push(wd::REFERENCE, EncodeValue::Lookup("Apparent".into()))?
//! .build()?;
//! assert_eq!(frame.pgn, 130306);
//!
//! // Decode it back — the read side mirrors the write side.
//! let decoded = db.decode(&frame).expect("valid frame decodes");
//! assert_eq!(decoded.id, "windData");
//! match &decoded.field(wd::REFERENCE).unwrap().value {
//! FieldValue::Lookup { name, .. } => assert_eq!(*name, Some("Apparent")),
//! other => panic!("unexpected: {other:?}"),
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Numbers and raw bits
//!
//! A number is a value in the field's unit, whether it is written as an
//! integer or not: `push(wd::WIND_SPEED, 5)` is 5 m/s, exactly like `5.0`.
//! To write a field's wire bits verbatim — a sentinel such as "not
//! available", say — wrap them in [`Raw`], the one spelling that skips the
//! scaling and the range check:
//!
//! ```
//! # use canboat::{Database, Raw, Units};
//! # use canboat::ids::field::wind_data as wd;
//! # let db = Database::embedded(Units::Si);
//! let five = db.encode("windData")?.push(wd::WIND_SPEED, 5)?.build()?;
//! let also_five = db.encode("windData")?.push(wd::WIND_SPEED, 5.0)?.build()?;
//! assert_eq!(five.data, also_five.data);
//! // 500 is the wire count of 0.01 m/s steps: the same 5 m/s.
//! let raw = db.encode("windData")?.push(wd::WIND_SPEED, Raw(500))?.build()?;
//! assert_eq!(raw.data, five.data);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! No constant to hand (the field is chosen at runtime — a config-driven
//! encoder, a CLI arg)? Use the `*_by_name` twins,
//! [`PgnBuilder::push_by_name`] and [`DecodedPgn::field_by_name`] — an `O(n)`
//! scan by schema name, resolved at runtime rather than compile time:
//!
//! ```
//! # use canboat::{Database, EncodeValue, Units};
//! # let db = Database::embedded(Units::Metric);
//! let frame = db
//! .encode("windData")?
//! .push_by_name("Wind Speed", 5.23)?
//! .push_by_name("Reference", EncodeValue::Lookup("Apparent".into()))?
//! .build()?;
//! assert_eq!(db.decode(&frame).unwrap().field_by_name("Wind Speed").is_some(), true);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Lookup (enum) fields
//!
//! A `LOOKUP` field carries an integer code that maps to a label. Encode it
//! by **label** ([`EncodeValue::Lookup`], shown above) or by **code** (an
//! integer); on decode, [`FieldValue::Lookup`] gives you both the number
//! and its resolved name, so you can match on whichever you have:
//!
//! ```
//! # use canboat::{Database, EncodeValue, FieldValue, Units};
//! # use canboat::ids::field::wind_data as wd;
//! # let db = Database::embedded(Units::Metric);
//! // Reference = 2 is "Apparent" — set the enum's code directly.
//! let frame = db.encode("windData")?.push(wd::REFERENCE, 2)?.build()?;
//!
//! let decoded = db.decode(&frame).unwrap();
//! match &decoded.field(wd::REFERENCE).unwrap().value {
//! FieldValue::Lookup { value, name } => {
//! assert_eq!(*value, 2); // the raw enum value
//! assert_eq!(*name, Some("Apparent")); // its schema label, if known
//! }
//! _ => unreachable!(),
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! For a live bus, add the `io` feature: `bus::Device::new(kind, address)`
//! opens any gateway canboat drives (`bus::Kind::ALL`) and hands back a
//! bidirectional `bus::DeviceHandle` (a [`read::FrameSource`] plus a
//! `bus::FrameSender`). To
//! own the bus with the address-claim, quirks, and the 2597–2606 TCP serving
//! layer already assembled, add the `bridge` feature and drive a
//! `bridge::Bridge` instead.
//!
//! # Features
//!
//! * `decode` (baseline) — sans-I/O core: schema, decode, encode, formatters,
//! and `codec`: the NGT-1 / iKonvert / Maretron wire protocols without a port.
//! No threads, no async, no sockets.
//! * `io` — byte-source readers (`read::*Reader`) for files / text, plus
//! `bus::Device` to read+write a live bus through any gateway.
//! * `raw` — `bus::Device::open_raw` alone: single CAN frames to and from
//! the gateways that pass them, with no NMEA 2000 in between.
//! * `node` — `device`: be a compliant N2K node (address claim + responder).
//! * `bridge` — `bridge`: the live CAN bus, fully assembled.
//! * `nmea0183`, `ais` — output-formatter sub-features.
//!
//! The `cli` feature (the package default) builds the `canboat` binary and is
//! not part of this library's public contract. Library consumers select
//! `default-features = false` plus the features they need.
// The public items are re-exported from private modules whose docs
// naturally cross-reference their private neighbours; rustdoc renders such
// links as plain code, which is the right thing for the facade's readers.
// Genuinely broken links stay fatal (`rustdoc::broken_intra_doc_links`).
// ───────────────────────── implementation (private) ─────────────────────────
// Everything below the facade lives in private modules: the compiler, not
// convention, keeps it off the public surface. Two lints are relaxed for
// them:
//
// * `missing_docs` applies at the definition site, so it would otherwise
// fire on every field and method of a re-exported type.
// * `dead_code` / `unused_imports` are only meaningful under the full
// feature set: a `decode`-only build legitimately leaves the format
// parsers, text formatter and snapshot cache unreachable, since only the
// `io` / `bridge` / `cli` layers call them. The default (`cli`) build,
// which CI's clippy job checks, still enforces both.
/// Build-time version + git commit for the analyzer JSON banner.
/// The `canboat` command-line tool (subcommands and their plumbing).
/// The sans-I/O engine: schema tables, decode, encode, formatters.
/// Sync I/O adapters and device drivers (`io`), the raw links (`raw`), plus
/// the transport-free node pieces (`node`).
/// The n2kd daemon: TCP serving, NMEA 0183 / AIS conversion, request engine.
/// The live-bus pipeline: device → decode → quirks → serving.
/// Entry point of the `canboat` binary; `src/main.rs` is a one-line call
/// to this. Not part of the library contract.
// ─────────────────────────── decode (baseline) ───────────────────────────
// Engine types, re-exported at the crate root under their locked public names.
// The internal engine names (PgnDatabase, RawFrame, FieldRef) are mapped to
// the public names here; FieldHandle was collapsed into FieldId in Phase 1.
pub use crate;
/// Schema introspection: the read-facing shape of the PGN/field definitions,
/// for consumers that treat the database as metadata (codegen, UI forms).
/// Generated compile-time identity constants: `ids::pgn::WIND_DATA`,
/// `ids::field::wind_data::WIND_ANGLE`. Resolve a field once, at build time.
/// Turn a [`DecodedPgn`] back into bytes/text. `write_nmea0183` / `write_ais`
/// land here when the `nmea0183` / `ais` features are wired.
/// Inbound: turn a byte source into a stream of [`DecodedPgn`].
///
/// [`FrameSource`](read::FrameSource) is the bring-your-own-transport seam —
/// implement it over your own CAN driver, then feed it to
/// [`Decoder`](read::Decoder) to get decoded records. Ready-made readers for
/// ASCII line formats, `.ebl` logs, and `.pcap`/`.nif` captures arrive with the
/// `io` feature. [`from_analyzer_json`](read::from_analyzer_json) rehydrates an
/// already-decoded analyzer-JSON line.
// ──────────────────────────────── bus ────────────────────────────────────
/// Talk to a live bus through a gateway: an Actisense NGT-1 or W2K-1, a
/// Yacht Devices gateway, an iKonvert, a MiniPlex, a SocketCAN interface,
/// and the rest of [`Kind::ALL`](bus::Kind::ALL). Reading a stream of
/// frames while writing frames back, without the full `bridge` pipeline or
/// its TCP serving layer. This is the middle rung between
/// bring-your-own [`read::FrameSource`] and the fully-assembled
/// `bridge::Bridge`.
///
/// Every gateway is opened the one way: name its [`Kind`](bus::Kind) and
/// where it is with [`Device::new`](bus::Device::new), set what it needs,
/// and `open` it. [`Kind`](bus::Kind) and
/// [`capabilities`](bus::Device::capabilities) say what a gateway can do,
/// and a setting it does not have is refused rather than ignored. The
/// handle that comes back, a [`DeviceHandle`](bus::DeviceHandle), is
/// bidirectional and composes with the rest of the crate:
///
/// * **read** — `handle.frames_rx` is an `mpsc::Receiver<Frame>`, hence a
/// [`read::FrameSource`]; feed it to a [`read::Decoder`] for decoded records
/// (fast-packet reassembly included).
/// * **write** — [`frame_sender`](bus::DeviceHandle::frame_sender) hands out a
/// cloneable [`FrameSender`](bus::FrameSender); build frames with
/// [`Database::encode`] and
/// [`send_frame`](bus::DeviceHandle::send_frame) them onto the bus.
///
/// ```no_run
/// use canboat::bus::{BusProtocol, Device, Kind};
/// use canboat::{Database, Units};
/// use canboat::ids::field::iso_request;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db = Database::embedded(Units::Metric);
/// let link = Device::new(Kind::NGT1, "/dev/ttyUSB0").open(BusProtocol::Nmea2000)?;
///
/// // Write: ask every device for its Product Information (PGN 126996).
/// let tx = link.frame_sender();
/// let request = db
/// .encode("isoRequest")?
/// .destination(255)
/// .push(iso_request::PGN, 126_996u32)?
/// .build()?;
/// tx.send_frame(request)?;
///
/// // Read: decode the live stream.
/// for pgn in canboat::read::Decoder::new(link.frames_rx, db) {
/// let pgn = pgn?;
/// println!("{} from {}", pgn.pgn, pgn.src);
/// }
/// # Ok(())
/// # }
/// ```
///
/// `open` needs the `io` feature;
/// [`open_raw`](bus::Device::open_raw), single CAN frames with nothing of
/// NMEA 2000 in between, only `raw` (and `raw-usb` for the CANalyst-II).
// ─────────────────────────────── codec ───────────────────────────────────
/// The gateways' wire protocols without the I/O: bytes in, [`Frame`]s out,
/// and back. For a transport the `bus` openers cannot reach — WebSerial or a
/// WebSocket in a browser, an async runtime, an embedded UART.
///
/// Each gateway is one stateful object implementing [`Codec`](codec::Codec)
/// — [`Ngt1`](codec::ngt1::Ngt1), [`Ikonvert`](codec::ikonvert::Ikonvert),
/// [`Maretron`](codec::maretron::Maretron) — that holds everything its
/// protocol needs: the partial message between reads, the init handshake,
/// the transmit list. It never touches a port, a thread or the clock; the
/// caller writes what it returns and passes the time in. The `io` feature's
/// `bus::Device` runs these same codecs on a pair of threads.
///
/// ```
/// use canboat::codec::{Codec, Event};
/// use canboat::codec::ikonvert::{Config, Ikonvert};
///
/// let mut gw = Ikonvert::new(Config::default());
/// let mut to_port: Vec<Vec<u8>> = vec![gw.open()]; // $PDGY,N2NET_OFFLINE
///
/// // Whatever the port delivers, fed in with the current time.
/// let now_ms = 1_780_082_164_826;
/// let mut events = Vec::new();
/// gw.receive(b"$PDGY,TEXT,Digital_Yacht_iKonvert\r\n", now_ms, &mut events);
/// for ev in events.drain(..) {
/// match ev {
/// Event::Frame(frame) => println!("PGN {} from {}", frame.pgn, frame.src),
/// Event::Send(bytes) => to_port.push(bytes), // the next handshake step
/// Event::Error(e) => eprintln!("{e}"),
/// }
/// }
/// assert_eq!(to_port[1], b"$PDGY,N2NET_RESET\r\n");
///
/// // Closing takes the iKonvert off the bus.
/// to_port.push(gw.close());
/// ```
///
/// To speak raw CAN over a byte pipe instead (SLCAN, candump over a socket),
/// [`can_id`](codec::can_id) maps the 29-bit identifier and
/// [`fastpacket`](codec::fastpacket) splits an outgoing message into its
/// CAN frames; [`Reassembler`] joins incoming ones. On a J1939 bus,
/// [`iso_tp`](codec::iso_tp) sends a message too long for one frame.
// ─────────────────────────────── device ──────────────────────────────────
/// Be a compliant N2K node without owning a transport, all [`Frame`]-in /
/// [`Frame`]-out — the caller owns the bus.
///
/// [`Name`](device::Name) builds the 64-bit ISO NAME; [`Claimer`](device::Claimer)
/// is the address-claim state machine (NAME arbitration). The response builders —
/// [`ProductInfo`](device::ProductInfo) (PGN 126996) and the
/// [`pgn_list_frames`](device::pgn_list_frames) /
/// [`iso_ack_frame`](device::iso_ack_frame) /
/// [`heartbeat_frame`](device::heartbeat_frame) helpers — emit the frames a node
/// answers discovery with; the caller drives them from its own event loop (as the
/// socketcan gateway and the motion quirk both do).
// ─────────────────────────────── bridge ──────────────────────────────────
/// The live CAN bus, fully assembled: own a socketcan interface (or another
/// [`FrameSource`](read) via a device backend), claim an address, apply
/// quirks, and expose an in-process [`DecodedPgn`] stream plus an optional
/// TCP serving layer (the 2597–2606 ports the `canboat server` daemon opens).
///
/// [`Bridge::new`](bridge::Bridge::new) builds the core;
/// [`Bridge::decoded`](bridge::Bridge::decoded) taps the decoded stream,
/// [`Bridge::serve`](bridge::Bridge::serve) opens the TCP ports, and
/// [`Bridge::spawn`](bridge::Bridge::spawn) (or the blocking
/// [`Bridge::run`](bridge::Bridge::run)) starts the bus.
/// [`BridgeConfig`](bridge::BridgeConfig) is the plain, clap-free config;
/// [`Quirk`](bridge::Quirk) selects a bus value-add.
///
/// **Backend selection.** The bus source is the gateway in
/// [`BridgeConfig::device`](bridge::BridgeConfig::device), a
/// [`Device`](crate::bus::Device) like any other, which the bridge opens with
/// reconnect; or, without one, `canboat_csv`, `replay` or stdin. So to run
/// off an NGT-1:
///
/// ```
/// # use canboat::bridge::{BridgeConfig, Device, Kind};
/// let config = BridgeConfig {
/// device: Some(Device::new(Kind::NGT1, "/dev/ttyUSB0")),
/// ..BridgeConfig::default()
/// };
/// ```
///
/// The `scx20` and `motion` quirks need a gateway where canboat is the node
/// (SocketCAN, a CANalyst-II, a USB-CAN-A) — they preserve a frame's source
/// address, which the other gateways rewrite on write — so
/// [`Bridge::new`](bridge::Bridge::new) rejects them on other backends; `wmm`
/// works on any writable backend.
///
/// ```no_run
/// use canboat::bridge::{Bridge, BridgeConfig, Device, Kind};
///
/// # fn main() -> anyhow::Result<()> {
/// // Own a SocketCAN interface, tap the decoded stream, and re-serve the
/// // 2597–2607 TCP ports so other LAN consumers keep working. With the
/// // `mdns` feature and `mdns: true`, `serve` also advertises them as
/// // `_canboat._tcp`.
/// let config = BridgeConfig {
/// device: Some(Device::new(Kind::SocketCan, "can0")),
/// ..BridgeConfig::default()
/// };
///
/// let mut bridge = Bridge::new(config)?;
/// let decoded = bridge.decoded(); // Receiver<Arc<DecodedPgn>>
/// bridge.serve()?;
/// bridge.spawn()?; // pipeline runs on a background thread
///
/// for pgn in decoded.iter() {
/// println!("{} from {}", pgn.pgn, pgn.src);
/// }
/// bridge.wait();
/// # Ok(())
/// # }
/// ```
// ───────────────────────────── json input ────────────────────────────────
/// Analyzer/canboatjs JSON records → wire frames (`convert --from json`,
/// the gateway bridges' stdin TX, and the wasm bindings). Behind its own
/// feature because it is the one place a real JSON parser (serde_json)
/// is warranted.
// ─────────────────────────────── prelude ─────────────────────────────────
/// The 90% path in one glob import: `use canboat::prelude::*;`.