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
// (C) 2009-2026, Kees Verruijt, Harlingen, The Netherlands.

//! PGN database — static, embedded at compile time.
//!
//! The database is generated by `build.rs` from the repository's own
//! `database/*.yaml`
//! from `database/*.yaml` (via keel) and lives in [`crate::engine::schema_data`].
//! Callers get a `&'static PgnDatabase` via [`PgnDatabase::embedded`];
//! there is no runtime JSON parser, no `load(path)`, no `LoadOptions`.

use crate::engine::schema_data;
use crate::engine::types::{
    BitLookupTable, FieldInfo, FieldRef, IndirectLookupTable, LookupFieldTypeTable,
    LookupFieldTypeValue, LookupTable, PgnInfo,
};

/// The canboat PGN database — a thin wrapper around the build-time
/// generated static schema tables.
///
/// One instance is exposed via [`Self::embedded`]; constructing your
/// own is not supported (and not useful — the data is hard-coded).
pub struct PgnDatabase {
    pub schema_version: &'static str,
    pub version: &'static str,
    /// FNV-1a/64 content hash of the schema source (the whole
    /// `database/**` YAML tree, `database/j1939/` included), emitted by
    /// keel. Two processes that exchange field indices must share this
    /// exact value — plus [`Self::units`] and [`Self::is_j1939`], the
    /// other two components of the database identity — before either
    /// can trust the other's per-field `order` numbers.
    pub schema_hash: u64,

    /// Which unit system this database presents (see [`Units`]). The
    /// schema hash is identical for both, so anything exchanging decoded
    /// *values* (not raw bits) across processes must also agree on this.
    units: Units,

    /// Which schema flavor this database's `pgns` array came from. The
    /// schema hash covers the whole database tree and is identical for
    /// both flavors, so anything exchanging field *indices* across
    /// processes must agree on `(schema_hash, units, flavor)` — the
    /// same index resolves to different PGNs in the two tables.
    protocol: crate::engine::BusProtocol,

    pgns: &'static [PgnInfo],
    /// `(pgn_number, indices_into_pgns)`, sorted by `pgn_number` for
    /// O(log n) lookup. The variant list per PGN preserves canboat.json
    /// declaration order.
    pgn_index: &'static [(u32, &'static [u32])],

    lookups: &'static [LookupTable],
    bit_lookups: &'static [BitLookupTable],
    indirect_lookups: &'static [IndirectLookupTable],
    field_type_lookups: &'static [LookupFieldTypeTable],

    /// Generated variant dispatch for this database's PGN table. Each
    /// schema flavor (NMEA 2000, J1939) emits its own — the returned
    /// index is only meaningful against `pgns`, so the two must never
    /// be mixed.
    pub(crate) dispatch: fn(u32, &[u8]) -> Option<usize>,
    /// Generated `Fallback: true` catch-all search for `pgns`.
    pub(crate) catchall: fn(u32) -> Option<usize>,
}

/// Unit system a [`PgnDatabase`] presents its numeric fields in.
///
/// canboat's schema is generated in two forms at build time (they share
/// everything but the ~150 fields whose unit differs, and all strings),
/// so this is a zero-cost choice of which static table you decode /
/// encode against — not a runtime conversion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum Units {
    /// Strict SI base units: `rad`, `K`, `Pa`, `C` (coulomb). What a
    /// physics-facing consumer (Signal K, control code) wants — and
    /// therefore **the default**. Matches `--units si` (canboat C's
    /// `analyzer -si`).
    #[default]
    Si,
    /// canboat's practical humanized units: `deg`, `°C`, `bar`, `Ah`.
    /// What a human reads; matches `--units metric`, i.e. canboat C's
    /// `analyzer` without `-si`. Was the default before the Rust
    /// binaries standardised on SI.
    Metric,
}

// Version constants always come from the main schema: SCHEMA_HASH
// already covers the whole database tree, `database/j1939/` included.
// The PGN table, its index, the generated dispatch/catchall *and* the
// lookup tables vary per flavor - the two trees draw on different
// manufacturer registries (MANUFACTURER_CODE vs J1939_MANUFACTURER_CODE),
// so each module carries only the enumerations its own PGNs reference.
macro_rules! embedded_db {
    ($flavor:ident, $pgns:ident, $ft_lookups:ident, $units:expr, $protocol:expr) => {
        PgnDatabase {
            schema_version: schema_data::SCHEMA_VERSION,
            version: schema_data::VERSION,
            schema_hash: schema_data::SCHEMA_HASH,
            units: $units,
            protocol: $protocol,
            pgns: crate::engine::$flavor::$pgns,
            pgn_index: crate::engine::$flavor::PGN_INDEX,
            lookups: crate::engine::$flavor::LOOKUPS,
            bit_lookups: crate::engine::$flavor::BIT_LOOKUPS,
            indirect_lookups: crate::engine::$flavor::INDIRECT_LOOKUPS,
            field_type_lookups: crate::engine::$flavor::$ft_lookups,
            dispatch: crate::engine::$flavor::dispatch,
            catchall: crate::engine::$flavor::find_catchall,
        }
    };
}

