Skip to main content

satellite_datetime/
ccsds.rs

1//! CCSDS 301.0-B-4 time codes. Recommended epoch: 1958-01-01 TAI (no leap seconds).
2
3use crate::constants::NS_PER_SEC;
4use crate::error::{Error, Result};
5use crate::instant::Instant;
6
7/// CUC configuration: 1–4 coarse octets (seconds) and 0–3 fine octets (fraction).
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub struct CucConfig {
10    /// Number of octets counting whole SI seconds from the TAI 1958 epoch (`1..=4`).
11    pub coarse_octets: u8,
12    /// Number of octets of binary fraction of a second (`0..=3`).
13    pub fine_octets: u8,
14}
15
16impl CucConfig {
17    /// 4-byte seconds + 2-byte fraction (~15.3 µs), a common agency choice.
18    pub const C4_F2: Self = Self {
19        coarse_octets: 4,
20        fine_octets: 2,
21    };
22
23    fn t_len(self) -> Result<usize> {
24        if !(1..=4).contains(&self.coarse_octets) || self.fine_octets > 3 {
25            return Err(Error::Codec);
26        }
27        Ok((self.coarse_octets + self.fine_octets) as usize)
28    }
29}
30
31/// One-octet CCSDS P-field for level-1 CUC (1958-01-01 TAI epoch).
32///
33/// Bit layout (MSB = bit 7): extension (0), time code ID `001`, coarse length minus
34/// one, fractional octet count. Matches CCSDS 301.0-B-4 §3.2.2 without a second P-octet.
35#[derive(Clone, Copy, Debug, Eq, PartialEq)]
36pub struct CucPField {
37    /// Coarse/fine layout implied by the preamble.
38    pub config: CucConfig,
39}
40
41const CUC_ID_TAI_1958: u8 = 0x01;
42const CUC_ID_AGENCY: u8 = 0x02;
43/// CDS level-1, 1958 epoch, 16-bit day, millisecond-of-day (no sub-millisecond segment).
44const CDS_P_DAY16_MS32: u8 = 0x40;
45
46impl CucPField {
47    /// Preamble for [`CucConfig::C4_F2`] (`0x1E`).
48    pub const C4_F2: Self = Self {
49        config: CucConfig::C4_F2,
50    };
51
52    /// Build a preamble for a supported coarse/fine layout.
53    pub fn new(config: CucConfig) -> Result<Self> {
54        config.t_len()?;
55        Ok(Self { config })
56    }
57
58    /// Parse a one-octet CUC P-field from the wire.
59    pub fn from_octet(octet: u8) -> Result<Self> {
60        if octet & 0x80 != 0 {
61            return Err(Error::Unsupported);
62        }
63        let id = (octet >> 4) & 0x07;
64        match id {
65            CUC_ID_TAI_1958 => {}
66            CUC_ID_AGENCY => return Err(Error::Unsupported),
67            _ => return Err(Error::Codec),
68        }
69        let coarse_minus_1 = (octet >> 2) & 0x03;
70        let fine = octet & 0x03;
71        let config = CucConfig {
72            coarse_octets: coarse_minus_1 + 1,
73            fine_octets: fine,
74        };
75        config.t_len()?;
76        Ok(Self { config })
77    }
78
79    /// Encode this preamble to one octet.
80    pub fn to_octet(self) -> u8 {
81        let c = self.config;
82        (CUC_ID_TAI_1958 << 4) | ((c.coarse_octets - 1) << 2) | c.fine_octets
83    }
84}
85
86fn decode_cds_p_octet(octet: u8) -> Result<()> {
87    if octet & 0x80 != 0 {
88        return Err(Error::Unsupported);
89    }
90    let id = (octet >> 4) & 0x07;
91    match id {
92        0x04 => {}
93        0x05 => return Err(Error::Unsupported),
94        _ => return Err(Error::Codec),
95    }
96    if octet & 0x0F != 0 {
97        return Err(Error::Unsupported);
98    }
99    Ok(())
100}
101
102/// Encode TAI since 1958-01-01 as CCSDS unsegmented time code (T-field only).
103pub fn encode_cuc(instant: Instant, cfg: CucConfig, out: &mut [u8]) -> Result<usize> {
104    let n = cfg.t_len()?;
105    if out.len() < n {
106        return Err(Error::BufferTooSmall);
107    }
108    let tai_ns = instant.as_tai_nanos();
109    if tai_ns < 0 {
110        return Err(Error::Codec);
111    }
112    let coarse = (tai_ns / NS_PER_SEC) as u64;
113    let frac_ns = (tai_ns % NS_PER_SEC) as u64;
114    let coarse_max = (1u64 << (8 * cfg.coarse_octets as u32)) - 1;
115    if coarse > coarse_max {
116        return Err(Error::Overflow);
117    }
118    let mut idx = 0;
119    for k in (0..cfg.coarse_octets).rev() {
120        out[idx] = ((coarse >> (8 * k)) & 0xff) as u8;
121        idx += 1;
122    }
123    // Fine field: binary fraction of a second, each octet is 1/256 of the previous.
124    let mut rem = frac_ns;
125    for _ in 0..cfg.fine_octets {
126        rem *= 256;
127        let byte = (rem / NS_PER_SEC as u64) as u8;
128        rem %= NS_PER_SEC as u64;
129        out[idx] = byte;
130        idx += 1;
131    }
132    Ok(n)
133}
134
135/// Decode a CUC T-field.
136pub fn decode_cuc(buf: &[u8], cfg: CucConfig) -> Result<Instant> {
137    let n = cfg.t_len()?;
138    if buf.len() < n {
139        return Err(Error::Codec);
140    }
141    let mut coarse: u64 = 0;
142    let mut i = 0;
143    for _ in 0..cfg.coarse_octets {
144        coarse = (coarse << 8) | buf[i] as u64;
145        i += 1;
146    }
147    let mut frac_ns: u64 = 0;
148    let mut num = 0u64;
149    let mut den = 1u64;
150    for _ in 0..cfg.fine_octets {
151        num = (num << 8) | buf[i] as u64;
152        den <<= 8;
153        i += 1;
154    }
155    if cfg.fine_octets > 0 {
156        frac_ns = ((num as u128 * NS_PER_SEC as u128) / den as u128) as u64;
157    }
158    let tai_ns = (coarse as i128)
159        .checked_mul(NS_PER_SEC)
160        .and_then(|s| s.checked_add(frac_ns as i128))
161        .ok_or(Error::Overflow)?;
162    Ok(Instant::from_tai_nanos(tai_ns))
163}
164
165/// Encode CUC P-field + T-field (`1 + coarse + fine` octets).
166pub fn encode_cuc_with_p(instant: Instant, cfg: CucConfig, out: &mut [u8]) -> Result<usize> {
167    let p = CucPField::new(cfg)?;
168    let t_len = cfg.t_len()?;
169    if out.len() < 1 + t_len {
170        return Err(Error::BufferTooSmall);
171    }
172    out[0] = p.to_octet();
173    let n = encode_cuc(instant, cfg, &mut out[1..])?;
174    Ok(1 + n)
175}
176
177/// Decode CUC P-field + T-field; returns the instant and the wire coarse/fine layout.
178pub fn decode_cuc_with_p(buf: &[u8]) -> Result<(Instant, CucConfig)> {
179    if buf.is_empty() {
180        return Err(Error::Codec);
181    }
182    let p = CucPField::from_octet(buf[0])?;
183    let instant = decode_cuc(&buf[1..], p.config)?;
184    Ok((instant, p.config))
185}
186
187/// CDS: 16-bit day count from 1958-01-01 + 32-bit milliseconds of day.
188pub fn encode_cds(instant: Instant, out: &mut [u8]) -> Result<usize> {
189    if out.len() < 6 {
190        return Err(Error::BufferTooSmall);
191    }
192    let ns = instant.as_tai_nanos();
193    if ns < 0 {
194        return Err(Error::Codec);
195    }
196    let days = ns / crate::NS_PER_DAY;
197    let ms = ((ns % crate::NS_PER_DAY) / 1_000_000) as u32;
198    if days > u16::MAX as i128 {
199        return Err(Error::Overflow);
200    }
201    let d = days as u16;
202    out[0] = (d >> 8) as u8;
203    out[1] = d as u8;
204    out[2] = (ms >> 24) as u8;
205    out[3] = (ms >> 16) as u8;
206    out[4] = (ms >> 8) as u8;
207    out[5] = ms as u8;
208    Ok(6)
209}
210
211/// Decode a 6-octet CDS T-field (day + millisecond of day).
212pub fn decode_cds(buf: &[u8]) -> Result<Instant> {
213    if buf.len() < 6 {
214        return Err(Error::Codec);
215    }
216    let days = u16::from_be_bytes([buf[0], buf[1]]) as i128;
217    let ms = u32::from_be_bytes([buf[2], buf[3], buf[4], buf[5]]) as i128;
218    if ms >= 86_400_000 {
219        return Err(Error::InvalidTime);
220    }
221    Ok(Instant::from_tai_nanos(
222        days * crate::NS_PER_DAY + ms * 1_000_000,
223    ))
224}
225
226/// Encode CDS P-field + 6-octet T-field (16-bit day + millisecond of day).
227pub fn encode_cds_with_p(instant: Instant, out: &mut [u8]) -> Result<usize> {
228    if out.len() < 7 {
229        return Err(Error::BufferTooSmall);
230    }
231    out[0] = CDS_P_DAY16_MS32;
232    encode_cds(instant, &mut out[1..])?;
233    Ok(7)
234}
235
236/// Decode CDS P-field + T-field.
237pub fn decode_cds_with_p(buf: &[u8]) -> Result<Instant> {
238    if buf.len() < 7 {
239        return Err(Error::Codec);
240    }
241    decode_cds_p_octet(buf[0])?;
242    decode_cds(&buf[1..])
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248    use crate::duration::Duration;
249
250    #[test]
251    fn cuc_roundtrip() {
252        let t = Instant::TAI_EPOCH
253            .checked_add(Duration::from_seconds(1_234_567))
254            .unwrap()
255            .checked_add(Duration::from_millis(15))
256            .unwrap();
257        let mut buf = [0u8; 8];
258        let n = encode_cuc(t, CucConfig::C4_F2, &mut buf).unwrap();
259        let back = decode_cuc(&buf[..n], CucConfig::C4_F2).unwrap();
260        let err = t.duration_since(back).unwrap().as_nanos().abs();
261        assert!(err < 20_000, "err ns {err}"); // 2-byte fraction ~15µs
262    }
263
264    #[test]
265    fn cds_roundtrip() {
266        let t = Instant::from_tai_nanos(10_000 * crate::NS_PER_DAY + 43_200_000 * 1_000_000);
267        let mut buf = [0u8; 6];
268        encode_cds(t, &mut buf).unwrap();
269        assert_eq!(decode_cds(&buf).unwrap(), t);
270    }
271
272    #[test]
273    fn cuc_p_c4f2_octet() {
274        assert_eq!(CucPField::C4_F2.to_octet(), 0x1E);
275        assert_eq!(
276            CucPField::from_octet(0x1E).unwrap().config,
277            CucConfig::C4_F2
278        );
279    }
280
281    #[test]
282    fn cuc_with_p_roundtrip() {
283        let t = Instant::TAI_EPOCH
284            .checked_add(Duration::from_seconds(42))
285            .unwrap();
286        let mut buf = [0u8; 9];
287        let n = encode_cuc_with_p(t, CucConfig::C4_F2, &mut buf).unwrap();
288        assert_eq!(n, 7);
289        assert_eq!(buf[0], 0x1E);
290        let (back, cfg) = decode_cuc_with_p(&buf[..n]).unwrap();
291        assert_eq!(cfg, CucConfig::C4_F2);
292        assert_eq!(back, t);
293    }
294
295    #[test]
296    fn cuc_p_rejects_extension_and_agency() {
297        assert_eq!(CucPField::from_octet(0x9E).unwrap_err(), Error::Unsupported);
298        assert_eq!(CucPField::from_octet(0x2E).unwrap_err(), Error::Unsupported);
299    }
300
301    #[test]
302    fn cds_with_p_roundtrip() {
303        let t = Instant::from_tai_nanos(10_000 * crate::NS_PER_DAY + 43_200_000 * 1_000_000);
304        let mut buf = [0u8; 7];
305        let n = encode_cds_with_p(t, &mut buf).unwrap();
306        assert_eq!(n, 7);
307        assert_eq!(buf[0], 0x40);
308        assert_eq!(decode_cds_with_p(&buf).unwrap(), t);
309    }
310
311    #[test]
312    fn cds_p_rejects_agency_layout() {
313        assert_eq!(
314            decode_cds_with_p(&[0x50, 0, 0, 0, 0, 0, 0]).unwrap_err(),
315            Error::Unsupported
316        );
317    }
318}