sidereon-core 0.25.0

Numerical astrodynamics propagation core plus the GNSS domain layer (SP3, broadcast ephemeris, multi-GNSS positioning, RTK/PPP, ionosphere/troposphere, DOP) behind a default-on gnss feature
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
//! RTCM 3 broadcast ephemeris messages 1019 (GPS), 1020 (GLONASS),
//! 1042 (BeiDou), 1044 (QZSS), and 1045/1046 (Galileo).
//!
//! Message 1019 (RTCM 10403.3 Table 3.5-21) carries one complete set of GPS
//! LNAV ephemeris and clock parameters; message 1020 (Table 3.5-22) carries one
//! GLONASS satellite's ephemeris. The GLONASS message stores its orbit terms in
//! sign-and-magnitude form (the leading bit is the sign), which the bit reader's
//! [`super::bits::BitReader::ism`] handles.
//!
//! Every field is stored as its raw transmitted integer (the `DFxxx` quantity),
//! preserving the integer-vs-sign-magnitude distinction exactly, so the body
//! round-trips byte-for-byte. The standard per-field scale factors are noted in
//! the struct docs; applying them yields the engineering-unit ephemeris that
//! [`crate::broadcast`] consumes.

use crate::astro::time::model::{GnssWeekTow, TimeScale};
use crate::broadcast::{ClockPolynomial, KeplerianElements};
use crate::constants::SECONDS_PER_HOUR;
use crate::error::{Error, Result};
use crate::id::{GnssSatelliteId, GnssSystem};
use crate::rinex_nav::{
    gps_fit_interval_from_flag, gps_ura_index_to_meters, BroadcastGroupDelays, BroadcastIssue,
    BroadcastRecord, NavMessage,
};

use super::bits::{BitReader, BitWriter};
use super::DecodeResult;

const SEMICIRCLE_TO_RAD: f64 = core::f64::consts::PI;
const GALILEO_WEEK_OFFSET_TO_GPS: u32 = 1024;

fn scaled_i(value: impl Into<i64>, exponent: i32) -> f64 {
    (value.into() as f64) * 2.0_f64.powi(exponent)
}

fn scaled_u(value: u64, exponent: i32) -> f64 {
    (value as f64) * 2.0_f64.powi(exponent)
}

fn scaled_semicircle(value: impl Into<i64>, exponent: i32) -> f64 {
    scaled_i(value, exponent) * SEMICIRCLE_TO_RAD
}

fn gnss_week_tow(
    system: TimeScale,
    week: u32,
    tow_s: f64,
    field: &'static str,
) -> Result<GnssWeekTow> {
    GnssWeekTow::new(system, week, tow_s)
        .and_then(GnssWeekTow::normalized)
        .map_err(|_| Error::InvalidInput(format!("RTCM broadcast {field} is not representable")))
}

fn galileo_sisa_m(index: u8) -> f64 {
    match index {
        0..=49 => f64::from(index) * 0.01,
        50..=74 => 0.50 + f64::from(index - 50) * 0.02,
        75..=99 => 1.00 + f64::from(index - 75) * 0.04,
        100..=125 => 2.00 + f64::from(index - 100) * 0.16,
        _ => 8192.0,
    }
}

fn ura_or_wide(index: u8) -> f64 {
    gps_ura_index_to_meters(i64::from(index)).unwrap_or(8192.0)
}

fn raw_health(healthy: bool) -> f64 {
    if healthy {
        0.0
    } else {
        1.0
    }
}

/// A decoded GPS broadcast ephemeris (message 1019).
///
/// Angular quantities are in semicircles (scale noted per field), harmonic
/// correction terms in radians, distances in meters, and clock terms in
/// seconds, each recovered by multiplying the raw integer by its scale factor.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GpsEphemeris {
    /// GPS satellite PRN (DF009).
    pub satellite_id: u8,
    /// GPS week number (DF076, 10 bits).
    pub week_number: u16,
    /// SV accuracy / URA index (DF077, 4 bits).
    pub sv_accuracy: u8,
    /// Code on L2 (DF078, 2 bits).
    pub code_on_l2: u8,
    /// Rate of inclination angle IDOT (DF079, int14, scale 2^-43 semicircles/s).
    pub idot: i32,
    /// Issue of data, ephemeris (DF071, 8 bits).
    pub iode: u8,
    /// Clock data reference time t_oc (DF081, uint16, scale 2^4 s).
    pub t_oc: u16,
    /// Clock drift rate a_f2 (DF082, int8, scale 2^-55 s/s^2).
    pub a_f2: i16,
    /// Clock drift a_f1 (DF083, int16, scale 2^-43 s/s).
    pub a_f1: i32,
    /// Clock bias a_f0 (DF084, int22, scale 2^-31 s).
    pub a_f0: i32,
    /// Issue of data, clock (DF085, 10 bits).
    pub iodc: u16,
    /// Orbit-radius sine correction C_rs (DF086, int16, scale 2^-5 m).
    pub c_rs: i32,
    /// Mean-motion difference dn (DF087, int16, scale 2^-43 semicircles/s).
    pub delta_n: i32,
    /// Mean anomaly at reference time M_0 (DF088, int32, scale 2^-31 semicircles).
    pub m0: i64,
    /// Latitude-argument cosine correction C_uc (DF089, int16, scale 2^-29 rad).
    pub c_uc: i32,
    /// Eccentricity e (DF090, uint32, scale 2^-33).
    pub eccentricity: u64,
    /// Latitude-argument sine correction C_us (DF091, int16, scale 2^-29 rad).
    pub c_us: i32,
    /// Square root of the semi-major axis sqrt(A) (DF092, uint32, scale 2^-19).
    pub sqrt_a: u64,
    /// Ephemeris reference time t_oe (DF093, uint16, scale 2^4 s).
    pub t_oe: u16,
    /// Inclination cosine correction C_ic (DF094, int16, scale 2^-29 rad).
    pub c_ic: i32,
    /// Longitude of ascending node Omega_0 (DF095, int32, scale 2^-31 semicircles).
    pub omega0: i64,
    /// Inclination sine correction C_is (DF096, int16, scale 2^-29 rad).
    pub c_is: i32,
    /// Inclination at reference time i_0 (DF097, int32, scale 2^-31 semicircles).
    pub i0: i64,
    /// Orbit-radius cosine correction C_rc (DF098, int16, scale 2^-5 m).
    pub c_rc: i32,
    /// Argument of perigee omega (DF099, int32, scale 2^-31 semicircles).
    pub omega: i64,
    /// Rate of right ascension Omega-dot (DF100, int24, scale 2^-43 semicircles/s).
    pub omega_dot: i32,
    /// Group delay differential t_GD (DF101, int8, scale 2^-31 s).
    pub t_gd: i16,
    /// SV health (DF102, 6 bits).
    pub sv_health: u8,
    /// L2 P-data flag (DF103).
    pub l2_p_data_flag: bool,
    /// Fit-interval flag (DF137).
    pub fit_interval: bool,
}

