rtcm3 0.1.0

no_std, no_alloc parser and encoder for RTCM3 GNSS RTK correction messages
Documentation
//! Stationary RTK Reference Station ARP (message type 1005): the base
//! station's antenna reference point position, mandatory for a rover to
//! use any correction stream at all.

use crate::bits::{BitReader, BitWriter};
use crate::error::BitError;

/// This message's type (DF002).
pub const TYPE: u16 = 1005;

/// A decoded Stationary RTK Reference Station ARP message.
#[allow(
    clippy::struct_excessive_bools,
    reason = "each bool is an independent single-bit wire flag defined by the RTCM3 spec, not related state"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StationArp {
    /// Reference station ID (DF003).
    pub reference_station_id: u16,
    /// ITRF realization year (DF021).
    pub itrf_realization_year: u8,
    /// Whether GPS observations are included in this station's stream (DF022).
    pub gps_indicator: bool,
    /// Whether GLONASS observations are included (DF023).
    pub glonass_indicator: bool,
    /// Whether Galileo observations are included (DF024).
    pub galileo_indicator: bool,
    /// Reference-station indicator: `true` for a physical reference
    /// station, `false` for a non-physical one (DF141).
    pub reference_station_indicator: bool,
    /// Antenna reference point ECEF X, raw units of 0.0001m (DF025).
    pub ecef_x_raw: i64,
    /// Single-receiver oscillator indicator (DF142).
    pub single_oscillator_indicator: bool,
    /// Antenna reference point ECEF Y, raw units of 0.0001m (DF026).
    pub ecef_y_raw: i64,
    /// Quarter-cycle phase shift indicator (DF364).
    pub quarter_cycle_indicator: u8,
    /// Antenna reference point ECEF Z, raw units of 0.0001m (DF027).
    pub ecef_z_raw: i64,
}

impl StationArp {
    /// ECEF X in meters.
    #[must_use]
    #[allow(
        clippy::cast_precision_loss,
        reason = "an i64 holding a 38-bit value converted to f64 loses no precision this raw value ever needs"
    )]
    pub fn x_meters(&self) -> f64 {
        self.ecef_x_raw as f64 * 0.0001
    }

    /// ECEF Y in meters.
    #[must_use]
    #[allow(clippy::cast_precision_loss, reason = "see x_meters")]
    pub fn y_meters(&self) -> f64 {
        self.ecef_y_raw as f64 * 0.0001
    }

    /// ECEF Z in meters.
    #[must_use]
    #[allow(clippy::cast_precision_loss, reason = "see x_meters")]
    pub fn z_meters(&self) -> f64 {
        self.ecef_z_raw as f64 * 0.0001
    }

    pub(crate) fn decode(r: &mut BitReader<'_>) -> Result<Self, BitError> {
        Ok(Self {
            reference_station_id: r.read_u16(12)?,
            itrf_realization_year: r.read_u8(6)?,
            gps_indicator: r.read_bool()?,
            glonass_indicator: r.read_bool()?,
            galileo_indicator: r.read_bool()?,
            reference_station_indicator: r.read_bool()?,
            ecef_x_raw: r.read_i64(38)?,
            single_oscillator_indicator: r.read_bool()?,
            ecef_y_raw: {
                r.skip(1)?; // DF001_1, reserved
                r.read_i64(38)?
            },
            quarter_cycle_indicator: r.read_u8(2)?,
            ecef_z_raw: r.read_i64(38)?,
        })
    }

    pub(crate) fn encode(&self, w: &mut BitWriter<'_>) -> Result<(), BitError> {
        w.write_u32(u32::from(self.reference_station_id), 12)?;
        w.write_u32(u32::from(self.itrf_realization_year), 6)?;
        w.write_bool(self.gps_indicator)?;
        w.write_bool(self.glonass_indicator)?;
        w.write_bool(self.galileo_indicator)?;
        w.write_bool(self.reference_station_indicator)?;
        write_i38(w, self.ecef_x_raw)?;
        w.write_bool(self.single_oscillator_indicator)?;
        w.skip(1)?; // DF001_1, reserved
        write_i38(w, self.ecef_y_raw)?;
        w.write_u32(u32::from(self.quarter_cycle_indicator), 2)?;
        write_i38(w, self.ecef_z_raw)
    }
}

/// Writes a 38-bit two's-complement value. `BitWriter::write_i32` only
/// covers 32 bits; ECEF coordinates need more range than that, so this
/// packs the low 38 bits directly instead.
fn write_i38(w: &mut BitWriter<'_>, value: i64) -> Result<(), BitError> {
    #[allow(
        clippy::cast_sign_loss,
        reason = "reinterpreting the two's-complement bit pattern, not a numeric conversion"
    )]
    let bits = value as u64;
    w.write_u64(bits & 0x3F_FFFF_FFFF, 38)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn hex_decode<const N: usize>(hex: &str) -> [u8; N] {
        let mut out = [0u8; N];
        for (i, chunk) in hex.as_bytes().chunks(2).enumerate() {
            let s = core::str::from_utf8(chunk).unwrap();
            out[i] = u8::from_str_radix(s, 16).unwrap();
        }
        out
    }

    #[test]
    fn decodes_a_real_captured_frame() {
        // Real MT1005 payload from pyrtcm's own test corpus
        // (pygpsdata-RTCM3.log): reference_station_id=0,
        // ecef_x=4444030.8028 ecef_y=3085671.2349 ecef_z=3366658.256,
        // gps/glonass/galileo indicators all true.
        let payload: [u8; 19] = hex_decode("3ed000038a58d9493c872f34109d07d6af4820");
        let mut r = BitReader::new(&payload);
        let message_type = r.read_u16(12).unwrap();
        assert_eq!(message_type, 1005);
        let m = StationArp::decode(&mut r).unwrap();
        assert_eq!(m.reference_station_id, 0);
        assert!(m.gps_indicator);
        assert!(m.glonass_indicator);
        assert!(m.galileo_indicator);
        assert!((m.x_meters() - 4_444_030.802_8).abs() < 1e-3);
        assert!((m.y_meters() - 3_085_671.234_9).abs() < 1e-3);
        assert!((m.z_meters() - 3_366_658.256).abs() < 1e-3);
    }

    #[test]
    fn round_trips_through_decode() {
        let original = StationArp {
            reference_station_id: 1234,
            itrf_realization_year: 20,
            gps_indicator: true,
            glonass_indicator: false,
            galileo_indicator: true,
            reference_station_indicator: false,
            ecef_x_raw: -44_440_308_028,
            single_oscillator_indicator: true,
            ecef_y_raw: 30_856_712_349,
            quarter_cycle_indicator: 2,
            ecef_z_raw: -33_666_582_560,
        };
        let mut buf = [0u8; 19];
        let mut w = BitWriter::new(&mut buf);
        original.encode(&mut w).unwrap();

        let mut r = BitReader::new(&buf);
        let decoded = StationArp::decode(&mut r).unwrap();
        assert_eq!(decoded, original);
    }
}