rustflexstack/facilities/vru_awareness_service/
vam_transmission.rs1use 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
39pub const T_GEN_VAM_MIN_MS: u64 = 100;
43pub const T_GEN_VAM_MAX_MS: u64 = 5_000;
45pub const T_CHECK_VAM_GEN_MS: u64 = T_GEN_VAM_MIN_MS;
47pub const T_GEN_VAM_DCC_MS: u64 = T_GEN_VAM_MIN_MS;
49pub const T_GEN_VAM_LF_MIN_MS: u64 = 2_000;
51
52const MIN_POSITION_CHANGE_M: f64 = 4.0;
56const MIN_SPEED_CHANGE_MPS: f64 = 0.5;
58const MIN_HEADING_CHANGE_DEG: f64 = 4.0;
60
61fn 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#[derive(Debug, Clone)]
79pub struct DeviceData {
80 pub station_id: u32,
82 pub station_type: u8,
91}
92
93impl Default for DeviceData {
94 fn default() -> Self {
96 DeviceData {
97 station_id: 0,
98 station_type: 2, }
100 }
101}
102
103fn build_vam(fix: &GpsFix, dd: &DeviceData, lf: Option<VruLowFrequencyContainer>) -> Vam {
107 let gen_dt = generation_delta_time_now();
108
109 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 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 let vam_params = VamParameters::new(
159 basic_container,
160 hf,
161 lf,
162 None, None, None, );
166
167 Vam::new(
168 vam_header(dd.station_id),
169 VruAwareness::new(gen_dt, vam_params),
170 )
171}
172
173fn 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 if last_lat.is_none() {
185 return true;
186 }
187
188 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 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 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
216fn build_lf_container() -> VruLowFrequencyContainer {
219 VruLowFrequencyContainer::new(
220 VruProfileAndSubprofile::pedestrian(VruSubProfilePedestrian::unavailable),
221 None, None, )
224}
225
226pub struct VAMTransmissionManagement;
233
234impl VAMTransmissionManagement {
235 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; 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 let mut last_lf_time: Option<Instant> = None;
259 let mut is_first_vam = true;
260
261 let mut current_fix: Option<GpsFix> = None;
263
264 loop {
265 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 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 should_send = true;
309 }
310
311 if !should_send {
312 continue;
313 }
314
315 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 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}