impl GpsEphemeris {
    /// The satellite identifier for this ephemeris.
    pub fn satellite(&self) -> Result<GnssSatelliteId> {
        GnssSatelliteId::new(GnssSystem::Gps, self.satellite_id)
            .map_err(|e| Error::Parse(format!("invalid GPS PRN in 1019: {e}")))
    }

    /// Decode a message 1019 body (without the transport frame).
    pub fn decode(body: &[u8]) -> Result<Self> {
        Self::decode_inner(body).map_err(Into::into)
    }

    pub(crate) fn decode_inner(body: &[u8]) -> DecodeResult<Self> {
        let mut r = BitReader::new(body);
        let message_number = r.u(12)? as u16;
        if message_number != 1019 {
            return Err(Error::Parse(format!(
                "message {message_number} is not GPS ephemeris 1019"
            ))
            .into());
        }
        Ok(Self {
            satellite_id: r.u(6)? as u8,
            week_number: r.u(10)? as u16,
            sv_accuracy: r.u(4)? as u8,
            code_on_l2: r.u(2)? as u8,
            idot: r.i(14)? as i32,
            iode: r.u(8)? as u8,
            t_oc: r.u(16)? as u16,
            a_f2: r.i(8)? as i16,
            a_f1: r.i(16)? as i32,
            a_f0: r.i(22)? as i32,
            iodc: r.u(10)? as u16,
            c_rs: r.i(16)? as i32,
            delta_n: r.i(16)? as i32,
            m0: r.i(32)?,
            c_uc: r.i(16)? as i32,
            eccentricity: r.u(32)?,
            c_us: r.i(16)? as i32,
            sqrt_a: r.u(32)?,
            t_oe: r.u(16)? as u16,
            c_ic: r.i(16)? as i32,
            omega0: r.i(32)?,
            c_is: r.i(16)? as i32,
            i0: r.i(32)?,
            c_rc: r.i(16)? as i32,
            omega: r.i(32)?,
            omega_dot: r.i(24)? as i32,
            t_gd: r.i(8)? as i16,
            sv_health: r.u(6)? as u8,
            l2_p_data_flag: r.flag()?,
            fit_interval: r.flag()?,
        })
    }

    /// Encode this GPS ephemeris body (without the transport frame).
    pub fn encode(&self) -> Vec<u8> {
        let mut w = BitWriter::new();
        w.push_u(1019, 12);
        w.push_u(u64::from(self.satellite_id), 6);
        w.push_u(u64::from(self.week_number), 10);
        w.push_u(u64::from(self.sv_accuracy), 4);
        w.push_u(u64::from(self.code_on_l2), 2);
        w.push_i(i64::from(self.idot), 14);
        w.push_u(u64::from(self.iode), 8);
        w.push_u(u64::from(self.t_oc), 16);
        w.push_i(i64::from(self.a_f2), 8);
        w.push_i(i64::from(self.a_f1), 16);
        w.push_i(i64::from(self.a_f0), 22);
        w.push_u(u64::from(self.iodc), 10);
        w.push_i(i64::from(self.c_rs), 16);
        w.push_i(i64::from(self.delta_n), 16);
        w.push_i(self.m0, 32);
        w.push_i(i64::from(self.c_uc), 16);
        w.push_u(self.eccentricity, 32);
        w.push_i(i64::from(self.c_us), 16);
        w.push_u(self.sqrt_a, 32);
        w.push_u(u64::from(self.t_oe), 16);
        w.push_i(i64::from(self.c_ic), 16);
        w.push_i(self.omega0, 32);
        w.push_i(i64::from(self.c_is), 16);
        w.push_i(self.i0, 32);
        w.push_i(i64::from(self.c_rc), 16);
        w.push_i(self.omega, 32);
        w.push_i(i64::from(self.omega_dot), 24);
        w.push_i(i64::from(self.t_gd), 8);
        w.push_u(u64::from(self.sv_health), 6);
        w.push_flag(self.l2_p_data_flag);
        w.push_flag(self.fit_interval);
        w.into_bytes()
    }

    /// Convert this decoded RTCM ephemeris to the broadcast record consumed by
    /// the solver. `full_week` is the caller-unrolled GPS week and must agree
    /// with the 10-bit RTCM week residue.
    pub fn to_broadcast_record(&self, full_week: u32) -> Result<BroadcastRecord> {
        if full_week % 1024 != u32::from(self.week_number) {
            return Err(Error::InvalidInput(format!(
                "GPS full week {full_week} disagrees with 10-bit RTCM week {}",
                self.week_number
            )));
        }
        let satellite_id = self.satellite()?;
        let toe_sow = f64::from(self.t_oe) * 16.0;
        let toc_sow = f64::from(self.t_oc) * 16.0;
        let toe = gnss_week_tow(TimeScale::Gpst, full_week, toe_sow, "GPS toe")?;
        let toc = gnss_week_tow(TimeScale::Gpst, full_week, toc_sow, "GPS toc")?;
        let fit_interval_s = gps_fit_interval_from_flag(
            i64::from(u8::from(self.fit_interval)),
            i64::from(self.iode),
            i64::from(self.iodc),
        )
        .map_err(|e| Error::InvalidInput(e.to_string()))?;
        Ok(BroadcastRecord {
            satellite_id,
            message: NavMessage::GpsLnav,
            issue_of_data: BroadcastIssue {
                issue: u32::from(self.iode),
                message: NavMessage::GpsLnav,
            },
            week: full_week,
            toe,
            toc,
            elements: KeplerianElements {
                sqrt_a: scaled_u(self.sqrt_a, -19),
                e: scaled_u(self.eccentricity, -33),
                m0: scaled_semicircle(self.m0, -31),
                delta_n: scaled_semicircle(self.delta_n, -43),
                omega0: scaled_semicircle(self.omega0, -31),
                i0: scaled_semicircle(self.i0, -31),
                omega: scaled_semicircle(self.omega, -31),
                omega_dot: scaled_semicircle(self.omega_dot, -43),
                idot: scaled_semicircle(self.idot, -43),
                cuc: scaled_i(self.c_uc, -29),
                cus: scaled_i(self.c_us, -29),
                crc: scaled_i(self.c_rc, -5),
                crs: scaled_i(self.c_rs, -5),
                cic: scaled_i(self.c_ic, -29),
                cis: scaled_i(self.c_is, -29),
                toe_sow,
            },
            clock: ClockPolynomial {
                af0: scaled_i(self.a_f0, -31),
                af1: scaled_i(self.a_f1, -43),
                af2: scaled_i(self.a_f2, -55),
                toc_sow,
            },
            group_delays: BroadcastGroupDelays::gps_lnav(scaled_i(self.t_gd, -31)),
            cnav: None,
            sv_health: f64::from(self.sv_health),
            sv_accuracy_m: ura_or_wide(self.sv_accuracy),
            fit_interval_s: Some(fit_interval_s),
        })
    }
}

