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