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
//! Types for blackbox log data frames.

#[macro_use]
mod trace_field;

pub(crate) mod gps;
pub(crate) mod gps_home;
pub(crate) mod main;
pub(crate) mod slow;

use alloc::borrow::ToOwned;
use alloc::format;
use alloc::vec::Vec;
use core::fmt;
use core::iter::{FusedIterator, Peekable};
use core::marker::PhantomData;

pub use self::gps::{GpsFrame, GpsFrameDef, GpsUnit, GpsValue};
pub(crate) use self::gps_home::{GpsHomeFrame, GpsPosition};
pub use self::main::{MainFrame, MainFrameDef, MainUnit, MainValue};
pub use self::slow::{SlowFrame, SlowFrameDef, SlowUnit, SlowValue};
use crate::filter::AppliedFilter;
use crate::headers::{ParseError, ParseResult};
use crate::parser::{Encoding, InternalResult};
use crate::predictor::{Predictor, PredictorContext};
use crate::units::prelude::*;
use crate::{units, Reader};

mod seal {
    pub trait Sealed {}
}

/// A parsed data frame definition.
///
/// **Note:** All methods exclude any required metadata fields. See each frame's
/// definition struct documentation for a list.
pub trait FrameDef<'data>: seal::Sealed {
    type Unit: Into<Unit>;

    /// Returns the number of fields in the frame.
    fn len(&self) -> usize;

    /// Returns `true` if the frame is empty, or none of its fields satisfy
    /// the configured filter.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns a field definition by its index.
    fn get<'def>(&'def self, index: usize) -> Option<FieldDef<'data, Self::Unit>>
    where
        'data: 'def;

    /// Iterates over all field definitions in order.
    fn iter<'def>(&'def self) -> FieldDefIter<'data, 'def, Self>
    where
        Self: Sized,
    {
        FieldDefIter {
            frame: self,
            next: 0,
            _data: &PhantomData,
        }
    }
}

/// Metadata describing one field.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct FieldDef<'data, U> {
    pub name: &'data str,
    pub unit: U,
    pub signed: bool,
}

#[derive(Debug)]
pub struct FieldDefIter<'data, 'def, F> {
    frame: &'def F,
    next: usize,
    _data: &'data PhantomData<()>,
}

impl<'data, F: FrameDef<'data>> Iterator for FieldDefIter<'data, '_, F> {
    type Item = FieldDef<'data, F::Unit>;

    fn next(&mut self) -> Option<Self::Item> {
        let value = self.frame.get(self.next)?;
        self.next += 1;
        Some(value)
    }
}

impl<'data, F: FrameDef<'data>> FusedIterator for FieldDefIter<'data, '_, F> {}

/// A parsed data frame.
///
/// **Note:** All methods exclude any required metadata fields. Those can be
/// accessed by the inherent methods on each frame struct.
pub trait Frame: seal::Sealed {
    type Value: Into<Value>;

    /// Returns the number of fields in the frame.
    fn len(&self) -> usize;

    /// Returns `true` if the frame is empty, or none of its fields satisfy
    /// the configured filter.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the raw bits of the parsed value of a field by its index.
    ///
    /// This ignores the signedness of the field. That can be retrieved from the
    /// field definition returned by [`FrameDef::get`].
    ///
    /// **Note:** Unlike the `--raw` flag for `blackbox_decode`, this does apply
    /// predictors. This method only skips converting the value into its proper
    /// units.
    fn get_raw(&self, index: usize) -> Option<u32>;

    // Iterates over all raw field values in order. See [`Frame::get_raw`].
    fn iter_raw(&self) -> RawFieldIter<'_, Self>
    where
        Self: Sized,
    {
        RawFieldIter {
            frame: self,
            next: 0,
        }
    }

    /// Gets the value of a field by its index.
    fn get(&self, index: usize) -> Option<Self::Value>;

    /// Iterates over all field values in order.
    fn iter(&self) -> FieldIter<'_, Self>
    where
        Self: Sized,
    {
        FieldIter {
            frame: self,
            next: 0,
        }
    }
}

/// An iterator over the raw values of the fields of a parsed frame. See
/// [`Frame::iter_raw`].
#[derive(Debug)]
pub struct RawFieldIter<'f, F> {
    frame: &'f F,
    next: usize,
}

impl<F: Frame> Iterator for RawFieldIter<'_, F> {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        let value = self.frame.get_raw(self.next)?;
        self.next += 1;
        Some(value)
    }
}

impl<F: Frame> FusedIterator for RawFieldIter<'_, F> {}

/// An iterator over the values of the fields of a parsed frame. See
/// [`Frame::iter`].
#[derive(Debug)]
pub struct FieldIter<'f, F> {
    frame: &'f F,
    next: usize,
}