/// A decoded Galileo F/NAV broadcast ephemeris (message 1045).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GalileoFnavEphemeris {
    pub satellite_id: u8,
    pub week_number: u16,
    pub iod_nav: u16,
    pub sisa: u8,
    pub idot: i32,
    pub t_oc: u16,
    pub a_f2: i16,
    pub a_f1: i32,
    pub a_f0: i64,
    pub c_rs: i32,
    pub delta_n: i32,
    pub m0: i64,
    pub c_uc: i32,
    pub eccentricity: u64,
    pub c_us: i32,
    pub sqrt_a: u64,
    pub t_oe: u16,
    pub c_ic: i32,
    pub omega0: i64,
    pub c_is: i32,
    pub i0: i64,
    pub c_rc: i32,
    pub omega: i64,
    pub omega_dot: i32,
    pub bgd_e5a_e1: i16,
    pub e5a_signal_health: u8,
    pub e5a_data_validity: bool,
    pub reserved: u8,
}

impl GalileoFnavEphemeris {
    pub fn satellite(&self) -> Result<GnssSatelliteId> {
        GnssSatelliteId::new(GnssSystem::Galileo, self.satellite_id)
            .map_err(|e| Error::Parse(format!("invalid Galileo SVID in 1045: {e}")))
    }

    pub fn decode(body: &[u8]) -> Result<Self> {
        Self::decode_inner(body).map_err(Into::into)
    }

    pub(crate) fn decode_inner(body: &[u8]) -> DecodeResult<Self> {
        let mut r = BitReader::new(body);
        let message_number = r.u(12)? as u16;
        if message_number != 1045 {
            return Err(Error::Parse(format!(
                "message {message_number} is not Galileo F/NAV ephemeris 1045"
            ))
            .into());
        }
        Ok(Self {
            satellite_id: r.u(6)? as u8,
            week_number: r.u(12)? as u16,
            iod_nav: r.u(10)? as u16,
            sisa: r.u(8)? as u8,
            idot: r.i(14)? as i32,
            t_oc: r.u(14)? as u16,
            a_f2: r.i(6)? as i16,
            a_f1: r.i(21)? as i32,
            a_f0: r.i(31)?,
            c_rs: r.i(16)? as i32,
            delta_n: r.i(16)? as i32,
            m0: r.i(32)?,
            c_uc: r.i(16)? as i32,
            eccentricity: r.u(32)?,
            c_us: r.i(16)? as i32,
            sqrt_a: r.u(32)?,
            t_oe: r.u(14)? as u16,
            c_ic: r.i(16)? as i32,
            omega0: r.i(32)?,
            c_is: r.i(16)? as i32,
            i0: r.i(32)?,
            c_rc: r.i(16)? as i32,
            omega: r.i(32)?,
            omega_dot: r.i(24)? as i32,
            bgd_e5a_e1: r.i(10)? as i16,
            e5a_signal_health: r.u(2)? as u8,
            e5a_data_validity: r.flag()?,
            reserved: r.u(7)? as u8,
        })
    }

    pub fn encode(&self) -> Vec<u8> {
        let mut w = BitWriter::new();
        w.push_u(1045, 12);
        w.push_u(u64::from(self.satellite_id), 6);
        w.push_u(u64::from(self.week_number), 12);
        w.push_u(u64::from(self.iod_nav), 10);
        w.push_u(u64::from(self.sisa), 8);
        w.push_i(i64::from(self.idot), 14);
        w.push_u(u64::from(self.t_oc), 14);
        w.push_i(i64::from(self.a_f2), 6);
        w.push_i(i64::from(self.a_f1), 21);
        w.push_i(self.a_f0, 31);
        w.push_i(i64::from(self.c_rs), 16);
        w.push_i(i64::from(self.delta_n), 16);
        w.push_i(self.m0, 32);
        w.push_i(i64::from(self.c_uc), 16);
        w.push_u(self.eccentricity, 32);
        w.push_i(i64::from(self.c_us), 16);
        w.push_u(self.sqrt_a, 32);
        w.push_u(u64::from(self.t_oe), 14);
        w.push_i(i64::from(self.c_ic), 16);
        w.push_i(self.omega0, 32);
        w.push_i(i64::from(self.c_is), 16);
        w.push_i(self.i0, 32);
        w.push_i(i64::from(self.c_rc), 16);
        w.push_i(self.omega, 32);
        w.push_i(i64::from(self.omega_dot), 24);
        w.push_i(i64::from(self.bgd_e5a_e1), 10);
        w.push_u(u64::from(self.e5a_signal_health), 2);
        w.push_flag(self.e5a_data_validity);
        w.push_u(u64::from(self.reserved), 7);
        w.into_bytes()
    }

    pub fn to_broadcast_record(&self) -> Result<BroadcastRecord> {
        galileo_to_record(
            self.satellite()?,
            u32::from(self.week_number),
            self.iod_nav,
            self.sisa,
            self.idot,
            self.t_oc,
            self.a_f2,
            self.a_f1,
            self.a_f0,
            self.c_rs,
            self.delta_n,
            self.m0,
            self.c_uc,
            self.eccentricity,
            self.c_us,
            self.sqrt_a,
            self.t_oe,
            self.c_ic,
            self.omega0,
            self.c_is,
            self.i0,
            self.c_rc,
            self.omega,
            self.omega_dot,
            self.bgd_e5a_e1,
            0,
            raw_health(self.e5a_signal_health == 0 && !self.e5a_data_validity),
            NavMessage::GalileoFnav,
        )
    }
}

