rtcm3 0.1.0

no_std, no_alloc parser and encoder for RTCM3 GNSS RTK correction messages
Documentation
//! GLONASS Code-Phase Biases (message type 1230): without this, GLONASS
//! observations in the MSM stream are usable for tracking but not for a
//! precise RTK fix.
//!
//! The four bias fields are each present only if the corresponding signal
//! is available - there's no separate mask field in this crate's
//! representation, since an `Option` already carries exactly that
//! presence/absence (a mask bit and a "carries a value" `Option` can't
//! disagree if there's only one of them).

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

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

/// A decoded GLONASS Code-Phase Biases message.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GlonassBias {
    /// Reference station ID (DF003).
    pub reference_station_id: u16,
    /// GLONASS code-phase bias indicator (DF421).
    pub code_phase_bias_indicator: bool,
    /// L1 C/A code-phase bias, raw units of 0.02m (DF423), if the L1 C/A
    /// signal is present in this station's stream.
    pub l1_ca_bias_raw: Option<i32>,
    /// L1 P code-phase bias, raw units of 0.02m (DF424).
    pub l1_p_bias_raw: Option<i32>,
    /// L2 C/A code-phase bias, raw units of 0.02m (DF425).
    pub l2_ca_bias_raw: Option<i32>,
    /// L2 P code-phase bias, raw units of 0.02m (DF426).
    pub l2_p_bias_raw: Option<i32>,
}

fn to_meters(raw: Option<i32>) -> Option<f64> {
    raw.map(|v| f64::from(v) * 0.02)
}

impl GlonassBias {
    /// L1 C/A code-phase bias in meters, if present.
    #[must_use]
    pub fn l1_ca_bias_meters(&self) -> Option<f64> {
        to_meters(self.l1_ca_bias_raw)
    }

    /// L1 P code-phase bias in meters, if present.
    #[must_use]
    pub fn l1_p_bias_meters(&self) -> Option<f64> {
        to_meters(self.l1_p_bias_raw)
    }

    /// L2 C/A code-phase bias in meters, if present.
    #[must_use]
    pub fn l2_ca_bias_meters(&self) -> Option<f64> {
        to_meters(self.l2_ca_bias_raw)
    }

    /// L2 P code-phase bias in meters, if present.
    #[must_use]
    pub fn l2_p_bias_meters(&self) -> Option<f64> {
        to_meters(self.l2_p_bias_raw)
    }

    pub(crate) fn decode(r: &mut BitReader<'_>) -> Result<Self, BitError> {
        let reference_station_id = r.read_u16(12)?;
        let code_phase_bias_indicator = r.read_bool()?;
        r.skip(3)?; // DF001_3, reserved
        let l1_ca_present = r.read_bool()?;
        let l1_p_present = r.read_bool()?;
        let l2_ca_present = r.read_bool()?;
        let l2_p_present = r.read_bool()?;
        Ok(Self {
            reference_station_id,
            code_phase_bias_indicator,
            l1_ca_bias_raw: l1_ca_present.then(|| r.read_i32(16)).transpose()?,
            l1_p_bias_raw: l1_p_present.then(|| r.read_i32(16)).transpose()?,
            l2_ca_bias_raw: l2_ca_present.then(|| r.read_i32(16)).transpose()?,
            l2_p_bias_raw: l2_p_present.then(|| r.read_i32(16)).transpose()?,
        })
    }

    pub(crate) fn encode(&self, w: &mut BitWriter<'_>) -> Result<(), BitError> {
        w.write_u32(u32::from(self.reference_station_id), 12)?;
        w.write_bool(self.code_phase_bias_indicator)?;
        w.skip(3)?; // DF001_3, reserved
        w.write_bool(self.l1_ca_bias_raw.is_some())?;
        w.write_bool(self.l1_p_bias_raw.is_some())?;
        w.write_bool(self.l2_ca_bias_raw.is_some())?;
        w.write_bool(self.l2_p_bias_raw.is_some())?;
        for v in [
            self.l1_ca_bias_raw,
            self.l1_p_bias_raw,
            self.l2_ca_bias_raw,
            self.l2_p_bias_raw,
        ]
        .into_iter()
        .flatten()
        {
            w.write_i32(v, 16)?;
        }
        Ok(())
    }
}

#[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_with_no_biases() {
        // Real MT1230 payload from pyrtcm's own test corpus
        // (pygpsdata-1230.bin, frame d300044ce00080ededd6): all four
        // signal-present bits are 0, so no bias fields follow at all -
        // the whole message is 32 bits.
        let payload: [u8; 4] = hex_decode("4ce00080");
        let mut r = BitReader::new(&payload);
        assert_eq!(r.read_u16(12).unwrap(), 1230);
        let m = GlonassBias::decode(&mut r).unwrap();
        assert_eq!(m.reference_station_id, 0);
        assert!(m.code_phase_bias_indicator);
        assert_eq!(m.l1_ca_bias_raw, None);
        assert_eq!(m.l1_p_bias_raw, None);
        assert_eq!(m.l2_ca_bias_raw, None);
        assert_eq!(m.l2_p_bias_raw, None);
    }

    #[test]
    fn decodes_a_real_captured_frame_with_all_four_biases_present() {
        // Real MT1230 payload from pyrtcm's own test corpus
        // (pygpsdata-1230.bin, frame d3000c4ce0000f000000000000000037b706):
        // all four signal-present bits are 1, so all four (zero-valued)
        // bias fields follow - 96 bits total.
        let payload: [u8; 12] = hex_decode("4ce0000f0000000000000000");
        let mut r = BitReader::new(&payload);
        assert_eq!(r.read_u16(12).unwrap(), 1230);
        let m = GlonassBias::decode(&mut r).unwrap();
        assert_eq!(m.reference_station_id, 0);
        assert!(!m.code_phase_bias_indicator);
        assert_eq!(m.l1_ca_bias_raw, Some(0));
        assert_eq!(m.l1_p_bias_raw, Some(0));
        assert_eq!(m.l2_ca_bias_raw, Some(0));
        assert_eq!(m.l2_p_bias_raw, Some(0));
    }

    #[test]
    fn round_trips_with_mixed_presence_and_nonzero_values() {
        let original = GlonassBias {
            reference_station_id: 99,
            code_phase_bias_indicator: true,
            l1_ca_bias_raw: Some(-150),
            l1_p_bias_raw: None,
            l2_ca_bias_raw: Some(300),
            l2_p_bias_raw: None,
        };
        // Sized for the worst case (all four biases present); encode only
        // writes as many bytes as this instance's fields actually need.
        let mut buf = [0u8; 12];
        let mut w = BitWriter::new(&mut buf);
        original.encode(&mut w).unwrap();

        let mut r = BitReader::new(&buf);
        let decoded = GlonassBias::decode(&mut r).unwrap();
        assert_eq!(decoded, original);
        assert!((decoded.l1_ca_bias_meters().unwrap() - -3.0).abs() < 1e-9);
        assert!((decoded.l2_ca_bias_meters().unwrap() - 6.0).abs() < 1e-9);
    }
}