1mod store;
26pub use store::{BroadcastStore, NavMessagePreference};
27
28mod write;
29pub use write::encode_nav;
30
31use crate::astro::time::model::{GnssWeekTow, TimeScale};
32use crate::astro::time::{civil, gnss};
33use crate::broadcast::{ClockPolynomial, ConstellationConstants, KeplerianElements};
34use crate::constants::{KM_TO_M, SECONDS_PER_HOUR, SECONDS_PER_WEEK};
35use crate::format::columns::{field, raw_field};
36use crate::id::{GnssSatelliteId, GnssSystem};
37use crate::ionex::GalileoNequickCoeffs;
38use crate::validate::{self, FieldError};
39
40fn parse_f64(line: &str, start: usize, end: usize) -> Option<f64> {
45 let value = crate::format::columns::fortran_f64(line, start, end, "numeric field")?;
46 write::d19_12_representable(value).then_some(value)
53}
54
55pub(crate) const MAX_EPHEMERIS_AGE_S: f64 = 4.0 * SECONDS_PER_HOUR;
62
63pub(crate) const GLONASS_MAX_AGE_S: f64 = 15.0 * 60.0;
67const GPS_NOMINAL_FIT_INTERVAL_S: f64 = 4.0 * SECONDS_PER_HOUR;
68const GPS_LEGACY_EXTENDED_FIT_INTERVAL_S: f64 = 8.0 * SECONDS_PER_HOUR;
69const GLONASS_FREQ_CHANNEL_MIN: i32 = -7;
70const GLONASS_FREQ_CHANNEL_MAX: i32 = 6;
71
72pub(crate) fn valid_glonass_frequency_channel(channel: i32) -> bool {
73 (GLONASS_FREQ_CHANNEL_MIN..=GLONASS_FREQ_CHANNEL_MAX).contains(&channel)
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77struct RinexVersion {
78 major: u8,
79 minor: u8,
80}
81
82impl RinexVersion {
83 fn gps_fit_interval_uses_legacy_flag(self) -> bool {
84 self.major == 3 && self.minor <= 2
85 }
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum NavMessage {
91 GpsLnav,
93 GpsCnav,
95 GpsCnav2,
97 QzssLnav,
99 QzssCnav,
101 QzssCnav2,
103 GalileoInav,
105 GalileoFnav,
107 BeidouD1,
109 BeidouD2,
111}
112
113impl NavMessage {
114 pub const fn is_cnav_family(self) -> bool {
116 matches!(
117 self,
118 Self::GpsCnav | Self::GpsCnav2 | Self::QzssCnav | Self::QzssCnav2
119 )
120 }
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub struct BroadcastIssue {
126 pub issue: u32,
128 pub message: NavMessage,
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum BroadcastGroupDelayTerm {
135 GpsTgd,
137 GalileoBgdE5aE1,
139 GalileoBgdE5bE1,
141 BeidouTgd1,
143 BeidouTgd2,
145 CnavIscL1Ca,
147 CnavIscL2C,
149 CnavIscL5I5,
151 CnavIscL5Q5,
153 CnavIscL1Cd,
155 CnavIscL1Cp,
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub enum CnavSignal {
162 L1Ca,
164 L2C,
166 L5I5,
168 L5Q5,
170 L1Cp,
172 L1Cd,
174}
175
176#[derive(Debug, Clone, Copy, PartialEq, Default)]
178pub struct BroadcastGroupDelays {
179 pub gps_tgd_s: Option<f64>,
181 pub galileo_bgd_e5a_e1_s: Option<f64>,
183 pub galileo_bgd_e5b_e1_s: Option<f64>,
185 pub beidou_tgd1_s: Option<f64>,
187 pub beidou_tgd2_s: Option<f64>,
189 pub cnav_isc_l1ca_s: Option<f64>,
191 pub cnav_isc_l2c_s: Option<f64>,
193 pub cnav_isc_l5i5_s: Option<f64>,
195 pub cnav_isc_l5q5_s: Option<f64>,
197 pub cnav_isc_l1cd_s: Option<f64>,
199 pub cnav_isc_l1cp_s: Option<f64>,
201}
202
203impl BroadcastGroupDelays {
204 pub const fn gps_lnav(tgd_s: f64) -> Self {
206 Self {
207 gps_tgd_s: Some(tgd_s),
208 galileo_bgd_e5a_e1_s: None,
209 galileo_bgd_e5b_e1_s: None,
210 beidou_tgd1_s: None,
211 beidou_tgd2_s: None,
212 cnav_isc_l1ca_s: None,
213 cnav_isc_l2c_s: None,
214 cnav_isc_l5i5_s: None,
215 cnav_isc_l5q5_s: None,
216 cnav_isc_l1cd_s: None,
217 cnav_isc_l1cp_s: None,
218 }
219 }
220
221 pub const fn galileo(bgd_e5a_e1_s: f64, bgd_e5b_e1_s: f64) -> Self {
223 Self {
224 gps_tgd_s: None,
225 galileo_bgd_e5a_e1_s: Some(bgd_e5a_e1_s),
226 galileo_bgd_e5b_e1_s: Some(bgd_e5b_e1_s),
227 beidou_tgd1_s: None,
228 beidou_tgd2_s: None,
229 cnav_isc_l1ca_s: None,
230 cnav_isc_l2c_s: None,
231 cnav_isc_l5i5_s: None,
232 cnav_isc_l5q5_s: None,
233 cnav_isc_l1cd_s: None,
234 cnav_isc_l1cp_s: None,
235 }
236 }
237
238 pub const fn beidou(tgd1_s: f64, tgd2_s: f64) -> Self {
240 Self {
241 gps_tgd_s: None,
242 galileo_bgd_e5a_e1_s: None,
243 galileo_bgd_e5b_e1_s: None,
244 beidou_tgd1_s: Some(tgd1_s),
245 beidou_tgd2_s: Some(tgd2_s),
246 cnav_isc_l1ca_s: None,
247 cnav_isc_l2c_s: None,
248 cnav_isc_l5i5_s: None,
249 cnav_isc_l5q5_s: None,
250 cnav_isc_l1cd_s: None,
251 cnav_isc_l1cp_s: None,
252 }
253 }
254
255 pub const fn cnav(
257 tgd_s: Option<f64>,
258 isc_l1ca_s: Option<f64>,
259 isc_l2c_s: Option<f64>,
260 isc_l5i5_s: Option<f64>,
261 isc_l5q5_s: Option<f64>,
262 isc_l1cd_s: Option<f64>,
263 isc_l1cp_s: Option<f64>,
264 ) -> Self {
265 Self {
266 gps_tgd_s: tgd_s,
267 galileo_bgd_e5a_e1_s: None,
268 galileo_bgd_e5b_e1_s: None,
269 beidou_tgd1_s: None,
270 beidou_tgd2_s: None,
271 cnav_isc_l1ca_s: isc_l1ca_s,
272 cnav_isc_l2c_s: isc_l2c_s,
273 cnav_isc_l5i5_s: isc_l5i5_s,
274 cnav_isc_l5q5_s: isc_l5q5_s,
275 cnav_isc_l1cd_s: isc_l1cd_s,
276 cnav_isc_l1cp_s: isc_l1cp_s,
277 }
278 }
279
280 pub const fn get(&self, term: BroadcastGroupDelayTerm) -> Option<f64> {
282 match term {
283 BroadcastGroupDelayTerm::GpsTgd => self.gps_tgd_s,
284 BroadcastGroupDelayTerm::GalileoBgdE5aE1 => self.galileo_bgd_e5a_e1_s,
285 BroadcastGroupDelayTerm::GalileoBgdE5bE1 => self.galileo_bgd_e5b_e1_s,
286 BroadcastGroupDelayTerm::BeidouTgd1 => self.beidou_tgd1_s,
287 BroadcastGroupDelayTerm::BeidouTgd2 => self.beidou_tgd2_s,
288 BroadcastGroupDelayTerm::CnavIscL1Ca => self.cnav_isc_l1ca_s,
289 BroadcastGroupDelayTerm::CnavIscL2C => self.cnav_isc_l2c_s,
290 BroadcastGroupDelayTerm::CnavIscL5I5 => self.cnav_isc_l5i5_s,
291 BroadcastGroupDelayTerm::CnavIscL5Q5 => self.cnav_isc_l5q5_s,
292 BroadcastGroupDelayTerm::CnavIscL1Cd => self.cnav_isc_l1cd_s,
293 BroadcastGroupDelayTerm::CnavIscL1Cp => self.cnav_isc_l1cp_s,
294 }
295 }
296
297 pub fn cnav_single_frequency_correction_s(&self, signal: CnavSignal) -> Option<f64> {
303 let isc = match signal {
304 CnavSignal::L1Ca => self.cnav_isc_l1ca_s,
305 CnavSignal::L2C => self.cnav_isc_l2c_s,
306 CnavSignal::L5I5 => self.cnav_isc_l5i5_s,
307 CnavSignal::L5Q5 => self.cnav_isc_l5q5_s,
308 CnavSignal::L1Cp => self.cnav_isc_l1cp_s,
309 CnavSignal::L1Cd => self.cnav_isc_l1cd_s,
310 }?;
311 Some(self.gps_tgd_s? - isc)
312 }
313
314 pub const fn for_message(self, system: GnssSystem, message: NavMessage) -> Option<f64> {
322 match (system, message) {
323 (GnssSystem::Gps, NavMessage::GpsLnav) | (GnssSystem::Qzss, NavMessage::QzssLnav) => {
324 self.get(BroadcastGroupDelayTerm::GpsTgd)
325 }
326 (GnssSystem::Galileo, NavMessage::GalileoFnav) => {
327 self.get(BroadcastGroupDelayTerm::GalileoBgdE5aE1)
328 }
329 (GnssSystem::Galileo, NavMessage::GalileoInav) => {
330 self.get(BroadcastGroupDelayTerm::GalileoBgdE5bE1)
331 }
332 (GnssSystem::BeiDou, NavMessage::BeidouD1 | NavMessage::BeidouD2) => {
333 self.get(BroadcastGroupDelayTerm::BeidouTgd1)
334 }
335 (
336 GnssSystem::Gps | GnssSystem::Qzss,
337 NavMessage::GpsCnav
338 | NavMessage::GpsCnav2
339 | NavMessage::QzssCnav
340 | NavMessage::QzssCnav2,
341 ) => match (self.gps_tgd_s, self.cnav_isc_l1ca_s) {
342 (Some(tgd), Some(isc)) => Some(tgd - isc),
343 (Some(tgd), None) => Some(tgd),
344 (None, Some(isc)) => Some(-isc),
345 (None, None) => Some(0.0),
346 },
347 _ => None,
348 }
349 }
350}
351
352#[derive(Debug, Clone, Copy, PartialEq)]
354pub struct CnavParameters {
355 pub adot_m_s: f64,
357 pub delta_n0_dot_rad_s2: f64,
359 pub top: GnssWeekTow,
361 pub ura_ed_index: i8,
363 pub ura_ned0_index: i8,
365 pub ura_ned1_index: u8,
367 pub ura_ned2_index: u8,
369 pub transmission_time_sow: f64,
371 pub flags: Option<u32>,
373}
374
375pub fn cnav_ura_nominal_m(index: i8) -> Option<f64> {
379 match index {
380 -16 | 15 => None,
381 1 => Some(2.8),
382 3 => Some(5.7),
383 5 => Some(11.3),
384 -15..=6 => Some(2.0_f64.powf(1.0 + f64::from(index) / 2.0)),
385 7..=14 => Some(2.0_f64.powi(i32::from(index) - 2)),
386 _ => None,
387 }
388}
389
390pub fn cnav_ura_ned_m(params: &CnavParameters, t: GnssWeekTow) -> Option<f64> {
392 let ned0 = cnav_ura_nominal_m(params.ura_ned0_index)?;
393 let ned1 = 2.0_f64.powi(-(14 + i32::from(params.ura_ned1_index)));
394 let ned2 = 2.0_f64.powi(-(28 + i32::from(params.ura_ned2_index)));
395 let dt_op = (f64::from(t.week) - f64::from(params.top.week)) * SECONDS_PER_WEEK
396 + (t.tow_s - params.top.tow_s);
397 let linear = ned0 + ned1 * dt_op;
398 if dt_op <= 93_600.0 {
399 Some(linear)
400 } else {
401 Some(linear + ned2 * (dt_op - 93_600.0) * (dt_op - 93_600.0))
402 }
403}
404
405pub fn is_beidou_geo(sat: GnssSatelliteId) -> bool {
408 sat.system == GnssSystem::BeiDou && (sat.prn <= 5 || (59..=61).contains(&sat.prn))
409}
410
411#[derive(Debug, Clone, Copy, PartialEq)]
415pub struct KlobucharAlphaBeta {
416 pub alpha: [f64; 4],
418 pub beta: [f64; 4],
420}
421
422#[derive(Debug, Clone, Copy, PartialEq, Default)]
429pub struct IonoCorrections {
430 pub gps: Option<KlobucharAlphaBeta>,
432 pub beidou: Option<KlobucharAlphaBeta>,
434 pub galileo: Option<GalileoNequickCoeffs>,
436}
437
438#[derive(Debug, Clone, Copy, PartialEq)]
442pub struct GlonassRecord {
443 pub satellite_id: GnssSatelliteId,
445 pub toe_utc_j2000_s: f64,
448 pub pos_m: [f64; 3],
450 pub vel_m_s: [f64; 3],
452 pub acc_m_s2: [f64; 3],
454 pub clk_bias: f64,
456 pub gamma_n: f64,
458 pub sv_health: f64,
460 pub freq_channel: i32,
462}
463
464#[derive(Debug, Clone, PartialEq, Eq)]
468pub struct SkippedGlonass {
469 pub token: String,
471}
472
473#[derive(Debug, Clone, PartialEq, Default)]
481pub struct GlonassParse {
482 pub records: Vec<GlonassRecord>,
484 pub skipped: Vec<SkippedGlonass>,
486}
487
488#[derive(Debug, Clone, Copy, PartialEq)]
490pub struct BroadcastRecord {
491 pub satellite_id: GnssSatelliteId,
493 pub message: NavMessage,
495 pub issue_of_data: BroadcastIssue,
497 pub week: u32,
499 pub toe: GnssWeekTow,
501 pub toc: GnssWeekTow,
503 pub elements: KeplerianElements,
505 pub clock: ClockPolynomial,
507 pub group_delays: BroadcastGroupDelays,
509 pub cnav: Option<CnavParameters>,
511 pub sv_health: f64,
513 pub sv_accuracy_m: f64,
515 pub fit_interval_s: Option<f64>,
520}
521
522impl BroadcastRecord {
523 pub const fn time_scale(&self) -> TimeScale {
525 self.toe.system
526 }
527
528 pub const fn constants(&self) -> ConstellationConstants {
530 match self.satellite_id.system {
531 GnssSystem::Galileo => ConstellationConstants::GALILEO,
532 GnssSystem::BeiDou => ConstellationConstants::BEIDOU,
533 _ => ConstellationConstants::GPS,
535 }
536 }
537
538 pub fn broadcast_clock_group_delay_s(&self) -> f64 {
540 self.group_delays
541 .for_message(self.satellite_id.system, self.message)
542 .unwrap_or(0.0)
543 }
544
545 pub fn from_lnav(
579 decoded: &crate::navigation::lnav::LnavDecoded,
580 satellite_id: GnssSatelliteId,
581 full_week: u32,
582 ) -> Result<Self, LnavRecordError> {
583 if satellite_id.system != GnssSystem::Gps {
584 return Err(LnavRecordError::NotGps(satellite_id));
585 }
586
587 if i64::from(full_week % 1024) != decoded.week_number {
592 return Err(LnavRecordError::WeekMismatch {
593 full_week,
594 decoded_week: decoded.week_number,
595 });
596 }
597
598 let sv_accuracy_m = gps_ura_index_to_meters(decoded.ura_index)
599 .ok_or(LnavRecordError::NoUraPrediction(decoded.ura_index))?;
600 let fit_interval_s =
601 gps_fit_interval_from_flag(decoded.fit_interval_flag, decoded.iode, decoded.iodc)?;
602
603 const SEMICIRCLE_TO_RAD: f64 = core::f64::consts::PI;
606
607 let elements = KeplerianElements {
608 sqrt_a: decoded.sqrt_a,
609 e: decoded.eccentricity,
610 m0: decoded.m0 * SEMICIRCLE_TO_RAD,
611 delta_n: decoded.delta_n * SEMICIRCLE_TO_RAD,
612 omega0: decoded.omega0 * SEMICIRCLE_TO_RAD,
613 i0: decoded.i0 * SEMICIRCLE_TO_RAD,
614 omega: decoded.omega * SEMICIRCLE_TO_RAD,
615 omega_dot: decoded.omega_dot * SEMICIRCLE_TO_RAD,
616 idot: decoded.idot * SEMICIRCLE_TO_RAD,
617 cuc: decoded.cuc,
618 cus: decoded.cus,
619 crc: decoded.crc,
620 crs: decoded.crs,
621 cic: decoded.cic,
622 cis: decoded.cis,
623 toe_sow: decoded.toe as f64,
624 };
625 let clock = ClockPolynomial {
626 af0: decoded.af0,
627 af1: decoded.af1,
628 af2: decoded.af2,
629 toc_sow: decoded.toc as f64,
630 };
631
632 let toe = GnssWeekTow::new(TimeScale::Gpst, full_week, elements.toe_sow)
633 .and_then(GnssWeekTow::normalized)
634 .map_err(|_| LnavRecordError::InvalidEpoch("toe"))?;
635 let toc = GnssWeekTow::new(TimeScale::Gpst, full_week, clock.toc_sow)
636 .and_then(GnssWeekTow::normalized)
637 .map_err(|_| LnavRecordError::InvalidEpoch("toc"))?;
638
639 Ok(BroadcastRecord {
640 satellite_id,
641 message: NavMessage::GpsLnav,
642 issue_of_data: BroadcastIssue {
643 issue: decoded.iode as u32,
644 message: NavMessage::GpsLnav,
645 },
646 week: full_week,
647 toe,
648 toc,
649 elements,
650 clock,
651 group_delays: BroadcastGroupDelays::gps_lnav(decoded.tgd),
652 cnav: None,
653 sv_health: decoded.sv_health as f64,
654 sv_accuracy_m,
655 fit_interval_s: Some(fit_interval_s),
656 })
657 }
658}
659
660pub(crate) fn gps_ura_index_to_meters(index: i64) -> Option<f64> {
666 let meters = match index {
667 0 => 2.4,
668 1 => 3.4,
669 2 => 4.85,
670 3 => 6.85,
671 4 => 9.65,
672 5 => 13.65,
673 6 => 24.0,
674 7 => 48.0,
675 8 => 96.0,
676 9 => 192.0,
677 10 => 384.0,
678 11 => 768.0,
679 12 => 1536.0,
680 13 => 3072.0,
681 14 => 6144.0,
682 _ => return None,
685 };
686 Some(meters)
687}
688
689const GPS_FIT_INTERVAL_6H_S: f64 = 6.0 * SECONDS_PER_HOUR;
690const GPS_FIT_INTERVAL_8H_S: f64 = 8.0 * SECONDS_PER_HOUR;
691const GPS_FIT_INTERVAL_14H_S: f64 = 14.0 * SECONDS_PER_HOUR;
692const GPS_FIT_INTERVAL_26H_S: f64 = 26.0 * SECONDS_PER_HOUR;
693
694pub(crate) fn gps_fit_interval_from_flag(
704 fit_interval_flag: i64,
705 iode: i64,
706 iodc: i64,
707) -> Result<f64, LnavRecordError> {
708 let unsupported = || LnavRecordError::FitIntervalUnsupported {
709 fit_interval_flag,
710 iode,
711 iodc,
712 };
713 match fit_interval_flag {
714 0 => Ok(GPS_NOMINAL_FIT_INTERVAL_S),
715 1 => {
716 if (0..240).contains(&iode) {
717 Ok(GPS_FIT_INTERVAL_6H_S)
721 } else if (240..=255).contains(&iode) {
722 match iodc {
724 240..=247 => Ok(GPS_FIT_INTERVAL_8H_S),
725 248..=255 | 496 => Ok(GPS_FIT_INTERVAL_14H_S),
726 497..=503 | 1021..=1023 => Ok(GPS_FIT_INTERVAL_26H_S),
727 _ => Err(unsupported()),
728 }
729 } else {
730 Err(unsupported())
731 }
732 }
733 _ => Err(unsupported()),
734 }
735}
736
737#[derive(Debug, Clone, Copy, PartialEq, Eq)]
739pub enum LnavRecordError {
740 NotGps(GnssSatelliteId),
742 InvalidEpoch(&'static str),
744 WeekMismatch {
747 full_week: u32,
749 decoded_week: i64,
751 },
752 NoUraPrediction(i64),
754 FitIntervalUnsupported {
757 fit_interval_flag: i64,
759 iode: i64,
761 iodc: i64,
763 },
764}
765
766impl core::fmt::Display for LnavRecordError {
767 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
768 match self {
769 LnavRecordError::NotGps(sat) => {
770 write!(f, "LNAV is a GPS message; {sat} is not a GPS satellite")
771 }
772 LnavRecordError::InvalidEpoch(field) => {
773 write!(f, "derived {field} week/TOW is not representable")
774 }
775 LnavRecordError::WeekMismatch {
776 full_week,
777 decoded_week,
778 } => write!(
779 f,
780 "full_week {full_week} (week % 1024 = {}) disagrees with decoded 10-bit week {decoded_week}",
781 full_week % 1024
782 ),
783 LnavRecordError::NoUraPrediction(index) => {
784 write!(f, "URA index {index} carries no accuracy prediction")
785 }
786 LnavRecordError::FitIntervalUnsupported {
787 fit_interval_flag,
788 iode,
789 iodc,
790 } => write!(
791 f,
792 "fit interval flag {fit_interval_flag} with IODE {iode} / IODC {iodc} is not a defined curve-fit interval"
793 ),
794 }
795 }
796}
797
798impl std::error::Error for LnavRecordError {}
799
800fn broadcast_time_scale(system: GnssSystem) -> TimeScale {
801 match system {
802 GnssSystem::Galileo => TimeScale::Gst,
803 GnssSystem::BeiDou => TimeScale::Bdt,
804 _ => TimeScale::Gpst,
805 }
806}
807
808#[derive(Debug, Clone, PartialEq, Eq)]
810pub enum NavParseError {
811 UnsupportedHeader(String),
813 MissingHeaderEnd,
815 TruncatedRecord(String),
817 BadField {
819 satellite: String,
821 field: &'static str,
823 },
824 BadHeaderField {
826 field: &'static str,
828 },
829}
830
831impl core::fmt::Display for NavParseError {
832 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
833 match self {
834 NavParseError::UnsupportedHeader(s) => write!(f, "unsupported RINEX NAV header: {s}"),
835 NavParseError::MissingHeaderEnd => write!(f, "no END OF HEADER line"),
836 NavParseError::TruncatedRecord(s) => write!(f, "truncated navigation record for {s}"),
837 NavParseError::BadField { satellite, field } => {
838 write!(f, "bad/missing {field} field in record for {satellite}")
839 }
840 NavParseError::BadHeaderField { field } => {
841 write!(f, "bad/missing {field} field in navigation header")
842 }
843 }
844 }
845}
846
847impl std::error::Error for NavParseError {}
848
849#[derive(Debug, Clone, PartialEq, Eq)]
850pub struct SkippedNavBlock {
851 pub satellite: String,
852 pub message: String,
853}
854
855#[derive(Debug, Clone, PartialEq)]
856pub struct NavParse {
857 pub records: Vec<BroadcastRecord>,
858 pub skipped: Vec<SkippedNavBlock>,
859}
860
861pub fn parse_nav(text: &str) -> Result<Vec<BroadcastRecord>, NavParseError> {
869 let mut lines = text.lines();
870 let version = verify_and_skip_header(&mut lines)?;
871 if version.major >= 4 {
872 parse_nav_v4(lines, version)
873 } else {
874 parse_nav_v3(lines, version)
875 }
876}
877
878pub fn parse_nav_lenient(text: &str) -> Result<NavParse, NavParseError> {
884 let mut lines = text.lines();
885 let version = verify_and_skip_header(&mut lines)?;
886 let (records, skipped) = if version.major >= 4 {
887 parse_nav_v4_lenient(lines, version)
888 } else {
889 parse_nav_v3_lenient(lines, version)
890 };
891 Ok(NavParse { records, skipped })
892}
893
894fn parse_nav_v3<'a, I>(
897 lines: I,
898 version: RinexVersion,
899) -> Result<Vec<BroadcastRecord>, NavParseError>
900where
901 I: Iterator<Item = &'a str>,
902{
903 let mut blocks: Vec<Vec<&str>> = Vec::new();
904 for line in lines {
905 if is_record_start(line) {
906 blocks.push(vec![line]);
907 } else if let Some(last) = blocks.last_mut() {
908 last.push(line);
909 }
910 }
911
912 let mut records = Vec::new();
913 for block in &blocks {
914 let letter = block[0].as_bytes()[0] as char;
915 match GnssSystem::from_letter(letter) {
916 Some(GnssSystem::Gps)
917 | Some(GnssSystem::Galileo)
918 | Some(GnssSystem::BeiDou)
919 | Some(GnssSystem::Qzss) => records.push(parse_keplerian_block(block, None, version)?),
920 _ => {}
922 }
923 }
924 Ok(records)
925}
926
927fn parse_nav_v3_lenient<'a, I>(
928 lines: I,
929 version: RinexVersion,
930) -> (Vec<BroadcastRecord>, Vec<SkippedNavBlock>)
931where
932 I: Iterator<Item = &'a str>,
933{
934 let mut blocks: Vec<Vec<&str>> = Vec::new();
935 for line in lines {
936 if is_record_start(line) {
937 blocks.push(vec![line]);
938 } else if let Some(last) = blocks.last_mut() {
939 last.push(line);
940 }
941 }
942
943 let mut records = Vec::new();
944 let mut skipped = Vec::new();
945 for block in &blocks {
946 let letter = block[0].as_bytes()[0] as char;
947 match GnssSystem::from_letter(letter) {
948 Some(GnssSystem::Gps)
949 | Some(GnssSystem::Galileo)
950 | Some(GnssSystem::BeiDou)
951 | Some(GnssSystem::Qzss) => match parse_keplerian_block(block, None, version) {
952 Ok(record) => records.push(record),
953 Err(error) => skipped.push(SkippedNavBlock {
954 satellite: nav_block_satellite(block),
955 message: error.to_string(),
956 }),
957 },
958 _ => {}
959 }
960 }
961 (records, skipped)
962}
963
964fn parse_nav_v4<'a, I>(
972 lines: I,
973 version: RinexVersion,
974) -> Result<Vec<BroadcastRecord>, NavParseError>
975where
976 I: Iterator<Item = &'a str>,
977{
978 let frames = v4_frames(lines);
981 let mut records = Vec::new();
982 for (marker, body) in &frames {
983 let Some((frame_type, sv, msg_token)) = parse_v4_marker(marker) else {
984 continue;
985 };
986 if frame_type != "EPH" {
987 continue; }
989 let letter = sv.as_bytes().first().copied().map_or(' ', char::from);
990 let Some(system) = GnssSystem::from_letter(letter) else {
991 continue;
992 };
993 let supported = matches!(
994 system,
995 GnssSystem::Gps | GnssSystem::Galileo | GnssSystem::BeiDou | GnssSystem::Qzss
996 );
997 if !supported {
998 continue; }
1000 if let Some(message) = nav_message_from_v4_token(msg_token, system) {
1001 validate_v4_ephemeris_marker(sv, message, body)?;
1002 if message.is_cnav_family() {
1003 records.push(parse_cnav_block(body, message)?);
1004 } else {
1005 records.push(parse_keplerian_block(body, Some(message), version)?);
1006 }
1007 } else if known_v4_ephemeris_token(msg_token)
1008 && !explicitly_skipped_v4_message(msg_token, system)
1009 {
1010 return Err(NavParseError::BadField {
1011 satellite: sv.to_string(),
1012 field: "message",
1013 });
1014 }
1015 }
1016 Ok(records)
1017}
1018
1019fn parse_nav_v4_lenient<'a, I>(
1020 lines: I,
1021 version: RinexVersion,
1022) -> (Vec<BroadcastRecord>, Vec<SkippedNavBlock>)
1023where
1024 I: Iterator<Item = &'a str>,
1025{
1026 let frames = v4_frames(lines);
1027 let mut records = Vec::new();
1028 let mut skipped = Vec::new();
1029 for (marker, body) in &frames {
1030 let Some((frame_type, sv, msg_token)) = parse_v4_marker(marker) else {
1031 continue;
1032 };
1033 if frame_type != "EPH" {
1034 continue;
1035 }
1036 let letter = sv.as_bytes().first().copied().map_or(' ', char::from);
1037 let Some(system) = GnssSystem::from_letter(letter) else {
1038 continue;
1039 };
1040 let supported = matches!(
1041 system,
1042 GnssSystem::Gps | GnssSystem::Qzss | GnssSystem::Galileo | GnssSystem::BeiDou
1043 );
1044 if !supported {
1045 continue;
1046 }
1047 if let Some(message) = nav_message_from_v4_token(msg_token, system) {
1048 let parsed = validate_v4_ephemeris_marker(sv, message, body)
1049 .and_then(|()| parse_keplerian_block(body, Some(message), version));
1050 match parsed {
1051 Ok(record) => records.push(record),
1052 Err(error) => skipped.push(SkippedNavBlock {
1053 satellite: sv.to_string(),
1054 message: error.to_string(),
1055 }),
1056 }
1057 }
1058 }
1059 (records, skipped)
1060}
1061
1062fn nav_block_satellite(block: &[&str]) -> String {
1063 block
1064 .first()
1065 .and_then(|line| line.get(0..3))
1066 .unwrap_or("")
1067 .trim()
1068 .to_string()
1069}
1070
1071fn v4_frames<'a, I>(lines: I) -> Vec<(&'a str, Vec<&'a str>)>
1072where
1073 I: Iterator<Item = &'a str>,
1074{
1075 let mut frames: Vec<(&str, Vec<&str>)> = Vec::new();
1076 for line in lines {
1077 if is_v4_frame_marker(line) {
1078 frames.push((line, Vec::new()));
1079 } else if let Some((_, body)) = frames.last_mut() {
1080 body.push(line);
1081 }
1082 }
1083 frames
1084}
1085
1086fn is_v4_frame_marker(line: &str) -> bool {
1088 line.starts_with("> ")
1089}
1090
1091fn parse_v4_marker(line: &str) -> Option<(&str, &str, &str)> {
1095 let rest = line.strip_prefix('>')?;
1096 let mut fields = rest.split_whitespace();
1097 let frame_type = fields.next()?;
1098 let sv = fields.next()?;
1099 let msg_token = fields.next()?;
1100 Some((frame_type, sv, msg_token))
1101}
1102
1103fn nav_message_from_v4_token(token: &str, system: GnssSystem) -> Option<NavMessage> {
1107 match (token, system) {
1108 ("LNAV", GnssSystem::Gps) => Some(NavMessage::GpsLnav),
1109 ("CNAV", GnssSystem::Gps) => Some(NavMessage::GpsCnav),
1110 ("CNV2", GnssSystem::Gps) => Some(NavMessage::GpsCnav2),
1111 ("LNAV", GnssSystem::Qzss) => Some(NavMessage::QzssLnav),
1112 ("CNAV", GnssSystem::Qzss) => Some(NavMessage::QzssCnav),
1113 ("CNV2", GnssSystem::Qzss) => Some(NavMessage::QzssCnav2),
1114 ("INAV", GnssSystem::Galileo) => Some(NavMessage::GalileoInav),
1115 ("FNAV", GnssSystem::Galileo) => Some(NavMessage::GalileoFnav),
1116 ("D1", GnssSystem::BeiDou) => Some(NavMessage::BeidouD1),
1117 ("D2", GnssSystem::BeiDou) => Some(NavMessage::BeidouD2),
1118 _ => None,
1119 }
1120}
1121
1122fn known_v4_ephemeris_token(token: &str) -> bool {
1123 matches!(
1124 token,
1125 "LNAV" | "CNAV" | "CNV1" | "CNV2" | "CNV3" | "INAV" | "FNAV" | "D1" | "D2"
1126 )
1127}
1128
1129fn explicitly_skipped_v4_message(token: &str, system: GnssSystem) -> bool {
1130 matches!(
1131 (token, system),
1132 ("CNV1" | "CNV2" | "CNV3", GnssSystem::BeiDou)
1133 )
1134}
1135
1136fn validate_v4_ephemeris_marker(
1137 marker_sv: &str,
1138 message: NavMessage,
1139 body: &[&str],
1140) -> Result<(), NavParseError> {
1141 let Some(body_sv) = body
1142 .first()
1143 .and_then(|line| line.get(0..3))
1144 .map(str::trim)
1145 .filter(|sv| !sv.is_empty())
1146 else {
1147 return Ok(());
1148 };
1149
1150 let same_satellite = match (
1151 marker_sv.parse::<GnssSatelliteId>(),
1152 body_sv.parse::<GnssSatelliteId>(),
1153 ) {
1154 (Ok(marker), Ok(body)) => marker == body,
1155 _ => marker_sv == body_sv,
1156 };
1157
1158 if !same_satellite {
1159 return Err(NavParseError::BadField {
1160 satellite: marker_sv.to_string(),
1161 field: "frame marker",
1162 });
1163 }
1164
1165 let system = body_sv
1166 .as_bytes()
1167 .first()
1168 .and_then(|b| GnssSystem::from_letter(*b as char))
1169 .ok_or_else(|| NavParseError::BadField {
1170 satellite: body_sv.to_string(),
1171 field: "system",
1172 })?;
1173 if !nav_message_matches_system(message, system) {
1174 return Err(NavParseError::BadField {
1175 satellite: body_sv.to_string(),
1176 field: "message",
1177 });
1178 }
1179
1180 Ok(())
1181}
1182
1183fn nav_message_matches_system(message: NavMessage, system: GnssSystem) -> bool {
1184 matches!(
1185 (message, system),
1186 (NavMessage::GpsLnav, GnssSystem::Gps)
1187 | (NavMessage::GpsCnav | NavMessage::GpsCnav2, GnssSystem::Gps)
1188 | (NavMessage::QzssLnav, GnssSystem::Qzss)
1189 | (
1190 NavMessage::QzssCnav | NavMessage::QzssCnav2,
1191 GnssSystem::Qzss,
1192 )
1193 | (
1194 NavMessage::GalileoInav | NavMessage::GalileoFnav,
1195 GnssSystem::Galileo,
1196 )
1197 | (
1198 NavMessage::BeidouD1 | NavMessage::BeidouD2,
1199 GnssSystem::BeiDou,
1200 )
1201 )
1202}
1203
1204pub fn parse_iono_corrections(text: &str) -> Result<IonoCorrections, NavParseError> {
1212 parse_iono_corrections_checked(text)
1213}
1214
1215fn parse_iono_corrections_checked(text: &str) -> Result<IonoCorrections, NavParseError> {
1216 let klobuchar_row = |line: &str| -> Result<[f64; 4], NavParseError> {
1223 Ok([
1224 strict_header_f64(line, 5, 17, "ionospheric correction")?,
1225 strict_header_f64(line, 17, 29, "ionospheric correction")?,
1226 strict_header_f64(line, 29, 41, "ionospheric correction")?,
1227 strict_header_f64(line, 41, 53, "ionospheric correction")?,
1228 ])
1229 };
1230 let nequick_row = |line: &str| -> Result<[f64; 3], NavParseError> {
1235 Ok([
1236 strict_header_f64(line, 5, 17, "ionospheric correction")?,
1237 strict_header_f64(line, 17, 29, "ionospheric correction")?,
1238 strict_header_f64(line, 29, 41, "ionospheric correction")?,
1239 ])
1240 };
1241 let (mut gpsa, mut gpsb, mut bdsa, mut bdsb, mut gal) = (None, None, None, None, None);
1242 for line in text.lines() {
1243 if line.contains("END OF HEADER") {
1244 break;
1245 }
1246 if !line.contains("IONOSPHERIC CORR") {
1247 continue;
1248 }
1249 match line.get(0..4).map(str::trim) {
1250 Some("GPSA") => gpsa = Some(klobuchar_row(line)?),
1251 Some("GPSB") => gpsb = Some(klobuchar_row(line)?),
1252 Some("BDSA") => bdsa = Some(klobuchar_row(line)?),
1253 Some("BDSB") => bdsb = Some(klobuchar_row(line)?),
1254 Some("GAL") => {
1255 let row = nequick_row(line)?;
1256 gal = Some(GalileoNequickCoeffs {
1257 ai0: row[0],
1258 ai1: row[1],
1259 ai2: row[2],
1260 });
1261 }
1262 _ => {}
1263 }
1264 }
1265 let pair = |a: Option<[f64; 4]>, b: Option<[f64; 4]>| match (a, b) {
1266 (Some(alpha), Some(beta)) => Some(KlobucharAlphaBeta { alpha, beta }),
1267 _ => None,
1268 };
1269 let mut iono = IonoCorrections {
1270 gps: pair(gpsa, gpsb),
1271 beidou: pair(bdsa, bdsb),
1272 galileo: gal,
1273 };
1274 parse_v4_body_iono_corrections(text, &mut iono)?;
1275 Ok(iono)
1276}
1277
1278fn parse_v4_body_iono_corrections(
1279 text: &str,
1280 iono: &mut IonoCorrections,
1281) -> Result<(), NavParseError> {
1282 let mut lines = text.lines();
1283 for line in lines.by_ref() {
1284 if line.contains("END OF HEADER") {
1285 break;
1286 }
1287 }
1288
1289 for (marker, body) in v4_frames(lines) {
1290 let Some((frame_type, sv, _msg_token)) = parse_v4_marker(marker) else {
1291 continue;
1292 };
1293 if frame_type != "ION" {
1294 continue;
1295 }
1296 let values = parse_v4_iono_values(sv, &body)?;
1297 match sv
1298 .as_bytes()
1299 .first()
1300 .and_then(|b| GnssSystem::from_letter(*b as char))
1301 {
1302 Some(GnssSystem::Gps) => {
1303 iono.gps = Some(KlobucharAlphaBeta {
1304 alpha: iono_values_4(&values, 0, sv)?,
1305 beta: iono_values_4(&values, 4, sv)?,
1306 });
1307 }
1308 Some(GnssSystem::BeiDou) => {
1309 iono.beidou = Some(KlobucharAlphaBeta {
1310 alpha: iono_values_4(&values, 0, sv)?,
1311 beta: iono_values_4(&values, 4, sv)?,
1312 });
1313 }
1314 Some(GnssSystem::Galileo) => {
1315 let coeffs = iono_values_3(&values, 0, sv)?;
1316 iono.galileo = Some(GalileoNequickCoeffs {
1317 ai0: coeffs[0],
1318 ai1: coeffs[1],
1319 ai2: coeffs[2],
1320 });
1321 }
1322 _ => {}
1323 }
1324 }
1325 Ok(())
1326}
1327
1328fn parse_v4_iono_values(sv: &str, body: &[&str]) -> Result<Vec<f64>, NavParseError> {
1329 if body.is_empty() {
1330 return Err(NavParseError::BadField {
1331 satellite: sv.to_string(),
1332 field: "ionospheric correction",
1333 });
1334 }
1335
1336 let mut values = Vec::new();
1337 for (idx, line) in body.iter().enumerate() {
1338 let ranges: &[(usize, usize)] = if idx == 0 {
1339 &[(23, 42), (42, 61), (61, 80)]
1340 } else {
1341 &[(4, 23), (23, 42), (42, 61), (61, 80)]
1342 };
1343 for &(start, end) in ranges {
1344 let raw = raw_field(line, start, end);
1345 if raw.trim().is_empty() {
1346 continue;
1347 }
1348 values.push(
1349 validate::strict_f64(raw, "ionospheric correction")
1350 .map_err(|error| map_record_field_error(error, sv))?,
1351 );
1352 }
1353 }
1354 Ok(values)
1355}
1356
1357fn iono_values_4(values: &[f64], start: usize, sv: &str) -> Result<[f64; 4], NavParseError> {
1358 let Some(slice) = values.get(start..start + 4) else {
1359 return Err(NavParseError::BadField {
1360 satellite: sv.to_string(),
1361 field: "ionospheric correction",
1362 });
1363 };
1364 Ok([slice[0], slice[1], slice[2], slice[3]])
1365}
1366
1367fn iono_values_3(values: &[f64], start: usize, sv: &str) -> Result<[f64; 3], NavParseError> {
1368 let Some(slice) = values.get(start..start + 3) else {
1369 return Err(NavParseError::BadField {
1370 satellite: sv.to_string(),
1371 field: "ionospheric correction",
1372 });
1373 };
1374 Ok([slice[0], slice[1], slice[2]])
1375}
1376
1377pub fn parse_leap_seconds(text: &str) -> Result<Option<f64>, NavParseError> {
1381 parse_leap_seconds_checked(text)
1382}
1383
1384fn parse_leap_seconds_checked(text: &str) -> Result<Option<f64>, NavParseError> {
1385 for line in text.lines() {
1386 if line.contains("END OF HEADER") {
1387 break;
1388 }
1389 if line.contains("LEAP SECONDS") {
1390 return strict_header_integer_f64(line, 0, 6, "leap seconds").map(Some);
1391 }
1392 }
1393 Ok(None)
1394}
1395
1396fn j2000_seconds_utc(y: i64, mo: i64, d: i64, h: i64, mi: i64, s: i64) -> f64 {
1401 civil::j2000_seconds(y as i32, mo as i32, d as i32, h as i32, mi as i32, s as f64)
1402}
1403
1404fn parse_glonass_epoch(l0: &str, sat: &str) -> Result<f64, NavParseError> {
1407 let year = strict_record_int::<i64>(l0, 4, 8, "epoch", sat)?;
1408 let month = strict_record_int::<i64>(l0, 9, 11, "epoch", sat)?;
1409 let day = strict_record_int::<i64>(l0, 12, 14, "epoch", sat)?;
1410 let hour = strict_record_int::<i64>(l0, 15, 17, "epoch", sat)?;
1411 let minute = strict_record_int::<i64>(l0, 18, 20, "epoch", sat)?;
1412 let second = strict_record_int::<i64>(l0, 21, 23, "epoch", sat)?;
1413 let civil = validate::civil_datetime_with_second_policy(
1414 year,
1415 month,
1416 day,
1417 hour,
1418 minute,
1419 second as f64,
1420 validate::CivilSecondPolicy::UtcLike,
1421 )
1422 .map_err(|_| NavParseError::BadField {
1423 satellite: sat.to_string(),
1424 field: "epoch",
1425 })?;
1426 Ok(j2000_seconds_utc(
1427 civil.year,
1428 i64::from(civil.month),
1429 i64::from(civil.day),
1430 i64::from(civil.hour),
1431 i64::from(civil.minute),
1432 civil.second as i64,
1433 ))
1434}
1435
1436fn parse_glonass_block(block: &[&str]) -> Result<GlonassRecord, NavParseError> {
1440 let l0 = block[0];
1441 let sat = l0.get(0..3).unwrap_or("").trim().to_string();
1442 if block.len() < 4 {
1443 return Err(NavParseError::TruncatedRecord(sat));
1444 }
1445 let bad = |what: &'static str| NavParseError::BadField {
1446 satellite: sat.clone(),
1447 field: what,
1448 };
1449 let satellite_id: GnssSatelliteId = sat.parse().map_err(|_| bad("prn"))?;
1450 let toe_utc_j2000_s = parse_glonass_epoch(l0, &sat)?;
1451 let clk_bias = parse_f64(l0, 23, 42).ok_or_else(|| bad("clock bias"))?;
1452 let gamma_n = parse_f64(l0, 42, 61).ok_or_else(|| bad("gamma_n"))?;
1453 let o1 = orbit_row(block[1]);
1454 let o2 = orbit_row(block[2]);
1455 let o3 = orbit_row(block[3]);
1456 let km = |v: Option<f64>, what: &'static str| v.map(|x| x * KM_TO_M).ok_or_else(|| bad(what));
1457 let g = |v: Option<f64>, what: &'static str| v.ok_or_else(|| bad(what));
1458 Ok(GlonassRecord {
1459 satellite_id,
1460 toe_utc_j2000_s,
1461 pos_m: [km(o1[0], "x")?, km(o2[0], "y")?, km(o3[0], "z")?],
1462 vel_m_s: [km(o1[1], "vx")?, km(o2[1], "vy")?, km(o3[1], "vz")?],
1463 acc_m_s2: [km(o1[2], "ax")?, km(o2[2], "ay")?, km(o3[2], "az")?],
1464 clk_bias,
1465 gamma_n,
1466 sv_health: g(o1[3], "health")?,
1467 freq_channel: glonass_frequency_channel(g(o2[3], "frequency channel")?, &sat)?,
1468 })
1469}
1470
1471pub fn parse_glonass(text: &str) -> Result<Vec<GlonassRecord>, NavParseError> {
1479 Ok(parse_glonass_lenient(text)?.records)
1480}
1481
1482pub fn parse_glonass_lenient(text: &str) -> Result<GlonassParse, NavParseError> {
1491 let mut lines = text.lines();
1492 verify_and_skip_header(&mut lines)?;
1493 let mut blocks: Vec<Vec<&str>> = Vec::new();
1494 for line in lines {
1495 if is_record_start(line) {
1496 blocks.push(vec![line]);
1497 } else if let Some(last) = blocks.last_mut() {
1498 last.push(line);
1499 }
1500 }
1501 let mut out = GlonassParse::default();
1502 for block in blocks.iter().filter(|b| b[0].starts_with('R')) {
1503 let sat = block[0].get(0..3).unwrap_or("").trim();
1509 if sat.parse::<GnssSatelliteId>().is_err() {
1510 out.skipped.push(SkippedGlonass {
1511 token: sat.to_string(),
1512 });
1513 continue;
1514 }
1515 out.records.push(parse_glonass_block(block)?);
1516 }
1517 Ok(out)
1518}
1519
1520fn verify_and_skip_header<'a, I>(lines: &mut I) -> Result<RinexVersion, NavParseError>
1524where
1525 I: Iterator<Item = &'a str>,
1526{
1527 let mut version_seen: Option<RinexVersion> = None;
1528 for line in lines.by_ref() {
1529 if line.contains("RINEX VERSION / TYPE") {
1530 let version = line.get(0..9).unwrap_or("").trim();
1532 let detected = parse_rinex_version(version);
1533 let is_nav = line.get(20..21) == Some("N");
1534 match (detected, is_nav) {
1535 (Some(v), true) => version_seen = Some(v),
1536 _ => {
1537 return Err(NavParseError::UnsupportedHeader(
1538 line.trim_end().to_string(),
1539 ))
1540 }
1541 }
1542 }
1543 if line.contains("END OF HEADER") {
1544 return version_seen.ok_or_else(|| {
1545 NavParseError::UnsupportedHeader("no RINEX VERSION / TYPE".to_string())
1546 });
1547 }
1548 }
1549 Err(NavParseError::MissingHeaderEnd)
1550}
1551
1552fn parse_rinex_version(version: &str) -> Option<RinexVersion> {
1553 let (major, minor) = version.split_once('.')?;
1554 let major = major.trim().parse::<u8>().ok()?;
1555 if !matches!(major, 3 | 4) {
1556 return None;
1557 }
1558 let minor_digits = minor
1559 .chars()
1560 .take_while(char::is_ascii_digit)
1561 .collect::<String>();
1562 if minor_digits.is_empty() {
1563 return None;
1564 }
1565 let minor = minor_digits.parse::<u8>().ok()?;
1566 Some(RinexVersion { major, minor })
1567}
1568
1569fn is_record_start(line: &str) -> bool {
1570 let Some(token) = line.get(0..3) else {
1571 return false;
1572 };
1573 let b = token.as_bytes();
1574 let prn = token[1..].trim();
1575 b[0].is_ascii_alphabetic()
1576 && (1..=2).contains(&prn.len())
1577 && prn.bytes().all(|byte| byte.is_ascii_digit())
1578}
1579
1580fn orbit_row(line: &str) -> [Option<f64>; 4] {
1582 [
1583 parse_f64(line, 4, 23),
1584 parse_f64(line, 23, 42),
1585 parse_f64(line, 42, 61),
1586 parse_f64(line, 61, 80),
1587 ]
1588}
1589
1590fn raw_orbit_field(line: &str, field_index: usize) -> &str {
1591 const RANGES: [(usize, usize); 4] = [(4, 23), (23, 42), (42, 61), (61, 80)];
1592 let (start, end) = RANGES[field_index];
1593 raw_field(line, start, end)
1594}
1595
1596#[derive(Debug, Clone, Copy)]
1597struct ClockReferenceEpoch {
1598 week: u32,
1599 sow: f64,
1600}
1601
1602fn parse_keplerian_block(
1603 block: &[&str],
1604 message_override: Option<NavMessage>,
1605 version: RinexVersion,
1606) -> Result<BroadcastRecord, NavParseError> {
1607 let l0 = block.first().copied().unwrap_or("");
1608 let sat = l0.get(0..3).unwrap_or("").trim().to_string();
1609 if block.len() < 8 {
1610 return Err(NavParseError::TruncatedRecord(sat));
1611 }
1612 let bad = |what: &'static str| NavParseError::BadField {
1613 satellite: sat.clone(),
1614 field: what,
1615 };
1616
1617 let letter = l0
1618 .as_bytes()
1619 .first()
1620 .copied()
1621 .map(|b| b as char)
1622 .ok_or_else(|| bad("system"))?;
1623 let system = GnssSystem::from_letter(letter).ok_or_else(|| bad("system"))?;
1624 let satellite_id: GnssSatelliteId = sat.parse().map_err(|_| bad("prn"))?;
1625
1626 let time_scale = broadcast_time_scale(system);
1628 let toc_epoch = parse_toc(l0, &sat, time_scale)?;
1629 let toc_sow = toc_epoch.sow;
1630 let af0 = parse_f64(l0, 23, 42).ok_or_else(|| bad("af0"))?;
1631 let af1 = parse_f64(l0, 42, 61).ok_or_else(|| bad("af1"))?;
1632 let af2 = parse_f64(l0, 61, 80).ok_or_else(|| bad("af2"))?;
1633
1634 let o1 = orbit_row(block[1]);
1635 let o2 = orbit_row(block[2]);
1636 let o3 = orbit_row(block[3]);
1637 let o4 = orbit_row(block[4]);
1638 let o5 = orbit_row(block[5]);
1639 let o6 = orbit_row(block[6]);
1640
1641 let g = |v: Option<f64>, what: &'static str| v.ok_or_else(|| bad(what));
1642
1643 let elements = KeplerianElements {
1644 crs: g(o1[1], "crs")?,
1645 delta_n: g(o1[2], "deltaN")?,
1646 m0: g(o1[3], "m0")?,
1647 cuc: g(o2[0], "cuc")?,
1648 e: g(o2[1], "e")?,
1649 cus: g(o2[2], "cus")?,
1650 sqrt_a: g(o2[3], "sqrtA")?,
1651 toe_sow: g(o3[0], "toe")?,
1652 cic: g(o3[1], "cic")?,
1653 omega0: g(o3[2], "omega0")?,
1654 cis: g(o3[3], "cis")?,
1655 i0: g(o4[0], "i0")?,
1656 crc: g(o4[1], "crc")?,
1657 omega: g(o4[2], "omega")?,
1658 omega_dot: g(o4[3], "omegaDot")?,
1659 idot: g(o5[0], "idot")?,
1660 };
1661 let clock = ClockPolynomial {
1662 af0,
1663 af1,
1664 af2,
1665 toc_sow,
1666 };
1667
1668 let week = finite_integral_u32(g(o5[2], "week")?, "week", &sat)?;
1669 let toe = GnssWeekTow::new(time_scale, week, elements.toe_sow)
1670 .and_then(GnssWeekTow::normalized)
1671 .map_err(|_| bad("toe"))?;
1672 let toc = GnssWeekTow::new(time_scale, toc_epoch.week, clock.toc_sow)
1673 .and_then(GnssWeekTow::normalized)
1674 .map_err(|_| bad("toc"))?;
1675 let message = if let Some(message) = message_override {
1676 message
1677 } else {
1678 match system {
1679 GnssSystem::Galileo => galileo_message(g(o5[1], "data sources")?, &sat)?,
1680 GnssSystem::BeiDou => {
1681 if is_beidou_geo(satellite_id) {
1682 NavMessage::BeidouD2
1683 } else {
1684 NavMessage::BeidouD1
1685 }
1686 }
1687 GnssSystem::Qzss => NavMessage::QzssLnav,
1688 _ => NavMessage::GpsLnav,
1689 }
1690 };
1691 let issue_of_data = BroadcastIssue {
1692 issue: finite_integral_u32(g(o1[0], "issue of data")?, "issue of data", &sat)?,
1693 message,
1694 };
1695
1696 let sv_accuracy_m = g(o6[0], "accuracy")?;
1697 let sv_health = g(o6[1], "health")?;
1698 let group_delays = match system {
1699 GnssSystem::Gps => BroadcastGroupDelays::gps_lnav(g(o6[2], "gps tgd")?),
1700 GnssSystem::Galileo => {
1704 BroadcastGroupDelays::galileo(g(o6[2], "bgd e5a/e1")?, g(o6[3], "bgd e5b/e1")?)
1705 }
1706 GnssSystem::BeiDou => {
1707 BroadcastGroupDelays::beidou(g(o6[2], "beidou tgd1")?, g(o6[3], "beidou tgd2")?)
1708 }
1709 _ => BroadcastGroupDelays::default(),
1710 };
1711
1712 let fit_interval_s = match system {
1715 GnssSystem::Gps => {
1716 Some(gps_fit_interval_s(block[7], version).map_err(|()| bad("fit interval"))?)
1717 }
1718 _ => None,
1719 };
1720
1721 Ok(BroadcastRecord {
1722 satellite_id,
1723 message,
1724 issue_of_data,
1725 week,
1726 toe,
1727 toc,
1728 elements,
1729 clock,
1730 group_delays,
1731 cnav: None,
1732 sv_health,
1733 sv_accuracy_m,
1734 fit_interval_s,
1735 })
1736}
1737
1738fn parse_cnav_block(block: &[&str], message: NavMessage) -> Result<BroadcastRecord, NavParseError> {
1739 let l0 = block.first().copied().unwrap_or("");
1740 let sat = l0.get(0..3).unwrap_or("").trim().to_string();
1741 let is_cnav2 = matches!(message, NavMessage::GpsCnav2 | NavMessage::QzssCnav2);
1742 let required_lines = if is_cnav2 { 10 } else { 9 };
1743 if block.len() < required_lines {
1744 return Err(NavParseError::TruncatedRecord(sat));
1745 }
1746 let bad = |what: &'static str| NavParseError::BadField {
1747 satellite: sat.clone(),
1748 field: what,
1749 };
1750
1751 let letter = l0
1752 .as_bytes()
1753 .first()
1754 .copied()
1755 .map(|b| b as char)
1756 .ok_or_else(|| bad("system"))?;
1757 GnssSystem::from_letter(letter).ok_or_else(|| bad("system"))?;
1758 let satellite_id: GnssSatelliteId = sat.parse().map_err(|_| bad("prn"))?;
1759 let toc_epoch = parse_toc(l0, &sat, TimeScale::Gpst)?;
1760 let af0 = parse_f64(l0, 23, 42).ok_or_else(|| bad("af0"))?;
1761 let af1 = parse_f64(l0, 42, 61).ok_or_else(|| bad("af1"))?;
1762 let af2 = parse_f64(l0, 61, 80).ok_or_else(|| bad("af2"))?;
1763
1764 let o1 = orbit_row(block[1]);
1765 let o2 = orbit_row(block[2]);
1766 let o3 = orbit_row(block[3]);
1767 let o4 = orbit_row(block[4]);
1768 let o5 = orbit_row(block[5]);
1769 let o6 = orbit_row(block[6]);
1770 let o8 = orbit_row(block[8]);
1771 let o9 = if is_cnav2 {
1772 Some(orbit_row(block[9]))
1773 } else {
1774 None
1775 };
1776
1777 let g = |v: Option<f64>, what: &'static str| v.ok_or_else(|| bad(what));
1778 let elements = KeplerianElements {
1779 crs: g(o1[1], "crs")?,
1780 delta_n: g(o1[2], "deltaN0")?,
1781 m0: g(o1[3], "m0")?,
1782 cuc: g(o2[0], "cuc")?,
1783 e: g(o2[1], "e")?,
1784 cus: g(o2[2], "cus")?,
1785 sqrt_a: g(o2[3], "sqrtA0")?,
1786 toe_sow: toc_epoch.sow,
1787 cic: g(o3[1], "cic")?,
1788 omega0: g(o3[2], "omega0")?,
1789 cis: g(o3[3], "cis")?,
1790 i0: g(o4[0], "i0")?,
1791 crc: g(o4[1], "crc")?,
1792 omega: g(o4[2], "omega")?,
1793 omega_dot: g(o4[3], "omegaDot")?,
1794 idot: g(o5[0], "idot")?,
1795 };
1796 let clock = ClockPolynomial {
1797 af0,
1798 af1,
1799 af2,
1800 toc_sow: toc_epoch.sow,
1801 };
1802
1803 let week = toc_epoch.week;
1804 let toe = GnssWeekTow::new(TimeScale::Gpst, week, elements.toe_sow)
1805 .and_then(GnssWeekTow::normalized)
1806 .map_err(|_| bad("toe"))?;
1807 let toc = GnssWeekTow::new(TimeScale::Gpst, week, clock.toc_sow)
1808 .and_then(GnssWeekTow::normalized)
1809 .map_err(|_| bad("toc"))?;
1810 let wn_op = finite_integral_u32(
1811 g(if is_cnav2 { o9.unwrap()[1] } else { o8[1] }, "wn_op")?,
1812 "wn_op",
1813 &sat,
1814 )?;
1815 let top_sow = g(o3[0], "top")?;
1816 let top = GnssWeekTow::new(TimeScale::Gpst, wn_op, top_sow)
1817 .and_then(GnssWeekTow::normalized)
1818 .map_err(|_| bad("top"))?;
1819 let ura_ed_index = finite_integral_i8(g(o6[0], "ura_ed")?, "ura_ed", -16, 15, &sat)?;
1820 let ura_ned0_index = finite_integral_i8(g(o5[2], "ura_ned0")?, "ura_ned0", -16, 15, &sat)?;
1821 let ura_ned1_index = finite_integral_u8(g(o5[3], "ura_ned1")?, "ura_ned1", 0, 7, &sat)?;
1822 let ura_ned2_index = finite_integral_u8(g(o6[3], "ura_ned2")?, "ura_ned2", 0, 7, &sat)?;
1823 let health_max = if is_cnav2 { 1 } else { 7 };
1824 let sv_health = f64::from(finite_integral_u8(
1825 g(o6[1], "health")?,
1826 "health",
1827 0,
1828 health_max,
1829 &sat,
1830 )?);
1831 let transmission_time_sow = g(if is_cnav2 { o9.unwrap()[0] } else { o8[0] }, "t_tm")?;
1832 let flags = optional_integral_u32(
1833 if is_cnav2 {
1834 raw_orbit_field(block[9], 2)
1835 } else {
1836 raw_orbit_field(block[8], 2)
1837 },
1838 "flags",
1839 &sat,
1840 )?;
1841
1842 let tgd = optional_cnav_delay(raw_orbit_field(block[6], 2), "tgd", &sat)?;
1843 let isc_l1ca = optional_cnav_delay(raw_orbit_field(block[7], 0), "isc_l1ca", &sat)?;
1844 let isc_l2c = optional_cnav_delay(raw_orbit_field(block[7], 1), "isc_l2c", &sat)?;
1845 let isc_l5i5 = optional_cnav_delay(raw_orbit_field(block[7], 2), "isc_l5i5", &sat)?;
1846 let isc_l5q5 = optional_cnav_delay(raw_orbit_field(block[7], 3), "isc_l5q5", &sat)?;
1847 let (isc_l1cd, isc_l1cp) = if is_cnav2 {
1848 (
1849 optional_cnav_delay(raw_orbit_field(block[8], 0), "isc_l1cd", &sat)?,
1850 optional_cnav_delay(raw_orbit_field(block[8], 1), "isc_l1cp", &sat)?,
1851 )
1852 } else {
1853 (None, None)
1854 };
1855
1856 let cnav = CnavParameters {
1857 adot_m_s: g(o1[0], "adot")?,
1858 delta_n0_dot_rad_s2: g(o5[1], "deltaN0Dot")?,
1859 top,
1860 ura_ed_index,
1861 ura_ned0_index,
1862 ura_ned1_index,
1863 ura_ned2_index,
1864 transmission_time_sow,
1865 flags,
1866 };
1867 let sv_accuracy_m = cnav_ura_nominal_m(ura_ed_index).unwrap_or(8192.0);
1868 let issue = (elements.toe_sow / 300.0).round() as u32;
1869
1870 Ok(BroadcastRecord {
1871 satellite_id,
1872 message,
1873 issue_of_data: BroadcastIssue { issue, message },
1874 week,
1875 toe,
1876 toc,
1877 elements,
1878 clock,
1879 group_delays: BroadcastGroupDelays::cnav(
1880 tgd, isc_l1ca, isc_l2c, isc_l5i5, isc_l5q5, isc_l1cd, isc_l1cp,
1881 ),
1882 cnav: Some(cnav),
1883 sv_health,
1884 sv_accuracy_m,
1885 fit_interval_s: Some(3.0 * SECONDS_PER_HOUR),
1886 })
1887}
1888
1889fn gps_fit_interval_s(orbit7: &str, version: RinexVersion) -> Result<f64, ()> {
1901 let value = match field(orbit7, 23, 42) {
1902 None => 0.0,
1903 Some(_) => parse_f64(orbit7, 23, 42).ok_or(())?,
1904 };
1905 if value == 0.0 {
1906 Ok(GPS_NOMINAL_FIT_INTERVAL_S)
1907 } else if version.gps_fit_interval_uses_legacy_flag() && value == 1.0 {
1908 Ok(GPS_LEGACY_EXTENDED_FIT_INTERVAL_S)
1909 } else {
1910 Ok(value * SECONDS_PER_HOUR)
1911 }
1912}
1913
1914fn galileo_message(data_sources: f64, sat: &str) -> Result<NavMessage, NavParseError> {
1918 let word = finite_integral_u32(data_sources, "data sources", sat)?;
1919 if word & 0b010 != 0 {
1920 Ok(NavMessage::GalileoFnav)
1921 } else if word & 0b101 != 0 {
1922 Ok(NavMessage::GalileoInav)
1923 } else {
1924 Ok(NavMessage::GalileoInav)
1926 }
1927}
1928
1929fn finite_integral_u32(value: f64, field: &'static str, sat: &str) -> Result<u32, NavParseError> {
1930 validate::finite(value, field).map_err(|error| map_record_field_error(error, sat))?;
1931 if value < 0.0 || value > f64::from(u32::MAX) || value.trunc() != value {
1932 return Err(NavParseError::BadField {
1933 satellite: sat.to_string(),
1934 field,
1935 });
1936 }
1937 Ok(value as u32)
1938}
1939
1940fn finite_integral_i8(
1941 value: f64,
1942 field: &'static str,
1943 min: i8,
1944 max: i8,
1945 sat: &str,
1946) -> Result<i8, NavParseError> {
1947 validate::finite(value, field).map_err(|error| map_record_field_error(error, sat))?;
1948 if value < f64::from(min) || value > f64::from(max) || value.trunc() != value {
1949 return Err(NavParseError::BadField {
1950 satellite: sat.to_string(),
1951 field,
1952 });
1953 }
1954 Ok(value as i8)
1955}
1956
1957fn finite_integral_u8(
1958 value: f64,
1959 field: &'static str,
1960 min: u8,
1961 max: u8,
1962 sat: &str,
1963) -> Result<u8, NavParseError> {
1964 validate::finite(value, field).map_err(|error| map_record_field_error(error, sat))?;
1965 if value < f64::from(min) || value > f64::from(max) || value.trunc() != value {
1966 return Err(NavParseError::BadField {
1967 satellite: sat.to_string(),
1968 field,
1969 });
1970 }
1971 Ok(value as u8)
1972}
1973
1974fn optional_integral_u32(
1975 raw: &str,
1976 field: &'static str,
1977 sat: &str,
1978) -> Result<Option<u32>, NavParseError> {
1979 if raw.trim().is_empty() {
1980 return Ok(None);
1981 }
1982 let value =
1983 validate::strict_f64(raw, field).map_err(|error| map_record_field_error(error, sat))?;
1984 finite_integral_u32(value, field, sat).map(Some)
1985}
1986
1987fn optional_cnav_delay(
1988 raw: &str,
1989 field: &'static str,
1990 sat: &str,
1991) -> Result<Option<f64>, NavParseError> {
1992 if raw.trim().is_empty() {
1993 return Ok(None);
1994 }
1995 let value =
1996 validate::strict_f64(raw, field).map_err(|error| map_record_field_error(error, sat))?;
1997 if !write::d19_12_representable(value) {
1998 return Err(NavParseError::BadField {
1999 satellite: sat.to_string(),
2000 field,
2001 });
2002 }
2003 let mut rendered = String::new();
2004 write::push_d19_12(&mut rendered, value);
2005 let mut sentinel = String::new();
2006 write::push_d19_12(&mut sentinel, -4096.0 * 2.0_f64.powi(-35));
2007 if rendered == sentinel {
2008 Ok(None)
2009 } else {
2010 Ok(Some(value))
2011 }
2012}
2013
2014fn glonass_frequency_channel(value: f64, sat: &str) -> Result<i32, NavParseError> {
2015 const FIELD: &str = "frequency channel";
2016 validate::finite(value, FIELD).map_err(|error| map_record_field_error(error, sat))?;
2017 let channel = value as i32;
2018 if value.trunc() != value || !valid_glonass_frequency_channel(channel) {
2019 return Err(NavParseError::BadField {
2020 satellite: sat.to_string(),
2021 field: FIELD,
2022 });
2023 }
2024 Ok(channel)
2025}
2026
2027fn strict_header_f64(
2028 line: &str,
2029 start: usize,
2030 end: usize,
2031 field: &'static str,
2032) -> Result<f64, NavParseError> {
2033 validate::strict_f64(raw_field(line, start, end), field).map_err(map_header_field_error)
2034}
2035
2036fn strict_header_integer_f64(
2037 line: &str,
2038 start: usize,
2039 end: usize,
2040 field: &'static str,
2041) -> Result<f64, NavParseError> {
2042 let value = strict_header_f64(line, start, end, field)?;
2043 if value.trunc() != value {
2044 return Err(NavParseError::BadHeaderField { field });
2045 }
2046 Ok(value)
2047}
2048
2049fn strict_record_int<T>(
2050 line: &str,
2051 start: usize,
2052 end: usize,
2053 field: &'static str,
2054 satellite: &str,
2055) -> Result<T, NavParseError>
2056where
2057 T: core::str::FromStr,
2058{
2059 validate::strict_int::<T>(raw_field(line, start, end), field)
2060 .map_err(|error| map_record_field_error(error, satellite))
2061}
2062
2063fn map_record_field_error(error: FieldError, satellite: &str) -> NavParseError {
2064 NavParseError::BadField {
2065 satellite: satellite.to_string(),
2066 field: error.field(),
2067 }
2068}
2069
2070fn map_header_field_error(error: FieldError) -> NavParseError {
2071 NavParseError::BadHeaderField {
2072 field: error.field(),
2073 }
2074}
2075
2076fn parse_toc(
2079 l0: &str,
2080 sat: &str,
2081 time_scale: TimeScale,
2082) -> Result<ClockReferenceEpoch, NavParseError> {
2083 let year = strict_record_int::<i64>(l0, 4, 8, "toc epoch", sat)?;
2084 let month = strict_record_int::<i64>(l0, 9, 11, "toc epoch", sat)?;
2085 let day = strict_record_int::<i64>(l0, 12, 14, "toc epoch", sat)?;
2086 let hour = strict_record_int::<i64>(l0, 15, 17, "toc epoch", sat)?;
2087 let minute = strict_record_int::<i64>(l0, 18, 20, "toc epoch", sat)?;
2088 let second = strict_record_int::<i64>(l0, 21, 23, "toc epoch", sat)?;
2089 let civil = validate::civil_datetime_with_second_policy(
2090 year,
2091 month,
2092 day,
2093 hour,
2094 minute,
2095 second as f64,
2096 validate::CivilSecondPolicy::Continuous,
2097 )
2098 .map_err(|_| NavParseError::BadField {
2099 satellite: sat.to_string(),
2100 field: "toc epoch",
2101 })?;
2102 let month = i64::from(civil.month);
2103 let day = i64::from(civil.day);
2104 let week = gnss::week_from_calendar(time_scale, civil.year, month, day).ok_or_else(|| {
2105 NavParseError::BadField {
2106 satellite: sat.to_string(),
2107 field: "toc epoch",
2108 }
2109 })?;
2110 let sow = gnss::seconds_of_week_from_calendar(
2111 civil.year,
2112 month,
2113 day,
2114 i64::from(civil.hour),
2115 i64::from(civil.minute),
2116 civil.second as i64,
2117 );
2118 Ok(ClockReferenceEpoch { week, sow })
2119}
2120
2121#[cfg(all(test, sidereon_repo_tests))]
2122mod tests;