/// A decoded Galileo I/NAV broadcast ephemeris (message 1046).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GalileoInavEphemeris {
    pub satellite_id: u8,
    pub week_number: u16,
    pub iod_nav: u16,
    pub sisa_index: u8,
    pub idot: i32,
    pub t_oc: u16,
    pub a_f2: i16,
    pub a_f1: i32,
    pub a_f0: i64,
    pub c_rs: i32,
    pub delta_n: i32,
    pub m0: i64,
    pub c_uc: i32,
    pub eccentricity: u64,
    pub c_us: i32,
    pub sqrt_a: u64,
    pub t_oe: u16,
    pub c_ic: i32,
    pub omega0: i64,
    pub c_is: i32,
    pub i0: i64,
    pub c_rc: i32,
    pub omega: i64,
    pub omega_dot: i32,
    pub bgd_e5a_e1: i16,
    pub bgd_e5b_e1: i16,
    pub e5b_signal_health: u8,
    pub e5b_data_validity: bool,
    pub e1b_signal_health: u8,
    pub e1b_data_validity: bool,
    pub reserved: u8,
}

impl GalileoInavEphemeris {
    pub fn satellite(&self) -> Result<GnssSatelliteId> {
        GnssSatelliteId::new(GnssSystem::Galileo, self.satellite_id)
            .map_err(|e| Error::Parse(format!("invalid Galileo SVID in 1046: {e}")))
    }

    pub fn decode(body: &[u8]) -> Result<Self> {
        Self::decode_inner(body).map_err(Into::into)
    }

    pub(crate) fn decode_inner(body: &[u8]) -> DecodeResult<Self> {
        let mut r = BitReader::new(body);
        let message_number = r.u(12)? as u16;
        if message_number != 1046 {
            return Err(Error::Parse(format!(
                "message {message_number} is not Galileo I/NAV ephemeris 1046"
            ))
            .into());
        }
        Ok(Self {
            satellite_id: r.u(6)? as u8,
            week_number: r.u(12)? as u16,
            iod_nav: r.u(10)? as u16,
            sisa_index: r.u(8)? as u8,
            idot: r.i(14)? as i32,
            t_oc: r.u(14)? as u16,
            a_f2: r.i(6)? as i16,
            a_f1: r.i(21)? as i32,
            a_f0: r.i(31)?,
            c_rs: r.i(16)? as i32,
            delta_n: r.i(16)? as i32,
            m0: r.i(32)?,
            c_uc: r.i(16)? as i32,
            eccentricity: r.u(32)?,
            c_us: r.i(16)? as i32,
            sqrt_a: r.u(32)?,
            t_oe: r.u(14)? as u16,
            c_ic: r.i(16)? as i32,
            omega0: r.i(32)?,
            c_is: r.i(16)? as i32,
            i0: r.i(32)?,
            c_rc: r.i(16)? as i32,
            omega: r.i(32)?,
            omega_dot: r.i(24)? as i32,
            bgd_e5a_e1: r.i(10)? as i16,
            bgd_e5b_e1: r.i(10)? as i16,
            e5b_signal_health: r.u(2)? as u8,
            e5b_data_validity: r.flag()?,
            e1b_signal_health: r.u(2)? as u8,
            e1b_data_validity: r.flag()?,
            reserved: r.u(2)? as u8,
        })
    }

    pub fn encode(&self) -> Vec<u8> {
        let mut w = BitWriter::new();
        w.push_u(1046, 12);
        w.push_u(u64::from(self.satellite_id), 6);
        w.push_u(u64::from(self.week_number), 12);
        w.push_u(u64::from(self.iod_nav), 10);
        w.push_u(u64::from(self.sisa_index), 8);
        w.push_i(i64::from(self.idot), 14);
        w.push_u(u64::from(self.t_oc), 14);
        w.push_i(i64::from(self.a_f2), 6);
        w.push_i(i64::from(self.a_f1), 21);
        w.push_i(self.a_f0, 31);
        w.push_i(i64::from(self.c_rs), 16);
        w.push_i(i64::from(self.delta_n), 16);
        w.push_i(self.m0, 32);
        w.push_i(i64::from(self.c_uc), 16);
        w.push_u(self.eccentricity, 32);
        w.push_i(i64::from(self.c_us), 16);
        w.push_u(self.sqrt_a, 32);
        w.push_u(u64::from(self.t_oe), 14);
        w.push_i(i64::from(self.c_ic), 16);
        w.push_i(self.omega0, 32);
        w.push_i(i64::from(self.c_is), 16);
        w.push_i(self.i0, 32);
        w.push_i(i64::from(self.c_rc), 16);
        w.push_i(self.omega, 32);
        w.push_i(i64::from(self.omega_dot), 24);
        w.push_i(i64::from(self.bgd_e5a_e1), 10);
        w.push_i(i64::from(self.bgd_e5b_e1), 10);
        w.push_u(u64::from(self.e5b_signal_health), 2);
        w.push_flag(self.e5b_data_validity);
        w.push_u(u64::from(self.e1b_signal_health), 2);
        w.push_flag(self.e1b_data_validity);
        w.push_u(u64::from(self.reserved), 2);
        w.into_bytes()
    }

    pub fn to_broadcast_record(&self) -> Result<BroadcastRecord> {
        galileo_to_record(
            self.satellite()?,
            u32::from(self.week_number),
            self.iod_nav,
            self.sisa_index,
            self.idot,
            self.t_oc,
            self.a_f2,
            self.a_f1,
            self.a_f0,
            self.c_rs,
            self.delta_n,
            self.m0,
            self.c_uc,
            self.eccentricity,
            self.c_us,
            self.sqrt_a,
            self.t_oe,
            self.c_ic,
            self.omega0,
            self.c_is,
            self.i0,
            self.c_rc,
            self.omega,
            self.omega_dot,
            self.bgd_e5a_e1,
            self.bgd_e5b_e1,
            raw_health(
                self.e1b_signal_health == 0
                    && !self.e1b_data_validity
                    && self.e5b_signal_health == 0
                    && !self.e5b_data_validity,
            ),
            NavMessage::GalileoInav,
        )
    }
}

