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::debug::PanicResources;
16use kernel::hil;
17use kernel::hil::gpio::Configure;
18use kernel::hil::gpio::Output;
19use kernel::hil::led::LedHigh;
20use kernel::hil::spi::SpiMaster;
21use kernel::hil::time::Counter;
22use kernel::platform::{KernelResources, SyscallDriverLookup};
23use kernel::scheduler::round_robin::RoundRobinSched;
24use kernel::utilities::single_thread_value::SingleThreadValue;
25#[allow(unused_imports)]
26use kernel::{create_capability, debug, debug_gpio, debug_verbose, static_init};
27
28use nrf52840::gpio::Pin;
29use nrf52840::interrupt_service::Nrf52840DefaultPeripherals;
30
31// Three-color LED.
32const LED_RED_PIN: Pin = Pin::P0_14;
33const LED_GREEN_PIN: Pin = Pin::P0_13;
34
35const BUTTON_RST_PIN: Pin = Pin::P0_18;
36
37const GPIO_D2: Pin = Pin::P0_17;
38const GPIO_D3: Pin = Pin::P0_16;
39const GPIO_D4: Pin = Pin::P0_15;
40const GPIO_D5: Pin = Pin::P1_09;
41const GPIO_D6: Pin = Pin::P1_04;
42const GPIO_D7: Pin = Pin::P1_03;
43
44const UART_TX_PIN: Pin = Pin::P0_24;
45const UART_RX_PIN: Pin = Pin::P0_22;
46
47/// I2C pins for all of the sensors.
48const I2C_SDA_PIN: Pin = Pin::P0_27;
49const I2C_SCL_PIN: Pin = Pin::P0_26;
50
51// Pins for communicating with LR1110
52const SPI_CS_PIN: Pin = Pin::P1_12;
53const SPI_SCK_PIN: Pin = Pin::P1_13;
54const SPI_MOSI_PIN: Pin = Pin::P1_14;
55const SPI_MISO_PIN: Pin = Pin::P1_15;
56const RADIO_BUSY_PIN: Pin = Pin::P1_11;
57const RADIO_RESET_PIN: Pin = Pin::P1_10;
58
59const LR_DIO9: Pin = Pin::P1_08;
60
61/// GPIO pin that controls VCC for the I2C bus and sensors.
62const I2C_PWR: Pin = Pin::P0_07;
63
64const LORA_SPI_DRIVER_NUM: usize = capsules_core::driver::NUM::LoRaPhySPI as usize;
65const LORA_GPIO_DRIVER_NUM: usize = capsules_core::driver::NUM::LoRaPhyGPIO as usize;
66
67/// UART Writer for panic!()s.
68pub mod io;
69
70// How should the kernel respond when a process faults. For this board we choose
71// to stop the app and print a notice, but not immediately panic.
72const FAULT_RESPONSE: capsules_system::process_policies::StopWithDebugFaultPolicy =
73    capsules_system::process_policies::StopWithDebugFaultPolicy {};
74
75// Number of concurrent processes this platform supports.
76const NUM_PROCS: usize = 8;
77
78/// The Chip type.
79pub type ChipHw = nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>;
80type ProcessPrinter = capsules_system::process_printer::ProcessPrinterText;
81
82/// Resources for when a board panics used by io.rs.
83static PANIC_RESOURCES: SingleThreadValue<PanicResources<ChipHw, ProcessPrinter>> =
84    SingleThreadValue::new(PanicResources::new());
85
86kernel::stack_size! {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    // Initialize deferred calls very early.
201    kernel::deferred_call::initialize_deferred_call_state::<
202        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
203    >();
204
205    // Bind global variables to this thread.
206    PANIC_RESOURCES.bind_to_thread::<<ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider>();
207
208    let ieee802154_ack_buf = static_init!(
209        [u8; nrf52840::ieee802154_radio::ACK_BUF_SIZE],
210        [0; nrf52840::ieee802154_radio::ACK_BUF_SIZE]
211    );
212
213    // Initialize chip peripheral drivers
214    let nrf52840_peripherals = static_init!(
215        Nrf52840DefaultPeripherals,
216        Nrf52840DefaultPeripherals::new(ieee802154_ack_buf)
217    );
218
219    // set up circular peripheral dependencies
220    nrf52840_peripherals.init();
221    let base_peripherals = &nrf52840_peripherals.nrf52;
222
223    // Create an array to hold process references.
224    let processes = components::process_array::ProcessArrayComponent::new()
225        .finalize(components::process_array_component_static!(NUM_PROCS));
226    PANIC_RESOURCES.get().map(|resources| {
227        resources.processes.put(processes.as_slice());
228    });
229
230    // Setup space to store the core kernel data structure.
231    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
232
233    nrf52_components::startup::NrfStartupComponent::new(
234        false,
235        BUTTON_RST_PIN,
236        nrf52840::uicr::Regulator0Output::DEFAULT,
237        &base_peripherals.nvmc,
238    )
239    .finalize(());
240
241    //--------------------------------------------------------------------------
242    // CAPABILITIES
243    //--------------------------------------------------------------------------
244
245    // Create capabilities that the board needs to call certain protected kernel
246    // functions.
247    let process_management_capability =
248        create_capability!(capabilities::ProcessManagementCapability);
249    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
250
251    //--------------------------------------------------------------------------
252    // DEBUG GPIO
253    //--------------------------------------------------------------------------
254
255    // Configure kernel debug GPIOs as early as possible. These are used by the
256    // `debug_gpio!(0, toggle)` macro. We configure these early so that the
257    // macro is available during most of the setup code and kernel execution.
258    let debug_gpios = static_init!(
259        [&'static dyn kernel::hil::gpio::Pin; 2],
260        [
261            &nrf52840_peripherals.gpio_port[LED_GREEN_PIN],
262            &nrf52840_peripherals.gpio_port[LED_RED_PIN]
263        ]
264    );
265    kernel::debug::initialize_debug_gpio::<
266        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
267    >();
268    kernel::debug::assign_gpios(debug_gpios);
269
270    //--------------------------------------------------------------------------
271    // GPIO
272    //--------------------------------------------------------------------------
273
274    let gpio = components::gpio::GpioComponent::new(
275        board_kernel,
276        capsules_core::gpio::DRIVER_NUM,
277        components::gpio_component_helper!(
278            nrf52840::gpio::GPIOPin,
279            2 => &nrf52840_peripherals.gpio_port[GPIO_D2],
280            3 => &nrf52840_peripherals.gpio_port[GPIO_D3],
281            4 => &nrf52840_peripherals.gpio_port[GPIO_D4],
282            5 => &nrf52840_peripherals.gpio_port[GPIO_D5],
283            6 => &nrf52840_peripherals.gpio_port[GPIO_D6],
284            7 => &nrf52840_peripherals.gpio_port[GPIO_D7],
285        ),
286    )
287    .finalize(components::gpio_component_static!(nrf52840::gpio::GPIOPin));
288
289    //--------------------------------------------------------------------------
290    // LEDs
291    //--------------------------------------------------------------------------
292
293    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
294        LedHigh<'static, nrf52840::gpio::GPIOPin>,
295        LedHigh::new(&nrf52840_peripherals.gpio_port[LED_GREEN_PIN]),
296        LedHigh::new(&nrf52840_peripherals.gpio_port[LED_RED_PIN]),
297    ));
298
299    //--------------------------------------------------------------------------
300    // ALARM & TIMER
301    //--------------------------------------------------------------------------
302
303    let rtc = &base_peripherals.rtc;
304    let _ = rtc.start();
305
306    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
307        .finalize(components::alarm_mux_component_static!(nrf52::rtc::Rtc));
308    let alarm = components::alarm::AlarmDriverComponent::new(
309        board_kernel,
310        capsules_core::alarm::DRIVER_NUM,
311        mux_alarm,
312    )
313    .finalize(components::alarm_component_static!(nrf52::rtc::Rtc));
314
315    //--------------------------------------------------------------------------
316    // UART & CONSOLE & DEBUG
317    //--------------------------------------------------------------------------
318
319    base_peripherals.uarte0.initialize(
320        nrf52::pinmux::Pinmux::new(UART_TX_PIN as u32),
321        nrf52::pinmux::Pinmux::new(UART_RX_PIN as u32),
322        None,
323        None,
324    );
325
326    // Create a shared UART channel for the console and for kernel debug.
327    let uart_mux = components::console::UartMuxComponent::new(&base_peripherals.uarte0, 115200)
328        .finalize(components::uart_mux_component_static!());
329
330    // Setup the console.
331    let console = components::console::ConsoleComponent::new(
332        board_kernel,
333        capsules_core::console::DRIVER_NUM,
334        uart_mux,
335    )
336    .finalize(components::console_component_static!());
337
338    // Create the debugger object that handles calls to `debug!()`.
339    components::debug_writer::DebugWriterComponent::new::<
340        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
341    >(
342        uart_mux,
343        create_capability!(capabilities::SetDebugWriterCapability),
344    )
345    .finalize(components::debug_writer_component_static!());
346
347    //--------------------------------------------------------------------------
348    // SENSORS
349    //--------------------------------------------------------------------------
350
351    // Enable the power supply for the I2C bus and attached sensors.
352    nrf52840_peripherals.gpio_port[I2C_PWR].make_output();
353    nrf52840_peripherals.gpio_port[I2C_PWR].set();
354
355    let mux_i2c = components::i2c::I2CMuxComponent::new(&base_peripherals.twi1, None)
356        .finalize(components::i2c_mux_component_static!(nrf52840::i2c::TWI));
357    base_peripherals.twi1.configure(
358        nrf52840::pinmux::Pinmux::new(I2C_SCL_PIN as u32),
359        nrf52840::pinmux::Pinmux::new(I2C_SDA_PIN as u32),
360    );
361
362    let sht4x = components::sht4x::SHT4xComponent::new(
363        mux_i2c,
364        capsules_extra::sht4x::BASE_ADDR,
365        mux_alarm,
366    )
367    .finalize(components::sht4x_component_static!(
368        nrf52::rtc::Rtc<'static>,
369        nrf52840::i2c::TWI
370    ));
371
372    let temperature = components::temperature::TemperatureComponent::new(
373        board_kernel,
374        capsules_extra::temperature::DRIVER_NUM,
375        sht4x,
376    )
377    .finalize(components::temperature_component_static!(SHT4xSensor));
378
379    let humidity = components::humidity::HumidityComponent::new(
380        board_kernel,
381        capsules_extra::humidity::DRIVER_NUM,
382        sht4x,
383    )
384    .finalize(components::humidity_component_static!(SHT4xSensor));
385
386    //--------------------------------------------------------------------------
387    // LoRa (SPI + GPIO)
388    //--------------------------------------------------------------------------
389
390    let mux_spi = components::spi::SpiMuxComponent::new(&base_peripherals.spim0)
391        .finalize(components::spi_mux_component_static!(nrf52840::spi::SPIM));
392
393    // Create the SPI system call capsule for accessing the LoRa radio.
394    let lr1110_spi = components::spi::SpiSyscallComponent::new(
395        board_kernel,
396        mux_spi,
397        hil::spi::cs::IntoChipSelect::<_, hil::spi::cs::ActiveLow>::into_cs(
398            &nrf52840_peripherals.gpio_port[SPI_CS_PIN],
399        ),
400        LORA_SPI_DRIVER_NUM,
401    )
402    .finalize(components::spi_syscall_component_static!(
403        nrf52840::spi::SPIM
404    ));
405
406    base_peripherals.spim0.configure(
407        nrf52840::pinmux::Pinmux::new(SPI_MOSI_PIN as u32),
408        nrf52840::pinmux::Pinmux::new(SPI_MISO_PIN as u32),
409        nrf52840::pinmux::Pinmux::new(SPI_SCK_PIN as u32),
410    );
411
412    base_peripherals
413        .spim0
414        .specify_chip_select(
415            hil::spi::cs::IntoChipSelect::<_, hil::spi::cs::ActiveLow>::into_cs(
416                &nrf52840_peripherals.gpio_port[SPI_CS_PIN],
417            ),
418        )
419        .unwrap();
420
421    // Pin mappings from the original WM1110 source code.
422    let lr1110_gpio = components::gpio::GpioComponent::new(
423        board_kernel,
424        LORA_GPIO_DRIVER_NUM,
425        components::gpio_component_helper!(
426            nrf52840::gpio::GPIOPin,
427            40 => &nrf52840_peripherals.gpio_port[LR_DIO9],
428            42 => &nrf52840_peripherals.gpio_port[RADIO_RESET_PIN],
429            43 => &nrf52840_peripherals.gpio_port[RADIO_BUSY_PIN],
430        ),
431    )
432    .finalize(components::gpio_component_static!(nrf52840::gpio::GPIOPin));
433
434    //--------------------------------------------------------------------------
435    // Process Console
436    //--------------------------------------------------------------------------
437
438    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
439        .finalize(components::process_printer_text_component_static!());
440    PANIC_RESOURCES.get().map(|resources| {
441        resources.printer.put(process_printer);
442    });
443
444    let _process_console = components::process_console::ProcessConsoleComponent::new(
445        board_kernel,
446        uart_mux,
447        mux_alarm,
448        process_printer,
449        Some(cortexm4::support::reset),
450    )
451    .finalize(components::process_console_component_static!(
452        nrf52840::rtc::Rtc
453    ));
454
455    //--------------------------------------------------------------------------
456    // RANDOM NUMBERS
457    //--------------------------------------------------------------------------
458
459    let rng = components::rng::RngComponent::new(
460        board_kernel,
461        capsules_core::rng::DRIVER_NUM,
462        &base_peripherals.trng,
463    )
464    .finalize(components::rng_component_static!(nrf52840::trng::Trng));
465
466    //--------------------------------------------------------------------------
467    // NONVOLATILE STORAGE
468    //--------------------------------------------------------------------------
469
470    let nonvolatile_storage = components::nonvolatile_storage::NonvolatileStorageComponent::new(
471        board_kernel,
472        capsules_extra::nonvolatile_storage_driver::DRIVER_NUM,
473        &base_peripherals.nvmc,
474        0xFC000,  // Start address for userspace accessible region
475        4096 * 4, // Length of userspace accessible region (16 pages)
476        0,        // No kernel access
477        0,
478    )
479    .finalize(components::nonvolatile_storage_component_static!(
480        nrf52840::nvmc::Nvmc
481    ));
482
483    //--------------------------------------------------------------------------
484    // FINAL SETUP AND BOARD BOOT
485    //--------------------------------------------------------------------------
486
487    // Start all of the clocks. Low power operation will require a better
488    // approach than this.
489    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
490
491    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
492        .finalize(components::round_robin_component_static!(NUM_PROCS));
493
494    let platform = Platform {
495        console,
496        led,
497        gpio,
498        rng,
499        alarm,
500        nonvolatile_storage,
501        ipc: kernel::ipc::IPC::new(
502            board_kernel,
503            kernel::ipc::DRIVER_NUM,
504            &memory_allocation_capability,
505        ),
506        scheduler,
507        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
508        temperature,
509        humidity,
510        lr1110_spi,
511        lr1110_gpio,
512    };
513
514    let chip = static_init!(
515        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
516        nrf52840::chip::NRF52::new(nrf52840_peripherals)
517    );
518    PANIC_RESOURCES.get().map(|resources| {
519        resources.chip.put(chip);
520    });
521
522    //--------------------------------------------------------------------------
523    // TESTS
524    //--------------------------------------------------------------------------
525
526    //--------------------------------------------------------------------------
527    // BOOT COMPLETE
528    //--------------------------------------------------------------------------
529
530    debug!("Initialization complete. Entering main loop.");
531    let _ = _process_console.start();
532
533    //--------------------------------------------------------------------------
534    // PROCESSES AND MAIN LOOP
535    //--------------------------------------------------------------------------
536
537    // These symbols are defined in the linker script.
538    extern "C" {
539        /// Beginning of the ROM region containing app images.
540        static _sapps: u8;
541        /// End of the ROM region containing app images.
542        static _eapps: u8;
543        /// Beginning of the RAM region for app memory.
544        static mut _sappmem: u8;
545        /// End of the RAM region for app memory.
546        static _eappmem: u8;
547    }
548
549    kernel::process::load_processes(
550        board_kernel,
551        chip,
552        core::slice::from_raw_parts(
553            core::ptr::addr_of!(_sapps),
554            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
555        ),
556        core::slice::from_raw_parts_mut(
557            core::ptr::addr_of_mut!(_sappmem),
558            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
559        ),
560        &FAULT_RESPONSE,
561        &process_management_capability,
562    )
563    .unwrap_or_else(|err| {
564        debug!("Error loading processes!");
565        debug!("{:?}", err);
566    });
567
568    (board_kernel, platform, chip)
569}
570
571/// Main function called after RAM initialized.
572#[no_mangle]
573pub unsafe fn main() {
574    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
575
576    let (board_kernel, platform, chip) = start();
577    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
578}