Skip to main content

nrf52/
ieee802154_radio.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! IEEE 802.15.4 radio driver for nRF52
6//!
7//! This driver implements a subset of 802.15.4 sending and receiving for the
8//! nRF52840 chip per the nRF52840_PS_v1.0 spec. Upon calling the initialization
9//! function, the chip is powered on and configured to the fields of the Radio
10//! struct. This driver maintains a state machine between receiving,
11//! transmitting, and sending acknowledgements. Because the nRF52840 15.4 radio
12//! chip does not possess hardware support for ACK, this driver implements
13//! software support for sending ACK when a received packet requests to be
14//! acknowledged. The driver currently lacks support to listen for requested ACK
15//! on packets the radio has sent. As of 8/14/23, the driver is able to send and
16//! receive 15.4 packets as used in the basic 15.4 libtock-c apps.
17//!
18//! ## Driver State Machine
19//!
20//! To aid in future implementations, this describes a simplified and concise
21//! version of the nrf52840 radio state machine specification and the state
22//! machine this driver separately maintains.
23//!
24//! To interact with the radio, tasks are issued to the radio which in turn
25//! trigger interrupt events. To receive, the radio must first "ramp up". The
26//! RXRU state is entered by issuing a RXEN task. Once the radio has ramped up
27//! successfully, it is now in the RXIDLE state and triggers a READY interrupt
28//! event. To optimize the radio's operation, this driver enables hardware
29//! shortcuts such that upon receiving the READY event, the radio chip
30//! immediately triggers a START task. The START task notifies the radio to begin
31//! officially "listening for packets" (RX state). Upon completing receiving the
32//! packet, the radio issues an END event. The driver then determines if the
33//! received packet has requested to be acknowledged (bit flag) and sends an ACK
34//! accordingly. Finally, the received packet buffer and accompanying fields are
35//! passed to the registered radio client. This marks the end of a receive cycle
36//! and a new READY event is issued to once again begin listening for packets.
37//!
38//! When a registered radio client wishes to send a packet. The transmit(...)
39//! method is called. To transmit a packet, the radio must first ramp up for
40//! receiving and then perform a clear channel assessment by listening for a
41//! specified period of time to determine if there is "traffic". If traffic is
42//! detected, the radio sets an alarm and waits to perform another CCA after this
43//! backoff. If the channel is determined to be clear, the radio then begins a TX
44//! ramp up, enters a TX state and then sends the packet. To progress through
45//! these states, hardware shortcuts are once again enabled in this driver. The
46//! driver first issues a DISABLE task. A hardware shortcut is enabled so that
47//! upon receipt of the disable task, the radio automatically issues a RXEN task
48//! to enter the RXRU state. Additionally, a shortcut is enabled such that when
49//! the RXREADY event is received, the radio automatically issues a CCA_START
50//! task. Finally, a shortcut is also enabled such that upon receiving a CCAIDLE
51//! event the radio automatically issues a TXEN event to ramp up the radio. The
52//! driver then handles receiving the READY interrupt event and triggers the
53//! START task to begin sending the packet. Upon completing the sending of the
54//! packet, the radio issues an END event, to which the driver then returns the
55//! radio to a receiving mode as described above. (For a more complete
56//! explanation of the radio's operation, refer to nRF52840_PS_v1.0)
57//!
58//! This radio state machine provides nine possible states the radio can exist
59//! in. For ease of implementation and clarity, this driver also maintains a
60//! simplified state machine. These states consist of the radio being off (OFF),
61//! receiving (RX), transmitting (TX), or acknowledging (ACK).
62
63// Author: Tyler Potyondy
64// 8/21/23
65
66use crate::timer::TimerAlarm;
67use core::cell::Cell;
68use kernel::ErrorCode;
69use kernel::deferred_call::{DeferredCall, DeferredCallClient};
70use kernel::hil::radio::{self, PowerClient, RadioChannel, RadioConfig, RadioData};
71use kernel::hil::time::{Alarm, AlarmClient, Time};
72use kernel::utilities::StaticRef;
73use kernel::utilities::cells::{OptionalCell, TakeCell};
74use tock_registers_v0::interfaces::{Readable, Writeable};
75use tock_registers_v0::registers::{ReadOnly, ReadWrite, WriteOnly};
76use tock_registers_v0::{register_bitfields, register_structs};
77
78use crate::constants::TxPower;
79
80const ACK_FLAG: u8 = 0b00100000;
81
82pub const IEEE802154_PAYLOAD_LENGTH: usize = 255;
83pub const IEEE802154_BACKOFF_PERIOD: usize = 320; //microseconds = 20 symbols
84pub const IEEE802154_ACK_TIME: usize = 512; //microseconds = 32 symbols
85pub const IEEE802154_MAX_POLLING_ATTEMPTS: u8 = 4;
86pub const IEEE802154_MIN_BE: u8 = 3;
87pub const IEEE802154_MAX_BE: u8 = 5;
88
89// ACK Requires MHR and MFR fields. More explicitly this is composed of:
90// | Frame Control (2 bytes) | Sequence Number (1 byte) | MFR (2 bytes) |.
91// In total the ACK frame is 5 bytes long + 2 PSDU bytes (7 bytes total).
92const SEQ_NUM_LEN: usize = 1;
93pub const ACK_BUF_SIZE: usize =
94    radio::SPI_HEADER_SIZE + radio::PHR_SIZE + radio::MHR_FC_SIZE + SEQ_NUM_LEN + radio::MFR_SIZE;
95
96/// Where the 15.4 packet from the radio is stored in the buffer.
97///
98/// The HIL reserves one byte at the beginning of the buffer for use by the
99/// capsule/hardware. We have no use for this, but the upper layers expect it so
100/// we skip over it.
101// We can't just drop the byte from the buffer because then it would be lost
102// forever when we tried to return the frame buffer.
103const BUF_PREFIX_SIZE: u32 = 1;
104
105register_structs! {
106    pub RadioRegisters {
107        /// Enable Radio in TX mode
108        (0x000 => task_txen: WriteOnly<u32, Task::Register>),
109        /// Enable Radio in RX mode
110        (0x004 => task_rxen: WriteOnly<u32, Task::Register>),
111        /// Start Radio
112        (0x008 => task_start: WriteOnly<u32, Task::Register>),
113        /// Stop Radio
114        (0x00C => task_stop: WriteOnly<u32, Task::Register>),
115        /// Disable Radio
116        (0x010 => task_disable: WriteOnly<u32, Task::Register>),
117        /// Start the RSSI and take one single sample of the receive signal strength
118        (0x014 => task_rssistart: WriteOnly<u32, Task::Register>),
119        /// Stop the RSSI measurement
120        (0x018 => task_rssistop: WriteOnly<u32, Task::Register>),
121        /// Start the bit counter
122        (0x01C => task_bcstart: WriteOnly<u32, Task::Register>),
123        /// Stop the bit counter
124        (0x020 => task_bcstop: WriteOnly<u32, Task::Register>),
125        (0x024 => _reserved1),
126        /// Start the CCA
127        (0x02C => task_ccastart: WriteOnly<u32, Task::Register>),
128        /// Stop the CCA
129        (0x030 => task_ccastop: WriteOnly<u32, Task::Register>),
130        (0x034 => _reserved2),
131        /// Radio has ramped up and is ready to be started
132        (0x100 => event_ready: ReadWrite<u32, Event::Register>),
133        /// Address sent or received
134        (0x104 => event_address: ReadWrite<u32, Event::Register>),
135        /// Packet payload sent or received
136        (0x108 => event_payload: ReadWrite<u32, Event::Register>),
137        /// Packet sent or received
138        (0x10C => event_end: ReadWrite<u32, Event::Register>),
139        /// Radio has been disabled
140        (0x110 => event_disabled: ReadWrite<u32, Event::Register>),
141        /// A device address match occurred on the last received packet
142        (0x114 => event_devmatch: ReadWrite<u32>),
143        /// No device address match occurred on the last received packet
144        (0x118 => event_devmiss: ReadWrite<u32, Event::Register>),
145        /// Sampling of receive signal strength complete
146        (0x11C => event_rssiend: ReadWrite<u32, Event::Register>),
147        (0x120 => _reserved3),
148        /// Bit counter reached bit count value
149        (0x128 => event_bcmatch: ReadWrite<u32, Event::Register>),
150        (0x12C => _reserved4),
151        /// Packet received with CRC ok
152        (0x130 => event_crcok: ReadWrite<u32, Event::Register>),
153        /// Packet received with CRC error
154        (0x134 => crcerror: ReadWrite<u32, Event::Register>),
155        /// IEEE 802.15.4 length field received
156        (0x138 => event_framestart: ReadWrite<u32, Event::Register>),
157        (0x13C => _reserved5),
158        /// Wireless medium in idle - clear to send
159        (0x144 => event_ccaidle: ReadWrite<u32, Event::Register>),
160        /// Wireless medium busy - do not send
161        (0x148 => event_ccabusy: ReadWrite<u32, Event::Register>),
162        (0x14C => _reserved6),
163        /// Shortcut register
164        (0x200 => shorts: ReadWrite<u32, Shortcut::Register>),
165        (0x204 => _reserved7),
166        /// Enable interrupt
167        (0x304 => intenset: ReadWrite<u32, Interrupt::Register>),
168        /// Disable interrupt
169        (0x308 => intenclr: ReadWrite<u32, Interrupt::Register>),
170        (0x30C => _reserved8),
171        /// CRC status
172        (0x400 => crcstatus: ReadOnly<u32, Event::Register>),
173        (0x404 => _reserved9),
174        /// Received address
175        (0x408 => rxmatch: ReadOnly<u32, ReceiveMatch::Register>),
176        /// CRC field of previously received packet
177        (0x40C => rxcrc: ReadOnly<u32, ReceiveCrc::Register>),
178        /// Device address match index
179        (0x410 => dai: ReadOnly<u32, DeviceAddressIndex::Register>),
180        (0x414 => _reserved10),
181        /// Packet pointer
182        (0x504 => packetptr: ReadWrite<u32, PacketPointer::Register>),
183        /// Frequency
184        (0x508 => frequency: ReadWrite<u32, Frequency::Register>),
185        /// Output power
186        (0x50C => txpower: ReadWrite<u32, TransmitPower::Register>),
187        /// Data rate and modulation
188        (0x510 => mode: ReadWrite<u32, Mode::Register>),
189        /// Packet configuration register 0
190        (0x514 => pcnf0: ReadWrite<u32, PacketConfiguration0::Register>),
191        /// Packet configuration register 1
192        (0x518 => pcnf1: ReadWrite<u32, PacketConfiguration1::Register>),
193        /// Base address 0
194        (0x51C => base0: ReadWrite<u32, BaseAddress::Register>),
195        /// Base address 1
196        (0x520 => base1: ReadWrite<u32, BaseAddress::Register>),
197        /// Prefix bytes for logical addresses 0-3
198        (0x524 => prefix0: ReadWrite<u32, Prefix0::Register>),
199        /// Prefix bytes for logical addresses 4-7
200        (0x528 => prefix1: ReadWrite<u32, Prefix1::Register>),
201        /// Transmit address select
202        (0x52C => txaddress: ReadWrite<u32, TransmitAddress::Register>),
203        /// Receive address select
204        (0x530 => rxaddresses: ReadWrite<u32, ReceiveAddresses::Register>),
205        /// CRC configuration
206        (0x534 => crccnf: ReadWrite<u32, CrcConfiguration::Register>),
207        /// CRC polynomial
208        (0x538 => crcpoly: ReadWrite<u32, CrcPolynomial::Register>),
209        /// CRC initial value
210        (0x53C => crcinit: ReadWrite<u32, CrcInitialValue::Register>),
211        (0x540 => _reserved11),
212        /// Interframe spacing in microseconds
213        (0x544 => tifs: ReadWrite<u32, InterFrameSpacing::Register>),
214        /// RSSI sample
215        (0x548 => rssisample: ReadWrite<u32, RssiSample::Register>),
216        (0x54C => _reserved12),
217        /// Current radio state
218        (0x550 => state: ReadOnly<u32, State::Register>),
219        /// Data whitening initial value
220        (0x554 => datawhiteiv: ReadWrite<u32, DataWhiteIv::Register>),
221        (0x558 => _reserved13),
222        /// Bit counter compare
223        (0x560 => bcc: ReadWrite<u32, BitCounterCompare::Register>),
224        (0x564 => _reserved14),
225        /// Device address base segments
226        (0x600 => dab: [ReadWrite<u32, DeviceAddressBase::Register>; 8]),
227        /// Device address prefix
228        (0x620 => dap: [ReadWrite<u32, DeviceAddressPrefix::Register>; 8]),
229        /// Device address match configuration
230        (0x640 => dacnf: ReadWrite<u32, DeviceAddressMatch::Register>),
231        /// MAC header Search Pattern Configuration
232        (0x644 => mhrmatchconf: ReadWrite<u32, MACHeaderSearch::Register>),
233        /// MAC Header Search Pattern Mask
234        (0x648 => mhrmatchmas: ReadWrite<u32, MACHeaderMask::Register>),
235        (0x64C => _reserved15),
236        /// Radio mode configuration register
237        (0x650 => modecnf0: ReadWrite<u32, RadioModeConfig::Register>),
238        (0x654 => _reserved16),
239        /// Clear Channel Assesment (CCA) control register
240        (0x66C => ccactrl: ReadWrite<u32, CCAControl::Register>),
241        (0x670 => _reserved17),
242        /// Peripheral power control
243        (0xFFC => power: ReadWrite<u32, Task::Register>),
244        (0x1000 => @END),
245    }
246}
247
248register_bitfields! [u32,
249    /// Task register
250    Task [
251        /// Enable task
252        ENABLE OFFSET(0) NUMBITS(1)
253    ],
254    /// Event register
255    Event [
256        /// Ready event
257        READY OFFSET(0) NUMBITS(1)
258    ],
259    /// Shortcut register
260    Shortcut [
261        /// Shortcut between READY event and START task
262        READY_START OFFSET(0) NUMBITS(1),
263        /// Shortcut between END event and DISABLE task
264        END_DISABLE OFFSET(1) NUMBITS(1),
265        /// Shortcut between DISABLED event and TXEN task
266        DISABLED_TXEN OFFSET(2) NUMBITS(1),
267        /// Shortcut between DISABLED event and RXEN task
268        DISABLED_RXEN OFFSET(3) NUMBITS(1),
269        /// Shortcut between ADDRESS event and RSSISTART task
270        ADDRESS_RSSISTART OFFSET(4) NUMBITS(1),
271        /// Shortcut between END event and START task
272        END_START OFFSET(5) NUMBITS(1),
273        /// Shortcut between ADDRESS event and BCSTART task
274        ADDRESS_BCSTART OFFSET(6) NUMBITS(1),
275        /// Shortcut between DISABLED event and RSSISTOP task
276        DISABLED_RSSISTOP OFFSET(8) NUMBITS(1),
277        /// Shortcut between CCAIDLE_TXEN
278        CCAIDLE_TXEN OFFSET(12) NUMBITS(1),
279        /// Shortcut between RXREADY_CCASTART
280        RXREADY_CCASTART OFFSET(11) NUMBITS(1),
281        /// Shortcut between TXREADY event and START task
282        TXREADY_START OFFSET(19) NUMBITS(1),
283
284    ],
285    /// Interrupt register
286    Interrupt [
287        /// READY event
288        READY OFFSET(0) NUMBITS(1),
289        /// ADDRESS event
290        ADDRESS OFFSET(1) NUMBITS(1),
291        /// PAYLOAD event
292        PAYLOAD OFFSET(2) NUMBITS(1),
293        /// END event
294        END OFFSET(3) NUMBITS(1),
295        /// DISABLED event
296        DISABLED OFFSET(4) NUMBITS(1),
297        /// DEVMATCH event
298        DEVMATCH OFFSET(5) NUMBITS(1),
299        /// DEVMISS event
300        DEVMISS OFFSET(6) NUMBITS(1),
301        /// RSSIEND event
302        RSSIEND OFFSET(7) NUMBITS(1),
303        /// BCMATCH event
304        BCMATCH OFFSET(10) NUMBITS(1),
305        /// CRCOK event
306        CRCOK OFFSET(12) NUMBITS(1),
307        /// CRCERROR event
308        CRCERROR OFFSET(13) NUMBITS(1),
309        /// CCAIDLE event
310        FRAMESTART OFFSET(14) NUMBITS(1),
311        /// CCAIDLE event
312        CCAIDLE OFFSET(17) NUMBITS(1),
313        /// CCABUSY event
314        CCABUSY OFFSET(18) NUMBITS(1),
315        /// TXREADY event
316        TXREADY OFFSET(21) NUMBITS(1),
317        /// RXREADY event
318        RXREADY OFFSET(22) NUMBITS(1),
319    ],
320    /// Receive match register
321    ReceiveMatch [
322        /// Logical address of which previous packet was received
323        MATCH OFFSET(0) NUMBITS(3)
324    ],
325    /// Received CRC register
326    ReceiveCrc [
327        /// CRC field of previously received packet
328        CRC OFFSET(0) NUMBITS(24)
329    ],
330    /// Device address match index register
331    DeviceAddressIndex [
332        /// Device address match index
333        /// Index (n) of device address, see DAB\[n\] and DAP\[n\], that got an
334        /// address match
335        INDEX OFFSET(0) NUMBITS(3)
336    ],
337    /// Packet pointer register
338    PacketPointer [
339        /// Packet address to be used for the next transmission or reception. When transmitting, the packet pointed to by this
340        /// address will be transmitted and when receiving, the received packet will be written to this address. This address is a byte
341        /// aligned ram address.
342        POINTER OFFSET(0) NUMBITS(32)
343    ],
344    /// Frequency register
345    Frequency [
346        /// Radio channel frequency
347        /// Frequency = 2400 + FREQUENCY (MHz)
348        FREQUENCY OFFSET(0) NUMBITS(7) [],
349        /// Channel map selection.
350        /// Channel map between 2400 MHZ .. 2500 MHZ
351        MAP OFFSET(8) NUMBITS(1) [
352            DEFAULT = 0,
353            LOW = 1
354        ]
355    ],
356    /// Transmitting power register
357    TransmitPower [
358        /// Radio output power
359        POWER OFFSET(0) NUMBITS(8) [
360            POS4DBM = 4,
361            POS3DBM = 3,
362            ODBM = 0,
363            NEG4DBM = 0xfc,
364            NEG8DBM = 0xf8,
365            NEG12DBM = 0xf4,
366            NEG16DBM = 0xf0,
367            NEG20DBM = 0xec,
368            NEG40DBM = 0xd8
369        ]
370    ],
371    /// Data rate and modulation register
372    Mode [
373        /// Radio data rate and modulation setting.
374        /// The radio supports Frequency-shift Keying (FSK) modulation
375        MODE OFFSET(0) NUMBITS(4) [
376            NRF_1MBIT = 0,
377            NRF_2MBIT = 1,
378            NRF_250KBIT = 2,
379            BLE_1MBIT = 3,
380            BLE_2MBIT = 4,
381            BLE_LR125KBIT = 5,
382            BLE_LR500KBIT = 6,
383            IEEE802154_250KBIT = 15
384        ]
385    ],
386    /// Packet configuration register 0
387    PacketConfiguration0 [
388        /// Length on air of LENGTH field in number of bits
389        LFLEN OFFSET(0) NUMBITS(4) [],
390        /// Length on air of S0 field in number of bytes
391        S0LEN OFFSET(8) NUMBITS(1) [],
392        /// Length on air of S1 field in number of bits.
393        S1LEN OFFSET(16) NUMBITS(4) [],
394        /// Include or exclude S1 field in RAM
395        S1INCL OFFSET(20) NUMBITS(1) [
396            AUTOMATIC = 0,
397            INCLUDE = 1
398        ],
399        /// Length of preamble on air. Decision point: TASKS_START task
400        PLEN OFFSET(24) NUMBITS(2) [
401            EIGHT = 0,
402            SIXTEEN = 1,
403            THIRTYTWOZEROS = 2,
404            LONGRANGE = 3
405        ],
406        CRCINC OFFSET(26) NUMBITS(1) [
407            EXCLUDE = 0,
408            INCLUDE = 1
409        ]
410    ],
411    /// Packet configuration register 1
412    PacketConfiguration1 [
413        /// Maximum length of packet payload
414        MAXLEN OFFSET(0) NUMBITS(8) [],
415        /// Static length in number of bytes
416        STATLEN OFFSET(8) NUMBITS(8) [],
417        /// Base address length in number of bytes
418        BALEN OFFSET(16) NUMBITS(3) [],
419        /// On air endianness
420        ENDIAN OFFSET(24) NUMBITS(1) [
421            LITTLE = 0,
422            BIG = 1
423        ],
424        /// Enable or disable packet whitening
425        WHITEEN OFFSET(25) NUMBITS(1) [
426            DISABLED = 0,
427            ENABLED = 1
428        ]
429    ],
430    /// Radio base address register
431    BaseAddress [
432        /// BASE0 or BASE1
433        BASE OFFSET(0) NUMBITS(32)
434    ],
435    /// Radio prefix0 registers
436    Prefix0 [
437        /// Address prefix 0
438        AP0 OFFSET(0) NUMBITS(8),
439        /// Address prefix 1
440        AP1 OFFSET(8) NUMBITS(8),
441        /// Address prefix 2
442        AP2 OFFSET(16) NUMBITS(8),
443        /// Address prefix 3
444        AP3 OFFSET(24) NUMBITS(8)
445    ],
446    /// Radio prefix0 registers
447    Prefix1 [
448        /// Address prefix 4
449        AP4 OFFSET(0) NUMBITS(8),
450        /// Address prefix 5
451        AP5 OFFSET(8) NUMBITS(8),
452        /// Address prefix 6
453        AP6 OFFSET(16) NUMBITS(8),
454        /// Address prefix 7
455        AP7 OFFSET(24) NUMBITS(8)
456    ],
457    /// Transmit address register
458    TransmitAddress [
459        /// Logical address to be used when transmitting a packet
460        ADDRESS OFFSET(0) NUMBITS(3)
461    ],
462    /// Receive addresses register
463    ReceiveAddresses [
464        /// Enable or disable reception on logical address 0-7
465        ADDRESS OFFSET(0) NUMBITS(8)
466    ],
467    /// CRC configuration register
468    CrcConfiguration [
469        /// CRC length in bytes
470        LEN OFFSET(0) NUMBITS(2) [
471            DISABLED = 0,
472            ONE = 1,
473            TWO = 2,
474            THREE = 3
475        ],
476        /// Include or exclude packet field from CRC calculation
477        SKIPADDR OFFSET(8) NUMBITS(2) [
478            INCLUDE = 0,
479            EXCLUDE = 1,
480            IEEE802154 = 2
481        ]
482    ],
483    /// CRC polynomial register
484    CrcPolynomial [
485        /// CRC polynomial
486        CRCPOLY OFFSET(0) NUMBITS(24)
487    ],
488    /// CRC initial value register
489    CrcInitialValue [
490       /// Initial value for CRC calculation
491       CRCINIT OFFSET(0) NUMBITS(24)
492    ],
493    /// Inter Frame Spacing in us register
494    InterFrameSpacing [
495        /// Inter Frame Spacing in us
496        /// Inter frame space is the time interval between two consecutive packets. It is defined as the time, in micro seconds, from the
497        /// end of the last bit of the previous packet to the start of the first bit of the subsequent packet
498        TIFS OFFSET(0) NUMBITS(8)
499    ],
500    /// RSSI sample register
501    RssiSample [
502        /// RSSI sample result
503        RSSISAMPLE OFFSET(0) NUMBITS(7)
504    ],
505    /// Radio state register
506    State [
507        /// Current radio state
508        STATE OFFSET(0) NUMBITS(4) [
509            DISABLED = 0,
510            RXRU = 1,
511            RXIDLE = 2,
512            RX = 3,
513            RXDISABLED = 4,
514            TXRU = 9,
515            TXIDLE = 10,
516            TX = 11,
517            TXDISABLED = 12
518        ]
519    ],
520    /// Data whitening initial value register
521    DataWhiteIv [
522        /// Data whitening initial value. Bit 6 is hard-wired to '1', writing '0'
523        /// to it has no effect, and it will always be read back and used by the device as '1'
524        DATEWHITEIV OFFSET(0) NUMBITS(7)
525    ],
526    /// Bit counter compare register
527    BitCounterCompare [
528        /// Bit counter compare
529        BCC OFFSET(0) NUMBITS(32)
530    ],
531    /// Device address base register
532    DeviceAddressBase [
533        /// Device address base 0-7
534        DAB OFFSET(0) NUMBITS(32)
535    ],
536    /// Device address prefix register
537    DeviceAddressPrefix [
538        /// Device address prefix 0-7
539        DAP OFFSET(0) NUMBITS(32)
540    ],
541    /// Device address match configuration register
542    DeviceAddressMatch [
543        /// Enable or disable device address matching on 0-7
544        ENA OFFSET(0) NUMBITS(8),
545        /// TxAdd for device address 0-7
546        TXADD OFFSET(8) NUMBITS(8)
547    ],
548    MACHeaderSearch [
549        CONFIG OFFSET(0) NUMBITS(32)
550    ],
551    MACHeaderMask [
552        PATTERN OFFSET(0) NUMBITS(32)
553    ],
554    CCAControl [
555        CCAMODE OFFSET(0) NUMBITS(3) [
556            ED_MODE = 0,
557            CARRIER_MODE = 1,
558            CARRIER_AND_ED_MODE = 2,
559            CARRIER_OR_ED_MODE = 3,
560            ED_MODE_TEST_1 = 4
561        ],
562        CCAEDTHRESH OFFSET(8) NUMBITS(8) [],
563        CCACORRTHRESH OFFSET(16) NUMBITS(8) [],
564        CCACORRCNT OFFSET(24) NUMBITS(8) []
565    ],
566    /// Radio mode configuration register
567    RadioModeConfig [
568        /// Radio ramp-up time
569        RU OFFSET(0) NUMBITS(1) [
570            DEFAULT = 0,
571            FAST = 1
572        ],
573        /// Default TX value
574        /// Specifies what the RADIO will transmit when it is not started, i.e. between:
575        /// RADIO.EVENTS_READY and RADIO.TASKS_START
576        /// RADIO.EVENTS_END and RADIO.TASKS_START
577        DTX OFFSET(8) NUMBITS(2) [
578            B1 = 0,
579            B0 = 1,
580            CENTER = 2
581        ]
582    ]
583];
584
585/// Operating mode of the radio.
586#[derive(Debug, Clone, Copy, PartialEq)]
587enum RadioState {
588    /// Radio peripheral is off.
589    OFF,
590    /// Currently transmitting a packet.
591    TX,
592    /// Default state when radio is on. Radio is configured to be in RX mode
593    /// when the radio is turned on but not transmitting.
594    RX,
595    /// Transmitting an acknowledgement packet.
596    ACK,
597}
598
599/// We use a single deferred call for two operations: triggering config clients
600/// and power change clients. This allows us to track which operation we need to
601/// perform when we get the deferred call callback.
602#[derive(Debug, Clone, Copy)]
603enum DeferredOperation {
604    /// Waiting to notify that the configuration operation is complete.
605    ConfigClientCallback,
606    /// Waiting to notify that the power state of the radio changed (ie it
607    /// turned on or off).
608    PowerClientCallback,
609}
610
611pub struct Radio<'a> {
612    registers: StaticRef<RadioRegisters>,
613    rx_client: OptionalCell<&'a dyn radio::RxClient>,
614    tx_client: OptionalCell<&'a dyn radio::TxClient>,
615    config_client: OptionalCell<&'a dyn radio::ConfigClient>,
616    power_client: OptionalCell<&'a dyn radio::PowerClient>,
617    tx_power: Cell<TxPower>,
618    tx_buf: TakeCell<'static, [u8]>,
619    rx_buf: TakeCell<'static, [u8]>,
620    ack_buf: TakeCell<'static, [u8]>,
621    addr: Cell<u16>,
622    addr_long: Cell<[u8; 8]>,
623    pan: Cell<u16>,
624    cca_count: Cell<u8>,
625    cca_be: Cell<u8>,
626    random_nonce: Cell<u32>,
627    channel: Cell<RadioChannel>,
628    timer0: OptionalCell<&'a TimerAlarm<'a>>,
629    state: Cell<RadioState>,
630    deferred_call: DeferredCall,
631    deferred_call_operation: OptionalCell<DeferredOperation>,
632}
633
634impl AlarmClient for Radio<'_> {
635    fn alarm(&self) {
636        // This alarm function is the callback for when the CCA backoff alarm completes
637        // Attempt a new CCA period by issuing CCASTART task
638        self.registers.task_ccastart.write(Task::ENABLE::SET);
639    }
640}
641
642impl<'a> Radio<'a> {
643    pub fn new(
644        registers: StaticRef<RadioRegisters>,
645        ack_buf: &'static mut [u8; ACK_BUF_SIZE],
646    ) -> Self {
647        Self {
648            registers,
649            rx_client: OptionalCell::empty(),
650            tx_client: OptionalCell::empty(),
651            config_client: OptionalCell::empty(),
652            power_client: OptionalCell::empty(),
653            tx_power: Cell::new(TxPower::ZerodBm),
654            tx_buf: TakeCell::empty(),
655            rx_buf: TakeCell::empty(),
656            ack_buf: TakeCell::new(ack_buf),
657            addr: Cell::new(0),
658            addr_long: Cell::new([0x00; 8]),
659            pan: Cell::new(0),
660            cca_count: Cell::new(0),
661            cca_be: Cell::new(0),
662            random_nonce: Cell::new(0xDEADBEEF),
663            channel: Cell::new(RadioChannel::Channel26),
664            timer0: OptionalCell::empty(),
665            state: Cell::new(RadioState::OFF),
666            deferred_call: DeferredCall::new(),
667            deferred_call_operation: OptionalCell::empty(),
668        }
669    }
670
671    pub fn set_timer_ref(&self, timer: &'a crate::timer::TimerAlarm<'a>) {
672        self.timer0.set(timer);
673    }
674
675    pub fn is_enabled(&self) -> bool {
676        self.registers
677            .mode
678            .matches_all(Mode::MODE::IEEE802154_250KBIT)
679    }
680
681    fn rx(&self) {
682        self.state.set(RadioState::RX);
683
684        // Unwrap fail = Radio RX Buffer is missing (may be due to receive client not replacing in receive(...) method,
685        // or some instance in  driver taking buffer without properly replacing).
686        let rbuf = self.rx_buf.take().unwrap();
687        self.rx_buf.replace(self.set_dma_ptr(rbuf));
688
689        // Instruct radio hardware to automatically progress from RXIDLE to RX
690        // state upon receipt of internal `READY` signal after radio ramp-up completes.
691        self.registers.shorts.write(Shortcut::READY_START::SET);
692
693        self.registers.task_rxen.write(Task::ENABLE::SET);
694    }
695
696    fn radio_on(&self) {
697        // reset and enable power
698        self.registers.power.write(Task::ENABLE::CLEAR);
699        self.registers.power.write(Task::ENABLE::SET);
700    }
701
702    fn radio_off(&self) {
703        self.state.set(RadioState::OFF);
704
705        self.registers.power.write(Task::ENABLE::CLEAR);
706    }
707
708    fn radio_is_on(&self) -> bool {
709        self.registers.power.is_set(Task::ENABLE)
710    }
711
712    fn set_dma_ptr(&self, buffer: &'static mut [u8]) -> &'static mut [u8] {
713        self.registers
714            .packetptr
715            .set(buffer.as_ptr() as u32 + BUF_PREFIX_SIZE);
716        buffer
717    }
718
719    fn crc_check(&self) -> Result<(), ErrorCode> {
720        if self.registers.crcstatus.is_set(Event::READY) {
721            Ok(())
722        } else {
723            Err(ErrorCode::FAIL)
724        }
725    }
726
727    // TODO: RECEIVING ACK FOR A SENT TX IS NOT IMPLEMENTED
728    //
729    // As a general note for the interrupt handler, event registers must still
730    // be cleared even when hardware shortcuts are enabled.
731    #[inline(never)]
732    pub fn handle_interrupt(&self) {
733        self.disable_all_interrupts();
734
735        let mut start_task = false;
736        let mut rx_init = false;
737
738        match self.state.get() {
739            // It should not be possible to receive an interrupt while the
740            // tracked radio state is OFF.
741            RadioState::OFF => {
742                kernel::debug!("[ERROR]--15.4 state machine");
743                kernel::debug!("Received interrupt while off");
744            }
745            RadioState::RX => {
746                ////////////////////////////////////////////////////////////////
747                // NOTE: This state machine assumes that the READY_START
748                // shortcut is enabled at this point in time. If the READY_START
749                // shortcut is not enabled, the state machine/driver will likely
750                // exhibit undefined behavior.
751                ////////////////////////////////////////////////////////////////
752
753                // Since READY_START shortcut enabled, always clear READY event
754                self.registers.event_ready.write(Event::READY::CLEAR);
755
756                // Completed receiving a packet, now determine if we need to send ACK
757                if self.registers.event_end.is_set(Event::READY) {
758                    self.registers.event_end.write(Event::READY::CLEAR);
759                    let crc = self.crc_check();
760
761                    // Unwrap fail = Radio RX Buffer is missing (may be due to
762                    // receive client not replacing in receive(...) method, or
763                    // some instance in driver taking buffer without properly
764                    // replacing).
765                    let rbuf = self.rx_buf.take().unwrap();
766
767                    // Data buffer format: | PREFIX | PHR | PSDU | LQI |
768                    //
769                    // Retrieve the length of the PSDU (actual frame). The frame
770                    // length is only 7 bits, but of course the field is a byte.
771                    // The nRF52840 product specification says this about the
772                    // PHR byte (Version 1.8, section 6.20.12.1):
773                    //
774                    // > The most significant bit is reserved and is set to zero
775                    // > for frames that are standard compliant. The radio
776                    // > module will report all eight bits and it can
777                    // > potentially be used to carry some information.
778                    //
779                    // We are not using that for any information so we just
780                    // force it to zero. This ensures that `data_len` will not
781                    // be longer than our buffer.
782                    let data_len = (rbuf[radio::PHR_OFFSET] & 0x7F) as usize;
783
784                    // LQI is found just after the data received.
785                    let lqi = rbuf[data_len];
786
787                    // We drop the CRC bytes (the MFR) from our frame.
788                    let frame_len = data_len - radio::MFR_SIZE;
789
790                    // 6th bit in the first byte of the MAC header determines if
791                    // sender requested ACK. If so send ACK first before handing
792                    // packet reception. This optimizes the time taken to send
793                    // an ACK. If we call the receive function here, there is a
794                    // non deterministic time required to complete the function
795                    // as it may be passed up the entirety of the networking
796                    // stack (leading to ACK timeout being exceeded).
797                    if rbuf[radio::PSDU_OFFSET] & ACK_FLAG != 0 && crc.is_ok() {
798                        self.ack_buf
799                            .take()
800                            .map_or(Err(ErrorCode::NOMEM), |ack_buf| {
801                                // Entered ACK state //
802                                self.state.set(RadioState::ACK);
803
804                                // 4th byte of received packet is the 15.4
805                                // sequence number.
806                                let sequence_number = rbuf[radio::PSDU_OFFSET + radio::MHR_FC_SIZE];
807
808                                // The frame control field is hardcoded for now;
809                                // this is the only possible type of ACK
810                                // currently supported so it is reasonable to
811                                // hardcode this.
812                                ack_buf[radio::PSDU_OFFSET] = 2;
813                                ack_buf[radio::PSDU_OFFSET + 1] = 0;
814                                ack_buf[radio::PSDU_OFFSET + radio::MHR_FC_SIZE] = sequence_number;
815
816                                // Ensure we replace our RX buffer for the time
817                                // being.
818                                self.rx_buf.replace(rbuf);
819
820                                // If the transmit function fails, replace the
821                                // buffer and return an error.
822                                if let Err((_, ret_buf)) = self.transmit(ack_buf, 3) {
823                                    self.ack_buf.replace(ret_buf);
824                                    Err(ErrorCode::FAIL)
825                                } else {
826                                    Ok(())
827                                }
828                            })
829                            .unwrap_or_else(|err| {
830                                // The ACK was not sent; we do not need to drop
831                                // the packet, but print msg for debugging
832                                // purposes, notify receive client of packet,
833                                // and reset radio to receiving.
834                                self.rx_client.map(|client| {
835                                    start_task = true;
836                                    client.receive(
837                                        self.rx_buf.take().unwrap(),
838                                        frame_len,
839                                        lqi,
840                                        crc.is_ok(),
841                                        Err(err),
842                                    );
843                                });
844
845                                kernel::debug!(
846                                    "[ACKFail] Failed sending ACK in response to received packet."
847                                );
848                            });
849                    } else {
850                        // Packet received that does not require an ACK. Pass
851                        // received packet to client and return radio to general
852                        // receiving state to listen for new packets.
853                        self.rx_client.map(|client| {
854                            start_task = true;
855                            client.receive(rbuf, frame_len, lqi, crc.is_ok(), Ok(()));
856                        });
857                    }
858                }
859            }
860            RadioState::TX => {
861                ////////////////////////////////////////////////////////////////
862                // NOTE: This state machine assumes that the DISABLED_RXEN,
863                // CCAIDLE_TXEN, RXREADY_CCASTART shortcuts are enabled at this
864                // point in time. If the READY_START shortcut is not enabled,
865                // the state machine/driver will likely exhibit undefined
866                // behavior.
867                ////////////////////////////////////////////////////////////////
868
869                // Handle Event_ready interrupt. The TX path performs both a TX
870                // ramp up and an RX ramp up. This means that there are two
871                // potential cases we must handle. The ready event due to the Rx
872                // Ramp up shortcuts to the CCASTART while the ready event due
873                // to the Tx ramp up requires we issue a start task in response
874                // to progress the state machine.
875                if self.registers.event_ready.is_set(Event::READY) {
876                    // In both cases, we must clear event
877                    self.registers.event_ready.write(Event::READY::CLEAR);
878
879                    // Ready event from Tx ramp up will be in radio internal
880                    // TXIDLE state
881                    if self.registers.state.get() == crate::constants::RADIO_STATE_TXIDLE {
882                        start_task = true;
883                    }
884                }
885
886                // Handle CCA related interrupts.
887                if self.registers.event_ccabusy.is_set(Event::READY) {
888                    self.registers.event_ccabusy.write(Event::READY::CLEAR);
889
890                    // Need to back off for a period of time outlined in the
891                    // IEEE 802.15.4 standard (see Figure 69 in section 7.5.1.4
892                    // The CSMA-CA algorithm of the standard).
893                    if self.cca_count.get() < IEEE802154_MAX_POLLING_ATTEMPTS {
894                        self.cca_count.set(self.cca_count.get() + 1);
895                        self.cca_be.set(self.cca_be.get() + 1);
896                        let backoff_periods = self.random_nonce() & ((1 << self.cca_be.get()) - 1);
897                        let current_time = self.timer0.unwrap_or_panic().now();
898                        self.timer0
899                            .unwrap_or_panic() // Unwrap fail = Missing timer reference for CSMA
900                            .set_alarm(
901                                current_time,
902                                kernel::hil::time::Ticks32::from(
903                                    backoff_periods * (IEEE802154_BACKOFF_PERIOD as u32),
904                                ),
905                            );
906                    } else {
907                        // We have exceeded the IEEE802154_MAX_POLLING_ATTEMPTS
908                        // and should fail the transmission/return buffer to
909                        // sending client.
910
911                        let result = Err(ErrorCode::BUSY);
912                        self.tx_client.map(|client| {
913                            // Unwrap fail = TX Buffer is missing and was
914                            // mistakenly not replaced after completion of
915                            // set_dma_ptr(...)
916                            let tbuf = self.tx_buf.take().unwrap();
917                            client.send_done(tbuf, false, result);
918                        });
919                        rx_init = true;
920                    }
921                }
922
923                // End event received; The TX is now finished and we need to
924                // notify the sending client.
925                if self.registers.event_end.is_set(Event::READY) {
926                    self.registers.event_end.write(Event::READY::CLEAR);
927                    let result = Ok(());
928
929                    // TODO: Acked is hardcoded to always return false; add
930                    // support to receive tx ACK.
931                    self.tx_client.map(|client| {
932                        // Unwrap fail = TX Buffer is missing and was mistakenly
933                        // not replaced after completion of set_dma_ptr(...)
934                        let tbuf = self.tx_buf.take().unwrap();
935                        client.send_done(tbuf, false, result);
936                    });
937                    rx_init = true;
938                }
939            }
940            RadioState::ACK => {
941                ////////////////////////////////////////////////////////////////
942                // NOTE: This state machine assumes that the READY_START
943                // shortcut is enabled at this point in time. If the READY_START
944                // shortcut is not enabled, the state machine/driver will likely
945                // exhibit undefined behavior.
946                ////////////////////////////////////////////////////////////////
947
948                // Since READY_START shortcut enabled, always clear READY event
949                self.registers.event_ready.write(Event::READY::CLEAR);
950
951                // Completed sending ACK
952                if self.registers.event_end.is_set(Event::READY) {
953                    self.registers.event_end.write(Event::READY::CLEAR);
954
955                    // Unwrap fail = TX Buffer is missing and was mistakenly not
956                    // replaced after completion of set_dma_ptr(...)
957                    let tbuf = self.tx_buf.take().unwrap();
958
959                    // We must replace the ACK buffer that was passed to tx_buf
960                    self.ack_buf.replace(tbuf);
961
962                    // Reset radio to proper receiving state
963                    rx_init = true;
964
965                    // Notify receive client of packet that triggered the ACK.
966                    self.rx_client.map(|client| {
967                        // Unwrap fail = Radio RX Buffer is missing (may be due
968                        // to receive client not replacing in receive(...)
969                        // method, or some instance in  driver taking buffer
970                        // without properly replacing).
971                        let rbuf = self.rx_buf.take().unwrap();
972
973                        // Data buffer format: | PREFIX | PHR | PSDU | LQI |
974                        //
975                        // See the RX case above for how these values are set.
976                        let data_len = (rbuf[radio::PHR_OFFSET] & 0x7F) as usize;
977                        let lqi = rbuf[data_len];
978                        let frame_len = data_len - radio::MFR_SIZE;
979
980                        // We know the CRC passed because otherwise we would not
981                        // have transmitted an ACK.
982                        client.receive(rbuf, frame_len, lqi, true, Ok(()));
983                    });
984                }
985            }
986        }
987
988        // Enabling hardware shortcuts allows for a much faster operation.
989        // However, this can also lead to race conditions and strange edge
990        // cases. Namely, if a task_start or rx_en is set while interrupts are
991        // disabled, the event_end interrupt can be "missed" and the interrupt
992        // handler will not be called. If the event is missed, the state machine
993        // is unable to progress and the driver enters a deadlock.
994        self.enable_interrupts();
995        if rx_init {
996            self.rx();
997        }
998        if start_task {
999            self.registers.task_start.write(Task::ENABLE::SET);
1000        }
1001    }
1002
1003    pub fn enable_interrupts(&self) {
1004        self.registers
1005            .intenset
1006            .write(Interrupt::READY::SET + Interrupt::CCABUSY::SET + Interrupt::END::SET);
1007    }
1008
1009    pub fn enable_interrupt(&self, intr: u32) {
1010        self.registers.intenset.set(intr);
1011    }
1012
1013    pub fn clear_interrupt(&self, intr: u32) {
1014        self.registers.intenclr.set(intr);
1015    }
1016
1017    pub fn disable_all_interrupts(&self) {
1018        // disable all possible interrupts
1019        self.registers.intenclr.set(0xffffffff);
1020    }
1021
1022    pub fn set_ack_buffer(&self, buffer: &'static mut [u8]) {
1023        self.ack_buf.replace(buffer);
1024    }
1025
1026    fn radio_initialize(&self) {
1027        self.radio_on();
1028
1029        // CONFIGURE RADIO //
1030        self.ieee802154_set_channel_rate();
1031
1032        self.ieee802154_set_packet_config();
1033
1034        self.ieee802154_set_crc_config();
1035
1036        self.ieee802154_set_rampup_mode();
1037
1038        self.ieee802154_set_cca_config();
1039
1040        self.ieee802154_set_tx_power();
1041
1042        self.ieee802154_set_channel_freq();
1043
1044        // Begin receiving procedure
1045        self.enable_interrupts();
1046        self.rx();
1047    }
1048
1049    // IEEE802.15.4 SPECIFICATION Section 6.20.12.5 of the NRF52840 Datasheet
1050    fn ieee802154_set_crc_config(&self) {
1051        self.registers
1052            .crccnf
1053            .write(CrcConfiguration::LEN::TWO + CrcConfiguration::SKIPADDR::IEEE802154);
1054        self.registers
1055            .crcinit
1056            .set(crate::constants::RADIO_CRCINIT_IEEE802154);
1057        self.registers
1058            .crcpoly
1059            .set(crate::constants::RADIO_CRCPOLY_IEEE802154);
1060    }
1061
1062    fn ieee802154_set_rampup_mode(&self) {
1063        self.registers
1064            .modecnf0
1065            .write(RadioModeConfig::RU::FAST + RadioModeConfig::DTX::CENTER);
1066    }
1067
1068    fn ieee802154_set_cca_config(&self) {
1069        self.registers.ccactrl.write(
1070            CCAControl::CCAMODE.val(crate::constants::IEEE802154_CCA_MODE)
1071                + CCAControl::CCAEDTHRESH.val(crate::constants::IEEE802154_CCA_ED_THRESH)
1072                + CCAControl::CCACORRTHRESH.val(crate::constants::IEEE802154_CCA_CORR_THRESH)
1073                + CCAControl::CCACORRCNT.val(crate::constants::IEEE802154_CCA_CORR_CNT),
1074        );
1075    }
1076
1077    // Packet configuration
1078    // Settings taken from RiotOS nrf52840 15.4 driver
1079    fn ieee802154_set_packet_config(&self) {
1080        self.registers.pcnf0.write(
1081            PacketConfiguration0::LFLEN.val(8)
1082                + PacketConfiguration0::PLEN::THIRTYTWOZEROS
1083                + PacketConfiguration0::CRCINC::INCLUDE,
1084        );
1085
1086        self.registers
1087            .pcnf1
1088            .write(PacketConfiguration1::MAXLEN.val(crate::constants::RADIO_PAYLOAD_LENGTH as u32));
1089    }
1090
1091    fn ieee802154_set_channel_rate(&self) {
1092        self.registers.mode.write(Mode::MODE::IEEE802154_250KBIT);
1093    }
1094
1095    fn ieee802154_set_channel_freq(&self) {
1096        let channel = self.channel.get();
1097        self.registers
1098            .frequency
1099            .write(Frequency::FREQUENCY.val(channel as u32));
1100    }
1101
1102    fn ieee802154_set_tx_power(&self) {
1103        self.registers.txpower.set(self.tx_power.get() as u32);
1104    }
1105
1106    pub fn startup(&self) -> Result<(), ErrorCode> {
1107        self.radio_initialize();
1108        Ok(())
1109    }
1110
1111    // Returns a new pseudo-random number and updates the randomness state.
1112    //
1113    // Uses the [Xorshift](https://en.wikipedia.org/wiki/Xorshift) algorithm to
1114    // produce pseudo-random numbers. Uses the `random_nonce` field to keep
1115    // state.
1116    fn random_nonce(&self) -> u32 {
1117        let mut next_nonce = ::core::num::Wrapping(self.random_nonce.get());
1118        next_nonce ^= next_nonce << 13;
1119        next_nonce ^= next_nonce >> 17;
1120        next_nonce ^= next_nonce << 5;
1121        self.random_nonce.set(next_nonce.0);
1122        self.random_nonce.get()
1123    }
1124}
1125
1126impl<'a> kernel::hil::radio::RadioConfig<'a> for Radio<'a> {
1127    fn initialize(&self) -> Result<(), ErrorCode> {
1128        Ok(())
1129    }
1130
1131    fn set_power_client(&self, client: &'a dyn PowerClient) {
1132        self.power_client.set(client);
1133    }
1134
1135    fn reset(&self) -> Result<(), ErrorCode> {
1136        self.radio_initialize();
1137        Ok(())
1138    }
1139
1140    fn start(&self) -> Result<(), ErrorCode> {
1141        self.radio_initialize();
1142
1143        // Configure deferred call to trigger callback.
1144        self.deferred_call_operation
1145            .set(DeferredOperation::PowerClientCallback);
1146        self.deferred_call.set();
1147
1148        Ok(())
1149    }
1150
1151    fn stop(&self) -> Result<(), ErrorCode> {
1152        self.radio_off();
1153
1154        // Configure deferred call to trigger callback.
1155        self.deferred_call_operation
1156            .set(DeferredOperation::PowerClientCallback);
1157        self.deferred_call.set();
1158
1159        Ok(())
1160    }
1161
1162    fn is_on(&self) -> bool {
1163        self.radio_is_on()
1164    }
1165
1166    fn busy(&self) -> bool {
1167        // `tx_buf` is only occupied when a transmission is underway.
1168        self.tx_buf.is_some()
1169    }
1170
1171    fn set_config_client(&self, client: &'a dyn radio::ConfigClient) {
1172        self.config_client.set(client);
1173    }
1174
1175    /// Commit the config calls to hardware, changing (in theory):
1176    ///
1177    /// - the RX address
1178    /// - PAN ID
1179    /// - TX power
1180    /// - channel
1181    ///
1182    /// to the specified values. **However**, the nRF52840 IEEE 802.15.4 radio
1183    /// does not support hardware-level address filtering (see
1184    /// [here](https://devzone.nordicsemi.com/f/nordic-q-a/19320/using-nrf52840-for-802-15-4)).
1185    /// So setting the addresses and PAN ID have no meaning for this chip and
1186    /// any filtering must be done in higher layers in software.
1187    ///
1188    /// Issues a callback to the config client when done.
1189    fn config_commit(&self) {
1190        // All we can configure is TX power and channel frequency.
1191        self.ieee802154_set_tx_power();
1192        self.ieee802154_set_channel_freq();
1193
1194        // Enable deferred call so we can generate a `ConfigClient` callback.
1195        self.deferred_call_operation
1196            .set(DeferredOperation::ConfigClientCallback);
1197        self.deferred_call.set();
1198    }
1199
1200    //#################################################
1201    // Accessors
1202    //#################################################
1203
1204    fn get_address(&self) -> u16 {
1205        self.addr.get()
1206    }
1207
1208    fn get_address_long(&self) -> [u8; 8] {
1209        self.addr_long.get()
1210    }
1211
1212    /// The 16-bit PAN ID
1213    fn get_pan(&self) -> u16 {
1214        self.pan.get()
1215    }
1216
1217    /// The transmit power, in dBm
1218    fn get_tx_power(&self) -> i8 {
1219        self.tx_power.get() as i8
1220    }
1221
1222    /// The 802.15.4 channel
1223    fn get_channel(&self) -> u8 {
1224        self.channel.get().get_channel_number()
1225    }
1226
1227    //#################################################
1228    // Mutators
1229    //#################################################
1230
1231    fn set_address(&self, addr: u16) {
1232        self.addr.set(addr);
1233    }
1234
1235    fn set_address_long(&self, addr: [u8; 8]) {
1236        self.addr_long.set(addr);
1237    }
1238
1239    fn set_pan(&self, id: u16) {
1240        self.pan.set(id);
1241    }
1242
1243    fn set_channel(&self, chan: RadioChannel) {
1244        self.channel.set(chan);
1245    }
1246
1247    fn set_tx_power(&self, tx_power: i8) -> Result<(), ErrorCode> {
1248        // Convert u8 to TxPower
1249        match crate::constants::TxPower::try_from(tx_power as u8) {
1250            // Invalid transmitting power, propagate error
1251            Err(()) => Err(ErrorCode::NOSUPPORT),
1252            // Valid transmitting power, propagate success
1253            Ok(res) => {
1254                self.tx_power.set(res);
1255                Ok(())
1256            }
1257        }
1258    }
1259}
1260
1261impl<'a> kernel::hil::radio::RadioData<'a> for Radio<'a> {
1262    fn set_receive_client(&self, client: &'a dyn radio::RxClient) {
1263        self.rx_client.set(client);
1264    }
1265
1266    fn set_receive_buffer(&self, buffer: &'static mut [u8]) {
1267        self.rx_buf.replace(buffer);
1268    }
1269
1270    fn set_transmit_client(&self, client: &'a dyn radio::TxClient) {
1271        self.tx_client.set(client);
1272    }
1273
1274    fn transmit(
1275        &self,
1276        buf: &'static mut [u8],
1277        frame_len: usize,
1278    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
1279        if self.state.get() == RadioState::OFF {
1280            return Err((ErrorCode::OFF, buf));
1281        } else if self.busy() {
1282            return Err((ErrorCode::BUSY, buf));
1283        } else if buf.len() < radio::PSDU_OFFSET + frame_len + radio::MFR_SIZE {
1284            // Not enough room for CRC or PHR or reserved byte
1285            return Err((ErrorCode::SIZE, buf));
1286        }
1287
1288        // Insert the PHR which is the PDSU length.
1289        buf[radio::PHR_OFFSET] = (frame_len + radio::MFR_SIZE) as u8;
1290
1291        // The tx_buf does not possess static memory. This buffer only
1292        // temporarily holds a reference to another buffer passed as a function
1293        // argument. The tx_buf holds ownership of this buffer until it is
1294        // returned through the send_done(...) function.
1295        self.tx_buf.replace(self.set_dma_ptr(buf));
1296
1297        // The transmit function handles sending both ACK and standard packets
1298        if let RadioState::ACK = self.state.get() {
1299            self.registers.task_txen.write(Task::ENABLE::SET);
1300        } else {
1301            // Configure radio for standard packet TX
1302            self.state.set(RadioState::TX);
1303
1304            // Instruct radio hardware to automatically progress from:
1305            // - RXDISABLE to RXRU state upon receipt of internal disabled event
1306            // - RXIDLE to RX state upon receipt of ready event and radio ramp
1307            //   up completed, begin CCA backoff
1308            // - RX to TXRU state upon internal receipt CCA completion event
1309            //   (clear to begin transmitting)
1310            self.registers.shorts.write(
1311                Shortcut::DISABLED_RXEN::SET
1312                    + Shortcut::RXREADY_CCASTART::SET
1313                    + Shortcut::CCAIDLE_TXEN::SET,
1314            );
1315
1316            // Radio is in proper shortcut state, disable and begin TX sequence
1317            self.registers.task_disable.write(Task::ENABLE::SET);
1318        }
1319
1320        Ok(())
1321    }
1322}
1323
1324impl DeferredCallClient for Radio<'_> {
1325    fn handle_deferred_call(&self) {
1326        // On deferred call we trigger the config or power callbacks. The
1327        // `.take()` ensures we clear what is pending.
1328        self.deferred_call_operation.take().map(|op| match op {
1329            DeferredOperation::ConfigClientCallback => {
1330                self.config_client.map(|client| {
1331                    client.config_done(Ok(()));
1332                });
1333            }
1334            DeferredOperation::PowerClientCallback => {
1335                self.power_client.map(|client| {
1336                    client.changed(self.radio_is_on());
1337                });
1338            }
1339        });
1340    }
1341
1342    fn register(&'static self) {
1343        self.deferred_call.register(self);
1344    }
1345}