1pub use super::cam_bindings::cam_pdu_descriptions::{
15 BasicVehicleContainerHighFrequency, BasicVehicleContainerLowFrequency, CamParameters,
16 CamPayload, EHorizonLocationSharingContainer, ExtensionContainerId, HighFrequencyContainer,
17 LowFrequencyContainer, PathPredictionContainer, RoadLanePositionsContainer,
18 SpecialVehicleContainer, TwoWheelerContainer, VehicleMovementControlContainer,
19 VeryLowFrequencyContainer, WrappedExtensionContainer, WrappedExtensionContainers, CAM,
20};
21pub use super::cam_bindings::etsi_its_cdd::{
22 AccelerationComponent, AccelerationConfidence, AccelerationValue, Altitude, AltitudeConfidence,
23 AltitudeValue, BasicContainer, Curvature, CurvatureCalculationMode, CurvatureConfidence,
24 CurvatureValue, DeltaAltitude, DeltaLatitude, DeltaLongitude, DeltaReferencePosition,
25 DriveDirection, ExteriorLights, GenerationDeltaTime, Heading, HeadingConfidence, HeadingValue,
26 ItsPduHeader, Latitude, Longitude, MessageId, OrdinalNumber1B, Path, PathDeltaTime, PathPoint,
27 PositionConfidenceEllipse, ReferencePositionWithConfidence, SemiAxisLength, Speed,
28 SpeedConfidence, SpeedValue, StationId, StationType, TrafficParticipantType, VehicleLength,
29 VehicleLengthConfidenceIndication, VehicleLengthValue, VehicleRole, VehicleWidth,
30 Wgs84AngleValue, YawRate, YawRateConfidence, YawRateValue,
31};
32
33use rasn::prelude::*;
34use std::ops::{Add, Sub};
35
36pub const EXTENSION_CONTAINER_ID_TWO_WHEELER: u8 = 1;
39pub const EXTENSION_CONTAINER_ID_E_HORIZON: u8 = 2;
40pub const EXTENSION_CONTAINER_ID_VLF: u8 = 3;
41pub const EXTENSION_CONTAINER_ID_PATH_PREDICTION: u8 = 4;
42pub const EXTENSION_CONTAINER_ID_ROAD_LANE_POS: u8 = 5;
43#[deprecated(note = "renamed to EXTENSION_CONTAINER_ID_ROAD_LANE_POS in CAM v2.3")]
45pub const EXTENSION_CONTAINER_ID_GEN_LANE_POS: u8 = EXTENSION_CONTAINER_ID_ROAD_LANE_POS;
46#[deprecated(note = "renamed to RoadLanePositionsContainer in CAM v2.3 (TS 103 900 V2.3.1)")]
48pub type GeneralizedLanePositionsContainer = RoadLanePositionsContainer;
49pub const EXTENSION_CONTAINER_ID_VEHICLE_MOVEMENT_CONTROL: u8 = 6;
50
51#[derive(Debug, Clone, PartialEq)]
53pub enum ExtensionContainer {
54 TwoWheeler(TwoWheelerContainer),
55 EHorizonLocationSharing(EHorizonLocationSharingContainer),
56 VeryLowFrequency(VeryLowFrequencyContainer),
57 PathPrediction(PathPredictionContainer),
58 RoadLanePositions(RoadLanePositionsContainer),
59 VehicleMovementControl(VehicleMovementControlContainer),
60}
61
62impl ExtensionContainer {
63 pub fn container_id(&self) -> u8 {
64 match self {
65 Self::TwoWheeler(_) => EXTENSION_CONTAINER_ID_TWO_WHEELER,
66 Self::EHorizonLocationSharing(_) => EXTENSION_CONTAINER_ID_E_HORIZON,
67 Self::VeryLowFrequency(_) => EXTENSION_CONTAINER_ID_VLF,
68 Self::PathPrediction(_) => EXTENSION_CONTAINER_ID_PATH_PREDICTION,
69 Self::RoadLanePositions(_) => EXTENSION_CONTAINER_ID_ROAD_LANE_POS,
70 Self::VehicleMovementControl(_) => EXTENSION_CONTAINER_ID_VEHICLE_MOVEMENT_CONTROL,
71 }
72 }
73}
74
75pub const ITS_EPOCH_MS: u64 = 1_072_915_200_000;
80pub const ELAPSED_MILLISECONDS: u64 = 5_000;
82
83impl GenerationDeltaTime {
84 pub fn new(msec: u16) -> Self {
85 GenerationDeltaTime(msec)
86 }
87
88 pub fn value(&self) -> u16 {
89 self.0
90 }
91
92 pub fn from_timestamp(utc_timestamp_in_seconds: f64) -> Self {
94 let ms = (utc_timestamp_in_seconds * 1000.0).round() as i64;
95 let diff = ms - (ITS_EPOCH_MS as i64) + (ELAPSED_MILLISECONDS as i64);
96 let msec = diff.rem_euclid(65536) as u16;
97 GenerationDeltaTime(msec)
98 }
99
100 pub fn from_unix_ms(unix_ms: u64) -> Self {
102 let diff = (unix_ms as i64) - (ITS_EPOCH_MS as i64) + (ELAPSED_MILLISECONDS as i64);
103 let msec = diff.rem_euclid(65536) as u16;
104 GenerationDeltaTime(msec)
105 }
106
107 pub fn as_timestamp_in_certain_point(&self, utc_timestamp_in_millis: u64) -> u64 {
110 let diff = (utc_timestamp_in_millis as i64) - (ITS_EPOCH_MS as i64)
111 + (ELAPSED_MILLISECONDS as i64);
112 let number_of_cycles = diff / 65536;
113 let transformed_timestamp =
114 (self.0 as i64) + 65536 * number_of_cycles + (ITS_EPOCH_MS as i64)
115 - (ELAPSED_MILLISECONDS as i64);
116
117 if transformed_timestamp <= utc_timestamp_in_millis as i64 {
118 transformed_timestamp as u64
119 } else {
120 ((self.0 as i64) + 65536 * (number_of_cycles - 1) + (ITS_EPOCH_MS as i64)
121 - (ELAPSED_MILLISECONDS as i64)) as u64
122 }
123 }
124}
125
126impl Add for GenerationDeltaTime {
127 type Output = GenerationDeltaTime;
128 fn add(self, rhs: Self) -> Self::Output {
129 GenerationDeltaTime(((self.0 as u32 + rhs.0 as u32) % 65536) as u16)
130 }
131}
132
133impl Sub for GenerationDeltaTime {
134 type Output = GenerationDeltaTime;
135 fn sub(self, rhs: Self) -> Self::Output {
136 let diff = (self.0 as i32) - (rhs.0 as i32);
137 let result = if diff < 0 { diff + 65536 } else { diff };
138 GenerationDeltaTime(result as u16)
139 }
140}
141
142pub fn generation_delta_time_from_unix_ms(unix_ms: u64) -> GenerationDeltaTime {
144 GenerationDeltaTime::from_unix_ms(unix_ms)
145}
146
147pub fn generation_delta_time_now() -> GenerationDeltaTime {
149 use std::time::{SystemTime, UNIX_EPOCH};
150 let ms = SystemTime::now()
151 .duration_since(UNIX_EPOCH)
152 .unwrap_or_default()
153 .as_millis() as u64;
154 generation_delta_time_from_unix_ms(ms)
155}
156
157pub fn cam_header(station_id: u32) -> ItsPduHeader {
161 ItsPduHeader::new(OrdinalNumber1B(2), MessageId(2), StationId(station_id))
162}
163
164pub type Cam = CAM;
168
169pub fn generate_white_cam_static() -> Cam {
171 let header = ItsPduHeader::new(OrdinalNumber1B(2), MessageId(2), StationId(0));
172
173 let ref_pos = ReferencePositionWithConfidence::new(
174 Latitude(900_000_001),
175 Longitude(1_800_000_001),
176 PositionConfidenceEllipse::new(
177 SemiAxisLength(4095),
178 SemiAxisLength(4095),
179 Wgs84AngleValue(3601),
180 ),
181 Altitude::new(AltitudeValue(800_001), AltitudeConfidence::unavailable),
182 );
183 let basic_container = BasicContainer::new(TrafficParticipantType(0), ref_pos);
184
185 let heading = Heading::new(HeadingValue(3601), HeadingConfidence(127));
186 let speed = Speed::new(SpeedValue(16383), SpeedConfidence(127));
187 let vehicle_length = VehicleLength::new(
188 VehicleLengthValue(1023),
189 VehicleLengthConfidenceIndication::unavailable,
190 );
191 let vehicle_width = VehicleWidth(62);
192 let longitudinal_acceleration =
193 AccelerationComponent::new(AccelerationValue(161), AccelerationConfidence(102));
194 let curvature = Curvature::new(CurvatureValue(1023), CurvatureConfidence::unavailable);
195 let yaw_rate = YawRate::new(YawRateValue(32767), YawRateConfidence::unavailable);
196
197 let hf = BasicVehicleContainerHighFrequency::new(
198 heading,
199 speed,
200 DriveDirection::unavailable,
201 vehicle_length,
202 vehicle_width,
203 longitudinal_acceleration,
204 curvature,
205 CurvatureCalculationMode::unavailable,
206 yaw_rate,
207 None,
208 None,
209 None,
210 None,
211 None,
212 None,
213 None,
214 );
215
216 Cam::new(
217 header,
218 CamPayload::new(
219 GenerationDeltaTime(0),
220 CamParameters::new(
221 basic_container,
222 HighFrequencyContainer::basicVehicleContainerHighFrequency(hf),
223 None,
224 None,
225 None,
226 ),
227 ),
228 )
229}
230
231#[derive(Clone, Debug, Default)]
240pub struct CamCoder;
241
242impl CamCoder {
243 pub fn new() -> Self {
244 CamCoder
245 }
246
247 pub fn encode(&self, cam: &Cam) -> Result<Vec<u8>, String> {
249 rasn::uper::encode(cam)
250 .map(|b| b.to_vec())
251 .map_err(|e| format!("CAM UPER encode error: {e}"))
252 }
253
254 pub fn decode(&self, bytes: &[u8]) -> Result<Cam, String> {
256 rasn::uper::decode::<Cam>(bytes).map_err(|e| format!("CAM UPER decode error: {e}"))
257 }
258
259 pub fn encode_extension_container(
261 &self,
262 container_id: u8,
263 container: &ExtensionContainer,
264 ) -> Result<Vec<u8>, String> {
265 if container.container_id() != container_id {
266 return Err(format!(
267 "Container variant id {} does not match requested id {container_id}",
268 container.container_id()
269 ));
270 }
271 match container {
272 ExtensionContainer::TwoWheeler(c) => rasn::uper::encode(c)
273 .map(|b| b.to_vec())
274 .map_err(|e| format!("TwoWheelerContainer encode error: {e}")),
275 ExtensionContainer::EHorizonLocationSharing(c) => rasn::uper::encode(c)
276 .map(|b| b.to_vec())
277 .map_err(|e| format!("EHorizonLocationSharingContainer encode error: {e}")),
278 ExtensionContainer::VeryLowFrequency(c) => rasn::uper::encode(c)
279 .map(|b| b.to_vec())
280 .map_err(|e| format!("VeryLowFrequencyContainer encode error: {e}")),
281 ExtensionContainer::PathPrediction(c) => rasn::uper::encode(c)
282 .map(|b| b.to_vec())
283 .map_err(|e| format!("PathPredictionContainer encode error: {e}")),
284 ExtensionContainer::RoadLanePositions(c) => rasn::uper::encode(c)
285 .map(|b| b.to_vec())
286 .map_err(|e| format!("RoadLanePositionsContainer encode error: {e}")),
287 ExtensionContainer::VehicleMovementControl(c) => rasn::uper::encode(c)
288 .map(|b| b.to_vec())
289 .map_err(|e| format!("VehicleMovementControlContainer encode error: {e}")),
290 }
291 }
292
293 pub fn decode_extension_container(
295 &self,
296 container_id: u8,
297 data: &[u8],
298 ) -> Result<ExtensionContainer, String> {
299 match container_id {
300 EXTENSION_CONTAINER_ID_TWO_WHEELER => rasn::uper::decode::<TwoWheelerContainer>(data)
301 .map(ExtensionContainer::TwoWheeler)
302 .map_err(|e| format!("TwoWheelerContainer decode error: {e}")),
303 EXTENSION_CONTAINER_ID_E_HORIZON => {
304 rasn::uper::decode::<EHorizonLocationSharingContainer>(data)
305 .map(ExtensionContainer::EHorizonLocationSharing)
306 .map_err(|e| format!("EHorizonLocationSharingContainer decode error: {e}"))
307 }
308 EXTENSION_CONTAINER_ID_VLF => rasn::uper::decode::<VeryLowFrequencyContainer>(data)
309 .map(ExtensionContainer::VeryLowFrequency)
310 .map_err(|e| format!("VeryLowFrequencyContainer decode error: {e}")),
311 EXTENSION_CONTAINER_ID_PATH_PREDICTION => {
312 rasn::uper::decode::<PathPredictionContainer>(data)
313 .map(ExtensionContainer::PathPrediction)
314 .map_err(|e| format!("PathPredictionContainer decode error: {e}"))
315 }
316 EXTENSION_CONTAINER_ID_ROAD_LANE_POS => {
317 rasn::uper::decode::<RoadLanePositionsContainer>(data)
318 .map(ExtensionContainer::RoadLanePositions)
319 .map_err(|e| format!("RoadLanePositionsContainer decode error: {e}"))
320 }
321 EXTENSION_CONTAINER_ID_VEHICLE_MOVEMENT_CONTROL => {
322 rasn::uper::decode::<VehicleMovementControlContainer>(data)
323 .map(ExtensionContainer::VehicleMovementControl)
324 .map_err(|e| format!("VehicleMovementControlContainer decode error: {e}"))
325 }
326 unknown => Err(format!("Unknown ExtensionContainerId: {unknown}")),
327 }
328 }
329
330 pub fn wrap_extension_container(
332 &self,
333 container: &ExtensionContainer,
334 ) -> Result<WrappedExtensionContainer, String> {
335 let id = container.container_id();
336 let bytes = self.encode_extension_container(id, container)?;
337 Ok(WrappedExtensionContainer::new(
338 ExtensionContainerId(Integer::from(id as i128)),
339 Any::new(bytes),
340 ))
341 }
342
343 pub fn unwrap_extension_container(
345 &self,
346 wrapped: &WrappedExtensionContainer,
347 ) -> Result<ExtensionContainer, String> {
348 let id = wrapped
349 .container_id
350 .0
351 .to_string()
352 .parse::<u8>()
353 .map_err(|e| format!("Invalid container id in wrapped container: {e}"))?;
354 self.decode_extension_container(id, wrapped.container_data.as_ref())
355 }
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361
362 #[test]
368 fn wrapped_extension_containers_uper() {
369 use crate::facilities::ca_basic_service::cam_bindings::cam_pdu_descriptions::{
370 ExtensionContainerId, WrappedExtensionContainer, WrappedExtensionContainers,
371 };
372 let containers = WrappedExtensionContainers(vec![WrappedExtensionContainer::new(
373 ExtensionContainerId(Integer::from(3)),
374 Any::new(vec![0x00]),
375 )]);
376 let encoded = rasn::uper::encode(&containers).unwrap();
377 assert_eq!(encoded, vec![0x01, 0x00, 0x80, 0x00]);
378 }
379
380 #[test]
386 fn cam_with_extension_container_matches_x691() {
387 let frozen = [
388 0x02, 0x02, 0x00, 0x00, 0x00, 0x01, 0x2f, 0x20, 0x80, 0x59, 0xca, 0x02, 0x27, 0xed,
389 0x92, 0x9d, 0xf5, 0xe0, 0xc8, 0x0c, 0x80, 0x01, 0xb7, 0x74, 0x3e, 0x00, 0x3d, 0xff,
390 0xc1, 0xf4, 0x7e, 0x3f, 0xe9, 0xed, 0x07, 0x37, 0xfe, 0xeb, 0xff, 0xf6, 0x00, 0x41,
391 0x00, 0x40, 0x20, 0x00, 0x00,
392 ];
393 let cam: Cam = rasn::uper::decode(&frozen).unwrap();
394 let ext = cam.cam.cam_parameters.extension_containers.clone().unwrap();
395 assert_eq!(ext.0.len(), 1);
396 assert_eq!(ext.0[0].container_id.0, Integer::from(3));
397 assert_eq!(ext.0[0].container_data.as_bytes(), &[0x00]);
398 assert_eq!(rasn::uper::encode(&cam).unwrap(), frozen.to_vec());
399 }
400
401 #[test]
402 fn generation_delta_time_set_in_normal_timestamp() {
403 let timestamp: f64 = 1675871599.0;
404 let gdt = GenerationDeltaTime::from_timestamp(timestamp);
405 let expected = (((timestamp * 1000.0) as i64 - 1072915200000 + 5000) % 65536) as u16;
406 assert_eq!(gdt.0, expected);
407 assert_eq!(gdt.0, 38176);
408 }
409
410 #[test]
411 fn generation_delta_time_as_timestamp_in_certain_point() {
412 let timestamp = 1755763553.722;
413 let reception_timestamp_millis = ((timestamp + 0.3) * 1000.0) as u64;
414 let gdt = GenerationDeltaTime::from_timestamp(timestamp);
415 assert_eq!(
416 gdt.as_timestamp_in_certain_point(reception_timestamp_millis),
417 (timestamp * 1000.0).round() as u64
418 );
419 }
420
421 #[test]
422 fn generation_delta_time_operators() {
423 let ts1 = GenerationDeltaTime::from_timestamp(1675871599.0);
424 let ts2 = GenerationDeltaTime::from_timestamp(1675871600.0);
425 assert!(ts2.0 > ts1.0);
426 assert!(ts1.0 < ts2.0);
427
428 let gdt = GenerationDeltaTime::from_timestamp(1675871599.0);
429 let result = gdt.clone() + GenerationDeltaTime(30);
430 assert_eq!(result.0, ((gdt.0 as u32 + 30) % 65536) as u16);
431
432 let gdt1 = GenerationDeltaTime(20);
433 let gdt2 = GenerationDeltaTime(30);
434 assert_eq!((gdt1 - gdt2).0, 65526);
435 }
436
437 #[test]
438 fn cam_header_fields() {
439 let hdr = cam_header(42);
440 assert_eq!(hdr.protocol_version.0, 2);
441 assert_eq!(hdr.message_id.0, 2);
442 assert_eq!(hdr.station_id.0, 42);
443 }
444
445 #[test]
446 fn cam_coder_new() {
447 let coder = CamCoder::new();
448 let coder2 = coder.clone();
449 let _ = format!("{:?}", coder2);
450 }
451
452 #[test]
453 fn cam_coder_decode_invalid_bytes() {
454 let coder = CamCoder::new();
455 let result = coder.decode(&[0xFF, 0xFF]);
456 assert!(result.is_err());
457 }
458
459 #[test]
460 fn white_cam_exact_wire_encoding() {
461 let coder = CamCoder::new();
462 let white_cam = generate_white_cam_static();
463 let encoded = coder.encode(&white_cam).expect("encode white cam");
464 let expected = b"\x02\x02\x00\x00\x00\x00\x00\x00\x00\ri:@:\xd2t\x80\
465 ?\xff\xff\xfc#\xb7t>\x00\xe1\x1f\xdf\xff\xfe\xbf\xe9\
466 \xed\x077\xfe\xeb\xff\xf6\x00";
467 assert_eq!(encoded, expected);
468 let decoded = coder.decode(&encoded).expect("decode white cam");
469 assert_eq!(decoded.header.protocol_version.0, 2);
470 assert_eq!(decoded.header.station_id.0, 0);
471 }
472
473 #[test]
474 fn extension_container_unknown_id_raises() {
475 let coder = CamCoder::new();
476 let err = coder.decode_extension_container(99, &[0x00]);
477 assert!(err.is_err());
478 }
479
480 #[test]
481 fn vlf_extension_container_roundtrip() {
482 let coder = CamCoder::new();
483 let vlf =
484 ExtensionContainer::VeryLowFrequency(VeryLowFrequencyContainer::new(None, None, None));
485 let bytes = coder
486 .encode_extension_container(EXTENSION_CONTAINER_ID_VLF, &vlf)
487 .expect("encode vlf");
488 assert_eq!(bytes, vec![0x00]);
489 let decoded = coder
490 .decode_extension_container(EXTENSION_CONTAINER_ID_VLF, &bytes)
491 .expect("decode vlf");
492 assert_eq!(decoded, vlf);
493 }
494
495 #[test]
496 fn two_wheeler_extension_container_roundtrip() {
497 let coder = CamCoder::new();
498 let tw = ExtensionContainer::TwoWheeler(TwoWheelerContainer::new(None, None, None, None));
499 let bytes = coder
500 .encode_extension_container(EXTENSION_CONTAINER_ID_TWO_WHEELER, &tw)
501 .expect("encode tw");
502 assert_eq!(bytes, vec![0x00]);
503 let decoded = coder
504 .decode_extension_container(EXTENSION_CONTAINER_ID_TWO_WHEELER, &bytes)
505 .expect("decode tw");
506 assert_eq!(decoded, tw);
507 }
508
509 #[test]
510 fn extension_containers_in_cam_roundtrip() {
511 let coder = CamCoder::new();
512 let mut cam = generate_white_cam_static();
513
514 let vlf =
515 ExtensionContainer::VeryLowFrequency(VeryLowFrequencyContainer::new(None, None, None));
516 let tw = ExtensionContainer::TwoWheeler(TwoWheelerContainer::new(None, None, None, None));
517
518 let wrapped_vlf = coder.wrap_extension_container(&vlf).expect("wrap vlf");
519 let wrapped_tw = coder.wrap_extension_container(&tw).expect("wrap tw");
520
521 cam.cam.cam_parameters.extension_containers =
522 Some(WrappedExtensionContainers(vec![wrapped_vlf, wrapped_tw]));
523
524 let encoded = coder.encode(&cam).expect("encode cam with extensions");
525 let decoded = coder.decode(&encoded).expect("decode cam with extensions");
526
527 let exts = decoded
528 .cam
529 .cam_parameters
530 .extension_containers
531 .expect("extensionContainers");
532 assert_eq!(exts.0.len(), 2);
533
534 let unwrapped0 = coder.unwrap_extension_container(&exts.0[0]).unwrap();
535 let unwrapped1 = coder.unwrap_extension_container(&exts.0[1]).unwrap();
536 assert_eq!(unwrapped0, vlf);
537 assert_eq!(unwrapped1, tw);
538 }
539}