#[allow(clippy::too_many_arguments)]
fn galileo_to_record(
    satellite_id: GnssSatelliteId,
    week: u32,
    iod_nav: u16,
    sisa: u8,
    idot: i32,
    t_oc: u16,
    a_f2: i16,
    a_f1: i32,
    a_f0: i64,
    c_rs: i32,
    delta_n: i32,
    m0: i64,
    c_uc: i32,
    eccentricity: u64,
    c_us: i32,
    sqrt_a: u64,
    t_oe: u16,
    c_ic: i32,
    omega0: i64,
    c_is: i32,
    i0: i64,
    c_rc: i32,
    omega: i64,
    omega_dot: i32,
    bgd_e5a_e1: i16,
    bgd_e5b_e1: i16,
    sv_health: f64,
    message: NavMessage,
) -> Result<BroadcastRecord> {
    let toe_sow = f64::from(t_oe) * 60.0;
    let toc_sow = f64::from(t_oc) * 60.0;
    let gps_aligned_week = week
        .checked_add(GALILEO_WEEK_OFFSET_TO_GPS)
        .ok_or_else(|| Error::InvalidInput("RTCM Galileo week overflows GPST axis".to_string()))?;
    let toe = gnss_week_tow(TimeScale::Gst, gps_aligned_week, toe_sow, "Galileo toe")?;
    let toc = gnss_week_tow(TimeScale::Gst, gps_aligned_week, toc_sow, "Galileo toc")?;
    Ok(BroadcastRecord {
        satellite_id,
        message,
        issue_of_data: BroadcastIssue {
            issue: u32::from(iod_nav),
            message,
        },
        week: gps_aligned_week,
        toe,
        toc,
        elements: KeplerianElements {
            sqrt_a: scaled_u(sqrt_a, -19),
            e: scaled_u(eccentricity, -33),
            m0: scaled_semicircle(m0, -31),
            delta_n: scaled_semicircle(delta_n, -43),
            omega0: scaled_semicircle(omega0, -31),
            i0: scaled_semicircle(i0, -31),
            omega: scaled_semicircle(omega, -31),
            omega_dot: scaled_semicircle(omega_dot, -43),
            idot: scaled_semicircle(idot, -43),
            cuc: scaled_i(c_uc, -29),
            cus: scaled_i(c_us, -29),
            crc: scaled_i(c_rc, -5),
            crs: scaled_i(c_rs, -5),
            cic: scaled_i(c_ic, -29),
            cis: scaled_i(c_is, -29),
            toe_sow,
        },
        clock: ClockPolynomial {
            af0: scaled_i(a_f0, -34),
            af1: scaled_i(a_f1, -46),
            af2: scaled_i(a_f2, -59),
            toc_sow,
        },
        group_delays: BroadcastGroupDelays::galileo(
            scaled_i(bgd_e5a_e1, -32),
            scaled_i(bgd_e5b_e1, -32),
        ),
        cnav: None,
        sv_health,
        sv_accuracy_m: galileo_sisa_m(sisa),
        fit_interval_s: None,
    })
}

/// A decoded BeiDou broadcast ephemeris (message 1042).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BeidouEphemeris {
    pub satellite_id: u8,
    pub week_number: u16,
    pub sv_urai: u8,
    pub idot: i32,
    pub aode: u8,
    pub t_oc: u32,
    pub a_f2: i16,
    pub a_f1: i32,
    pub a_f0: i32,
    pub aodc: u8,
    pub c_rs: i32,
    pub delta_n: i32,
    pub m0: i64,
    pub c_uc: i32,
    pub eccentricity: u64,
    pub c_us: i32,
    pub sqrt_a: u64,
    pub t_oe: u32,
    pub c_ic: i32,
    pub omega0: i64,
    pub c_is: i32,
    pub i0: i64,
    pub c_rc: i32,
    pub omega: i64,
    pub omega_dot: i32,
    pub t_gd1: i16,
    pub t_gd2: i16,
    pub sv_health: bool,
}

impl BeidouEphemeris {
    pub fn satellite(&self) -> Result<GnssSatelliteId> {
        GnssSatelliteId::new(GnssSystem::BeiDou, self.satellite_id)
            .map_err(|e| Error::Parse(format!("invalid BeiDou satellite ID in 1042: {e}")))
    }

    pub fn decode(body: &[u8]) -> Result<Self> {
        Self::decode_inner(body).map_err(Into::into)
    }

    pub(crate) fn decode_inner(body: &[u8]) -> DecodeResult<Self> {
        let mut r = BitReader::new(body);
        let message_number = r.u(12)? as u16;
        if message_number != 1042 {
            return Err(Error::Parse(format!(
                "message {message_number} is not BeiDou ephemeris 1042"
            ))
            .into());
        }
        Ok(Self {
            satellite_id: r.u(6)? as u8,
            week_number: r.u(13)? as u16,
            sv_urai: r.u(4)? as u8,
            idot: r.i(14)? as i32,
            aode: r.u(5)? as u8,
            t_oc: r.u(17)? as u32,
            a_f2: r.i(11)? as i16,
            a_f1: r.i(22)? as i32,
            a_f0: r.i(24)? as i32,
            aodc: r.u(5)? as u8,
            c_rs: r.i(18)? as i32,
            delta_n: r.i(16)? as i32,
            m0: r.i(32)?,
            c_uc: r.i(18)? as i32,
            eccentricity: r.u(32)?,
            c_us: r.i(18)? as i32,
            sqrt_a: r.u(32)?,
            t_oe: r.u(17)? as u32,
            c_ic: r.i(18)? as i32,
            omega0: r.i(32)?,
            c_is: r.i(18)? as i32,
            i0: r.i(32)?,
            c_rc: r.i(18)? as i32,
            omega: r.i(32)?,
            omega_dot: r.i(24)? as i32,
            t_gd1: r.i(10)? as i16,
            t_gd2: r.i(10)? as i16,
            sv_health: r.flag()?,
        })
    }

    pub fn encode(&self) -> Vec<u8> {
        let mut w = BitWriter::new();
        w.push_u(1042, 12);
        w.push_u(u64::from(self.satellite_id), 6);
        w.push_u(u64::from(self.week_number), 13);
        w.push_u(u64::from(self.sv_urai), 4);
        w.push_i(i64::from(self.idot), 14);
        w.push_u(u64::from(self.aode), 5);
        w.push_u(u64::from(self.t_oc), 17);
        w.push_i(i64::from(self.a_f2), 11);
        w.push_i(i64::from(self.a_f1), 22);
        w.push_i(i64::from(self.a_f0), 24);
        w.push_u(u64::from(self.aodc), 5);
        w.push_i(i64::from(self.c_rs), 18);
        w.push_i(i64::from(self.delta_n), 16);
        w.push_i(self.m0, 32);
        w.push_i(i64::from(self.c_uc), 18);
        w.push_u(self.eccentricity, 32);
        w.push_i(i64::from(self.c_us), 18);
        w.push_u(self.sqrt_a, 32);
        w.push_u(u64::from(self.t_oe), 17);
        w.push_i(i64::from(self.c_ic), 18);
        w.push_i(self.omega0, 32);
        w.push_i(i64::from(self.c_is), 18);
        w.push_i(self.i0, 32);
        w.push_i(i64::from(self.c_rc), 18);
        w.push_i(self.omega, 32);
        w.push_i(i64::from(self.omega_dot), 24);
        w.push_i(i64::from(self.t_gd1), 10);
        w.push_i(i64::from(self.t_gd2), 10);
        w.push_flag(self.sv_health);
        w.into_bytes()
    }