static EMBEDDED_SI: PgnDatabase = embedded_db!(
    schema_data,
    PGNS_SI,
    FIELD_TYPE_LOOKUPS_SI,
    Units::Si,
    crate::engine::BusProtocol::Nmea2000
);
static EMBEDDED_METRIC: PgnDatabase = embedded_db!(
    schema_data,
    PGNS_METRIC,
    FIELD_TYPE_LOOKUPS_METRIC,
    Units::Metric,
    crate::engine::BusProtocol::Nmea2000
);
static EMBEDDED_J1939_SI: PgnDatabase = embedded_db!(
    schema_data_j1939,
    PGNS_SI,
    FIELD_TYPE_LOOKUPS_SI,
    Units::Si,
    crate::engine::BusProtocol::J1939
);
static EMBEDDED_J1939_METRIC: PgnDatabase = embedded_db!(
    schema_data_j1939,
    PGNS_METRIC,
    FIELD_TYPE_LOOKUPS_METRIC,
    Units::Metric,
    crate::engine::BusProtocol::J1939
);
static EMBEDDED_QUICK_SI: PgnDatabase = embedded_db!(
    schema_data_quick,
    PGNS_SI,
    FIELD_TYPE_LOOKUPS_SI,
    Units::Si,
    crate::engine::BusProtocol::Quick
);
static EMBEDDED_QUICK_METRIC: PgnDatabase = embedded_db!(
    schema_data_quick,
    PGNS_METRIC,
    FIELD_TYPE_LOOKUPS_METRIC,
    Units::Metric,
    crate::engine::BusProtocol::Quick
);

