Skip to main content

rustflexstack/facilities/decentralized_environmental_notification_service/
denm_transmission.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 transmission: originating ITS-S operation of the DEN service
5//! (ETSI TS 103 831 V2.3.1 (2025-11), clauses 5.3.1 and 8.2).
6//!
7//! The protocol rules live in [`super::den_protocol`]; this module turns
8//! application requests into protocol operations and hands the resulting DENMs
9//! to BTP (port 2002, GeoBroadcast, clause 6.1.3.4).
10//!
11//! Two request styles are supported:
12//! * the standard requests [`DENMTransmissionManagement::trigger`],
13//!   [`update`](DENMTransmissionManagement::update) and
14//!   [`terminate`](DENMTransmissionManagement::terminate) (AppDENM_trigger,
15//!   AppDENM_update, AppDENM_termination) taking a [`DenmRequest`];
16//! * the road-hazard [`DENRequest`], converted to an AppDENM_trigger with
17//!   repetition ([`DENMTransmissionManagement::trigger_denm_sending`]).
18//!
19//! Mirrors `flexstack/facilities/decentralized_environmental_notification_service/denm_transmission_management.py`.
20
21use super::den_protocol::{DenActionId, DenProtocol, DenResult, DenmRequest, OutgoingDenm};
22use super::denm_coder::{
23    denm_header, timestamp_its_now, ActionId, Altitude, AltitudeConfidence, AltitudeValue,
24    CauseCodeChoice, CauseCodeV2, DeltaAltitude, DeltaLatitude, DeltaLongitude,
25    DeltaReferencePosition, DeltaTimeMilliSecondPositive, DeltaTimeSecond, Denm, DenmCoder,
26    DenmPayload, HeadingValue, InformationQuality, Latitude, LocationContainer, Longitude,
27    ManagementContainer, Path, PathPoint, PosConfidenceEllipse, ReferencePosition, SemiAxisLength,
28    SequenceNumber, SituationContainer, Speed, SpeedConfidence, SpeedValue, StationId, StationType,
29    Traces, TrafficParticipantType, Wgs84Angle, Wgs84AngleConfidence, Wgs84AngleValue,
30};
31use crate::btp::router::BTPRouterHandle;
32use crate::btp::service_access_point::BTPDataRequest;
33use crate::geonet::gn_address::{GNAddress, M, MID, ST};
34use crate::geonet::service_access_point::{
35    Area, CommonNH, CommunicationProfile, HeaderSubType, HeaderType, PacketTransportType,
36};
37use crate::security::sn_sap::SecurityProfile;
38use std::sync::{Arc, Condvar, Mutex};
39
40/// BTP port of the DEN service (ETSI TS 103 248).
41pub const DENM_BTP_PORT: u16 = 2002;
42/// ITS-AID of the DEN service (ETSI TS 102 965).
43pub const DENM_ITS_AID: u64 = 37;
44
45/// Source of the current time of the DEN service (TimestampIts, ms).
46pub type DenClock = Arc<dyn Fn() -> u64 + Send + Sync>;
47
48/// Protocol engine shared by transmission, reception and the timer thread.
49pub struct DenShared {
50    pub protocol: Mutex<DenProtocol>,
51    /// Signalled whenever the protocol timers may have changed.
52    pub wakeup: Condvar,
53    clock: Option<DenClock>,
54}
55
56impl DenShared {
57    pub fn new(protocol: DenProtocol) -> Arc<Self> {
58        Self::with_clock(protocol, None)
59    }
60
61    /// Shared engine whose time is read from `clock` (the system time when `None`).
62    pub fn with_clock(protocol: DenProtocol, clock: Option<DenClock>) -> Arc<Self> {
63        Arc::new(DenShared {
64            protocol: Mutex::new(protocol),
65            wakeup: Condvar::new(),
66            clock,
67        })
68    }
69
70    /// Current TimestampIts (ms) of the DEN service.
71    pub fn now(&self) -> u64 {
72        self.clock
73            .as_ref()
74            .map_or_else(|| timestamp_its_now().0, |clock| clock())
75    }
76}
77
78// ─── VehicleData ─────────────────────────────────────────────────────────────
79
80/// Static vehicle data used to populate every DENM.
81///
82/// Mirrors `VehicleData` from the CA Basic Service Python implementation
83/// (re-used in the DEN Service as well).
84#[derive(Debug, Clone)]
85pub struct VehicleData {
86    /// ITS station ID.
87    pub station_id: u32,
88    /// ITS station type (TrafficParticipantType).
89    /// Common values: 0 = unknown, 5 = passengerCar, 6 = bus, 15 = rsu.
90    pub station_type: u8,
91}
92
93impl Default for VehicleData {
94    fn default() -> Self {
95        VehicleData {
96            station_id: 0,
97            station_type: 5, // passengerCar
98        }
99    }
100}
101
102// ─── DENRequest ──────────────────────────────────────────────────────────────
103
104/// Parameters passed by the application layer to request a DENM transmission.
105///
106/// Mirrors `DENRequest` from
107/// `flexstack/applications/road_hazard_signalling_service/service_access_point.py`.
108#[derive(Debug, Clone)]
109pub struct DENRequest {
110    // ── Event position ───────────────────────────────────────────────────────
111    /// Event latitude in decimal degrees (WGS-84).
112    pub event_latitude: f64,
113    /// Event longitude in decimal degrees (WGS-84).
114    pub event_longitude: f64,
115    /// Event altitude in metres above WGS-84 ellipsoid.
116    pub event_altitude_m: f64,
117
118    // ── Cause code ───────────────────────────────────────────────────────────
119    /// ITS cause code choice for the event type.
120    pub cause_code: CauseCodeChoice,
121
122    // ── Quality / kinematics at the event ────────────────────────────────────
123    /// Information quality (0 = unavailable, 1–7 valid, 7 = highest).
124    pub information_quality: u8,
125    /// Event speed in 0.01 m/s (16 383 = unavailable).
126    pub event_speed_raw: u16,
127    /// Event heading in 0.1 ° (3 601 = unavailable).
128    pub event_heading_raw: u16,
129
130    // ── Transmission timing ──────────────────────────────────────────────────
131    /// DENM re-transmission interval in milliseconds.
132    pub denm_interval_ms: u64,
133    /// Total period to keep sending DENMs in milliseconds.
134    pub time_period_ms: u64,
135
136    // ── Geo-broadcast radius ─────────────────────────────────────────────────
137    /// Radius of the geo-broadcast circle in metres.
138    pub relevance_radius_m: u32,
139}
140
141impl Default for DENRequest {
142    fn default() -> Self {
143        DENRequest {
144            event_latitude: 0.0,
145            event_longitude: 0.0,
146            event_altitude_m: 0.0,
147            cause_code: CauseCodeChoice::accident2(super::denm_coder::AccidentSubCauseCode(0)),
148            information_quality: 0,
149            event_speed_raw: 16383,  // unavailable
150            event_heading_raw: 3601, // unavailable
151            denm_interval_ms: 1000,
152            time_period_ms: 5000,
153            relevance_radius_m: 1000,
154        }
155    }
156}
157
158// ─── DENM builder ────────────────────────────────────────────────────────────
159
160/// Build a single [`Denm`] PDU from a [`DENRequest`] and vehicle data.
161pub fn build_denm(request: &DENRequest, vd: &VehicleData, seq_nr: u16) -> Denm {
162    let now = timestamp_its_now();
163
164    // ── ManagementContainer ───────────────────────────────────────────────────
165    let event_pos = ReferencePosition::new(
166        Latitude(((request.event_latitude * 1e7).round() as i32).clamp(-900_000_000, 900_000_000)),
167        Longitude(
168            ((request.event_longitude * 1e7).round() as i32).clamp(-1_800_000_000, 1_800_000_000),
169        ),
170        PosConfidenceEllipse::new(
171            SemiAxisLength(4095), // unavailable
172            SemiAxisLength(4095), // unavailable
173            HeadingValue(3601),   // unavailable (uses HeadingValue in DENM)
174        ),
175        Altitude::new(
176            AltitudeValue(
177                ((request.event_altitude_m * 100.0).round() as i32).clamp(-100_000, 800_000),
178            ),
179            AltitudeConfidence::unavailable,
180        ),
181    );
182
183    let action_id = ActionId::new(StationId(vd.station_id), SequenceNumber(seq_nr));
184
185    let management = ManagementContainer::new(
186        action_id,
187        now.clone(), // detectionTime
188        now.clone(), // referenceTime
189        None,        // termination — active DENM
190        event_pos,
191        None,                 // awarenessDistance
192        None,                 // trafficDirection
193        DeltaTimeSecond(600), // validityDuration: 600 s default
194        Some(DeltaTimeMilliSecondPositive(
195            request.denm_interval_ms.min(10_000) as u16,
196        )),
197        StationType(TrafficParticipantType(vd.station_type)),
198    );
199
200    // ── SituationContainer ────────────────────────────────────────────────────
201    let situation = SituationContainer::new(
202        InformationQuality(request.information_quality.min(7)),
203        CauseCodeV2::new(request.cause_code.clone()),
204        None, // linkedCause
205        None, // eventZone
206        None, // ext_group_linked_denms
207        None, // ext_group_event_end_factor
208    );
209
210    // ── LocationContainer ─────────────────────────────────────────────────────
211    // A minimal detection zone: one path with one point at the event position
212    // delta (zero offset — the event is at the reference position).
213    let path_point = PathPoint::new(
214        DeltaReferencePosition::new(
215            DeltaLatitude(131072),  // 131072 = unavailable
216            DeltaLongitude(131072), // 131072 = unavailable
217            DeltaAltitude(12800),   // 12800  = unavailable
218        ),
219        None, // pathDeltaTime
220    );
221    let path = Path(rasn::types::SequenceOf::from(vec![path_point]));
222    let traces = Traces(rasn::types::SequenceOf::from(vec![path]));
223
224    let event_speed = Speed::new(
225        SpeedValue(request.event_speed_raw.min(16_383)),
226        SpeedConfidence(127), // unavailable
227    );
228    let event_heading = Wgs84Angle::new(
229        Wgs84AngleValue(request.event_heading_raw.min(3601)),
230        Wgs84AngleConfidence(127), // unavailable
231    );
232
233    let location = LocationContainer::new(
234        Some(event_speed),
235        Some(event_heading),
236        traces,
237        None, // roadType
238        None, // ext_group_lane_positions
239    );
240
241    // ── Assemble DENM ─────────────────────────────────────────────────────────
242    Denm::new(
243        denm_header(vd.station_id),
244        DenmPayload::new(
245            management,
246            Some(situation),
247            Some(location),
248            None, // alacarte
249        ),
250    )
251}
252
253// ─── DENMTransmissionManagement ──────────────────────────────────────────────
254
255/// Originating ITS-S operation of the DEN service (clause 8.2).
256///
257/// Mirrors `DENMTransmissionManagement` in the Python stack.
258pub struct DENMTransmissionManagement {
259    btp_handle: BTPRouterHandle,
260    coder: DenmCoder,
261    vehicle_data: VehicleData,
262    shared: Arc<DenShared>,
263}
264
265/// Engine for a DEN service of this station; DENMs are validated by encoding.
266pub fn new_protocol(
267    vehicle_data: &VehicleData,
268    kaf_enabled: bool,
269    coder: &DenmCoder,
270) -> DenProtocol {
271    let coder = coder.clone();
272    DenProtocol::new(
273        vehicle_data.station_id,
274        vehicle_data.station_type,
275        kaf_enabled,
276        Some(Box::new(move |denm: &Denm| coder.encode(denm).map(|_| ()))),
277    )
278}
279
280impl DENMTransmissionManagement {
281    /// Standalone transmission management with its own protocol engine (no
282    /// timer thread: DENM repetition needs the DEN service).
283    pub fn new(btp_handle: BTPRouterHandle, coder: DenmCoder, vehicle_data: VehicleData) -> Self {
284        let shared = DenShared::new(new_protocol(&vehicle_data, false, &coder));
285        Self::with_shared(btp_handle, coder, vehicle_data, shared)
286    }
287
288    /// Transmission management on a protocol engine shared with reception.
289    pub fn with_shared(
290        btp_handle: BTPRouterHandle,
291        coder: DenmCoder,
292        vehicle_data: VehicleData,
293        shared: Arc<DenShared>,
294    ) -> Self {
295        DENMTransmissionManagement {
296            btp_handle,
297            coder,
298            vehicle_data,
299            shared,
300        }
301    }
302
303    // ── Standard application requests (clause 5.3.1) ──────────────────────
304
305    /// AppDENM_trigger: returns the new actionId or a failure notification.
306    pub fn trigger(&self, request: &DenmRequest) -> DenResult {
307        let now = self.shared.now();
308        let (result, outgoing) = self.shared.protocol.lock().unwrap().trigger(request, now);
309        self.dispatch(result, outgoing)
310    }
311
312    /// AppDENM_update for an event triggered by this ITS-S.
313    pub fn update(&self, action_id: DenActionId, request: &DenmRequest) -> DenResult {
314        let now = self.shared.now();
315        let (result, outgoing) = self
316            .shared
317            .protocol
318            .lock()
319            .unwrap()
320            .update(action_id, request, now);
321        self.dispatch(result, outgoing)
322    }
323
324    /// AppDENM_termination: cancellation (own event) or negation (received event).
325    pub fn terminate(&self, action_id: DenActionId, request: &DenmRequest) -> DenResult {
326        let now = self.shared.now();
327        let (result, outgoing) = self
328            .shared
329            .protocol
330            .lock()
331            .unwrap()
332            .terminate(action_id, request, now);
333        self.dispatch(result, outgoing)
334    }
335
336    // ── Road hazard signalling requests (DENRequest) ───────────────────────
337
338    /// AppDENM_trigger repeated every `denm_interval_ms` for `time_period_ms`
339    /// (DENM repetition, clause 6.1.2.3), with transmissionInterval set so
340    /// receivers may keep it alive. Repetition needs the DEN service timer.
341    pub fn trigger_denm_sending(&self, request: DENRequest) {
342        let _ = self.trigger(&self.to_denm_request(&request, true));
343    }
344
345    /// A single new DENM, no repetition.
346    pub fn send_single_denm(&self, request: &DENRequest) {
347        let _ = self.trigger(&self.to_denm_request(request, false));
348    }
349
350    /// AppDENM_trigger request carrying the content of a road-hazard request.
351    pub fn to_denm_request(&self, request: &DENRequest, repeat: bool) -> DenmRequest {
352        let denm = build_denm(request, &self.vehicle_data, 0);
353        let mut out = DenmRequest::new(denm.denm.management.event_position.clone());
354        out.situation = denm.denm.situation;
355        out.location = denm.denm.location;
356        out.validity_duration = Some(if request.time_period_ms == 0 {
357            super::den_protocol::DEFAULT_VALIDITY_DURATION_S
358        } else {
359            request.time_period_ms.div_ceil(1000).max(1) as u32
360        });
361        out.transmission_interval = Some(request.denm_interval_ms.clamp(1, 10_000) as u16);
362        out.station_type = Some(self.vehicle_data.station_type);
363        if repeat {
364            out.repetition_interval = Some(request.denm_interval_ms);
365            out.repetition_duration = Some(request.time_period_ms);
366        }
367        out.destination_area = Some(Area {
368            latitude: denm.denm.management.event_position.latitude.0 as u32,
369            longitude: denm.denm.management.event_position.longitude.0 as u32,
370            a: request.relevance_radius_m.min(u32::from(u16::MAX)) as u16,
371            b: 0,
372            angle: 0,
373        });
374        out
375    }
376
377    // ── Transmission ───────────────────────────────────────────────────────
378
379    fn dispatch(&self, result: DenResult, outgoing: Vec<OutgoingDenm>) -> DenResult {
380        for item in &outgoing {
381            transmit(&self.btp_handle, &self.coder, item);
382        }
383        if let Err(failure) = result {
384            eprintln!("[DEN] request failed: {failure:?}");
385        }
386        self.shared.wakeup.notify_all();
387        result
388    }
389
390    /// Encode a DENM and pass it to BTP-B port 2002 over GeoBroadcast.
391    pub fn transmit(&self, outgoing: &OutgoingDenm) {
392        transmit(&self.btp_handle, &self.coder, outgoing);
393    }
394}
395
396/// Encode a DENM and pass it to BTP-B port 2002 over GeoBroadcast.
397pub fn transmit(btp_handle: &BTPRouterHandle, coder: &DenmCoder, outgoing: &OutgoingDenm) {
398    let Ok(data) = coder.encode(&outgoing.denm) else {
399        return;
400    };
401    btp_handle.send_btp_data_request(BTPDataRequest {
402        btp_type: CommonNH::BtpB,
403        source_port: 0,
404        destination_port: DENM_BTP_PORT,
405        destination_port_info: 0,
406        gn_packet_transport_type: PacketTransportType {
407            header_type: HeaderType::GeoBroadcast,
408            header_sub_type: HeaderSubType::GeoBroadcast(outgoing.area_type),
409        },
410        gn_destination_address: GNAddress {
411            m: M::GnMulticast,
412            st: ST::Unknown,
413            mid: MID::new([0xFF; 6]),
414        },
415        communication_profile: CommunicationProfile::Unspecified,
416        gn_area: outgoing.area,
417        traffic_class: outgoing.traffic_class,
418        security_profile: SecurityProfile::DecentralizedEnvironmentalNotificationMessage,
419        its_aid: DENM_ITS_AID,
420        // Sender-side SSP check (clause 6.2.2.2): sign only with an AT
421        // granting the cause code of this DENM.
422        security_permissions: super::denm_ssp::permissions_bitmap(&outgoing.denm),
423        gn_max_hop_limit: 10,
424        gn_max_packet_lifetime: None,
425        gn_repetition_interval: None,
426        gn_max_repetition_time: None,
427        destination: None,
428        length: data.len() as u16,
429        data,
430    });
431}
432
433#[cfg(test)]
434mod tests {
435    use super::super::denm_coder::AccidentSubCauseCode;
436    use super::*;
437    use crate::geonet::mib::Mib;
438    use crate::geonet::service_access_point::GeoBroadcastHST;
439    use std::time::Duration;
440
441    fn vehicle(station_id: u32) -> VehicleData {
442        VehicleData {
443            station_id,
444            station_type: 5,
445        }
446    }
447
448    /// New event (TS 103 831 clauses 6.1.1, 8.2.2): the actionID of a new DENM contains the StationID of
449    /// the originating ITS-S.
450    #[test]
451    fn build_denm_action_id_contains_station_id() {
452        let denm = build_denm(&DENRequest::default(), &vehicle(4242), 7);
453        let action_id = &denm.denm.management.action_id;
454        assert_eq!(action_id.originating_station_id.0, 4242);
455        assert_eq!(action_id.sequence_number.0, 7);
456        assert_eq!(denm.header.station_id.0, 4242);
457    }
458
459    /// New event (TS 103 831 clauses 6.1.1, 8.2.2): cause and sub-cause are those provided by the
460    /// application.
461    #[test]
462    fn build_denm_carries_application_cause_code() {
463        let request = DENRequest {
464            cause_code: CauseCodeChoice::accident2(AccidentSubCauseCode(3)),
465            ..DENRequest::default()
466        };
467        let denm = build_denm(&request, &vehicle(1), 0);
468        let situation = denm.denm.situation.expect("situation container");
469        assert_eq!(situation.event_type.cc_and_scc, request.cause_code);
470    }
471
472    /// New event (TS 103 831 clauses 6.1.1, 8.2.2): referenceTime of a new DENM is the current time.
473    #[test]
474    fn build_denm_reference_time_is_now() {
475        let before = timestamp_its_now().0;
476        let denm = build_denm(&DENRequest::default(), &vehicle(1), 0);
477        let after = timestamp_its_now().0;
478        let reference = denm.denm.management.reference_time.0;
479        assert!(reference >= before && reference <= after);
480    }
481
482    /// DENM encapsulation (TS 103 831 clause 5.4.2.2): a DENM is sent as BTP-B to port 2002 in a
483    /// GeoNetworking GBC (circle) packet.
484    #[test]
485    fn send_single_denm_uses_btp_b_port_2002_over_gbc() {
486        let (btp_handle, gn_rx) = crate::btp::router::Router::spawn(Mib::new());
487        let dtm = DENMTransmissionManagement::new(btp_handle, DenmCoder::new(), vehicle(1));
488        dtm.send_single_denm(&DENRequest::default());
489
490        let gn_req = gn_rx
491            .recv_timeout(Duration::from_secs(1))
492            .expect("DENM did not reach GeoNetworking");
493        assert_eq!(gn_req.upper_protocol_entity, CommonNH::BtpB);
494        assert_eq!(
495            gn_req.packet_transport_type.header_type,
496            HeaderType::GeoBroadcast
497        );
498        assert_eq!(
499            gn_req.packet_transport_type.header_sub_type,
500            HeaderSubType::GeoBroadcast(GeoBroadcastHST::GeoBroadcastCircle)
501        );
502        // BTP-B header: destination port 2002 (0x07D2).
503        assert_eq!(&gn_req.data[0..2], &[0x07, 0xD2]);
504        assert_eq!(gn_req.its_aid, 37);
505    }
506}