    pub fn to_broadcast_record(&self) -> Result<BroadcastRecord> {
        let satellite_id = self.satellite()?;
        let week = u32::from(self.week_number);
        let toe_sow = f64::from(self.t_oe) * 8.0;
        let toc_sow = f64::from(self.t_oc) * 8.0;
        let toe = gnss_week_tow(TimeScale::Bdt, week, toe_sow, "BeiDou toe")?;
        let toc = gnss_week_tow(TimeScale::Bdt, week, toc_sow, "BeiDou toc")?;
        let message = if crate::rinex_nav::is_beidou_geo(satellite_id) {
            NavMessage::BeidouD2
        } else {
            NavMessage::BeidouD1
        };
        Ok(BroadcastRecord {
            satellite_id,
            message,
            issue_of_data: BroadcastIssue {
                issue: u32::from(self.aode),
                message,
            },
            week,
            toe,
            toc,
            elements: KeplerianElements {
                sqrt_a: scaled_u(self.sqrt_a, -19),
                e: scaled_u(self.eccentricity, -33),
                m0: scaled_semicircle(self.m0, -31),
                delta_n: scaled_semicircle(self.delta_n, -43),
                omega0: scaled_semicircle(self.omega0, -31),
                i0: scaled_semicircle(self.i0, -31),
                omega: scaled_semicircle(self.omega, -31),
                omega_dot: scaled_semicircle(self.omega_dot, -43),
                idot: scaled_semicircle(self.idot, -43),
                cuc: scaled_i(self.c_uc, -31),
                cus: scaled_i(self.c_us, -31),
                crc: scaled_i(self.c_rc, -6),
                crs: scaled_i(self.c_rs, -6),
                cic: scaled_i(self.c_ic, -31),
                cis: scaled_i(self.c_is, -31),
                toe_sow,
            },
            clock: ClockPolynomial {
                af0: scaled_i(self.a_f0, -33),
                af1: scaled_i(self.a_f1, -50),
                af2: scaled_i(self.a_f2, -66),
                toc_sow,
            },
            group_delays: BroadcastGroupDelays::beidou(
                f64::from(self.t_gd1) * 1.0e-10,
                f64::from(self.t_gd2) * 1.0e-10,
            ),
            cnav: None,
            sv_health: f64::from(u8::from(self.sv_health)),
            sv_accuracy_m: ura_or_wide(self.sv_urai),
            fit_interval_s: None,
        })
    }
}

/// A decoded QZSS broadcast ephemeris (message 1044).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct QzssEphemeris {
    pub satellite_id: u8,
    pub t_oc: u16,
    pub a_f2: i16,
    pub a_f1: i32,
    pub a_f0: i32,
    pub iode: u8,
    pub c_rs: i32,
    pub delta_n: i32,
    pub m0: i64,
    pub c_uc: i32,
    pub eccentricity: u64,
    pub c_us: i32,
    pub sqrt_a: u64,
    pub t_oe: u16,
    pub c_ic: i32,
    pub omega0: i64,
    pub c_is: i32,
    pub i0: i64,
    pub c_rc: i32,
    pub omega: i64,
    pub omega_dot: i32,
    pub idot: i32,
    pub codes_on_l2: u8,
    pub week_number: u16,
    pub ura: u8,
    pub sv_health: u8,
    pub t_gd: i16,
    pub iodc: u16,
    pub fit_interval: bool,
}

impl QzssEphemeris {
    pub fn satellite(&self) -> Result<GnssSatelliteId> {
        GnssSatelliteId::new(GnssSystem::Qzss, self.satellite_id)
            .map_err(|e| Error::Parse(format!("invalid QZSS satellite ID in 1044: {e}")))
    }

    pub fn decode(body: &[u8]) -> Result<Self> {
        Self::decode_inner(body).map_err(Into::into)
    }

    pub(crate) fn decode_inner(body: &[u8]) -> DecodeResult<Self> {
        let mut r = BitReader::new(body);
        let message_number = r.u(12)? as u16;
        if message_number != 1044 {
            return Err(Error::Parse(format!(
                "message {message_number} is not QZSS ephemeris 1044"
            ))
            .into());
        }
        Ok(Self {
            satellite_id: r.u(4)? as u8,
            t_oc: r.u(16)? as u16,
            a_f2: r.i(8)? as i16,
            a_f1: r.i(16)? as i32,
            a_f0: r.i(22)? as i32,
            iode: r.u(8)? as u8,
            c_rs: r.i(16)? as i32,
            delta_n: r.i(16)? as i32,
            m0: r.i(32)?,
            c_uc: r.i(16)? as i32,
            eccentricity: r.u(32)?,
            c_us: r.i(16)? as i32,
            sqrt_a: r.u(32)?,
            t_oe: r.u(16)? as u16,
            c_ic: r.i(16)? as i32,
            omega0: r.i(32)?,
            c_is: r.i(16)? as i32,
            i0: r.i(32)?,
            c_rc: r.i(16)? as i32,
            omega: r.i(32)?,
            omega_dot: r.i(24)? as i32,
            idot: r.i(14)? as i32,
            codes_on_l2: r.u(2)? as u8,
            week_number: r.u(10)? as u16,
            ura: r.u(4)? as u8,
            sv_health: r.u(6)? as u8,
            t_gd: r.i(8)? as i16,
            iodc: r.u(10)? as u16,
            fit_interval: r.flag()?,
        })
    }

