rustflexstack/facilities/vru_awareness_service/vam_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//! VAM Reception Management — ETSI TS 103 300-3 V2.3.1 (2025-12).
5//!
6//! Mirrors `VAMReceptionManagement` in
7//! `flexstack/facilities/vru_awareness_service/vam_reception_management.py`.
8//!
9//! [`VAMReceptionManagement::spawn`] starts a background thread that:
10//! 1. Registers BTP port 2018 with the BTP router.
11//! 2. Waits for [`BTPDataIndication`] messages from the router.
12//! 3. Decodes the UPER payload via [`VamCoder`].
13//! 4. Forwards the decoded [`Vam`] to the caller via an MPSC channel.
14
15use super::vam_coder::{Vam, VamCoder};
16use crate::btp::router::BTPRouterHandle;
17use crate::btp::service_access_point::BTPDataIndication;
18use std::sync::mpsc::{self, Sender};
19use std::thread;
20
21/// ITS-AID of the service (ETSI TS 102 965).
22pub const VAM_ITS_AID: u64 = 638;
23
24/// VAM Reception Management.
25///
26/// Spawned as a background thread via [`VAMReceptionManagement::spawn`].
27pub struct VAMReceptionManagement;
28
29impl VAMReceptionManagement {
30 /// Spawn the reception management thread.
31 ///
32 /// # Arguments
33 /// * `btp_handle` — handle to the BTP router; used to register port 2018.
34 /// * `coder` — shared [`VamCoder`] instance for UPER decoding.
35 /// * `vam_tx` — sender into which decoded [`Vam`] PDUs are pushed.
36 ///
37 /// The caller should hold the corresponding `Receiver<Vam>` — typically
38 /// returned from [`VruAwarenessService::new`].
39 pub fn spawn(btp_handle: BTPRouterHandle, coder: VamCoder, vam_tx: Sender<Vam>) {
40 // Create an internal BTPDataIndication channel and register it
41 // on BTP port 2018 (VAM destination port per ETSI TS 103 300-3).
42 let (ind_tx, ind_rx) = mpsc::channel::<BTPDataIndication>();
43 btp_handle.register_port(2018, ind_tx);
44
45 thread::spawn(move || {
46 while let Ok(indication) = ind_rx.recv() {
47 // A secured VAM shall carry the VAM ITS-AID (ETSI TS 103 097
48 // V2.2.1 clause 7.1.3).
49 if indication.gn_its_aid.is_some_and(|aid| aid != VAM_ITS_AID) {
50 continue;
51 }
52 if let Ok(vam) = coder.decode(&indication.data) {
53 // Forward to caller; if they dropped the receiver, stop quietly.
54 if vam_tx.send(vam).is_err() {
55 break;
56 }
57 }
58 }
59 });
60 }
61}