Skip to main content

rustflexstack/facilities/decentralized_environmental_notification_service/
denm_reception.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 reception: receiving ITS-S operation of the DEN service
5//! (ETSI TS 103 831 V2.3.1 (2025-11), clause 8.4) and the reception side of
6//! the optional Keep-Alive Forwarding (clause 8.3).
7//!
8//! A background thread registered on BTP port 2002 decodes each DENM and
9//! processes it against the receiving ITS-S message table of the shared
10//! [`DenProtocol`](super::den_protocol::DenProtocol). Accepted DENMs (new
11//! event, update, termination of a known event) are passed on; outdated,
12//! repeated, expired and unknown-termination DENMs are discarded.
13//!
14//! Mirrors `flexstack/facilities/decentralized_environmental_notification_service/denm_reception_management.py`.
15
16use super::den_protocol::{DenmState, ReceptionOutcome};
17use super::denm_coder::{Denm, DenmCoder};
18use super::denm_ssp::ssp_consistent;
19use super::denm_transmission::{new_protocol, DenShared, VehicleData, DENM_BTP_PORT};
20use crate::btp::router::BTPRouterHandle;
21use crate::btp::service_access_point::BTPDataIndication;
22use crate::geonet::service_access_point::{HeaderSubType, HeaderType};
23use std::sync::mpsc::{self, Sender};
24use std::sync::Arc;
25use std::thread;
26
27/// DENM passed to ITS-S applications (IF.DataCollect, clause 5.3.1.5).
28#[derive(Debug, Clone)]
29pub struct ReceivedDenm {
30    pub denm: Denm,
31    /// State of the event after this DENM: active, cancelled or negated.
32    pub state: DenmState,
33}
34
35/// DENM Reception Management.
36pub struct DENMReceptionManagement;
37
38impl DENMReceptionManagement {
39    /// Spawn a standalone reception thread with its own protocol engine.
40    /// Accepted DENMs are pushed into `denm_tx`.
41    pub fn spawn(btp_handle: BTPRouterHandle, coder: DenmCoder, denm_tx: Sender<Denm>) {
42        let shared = DenShared::new(new_protocol(&VehicleData::default(), false, &coder));
43        Self::spawn_with(btp_handle, coder, shared, Some(denm_tx), None);
44    }
45
46    /// Spawn the reception thread on a protocol engine shared with
47    /// transmission and the timer thread. Accepted DENMs go to `denm_tx`
48    /// (DENM only) and `events_tx` (DENM and state).
49    pub fn spawn_with(
50        btp_handle: BTPRouterHandle,
51        coder: DenmCoder,
52        shared: Arc<DenShared>,
53        denm_tx: Option<Sender<Denm>>,
54        events_tx: Option<Sender<ReceivedDenm>>,
55    ) {
56        let (ind_tx, ind_rx) = mpsc::channel::<BTPDataIndication>();
57        btp_handle.register_port(DENM_BTP_PORT, ind_tx);
58        thread::spawn(move || {
59            while let Ok(indication) = ind_rx.recv() {
60                let Some(received) = process_indication(&coder, &shared, &indication) else {
61                    continue;
62                };
63                let mut delivered = false;
64                if let Some(tx) = &denm_tx {
65                    delivered |= tx.send(received.denm.clone()).is_ok();
66                }
67                if let Some(tx) = &events_tx {
68                    delivered |= tx.send(received).is_ok();
69                }
70                if !delivered && (denm_tx.is_some() || events_tx.is_some()) {
71                    break; // every consumer is gone
72                }
73            }
74        });
75    }
76}
77
78/// Decode and process one BTP indication (clause 8.4.2). Returns the DENM and
79/// its state when the receiving ITS-S accepts it.
80pub fn process_indication(
81    coder: &DenmCoder,
82    shared: &DenShared,
83    indication: &BTPDataIndication,
84) -> Option<ReceivedDenm> {
85    // ETSI TS 103 097 V2.2.1 clause 7.1.2: a
86    // secured DENM shall carry the DENM ITS-AID.
87    if indication
88        .gn_its_aid
89        .is_some_and(|aid| aid != super::denm_transmission::DENM_ITS_AID)
90    {
91        return None;
92    }
93    // DENM decoding exception (clause 8.4.3.2): discard.
94    let denm = coder.decode(&indication.data).ok()?;
95    let area = match (
96        indication.gn_destination_area,
97        &indication.gn_packet_transport_type.header_type,
98        &indication.gn_packet_transport_type.header_sub_type,
99    ) {
100        (Some(area), HeaderType::GeoBroadcast, HeaderSubType::GeoBroadcast(kind)) => {
101            Some((area, *kind))
102        }
103        _ => None,
104    };
105    let now = shared.now();
106    let ssp_ok = ssp_consistent(indication.gn_permissions.as_deref(), &denm);
107    let outcome: ReceptionOutcome = shared
108        .protocol
109        .lock()
110        .unwrap()
111        .receive(&denm, now, area, ssp_ok);
112    shared.wakeup.notify_all();
113    if !outcome.accepted {
114        return None;
115    }
116    Some(ReceivedDenm {
117        denm,
118        state: outcome.state.unwrap_or(DenmState::Active),
119    })
120}