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