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