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