impl<F: Frame> Iterator for FieldIter<'_, F> {
    type Item = F::Value;

    fn next(&mut self) -> Option<Self::Item> {
        let value = self.frame.get(self.next)?;
        self.next += 1;
        Some(value)
    }
}

impl<F: Frame> FusedIterator for FieldIter<'_, F> {}

/// A wrapper around a frame definition that applies any filter configured in
/// the [`DataParser`][crate::DataParser].
#[derive(Debug)]
pub struct FilteredFrameDef<'a, F> {
    def: &'a F,
    filter: &'a AppliedFilter,
}

impl<'a, F> FilteredFrameDef<'a, F> {
    pub(super) fn new(def: &'a F, filter: &'a AppliedFilter) -> Self {
        Self { def, filter }
    }
}

impl<F: seal::Sealed> seal::Sealed for FilteredFrameDef<'_, F> {}

impl<'data, F: FrameDef<'data>> FrameDef<'data> for FilteredFrameDef<'_, F> {
    type Unit = F::Unit;

    #[inline]
    fn len(&self) -> usize {
        self.filter.len()
    }

    fn get<'def>(&'def self, index: usize) -> Option<FieldDef<'data, Self::Unit>>
    where
        'data: 'def,
    {
        let index = self.filter.get(index)?;
        self.def.get(index)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum FrameKind {
    Event,
    Data(DataFrameKind),
}

impl FrameKind {
    pub(crate) const fn from_byte(byte: u8) -> Option<Self> {
        match byte {
            b'E' => Some(Self::Event),
            _ => {
                if let Some(kind) = DataFrameKind::from_byte(byte) {
                    Some(Self::Data(kind))
                } else {
                    None
                }
            }
        }
    }
}

impl From<FrameKind> for char {
    fn from(kind: FrameKind) -> Self {
        match kind {
            FrameKind::Event => 'E',
            FrameKind::Data(kind) => kind.into(),
        }
    }
}

impl From<FrameKind> for u8 {
    fn from(kind: FrameKind) -> Self {
        match kind {
            FrameKind::Event => b'E',
            FrameKind::Data(kind) => kind.into(),
        }
    }
}

impl fmt::Display for FrameKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Event => f.write_str("event"),
            Self::Data(kind) => kind.fmt(f),
        }
    }
}

byte_enum! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    #[cfg_attr(feature = "_serde", derive(serde::Serialize))]
    #[repr(u8)]
    pub enum DataFrameKind {
        Intra = b'I',
        Inter = b'P',
        Gps = b'G',
        GpsHome = b'H',
        Slow = b'S',
    }
}

impl DataFrameKind {
    pub(crate) fn from_letter(s: &str) -> Option<Self> {
        match s {
            "G" => Some(Self::Gps),
            "H" => Some(Self::GpsHome),
            "I" => Some(Self::Intra),
            "P" => Some(Self::Inter),
            "S" => Some(Self::Slow),
            _ => None,
        }
    }
}

impl From<DataFrameKind> for char {
    fn from(kind: DataFrameKind) -> Self {
        match kind {
            DataFrameKind::Gps => 'G',
            DataFrameKind::GpsHome => 'H',
            DataFrameKind::Intra => 'I',
            DataFrameKind::Inter => 'P',
            DataFrameKind::Slow => 'S',
        }
    }
}

impl fmt::Display for DataFrameKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let kind = match self {
            Self::Intra => "intra",
            Self::Inter => "inter",
            Self::Gps => "GPS",
            Self::GpsHome => "GPS home",
            Self::Slow => "slow",
        };

        f.write_str(kind)
    }
}

