Skip to main content

rustflexstack/facilities/vru_awareness_service/
vam_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//! VAM Transmission Management — ETSI TS 103 300-3 V2.3.1 (2025-12).
5//!
6//! Mirrors `VAMTransmissionManagement` in
7//! `flexstack/facilities/vru_awareness_service/vam_transmission_management.py`.
8//!
9//! Key behavioural properties:
10//!   - Timer-based (T_CheckVamGen) architecture with condition evaluation (clause 6.4.1).
11//!   - Triggering conditions: elapsed time (T_GenVamMax), position (4 m), speed (0.5 m/s),
12//!     heading (4°).
13//!   - VRU Low-Frequency Container included on first VAM, then every ≥ 2 000 ms (clause 6.2).
14//!   - Security profile: VRU_AWARENESS_MESSAGE, ITS-AID: 638.
15
16use super::vam_bindings::etsi_its_cdd::{VruProfileAndSubprofile, VruSubProfilePedestrian};
17use super::vam_bindings::vam_pdu_descriptions::VruLowFrequencyContainer;
18use super::vam_coder::{
19    generation_delta_time_now, vam_header, AccelerationConfidence, Altitude, AltitudeConfidence,
20    AltitudeValue, BasicContainer, Latitude, Longitude, LongitudinalAcceleration,
21    LongitudinalAccelerationValue, PositionConfidenceEllipse, ReferencePositionWithConfidence,
22    SemiAxisLength, Speed, SpeedConfidence, SpeedValue, TrafficParticipantType, Vam, VamCoder,
23    VamParameters, VruAwareness, VruHighFrequencyContainer, Wgs84Angle, Wgs84AngleConfidence,
24    Wgs84AngleValue,
25};
26use crate::btp::router::BTPRouterHandle;
27use crate::btp::service_access_point::BTPDataRequest;
28use crate::facilities::location_service::GpsFix;
29use crate::geonet::gn_address::{GNAddress, M, MID, ST};
30use crate::geonet::service_access_point::{
31    Area, CommonNH, CommunicationProfile, HeaderSubType, HeaderType, PacketTransportType,
32    TopoBroadcastHST, TrafficClass,
33};
34use crate::security::sn_sap::SecurityProfile;
35use std::sync::mpsc::{Receiver, RecvTimeoutError};
36use std::thread;
37use std::time::{Duration, Instant};
38
39// ─── Timing constants (ETSI TS 103 300-3 V2.3.1 Table 16, clause 6.2) ───────
40
41/// T_GenVamMin [ms]: minimum time between consecutive VAM generation events.
42pub const T_GEN_VAM_MIN_MS: u64 = 100;
43/// T_GenVamMax [ms]: maximum time between consecutive VAM generation events.
44pub const T_GEN_VAM_MAX_MS: u64 = 5_000;
45/// T_CheckVamGen [ms]: timer period for condition evaluation (≤ T_GenVamMin).
46pub const T_CHECK_VAM_GEN_MS: u64 = T_GEN_VAM_MIN_MS;
47/// T_GenVam_DCC [ms]: DCC-imposed minimum interval.
48pub const T_GEN_VAM_DCC_MS: u64 = T_GEN_VAM_MIN_MS;
49/// T_GenVam_LFMin [ms]: minimum interval between LF container inclusions.
50pub const T_GEN_VAM_LF_MIN_MS: u64 = 2_000;
51
52// ─── Triggering thresholds (Table 17, clause 6.4) ────────────────────────────
53
54/// Minimum Euclidean position change to trigger a new VAM [m].
55const MIN_POSITION_CHANGE_M: f64 = 4.0;
56/// Minimum ground-speed change to trigger a new VAM [m/s].
57const MIN_SPEED_CHANGE_MPS: f64 = 0.5;
58/// Minimum heading-vector orientation change to trigger a new VAM [degrees].
59const MIN_HEADING_CHANGE_DEG: f64 = 4.0;
60
61// ─── Haversine ────────────────────────────────────────────────────────────────
62
63fn haversine_m(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
64    const R: f64 = 6_371_000.0;
65    let dlat = (lat2 - lat1).to_radians();
66    let dlon = (lon2 - lon1).to_radians();
67    let a = (dlat / 2.0).sin().powi(2)
68        + lat1.to_radians().cos() * lat2.to_radians().cos() * (dlon / 2.0).sin().powi(2);
69    R * 2.0 * a.sqrt().atan2((1.0 - a).max(0.0).sqrt())
70}
71
72// ─── DeviceData ───────────────────────────────────────────────────────────────
73
74/// Static device data used to populate every VAM.
75///
76/// Mirrors the `DeviceDataProvider` frozen dataclass in the Python
77/// implementation (`vam_transmission_management.py`).
78#[derive(Debug, Clone)]
79pub struct DeviceData {
80    /// ITS station ID (0–4 294 967 295).
81    pub station_id: u32,
82    /// ITS station type / traffic participant type (0–255).
83    ///
84    /// VRU-relevant values per ETSI TS 102 894-2:
85    /// - 0 = unknown
86    /// - 1 = pedestrian
87    /// - 2 = cyclist
88    /// - 3 = moped
89    /// - 4 = motorcycle
90    pub station_type: u8,
91}
92
93impl Default for DeviceData {
94    /// Sensible defaults — cyclist, station_id 0.
95    fn default() -> Self {
96        DeviceData {
97            station_id: 0,
98            station_type: 2, // cyclist
99        }
100    }
101}
102
103// ─── VAM builder ──────────────────────────────────────────────────────────────
104
105/// Build a complete [`Vam`] from a GPS fix and static device data.
106fn build_vam(fix: &GpsFix, dd: &DeviceData, lf: Option<VruLowFrequencyContainer>) -> Vam {
107    let gen_dt = generation_delta_time_now();
108
109    // ── BasicContainer ────────────────────────────────────────────────────────
110    let ref_pos = ReferencePositionWithConfidence::new(
111        Latitude(((fix.latitude * 1e7).round() as i32).clamp(-900_000_000, 900_000_000)),
112        Longitude(((fix.longitude * 1e7).round() as i32).clamp(-1_800_000_000, 1_800_000_000)),
113        PositionConfidenceEllipse::new(
114            SemiAxisLength(4095),
115            SemiAxisLength(4095),
116            Wgs84AngleValue(3601),
117        ),
118        Altitude::new(
119            AltitudeValue(((fix.altitude_m * 100.0).round() as i32).clamp(-100_000, 800_000)),
120            AltitudeConfidence::unavailable,
121        ),
122    );
123
124    let basic_container = BasicContainer::new(TrafficParticipantType(dd.station_type), ref_pos);
125
126    // ── VruHighFrequencyContainer ─────────────────────────────────────────────
127    let heading_raw = ((fix.heading_deg * 10.0).round() as u16).clamp(0, 3600);
128    let heading = Wgs84Angle::new(Wgs84AngleValue(heading_raw), Wgs84AngleConfidence(127));
129
130    let speed = Speed::new(
131        SpeedValue(((fix.speed_mps * 100.0).round() as u16).min(16_382)),
132        SpeedConfidence(127),
133    );
134
135    let longitudinal_acceleration = LongitudinalAcceleration::new(
136        LongitudinalAccelerationValue(161),
137        AccelerationConfidence(102),
138    );
139
140    let hf = VruHighFrequencyContainer::new(
141        heading,
142        speed,
143        longitudinal_acceleration,
144        None,
145        None,
146        None,
147        None,
148        None,
149        None,
150        None,
151        None,
152        None,
153        None,
154        None,
155    );
156
157    // ── Assemble VAM ──────────────────────────────────────────────────────────
158    let vam_params = VamParameters::new(
159        basic_container,
160        hf,
161        lf,
162        None, // vruClusterInformationContainer
163        None, // vruClusterOperationContainer
164        None, // vruMotionPredictionContainer
165    );
166
167    Vam::new(
168        vam_header(dd.station_id),
169        VruAwareness::new(gen_dt, vam_params),
170    )
171}
172
173// ─── Dynamics check — clause 6.4.1 ──────────────────────────────────────────
174
175/// Return `true` if at least one triggering threshold is exceeded.
176fn check_triggers(
177    fix: &GpsFix,
178    last_lat: Option<f64>,
179    last_lon: Option<f64>,
180    last_speed: Option<f64>,
181    last_heading: Option<f64>,
182) -> bool {
183    // No reference — treat as changed
184    if last_lat.is_none() {
185        return true;
186    }
187
188    // Position (Euclidean / haversine)
189    if let (Some(prev_lat), Some(prev_lon)) = (last_lat, last_lon) {
190        if haversine_m(prev_lat, prev_lon, fix.latitude, fix.longitude) > MIN_POSITION_CHANGE_M {
191            return true;
192        }
193    }
194
195    // Speed
196    if let Some(prev_speed) = last_speed {
197        if (fix.speed_mps - prev_speed).abs() > MIN_SPEED_CHANGE_MPS {
198            return true;
199        }
200    }
201
202    // Heading
203    if let Some(prev_heading) = last_heading {
204        let mut diff = (fix.heading_deg - prev_heading).abs();
205        if diff > 180.0 {
206            diff = 360.0 - diff;
207        }
208        if diff > MIN_HEADING_CHANGE_DEG {
209            return true;
210        }
211    }
212
213    false
214}
215
216// ─── LF container builder ───────────────────────────────────────────────────
217
218fn build_lf_container() -> VruLowFrequencyContainer {
219    VruLowFrequencyContainer::new(
220        VruProfileAndSubprofile::pedestrian(VruSubProfilePedestrian::unavailable),
221        None, // sizeClass
222        None, // exteriorLights
223    )
224}
225
226// ─── VAMTransmissionManagement ───────────────────────────────────────────────
227
228/// VAM Transmission Management — ETSI TS 103 300-3 V2.3.1 clause 6.
229///
230/// Timer-based (T_CheckVamGen) architecture. Evaluates triggering conditions
231/// on every tick per clause 6.4.1.
232pub struct VAMTransmissionManagement;
233
234impl VAMTransmissionManagement {
235    /// Spawn the transmission management thread.
236    ///
237    /// Implements the T_CheckVamGen timer loop. The thread drains GPS fixes
238    /// from `gps_rx`, caching the latest, and evaluates VAM generation
239    /// conditions every `T_CHECK_VAM_GEN_MS` milliseconds.
240    pub fn spawn(
241        btp_handle: BTPRouterHandle,
242        coder: VamCoder,
243        device_data: DeviceData,
244        gps_rx: Receiver<GpsFix>,
245    ) {
246        thread::spawn(move || {
247            let t_gen_vam_ms: u64 = T_GEN_VAM_MIN_MS;
248            let _ = t_gen_vam_ms; // used for future DCC integration
249
250            // State of last transmitted VAM
251            let mut last_vam_time: Option<Instant> = None;
252            let mut last_vam_lat: Option<f64> = None;
253            let mut last_vam_lon: Option<f64> = None;
254            let mut last_vam_speed: Option<f64> = None;
255            let mut last_vam_heading: Option<f64> = None;
256
257            // LF container timing
258            let mut last_lf_time: Option<Instant> = None;
259            let mut is_first_vam = true;
260
261            // Cached GPS fix
262            let mut current_fix: Option<GpsFix> = None;
263
264            loop {
265                // Drain GPS fixes for T_CHECK_VAM_GEN_MS, then evaluate conditions
266                let deadline = Instant::now() + Duration::from_millis(T_CHECK_VAM_GEN_MS);
267                loop {
268                    let remaining = deadline.saturating_duration_since(Instant::now());
269                    if remaining.is_zero() {
270                        break;
271                    }
272                    match gps_rx.recv_timeout(remaining) {
273                        Ok(fix) => current_fix = Some(fix),
274                        Err(RecvTimeoutError::Timeout) => break,
275                        Err(RecvTimeoutError::Disconnected) => {
276                            return;
277                        }
278                    }
279                }
280
281                let fix = match current_fix {
282                    Some(ref f) => *f,
283                    None => continue,
284                };
285
286                let now = Instant::now();
287                let mut should_send = false;
288
289                if let Some(last_time) = last_vam_time {
290                    let elapsed_ms = now.duration_since(last_time).as_millis() as u64;
291
292                    // Condition 1: elapsed ≥ T_GenVamMax
293                    // Conditions 2-4: dynamics changed AND elapsed ≥ T_GenVam_DCC
294                    if elapsed_ms >= T_GEN_VAM_MAX_MS
295                        || (elapsed_ms >= T_GEN_VAM_DCC_MS
296                            && check_triggers(
297                                &fix,
298                                last_vam_lat,
299                                last_vam_lon,
300                                last_vam_speed,
301                                last_vam_heading,
302                            ))
303                    {
304                        should_send = true;
305                    }
306                } else {
307                    // First VAM after activation — send immediately
308                    should_send = true;
309                }
310
311                if !should_send {
312                    continue;
313                }
314
315                // Determine LF container inclusion (clause 6.2)
316                let include_lf = is_first_vam
317                    || last_lf_time.is_none()
318                    || now.duration_since(last_lf_time.unwrap()).as_millis() as u64
319                        >= T_GEN_VAM_LF_MIN_MS;
320
321                let lf = if include_lf {
322                    Some(build_lf_container())
323                } else {
324                    None
325                };
326
327                let vam = build_vam(&fix, &device_data, lf);
328
329                if let Ok(data) = coder.encode(&vam) {
330                    let req = BTPDataRequest {
331                        btp_type: CommonNH::BtpB,
332                        source_port: 0,
333                        destination_port: 2018,
334                        destination_port_info: 0,
335                        gn_packet_transport_type: PacketTransportType {
336                            header_type: HeaderType::Tsb,
337                            header_sub_type: HeaderSubType::TopoBroadcast(
338                                TopoBroadcastHST::SingleHop,
339                            ),
340                        },
341                        gn_destination_address: GNAddress {
342                            m: M::GnMulticast,
343                            st: ST::Unknown,
344                            mid: MID::new([0xFF; 6]),
345                        },
346                        communication_profile: CommunicationProfile::Unspecified,
347                        gn_area: Area {
348                            latitude: 0,
349                            longitude: 0,
350                            a: 0,
351                            b: 0,
352                            angle: 0,
353                        },
354                        traffic_class: TrafficClass {
355                            scf: false,
356                            channel_offload: false,
357                            tc_id: 0,
358                        },
359                        security_profile: SecurityProfile::VruAwarenessMessage,
360                        its_aid: 638,
361                        security_permissions: vec![],
362                        gn_max_hop_limit: 1,
363                        gn_max_packet_lifetime: None,
364                        gn_repetition_interval: None,
365                        gn_max_repetition_time: None,
366                        destination: None,
367                        length: data.len() as u16,
368                        data,
369                    };
370                    btp_handle.send_btp_data_request(req);
371
372                    // Update state
373                    last_vam_time = Some(now);
374                    last_vam_lat = Some(fix.latitude);
375                    last_vam_lon = Some(fix.longitude);
376                    last_vam_speed = Some(fix.speed_mps);
377                    last_vam_heading = Some(fix.heading_deg);
378
379                    if include_lf {
380                        last_lf_time = Some(now);
381                    }
382                    is_first_vam = false;
383                }
384            }
385        });
386    }
387}