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
use core::str;

use nom::{
    bytes::complete::{take, take_until},
    character::complete::char,
    combinator::map_res,
    sequence::preceded,
    IResult,
};

use cfg_if::cfg_if;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::{sentences::*, Error, SentenceType};

/// The maximum message length parsable by the crate.
///
/// From `gpsd`:
///
/// > We've had reports that on the Garmin GPS-10 the device sometimes
/// (1:1000 or so) sends garbage packets that have a valid checksum
/// but are like 2 successive NMEA packets merged together in one
/// with some fields lost. Usually these are much longer than the
/// legal limit for NMEA, so we can cope by just tossing out overlong
/// packets.  This may be a generic bug of all Garmin chipsets.
/// NMEA 3.01, Section 5.3 says the max sentence length shall be
/// 82 chars, including the leading $ and terminating \r\n.
///
/// > Some receivers (TN-200, GSW 2.3.2) emit oversized sentences.
/// The Trimble BX-960 receiver emits a 91-character GGA message.
/// The current hog champion is the Skytraq S2525F8 which emits
/// a 100-character PSTI message.
pub const SENTENCE_MAX_LEN: usize = 102;

/// Maximum length of a single waypoint id data in sentence
pub const TEXT_PARAMETER_MAX_LEN: usize = 64;

/// A known and parsable Nmea sentence type.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct NmeaSentence<'a> {
    pub talker_id: &'a str,
    pub message_id: SentenceType,
    pub data: &'a str,
    pub checksum: u8,
}

impl<'a> NmeaSentence<'a> {
    pub fn calc_checksum(&self) -> u8 {
        checksum(
            self.talker_id
                .as_bytes()
                .iter()
                .chain(self.message_id.as_str().as_bytes())
                .chain(&[b','])
                .chain(self.data.as_bytes()),
        )
    }
}

pub(crate) fn checksum<'a, I: Iterator<Item = &'a u8>>(bytes: I) -> u8 {
    bytes.fold(0, |c, x| c ^ *x)
}

fn parse_hex(data: &str) -> Result<u8, &'static str> {
    u8::from_str_radix(data, 16).map_err(|_| "Failed to parse checksum as hex number")
}

fn parse_checksum(i: &str) -> IResult<&str, u8> {
    map_res(preceded(char('*'), take(2usize)), parse_hex)(i)
}

fn parse_sentence_type(i: &str) -> IResult<&str, SentenceType> {
    map_res(take(3usize), |sentence_type: &str| {
        SentenceType::try_from(sentence_type).map_err(|_| "Unknown sentence type")
    })(i)
}

fn do_parse_nmea_sentence(i: &str) -> IResult<&str, NmeaSentence> {
    let (i, talker_id) = preceded(char('$'), take(2usize))(i)?;
    let (i, message_id) = parse_sentence_type(i)?;
    let (i, _) = char(',')(i)?;
    let (i, data) = take_until("*")(i)?;
    let (i, checksum) = parse_checksum(i)?;

    Ok((
        i,
        NmeaSentence {
            talker_id,
            message_id,
            data,
            checksum,
        },
    ))
}

pub fn parse_nmea_sentence(sentence: &str) -> core::result::Result<NmeaSentence, Error<'_>> {
    if sentence.len() > SENTENCE_MAX_LEN {
        Err(Error::SentenceLength(sentence.len()))
    } else {
        Ok(do_parse_nmea_sentence(sentence)?.1)
    }
}

/// The result of parsing a single NMEA message.
#[derive(Debug, PartialEq)]
pub enum ParseResult {
    AAM(AamData),
    ALM(AlmData),
    BOD(BodData),
    BWC(BwcData),
    BWW(BwwData),
    DBK(DbkData),
    GBS(GbsData),
    GGA(GgaData),
    GLL(GllData),
    GNS(GnsData),
    GSA(GsaData),
    GSV(GsvData),
    HDT(HdtData),
    MDA(MdaData),
    MTW(MtwData),
    MWV(MwvData),
    RMC(RmcData),
    TXT(TxtData),
    VHW(VhwData),
    VTG(VtgData),
    ZDA(ZdaData),
    ZFO(ZfoData),
    ZTG(ZtgData),
    PGRMZ(PgrmzData),
    /// A message that is not supported by the crate and cannot be parsed.
    Unsupported(SentenceType),
}

impl From<&ParseResult> for SentenceType {
    fn from(parse_result: &ParseResult) -> Self {
        match parse_result {
            ParseResult::AAM(_) => SentenceType::AAM,
            ParseResult::ALM(_) => SentenceType::ALM,
            ParseResult::BOD(_) => SentenceType::BOD,
            ParseResult::BWC(_) => SentenceType::BWC,
            ParseResult::BWW(_) => SentenceType::BWW,
            ParseResult::DBK(_) => SentenceType::DBK,
            ParseResult::GBS(_) => SentenceType::GBS,
            ParseResult::GGA(_) => SentenceType::GGA,
            ParseResult::GLL(_) => SentenceType::GLL,
            ParseResult::GNS(_) => SentenceType::GNS,
            ParseResult::GSA(_) => SentenceType::GSA,
            ParseResult::GSV(_) => SentenceType::GSV,
            ParseResult::HDT(_) => SentenceType::HDT,
            ParseResult::MDA(_) => SentenceType::MDA,
            ParseResult::MTW(_) => SentenceType::MTW,
            ParseResult::MWV(_) => SentenceType::MWV,
            ParseResult::RMC(_) => SentenceType::RMC,
            ParseResult::TXT(_) => SentenceType::TXT,
            ParseResult::VHW(_) => SentenceType::VHW,
            ParseResult::VTG(_) => SentenceType::VTG,
            ParseResult::ZFO(_) => SentenceType::ZFO,
            ParseResult::ZTG(_) => SentenceType::ZTG,
            ParseResult::PGRMZ(_) => SentenceType::RMZ,
            ParseResult::ZDA(_) => SentenceType::ZDA,
            ParseResult::Unsupported(sentence_type) => *sentence_type,
        }
    }
}

