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