esp-radio 0.18.0

A WiFi, Bluetooth and ESP-NOW driver for use with Espressif chips and bare-metal Rust
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
//! # Low-level [IEEE 802.15.4] driver
//!
//! Implements the PHY/MAC layers of the IEEE 802.15.4 protocol stack, and
//! supports sending and receiving of raw frames.
//!
//! This module is intended to be used to implement support for higher-level
//! communication protocols, for example [openthread].
//!
//! Note that this module requires the `unstable` feature on both `esp-radio`
//! and `esp-hal`.
//!
//! NOTE: Coexistence with Wi-Fi or Bluetooth is currently not possible. If you do it anyway,
//! things will break.
//!
//! [IEEE 802.15.4]: https://en.wikipedia.org/wiki/IEEE_802.15.4
//! [openthread]: https://github.com/esp-rs/openthread

#![allow(missing_docs)]

use byte::{BytesExt, TryRead};
use docsplay::Display;
use esp_hal::peripherals::IEEE802154;
use esp_phy::{PhyClockGuard, PhyInitGuard};
use esp_sync::NonReentrantMutex;
use ieee802154::mac::{self, FooterMode, FrameSerDesContext};

use self::{
    frame::FRAME_SIZE,
    pib::{CONFIG_IEEE802154_CCA_THRESHOLD, IEEE802154_FRAME_EXT_ADDR_SIZE},
    raw::*,
};
pub use self::{
    frame::{Frame, ReceivedFrame},
    pib::{CcaMode, PendingMode},
    raw::RawReceived,
};
mod frame;
mod hal;
mod pib;
mod raw;

/// IEEE 802.15.4 errors
#[derive(Display, Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
pub enum Error {
    /// The requested data is bigger than available range, and/or the offset is
    /// invalid.
    Incomplete,

    /// The requested data content is invalid.
    BadInput,
}

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

impl From<byte::Error> for Error {
    fn from(err: byte::Error) -> Self {
        match err {
            byte::Error::Incomplete | byte::Error::BadOffset(_) => Error::Incomplete,
            byte::Error::BadInput { .. } => Error::BadInput,
        }
    }
}

/// IEEE 802.15.4 driver configuration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
pub struct Config {
    pub auto_ack_tx: bool,
    pub auto_ack_rx: bool,
    pub enhance_ack_tx: bool,
    pub promiscuous: bool,
    pub coordinator: bool,
    pub rx_when_idle: bool,
    pub txpower: i8,
    pub channel: u8,
    pub cca_threshold: i8,
    pub cca_mode: CcaMode,
    pub pan_id: Option<u16>,
    pub short_addr: Option<u16>,
    pub ext_addr: Option<u64>,
    pub rx_queue_size: usize,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            auto_ack_tx: Default::default(),
            auto_ack_rx: Default::default(),
            enhance_ack_tx: Default::default(),
            promiscuous: Default::default(),
            coordinator: Default::default(),
            rx_when_idle: Default::default(),
            txpower: 20,
            channel: 15,
            cca_threshold: CONFIG_IEEE802154_CCA_THRESHOLD,
            cca_mode: CcaMode::Ed,
            pan_id: None,
            short_addr: None,
            ext_addr: None,
            rx_queue_size: 10,
        }
    }
}

/// IEEE 802.15.4 driver
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
pub struct Ieee802154<'a> {
    _align: u32,
    transmit_buffer: [u8; FRAME_SIZE],
    _phy_clock_guard: PhyClockGuard<'a>,
    _phy_init_guard: PhyInitGuard<'a>,
}

impl<'a> Ieee802154<'a> {
    /// Construct a new driver, enabling the IEEE 802.15.4 radio in the process
    ///
    /// NOTE: Coexistence with Wi-Fi or Bluetooth is currently not possible. If you do it anyway,
    /// things will break.
    #[instability::unstable]
    pub fn new(radio: IEEE802154<'a>) -> Self {
        let (_phy_clock_guard, _phy_init_guard) = esp_ieee802154_enable(radio);
        Self {
            _align: 0,
            transmit_buffer: [0u8; FRAME_SIZE],
            _phy_clock_guard,
            _phy_init_guard,
        }
    }

    /// Set the configuration for the driver
    #[instability::unstable]
    pub fn set_config(&mut self, cfg: Config) {
        set_auto_ack_tx(cfg.auto_ack_tx);
        set_auto_ack_rx(cfg.auto_ack_rx);
        set_enhance_ack_tx(cfg.enhance_ack_tx);
        set_promiscuous(cfg.promiscuous);
        set_coordinator(cfg.coordinator);
        set_rx_when_idle(cfg.rx_when_idle);
        set_tx_power(cfg.txpower);
        set_channel(cfg.channel);
        set_cca_theshold(cfg.cca_threshold);
        set_cca_mode(cfg.cca_mode);

        if let Some(pan_id) = cfg.pan_id {
            set_panid(0, pan_id);
        }

        if let Some(short_addr) = cfg.short_addr {
            set_short_address(0, short_addr);
        }

        if let Some(ext_addr) = cfg.ext_addr {
            let mut address = [0u8; IEEE802154_FRAME_EXT_ADDR_SIZE];
            address.copy_from_slice(&ext_addr.to_le_bytes());

            set_extended_address(0, address);
        }

        raw::set_queue_size(cfg.rx_queue_size);
    }

