Skip to main content

rustflexstack/geonet/
dcc_net.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! DCC_NET: the GeoNetworking part of Decentralized Congestion Control over
5//! ITS-G5 (ETSI TS 103 836-4-2 V2.1.1 (2025-04), clauses 5 to 7).
6//!
7//! - DCC variables CBR_L_0_Hop, CBR_L_1_Hop, CBR_L_2_Hop and the global CBR_G,
8//!   calculated every `itsGNCBRGTriggerInterval` with a random start offset
9//!   (clauses 5.2 and 5.3);
10//! - Location Table Entry Extension for ITS-G5 (LocTEX-G5) per neighbour,
11//!   soft-state with lifetime `itsGnLifetimeLocTEX` (clause 6.2);
12//! - the DCC-MCO field of the SHB Extended Header (clause 6.3.3, table 3).
13//!
14//! The local CBR (CBR_L_0_Hop) is measured by the access layer and read from a
15//! [`CbrProvider`], e.g. [`Nl80211SurveyCbr`](crate::management::cbr::Nl80211SurveyCbr)
16//! on a Linux ITS-G5 interface. CBR_G is published in [`DccNet::global_cbr`] (a
17//! [`SharedCbr`]) so that the DCC entity uses it as input (clause 5.3,
18//! DCC_CROSS).
19//!
20//! Wiring on a Linux ITS-G5 interface:
21//!
22//! ```ignore
23//! use rustflexstack::geonet::dcc_net::DccNet;
24//! use rustflexstack::management::cbr::{nl80211_tx_power_dbm, Nl80211SurveyCbr};
25//! use rustflexstack::management::dcc_entity::{DccEntity, DccMode};
26//!
27//! let dcc_net = DccNet::new(
28//!     Some(Box::new(Nl80211SurveyCbr::new("wlan0"))),
29//!     nl80211_tx_power_dbm("wlan0").unwrap_or(0.0),
30//! );
31//! let dcc = DccEntity::new(DccMode::reactive(), Box::new(dcc_net.global_cbr.clone()));
32//! let (gn, ll_rx, btp_rx) = Router::spawn_with_dcc_net(mib, None, None, None, Some(dcc_net));
33//! ```
34//!
35//! Mirrors `flexstack/geonet/dcc_net.py`.
36
37use std::collections::HashMap;
38
39use super::gn_address::GNAddress;
40use crate::management::cbr::{CbrProvider, SharedCbr};
41
42/// Annex A, table A.1: lifetime of the LocTEX-G5 [ms].
43pub const ITS_GN_LIFETIME_LOCTEX_MS: u64 = 1000;
44/// Annex A, table A.1: CBR_Target.
45pub const ITS_GN_CBR_TARGET: f64 = 0.62;
46/// Annex A, table A.1: T_Trig [ms].
47pub const ITS_GN_CBR_G_TRIGGER_INTERVAL_MS: u64 = 100;
48/// Annex A, table A.1: T_Cbr [ms].
49pub const ITS_GN_CBR_LIFETIME_MS: u64 = 1000;
50/// Table 3: E.I.R.P. range of the Transmit power sub-field [dBm].
51const TX_POWER_MAX_DBM: f64 = 31.0;
52
53/// DCC-MCO field (octets 40-43 of the SHB packet header, table 3): CBRs as
54/// floor(CBR x 255), transmit power in dBm clamped to [0, 31], octet 43
55/// reserved for MCO.
56pub fn encode_dcc_mco(cbr_l_0_hop: f64, cbr_l_1_hop: f64, tx_power_dbm: f64) -> [u8; 4] {
57    let cbr_octet = |cbr: f64| (cbr * 255.0).floor().clamp(0.0, 255.0) as u8;
58    let power = tx_power_dbm.floor().clamp(0.0, TX_POWER_MAX_DBM) as u8;
59    [
60        cbr_octet(cbr_l_0_hop),
61        cbr_octet(cbr_l_1_hop),
62        power & 0x1F,
63        0,
64    ]
65}
66
67/// (CBR_R_0_Hop, CBR_R_1_Hop, transmit power [dBm]) of a received DCC-MCO
68/// field, or `None` when the field is absent: a sender without DCC_NET leaves
69/// the four octets zero-filled (TS 103 836-4-1 reserved field).
70pub fn decode_dcc_mco(field: &[u8]) -> Option<(f64, f64, u8)> {
71    if field.len() != 4 || field == [0, 0, 0, 0] {
72        return None;
73    }
74    Some((
75        field[0] as f64 / 255.0,
76        field[1] as f64 / 255.0,
77        field[2] & 0x1F,
78    ))
79}
80
81/// Location Table Entry Extension for ITS-G5 (clause 6.2.2).
82#[derive(Debug, Clone, PartialEq)]
83pub struct LocTexG5 {
84    /// Local time of the last update [ms].
85    pub tst_g5_ms: u64,
86    /// TST of the SO PV of the updating SHB [ms, mod 2^32].
87    pub tst_so_pv: u32,
88    pub tx_power_dbm: u8,
89    pub rssi_dbm: Option<f64>,
90    pub cbr_r_0_hop: f64,
91    pub cbr_r_1_hop: f64,
92}
93
94/// Steps 1-2 / 3-4 of clause 5.3: the maximum when the average exceeds
95/// CBR_Target, otherwise the second largest value (the only value when there
96/// is one, 0 when there is none).
97fn reduce(values: &[f64], target: f64) -> f64 {
98    if values.is_empty() {
99        return 0.0;
100    }
101    let mut ordered = values.to_vec();
102    ordered.sort_by(|a, b| b.total_cmp(a));
103    let average = values.iter().sum::<f64>() / values.len() as f64;
104    if average > target || ordered.len() == 1 {
105        ordered[0]
106    } else {
107        ordered[1]
108    }
109}
110
111/// DCC_NET entity of a GeoAdhoc router over ITS-G5.
112pub struct DccNet {
113    /// Source of CBR_L_0_Hop, polled at every trigger; `None` when the
114    /// application reports it with [`DccNet::report_local_cbr`].
115    pub local_cbr: Option<Box<dyn CbrProvider>>,
116    /// E.I.R.P. of the transmitted packets, e.g. from
117    /// [`nl80211_tx_power_dbm`](crate::management::cbr::nl80211_tx_power_dbm).
118    pub tx_power_dbm: f64,
119    pub cbr_target: f64,
120    pub trigger_interval_ms: u64,
121    pub cbr_lifetime_ms: u64,
122    pub loctex_lifetime_ms: u64,
123    pub cbr_l_0_hop: f64,
124    pub cbr_l_1_hop: f64,
125    pub cbr_l_2_hop: f64,
126    pub cbr_g: f64,
127    /// CBR_G for the DCC entity (DCC_CROSS); clones share the value.
128    pub global_cbr: SharedCbr,
129    /// LocTEX-G5 per neighbour, keyed by `GNAddress::encode_to_int`.
130    pub loctex: HashMap<u64, LocTexG5>,
131    rng: Box<dyn FnMut() -> f64 + Send>,
132    next_trigger_ms: Option<u64>,
133}
134
135impl DccNet {
136    /// DCC_NET with the annex A constants and a random trigger offset.
137    pub fn new(local_cbr: Option<Box<dyn CbrProvider>>, tx_power_dbm: f64) -> Self {
138        DccNet {
139            local_cbr,
140            tx_power_dbm,
141            cbr_target: ITS_GN_CBR_TARGET,
142            trigger_interval_ms: ITS_GN_CBR_G_TRIGGER_INTERVAL_MS,
143            cbr_lifetime_ms: ITS_GN_CBR_LIFETIME_MS,
144            loctex_lifetime_ms: ITS_GN_LIFETIME_LOCTEX_MS,
145            cbr_l_0_hop: 0.0,
146            cbr_l_1_hop: 0.0,
147            cbr_l_2_hop: 0.0,
148            cbr_g: 0.0,
149            global_cbr: SharedCbr::new(),
150            loctex: HashMap::new(),
151            rng: Box::new(rand::random::<f64>),
152            next_trigger_ms: None,
153        }
154    }
155
156    /// Replace the uniform [0, 1) source of the random trigger offset.
157    pub fn with_rng(mut self, rng: Box<dyn FnMut() -> f64 + Send>) -> Self {
158        self.rng = rng;
159        self
160    }
161
162    /// Set CBR_L_0_Hop from an access layer that pushes measurements.
163    pub fn report_local_cbr(&mut self, cbr: f64) {
164        if (0.0..=1.0).contains(&cbr) {
165            self.cbr_l_0_hop = cbr;
166        }
167    }
168
169    /// DCC-MCO field for the next SHB (clause 7.2.1).
170    pub fn dcc_mco(&self) -> [u8; 4] {
171        encode_dcc_mco(self.cbr_l_0_hop, self.cbr_l_1_hop, self.tx_power_dbm)
172    }
173
174    /// Update the LocTEX-G5 of a neighbour from a received, non-duplicate SHB
175    /// (clauses 6.2.3 and 7.2.2). Not updated when the SHB has no DCC-MCO.
176    pub fn update_loctex(
177        &mut self,
178        gn_addr: GNAddress,
179        tst_so_pv: u32,
180        field: &[u8],
181        now_ms: u64,
182        rssi_dbm: Option<f64>,
183    ) -> bool {
184        let Some((cbr_r_0_hop, cbr_r_1_hop, tx_power_dbm)) = decode_dcc_mco(field) else {
185            return false;
186        };
187        self.loctex.insert(
188            gn_addr.encode_to_int(),
189            LocTexG5 {
190                tst_g5_ms: now_ms,
191                tst_so_pv,
192                tx_power_dbm,
193                rssi_dbm,
194                cbr_r_0_hop,
195                cbr_r_1_hop,
196            },
197        );
198        true
199    }
200
201    /// LocTEX-G5 of a neighbour.
202    pub fn loctex_of(&self, gn_addr: &GNAddress) -> Option<&LocTexG5> {
203        self.loctex.get(&gn_addr.encode_to_int())
204    }
205
206    /// Next T_Trig expiry; the first one has a random offset within T_Trig.
207    pub fn next_trigger(&mut self, now_ms: u64) -> u64 {
208        if self.next_trigger_ms.is_none() {
209            let offset = ((self.rng)() * self.trigger_interval_ms as f64) as u64;
210            self.next_trigger_ms = Some(now_ms + offset);
211        }
212        self.next_trigger_ms.unwrap_or(now_ms)
213    }
214
215    /// Next T_Trig expiry if already scheduled (no side effects).
216    pub fn scheduled_trigger(&self) -> Option<u64> {
217        self.next_trigger_ms
218    }
219
220    /// Calculate CBR_G (steps 1 to 5 of clause 5.3), expire LocTEX-G5
221    /// entries, read the new CBR_L_0_Hop and publish CBR_G. Returns CBR_G.
222    pub fn trigger(&mut self, now_ms: u64) -> f64 {
223        let local = self.local_cbr.as_mut().and_then(|p| p.measure_cbr());
224        let lifetime = self.loctex_lifetime_ms;
225        self.loctex
226            .retain(|_, e| now_ms.saturating_sub(e.tst_g5_ms) <= lifetime);
227        let recent: Vec<&LocTexG5> = self
228            .loctex
229            .values()
230            .filter(|e| now_ms.saturating_sub(e.tst_g5_ms) <= self.cbr_lifetime_ms)
231            .collect();
232        let r0: Vec<f64> = recent.iter().map(|e| e.cbr_r_0_hop).collect();
233        let r1: Vec<f64> = recent.iter().map(|e| e.cbr_r_1_hop).collect();
234        self.cbr_l_1_hop = reduce(&r0, self.cbr_target);
235        self.cbr_l_2_hop = reduce(&r1, self.cbr_target);
236        // Step 5: CBR_G(n) = max(CBR_L_0_Hop(n-1), CBR_L_1_Hop(n), CBR_L_2_Hop(n))
237        self.cbr_g = self.cbr_l_0_hop.max(self.cbr_l_1_hop).max(self.cbr_l_2_hop);
238        if let Some(cbr) = local.filter(|c| (0.0..=1.0).contains(c)) {
239            self.cbr_l_0_hop = cbr;
240        }
241        self.next_trigger_ms = Some(now_ms + self.trigger_interval_ms);
242        self.global_cbr.report(self.cbr_g);
243        self.cbr_g
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250    use crate::geonet::gn_address::{M, MID, ST};
251    use crate::management::cbr::SharedCbr;
252
253    fn addr(n: u8) -> GNAddress {
254        GNAddress::new(M::GnUnicast, ST::Unknown, MID::new([2, 0, 0, 0, 0, n]))
255    }
256
257    fn dcc(offset: f64) -> DccNet {
258        DccNet::new(None, 20.0).with_rng(Box::new(move || offset))
259    }
260
261    fn loctex(d: &mut DccNet, n: u8, r0: f64, r1: f64, now: u64) {
262        d.update_loctex(addr(n), 0, &encode_dcc_mco(r0, r1, 20.0), now, None);
263    }
264
265    #[test]
266    fn dcc_mco_encoding() {
267        assert_eq!(encode_dcc_mco(0.5, 0.8, 20.0), [127, 204, 20, 0]);
268        assert_eq!(encode_dcc_mco(1.0, 0.0, 40.0), [255, 0, 31, 0]);
269        assert_eq!(encode_dcc_mco(0.0, 0.0, -3.0), [0, 0, 0, 0]);
270    }
271
272    #[test]
273    fn dcc_mco_decoding() {
274        assert_eq!(
275            decode_dcc_mco(&[204, 51, 23, 0]),
276            Some((204.0 / 255.0, 51.0 / 255.0, 23))
277        );
278        assert_eq!(decode_dcc_mco(&[0, 0, 0, 0]), None);
279    }
280
281    #[test]
282    fn first_trigger_has_random_offset() {
283        let mut d = dcc(0.5);
284        assert_eq!(d.next_trigger(1000), 1050);
285        d.trigger(1050);
286        assert_eq!(d.next_trigger(1050), 1150);
287    }
288
289    #[test]
290    fn maximum_above_target_second_largest_below() {
291        let mut d = dcc(0.0);
292        for (n, r0) in [(1u8, 0.9), (2, 0.8), (3, 0.7)] {
293            loctex(&mut d, n, r0, 0.1 * n as f64, 0);
294        }
295        d.trigger(0);
296        assert!((d.cbr_l_1_hop - 0.9).abs() < 0.01);
297        assert!((d.cbr_l_2_hop - 0.2).abs() < 0.01);
298        let mut d = dcc(0.0);
299        for (n, r0) in [(1u8, 0.5), (2, 0.3), (3, 0.1)] {
300            loctex(&mut d, n, r0, 0.0, 0);
301        }
302        d.trigger(0);
303        assert!((d.cbr_l_1_hop - 0.3).abs() < 0.01);
304    }
305
306    /// Step 5: CBR_G(n) = max(CBR_L_0_Hop(n-1), CBR_L_1_Hop(n), CBR_L_2_Hop(n)).
307    #[test]
308    fn cbr_g_uses_previous_local_cbr() {
309        let local = SharedCbr::new();
310        let mut d = DccNet::new(Some(Box::new(local.clone())), 20.0).with_rng(Box::new(|| 0.0));
311        local.report(0.7);
312        assert_eq!(d.trigger(0), 0.0);
313        assert_eq!(d.cbr_l_0_hop, 0.7);
314        assert_eq!(d.trigger(100), 0.7);
315        assert_eq!(d.global_cbr.latest(), Some(0.7));
316    }
317
318    /// Entries older than T_Cbr do not count; LocTEX-G5 expires.
319    #[test]
320    fn outdated_values_are_ignored() {
321        let mut d = dcc(0.0);
322        loctex(&mut d, 1, 0.9, 0.9, 0);
323        d.trigger(500);
324        assert!(d.cbr_l_1_hop > 0.8);
325        d.trigger(1100);
326        assert_eq!((d.cbr_l_1_hop, d.cbr_l_2_hop), (0.0, 0.0));
327        assert!(d.loctex.is_empty());
328    }
329
330    /// DCC_CROSS: CBR_G is the input of the DCC algorithm (clause 5.3).
331    #[test]
332    fn global_cbr_drives_the_dcc_entity() {
333        use crate::management::dcc_entity::{DccEntity, DccMode};
334        let mut d = dcc(0.0);
335        for n in [1u8, 2] {
336            loctex(&mut d, n, 0.9, 0.0, 0);
337        }
338        d.trigger(0);
339        let mut entity = DccEntity::new(DccMode::reactive(), Box::new(d.global_cbr.clone()));
340        assert!(entity.evaluate().unwrap().t_gen_cam_dcc_ms > 100);
341    }
342}