Skip to main content

rustflexstack/facilities/ca_basic_service/
cam_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//! CAM Transmission Management — ETSI TS 103 900 V2.3.1 (2026-05), the latest version.
5//!
6//! Mirrors `CAMTransmissionManagement` in
7//! `flexstack/facilities/ca_basic_service/cam_transmission_management.py`.
8//!
9//! Key standard-compliance additions:
10//!   - Timer-based (T_CheckCamGen) instead of GPS-callback-reactive (§6.1.2, Annex B).
11//!   - T_GenCam is initialised to T_GenCamMax (not T_GenCamMin) as mandated by §6.1.2.
12//!   - Condition 1 (dynamics: heading/position/speed) and Condition 2 (time) are both
13//!     evaluated on every T_CheckCamGen tick.
14//!   - A condition-1 CAM sets T_GenCam to the elapsed time; N_GenCam consecutive
15//!     condition-2 CAMs reset it to T_GenCamMax; the first CAM keeps T_GenCamMax.
16//!   - Low-Frequency, Special-Vehicle, Very-Low-Frequency and Two-Wheeler extension
17//!     containers are included according to §6.1.2.
18//!   - GN max packet lifetime 950 ms, below 1 s (TS 102 868-2 TP/CAM/MSD/PAR/BV-03;
19//!     single-hop BTP-B/SHB per §6.1.1 and §5.3.4; V2.2.1 §5.3.4.1 allows at most
20//!     1000 ms, V2.3.1 leaves it to the NTL protocol stack).
21//!   - Ingestion into LDM on transmission if LDM adapter is configured.
22
23use super::cam_bindings::cam_pdu_descriptions::{
24    BasicVehicleContainerLowFrequency, ExtensionContainerId, LowFrequencyContainer,
25    SpecialVehicleContainer, TwoWheelerContainer, VeryLowFrequencyContainer,
26    WrappedExtensionContainer, WrappedExtensionContainers,
27};
28use super::cam_bindings::etsi_its_cdd::{
29    AccelerationControl, DeltaAltitude, DeltaLatitude, DeltaLongitude, DeltaReferencePosition,
30    ExteriorLights, Path, PathDeltaTime, PathPoint, VehicleRole,
31};
32use super::cam_coder::{
33    cam_header, generate_white_cam_static, generation_delta_time_now, AccelerationComponent,
34    AccelerationConfidence, AccelerationValue, Altitude, AltitudeConfidence, AltitudeValue,
35    BasicContainer, BasicVehicleContainerHighFrequency, Cam, CamCoder, CamParameters, CamPayload,
36    Curvature, CurvatureCalculationMode, CurvatureConfidence, CurvatureValue, DriveDirection,
37    GenerationDeltaTime, Heading, HeadingConfidence, HeadingValue, HighFrequencyContainer,
38    Latitude, Longitude, PositionConfidenceEllipse, ReferencePositionWithConfidence,
39    SemiAxisLength, Speed, SpeedConfidence, SpeedValue, StationId, TrafficParticipantType,
40    VehicleLength, VehicleLengthConfidenceIndication, VehicleLengthValue, VehicleWidth,
41    Wgs84AngleValue, YawRate, YawRateConfidence, YawRateValue,
42};
43use super::cam_ldm_adaptation::CABasicServiceLDM;
44use crate::btp::router::BTPRouterHandle;
45use crate::btp::service_access_point::BTPDataRequest;
46use crate::facilities::location_service::GpsFix;
47use crate::geonet::gn_address::{GNAddress, M, MID, ST};
48use crate::geonet::service_access_point::{
49    Area, CommonNH, CommunicationProfile, HeaderSubType, HeaderType, PacketTransportType,
50    TopoBroadcastHST, TrafficClass,
51};
52use crate::security::sn_sap::SecurityProfile;
53use rand::Rng;
54use rasn::prelude::*;
55use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
56use std::sync::mpsc::{Receiver, RecvTimeoutError};
57use std::sync::{Arc, Mutex};
58use std::thread;
59use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
60
61// ─── Timing constants (ETSI TS 103 900 V2.3.1 §6.1.2) ───────────────────────
62
63/// T_GenCamMin [ms]: minimum CAM generation interval (10 Hz maximum rate).
64pub const T_GEN_CAM_MIN_MS: u64 = 100;
65/// T_GenCamMax [ms]: maximum CAM generation interval (1 Hz minimum rate).
66pub const T_GEN_CAM_MAX_MS: u64 = 1_000;
67/// T_CheckCamGen [ms]: timer period for condition evaluation (≤ T_GenCamMin).
68pub const T_CHECK_CAM_GEN_MS: u64 = T_GEN_CAM_MIN_MS;
69/// Default T_GenCam_DCC [ms] used until a DCC entity provides a value.
70///
71/// T_GenCam_DCC is the DCC-imposed minimum interval ∈ [T_GenCamMin, T_GenCamMax]
72/// (§6.1.2). Set it at runtime with
73/// [`CAMTransmissionManagement::set_t_gen_cam_dcc`], typically from a
74/// [`DccEntity`](crate::management::DccEntity) listener.
75pub const T_GEN_CAM_DCC_MS: u64 = T_GEN_CAM_MIN_MS;
76
77// ─── Optional-container intervals (§6.1.2) ───────────────────────────────────
78
79/// N_GenCam: consecutive condition-2 CAMs after which T_GenCam returns to T_GenCamMax (§6.1.2).
80pub const N_GEN_CAM_DEFAULT: u32 = 3;
81/// Low-frequency container minimum interval [ms].
82pub const T_GEN_CAM_LF_MS: u64 = 500;
83/// GN packet lifetime of CAMs [s]: below 1 s (TS 102 868-2 TP/CAM/MSD/PAR/BV-03;
84/// TS 103 900 V2.2.1 §5.3.4.1: at most 1000 ms); 950 ms = 19 x 50 ms.
85pub const CAM_PACKET_LIFETIME_S: f64 = 0.95;
86/// Tolerance of the elapsed-time comparisons [ms]: the evaluations are at
87/// least T_CheckCamGen apart, but millisecond truncation of the timestamps can
88/// make the measured interval 1 ms shorter.
89pub const TIMESTAMP_TOLERANCE_MS: u64 = 1;
90/// Special-vehicle container minimum interval [ms].
91pub const T_GEN_CAM_SPECIAL_MS: u64 = 500;
92/// Very-low-frequency container minimum interval [ms].
93pub const T_GEN_CAM_VLF_MS: u64 = 10_000;
94
95/// Station types that must include the Two-Wheeler extension container (§6.1.2):
96/// cyclist(2), moped(3), motorcycle(4).
97pub const TWO_WHEELER_STATION_TYPES: [u8; 3] = [2, 3, 4];
98
99/// VehicleRole enum names indexed by integer value (§6.1.2 / CDD).
100pub const VEHICLE_ROLE_NAMES: [VehicleRole; 16] = [
101    VehicleRole::default,
102    VehicleRole::publicTransport,
103    VehicleRole::specialTransport,
104    VehicleRole::dangerousGoods,
105    VehicleRole::roadWork,
106    VehicleRole::rescue,
107    VehicleRole::emergency,
108    VehicleRole::safetyCar,
109    VehicleRole::agriculture,
110    VehicleRole::commercial,
111    VehicleRole::military,
112    VehicleRole::roadOperator,
113    VehicleRole::taxi,
114    VehicleRole::uvar,
115    VehicleRole::rfu1,
116    VehicleRole::rfu2,
117];
118
119// ─── Haversine ────────────────────────────────────────────────────────────────
120
121/// Return the great-circle distance in metres between two WGS-84 points.
122pub fn haversine_m(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
123    const R: f64 = 6_371_000.0;
124    let dlat = (lat2 - lat1).to_radians();
125    let dlon = (lon2 - lon1).to_radians();
126    let a = (dlat / 2.0).sin().powi(2)
127        + lat1.to_radians().cos() * lat2.to_radians().cos() * (dlon / 2.0).sin().powi(2);
128    R * 2.0 * a.sqrt().atan2((1.0 - a).max(0.0).sqrt())
129}
130
131// ─── Confidence Helpers ───────────────────────────────────────────────────────
132
133/// Translates the epx and epy TPV values (in metres) to the position confidence ellipse value.
134pub fn create_position_confidence(epx: f64, epy: f64) -> PositionConfidenceEllipse {
135    let mut semi_major = (epx * 100.0).round() as u16;
136    let mut semi_minor = (epy * 100.0).round() as u16;
137    if epy >= epx {
138        semi_major = (epy * 100.0).round() as u16;
139        semi_minor = (epx * 100.0).round() as u16;
140    }
141    PositionConfidenceEllipse::new(
142        SemiAxisLength(semi_major.min(4095)),
143        SemiAxisLength(semi_minor.min(4095)),
144        Wgs84AngleValue(0),
145    )
146}
147
148/// Translates the epv TPV value (in metres) to the altitude confidence value.
149pub fn create_altitude_confidence(epv: f64) -> AltitudeConfidence {
150    if epv < 0.01 {
151        AltitudeConfidence::alt_000_01
152    } else if epv < 0.02 {
153        AltitudeConfidence::alt_000_02
154    } else if epv < 0.05 {
155        AltitudeConfidence::alt_000_05
156    } else if epv < 0.10 {
157        AltitudeConfidence::alt_000_10
158    } else if epv < 0.20 {
159        AltitudeConfidence::alt_000_20
160    } else if epv < 0.50 {
161        AltitudeConfidence::alt_000_50
162    } else if epv < 1.0 {
163        AltitudeConfidence::alt_001_00
164    } else if epv < 2.0 {
165        AltitudeConfidence::alt_002_00
166    } else if epv < 5.0 {
167        AltitudeConfidence::alt_005_00
168    } else if epv < 10.0 {
169        AltitudeConfidence::alt_010_00
170    } else if epv < 20.0 {
171        AltitudeConfidence::alt_020_00
172    } else if epv < 50.0 {
173        AltitudeConfidence::alt_050_00
174    } else if epv < 100.0 {
175        AltitudeConfidence::alt_100_00
176    } else if epv <= 200.0 {
177        AltitudeConfidence::alt_200_00
178    } else {
179        AltitudeConfidence::outOfRange
180    }
181}
182
183/// Translates the epd TPV value (in degrees) to the heading confidence value.
184pub fn create_heading_confidence(epd: f64) -> HeadingConfidence {
185    if epd <= 12.5 {
186        HeadingConfidence(((epd * 10.0).round() as u8).min(126))
187    } else {
188        HeadingConfidence(126)
189    }
190}
191
192// ─── VehicleData ─────────────────────────────────────────────────────────────
193
194/// Static vehicle data used to populate every CAM.
195///
196/// Mirrors the `VehicleData` frozen dataclass in the Python implementation
197/// (ETSI TS 103 900 V2.3.1).
198#[derive(Debug, Clone, PartialEq)]
199pub struct VehicleData {
200    /// ITS station ID (0–4 294 967 295).
201    pub station_id: u32,
202    /// ITS station type / traffic participant type (0–255).
203    /// Common values: 0 = unknown, 2 = cyclist, 3 = moped, 4 = motorcycle, 5 = passengerCar.
204    pub station_type: u8,
205    /// Drive direction (forward / backward / unavailable).
206    pub drive_direction: DriveDirection,
207    /// Vehicle length in 0.1 m units (1–1 022 valid; 1 023 = unavailable).
208    pub vehicle_length_value: u16,
209    /// Vehicle width in 0.1 m units (1–61 valid; 62 = unavailable).
210    pub vehicle_width: u8,
211    /// VehicleRole (0=default). Used in the Low-Frequency container and to
212    /// decide whether a Special-Vehicle container is required (§6.1.2).
213    pub vehicle_role: u8,
214    /// ExteriorLights BIT STRING (SIZE(8)). One byte; bits ordered MSB→LSB
215    /// correspond to lowBeam(0)…parkingLights(7). Default = all off.
216    pub exterior_lights: Vec<u8>,
217    /// Special vehicle container data (CHOICE variant), e.g.
218    /// `SpecialVehicleContainer::emergencyContainer(...)`.
219    /// `None` if not applicable.
220    pub special_vehicle_data: Option<SpecialVehicleContainer>,
221}
222
223impl Default for VehicleData {
224    /// Sensible defaults — PassengerCar, all kinematic fields unavailable.
225    fn default() -> Self {
226        VehicleData {
227            station_id: 0,
228            station_type: 0,
229            drive_direction: DriveDirection::unavailable,
230            vehicle_length_value: 1023,
231            vehicle_width: 62,
232            vehicle_role: 0,
233            exterior_lights: vec![0x00],
234            special_vehicle_data: None,
235        }
236    }
237}
238
239impl VehicleData {
240    /// Validate vehicle data parameters according to ETSI specifications.
241    pub fn validate(&self) -> Result<(), String> {
242        if self.vehicle_role > 15 {
243            return Err("vehicle_role must be between 0 and 15".to_string());
244        }
245        if self.vehicle_length_value > 1023 {
246            return Err("Vehicle length must be between 0 and 1023".to_string());
247        }
248        if self.vehicle_width > 62 {
249            return Err("Vehicle width must be between 0 and 62".to_string());
250        }
251        if self.exterior_lights.is_empty() {
252            return Err("exterior_lights must be at least 1 byte".to_string());
253        }
254        // The special vehicle container must be the one of the vehicle role
255        // (TS 103 900 V2.3.1 clause 7.6, Annex A).
256        if let Some(container) = &self.special_vehicle_data {
257            let given = super::cam_ssp::special_container_name(container);
258            match super::cam_ssp::role_special_container(self.vehicle_role) {
259                None => {
260                    return Err(format!(
261                        "vehicle_role {} has no special vehicle container",
262                        self.vehicle_role
263                    ))
264                }
265                Some(expected) if expected != given => {
266                    return Err(format!(
267                        "vehicle_role {} requires {expected}, got {given}",
268                        self.vehicle_role
269                    ))
270                }
271                _ => {}
272            }
273        }
274        Ok(())
275    }
276
277    /// Construct a new `VehicleData` validating its parameters.
278    #[allow(clippy::too_many_arguments)]
279    pub fn new(
280        station_id: u32,
281        station_type: u8,
282        drive_direction: DriveDirection,
283        vehicle_length_value: u16,
284        vehicle_width: u8,
285        vehicle_role: u8,
286        exterior_lights: Vec<u8>,
287        special_vehicle_data: Option<SpecialVehicleContainer>,
288    ) -> Result<Self, String> {
289        let vd = VehicleData {
290            station_id,
291            station_type,
292            drive_direction,
293            vehicle_length_value,
294            vehicle_width,
295            vehicle_role,
296            exterior_lights,
297            special_vehicle_data,
298        };
299        vd.validate()?;
300        Ok(vd)
301    }
302}
303
304// ─── CooperativeAwarenessMessage ─────────────────────────────────────────────
305
306/// High-level Cooperative Awareness Message builder / container.
307///
308/// Mirrors `CooperativeAwarenessMessage` in Python.
309#[derive(Debug, Clone, PartialEq)]
310pub struct CooperativeAwarenessMessage {
311    pub cam: Cam,
312}
313
314impl Default for CooperativeAwarenessMessage {
315    fn default() -> Self {
316        Self::new()
317    }
318}
319
320impl CooperativeAwarenessMessage {
321    /// Create a new `CooperativeAwarenessMessage` initialized as a white CAM.
322    pub fn new() -> Self {
323        CooperativeAwarenessMessage {
324            cam: generate_white_cam_static(),
325        }
326    }
327
328    /// Generate a white CAM statically.
329    pub fn generate_white_cam_static() -> Cam {
330        generate_white_cam_static()
331    }
332
333    /// Generate a white CAM.
334    pub fn generate_white_cam(&self) -> Cam {
335        generate_white_cam_static()
336    }
337
338    /// Populate CAM fields with vehicle data.
339    pub fn fullfill_with_vehicle_data(&mut self, vehicle_data: &VehicleData) {
340        self.cam.header.station_id = StationId(vehicle_data.station_id);
341        self.cam.cam.cam_parameters.basic_container.station_type =
342            TrafficParticipantType(vehicle_data.station_type);
343
344        if let HighFrequencyContainer::basicVehicleContainerHighFrequency(ref mut hf) =
345            self.cam.cam.cam_parameters.high_frequency_container
346        {
347            hf.drive_direction = vehicle_data.drive_direction;
348            hf.vehicle_length.vehicle_length_value =
349                VehicleLengthValue(vehicle_data.vehicle_length_value);
350            hf.vehicle_width = VehicleWidth(vehicle_data.vehicle_width);
351        }
352    }
353
354    /// Populate CAM generation delta time from a UNIX timestamp in seconds.
355    pub fn fullfill_gen_delta_time_with_timestamp(&mut self, timestamp_s: f64) {
356        self.cam.cam.generation_delta_time = GenerationDeltaTime::from_timestamp(timestamp_s);
357    }
358
359    /// Populate CAM fields with GPS fix / TPV data.
360    pub fn fullfill_with_tpv_data(&mut self, fix: &GpsFix) {
361        let now_s = SystemTime::now()
362            .duration_since(UNIX_EPOCH)
363            .unwrap_or_default()
364            .as_secs_f64();
365        self.fullfill_gen_delta_time_with_timestamp(now_s);
366
367        let ref_pos = &mut self
368            .cam
369            .cam
370            .cam_parameters
371            .basic_container
372            .reference_position;
373        ref_pos.latitude =
374            Latitude(((fix.latitude * 1e7).round() as i32).clamp(-900_000_000, 900_000_000));
375        ref_pos.longitude =
376            Longitude(((fix.longitude * 1e7).round() as i32).clamp(-1_800_000_000, 1_800_000_000));
377
378        let alt_val = ((fix.altitude_m * 100.0).round() as i32).clamp(-100_000, 800_000);
379        ref_pos.altitude.altitude_value = AltitudeValue(alt_val);
380
381        if let HighFrequencyContainer::basicVehicleContainerHighFrequency(ref mut hf) =
382            self.cam.cam.cam_parameters.high_frequency_container
383        {
384            hf.heading.heading_value =
385                HeadingValue(((fix.heading_deg * 10.0).round() as u16).clamp(0, 3600));
386            let spd = ((fix.speed_mps * 100.0).round() as u16).min(16_382);
387            hf.speed.speed_value = SpeedValue(spd);
388        }
389    }
390}
391
392// ─── Path history entry ──────────────────────────────────────────────────────
393
394#[derive(Debug, Clone, Copy)]
395pub struct PathEntry {
396    pub lat: f64,
397    pub lon: f64,
398    pub time_ms: u64,
399}
400
401// ─── Transmission State ──────────────────────────────────────────────────────
402
403#[derive(Debug, Default)]
404pub struct TransmissionState {
405    pub last_cam_time_ms: Option<u64>,
406    pub last_cam_heading: Option<f64>,
407    pub last_cam_lat: Option<f64>,
408    pub last_cam_lon: Option<f64>,
409    pub last_cam_speed: Option<f64>,
410
411    pub cam_count: u64,
412    pub last_lf_time_ms: Option<u64>,
413    pub last_vlf_time_ms: Option<u64>,
414    pub last_special_time_ms: Option<u64>,
415
416    pub path_history: Vec<PathEntry>,
417    pub current_fix: Option<GpsFix>,
418    pub last_cam_generation_delta_time: Option<GenerationDeltaTime>,
419}
420
421// ─── In-vehicle data (§5.2, §7.1) ─────────────────────────────────────────────
422
423/// AccelerationControl BIT STRING (SIZE(7)) bit names (ETSI TS 102 894-2 CDD).
424pub const ACCELERATION_CONTROL_BITS: [&str; 7] = [
425    "brakePedalEngaged",
426    "gasPedalEngaged",
427    "emergencyBrakeEngaged",
428    "collisionWarningEngaged",
429    "accEngaged",
430    "cruiseControlEngaged",
431    "speedLimiterEngaged",
432];
433/// ExteriorLights BIT STRING (SIZE(8)) bit names (ETSI TS 102 894-2 CDD).
434pub const EXTERIOR_LIGHTS_BITS: [&str; 8] = [
435    "lowBeamHeadlightsOn",
436    "highBeamHeadlightsOn",
437    "leftTurnSignalOn",
438    "rightTurnSignalOn",
439    "daytimeRunningLightsOn",
440    "reverseLightOn",
441    "fogLightOn",
442    "parkingLightsOn",
443];
444
445/// Latest in-vehicle data provided to the CA basic service (ETSI TS 103 900
446/// V2.3.1 clauses 5.2 and 7.1): the next generated CAM carries these values.
447/// `None` keeps the static value of [`VehicleData`] (drive direction, exterior
448/// lights) or omits the optional field (accelerationControl). The bit arrays
449/// are indexed as [`ACCELERATION_CONTROL_BITS`] / [`EXTERIOR_LIGHTS_BITS`].
450#[derive(Debug, Clone, PartialEq)]
451pub struct InVehicleData {
452    /// CurvatureValue (-1023..1023, 1023 = unavailable).
453    pub curvature_value: i16,
454    pub curvature_confidence: CurvatureConfidence,
455    pub curvature_calculation_mode: CurvatureCalculationMode,
456    /// YawRateValue in 0,01 degree/s (-32766..32767, 32767 = unavailable).
457    pub yaw_rate_value: i16,
458    pub yaw_rate_confidence: YawRateConfidence,
459    pub drive_direction: Option<DriveDirection>,
460    pub acceleration_control: Option<[bool; 7]>,
461    pub exterior_lights: Option<[bool; 8]>,
462}
463
464impl Default for InVehicleData {
465    fn default() -> Self {
466        InVehicleData {
467            curvature_value: 1023,
468            curvature_confidence: CurvatureConfidence::unavailable,
469            curvature_calculation_mode: CurvatureCalculationMode::unavailable,
470            yaw_rate_value: 32767,
471            yaw_rate_confidence: YawRateConfidence::unavailable,
472            drive_direction: None,
473            acceleration_control: None,
474            exterior_lights: None,
475        }
476    }
477}
478
479impl InVehicleData {
480    /// Check the value ranges of the CDD.
481    pub fn validate(&self) -> Result<(), String> {
482        if !(-1023..=1023).contains(&self.curvature_value) {
483            return Err("curvature_value out of range (-1023..1023)".into());
484        }
485        if self.yaw_rate_value < -32766 {
486            return Err("yaw_rate_value out of range (-32766..32767)".into());
487        }
488        Ok(())
489    }
490}
491
492fn bit_string<const N: usize>(bits: &[bool; N]) -> rasn::types::FixedBitString<N> {
493    let mut out = rasn::types::FixedBitString::<N>::default();
494    for (i, bit) in bits.iter().enumerate() {
495        out.set(i, *bit);
496    }
497    out
498}
499
500// ─── CAMTransmissionManagement ───────────────────────────────────────────────
501
502/// CAM Transmission Management — ETSI TS 103 900 V2.3.1 §6.1.
503#[derive(Clone)]
504pub struct CAMTransmissionManagement {
505    pub btp_handle: BTPRouterHandle,
506    pub cam_coder: CamCoder,
507    pub vehicle_data: VehicleData,
508    pub ca_basic_service_ldm: Option<CABasicServiceLDM>,
509
510    pub t_gen_cam_ms: Arc<AtomicU64>,
511    /// T_GenCam_DCC [ms], provided by the management layer (DCC).
512    pub t_gen_cam_dcc_ms: Arc<AtomicU64>,
513    pub n_gen_cam_counter: Arc<AtomicU32>,
514
515    pub state: Arc<Mutex<TransmissionState>>,
516    pub active: Arc<AtomicBool>,
517    /// Latest in-vehicle data (§5.2, §7.1).
518    pub in_vehicle_data: Arc<Mutex<InVehicleData>>,
519}
520
521impl CAMTransmissionManagement {
522    /// Create a new `CAMTransmissionManagement` instance.
523    pub fn new(
524        btp_handle: BTPRouterHandle,
525        cam_coder: CamCoder,
526        vehicle_data: VehicleData,
527        ca_basic_service_ldm: Option<CABasicServiceLDM>,
528    ) -> Self {
529        CAMTransmissionManagement {
530            btp_handle,
531            cam_coder,
532            vehicle_data,
533            ca_basic_service_ldm,
534            t_gen_cam_ms: Arc::new(AtomicU64::new(T_GEN_CAM_MAX_MS)),
535            t_gen_cam_dcc_ms: Arc::new(AtomicU64::new(T_GEN_CAM_DCC_MS)),
536            n_gen_cam_counter: Arc::new(AtomicU32::new(0)),
537            state: Arc::new(Mutex::new(TransmissionState::default())),
538            active: Arc::new(AtomicBool::new(false)),
539            in_vehicle_data: Arc::new(Mutex::new(InVehicleData::default())),
540        }
541    }
542
543    /// Update the latest in-vehicle data (§5.2, §7.1): the next CAM carries
544    /// the new values. Invalid values return an error and leave the data
545    /// unchanged.
546    pub fn update_in_vehicle_data(
547        &self,
548        update: impl FnOnce(&mut InVehicleData),
549    ) -> Result<InVehicleData, String> {
550        let mut guard = self
551            .in_vehicle_data
552            .lock()
553            .map_err(|_| "in-vehicle data lock poisoned".to_string())?;
554        let mut data = guard.clone();
555        update(&mut data);
556        data.validate()?;
557        *guard = data.clone();
558        Ok(data)
559    }
560
561    /// The latest in-vehicle data.
562    pub fn in_vehicle_data(&self) -> InVehicleData {
563        self.in_vehicle_data
564            .lock()
565            .map(|d| d.clone())
566            .unwrap_or_default()
567    }
568
569    /// Activate the CA service (§5.3.1 (CA_Activation)).
570    ///
571    /// Resets per-activation dynamics and timer state.
572    pub fn start(&self) {
573        if self.active.swap(true, Ordering::SeqCst) {
574            return; // Already active
575        }
576        self.t_gen_cam_ms.store(T_GEN_CAM_MAX_MS, Ordering::SeqCst);
577        self.n_gen_cam_counter.store(0, Ordering::SeqCst);
578
579        if let Ok(mut st) = self.state.lock() {
580            st.cam_count = 0;
581            st.last_cam_time_ms = None;
582            st.last_cam_heading = None;
583            st.last_cam_lat = None;
584            st.last_cam_lon = None;
585            st.last_cam_speed = None;
586            st.last_lf_time_ms = None;
587            st.last_vlf_time_ms = None;
588            st.last_special_time_ms = None;
589            st.path_history.clear();
590        }
591    }
592
593    /// Deactivate the CA service (§5.3.1 (CA_Activation)).
594    pub fn stop(&self) {
595        self.active.store(false, Ordering::SeqCst);
596    }
597
598    /// Whether the transmission service is active.
599    pub fn is_active(&self) -> bool {
600        self.active.load(Ordering::SeqCst)
601    }
602
603    /// Current T_GenCam value in milliseconds.
604    pub fn t_gen_cam(&self) -> u64 {
605        self.t_gen_cam_ms.load(Ordering::SeqCst)
606    }
607
608    /// Current T_GenCam_DCC value in milliseconds.
609    pub fn t_gen_cam_dcc(&self) -> u64 {
610        self.t_gen_cam_dcc_ms.load(Ordering::SeqCst)
611    }
612
613    /// Set T_GenCam_DCC (§6.1.2), clamped to [T_GenCamMin, T_GenCamMax].
614    ///
615    /// Shared by all clones of this instance, so it may be called from a DCC
616    /// entity thread while the transmission thread is running.
617    pub fn set_t_gen_cam_dcc(&self, t_gen_cam_dcc_ms: u64) {
618        let clamped = t_gen_cam_dcc_ms.clamp(T_GEN_CAM_MIN_MS, T_GEN_CAM_MAX_MS);
619        self.t_gen_cam_dcc_ms.store(clamped, Ordering::SeqCst);
620    }
621
622    /// Number of CAMs sent since activation.
623    pub fn cam_count(&self) -> u64 {
624        self.state.lock().map(|st| st.cam_count).unwrap_or(0)
625    }
626
627    /// Timestamp (ms) of the last transmitted CAM.
628    pub fn last_cam_time_ms(&self) -> Option<u64> {
629        self.state.lock().ok().and_then(|st| st.last_cam_time_ms)
630    }
631
632    /// Cache the latest position data (§6.1.2).
633    ///
634    /// This method only updates the internal position cache and does not
635    /// trigger transmission directly.
636    pub fn location_service_callback(&self, fix: GpsFix) {
637        if let Ok(mut st) = self.state.lock() {
638            st.current_fix = Some(fix);
639        }
640    }
641
642    /// Return true if at least one dynamics threshold is exceeded (§6.1.2 Condition 1).
643    ///
644    /// Thresholds:
645    ///   - |Δheading| > 4°
646    ///   - |Δposition| > 4 m (haversine)
647    ///   - |Δspeed| > 0.5 m/s
648    pub fn check_dynamics(&self, fix: &GpsFix) -> bool {
649        let st = match self.state.lock() {
650            Ok(s) => s,
651            Err(_) => return true,
652        };
653
654        if st.last_cam_heading.is_none() {
655            return true; // No reference — treat as changed
656        }
657
658        // Heading
659        if let Some(prev) = st.last_cam_heading {
660            let mut diff = (fix.heading_deg - prev).abs();
661            if diff > 180.0 {
662                diff = 360.0 - diff;
663            }
664            if diff > 4.0 {
665                return true;
666            }
667        }
668
669        // Position
670        if let (Some(prev_lat), Some(prev_lon)) = (st.last_cam_lat, st.last_cam_lon) {
671            if haversine_m(prev_lat, prev_lon, fix.latitude, fix.longitude) > 4.0 {
672                return true;
673            }
674        }
675
676        // Speed
677        if let Some(prev_speed) = st.last_cam_speed {
678            if (fix.speed_mps - prev_speed).abs() > 0.5 {
679                return true;
680            }
681        }
682
683        false
684    }
685
686    /// Low-Frequency container: first CAM, then every ≥ 500 ms (§6.1.2).
687    pub fn should_include_lf(&self, now_ms: u64) -> bool {
688        let st = match self.state.lock() {
689            Ok(s) => s,
690            Err(_) => return true,
691        };
692        if st.cam_count == 0 {
693            return true;
694        }
695        match st.last_lf_time_ms {
696            None => true,
697            Some(t) => now_ms.saturating_sub(t) >= T_GEN_CAM_LF_MS,
698        }
699    }
700
701    /// Special-Vehicle container: first CAM (if role ≠ default), then ≥ 500 ms (§6.1.2).
702    pub fn should_include_special_vehicle(&self, now_ms: u64) -> bool {
703        if self.vehicle_data.vehicle_role == 0 {
704            return false;
705        }
706        let st = match self.state.lock() {
707            Ok(s) => s,
708            Err(_) => return true,
709        };
710        if st.cam_count == 0 {
711            return true;
712        }
713        match st.last_special_time_ms {
714            None => true,
715            Some(t) => now_ms.saturating_sub(t) >= T_GEN_CAM_SPECIAL_MS,
716        }
717    }
718
719    /// Very-Low-Frequency extension container (§6.1.2):
720    ///   - Second CAM after activation (cam_count == 1).
721    ///   - After that: ≥ 10 s elapsed AND LF/special containers NOT included.
722    pub fn should_include_vlf(&self, now_ms: u64, include_lf: bool, include_special: bool) -> bool {
723        let st = match self.state.lock() {
724            Ok(s) => s,
725            Err(_) => return false,
726        };
727        if st.cam_count == 1 {
728            return true;
729        }
730        match st.last_vlf_time_ms {
731            None => false,
732            Some(t) => {
733                now_ms.saturating_sub(t) >= T_GEN_CAM_VLF_MS && !include_lf && !include_special
734            }
735        }
736    }
737
738    /// Two-Wheeler extension container in ALL CAMs for cyclist/moped/motorcycle (§6.1.2).
739    pub fn should_include_two_wheeler(&self) -> bool {
740        TWO_WHEELER_STATION_TYPES.contains(&self.vehicle_data.station_type)
741    }
742
743    /// Build the BasicVehicleContainerLowFrequency container.
744    pub fn build_lf_container(&self, fix: &GpsFix, now_ms: u64) -> LowFrequencyContainer {
745        let role_idx = self.vehicle_data.vehicle_role as usize;
746        let role = if role_idx < VEHICLE_ROLE_NAMES.len() {
747            VEHICLE_ROLE_NAMES[role_idx]
748        } else {
749            VehicleRole::default
750        };
751
752        let ext_lights = match self.in_vehicle_data().exterior_lights {
753            Some(bits) => ExteriorLights(bit_string(&bits)),
754            None => {
755                let mut ext_bits = rasn::types::FixedBitString::<8>::default();
756                let lights_byte = self
757                    .vehicle_data
758                    .exterior_lights
759                    .first()
760                    .copied()
761                    .unwrap_or(0);
762                for i in 0..8 {
763                    if lights_byte & (1 << (7 - i)) != 0 {
764                        ext_bits.set(i, true);
765                    }
766                }
767                ExteriorLights(ext_bits)
768            }
769        };
770
771        let path_points = self.get_path_history(fix, now_ms);
772        let path = Path(path_points);
773
774        LowFrequencyContainer::basicVehicleContainerLowFrequency(
775            BasicVehicleContainerLowFrequency::new(role, ext_lights, path),
776        )
777    }
778
779    /// Convert stored path history to a list of relative PathPoint entries (capped at 23).
780    pub fn get_path_history(&self, current_fix: &GpsFix, now_ms: u64) -> Vec<PathPoint> {
781        let st = match self.state.lock() {
782            Ok(s) => s,
783            Err(_) => return Vec::new(),
784        };
785
786        let mut result = Vec::new();
787        for entry in st.path_history.iter().rev() {
788            let delta_lat = ((entry.lat - current_fix.latitude) * 1e7).round() as i32;
789            let delta_lon = ((entry.lon - current_fix.longitude) * 1e7).round() as i32;
790            if !(-131_071..=131_072).contains(&delta_lat) {
791                break;
792            }
793            if !(-131_071..=131_072).contains(&delta_lon) {
794                break;
795            }
796            let delta_time_10ms = ((now_ms.saturating_sub(entry.time_ms)) / 10).clamp(1, 65_534);
797            result.push(PathPoint::new(
798                DeltaReferencePosition::new(
799                    DeltaLatitude(delta_lat),
800                    DeltaLongitude(delta_lon),
801                    DeltaAltitude(12800), // unavailable
802                ),
803                Some(PathDeltaTime(Integer::from(delta_time_10ms as i128))),
804            ));
805            if result.len() >= 23 {
806                break;
807            }
808        }
809        result
810    }
811
812    /// Evaluate CAM conditions and generate/send if either condition 1 or 2 is met.
813    pub fn evaluate_and_maybe_send(&self, now_ms: u64) -> Option<Cam> {
814        let fix = {
815            let st = self.state.lock().ok()?;
816            st.current_fix?
817        };
818
819        let (last_time, t_gen_cam) = {
820            let st = self.state.lock().ok()?;
821            (
822                st.last_cam_time_ms,
823                self.t_gen_cam_ms.load(Ordering::SeqCst),
824            )
825        };
826        let t_gen_cam_dcc = self.t_gen_cam_dcc_ms.load(Ordering::SeqCst);
827
828        // First CAM after activation — send immediately; T_GenCam keeps its
829        // default T_GenCamMax (condition 0: neither 1 nor 2).
830        let Some(last_time) = last_time else {
831            return self.generate_and_send_cam(&fix, now_ms, 0).ok();
832        };
833
834        let elapsed_ms = now_ms
835            .saturating_sub(last_time)
836            .saturating_add(TIMESTAMP_TOLERANCE_MS);
837
838        // Condition 1 (§6.1.2): elapsed ≥ T_GenCam_DCC AND dynamics changed
839        if elapsed_ms >= t_gen_cam_dcc && self.check_dynamics(&fix) {
840            return self.generate_and_send_cam(&fix, now_ms, 1).ok();
841        }
842
843        // Condition 2 (§6.1.2): elapsed ≥ T_GenCam AND elapsed ≥ T_GenCam_DCC
844        if elapsed_ms >= t_gen_cam && elapsed_ms >= t_gen_cam_dcc {
845            return self.generate_and_send_cam(&fix, now_ms, 2).ok();
846        }
847
848        None
849    }
850
851    /// Build, encode, and transmit a CAM (Annex B.2.4).
852    pub fn generate_and_send_cam(
853        &self,
854        fix: &GpsFix,
855        now_ms: u64,
856        condition: u8,
857    ) -> Result<Cam, String> {
858        let elapsed_ms = self
859            .state
860            .lock()
861            .ok()
862            .and_then(|st| st.last_cam_time_ms)
863            .map(|t| now_ms.saturating_sub(t))
864            .unwrap_or(0);
865
866        let include_lf = self.should_include_lf(now_ms);
867        let include_special = self.should_include_special_vehicle(now_ms);
868        let include_vlf = self.should_include_vlf(now_ms, include_lf, include_special);
869        let include_tw = self.should_include_two_wheeler();
870
871        // ── BasicContainer ──────────────────────────────────────────────────
872        let ref_pos = ReferencePositionWithConfidence::new(
873            Latitude(((fix.latitude * 1e7).round() as i32).clamp(-900_000_000, 900_000_000)),
874            Longitude(((fix.longitude * 1e7).round() as i32).clamp(-1_800_000_000, 1_800_000_000)),
875            PositionConfidenceEllipse::new(
876                SemiAxisLength(4095),
877                SemiAxisLength(4095),
878                Wgs84AngleValue(3601),
879            ),
880            Altitude::new(
881                AltitudeValue(((fix.altitude_m * 100.0).round() as i32).clamp(-100_000, 800_000)),
882                AltitudeConfidence::unavailable,
883            ),
884        );
885        let basic_container = BasicContainer::new(
886            TrafficParticipantType(self.vehicle_data.station_type),
887            ref_pos,
888        );
889
890        // ── HighFrequencyContainer ───────────────────────────────────────────
891        let heading = Heading::new(
892            HeadingValue(((fix.heading_deg * 10.0).round() as u16).clamp(0, 3600)),
893            HeadingConfidence(127),
894        );
895        let speed = Speed::new(
896            SpeedValue(((fix.speed_mps * 100.0).round() as u16).min(16_382)),
897            SpeedConfidence(127),
898        );
899        let vehicle_length = VehicleLength::new(
900            VehicleLengthValue(self.vehicle_data.vehicle_length_value.clamp(1, 1023)),
901            VehicleLengthConfidenceIndication::unavailable,
902        );
903        let vehicle_width = VehicleWidth(self.vehicle_data.vehicle_width.clamp(1, 62));
904        let longitudinal_acceleration =
905            AccelerationComponent::new(AccelerationValue(161), AccelerationConfidence(102));
906        // Latest in-vehicle data (§5.2, §7.1)
907        let in_vehicle = self.in_vehicle_data();
908        let curvature = Curvature::new(
909            CurvatureValue(in_vehicle.curvature_value),
910            in_vehicle.curvature_confidence,
911        );
912        let yaw_rate = YawRate::new(
913            YawRateValue(in_vehicle.yaw_rate_value),
914            in_vehicle.yaw_rate_confidence,
915        );
916        let acceleration_control = in_vehicle
917            .acceleration_control
918            .as_ref()
919            .map(|bits| AccelerationControl(bit_string(bits)));
920
921        let hf = BasicVehicleContainerHighFrequency::new(
922            heading,
923            speed,
924            in_vehicle
925                .drive_direction
926                .unwrap_or(self.vehicle_data.drive_direction),
927            vehicle_length,
928            vehicle_width,
929            longitudinal_acceleration,
930            curvature,
931            in_vehicle.curvature_calculation_mode,
932            yaw_rate,
933            acceleration_control,
934            None,
935            None,
936            None,
937            None,
938            None,
939            None,
940        );
941
942        // ── Optional Containers ──────────────────────────────────────────────
943        let lf = if include_lf {
944            Some(self.build_lf_container(fix, now_ms))
945        } else {
946            None
947        };
948
949        let special = if include_special {
950            self.vehicle_data.special_vehicle_data.clone()
951        } else {
952            None
953        };
954
955        let mut ext_vec = Vec::new();
956        if include_tw {
957            let tw = TwoWheelerContainer::new(None, None, None, None);
958            if let Ok(tw_bytes) = rasn::uper::encode(&tw) {
959                ext_vec.push(WrappedExtensionContainer::new(
960                    ExtensionContainerId(Integer::from(1i128)),
961                    Any::new(tw_bytes.to_vec()),
962                ));
963            }
964        }
965        if include_vlf {
966            let vlf = VeryLowFrequencyContainer::new(None, None, None);
967            if let Ok(vlf_bytes) = rasn::uper::encode(&vlf) {
968                ext_vec.push(WrappedExtensionContainer::new(
969                    ExtensionContainerId(Integer::from(3i128)),
970                    Any::new(vlf_bytes.to_vec()),
971                ));
972            }
973        }
974        let extensions = if ext_vec.is_empty() {
975            None
976        } else {
977            Some(WrappedExtensionContainers(ext_vec))
978        };
979
980        let cam = Cam::new(
981            cam_header(self.vehicle_data.station_id),
982            CamPayload::new(
983                generation_delta_time_now(),
984                CamParameters::new(
985                    basic_container,
986                    HighFrequencyContainer::basicVehicleContainerHighFrequency(hf),
987                    lf,
988                    special,
989                    extensions,
990                ),
991            ),
992        );
993
994        // Transmit (Annex B.2.5 — on encoding/transmission failure skip state update)
995        self.send_cam(&cam)?;
996
997        // Update state after successful send
998        self.update_send_state(
999            fix,
1000            now_ms,
1001            elapsed_ms,
1002            condition,
1003            include_lf,
1004            include_special,
1005            include_vlf,
1006        );
1007
1008        Ok(cam)
1009    }
1010
1011    /// Encode and transmit a CAM PDU via BTP-B/SHB (§6.1.1, §5.3.4; V2.2.1 §5.3.4.1).
1012    pub fn send_cam(&self, cam: &Cam) -> Result<(), String> {
1013        let data = self.cam_coder.encode(cam)?;
1014        let request = BTPDataRequest {
1015            btp_type: CommonNH::BtpB,
1016            source_port: 0,
1017            destination_port: 2001,
1018            destination_port_info: 0,
1019            gn_packet_transport_type: PacketTransportType {
1020                header_type: HeaderType::Tsb,
1021                header_sub_type: HeaderSubType::TopoBroadcast(TopoBroadcastHST::SingleHop),
1022            },
1023            gn_destination_address: GNAddress {
1024                m: M::GnMulticast,
1025                st: ST::Unknown,
1026                mid: MID::new([0xFF; 6]),
1027            },
1028            communication_profile: CommunicationProfile::Unspecified,
1029            gn_area: Area {
1030                latitude: 0,
1031                longitude: 0,
1032                a: 0,
1033                b: 0,
1034                angle: 0,
1035            },
1036            traffic_class: TrafficClass {
1037                scf: false,
1038                channel_offload: false,
1039                tc_id: 0,
1040            },
1041            security_profile: SecurityProfile::CooperativeAwarenessMessage,
1042            its_aid: 36,
1043            // Sender-side SSP check (clause 6.2.2.2): sign only with an AT
1044            // granting the protected content of this CAM.
1045            security_permissions: super::cam_ssp::permissions_bitmap(cam, Some(&self.cam_coder)),
1046            gn_max_hop_limit: 1,
1047            gn_max_packet_lifetime: Some(CAM_PACKET_LIFETIME_S),
1048            gn_repetition_interval: None,
1049            gn_max_repetition_time: None,
1050            destination: None,
1051            length: data.len() as u16,
1052            data,
1053        };
1054
1055        self.btp_handle.send_btp_data_request(request);
1056
1057        if let Some(ref ldm) = self.ca_basic_service_ldm {
1058            let _ = ldm.add_provider_data_to_ldm(cam);
1059        }
1060
1061        Ok(())
1062    }
1063
1064    /// Update state variables after a successful CAM transmission.
1065    #[allow(clippy::too_many_arguments)]
1066    pub fn update_send_state(
1067        &self,
1068        fix: &GpsFix,
1069        now_ms: u64,
1070        elapsed_ms: u64,
1071        condition: u8,
1072        include_lf: bool,
1073        include_special: bool,
1074        include_vlf: bool,
1075    ) {
1076        // §6.1.2: a condition-1 CAM sets T_GenCam to the time elapsed since the
1077        // last CAM; after N_GenCam consecutive CAMs due to condition 2,
1078        // T_GenCam is set to T_GenCamMax. The first CAM after activation
1079        // (condition 0) leaves the default T_GenCamMax.
1080        if condition == 1 {
1081            let clamped = elapsed_ms.clamp(T_GEN_CAM_MIN_MS, T_GEN_CAM_MAX_MS);
1082            self.t_gen_cam_ms.store(clamped, Ordering::SeqCst);
1083            self.n_gen_cam_counter.store(0, Ordering::SeqCst);
1084        } else if condition == 2 {
1085            let prev_n = self.n_gen_cam_counter.fetch_add(1, Ordering::SeqCst);
1086            if prev_n + 1 >= N_GEN_CAM_DEFAULT {
1087                self.t_gen_cam_ms.store(T_GEN_CAM_MAX_MS, Ordering::SeqCst);
1088                self.n_gen_cam_counter.store(0, Ordering::SeqCst);
1089            }
1090        }
1091
1092        if let Ok(mut st) = self.state.lock() {
1093            st.last_cam_time_ms = Some(now_ms);
1094            st.last_cam_heading = Some(fix.heading_deg);
1095            st.last_cam_lat = Some(fix.latitude);
1096            st.last_cam_lon = Some(fix.longitude);
1097            st.last_cam_speed = Some(fix.speed_mps);
1098
1099            st.path_history.push(PathEntry {
1100                lat: fix.latitude,
1101                lon: fix.longitude,
1102                time_ms: now_ms,
1103            });
1104            if st.path_history.len() > 40 {
1105                st.path_history.remove(0);
1106            }
1107
1108            if include_lf {
1109                st.last_lf_time_ms = Some(now_ms);
1110            }
1111            if include_special {
1112                st.last_special_time_ms = Some(now_ms);
1113            }
1114            if include_vlf {
1115                st.last_vlf_time_ms = Some(now_ms);
1116            }
1117
1118            st.cam_count += 1;
1119            st.last_cam_generation_delta_time = Some(GenerationDeltaTime::from_unix_ms(now_ms));
1120        }
1121    }
1122
1123    /// Spawn the transmission management thread.
1124    pub fn spawn(
1125        btp_handle: BTPRouterHandle,
1126        coder: CamCoder,
1127        vehicle_data: VehicleData,
1128        gps_rx: Receiver<GpsFix>,
1129    ) {
1130        let ctm = CAMTransmissionManagement::new(btp_handle, coder, vehicle_data, None);
1131        ctm.start();
1132
1133        thread::spawn(move || {
1134            // Annex B.2.4 step 1 — non-clock-synchronised start (random initial delay)
1135            let initial_delay =
1136                Duration::from_millis(rand::thread_rng().gen_range(0..T_CHECK_CAM_GEN_MS));
1137            thread::sleep(initial_delay);
1138
1139            loop {
1140                if !ctm.is_active() {
1141                    break;
1142                }
1143                let deadline = Instant::now() + Duration::from_millis(T_CHECK_CAM_GEN_MS);
1144                loop {
1145                    let remaining = deadline.saturating_duration_since(Instant::now());
1146                    if remaining.is_zero() {
1147                        break;
1148                    }
1149                    match gps_rx.recv_timeout(remaining) {
1150                        Ok(fix) => ctm.location_service_callback(fix),
1151                        Err(RecvTimeoutError::Timeout) => break,
1152                        Err(RecvTimeoutError::Disconnected) => {
1153                            return;
1154                        }
1155                    }
1156                }
1157
1158                let now_ms = SystemTime::now()
1159                    .duration_since(UNIX_EPOCH)
1160                    .unwrap_or_default()
1161                    .as_millis() as u64;
1162
1163                let _ = ctm.evaluate_and_maybe_send(now_ms);
1164            }
1165        });
1166    }
1167}
1168
1169#[cfg(test)]
1170mod tests {
1171    use super::*;
1172    use crate::facilities::local_dynamic_map::LdmFacility;
1173    use crate::geonet::mib::Mib;
1174
1175    fn make_test_fix(lat: f64, lon: f64, heading: f64, speed: f64) -> GpsFix {
1176        GpsFix {
1177            latitude: lat,
1178            longitude: lon,
1179            altitude_m: 100.0,
1180            speed_mps: speed,
1181            heading_deg: heading,
1182            pai: true,
1183            fix_time_ms: None,
1184        }
1185    }
1186
1187    fn make_test_ctm(
1188        vd: Option<VehicleData>,
1189        ldm: Option<CABasicServiceLDM>,
1190    ) -> CAMTransmissionManagement {
1191        let (btp_handle, _) = crate::btp::router::Router::spawn(Mib::new());
1192        let coder = CamCoder::new();
1193        let vehicle_data = vd.unwrap_or_else(|| VehicleData {
1194            station_id: 1,
1195            station_type: 5,
1196            drive_direction: DriveDirection::forward,
1197            vehicle_length_value: 50,
1198            vehicle_width: 30,
1199            ..VehicleData::default()
1200        });
1201        CAMTransmissionManagement::new(btp_handle, coder, vehicle_data, ldm)
1202    }
1203
1204    // ─── VehicleData tests ───────────────────────────────────────────────────
1205
1206    #[test]
1207    fn test_vehicle_data_defaults_and_validation() {
1208        let vd = VehicleData::default();
1209        assert_eq!(vd.vehicle_role, 0);
1210        assert_eq!(vd.exterior_lights, vec![0x00]);
1211        assert!(vd.special_vehicle_data.is_none());
1212        assert!(vd.validate().is_ok());
1213
1214        let mut invalid_role = vd.clone();
1215        invalid_role.vehicle_role = 16;
1216        assert!(invalid_role.validate().is_err());
1217
1218        let mut invalid_lights = vd;
1219        invalid_lights.exterior_lights = vec![];
1220        assert!(invalid_lights.validate().is_err());
1221    }
1222
1223    // ─── Haversine tests ─────────────────────────────────────────────────────
1224
1225    #[test]
1226    fn test_haversine_properties() {
1227        assert!(haversine_m(41.0, 2.0, 41.0, 2.0).abs() < 1e-4);
1228        let d = haversine_m(41.0, 2.0, 41.000045, 2.0);
1229        assert!(d > 4.5 && d < 5.5);
1230        let d1 = haversine_m(41.0, 2.0, 41.001, 2.001);
1231        let d2 = haversine_m(41.001, 2.001, 41.0, 2.0);
1232        assert!((d1 - d2).abs() < 1e-5);
1233    }
1234
1235    // ─── Confidence Helpers tests ────────────────────────────────────────────
1236
1237    #[test]
1238    fn test_confidence_helpers() {
1239        let pos_conf = create_position_confidence(8.75, 10.59);
1240        assert_eq!(pos_conf.semi_major_axis_length.0, 1059);
1241        assert_eq!(pos_conf.semi_minor_axis_length.0, 875);
1242
1243        assert_eq!(
1244            create_altitude_confidence(0.005),
1245            AltitudeConfidence::alt_000_01
1246        );
1247        assert_eq!(
1248            create_altitude_confidence(0.15),
1249            AltitudeConfidence::alt_000_20
1250        );
1251        assert_eq!(
1252            create_altitude_confidence(250.0),
1253            AltitudeConfidence::outOfRange
1254        );
1255
1256        assert_eq!(create_heading_confidence(5.0).0, 50);
1257        assert_eq!(create_heading_confidence(20.0).0, 126);
1258    }
1259
1260    // ─── Lifecycle tests ─────────────────────────────────────────────────────
1261
1262    #[test]
1263    fn test_ctm_init_and_start_stop() {
1264        let ctm = make_test_ctm(None, None);
1265        assert_eq!(ctm.t_gen_cam(), T_GEN_CAM_MAX_MS);
1266        assert!(!ctm.is_active());
1267        assert_eq!(ctm.cam_count(), 0);
1268        assert!(ctm.last_cam_time_ms().is_none());
1269
1270        ctm.start();
1271        assert!(ctm.is_active());
1272        // Idempotent double start
1273        ctm.start();
1274        assert!(ctm.is_active());
1275
1276        ctm.stop();
1277        assert!(!ctm.is_active());
1278    }
1279
1280    #[test]
1281    fn test_location_service_callback_caches_fix() {
1282        let ctm = make_test_ctm(None, None);
1283        let fix = make_test_fix(41.0, 2.0, 90.0, 5.0);
1284        ctm.location_service_callback(fix);
1285        let cached = ctm.state.lock().unwrap().current_fix;
1286        assert!(cached.is_some());
1287        assert_eq!(cached.unwrap().latitude, 41.0);
1288    }
1289
1290    // ─── Dynamics check tests ────────────────────────────────────────────────
1291
1292    #[test]
1293    fn test_dynamics_check() {
1294        let ctm = make_test_ctm(None, None);
1295        let fix = make_test_fix(41.0, 2.0, 90.0, 5.0);
1296        // No reference -> returns true
1297        assert!(ctm.check_dynamics(&fix));
1298
1299        ctm.generate_and_send_cam(&fix, 1_000_000, 1).unwrap();
1300
1301        // Under 4 deg heading -> false
1302        assert!(!ctm.check_dynamics(&make_test_fix(41.0, 2.0, 93.0, 5.0)));
1303        // Over 4 deg heading -> true
1304        assert!(ctm.check_dynamics(&make_test_fix(41.0, 2.0, 95.0, 5.0)));
1305
1306        // Heading 360 wrap-around: from 358 to 3 is 5 deg -> true
1307        {
1308            let mut st = ctm.state.lock().unwrap();
1309            st.last_cam_heading = Some(358.0);
1310        }
1311        assert!(ctm.check_dynamics(&make_test_fix(41.0, 2.0, 3.0, 5.0)));
1312
1313        // Position over 4 m -> true
1314        {
1315            let mut st = ctm.state.lock().unwrap();
1316            st.last_cam_heading = Some(90.0);
1317        }
1318        assert!(ctm.check_dynamics(&make_test_fix(41.000045, 2.0, 90.0, 5.0)));
1319
1320        // Speed diff over 0.5 m/s -> true
1321        assert!(ctm.check_dynamics(&make_test_fix(41.0, 2.0, 90.0, 5.6)));
1322        // Speed diff under 0.5 m/s -> false
1323        assert!(!ctm.check_dynamics(&make_test_fix(41.0, 2.0, 90.0, 5.4)));
1324    }
1325
1326    // ─── Container inclusion tests ───────────────────────────────────────────
1327
1328    /// §6.1.2: LF and special-vehicle containers are repeated when ≥ 500 ms
1329    /// have elapsed since they were last included, not before
1330    /// (TS 103 900 clause 6.1.2).
1331    #[test]
1332    fn test_lf_and_special_container_500ms_timing() {
1333        let ctm = make_test_ctm(
1334            Some(VehicleData {
1335                vehicle_role: 6,
1336                ..VehicleData::default()
1337            }),
1338            None,
1339        );
1340        {
1341            let mut st = ctm.state.lock().unwrap();
1342            st.cam_count = 3;
1343            st.last_lf_time_ms = Some(1_000);
1344            st.last_special_time_ms = Some(1_000);
1345        }
1346        assert!(!ctm.should_include_lf(1_499));
1347        assert!(ctm.should_include_lf(1_500));
1348        assert!(!ctm.should_include_special_vehicle(1_499));
1349        assert!(ctm.should_include_special_vehicle(1_500));
1350    }
1351
1352    /// §6.1.2: after the second CAM, the VLF extension container is included
1353    /// when ≥ 10 s have elapsed and neither LF nor special-vehicle container is
1354    /// included in the same CAM (TS 103 900 clause 6.1.2).
1355    #[test]
1356    fn test_vlf_container_10s_timing() {
1357        let ctm = make_test_ctm(None, None);
1358        {
1359            let mut st = ctm.state.lock().unwrap();
1360            st.cam_count = 5;
1361            st.last_vlf_time_ms = Some(1_000);
1362        }
1363        assert!(!ctm.should_include_vlf(10_999, false, false));
1364        assert!(ctm.should_include_vlf(11_000, false, false));
1365        assert!(!ctm.should_include_vlf(11_000, true, false));
1366        assert!(!ctm.should_include_vlf(11_000, false, true));
1367    }
1368
1369    /// V2.2.1 §5.3.4.1 / V2.3.1 §6.1.1: a CAM leaves the CA service as BTP-B to port 2001 in a GN
1370    /// single-hop broadcast with packet lifetime ≤ 1 s
1371    /// (TS 103 900 V2.2.1 clause 5.3.4.1).
1372    #[test]
1373    fn test_send_cam_btp_b_shb_port_2001_lifetime() {
1374        let (btp_handle, gn_rx) = crate::btp::router::Router::spawn(Mib::new());
1375        let vehicle_data = VehicleData {
1376            station_id: 1,
1377            station_type: 5,
1378            drive_direction: DriveDirection::forward,
1379            vehicle_length_value: 50,
1380            vehicle_width: 30,
1381            ..VehicleData::default()
1382        };
1383        let ctm = CAMTransmissionManagement::new(btp_handle, CamCoder::new(), vehicle_data, None);
1384        let fix = make_test_fix(41.552, 2.134, 90.0, 5.0);
1385        assert!(ctm.generate_and_send_cam(&fix, 1_000, 1).is_ok());
1386
1387        let gn_req = gn_rx
1388            .recv_timeout(std::time::Duration::from_secs(1))
1389            .expect("CAM did not reach GeoNetworking");
1390        assert_eq!(gn_req.upper_protocol_entity, CommonNH::BtpB);
1391        assert_eq!(gn_req.packet_transport_type.header_type, HeaderType::Tsb);
1392        assert_eq!(
1393            gn_req.packet_transport_type.header_sub_type,
1394            HeaderSubType::TopoBroadcast(TopoBroadcastHST::SingleHop)
1395        );
1396        let lifetime = gn_req.max_packet_lifetime.expect("lifetime must be set");
1397        assert!(lifetime > 0.0 && lifetime <= 1.0);
1398        // BTP-B header: destination port 2001 (0x07D1).
1399        assert_eq!(&gn_req.data[0..2], &[0x07, 0xD1]);
1400    }
1401
1402    /// §6.1.2: the two-wheeler container is included in all CAMs of cyclists,
1403    /// mopeds and motorcycles, and not for other station types
1404    /// (TS 103 900 clause 6.1.2).
1405    #[test]
1406    fn test_two_wheeler_container_station_types() {
1407        for (station_type, expected) in [(2u8, true), (3, true), (4, true), (5, false)] {
1408            let ctm = make_test_ctm(
1409                Some(VehicleData {
1410                    station_type,
1411                    ..VehicleData::default()
1412                }),
1413                None,
1414            );
1415            assert_eq!(
1416                ctm.should_include_two_wheeler(),
1417                expected,
1418                "station type {station_type}"
1419            );
1420        }
1421    }
1422
1423    /// §5.3.1 / Annex B.2.4: the CAM carries the latest in-vehicle data
1424    /// (position, speed, heading of the latest fix) (TS 103 900 clause 7.1).
1425    #[test]
1426    fn test_cam_carries_latest_vehicle_data() {
1427        let ctm = make_test_ctm(None, None);
1428        let first = make_test_fix(41.552, 2.134, 90.0, 5.0);
1429        ctm.generate_and_send_cam(&first, 1_000, 1).unwrap();
1430        let latest = make_test_fix(41.553, 2.135, 180.0, 12.5);
1431        let cam = ctm.generate_and_send_cam(&latest, 2_000, 1).unwrap();
1432        let params = &cam.cam.cam_parameters;
1433        let pos = &params.basic_container.reference_position;
1434        assert_eq!(pos.latitude.0, 415_530_000);
1435        assert_eq!(pos.longitude.0, 21_350_000);
1436        let HighFrequencyContainer::basicVehicleContainerHighFrequency(hf) =
1437            &params.high_frequency_container
1438        else {
1439            panic!("vehicle CAM carries the basic vehicle HF container");
1440        };
1441        assert_eq!(hf.speed.speed_value.0, 1250);
1442        assert_eq!(hf.heading.heading_value.0, 1800);
1443    }
1444
1445    #[test]
1446    fn test_container_inclusions() {
1447        let ctm = make_test_ctm(None, None);
1448        // LF on first CAM
1449        assert!(ctm.should_include_lf(1000));
1450        // Special not on default role
1451        assert!(!ctm.should_include_special_vehicle(1000));
1452
1453        let ctm_spec = make_test_ctm(
1454            Some(VehicleData {
1455                vehicle_role: 6,
1456                ..VehicleData::default()
1457            }),
1458            None,
1459        );
1460        // Special on first CAM when role != default
1461        assert!(ctm_spec.should_include_special_vehicle(1000));
1462
1463        // VLF: not on first CAM, but on second CAM (cam_count == 1)
1464        assert!(!ctm.should_include_vlf(1000, false, false));
1465        {
1466            let mut st = ctm.state.lock().unwrap();
1467            st.cam_count = 1;
1468        }
1469        assert!(ctm.should_include_vlf(1000, false, false));
1470
1471        // Two-Wheeler
1472        let ctm_cyclist = make_test_ctm(
1473            Some(VehicleData {
1474                station_type: 2,
1475                ..VehicleData::default()
1476            }),
1477            None,
1478        );
1479        assert!(ctm_cyclist.should_include_two_wheeler());
1480        assert!(!ctm.should_include_two_wheeler());
1481    }
1482
1483    // ─── T_GenCam State Machine tests ────────────────────────────────────────
1484
1485    #[test]
1486    fn test_condition1_sets_t_gen_cam_to_elapsed() {
1487        let ctm = make_test_ctm(None, None);
1488        let fix = make_test_fix(41.0, 2.0, 90.0, 5.0);
1489
1490        // Prior CAM at 1000 ms
1491        ctm.generate_and_send_cam(&fix, 1_000, 1).unwrap();
1492
1493        // Elapsed = 1500 - 1000 = 500 ms
1494        ctm.generate_and_send_cam(&fix, 1_500, 1).unwrap();
1495        assert_eq!(ctm.t_gen_cam(), 500);
1496    }
1497
1498    #[test]
1499    fn test_condition2_resets_t_gen_cam_to_max() {
1500        // §6.1.2: T_GenCam returns to T_GenCamMax after N_GenCam consecutive
1501        // condition-2 CAMs, not before.
1502        let ctm = make_test_ctm(None, None);
1503        let fix = make_test_fix(41.0, 2.0, 90.0, 5.0);
1504
1505        ctm.generate_and_send_cam(&fix, 1_000, 0).unwrap();
1506        ctm.t_gen_cam_ms.store(400, Ordering::SeqCst); // set by a condition-1 CAM
1507        for count in 1..N_GEN_CAM_DEFAULT as u64 {
1508            ctm.generate_and_send_cam(&fix, 1_000 + 2_000 * count, 2)
1509                .unwrap();
1510            assert_eq!(ctm.t_gen_cam(), 400);
1511        }
1512        ctm.generate_and_send_cam(&fix, 1_000 + 2_000 * N_GEN_CAM_DEFAULT as u64, 2)
1513            .unwrap();
1514        assert_eq!(ctm.t_gen_cam(), T_GEN_CAM_MAX_MS);
1515    }
1516
1517    #[test]
1518    fn test_n_gen_cam_resets_after_default_consecutive() {
1519        // §6.1.2: a condition-1 CAM sets T_GenCam to the elapsed time and
1520        // restarts the count of consecutive condition-2 CAMs; the first CAM
1521        // after activation (condition 0) keeps T_GenCamMax.
1522        let ctm = make_test_ctm(None, None);
1523        let fix = make_test_fix(41.0, 2.0, 90.0, 5.0);
1524
1525        ctm.generate_and_send_cam(&fix, 1_000, 0).unwrap();
1526        assert_eq!(ctm.t_gen_cam(), T_GEN_CAM_MAX_MS);
1527        ctm.n_gen_cam_counter
1528            .store(N_GEN_CAM_DEFAULT - 1, Ordering::SeqCst);
1529        ctm.generate_and_send_cam(&fix, 1_300, 1).unwrap();
1530        assert_eq!(ctm.t_gen_cam(), 300);
1531        assert_eq!(ctm.n_gen_cam_counter.load(Ordering::SeqCst), 0);
1532    }
1533
1534    #[test]
1535    fn test_t_gen_cam_clamped_to_min() {
1536        let ctm = make_test_ctm(None, None);
1537        let fix = make_test_fix(41.0, 2.0, 90.0, 5.0);
1538
1539        ctm.generate_and_send_cam(&fix, 1_950, 1).unwrap();
1540        // Elapsed = 2000 - 1950 = 50 ms < 100 ms -> clamped to T_GEN_CAM_MIN_MS
1541        ctm.generate_and_send_cam(&fix, 2_000, 1).unwrap();
1542        assert_eq!(ctm.t_gen_cam(), T_GEN_CAM_MIN_MS);
1543    }
1544
1545    // ─── Conditions Evaluation integration tests ─────────────────────────────
1546
1547    #[test]
1548    fn test_evaluate_and_maybe_send() {
1549        let ctm = make_test_ctm(None, None);
1550        // No fix -> None
1551        assert!(ctm.evaluate_and_maybe_send(1000).is_none());
1552
1553        let fix = make_test_fix(41.0, 2.0, 90.0, 5.0);
1554        ctm.location_service_callback(fix);
1555
1556        // First CAM sends immediately
1557        let first = ctm.evaluate_and_maybe_send(1000);
1558        assert!(first.is_some());
1559
1560        // Condition 2 triggers after t_gen_cam
1561        assert!(ctm.evaluate_and_maybe_send(1050).is_none());
1562        assert!(ctm.evaluate_and_maybe_send(2001).is_some());
1563    }
1564
1565    // ─── T_GenCam_DCC (management-layer coupling) tests ─────────────────────
1566
1567    #[test]
1568    fn test_t_gen_cam_dcc_default_and_clamping() {
1569        let ctm = make_test_ctm(None, None);
1570        assert_eq!(ctm.t_gen_cam_dcc(), T_GEN_CAM_DCC_MS);
1571        ctm.set_t_gen_cam_dcc(400);
1572        assert_eq!(ctm.t_gen_cam_dcc(), 400);
1573        ctm.set_t_gen_cam_dcc(10);
1574        assert_eq!(ctm.t_gen_cam_dcc(), T_GEN_CAM_MIN_MS);
1575        ctm.set_t_gen_cam_dcc(5_000);
1576        assert_eq!(ctm.t_gen_cam_dcc(), T_GEN_CAM_MAX_MS);
1577    }
1578
1579    #[test]
1580    fn test_t_gen_cam_dcc_gates_condition1() {
1581        let ctm = make_test_ctm(None, None);
1582        ctm.set_t_gen_cam_dcc(500);
1583        ctm.location_service_callback(make_test_fix(41.0, 2.0, 90.0, 5.0));
1584        assert!(ctm.evaluate_and_maybe_send(1_000).is_some());
1585
1586        // Heading change of 45° satisfies the dynamics check ...
1587        ctm.location_service_callback(make_test_fix(41.0, 2.0, 135.0, 5.0));
1588        // ... but elapsed (200 ms) < T_GenCam_DCC (500 ms): no CAM.
1589        assert!(ctm.evaluate_and_maybe_send(1_200).is_none());
1590        // Once elapsed ≥ T_GenCam_DCC the condition-1 CAM is sent.
1591        assert!(ctm.evaluate_and_maybe_send(1_500).is_some());
1592    }
1593
1594    #[test]
1595    fn test_t_gen_cam_dcc_gates_condition2() {
1596        let ctm = make_test_ctm(None, None);
1597        ctm.location_service_callback(make_test_fix(41.0, 2.0, 90.0, 5.0));
1598        assert!(ctm.evaluate_and_maybe_send(1_000).is_some());
1599        ctm.t_gen_cam_ms.store(400, Ordering::SeqCst);
1600        ctm.set_t_gen_cam_dcc(800);
1601        // elapsed ≥ T_GenCam but < T_GenCam_DCC: no CAM.
1602        assert!(ctm.evaluate_and_maybe_send(1_500).is_none());
1603        assert!(ctm.evaluate_and_maybe_send(1_800).is_some());
1604    }
1605
1606    /// Millisecond truncation: 999 ms after the last CAM counts as T_GenCam
1607    /// (1000 ms); 998 ms does not. Mirrors the Python test of the same name.
1608    #[test]
1609    fn test_elapsed_time_tolerance_is_one_millisecond() {
1610        for (elapsed, sent) in [(998, false), (999, true)] {
1611            let ctm = make_test_ctm(None, None);
1612            ctm.location_service_callback(make_test_fix(41.0, 2.0, 90.0, 5.0));
1613            assert!(ctm.evaluate_and_maybe_send(1_000).is_some());
1614            assert_eq!(
1615                ctm.evaluate_and_maybe_send(1_000 + elapsed).is_some(),
1616                sent,
1617                "elapsed {elapsed} ms"
1618            );
1619        }
1620    }
1621
1622    #[test]
1623    fn test_t_gen_cam_dcc_shared_between_clones() {
1624        let ctm = make_test_ctm(None, None);
1625        let worker = ctm.clone();
1626        ctm.set_t_gen_cam_dcc(700);
1627        assert_eq!(worker.t_gen_cam_dcc(), 700);
1628    }
1629
1630    #[test]
1631    fn test_dcc_entity_drives_t_gen_cam_dcc() {
1632        use crate::management::{DccEntity, DccMode, SharedCbr};
1633        let ctm = make_test_ctm(None, None);
1634        let cbr = SharedCbr::new();
1635        let mut dcc = DccEntity::new(DccMode::reactive(), Box::new(cbr.clone()));
1636        let target = ctm.clone();
1637        dcc.add_t_gen_cam_dcc_listener(move |ms| target.set_t_gen_cam_dcc(ms));
1638
1639        cbr.report(0.9); // Restrictive band; reactive DCC steps up one state per evaluation
1640        dcc.evaluate();
1641        assert_eq!(ctm.t_gen_cam_dcc(), 200); // Active1 T_off
1642        dcc.evaluate();
1643        assert_eq!(ctm.t_gen_cam_dcc(), 400); // Active2 T_off
1644    }
1645
1646    // ─── Path History tests ──────────────────────────────────────────────────
1647
1648    #[test]
1649    fn test_path_history() {
1650        let ctm = make_test_ctm(None, None);
1651        let fix1 = make_test_fix(41.0001, 2.0, 90.0, 5.0);
1652        ctm.generate_and_send_cam(&fix1, 1_000_000, 1).unwrap();
1653
1654        let fix2 = make_test_fix(41.0, 2.0, 90.0, 5.0);
1655        let pts = ctm.get_path_history(&fix2, 1_001_000);
1656        assert_eq!(pts.len(), 1);
1657        assert_eq!(pts[0].path_position.delta_latitude.0, 1000);
1658    }
1659
1660    // ─── LDM integration test ────────────────────────────────────────────────
1661
1662    #[test]
1663    fn test_send_cam_updates_ldm_when_present() {
1664        let ldm = LdmFacility::new(415_520_000, 21_340_000, 50_000.0);
1665        let ldm_adapter = CABasicServiceLDM::new(ldm, 5);
1666        let ctm = make_test_ctm(None, Some(ldm_adapter));
1667        let fix = make_test_fix(41.552, 2.134, 90.0, 5.0);
1668        let res = ctm.generate_and_send_cam(&fix, 1_000, 1);
1669        assert!(res.is_ok());
1670    }
1671}