Skip to main content

rustflexstack/facilities/decentralized_environmental_notification_service/
denm_coder.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! DENM UPER codec shim.
5//!
6//! Re-exports the compiled ASN.1 types from [`super::denm_bindings`] and
7//! wraps the stateless UPER encode/decode calls in a [`DenmCoder`] struct
8//! that can be cloned and shared cheaply between threads.
9//!
10//! All ASN.1 type definitions live in [`super::denm_bindings`].
11
12// ─── Re-exports from compiled ASN.1 bindings ─────────────────────────────────
13
14pub use super::denm_bindings::denm_pdu_description::{
15    AlacarteContainer, DenmPayload, LocationContainer, ManagementContainer, SituationContainer,
16    Termination, DENM,
17};
18pub use super::denm_bindings::etsi_its_cdd::{
19    AccidentSubCauseCode, ActionId, Altitude, AltitudeConfidence, AltitudeValue, CauseCodeChoice,
20    CauseCodeV2, DeltaAltitude, DeltaLatitude, DeltaLongitude, DeltaReferencePosition,
21    DeltaTimeMilliSecondPositive, DeltaTimeSecond, HeadingValue, InformationQuality, ItsPduHeader,
22    Latitude, Longitude, MessageId, OrdinalNumber1B, Path, PathPoint, PosConfidenceEllipse,
23    ReferencePosition, SemiAxisLength, SequenceNumber, Speed, SpeedConfidence, SpeedValue,
24    StationId, StationType, SubCauseCodeType, TimestampIts, Traces, TrafficParticipantType,
25    Wgs84Angle, Wgs84AngleConfidence, Wgs84AngleValue,
26};
27
28// ─── ITS epoch constant ───────────────────────────────────────────────────────
29
30/// ITS epoch offset from UNIX epoch in milliseconds
31/// (2004-01-01T00:00:00 UTC = 1 072 911 600 s).
32use crate::security::time_service::unix_ms_to_its_ms;
33
34/// Return the current ITS timestamp (milliseconds since ITS epoch) as a
35/// [`TimestampIts`].
36///
37/// TimestampIts is a u64 counting milliseconds since 2004-01-01T00:00:00 UTC.
38pub fn timestamp_its_now() -> TimestampIts {
39    use std::time::{SystemTime, UNIX_EPOCH};
40    let unix_ms = SystemTime::now()
41        .duration_since(UNIX_EPOCH)
42        .unwrap_or_default()
43        .as_millis() as u64;
44    TimestampIts(unix_ms_to_its_ms(unix_ms))
45}
46
47// ─── ITS PDU Header helper ────────────────────────────────────────────────────
48
49/// Build a standard DENM ITS PDU Header (protocol version 2, message ID 1).
50pub fn denm_header(station_id: u32) -> ItsPduHeader {
51    ItsPduHeader::new(OrdinalNumber1B(2), MessageId(1), StationId(station_id))
52}
53
54// ─── Top-level type alias ─────────────────────────────────────────────────────
55
56/// Top-level DENM PDU (alias for [`DENM`] from denm_bindings).
57pub type Denm = DENM;
58
59// ─── DenmCoder ───────────────────────────────────────────────────────────────
60
61/// UPER encoder/decoder for DENM PDUs.
62///
63/// Mirrors `DENMCoder` in
64/// `flexstack/facilities/decentralized_environmental_notification_service/denm_coder.py`.
65///
66/// Internally stateless. `Clone` is cheap — used to share a single instance
67/// between the transmission and reception management threads.
68#[derive(Clone, Debug, Default)]
69pub struct DenmCoder;
70
71impl DenmCoder {
72    pub fn new() -> Self {
73        DenmCoder
74    }
75
76    /// UPER-encode a [`Denm`] PDU to bytes.
77    pub fn encode(&self, denm: &Denm) -> Result<Vec<u8>, String> {
78        rasn::uper::encode(denm)
79            .map(|b| b.to_vec())
80            .map_err(|e| format!("DENM UPER encode error: {e}"))
81    }
82
83    /// UPER-decode a [`Denm`] PDU from bytes.
84    pub fn decode(&self, bytes: &[u8]) -> Result<Denm, String> {
85        rasn::uper::decode::<Denm>(bytes).map_err(|e| format!("DENM UPER decode error: {e}"))
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92
93    #[test]
94    fn timestamp_its_now_positive() {
95        let ts = timestamp_its_now();
96        assert!(ts.0 > 0);
97    }
98
99    #[test]
100    fn denm_header_fields() {
101        let hdr = denm_header(99);
102        assert_eq!(hdr.protocol_version.0, 2);
103        assert_eq!(hdr.message_id.0, 1);
104        assert_eq!(hdr.station_id.0, 99);
105    }
106
107    #[test]
108    fn denm_coder_new() {
109        let coder = DenmCoder::new();
110        let coder2 = coder.clone();
111        let _ = format!("{:?}", coder2);
112    }
113
114    #[test]
115    fn denm_coder_default() {
116        let _coder = DenmCoder;
117    }
118
119    #[test]
120    fn denm_coder_decode_invalid_bytes() {
121        let coder = DenmCoder::new();
122        let result = coder.decode(&[0xFF, 0xFF]);
123        assert!(result.is_err());
124    }
125}