Skip to main content

rustflexstack/geonet/
position_vector.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4use std::cmp::{PartialEq, PartialOrd};
5use std::ops::{Add, Sub};
6
7use super::gn_address::GNAddress;
8
9#[derive(Clone, Copy, Debug)]
10pub struct Tst {
11    msec: u32,
12}
13
14impl Tst {
15    /// TST of a Unix (UTC) timestamp in ms: TAI milliseconds since the ITS
16    /// epoch 2004-01-01T00:00:00Z, modulo 2^32 (ETSI TS 103 836-4-1).
17    pub fn set_in_normal_timestamp_milliseconds(msec: u64) -> Self {
18        let its_ms = crate::security::time_service::unix_ms_to_its_ms(msec);
19        Tst {
20            msec: (its_ms & 0xFFFF_FFFF) as u32,
21        }
22    }
23
24    pub fn set_in_normal_timestamp_seconds(sec: u64) -> Self {
25        Self::set_in_normal_timestamp_milliseconds(sec * 1000)
26    }
27
28    pub fn encode(&self) -> [u8; 4] {
29        self.msec.to_be_bytes()
30    }
31
32    pub fn decode(bytes: &[u8]) -> Self {
33        let mut msec: u32 = 0;
34        for (i, &byte) in bytes.iter().enumerate().take(4) {
35            msec |= (byte as u32) << (8 * (3 - i));
36        }
37        Tst { msec }
38    }
39}
40
41impl Sub for Tst {
42    type Output = u32;
43
44    fn sub(self, other: Self) -> u32 {
45        self.msec.wrapping_sub(other.msec)
46    }
47}
48
49impl Add for Tst {
50    type Output = Tst;
51
52    fn add(self, other: Self) -> Tst {
53        Tst {
54            msec: self.msec + other.msec,
55        }
56    }
57}
58
59impl PartialEq for Tst {
60    fn eq(&self, other: &Self) -> bool {
61        self.msec == other.msec
62    }
63}
64
65impl PartialOrd for Tst {
66    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
67        // 2^31 is the serial-number half-range used for TAI ms wraparound comparison
68        // (RFC 1982 / ETSI TS 103 836-4-1 V2.2.1, Annex C.2).
69        // We must NOT use 2u32.pow(32) — that overflows u32 in debug builds.
70        const HALF: u32 = 0x8000_0000;
71        if (self.msec > other.msec && self.msec - other.msec <= HALF)
72            || (other.msec > self.msec && other.msec - self.msec > HALF)
73        {
74            Some(std::cmp::Ordering::Greater)
75        } else if self == other {
76            Some(std::cmp::Ordering::Equal)
77        } else {
78            Some(std::cmp::Ordering::Less)
79        }
80    }
81}
82
83#[derive(Clone, Copy, Debug)]
84pub struct LongPositionVector {
85    pub gn_addr: GNAddress,
86    pub tst: Tst,
87    pub latitude: u32,
88    pub longitude: u32,
89    pub pai: bool,
90    pub s: u16,
91    pub h: u16,
92}
93
94impl LongPositionVector {
95    pub fn encode(&self) -> [u8; 24] {
96        let mut bytes: [u8; 24] = [0; 24];
97        bytes[0..8].clone_from_slice(&self.gn_addr.encode());
98        bytes[8..12].clone_from_slice(&self.tst.encode());
99        bytes[12..16].clone_from_slice(&self.latitude.to_be_bytes());
100        bytes[16..20].clone_from_slice(&self.longitude.to_be_bytes());
101        // Byte 20: PAI flag (bit 7) | speed high byte (bits 0-6)
102        bytes[20] = ((self.pai as u8) << 7) | ((self.s >> 8) as u8 & 0x7F);
103        bytes[21] = (self.s & 0xFF) as u8;
104        bytes[22..24].clone_from_slice(&self.h.to_be_bytes());
105        bytes
106    }
107
108    pub fn decode(bytes: [u8; 24]) -> Self {
109        let gn_addr = GNAddress::decode(&bytes[0..8]);
110        let tst = Tst::decode(&bytes[8..12]);
111        let mut latitude: u32 = 0;
112        for i in 0..4 {
113            latitude |= (bytes[12 + i] as u32) << (8 * (3 - i));
114        }
115        let mut longitude: u32 = 0;
116        for i in 0..4 {
117            longitude |= (bytes[16 + i] as u32) << (8 * (3 - i));
118        }
119        let pai = (bytes[20] >> 7) == 1;
120        // Speed is 15 bits: lower 7 bits of byte 20 + all of byte 21
121        let s: u16 = (((bytes[20] & 0x7F) as u16) << 8) | (bytes[21] as u16);
122        let mut h: u16 = 0;
123        for i in 0..2 {
124            h |= (bytes[22 + i] as u16) << (8 * (1 - i));
125        }
126        LongPositionVector {
127            gn_addr,
128            tst,
129            latitude,
130            longitude,
131            pai,
132            s,
133            h,
134        }
135    }
136}
137
138impl PartialEq for LongPositionVector {
139    fn eq(&self, other: &Self) -> bool {
140        self.gn_addr == other.gn_addr
141            && self.tst == other.tst
142            && self.latitude == other.latitude
143            && self.longitude == other.longitude
144            && self.pai == other.pai
145            && self.s == other.s
146            && self.h == other.h
147    }
148}
149
150impl LongPositionVector {
151    /// Update position, speed, heading and accuracy from a GPS measurement.
152    ///
153    /// * `latitude_deg`  – latitude in degrees (positive = North)
154    /// * `longitude_deg` – longitude in degrees (positive = East)
155    /// * `speed_mps`     – speed in m/s (0.01 m/s resolution, max 163.82 m/s)
156    /// * `heading_deg`   – heading in degrees (0 = North, clockwise)
157    /// * `pai`           – position accuracy indicator
158    pub fn update_from_gps(
159        &mut self,
160        latitude_deg: f64,
161        longitude_deg: f64,
162        speed_mps: f64,
163        heading_deg: f64,
164        pai: bool,
165    ) {
166        self.update_from_gps_at(
167            latitude_deg,
168            longitude_deg,
169            speed_mps,
170            heading_deg,
171            pai,
172            None,
173        );
174    }
175
176    /// [`LongPositionVector::update_from_gps`] with the UTC acquisition time
177    /// of the position (ms since the Unix epoch) as TST (clause 9.5.2.2);
178    /// the current time when `None`.
179    pub fn update_from_gps_at(
180        &mut self,
181        latitude_deg: f64,
182        longitude_deg: f64,
183        speed_mps: f64,
184        heading_deg: f64,
185        pai: bool,
186        fix_time_ms: Option<u64>,
187    ) {
188        use std::time::SystemTime;
189        // Encode latitude and longitude as 1/10 microdegrees (i32, cast to u32)
190        self.latitude = ((latitude_deg * 1e7) as i32) as u32;
191        self.longitude = ((longitude_deg * 1e7) as i32) as u32;
192        // Speed in units of 0.01 m/s, 15-bit value
193        self.s = ((speed_mps / 0.01) as u16).min(0x7FFF);
194        // Heading in units of 0.1 degrees, 16-bit value
195        self.h = ((heading_deg * 10.0) as u16) % 3600;
196        self.pai = pai;
197        // TST: acquisition time of the position (TAI), the current time if unknown
198        let unix_ms = fix_time_ms.unwrap_or_else(|| {
199            SystemTime::now()
200                .duration_since(SystemTime::UNIX_EPOCH)
201                .unwrap_or_default()
202                .as_millis() as u64
203        });
204        self.tst = Tst::set_in_normal_timestamp_milliseconds(unix_ms);
205    }
206}
207
208#[derive(Clone, Debug)]
209pub struct ShortPositionVector {
210    pub gn_address: GNAddress,
211    pub tst: Tst,
212    pub latitude: u32,
213    pub longitude: u32,
214}
215
216impl ShortPositionVector {
217    pub fn encode(&self) -> [u8; 20] {
218        let mut bytes: [u8; 20] = [0; 20];
219        bytes[0..8].clone_from_slice(&self.gn_address.encode());
220        bytes[8..12].clone_from_slice(&self.tst.encode());
221        bytes[12..16].clone_from_slice(&self.latitude.to_be_bytes());
222        bytes[16..20].clone_from_slice(&self.longitude.to_be_bytes());
223        bytes
224    }
225
226    pub fn decode(bytes: [u8; 20]) -> Self {
227        let gn_address = GNAddress::decode(&bytes[0..8]);
228        let tst = Tst::decode(&bytes[8..12]);
229        let mut latitude: u32 = 0;
230        for i in 0..4 {
231            latitude |= (bytes[12 + i] as u32) << (8 * (3 - i));
232        }
233        let mut longitude: u32 = 0;
234        for i in 0..4 {
235            longitude |= (bytes[16 + i] as u32) << (8 * (3 - i));
236        }
237        ShortPositionVector {
238            gn_address,
239            tst,
240            latitude,
241            longitude,
242        }
243    }
244}
245
246impl PartialEq for ShortPositionVector {
247    fn eq(&self, other: &Self) -> bool {
248        self.gn_address == other.gn_address
249            && self.tst == other.tst
250            && self.latitude == other.latitude
251            && self.longitude == other.longitude
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258    use crate::geonet::gn_address::{GNAddress, M, MID, ST};
259
260    // ── Tst ────────────────────────────────────────────────────────────
261
262    #[test]
263    fn tst_from_unix_ms() {
264        // 2024-06-01T00:00:00 UTC ≈ 1 717 200 000 000 ms
265        let unix_ms: u64 = 1_717_200_000_000;
266        let tst = Tst::set_in_normal_timestamp_milliseconds(unix_ms);
267        // ITS epoch 2004-01-01T00:00:00Z = 1 072 915 200 s, plus 5 leap seconds (TAI).
268        let expected = ((unix_ms - 1_072_915_200_000 + 5_000) & 0xFFFF_FFFF) as u32;
269        assert_eq!(tst.msec, expected);
270    }
271
272    #[test]
273    fn tst_zero_before_epoch() {
274        // Before TAI offset → should be 0
275        let tst = Tst::set_in_normal_timestamp_milliseconds(0);
276        assert_eq!(tst.msec, 0);
277    }
278
279    #[test]
280    fn tst_encode_decode_roundtrip() {
281        let tst = Tst::set_in_normal_timestamp_milliseconds(1_717_200_000_000);
282        let bytes = tst.encode();
283        let decoded = Tst::decode(&bytes);
284        assert_eq!(tst, decoded);
285    }
286
287    #[test]
288    fn tst_subtraction() {
289        let a = Tst { msec: 5000 };
290        let b = Tst { msec: 3000 };
291        assert_eq!(a - b, 2000);
292    }
293
294    #[test]
295    fn tst_addition() {
296        let a = Tst { msec: 1000 };
297        let b = Tst { msec: 2000 };
298        let c = a + b;
299        assert_eq!(c.msec, 3000);
300    }
301
302    #[test]
303    fn tst_equality() {
304        let a = Tst { msec: 42 };
305        let b = Tst { msec: 42 };
306        assert_eq!(a, b);
307    }
308
309    #[test]
310    fn tst_ordering_simple() {
311        let a = Tst { msec: 100 };
312        let b = Tst { msec: 200 };
313        assert!(a < b);
314        assert!(b > a);
315    }
316
317    #[test]
318    fn tst_ordering_wraparound() {
319        // RFC 1982: if b - a > HALF, then a > b (wraparound)
320        let a = Tst { msec: 0xFFFF_FFFF };
321        let b = Tst { msec: 1 };
322        // a is "before" b in the wraparound sense
323        assert!(a < b);
324    }
325
326    // ── LongPositionVector ─────────────────────────────────────────────
327
328    #[test]
329    fn lpv_encode_decode_roundtrip() {
330        let addr = GNAddress::new(M::GnUnicast, ST::PassengerCar, MID::new([1, 2, 3, 4, 5, 6]));
331        let tst = Tst::set_in_normal_timestamp_milliseconds(1_717_200_000_000);
332        let lpv = LongPositionVector {
333            gn_addr: addr,
334            tst,
335            latitude: 415520000, // 41.552°
336            longitude: 21340000, // 2.134°
337            pai: true,
338            s: 1000, // 10.00 m/s
339            h: 900,  // 90.0°
340        };
341        let encoded = lpv.encode();
342        assert_eq!(encoded.len(), 24);
343        let decoded = LongPositionVector::decode(encoded);
344        assert_eq!(lpv, decoded);
345    }
346
347    #[test]
348    fn lpv_pai_flag() {
349        let mut lpv = LongPositionVector::decode([0u8; 24]);
350        lpv.pai = true;
351        let encoded = lpv.encode();
352        assert_eq!(encoded[20] >> 7, 1);
353
354        lpv.pai = false;
355        let encoded = lpv.encode();
356        assert_eq!(encoded[20] >> 7, 0);
357    }
358
359    #[test]
360    fn lpv_speed_15bit() {
361        let mut lpv = LongPositionVector::decode([0u8; 24]);
362        lpv.s = 0x7FFF; // max 15-bit
363        lpv.pai = false;
364        let encoded = lpv.encode();
365        let decoded = LongPositionVector::decode(encoded);
366        assert_eq!(decoded.s, 0x7FFF);
367    }
368
369    #[test]
370    fn lpv_equality() {
371        let a = LongPositionVector::decode([0u8; 24]);
372        let b = LongPositionVector::decode([0u8; 24]);
373        assert_eq!(a, b);
374    }
375
376    // ── ShortPositionVector ────────────────────────────────────────────
377
378    #[test]
379    fn spv_encode_decode_roundtrip() {
380        let addr = GNAddress::new(
381            M::GnMulticast,
382            ST::Bus,
383            MID::new([0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF]),
384        );
385        let tst = Tst::set_in_normal_timestamp_milliseconds(1_717_200_000_000);
386        let spv = ShortPositionVector {
387            gn_address: addr,
388            tst,
389            latitude: 415520000,
390            longitude: 21340000,
391        };
392        let encoded = spv.encode();
393        assert_eq!(encoded.len(), 20);
394        let decoded = ShortPositionVector::decode(encoded);
395        assert_eq!(spv, decoded);
396    }
397
398    #[test]
399    fn spv_equality() {
400        let a = ShortPositionVector::decode([0u8; 20]);
401        let b = ShortPositionVector::decode([0u8; 20]);
402        assert_eq!(a, b);
403    }
404}