wm1110dev/
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 2023.
4
5//! Tock kernel for the Wio WM1110 Development Board.
6//!
7//! It is based on nRF52840 SoC and Semtech LR1110.
8
9#![no_std]
10#![no_main]
11#![deny(missing_docs)]
12
13use kernel::capabilities;
14use kernel::component::Component;
15use kernel::hil;
16use kernel::hil::gpio::Configure;
17use kernel::hil::gpio::Output;
18use kernel::hil::led::LedHigh;
19use kernel::hil::spi::SpiMaster;
20use kernel::hil::time::Counter;
21use kernel::platform::{KernelResources, SyscallDriverLookup};
22use kernel::process::ProcessArray;
23use kernel::scheduler::round_robin::RoundRobinSched;
24#[allow(unused_imports)]
25use kernel::{create_capability, debug, debug_gpio, debug_verbose, static_init};
26
27use nrf52840::gpio::Pin;
28use nrf52840::interrupt_service::Nrf52840DefaultPeripherals;
29
30// Three-color LED.
31const LED_RED_PIN: Pin = Pin::P0_14;
32const LED_GREEN_PIN: Pin = Pin::P0_13;
33
34const BUTTON_RST_PIN: Pin = Pin::P0_18;
35
36const GPIO_D2: Pin = Pin::P0_17;
37const GPIO_D3: Pin = Pin::P0_16;
38const GPIO_D4: Pin = Pin::P0_15;
39const GPIO_D5: Pin = Pin::P1_09;
40const GPIO_D6: Pin = Pin::P1_04;
41const GPIO_D7: Pin = Pin::P1_03;
42
43const UART_TX_PIN: Pin = Pin::P0_24;
44const UART_RX_PIN: Pin = Pin::P0_22;
45
46/// I2C pins for all of the sensors.
47const I2C_SDA_PIN: Pin = Pin::P0_27;
48const I2C_SCL_PIN: Pin = Pin::P0_26;
49
50// Pins for communicating with LR1110
51const SPI_CS_PIN: Pin = Pin::P1_12;
52const SPI_SCK_PIN: Pin = Pin::P1_13;
53const SPI_MOSI_PIN: Pin = Pin::P1_14;
54const SPI_MISO_PIN: Pin = Pin::P1_15;
55const RADIO_BUSY_PIN: Pin = Pin::P1_11;
56const RADIO_RESET_PIN: Pin = Pin::P1_10;
57
58const LR_DIO9: Pin = Pin::P1_08;
59
60/// GPIO pin that controls VCC for the I2C bus and sensors.
61const I2C_PWR: Pin = Pin::P0_07;
62
63const LORA_SPI_DRIVER_NUM: usize = capsules_core::driver::NUM::LoRaPhySPI as usize;
64const LORA_GPIO_DRIVER_NUM: usize = capsules_core::driver::NUM::LoRaPhyGPIO as usize;
65
66/// UART Writer for panic!()s.
67pub mod io;
68
69// How should the kernel respond when a process faults. For this board we choose
70// to stop the app and print a notice, but not immediately panic.
71const FAULT_RESPONSE: capsules_system::process_policies::StopWithDebugFaultPolicy =
72    capsules_system::process_policies::StopWithDebugFaultPolicy {};
73
74// Number of concurrent processes this platform supports.
75const NUM_PROCS: usize = 8;
76
77type ChipHw = nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>;
78
79/// Static variables used by io.rs.
80static mut PROCESSES: Option<&'static ProcessArray<NUM_PROCS>> = None;
81static mut CHIP: Option<&'static nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>> = None;
82static mut PROCESS_PRINTER: Option<&'static capsules_system::process_printer::ProcessPrinterText> =
83    None;
84
85kernel::stack_size! {0x1000}
86
87type SHT4xSensor = components::sht4x::SHT4xComponentType<
88    capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<'static, nrf52::rtc::Rtc<'static>>,
89    capsules_core::virtualizers::virtual_i2c::I2CDevice<'static, nrf52840::i2c::TWI<'static>>,
90>;
91type TemperatureDriver = components::temperature::TemperatureComponentType<SHT4xSensor>;
92type HumidityDriver = components::humidity::HumidityComponentType<SHT4xSensor>;
93type RngDriver = components::rng::RngComponentType<nrf52840::trng::Trng<'static>>;
94
95type NonvolatileDriver = components::nonvolatile_storage::NonvolatileStorageComponentType;
96
97/// Supported drivers by the platform
98pub struct Platform {
99    console: &'static capsules_core::console::Console<'static>,
100    gpio: &'static capsules_core::gpio::GPIO<'static, nrf52::gpio::GPIOPin<'static>>,
101    led: &'static capsules_core::led::LedDriver<
102        'static,
103        LedHigh<'static, nrf52::gpio::GPIOPin<'static>>,
104        2,
105    >,
106    rng: &'static RngDriver,
107    ipc: kernel::ipc::IPC<{ NUM_PROCS as u8 }>,
108    nonvolatile_storage: &'static NonvolatileDriver,
109    alarm: &'static capsules_core::alarm::AlarmDriver<
110        'static,
111        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<
112            'static,
113            nrf52::rtc::Rtc<'static>,
114        >,
115    >,
116    temperature: &'static TemperatureDriver,
117    humidity: &'static HumidityDriver,
118    lr1110_gpio: &'static capsules_core::gpio::GPIO<'static, nrf52840::gpio::GPIOPin<'static>>,
119    lr1110_spi: &'static capsules_core::spi_controller::Spi<
120        'static,
121        capsules_core::virtualizers::virtual_spi::VirtualSpiMasterDevice<
122            'static,
123            nrf52840::spi::SPIM<'static>,
124        >,
125    >,
126    scheduler: &'static RoundRobinSched<'static>,
127    systick: cortexm4::systick::SysTick,
128}
129
130impl SyscallDriverLookup for Platform {
131    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
132    where
133        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
134    {
135        match driver_num {
136            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
137            capsules_core::gpio::DRIVER_NUM => f(Some(self.gpio)),
138            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
139            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
140            capsules_core::rng::DRIVER_NUM => f(Some(self.rng)),
141            capsules_extra::nonvolatile_storage_driver::DRIVER_NUM => {
142                f(Some(self.nonvolatile_storage))
143            }
144            LORA_SPI_DRIVER_NUM => f(Some(self.lr1110_spi)),
145            LORA_GPIO_DRIVER_NUM => f(Some(self.lr1110_gpio)),
146            kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
147            capsules_extra::temperature::DRIVER_NUM => f(Some(self.temperature)),
148            capsules_extra::humidity::DRIVER_NUM => f(Some(self.humidity)),
149            _ => f(None),
150        }
151    }
152}
153
154impl KernelResources<nrf52::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>>
155    for Platform
156{
157    type SyscallDriverLookup = Self;
158    type SyscallFilter = ();
159    type ProcessFault = ();
160    type Scheduler = RoundRobinSched<'static>;
161    type SchedulerTimer = cortexm4::systick::SysTick;
162    type WatchDog = ();
163    type ContextSwitchCallback = ();
164
165    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
166        self
167    }
168    fn syscall_filter(&self) -> &Self::SyscallFilter {
169        &()
170    }
171    fn process_fault(&self) -> &Self::ProcessFault {
172        &()
173    }
174    fn scheduler(&self) -> &Self::Scheduler {
175        self.scheduler
176    }
177    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
178        &self.systick
179    }
180    fn watchdog(&self) -> &Self::WatchDog {
181        &()
182    }
183    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
184        &()
185    }
186}
187
188/// This is in a separate, inline(never) function so that its stack frame is
189/// removed when this function returns. Otherwise, the stack space used for
190/// these static_inits is wasted.
191#[inline(never)]
192pub unsafe fn start() -> (
193    &'static kernel::Kernel,
194    Platform,
195    &'static nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>,
196) {
197    nrf52840::init();
198
199    // Initialize deferred calls very early.
200    kernel::deferred_call::initialize_deferred_call_state::<
201        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
202    >();
203
204    let ieee802154_ack_buf = static_init!(
205        [u8; nrf52840::ieee802154_radio::ACK_BUF_SIZE],
206        [0; nrf52840::ieee802154_radio::ACK_BUF_SIZE]
207    );
208
209    // Initialize chip peripheral drivers
210    let nrf52840_peripherals = static_init!(
211        Nrf52840DefaultPeripherals,
212        Nrf52840DefaultPeripherals::new(ieee802154_ack_buf)
213    );
214
215    // set up circular peripheral dependencies
216    nrf52840_peripherals.init();
217    let base_peripherals = &nrf52840_peripherals.nrf52;
218
219    // Create an array to hold process references.
220    let processes = components::process_array::ProcessArrayComponent::new()
221        .finalize(components::process_array_component_static!(NUM_PROCS));
222    PROCESSES = Some(processes);
223
224    // Setup space to store the core kernel data structure.
225    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
226
227    nrf52_components::startup::NrfStartupComponent::new(
228        false,
229        BUTTON_RST_PIN,
230        nrf52840::uicr::Regulator0Output::DEFAULT,
231        &base_peripherals.nvmc,
232    )
233    .finalize(());
234
235    //--------------------------------------------------------------------------
236    // CAPABILITIES
237    //--------------------------------------------------------------------------
238
239    // Create capabilities that the board needs to call certain protected kernel
240    // functions.
241    let process_management_capability =
242        create_capability!(capabilities::ProcessManagementCapability);
243    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
244
245    //--------------------------------------------------------------------------
246    // DEBUG GPIO
247    //--------------------------------------------------------------------------
248
249    // Configure kernel debug GPIOs as early as possible. These are used by the
250    // `debug_gpio!(0, toggle)` macro. We configure these early so that the
251    // macro is available during most of the setup code and kernel execution.
252    let debug_gpios = static_init!(
253        [&'static dyn kernel::hil::gpio::Pin; 2],
254        [
255            &nrf52840_peripherals.gpio_port[LED_GREEN_PIN],
256            &nrf52840_peripherals.gpio_port[LED_RED_PIN]
257        ]
258    );
259    kernel::debug::initialize_debug_gpio::<
260        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
261    >();
262    kernel::debug::assign_gpios(debug_gpios);
263
264    //--------------------------------------------------------------------------
265    // GPIO
266    //--------------------------------------------------------------------------
267
268    let gpio = components::gpio::GpioComponent::new(
269        board_kernel,
270        capsules_core::gpio::DRIVER_NUM,
271        components::gpio_component_helper!(
272            nrf52840::gpio::GPIOPin,
273            2 => &nrf52840_peripherals.gpio_port[GPIO_D2],
274            3 => &nrf52840_peripherals.gpio_port[GPIO_D3],
275            4 => &nrf52840_peripherals.gpio_port[GPIO_D4],
276            5 => &nrf52840_peripherals.gpio_port[GPIO_D5],
277            6 => &nrf52840_peripherals.gpio_port[GPIO_D6],
278            7 => &nrf52840_peripherals.gpio_port[GPIO_D7],
279        ),
280    )
281    .finalize(components::gpio_component_static!(nrf52840::gpio::GPIOPin));
282
283    //--------------------------------------------------------------------------
284    // LEDs
285    //--------------------------------------------------------------------------
286
287    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
288        LedHigh<'static, nrf52840::gpio::GPIOPin>,
289        LedHigh::new(&nrf52840_peripherals.gpio_port[LED_GREEN_PIN]),
290        LedHigh::new(&nrf52840_peripherals.gpio_port[LED_RED_PIN]),
291    ));
292
293    //--------------------------------------------------------------------------
294    // ALARM & TIMER
295    //--------------------------------------------------------------------------
296
297    let rtc = &base_peripherals.rtc;
298    let _ = rtc.start();
299
300    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
301        .finalize(components::alarm_mux_component_static!(nrf52::rtc::Rtc));
302    let alarm = components::alarm::AlarmDriverComponent::new(
303        board_kernel,
304        capsules_core::alarm::DRIVER_NUM,
305        mux_alarm,
306    )
307    .finalize(components::alarm_component_static!(nrf52::rtc::Rtc));
308
309    //--------------------------------------------------------------------------
310    // UART & CONSOLE & DEBUG
311    //--------------------------------------------------------------------------
312
313    base_peripherals.uarte0.initialize(
314        nrf52::pinmux::Pinmux::new(UART_TX_PIN as u32),
315        nrf52::pinmux::Pinmux::new(UART_RX_PIN as u32),
316        None,
317        None,
318    );
319
320    // Create a shared UART channel for the console and for kernel debug.
321    let uart_mux = components::console::UartMuxComponent::new(&base_peripherals.uarte0, 115200)
322        .finalize(components::uart_mux_component_static!());
323
324    // Setup the console.
325    let console = components::console::ConsoleComponent::new(
326        board_kernel,
327        capsules_core::console::DRIVER_NUM,
328        uart_mux,
329    )
330    .finalize(components::console_component_static!());
331
332    // Create the debugger object that handles calls to `debug!()`.
333    components::debug_writer::DebugWriterComponent::new::<
334        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
335    >(
336        uart_mux,
337        create_capability!(capabilities::SetDebugWriterCapability),
338    )
339    .finalize(components::debug_writer_component_static!());
340
341    //--------------------------------------------------------------------------
342    // SENSORS
343    //--------------------------------------------------------------------------
344
345    // Enable the power supply for the I2C bus and attached sensors.
346    nrf52840_peripherals.gpio_port[I2C_PWR].make_output();
347    nrf52840_peripherals.gpio_port[I2C_PWR].set();
348
349    let mux_i2c = components::i2c::I2CMuxComponent::new(&base_peripherals.twi1, None)
350        .finalize(components::i2c_mux_component_static!(nrf52840::i2c::TWI));
351    base_peripherals.twi1.configure(
352        nrf52840::pinmux::Pinmux::new(I2C_SCL_PIN as u32),
353        nrf52840::pinmux::Pinmux::new(I2C_SDA_PIN as u32),
354    );
355
356    let sht4x = components::sht4x::SHT4xComponent::new(
357        mux_i2c,
358        capsules_extra::sht4x::BASE_ADDR,
359        mux_alarm,
360    )
361    .finalize(components::sht4x_component_static!(
362        nrf52::rtc::Rtc<'static>,
363        nrf52840::i2c::TWI
364    ));
365
366    let temperature = components::temperature::TemperatureComponent::new(
367        board_kernel,
368        capsules_extra::temperature::DRIVER_NUM,
369        sht4x,
370    )
371    .finalize(components::temperature_component_static!(SHT4xSensor));
372
373    let humidity = components::humidity::HumidityComponent::new(
374        board_kernel,
375        capsules_extra::humidity::DRIVER_NUM,
376        sht4x,
377    )
378    .finalize(components::humidity_component_static!(SHT4xSensor));
379
380    //--------------------------------------------------------------------------
381    // LoRa (SPI + GPIO)
382    //--------------------------------------------------------------------------
383
384    let mux_spi = components::spi::SpiMuxComponent::new(&base_peripherals.spim0)
385        .finalize(components::spi_mux_component_static!(nrf52840::spi::SPIM));
386
387    // Create the SPI system call capsule for accessing the LoRa radio.
388    let lr1110_spi = components::spi::SpiSyscallComponent::new(
389        board_kernel,
390        mux_spi,
391        hil::spi::cs::IntoChipSelect::<_, hil::spi::cs::ActiveLow>::into_cs(
392            &nrf52840_peripherals.gpio_port[SPI_CS_PIN],
393        ),
394        LORA_SPI_DRIVER_NUM,
395    )
396    .finalize(components::spi_syscall_component_static!(
397        nrf52840::spi::SPIM
398    ));
399
400    base_peripherals.spim0.configure(
401        nrf52840::pinmux::Pinmux::new(SPI_MOSI_PIN as u32),
402        nrf52840::pinmux::Pinmux::new(SPI_MISO_PIN as u32),
403        nrf52840::pinmux::Pinmux::new(SPI_SCK_PIN as u32),
404    );
405
406    base_peripherals
407        .spim0
408        .specify_chip_select(
409            hil::spi::cs::IntoChipSelect::<_, hil::spi::cs::ActiveLow>::into_cs(
410                &nrf52840_peripherals.gpio_port[SPI_CS_PIN],
411            ),
412        )
413        .unwrap();
414
415    // Pin mappings from the original WM1110 source code.
416    let lr1110_gpio = components::gpio::GpioComponent::new(
417        board_kernel,
418        LORA_GPIO_DRIVER_NUM,
419        components::gpio_component_helper!(
420            nrf52840::gpio::GPIOPin,
421            40 => &nrf52840_peripherals.gpio_port[LR_DIO9],
422            42 => &nrf52840_peripherals.gpio_port[RADIO_RESET_PIN],
423            43 => &nrf52840_peripherals.gpio_port[RADIO_BUSY_PIN],
424        ),
425    )
426    .finalize(components::gpio_component_static!(nrf52840::gpio::GPIOPin));
427
428    //--------------------------------------------------------------------------
429    // Process Console
430    //--------------------------------------------------------------------------
431
432    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
433        .finalize(components::process_printer_text_component_static!());
434    PROCESS_PRINTER = Some(process_printer);
435
436    let _process_console = components::process_console::ProcessConsoleComponent::new(
437        board_kernel,
438        uart_mux,
439        mux_alarm,
440        process_printer,
441        Some(cortexm4::support::reset),
442    )
443    .finalize(components::process_console_component_static!(
444        nrf52840::rtc::Rtc
445    ));
446
447    //--------------------------------------------------------------------------
448    // RANDOM NUMBERS
449    //--------------------------------------------------------------------------
450
451    let rng = components::rng::RngComponent::new(
452        board_kernel,
453        capsules_core::rng::DRIVER_NUM,
454        &base_peripherals.trng,
455    )
456    .finalize(components::rng_component_static!(nrf52840::trng::Trng));
457
458    //--------------------------------------------------------------------------
459    // NONVOLATILE STORAGE
460    //--------------------------------------------------------------------------
461
462    let nonvolatile_storage = components::nonvolatile_storage::NonvolatileStorageComponent::new(
463        board_kernel,
464        capsules_extra::nonvolatile_storage_driver::DRIVER_NUM,
465        &base_peripherals.nvmc,
466        0xFC000,  // Start address for userspace accessible region
467        4096 * 4, // Length of userspace accessible region (16 pages)
468        0,        // No kernel access
469        0,
470    )
471    .finalize(components::nonvolatile_storage_component_static!(
472        nrf52840::nvmc::Nvmc
473    ));
474
475    //--------------------------------------------------------------------------
476    // FINAL SETUP AND BOARD BOOT
477    //--------------------------------------------------------------------------
478
479    // Start all of the clocks. Low power operation will require a better
480    // approach than this.
481    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
482
483    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
484        .finalize(components::round_robin_component_static!(NUM_PROCS));
485
486    let platform = Platform {
487        console,
488        led,
489        gpio,
490        rng,
491        alarm,
492        nonvolatile_storage,
493        ipc: kernel::ipc::IPC::new(
494            board_kernel,
495            kernel::ipc::DRIVER_NUM,
496            &memory_allocation_capability,
497        ),
498        scheduler,
499        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
500        temperature,
501        humidity,
502        lr1110_spi,
503        lr1110_gpio,
504    };
505
506    let chip = static_init!(
507        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
508        nrf52840::chip::NRF52::new(nrf52840_peripherals)
509    );
510    CHIP = Some(chip);
511
512    //--------------------------------------------------------------------------
513    // TESTS
514    //--------------------------------------------------------------------------
515
516    //--------------------------------------------------------------------------
517    // BOOT COMPLETE
518    //--------------------------------------------------------------------------
519
520    debug!("Initialization complete. Entering main loop.");
521    let _ = _process_console.start();
522
523    //--------------------------------------------------------------------------
524    // PROCESSES AND MAIN LOOP
525    //--------------------------------------------------------------------------
526
527    // These symbols are defined in the linker script.
528    extern "C" {
529        /// Beginning of the ROM region containing app images.
530        static _sapps: u8;
531        /// End of the ROM region containing app images.
532        static _eapps: u8;
533        /// Beginning of the RAM region for app memory.
534        static mut _sappmem: u8;
535        /// End of the RAM region for app memory.
536        static _eappmem: u8;
537    }
538
539    kernel::process::load_processes(
540        board_kernel,
541        chip,
542        core::slice::from_raw_parts(
543            core::ptr::addr_of!(_sapps),
544            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
545        ),
546        core::slice::from_raw_parts_mut(
547            core::ptr::addr_of_mut!(_sappmem),
548            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
549        ),
550        &FAULT_RESPONSE,
551        &process_management_capability,
552    )
553    .unwrap_or_else(|err| {
554        debug!("Error loading processes!");
555        debug!("{:?}", err);
556    });
557
558    (board_kernel, platform, chip)
559}
560
561/// Main function called after RAM initialized.
562#[no_mangle]
563pub unsafe fn main() {
564    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
565
566    let (board_kernel, platform, chip) = start();
567    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
568}