1#![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
30const 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
46const I2C_SDA_PIN: Pin = Pin::P0_27;
48const I2C_SCL_PIN: Pin = Pin::P0_26;
49
50const 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
60const 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
66pub mod io;
68
69const FAULT_RESPONSE: capsules_system::process_policies::StopWithDebugFaultPolicy =
72    capsules_system::process_policies::StopWithDebugFaultPolicy {};
73
74const NUM_PROCS: usize = 8;
76
77type ChipHw = nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>;
78
79static 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
97pub 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#[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    let ieee802154_ack_buf = static_init!(
200        [u8; nrf52840::ieee802154_radio::ACK_BUF_SIZE],
201        [0; nrf52840::ieee802154_radio::ACK_BUF_SIZE]
202    );
203
204    let nrf52840_peripherals = static_init!(
206        Nrf52840DefaultPeripherals,
207        Nrf52840DefaultPeripherals::new(ieee802154_ack_buf)
208    );
209
210    nrf52840_peripherals.init();
212    let base_peripherals = &nrf52840_peripherals.nrf52;
213
214    let processes = components::process_array::ProcessArrayComponent::new()
216        .finalize(components::process_array_component_static!(NUM_PROCS));
217    PROCESSES = Some(processes);
218
219    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
221
222    nrf52_components::startup::NrfStartupComponent::new(
223        false,
224        BUTTON_RST_PIN,
225        nrf52840::uicr::Regulator0Output::DEFAULT,
226        &base_peripherals.nvmc,
227    )
228    .finalize(());
229
230    let process_management_capability =
237        create_capability!(capabilities::ProcessManagementCapability);
238    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
239
240    kernel::debug::assign_gpios(
248        Some(&nrf52840_peripherals.gpio_port[LED_GREEN_PIN]),
249        Some(&nrf52840_peripherals.gpio_port[LED_RED_PIN]),
250        None,
251    );
252
253    let gpio = components::gpio::GpioComponent::new(
258        board_kernel,
259        capsules_core::gpio::DRIVER_NUM,
260        components::gpio_component_helper!(
261            nrf52840::gpio::GPIOPin,
262            2 => &nrf52840_peripherals.gpio_port[GPIO_D2],
263            3 => &nrf52840_peripherals.gpio_port[GPIO_D3],
264            4 => &nrf52840_peripherals.gpio_port[GPIO_D4],
265            5 => &nrf52840_peripherals.gpio_port[GPIO_D5],
266            6 => &nrf52840_peripherals.gpio_port[GPIO_D6],
267            7 => &nrf52840_peripherals.gpio_port[GPIO_D7],
268        ),
269    )
270    .finalize(components::gpio_component_static!(nrf52840::gpio::GPIOPin));
271
272    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
277        LedHigh<'static, nrf52840::gpio::GPIOPin>,
278        LedHigh::new(&nrf52840_peripherals.gpio_port[LED_GREEN_PIN]),
279        LedHigh::new(&nrf52840_peripherals.gpio_port[LED_RED_PIN]),
280    ));
281
282    let rtc = &base_peripherals.rtc;
287    let _ = rtc.start();
288
289    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
290        .finalize(components::alarm_mux_component_static!(nrf52::rtc::Rtc));
291    let alarm = components::alarm::AlarmDriverComponent::new(
292        board_kernel,
293        capsules_core::alarm::DRIVER_NUM,
294        mux_alarm,
295    )
296    .finalize(components::alarm_component_static!(nrf52::rtc::Rtc));
297
298    base_peripherals.uarte0.initialize(
303        nrf52::pinmux::Pinmux::new(UART_TX_PIN as u32),
304        nrf52::pinmux::Pinmux::new(UART_RX_PIN as u32),
305        None,
306        None,
307    );
308
309    let uart_mux = components::console::UartMuxComponent::new(&base_peripherals.uarte0, 115200)
311        .finalize(components::uart_mux_component_static!());
312
313    let console = components::console::ConsoleComponent::new(
315        board_kernel,
316        capsules_core::console::DRIVER_NUM,
317        uart_mux,
318    )
319    .finalize(components::console_component_static!());
320
321    components::debug_writer::DebugWriterComponent::new::<
323        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
324    >(
325        uart_mux,
326        create_capability!(capabilities::SetDebugWriterCapability),
327    )
328    .finalize(components::debug_writer_component_static!());
329
330    nrf52840_peripherals.gpio_port[I2C_PWR].make_output();
336    nrf52840_peripherals.gpio_port[I2C_PWR].set();
337
338    let mux_i2c = components::i2c::I2CMuxComponent::new(&base_peripherals.twi1, None)
339        .finalize(components::i2c_mux_component_static!(nrf52840::i2c::TWI));
340    base_peripherals.twi1.configure(
341        nrf52840::pinmux::Pinmux::new(I2C_SCL_PIN as u32),
342        nrf52840::pinmux::Pinmux::new(I2C_SDA_PIN as u32),
343    );
344
345    let sht4x = components::sht4x::SHT4xComponent::new(
346        mux_i2c,
347        capsules_extra::sht4x::BASE_ADDR,
348        mux_alarm,
349    )
350    .finalize(components::sht4x_component_static!(
351        nrf52::rtc::Rtc<'static>,
352        nrf52840::i2c::TWI
353    ));
354
355    let temperature = components::temperature::TemperatureComponent::new(
356        board_kernel,
357        capsules_extra::temperature::DRIVER_NUM,
358        sht4x,
359    )
360    .finalize(components::temperature_component_static!(SHT4xSensor));
361
362    let humidity = components::humidity::HumidityComponent::new(
363        board_kernel,
364        capsules_extra::humidity::DRIVER_NUM,
365        sht4x,
366    )
367    .finalize(components::humidity_component_static!(SHT4xSensor));
368
369    let mux_spi = components::spi::SpiMuxComponent::new(&base_peripherals.spim0)
374        .finalize(components::spi_mux_component_static!(nrf52840::spi::SPIM));
375
376    let lr1110_spi = components::spi::SpiSyscallComponent::new(
378        board_kernel,
379        mux_spi,
380        hil::spi::cs::IntoChipSelect::<_, hil::spi::cs::ActiveLow>::into_cs(
381            &nrf52840_peripherals.gpio_port[SPI_CS_PIN],
382        ),
383        LORA_SPI_DRIVER_NUM,
384    )
385    .finalize(components::spi_syscall_component_static!(
386        nrf52840::spi::SPIM
387    ));
388
389    base_peripherals.spim0.configure(
390        nrf52840::pinmux::Pinmux::new(SPI_MOSI_PIN as u32),
391        nrf52840::pinmux::Pinmux::new(SPI_MISO_PIN as u32),
392        nrf52840::pinmux::Pinmux::new(SPI_SCK_PIN as u32),
393    );
394
395    base_peripherals
396        .spim0
397        .specify_chip_select(
398            hil::spi::cs::IntoChipSelect::<_, hil::spi::cs::ActiveLow>::into_cs(
399                &nrf52840_peripherals.gpio_port[SPI_CS_PIN],
400            ),
401        )
402        .unwrap();
403
404    let lr1110_gpio = components::gpio::GpioComponent::new(
406        board_kernel,
407        LORA_GPIO_DRIVER_NUM,
408        components::gpio_component_helper!(
409            nrf52840::gpio::GPIOPin,
410            40 => &nrf52840_peripherals.gpio_port[LR_DIO9],
411            42 => &nrf52840_peripherals.gpio_port[RADIO_RESET_PIN],
412            43 => &nrf52840_peripherals.gpio_port[RADIO_BUSY_PIN],
413        ),
414    )
415    .finalize(components::gpio_component_static!(nrf52840::gpio::GPIOPin));
416
417    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
422        .finalize(components::process_printer_text_component_static!());
423    PROCESS_PRINTER = Some(process_printer);
424
425    let _process_console = components::process_console::ProcessConsoleComponent::new(
426        board_kernel,
427        uart_mux,
428        mux_alarm,
429        process_printer,
430        Some(cortexm4::support::reset),
431    )
432    .finalize(components::process_console_component_static!(
433        nrf52840::rtc::Rtc
434    ));
435
436    let rng = components::rng::RngComponent::new(
441        board_kernel,
442        capsules_core::rng::DRIVER_NUM,
443        &base_peripherals.trng,
444    )
445    .finalize(components::rng_component_static!(nrf52840::trng::Trng));
446
447    let nonvolatile_storage = components::nonvolatile_storage::NonvolatileStorageComponent::new(
452        board_kernel,
453        capsules_extra::nonvolatile_storage_driver::DRIVER_NUM,
454        &base_peripherals.nvmc,
455        0xFC000,  4096 * 4, 0,        0,
459    )
460    .finalize(components::nonvolatile_storage_component_static!(
461        nrf52840::nvmc::Nvmc
462    ));
463
464    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
471
472    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
473        .finalize(components::round_robin_component_static!(NUM_PROCS));
474
475    let platform = Platform {
476        console,
477        led,
478        gpio,
479        rng,
480        alarm,
481        nonvolatile_storage,
482        ipc: kernel::ipc::IPC::new(
483            board_kernel,
484            kernel::ipc::DRIVER_NUM,
485            &memory_allocation_capability,
486        ),
487        scheduler,
488        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
489        temperature,
490        humidity,
491        lr1110_spi,
492        lr1110_gpio,
493    };
494
495    let chip = static_init!(
496        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
497        nrf52840::chip::NRF52::new(nrf52840_peripherals)
498    );
499    CHIP = Some(chip);
500
501    debug!("Initialization complete. Entering main loop.");
510    let _ = _process_console.start();
511
512    extern "C" {
518        static _sapps: u8;
520        static _eapps: u8;
522        static mut _sappmem: u8;
524        static _eappmem: u8;
526    }
527
528    kernel::process::load_processes(
529        board_kernel,
530        chip,
531        core::slice::from_raw_parts(
532            core::ptr::addr_of!(_sapps),
533            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
534        ),
535        core::slice::from_raw_parts_mut(
536            core::ptr::addr_of_mut!(_sappmem),
537            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
538        ),
539        &FAULT_RESPONSE,
540        &process_management_capability,
541    )
542    .unwrap_or_else(|err| {
543        debug!("Error loading processes!");
544        debug!("{:?}", err);
545    });
546
547    (board_kernel, platform, chip)
548}
549
550#[no_mangle]
552pub unsafe fn main() {
553    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
554
555    let (board_kernel, platform, chip) = start();
556    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
557}