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