Skip to main content

rustflexstack/facilities/decentralized_environmental_notification_service/
mod.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! Decentralized Environmental Notification (DEN) Service.
5//!
6//! Implements ETSI TS 103 831 V2.3.1 (2025-11) "Decentralized Environmental
7//! Notification Service; Release 2" (latest version), the successor of ETSI
8//! EN 302 637-3 V1.3.1 (2019-04). DENMs use DENM-PDU-Descriptions v2.3
9//! (Annex A) over the Common Data Dictionary v4.3 (ETSI TS 102 894-2).
10//!
11//! # Architecture
12//! ```text
13//! Application ──DenmRequest / DENRequest──► DENMTransmissionManagement ──► BTP (port 2002)
14//!                                                │  (originating ITS-S, clause 8.2)
15//!                                    DenProtocol (message tables, timers)
16//!                                                │  (receiving ITS-S 8.4, KAF 8.3)
17//! Application ◄──Denm / ReceivedDenm── DENMReceptionManagement ◄── BTP
18//!                       timer thread ── tick() ──► repetitions, KAF forwards
19//! ```
20//!
21//! # Quick start
22//! ```no_run
23//! use rustflexstack::btp::router::Router as BTPRouter;
24//! use rustflexstack::geonet::mib::Mib;
25//! use rustflexstack::facilities::decentralized_environmental_notification_service::{
26//!     DecentralizedEnvironmentalNotificationService, VehicleData, DENRequest,
27//! };
28//! use rustflexstack::facilities::decentralized_environmental_notification_service::denm_coder::CauseCodeChoice;
29//!
30//! let mib = Mib::new();
31//! let (btp_handle, _) = BTPRouter::spawn(mib);
32//!
33//! let (den_svc, denm_rx) = DecentralizedEnvironmentalNotificationService::new(
34//!     btp_handle,
35//!     VehicleData::default(),
36//! );
37//!
38//! // Trigger a road-hazard DENM (accident, sub-cause 0).
39//! den_svc.trigger_denm(DENRequest::default());
40//!
41//! while let Ok(denm) = denm_rx.recv() {
42//!     println!("DENM from station {}", denm.header.station_id.0);
43//! }
44//! ```
45
46#[cfg(test)]
47pub(crate) mod conformance;
48pub mod den_protocol;
49pub mod denm_bindings;
50pub mod denm_coder;
51pub mod denm_reception;
52pub mod denm_ssp;
53pub mod denm_transmission;
54
55pub use den_protocol::{
56    DenActionId, DenFailure, DenProtocol, DenResult, DenmRequest, DenmState, OutgoingDenm,
57};
58pub use denm_coder::{Denm, DenmCoder};
59pub use denm_reception::{DENMReceptionManagement, ReceivedDenm};
60pub use denm_transmission::{
61    DENMTransmissionManagement, DENRequest, DenClock, DenShared, VehicleData,
62};
63
64use crate::btp::router::BTPRouterHandle;
65use std::sync::atomic::{AtomicBool, Ordering};
66use std::sync::mpsc::{self, Receiver, Sender};
67use std::sync::Arc;
68use std::thread::{self, JoinHandle};
69use std::time::Duration;
70
71const MAX_IDLE_WAIT: Duration = Duration::from_secs(1);
72
73/// Options of the DEN service.
74#[derive(Default)]
75pub struct DenConfig {
76    /// Activate Keep-Alive Forwarding of received DENMs (clause 6.1.4.2). KAF
77    /// only forwards while [`DecentralizedEnvironmentalNotificationService::set_ego_position`]
78    /// has placed the station inside the DENM destination area.
79    pub kaf_enabled: bool,
80    /// Also deliver accepted DENMs with their state (active / cancelled / negated).
81    pub events: Option<Sender<ReceivedDenm>>,
82    /// Be notified when a received event expires (T_R_Validity).
83    pub expiry: Option<Sender<DenActionId>>,
84    /// Do not start the timer thread (tests drive [`DecentralizedEnvironmentalNotificationService::process_timers`]).
85    pub no_scheduler: bool,
86    /// Time source of the service (TimestampIts, ms); the system time when `None`.
87    pub clock: Option<DenClock>,
88}
89
90/// Top-level Decentralized Environmental Notification Service.
91///
92/// Mirrors `DecentralizedEnvironmentalNotificationService` in
93/// `flexstack/facilities/decentralized_environmental_notification_service/den_service.py`.
94pub struct DecentralizedEnvironmentalNotificationService {
95    tx_management: DENMTransmissionManagement,
96    shared: Arc<DenShared>,
97    btp_handle: BTPRouterHandle,
98    coder: DenmCoder,
99    expiry: Option<Sender<DenActionId>>,
100    running: Arc<AtomicBool>,
101    scheduler: Option<JoinHandle<()>>,
102}
103
104impl DecentralizedEnvironmentalNotificationService {
105    /// Create a DEN service. Returns `(service, denm_receiver)`; accepted
106    /// incoming DENMs are delivered on `denm_receiver`. Reception and the
107    /// timer thread start immediately.
108    pub fn new(btp_handle: BTPRouterHandle, vehicle_data: VehicleData) -> (Self, Receiver<Denm>) {
109        Self::with_config(btp_handle, vehicle_data, DenConfig::default())
110    }
111
112    /// Create a DEN service with options (KAF, events with state, expiry).
113    pub fn with_config(
114        btp_handle: BTPRouterHandle,
115        vehicle_data: VehicleData,
116        config: DenConfig,
117    ) -> (Self, Receiver<Denm>) {
118        let coder = DenmCoder::new();
119        let shared = DenShared::with_clock(
120            denm_transmission::new_protocol(&vehicle_data, config.kaf_enabled, &coder),
121            config.clock,
122        );
123        let (denm_tx, denm_rx) = mpsc::channel::<Denm>();
124        DENMReceptionManagement::spawn_with(
125            btp_handle.clone(),
126            coder.clone(),
127            shared.clone(),
128            Some(denm_tx),
129            config.events,
130        );
131        let tx_management = DENMTransmissionManagement::with_shared(
132            btp_handle.clone(),
133            coder.clone(),
134            vehicle_data,
135            shared.clone(),
136        );
137        let mut svc = DecentralizedEnvironmentalNotificationService {
138            tx_management,
139            shared,
140            btp_handle,
141            coder,
142            expiry: config.expiry,
143            running: Arc::new(AtomicBool::new(false)),
144            scheduler: None,
145        };
146        if !config.no_scheduler {
147            svc.start();
148        }
149        (svc, denm_rx)
150    }
151
152    // ── Application interface ──────────────────────────────────────────────
153
154    /// AppDENM_trigger.
155    pub fn trigger(&self, request: &DenmRequest) -> DenResult {
156        self.tx_management.trigger(request)
157    }
158
159    /// AppDENM_update.
160    pub fn update(&self, action_id: DenActionId, request: &DenmRequest) -> DenResult {
161        self.tx_management.update(action_id, request)
162    }
163
164    /// AppDENM_termination.
165    pub fn terminate(&self, action_id: DenActionId, request: &DenmRequest) -> DenResult {
166        self.tx_management.terminate(action_id, request)
167    }
168
169    /// Road-hazard DENM repeated every `denm_interval_ms` for `time_period_ms`.
170    pub fn trigger_denm(&self, request: DENRequest) {
171        self.tx_management.trigger_denm_sending(request);
172    }
173
174    /// Send a single road-hazard DENM (no repetition).
175    pub fn send_single_denm(&self, request: &DENRequest) {
176        self.tx_management.send_single_denm(request);
177    }
178
179    /// Pseudonym change: re-label all stored own DENMs (clause 6.1.1.2).
180    pub fn update_station_id(&self, station_id: u32) {
181        self.shared
182            .protocol
183            .lock()
184            .unwrap()
185            .update_station_id(station_id);
186    }
187
188    /// Own position in 1/10 micro-degree, used by Keep-Alive Forwarding.
189    pub fn set_ego_position(&self, latitude: i32, longitude: i32) {
190        self.shared
191            .protocol
192            .lock()
193            .unwrap()
194            .set_ego_position(latitude, longitude);
195    }
196
197    /// Shared protocol engine (message tables), e.g. for inspection.
198    pub fn shared(&self) -> &Arc<DenShared> {
199        &self.shared
200    }
201
202    // ── Timers ─────────────────────────────────────────────────────────────
203
204    /// Fire the expired protocol timers at `now` (TimestampIts ms; current
205    /// time when `None`) and transmit the resulting DENMs.
206    pub fn process_timers(&self, now: Option<u64>) {
207        process_timers(
208            &self.shared,
209            &self.btp_handle,
210            &self.coder,
211            self.expiry.as_ref(),
212            now,
213        );
214    }
215
216    /// Start the timer thread (idempotent).
217    pub fn start(&mut self) {
218        if self.running.swap(true, Ordering::SeqCst) {
219            return;
220        }
221        let (shared, running) = (self.shared.clone(), self.running.clone());
222        let (btp, coder, expiry) = (
223            self.btp_handle.clone(),
224            self.coder.clone(),
225            self.expiry.clone(),
226        );
227        self.scheduler = Some(thread::spawn(move || loop {
228            {
229                let guard = shared.protocol.lock().unwrap();
230                if !running.load(Ordering::SeqCst) {
231                    return;
232                }
233                let now = shared.now();
234                match guard.next_deadline() {
235                    Some(deadline) if deadline <= now => {}
236                    deadline => {
237                        let wait = deadline
238                            .map(|d| Duration::from_millis(d - now).min(MAX_IDLE_WAIT))
239                            .unwrap_or(MAX_IDLE_WAIT);
240                        let _ = shared.wakeup.wait_timeout(guard, wait).unwrap();
241                        continue;
242                    }
243                }
244            }
245            process_timers(&shared, &btp, &coder, expiry.as_ref(), None);
246        }));
247    }
248
249    /// Stop the timer thread.
250    pub fn stop(&mut self) {
251        self.running.store(false, Ordering::SeqCst);
252        self.shared.wakeup.notify_all();
253        if let Some(handle) = self.scheduler.take() {
254            let _ = handle.join();
255        }
256    }
257}
258
259impl Drop for DecentralizedEnvironmentalNotificationService {
260    fn drop(&mut self) {
261        self.stop();
262    }
263}
264
265fn process_timers(
266    shared: &DenShared,
267    btp_handle: &BTPRouterHandle,
268    coder: &DenmCoder,
269    expiry: Option<&Sender<DenActionId>>,
270    now: Option<u64>,
271) {
272    let now = now.unwrap_or_else(|| shared.now());
273    let (outgoing, expired) = shared.protocol.lock().unwrap().tick(now);
274    for item in &outgoing {
275        denm_transmission::transmit(btp_handle, coder, item);
276    }
277    if let Some(tx) = expiry {
278        for action_id in expired {
279            let _ = tx.send(action_id);
280        }
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    //! Mirrors test_den_service.py and test_denm_reception_management.py.
287    use super::den_protocol::{DenmRequest, DenmState};
288    use super::denm_coder::Termination;
289    use super::denm_reception::process_indication;
290    use super::denm_transmission::{build_denm, new_protocol};
291    use super::*;
292    use crate::btp::service_access_point::BTPDataIndication;
293    use crate::geonet::mib::Mib;
294    use crate::geonet::service_access_point::{
295        Area, GNDataRequest, GeoBroadcastHST, HeaderSubType, HeaderType,
296    };
297    use std::sync::mpsc::Receiver;
298
299    fn request() -> DenmRequest {
300        let t = build_denm(&DENRequest::default(), &VehicleData::default(), 0);
301        let mut r = DenmRequest::new(t.denm.management.event_position.clone());
302        r.situation = t.denm.situation;
303        r.location = t.denm.location;
304        r
305    }
306
307    fn service(
308        config: DenConfig,
309    ) -> (
310        DecentralizedEnvironmentalNotificationService,
311        Receiver<GNDataRequest>,
312    ) {
313        let (btp, gn_rx) = crate::btp::router::Router::spawn(Mib::new());
314        let vd = VehicleData {
315            station_id: 7,
316            station_type: 5,
317        };
318        let (svc, _rx) =
319            DecentralizedEnvironmentalNotificationService::with_config(btp, vd, config);
320        (svc, gn_rx)
321    }
322
323    fn received(gn_rx: &Receiver<GNDataRequest>) -> Vec<Denm> {
324        let coder = DenmCoder::new();
325        let mut out = vec![];
326        while let Ok(r) = gn_rx.recv_timeout(Duration::from_millis(200)) {
327            out.push(coder.decode(&r.data[4..]).unwrap());
328        }
329        out
330    }
331
332    #[test]
333    fn process_timers_sends_repetitions_with_same_reference_time() {
334        let (svc, gn_rx) = service(DenConfig {
335            no_scheduler: true,
336            ..Default::default()
337        });
338        let mut r = request();
339        r.repetition_interval = Some(100);
340        r.repetition_duration = Some(1000);
341        let id = svc.trigger(&r).unwrap();
342        let reference = svc.shared().protocol.lock().unwrap().originating[&id]
343            .denm
344            .denm
345            .management
346            .reference_time
347            .0;
348        svc.process_timers(Some(reference + 100));
349        svc.process_timers(Some(reference + 200));
350        let sent = received(&gn_rx);
351        assert_eq!(sent.len(), 3);
352        assert!(sent
353            .iter()
354            .all(|d| d.denm.management.reference_time.0 == reference));
355    }
356
357    #[test]
358    fn scheduler_thread_sends_repetitions() {
359        let (mut svc, gn_rx) = service(DenConfig::default());
360        let mut r = request();
361        r.repetition_interval = Some(50);
362        r.repetition_duration = Some(1000);
363        svc.trigger(&r).unwrap();
364        let mut n = 0;
365        while gn_rx.recv_timeout(Duration::from_secs(2)).is_ok() {
366            n += 1;
367            if n == 3 {
368                break;
369            }
370        }
371        assert_eq!(n, 3);
372        svc.stop();
373    }
374
375    #[test]
376    fn trigger_update_terminate_on_the_wire() {
377        let (svc, gn_rx) = service(DenConfig {
378            no_scheduler: true,
379            ..Default::default()
380        });
381        let id = svc.trigger(&request()).unwrap();
382        assert!(svc.update(id, &request()).is_ok());
383        assert!(svc.terminate(id, &request()).is_ok());
384        let terminations: Vec<_> = received(&gn_rx)
385            .iter()
386            .map(|d| d.denm.management.termination)
387            .collect();
388        assert_eq!(
389            terminations,
390            vec![None, None, Some(Termination::isCancellation)]
391        );
392    }
393
394    #[test]
395    fn legacy_trigger_denm_schedules_repetition() {
396        let (svc, gn_rx) = service(DenConfig {
397            no_scheduler: true,
398            ..Default::default()
399        });
400        svc.trigger_denm(DENRequest::default());
401        let p = svc.shared().protocol.lock().unwrap();
402        let entry = p.originating.values().next().unwrap();
403        assert_eq!(entry.repetition_interval, Some(1000));
404        assert!(entry.next_repetition.is_some());
405        assert_eq!(
406            entry
407                .denm
408                .denm
409                .management
410                .transmission_interval
411                .as_ref()
412                .map(|t| t.0),
413            Some(1000)
414        );
415        assert_eq!(entry.denm.denm.management.validity_duration.0, 5);
416        drop(p);
417        assert_eq!(received(&gn_rx).len(), 1);
418    }
419
420    fn indication(denm: &Denm, permissions: Option<Vec<u8>>) -> BTPDataIndication {
421        let mut ind = BTPDataIndication::new();
422        ind.destination_port = 2002;
423        ind.gn_packet_transport_type.header_type = HeaderType::GeoBroadcast;
424        ind.gn_packet_transport_type.header_sub_type =
425            HeaderSubType::GeoBroadcast(GeoBroadcastHST::GeoBroadcastCircle);
426        ind.gn_destination_area = Some(Area {
427            latitude: 1,
428            longitude: 2,
429            a: 1000,
430            b: 0,
431            angle: 0,
432        });
433        ind.gn_permissions = permissions;
434        ind.data = DenmCoder::new().encode(denm).unwrap();
435        ind
436    }
437
438    fn originated() -> Denm {
439        let coder = DenmCoder::new();
440        let mut p = new_protocol(
441            &VehicleData {
442                station_id: 3,
443                station_type: 5,
444            },
445            false,
446            &coder,
447        );
448        let mut r = request();
449        r.transmission_interval = Some(100);
450        p.trigger(&r, denm_coder::timestamp_its_now().0)
451            .1
452            .remove(0)
453            .denm
454    }
455
456    #[test]
457    fn reception_accepts_new_event_once() {
458        let coder = DenmCoder::new();
459        let shared = DenShared::new(new_protocol(&VehicleData::default(), true, &coder));
460        let denm = originated();
461        let rx = process_indication(&coder, &shared, &indication(&denm, None)).unwrap();
462        assert_eq!(rx.state, DenmState::Active);
463        assert!(process_indication(&coder, &shared, &indication(&denm, None)).is_none());
464        let p = shared.protocol.lock().unwrap();
465        assert_eq!(p.forwarding.values().next().unwrap().area.a, 1000);
466    }
467
468    /// ETSI TS 103 097 clause 7.1.2: a secured DENM shall carry the DENM ITS-AID.
469    #[test]
470    fn reception_discards_secured_denm_with_another_its_aid() {
471        let coder = DenmCoder::new();
472        let shared = DenShared::new(new_protocol(&VehicleData::default(), false, &coder));
473        let denm = originated();
474        let mut ind = indication(&denm, None);
475        ind.gn_its_aid = Some(36);
476        assert!(process_indication(&coder, &shared, &ind).is_none());
477        ind.gn_its_aid = Some(37);
478        assert!(process_indication(&coder, &shared, &ind).is_some());
479    }
480
481    /// Sender-side SSP: accident(2) needs octet 1 bit 0x40 (Table 10).
482    #[test]
483    fn permissions_bitmap_requests_the_cause_code_bit() {
484        let mut denm = originated();
485        assert_eq!(denm_ssp::permissions_bitmap(&denm), vec![0, 0x40]);
486        denm.denm.situation = None;
487        assert_eq!(denm_ssp::permissions_bitmap(&denm), vec![0]);
488    }
489
490    #[test]
491    fn reception_checks_ssp_and_discards_undecodable() {
492        let coder = DenmCoder::new();
493        let shared = DenShared::new(new_protocol(&VehicleData::default(), false, &coder));
494        let denm = originated(); // accident(2)
495        assert!(process_indication(
496            &coder,
497            &shared,
498            &indication(&denm, Some(vec![2, 0x80, 0, 0, 0]))
499        )
500        .is_none());
501        assert!(process_indication(
502            &coder,
503            &shared,
504            &indication(&denm, Some(vec![2, 0x40, 0, 0, 0]))
505        )
506        .is_some());
507        let mut bad = BTPDataIndication::new();
508        bad.data = vec![0xFF, 0x00];
509        assert!(process_indication(&coder, &shared, &bad).is_none());
510    }
511
512    #[test]
513    fn expiry_is_notified() {
514        let (exp_tx, exp_rx) = mpsc::channel();
515        let (svc, _) = service(DenConfig {
516            no_scheduler: true,
517            expiry: Some(exp_tx),
518            ..Default::default()
519        });
520        let coder = DenmCoder::new();
521        let denm = originated();
522        process_indication(&coder, svc.shared(), &indication(&denm, None)).unwrap();
523        let detection = denm.denm.management.detection_time.0;
524        svc.process_timers(Some(detection + 600_000));
525        assert_eq!(
526            exp_rx.try_recv().unwrap(),
527            DenActionId::from_asn(&denm.denm.management.action_id)
528        );
529    }
530
531    #[test]
532    fn station_id_and_ego_position() {
533        let (svc, _) = service(DenConfig {
534            no_scheduler: true,
535            kaf_enabled: true,
536            ..Default::default()
537        });
538        let mut r = request();
539        r.repetition_interval = Some(100);
540        r.repetition_duration = Some(1000);
541        let id = svc.trigger(&r).unwrap();
542        svc.update_station_id(8);
543        svc.set_ego_position(1, 2);
544        let p = svc.shared().protocol.lock().unwrap();
545        assert!(p.originating.contains_key(&DenActionId {
546            station_id: 8,
547            sequence_number: id.sequence_number
548        }));
549        assert_eq!(p.ego_position, Some((1, 2)));
550        assert!(p.kaf_enabled);
551    }
552}