Skip to main content

neo_gps/
lib.rs

1//! # neo-gps
2//!
3//! A `no_std`, zero-allocation driver for the u-blox NEO-xM GPS family
4//! (NEO-6M, NEO-7M, NEO-8M, NEO-M9N, NEO-M10) over UART. It works in both
5//! async (`async` feature, the default) and blocking (`sync` feature) code.
6//!
7//! ## Example
8//!
9//! ```ignore
10//! use neo_gps::NeoGps;
11//!
12//! let uart = BufferedUart::new(/* ... */); // 9600 8N1, any embedded-io-async Read + Write
13//! let mut gps = NeoGps::new(uart);
14//!
15//! loop {
16//!     let pos = gps.next_coordinate().await?; // only returns once there is a real fix
17//!     defmt::info!("lat={} lon={}", pos.lat_1e7, pos.lon_1e7); // degrees × 1e7
18//! }
19//! ```
20//!
21//! See [`NeoGps`] for configuration, and the
22//! [README](https://github.com/I-Azy-I/neo-gps) for the full feature list.
23
24#![cfg_attr(not(test), no_std)]
25#![deny(unsafe_code)]
26// Kept on so a new public item cannot ship with an empty `///` again.
27#![warn(missing_docs)]
28// Set by docs.rs (see `[package.metadata.docs.rs]`) so feature-gated items
29// carry an "Available on crate feature X" badge. Nightly-only, hence the cfg.
30#![cfg_attr(docsrs, feature(doc_cfg))]
31
32pub mod codec;
33mod deframer;
34pub mod nmea;
35pub mod ubx;
36
37#[cfg(all(feature = "sync", feature = "async"))]
38compile_error!("features `sync` and `async` are mutually exclusive; enable exactly one");
39#[cfg(not(any(feature = "sync", feature = "async")))]
40compile_error!("enable one of the `sync` (embedded-io) or `async` (embedded-io-async) features");
41
42#[cfg(all(feature = "sync", not(feature = "async")))]
43pub(crate) use embedded_io as eio;
44#[cfg(feature = "async")]
45pub(crate) use embedded_io_async as eio;
46
47use deframer::*;
48use eio::{Read, Write};
49use nmea::Sentence;
50use ubx::{UbxFrame, CLASS_CFG, CLASS_MON, CLASS_NAV};
51/// Errors produced by the driver.
52///
53/// `non_exhaustive`: new failure modes should not break your `match`.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55#[non_exhaustive]
56pub enum Error<E> {
57    /// Underlying UART error
58    Io(E),
59    /// The UART read returned 0 bytes (EOF on adapted streams).
60    Eof,
61    /// The module answered a configuration frame with `ACK-NAK`.
62    Nak {
63        /// Message class that was refused.
64        class: u8,
65        /// Message id that was refused.
66        id: u8,
67    },
68    /// No `ACK`/reply arrived within the frame budget.
69    NoReply,
70    /// The requested feature is not supported by the detected module
71    /// (e.g. `CFG-GNSS` on a NEO-6M, or a nav rate above the module maximum).
72    Unsupported,
73    /// A frame was too large for the internal buffer.
74    Overflow,
75}
76
77impl<E> From<E> for Error<E> {
78    fn from(e: E) -> Self {
79        Error::Io(e)
80    }
81}
82
83/// Module generation, derived from the `PROTVER` reported by `UBX-MON-VER`.
84///
85/// `non_exhaustive`: u-blox keeps shipping generations, and adding one here
86/// should not break your `match`.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88#[non_exhaustive]
89pub enum Generation {
90    /// NEO-6 series (protocol < 14). GPS only.
91    Series6,
92    /// NEO-7 series (protocol 14). GPS + GLONASS (not concurrent).
93    Series7,
94    /// NEO-8 series (protocol 15..=23). Concurrent multi-GNSS.
95    Series8,
96    /// M9 series (protocol 24..=33). Still speaks the legacy `CFG` messages.
97    Series9,
98    /// M10 and later (protocol >= 34). Configured only through
99    /// `CFG-VALSET`/`VALGET`, which this driver does not implement yet: see
100    /// [`Capabilities::has_legacy_cfg`].
101    Series10,
102}
103
104/// What the connected module can do. Filled by [`NeoGps::probe`],
105/// or constructed manually if the module type is known at compile time.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub struct Capabilities {
108    /// Which family the module belongs to.
109    pub generation: Generation,
110    /// u-blox protocol version, e.g. 12 (NEO-6), 15..23 (NEO-8), 32 (M10).
111    pub protocol_version: u8,
112}
113
114impl Capabilities {
115    /// Capabilities to assume before probing: the oldest module in the family.
116    ///
117    /// # Example
118    /// ```
119    /// use neo_gps::{Capabilities, Generation};
120    /// assert_eq!(Capabilities::conservative().generation, Generation::Series6);
121    /// ```
122    pub const fn conservative() -> Self {
123        Capabilities {
124            generation: Generation::Series6,
125            protocol_version: 12,
126        }
127    }
128
129    /// Fastest navigation update interval the module sustains **in its
130    /// default constellation configuration**, in milliseconds.
131    ///
132    /// This is the number to hand to
133    /// [`set_nav_rate_ms`](NeoGps::set_nav_rate_ms) when you have not changed
134    /// which constellations are enabled. It is not always the datasheet
135    /// headline: a stock NEO-M8N tracks GPS and GLONASS together and manages
136    /// 5 Hz, though it reaches 10 Hz on one constellation. See
137    /// [`max_rate_ms_single_gnss`](Self::max_rate_ms_single_gnss).
138    ///
139    /// # Example
140    /// ```
141    /// use neo_gps::Capabilities;
142    /// assert_eq!(Capabilities::conservative().max_rate_ms(), 200); // NEO-6: 5 Hz
143    /// ```
144    pub fn max_rate_ms(&self) -> u16 {
145        match self.generation {
146            Generation::Series6 => 200,  // 5 Hz
147            Generation::Series7 => 100,  // 10 Hz
148            Generation::Series8 => 200,  // 5 Hz with the default GPS + GLONASS
149            Generation::Series9 => 40,   // 25 Hz
150            Generation::Series10 => 100, // 10 Hz with 3+ concurrent GNSS
151        }
152    }
153
154    /// Fastest navigation update interval the hardware reaches at all, which
155    /// generally means with a single constellation enabled.
156    ///
157    /// The bound [`set_nav_rate_ms`](NeoGps::set_nav_rate_ms) enforces, so a
158    /// caller who has narrowed the constellations with
159    /// [`set_constellation`](NeoGps::set_constellation) can still ask for the
160    /// full rate. Equal to [`max_rate_ms`](Self::max_rate_ms) on the
161    /// generations where the two do not differ.
162    ///
163    /// # Example
164    /// ```
165    /// use neo_gps::{Capabilities, Generation};
166    /// let m8 = Capabilities { generation: Generation::Series8, protocol_version: 18 };
167    /// assert_eq!(m8.max_rate_ms(), 200);             // stock: GPS + GLONASS
168    /// assert_eq!(m8.max_rate_ms_single_gnss(), 100); // one constellation
169    /// ```
170    pub fn max_rate_ms_single_gnss(&self) -> u16 {
171        match self.generation {
172            Generation::Series6 => 200,
173            Generation::Series7 => 100,
174            Generation::Series8 => 100, // 10 Hz on one constellation
175            Generation::Series9 => 40,
176            Generation::Series10 => 40, // 25 Hz on one constellation
177        }
178    }
179
180    /// Whether the module accepts the legacy `UBX-CFG-*` messages this driver
181    /// is built on (`CFG-MSG`, `CFG-RATE`, `CFG-PRT`, `CFG-NAV5`, `CFG-GNSS`).
182    ///
183    /// False from protocol 34 (M10) on, where the whole `CFG` class is
184    /// `CFG-CFG`, `CFG-RST` and the `CFG-VALSET`/`VALGET`/`VALDEL`
185    /// configuration interface, which this driver does not speak yet. On such
186    /// a module the affected methods return [`Error::Unsupported`] instead of
187    /// sending a frame that would be NAKed;
188    /// [`save_config`](NeoGps::save_config),
189    /// [`factory_reset`](NeoGps::factory_reset) and [`reset`](NeoGps::reset)
190    /// still work, since `CFG-CFG` and `CFG-RST` survived.
191    ///
192    /// # Example
193    /// ```
194    /// use neo_gps::{Capabilities, Generation};
195    /// let m9 = Capabilities { generation: Generation::Series9, protocol_version: 32 };
196    /// let m10 = Capabilities { generation: Generation::Series10, protocol_version: 34 };
197    /// assert!(m9.has_legacy_cfg());
198    /// assert!(!m10.has_legacy_cfg());
199    /// ```
200    pub fn has_legacy_cfg(&self) -> bool {
201        self.protocol_version < 34
202    }
203
204    /// Whether the module has `UBX-NAV-PVT`, the all-in-one binary nav
205    /// message (protocol 14 and later).
206    ///
207    /// # Example
208    /// ```
209    /// use neo_gps::{Capabilities, Generation};
210    /// let m8 = Capabilities { generation: Generation::Series8, protocol_version: 18 };
211    /// assert!(m8.has_nav_pvt());
212    /// ```
213    pub fn has_nav_pvt(&self) -> bool {
214        self.protocol_version >= 14
215    }
216
217    /// Whether the module has `UBX-NAV-SOL` (u-blox 6/7/8). Gone from
218    /// protocol 24 on, where `NAV-PVT` replaces it.
219    ///
220    /// # Example
221    /// ```
222    /// use neo_gps::Capabilities;
223    /// assert!(Capabilities::conservative().has_nav_sol()); // NEO-6: yes
224    /// ```
225    pub fn has_nav_sol(&self) -> bool {
226        self.protocol_version < 24
227    }
228
229    /// Whether the module has `UBX-NAV-SAT` for per-satellite data
230    /// (protocol 15 and later). Older modules carry the same information in
231    /// `UBX-NAV-SVINFO`; see [`has_nav_svinfo`](Self::has_nav_svinfo).
232    ///
233    /// # Example
234    /// ```
235    /// use neo_gps::{Capabilities, Generation};
236    /// let m8 = Capabilities { generation: Generation::Series8, protocol_version: 18 };
237    /// assert!(m8.has_nav_sat());
238    /// assert!(!Capabilities::conservative().has_nav_sat()); // NEO-6: SVINFO
239    /// ```
240    pub fn has_nav_sat(&self) -> bool {
241        self.protocol_version >= 15
242    }
243
244    /// Whether the module has `UBX-NAV-SVINFO`, the predecessor of
245    /// `UBX-NAV-SAT`. Removed from protocol 24 on, alongside `NAV-SOL`.
246    ///
247    /// # Example
248    /// ```
249    /// use neo_gps::Capabilities;
250    /// assert!(Capabilities::conservative().has_nav_svinfo());
251    /// ```
252    pub fn has_nav_svinfo(&self) -> bool {
253        self.protocol_version < 24
254    }
255
256    /// Whether the module has `UBX-CFG-GNSS` for constellation selection.
257    ///
258    /// Introduced with the 7 series (protocol 14); absent from the 6 series,
259    /// and gone again from protocol 34 (M10) with the rest of the legacy
260    /// `CFG` class.
261    ///
262    /// # Example
263    /// ```
264    /// use neo_gps::{Capabilities, Generation};
265    /// assert!(!Capabilities::conservative().has_cfg_gnss()); // not on NEO-6
266    /// let neo7 = Capabilities { generation: Generation::Series7, protocol_version: 14 };
267    /// assert!(neo7.has_cfg_gnss());
268    /// ```
269    pub fn has_cfg_gnss(&self) -> bool {
270        self.protocol_version >= 14 && self.has_legacy_cfg()
271    }
272}
273
274/// A parsed item from the module's output stream.
275///
276/// `non_exhaustive`: more message types get decoded over time, and adding a
277/// variant should not break your `match`.
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279#[non_exhaustive]
280pub enum Event {
281    /// A supported, checksum-valid NMEA sentence.
282    Nmea(Sentence),
283    /// A checksum-valid NMEA sentence the driver does not decode
284    /// (talker + type provided, e.g. `(b"GP", b"GSV")`).
285    NmeaOther {
286        /// Talker id, e.g. `b"GP"`.
287        talker: [u8; 2],
288        /// Sentence type, e.g. `b"GSV"`.
289        mtype: [u8; 3],
290    },
291    /// `UBX-NAV-PVT` (only after [`NeoGps::enable_nav_pvt`], 7-series and later).
292    NavPvt(ubx::NavPvt),
293    /// `UBX-NAV-POSLLH` (after [`NeoGps::enable_nav_posllh`]; all generations,
294    /// incl. NEO-6M).
295    NavPosllh(ubx::NavPosllh),
296    /// `UBX-NAV-SOL` (after [`NeoGps::enable_nav_sol`]; u-blox 6/7/8 only).
297    NavSol(ubx::NavSol),
298    /// `UBX-NAV-VELNED` (after [`NeoGps::enable_nav_velned`]; all generations).
299    NavVelned(ubx::NavVelned),
300    /// `UBX-ACK-ACK` / `UBX-ACK-NAK` for a `CFG` frame.
301    Ack {
302        /// Message class being acknowledged.
303        class: u8,
304        /// Message id being acknowledged.
305        id: u8,
306        /// `true` for `ACK-ACK`, `false` for `ACK-NAK`.
307        ok: bool,
308    },
309    /// Any other checksum-valid UBX frame.
310    UbxOther {
311        /// Message class.
312        class: u8,
313        /// Message id.
314        id: u8,
315    },
316}
317
318/// A position from [`NeoGps::next_coordinate`], in degrees * 1e7. Never the
319/// pre-fix `0, 0`.
320#[derive(Debug, Clone, Copy, PartialEq, Eq)]
321pub struct Coordinate {
322    /// Latitude, degrees * 1e7, positive north.
323    pub lat_1e7: i32,
324    /// Longitude, degrees * 1e7, positive east.
325    pub lon_1e7: i32,
326}
327
328/// Frames to read while waiting for an ACK or poll reply before giving up.
329const REPLY_FRAME_BUDGET: usize = 64;
330
331/// Driver for the NEO-xM family.
332///
333/// `S` is any `embedded-io[-async]` `Read + Write`, such as an embassy
334/// `BufferedUart` or a serial port wrapped by `embedded-io-adapters`.
335pub struct NeoGps<S> {
336    uart: S,
337    caps: Capabilities,
338    deframer: Deframer,
339    scratch: [u8; 64],
340    /// Unconsumed tail of the last UART read.
341    pending: usize,
342    pending_pos: usize,
343    /// Consecutive failed reads so far.
344    read_err_streak: u8,
345    /// How many consecutive failed reads to retry before surfacing `Io`.
346    read_error_tolerance: u8,
347
348    skip_unknown_sentences: bool,
349}
350
351/// Default for [`NeoGps::set_read_error_tolerance`].
352pub const DEFAULT_READ_ERROR_TOLERANCE: u8 = 16;
353
354#[maybe_async_cfg::maybe(sync(feature = "sync", keep_self), async(feature = "async", keep_self))]
355impl<S: Read + Write> NeoGps<S> {
356    /// Wrap a UART. Does no I/O. Capabilities start at
357    /// [`Capabilities::conservative`] until you call [`probe`](Self::probe).
358    ///
359    /// # Example
360    /// ```ignore
361    /// let mut gps = NeoGps::new(uart); // uart: impl embedded_io_async::Read + Write
362    /// ```
363    pub fn new(uart: S) -> Self {
364        NeoGps {
365            uart,
366            caps: Capabilities::conservative(),
367            deframer: Deframer::new(),
368            scratch: [0; 64],
369            pending: 0,
370            pending_pos: 0,
371            read_err_streak: 0,
372            read_error_tolerance: DEFAULT_READ_ERROR_TOLERANCE,
373            skip_unknown_sentences: true,
374        }
375    }
376
377    /// How many consecutive failed reads [`next_event`](Self::next_event)
378    /// retries before returning [`Error::Io`]. `0` propagates the first one.
379    ///
380    /// # Example
381    /// ```ignore
382    /// gps.set_read_error_tolerance(0); // propagate every UART error
383    /// ```
384    pub fn set_read_error_tolerance(&mut self, n: u8) {
385        self.read_error_tolerance = n;
386    }
387
388    /// Whether [`next_event`](Self::next_event) hides frames the driver does
389    /// not decode ([`Event::NmeaOther`] and [`Event::UbxOther`]). `true` by
390    /// default. Set it to `false` to decode them yourself from
391    /// [`last_ubx_frame`](Self::last_ubx_frame) or
392    /// [`last_nmea_line`](Self::last_nmea_line).
393    ///
394    /// # Example
395    /// ```ignore
396    /// gps.set_skip_unknown_sentences(false); // see GSV, PUBX, NAV-SAT, ...
397    /// ```
398    pub fn set_skip_unknown_sentences(&mut self, skip: bool) {
399        self.skip_unknown_sentences = skip;
400    }
401
402    /// Release the UART.
403    ///
404    /// # Example
405    /// ```ignore
406    /// let uart = gps.free();
407    /// ```
408    pub fn free(self) -> S {
409        self.uart
410    }
411
412    /// Currently assumed capabilities.
413    ///
414    /// # Example
415    /// ```ignore
416    /// let hz_max = 1000 / gps.capabilities().max_rate_ms() as u32;
417    /// ```
418    pub fn capabilities(&self) -> Capabilities {
419        self.caps
420    }
421
422    /// Set the capabilities to assume, instead of calling
423    /// [`probe`](Self::probe).
424    ///
425    /// # Example
426    /// ```ignore
427    /// gps.set_capabilities(Capabilities { generation: Generation::Series8, protocol_version: 18 });
428    /// ```
429    pub fn set_capabilities(&mut self, caps: Capabilities) {
430        self.caps = caps;
431    }
432
433    /// Read and parse the next frame from the module.
434    ///
435    /// Frames the driver does not decode are skipped unless you call
436    /// [`set_skip_unknown_sentences(false)`](Self::set_skip_unknown_sentences).
437    ///
438    /// # Example
439    /// ```ignore
440    /// while let Ok(ev) = gps.next_event().await {
441    ///     if let Event::Nmea(Sentence::Rmc(rmc)) = ev { /* rmc.lat_1e7 ... */ }
442    /// }
443    /// ```
444    pub async fn next_event(&mut self) -> Result<Event, Error<S::Error>> {
445        loop {
446            let ev = self.read_event().await?;
447            if self.skip_unknown_sentences
448                && matches!(ev, Event::NmeaOther { .. } | Event::UbxOther { .. })
449            {
450                continue;
451            }
452            return Ok(ev);
453        }
454    }
455
456    /// Read frames until one carries a position with a confirmed fix, and
457    /// return it. Everything else is discarded, so the result is never the
458    /// pre-fix `0, 0`.
459    ///
460    /// Takes it from NMEA `RMC` or `GGA` (both on by default), or from
461    /// `NAV-PVT` if you enabled it. Needs the `builtin-codec` feature, which
462    /// is on by default.
463    ///
464    /// All three sources are judged equally strictly, so it does not matter
465    /// which one arrives first: `RMC` must be status `A`, `NAV-PVT` must have
466    /// `gnssFixOK`, and `GGA` must be
467    /// [`is_gnss_fix`](crate::nmea::FixQuality::is_gnss_fix). A dead-reckoning
468    /// or simulated position is not returned; use
469    /// [`next_event`](Self::next_event) if you want those.
470    ///
471    /// # Example
472    /// ```ignore
473    /// loop {
474    ///     let pos = gps.next_coordinate().await?;
475    ///     info!("lat_1e7={} lon_1e7={}", pos.lat_1e7, pos.lon_1e7);
476    /// }
477    /// ```
478    pub async fn next_coordinate(&mut self) -> Result<Coordinate, Error<S::Error>> {
479        loop {
480            let coord = match self.read_event().await? {
481                Event::Nmea(Sentence::Rmc(rmc)) if rmc.valid => {
482                    rmc.lat_1e7.zip(rmc.lon_1e7).map(|(lat, lon)| Coordinate {
483                        lat_1e7: lat,
484                        lon_1e7: lon,
485                    })
486                }
487                Event::Nmea(Sentence::Gga(gga)) if gga.quality.is_gnss_fix() => {
488                    gga.lat_1e7.zip(gga.lon_1e7).map(|(lat, lon)| Coordinate {
489                        lat_1e7: lat,
490                        lon_1e7: lon,
491                    })
492                }
493                Event::NavPvt(pvt) if pvt.gnss_fix_ok() => Some(Coordinate {
494                    lat_1e7: pvt.lat_1e7,
495                    lon_1e7: pvt.lon_1e7,
496                }),
497                _ => None,
498            };
499            if let Some(c) = coord {
500                return Ok(c);
501            }
502        }
503    }
504
505    /// The next frame, without the
506    /// [`skip_unknown_sentences`](Self::set_skip_unknown_sentences) filter.
507    async fn read_event(&mut self) -> Result<Event, Error<S::Error>> {
508        loop {
509            // Drain bytes already read from the UART first.
510            while self.pending_pos < self.pending {
511                let b = self.scratch[self.pending_pos];
512                self.pending_pos += 1;
513                if let Some(ev) = self.deframer.push(b) {
514                    return Ok(ev);
515                }
516            }
517            let n = match self.uart.read(&mut self.scratch).await {
518                Ok(n) => {
519                    self.read_err_streak = 0;
520                    n
521                }
522                Err(e) => {
523                    // Damaged bytes make the frame in progress suspect, so
524                    // drop it rather than splice them into a length field.
525                    self.deframer.reset();
526                    self.read_err_streak = self.read_err_streak.saturating_add(1);
527                    if self.read_err_streak > self.read_error_tolerance {
528                        self.read_err_streak = 0;
529                        return Err(Error::Io(e));
530                    }
531                    continue;
532                }
533            };
534            if n == 0 {
535                // Ok(0) is end-of-stream: the port is gone, retrying spins.
536                return Err(Error::Eof);
537            }
538            self.pending = n;
539            self.pending_pos = 0;
540        }
541    }
542
543    /// Payload bytes of the most recent UBX frame from
544    /// [`next_event`](Self::next_event), for decoding messages the driver
545    /// does not wrap.
546    ///
547    /// Valid until the next UBX frame arrives. Payloads over 384 bytes are
548    /// truncated.
549    ///
550    /// # Example
551    /// ```ignore
552    /// if let Event::UbxOther { class: 0x01, id: 0x35 } = ev { // NAV-SAT
553    ///     let num_svs = gps.last_ubx_payload()[5];
554    /// }
555    /// ```
556    pub fn last_ubx_payload(&self) -> &[u8] {
557        self.deframer.last_ubx_payload()
558    }
559
560    /// The whole last UBX frame: sync bytes, header, payload, checksum. This
561    /// is what external codecs such as the `ublox` crate take. Valid for as
562    /// long as [`last_ubx_payload`](Self::last_ubx_payload).
563    ///
564    /// # Example
565    /// ```ignore
566    /// if let Event::UbxOther { .. } = ev {
567    ///     codec::ublox::decode(&mut parser, gps.last_ubx_frame(), |pkt| { /* ... */ });
568    /// }
569    /// ```
570    pub fn last_ubx_frame(&self) -> &[u8] {
571        self.deframer.last_ubx_frame()
572    }
573
574    /// Bytes of the most recent NMEA sentence from
575    /// [`next_event`](Self::next_event): the text between `$` and CR/LF,
576    /// checksum trailer included. Use it to decode sentences the driver does
577    /// not wrap (GSV, PUBX, ...) yourself or with the `nmea` crate.
578    ///
579    /// Valid until the next NMEA event.
580    ///
581    /// # Example
582    /// ```ignore
583    /// if let Event::NmeaOther { mtype, .. } = ev {
584    ///     decode_gsv(gps.last_nmea_line()); // e.g. "GPGSV,3,1,...*hh"
585    /// }
586    /// ```
587    pub fn last_nmea_line(&self) -> &[u8] {
588        self.deframer.last_nmea_line()
589    }
590
591    /// Per-satellite data from the last `NAV-SAT` or `NAV-SVINFO` frame, or
592    /// `None` if the last UBX frame was something else.
593    ///
594    /// Deliberately not an [`Event`] variant: these messages carry a few
595    /// dozen satellites, which does not belong in a `Copy` enum. The iterator
596    /// borrows the frame snapshot instead and decodes lazily, so it stays
597    /// valid until the next UBX frame arrives.
598    ///
599    /// Enable the stream with
600    /// [`enable_satellite_info`](Self::enable_satellite_info); both messages
601    /// arrive as [`Event::UbxOther`], so
602    /// [`set_skip_unknown_sentences(false)`](Self::set_skip_unknown_sentences)
603    /// is needed to see them.
604    ///
605    /// # Example
606    /// ```ignore
607    /// if let Event::UbxOther { .. } = ev {
608    ///     if let Some(sats) = gps.satellites() {
609    ///         let used = sats.filter(|s| s.used_in_fix).count();
610    ///     }
611    /// }
612    /// ```
613    pub fn satellites(&self) -> Option<ubx::Satellites<'_>> {
614        let frame = self.last_ubx_frame();
615        if frame.len() < 8 || frame[2] != CLASS_NAV {
616            return None;
617        }
618        match frame[3] {
619            ubx::NAV_SAT => ubx::Satellites::from_nav_sat(self.last_ubx_payload()),
620            ubx::NAV_SVINFO => ubx::Satellites::from_nav_svinfo(self.last_ubx_payload()),
621            _ => None,
622        }
623    }
624
625    /// Send a raw UBX frame, for messages the driver does not wrap.
626    ///
627    /// # Example
628    /// ```ignore
629    /// gps.send_ubx(0x06, 0x24, &cfg_nav5_payload).await?; // CFG-NAV5
630    /// ```
631    pub async fn send_ubx(
632        &mut self,
633        class: u8,
634        id: u8,
635        payload: &[u8],
636    ) -> Result<(), Error<S::Error>> {
637        let mut frame = UbxFrame::new(class, id);
638        if frame.extend(payload).is_none() {
639            return Err(Error::Overflow);
640        }
641        self.uart.write_all(frame.finish()).await?;
642        Ok(())
643    }
644
645    /// Send a `CFG` frame and wait for its `ACK-ACK` or `ACK-NAK`.
646    ///
647    /// Frames arriving meanwhile are discarded, so use this while
648    /// configuring, not while streaming fixes.
649    ///
650    /// # Example
651    /// ```ignore
652    /// gps.send_cfg_acked(0x24, &cfg_nav5_payload).await?; // Err(Nak{..}) if refused
653    /// ```
654    pub async fn send_cfg_acked(&mut self, id: u8, payload: &[u8]) -> Result<(), Error<S::Error>> {
655        self.send_ubx(CLASS_CFG, id, payload).await?;
656        for _ in 0..REPLY_FRAME_BUDGET {
657            match self.read_event().await? {
658                Event::Ack { class, id: aid, ok } if class == CLASS_CFG && aid == id => {
659                    return if ok {
660                        Ok(())
661                    } else {
662                        Err(Error::Nak { class, id: aid })
663                    };
664                }
665                _ => {}
666            }
667        }
668        Err(Error::NoReply)
669    }
670
671    /// Poll `UBX-MON-VER`, work out the module generation, and store it.
672    ///
673    /// Modules older than the `PROTVER` string (NEO-6) come back as
674    /// [`Generation::Series6`].
675    ///
676    /// # Example
677    /// ```ignore
678    /// let caps = gps.probe().await?; // Series6/7/8/9Plus from MON-VER
679    /// ```
680    pub async fn probe(&mut self) -> Result<Capabilities, Error<S::Error>> {
681        self.send_ubx(CLASS_MON, ubx::MON_VER, &[]).await?;
682        for i in 0..REPLY_FRAME_BUDGET {
683            // Re-poll once in case the first one was lost to line noise.
684            if i == REPLY_FRAME_BUDGET / 2 {
685                self.send_ubx(CLASS_MON, ubx::MON_VER, &[]).await?;
686            }
687            match self.read_event().await? {
688                Event::UbxOther { class, id } if class == CLASS_MON && id == ubx::MON_VER => {
689                    let protver = self.deframer.last_ubx_protver().unwrap_or(12);
690                    let generation = match protver {
691                        0..=13 => Generation::Series6,
692                        14 => Generation::Series7,
693                        15..=23 => Generation::Series8,
694                        24..=33 => Generation::Series9,
695                        _ => Generation::Series10,
696                    };
697                    self.caps = Capabilities {
698                        generation,
699                        protocol_version: protver,
700                    };
701                    return Ok(self.caps);
702                }
703                _ => {}
704            }
705        }
706        Err(Error::NoReply)
707    }
708
709    /// Set the interval between fixes, in milliseconds (1000 = 1 Hz).
710    /// Returns [`Error::Unsupported`] for rates the module cannot sustain.
711    ///
712    /// # Example
713    /// ```ignore
714    /// gps.set_nav_rate_ms(200).await?; // 5 Hz
715    /// ```
716    pub async fn set_nav_rate_ms(&mut self, ms: u16) -> Result<(), Error<S::Error>> {
717        if !self.caps.has_legacy_cfg() || ms < self.caps.max_rate_ms_single_gnss() {
718            return Err(Error::Unsupported);
719        }
720        let mut p = [0u8; 6];
721        p[0..2].copy_from_slice(&ms.to_le_bytes());
722        p[2..4].copy_from_slice(&1u16.to_le_bytes()); // navRate: 1 cycle
723        p[4..6].copy_from_slice(&1u16.to_le_bytes()); // timeRef: GPS time
724        self.send_cfg_acked(ubx::CFG_RATE, &p).await
725    }
726
727    /// Set how often a message is output on the current port (`CFG-MSG`).
728    /// `rate = 0` disables it, `1` sends it with every solution.
729    ///
730    /// # Example
731    /// ```ignore
732    /// gps.set_msg_rate(0xF0, 0x03, 5).await?; // GSV every 5th fix
733    /// ```
734    pub async fn set_msg_rate(
735        &mut self,
736        class: u8,
737        id: u8,
738        rate: u8,
739    ) -> Result<(), Error<S::Error>> {
740        if !self.caps.has_legacy_cfg() {
741            return Err(Error::Unsupported);
742        }
743        self.send_cfg_acked(ubx::CFG_MSG, &[class, id, rate]).await
744    }
745
746    /// Mute a standard NMEA sentence (class 0xF0).
747    /// `id`: 0x00 GGA, 0x01 GLL, 0x02 GSA, 0x03 GSV, 0x04 RMC, 0x05 VTG.
748    ///
749    /// # Example
750    /// ```ignore
751    /// gps.disable_nmea(0x03).await?; // mute GSV
752    /// ```
753    pub async fn disable_nmea(&mut self, id: u8) -> Result<(), Error<S::Error>> {
754        self.set_msg_rate(0xF0, id, 0).await
755    }
756
757    /// Start `UBX-NAV-PVT` output (7 series and later). Returns
758    /// [`Error::Unsupported`] on older modules.
759    ///
760    /// # Example
761    /// ```ignore
762    /// if gps.capabilities().has_nav_pvt() { gps.enable_nav_pvt().await?; }
763    /// ```
764    pub async fn enable_nav_pvt(&mut self) -> Result<(), Error<S::Error>> {
765        if !self.caps.has_nav_pvt() {
766            return Err(Error::Unsupported);
767        }
768        self.set_msg_rate(CLASS_NAV, ubx::NAV_PVT, 1).await
769    }
770
771    /// Start `UBX-NAV-VELNED` output. Every generation has it, which makes it
772    /// the way to get binary velocity out of a module with no `NAV-PVT`.
773    ///
774    /// # Example
775    /// ```ignore
776    /// gps.enable_nav_velned().await?; // binary velocity on a NEO-6M
777    /// ```
778    pub async fn enable_nav_velned(&mut self) -> Result<(), Error<S::Error>> {
779        self.set_msg_rate(CLASS_NAV, ubx::NAV_VELNED, 1).await
780    }
781
782    /// Start whichever per-satellite message the module has: `NAV-SAT` on
783    /// protocol 15 and later, `NAV-SVINFO` before that.
784    ///
785    /// Read the result with [`satellites`](Self::satellites).
786    ///
787    /// # Example
788    /// ```ignore
789    /// gps.probe().await?;
790    /// gps.enable_satellite_info().await?;
791    /// gps.set_skip_unknown_sentences(false); // both arrive as UbxOther
792    /// ```
793    pub async fn enable_satellite_info(&mut self) -> Result<(), Error<S::Error>> {
794        if self.caps.has_nav_sat() {
795            self.set_msg_rate(CLASS_NAV, ubx::NAV_SAT, 1).await
796        } else if self.caps.has_nav_svinfo() {
797            self.set_msg_rate(CLASS_NAV, ubx::NAV_SVINFO, 1).await
798        } else {
799            Err(Error::Unsupported)
800        }
801    }
802
803    /// Start `UBX-NAV-POSLLH` output. Every generation has it.
804    ///
805    /// # Example
806    /// ```ignore
807    /// gps.enable_nav_posllh().await?; // binary position on a NEO-6M
808    /// ```
809    pub async fn enable_nav_posllh(&mut self) -> Result<(), Error<S::Error>> {
810        self.set_msg_rate(CLASS_NAV, ubx::NAV_POSLLH, 1).await
811    }
812
813    /// Start `UBX-NAV-SOL` output (u-blox 6/7/8). Returns
814    /// [`Error::Unsupported`] on M9 and later, which do not have it.
815    ///
816    /// # Example
817    /// ```ignore
818    /// gps.enable_nav_sol().await?; // fix status + DOP on a NEO-6M
819    /// ```
820    pub async fn enable_nav_sol(&mut self) -> Result<(), Error<S::Error>> {
821        if !self.caps.has_nav_sol() {
822            return Err(Error::Unsupported);
823        }
824        self.set_msg_rate(CLASS_NAV, ubx::NAV_SOL, 1).await
825    }
826
827    /// Start the best binary navigation output the module has: `NAV-PVT` on
828    /// the 7 series and later, `NAV-POSLLH` plus `NAV-SOL` otherwise.
829    ///
830    /// Call it after [`probe`](Self::probe), then expect either
831    /// [`Event::NavPvt`] or the [`Event::NavPosllh`] and [`Event::NavSol`]
832    /// pair.
833    ///
834    /// # Example
835    /// ```ignore
836    /// gps.probe().await?;
837    /// gps.enable_binary_nav().await?; // right messages for any NEO-xM
838    /// ```
839    pub async fn enable_binary_nav(&mut self) -> Result<(), Error<S::Error>> {
840        if self.caps.has_nav_pvt() {
841            self.enable_nav_pvt().await
842        } else {
843            self.enable_nav_posllh().await?;
844            self.enable_nav_sol().await
845        }
846    }
847
848    /// Tune the receiver's filters for how the antenna actually moves
849    /// (`CFG-NAV5`). The factory default is
850    /// [`Portable`](ubx::DynamicModel::Portable).
851    ///
852    /// # Example
853    /// ```ignore
854    /// use neo_gps::ubx::DynamicModel;
855    /// gps.set_dynamic_model(DynamicModel::Airborne4G).await?;
856    /// ```
857    pub async fn set_dynamic_model(
858        &mut self,
859        model: ubx::DynamicModel,
860    ) -> Result<(), Error<S::Error>> {
861        if !self.caps.has_legacy_cfg() {
862            return Err(Error::Unsupported);
863        }
864        let mut p = [0u8; 36];
865        p[0..2].copy_from_slice(&0x0001u16.to_le_bytes()); // mask: dynModel only
866        p[2] = model as u8;
867        self.send_cfg_acked(ubx::CFG_NAV5, &p).await
868    }
869
870    /// Turn one GNSS constellation on or off (`CFG-GNSS`).
871    ///
872    /// Polls the module's current configuration, flips the enable bit for
873    /// `which`, and writes it back, so the other constellations and their
874    /// channel allocations are left exactly as they were.
875    ///
876    /// Only meaningful from the 8 series; check
877    /// [`Capabilities::has_cfg_gnss`] first. Returns [`Error::Unsupported`]
878    /// if the module does not report a block for `which`.
879    ///
880    /// # Example
881    /// ```ignore
882    /// use neo_gps::ubx::Constellation;
883    /// if gps.capabilities().has_cfg_gnss() {
884    ///     gps.set_constellation(Constellation::Glonass, true).await?;
885    /// }
886    /// ```
887    pub async fn set_constellation(
888        &mut self,
889        which: ubx::Constellation,
890        enable: bool,
891    ) -> Result<(), Error<S::Error>> {
892        if !self.caps.has_cfg_gnss() {
893            return Err(Error::Unsupported);
894        }
895        self.send_ubx(CLASS_CFG, ubx::CFG_GNSS, &[]).await?;
896
897        let mut cfg = [0u8; ubx::TX_MAX_PAYLOAD];
898        let len = 'poll: {
899            for _ in 0..REPLY_FRAME_BUDGET {
900                if let Event::UbxOther { class, id } = self.read_event().await? {
901                    if class == CLASS_CFG && id == ubx::CFG_GNSS {
902                        let p = self.deframer.last_ubx_payload();
903                        // 4-byte header then 8 bytes per configuration block.
904                        if p.len() < 4 || p.len() > cfg.len() {
905                            return Err(Error::Overflow);
906                        }
907                        cfg[..p.len()].copy_from_slice(p);
908                        break 'poll p.len();
909                    }
910                }
911            }
912            return Err(Error::NoReply);
913        };
914
915        let blocks = cfg[3] as usize;
916        for b in 0..blocks {
917            let off = 4 + b * 8;
918            if off + 8 > len {
919                break;
920            }
921            if cfg[off] != which as u8 {
922                continue;
923            }
924            if enable {
925                cfg[off + 4] |= 0x01;
926            } else {
927                cfg[off + 4] &= !0x01;
928            }
929            return self.send_cfg_acked(ubx::CFG_GNSS, &cfg[..len]).await;
930        }
931        Err(Error::Unsupported)
932    }
933
934    /// Switch the receiver into power save mode, or back to continuous
935    /// tracking (`CFG-RXM`).
936    ///
937    /// # Example
938    /// ```ignore
939    /// gps.set_power_save(true).await?; // battery-powered tracker
940    /// ```
941    pub async fn set_power_save(&mut self, on: bool) -> Result<(), Error<S::Error>> {
942        if !self.caps.has_legacy_cfg() {
943            return Err(Error::Unsupported);
944        }
945        // Byte 0 is reserved and the interface description says to send 8.
946        self.send_cfg_acked(ubx::CFG_RXM, &[8, u8::from(on)]).await
947    }
948
949    /// Change the module's UART baud rate (`CFG-PRT`), leaving both UBX and
950    /// NMEA enabled in and out at 8N1.
951    ///
952    /// **Your UART is not changed**, and cannot be: the driver only has a byte
953    /// stream. The module switches as soon as the frame lands, so the two ends
954    /// are mismatched from that moment until you reconfigure yours. There is
955    /// also no ACK to wait for, since the reply would arrive at whichever rate
956    /// the module has already moved to.
957    ///
958    /// # Example
959    /// ```ignore
960    /// gps.set_baud(115_200).await?;
961    /// let uart = gps.free();                       // take the UART back
962    /// let uart = reconfigure(uart, 115_200);       // your HAL's job
963    /// let mut gps = NeoGps::new(uart);
964    /// ```
965    pub async fn set_baud(&mut self, baud: u32) -> Result<(), Error<S::Error>> {
966        if !self.caps.has_legacy_cfg() {
967            return Err(Error::Unsupported);
968        }
969        let mut p = [0u8; 20];
970        p[0] = 1; // portID: UART1
971        p[4..8].copy_from_slice(&0x0000_08C0u32.to_le_bytes()); // mode: 8N1
972        p[8..12].copy_from_slice(&baud.to_le_bytes());
973        p[12..14].copy_from_slice(&0x0007u16.to_le_bytes()); // in: UBX+NMEA+RTCM
974        p[14..16].copy_from_slice(&0x0003u16.to_le_bytes()); // out: UBX+NMEA
975        self.send_ubx(CLASS_CFG, ubx::CFG_PRT, &p).await
976    }
977
978    /// Restart the receiver (`CFG-RST`), keeping as much stored data as
979    /// `kind` allows.
980    ///
981    /// Returns as soon as the frame is written. There is nothing to wait for:
982    /// the module restarts instead of acknowledging, and goes quiet for a
983    /// moment before its first sentence appears.
984    ///
985    /// # Example
986    /// ```ignore
987    /// use neo_gps::ubx::ResetKind;
988    /// gps.reset(ResetKind::Cold).await?; // full restart, slowest fix
989    /// ```
990    pub async fn reset(&mut self, kind: ubx::ResetKind) -> Result<(), Error<S::Error>> {
991        let mut p = [0u8; 4];
992        p[0..2].copy_from_slice(&kind.bbr_mask().to_le_bytes());
993        p[2] = 0x01; // controlled software reset
994        self.send_ubx(CLASS_CFG, ubx::CFG_RST, &p).await
995    }
996
997    /// Wipe the saved configuration and load the factory defaults
998    /// (`CFG-CFG`), undoing every setting including a saved
999    /// [`save_config`](Self::save_config).
1000    ///
1001    /// The defaults land in RAM immediately. Follow with
1002    /// [`reset`](Self::reset) if you want the module to come up from scratch,
1003    /// and note this puts the baud rate back to 9600.
1004    ///
1005    /// Returns as soon as the frame is written, like [`reset`](Self::reset)
1006    /// and [`set_baud`](Self::set_baud). There is no ACK to rely on: the
1007    /// cleared configuration includes the port settings, so the module
1008    /// reinitialises the UART, and whether the acknowledgement escapes first
1009    /// is a race. Confirm by observing the defaults instead, for example a
1010    /// sentence you had muted coming back.
1011    ///
1012    /// # Example
1013    /// ```ignore
1014    /// gps.factory_reset().await?;
1015    /// // GSV is in the factory sentence set, so it returns on its own.
1016    /// ```
1017    pub async fn factory_reset(&mut self) -> Result<(), Error<S::Error>> {
1018        let mut p = [0u8; 12];
1019        p[0..4].copy_from_slice(&0x0000_FFFFu32.to_le_bytes()); // clearMask: all
1020        p[8..12].copy_from_slice(&0x0000_FFFFu32.to_le_bytes()); // loadMask: all
1021        self.send_ubx(CLASS_CFG, ubx::CFG_CFG, &p).await
1022    }
1023
1024    /// Save the current configuration to battery-backed RAM and flash
1025    /// (`CFG-CFG`), so it survives a power cycle.
1026    ///
1027    /// # Example
1028    /// ```ignore
1029    /// gps.save_config().await?; // persists through power cycles (needs BBR/flash)
1030    /// ```
1031    pub async fn save_config(&mut self) -> Result<(), Error<S::Error>> {
1032        let mut p = [0u8; 12];
1033        p[4..8].copy_from_slice(&0x0000_FFFFu32.to_le_bytes()); // saveMask: all
1034        self.send_cfg_acked(ubx::CFG_CFG, &p).await
1035    }
1036}
1037
1038#[cfg(all(test, feature = "builtin-codec"))]
1039mod tests;
1040#[cfg(all(test, any(feature = "nmea", feature = "ublox")))]
1041mod tests_codec;
1042#[cfg(all(test, feature = "builtin-codec"))]
1043mod tests_datasheet;
1044#[cfg(test)]
1045mod tests_transport;
1046#[cfg(test)]
1047pub(crate) mod testutil;