geonetworking 0.3.0

Tools for encoding and decoding a geonetworking header according to EN 302 636-4-1 v1.3.1
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
//! Message types from EN 302 636-4-1

extern crate alloc;
use crate::{bits, Bits};
use alloc::string::ToString;

#[cfg(feature = "json")]
use serde::{Deserialize, Serialize};

const LATLON_TO_INT_FACTOR: f32 = 1e7; // unit: 1/10 micro degree
const ANGLE_TO_INT_FACTOR: f32 = 10f32; // unit: 0.1 degree

#[derive(Debug, PartialEq, Eq)]
pub enum Error {
    /// (integer) value does not fit the target type
    ValueOutOfBounds(OutOfBoundsError),
    /// value does not fit the plausible value range
    ValueOutOfRange(alloc::string::String),
}

impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Error::ValueOutOfBounds(out_of_bounds_error) => write!(f, "{out_of_bounds_error}"),
            Error::ValueOutOfRange(value_name) => {
                write!(f, "Value out of range: '{value_name}' is not a sane value")
            }
        }
    }
}

impl core::error::Error for Error {}

#[derive(Debug, PartialEq, Eq)]
pub struct OutOfBoundsError {
    pub value_name: alloc::string::String,
    pub bounds_name: alloc::string::String,
}

impl core::fmt::Display for OutOfBoundsError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "Value out of bounds: given '{}' does not fit inside an {}",
            self.value_name, self.bounds_name
        )
    }
}

impl OutOfBoundsError {
    fn new(value_name: &str, bounds_name: &str) -> Self {
        Self {
            value_name: value_name.to_string(),
            bounds_name: bounds_name.to_string(),
        }
    }
}

fn make_latitude(deg: f32) -> Result<i32, Error> {
    #[allow(clippy::cast_possible_truncation)]
    let raw = (deg * LATLON_TO_INT_FACTOR) as i32;
    if (-900_000_000..=900_000_000).contains(&raw) {
        Ok(raw)
    } else {
        Err(Error::ValueOutOfRange("latitude".to_string()))
    }
}

fn make_longitude(deg: f32) -> Result<i32, Error> {
    #[allow(clippy::cast_possible_truncation)]
    let raw = (deg * LATLON_TO_INT_FACTOR) as i32;
    if (-1_800_000_000..=1_800_000_000).contains(&raw) {
        Ok(raw)
    } else {
        Err(Error::ValueOutOfRange("longitude".to_string()))
    }
}