    /// Start receiving frames
    #[instability::unstable]
    pub fn start_receive(&mut self) {
        ieee802154_receive();
    }

    /// Return the raw data of a received frame
    #[instability::unstable]
    pub fn raw_received(&mut self) -> Option<RawReceived> {
        raw::ensure_receive_enabled();
        ieee802154_poll()
    }

    /// Get the ACK frame received in response to the last transmission.
    ///
    /// When a transmitted frame requires acknowledgment, the peer sends back
    /// an ACK frame. This method returns that ACK frame data, which includes
    /// the Frame Pending bit and other information needed by upper layers
    /// like OpenThread.
    ///
    /// Returns `None` if no ACK was received (frame didn't require ACK,
    /// ACK timed out, or no transmission has occurred).
    ///
    /// The ACK frame is cleared at the start of each new transmission.
    #[instability::unstable]
    pub fn get_ack_frame(&self) -> Option<RawReceived> {
        raw::get_ack_frame()
    }

    /// Get a received frame, if available
    #[instability::unstable]
    pub fn received(&mut self) -> Option<Result<ReceivedFrame, Error>> {
        raw::ensure_receive_enabled();
        if let Some(raw) = ieee802154_poll() {
            let maybe_decoded = if raw.data[0] as usize > raw.data.len() {
                // try to decode up to data.len()
                mac::Frame::try_read(&raw.data[1..][..raw.data.len()], FooterMode::Explicit)
            } else {
                mac::Frame::try_read(&raw.data[1..][..raw.data[0] as usize], FooterMode::Explicit)
            };

            let result = match maybe_decoded {
                Ok((decoded, _)) => {
                    // crc is not written to rx buffer
                    let rssi = if (raw.data[0] as usize > raw.data.len()) || (raw.data[0] == 0) {
                        raw.data[raw.data.len() - 1] as i8
                    } else {
                        raw.data[raw.data[0] as usize - 1] as i8
                    };

                    Ok(ReceivedFrame {
                        frame: Frame {
                            header: decoded.header,
                            content: decoded.content,
                            payload: decoded.payload.to_vec(),
                            footer: decoded.footer,
                        },
                        channel: raw.channel,
                        rssi,
                        lqi: rssi_to_lqi(rssi),
                    })
                }
                Err(err) => Err(err.into()),
            };

            Some(result)
        } else {
            None
        }
    }

    /// Transmit a frame
    ///
    /// If `cca` is true, a Clear Channel Assessment is performed before
    /// transmitting. The transmission is aborted if the channel is busy.
    #[instability::unstable]
    pub fn transmit(&mut self, frame: &Frame, cca: bool) -> Result<(), Error> {
        let frm = mac::Frame {
            header: frame.header,
            content: frame.content,
            payload: &frame.payload,
            footer: frame.footer,
        };

        let mut offset = 1usize;
        self.transmit_buffer
            .write_with(
                &mut offset,
                frm,
                &mut FrameSerDesContext::no_security(FooterMode::Explicit),
            )
            .unwrap();
        self.transmit_buffer[0] = (offset - 1) as u8;

        ieee802154_transmit(self.transmit_buffer.as_ptr(), cca);

        Ok(())
    }

    /// Transmit a raw frame
    ///
    /// If `cca` is true, a Clear Channel Assessment is performed before
    /// transmitting. The transmission is aborted if the channel is busy.
    #[instability::unstable]
    pub fn transmit_raw(&mut self, frame: &[u8], cca: bool) -> Result<(), Error> {
        self.transmit_buffer[1..][..frame.len()].copy_from_slice(frame);
        self.transmit_buffer[0] = frame.len() as u8;

        ieee802154_transmit(self.transmit_buffer.as_ptr(), cca);

        Ok(())
    }

    /// Set the transmit done callback function.
    #[instability::unstable]
    pub fn set_tx_done_callback(&mut self, callback: &'a mut (dyn FnMut() + Send)) {
        CALLBACKS.with(|cbs| {
            let cb: &'static mut (dyn FnMut() + Send) = unsafe { core::mem::transmute(callback) };
            cbs.tx_done = Some(cb);
        });
    }

    /// Clear the transmit done callback function.
    #[instability::unstable]
    pub fn clear_tx_done_callback(&mut self) {
        CALLBACKS.with(|cbs| cbs.tx_done = None);
    }

    /// Set the receive available callback function.
    #[instability::unstable]
    pub fn set_rx_available_callback(&mut self, callback: &'a mut (dyn FnMut() + Send)) {
        CALLBACKS.with(|cbs| {
            let cb: &'static mut (dyn FnMut() + Send) = unsafe { core::mem::transmute(callback) };
            cbs.rx_available = Some(cb);
        });
    }

