1use super::den_protocol::{DenActionId, DenProtocol, DenResult, DenmRequest, OutgoingDenm};
22use super::denm_coder::{
23 denm_header, timestamp_its_now, ActionId, Altitude, AltitudeConfidence, AltitudeValue,
24 CauseCodeChoice, CauseCodeV2, DeltaAltitude, DeltaLatitude, DeltaLongitude,
25 DeltaReferencePosition, DeltaTimeMilliSecondPositive, DeltaTimeSecond, Denm, DenmCoder,
26 DenmPayload, HeadingValue, InformationQuality, Latitude, LocationContainer, Longitude,
27 ManagementContainer, Path, PathPoint, PosConfidenceEllipse, ReferencePosition, SemiAxisLength,
28 SequenceNumber, SituationContainer, Speed, SpeedConfidence, SpeedValue, StationId, StationType,
29 Traces, TrafficParticipantType, Wgs84Angle, Wgs84AngleConfidence, Wgs84AngleValue,
30};
31use crate::btp::router::BTPRouterHandle;
32use crate::btp::service_access_point::BTPDataRequest;
33use crate::geonet::gn_address::{GNAddress, M, MID, ST};
34use crate::geonet::service_access_point::{
35 Area, CommonNH, CommunicationProfile, HeaderSubType, HeaderType, PacketTransportType,
36};
37use crate::security::sn_sap::SecurityProfile;
38use std::sync::{Arc, Condvar, Mutex};
39
40pub const DENM_BTP_PORT: u16 = 2002;
42pub const DENM_ITS_AID: u64 = 37;
44
45pub type DenClock = Arc<dyn Fn() -> u64 + Send + Sync>;
47
48pub struct DenShared {
50 pub protocol: Mutex<DenProtocol>,
51 pub wakeup: Condvar,
53 clock: Option<DenClock>,
54}
55
56impl DenShared {
57 pub fn new(protocol: DenProtocol) -> Arc<Self> {
58 Self::with_clock(protocol, None)
59 }
60
61 pub fn with_clock(protocol: DenProtocol, clock: Option<DenClock>) -> Arc<Self> {
63 Arc::new(DenShared {
64 protocol: Mutex::new(protocol),
65 wakeup: Condvar::new(),
66 clock,
67 })
68 }
69
70 pub fn now(&self) -> u64 {
72 self.clock
73 .as_ref()
74 .map_or_else(|| timestamp_its_now().0, |clock| clock())
75 }
76}
77
78#[derive(Debug, Clone)]
85pub struct VehicleData {
86 pub station_id: u32,
88 pub station_type: u8,
91}
92
93impl Default for VehicleData {
94 fn default() -> Self {
95 VehicleData {
96 station_id: 0,
97 station_type: 5, }
99 }
100}
101
102#[derive(Debug, Clone)]
109pub struct DENRequest {
110 pub event_latitude: f64,
113 pub event_longitude: f64,
115 pub event_altitude_m: f64,
117
118 pub cause_code: CauseCodeChoice,
121
122 pub information_quality: u8,
125 pub event_speed_raw: u16,
127 pub event_heading_raw: u16,
129
130 pub denm_interval_ms: u64,
133 pub time_period_ms: u64,
135
136 pub relevance_radius_m: u32,
139}
140
141impl Default for DENRequest {
142 fn default() -> Self {
143 DENRequest {
144 event_latitude: 0.0,
145 event_longitude: 0.0,
146 event_altitude_m: 0.0,
147 cause_code: CauseCodeChoice::accident2(super::denm_coder::AccidentSubCauseCode(0)),
148 information_quality: 0,
149 event_speed_raw: 16383, event_heading_raw: 3601, denm_interval_ms: 1000,
152 time_period_ms: 5000,
153 relevance_radius_m: 1000,
154 }
155 }
156}
157
158pub fn build_denm(request: &DENRequest, vd: &VehicleData, seq_nr: u16) -> Denm {
162 let now = timestamp_its_now();
163
164 let event_pos = ReferencePosition::new(
166 Latitude(((request.event_latitude * 1e7).round() as i32).clamp(-900_000_000, 900_000_000)),
167 Longitude(
168 ((request.event_longitude * 1e7).round() as i32).clamp(-1_800_000_000, 1_800_000_000),
169 ),
170 PosConfidenceEllipse::new(
171 SemiAxisLength(4095), SemiAxisLength(4095), HeadingValue(3601), ),
175 Altitude::new(
176 AltitudeValue(
177 ((request.event_altitude_m * 100.0).round() as i32).clamp(-100_000, 800_000),
178 ),
179 AltitudeConfidence::unavailable,
180 ),
181 );
182
183 let action_id = ActionId::new(StationId(vd.station_id), SequenceNumber(seq_nr));
184
185 let management = ManagementContainer::new(
186 action_id,
187 now.clone(), now.clone(), None, event_pos,
191 None, None, DeltaTimeSecond(600), Some(DeltaTimeMilliSecondPositive(
195 request.denm_interval_ms.min(10_000) as u16,
196 )),
197 StationType(TrafficParticipantType(vd.station_type)),
198 );
199
200 let situation = SituationContainer::new(
202 InformationQuality(request.information_quality.min(7)),
203 CauseCodeV2::new(request.cause_code.clone()),
204 None, None, None, None, );
209
210 let path_point = PathPoint::new(
214 DeltaReferencePosition::new(
215 DeltaLatitude(131072), DeltaLongitude(131072), DeltaAltitude(12800), ),
219 None, );
221 let path = Path(rasn::types::SequenceOf::from(vec![path_point]));
222 let traces = Traces(rasn::types::SequenceOf::from(vec![path]));
223
224 let event_speed = Speed::new(
225 SpeedValue(request.event_speed_raw.min(16_383)),
226 SpeedConfidence(127), );
228 let event_heading = Wgs84Angle::new(
229 Wgs84AngleValue(request.event_heading_raw.min(3601)),
230 Wgs84AngleConfidence(127), );
232
233 let location = LocationContainer::new(
234 Some(event_speed),
235 Some(event_heading),
236 traces,
237 None, None, );
240
241 Denm::new(
243 denm_header(vd.station_id),
244 DenmPayload::new(
245 management,
246 Some(situation),
247 Some(location),
248 None, ),
250 )
251}
252
253pub struct DENMTransmissionManagement {
259 btp_handle: BTPRouterHandle,
260 coder: DenmCoder,
261 vehicle_data: VehicleData,
262 shared: Arc<DenShared>,
263}
264
265pub fn new_protocol(
267 vehicle_data: &VehicleData,
268 kaf_enabled: bool,
269 coder: &DenmCoder,
270) -> DenProtocol {
271 let coder = coder.clone();
272 DenProtocol::new(
273 vehicle_data.station_id,
274 vehicle_data.station_type,
275 kaf_enabled,
276 Some(Box::new(move |denm: &Denm| coder.encode(denm).map(|_| ()))),
277 )
278}
279
280impl DENMTransmissionManagement {
281 pub fn new(btp_handle: BTPRouterHandle, coder: DenmCoder, vehicle_data: VehicleData) -> Self {
284 let shared = DenShared::new(new_protocol(&vehicle_data, false, &coder));
285 Self::with_shared(btp_handle, coder, vehicle_data, shared)
286 }
287
288 pub fn with_shared(
290 btp_handle: BTPRouterHandle,
291 coder: DenmCoder,
292 vehicle_data: VehicleData,
293 shared: Arc<DenShared>,
294 ) -> Self {
295 DENMTransmissionManagement {
296 btp_handle,
297 coder,
298 vehicle_data,
299 shared,
300 }
301 }
302
303 pub fn trigger(&self, request: &DenmRequest) -> DenResult {
307 let now = self.shared.now();
308 let (result, outgoing) = self.shared.protocol.lock().unwrap().trigger(request, now);
309 self.dispatch(result, outgoing)
310 }
311
312 pub fn update(&self, action_id: DenActionId, request: &DenmRequest) -> DenResult {
314 let now = self.shared.now();
315 let (result, outgoing) = self
316 .shared
317 .protocol
318 .lock()
319 .unwrap()
320 .update(action_id, request, now);
321 self.dispatch(result, outgoing)
322 }
323
324 pub fn terminate(&self, action_id: DenActionId, request: &DenmRequest) -> DenResult {
326 let now = self.shared.now();
327 let (result, outgoing) = self
328 .shared
329 .protocol
330 .lock()
331 .unwrap()
332 .terminate(action_id, request, now);
333 self.dispatch(result, outgoing)
334 }
335
336 pub fn trigger_denm_sending(&self, request: DENRequest) {
342 let _ = self.trigger(&self.to_denm_request(&request, true));
343 }
344
345 pub fn send_single_denm(&self, request: &DENRequest) {
347 let _ = self.trigger(&self.to_denm_request(request, false));
348 }
349
350 pub fn to_denm_request(&self, request: &DENRequest, repeat: bool) -> DenmRequest {
352 let denm = build_denm(request, &self.vehicle_data, 0);
353 let mut out = DenmRequest::new(denm.denm.management.event_position.clone());
354 out.situation = denm.denm.situation;
355 out.location = denm.denm.location;
356 out.validity_duration = Some(if request.time_period_ms == 0 {
357 super::den_protocol::DEFAULT_VALIDITY_DURATION_S
358 } else {
359 request.time_period_ms.div_ceil(1000).max(1) as u32
360 });
361 out.transmission_interval = Some(request.denm_interval_ms.clamp(1, 10_000) as u16);
362 out.station_type = Some(self.vehicle_data.station_type);
363 if repeat {
364 out.repetition_interval = Some(request.denm_interval_ms);
365 out.repetition_duration = Some(request.time_period_ms);
366 }
367 out.destination_area = Some(Area {
368 latitude: denm.denm.management.event_position.latitude.0 as u32,
369 longitude: denm.denm.management.event_position.longitude.0 as u32,
370 a: request.relevance_radius_m.min(u32::from(u16::MAX)) as u16,
371 b: 0,
372 angle: 0,
373 });
374 out
375 }
376
377 fn dispatch(&self, result: DenResult, outgoing: Vec<OutgoingDenm>) -> DenResult {
380 for item in &outgoing {
381 transmit(&self.btp_handle, &self.coder, item);
382 }
383 if let Err(failure) = result {
384 eprintln!("[DEN] request failed: {failure:?}");
385 }
386 self.shared.wakeup.notify_all();
387 result
388 }
389
390 pub fn transmit(&self, outgoing: &OutgoingDenm) {
392 transmit(&self.btp_handle, &self.coder, outgoing);
393 }
394}
395
396pub fn transmit(btp_handle: &BTPRouterHandle, coder: &DenmCoder, outgoing: &OutgoingDenm) {
398 let Ok(data) = coder.encode(&outgoing.denm) else {
399 return;
400 };
401 btp_handle.send_btp_data_request(BTPDataRequest {
402 btp_type: CommonNH::BtpB,
403 source_port: 0,
404 destination_port: DENM_BTP_PORT,
405 destination_port_info: 0,
406 gn_packet_transport_type: PacketTransportType {
407 header_type: HeaderType::GeoBroadcast,
408 header_sub_type: HeaderSubType::GeoBroadcast(outgoing.area_type),
409 },
410 gn_destination_address: GNAddress {
411 m: M::GnMulticast,
412 st: ST::Unknown,
413 mid: MID::new([0xFF; 6]),
414 },
415 communication_profile: CommunicationProfile::Unspecified,
416 gn_area: outgoing.area,
417 traffic_class: outgoing.traffic_class,
418 security_profile: SecurityProfile::DecentralizedEnvironmentalNotificationMessage,
419 its_aid: DENM_ITS_AID,
420 security_permissions: super::denm_ssp::permissions_bitmap(&outgoing.denm),
423 gn_max_hop_limit: 10,
424 gn_max_packet_lifetime: None,
425 gn_repetition_interval: None,
426 gn_max_repetition_time: None,
427 destination: None,
428 length: data.len() as u16,
429 data,
430 });
431}
432
433#[cfg(test)]
434mod tests {
435 use super::super::denm_coder::AccidentSubCauseCode;
436 use super::*;
437 use crate::geonet::mib::Mib;
438 use crate::geonet::service_access_point::GeoBroadcastHST;
439 use std::time::Duration;
440
441 fn vehicle(station_id: u32) -> VehicleData {
442 VehicleData {
443 station_id,
444 station_type: 5,
445 }
446 }
447
448 #[test]
451 fn build_denm_action_id_contains_station_id() {
452 let denm = build_denm(&DENRequest::default(), &vehicle(4242), 7);
453 let action_id = &denm.denm.management.action_id;
454 assert_eq!(action_id.originating_station_id.0, 4242);
455 assert_eq!(action_id.sequence_number.0, 7);
456 assert_eq!(denm.header.station_id.0, 4242);
457 }
458
459 #[test]
462 fn build_denm_carries_application_cause_code() {
463 let request = DENRequest {
464 cause_code: CauseCodeChoice::accident2(AccidentSubCauseCode(3)),
465 ..DENRequest::default()
466 };
467 let denm = build_denm(&request, &vehicle(1), 0);
468 let situation = denm.denm.situation.expect("situation container");
469 assert_eq!(situation.event_type.cc_and_scc, request.cause_code);
470 }
471
472 #[test]
474 fn build_denm_reference_time_is_now() {
475 let before = timestamp_its_now().0;
476 let denm = build_denm(&DENRequest::default(), &vehicle(1), 0);
477 let after = timestamp_its_now().0;
478 let reference = denm.denm.management.reference_time.0;
479 assert!(reference >= before && reference <= after);
480 }
481
482 #[test]
485 fn send_single_denm_uses_btp_b_port_2002_over_gbc() {
486 let (btp_handle, gn_rx) = crate::btp::router::Router::spawn(Mib::new());
487 let dtm = DENMTransmissionManagement::new(btp_handle, DenmCoder::new(), vehicle(1));
488 dtm.send_single_denm(&DENRequest::default());
489
490 let gn_req = gn_rx
491 .recv_timeout(Duration::from_secs(1))
492 .expect("DENM did not reach GeoNetworking");
493 assert_eq!(gn_req.upper_protocol_entity, CommonNH::BtpB);
494 assert_eq!(
495 gn_req.packet_transport_type.header_type,
496 HeaderType::GeoBroadcast
497 );
498 assert_eq!(
499 gn_req.packet_transport_type.header_sub_type,
500 HeaderSubType::GeoBroadcast(GeoBroadcastHST::GeoBroadcastCircle)
501 );
502 assert_eq!(&gn_req.data[0..2], &[0x07, 0xD2]);
504 assert_eq!(gn_req.its_aid, 37);
505 }
506}