impl PgnDatabase {
    /// The build-time embedded database in the requested [`Units`].
    #[inline]
    pub fn embedded(units: Units) -> &'static Self {
        match units {
            Units::Si => &EMBEDDED_SI,
            Units::Metric => &EMBEDDED_METRIC,
        }
    }

    /// The build-time embedded **J1939** database — the Rust mirror of
    /// the C `analyzer-j1939` tables, generated from
    /// `database/j1939/pgns/`. Decoding against it is exclusive:
    /// J1939-only PGNs (EEC1, DTCs, …) resolve here and nowhere else,
    /// and NMEA-2000-only PGNs deliberately do not. The ISO PGNs both
    /// buses share (address claim, requests, TP) are present in both
    /// flavors.
    #[inline]
    pub fn embedded_j1939(units: Units) -> &'static Self {
        match units {
            Units::Si => &EMBEDDED_J1939_SI,
            Units::Metric => &EMBEDDED_J1939_METRIC,
        }
    }

    /// The build-time embedded **Quick PCS** database, generated from
    /// `database/quick/pgns/`: 11-bit message types, carried as the frame's
    /// `pgn`. Like the J1939 one, decoding against it is exclusive.
    #[inline]
    pub fn embedded_quick(units: Units) -> &'static Self {
        match units {
            Units::Si => &EMBEDDED_QUICK_SI,
            Units::Metric => &EMBEDDED_QUICK_METRIC,
        }
    }

    /// The unit system this database decodes into.
    #[inline]
    pub fn units(&self) -> Units {
        self.units
    }

    /// True when this database carries the J1939 PGN tables. Part of
    /// the database identity alongside [`Self::units`] and
    /// `schema_hash` — the flavors share the hash but not the index
    /// space.
    #[inline]
    pub fn is_j1939(&self) -> bool {
        self.protocol == crate::engine::BusProtocol::J1939
    }

    /// The protocol whose PGN tables this database carries.
    #[inline]
    pub fn protocol(&self) -> crate::engine::BusProtocol {
        self.protocol
    }

    /// Total number of PGN definitions (including manufacturer variants).
    pub fn pgn_count(&self) -> usize {
        self.pgns.len()
    }

    /// Iterate over every PGN definition in load order.
    pub fn pgns(&self) -> std::slice::Iter<'static, PgnInfo> {
        let pgns: &'static [PgnInfo] = self.pgns;
        pgns.iter()
    }

    /// This db's `&'static` PGN slice — the SI or Metric array. Internal:
    /// the schema-index dispatch resolves against it (see
    /// [`crate::engine::decode::PgnDatabase::pick_variant`]).
    pub(crate) fn pgn_slice(&self) -> &'static [PgnInfo] {
        self.pgns
    }

    /// Iterator over every definition for a given PGN number.
    pub fn pgn_variants(&self, pgn: u32) -> PgnVariants {
        let index: &'static [(u32, &'static [u32])] = self.pgn_index;
        let pgns: &'static [PgnInfo] = self.pgns;
        let slice: &'static [u32] = match index.binary_search_by_key(&pgn, |&(p, _)| p) {
            Ok(i) => index[i].1,
            Err(_) => &[],
        };
        PgnVariants {
            inner: slice.iter(),
            pgns,
        }
    }

    /// First definition for a PGN number, or `None`.
    pub fn first_pgn(&self, pgn: u32) -> Option<&'static PgnInfo> {
        match self.pgn_index.binary_search_by_key(&pgn, |&(p, _)| p) {
            Ok(i) => self.pgn_index[i].1.first().map(|&j| &self.pgns[j as usize]),
            Err(_) => None,
        }
    }

    /// The definitions of a PGN number that are not a range catch-all,
    /// in order: what canboat's `searchForPgn` (analyzer/pgn.c) starts
    /// from, as it steps past a catch-all listed first. 126720's is, so
    /// a 126208 parameter list for 126720 is matched against the
    /// manufacturer variants.
    pub(crate) fn specific_variants(&self, pgn: u32) -> impl Iterator<Item = &'static PgnInfo> {
        self.pgn_variants(pgn).filter(|p| p.fallback != Some(true))
    }

    /// First definition whose `Id` field matches `id` (e.g.
    /// `"cogSogRapidUpdate"`). O(n) linear scan — call once at startup
    /// and cache the resulting `&'static PgnInfo`.
    pub fn pgn_by_id(&self, id: &str) -> Option<&'static PgnInfo> {
        self.pgns.iter().find(|p| p.id == id)
    }

    /// Start encoding a message for the PGN with this schema id (e.g.
    /// `"isoRequest"`, `"windData"`). See [`crate::engine::encode`].
    pub fn encode(
        &'static self,
        pgn_id: &str,
    ) -> Result<crate::engine::encode::PgnBuilder, crate::engine::encode::EncodeError> {
        let pgn = self
            .pgn_by_id(pgn_id)
            .ok_or_else(|| crate::engine::encode::EncodeError::NoSuchPgnId(pgn_id.to_string()))?;
        Ok(crate::engine::encode::PgnBuilder::for_pgn(self, pgn))
    }

    /// Start encoding a message for a generated PGN constant
    /// (`crate::engine::pgn::WIND_DATA`) — the compile-checked counterpart
    /// to [`Self::encode`]. The constant points at the SI schema array,
    /// so this re-resolves it by `id` against this database's own arrays,
    /// meaning field scaling happens in this db's [`Units`].
    pub fn encode_for(&'static self, pgn: &'static PgnInfo) -> crate::engine::encode::PgnBuilder {
        let resolved = self.pgn_by_id(pgn.id).unwrap_or(pgn);
        crate::engine::encode::PgnBuilder::for_pgn(self, resolved)
    }

    /// Start encoding a message by PGN number. Returns
    /// [`crate::engine::encode::EncodeError::AmbiguousPgn`] when the number has
    /// more than one schema variant — use [`Self::encode`] with the id.
    pub fn encode_by_pgn(
        &'static self,
        pgn: u32,
    ) -> Result<crate::engine::encode::PgnBuilder, crate::engine::encode::EncodeError> {
        let mut variants = self.pgn_variants(pgn);
        let first = variants
            .next()
            .ok_or(crate::engine::encode::EncodeError::NoSuchPgn(pgn))?;
        let extra = variants.count();
        if extra > 0 {
            return Err(crate::engine::encode::EncodeError::AmbiguousPgn {
                pgn,
                variants: extra + 1,
            });
        }
        Ok(crate::engine::encode::PgnBuilder::for_pgn(self, first))
    }

    /// Resolve a (PGN id, field id) pair into a [`FieldRef`] that later
    /// indexes into [`crate::engine::DecodedPgn`] at `O(1)` via
    /// [`crate::engine::DecodedPgn::field`]. Both inputs are canboat-json `Id`
    /// values (camelCase machine identifiers, e.g.
    /// `("isoAddressClaim", "uniqueNumber")`). The infallible,
    /// compile-checked counterpart is the generated `field::…` constant,
    /// which is itself a `FieldRef`.
    pub fn field(&self, pgn_id: &str, field_id: &str) -> Option<FieldRef> {
        let info = self.pgn_by_id(pgn_id)?;
        let f = info.fields.iter().find(|f| f.id == field_id)?;
        Some(FieldRef {
            pgn: info,
            field: f,
        })
    }

    /// Find a catch-all "fallback" PGN definition for an unknown `pgn`.
    /// Mirrors canboat's `searchForUnknownPgn`: the largest entry with
    /// `Fallback: true` whose pgn number is `<= pgn`. O(log n) via the
    /// build-time sparse fallback table.
    pub fn fallback_pgn(&self, pgn: u32) -> Option<&'static PgnInfo> {
        // The catch-all search returns a schema index shared by both
        // unit arrays of this db's flavor; resolve it against its own
        // `pgns`.
        Some(&self.pgns[(self.catchall)(pgn)?])
    }

    /// Look up an enum table by name (e.g. `"MANUFACTURER_CODE"`).
    pub fn lookup(&self, name: &str) -> Option<&'static LookupTable> {
        match self.lookups.binary_search_by(|t| t.name.cmp(name)) {
            Ok(i) => Some(&self.lookups[i]),
            Err(_) => None,
        }
    }

    /// Look up a bit-flag table by name.
    pub fn bit_lookup(&self, name: &str) -> Option<&'static BitLookupTable> {
        match self.bit_lookups.binary_search_by(|t| t.name.cmp(name)) {
            Ok(i) => Some(&self.bit_lookups[i]),
            Err(_) => None,
        }
    }

    /// Resolve `(value1, value2)` through an INDIRECT_LOOKUP table.
    pub fn indirect_lookup(&self, name: &str, value1: u64, value2: u64) -> Option<&'static str> {
        let table = match self.indirect_lookups.binary_search_by(|t| t.name.cmp(name)) {
            Ok(i) => &self.indirect_lookups[i],
            Err(_) => return None,
        };
        table.get(value1, value2).map(|v| v.name)
    }

    /// Resolve a DYNAMIC_FIELD_KEY value through a
    /// LookupFieldTypeEnumeration.
    pub fn field_type_lookup(&self, name: &str, key: u64) -> Option<&'static LookupFieldTypeValue> {
        let table = match self
            .field_type_lookups
            .binary_search_by(|t| t.name.cmp(name))
        {
            Ok(i) => &self.field_type_lookups[i],
            Err(_) => return None,
        };
        table.get(key)
    }

    /// Reverse of [`Self::field_type_lookup`]: resolve a DYNAMIC_FIELD_KEY
    /// *label* (e.g. "Polar Performance") to its entry. Lets a config layer
    /// pre-resolve a human key name to its stable numeric `value` once, then
    /// match records by that number at runtime — robust against decode/wire
    /// name-resolution gaps that a name match would silently miss. Linear
    /// over the (small) table; intended for load-time use, not the hot path.
    pub fn field_type_lookup_by_name(
        &self,
        name: &str,
        value_name: &str,
    ) -> Option<&'static LookupFieldTypeValue> {
        let table = match self
            .field_type_lookups
            .binary_search_by(|t| t.name.cmp(name))
        {
            Ok(i) => &self.field_type_lookups[i],
            Err(_) => return None,
        };
        table.values.iter().find(|v| v.name == value_name)
    }
}

/// Iterator returned by [`PgnDatabase::pgn_variants`]. Walks the
/// index slice for a single PGN number, yielding `&'static PgnInfo`
/// for each variant.
pub struct PgnVariants {
    inner: std::slice::Iter<'static, u32>,
    pgns: &'static [PgnInfo],
}

impl Iterator for PgnVariants {
    type Item = &'static PgnInfo;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|&i| &self.pgns[i as usize])
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl ExactSizeIterator for PgnVariants {}

// Silence unused-import warnings when downstream callers don't touch
// these accessor types directly. They're part of the public API but
// only appear in return types.
#[allow(dead_code)]
fn _api_anchor(_: &FieldInfo) {}