trait FieldDefDetails<'data> {
    fn name(&self) -> &'data str;
    fn predictor(&self) -> Predictor;
    fn encoding(&self) -> Encoding;
    fn signed(&self) -> bool;
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "_serde", derive(serde::Serialize))]
pub enum Unit {
    Amperage,
    Voltage,
    Acceleration,
    Rotation,
    FlightMode,
    State,
    FailsafePhase,
    GpsCoordinate,
    Altitude,
    Velocity,
    GpsHeading,
    Boolean,
    Unitless,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Value {
    Amperage(ElectricCurrent),
    Voltage(ElectricPotential),
    Acceleration(Acceleration),
    Rotation(AngularVelocity),
    FlightMode(units::FlightModeSet),
    State(units::StateSet),
    FailsafePhase(units::FailsafePhase),
    Boolean(bool),
    GpsCoordinate(f64),
    Altitude(Length),
    Velocity(Velocity),
    GpsHeading(f64),
    Unsigned(u32),
    Signed(i32),
}

pub(crate) fn is_frame_def_header(header: &str) -> bool {
    parse_frame_def_header(header).is_some()
}

pub(crate) fn parse_frame_def_header(header: &str) -> Option<(DataFrameKind, DataFrameProperty)> {
    let header = header.strip_prefix("Field ")?;
    let (kind, property) = header.split_once(' ')?;

    Some((
        DataFrameKind::from_letter(kind)?,
        DataFrameProperty::from_name(property)?,
    ))
}

// TODO: width?
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DataFrameProperty {
    Name,
    Predictor,
    Encoding,
    Signed,
}

impl DataFrameProperty {
    pub(crate) fn from_name(s: &str) -> Option<Self> {
        match s {
            "name" => Some(Self::Name),
            "predictor" => Some(Self::Predictor),
            "encoding" => Some(Self::Encoding),
            "signed" => Some(Self::Signed),
            _ => None,
        }
    }
}

fn missing_header_error(kind: DataFrameKind, property: &'static str) -> ParseError {
    tracing::error!("missing header `Field {} {property}`", char::from(kind));
    ParseError::MissingHeader
}

fn parse_names(
    kind: DataFrameKind,
    names: Option<&str>,
) -> ParseResult<impl Iterator<Item = &'_ str>> {
    let names = names.ok_or_else(|| missing_header_error(kind, "name"))?;
    Ok(names.split(','))
}

fn parse_enum_list<'a, T>(
    kind: DataFrameKind,
    property: &'static str,
    s: Option<&'a str>,
    parse: impl Fn(&str) -> Option<T> + 'a,
) -> ParseResult<impl Iterator<Item = ParseResult<T>> + 'a> {
    let s = s.ok_or_else(|| missing_header_error(kind, property))?;
    Ok(s.split(',').map(move |s| {
        parse(s).ok_or_else(|| ParseError::InvalidHeader {
            header: format!("Field {} {property}", char::from(kind)),
            value: s.to_owned(),
        })
    }))
}

#[inline]
fn parse_predictors(
    kind: DataFrameKind,
    predictors: Option<&'_ str>,
) -> ParseResult<impl Iterator<Item = ParseResult<Predictor>> + '_> {
    parse_enum_list(kind, "predictor", predictors, Predictor::from_num_str)
}

#[inline]
fn parse_encodings(
    kind: DataFrameKind,
    encodings: Option<&'_ str>,
) -> ParseResult<impl Iterator<Item = ParseResult<Encoding>> + '_> {
    parse_enum_list(kind, "encoding", encodings, Encoding::from_num_str)
}

fn parse_signs(
    kind: DataFrameKind,
    names: Option<&str>,
) -> ParseResult<impl Iterator<Item = bool> + '_> {
    let names = names.ok_or_else(|| missing_header_error(kind, "signed"))?;
    Ok(names.split(',').map(|s| s.trim() != "0"))
}

fn count_fields_with_same_encoding(
    fields: &mut Peekable<impl Iterator<Item = Encoding>>,
    max: usize,
    encoding: Encoding,
) -> usize {
    let mut extra = 0;
    while extra < max && fields.next_if_eq(&encoding).is_some() {
        extra += 1;
    }
    extra
}

fn read_field_values<T>(
    data: &mut Reader,
    fields: &[T],
    get_encoding: impl Fn(&T) -> Encoding,
) -> InternalResult<Vec<u32>> {
    let mut encodings = fields.iter().map(get_encoding).peekable();
    let mut values = Vec::with_capacity(encodings.len());

    while let Some(encoding) = encodings.next() {
        let extra = encoding.max_chunk_size() - 1;
        let extra = count_fields_with_same_encoding(&mut encodings, extra, encoding);

        encoding.decode_into(data, extra, &mut values)?;
    }

    debug_assert_eq!(values.len(), fields.len());

    Ok(values)
}

fn parse_impl<'data, F: FieldDefDetails<'data>>(
    mut ctx: PredictorContext<'_, 'data>,
    raw: &[u32],
    fields: impl IntoIterator<Item = F>,
    update_ctx: impl Fn(&mut PredictorContext<'_, 'data>, usize),
) -> Vec<u32> {
    let mut values = Vec::with_capacity(raw.len());

    for (i, field) in fields.into_iter().enumerate() {
        let encoding = field.encoding();
        let predictor = field.predictor();

        let raw = raw[i];
        let signed = encoding.is_signed();

        update_ctx(&mut ctx, i);

        trace_field!(pre, field = field, enc = encoding, raw = raw);

        let value = predictor.apply(raw, signed, Some(&values), &ctx);
        values.push(value);

        trace_field!(
            post,
            field = field,
            pred = predictor,
            final = value
        );
    }

    values
}