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    // Initialize deferred calls very early.
254    kernel::deferred_call::initialize_deferred_call_state::<
255        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
256    >();
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    // Create an array to hold process references.
278    let processes = components::process_array::ProcessArrayComponent::new()
279        .finalize(components::process_array_component_static!(NUM_PROCS));
280    PROCESSES = Some(processes);
281
282    // Setup space to store the core kernel data structure.
283    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
284
285    //--------------------------------------------------------------------------
286    // CAPABILITIES
287    //--------------------------------------------------------------------------
288
289    // Create capabilities that the board needs to call certain protected kernel
290    // functions.
291    let process_management_capability =
292        create_capability!(capabilities::ProcessManagementCapability);
293    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
294
295    //--------------------------------------------------------------------------
296    // DEBUG GPIO
297    //--------------------------------------------------------------------------
298
299    // Configure kernel debug GPIOs as early as possible. These are used by the
300    // `debug_gpio!(0, toggle)` macro. We configure these early so that the
301    // macro is available during most of the setup code and kernel execution.
302    let debug_gpios = static_init!(
303        [&'static dyn kernel::hil::gpio::Pin; 1],
304        [&nrf52840_peripherals.gpio_port[LED_KERNEL_PIN]]
305    );
306    kernel::debug::initialize_debug_gpio::<
307        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
308    >();
309    kernel::debug::assign_gpios(debug_gpios);
310
311    //--------------------------------------------------------------------------
312    // GPIO
313    //--------------------------------------------------------------------------
314
315    let gpio = components::gpio::GpioComponent::new(
316        board_kernel,
317        capsules_core::gpio::DRIVER_NUM,
318        components::gpio_component_helper!(
319            nrf52840::gpio::GPIOPin,
320            2 => &nrf52840_peripherals.gpio_port[GPIO_D2],
321            3 => &nrf52840_peripherals.gpio_port[GPIO_D3],
322            4 => &nrf52840_peripherals.gpio_port[GPIO_D4],
323            5 => &nrf52840_peripherals.gpio_port[GPIO_D5],
324            6 => &nrf52840_peripherals.gpio_port[GPIO_D6],
325            7 => &nrf52840_peripherals.gpio_port[GPIO_D7],
326            8 => &nrf52840_peripherals.gpio_port[GPIO_D8],
327            9 => &nrf52840_peripherals.gpio_port[GPIO_D9],
328            10 => &nrf52840_peripherals.gpio_port[GPIO_D10]
329        ),
330    )
331    .finalize(components::gpio_component_static!(nrf52840::gpio::GPIOPin));
332
333    //--------------------------------------------------------------------------
334    // LEDs
335    //--------------------------------------------------------------------------
336
337    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
338        LedLow<'static, nrf52840::gpio::GPIOPin>,
339        LedLow::new(&nrf52840_peripherals.gpio_port[LED_RED_PIN]),
340        LedLow::new(&nrf52840_peripherals.gpio_port[LED_GREEN_PIN]),
341        LedLow::new(&nrf52840_peripherals.gpio_port[LED_BLUE_PIN]),
342    ));
343
344    //--------------------------------------------------------------------------
345    // ALARM & TIMER
346    //--------------------------------------------------------------------------
347
348    let rtc = &base_peripherals.rtc;
349    let _ = rtc.start();
350
351    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
352        .finalize(components::alarm_mux_component_static!(nrf52::rtc::Rtc));
353    let alarm = components::alarm::AlarmDriverComponent::new(
354        board_kernel,
355        capsules_core::alarm::DRIVER_NUM,
356        mux_alarm,
357    )
358    .finalize(components::alarm_component_static!(nrf52::rtc::Rtc));
359
360    //--------------------------------------------------------------------------
361    // UART & CONSOLE & DEBUG
362    //--------------------------------------------------------------------------
363
364    // Setup the CDC-ACM over USB driver that we will use for UART.
365    // We use the Arduino Vendor ID and Product ID since the device is the same.
366
367    // Create the strings we include in the USB descriptor. We use the hardcoded
368    // DEVICEADDR register on the nRF52 to set the serial number.
369    let serial_number_buf = static_init!([u8; 17], [0; 17]);
370    let serial_number_string: &'static str =
371        (*addr_of!(nrf52::ficr::FICR_INSTANCE)).address_str(serial_number_buf);
372    let strings = static_init!(
373        [&str; 3],
374        [
375            "Arduino",                         // Manufacturer
376            "Nano 33 BLE Sense Rev2 - TockOS", // Product
377            serial_number_string,              // Serial number
378        ]
379    );
380
381    let cdc = components::cdc::CdcAcmComponent::new(
382        &nrf52840_peripherals.usbd,
383        capsules_extra::usb::cdc::MAX_CTRL_PACKET_SIZE_NRF52840,
384        0x2341,
385        0x005a,
386        strings,
387        mux_alarm,
388        Some(&baud_rate_reset_bootloader_enter),
389    )
390    .finalize(components::cdc_acm_component_static!(
391        nrf52::usbd::Usbd,
392        nrf52::rtc::Rtc
393    ));
394    CDC_REF_FOR_PANIC = Some(cdc); //for use by panic handler
395
396    // Process Printer for displaying process information.
397    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
398        .finalize(components::process_printer_text_component_static!());
399    PROCESS_PRINTER = Some(process_printer);
400
401    // Create a shared UART channel for the console and for kernel debug.
402    let uart_mux = components::console::UartMuxComponent::new(cdc, 115200)
403        .finalize(components::uart_mux_component_static!());
404
405    let pconsole = components::process_console::ProcessConsoleComponent::new(
406        board_kernel,
407        uart_mux,
408        mux_alarm,
409        process_printer,
410        Some(cortexm4::support::reset),
411    )
412    .finalize(components::process_console_component_static!(
413        nrf52::rtc::Rtc<'static>
414    ));
415
416    // Setup the console.
417    let console = components::console::ConsoleComponent::new(
418        board_kernel,
419        capsules_core::console::DRIVER_NUM,
420        uart_mux,
421    )
422    .finalize(components::console_component_static!());
423    // Create the debugger object that handles calls to `debug!()`.
424    components::debug_writer::DebugWriterComponent::new::<
425        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
426    >(
427        uart_mux,
428        create_capability!(capabilities::SetDebugWriterCapability),
429    )
430    .finalize(components::debug_writer_component_static!());
431
432    //--------------------------------------------------------------------------
433    // RANDOM NUMBERS
434    //--------------------------------------------------------------------------
435
436    let rng = components::rng::RngComponent::new(
437        board_kernel,
438        capsules_core::rng::DRIVER_NUM,
439        &base_peripherals.trng,
440    )
441    .finalize(components::rng_component_static!(nrf52840::trng::Trng));
442
443    //--------------------------------------------------------------------------
444    // ADC
445    //--------------------------------------------------------------------------
446    base_peripherals.adc.calibrate();
447
448    let adc_mux = components::adc::AdcMuxComponent::new(&base_peripherals.adc)
449        .finalize(components::adc_mux_component_static!(nrf52840::adc::Adc));
450
451    let adc_syscall =
452        components::adc::AdcVirtualComponent::new(board_kernel, capsules_core::adc::DRIVER_NUM)
453            .finalize(components::adc_syscall_component_helper!(
454                // A0
455                components::adc::AdcComponent::new(
456                    adc_mux,
457                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput2)
458                )
459                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
460                // A1
461                components::adc::AdcComponent::new(
462                    adc_mux,
463                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput3)
464                )
465                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
466                // A2
467                components::adc::AdcComponent::new(
468                    adc_mux,
469                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput6)
470                )
471                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
472                // A3
473                components::adc::AdcComponent::new(
474                    adc_mux,
475                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput5)
476                )
477                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
478                // A4
479                components::adc::AdcComponent::new(
480                    adc_mux,
481                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput7)
482                )
483                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
484                // A5
485                components::adc::AdcComponent::new(
486                    adc_mux,
487                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput0)
488                )
489                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
490                // A6
491                components::adc::AdcComponent::new(
492                    adc_mux,
493                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput4)
494                )
495                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
496                // A7
497                components::adc::AdcComponent::new(
498                    adc_mux,
499                    nrf52840::adc::AdcChannelSetup::new(nrf52840::adc::AdcChannel::AnalogInput1)
500                )
501                .finalize(components::adc_component_static!(nrf52840::adc::Adc)),
502            ));
503
504    //--------------------------------------------------------------------------
505    // SENSORS
506    //--------------------------------------------------------------------------
507
508    let sensors_i2c_bus = components::i2c::I2CMuxComponent::new(&base_peripherals.twi1, None)
509        .finalize(components::i2c_mux_component_static!(nrf52840::i2c::TWI));
510    base_peripherals.twi1.configure(
511        nrf52840::pinmux::Pinmux::new(I2C_SCL_PIN as u32),
512        nrf52840::pinmux::Pinmux::new(I2C_SDA_PIN as u32),
513    );
514
515    let _ = &nrf52840_peripherals.gpio_port[I2C_PULLUP_PIN].make_output();
516    nrf52840_peripherals.gpio_port[I2C_PULLUP_PIN].set();
517
518    let apds9960 = components::apds9960::Apds9960Component::new(
519        sensors_i2c_bus,
520        0x39,
521        &nrf52840_peripherals.gpio_port[APDS9960_PIN],
522    )
523    .finalize(components::apds9960_component_static!(nrf52840::i2c::TWI));
524    let proximity = components::proximity::ProximityComponent::new(
525        apds9960,
526        board_kernel,
527        capsules_extra::proximity::DRIVER_NUM,
528    )
529    .finalize(components::proximity_component_static!());
530
531    let lps22hb = components::lps22hb::Lps22hbComponent::new(sensors_i2c_bus, 0x5C)
532        .finalize(components::lps22hb_component_static!(nrf52840::i2c::TWI));
533    let pressure = components::pressure::PressureComponent::new(
534        board_kernel,
535        capsules_extra::pressure::DRIVER_NUM,
536        lps22hb,
537    )
538    .finalize(components::pressure_component_static!(
539        capsules_extra::lps22hb::Lps22hb<
540            'static,
541            capsules_core::virtualizers::virtual_i2c::I2CDevice<'static, nrf52840::i2c::TWI>,
542        >
543    ));
544
545    let hs3003 = components::hs3003::Hs3003Component::new(sensors_i2c_bus, 0x44)
546        .finalize(components::hs3003_component_static!(nrf52840::i2c::TWI));
547    let temperature = components::temperature::TemperatureComponent::new(
548        board_kernel,
549        capsules_extra::temperature::DRIVER_NUM,
550        hs3003,
551    )
552    .finalize(components::temperature_component_static!(HS3003Sensor));
553    let humidity = components::humidity::HumidityComponent::new(
554        board_kernel,
555        capsules_extra::humidity::DRIVER_NUM,
556        hs3003,
557    )
558    .finalize(components::humidity_component_static!(HS3003Sensor));
559
560    //--------------------------------------------------------------------------
561    // WIRELESS
562    //--------------------------------------------------------------------------
563
564    let ble_radio = components::ble::BLEComponent::new(
565        board_kernel,
566        capsules_extra::ble_advertising_driver::DRIVER_NUM,
567        &base_peripherals.ble_radio,
568        mux_alarm,
569    )
570    .finalize(components::ble_component_static!(
571        nrf52840::rtc::Rtc,
572        nrf52840::ble_radio::Radio
573    ));
574
575    use capsules_extra::net::ieee802154::MacAddress;
576
577    let aes_mux = components::ieee802154::MuxAes128ccmComponent::new(&base_peripherals.ecb)
578        .finalize(components::mux_aes128ccm_component_static!(
579            nrf52840::aes::AesECB
580        ));
581
582    let device_id = (*addr_of!(nrf52840::ficr::FICR_INSTANCE)).id();
583    let device_id_bottom_16 = u16::from_le_bytes([device_id[0], device_id[1]]);
584    let (ieee802154_radio, mux_mac) = components::ieee802154::Ieee802154Component::new(
585        board_kernel,
586        capsules_extra::ieee802154::DRIVER_NUM,
587        &nrf52840_peripherals.ieee802154_radio,
588        aes_mux,
589        PAN_ID,
590        device_id_bottom_16,
591        device_id,
592    )
593    .finalize(components::ieee802154_component_static!(
594        nrf52840::ieee802154_radio::Radio,
595        nrf52840::aes::AesECB<'static>
596    ));
597    use capsules_extra::net::ipv6::ip_utils::IPAddr;
598
599    let local_ip_ifaces = static_init!(
600        [IPAddr; 3],
601        [
602            IPAddr([
603                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
604                0x0e, 0x0f,
605            ]),
606            IPAddr([
607                0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
608                0x1e, 0x1f,
609            ]),
610            IPAddr::generate_from_mac(capsules_extra::net::ieee802154::MacAddress::Short(
611                device_id_bottom_16
612            )),
613        ]
614    );
615
616    let (udp_send_mux, udp_recv_mux, udp_port_table) = components::udp_mux::UDPMuxComponent::new(
617        mux_mac,
618        DEFAULT_CTX_PREFIX_LEN,
619        DEFAULT_CTX_PREFIX,
620        DST_MAC_ADDR,
621        MacAddress::Short(device_id_bottom_16),
622        local_ip_ifaces,
623        mux_alarm,
624    )
625    .finalize(components::udp_mux_component_static!(
626        nrf52840::rtc::Rtc,
627        Ieee802154MacDevice
628    ));
629
630    // UDP driver initialization happens here
631    let udp_driver = components::udp_driver::UDPDriverComponent::new(
632        board_kernel,
633        capsules_extra::net::udp::DRIVER_NUM,
634        udp_send_mux,
635        udp_recv_mux,
636        udp_port_table,
637        local_ip_ifaces,
638    )
639    .finalize(components::udp_driver_component_static!(nrf52840::rtc::Rtc));
640
641    //--------------------------------------------------------------------------
642    // FINAL SETUP AND BOARD BOOT
643    //--------------------------------------------------------------------------
644
645    // Start all of the clocks. Low power operation will require a better
646    // approach than this.
647    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
648
649    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
650        .finalize(components::round_robin_component_static!(NUM_PROCS));
651
652    let platform = Platform {
653        ble_radio,
654        ieee802154_radio,
655        console,
656        pconsole,
657        proximity,
658        pressure,
659        temperature,
660        humidity,
661        adc: adc_syscall,
662        led,
663        gpio,
664        rng,
665        alarm,
666        udp_driver,
667        ipc: kernel::ipc::IPC::new(
668            board_kernel,
669            kernel::ipc::DRIVER_NUM,
670            &memory_allocation_capability,
671        ),
672        scheduler,
673        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
674    };
675
676    let chip = static_init!(
677        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
678        nrf52840::chip::NRF52::new(nrf52840_peripherals)
679    );
680    CHIP = Some(chip);
681
682    // Need to disable the MPU because the bootloader seems to set it up.
683    chip.mpu().clear_mpu();
684
685    // Configure the USB stack to enable a serial port over CDC-ACM.
686    cdc.enable();
687    cdc.attach();
688
689    //--------------------------------------------------------------------------
690    // TESTS
691    //--------------------------------------------------------------------------
692    // test::linear_log_test::run(
693    //     mux_alarm,
694    //     &nrf52840_peripherals.nrf52.nvmc,
695    // );
696    // test::log_test::run(
697    //     mux_alarm,
698    //     &nrf52840_peripherals.nrf52.nvmc,
699    // );
700
701    debug!("Initialization complete. Entering main loop.");
702    let _ = platform.pconsole.start();
703
704    //--------------------------------------------------------------------------
705    // PROCESSES AND MAIN LOOP
706    //--------------------------------------------------------------------------
707
708    // These symbols are defined in the linker script.
709    extern "C" {
710        /// Beginning of the ROM region containing app images.
711        static _sapps: u8;
712        /// End of the ROM region containing app images.
713        static _eapps: u8;
714        /// Beginning of the RAM region for app memory.
715        static mut _sappmem: u8;
716        /// End of the RAM region for app memory.
717        static _eappmem: u8;
718    }
719
720    kernel::process::load_processes(
721        board_kernel,
722        chip,
723        core::slice::from_raw_parts(
724            core::ptr::addr_of!(_sapps),
725            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
726        ),
727        core::slice::from_raw_parts_mut(
728            core::ptr::addr_of_mut!(_sappmem),
729            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
730        ),
731        &FAULT_RESPONSE,
732        &process_management_capability,
733    )
734    .unwrap_or_else(|err| {
735        debug!("Error loading processes!");
736        debug!("{:?}", err);
737    });
738
739    (board_kernel, platform, chip)
740}
741
742/// Main function called after RAM initialized.
743#[no_mangle]
744pub unsafe fn main() {
745    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
746
747    let (board_kernel, platform, chip) = start();
748    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
749}