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    let ieee802154_ack_buf = static_init!(
202        [u8; nrf52840::ieee802154_radio::ACK_BUF_SIZE],
203        [0; nrf52840::ieee802154_radio::ACK_BUF_SIZE]
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    // GPIOs
224    let gpio = components::gpio::GpioComponent::new(
225        board_kernel,
226        capsules_core::gpio::DRIVER_NUM,
227        components::gpio_component_helper!(
228            nrf52840::gpio::GPIOPin,
229            0 => &nrf52840_peripherals.gpio_port[Pin::P0_29],
230        ),
231    )
232    .finalize(components::gpio_component_static!(nrf52840::gpio::GPIOPin));
233
234    let button = components::button::ButtonComponent::new(
235        board_kernel,
236        capsules_core::button::DRIVER_NUM,
237        components::button_component_helper!(
238            nrf52840::gpio::GPIOPin,
239            (
240                &nrf52840_peripherals.gpio_port[BUTTON_PIN],
241                kernel::hil::gpio::ActivationMode::ActiveLow,
242                kernel::hil::gpio::FloatingState::PullUp
243            )
244        ),
245    )
246    .finalize(components::button_component_static!(
247        nrf52840::gpio::GPIOPin
248    ));
249
250    let led = components::led::LedsComponent::new().finalize(components::led_component_static!(
251        LedHigh<'static, nrf52840::gpio::GPIOPin>,
252        LedHigh::new(&nrf52840_peripherals.gpio_port[LED1_PIN]),
253        LedHigh::new(&nrf52840_peripherals.gpio_port[VIBRA1_PIN]),
254    ));
255
256    let chip = static_init!(
257        nrf52840::chip::NRF52<Nrf52840DefaultPeripherals>,
258        nrf52840::chip::NRF52::new(nrf52840_peripherals)
259    );
260    CHIP = Some(chip);
261
262    nrf52_components::startup::NrfStartupComponent::new(
263        false,
264        // the button pin cannot be used to reset the device,
265        // but the API expects some pin,
266        // so might as well give a useless one.
267        BUTTON_PIN,
268        nrf52840::uicr::Regulator0Output::V3_0,
269        &base_peripherals.nvmc,
270    )
271    .finalize(());
272
273    // Create capabilities that the board needs to call certain protected kernel
274    // functions.
275
276    let memory_allocation_capability = create_capability!(capabilities::MemoryAllocationCapability);
277
278    let gpio_port = &nrf52840_peripherals.gpio_port;
279
280    // Configure kernel debug gpios as early as possible
281    kernel::debug::assign_gpios(Some(&gpio_port[LED1_PIN]), None, None);
282
283    let rtc = &base_peripherals.rtc;
284    let _ = rtc.start();
285    let mux_alarm = components::alarm::AlarmMuxComponent::new(rtc)
286        .finalize(components::alarm_mux_component_static!(nrf52840::rtc::Rtc));
287    let alarm = components::alarm::AlarmDriverComponent::new(
288        board_kernel,
289        capsules_core::alarm::DRIVER_NUM,
290        mux_alarm,
291    )
292    .finalize(components::alarm_component_static!(nrf52840::rtc::Rtc));
293
294    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
295        .finalize(components::process_printer_text_component_static!());
296    PROCESS_PRINTER = Some(process_printer);
297
298    // Initialize early so any panic beyond this point can use the RTT memory object.
299    let uart_channel = {
300        // RTT communication channel
301        let rtt_memory = components::segger_rtt::SeggerRttMemoryComponent::new()
302            .finalize(components::segger_rtt_memory_component_static!());
303
304        // TODO: This is inherently unsafe as it aliases the mutable reference to rtt_memory. This
305        // aliases reference is only used inside a panic handler, which should be OK, but maybe we
306        // should use a const reference to rtt_memory and leverage interior mutability instead.
307        self::io::set_rtt_memory(&*core::ptr::from_mut(rtt_memory.rtt_memory));
308
309        components::segger_rtt::SeggerRttComponent::new(mux_alarm, rtt_memory)
310            .finalize(components::segger_rtt_component_static!(nrf52840::rtc::Rtc))
311    };
312
313    // Create a shared UART channel for the console and for kernel debug.
314    let uart_mux = components::console::UartMuxComponent::new(uart_channel, 115200)
315        .finalize(components::uart_mux_component_static!());
316
317    let pconsole = components::process_console::ProcessConsoleComponent::new(
318        board_kernel,
319        uart_mux,
320        mux_alarm,
321        process_printer,
322        Some(cortexm4::support::reset),
323    )
324    .finalize(components::process_console_component_static!(
325        nrf52840::rtc::Rtc<'static>
326    ));
327
328    // Setup the console.
329    let console = components::console::ConsoleComponent::new(
330        board_kernel,
331        capsules_core::console::DRIVER_NUM,
332        uart_mux,
333    )
334    .finalize(components::console_component_static!());
335    // Create the debugger object that handles calls to `debug!()`.
336    components::debug_writer::DebugWriterComponent::new::<
337        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
338    >(
339        uart_mux,
340        create_capability!(capabilities::SetDebugWriterCapability),
341    )
342    .finalize(components::debug_writer_component_static!());
343
344    let ble_radio = components::ble::BLEComponent::new(
345        board_kernel,
346        capsules_extra::ble_advertising_driver::DRIVER_NUM,
347        &base_peripherals.ble_radio,
348        mux_alarm,
349    )
350    .finalize(components::ble_component_static!(
351        nrf52840::rtc::Rtc,
352        nrf52840::ble_radio::Radio
353    ));
354
355    let aes_mux = static_init!(
356        MuxAES128CCM<'static, nrf52840::aes::AesECB>,
357        MuxAES128CCM::new(&base_peripherals.ecb,)
358    );
359    base_peripherals.ecb.set_client(aes_mux);
360    aes_mux.register();
361
362    let (ieee802154_radio, _mux_mac) = components::ieee802154::Ieee802154Component::new(
363        board_kernel,
364        capsules_extra::ieee802154::DRIVER_NUM,
365        &nrf52840_peripherals.ieee802154_radio,
366        aes_mux,
367        PAN_ID,
368        SRC_MAC,
369        DEFAULT_EXT_SRC_MAC,
370    )
371    .finalize(components::ieee802154_component_static!(
372        nrf52840::ieee802154_radio::Radio,
373        nrf52840::aes::AesECB<'static>
374    ));
375
376    // Not exposed in favor of the BMP280, but present.
377    // Possibly needs power management all the same.
378    let _temp = components::temperature::TemperatureComponent::new(
379        board_kernel,
380        capsules_extra::temperature::DRIVER_NUM,
381        &base_peripherals.temp,
382    )
383    .finalize(components::temperature_component_static!(
384        nrf52840::temperature::Temp
385    ));
386
387    let sensors_i2c_bus = static_init!(
388        capsules_core::virtualizers::virtual_i2c::MuxI2C<'static, nrf52840::i2c::TWI>,
389        capsules_core::virtualizers::virtual_i2c::MuxI2C::new(&base_peripherals.twi1, None,)
390    );
391    sensors_i2c_bus.register();
392
393    base_peripherals.twi1.configure(
394        nrf52840::pinmux::Pinmux::new(I2C_TEMP_SCL_PIN as u32),
395        nrf52840::pinmux::Pinmux::new(I2C_TEMP_SDA_PIN as u32),
396    );
397    base_peripherals.twi1.set_master_client(sensors_i2c_bus);
398
399    let bmp280 = components::bmp280::Bmp280Component::new(
400        sensors_i2c_bus,
401        capsules_extra::bmp280::BASE_ADDR,
402        mux_alarm,
403    )
404    .finalize(components::bmp280_component_static!(
405        nrf52840::rtc::Rtc<'static>,
406        nrf52840::i2c::TWI
407    ));
408
409    let temperature = components::temperature::TemperatureComponent::new(
410        board_kernel,
411        capsules_extra::temperature::DRIVER_NUM,
412        bmp280,
413    )
414    .finalize(components::temperature_component_static!(Bmp280Sensor));
415
416    let rng = components::rng::RngComponent::new(
417        board_kernel,
418        capsules_core::rng::DRIVER_NUM,
419        &base_peripherals.trng,
420    )
421    .finalize(components::rng_component_static!(nrf52840::trng::Trng));
422
423    // Initialize AC using AIN5 (P0.29) as VIN+ and VIN- as AIN0 (P0.02)
424    // These are hardcoded pin assignments specified in the driver
425    let analog_comparator_channel = static_init!(
426        nrf52840::acomp::Channel,
427        nrf52840::acomp::Channel::new(nrf52840::acomp::ChannelNumber::AC0)
428    );
429    let analog_comparator = components::analog_comparator::AnalogComparatorComponent::new(
430        &base_peripherals.acomp,
431        components::analog_comparator_component_helper!(
432            nrf52840::acomp::Channel,
433            analog_comparator_channel,
434        ),
435        board_kernel,
436        capsules_extra::analog_comparator::DRIVER_NUM,
437    )
438    .finalize(components::analog_comparator_component_static!(
439        nrf52840::acomp::Comparator
440    ));
441
442    nrf52_components::NrfClockComponent::new(&base_peripherals.clock).finalize(());
443
444    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
445        .finalize(components::round_robin_component_static!(NUM_PROCS));
446
447    let periodic_virtual_alarm = static_init!(
448        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<'static, nrf52840::rtc::Rtc>,
449        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm::new(mux_alarm)
450    );
451    periodic_virtual_alarm.setup();
452
453    let screen = {
454        let mux_spi = components::spi::SpiMuxComponent::new(&base_peripherals.spim2)
455            .finalize(components::spi_mux_component_static!(nrf52840::spi::SPIM));
456
457        use kernel::hil::spi::SpiMaster;
458        base_peripherals
459            .spim2
460            .set_rate(1_000_000)
461            .expect("SPIM2 set rate");
462
463        base_peripherals.spim2.configure(
464            nrf52840::pinmux::Pinmux::new(Pin::P0_27 as u32),
465            nrf52840::pinmux::Pinmux::new(Pin::P0_28 as u32),
466            nrf52840::pinmux::Pinmux::new(Pin::P0_26 as u32),
467        );
468
469        let disp_pin = &nrf52840_peripherals.gpio_port[Pin::P0_07];
470        let cs_pin = &nrf52840_peripherals.gpio_port[Pin::P0_05];
471
472        let display = components::lpm013m126::Lpm013m126Component::new(
473            mux_spi,
474            cs_pin,
475            disp_pin,
476            &nrf52840_peripherals.gpio_port[Pin::P0_06],
477            mux_alarm,
478        )
479        .finalize(components::lpm013m126_component_static!(
480            nrf52840::rtc::Rtc<'static>,
481            nrf52840::gpio::GPIOPin,
482            nrf52840::spi::SPIM
483        ));
484
485        let screen = components::screen::ScreenComponent::new(
486            board_kernel,
487            capsules_extra::screen::screen::DRIVER_NUM,
488            display,
489            None,
490        )
491        .finalize(components::screen_component_static!(4096));
492        // Power on screen if not already powered
493        let _ = display.set_power(true);
494        screen
495    };
496
497    let platform = Platform {
498        temperature,
499        button,
500        ble_radio,
501        ieee802154_radio,
502        pconsole,
503        console,
504        led,
505        gpio,
506        rng,
507        alarm,
508        analog_comparator,
509        screen,
510        ipc: kernel::ipc::IPC::new(
511            board_kernel,
512            kernel::ipc::DRIVER_NUM,
513            &memory_allocation_capability,
514        ),
515        scheduler,
516        systick: cortexm4::systick::SysTick::new_with_calibration(64000000),
517    };
518
519    /// I split this out to be able to start applications with a delay
520    /// after the board is initialized.
521    /// The benefit to debugging is that if I want to print
522    /// some debug information while the board initalizes,
523    /// it won't be affected by an application that prints so much
524    /// that it overflows the output buffer.
525    ///
526    /// It's also useful for a future "fake off" functionality,
527    /// where if a button is pressed, processes are stopped,
528    /// but when pressed again, they are loaded anew.
529    fn load_processes(
530        board_kernel: &'static kernel::Kernel,
531        chip: &'static nrf52840::chip::NRF52<'static, Nrf52840DefaultPeripherals<'static>>,
532    ) {
533        let process_management_capability =
534            create_capability!(capabilities::ProcessManagementCapability);
535        unsafe {
536            kernel::process::load_processes(
537                board_kernel,
538                chip,
539                core::slice::from_raw_parts(
540                    core::ptr::addr_of!(_sapps),
541                    core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
542                ),
543                core::slice::from_raw_parts_mut(
544                    core::ptr::addr_of_mut!(_sappmem),
545                    core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
546                ),
547                &FAULT_RESPONSE,
548                &process_management_capability,
549            )
550            .unwrap_or_else(|err| {
551                debug!("Error loading processes!");
552                debug!("{:?}", err);
553            });
554        }
555    }
556
557    let _ = platform.pconsole.start();
558    debug!("Initialization complete. Entering main loop\r");
559    debug!("{}", &*addr_of!(nrf52840::ficr::FICR_INSTANCE));
560
561    load_processes(board_kernel, chip);
562    // These symbols are defined in the linker script.
563    extern "C" {
564        /// Beginning of the ROM region containing app images.
565        static _sapps: u8;
566        /// End of the ROM region containing app images.
567        static _eapps: u8;
568        /// Beginning of the RAM region for app memory.
569        static mut _sappmem: u8;
570        /// End of the RAM region for app memory.
571        static _eappmem: u8;
572    }
573
574    (board_kernel, platform, chip)
575}
576
577/// Main function called after RAM initialized.
578#[no_mangle]
579pub unsafe fn main() {
580    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
581
582    let (board_kernel, platform, chip) = start();
583    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
584}