    /// Clear the receive available callback function.
    #[instability::unstable]
    pub fn clear_rx_available_callback(&mut self) {
        CALLBACKS.with(|cbs| cbs.rx_available = None);
    }

    /// Set the transmit done callback function.
    #[instability::unstable]
    pub fn set_tx_done_callback_fn(&mut self, callback: fn()) {
        CALLBACKS.with(|cbs| cbs.tx_done_fn = Some(callback));
    }

    /// Clear the transmit done callback function.
    #[instability::unstable]
    pub fn clear_tx_done_callback_fn(&mut self) {
        CALLBACKS.with(|cbs| cbs.tx_done_fn = None);
    }

    /// Set the receive available callback function.
    #[instability::unstable]
    pub fn set_rx_available_callback_fn(&mut self, callback: fn()) {
        CALLBACKS.with(|cbs| cbs.rx_available_fn = Some(callback));
    }

    /// Clear the receive available callback function.
    #[instability::unstable]
    pub fn clear_rx_available_callback_fn(&mut self) {
        CALLBACKS.with(|cbs| cbs.rx_available_fn = None);
    }

    /// Set the transmit failed callback function.
    #[instability::unstable]
    pub fn set_tx_failed_callback(&mut self, callback: &'a mut (dyn FnMut() + Send)) {
        CALLBACKS.with(|cbs| {
            let cb: &'static mut (dyn FnMut() + Send) = unsafe { core::mem::transmute(callback) };
            cbs.tx_failed = Some(cb);
        });
    }

    /// Clear the transmit failed callback function.
    #[instability::unstable]
    pub fn clear_tx_failed_callback(&mut self) {
        CALLBACKS.with(|cbs| cbs.tx_failed = None);
    }

    /// Set the transmit failed callback function pointer.
    #[instability::unstable]
    pub fn set_tx_failed_callback_fn(&mut self, callback: fn()) {
        CALLBACKS.with(|cbs| cbs.tx_failed_fn = Some(callback));
    }

    /// Clear the transmit failed callback function.
    #[instability::unstable]
    pub fn clear_tx_failed_callback_fn(&mut self) {
        CALLBACKS.with(|cbs| cbs.tx_failed_fn = None);
    }
}

impl Drop for Ieee802154<'_> {
    fn drop(&mut self) {
        self.clear_tx_done_callback();
        self.clear_tx_done_callback_fn();
        self.clear_rx_available_callback();
        self.clear_rx_available_callback_fn();
        self.clear_tx_failed_callback();
        self.clear_tx_failed_callback_fn();
    }
}

/// Convert from RSSI (Received Signal Strength Indicator) to LQI (Link Quality
/// Indication)
///
/// RSSI is a measure of incoherent (raw) RF power in a channel. LQI is a
/// cumulative value used in multi-hop networks to assess the cost of a link.
#[instability::unstable]
pub fn rssi_to_lqi(rssi: i8) -> u8 {
    if rssi < -80 {
        0
    } else if rssi > -30 {
        0xff
    } else {
        let lqi_convert = ((rssi as u32).wrapping_add(80)) * 255;
        (lqi_convert / 50) as u8
    }
}

struct Callbacks {
    tx_done: Option<&'static mut (dyn FnMut() + Send)>,
    rx_available: Option<&'static mut (dyn FnMut() + Send)>,
    tx_failed: Option<&'static mut (dyn FnMut() + Send)>,
    // TODO: remove these - Box<dyn FnMut> should be good enough
    tx_done_fn: Option<fn()>,
    rx_available_fn: Option<fn()>,
    tx_failed_fn: Option<fn()>,
}

impl Callbacks {
    fn call_tx_done(&mut self) {
        if let Some(cb) = self.tx_done.as_mut() {
            cb();
        }
        if let Some(cb) = self.tx_done_fn.as_mut() {
            cb();
        }
    }

    fn call_rx_available(&mut self) {
        if let Some(cb) = self.rx_available.as_mut() {
            cb();
        }
        if let Some(cb) = self.rx_available_fn.as_mut() {
            cb();
        }
    }

    fn call_tx_failed(&mut self) {
        if let Some(cb) = self.tx_failed.as_mut() {
            cb();
        }
        if let Some(cb) = self.tx_failed_fn.as_mut() {
            cb();
        }
    }
}

static CALLBACKS: NonReentrantMutex<Callbacks> = NonReentrantMutex::new(Callbacks {
    tx_done: None,
    rx_available: None,
    tx_failed: None,
    tx_done_fn: None,
    rx_available_fn: None,
    tx_failed_fn: None,
});

fn tx_done() {
    trace!("tx_done callback");

    CALLBACKS.with(|cbs| cbs.call_tx_done());
}

fn tx_failed() {
    trace!("tx_failed callback");

    CALLBACKS.with(|cbs| cbs.call_tx_failed());
}

fn rx_available() {
    trace!("rx available callback");

    CALLBACKS.with(|cbs| cbs.call_rx_available());
}