sma_q3/
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 SMA Q3 smartwatch.
6//!
7//! It is based on nRF52840 SoC (Cortex M4 core with a BLE transceiver) with
8//! SWD as I/O and many peripherals.
9//!
10//! Reverse-engineered documentation available at:
11//! <https://hackaday.io/project/175577-hackable-nrf52840-smart-watch>
12
13#![no_std]
14#![no_main]
15#![deny(missing_docs)]
16
17use core::ptr::addr_of;
18
19use capsules_core::virtualizers::virtual_aes_ccm::MuxAES128CCM;
20use capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm;
21use capsules_core::virtualizers::virtual_spi::VirtualSpiMasterDevice;
22use kernel::component::Component;
23use kernel::deferred_call::DeferredCallClient;
24use kernel::hil::i2c::I2CMaster;
25use kernel::hil::led::LedHigh;
26use kernel::hil::screen::Screen;
27use kernel::hil::symmetric_encryption::AES128;
28use kernel::hil::time::Counter;
29use kernel::platform::{KernelResources, SyscallDriverLookup};
30use kernel::process::ProcessArray;
31use kernel::scheduler::round_robin::RoundRobinSched;
32#[allow(unused_imports)]
33use kernel::{capabilities, create_capability, debug, debug_gpio, debug_verbose, static_init};
34use nrf52840::gpio::Pin;
35use nrf52840::interrupt_service::Nrf52840DefaultPeripherals;
36
37// The backlight LED
38const LED1_PIN: Pin = Pin::P0_08;
39
40// Vibration motor
41const VIBRA1_PIN: Pin = Pin::P0_19;
42
43// The side button
44const BUTTON_PIN: Pin = Pin::P0_17;
45
46/// I2C pins for the temp/pressure sensor
47const I2C_TEMP_SDA_PIN: Pin = Pin::P1_15;
48const I2C_TEMP_SCL_PIN: Pin = Pin::P0_02;
49
50// Constants related to the configuration of the 15.4 network stack; DEFAULT_EXT_SRC_MAC
51// should be replaced by an extended src address generated from device serial number
52const SRC_MAC: u16 = 0xf00f;
53const PAN_ID: u16 = 0xABCD;
54const DEFAULT_EXT_SRC_MAC: [u8; 8] = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77];
55
56/// UART Writer
57pub mod io;
58
59// State for loading and holding applications.
60// How should the kernel respond when a process faults.
61const FAULT_RESPONSE: capsules_system::process_policies::PanicFaultPolicy =
62    capsules_system::process_policies::PanicFaultPolicy {};
63
64// Number of concurrent processes this platform supports.
65const NUM_PROCS: usize = 8;
66
67type ChipHw = nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>;
68
69/// Static variables used by io.rs.
70static mut PROCESSES: Option<&'static ProcessArray<NUM_PROCS>> = None;
71
72// Static reference to chip for panic dumps
73static mut CHIP: Option<&'static nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>> = None;
74// Static reference to process printer for panic dumps
75static mut PROCESS_PRINTER: Option<&'static capsules_system::process_printer::ProcessPrinterText> =
76    None;
77
78kernel::stack_size! {0x1000}
79
80type Bmp280Sensor = components::bmp280::Bmp280ComponentType<
81    VirtualMuxAlarm<'static, nrf52840::rtc::Rtc<'static>>,
82    capsules_core::virtualizers::virtual_i2c::I2CDevice<'static, nrf52840::i2c::TWI<'static>>,
83>;
84type TemperatureDriver = components::temperature::TemperatureComponentType<Bmp280Sensor>;
85type RngDriver = components::rng::RngComponentType<nrf52840::trng::Trng<'static>>;
86
87type Ieee802154Driver = components::ieee802154::Ieee802154ComponentType<
88    nrf52840::ieee802154_radio::Radio<'static>,
89    nrf52840::aes::AesECB<'static>,
90>;
91
92/// Supported drivers by the platform
93pub struct Platform {
94    temperature: &'static TemperatureDriver,
95    ble_radio: &'static capsules_extra::ble_advertising_driver::BLE<
96        'static,
97        nrf52840::ble_radio::Radio<'static>,
98        VirtualMuxAlarm<'static, nrf52840::rtc::Rtc<'static>>,
99    >,
100    ieee802154_radio: &'static Ieee802154Driver,
101    button: &'static capsules_core::button::Button<'static, nrf52840::gpio::GPIOPin<'static>>,
102    pconsole: &'static capsules_core::process_console::ProcessConsole<
103        'static,
104        { capsules_core::process_console::DEFAULT_COMMAND_HISTORY_LEN },
105        VirtualMuxAlarm<'static, nrf52840::rtc::Rtc<'static>>,
106        components::process_console::Capability,
107    >,
108    console: &'static capsules_core::console::Console<'static>,
109    gpio: &'static capsules_core::gpio::GPIO<'static, nrf52840::gpio::GPIOPin<'static>>,
110    led: &'static capsules_core::led::LedDriver<
111        'static,
112        LedHigh<'static, nrf52840::gpio::GPIOPin<'static>>,
113        2,
114    >,
115    rng: &'static RngDriver,
116    ipc: kernel::ipc::IPC<{ NUM_PROCS as u8 }>,
117    analog_comparator: &'static capsules_extra::analog_comparator::AnalogComparator<
118        'static,
119        nrf52840::acomp::Comparator<'static>,
120    >,
121    alarm: &'static capsules_core::alarm::AlarmDriver<
122        'static,
123        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<
124            'static,
125            nrf52840::rtc::Rtc<'static>,
126        >,
127    >,
128    screen: &'static capsules_extra::screen::screen::Screen<'static>,
129    scheduler: &'static RoundRobinSched<'static>,
130    systick: cortexm4::systick::SysTick,
131}
132
133impl SyscallDriverLookup for Platform {
134    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
135    where
136        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
137    {
138        match driver_num {
139            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
140            capsules_core::gpio::DRIVER_NUM => f(Some(self.gpio)),
141            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
142            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
143            capsules_core::button::DRIVER_NUM => f(Some(self.button)),
144            capsules_core::rng::DRIVER_NUM => f(Some(self.rng)),
145            capsules_extra::ble_advertising_driver::DRIVER_NUM => f(Some(self.ble_radio)),
146            capsules_extra::ieee802154::DRIVER_NUM => f(Some(self.ieee802154_radio)),
147            capsules_extra::temperature::DRIVER_NUM => f(Some(self.temperature)),
148            capsules_extra::analog_comparator::DRIVER_NUM => f(Some(self.analog_comparator)),
149            capsules_extra::screen::screen::DRIVER_NUM => f(Some(self.screen)),
150            kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
151            _ => f(None),
152        }
153    }
154}
155
156impl KernelResources<nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>>
157    for Platform
158{
159    type SyscallDriverLookup = Self;
160    type SyscallFilter = ();
161    type ProcessFault = ();
162    type Scheduler = RoundRobinSched<'static>;
163    type SchedulerTimer = cortexm4::systick::SysTick;
164    type WatchDog = ();
165    type ContextSwitchCallback = ();
166
167    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
168        self
169    }
170    fn syscall_filter(&self) -> &Self::SyscallFilter {
171        &()
172    }
173    fn process_fault(&self) -> &Self::ProcessFault {
174        &()
175    }
176    fn scheduler(&self) -> &Self::Scheduler {
177        self.scheduler
178    }
179    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
180        &self.systick
181    }
182    fn watchdog(&self) -> &Self::WatchDog {
183        &()
184    }
185    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
186        &()
187    }
188}
189
190/// This is in a separate, inline(never) function so that its stack frame is
191/// removed when this function returns. Otherwise, the stack space used for
192/// these static_inits is wasted.
193#[inline(never)]
194pub unsafe fn start() -> (
195    &'static kernel::Kernel,
196    Platform,
197    &'static nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>,
198) {
199    nrf52840::init();
200
201    // Initialize deferred calls very early.
202    kernel::deferred_call::initialize_deferred_call_state::<
203        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
204    >();
205
206    let ieee802154_ack_buf = static_init!(
207        [u8; nrf52840::ieee802154_radio::ACK_BUF_SIZE],
208        [0; nrf52840::ieee802154_radio::ACK_BUF_SIZE]
209    );
210    // Initialize chip peripheral drivers
211    let nrf52840_peripherals = static_init!(
212        Nrf52840DefaultPeripherals,
213        Nrf52840DefaultPeripherals::new(ieee802154_ack_buf)
214    );
215
216    // set up circular peripheral dependencies
217    nrf52840_peripherals.init();
218    let base_peripherals = &nrf52840_peripherals.nrf52;
219
220    // Create an array to hold process references.
221    let processes = components::process_array::ProcessArrayComponent::new()
222        .finalize(components::process_array_component_static!(NUM_PROCS));
223    PROCESSES = Some(processes);
224
225    // Setup space to store the core kernel data structure.
226    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
227
228    // GPIOs
229    let gpio = components::gpio::GpioComponent::new(
230        board_kernel,
231        capsules_core::gpio::DRIVER_NUM,
232        components::gpio_component_helper!(
233            nrf52840::gpio::GPIOPin,
234            0 => &nrf52840_peripherals.gpio_port[Pin::P0_29],
235        ),
236    )
237    .finalize(components::gpio_component_static!(nrf52840::gpio::GPIOPin));
238
239    let button = components::button::ButtonComponent::new(
240        board_kernel,
241        capsules_core::button::DRIVER_NUM,
242        components::button_component_helper!(
243            nrf52840::gpio::GPIOPin,
244            (
245                &nrf52840_peripherals.gpio_port[BUTTON_PIN],
246                kernel::hil::gpio::ActivationMode::ActiveLow,
247                kernel::hil::gpio::FloatingState::PullUp
248            )
249        ),
250    )
251    .finalize(components::button_component_static!(
252        nrf52840::gpio::GPIOPin
253    ));
254
255    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
256        LedHigh<'static, nrf52840::gpio::GPIOPin>,
257        LedHigh::new(&nrf52840_peripherals.gpio_port[LED1_PIN]),
258        LedHigh::new(&nrf52840_peripherals.gpio_port[VIBRA1_PIN]),
259    ));
260
261    let chip = static_init!(
262        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
263        nrf52840::chip::NRF52::new(nrf52840_peripherals)
264    );
265    CHIP = Some(chip);
266
267    nrf52_components::startup::NrfStartupComponent::new(
268        false,
269        // the button pin cannot be used to reset the device,
270        // but the API expects some pin,
271        // so might as well give a useless one.
272        BUTTON_PIN,
273        nrf52840::uicr::Regulator0Output::V3_0,
274        &base_peripherals.nvmc,
275    )
276    .finalize(());
277
278    // Create capabilities that the board needs to call certain protected kernel
279    // functions.
280
281    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
282
283    let gpio_port = &nrf52840_peripherals.gpio_port;
284
285    // Configure kernel debug gpios as early as possible
286    let debug_gpios = static_init!(
287        [&'static dyn kernel::hil::gpio::Pin; 1],
288        [&gpio_port[LED1_PIN]]
289    );
290    kernel::debug::initialize_debug_gpio::<
291        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
292    >();
293    kernel::debug::assign_gpios(debug_gpios);
294
295    let rtc = &base_peripherals.rtc;
296    let _ = rtc.start();
297    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
298        .finalize(components::alarm_mux_component_static!(nrf52840::rtc::Rtc));
299    let alarm = components::alarm::AlarmDriverComponent::new(
300        board_kernel,
301        capsules_core::alarm::DRIVER_NUM,
302        mux_alarm,
303    )
304    .finalize(components::alarm_component_static!(nrf52840::rtc::Rtc));
305
306    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
307        .finalize(components::process_printer_text_component_static!());
308    PROCESS_PRINTER = Some(process_printer);
309
310    // Initialize early so any panic beyond this point can use the RTT memory object.
311    let uart_channel = {
312        // RTT communication channel
313        let rtt_memory = components::segger_rtt::SeggerRttMemoryComponent::new()
314            .finalize(components::segger_rtt_memory_component_static!());
315
316        // TODO: This is inherently unsafe as it aliases the mutable reference to rtt_memory. This
317        // aliases reference is only used inside a panic handler, which should be OK, but maybe we
318        // should use a const reference to rtt_memory and leverage interior mutability instead.
319        self::io::set_rtt_memory(&*core::ptr::from_mut(rtt_memory.rtt_memory));
320
321        components::segger_rtt::SeggerRttComponent::new(mux_alarm, rtt_memory)
322            .finalize(components::segger_rtt_component_static!(nrf52840::rtc::Rtc))
323    };
324
325    // Create a shared UART channel for the console and for kernel debug.
326    let uart_mux = components::console::UartMuxComponent::new(uart_channel, 115200)
327        .finalize(components::uart_mux_component_static!());
328
329    let pconsole = components::process_console::ProcessConsoleComponent::new(
330        board_kernel,
331        uart_mux,
332        mux_alarm,
333        process_printer,
334        Some(cortexm4::support::reset),
335    )
336    .finalize(components::process_console_component_static!(
337        nrf52840::rtc::Rtc<'static>
338    ));
339
340    // Setup the console.
341    let console = components::console::ConsoleComponent::new(
342        board_kernel,
343        capsules_core::console::DRIVER_NUM,
344        uart_mux,
345    )
346    .finalize(components::console_component_static!());
347    // Create the debugger object that handles calls to `debug!()`.
348    components::debug_writer::DebugWriterComponent::new::<
349        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
350    >(
351        uart_mux,
352        create_capability!(capabilities::SetDebugWriterCapability),
353    )
354    .finalize(components::debug_writer_component_static!());
355
356    let ble_radio = components::ble::BLEComponent::new(
357        board_kernel,
358        capsules_extra::ble_advertising_driver::DRIVER_NUM,
359        &base_peripherals.ble_radio,
360        mux_alarm,
361    )
362    .finalize(components::ble_component_static!(
363        nrf52840::rtc::Rtc,
364        nrf52840::ble_radio::Radio
365    ));
366
367    let aes_mux = static_init!(
368        MuxAES128CCM<'static, nrf52840::aes::AesECB>,
369        MuxAES128CCM::new(&base_peripherals.ecb,)
370    );
371    base_peripherals.ecb.set_client(aes_mux);
372    aes_mux.register();
373
374    let (ieee802154_radio, _mux_mac) = components::ieee802154::Ieee802154Component::new(
375        board_kernel,
376        capsules_extra::ieee802154::DRIVER_NUM,
377        &nrf52840_peripherals.ieee802154_radio,
378        aes_mux,
379        PAN_ID,
380        SRC_MAC,
381        DEFAULT_EXT_SRC_MAC,
382    )
383    .finalize(components::ieee802154_component_static!(
384        nrf52840::ieee802154_radio::Radio,
385        nrf52840::aes::AesECB<'static>
386    ));
387
388    // Not exposed in favor of the BMP280, but present.
389    // Possibly needs power management all the same.
390    let _temp = components::temperature::TemperatureComponent::new(
391        board_kernel,
392        capsules_extra::temperature::DRIVER_NUM,
393        &base_peripherals.temp,
394    )
395    .finalize(components::temperature_component_static!(
396        nrf52840::temperature::Temp
397    ));
398
399    let sensors_i2c_bus = static_init!(
400        capsules_core::virtualizers::virtual_i2c::MuxI2C<'static, nrf52840::i2c::TWI>,
401        capsules_core::virtualizers::virtual_i2c::MuxI2C::new(&base_peripherals.twi1, None,)
402    );
403    sensors_i2c_bus.register();
404
405    base_peripherals.twi1.configure(
406        nrf52840::pinmux::Pinmux::new(I2C_TEMP_SCL_PIN as u32),
407        nrf52840::pinmux::Pinmux::new(I2C_TEMP_SDA_PIN as u32),
408    );
409    base_peripherals.twi1.set_master_client(sensors_i2c_bus);
410
411    let bmp280 = components::bmp280::Bmp280Component::new(
412        sensors_i2c_bus,
413        capsules_extra::bmp280::BASE_ADDR,
414        mux_alarm,
415    )
416    .finalize(components::bmp280_component_static!(
417        nrf52840::rtc::Rtc<'static>,
418        nrf52840::i2c::TWI
419    ));
420
421    let temperature = components::temperature::TemperatureComponent::new(
422        board_kernel,
423        capsules_extra::temperature::DRIVER_NUM,
424        bmp280,
425    )
426    .finalize(components::temperature_component_static!(Bmp280Sensor));
427
428    let rng = components::rng::RngComponent::new(
429        board_kernel,
430        capsules_core::rng::DRIVER_NUM,
431        &base_peripherals.trng,
432    )
433    .finalize(components::rng_component_static!(nrf52840::trng::Trng));
434
435    // Initialize AC using AIN5 (P0.29) as VIN+ and VIN- as AIN0 (P0.02)
436    // These are hardcoded pin assignments specified in the driver
437    let analog_comparator_channel = static_init!(
438        nrf52840::acomp::Channel,
439        nrf52840::acomp::Channel::new(nrf52840::acomp::ChannelNumber::AC0)
440    );
441    let analog_comparator = components::analog_comparator::AnalogComparatorComponent::new(
442        &base_peripherals.acomp,
443        components::analog_comparator_component_helper!(
444            nrf52840::acomp::Channel,
445            analog_comparator_channel,
446        ),
447        board_kernel,
448        capsules_extra::analog_comparator::DRIVER_NUM,
449    )
450    .finalize(components::analog_comparator_component_static!(
451        nrf52840::acomp::Comparator
452    ));
453
454    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
455
456    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
457        .finalize(components::round_robin_component_static!(NUM_PROCS));
458
459    let periodic_virtual_alarm = static_init!(
460        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<'static, nrf52840::rtc::Rtc>,
461        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm::new(mux_alarm)
462    );
463    periodic_virtual_alarm.setup();
464
465    let screen = {
466        let mux_spi = components::spi::SpiMuxComponent::new(&base_peripherals.spim2)
467            .finalize(components::spi_mux_component_static!(nrf52840::spi::SPIM));
468
469        use kernel::hil::spi::SpiMaster;
470        base_peripherals
471            .spim2
472            .set_rate(1_000_000)
473            .expect("SPIM2 set rate");
474
475        base_peripherals.spim2.configure(
476            nrf52840::pinmux::Pinmux::new(Pin::P0_27 as u32),
477            nrf52840::pinmux::Pinmux::new(Pin::P0_28 as u32),
478            nrf52840::pinmux::Pinmux::new(Pin::P0_26 as u32),
479        );
480
481        let disp_pin = &nrf52840_peripherals.gpio_port[Pin::P0_07];
482        let cs_pin = &nrf52840_peripherals.gpio_port[Pin::P0_05];
483
484        let display = components::lpm013m126::Lpm013m126Component::new(
485            mux_spi,
486            cs_pin,
487            disp_pin,
488            &nrf52840_peripherals.gpio_port[Pin::P0_06],
489            mux_alarm,
490        )
491        .finalize(components::lpm013m126_component_static!(
492            nrf52840::rtc::Rtc<'static>,
493            nrf52840::gpio::GPIOPin,
494            nrf52840::spi::SPIM
495        ));
496
497        let screen = components::screen::ScreenComponent::new(
498            board_kernel,
499            capsules_extra::screen::screen::DRIVER_NUM,
500            display,
501            None,
502        )
503        .finalize(components::screen_component_static!(4096));
504        // Power on screen if not already powered
505        let _ = display.set_power(true);
506        screen
507    };
508
509    let platform = Platform {
510        temperature,
511        button,
512        ble_radio,
513        ieee802154_radio,
514        pconsole,
515        console,
516        led,
517        gpio,
518        rng,
519        alarm,
520        analog_comparator,
521        screen,
522        ipc: kernel::ipc::IPC::new(
523            board_kernel,
524            kernel::ipc::DRIVER_NUM,
525            &memory_allocation_capability,
526        ),
527        scheduler,
528        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
529    };
530
531    /// I split this out to be able to start applications with a delay
532    /// after the board is initialized.
533    /// The benefit to debugging is that if I want to print
534    /// some debug information while the board initalizes,
535    /// it won't be affected by an application that prints so much
536    /// that it overflows the output buffer.
537    ///
538    /// It's also useful for a future "fake off" functionality,
539    /// where if a button is pressed, processes are stopped,
540    /// but when pressed again, they are loaded anew.
541    fn load_processes(
542        board_kernel: &'static kernel::Kernel,
543        chip: &'static nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>,
544    ) {
545        let process_management_capability =
546            create_capability!(capabilities::ProcessManagementCapability);
547        unsafe {
548            kernel::process::load_processes(
549                board_kernel,
550                chip,
551                core::slice::from_raw_parts(
552                    core::ptr::addr_of!(_sapps),
553                    core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
554                ),
555                core::slice::from_raw_parts_mut(
556                    core::ptr::addr_of_mut!(_sappmem),
557                    core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
558                ),
559                &FAULT_RESPONSE,
560                &process_management_capability,
561            )
562            .unwrap_or_else(|err| {
563                debug!("Error loading processes!");
564                debug!("{:?}", err);
565            });
566        }
567    }
568
569    let _ = platform.pconsole.start();
570    debug!("Initialization complete. Entering main loop\r");
571    debug!("{}", &*addr_of!(nrf52840::ficr::FICR_INSTANCE));
572
573    load_processes(board_kernel, chip);
574    // These symbols are defined in the linker script.
575    extern "C" {
576        /// Beginning of the ROM region containing app images.
577        static _sapps: u8;
578        /// End of the ROM region containing app images.
579        static _eapps: u8;
580        /// Beginning of the RAM region for app memory.
581        static mut _sappmem: u8;
582        /// End of the RAM region for app memory.
583        static _eappmem: u8;
584    }
585
586    (board_kernel, platform, chip)
587}
588
589/// Main function called after RAM initialized.
590#[no_mangle]
591pub unsafe fn main() {
592    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
593
594    let (board_kernel, platform, chip) = start();
595    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
596}