fn make_heading(deg: f32) -> Result<u16, Error> {
    if deg < 0. {
        return Err(Error::ValueOutOfRange("heading".to_string()));
    }

    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let raw = (deg * ANGLE_TO_INT_FACTOR) as u16;
    if raw > 3600 {
        Err(Error::ValueOutOfRange("heading".to_string()))
    } else {
        Ok(raw)
    }
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct Address {
    /// This bit allows distinguishing between manually configured network address (clause 10.2.1.3.3) (update)
    /// and the initial GeoNetworking address (clause 10.2.1.3.2). M is set to 1 if the address is manually configured otherwise it equals 0.
    pub manually_configured: bool,
    /// ITS Station type
    pub station_type: StationType,
    /// Reserved
    pub reserved: Bits<10>,
    /// Represents the `LL_ADDR`
    pub address: [u8; 6],
}

impl Address {
    #[must_use]
    pub fn new(manually_configured: bool, station_type: StationType, address: [u8; 6]) -> Self {
        Self {
            manually_configured,
            station_type,
            reserved: bits![0;10],
            address,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum StationType {
    #[default]
    Unknown = 0,
    Pedestrian = 1,
    Cyclist = 2,
    Moped = 3,
    Motorcycle = 4,
    PassengerCar = 5,
    Bus = 6,
    LightTruck = 7,
    HeavyTruck = 8,
    Trailer = 9,
    SpecialVehicle = 10,
    Tram = 11,
    RoadSideUnit = 15,
}

/// Expresses the time in milliseconds at which the latitude and longitude
/// of the ITS-S were acquired by the GeoAdhoc router. The time is encoded as:
/// TST = TST(TAI) % 2^32
/// where TST(TAI) is the number of elapsed TAI milliseconds since 2004-01-01 00:00:00.000 UTC
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct Timestamp(pub u32);

impl Timestamp {
    #[must_use]
    pub fn as_unix_timestamp(&self) -> u64 {
        u64::from(self.0) + 1_072_915_200_000
    }

    /// Creates a Geonetworking Timestamp from an `TimestampITS` value
    #[must_use]
    pub fn from_its_timestamp(timestamp_its: u64) -> Self {
        #[allow(clippy::cast_possible_truncation)]
        let ts_mod = (timestamp_its % 4_294_967_296) as u32;
        Self(ts_mod)
    }
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct LongPositionVector {
    pub gn_address: Address,
    /// Expresses the time in milliseconds at which the latitude and longitude
    /// of the ITS-S were acquired by the GeoAdhoc router. The time is encoded as:
    /// TST = TST(TAI) % 2^32
    /// where TST(TAI) is the number of elapsed TAI milliseconds since 2004-01-01 00:00:00.000 UTC
    pub timestamp: Timestamp,
    /// WGS 84 [i.6] latitude of the GeoAdhoc router reference position expressed in 1/10 micro degree
    pub latitude: i32,
    /// WGS 84 [i.6] longitude of the GeoAdhoc router reference position expressed in 1/10 micro degree
    pub longitude: i32,
    /// Position accuracy indicator of the GeoAdhoc router reference position
    /// Set to 1 (i.e. True) if the semiMajorConfidence of the `PosConfidenceEllipse` as specified in ETSI TS 102 894-2 \[11\]
    /// is smaller than the GN protocol constant itsGnPaiInterval / 2
    /// Set to 0 (i.e. False) otherwise
    pub position_accuracy: bool,
    /// Speed of the GeoAdhoc router expressed in signed units of 0,01 meter per second
    pub speed: i16,
    /// Heading of the GeoAdhoc router, expressed in unsigned units of 0,1 degree from North
    pub heading: u16,
}

impl LongPositionVector {
    const MPS_TO_INT_FACTOR: f32 = 100f32; // unit: 0.01 metre per second
    const SPEED_MIN: i16 = -16_384;
    const SPEED_MAX: i16 = 16_383;

    /// Creates new instance from floating point values
    ///
    /// Provide:
    /// - a timestamp as `TimestampIts` value
    /// - latitude and longitude in degrees north/ east
    /// - speed in meters per second
    /// - heading in degrees from north
    ///
    /// # Errors
    /// Returns [`Error::ValueOutOfRange`] when some input value is outside the plausible value range.
    /// Returns [`Error::ValueOutOfBounds`] when some input value does not fit the target value range.
    pub fn try_from_values(
        gn_address: Address,
        timestamp_its: u64,
        latitude_deg: f32,
        longitude_deg: f32,
        position_accuracy: bool,
        speed_mps: f32,
        heading_deg: f32,
    ) -> Result<Self, Error> {
        let latitude = make_latitude(latitude_deg)?;
        let longitude = make_longitude(longitude_deg)?;

        #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
        let speed = (speed_mps * Self::MPS_TO_INT_FACTOR) as i16; // integer value range will be checked by Self::try_new

        let heading = make_heading(heading_deg)?;

        let timestamp = Timestamp::from_its_timestamp(timestamp_its);

        Self::try_new(
            gn_address,
            timestamp,
            latitude,
            longitude,
            position_accuracy,
            speed,
            heading,
        )
    }

    /// Creates new instance from parts
    ///
    /// # Errors
    /// Returns [`Error::ValueOutOfBounds`] when some input value does not fit the target value range.
    /// The values will only be checked for integer range, not plausibility.
    pub fn try_new(
        gn_address: Address,
        timestamp: Timestamp,
        latitude: i32,
        longitude: i32,
        position_accuracy: bool,
        speed: i16,
        heading: u16,
    ) -> Result<Self, Error> {
        // speed value is 15 bit signed integer
        if !(Self::SPEED_MIN..=Self::SPEED_MAX).contains(&speed) {
            return Err(Error::ValueOutOfBounds(OutOfBoundsError::new(
                "speed", "i15",
            )));
        }

        Ok(Self {
            gn_address,
            timestamp,
            latitude,
            longitude,
            position_accuracy,
            speed,
            heading,
        })
    }

    #[must_use]
    /// Returns latitude and longitude in degrees
    pub fn get_position_deg(&self) -> (f32, f32) {
        #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
        let lat = (self.latitude as f32) / LATLON_TO_INT_FACTOR;
        #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
        let lon = (self.longitude as f32) / LATLON_TO_INT_FACTOR;
        (lat, lon)
    }

    #[must_use]
    pub fn get_speed_mps(&self) -> f32 {
        f32::from(self.speed) / Self::MPS_TO_INT_FACTOR
    }

    #[must_use]
    pub fn get_heading_deg(&self) -> f32 {
        f32::from(self.heading) / ANGLE_TO_INT_FACTOR
    }

    /// Clamps a speed value in meters per second to the allowed value range in the LPV
    #[must_use]
    pub fn clamp_speed_mps(speed_mps: f32) -> f32 {
        let min_mps = f32::from(Self::SPEED_MIN) / Self::MPS_TO_INT_FACTOR;
        let max_mps = f32::from(Self::SPEED_MAX) / Self::MPS_TO_INT_FACTOR;

        speed_mps.clamp(min_mps, max_mps)
    }
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct ShortPositionVector {
    pub gn_address: Address,
    /// Expresses the time in milliseconds at which the latitude and longitude
    /// of the ITS-S were acquired by the GeoAdhoc router. The time is encoded as:
    /// TST = TST(TAI) % 2^32
    /// where TST(TAI) is the number of elapsed TAI milliseconds since 2004-01-01 00:00:00.000 UTC
    pub timestamp: Timestamp,
    /// WGS 84 [i.6] latitude of the GeoAdhoc router reference position expressed in 1/10 micro degree
    pub latitude: i32,
    /// WGS 84 [i.6] longitude of the GeoAdhoc router reference position expressed in 1/10 micro degree
    pub longitude: i32,
}

impl ShortPositionVector {
    /// Creates new instance from floating point values
    ///
    /// Provide:
    /// - a timestamp as `TimestampIts` value
    /// - latitude and longitude in degrees north/ east
    ///
    /// # Errors
    /// Returns [`Error::ValueOutOfRange`] when some input value is outside the plausible value range.
    pub fn try_from_values(
        gn_address: Address,
        timestamp_its: u64,
        latitude_deg: f32,
        longitude_deg: f32,
    ) -> Result<Self, Error> {
        let latitude = make_latitude(latitude_deg)?;
        let longitude = make_longitude(longitude_deg)?;

        let timestamp = Timestamp::from_its_timestamp(timestamp_its);

        Ok(Self {
            gn_address,
            timestamp,
            latitude,
            longitude,
        })
    }
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct BasicHeader {
    /// Identifies the version of the GeoNetworking protocol
    pub version: u8,
    /// Identifies the type of header immediately following the GeoNetworking Basic Header
    pub next_header: NextAfterBasic,
    /// Reserved. Set to 0
    pub reserved: Bits<8>,
    /// Lifetime field. Indicates the maximum tolerable time a packet may be buffered until it reaches its destination
    /// Bit 0 to Bit 5: LT sub-field Multiplier
    /// Bit 6 to Bit 7: LT sub-field Base
    pub lifetime: Lifetime,
    /// Decremented by 1 by each GeoAdhoc router that forwards the packet
    /// The packet shall not be forwarded if RHL is decremented to zero
    pub remaining_hop_limit: u8,
}

impl BasicHeader {
    /// Creates new instance from parts
    ///
    /// # Errors
    /// Returns [`Error::ValueOutOfBounds`] when some input value does not fit the target value range.
    /// The values will only be checked for integer range, not plausibility.
    pub fn try_new(
        version: u8,
        next_header: NextAfterBasic,
        lifetime: Lifetime,
        remaining_hop_limit: u8,
    ) -> Result<Self, Error> {
        // version is 4 bit unsigned
        if version > 15 {
            return Err(Error::ValueOutOfBounds(OutOfBoundsError::new(
                "version", "u4",
            )));
        }

        Ok(Self {
            version,
            next_header,
            reserved: bits![0; 8],
            lifetime,
            remaining_hop_limit,
        })
    }
}

#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
/// Identifies the type of header immediately following the GeoNetworking Basic Header
pub enum NextAfterBasic {
    Any = 0,
    CommonHeader = 1,
    SecuredPacket = 2,
}

#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
/// Lifetime field. Indicates the maximum tolerable time a packet may be buffered until it reaches its destination
/// Bit 0 to Bit 5: LT sub-field Multiplier
/// Bit 6 to Bit 7: LT sub-field Base
pub struct Lifetime(pub u8);

impl Lifetime {
    #[must_use]
    pub fn from_raw(value: u8) -> Self {
        Self(value)
    }

    #[must_use]
    pub fn from_milliseconds(millis: u32) -> Self {
        // lifetime bases:
        // - 0:  50 ms
        // - 1:   1 s
        // - 2:  10 s
        // - 3: 100 s
        // lifetime multiplier: 6 bit -> 0..63
        const ITS_GN_MAX_PACKET_LIFETIME: u32 = 600_000; // itsGnMaxPacketLifetime according to ETSI EN 302 636-4-1 V1.4.1

        // use base with highest resolution for as long as possible, but without creating "jumps".
        // e.g. 3150 ms is not represented as 63*50 ms because next higher value (3200 ms) can only be represented as 3*1 second.
        let (multiplier, base) = if millis < 3000 {
            // max. value which can be represented: 63 * 50 ms = 3150 ms
            let multiplier = millis / 50;

            (multiplier, 0) // multiplier 50ms
        } else if millis < 60_000 {
            // max. value which can be represented: 63 * 1 s = 63 s
            let multiplier = millis / 1000;

            (multiplier, 1) // multiplier 1s/ 1000ms
        } else if millis < 600_000 {
            // max. value which can be represented: 63 * 10 s = 630 s
            let multiplier = millis / 10_000;

            (multiplier, 2) // multiplier 10s/ 10000ms
        } else if millis < ITS_GN_MAX_PACKET_LIFETIME {
            let multiplier = millis / 100_000;

            (multiplier, 3) // multiplier 100s
        } else {
            (ITS_GN_MAX_PACKET_LIFETIME / 100_000, 3) // multiplier 100s/ 100000ms
        };

        #[allow(clippy::cast_possible_truncation)]
        let lifetime_data = (multiplier << 2) as u8 | (base & 0x03);

        Self(lifetime_data)
    }

    /// returns the lifetime base (bit 6 and 7)
    #[must_use]
    pub fn base(&self) -> u8 {
        self.0 & 0b0000_0011
    }

    /// returns the lifetime multiplier (bit 0 to 5)
    #[must_use]
    pub fn multiplier(&self) -> u8 {
        self.0 >> 2
    }

    /// returns the lifetime value in milliseconds
    #[must_use]
    pub fn as_milliseconds(&self) -> u32 {
        match self.base() {
            0 => 50 * u32::from(self.multiplier()),
            1 => 1000 * u32::from(self.multiplier()),
            2 => 10000 * u32::from(self.multiplier()),
            3 => 100_000 * u32::from(self.multiplier()),
            _ => unreachable!(),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct CommonHeader {
    /// Identifies the type of header immediately following the GeoNetworking headers
    pub next_header: NextAfterCommon,
    /// Reserved. Set to 0
    pub reserved_1: Bits<4>,
    /// Identifies the type and sub-type of the GeoNetworking header
    pub header_type_and_subtype: HeaderType,
    /// Traffic class that represents Facility-layer requirements on packet transport
    pub traffic_class: TrafficClass,
    /// Bit 0: Indicates whether the ITS-S is mobile or stationary (GN protocol constant itsGnIsMobile)
    /// Bit 1 to Bit 7: Reserved, set to 0
    pub flags: Bits<8>,
    /// Length of the GeoNetworking payload, i.e. the rest of the packet following the whole GeoNetworking header in octets, for example BTP + CAM
    pub payload_length: u16,
    ///  The Maximum hop limit is not decremented by a GeoAdhoc router that forwards the packet
    pub maximum_hop_limit: u8,
    /// Reserved. Set to 0
    pub reserved_2: Bits<8>,
}

impl CommonHeader {
    #[must_use]
    pub fn new(
        next_header: NextAfterCommon,
        header_type_and_subtype: HeaderType,
        traffic_class: TrafficClass,
        flags: [bool; 8],
        payload_length: u16,
        maximum_hop_limit: u8,
    ) -> Self {
        let flags = Bits(flags.iter().collect::<_>());

        Self {
            next_header,
            reserved_1: bits![0; 4],
            header_type_and_subtype,
            traffic_class,
            flags,
            payload_length,
            maximum_hop_limit,
            reserved_2: bits![0; 8],
        }
    }

    /// Creates new instance from individual values
    #[must_use]
    pub fn from_values(
        next_header: NextAfterCommon,
        header_type_and_subtype: HeaderType,
        traffic_class: TrafficClass,
        is_mobile: bool,
        payload_length: u16,
        maximum_hop_limit: u8,
    ) -> Self {
        let mobile_flag = u8::from(is_mobile);
        let flags = bits![mobile_flag, 0, 0, 0, 0, 0, 0, 0];

        Self {
            next_header,
            reserved_1: bits![0; 4],
            header_type_and_subtype,
            traffic_class,
            flags,
            payload_length,
            maximum_hop_limit,
            reserved_2: bits![0; 8],
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
/// Traffic class that represents Facility-layer requirements on packet transport
pub struct TrafficClass {
    /// Indicates whether the packet shall be buffered when no suitable neighbour exists
    pub store_carry_forward: bool,
    /// Indicates whether the packet may be offloaded to another channel than specified in the traffic class ID
    pub channel_offload: bool,
    /// Traffic class ID as specified in the media-dependent part of GeoNetworking corresponding to the interface
    /// over which the packet will be transmitted, e.g. in ETSI TS 102 636-4-2 [i.11] for ITS-G5 and ETSI TS 103 613 [i.10] for LTE-V2X
    pub traffic_class_id: u8,
}

impl TrafficClass {
    /// Creates new instance from parts
    ///
    /// # Errors
    /// Returns [`Error::ValueOutOfBounds`] when some input value does not fit the target value range.
    /// The values will only be checked for integer range, not plausibility.
    pub fn try_new(
        store_carry_forward: bool,
        channel_offload: bool,
        traffic_class_id: u8,
    ) -> Result<Self, Error> {
        // traffic_class_id is 6 bit unsigned
        if traffic_class_id > 63 {
            return Err(Error::ValueOutOfBounds(OutOfBoundsError::new(
                "traffic_class_id",
                "u6",
            )));
        }

        Ok(Self {
            store_carry_forward,
            channel_offload,
            traffic_class_id,
        })
    }
}

#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
/// Identifies the type of header immediately following the GeoNetworking Common Header
pub enum NextAfterCommon {
    Any = 0,
    /// Transport protocol (BTP-A for interactive packet transport) as defined in ETSI EN 302 636-5-1
    BTPA = 1,
    /// Transport protocol (BTP-B for non-interactive packet transport) as defined in ETSI EN 302 636-5-1
    BTPB = 2,
    /// IPv6 header as defined in ETSI EN 302 636-6-1
    IPv6 = 3,
}

#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
/// Identifies the type of the GeoNetworking header
pub enum HeaderType {
    Any,
    Beacon,
    GeoUnicast,
    /// Geographically-Scoped Anycast (GAC)
    GeoAnycast(AreaType),
    /// Geographically-Scoped broadcast (GBC)
    GeoBroadcast(AreaType),
    TopologicallyScopedBroadcast(BroadcastType),
    LocationService(LocationServiceType),
}

#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
/// Area type used in header subtypes
pub enum AreaType {
    Circular,
    Rectangular,
    Ellipsoidal,
}

#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
/// Broadcast type used in header subtypes
pub enum BroadcastType {
    SingleHop,
    MultiHop,
}

#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
/// Subtype of location service
pub enum LocationServiceType {
    Request,
    Reply,
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum ExtendedHeader {
    GUC(GeoUnicast),
    TSB(TopologicallyScopedBroadcast),
    SHB(SingleHopBroadcast),
    GBC(GeoBroadcast),
    GAC(GeoAnycast),
    Beacon(Beacon),
    LSRequest(LSRequest),
    LSReply(LSReply),
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct GeoUnicast {
    /// Sequence number field. Indicates the index of the sent GUC packet (clause 8.3) and used to detect duplicate GeoNetworking packets
    pub sequence_number: u16,
    /// Reserved. Set to 0
    pub reserved: Bits<16>,
    /// Long Position Vector containing the reference position of the source
    pub source_position_vector: LongPositionVector,
    /// Short Position Vector containing the position of the destination
    pub destination_position_vector: ShortPositionVector,
}

impl GeoUnicast {
    #[must_use]
    pub fn new(
        sequence_number: u16,
        source_position_vector: LongPositionVector,
        destination_position_vector: ShortPositionVector,
    ) -> Self {
        Self {
            sequence_number,
            reserved: bits![0; 16],
            source_position_vector,
            destination_position_vector,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct TopologicallyScopedBroadcast {
    /// Sequence number field. Indicates the index of the sent TSB packet (clause 8.3) and used to detect duplicate GeoNetworking packets
    pub sequence_number: u16,
    /// Reserved. Set to 0
    pub reserved: Bits<16>,
    /// Long Position Vector containing the reference position of the source
    pub source_position_vector: LongPositionVector,
}

impl TopologicallyScopedBroadcast {
    #[must_use]
    pub fn new(sequence_number: u16, source_position_vector: LongPositionVector) -> Self {
        Self {
            sequence_number,
            reserved: bits![0; 16],
            source_position_vector,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct SingleHopBroadcast {
    /// Long Position Vector containing the reference position of the source
    pub source_position_vector: LongPositionVector,
    /// Used for media-dependent operations. If not used, it shall be set to 0
    pub media_dependent_data: [u8; 4],
}

pub type GeoBroadcast = GeoAnycast;

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
/// In case of a circular area (GeoNetworking packet sub-type HST = 0), the fields shall be set to the following values:
/// 1) Distance a is set to the radius r.
/// 2) Distance b is set to 0.
/// 3) Angle is set to 0.
pub struct GeoAnycast {
    /// Sequence number field. Indicates the index of the sent GBC/GAC packet (clause 8.3) and used to detect duplicate GeoNetworking packets
    pub sequence_number: u16,
    /// Reserved. Set to 0
    pub reserved_1: Bits<16>,
    /// Long Position Vector containing the reference position of the source
    pub source_position_vector: LongPositionVector,
    /// WGS 84 [i.6] latitude for the centre position of the geometric shape as defined in ETSI EN 302 931 \[8\] in 1/10 micro degree
    pub geo_area_position_latitude: i32,
    /// WGS 84 [i.6] longitude for the centre position of the geometric shape as defined in ETSI EN 302 931 \[8\] in 1/10 micro degree
    pub geo_area_position_longitude: i32,
    /// Distance a of the geometric shape as defined in ETSI EN 302 931 \[8\] in meters
    pub distance_a: u16,
    /// Distance b of the geometric shape as defined in ETSI EN 302 931 \[8\] in meters
    pub distance_b: u16,
    /// Angle of the geometric shape as defined in ETSI EN 302 931 \[8\] in degrees from North
    pub angle: u16,
    /// Reserved. Set to 0
    pub reserved_2: Bits<16>,
}

impl GeoAnycast {
    /// Creates new instance from floating point values
    ///
    /// Provide:
    /// - latitude and longitude in degrees north/ east
    /// - distances in meters
    /// - angle in degrees from north
    ///
    /// # Errors
    /// Returns [`Error::ValueOutOfRange`] when some input value is outside the plausible value range.
    pub fn try_from_values(
        sequence_number: u16,
        source_position_vector: LongPositionVector,
        latitude_deg: f32,
        longitude_deg: f32,
        distance_a: u16,
        distance_b: u16,
        angle: u16,
    ) -> Result<Self, Error> {
        let latitude = make_latitude(latitude_deg)?;
        let longitude = make_longitude(longitude_deg)?;

        if angle > 360 {
            return Err(Error::ValueOutOfRange("angle".to_string()));
        }

        Ok(Self::new(
            sequence_number,
            source_position_vector,
            latitude,
            longitude,
            distance_a,
            distance_b,
            angle,
        ))
    }

    #[must_use]
    pub fn new(
        sequence_number: u16,
        source_position_vector: LongPositionVector,
        geo_area_position_latitude: i32,
        geo_area_position_longitude: i32,
        distance_a: u16,
        distance_b: u16,
        angle: u16,
    ) -> Self {
        Self {
            sequence_number,
            reserved_1: bits![0; 16],
            source_position_vector,
            geo_area_position_latitude,
            geo_area_position_longitude,
            distance_a,
            distance_b,
            angle,
            reserved_2: bits![0; 16],
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct Beacon {
    /// Long Position Vector containing the reference position of the source
    pub source_position_vector: LongPositionVector,
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct LSRequest {
    /// Sequence number field. Indicates the index of the sent LS Request packet (clause 8.3) and used to detect duplicate GeoNetworking packets
    pub sequence_number: u16,
    /// Reserved. Set to 0
    pub reserved: Bits<16>,
    /// Long Position Vector containing the reference position of the source
    pub source_position_vector: LongPositionVector,
    /// The `GN_ADDR` address for the GeoAdhoc router entity for which the location is being requested
    pub request_gn_address: Address,
}

impl LSRequest {
    #[must_use]
    pub fn new(
        sequence_number: u16,
        source_position_vector: LongPositionVector,
        request_gn_address: Address,
    ) -> Self {
        Self {
            sequence_number,
            reserved: bits![0; 16],
            source_position_vector,
            request_gn_address,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct LSReply {
    /// Sequence number field. Indicates the index of the sent LS Reply packet (clause 8.3) and used to detect duplicate GeoNetworking packets
    pub sequence_number: u16,
    /// Reserved. Set to 0
    pub reserved: Bits<16>,
    /// Long Position Vector containing the reference position of the source, which represents the Request `GN_ADDR` in the corresponding LS Request
    pub source_position_vector: LongPositionVector,
    /// Short Position Vector containing the position of the destination
    pub destination_position_vector: ShortPositionVector,
}

impl LSReply {
    #[must_use]
    pub fn new(
        sequence_number: u16,
        source_position_vector: LongPositionVector,
        destination_position_vector: ShortPositionVector,
    ) -> Self {
        Self {
            sequence_number,
            reserved: bits![0; 16],
            source_position_vector,
            destination_position_vector,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn convert_latitude() {
        assert_eq!(Ok(0), make_latitude(0.));
        assert_eq!(Ok(900_000_000), make_latitude(90.));
        assert_eq!(Ok(-900_000_000), make_latitude(-90.));
        assert!(make_latitude(90.1).is_err());
        assert!(make_latitude(-90.1).is_err());
    }

    #[test]
    fn convert_longitude() {
        assert_eq!(Ok(0), make_longitude(0.));
        assert_eq!(Ok(1_800_000_000), make_longitude(180.));
        assert_eq!(Ok(-1_800_000_000), make_longitude(-180.));
        assert!(make_longitude(180.1).is_err());
        assert!(make_longitude(-180.1).is_err());
    }

    #[test]
    fn convert_heading() {
        assert_eq!(Ok(0), make_heading(0.));
        assert_eq!(Ok(3600), make_heading(360.));
        assert!(make_heading(360.1).is_err());
        assert!(make_heading(-1.).is_err());
    }
}