/// Parse a NMEA 0183 sentence from bytes and extract data from it.
///
/// # Errors
///
/// Apart from errors returned by the message parsing itself, it will return
/// [`Error::Utf8Decoding`] when the bytes are not a valid UTF-8 string.
pub fn parse_bytes(sentence_input: &[u8]) -> Result<ParseResult, Error> {
    let string = core::str::from_utf8(sentence_input).map_err(|_err| Error::Utf8Decoding)?;

    parse_str(string)
}

/// Parse a NMEA 0183 sentence from a string slice and extract data from it.
///
/// Should not contain `\r\n` ending.
///
/// # Errors
///
/// - [`Error::ASCII`] when string contains non-ASCII characters.
pub fn parse_str(sentence_input: &str) -> Result<ParseResult, Error> {
    if !sentence_input.is_ascii() {
        return Err(Error::ASCII);
    }

    let nmea_sentence = parse_nmea_sentence(sentence_input)?;
    let calculated_checksum = nmea_sentence.calc_checksum();

    if nmea_sentence.checksum == calculated_checksum {
        // Ordered alphabetically
        match nmea_sentence.message_id {
            SentenceType::AAM => {
                cfg_if! {
                    if #[cfg(feature = "AAM")] {
                        parse_aam(nmea_sentence).map(ParseResult::AAM)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::ALM => {
                cfg_if! {
                    if #[cfg(feature = "ALM")] {
                        parse_alm(nmea_sentence).map(ParseResult::ALM)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::BOD => {
                cfg_if! {
                    if #[cfg(feature = "BOD")] {
                        parse_bod(nmea_sentence).map(ParseResult::BOD)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::BWC => {
                cfg_if! {
                    if #[cfg(feature = "BWC")] {
                        parse_bwc(nmea_sentence).map(ParseResult::BWC)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::BWW => {
                cfg_if! {
                    if #[cfg(feature = "BWW")] {
                        parse_bww(nmea_sentence).map(ParseResult::BWW)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::DBK => {
                cfg_if! {
                    if #[cfg(feature = "DBK")] {
                        parse_dbk(nmea_sentence).map(Into::into)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::GBS => {
                cfg_if! {
                    if #[cfg(feature = "GBS")] {
                        parse_gbs(nmea_sentence).map(ParseResult::GBS)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::GGA => {
                cfg_if! {
                    if #[cfg(feature = "GGA")] {
                        parse_gga(nmea_sentence).map(ParseResult::GGA)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::GLL => {
                cfg_if! {
                    if #[cfg(feature = "GLL")] {
                        parse_gll(nmea_sentence).map(ParseResult::GLL)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::GNS => {
                cfg_if! {
                    if #[cfg(feature = "GNS")] {
                        parse_gns(nmea_sentence).map(ParseResult::GNS)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::GSA => {
                cfg_if! {
                    if #[cfg(feature = "GSA")] {
                        parse_gsa(nmea_sentence).map(ParseResult::GSA)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::GSV => {
                cfg_if! {
                    if #[cfg(feature = "GSV")] {
                        parse_gsv(nmea_sentence).map(ParseResult::GSV)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::HDT => {
                cfg_if! {
                    if #[cfg(feature = "HDT")] {
                        parse_hdt(nmea_sentence).map(ParseResult::HDT)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::MDA => {
                cfg_if! {
                    if #[cfg(feature = "MDA")] {
                        parse_mda(nmea_sentence).map(ParseResult::MDA)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::MTW => {
                cfg_if! {
                    if #[cfg(feature = "MTW")] {
                        parse_mtw(nmea_sentence).map(ParseResult::MTW)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::MWV => {
                cfg_if! {
                    if #[cfg(feature = "MWV")] {
                        parse_mwv(nmea_sentence).map(ParseResult::MWV)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::RMC => {
                cfg_if! {
                    if #[cfg(feature = "RMC")] {
                        parse_rmc(nmea_sentence).map(ParseResult::RMC)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::RMZ => {
                cfg_if! {
                    if #[cfg(feature = "RMZ")] {
                        parse_pgrmz(nmea_sentence).map(ParseResult::PGRMZ)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::TXT => {
                cfg_if! {
                    if #[cfg(feature = "TXT")] {
                        parse_txt(nmea_sentence).map(ParseResult::TXT)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::VHW => {
                cfg_if! {
                    if #[cfg(feature = "VHW")] {
                        parse_vhw(nmea_sentence).map(ParseResult::VHW)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::VTG => {
                cfg_if! {
                    if #[cfg(feature = "VTG")] {
                        parse_vtg(nmea_sentence).map(ParseResult::VTG)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::ZDA => {
                cfg_if! {
                    if #[cfg(feature = "ZDA")] {
                        parse_zda(nmea_sentence).map(ParseResult::ZDA)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::ZFO => {
                cfg_if! {
                    if #[cfg(feature = "ZFO")] {
                        parse_zfo(nmea_sentence).map(ParseResult::ZFO)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            SentenceType::ZTG => {
                cfg_if! {
                    if #[cfg(feature = "ZTG")] {
                        parse_ztg(nmea_sentence).map(ParseResult::ZTG)
                    } else {
                        return Err(Error::DisabledSentence);
                    }
                }
            }
            sentence_type => Ok(ParseResult::Unsupported(sentence_type)),
        }
    } else {
        Err(Error::ChecksumMismatch {
            calculated: calculated_checksum,
            found: nmea_sentence.checksum,
        })
    }
}