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