    pub fn encode(&self) -> Vec<u8> {
        let mut w = BitWriter::new();
        w.push_u(1044, 12);
        w.push_u(u64::from(self.satellite_id), 4);
        w.push_u(u64::from(self.t_oc), 16);
        w.push_i(i64::from(self.a_f2), 8);
        w.push_i(i64::from(self.a_f1), 16);
        w.push_i(i64::from(self.a_f0), 22);
        w.push_u(u64::from(self.iode), 8);
        w.push_i(i64::from(self.c_rs), 16);
        w.push_i(i64::from(self.delta_n), 16);
        w.push_i(self.m0, 32);
        w.push_i(i64::from(self.c_uc), 16);
        w.push_u(self.eccentricity, 32);
        w.push_i(i64::from(self.c_us), 16);
        w.push_u(self.sqrt_a, 32);
        w.push_u(u64::from(self.t_oe), 16);
        w.push_i(i64::from(self.c_ic), 16);
        w.push_i(self.omega0, 32);
        w.push_i(i64::from(self.c_is), 16);
        w.push_i(self.i0, 32);
        w.push_i(i64::from(self.c_rc), 16);
        w.push_i(self.omega, 32);
        w.push_i(i64::from(self.omega_dot), 24);
        w.push_i(i64::from(self.idot), 14);
        w.push_u(u64::from(self.codes_on_l2), 2);
        w.push_u(u64::from(self.week_number), 10);
        w.push_u(u64::from(self.ura), 4);
        w.push_u(u64::from(self.sv_health), 6);
        w.push_i(i64::from(self.t_gd), 8);
        w.push_u(u64::from(self.iodc), 10);
        w.push_flag(self.fit_interval);
        w.into_bytes()
    }

    pub fn to_broadcast_record(&self, full_week: u32) -> Result<BroadcastRecord> {
        if full_week % 1024 != u32::from(self.week_number) {
            return Err(Error::InvalidInput(format!(
                "QZSS full week {full_week} disagrees with 10-bit RTCM week {}",
                self.week_number
            )));
        }
        let satellite_id = self.satellite()?;
        let toe_sow = f64::from(self.t_oe) * 16.0;
        let toc_sow = f64::from(self.t_oc) * 16.0;
        let toe = gnss_week_tow(TimeScale::Gpst, full_week, toe_sow, "QZSS toe")?;
        let toc = gnss_week_tow(TimeScale::Gpst, full_week, toc_sow, "QZSS toc")?;
        Ok(BroadcastRecord {
            satellite_id,
            message: NavMessage::QzssLnav,
            issue_of_data: BroadcastIssue {
                issue: u32::from(self.iode),
                message: NavMessage::QzssLnav,
            },
            week: full_week,
            toe,
            toc,
            elements: KeplerianElements {
                sqrt_a: scaled_u(self.sqrt_a, -19),
                e: scaled_u(self.eccentricity, -33),
                m0: scaled_semicircle(self.m0, -31),
                delta_n: scaled_semicircle(self.delta_n, -43),
                omega0: scaled_semicircle(self.omega0, -31),
                i0: scaled_semicircle(self.i0, -31),
                omega: scaled_semicircle(self.omega, -31),
                omega_dot: scaled_semicircle(self.omega_dot, -43),
                idot: scaled_semicircle(self.idot, -43),
                cuc: scaled_i(self.c_uc, -29),
                cus: scaled_i(self.c_us, -29),
                crc: scaled_i(self.c_rc, -5),
                crs: scaled_i(self.c_rs, -5),
                cic: scaled_i(self.c_ic, -29),
                cis: scaled_i(self.c_is, -29),
                toe_sow,
            },
            clock: ClockPolynomial {
                af0: scaled_i(self.a_f0, -31),
                af1: scaled_i(self.a_f1, -43),
                af2: scaled_i(self.a_f2, -55),
                toc_sow,
            },
            group_delays: BroadcastGroupDelays::gps_lnav(scaled_i(self.t_gd, -31)),
            cnav: None,
            sv_health: f64::from(self.sv_health),
            sv_accuracy_m: ura_or_wide(self.ura),
            fit_interval_s: Some(if self.fit_interval {
                6.0 * SECONDS_PER_HOUR
            } else {
                2.0 * SECONDS_PER_HOUR
            }),
        })
    }
}

/// A decoded GLONASS broadcast ephemeris (message 1020).
///
/// The orbit position / velocity / acceleration terms use sign-and-magnitude
/// integers (DF111..DF119). Every field below is the raw transmitted integer;
/// the noted scale factors recover km, km/s, km/s^2, and seconds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GlonassEphemeris {
    /// GLONASS satellite slot number (DF038, 6 bits).
    pub satellite_id: u8,
    /// Frequency channel number (DF040, 5 bits; the wire value is k + 7).
    pub frequency_channel: u8,
    /// Almanac health C_n (DF104).
    pub almanac_health: bool,
    /// Almanac health availability (DF105).
    pub almanac_health_availability: bool,
    /// P1 flag (DF106, 2 bits).
    pub p1: u8,
    /// Frame time t_k (DF107, 12 bits).
    pub t_k: u16,
    /// MSB of the B_n health word (DF108).
    pub b_n_msb: bool,
    /// P2 flag (DF109).
    pub p2: bool,
    /// Ephemeris reference time t_b (DF110, 7 bits).
    pub t_b: u8,
    /// X-velocity (DF111, sign-magnitude 24-bit, scale 2^-20 km/s).
    pub xn_dot: i32,
    /// X-position (DF112, sign-magnitude 27-bit, scale 2^-11 km).
    pub xn: i32,
    /// X-acceleration (DF113, sign-magnitude 5-bit, scale 2^-30 km/s^2).
    pub xn_dot_dot: i8,
    /// Y-velocity (DF114, sign-magnitude 24-bit, scale 2^-20 km/s).
    pub yn_dot: i32,
    /// Y-position (DF115, sign-magnitude 27-bit, scale 2^-11 km).
    pub yn: i32,
    /// Y-acceleration (DF116, sign-magnitude 5-bit, scale 2^-30 km/s^2).
    pub yn_dot_dot: i8,
    /// Z-velocity (DF117, sign-magnitude 24-bit, scale 2^-20 km/s).
    pub zn_dot: i32,
    /// Z-position (DF118, sign-magnitude 27-bit, scale 2^-11 km).
    pub zn: i32,
    /// Z-acceleration (DF119, sign-magnitude 5-bit, scale 2^-30 km/s^2).
    pub zn_dot_dot: i8,
    /// P3 flag (DF120).
    pub p3: bool,
    /// Relative carrier-frequency offset gamma_n (DF121, sign-magnitude 11-bit,
    /// scale 2^-40).
    pub gamma_n: i16,
    /// GLONASS-M P flag (DF122, 2 bits).
    pub m_p: u8,
    /// Third-string l_n health flag (DF123).
    pub m_l_n_third: bool,
    /// Clock bias tau_n (DF124, sign-magnitude 22-bit, scale 2^-30 s).
    pub tau_n: i32,
    /// Inter-frequency bias delta_tau_n (DF125, sign-magnitude 5-bit, scale
    /// 2^-30 s).
    pub delta_tau_n: i8,
    /// Age of operation E_n (DF126, 5 bits, days).
    pub e_n: u8,
    /// GLONASS-M P4 flag (DF127).
    pub m_p4: bool,
    /// GLONASS-M F_t accuracy index (DF128, 4 bits).
    pub m_f_t: u8,
    /// GLONASS-M N_t calendar day number (DF129, 11 bits).
    pub m_n_t: u16,
    /// GLONASS-M M satellite type (DF130, 2 bits).
    pub m_m: u8,
    /// Additional data availability (DF131).
    pub additional_data_available: bool,
    /// N_A almanac reference day (DF132, 11 bits).
    pub n_a: u16,
    /// System time scale offset tau_c (DF133, sign-magnitude 32-bit, scale
    /// 2^-31 s).
    pub tau_c: i64,
    /// GLONASS-M N_4 four-year interval number (DF134, 5 bits).
    pub m_n4: u8,
    /// GLONASS-M tau_GPS offset to GPS time (DF135, sign-magnitude 22-bit, scale
    /// 2^-30 s).
    pub m_tau_gps: i32,
    /// Fifth-string l_n health flag (DF136).
    pub m_l_n_fifth: bool,
    /// Reserved field DF001 (7 bits), preserved for exact round-trip.
    pub reserved: u8,
}

