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