Skip to main content

nrf52/
ble_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//! Radio driver, Bluetooth Low Energy, NRF52
6//!
7//! The generic radio configuration i.e., not specific to Bluetooth are
8//! functions and similar which do not start with `ble`. Moreover, Bluetooth
9//! Low Energy specific radio configuration starts with `ble`
10//!
11//! For more readability the Bluetooth specific configuration may be moved to
12//! separate trait
13//!
14//! ### Author
15//! * Niklas Adolfsson <niklasadolfsson1@gmail.com>
16//! * Date: July 18, 2017
17//!
18//! ### Packet Configuration
19//! ```txt
20//! +----------+------+--------+----+--------+----+---------+-----+
21//! | Preamble | Base | Prefix | S0 | Length | S1 | Payload | CRC |
22//! +----------+------+--------+----+--------+----+---------+-----+
23//! ```
24//!
25//! * Preamble - 1 byte
26//!
27//! * Base and prefix forms together the access address
28//!
29//! * S0, an optional parameter that is configured to indicate how many bytes of
30//!   the payload is the PDU Type. Configured as 1 byte!
31//!
32//! * Length, an optional parameter that is configured to indicate how many bits
33//!   of the payload is the length field. Configured as 8 bits!
34//!
35//! * S1, Not used
36//!
37//! * Payload - 2 to 255 bytes
38//!
39//! * CRC - 3 bytes
40
41use core::cell::Cell;
42use core::ptr::addr_of;
43use core::ptr::addr_of_mut;
44use kernel::ErrorCode;
45use kernel::hil::ble_advertising;
46use kernel::hil::ble_advertising::RadioChannel;
47use kernel::utilities::StaticRef;
48use kernel::utilities::cells::OptionalCell;
49use kernel::utilities::cells::TakeCell;
50use nrf5x::constants::TxPower;
51use tock_registers_v0::interfaces::{Readable, Writeable};
52use tock_registers_v0::registers::{ReadOnly, ReadWrite, WriteOnly};
53use tock_registers_v0::{register_bitfields, register_structs};
54
55register_structs! {
56    pub RadioRegisters {
57        /// Enable Radio in TX mode
58        (0x000 => task_txen: WriteOnly<u32, Task::Register>),
59        /// Enable Radio in RX mode
60        (0x004 => task_rxen: WriteOnly<u32, Task::Register>),
61        /// Start Radio
62        (0x008 => task_start: WriteOnly<u32, Task::Register>),
63        /// Stop Radio
64        (0x00C => task_stop: WriteOnly<u32, Task::Register>),
65        /// Disable Radio
66        (0x010 => task_disable: WriteOnly<u32, Task::Register>),
67        /// Start the RSSI and take one single sample of the receive signal strength
68        (0x014 => task_rssistart: WriteOnly<u32, Task::Register>),
69        /// Stop the RSSI measurement
70        (0x018 => task_rssistop: WriteOnly<u32, Task::Register>),
71        /// Start the bit counter
72        (0x01C => task_bcstart: WriteOnly<u32, Task::Register>),
73        /// Stop the bit counter
74        (0x020 => task_bcstop: WriteOnly<u32, Task::Register>),
75        (0x024 => _reserved1),
76        /// Radio has ramped up and is ready to be started
77        (0x100 => event_ready: ReadWrite<u32, Event::Register>),
78        /// Address sent or received
79        (0x104 => event_address: ReadWrite<u32, Event::Register>),
80        /// Packet payload sent or received
81        (0x108 => event_payload: ReadWrite<u32, Event::Register>),
82        /// Packet sent or received
83        (0x10C => event_end: ReadWrite<u32, Event::Register>),
84        /// Radio has been disabled
85        (0x110 => event_disabled: ReadWrite<u32, Event::Register>),
86        /// A device address match occurred on the last received packet
87        (0x114 => event_devmatch: ReadWrite<u32>),
88        /// No device address match occurred on the last received packet
89        (0x118 => event_devmiss: ReadWrite<u32, Event::Register>),
90        /// Sampling of receive signal strength complete
91        (0x11C => event_rssiend: ReadWrite<u32, Event::Register>),
92        (0x120 => _reserved2),
93        /// Bit counter reached bit count value
94        (0x128 => event_bcmatch: ReadWrite<u32, Event::Register>),
95        (0x12C => _reserved3),
96        /// Packet received with CRC ok
97        (0x130 => event_crcok: ReadWrite<u32, Event::Register>),
98        /// Packet received with CRC error
99        (0x134 => crcerror: ReadWrite<u32, Event::Register>),
100        (0x138 => _reserved4),
101        /// Shortcut register
102        (0x200 => shorts: ReadWrite<u32, Shortcut::Register>),
103        (0x204 => _reserved5),
104        /// Enable interrupt
105        (0x304 => intenset: ReadWrite<u32, Interrupt::Register>),
106        /// Disable interrupt
107        (0x308 => intenclr: ReadWrite<u32, Interrupt::Register>),
108        (0x30C => _reserved6),
109        /// CRC status
110        (0x400 => crcstatus: ReadOnly<u32, Event::Register>),
111        (0x404 => _reserved7),
112        /// Received address
113        (0x408 => rxmatch: ReadOnly<u32, ReceiveMatch::Register>),
114        /// CRC field of previously received packet
115        (0x40C => rxcrc: ReadOnly<u32, ReceiveCrc::Register>),
116        /// Device address match index
117        (0x410 => dai: ReadOnly<u32, DeviceAddressIndex::Register>),
118        (0x414 => _reserved8),
119        /// Packet pointer
120        (0x504 => packetptr: ReadWrite<u32, PacketPointer::Register>),
121        /// Frequency
122        (0x508 => frequency: ReadWrite<u32, Frequency::Register>),
123        /// Output power
124        (0x50C => txpower: ReadWrite<u32, TransmitPower::Register>),
125        /// Data rate and modulation
126        (0x510 => mode: ReadWrite<u32, Mode::Register>),
127        /// Packet configuration register 0
128        (0x514 => pcnf0: ReadWrite<u32, PacketConfiguration0::Register>),
129        /// Packet configuration register 1
130        (0x518 => pcnf1: ReadWrite<u32, PacketConfiguration1::Register>),
131        /// Base address 0
132        (0x51C => base0: ReadWrite<u32, BaseAddress::Register>),
133        /// Base address 1
134        (0x520 => base1: ReadWrite<u32, BaseAddress::Register>),
135        /// Prefix bytes for logical addresses 0-3
136        (0x524 => prefix0: ReadWrite<u32, Prefix0::Register>),
137        /// Prefix bytes for logical addresses 4-7
138        (0x528 => prefix1: ReadWrite<u32, Prefix1::Register>),
139        /// Transmit address select
140        (0x52C => txaddress: ReadWrite<u32, TransmitAddress::Register>),
141        /// Receive address select
142        (0x530 => rxaddresses: ReadWrite<u32, ReceiveAddresses::Register>),
143        /// CRC configuration
144        (0x534 => crccnf: ReadWrite<u32, CrcConfiguration::Register>),
145        /// CRC polynomial
146        (0x538 => crcpoly: ReadWrite<u32, CrcPolynomial::Register>),
147        /// CRC initial value
148        (0x53C => crcinit: ReadWrite<u32, CrcInitialValue::Register>),
149        (0x540 => _reserved9),
150        /// Interframe spacing in microseconds
151        (0x544 => tifs: ReadWrite<u32, InterFrameSpacing::Register>),
152        /// RSSI sample
153        (0x548 => rssisample: ReadWrite<u32, RssiSample::Register>),
154        (0x54C => _reserved10),
155        /// Current radio state
156        (0x550 => state: ReadOnly<u32, State::Register>),
157        /// Data whitening initial value
158        (0x554 => datawhiteiv: ReadWrite<u32, DataWhiteIv::Register>),
159        (0x558 => _reserved11),
160        /// Bit counter compare
161        (0x560 => bcc: ReadWrite<u32, BitCounterCompare::Register>),
162        (0x564 => _reserved12),
163        /// Device address base segments
164        (0x600 => dab: [ReadWrite<u32, DeviceAddressBase::Register>; 8]),
165        /// Device address prefix
166        (0x620 => dap: [ReadWrite<u32, DeviceAddressPrefix::Register>; 8]),
167        /// Device address match configuration
168        (0x640 => dacnf: ReadWrite<u32, DeviceAddressMatch::Register>),
169        (0x644 => _reserved13),
170        /// Radio mode configuration register
171        (0x650 => modecnf0: ReadWrite<u32, RadioModeConfig::Register>),
172        (0x654 => _reserved14),
173        /// Peripheral power control
174        (0xFFC => power: ReadWrite<u32, Task::Register>),
175        (0x1000 => @END),
176    }
177}
178
179register_bitfields! [u32,
180    /// Task register
181    Task [
182        /// Enable task
183        ENABLE OFFSET(0) NUMBITS(1)
184    ],
185    /// Event register
186    Event [
187        /// Ready event
188        READY OFFSET(0) NUMBITS(1)
189    ],
190    /// Shortcut register
191    Shortcut [
192        /// Shortcut between READY event and START task
193        READY_START OFFSET(0) NUMBITS(1),
194        /// Shortcut between END event and DISABLE task
195        END_DISABLE OFFSET(1) NUMBITS(1),
196        /// Shortcut between DISABLED event and TXEN task
197        DISABLED_TXEN OFFSET(2) NUMBITS(1),
198        /// Shortcut between DISABLED event and RXEN task
199        DISABLED_RXEN OFFSET(3) NUMBITS(1),
200        /// Shortcut between ADDRESS event and RSSISTART task
201        ADDRESS_RSSISTART OFFSET(4) NUMBITS(1),
202        /// Shortcut between END event and START task
203        END_START OFFSET(5) NUMBITS(1),
204        /// Shortcut between ADDRESS event and BCSTART task
205        ADDRESS_BCSTART OFFSET(6) NUMBITS(1),
206        /// Shortcut between DISABLED event and RSSISTOP task
207        DISABLED_RSSISTOP OFFSET(8) NUMBITS(1)
208    ],
209    /// Interrupt register
210    Interrupt [
211        /// READY event
212        READY OFFSET(0) NUMBITS(1),
213        /// ADDRESS event
214        ADDRESS OFFSET(1) NUMBITS(1),
215        /// PAYLOAD event
216        PAYLOAD OFFSET(2) NUMBITS(1),
217        /// END event
218        END OFFSET(3) NUMBITS(1),
219        /// DISABLED event
220        DISABLED OFFSET(4) NUMBITS(1),
221        /// DEVMATCH event
222        DEVMATCH OFFSET(5) NUMBITS(1),
223        /// DEVMISS event
224        DEVMISS OFFSET(6) NUMBITS(1),
225        /// RSSIEND event
226        RSSIEND OFFSET(7) NUMBITS(1),
227        /// BCMATCH event
228        BCMATCH OFFSET(10) NUMBITS(1),
229        /// CRCOK event
230        CRCOK OFFSET(12) NUMBITS(1),
231        /// CRCERROR event
232        CRCERROR OFFSET(13) NUMBITS(1)
233    ],
234    /// Receive match register
235    ReceiveMatch [
236        /// Logical address of which previous packet was received
237        MATCH OFFSET(0) NUMBITS(3)
238    ],
239    /// Received CRC register
240    ReceiveCrc [
241        /// CRC field of previously received packet
242        CRC OFFSET(0) NUMBITS(24)
243    ],
244    /// Device address match index register
245    DeviceAddressIndex [
246        /// Device address match index
247        /// Index (n) of device address, see DAB\[n\] and DAP\[n\], that got an
248        /// address match
249        INDEX OFFSET(0) NUMBITS(3)
250    ],
251    /// Packet pointer register
252    PacketPointer [
253        /// Packet address to be used for the next transmission or reception. When transmitting, the packet pointed to by this
254        /// address will be transmitted and when receiving, the received packet will be written to this address. This address is a byte
255        /// aligned ram address.
256        POINTER OFFSET(0) NUMBITS(32)
257    ],
258    /// Frequency register
259    Frequency [
260        /// Radio channel frequency
261        /// Frequency = 2400 + FREQUENCY (MHz)
262        FREQUENCY OFFSET(0) NUMBITS(7) [],
263        /// Channel map selection.
264        /// Channel map between 2400 MHZ .. 2500 MHZ
265        MAP OFFSET(8) NUMBITS(1) [
266            DEFAULT = 0,
267            LOW = 1
268        ]
269    ],
270    /// Transmitting power register
271    TransmitPower [
272        /// Radio output power
273        POWER OFFSET(0) NUMBITS(8) [
274            POS4DBM = 4,
275            POS3DBM = 3,
276            ODBM = 0,
277            NEG4DBM = 0xfc,
278            NEG8DBM = 0xf8,
279            NEG12DBM = 0xf4,
280            NEG16DBM = 0xf0,
281            NEG20DBM = 0xec,
282            NEG40DBM = 0xd8
283        ]
284    ],
285    /// Data rate and modulation register
286    Mode [
287        /// Radio data rate and modulation setting.
288        /// The radio supports Frequency-shift Keying (FSK) modulation
289        MODE OFFSET(0) NUMBITS(4) [
290            NRF_1MBIT = 0,
291            NRF_2MBIT = 1,
292            NRF_250KBIT = 2,
293            BLE_1MBIT = 3
294        ]
295    ],
296    /// Packet configuration register 0
297    PacketConfiguration0 [
298        /// Length on air of LENGTH field in number of bits
299        LFLEN OFFSET(0) NUMBITS(4) [],
300        /// Length on air of S0 field in number of bytes
301        S0LEN OFFSET(8) NUMBITS(1) [],
302        /// Length on air of S1 field in number of bits.
303        S1LEN OFFSET(16) NUMBITS(4) [],
304        /// Include or exclude S1 field in RAM
305        S1INCL OFFSET(20) NUMBITS(1) [
306            AUTOMATIC = 0,
307            INCLUDE = 1
308        ],
309        /// Length of preamble on air. Decision point: TASKS_START task
310        PLEN OFFSET(24) NUMBITS(1) [
311            EIGHT = 0,
312            SIXTEEN = 1
313        ]
314    ],
315    /// Packet configuration register 1
316    PacketConfiguration1 [
317        /// Maximum length of packet payload
318        MAXLEN OFFSET(0) NUMBITS(8) [],
319        /// Static length in number of bytes
320        STATLEN OFFSET(8) NUMBITS(8) [],
321        /// Base address length in number of bytes
322        BALEN OFFSET(16) NUMBITS(3) [],
323        /// On air endianness
324        ENDIAN OFFSET(24) NUMBITS(1) [
325            LITTLE = 0,
326            BIG = 1
327        ],
328        /// Enable or disable packet whitening
329        WHITEEN OFFSET(25) NUMBITS(1) [
330            DISABLED = 0,
331            ENABLED = 1
332        ]
333    ],
334    /// Radio base address register
335    BaseAddress [
336        /// BASE0 or BASE1
337        BASE OFFSET(0) NUMBITS(32)
338    ],
339    /// Radio prefix0 registers
340    Prefix0 [
341        /// Address prefix 0
342        AP0 OFFSET(0) NUMBITS(8),
343        /// Address prefix 1
344        AP1 OFFSET(8) NUMBITS(8),
345        /// Address prefix 2
346        AP2 OFFSET(16) NUMBITS(8),
347        /// Address prefix 3
348        AP3 OFFSET(24) NUMBITS(8)
349    ],
350    /// Radio prefix0 registers
351    Prefix1 [
352        /// Address prefix 4
353        AP4 OFFSET(0) NUMBITS(8),
354        /// Address prefix 5
355        AP5 OFFSET(8) NUMBITS(8),
356        /// Address prefix 6
357        AP6 OFFSET(16) NUMBITS(8),
358        /// Address prefix 7
359        AP7 OFFSET(24) NUMBITS(8)
360    ],
361    /// Transmit address register
362    TransmitAddress [
363        /// Logical address to be used when transmitting a packet
364        ADDRESS OFFSET(0) NUMBITS(3)
365    ],
366    /// Receive addresses register
367    ReceiveAddresses [
368        /// Enable or disable reception on logical address 0-7
369        ADDRESS OFFSET(0) NUMBITS(8)
370    ],
371    /// CRC configuration register
372    CrcConfiguration [
373        /// CRC length in bytes
374        LEN OFFSET(0) NUMBITS(2) [
375            DISABLED = 0,
376            ONE = 1,
377            TWO = 2,
378            THREE = 3
379        ],
380        /// Include or exclude packet field from CRC calculation
381        SKIPADDR OFFSET(8) NUMBITS(1) [
382            INCLUDE = 0,
383            EXCLUDE = 1
384        ]
385    ],
386    /// CRC polynomial register
387    CrcPolynomial [
388        /// CRC polynomial
389        CRCPOLY OFFSET(0) NUMBITS(24)
390    ],
391    /// CRC initial value register
392    CrcInitialValue [
393       /// Initial value for CRC calculation
394       CRCINIT OFFSET(0) NUMBITS(24)
395    ],
396    /// Inter Frame Spacing in us register
397    InterFrameSpacing [
398        /// Inter Frame Spacing in us
399        /// Inter frame space is the time interval between two consecutive packets. It is defined as the time, in micro seconds, from the
400        /// end of the last bit of the previous packet to the start of the first bit of the subsequent packet
401        TIFS OFFSET(0) NUMBITS(8)
402    ],
403    /// RSSI sample register
404    RssiSample [
405        /// RSSI sample result
406        RSSISAMPLE OFFSET(0) NUMBITS(7)
407    ],
408    /// Radio state register
409    State [
410        /// Current radio state
411        STATE OFFSET(0) NUMBITS(4) [
412            DISABLED = 0,
413            RXRU = 1,
414            RXIDLE = 2,
415            RX = 3,
416            RXDISABLED = 4,
417            TXRU = 9,
418            TXIDLE = 10,
419            TX = 11,
420            TXDISABLED = 12
421        ]
422    ],
423    /// Data whitening initial value register
424    DataWhiteIv [
425        /// Data whitening initial value. Bit 6 is hard-wired to '1', writing '0'
426        /// to it has no effect, and it will always be read back and used by the device as '1'
427        DATEWHITEIV OFFSET(0) NUMBITS(7)
428    ],
429    /// Bit counter compare register
430    BitCounterCompare [
431        /// Bit counter compare
432        BCC OFFSET(0) NUMBITS(32)
433    ],
434    /// Device address base register
435    DeviceAddressBase [
436        /// Device address base 0-7
437        DAB OFFSET(0) NUMBITS(32)
438    ],
439    /// Device address prefix register
440    DeviceAddressPrefix [
441        /// Device address prefix 0-7
442        DAP OFFSET(0) NUMBITS(32)
443    ],
444    /// Device address match configuration register
445    DeviceAddressMatch [
446        /// Enable or disable device address matching on 0-7
447        ENA OFFSET(0) NUMBITS(8),
448        /// TxAdd for device address 0-7
449        TXADD OFFSET(8) NUMBITS(8)
450    ],
451    /// Radio mode configuration register
452    RadioModeConfig [
453        /// Radio ramp-up time
454        RU OFFSET(0) NUMBITS(1) [
455            DEFAULT = 0,
456            FAST = 1
457        ],
458        /// Default TX value
459        /// Specifies what the RADIO will transmit when it is not started, i.e. between:
460        /// RADIO.EVENTS_READY and RADIO.TASKS_START
461        /// RADIO.EVENTS_END and RADIO.TASKS_START
462        DTX OFFSET(8) NUMBITS(2) [
463            B1 = 0,
464            B0 = 1,
465            CENTER = 2
466        ]
467    ]
468];
469
470static mut PAYLOAD: [u8; nrf5x::constants::RADIO_PAYLOAD_LENGTH] =
471    [0x00; nrf5x::constants::RADIO_PAYLOAD_LENGTH];
472
473pub struct Radio<'a> {
474    registers: StaticRef<RadioRegisters>,
475    tx_power: Cell<TxPower>,
476    rx_client: OptionalCell<&'a dyn ble_advertising::RxClient>,
477    tx_client: OptionalCell<&'a dyn ble_advertising::TxClient>,
478    buffer: TakeCell<'static, [u8]>,
479}
480
481impl<'a> Radio<'a> {
482    pub const fn new(registers: StaticRef<RadioRegisters>) -> Radio<'a> {
483        Radio {
484            registers,
485            tx_power: Cell::new(TxPower::ZerodBm),
486            rx_client: OptionalCell::empty(),
487            tx_client: OptionalCell::empty(),
488            buffer: TakeCell::empty(),
489        }
490    }
491
492    pub fn is_enabled(&self) -> bool {
493        self.registers.mode.matches_all(Mode::MODE::BLE_1MBIT)
494    }
495
496    fn tx(&self) {
497        self.registers.event_ready.write(Event::READY::CLEAR);
498        self.registers.task_txen.write(Task::ENABLE::SET);
499    }
500
501    fn rx(&self) {
502        self.registers.event_ready.write(Event::READY::CLEAR);
503        self.registers.task_rxen.write(Task::ENABLE::SET);
504    }
505
506    fn set_rx_address(&self) {
507        self.registers
508            .rxaddresses
509            .write(ReceiveAddresses::ADDRESS.val(1));
510    }
511
512    fn set_tx_address(&self) {
513        self.registers
514            .txaddress
515            .write(TransmitAddress::ADDRESS.val(0));
516    }
517
518    fn radio_on(&self) {
519        // reset and enable power
520        self.registers.power.write(Task::ENABLE::CLEAR);
521        self.registers.power.write(Task::ENABLE::SET);
522    }
523
524    fn radio_off(&self) {
525        self.registers.power.write(Task::ENABLE::CLEAR);
526    }
527
528    fn set_tx_power(&self) {
529        self.registers.txpower.set(self.tx_power.get() as u32);
530    }
531
532    fn set_dma_ptr(&self) {
533        self.registers.packetptr.set(addr_of!(PAYLOAD) as u32);
534    }
535
536    #[inline(never)]
537    pub fn handle_interrupt(&self) {
538        self.disable_all_interrupts();
539
540        if self.registers.event_ready.is_set(Event::READY) {
541            self.registers.event_ready.write(Event::READY::CLEAR);
542            self.registers.event_end.write(Event::READY::CLEAR);
543            self.registers.task_start.write(Task::ENABLE::SET);
544        }
545
546        if self.registers.event_address.is_set(Event::READY) {
547            self.registers.event_address.write(Event::READY::CLEAR);
548        }
549        if self.registers.event_payload.is_set(Event::READY) {
550            self.registers.event_payload.write(Event::READY::CLEAR);
551        }
552
553        // tx or rx finished!
554        if self.registers.event_end.is_set(Event::READY) {
555            self.registers.event_end.write(Event::READY::CLEAR);
556
557            let result = if self.registers.crcstatus.is_set(Event::READY) {
558                Ok(())
559            } else {
560                Err(ErrorCode::FAIL)
561            };
562
563            match self.registers.state.get() {
564                nrf5x::constants::RADIO_STATE_TXRU
565                | nrf5x::constants::RADIO_STATE_TXIDLE
566                | nrf5x::constants::RADIO_STATE_TXDISABLE
567                | nrf5x::constants::RADIO_STATE_TX => {
568                    self.radio_off();
569                    self.tx_client
570                        .map(|client| client.transmit_event(self.buffer.take().unwrap(), result));
571                }
572                nrf5x::constants::RADIO_STATE_RXRU
573                | nrf5x::constants::RADIO_STATE_RXIDLE
574                | nrf5x::constants::RADIO_STATE_RXDISABLE
575                | nrf5x::constants::RADIO_STATE_RX => {
576                    self.radio_off();
577                    unsafe {
578                        self.rx_client.map(|client| {
579                            // Length is: S0 (1 Byte) + Length (1 Byte) + S1 (0 Bytes) + Payload
580                            // And because the length field is directly read from the packet
581                            // We need to add 2 to length to get the total length
582                            client.receive_event(
583                                &mut *addr_of_mut!(PAYLOAD),
584                                PAYLOAD[1] + 2,
585                                result,
586                            )
587                        });
588                    }
589                }
590                // Radio state - Disabled
591                _ => (),
592            }
593        }
594        self.enable_interrupts();
595    }
596
597    pub fn enable_interrupts(&self) {
598        self.registers.intenset.write(
599            Interrupt::READY::SET
600                + Interrupt::ADDRESS::SET
601                + Interrupt::PAYLOAD::SET
602                + Interrupt::END::SET,
603        );
604    }
605
606    pub fn enable_interrupt(&self, intr: u32) {
607        self.registers.intenset.set(intr);
608    }
609
610    pub fn clear_interrupt(&self, intr: u32) {
611        self.registers.intenclr.set(intr);
612    }
613
614    pub fn disable_all_interrupts(&self) {
615        // disable all possible interrupts
616        self.registers.intenclr.set(0xffffffff);
617    }
618
619    fn replace_radio_buffer(&self, buf: &'static mut [u8]) -> &'static mut [u8] {
620        // set payload
621        for (i, c) in buf.as_ref().iter().enumerate() {
622            unsafe {
623                PAYLOAD[i] = *c;
624            }
625        }
626        buf
627    }
628
629    fn ble_initialize(&self, channel: RadioChannel) {
630        self.radio_on();
631
632        self.ble_set_tx_power();
633
634        self.ble_set_channel_rate();
635
636        self.ble_set_channel_freq(channel);
637        self.ble_set_data_whitening(channel);
638
639        self.set_tx_address();
640        self.set_rx_address();
641
642        self.ble_set_packet_config();
643        self.ble_set_advertising_access_address();
644
645        self.ble_set_crc_config();
646
647        self.set_dma_ptr();
648    }
649
650    // BLUETOOTH SPECIFICATION Version 4.2 [Vol 6, Part B], section 3.1.1 CRC Generation
651    fn ble_set_crc_config(&self) {
652        self.registers
653            .crccnf
654            .write(CrcConfiguration::LEN::THREE + CrcConfiguration::SKIPADDR::EXCLUDE);
655        self.registers
656            .crcinit
657            .set(nrf5x::constants::RADIO_CRCINIT_BLE);
658        self.registers
659            .crcpoly
660            .set(nrf5x::constants::RADIO_CRCPOLY_BLE);
661    }
662
663    // BLUETOOTH SPECIFICATION Version 4.2 [Vol 6, Part B], section 2.1.2 Access Address
664    // Set access address to 0x8E89BED6
665    fn ble_set_advertising_access_address(&self) {
666        self.registers.prefix0.set(0x0000008e);
667        self.registers.base0.set(0x89bed600);
668    }
669
670    // Packet configuration
671    // BLUETOOTH SPECIFICATION Version 4.2 [Vol 6, Part B], section 2.1 Packet Format
672    //
673    // LSB                                                      MSB
674    // +----------+   +----------------+   +---------------+   +------------+
675    // | Preamble | - | Access Address | - | PDU           | - | CRC        |
676    // | (1 byte) |   | (4 bytes)      |   | (2-255 bytes) |   | (3 bytes)  |
677    // +----------+   +----------------+   +---------------+   +------------+
678    //
679    fn ble_set_packet_config(&self) {
680        // sets the header of PDU TYPE to 1 byte
681        // sets the header length to 1 byte
682        self.registers.pcnf0.write(
683            PacketConfiguration0::LFLEN.val(8)
684                + PacketConfiguration0::S0LEN.val(1)
685                + PacketConfiguration0::S1LEN::CLEAR
686                + PacketConfiguration0::S1INCL::CLEAR
687                + PacketConfiguration0::PLEN::EIGHT,
688        );
689
690        self.registers.pcnf1.write(
691            PacketConfiguration1::WHITEEN::ENABLED
692                + PacketConfiguration1::ENDIAN::LITTLE
693                + PacketConfiguration1::BALEN.val(3)
694                + PacketConfiguration1::STATLEN::CLEAR
695                + PacketConfiguration1::MAXLEN.val(255),
696        );
697    }
698
699    // BLUETOOTH SPECIFICATION Version 4.2 [Vol 6, Part A], 4.6 REFERENCE SIGNAL DEFINITION
700    // Bit Rate = 1 Mb/s ±1 ppm
701    fn ble_set_channel_rate(&self) {
702        self.registers.mode.write(Mode::MODE::BLE_1MBIT);
703    }
704
705    // BLUETOOTH SPECIFICATION Version 4.2 [Vol 6, Part B], section 3.2 Data Whitening
706    // Configure channel index to the LFSR and the hardware solves the rest
707    fn ble_set_data_whitening(&self, channel: RadioChannel) {
708        self.registers.datawhiteiv.set(channel.get_channel_index());
709    }
710
711    // BLUETOOTH SPECIFICATION Version 4.2 [Vol 6, Part B], section 1.4.1
712    // RF Channels:     0 - 39
713    // Data:            0 - 36
714    // Advertising:     37, 38, 39
715    fn ble_set_channel_freq(&self, channel: RadioChannel) {
716        self.registers
717            .frequency
718            .write(Frequency::FREQUENCY.val(channel as u32));
719    }
720
721    // BLUETOOTH SPECIFICATION Version 4.2 [Vol 6, Part B], section 3 TRANSMITTER CHARACTERISTICS
722    // Minimum Output Power : -20dBm
723    // Maximum Output Power : +10dBm
724    //
725    // no check is required because the BleConfig::set_tx_power() method ensures that only
726    // valid tranmitting power is configured!
727    fn ble_set_tx_power(&self) {
728        self.set_tx_power();
729    }
730}
731
732impl<'a> ble_advertising::BleAdvertisementDriver<'a> for Radio<'a> {
733    fn transmit_advertisement(&self, buf: &'static mut [u8], _len: usize, channel: RadioChannel) {
734        let res = self.replace_radio_buffer(buf);
735        self.buffer.replace(res);
736        self.ble_initialize(channel);
737        self.tx();
738        self.enable_interrupts();
739    }
740
741    fn receive_advertisement(&self, channel: RadioChannel) {
742        self.ble_initialize(channel);
743        self.rx();
744        self.enable_interrupts();
745    }
746
747    fn set_receive_client(&self, client: &'a dyn ble_advertising::RxClient) {
748        self.rx_client.set(client);
749    }
750
751    fn set_transmit_client(&self, client: &'a dyn ble_advertising::TxClient) {
752        self.tx_client.set(client);
753    }
754}
755
756impl ble_advertising::BleConfig for Radio<'_> {
757    // The BLE Advertising Driver validates that the `tx_power` is between -20 to 10 dBm but then
758    // underlying chip must validate if the current `tx_power` is supported as well
759    fn set_tx_power(&self, tx_power: u8) -> Result<(), ErrorCode> {
760        // Convert u8 to TxPower
761        match nrf5x::constants::TxPower::try_from(tx_power) {
762            // Invalid transmitting power, propogate error
763            Err(()) => Err(ErrorCode::NOSUPPORT),
764            // Valid transmitting power, propogate success
765            Ok(res) => {
766                self.tx_power.set(res);
767                Ok(())
768            }
769        }
770    }
771}