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