nano33ble_rev2/
main.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 2023.
4
5//! Tock kernel for the Arduino Nano 33 BLE Sense Rev2.
6//!
7//! It is based on nRF52840 SoC (Cortex M4 core with a BLE + IEEE 802.15.4 transceiver).
8
9#![no_std]
10// Disable this attribute when documenting, as a workaround for
11// https://github.com/rust-lang/rust/issues/62184.
12#![cfg_attr(not(doc), no_main)]
13#![deny(missing_docs)]
14
15use core::ptr::addr_of;
16use core::ptr::addr_of_mut;
17
18use kernel::capabilities;
19use kernel::component::Component;
20use kernel::hil::gpio::Configure;
21use kernel::hil::gpio::Output;
22use kernel::hil::led::LedLow;
23use kernel::hil::time::Counter;
24use kernel::hil::usb::Client;
25use kernel::platform::chip::Chip;
26use kernel::platform::{KernelResources, SyscallDriverLookup};
27use kernel::scheduler::round_robin::RoundRobinSched;
28#[allow(unused_imports)]
29use kernel::{create_capability, debug, debug_gpio, debug_verbose, static_init};
30
31use nrf52840::gpio::Pin;
32use nrf52840::interrupt_service::Nrf52840DefaultPeripherals;
33
34// Three-color LED.
35const LED_RED_PIN: Pin = Pin::P0_24;
36const LED_GREEN_PIN: Pin = Pin::P0_16;
37const LED_BLUE_PIN: Pin = Pin::P0_06;
38
39const LED_KERNEL_PIN: Pin = Pin::P0_13;
40
41const _BUTTON_RST_PIN: Pin = Pin::P0_18;
42
43const GPIO_D2: Pin = Pin::P1_11;
44const GPIO_D3: Pin = Pin::P1_12;
45const GPIO_D4: Pin = Pin::P1_15;
46const GPIO_D5: Pin = Pin::P1_13;
47const GPIO_D6: Pin = Pin::P1_14;
48const GPIO_D7: Pin = Pin::P0_23;
49const GPIO_D8: Pin = Pin::P0_21;
50const GPIO_D9: Pin = Pin::P0_27;
51const GPIO_D10: Pin = Pin::P1_02;
52
53const _UART_TX_PIN: Pin = Pin::P1_03;
54const _UART_RX_PIN: Pin = Pin::P1_10;
55
56/// I2C pins for all of the sensors.
57const I2C_SDA_PIN: Pin = Pin::P0_14;
58const I2C_SCL_PIN: Pin = Pin::P0_15;
59
60/// GPIO tied to the VCC of the I2C pullup resistors.
61const I2C_PULLUP_PIN: Pin = Pin::P1_00;
62
63/// Interrupt pin for the APDS9960 sensor.
64const APDS9960_PIN: Pin = Pin::P0_19;
65
66// Constants related to the configuration of the 15.4 network stack
67/// Personal Area Network ID for the IEEE 802.15.4 radio
68const PAN_ID: u16 = 0xABCD;
69/// Gateway (or next hop) MAC Address
70const DST_MAC_ADDR: capsules_extra::net::ieee802154::MacAddress =
71    capsules_extra::net::ieee802154::MacAddress::Short(49138);
72const DEFAULT_CTX_PREFIX_LEN: u8 = 8; //Length of context for 6LoWPAN compression
73const DEFAULT_CTX_PREFIX: [u8; 16] = [0x0_u8; 16]; //Context for 6LoWPAN Compression
74
75/// UART Writer for panic!()s.
76pub mod io;
77
78// How should the kernel respond when a process faults. For this board we choose
79// to stop the app and print a notice, but not immediately panic. This allows
80// users to debug their apps, but avoids issues with using the USB/CDC stack
81// synchronously for panic! too early after the board boots.
82const FAULT_RESPONSE: capsules_system::process_policies::StopWithDebugFaultPolicy =
83    capsules_system::process_policies::StopWithDebugFaultPolicy {};
84
85// Number of concurrent processes this platform supports.
86const NUM_PROCS: usize = 8;
87
88// State for loading and holding applications.
89static mut PROCESSES: [Option<&'static dyn kernel::process::Process>; NUM_PROCS] =
90    [None; NUM_PROCS];
91
92static mut CHIP: Option<&'static nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>> = None;
93static mut PROCESS_PRINTER: Option<&'static capsules_system::process_printer::ProcessPrinterText> =
94    None;
95static mut CDC_REF_FOR_PANIC: Option<
96    &'static capsules_extra::usb::cdc::CdcAcm<
97        'static,
98        nrf52::usbd::Usbd,
99        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<'static, nrf52::rtc::Rtc>,
100    >,
101> = None;
102static mut NRF52_POWER: Option<&'static nrf52840::power::Power> = None;
103
104/// Dummy buffer that causes the linker to reserve enough space for the stack.
105#[no_mangle]
106#[link_section = ".stack_buffer"]
107pub static mut STACK_MEMORY: [u8; 0x1000] = [0; 0x1000];
108
109// Function for the CDC/USB stack to use to enter the bootloader.
110fn baud_rate_reset_bootloader_enter() {
111    unsafe {
112        // 0x90 is the magic value the bootloader expects
113        NRF52_POWER.unwrap().set_gpregret(0x90);
114        cortexm4::scb::reset();
115    }
116}
117
118type HS3003Sensor = components::hs3003::Hs3003ComponentType<
119    capsules_core::virtualizers::virtual_i2c::I2CDevice<'static, nrf52840::i2c::TWI<'static>>,
120>;
121type TemperatureDriver = components::temperature::TemperatureComponentType<HS3003Sensor>;
122type HumidityDriver = components::humidity::HumidityComponentType<HS3003Sensor>;
123type Ieee802154MacDevice = components::ieee802154::Ieee802154ComponentMacDeviceType<
124    nrf52840::ieee802154_radio::Radio<'static>,
125    nrf52840::aes::AesECB<'static>,
126>;
127type Ieee802154Driver = components::ieee802154::Ieee802154ComponentType<
128    nrf52840::ieee802154_radio::Radio<'static>,
129    nrf52840::aes::AesECB<'static>,
130>;
131type RngDriver = components::rng::RngComponentType<nrf52840::trng::Trng<'static>>;
132
133/// Supported drivers by the platform
134pub struct Platform {
135    ble_radio: &'static capsules_extra::ble_advertising_driver::BLE<
136        'static,
137        nrf52::ble_radio::Radio<'static>,
138        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<
139            'static,
140            nrf52::rtc::Rtc<'static>,
141        >,
142    >,
143    ieee802154_radio: &'static Ieee802154Driver,
144    console: &'static capsules_core::console::Console<'static>,
145    pconsole: &'static capsules_core::process_console::ProcessConsole<
146        'static,
147        { capsules_core::process_console::DEFAULT_COMMAND_HISTORY_LEN },
148        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<
149            'static,
150            nrf52::rtc::Rtc<'static>,
151        >,
152        components::process_console::Capability,
153    >,
154    proximity: &'static capsules_extra::proximity::ProximitySensor<'static>,
155    pressure: &'static capsules_extra::pressure::PressureSensor<
156        'static,
157        capsules_extra::lps22hb::Lps22hb<
158            'static,
159            capsules_core::virtualizers::virtual_i2c::I2CDevice<
160                'static,
161                nrf52840::i2c::TWI<'static>,
162            >,
163        >,
164    >,
165    temperature: &'static TemperatureDriver,
166    humidity: &'static HumidityDriver,
167    gpio: &'static capsules_core::gpio::GPIO<'static, nrf52::gpio::GPIOPin<'static>>,
168    led: &'static capsules_core::led::LedDriver<
169        'static,
170        LedLow<'static, nrf52::gpio::GPIOPin<'static>>,
171        3,
172    >,
173    adc: &'static capsules_core::adc::AdcVirtualized<'static>,
174    rng: &'static RngDriver,
175    ipc: kernel::ipc::IPC<{ NUM_PROCS as u8 }>,
176    alarm: &'static capsules_core::alarm::AlarmDriver<
177        'static,
178        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<
179            'static,
180            nrf52::rtc::Rtc<'static>,
181        >,
182    >,
183    udp_driver: &'static capsules_extra::net::udp::UDPDriver<'static>,
184    scheduler: &'static RoundRobinSched<'static>,
185    systick: cortexm4::systick::SysTick,
186}
187
188impl SyscallDriverLookup for Platform {
189    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
190    where
191        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
192    {
193        match driver_num {
194            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
195            capsules_extra::proximity::DRIVER_NUM => f(Some(self.proximity)),
196            capsules_extra::pressure::DRIVER_NUM => f(Some(self.pressure)),
197            capsules_extra::temperature::DRIVER_NUM => f(Some(self.temperature)),
198            capsules_extra::humidity::DRIVER_NUM => f(Some(self.humidity)),
199            capsules_core::gpio::DRIVER_NUM => f(Some(self.gpio)),
200            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
201            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
202            capsules_core::adc::DRIVER_NUM => f(Some(self.adc)),
203            capsules_core::rng::DRIVER_NUM => f(Some(self.rng)),
204            capsules_extra::ble_advertising_driver::DRIVER_NUM => f(Some(self.ble_radio)),
205            capsules_extra::ieee802154::DRIVER_NUM => f(Some(self.ieee802154_radio)),
206            capsules_extra::net::udp::DRIVER_NUM => f(Some(self.udp_driver)),
207            kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
208            _ => f(None),
209        }
210    }
211}
212
213impl KernelResources<nrf52::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>>
214    for Platform
215{
216    type SyscallDriverLookup = Self;
217    type SyscallFilter = ();
218    type ProcessFault = ();
219    type Scheduler = RoundRobinSched<'static>;
220    type SchedulerTimer = cortexm4::systick::SysTick;
221    type WatchDog = ();
222    type ContextSwitchCallback = ();
223
224    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
225        self
226    }
227    fn syscall_filter(&self) -> &Self::SyscallFilter {
228        &()
229    }
230    fn process_fault(&self) -> &Self::ProcessFault {
231        &()
232    }
233    fn scheduler(&self) -> &Self::Scheduler {
234        self.scheduler
235    }
236    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
237        &self.systick
238    }
239    fn watchdog(&self) -> &Self::WatchDog {
240        &()
241    }
242    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
243        &()
244    }
245}
246
247/// This is in a separate, inline(never) function so that its stack frame is
248/// removed when this function returns. Otherwise, the stack space used for
249/// these static_inits is wasted.
250#[inline(never)]
251pub unsafe fn start() -> (
252    &'static kernel::Kernel,
253    Platform,
254    &'static nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>,
255) {
256    nrf52840::init();
257
258    let ieee802154_ack_buf = static_init!(
259        [u8; nrf52840::ieee802154_radio::ACK_BUF_SIZE],
260        [0; nrf52840::ieee802154_radio::ACK_BUF_SIZE]
261    );
262
263    // Initialize chip peripheral drivers
264    let nrf52840_peripherals = static_init!(
265        Nrf52840DefaultPeripherals,
266        Nrf52840DefaultPeripherals::new(ieee802154_ack_buf)
267    );
268
269    // set up circular peripheral dependencies
270    nrf52840_peripherals.init();
271    let base_peripherals = &nrf52840_peripherals.nrf52;
272
273    // Save a reference to the power module for resetting the board into the
274    // bootloader.
275    NRF52_POWER = Some(&base_peripherals.pwr_clk);
276
277    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(&*addr_of!(PROCESSES)));
278
279    //--------------------------------------------------------------------------
280    // CAPABILITIES
281    //--------------------------------------------------------------------------
282
283    // Create capabilities that the board needs to call certain protected kernel
284    // functions.
285    let process_management_capability =
286        create_capability!(capabilities::ProcessManagementCapability);
287    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
288
289    //--------------------------------------------------------------------------
290    // DEBUG GPIO
291    //--------------------------------------------------------------------------
292
293    // Configure kernel debug GPIOs as early as possible. These are used by the
294    // `debug_gpio!(0, toggle)` macro. We configure these early so that the
295    // macro is available during most of the setup code and kernel execution.
296    kernel::debug::assign_gpios(
297        Some(&nrf52840_peripherals.gpio_port[LED_KERNEL_PIN]),
298        None,
299        None,
300    );
301
302    //--------------------------------------------------------------------------
303    // GPIO
304    //--------------------------------------------------------------------------
305
306    let gpio = components::gpio::GpioComponent::new(
307        board_kernel,
308        capsules_core::gpio::DRIVER_NUM,
309        components::gpio_component_helper!(
310            nrf52840::gpio::GPIOPin,
311            2 => &nrf52840_peripherals.gpio_port[GPIO_D2],
312            3 => &nrf52840_peripherals.gpio_port[GPIO_D3],
313            4 => &nrf52840_peripherals.gpio_port[GPIO_D4],
314            5 => &nrf52840_peripherals.gpio_port[GPIO_D5],
315            6 => &nrf52840_peripherals.gpio_port[GPIO_D6],
316            7 => &nrf52840_peripherals.gpio_port[GPIO_D7],
317            8 => &nrf52840_peripherals.gpio_port[GPIO_D8],
318            9 => &nrf52840_peripherals.gpio_port[GPIO_D9],
319            10 => &nrf52840_peripherals.gpio_port[GPIO_D10]
320        ),
321    )
322    .finalize(components::gpio_component_static!(nrf52840::gpio::GPIOPin));
323
324    //--------------------------------------------------------------------------
325    // LEDs
326    //--------------------------------------------------------------------------
327
328    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
329        LedLow<'static, nrf52840::gpio::GPIOPin>,
330        LedLow::new(&nrf52840_peripherals.gpio_port[LED_RED_PIN]),
331        LedLow::new(&nrf52840_peripherals.gpio_port[LED_GREEN_PIN]),
332        LedLow::new(&nrf52840_peripherals.gpio_port[LED_BLUE_PIN]),
333    ));
334
335    //--------------------------------------------------------------------------
336    // ALARM & TIMER
337    //--------------------------------------------------------------------------
338
339    let rtc = &base_peripherals.rtc;
340    let _ = rtc.start();
341
342    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
343        .finalize(components::alarm_mux_component_static!(nrf52::rtc::Rtc));
344    let alarm = components::alarm::AlarmDriverComponent::new(
345        board_kernel,
346        capsules_core::alarm::DRIVER_NUM,
347        mux_alarm,
348    )
349    .finalize(components::alarm_component_static!(nrf52::rtc::Rtc));
350
351    //--------------------------------------------------------------------------
352    // UART & CONSOLE & DEBUG
353    //--------------------------------------------------------------------------
354
355    // Setup the CDC-ACM over USB driver that we will use for UART.
356    // We use the Arduino Vendor ID and Product ID since the device is the same.
357
358    // Create the strings we include in the USB descriptor. We use the hardcoded
359    // DEVICEADDR register on the nRF52 to set the serial number.
360    let serial_number_buf = static_init!([u8; 17], [0; 17]);
361    let serial_number_string: &'static str =
362        (*addr_of!(nrf52::ficr::FICR_INSTANCE)).address_str(serial_number_buf);
363    let strings = static_init!(
364        [&str; 3],
365        [
366            "Arduino",                         // Manufacturer
367            "Nano 33 BLE Sense Rev2 - TockOS", // Product
368            serial_number_string,              // Serial number
369        ]
370    );
371
372    let cdc = components::cdc::CdcAcmComponent::new(
373        &nrf52840_peripherals.usbd,
374        capsules_extra::usb::cdc::MAX_CTRL_PACKET_SIZE_NRF52840,
375        0x2341,
376        0x005a,
377        strings,
378        mux_alarm,
379        Some(&baud_rate_reset_bootloader_enter),
380    )
381    .finalize(components::cdc_acm_component_static!(
382        nrf52::usbd::Usbd,
383        nrf52::rtc::Rtc
384    ));
385    CDC_REF_FOR_PANIC = Some(cdc); //for use by panic handler
386
387    // Process Printer for displaying process information.
388    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
389        .finalize(components::process_printer_text_component_static!());
390    PROCESS_PRINTER = Some(process_printer);
391
392    // Create a shared UART channel for the console and for kernel debug.
393    let uart_mux = components::console::UartMuxComponent::new(cdc, 115200)
394        .finalize(components::uart_mux_component_static!());
395
396    let pconsole = components::process_console::ProcessConsoleComponent::new(
397        board_kernel,
398        uart_mux,
399        mux_alarm,
400        process_printer,
401        Some(cortexm4::support::reset),
402    )
403    .finalize(components::process_console_component_static!(
404        nrf52::rtc::Rtc<'static>
405    ));
406
407    // Setup the console.
408    let console = components::console::ConsoleComponent::new(
409        board_kernel,
410        capsules_core::console::DRIVER_NUM,
411        uart_mux,
412    )
413    .finalize(components::console_component_static!());
414    // Create the debugger object that handles calls to `debug!()`.
415    components::debug_writer::DebugWriterComponent::new(uart_mux)
416        .finalize(components::debug_writer_component_static!());
417
418    //--------------------------------------------------------------------------
419    // RANDOM NUMBERS
420    //--------------------------------------------------------------------------
421
422    let rng = components::rng::RngComponent::new(
423        board_kernel,
424        capsules_core::rng::DRIVER_NUM,
425        &base_peripherals.trng,
426    )
427    .finalize(components::rng_component_static!(nrf52840::trng::Trng));
428
429    //--------------------------------------------------------------------------
430    // ADC
431    //--------------------------------------------------------------------------
432    base_peripherals.adc.calibrate();
433
434    let adc_mux = components::adc::AdcMuxComponent::new(&base_peripherals.adc)
435        .finalize(components::adc_mux_component_static!(nrf52840::adc::Adc));
436
437    let adc_syscall =
438        components::adc::AdcVirtualComponent::new(board_kernel, capsules_core::adc::DRIVER_NUM)
439            .finalize(components::adc_syscall_component_helper!(
440                // A0
441                components::adc::AdcComponent::new(
442                    adc_mux,
443                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput2)
444                )
445                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
446                // A1
447                components::adc::AdcComponent::new(
448                    adc_mux,
449                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput3)
450                )
451                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
452                // A2
453                components::adc::AdcComponent::new(
454                    adc_mux,
455                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput6)
456                )
457                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
458                // A3
459                components::adc::AdcComponent::new(
460                    adc_mux,
461                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput5)
462                )
463                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
464                // A4
465                components::adc::AdcComponent::new(
466                    adc_mux,
467                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput7)
468                )
469                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
470                // A5
471                components::adc::AdcComponent::new(
472                    adc_mux,
473                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput0)
474                )
475                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
476                // A6
477                components::adc::AdcComponent::new(
478                    adc_mux,
479                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput4)
480                )
481                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
482                // A7
483                components::adc::AdcComponent::new(
484                    adc_mux,
485                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput1)
486                )
487                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
488            ));
489
490    //--------------------------------------------------------------------------
491    // SENSORS
492    //--------------------------------------------------------------------------
493
494    let sensors_i2c_bus = components::i2c::I2CMuxComponent::new(&base_peripherals.twi1, None)
495        .finalize(components::i2c_mux_component_static!(nrf52840::i2c::TWI));
496    base_peripherals.twi1.configure(
497        nrf52840::pinmux::Pinmux::new(I2C_SCL_PIN as u32),
498        nrf52840::pinmux::Pinmux::new(I2C_SDA_PIN as u32),
499    );
500
501    let _ = &nrf52840_peripherals.gpio_port[I2C_PULLUP_PIN].make_output();
502    nrf52840_peripherals.gpio_port[I2C_PULLUP_PIN].set();
503
504    let apds9960 = components::apds9960::Apds9960Component::new(
505        sensors_i2c_bus,
506        0x39,
507        &nrf52840_peripherals.gpio_port[APDS9960_PIN],
508    )
509    .finalize(components::apds9960_component_static!(nrf52840::i2c::TWI));
510    let proximity = components::proximity::ProximityComponent::new(
511        apds9960,
512        board_kernel,
513        capsules_extra::proximity::DRIVER_NUM,
514    )
515    .finalize(components::proximity_component_static!());
516
517    let lps22hb = components::lps22hb::Lps22hbComponent::new(sensors_i2c_bus, 0x5C)
518        .finalize(components::lps22hb_component_static!(nrf52840::i2c::TWI));
519    let pressure = components::pressure::PressureComponent::new(
520        board_kernel,
521        capsules_extra::pressure::DRIVER_NUM,
522        lps22hb,
523    )
524    .finalize(components::pressure_component_static!(
525        capsules_extra::lps22hb::Lps22hb<
526            'static,
527            capsules_core::virtualizers::virtual_i2c::I2CDevice<'static, nrf52840::i2c::TWI>,
528        >
529    ));
530
531    let hs3003 = components::hs3003::Hs3003Component::new(sensors_i2c_bus, 0x44)
532        .finalize(components::hs3003_component_static!(nrf52840::i2c::TWI));
533    let temperature = components::temperature::TemperatureComponent::new(
534        board_kernel,
535        capsules_extra::temperature::DRIVER_NUM,
536        hs3003,
537    )
538    .finalize(components::temperature_component_static!(HS3003Sensor));
539    let humidity = components::humidity::HumidityComponent::new(
540        board_kernel,
541        capsules_extra::humidity::DRIVER_NUM,
542        hs3003,
543    )
544    .finalize(components::humidity_component_static!(HS3003Sensor));
545
546    //--------------------------------------------------------------------------
547    // WIRELESS
548    //--------------------------------------------------------------------------
549
550    let ble_radio = components::ble::BLEComponent::new(
551        board_kernel,
552        capsules_extra::ble_advertising_driver::DRIVER_NUM,
553        &base_peripherals.ble_radio,
554        mux_alarm,
555    )
556    .finalize(components::ble_component_static!(
557        nrf52840::rtc::Rtc,
558        nrf52840::ble_radio::Radio
559    ));
560
561    use capsules_extra::net::ieee802154::MacAddress;
562
563    let aes_mux = components::ieee802154::MuxAes128ccmComponent::new(&base_peripherals.ecb)
564        .finalize(components::mux_aes128ccm_component_static!(
565            nrf52840::aes::AesECB
566        ));
567
568    let device_id = (*addr_of!(nrf52840::ficr::FICR_INSTANCE)).id();
569    let device_id_bottom_16 = u16::from_le_bytes([device_id[0], device_id[1]]);
570    let (ieee802154_radio, mux_mac) = components::ieee802154::Ieee802154Component::new(
571        board_kernel,
572        capsules_extra::ieee802154::DRIVER_NUM,
573        &nrf52840_peripherals.ieee802154_radio,
574        aes_mux,
575        PAN_ID,
576        device_id_bottom_16,
577        device_id,
578    )
579    .finalize(components::ieee802154_component_static!(
580        nrf52840::ieee802154_radio::Radio,
581        nrf52840::aes::AesECB<'static>
582    ));
583    use capsules_extra::net::ipv6::ip_utils::IPAddr;
584
585    let local_ip_ifaces = static_init!(
586        [IPAddr; 3],
587        [
588            IPAddr([
589                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
590                0x0e, 0x0f,
591            ]),
592            IPAddr([
593                0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
594                0x1e, 0x1f,
595            ]),
596            IPAddr::generate_from_mac(capsules_extra::net::ieee802154::MacAddress::Short(
597                device_id_bottom_16
598            )),
599        ]
600    );
601
602    let (udp_send_mux, udp_recv_mux, udp_port_table) = components::udp_mux::UDPMuxComponent::new(
603        mux_mac,
604        DEFAULT_CTX_PREFIX_LEN,
605        DEFAULT_CTX_PREFIX,
606        DST_MAC_ADDR,
607        MacAddress::Short(device_id_bottom_16),
608        local_ip_ifaces,
609        mux_alarm,
610    )
611    .finalize(components::udp_mux_component_static!(
612        nrf52840::rtc::Rtc,
613        Ieee802154MacDevice
614    ));
615
616    // UDP driver initialization happens here
617    let udp_driver = components::udp_driver::UDPDriverComponent::new(
618        board_kernel,
619        capsules_extra::net::udp::DRIVER_NUM,
620        udp_send_mux,
621        udp_recv_mux,
622        udp_port_table,
623        local_ip_ifaces,
624    )
625    .finalize(components::udp_driver_component_static!(nrf52840::rtc::Rtc));
626
627    //--------------------------------------------------------------------------
628    // FINAL SETUP AND BOARD BOOT
629    //--------------------------------------------------------------------------
630
631    // Start all of the clocks. Low power operation will require a better
632    // approach than this.
633    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
634
635    let scheduler = components::sched::round_robin::RoundRobinComponent::new(&*addr_of!(PROCESSES))
636        .finalize(components::round_robin_component_static!(NUM_PROCS));
637
638    let platform = Platform {
639        ble_radio,
640        ieee802154_radio,
641        console,
642        pconsole,
643        proximity,
644        pressure,
645        temperature,
646        humidity,
647        adc: adc_syscall,
648        led,
649        gpio,
650        rng,
651        alarm,
652        udp_driver,
653        ipc: kernel::ipc::IPC::new(
654            board_kernel,
655            kernel::ipc::DRIVER_NUM,
656            &memory_allocation_capability,
657        ),
658        scheduler,
659        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
660    };
661
662    let chip = static_init!(
663        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
664        nrf52840::chip::NRF52::new(nrf52840_peripherals)
665    );
666    CHIP = Some(chip);
667
668    // Need to disable the MPU because the bootloader seems to set it up.
669    chip.mpu().clear_mpu();
670
671    // Configure the USB stack to enable a serial port over CDC-ACM.
672    cdc.enable();
673    cdc.attach();
674
675    //--------------------------------------------------------------------------
676    // TESTS
677    //--------------------------------------------------------------------------
678    // test::linear_log_test::run(
679    //     mux_alarm,
680    //     &nrf52840_peripherals.nrf52.nvmc,
681    // );
682    // test::log_test::run(
683    //     mux_alarm,
684    //     &nrf52840_peripherals.nrf52.nvmc,
685    // );
686
687    debug!("Initialization complete. Entering main loop.");
688    let _ = platform.pconsole.start();
689
690    //--------------------------------------------------------------------------
691    // PROCESSES AND MAIN LOOP
692    //--------------------------------------------------------------------------
693
694    // These symbols are defined in the linker script.
695    extern "C" {
696        /// Beginning of the ROM region containing app images.
697        static _sapps: u8;
698        /// End of the ROM region containing app images.
699        static _eapps: u8;
700        /// Beginning of the RAM region for app memory.
701        static mut _sappmem: u8;
702        /// End of the RAM region for app memory.
703        static _eappmem: u8;
704    }
705
706    kernel::process::load_processes(
707        board_kernel,
708        chip,
709        core::slice::from_raw_parts(
710            core::ptr::addr_of!(_sapps),
711            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
712        ),
713        core::slice::from_raw_parts_mut(
714            core::ptr::addr_of_mut!(_sappmem),
715            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
716        ),
717        &mut *addr_of_mut!(PROCESSES),
718        &FAULT_RESPONSE,
719        &process_management_capability,
720    )
721    .unwrap_or_else(|err| {
722        debug!("Error loading processes!");
723        debug!("{:?}", err);
724    });
725
726    (board_kernel, platform, chip)
727}
728
729/// Main function called after RAM initialized.
730#[no_mangle]
731pub unsafe fn main() {
732    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
733
734    let (board_kernel, platform, chip) = start();
735    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
736}