impl GlonassEphemeris {
    /// The satellite identifier for this ephemeris.
    pub fn satellite(&self) -> Result<GnssSatelliteId> {
        GnssSatelliteId::new(GnssSystem::Glonass, self.satellite_id)
            .map_err(|e| Error::Parse(format!("invalid GLONASS slot in 1020: {e}")))
    }

    /// Decode a message 1020 body (without the transport frame).
    pub fn decode(body: &[u8]) -> Result<Self> {
        Self::decode_inner(body).map_err(Into::into)
    }

    pub(crate) fn decode_inner(body: &[u8]) -> DecodeResult<Self> {
        let mut r = BitReader::new(body);
        let message_number = r.u(12)? as u16;
        if message_number != 1020 {
            return Err(Error::Parse(format!(
                "message {message_number} is not GLONASS ephemeris 1020"
            ))
            .into());
        }
        Ok(Self {
            satellite_id: r.u(6)? as u8,
            frequency_channel: r.u(5)? as u8,
            almanac_health: r.flag()?,
            almanac_health_availability: r.flag()?,
            p1: r.u(2)? as u8,
            t_k: r.u(12)? as u16,
            b_n_msb: r.flag()?,
            p2: r.flag()?,
            t_b: r.u(7)? as u8,
            xn_dot: r.ism(24)? as i32,
            xn: r.ism(27)? as i32,
            xn_dot_dot: r.ism(5)? as i8,
            yn_dot: r.ism(24)? as i32,
            yn: r.ism(27)? as i32,
            yn_dot_dot: r.ism(5)? as i8,
            zn_dot: r.ism(24)? as i32,
            zn: r.ism(27)? as i32,
            zn_dot_dot: r.ism(5)? as i8,
            p3: r.flag()?,
            gamma_n: r.ism(11)? as i16,
            m_p: r.u(2)? as u8,
            m_l_n_third: r.flag()?,
            tau_n: r.ism(22)? as i32,
            delta_tau_n: r.ism(5)? as i8,
            e_n: r.u(5)? as u8,
            m_p4: r.flag()?,
            m_f_t: r.u(4)? as u8,
            m_n_t: r.u(11)? as u16,
            m_m: r.u(2)? as u8,
            additional_data_available: r.flag()?,
            n_a: r.u(11)? as u16,
            tau_c: r.ism(32)?,
            m_n4: r.u(5)? as u8,
            m_tau_gps: r.ism(22)? as i32,
            m_l_n_fifth: r.flag()?,
            reserved: r.u(7)? as u8,
        })
    }

    /// Encode this GLONASS ephemeris body (without the transport frame).
    pub fn encode(&self) -> Vec<u8> {
        let mut w = BitWriter::new();
        w.push_u(1020, 12);
        w.push_u(u64::from(self.satellite_id), 6);
        w.push_u(u64::from(self.frequency_channel), 5);
        w.push_flag(self.almanac_health);
        w.push_flag(self.almanac_health_availability);
        w.push_u(u64::from(self.p1), 2);
        w.push_u(u64::from(self.t_k), 12);
        w.push_flag(self.b_n_msb);
        w.push_flag(self.p2);
        w.push_u(u64::from(self.t_b), 7);
        w.push_ism(i64::from(self.xn_dot), 24);
        w.push_ism(i64::from(self.xn), 27);
        w.push_ism(i64::from(self.xn_dot_dot), 5);
        w.push_ism(i64::from(self.yn_dot), 24);
        w.push_ism(i64::from(self.yn), 27);
        w.push_ism(i64::from(self.yn_dot_dot), 5);
        w.push_ism(i64::from(self.zn_dot), 24);
        w.push_ism(i64::from(self.zn), 27);
        w.push_ism(i64::from(self.zn_dot_dot), 5);
        w.push_flag(self.p3);
        w.push_ism(i64::from(self.gamma_n), 11);
        w.push_u(u64::from(self.m_p), 2);
        w.push_flag(self.m_l_n_third);
        w.push_ism(i64::from(self.tau_n), 22);
        w.push_ism(i64::from(self.delta_tau_n), 5);
        w.push_u(u64::from(self.e_n), 5);
        w.push_flag(self.m_p4);
        w.push_u(u64::from(self.m_f_t), 4);
        w.push_u(u64::from(self.m_n_t), 11);
        w.push_u(u64::from(self.m_m), 2);
        w.push_flag(self.additional_data_available);
        w.push_u(u64::from(self.n_a), 11);
        w.push_ism(self.tau_c, 32);
        w.push_u(u64::from(self.m_n4), 5);
        w.push_ism(i64::from(self.m_tau_gps), 22);
        w.push_flag(self.m_l_n_fifth);
        w.push_u(u64::from(self.reserved), 7);
        w.into_bytes()
    }
}